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,qBAAwB,WAAY,CACxFA,EAAO,oBAAoBN,GAAiBC,CAAO,CAAC,EACpD,MACF,CAEA,GAAI,kBAAmBK,GAAU,OAAOA,EAAO,eAAe,WAAc,WAAY,CACtFA,EAAO,cAAc,UAAUN,GAAiBC,CAAO,CAAC,EACxD,MACF,CAKA,GAAIM,EAAW,OAAO,IAAI,yBAAyB,CAAC,EAAG,CAErDC,GAAgBR,GAAiBC,CAAO,CAAC,EACzC,MACF,CAEA,GAAI,OAAO,WAAY,IACrB,QAIE,WAAQ,IAAI,0BACZ,WAAQ,IAAI,kBACZ,WAAQ,IAAI,WACZ,WAAQ,IAAI,UACZ,WAAQ,IAAI,QACZ,WAAQ,IAAI,UAId,MAAMD,GAAiBC,CAAO,CAElC,CCjDO,SAASQ,GAAqBC,EAA6B,CAGhE,OAAOA,EAAY,QAAQ,sBAAuB,MAAM,EAAE,QAAQ,KAAM,OAAO,CACjF","names":["DEBUG_BUILD","GLOBAL_OBJ","SDK_VERSION","getMainCarrier","getSentryCarrier","GLOBAL_OBJ","carrier","__SENTRY__","SDK_VERSION","getGlobalSingleton","name","creator","obj","CONSOLE_LEVELS","PREFIX","originalConsoleMethods","consoleSandbox","callback","GLOBAL_OBJ","console","wrappedFuncs","wrappedLevels","level","originalConsoleMethod","enable","_getLoggerSettings","disable","isEnabled","log","args","_maybeLog","warn","error","DEBUG_BUILD","getGlobalSingleton","debug","UNKNOWN_FUNCTION","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","createStackParser","parsers","sortedParsers","a","b","p","stack","skipFirstLines","framesToPop","frames","lines","i","line","cleanedLine","parser","frame","stripSentryFramesAndReverse","stackParserFromStackParserOptions","stackParser","localStack","getLastStackFrame","arr","defaultFunctionName","getFunctionName","fn","getFramesFromEvent","event","exception","value","getVueInternalName","normalizeStackTracePath","path","filename","handlers","instrumented","addHandler","type","handler","resetInstrumentationHandlers","key","maybeInstrument","instrumentFn","e","DEBUG_BUILD","debug","triggerHandlers","data","typeHandlers","getFunctionName","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentError","GLOBAL_OBJ","msg","url","line","column","error","triggerHandlers","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentUnhandledRejection","GLOBAL_OBJ","triggerHandlers","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isDOMError","isDOMException","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","isElement","isRegExp","isThenable","isSyntheticEvent","base","isVueViewModel","isRequest","request","WINDOW","GLOBAL_OBJ","DEFAULT_MAX_STRING_LENGTH","htmlTreeAsString","elem","options","currentElem","MAX_TRAVERSE_HEIGHT","out","height","len","separator","sepLength","nextStr","keyAttrs","maxStringLength","_htmlElementAsString","el","keyAttrPairs","keyAttr","keyAttrPair","className","isString","classes","c","k","attr","getLocationHref","getComponentName","i","fill","source","name","replacementFactory","original","wrapped","markFunctionWrapped","DEBUG_BUILD","debug","addNonEnumerableProperty","obj","value","proto","getOriginalFunction","func","convertToPlainObject","isError","getOwnProperties","isEvent","newObj","serializeEventTarget","isInstanceOf","target","isElement","htmlTreeAsString","extractExceptionKeysForMessage","exception","keys","dropUndefinedKeys","inputValue","_dropUndefinedKeys","memoizationMap","memoVal","returnValue","isPojo","key","val","input","constructor","objectify","wat","objectified","isPrimitive","RESOLVED_RUNNER","withRandomSafeContext","cb","sym","globalWithSymbol","GLOBAL_OBJ","safeMathRandom","safeDateNow","truncate","str","max","snipLine","line","colno","newLine","lineLength","start","end","safeJoin","input","delimiter","output","i","value","isVueViewModel","getVueInternalName","isMatchingPattern","pattern","requireExactStringMatch","isString","isRegExp","stringMatchesSomePattern","testString","patterns","getCrypto","gbl","GLOBAL_OBJ","emptyUuid","getRandomByte","safeMathRandom","uuid4","crypto","withRandomSafeContext","c","getFirstException","event","getEventDescription","message","eventId","firstException","addExceptionTypeValue","value","type","exception","values","addExceptionMechanism","newMechanism","defaultMechanism","currentMechanism","mergedData","SEMVER_REGEXP","_parseInt","input","parseSemver","match","major","minor","patch","addContextToFrame","lines","frame","linesOfContext","maxLines","sourceLine","line","snipLine","lineIndex","checkOrSetAlreadyCaught","isAlreadyCaptured","addNonEnumerableProperty","ONE_SECOND_IN_MS","dateTimestampInSeconds","safeDateNow","createUnixTimestampInSecondsFunc","performance","GLOBAL_OBJ","timeOrigin","withRandomSafeContext","_cachedTimestampInSeconds","timestampInSeconds","cachedTimeOrigin","getBrowserTimeOrigin","threshold","performanceNow","dateNow","navigationStart","browserPerformanceTimeOrigin","makeSession","context","startingTime","timestampInSeconds","session","uuid4","sessionToJSON","updateSession","duration","closeSession","status","merge","initialObj","mergeObj","levels","output","key","generateTraceId","uuid4","generateSpanId","SCOPE_SPAN_FIELD","_setSpanForScope","scope","span","addNonEnumerableProperty","_getSpanForScope","DEFAULT_MAX_BREADCRUMBS","Scope","_Scope","generateTraceId","safeMathRandom","newScope","_setSpanForScope","_getSpanForScope","client","lastEventId","callback","user","updateSession","conversationId","tags","key","value","newAttributes","extras","extra","fingerprint","level","name","context","session","captureContext","scopeToMerge","scopeInstance","isPlainObject","attributes","contexts","propagationContext","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","dateTimestampInSeconds","truncate","attachment","newData","merge","exception","hint","eventId","uuid4","DEBUG_BUILD","debug","syntheticException","message","event","getDefaultCurrentScope","getGlobalSingleton","Scope","getDefaultIsolationScope","isActualPromise","p","kChainedCopy","chainAndCopyPromiseLike","original","onSuccess","onError","chained","value","err","copyProps","mutated","key","args","AsyncContextStack","scope","isolationScope","assignedScope","Scope","assignedIsolationScope","callback","maybePromiseResult","e","isThenable","chainAndCopyPromiseLike","getAsyncContextStack","registry","getMainCarrier","sentry","getSentryCarrier","getDefaultCurrentScope","getDefaultIsolationScope","withScope","withSetScope","stack","withIsolationScope","getStackAsyncContextStrategy","_isolationScope","setAsyncContextStrategy","strategy","registry","getMainCarrier","sentry","getSentryCarrier","getAsyncContextStrategy","carrier","getStackAsyncContextStrategy","getCurrentScope","carrier","getMainCarrier","getAsyncContextStrategy","getIsolationScope","getGlobalScope","getGlobalSingleton","Scope","withScope","rest","acs","scope","callback","withIsolationScope","isolationScope","getClient","getTraceContextFromScope","propagationContext","traceId","parentSpanId","propagationSpanId","traceContext","generateSpanId","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","SEMANTIC_ATTRIBUTE_PROFILE_ID","SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME","SEMANTIC_ATTRIBUTE_CACHE_HIT","SEMANTIC_ATTRIBUTE_CACHE_KEY","SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE","SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD","SEMANTIC_ATTRIBUTE_URL_FULL","SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE","GEN_AI_CONVERSATION_ID_ATTRIBUTE","SPAN_STATUS_UNSET","SPAN_STATUS_OK","SPAN_STATUS_ERROR","getSpanStatusFromHttpCode","httpStatus","setHttpStatus","span","spanStatus","SCOPE_ON_START_SPAN_FIELD","ISOLATION_SCOPE_ON_START_SPAN_FIELD","wrapScopeWithWeakRef","scope","WeakRefClass","GLOBAL_OBJ","unwrapScopeFromWeakRef","scopeRef","setCapturedScopesOnSpan","span","isolationScope","addNonEnumerableProperty","getCapturedScopesOnSpan","spanWithScopes","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","baggageHeaderToDynamicSamplingContext","baggageHeader","baggageObject","parseBaggageHeader","dynamicSamplingContext","acc","key","value","nonPrefixedKey","dynamicSamplingContextToSentryBaggageHeader","sentryPrefixedDSC","dscKey","dscValue","objectToBaggageHeader","isString","curr","currBaggageObject","baggageHeaderToObject","baggageEntry","eqIdx","keyOrValue","object","objectKey","objectValue","currentIndex","newBaggageHeader","DEBUG_BUILD","debug","ORG_ID_REGEX","DSN_REGEX","isValidProtocol","protocol","dsnToString","dsn","withPassword","host","path","pass","port","projectId","publicKey","dsnFromString","str","match","consoleSandbox","lastPath","split","projectMatch","dsnFromComponents","components","validateDsn","DEBUG_BUILD","component","debug","extractOrgIdFromDsnHost","extractOrgIdFromClient","client","options","org_id","makeDsn","from","parseSampleRate","sampleRate","rate","TRACEPARENT_REGEXP","extractTraceparentData","traceparent","matches","parentSampled","propagationContextFromHeaders","sentryTrace","baggage","traceparentData","dynamicSamplingContext","baggageHeaderToDynamicSamplingContext","generateTraceId","safeMathRandom","sampleRand","getSampleRandFromTraceparentAndDsc","traceId","parentSpanId","generateSentryTraceHeader","spanId","generateSpanId","sampled","sampledString","generateTraceparentHeader","dsc","parsedSampleRand","parseSampleRate","parsedSampleRate","shouldContinueTrace","client","baggageOrgId","clientOrgId","extractOrgIdFromClient","debug","TRACE_FLAG_NONE","TRACE_FLAG_SAMPLED","hasShownSpanDropWarning","spanToTransactionTraceContext","span","span_id","trace_id","data","op","parent_span_id","status","origin","links","spanToJSON","spanToTraceContext","spanId","isRemote","scope","getCapturedScopesOnSpan","generateSpanId","spanToTraceHeader","traceId","sampled","spanIsSampled","generateSentryTraceHeader","spanToTraceparentHeader","generateTraceparentHeader","convertSpanLinksForEnvelope","traceFlags","restContext","attributes","spanTimeInputToSeconds","input","ensureTimestampInSeconds","timestampInSeconds","timestamp","spanIsSentrySpan","spanIsOpenTelemetrySdkTraceBaseSpan","startTime","name","endTime","parentSpanId","getStatusMessage","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","castSpan","CHILD_SPANS_FIELD","ROOT_SPAN_FIELD","addChildSpanToSpan","childSpan","rootSpan","addNonEnumerableProperty","removeChildSpanFromSpan","getSpanDescendants","resultSet","addSpanChildren","childSpans","getRootSpan","getActiveSpan","carrier","getMainCarrier","acs","getAsyncContextStrategy","_getSpanForScope","getCurrentScope","showSpanDropWarning","consoleSandbox","updateSpanName","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","errorsInstrumented","registerSpanErrorInstrumentation","errorCallback","activeSpan","getActiveSpan","rootSpan","getRootSpan","message","DEBUG_BUILD","debug","addGlobalErrorInstrumentationHandler","addGlobalUnhandledRejectionInstrumentationHandler","hasSpansEnabled","maybeOptions","options","getClient","logIgnoredSpan","droppedSpan","debug","shouldIgnoreSpan","span","ignoreSpans","pattern","isStringOrRegExp","isMatchingPattern","DEBUG_BUILD","nameMatches","opMatches","reparentChildSpans","spans","dropSpan","droppedSpanParentId","droppedSpanId","value","DEFAULT_ENVIRONMENT","DEV_ENVIRONMENT","FROZEN_DSC_FIELD","freezeDscOnSpan","span","dsc","addNonEnumerableProperty","getDynamicSamplingContextFromClient","trace_id","client","options","public_key","DEFAULT_ENVIRONMENT","extractOrgIdFromClient","getDynamicSamplingContextFromScope","scope","propagationContext","getDynamicSamplingContextFromSpan","getClient","rootSpan","getRootSpan","rootSpanJson","spanToJSON","rootSpanAttributes","traceState","rootSpanSampleRate","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","applyLocalSampleRateToDsc","frozenDsc","traceStateDsc","dscOnTraceState","baggageHeaderToDynamicSamplingContext","source","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","name","hasSpansEnabled","spanIsSampled","getCapturedScopesOnSpan","spanToBaggageHeader","dynamicSamplingContextToSentryBaggageHeader","SentryNonRecordingSpan","spanContext","generateTraceId","generateSpanId","TRACE_FLAG_NONE","_timestamp","_key","_value","_values","_status","_name","_attributesOrStartTime","_startTime","_link","_links","_exception","_time","normalize","input","depth","maxProperties","visit","err","normalizeToSize","object","maxSize","normalized","jsonSize","key","value","memo","memoBuilder","memoize","unmemoize","stringified","stringifyValue","remainingDepth","valueWithToJSON","jsonValue","numAdded","visitable","convertToPlainObject","visitKey","visitValue","isVueViewModel","getVueInternalName","isSyntheticEvent","getFunctionName","objName","getConstructorName","prototype","utf8Length","normalizeUrlToBase","url","basePath","escapedBase","newUrl","inner","obj","createEnvelope","headers","items","addItemToEnvelope","envelope","newItem","forEachEnvelopeItem","callback","envelopeItems","envelopeItem","envelopeItemType","envelopeContainsItemType","types","_","type","encodeUTF8","input","carrier","getSentryCarrier","GLOBAL_OBJ","decodeUTF8","serializeEnvelope","envHeaders","parts","append","next","item","itemHeaders","payload","stringifiedPayload","normalize","concatBuffers","buffers","totalLength","acc","buf","merged","offset","buffer","parseEnvelope","env","readBinary","length","bin","readJson","i","envelopeHeader","itemHeader","binaryLength","createSpanEnvelopeItem","spanJson","createAttachmentEnvelopeItem","attachment","DATA_CATEGORY_OVERRIDES","_isOverriddenType","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","name","version","createEventEnvelopeHeaders","event","sdkInfo","tunnel","dsn","dynamicSamplingContext","dsnToString","_enhanceEventWithSdkInfo","event","newSdkInfo","eventSdkInfo","createSessionEnvelope","session","dsn","metadata","tunnel","sdkInfo","getSdkMetadataForEnvelopeHeader","envelopeHeaders","dsnToString","envelopeItem","createEnvelope","createEventEnvelope","eventType","createEventEnvelopeHeaders","createSpanEnvelope","spans","client","dscHasRequiredProps","dsc","getDynamicSamplingContextFromSpan","headers","beforeSendSpan","ignoreSpans","filteredSpans","span","shouldIgnoreSpan","spanToJSON","droppedSpans","convertToSpanJSON","spanJson","processedSpan","showSpanDropWarning","items","createSpanEnvelopeItem","logSpanStart","span","DEBUG_BUILD","description","op","parentSpanId","spanToJSON","spanId","sampled","spanIsSampled","rootSpan","getRootSpan","isRootSpan","header","infoParts","debug","logSpanEnd","msg","setMeasurement","name","value","unit","activeSpan","getActiveSpan","rootSpan","getRootSpan","DEBUG_BUILD","debug","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT","timedEventsToMeasurements","events","measurements","event","attributes","MAX_SPAN_COUNT","SentrySpan","spanContext","generateTraceId","generateSpanId","timestampInSeconds","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","link","links","_exception","_time","spanId","traceId","sampled","TRACE_FLAG_SAMPLED","TRACE_FLAG_NONE","key","value","attributes","timeInput","spanTimeInputToSeconds","name","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","endTimestamp","logSpanEnd","getStatusMessage","SEMANTIC_ATTRIBUTE_PROFILE_ID","SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME","timedEventsToMeasurements","getRootSpan","convertSpanLinksForEnvelope","attributesOrStartTime","startTime","DEBUG_BUILD","debug","time","isSpanTimeInput","event","client","getClient","sendSpanEnvelope","createSpanEnvelope","transactionEvent","getCapturedScopesOnSpan","getCurrentScope","isFullFinishedSpan","spanToJSON","capturedSpanScope","capturedSpanIsolationScope","normalizedRequest","spans","getSpanDescendants","span","isStandaloneSpan","source","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","transaction","spanToTransactionTraceContext","a","b","getDynamicSamplingContextFromSpan","measurements","input","envelope","spanItems","handleCallbackErrors","fn","onError","onFinally","onSuccess","maybePromiseResult","e","maybeHandlePromiseRejection","value","isThenable","chainAndCopyPromiseLike","result","err","sampleSpan","options","samplingContext","sampleRand","hasSpansEnabled","localSampleRateWasApplied","sampleRate","fallbackSampleRate","parsedSampleRate","parseSampleRate","DEBUG_BUILD","debug","shouldSample","SUPPRESS_TRACING_KEY","startSpan","options","callback","acs","getAcs","spanArguments","parseSentrySpanArguments","forceTransaction","customParentSpan","customScope","customForkedScope","withScope","getActiveSpanWrapper","scope","getCurrentScope","parentSpan","getParentSpan","activeSpan","SentryNonRecordingSpan","createChildOrRootSpan","_setSpanForScope","handleCallbackErrors","status","spanToJSON","startSpanManual","startInactiveSpan","withActiveSpan","continueTrace","carrier","getMainCarrier","getAsyncContextStrategy","sentryTrace","baggage","client","getClient","incomingDsc","baggageHeaderToDynamicSamplingContext","shouldContinueTrace","startNewTrace","propagationContext","propagationContextFromHeaders","span","suppressTracing","res","generateTraceId","safeMathRandom","DEBUG_BUILD","debug","hasSpansEnabled","dsc","getDynamicSamplingContextFromSpan","freezeDscOnSpan","isolationScope","getIsolationScope","_startChildSpan","addChildSpanToSpan","traceId","parentSpanId","parentSampled","spanIsSampled","_startRootSpan","logSpanStart","setCapturedScopesOnSpan","initialCtx","ctx","spanTimeInputToSeconds","name","mutableSpanSamplingData","finalParentSampled","finalAttributes","currentPropagationContext","sampled","sampleRate","localSampleRateWasApplied","sampleSpan","parseSampleRate","rootSpan","SentrySpan","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","spanId","childSpan","_getSpanForScope","getRootSpan","TRACING_DEFAULTS","FINISH_REASON_HEARTBEAT_FAILED","FINISH_REASON_IDLE_TIMEOUT","FINISH_REASON_FINAL_TIMEOUT","FINISH_REASON_EXTERNAL_FINISH","startIdleSpan","startSpanOptions","options","activities","_finished","_idleTimeoutID","_finishReason","_autoFinishAllowed","_cleanupHooks","idleTimeout","finalTimeout","childSpanTimeout","beforeSpanEnd","trimIdleSpanEndTimestamp","client","getClient","hasSpansEnabled","span","SentryNonRecordingSpan","dsc","getDynamicSamplingContextFromSpan","freezeDscOnSpan","scope","getCurrentScope","previousActiveSpan","getActiveSpan","_startIdleSpan","target","thisArg","args","definedEndTimestamp","rest","timestamp","timestampInSeconds","spanEndTimestamp","spanTimeInputToSeconds","spans","getSpanDescendants","child","spanJson","spanToJSON","onIdleSpanEnded","ignoreSpans","latestSpanEndTimestamp","acc","current","currentSpanJson","shouldIgnoreSpan","spanStartTimestamp","endTimestamp","_cancelIdleTimeout","_restartIdleTimeout","_restartChildSpanTimeout","_pushActivity","spanId","_popActivity","cleanup","_setSpanForScope","spanJSON","startTimestamp","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","currentStatus","debug","childSpans","discardedSpans","childSpan","DEBUG_BUILD","childSpanJSON","childEndTimestamp","childStartTimestamp","spanStartedBeforeIdleSpanEnd","timeoutWithMarginOfError","spanEndedBeforeFinalTimeout","stringifiedSpan","removeChildSpanFromSpan","startedSpan","SentrySpan","endedSpan","spanToAllowAutoFinish","startInactiveSpan","STATE_PENDING","STATE_RESOLVED","STATE_REJECTED","resolvedSyncPromise","value","SyncPromise","resolve","rejectedSyncPromise","reason","_","reject","_SyncPromise","executor","onfulfilled","onrejected","result","e","val","onfinally","isRejected","cachedHandlers","handler","setResult","state","isThenable","notifyEventProcessors","processors","event","hint","index","result","_notifyEventProcessors","isThenable","resolvedSyncPromise","error","rejectedSyncPromise","processor","DEBUG_BUILD","debug","final","parsedStackResults","lastSentryKeysCount","lastNativeKeysCount","cachedFilenameDebugIds","getFilenameToDebugIdMap","stackParser","sentryDebugIdMap","GLOBAL_OBJ","nativeDebugIdMap","sentryDebugIdKeys","nativeDebugIdKeys","processDebugIds","debugIdKeys","debugIdMap","key","debugId","result","parsedStack","i","filename","getDebugImagesForResources","resource_paths","filenameDebugIdMap","images","path","normalizedPath","normalizeStackTracePath","applyScopeDataToEvent","event","data","fingerprint","span","breadcrumbs","sdkProcessingMetadata","applyDataToEvent","applySpanToEvent","applyFingerprintToEvent","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","extra","tags","attributes","user","contexts","level","eventProcessors","attachments","propagationContext","transactionName","mergeAndOverwriteScopeData","merge","prop","mergeVal","getCombinedScopeData","isolationScope","currentScope","scopeData","getGlobalScope","mergedBreadcrumbs","spanToTraceContext","getDynamicSamplingContextFromSpan","rootSpan","getRootSpan","spanToJSON","prepareEvent","options","event","hint","scope","client","isolationScope","normalizeDepth","normalizeMaxBreadth","prepared","uuid4","dateTimestampInSeconds","integrations","i","applyClientOptions","applyIntegrationsMetadata","applyDebugIds","finalScope","getFinalScope","addExceptionMechanism","clientEventProcessors","data","getCombinedScopeData","attachments","applyScopeDataToEvent","eventProcessors","resolvedSyncPromise","notifyEventProcessors","evt","applyDebugMeta","normalizeEvent","environment","release","dist","maxValueLength","DEFAULT_ENVIRONMENT","request","truncate","exception","stackParser","filenameDebugIdMap","getFilenameToDebugIdMap","frame","images","filename","debug_id","integrationNames","depth","maxBreadth","normalized","b","normalize","span","captureContext","Scope","parseEventHintOrCaptureContext","hintIsScopeOrFunction","hintIsScopeContext","captureContextKeys","key","captureException","exception","hint","getCurrentScope","parseEventHintOrCaptureContext","captureMessage","message","captureContext","level","captureEvent","event","setContext","name","context","getIsolationScope","setExtras","extras","setExtra","key","extra","setTags","tags","setTag","value","setUser","user","setConversationId","conversationId","lastEventId","captureCheckIn","checkIn","upsertMonitorConfig","scope","client","getClient","DEBUG_BUILD","debug","uuid4","withMonitor","monitorSlug","callback","runCallback","checkInId","now","timestampInSeconds","finishCheckIn","status","maybePromiseResult","e","isThenable","r","withIsolationScope","startNewTrace","flush","timeout","close","isInitialized","isEnabled","addEventProcessor","startSession","isolationScope","getCombinedScopeData","userAgent","GLOBAL_OBJ","session","makeSession","currentSession","updateSession","endSession","closeSession","_sendSessionUpdate","captureSession","end","SENTRY_API_VERSION","getBaseApiEndpoint","dsn","protocol","port","_getIngestEndpoint","_encodedAuth","sdkInfo","params","getEnvelopeEndpointWithUrlEncodedAuth","tunnel","getReportDialogEndpoint","dsnLike","dialogOptions","makeDsn","endpoint","encodedOptions","dsnToString","key","user","installedIntegrations","filterDuplicates","integrations","integrationsByName","currentInstance","name","existingInstance","getIntegrationsToSetup","options","defaultIntegrations","userIntegrations","integration","resolvedUserIntegrations","setupIntegrations","client","integrationIndex","setupIntegration","afterSetupIntegrations","DEBUG_BUILD","debug","callback","event","hint","processor","addIntegration","getClient","defineIntegration","fn","isAttributeObject","maybeObj","attributeValueToTypedAttributeValue","rawValue","useFallback","value","unit","attributeValue","getTypedAttributeValue","checkedUnit","stringValue","serializeAttributes","attributes","fallback","serializedAttributes","key","typedValue","primitiveType","SEQUENCE_ATTR_KEY","_sequenceNumber","_previousTimestampMs","getSequenceAttribute","timestampInSeconds","nowMs","value","_getTraceInfoFromScope","client","scope","withScope","span","getActiveSpan","traceContext","spanToTraceContext","getTraceContextFromScope","getDynamicSamplingContextFromSpan","getDynamicSamplingContextFromScope","SEVERITY_TEXT_TO_SEVERITY_NUMBER","createLogContainerEnvelopeItem","items","createLogEnvelope","logs","metadata","tunnel","dsn","headers","dsnToString","createEnvelope","MAX_LOG_BUFFER_SIZE","setLogAttribute","logAttributes","key","value","setEvenIfPresent","_INTERNAL_captureSerializedLog","client","serializedLog","bufferMap","_getBufferMap","logBuffer","_INTERNAL_getLogBuffer","_INTERNAL_flushLogsBuffer","_INTERNAL_captureLog","beforeLog","currentScope","getCurrentScope","captureSerializedLog","getClient","DEBUG_BUILD","debug","release","environment","enableLogs","beforeSendLog","traceContext","_getTraceInfoFromScope","processedLogAttributes","id","email","username","scopeAttributes","getCombinedScopeData","getIsolationScope","name","version","replay","replayId","beforeLogMessage","isParameterizedString","__sentry_template_string__","__sentry_template_values__","param","index","span","_getSpanForScope","processedLog","log","consoleSandbox","level","message","severityNumber","timestamp","timestampInSeconds","sequenceAttr","getSequenceAttribute","SEVERITY_TEXT_TO_SEVERITY_NUMBER","serializeAttributes","maybeLogBuffer","clientOptions","envelope","createLogEnvelope","getGlobalSingleton","createMetricContainerEnvelopeItem","items","createMetricEnvelope","metrics","metadata","tunnel","dsn","headers","dsnToString","createEnvelope","MAX_METRIC_BUFFER_SIZE","setMetricAttribute","metricAttributes","key","value","setEvenIfPresent","_INTERNAL_captureSerializedMetric","client","serializedMetric","bufferMap","_getBufferMap","metricBuffer","_INTERNAL_getMetricBuffer","_INTERNAL_flushMetricsBuffer","_enrichMetricAttributes","beforeMetric","user","release","environment","processedMetricAttributes","name","version","replay","replayId","_buildSerializedMetric","metric","currentScope","scopeAttributes","traceContext","_getTraceInfoFromScope","span","_getSpanForScope","traceId","spanId","timestamp","timestampInSeconds","sequenceAttr","getSequenceAttribute","serializeAttributes","_INTERNAL_captureMetric","options","getCurrentScope","captureSerializedMetric","getClient","DEBUG_BUILD","debug","_experiments","enableMetrics","beforeSendMetric","getCombinedScopeData","getIsolationScope","enrichedMetric","beforeSendCallback","processedMetric","maybeMetricBuffer","clientOptions","envelope","createMetricEnvelope","getGlobalSingleton","safeUnref","timer","SENTRY_BUFFER_FULL_ERROR","makePromiseBuffer","limit","buffer","isReady","remove","task","add","taskProducer","rejectedSyncPromise","drain","timeout","resolvedSyncPromise","drainPromise","promises","resolve","safeUnref","DEFAULT_RETRY_AFTER","parseRetryAfterHeader","header","now","safeDateNow","headerDelay","headerDate","disabledUntil","limits","dataCategory","isRateLimited","updateRateLimits","statusCode","headers","updatedRateLimits","rateLimitHeader","retryAfterHeader","limit","retryAfter","categories","namespaces","delay","category","DEFAULT_TRANSPORT_BUFFER_SIZE","createTransport","options","makeRequest","buffer","makePromiseBuffer","rateLimits","flush","timeout","send","envelope","filteredEnvelopeItems","forEachEnvelopeItem","item","type","dataCategory","envelopeItemTypeToDataCategory","isRateLimited","filteredEnvelope","createEnvelope","recordEnvelopeLoss","reason","envelopeContainsItemType","DEBUG_BUILD","debug","requestTask","serializeEnvelope","response","updateRateLimits","error","result","SENTRY_BUFFER_FULL_ERROR","createClientReportEnvelope","discarded_events","dsn","timestamp","clientReportItem","dateTimestampInSeconds","createEnvelope","getPossibleEventMessages","event","possibleMessages","lastException","convertTransactionEventToSpanJson","event","trace_id","parent_span_id","span_id","status","origin","data","op","SEMANTIC_ATTRIBUTE_PROFILE_ID","SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME","convertSpanJsonToTransactionEvent","span","ALREADY_SEEN_ERROR","MISSING_RELEASE_FOR_SESSION_ERROR","INTERNAL_ERROR_SYMBOL","DO_NOT_SEND_EVENT_SYMBOL","DEFAULT_FLUSH_INTERVAL","_makeInternalError","message","_makeDoNotSendEventError","_isInternalError","error","_isDoNotSendEventError","setupWeightBasedFlushing","client","afterCaptureHook","flushHook","estimateSizeFn","flushFn","weight","flushTimeout","isTimerActive","item","safeUnref","Client","options","makePromiseBuffer","DEFAULT_TRANSPORT_BUFFER_SIZE","makeDsn","DEBUG_BUILD","debug","url","getEnvelopeEndpointWithUrlEncodedAuth","estimateLogSizeInBytes","_INTERNAL_flushLogsBuffer","estimateMetricSizeInBytes","_INTERNAL_flushMetricsBuffer","exception","hint","scope","eventId","uuid4","checkOrSetAlreadyCaught","hintWithEventId","event","res","level","currentScope","eventMessage","isParameterizedString","isMessage","isPrimitive","promisedEvent","sdkProcessingMetadata","capturedSpanScope","capturedSpanIsolationScope","dataCategory","getDataCategoryByType","session","updateSession","timeout","transport","clientFinished","transportFlushed","result","eventProcessor","name","integrationName","integration","isAlreadyInstalled","setupIntegration","afterSetupIntegrations","env","createEventEnvelope","attachment","addItemToEnvelope","createAttachmentEnvelopeItem","sendResponse","clientReleaseOption","clientEnvironmentOption","DEFAULT_ENVIRONMENT","sessionAttrs","createSessionEnvelope","reason","category","count","key","hook","callback","hookCallbacks","uniqueCallback","args","rest","callbacks","envelope","integrations","setupIntegrations","crashed","errored","exceptions","ex","sessionNonTerminal","ticked","resolve","isolationScope","prepareEvent","evt","getTraceContextFromScope","dynamicSamplingContext","getDynamicSamplingContextFromScope","getCurrentScope","getIsolationScope","isErrorEvent","getPossibleEventMessages","finalEvent","sampleRate","isTransaction","isTransactionEvent","isError","beforeSendLabel","parsedSampleRate","parseSampleRate","safeMathRandom","rejectedSyncPromise","prepared","processBeforeSend","_validateBeforeSendResult","processedEvent","spanCount","spanCountBefore","spanCountAfter","droppedSpanCount","transactionInfo","source","taskProducer","value","SENTRY_BUFFER_FULL_ERROR","outcomes","quantity","createClientReportEnvelope","dsnToString","type","beforeSendResult","invalidValueError","isThenable","isPlainObject","e","beforeSend","beforeSendTransaction","beforeSendSpan","ignoreSpans","rootSpanJson","convertTransactionEventToSpanJson","shouldIgnoreSpan","processedRootSpanJson","merge","convertSpanJsonToTransactionEvent","showSpanDropWarning","processedSpans","initialSpans","span","reparentChildSpans","processedSpan","droppedSpans","metric","estimateAttributesSizeInBytes","log","attributes","estimatePrimitiveSizeInBytes","createCheckInEnvelope","checkIn","dynamicSamplingContext","metadata","tunnel","dsn","headers","dsnToString","item","createCheckInEnvelopeItem","createEnvelope","addUserAgentToTransportHeaders","options","sdkMetadata","sdkUserAgent","parseStackFrames","stackParser","error","hasSentryFetchUrlHost","isError","_enhanceErrorWithSentryInfo","exceptionFromError","exception","frames","getErrorPropertyFromObject","obj","prop","value","getMessageForObject","message","keys","extractExceptionKeysForMessage","isErrorEvent","className","getObjectClassName","prototype","getException","client","mechanism","hint","isPlainObject","normalizeDepth","extras","normalizeToSize","errorFromProp","ex","eventFromUnknownInput","event","addExceptionTypeValue","addExceptionMechanism","eventFromMessage","level","attachStacktrace","isParameterizedString","__sentry_template_string__","__sentry_template_values__","ServerRuntimeClient","Client","options","registerSpanErrorInstrumentation","addUserAgentToTransportHeaders","exception","hint","event","eventFromUnknownInput","resolvedSyncPromise","message","level","eventFromMessage","scope","setCurrentRequestSessionErroredOrCrashed","checkIn","monitorConfig","id","uuid4","DEBUG_BUILD","debug","release","environment","tunnel","serializedCheckIn","dynamicSamplingContext","traceContext","_getTraceInfoFromScope","envelope","createCheckInEnvelope","hookName","makePromiseBuffer","DEFAULT_TRANSPORT_BUFFER_SIZE","currentScope","isolationScope","metric","eventHint","requestSession","getIsolationScope","isHandledException","initAndBind","clientClass","options","DEBUG_BUILD","debug","consoleSandbox","getCurrentScope","client","setCurrentClient","MIN_DELAY","START_DELAY","MAX_DELAY","makeOfflineTransport","createTransport","log","args","DEBUG_BUILD","debug","options","transport","store","retryDelay","flushTimer","shouldQueue","env","error","envelopeContainsItemType","flushIn","delay","safeUnref","found","send","e","flushWithBackOff","envelope","isRetry","result","parseRetryAfterHeader","timeout","MULTIPLEXED_TRANSPORT_EXTRA_KEY","eventFromEnvelope","env","types","event","forEachEnvelopeItem","item","type","makeOverrideReleaseTransport","createTransport","release","options","transport","envelope","overrideDsn","dsn","createEnvelope","makeMultiplexedTransport","matcher","fallbackTransport","otherTransports","actualMatcher","args","getTransport","key","validatedDsn","dsnFromString","url","getEnvelopeEndpointWithUrlEncodedAuth","send","getEvent","eventTypes","transports","result","t","transportsWithFallback","flush","timeout","allTransports","r","SKIPPED_AI_PROVIDERS","_INTERNAL_skipAiProviderWrapping","modules","module","DEBUG_BUILD","debug","_INTERNAL_shouldSkipAiProviderWrapping","_INTERNAL_clearAiProviderSkips","FALSY_ENV_VALUES","TRUTHY_ENV_VALUES","envToBool","value","options","normalized","DEFAULT_BASE_URL","isURLObjectRelative","url","parseStringToURLObject","urlBase","isRelative","base","fullUrlObject","getSanitizedUrlStringFromUrlObject","newUrl","getHttpSpanNameFromUrlObject","urlObject","kind","request","routeName","method","route","getHttpSpanDetailsFromUrlObject","spanOrigin","attributes","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD","SEMANTIC_ATTRIBUTE_URL_FULL","parseUrl","match","query","fragment","stripUrlQueryAndFragment","urlPath","getSanitizedUrlString","protocol","host","path","filteredHost","stripDataUrlContent","includeDataPrefix","mimeType","isBase64","dataStart","dataPrefix","data","isSentryRequestUrl","url","client","dsn","tunnel","checkDsn","checkTunnel","removeTrailingSlash","urlParts","parseStringToURLObject","isURLObjectRelative","str","parameterize","strings","values","formatted","fmt","handleTunnelRequest","options","request","allowedDsns","body","envelopeHeader","parseEnvelope","dsn","allowed","debug","dsnComponents","makeDsn","sentryIngestUrl","getEnvelopeEndpointWithUrlEncodedAuth","error","addAutoIpAddressToUser","objWithMaybeUser","addAutoIpAddressToSession","session","applySdkMetadata","options","name","names","source","sdk","SDK_VERSION","getTraceData","options","client","getClient","isEnabled","carrier","getMainCarrier","acs","getAsyncContextStrategy","scope","getCurrentScope","span","getActiveSpan","sentryTrace","spanToTraceHeader","scopeToTraceHeader","dsc","getDynamicSamplingContextFromSpan","getDynamicSamplingContextFromScope","baggage","dynamicSamplingContextToSentryBaggageHeader","TRACEPARENT_REGEXP","debug","traceData","spanToTraceparentHeader","scopeToTraceparentHeader","traceId","sampled","propagationSpanId","generateSentryTraceHeader","generateTraceparentHeader","NOT_PROPAGATED_MESSAGE","shouldPropagateTraceForUrl","url","tracePropagationTargets","decisionMap","cachedDecision","DEBUG_BUILD","debug","decision","stringMatchesSomePattern","getTraceMetaTags","traceData","getTraceData","key","value","debounce","func","wait","options","callbackReturnValue","timerId","maxTimerId","maxWait","setTimeoutImpl","invokeFunc","cancelTimers","flush","debounced","winterCGHeadersToDict","winterCGHeaders","headers","value","key","headersToDict","reqHeaders","winterCGRequestToRequestData","req","extractQueryParamsFromUrl","httpRequestToRequestData","request","host","protocol","url","absoluteUrl","getAbsoluteUrl","data","cookies","SENSITIVE_HEADER_SNIPPETS","PII_HEADER_SNIPPETS","httpHeadersToSpanAttributes","sendDefaultPii","lifecycle","spanAttributes","lowerCasedHeaderKey","isSetCookie","semicolonIndex","cookieString","cookie","equalSignIndex","cookieKey","cookieValue","lowerCasedCookieKey","addSpanAttribute","normalizeAttributeKey","headerKey","sendPii","headerValue","handleHttpHeader","normalizedKey","lowerCasedKey","snippet","v","queryParams","DEFAULT_BREADCRUMBS","addBreadcrumb","breadcrumb","hint","client","getClient","isolationScope","getIsolationScope","beforeBreadcrumb","maxBreadcrumbs","mergedBreadcrumb","dateTimestampInSeconds","finalBreadcrumb","consoleSandbox","originalFunctionToString","INTEGRATION_NAME","SETUP_CLIENTS","_functionToStringIntegration","args","originalFunction","getOriginalFunction","context","getClient","client","functionToStringIntegration","DEFAULT_IGNORE_ERRORS","INTEGRATION_NAME","eventFiltersIntegration","options","mergedOptions","client","clientOptions","_mergeOptions","event","_hint","_shouldDropEvent","inboundFiltersIntegration","internalOptions","_isIgnoredTransaction","DEBUG_BUILD","debug","getEventDescription","_isIgnoredError","_isUselessError","_isDeniedUrl","_getEventFilterUrl","_isAllowedUrl","ignoreErrors","getPossibleEventMessages","message","stringMatchesSomePattern","ignoreTransactions","name","denyUrls","url","allowUrls","_getLastValidUrl","frames","i","frame","value","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","parser","key","limit","event","hint","isInstanceOf","originalException","aggregateExceptionsFromError","error","prevExceptions","exception","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","isExceptionGroup","childError","i","source","parentId","DEFAULT_KEY","DEFAULT_LIMIT","INTEGRATION_NAME","_linkedErrorsIntegration","options","limit","key","event","hint","client","applyAggregateErrorsToEvent","exceptionFromError","linkedErrorsIntegration","filenameMetadataMap","parsedStacks","getFilenameToMetadataMap","parser","GLOBAL_OBJ","filenameMap","stack","metadata","frames","frame","ensureMetadataStacksAreParsed","getMetadataForUrl","filename","addMetadataToStackFrames","event","exception","stripMetadataFromStackFrames","moduleMetadataIntegration","client","envelope","forEachEnvelopeItem","item","type","event","stripMetadataFromStackFrames","stackParser","addMetadataToStackFrames","parseCookie","str","obj","index","eqIdx","endIdx","key","val","ipHeaderNames","getClientIPAddress","headers","lowerCaseHeaders","key","headerName","rawValue","value","parseForwardedHeader","v","acc","val","ip","isIP","part","str","DEFAULT_INCLUDE","INTEGRATION_NAME","_requestDataIntegration","options","include","event","_hint","client","sdkProcessingMetadata","normalizedRequest","ipAddress","includeWithDefaultPiiApplied","addNormalizedRequestDataToEvent","requestDataIntegration","req","additionalData","extractNormalizedRequestData","ip","getClientIPAddress","requestData","headers","ipHeaderNames","ipHeaderName","cookies","parseCookie","addConsoleInstrumentationHandler","handler","type","addHandler","maybeInstrument","instrumentConsole","GLOBAL_OBJ","CONSOLE_LEVELS","level","fill","originalConsoleMethod","originalConsoleMethods","args","triggerHandlers","severityLevelFromString","level","INTEGRATION_NAME","_captureConsoleIntegration","options","levels","CONSOLE_LEVELS","handled","client","GLOBAL_OBJ","addConsoleInstrumentationHandler","args","level","getClient","consoleHandler","captureConsoleIntegration","severityLevel","severityLevelFromString","syntheticException","captureContext","withScope","scope","event","addExceptionMechanism","message","safeJoin","error","arg","captureException","INTEGRATION_NAME","_dedupeIntegration","previousEvent","currentEvent","_shouldDropEvent","DEBUG_BUILD","debug","dedupeIntegration","_isSameMessageEvent","_isSameExceptionEvent","currentMessage","previousMessage","_isSameFingerprint","_isSameStacktrace","previousException","_getExceptionFromEvent","currentException","currentFrames","getFramesFromEvent","previousFrames","i","frameA","frameB","currentFingerprint","previousFingerprint","event","INTEGRATION_NAME","_extraErrorDataIntegration","options","depth","captureErrorCause","event","hint","client","maxValueLength","_enhanceEventWithErrorData","extraErrorDataIntegration","isError","exceptionName","errorData","_extractErrorData","contexts","normalizedErrorData","normalize","isPlainObject","addNonEnumerableProperty","error","nativeKeys","extraErrorInfo","key","value","truncate","errorName","serializedError","oO","DEBUG_BUILD","debug","normalizeArray","parts","allowAboveRoot","up","i","last","splitPathRe","splitPath","filename","truncated","resolve","args","resolvedPath","resolvedAbsolute","path","p","trim","arr","start","end","relative","from","to","fromParts","toParts","length","samePartsLength","outputParts","normalizePath","isPathAbsolute","isAbsolute","trailingSlash","normalizedPath","join","dirname","result","root","dir","basename","ext","f","INTEGRATION_NAME","rewriteFramesIntegration","options","root","prefix","isBrowser","GLOBAL_OBJ","iteratee","generateIteratee","_processExceptionsEvent","event","value","_processStacktrace","stacktrace","f","originalEvent","processedEvent","frame","isWindowsFrame","startsWithSlash","oldFilename","filename","base","relative","basename","AUTH_OPERATIONS_TO_INSTRUMENT","AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT","FILTER_MAPPINGS","DB_OPERATIONS_TO_INSTRUMENT","markAsInstrumented","fn","isInstrumented","extractOperation","method","headers","translateFiltersIntoMethods","key","query","filter","value","instrumentAuthOperation","operation","isAdmin","target","thisArg","argumentsList","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","span","res","captureException","err","instrumentSupabaseAuthClient","supabaseClientInstance","auth","authOperation","instrumentSupabaseClientConstructor","SupabaseClient","rv","PostgRESTQueryBuilder","instrumentPostgRESTQueryBuilder","instrumentPostgRESTFilterBuilder","PostgRESTFilterBuilder","operations","typedThis","pathParts","table","queryItems","body","isPlainObject","description","attributes","setHttpStatus","supabaseContext","scope","e","addExceptionMechanism","breadcrumb","data","addBreadcrumb","DEBUG_BUILD","debug","instrumentSupabaseClient","supabaseClient","SupabaseClientConstructor","INTEGRATION_NAME","_supabaseIntegration","supabaseIntegration","options","SQL_OPERATION_REGEX","CONNECTION_CONTEXT_SYMBOL","INSTRUMENTED_MARKER","QUERY_FROM_INSTRUMENTED_SQL","instrumentPostgresJsSql","sql","options","DEBUG_BUILD","debug","_instrumentSqlInstance","parentConnectionContext","proxiedSql","target","thisArg","argumentsList","query","_wrapSingleQueryHandle","prop","original","_wrapQueryMethod","_wrapCallbackMethod","_attachConnectionContext","args","parentSqlInstance","parentContext","result","sqlInstance","callback","wrappedCallback","instrumentedSql","newArgs","originalHandle","wrappedHandle","_shouldCreateSpans","fullQuery","_reconstructQuery","sanitizedSqlQuery","_sanitizeSqlQuery","startSpanManual","span","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","connectionContext","_setConnectionAttributes","e","queryWithCallbacks","resolveTarget","resolveThisArg","resolveArgs","_setOperationName","rejectTarget","rejectThisArg","rejectArgs","getActiveSpan","strings","acc","str","i","sqlQuery","portNumber","sanitizedQuery","command","operationMatch","opts","host","port","DEFAULT_LIMIT","INTEGRATION_NAME","originalExceptionIsZodError","originalException","isError","flattenIssue","issue","flattenIssuePath","path","p","formatIssueMessage","zodError","errorKeyMap","iss","issuePath","errorKeys","rootExpectedType","truncate","applyZodErrorsToEvent","limit","saveZodIssuesAsAttachment","event","hint","flattenedIssues","e","_zodErrorsIntegration","options","originalEvent","zodErrorsIntegration","thirdPartyErrorFilterIntegration","options","client","envelope","forEachEnvelopeItem","item","type","event","stripMetadataFromStackFrames","stackParser","addMetadataToStackFrames","frameKeys","getBundleKeysForAllFramesWithFilenames","arrayMethod","keys","key","isSentryInternalFrame","frame","frameIndex","SENTRY_INTERNAL_FN_APPLY","len","i","SENTRY_INTERNAL_COMMENT","ignoreSentryInternalFrames","frames","getFramesFromEvent","index","BUNDLER_PLUGIN_APP_KEY_PREFIX","INTEGRATION_NAME","consoleIntegration","options","levels","CONSOLE_LEVELS","client","addConsoleInstrumentationHandler","args","level","getClient","addConsoleBreadcrumb","breadcrumb","severityLevelFromString","formatConsoleArgs","assertionArgs","addBreadcrumb","values","GLOBAL_OBJ","safeJoin","_INTERNAL_FLAG_BUFFER_SIZE","_INTERNAL_MAX_FLAGS_PER_SPAN","SPAN_FLAG_ATTRIBUTE_PREFIX","_INTERNAL_copyFlagsFromScopeToEvent","event","flagContext","getCurrentScope","flagBuffer","_INTERNAL_insertFlagToScope","name","value","maxSize","scopeContexts","flags","_INTERNAL_insertToFlagBuffer","DEBUG_BUILD","debug","index","f","_INTERNAL_addFeatureFlagToActiveSpan","maxFlagsPerSpan","span","getActiveSpan","attributes","spanToJSON","key","featureFlagsIntegration","event","_hint","_client","_INTERNAL_copyFlagsFromScopeToEvent","name","value","_INTERNAL_insertFlagToScope","_INTERNAL_addFeatureFlagToActiveSpan","growthbookIntegration","growthbookClass","proto","fill","_wrapAndCaptureBooleanResult","event","_hint","_client","_INTERNAL_copyFlagsFromScopeToEvent","original","args","flagName","result","_INTERNAL_insertFlagToScope","_INTERNAL_addFeatureFlagToActiveSpan","INTEGRATION_NAME","_conversationIdIntegration","client","span","scopeData","getCurrentScope","isolationScopeData","getIsolationScope","conversationId","GEN_AI_CONVERSATION_ID_ATTRIBUTE","conversationIdIntegration","isProfilingIntegrationWithProfiler","integration","startProfiler","client","getClient","DEBUG_BUILD","debug","stopProfiler","profiler","instrumentFetchRequest","handlerData","shouldCreateSpan","shouldAttachHeaders","spans","spanOriginOrOptions","method","url","shouldCreateSpanResult","hasSpansEnabled","spanId","span","endSpan","_callOnRequestSpanEnd","spanOrigin","propagateTraceparent","hasParent","getActiveSpan","startInactiveSpan","getSpanStartOptions","SentryNonRecordingSpan","request","options","headers","_addTracingHeadersToFetchRequest","client","getClient","fetchHint","fetchOptionsObj","traceHeaders","getTraceData","sentryTrace","baggage","traceparent","originalHeaders","isRequest","isHeaders","newHeaders","prevBaggageHeader","baggageHeaderHasSentryBaggageValues","header","prevBaggageHeaderWithSentryValues","existingSentryTraceHeader","existingTraceparentHeader","existingBaggageHeader","newBaggageHeaders","headerItem","setHttpStatus","contentLength","contentLengthNum","baggageHeader","baggageEntry","SENTRY_BAGGAGE_KEY_PREFIX","isInstanceOf","sanitizedUrl","stripDataUrlContent","getFetchSpanAttributes","parsedUrl","parseStringToURLObject","getSanitizedUrlStringFromUrlObject","attributes","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","isURLObjectRelative","trpcCaptureContext","captureIfError","nextResult","captureException","trpcMiddleware","options","opts","path","type","next","rawInput","getRawInput","clientOptions","getClient","trpcContext","addNonEnumerableProperty","normalize","rawRes","withIsolationScope","scope","startSpanManual","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","span","e","captureError","error","errorType","extraData","getClient","activeSpan","getActiveSpan","captureException","wrapMethodHandler","serverInstance","methodName","fill","originalMethod","name","args","handler","wrappedHandler","createWrappedHandler","originalHandler","handlerName","handlerArgs","createErrorCapturingHandler","error","DEBUG_BUILD","debug","result","captureHandlerError","extraData","captureError","wrapToolHandlers","wrapResourceHandlers","wrapPromptHandlers","wrapAllMCPHandlers","MCP_METHOD_NAME_ATTRIBUTE","MCP_REQUEST_ID_ATTRIBUTE","MCP_SESSION_ID_ATTRIBUTE","MCP_TRANSPORT_ATTRIBUTE","MCP_SERVER_NAME_ATTRIBUTE","MCP_SERVER_TITLE_ATTRIBUTE","MCP_SERVER_VERSION_ATTRIBUTE","MCP_PROTOCOL_VERSION_ATTRIBUTE","MCP_TOOL_NAME_ATTRIBUTE","MCP_RESOURCE_URI_ATTRIBUTE","MCP_PROMPT_NAME_ATTRIBUTE","MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE","MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE","MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE","MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE","MCP_REQUEST_ARGUMENT","MCP_LOGGING_LEVEL_ATTRIBUTE","MCP_LOGGING_LOGGER_ATTRIBUTE","MCP_LOGGING_DATA_TYPE_ATTRIBUTE","MCP_LOGGING_MESSAGE_ATTRIBUTE","NETWORK_TRANSPORT_ATTRIBUTE","NETWORK_PROTOCOL_VERSION_ATTRIBUTE","CLIENT_ADDRESS_ATTRIBUTE","CLIENT_PORT_ATTRIBUTE","MCP_SERVER_OP_VALUE","MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE","MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE","MCP_FUNCTION_ORIGIN_VALUE","MCP_NOTIFICATION_ORIGIN_VALUE","MCP_ROUTE_SOURCE_VALUE","isJsonRpcRequest","message","isJsonRpcNotification","isJsonRpcResponse","validateMcpServerInstance","instance","DEBUG_BUILD","debug","isValidContentItem","item","buildAllContentItemAttributes","content","includeContent","attributes","MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE","i","item","isValidContentItem","prefix","safeSet","key","value","resource","extractToolResultAttributes","result","recordOutputs","MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE","extractPromptResultAttributes","MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE","MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE","messages","message","attrName","sessionToSessionData","statelessSessionData","getSessionData","transport","sessionId","setSessionData","data","storeSessionDataForTransport","sessionData","updateSessionDataForTransport","partialSessionData","existingData","getClientInfoForTransport","getProtocolVersionForTransport","getSessionDataForTransport","cleanupSessionDataForTransport","extractPartyInfo","obj","partyInfo","isValidContentItem","extractSessionDataFromInitializeRequest","request","sessionData","extractSessionDataFromInitializeResponse","result","getClientAttributes","transport","clientInfo","getClientInfoForTransport","attributes","buildClientAttributesFromInfo","getServerAttributes","serverInfo","getSessionDataForTransport","MCP_SERVER_NAME_ATTRIBUTE","MCP_SERVER_TITLE_ATTRIBUTE","MCP_SERVER_VERSION_ATTRIBUTE","buildServerAttributesFromInfo","extractClientInfo","extra","getTransportTypes","transportName","networkTransport","lowerTransportName","buildTransportAttributes","sessionId","mcpTransport","clientAttributes","serverAttributes","protocolVersion","getProtocolVersionForTransport","MCP_SESSION_ID_ATTRIBUTE","CLIENT_ADDRESS_ATTRIBUTE","CLIENT_PORT_ATTRIBUTE","MCP_TRANSPORT_ATTRIBUTE","NETWORK_TRANSPORT_ATTRIBUTE","NETWORK_PROTOCOL_VERSION_ATTRIBUTE","MCP_PROTOCOL_VERSION_ATTRIBUTE","sessionToSpanMap","statelessSpanMap","getOrCreateSpanMap","transport","sessionId","spanMap","storeSpanForRequest","requestId","span","method","completeSpanWithResults","result","options","spanData","sessionData","extractSessionDataFromInitializeResponse","initAttributes","buildServerAttributesFromInfo","MCP_PROTOCOL_VERSION_ATTRIBUTE","toolAttributes","extractToolResultAttributes","promptAttributes","extractPromptResultAttributes","cleanupPendingSpansForTransport","METHOD_CONFIGS","MCP_TOOL_NAME_ATTRIBUTE","MCP_RESOURCE_URI_ATTRIBUTE","MCP_PROMPT_NAME_ATTRIBUTE","extractTargetInfo","method","params","config","target","getRequestArguments","args","argumentsObj","key","value","MCP_REQUEST_ARGUMENT","formatLoggingData","data","getNotificationAttributes","method","params","recordInputs","attributes","MCP_LOGGING_LEVEL_ATTRIBUTE","MCP_LOGGING_LOGGER_ATTRIBUTE","MCP_LOGGING_DATA_TYPE_ATTRIBUTE","MCP_LOGGING_MESSAGE_ATTRIBUTE","MCP_RESOURCE_URI_ATTRIBUTE","urlObject","parseStringToURLObject","isURLObjectRelative","buildTypeSpecificAttributes","type","message","request","targetInfo","extractTargetInfo","MCP_REQUEST_ID_ATTRIBUTE","getRequestArguments","NETWORK_PII_ATTRIBUTES","CLIENT_ADDRESS_ATTRIBUTE","CLIENT_PORT_ATTRIBUTE","MCP_RESOURCE_URI_ATTRIBUTE","isNetworkPiiAttribute","key","filterMcpPiiFromSpanData","spanData","sendDefaultPii","acc","value","createSpanName","method","target","buildSentryAttributes","type","op","origin","MCP_SERVER_OP_VALUE","MCP_FUNCTION_ORIGIN_VALUE","MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE","MCP_NOTIFICATION_ORIGIN_VALUE","MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","MCP_ROUTE_SOURCE_VALUE","createMcpSpan","config","message","transport","extra","callback","options","params","spanName","targetInfo","extractTargetInfo","rawAttributes","buildTransportAttributes","MCP_METHOD_NAME_ATTRIBUTE","buildTypeSpecificAttributes","sendDefaultPii","getClient","attributes","filterMcpPiiFromSpanData","startSpan","createMcpNotificationSpan","jsonRpcMessage","createMcpOutgoingNotificationSpan","buildMcpServerSpanConfig","wrapTransportOnMessage","transport","options","fill","originalOnMessage","message","extra","isJsonRpcRequest","isInitialize","initSessionData","extractSessionDataFromInitializeRequest","storeSessionDataForTransport","isolationScope","getIsolationScope","withIsolationScope","spanConfig","buildMcpServerSpanConfig","span","startInactiveSpan","buildClientAttributesFromInfo","MCP_PROTOCOL_VERSION_ATTRIBUTE","storeSpanForRequest","withActiveSpan","isJsonRpcNotification","createMcpNotificationSpan","wrapTransportSend","originalSend","args","createMcpOutgoingNotificationSpan","isJsonRpcResponse","captureJsonRpcErrorResponse","isValidContentItem","serverData","extractSessionDataFromInitializeResponse","updateSessionDataForTransport","completeSpanWithResults","wrapTransportOnClose","originalOnClose","cleanupPendingSpansForTransport","cleanupSessionDataForTransport","wrapTransportError","originalOnError","error","captureTransportError","errorResponse","jsonRpcError","captureError","wrappedMcpServerInstances","wrapMcpServerWithSentry","mcpServerInstance","options","validateMcpServerInstance","serverInstance","sendDefaultPii","getClient","resolvedOptions","fill","originalConnect","transport","restArgs","result","wrapTransportOnMessage","wrapTransportSend","wrapTransportOnClose","wrapTransportError","wrapAllMCPHandlers","captureFeedback","params","hint","scope","getCurrentScope","message","name","email","url","source","associatedEventId","tags","feedbackEvent","client","getClient","captureLog","level","message","attributes","scope","severityNumber","_INTERNAL_captureLog","trace","debug","info","warn","error","fatal","formatConsoleArgs","values","normalizeDepth","normalizeMaxBreadth","GLOBAL_OBJ","safeJoinConsoleArgs","value","isPrimitive","normalize","hasConsoleSubstitutions","str","createConsoleTemplateAttributes","firstArg","followingArgs","attributes","template","arg","index","INTEGRATION_NAME","DEFAULT_ATTRIBUTES","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","_consoleLoggingIntegration","options","levels","CONSOLE_LEVELS","client","enableLogs","normalizeDepth","normalizeMaxBreadth","DEBUG_BUILD","debug","addConsoleInstrumentationHandler","args","level","getClient","firstArg","followingArgs","assertionMessage","formatConsoleArgs","_INTERNAL_captureLog","isLevelLog","shouldGenerateTemplate","hasConsoleSubstitutions","attributes","createConsoleTemplateAttributes","consoleLoggingIntegration","captureMetric","type","name","value","options","_INTERNAL_captureMetric","count","gauge","distribution","DEFAULT_CAPTURED_LEVELS","createConsolaReporter","options","levels","providedClient","logObj","type","level","consolaMessage","args","tag","_date","rest","client","getClient","logSeverityLevel","getLogSeverityLevel","normalizeDepth","normalizeMaxBreadth","attributes","key","value","normalize","extractionResult","processExtractedAttributes","defaultExtractAttributes","_INTERNAL_captureLog","formatConsoleArgs","CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP","CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP","mappedLevel","message","firstArg","isPlainObject","remainingArgsStartIndex","remainingArgs","followingArgs","shouldAddTemplateAttr","hasConsoleSubstitutions","messageTemplate","messageParameters","messageParamAttributes","templateAttrs","createConsoleTemplateAttributes","arg","index","GEN_AI_PROMPT_ATTRIBUTE","GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE","GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","GEN_AI_AGENT_NAME_ATTRIBUTE","GEN_AI_PIPELINE_NAME_ATTRIBUTE","GEN_AI_CONVERSATION_ID_ATTRIBUTE","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE","GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE","GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE","GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE","GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE","GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE","GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE","GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE","GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE","GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE","GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE","GEN_AI_TOOL_NAME_ATTRIBUTE","GEN_AI_TOOL_CALL_ID_ATTRIBUTE","GEN_AI_TOOL_TYPE_ATTRIBUTE","GEN_AI_TOOL_INPUT_ATTRIBUTE","GEN_AI_TOOL_OUTPUT_ATTRIBUTE","GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE","OPENAI_RESPONSE_ID_ATTRIBUTE","OPENAI_RESPONSE_MODEL_ATTRIBUTE","OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE","OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE","OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE","OPENAI_OPERATIONS","ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE","toolCallSpanContextMap","INVOKE_AGENT_OPS","GENERATE_CONTENT_OPS","EMBEDDINGS_OPS","RERANK_OPS","DO_SPAN_NAME_PREFIX","isContentMedia","part","isContentMediaSource","hasInlineData","hasImageUrl","hasInputAudio","hasFileData","hasMediaTypeData","hasVercelFileData","hasVercelImageData","hasBlobOrBase64Type","hasB64Json","hasImageGenerationResult","hasDataUri","hasNestedImageUrl","REMOVED_STRING","MEDIA_FIELDS","stripInlineMediaFromSingleMessage","strip","field","DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT","utf8Bytes","text","jsonBytes","value","truncateTextByBytes","maxBytes","low","high","bestFit","mid","candidate","getItemText","item","withItemText","isContentMessage","message","isContentArrayMessage","isPartsMessage","truncateContentMessage","emptyMessage","overhead","availableForContent","truncatedContent","getArrayItems","truncateArrayMessage","key","items","emptyItems","remainingBytes","includedItems","textSize","truncated","truncateSingleMessage","stripInlineMediaFromMessages","messages","newMessage","isContentMedia","stripInlineMediaFromSingleMessage","truncateMessagesByBytes","effectiveMaxBytes","lastMessage","stripped","strippedMessage","truncateGenAiMessages","truncateGenAiStringInput","input","resolveAIRecordingOptions","options","sendDefaultPii","getClient","getFinalOperationName","methodPath","getSpanOperation","buildMethodPath","currentPath","prop","setTokenUsageAttributes","span","promptTokens","completionTokens","cachedInputTokens","cachedOutputTokens","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","totalTokens","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","getTruncatedJsonString","value","truncateGenAiStringInput","truncatedMessages","truncateGenAiMessages","extractSystemInstructions","messages","systemMessageIndex","msg","systemMessage","systemContent","systemInstructions","filteredMessages","createWithResponseWrapper","originalWithResponse","instrumentedPromise","mechanismType","safeOriginalWithResponse","error","captureException","instrumentedResult","originalWrapper","wrapPromiseWithMethods","originalPromiseLike","isThenable","target","source","OPERATION_NAME_ATTRIBUTE","AI_OPERATION_ID_ATTRIBUTE","AI_PROMPT_ATTRIBUTE","AI_SCHEMA_ATTRIBUTE","AI_RESPONSE_OBJECT_ATTRIBUTE","AI_VALUES_ATTRIBUTE","AI_RESPONSE_TEXT_ATTRIBUTE","AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","AI_RESPONSE_FINISH_REASON_ATTRIBUTE","AI_PROMPT_MESSAGES_ATTRIBUTE","AI_PROMPT_TOOLS_ATTRIBUTE","AI_MODEL_ID_ATTRIBUTE","AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE","AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE","AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE","AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE","AI_USAGE_PROMPT_TOKENS_ATTRIBUTE","AI_USAGE_TOKENS_ATTRIBUTE","AI_TOOL_CALL_NAME_ATTRIBUTE","AI_TOOL_CALL_ID_ATTRIBUTE","AI_TOOL_CALL_ARGS_ATTRIBUTE","AI_TOOL_CALL_RESULT_ATTRIBUTE","accumulateTokensForParent","span","tokenAccumulator","parentSpanId","inputTokens","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","outputTokens","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","existing","applyAccumulatedTokens","spanOrTrace","accumulated","buildToolDescriptionMap","spans","toolDescriptions","availableTools","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","tools","tool","applyToolDescriptionsAndTokens","toolName","GEN_AI_TOOL_NAME_ATTRIBUTE","description","GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE","_INTERNAL_getSpanContextForToolCallId","toolCallId","toolCallSpanContextMap","_INTERNAL_cleanupToolCallSpanContext","convertAvailableToolsToJsonString","toolObjects","filterMessagesArray","input","m","convertUserInputToMessagesFormat","userInput","p","messages","prompt","system","result","requestMessagesFromPrompt","attributes","AI_PROMPT_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","AI_PROMPT_MESSAGES_ATTRIBUTE","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","filteredLength","truncatedMessages","getTruncatedJsonString","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","getSpanOpFromName","name","GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE","GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE","GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE","GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE","GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE","GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE","GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE","GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE","GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE","mapVercelAiOperationName","operationName","INVOKE_AGENT_OPS","GENERATE_CONTENT_OPS","EMBEDDINGS_OPS","RERANK_OPS","onVercelAiSpanStart","span","attributes","name","spanToJSON","AI_TOOL_CALL_NAME_ATTRIBUTE","AI_TOOL_CALL_ID_ATTRIBUTE","processToolCallSpan","AI_OPERATION_ID_ATTRIBUTE","processGenerateSpan","vercelAiEventProcessor","event","tokenAccumulator","processEndedVercelAiSpan","accumulateTokensForParent","applyToolDescriptionsAndTokens","trace","applyAccumulatedTokens","normalizeFinishReason","finishReason","buildOutputMessages","responseText","AI_RESPONSE_TEXT_ATTRIBUTE","responseToolCalls","AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","AI_RESPONSE_FINISH_REASON_ATTRIBUTE","parts","toolCalls","toolCall","args","outputMessage","GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE","origin","renameAttributeKey","AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","AI_USAGE_PROMPT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE","AI_USAGE_TOKENS_ATTRIBUTE","outputTokens","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","AI_PROMPT_TOOLS_ATTRIBUTE","convertAvailableToolsToJsonString","OPERATION_NAME_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","AI_PROMPT_MESSAGES_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","AI_RESPONSE_OBJECT_ATTRIBUTE","AI_TOOL_CALL_ARGS_ATTRIBUTE","GEN_AI_TOOL_INPUT_ATTRIBUTE","AI_TOOL_CALL_RESULT_ATTRIBUTE","GEN_AI_TOOL_OUTPUT_ATTRIBUTE","AI_SCHEMA_ATTRIBUTE","AI_MODEL_ID_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","AI_VALUES_ATTRIBUTE","parsed","v","GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE","addProviderMetadataToAttributes","key","oldKey","newKey","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","GEN_AI_TOOL_NAME_ATTRIBUTE","GEN_AI_TOOL_CALL_ID_ATTRIBUTE","toolCallId","toolCallSpanContextMap","GEN_AI_TOOL_TYPE_ATTRIBUTE","toolName","nameWthoutAi","functionId","AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE","requestMessagesFromPrompt","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","op","getSpanOpFromName","modelId","doSpanPrefix","DO_SPAN_NAME_PREFIX","addVercelAiProcessors","client","providerMetadata","AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE","providerMetadataObject","openaiMetadata","setAttributeIfDefined","cachedInputTokens","cacheWriteInputTokens","GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE","value","OPENAI_INTEGRATION_NAME","INSTRUMENTED_METHODS","RESPONSES_TOOL_CALL_EVENT_TYPES","RESPONSE_EVENT_TYPES","getOperationName","methodPath","OPENAI_OPERATIONS","getSpanOperation","shouldInstrument","INSTRUMENTED_METHODS","isChatCompletionResponse","response","isResponsesApiResponse","isEmbeddingsResponse","responseObject","isConversationResponse","isResponsesApiStreamEvent","event","isChatCompletionChunk","addChatCompletionAttributes","span","recordOutputs","setCommonResponseAttributes","setTokenUsageAttributes","finishReasons","choice","reason","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","toolCalls","calls","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","addResponsesApiAttributes","responseWithOutput","functionCalls","item","addEmbeddingsAttributes","OPENAI_RESPONSE_MODEL_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","addConversationAttributes","id","created_at","OPENAI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_CONVERSATION_ID_ATTRIBUTE","OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE","promptTokens","completionTokens","totalTokens","OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","model","timestamp","extractConversationId","params","extractRequestParameters","attributes","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE","GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE","conversationId","processChatCompletionToolCalls","toolCalls","state","toolCall","index","existingToolCall","processChatCompletionChunk","chunk","recordOutputs","choice","processResponsesApiEvent","streamEvent","span","captureException","event","RESPONSE_EVENT_TYPES","response","instrumentStream","stream","isChatCompletionChunk","isResponsesApiStreamEvent","setCommonResponseAttributes","setTokenUsageAttributes","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","allToolCalls","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","extractAvailableTools","params","tools","webSearchOptions","availableTools","error","DEBUG_BUILD","debug","extractRequestAttributes","args","methodPath","attributes","GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","getOperationName","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","extractRequestParameters","GEN_AI_REQUEST_MODEL_ATTRIBUTE","addResponseAttributes","span","result","recordOutputs","response","isChatCompletionResponse","addChatCompletionAttributes","responseTexts","choice","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","isResponsesApiResponse","addResponsesApiAttributes","isEmbeddingsResponse","addEmbeddingsAttributes","isConversationResponse","addConversationAttributes","addRequestAttributes","operationName","OPENAI_OPERATIONS","input","GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE","src","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","truncatedInput","getTruncatedJsonString","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","instrumentMethod","originalMethod","context","options","requestAttributes","model","isStreamRequested","spanConfig","getSpanOperation","originalResult","instrumentedPromise","startSpanManual","instrumentStream","captureException","wrapPromiseWithMethods","startSpan","createDeepProxy","target","currentPath","obj","prop","value","buildMethodPath","shouldInstrument","instrumentOpenAiClient","client","resolveAIRecordingOptions","ANTHROPIC_AI_INTEGRATION_NAME","ANTHROPIC_AI_INSTRUMENTED_METHODS","shouldInstrument","methodPath","ANTHROPIC_AI_INSTRUMENTED_METHODS","setMessagesAttribute","span","messages","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","filteredLength","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","getTruncatedJsonString","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS","mapAnthropicErrorToStatusMessage","errorType","handleResponseError","response","captureException","messagesFromParams","params","system","input","systemMessages","inputParamMessages","messagesParamMessages","userMessages","isErrorEvent","event","span","mapAnthropicErrorToStatusMessage","captureException","handleMessageMetadata","state","message","handleContentBlockStart","handleContentBlockDelta","recordOutputs","active","handleContentBlockStop","raw","parsedInput","processEvent","finalizeStreamSpan","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","setTokenUsageAttributes","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","instrumentAsyncIterableStream","stream","instrumentMessageStream","error","extractRequestAttributes","args","methodPath","attributes","GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","getFinalOperationName","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","params","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","addPrivateRequestAttributes","span","messages","messagesFromParams","setMessagesAttribute","GEN_AI_PROMPT_ATTRIBUTE","addContentAttributes","response","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","item","text","toolCalls","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","addMetadataAttributes","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE","setTokenUsageAttributes","addResponseAttributes","recordOutputs","handleResponseError","handleStreamingError","error","captureException","handleStreamingRequest","originalMethod","target","context","requestAttributes","operationName","options","isStreamRequested","isStreamingMethod","model","spanConfig","getSpanOperation","originalResult","instrumentedPromise","startSpanManual","result","instrumentAsyncIterableStream","wrapPromiseWithMethods","messageStream","instrumentMessageStream","instrumentMethod","thisArg","startSpan","createDeepProxy","currentPath","obj","prop","value","buildMethodPath","shouldInstrument","instrumentAnthropicAiClient","anthropicAiClient","resolveAIRecordingOptions","GOOGLE_GENAI_INTEGRATION_NAME","GOOGLE_GENAI_INSTRUMENTED_METHODS","GOOGLE_GENAI_SYSTEM_NAME","CHATS_CREATE_METHOD","CHAT_PATH","isErrorChunk","chunk","span","feedback","message","captureException","handleResponseMetadata","state","usage","handleCandidateContent","recordOutputs","candidate","part","processChunk","instrumentStream","stream","attrs","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","shouldInstrument","methodPath","GOOGLE_GENAI_INSTRUMENTED_METHODS","methodName","isStreamingMethod","contentUnionToMessages","content","role","extractModel","params","context","contextObj","extractConfigAttributes","config","attributes","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE","extractRequestAttributes","methodPath","GEN_AI_SYSTEM_ATTRIBUTE","GOOGLE_GENAI_SYSTEM_NAME","GEN_AI_OPERATION_NAME_ATTRIBUTE","getFinalOperationName","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","GEN_AI_REQUEST_MODEL_ATTRIBUTE","functionDeclarations","tool","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","addPrivateRequestAttributes","span","messages","contentUnionToMessages","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","filteredLength","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","truncateGenAiMessages","addResponseAttributes","response","recordOutputs","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","usage","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","responseTexts","candidate","part","text","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","functionCalls","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","instrumentMethod","originalMethod","options","isSyncCreate","CHATS_CREATE_METHOD","target","_","args","requestAttributes","model","operationName","isStreamingMethod","startSpanManual","getSpanOperation","stream","instrumentStream","error","captureException","startSpan","handleCallbackErrors","result","createDeepProxy","currentPath","t","prop","receiver","value","buildMethodPath","shouldInstrument","instrumentedMethod","CHAT_PATH","instrumentGoogleGenAIClient","client","resolveAIRecordingOptions","LANGCHAIN_INTEGRATION_NAME","LANGCHAIN_ORIGIN","ROLE_MAP","setIfDefined","target","key","value","setNumberIfDefined","n","asString","v","normalizeContent","stripped","part","isContentMedia","stripInlineMediaFromSingleMessage","normalizeMessageRole","role","normalized","ROLE_MAP","normalizeRoleNameFromCtor","name","getInvocationParams","tags","normalizeLangChainMessages","messages","message","maybeGetType","messageType","id","ctor","extractCommonRequestAttributes","serialized","invocationParams","langSmithMetadata","attrs","kwargs","temperature","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","maxTokens","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","topP","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","frequencyPenalty","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","presencePenalty","GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","baseRequestAttributes","system","modelName","GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","LANGCHAIN_ORIGIN","extractLLMRequestAttributes","llm","prompts","recordInputs","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","p","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","extractChatModelRequestAttributes","langChainMessages","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","filteredLength","truncated","truncateGenAiMessages","addToolCallsAttributes","generations","toolCalls","flatGenerations","gen","content","item","t","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","addTokenUsageAttributes","llmOutput","tokenUsage","anthropicUsage","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","input","output","total","GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE","extractLlmResponseAttributes","llmResult","recordOutputs","finishReasons","g","r","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","texts","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","v1Message","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","responseId","GEN_AI_RESPONSE_ID_ATTRIBUTE","stopReason","GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE","createLangChainCallbackHandler","options","recordInputs","recordOutputs","resolveAIRecordingOptions","spanMap","exitSpan","runId","span","handler","llm","prompts","_parentRunId","_extraParams","tags","metadata","_runName","invocationParams","getInvocationParams","attributes","extractLLMRequestAttributes","modelName","GEN_AI_REQUEST_MODEL_ATTRIBUTE","operationName","GEN_AI_OPERATION_NAME_ATTRIBUTE","startSpanManual","SEMANTIC_ATTRIBUTE_SENTRY_OP","messages","extractChatModelRequestAttributes","output","_tags","extractLlmResponseAttributes","error","captureException","LANGCHAIN_ORIGIN","chain","inputs","_metadata","_runType","runName","chainName","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","outputs","tool","input","toolName","GEN_AI_TOOL_NAME_ATTRIBUTE","GEN_AI_TOOL_INPUT_ATTRIBUTE","GEN_AI_TOOL_OUTPUT_ATTRIBUTE","LANGGRAPH_INTEGRATION_NAME","LANGGRAPH_ORIGIN","extractToolCalls","messages","toolCalls","message","msgToolCalls","extractTokenUsageFromMessage","msg","inputTokens","outputTokens","totalTokens","usage","metadata","tokenUsage","extractModelMetadata","span","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","extractToolsFromCompiledGraph","compiledGraph","tools","tool","setResponseAttributes","inputMessages","result","outputMessages","inputCount","newMessages","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","normalizedNewMessages","normalizeLangChainMessages","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","totalInputTokens","totalOutputTokens","tokens","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","instrumentStateGraphCompile","originalCompile","options","target","thisArg","args","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","LANGGRAPH_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_OP","GEN_AI_OPERATION_NAME_ATTRIBUTE","span","compiledGraph","compileOptions","GEN_AI_AGENT_NAME_ATTRIBUTE","originalInvoke","instrumentCompiledGraphInvoke","error","captureException","graphInstance","GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE","graphName","GEN_AI_PIPELINE_NAME_ATTRIBUTE","threadId","GEN_AI_CONVERSATION_ID_ATTRIBUTE","tools","extractToolsFromCompiledGraph","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","recordInputs","recordOutputs","inputMessages","normalizedMessages","normalizeLangChainMessages","systemInstructions","filteredMessages","extractSystemInstructions","GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE","truncatedMessages","truncateGenAiMessages","filteredLength","GEN_AI_INPUT_MESSAGES_ATTRIBUTE","GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE","result","setResponseAttributes","instrumentLangGraph","stateGraph","resolveAIRecordingOptions","getBreadcrumbLogLevelFromHttpStatusCode","statusCode","SentryError","message","logLevel","WINDOW","GLOBAL_OBJ","supportsErrorEvent","supportsDOMError","supportsDOMException","supportsHistory","supportsFetch","_isFetchSupported","isNativeFunction","func","supportsNativeFetch","result","doc","sandbox","err","DEBUG_BUILD","debug","supportsReportingObserver","supportsReferrerPolicy","addFetchInstrumentationHandler","handler","skipNativeFetchCheck","type","addHandler","maybeInstrument","instrumentFetch","addFetchEndInstrumentationHandler","streamHandler","onFetchResolved","supportsNativeFetch","fill","GLOBAL_OBJ","originalFetch","args","virtualError","method","url","parseFetchArgs","handlerData","timestampInSeconds","getHeadersFromFetchArgs","triggerHandlers","response","error","isError","addNonEnumerableProperty","enhanceOption","getClient","hostname","resolveResponse","res","onFinishedResolving","body","responseReader","maxFetchDurationTimeout","readingActive","chunkTimeout","done","clonedResponseForResolving","hasProp","obj","prop","getUrlFromResource","resource","fetchArgs","options","isRequest","arg","requestArgument","optionsArgument","isBrowserBundle","getSDKSource","isNodeEnv","isBrowserBundle","dynamicRequire","mod","request","loadModule","moduleName","existingModule","cwd","isBrowser","isNodeEnv","isElectronNodeRenderer","GLOBAL_OBJ","replaceExports","exports","exportName","wrappedConstructor","original","filenameIsInApp","filename","isNative","node","getModule","FILENAME_MATCH","FULL_MATCH","DATA_URI_MATCH","line","dataUriMatch","lineMatch","object","method","functionName","typeName","methodName","methodStart","objectEnd","normalizeStackTracePath","maybeDecodedFilename","_safeDecodeURI","_parseIntOrUndefined","nodeStackLineParser","input","watchdogTimer","createTimer","pollInterval","anrThreshold","callback","timer","triggered","enabled","diffMs","state","callFrameToStackFrame","frame","url","getModuleFromFilename","filename","colno","lineno","filenameIsInApp","LRUMap","_maxSize","key","value","nextKey","values","vercelWaitUntil","task","ctx","GLOBAL_OBJ","flushWithTimeout","timeout","debug","flush","e","flushIfServerless","params","GLOBAL_OBJ","vercelWaitUntil","escapeStringForRegex","regexString"],"sources":["../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/debug-build.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/worldwide.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/version.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/carrier.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/debug-logger.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/stacktrace.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/instrument/handlers.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/instrument/globalError.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/instrument/globalUnhandledRejection.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/is.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/browser.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/object.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/randomSafeContext.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/string.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/misc.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/time.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/session.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/merge.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/propagationContext.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/spanOnScope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/scope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/defaultScopes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/chain-and-copy-promiselike.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/asyncContext/stackStrategy.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/asyncContext/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/currentScopes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/semanticAttributes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/spanstatus.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/baggage.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/dsn.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/parseSampleRate.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/tracing.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/spanUtils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/errors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/hasSpansEnabled.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/should-ignore-span.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/dynamicSamplingContext.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/sentryNonRecordingSpan.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/normalize.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/envelope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/envelope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/logSpans.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/measurement.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/sentrySpan.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/handleCallbackErrors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/sampling.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/trace.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/idleSpan.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/syncpromise.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/eventProcessors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/debug-ids.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/scopeData.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/prepareEvent.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/exports.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/api.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integration.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/attributes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/timestampSequence.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/trace-info.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/envelope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/internal.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/metrics/envelope.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/metrics/internal.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/timer.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/promisebuffer.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/ratelimit.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/transports/base.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/clientreport.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/eventUtils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/transactionEvent.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/client.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/checkin.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/transports/userAgent.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/eventbuilder.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/server-runtime-client.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/sdk.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/transports/offline.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/transports/multiplexed.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/ai/providerSkip.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/envToBool.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/url.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/isSentryRequestUrl.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/parameterize.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/tunnel.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/ipAddress.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/sdkMetadata.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/traceData.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/tracePropagationTargets.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/meta.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/debounce.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/request.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/breadcrumbs.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/functiontostring.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/eventFilters.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/aggregate-errors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/linkederrors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/metadata.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/moduleMetadata.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/cookie.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/vendor/getIpAddress.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/requestdata.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/instrument/console.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/severity.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/captureconsole.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/dedupe.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/extraerrordata.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/path.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/rewriteframes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/supabase.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/postgresjs.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/zoderrors.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/third-party-errors-filter.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/console.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/featureFlags.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/featureFlags/featureFlagsIntegration.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/featureFlags/growthbook.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/conversationId.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/profiling.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/fetch.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/trpc.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/errorCapture.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/handlers.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/attributes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/validation.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/resultExtraction.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/sessionManagement.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/sessionExtraction.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/correlation.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/methodConfig.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/attributeExtraction.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/piiFiltering.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/spans.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/transport.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/mcp-server/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/feedback.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/public-api.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/logs/console-integration.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/metrics/public-api.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/integrations/consola.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/ai/gen-ai-attributes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/vercel-ai/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/ai/mediaStripping.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/ai/messageTruncation.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/ai/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/vercel-ai/vercel-ai-attributes.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/vercel-ai/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/vercel-ai/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/openai/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/openai/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/openai/streaming.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/openai/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/anthropic-ai/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/anthropic-ai/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/anthropic-ai/streaming.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/anthropic-ai/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/google-genai/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/google-genai/streaming.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/google-genai/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/google-genai/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langchain/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langchain/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langchain/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langgraph/constants.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langgraph/utils.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/tracing/langgraph/index.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/breadcrumb-log-level.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/error.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/supports.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/instrument/fetch.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/env.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/node.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/isBrowser.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/exports.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/node-stack-trace.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/anr.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/lru.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/vercelWaitUntil.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/utils/flushIfServerless.ts","../esm/npm/@sentry/core@10.46.0/node_modules/@sentry/core/src/vendor/escapeStringForRegex.ts"],"sourcesContent":["declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the `debug` singleton, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Carrier } from '../carrier';\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions  */\nexport type InternalGlobal = {\n  navigator?: { userAgent?: string; maxTouchPoints?: number };\n  console: Console;\n  PerformanceObserver?: any;\n  Sentry?: any;\n  onerror?: {\n    (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n    __SENTRY_INSTRUMENTED__?: true;\n  };\n  onunhandledrejection?: {\n    (event: unknown): boolean;\n    __SENTRY_INSTRUMENTED__?: true;\n  };\n  SENTRY_ENVIRONMENT?: string;\n  SENTRY_DSN?: string;\n  SENTRY_RELEASE?: {\n    id?: string;\n  };\n  SENTRY_SDK_SOURCE?: SdkSource;\n  /**\n   * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n   * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n   * file.\n   */\n  _sentryDebugIds?: Record\u003cstring, string\u003e;\n  /**\n   * Native debug IDs implementation (e.g., from Vercel).\n   * This uses the same format as _sentryDebugIds but with a different global name.\n   * Keys are `error.stack` strings, values are debug IDs.\n   */\n  _debugIds?: Record\u003cstring, string\u003e;\n  /**\n   * Raw module metadata that is injected by bundler plugins.\n   *\n   * Keys are `error.stack` strings, values are the metadata.\n   */\n  _sentryModuleMetadata?: Record\u003cstring, any\u003e;\n  _sentryEsmLoaderHookRegistered?: boolean;\n} \u0026 Carrier;\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ = globalThis as unknown as InternalGlobal;\n","// This is a magic string replaced by rollup\ndeclare const __SENTRY_SDK_VERSION__: string;\n\nexport const SDK_VERSION = typeof __SENTRY_SDK_VERSION__ === 'string' ? __SENTRY_SDK_VERSION__ : '0.0.0-unknown.0';\n","import type { AsyncContextStack } from './asyncContext/stackStrategy';\nimport type { AsyncContextStrategy } from './asyncContext/types';\nimport type { Client } from './client';\nimport type { Scope } from './scope';\nimport type { SerializedLog } from './types-hoist/log';\nimport type { SerializedMetric } from './types-hoist/metric';\nimport { SDK_VERSION } from './utils/version';\nimport { GLOBAL_OBJ } from './utils/worldwide';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n  __SENTRY__?: VersionedCarrier;\n}\n\ntype VersionedCarrier = {\n  version?: string;\n} \u0026 Record\u003cExclude\u003cstring, 'version'\u003e, SentryCarrier\u003e;\n\nexport interface SentryCarrier {\n  acs?: AsyncContextStrategy;\n  stack?: AsyncContextStack;\n\n  globalScope?: Scope;\n  defaultIsolationScope?: Scope;\n  defaultCurrentScope?: Scope;\n  loggerSettings?: { enabled: boolean };\n  /**\n   * A map of Sentry clients to their log buffers.\n   * This is used to store logs that are sent to Sentry.\n   */\n  clientToLogBufferMap?: WeakMap\u003cClient, Array\u003cSerializedLog\u003e\u003e;\n\n  /**\n   * A map of Sentry clients to their metric buffers.\n   * This is used to store metrics that are sent to Sentry.\n   */\n  clientToMetricBufferMap?: WeakMap\u003cClient, Array\u003cSerializedMetric\u003e\u003e;\n\n  /** Overwrites TextEncoder used in `@sentry/core`, need for `react-native@0.73` and older */\n  encodePolyfill?: (input: string) =\u003e Uint8Array;\n  /** Overwrites TextDecoder used in `@sentry/core`, need for `react-native@0.73` and older */\n  decodePolyfill?: (input: Uint8Array) =\u003e string;\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n  // This ensures a Sentry carrier exists\n  getSentryCarrier(GLOBAL_OBJ);\n  return GLOBAL_OBJ;\n}\n\n/** Will either get the existing sentry carrier, or create a new one. */\nexport function getSentryCarrier(carrier: Carrier): SentryCarrier {\n  const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n\n  // For now: First SDK that sets the .version property wins\n  __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n\n  // Intentionally populating and returning the version of \"this\" SDK instance\n  // rather than what's set in .version so that \"this\" SDK always gets its carrier\n  return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__[]` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton\u003cProp extends keyof SentryCarrier\u003e(\n  name: Prop,\n  creator: () =\u003e NonNullable\u003cSentryCarrier[Prop]\u003e,\n  obj = GLOBAL_OBJ,\n): NonNullable\u003cSentryCarrier[Prop]\u003e {\n  const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {});\n  const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n  // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes\n  return carrier[name] || (carrier[name] = creator());\n}\n","import { getGlobalSingleton } from '../carrier';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ConsoleLevel } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from './worldwide';\n\nexport interface SentryDebugLogger {\n  disable(): void;\n  enable(): void;\n  isEnabled(): boolean;\n  log(...args: Parameters\u003ctypeof console.log\u003e): void;\n  warn(...args: Parameters\u003ctypeof console.warn\u003e): void;\n  error(...args: Parameters\u003ctypeof console.error\u003e): void;\n}\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n  'debug',\n  'info',\n  'warn',\n  'error',\n  'log',\n  'assert',\n  'trace',\n] as const;\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: Partial\u003c{\n  log(...args: Parameters\u003ctypeof console.log\u003e): void;\n  info(...args: Parameters\u003ctypeof console.info\u003e): void;\n  warn(...args: Parameters\u003ctypeof console.warn\u003e): void;\n  error(...args: Parameters\u003ctypeof console.error\u003e): void;\n  debug(...args: Parameters\u003ctypeof console.debug\u003e): void;\n  assert(...args: Parameters\u003ctypeof console.assert\u003e): void;\n  trace(...args: Parameters\u003ctypeof console.trace\u003e): void;\n}\u003e = {};\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox\u003cT\u003e(callback: () =\u003e T): T {\n  if (!('console' in GLOBAL_OBJ)) {\n    return callback();\n  }\n\n  const console = GLOBAL_OBJ.console;\n  const wrappedFuncs: Partial\u003cRecord\u003cConsoleLevel, (...args: unknown[]) =\u003e void\u003e\u003e = {};\n\n  const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n  // Restore all wrapped console methods\n  wrappedLevels.forEach(level =\u003e {\n    const originalConsoleMethod = originalConsoleMethods[level];\n    wrappedFuncs[level] = console[level] as (...args: unknown[]) =\u003e void;\n    console[level] = originalConsoleMethod as (...args: unknown[]) =\u003e void;\n  });\n\n  try {\n    return callback();\n  } finally {\n    // Revert restoration to wrapped state\n    wrappedLevels.forEach(level =\u003e {\n      console[level] = wrappedFuncs[level] as (...args: unknown[]) =\u003e void;\n    });\n  }\n}\n\nfunction enable(): void {\n  _getLoggerSettings().enabled = true;\n}\n\nfunction disable(): void {\n  _getLoggerSettings().enabled = false;\n}\n\nfunction isEnabled(): boolean {\n  return _getLoggerSettings().enabled;\n}\n\nfunction log(...args: Parameters\u003ctypeof console.log\u003e): void {\n  _maybeLog('log', ...args);\n}\n\nfunction warn(...args: Parameters\u003ctypeof console.warn\u003e): void {\n  _maybeLog('warn', ...args);\n}\n\nfunction error(...args: Parameters\u003ctypeof console.error\u003e): void {\n  _maybeLog('error', ...args);\n}\n\nfunction _maybeLog(level: ConsoleLevel, ...args: Parameters\u003c(typeof console)[typeof level]\u003e): void {\n  if (!DEBUG_BUILD) {\n    return;\n  }\n\n  if (isEnabled()) {\n    consoleSandbox(() =\u003e {\n      GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);\n    });\n  }\n}\n\nfunction _getLoggerSettings(): { enabled: boolean } {\n  if (!DEBUG_BUILD) {\n    return { enabled: false };\n  }\n\n  return getGlobalSingleton('loggerSettings', () =\u003e ({ enabled: false }));\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n */\nexport const debug = {\n  /** Enable logging. */\n  enable,\n  /** Disable logging. */\n  disable,\n  /** Check if logging is enabled. */\n  isEnabled,\n  /** Log a message. */\n  log,\n  /** Log a warning. */\n  warn,\n  /** Log an error. */\n  error,\n} satisfies SentryDebugLogger;\n","import type { Event } from '../types-hoist/event';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport type { StackLineParser, StackParser } from '../types-hoist/stacktrace';\nimport type { VNode, VueViewModel } from '../types-hoist/vue';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\nexport const UNKNOWN_FUNCTION = '?';\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n  const sortedParsers = parsers.sort((a, b) =\u003e a[0] - b[0]).map(p =\u003e p[1]);\n\n  return (stack: string, skipFirstLines: number = 0, framesToPop: number = 0): StackFrame[] =\u003e {\n    const frames: StackFrame[] = [];\n    const lines = stack.split('\\n');\n\n    for (let i = skipFirstLines; i \u003c lines.length; i++) {\n      let line = lines[i] as string;\n      // Truncate lines over 1kb because many of the regular expressions use\n      // backtracking which results in run time that increases exponentially\n      // with input size. Huge strings can result in hangs/Denial of Service:\n      // https://github.com/getsentry/sentry-javascript/issues/2286\n      if (line.length \u003e 1024) {\n        line = line.slice(0, 1024);\n      }\n\n      // https://github.com/getsentry/sentry-javascript/issues/5459\n      // Remove webpack (error: *) wrappers\n      const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n      // https://github.com/getsentry/sentry-javascript/issues/7813\n      // Skip Error: lines\n      if (cleanedLine.match(/\\S*Error: /)) {\n        continue;\n      }\n\n      for (const parser of sortedParsers) {\n        const frame = parser(cleanedLine);\n\n        if (frame) {\n          frames.push(frame);\n          break;\n        }\n      }\n\n      if (frames.length \u003e= STACKTRACE_FRAME_LIMIT + framesToPop) {\n        break;\n      }\n    }\n\n    return stripSentryFramesAndReverse(frames.slice(framesToPop));\n  };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n  if (Array.isArray(stackParser)) {\n    return createStackParser(...stackParser);\n  }\n  return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray\u003cStackFrame\u003e): StackFrame[] {\n  if (!stack.length) {\n    return [];\n  }\n\n  const localStack = Array.from(stack);\n\n  // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n  if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {\n    localStack.pop();\n  }\n\n  // Reversing in the middle of the procedure allows us to just pop the values off the stack\n  localStack.reverse();\n\n  // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n  if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n    localStack.pop();\n\n    // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n    // is produced within the scope itself, making it:\n    //\n    //   Sentry.captureException()\n    //   scope.captureException()\n    //\n    // instead of just the top `Sentry` call itself.\n    // This forces us to possibly strip an additional frame in the exact same was as above.\n    if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n      localStack.pop();\n    }\n  }\n\n  return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame =\u003e ({\n    ...frame,\n    filename: frame.filename || getLastStackFrame(localStack).filename,\n    function: frame.function || UNKNOWN_FUNCTION,\n  }));\n}\n\nfunction getLastStackFrame(arr: StackFrame[]): StackFrame {\n  return arr[arr.length - 1] || {};\n}\n\nconst defaultFunctionName = '\u003canonymous\u003e';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n  try {\n    if (!fn || typeof fn !== 'function') {\n      return defaultFunctionName;\n    }\n    return fn.name || defaultFunctionName;\n  } catch {\n    // Just accessing custom props in some Selenium environments\n    // can cause a \"Permission denied\" exception (see raven-js#495).\n    return defaultFunctionName;\n  }\n}\n\n/**\n * Get's stack frames from an event without needing to check for undefined properties.\n */\nexport function getFramesFromEvent(event: Event): StackFrame[] | undefined {\n  const exception = event.exception;\n\n  if (exception) {\n    const frames: StackFrame[] = [];\n    try {\n      // @ts-expect-error Object could be undefined\n      exception.values.forEach(value =\u003e {\n        // @ts-expect-error Value could be undefined\n        if (value.stacktrace.frames) {\n          // @ts-expect-error Value could be undefined\n          frames.push(...value.stacktrace.frames);\n        }\n      });\n      return frames;\n    } catch {\n      return undefined;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Get the internal name of an internal Vue value, to represent it in a stacktrace.\n *\n * @param value The value to get the internal name of.\n */\nexport function getVueInternalName(value: VueViewModel | VNode): string {\n  // Check if it's a VNode (has __v_isVNode) or a component instance (has _isVue/__isVue)\n  const isVNode = '__v_isVNode' in value \u0026\u0026 value.__v_isVNode;\n\n  return isVNode ? '[VueVNode]' : '[VueViewModel]';\n}\n\n/**\n * Normalizes stack line paths by removing file:// prefix and leading slashes for Windows paths\n */\nexport function normalizeStackTracePath(path: string | undefined): string | undefined {\n  let filename = path?.startsWith('file://') ? path.slice(7) : path;\n  // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`\n  if (filename?.match(/\\/[A-Z]:/)) {\n    filename = filename.slice(1);\n  }\n  return filename;\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { debug } from '../utils/debug-logger';\nimport { getFunctionName } from '../utils/stacktrace';\n\nexport type InstrumentHandlerType =\n  | 'console'\n  | 'dom'\n  | 'fetch'\n  | 'fetch-body-resolved'\n  | 'history'\n  | 'xhr'\n  | 'error'\n  | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) =\u003e void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n  handlers[type] = handlers[type] || [];\n  handlers[type].push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n  Object.keys(handlers).forEach(key =\u003e {\n    handlers[key as InstrumentHandlerType] = undefined;\n  });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () =\u003e void): void {\n  if (!instrumented[type]) {\n    instrumented[type] = true;\n    try {\n      instrumentFn();\n    } catch (e) {\n      DEBUG_BUILD \u0026\u0026 debug.error(`Error while instrumenting ${type}`, e);\n    }\n  }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n  const typeHandlers = type \u0026\u0026 handlers[type];\n  if (!typeHandlers) {\n    return;\n  }\n\n  for (const handler of typeHandlers) {\n    try {\n      handler(data);\n    } catch (e) {\n      DEBUG_BUILD \u0026\u0026\n        debug.error(\n          `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n          e,\n        );\n    }\n  }\n}\n","import type { HandlerDataError } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) =\u003e void): void {\n  const type = 'error';\n  addHandler(type, handler);\n  maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n  _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n  // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n  // is that we are using this handler in the Loader Script, to handle buffered errors consistently\n  GLOBAL_OBJ.onerror = function (\n    msg: string | object,\n    url?: string,\n    line?: number,\n    column?: number,\n    error?: Error,\n  ): boolean {\n    const handlerData: HandlerDataError = {\n      column,\n      error,\n      line,\n      msg,\n      url,\n    };\n    triggerHandlers('error', handlerData);\n\n    if (_oldOnErrorHandler) {\n      // eslint-disable-next-line prefer-rest-params\n      return _oldOnErrorHandler.apply(this, arguments);\n    }\n\n    return false;\n  };\n\n  GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { HandlerDataUnhandledRejection } from '../types-hoist/instrument';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n  handler: (data: HandlerDataUnhandledRejection) =\u003e void,\n): void {\n  const type = 'unhandledrejection';\n  addHandler(type, handler);\n  maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n  _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n  // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n  // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n  GLOBAL_OBJ.onunhandledrejection = function (e: unknown): boolean {\n    const handlerData: HandlerDataUnhandledRejection = e;\n    triggerHandlers('unhandledrejection', handlerData);\n\n    if (_oldOnUnhandledRejectionHandler) {\n      // eslint-disable-next-line prefer-rest-params\n      return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n    }\n\n    return true;\n  };\n\n  GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Primitive } from '../types-hoist/misc';\nimport type { ParameterizedString } from '../types-hoist/parameterize';\nimport type { PolymorphicEvent } from '../types-hoist/polymorphics';\nimport type { VNode, VueViewModel } from '../types-hoist/vue';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n  switch (objectToString.call(wat)) {\n    case '[object Error]':\n    case '[object Exception]':\n    case '[object DOMException]':\n    case '[object WebAssembly.Exception]':\n      return true;\n    default:\n      return isInstanceOf(wat, Error);\n  }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n  return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n  return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n  return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n  return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n  return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n  return (\n    typeof wat === 'object' \u0026\u0026\n    wat !== null \u0026\u0026\n    '__sentry_template_string__' in wat \u0026\u0026\n    '__sentry_template_values__' in wat\n  );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n  return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' \u0026\u0026 typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record\u003cstring, unknown\u003e {\n  return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n  return typeof Event !== 'undefined' \u0026\u0026 isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n  return typeof Element !== 'undefined' \u0026\u0026 isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n  return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike\u003cany\u003e {\n  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n  return Boolean(wat?.then \u0026\u0026 typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n  return isPlainObject(wat) \u0026\u0026 'nativeEvent' in wat \u0026\u0026 'preventDefault' in wat \u0026\u0026 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\n// TODO: fix in v11, convert any to unknown\n// export function isInstanceOf\u003cT\u003e(wat: unknown, base: { new (...args: any[]): T }): wat is T {\nexport function isInstanceOf\u003cT\u003e(wat: any, base: any): wat is T {\n  try {\n    return wat instanceof base;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel or a VNode.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): wat is VueViewModel | VNode {\n  // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n  // We also need to check for __v_isVNode because Vue 3 component render instances have an internal __v_isVNode property.\n  return !!(\n    typeof wat === 'object' \u0026\u0026\n    wat !== null \u0026\u0026\n    ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue || (wat as { __v_isVNode?: boolean }).__v_isVNode)\n  );\n}\n\n/**\n * Checks whether the given parameter is a Standard Web API Request instance.\n *\n * Returns false if Request is not available in the current runtime.\n */\nexport function isRequest(request: unknown): request is Request {\n  return typeof Request !== 'undefined' \u0026\u0026 isInstanceOf(request, Request);\n}\n","import { isString } from './is';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n  parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] =\u003e body \u003e div \u003e input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n  elem: unknown,\n  options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n  if (!elem) {\n    return '\u003cunknown\u003e';\n  }\n\n  // try/catch both:\n  // - accessing event.target (see getsentry/raven-js#838, #768)\n  // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n  // - can throw an exception in some circumstances.\n  try {\n    let currentElem = elem as SimpleNode;\n    const MAX_TRAVERSE_HEIGHT = 5;\n    const out = [];\n    let height = 0;\n    let len = 0;\n    const separator = ' \u003e ';\n    const sepLength = separator.length;\n    let nextStr;\n    const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n    const maxStringLength = (!Array.isArray(options) \u0026\u0026 options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n    while (currentElem \u0026\u0026 height++ \u003c MAX_TRAVERSE_HEIGHT) {\n      nextStr = _htmlElementAsString(currentElem, keyAttrs);\n      // bail out if\n      // - nextStr is the 'html' element\n      // - the length of the string that would be created exceeds maxStringLength\n      //   (ignore this limit if we are on the first iteration)\n      if (nextStr === 'html' || (height \u003e 1 \u0026\u0026 len + out.length * sepLength + nextStr.length \u003e= maxStringLength)) {\n        break;\n      }\n\n      out.push(nextStr);\n\n      len += nextStr.length;\n      currentElem = currentElem.parentNode;\n    }\n\n    return out.reverse().join(separator);\n  } catch {\n    return '\u003cunknown\u003e';\n  }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] =\u003e input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n  const elem = el as {\n    tagName?: string;\n    id?: string;\n    className?: string;\n    getAttribute(key: string): string;\n  };\n\n  const out = [];\n\n  if (!elem?.tagName) {\n    return '';\n  }\n\n  // @ts-expect-error WINDOW has HTMLElement\n  if (WINDOW.HTMLElement) {\n    // If using the component name annotation plugin, this value may be available on the DOM node\n    if (elem instanceof HTMLElement \u0026\u0026 elem.dataset) {\n      if (elem.dataset['sentryComponent']) {\n        return elem.dataset['sentryComponent'];\n      }\n      if (elem.dataset['sentryElement']) {\n        return elem.dataset['sentryElement'];\n      }\n    }\n  }\n\n  out.push(elem.tagName.toLowerCase());\n\n  // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n  const keyAttrPairs = keyAttrs?.length\n    ? keyAttrs.filter(keyAttr =\u003e elem.getAttribute(keyAttr)).map(keyAttr =\u003e [keyAttr, elem.getAttribute(keyAttr)])\n    : null;\n\n  if (keyAttrPairs?.length) {\n    keyAttrPairs.forEach(keyAttrPair =\u003e {\n      out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n    });\n  } else {\n    if (elem.id) {\n      out.push(`#${elem.id}`);\n    }\n\n    const className = elem.className;\n    if (className \u0026\u0026 isString(className)) {\n      const classes = className.split(/\\s+/);\n      for (const c of classes) {\n        out.push(`.${c}`);\n      }\n    }\n  }\n  for (const k of ['aria-label', 'type', 'name', 'title', 'alt']) {\n    const attr = elem.getAttribute(k);\n    if (attr) {\n      out.push(`[${k}=\"${attr}\"]`);\n    }\n  }\n\n  return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n  try {\n    return WINDOW.document.location.href;\n  } catch {\n    return '';\n  }\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking\n * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n  // @ts-expect-error WINDOW has HTMLElement\n  if (!WINDOW.HTMLElement) {\n    return null;\n  }\n\n  let currentElem = elem as SimpleNode;\n  const MAX_TRAVERSE_HEIGHT = 5;\n  for (let i = 0; i \u003c MAX_TRAVERSE_HEIGHT; i++) {\n    if (!currentElem) {\n      return null;\n    }\n\n    if (currentElem instanceof HTMLElement) {\n      if (currentElem.dataset['sentryComponent']) {\n        return currentElem.dataset['sentryComponent'];\n      }\n      if (currentElem.dataset['sentryElement']) {\n        return currentElem.dataset['sentryElement'];\n      }\n    }\n\n    currentElem = currentElem.parentNode;\n  }\n\n  return null;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { htmlTreeAsString } from './browser';\nimport { debug } from './debug-logger';\nimport { isElement, isError, isEvent, isInstanceOf, isPrimitive } from './is';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * If the method on the passed object is not a function, the wrapper will not be applied.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, \u003cother\n * args\u003e)` or `origMethod.apply(this, [\u003cother args\u003e])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) =\u003e any): void {\n  if (!(name in source)) {\n    return;\n  }\n\n  // explicitly casting to unknown because we don't know the type of the method initially at all\n  const original = source[name] as unknown;\n\n  if (typeof original !== 'function') {\n    return;\n  }\n\n  const wrapped = replacementFactory(original) as WrappedFunction;\n\n  // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n  // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n  if (typeof wrapped === 'function') {\n    markFunctionWrapped(wrapped, original);\n  }\n\n  try {\n    source[name] = wrapped;\n  } catch {\n    DEBUG_BUILD \u0026\u0026 debug.log(`Failed to replace method \"${name}\" in object`, source);\n  }\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n  try {\n    Object.defineProperty(obj, name, {\n      // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n      value,\n      writable: true,\n      configurable: true,\n    });\n  } catch {\n    DEBUG_BUILD \u0026\u0026 debug.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n  }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n  try {\n    const proto = original.prototype || {};\n    wrapped.prototype = original.prototype = proto;\n    addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n  } catch {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available.  See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function getOriginalFunction\u003cT extends Function\u003e(func: WrappedFunction\u003cT\u003e): T | undefined {\n  return func.__sentry_original__;\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n *  an Error.\n */\nexport function convertToPlainObject\u003cV\u003e(value: V):\n  | {\n      [ownProps: string]: unknown;\n      type: string;\n      target: string;\n      currentTarget: string;\n      detail?: unknown;\n    }\n  | {\n      [ownProps: string]: unknown;\n      message: string;\n      name: string;\n      stack?: string;\n    }\n  | V {\n  if (isError(value)) {\n    return {\n      message: value.message,\n      name: value.name,\n      stack: value.stack,\n      ...getOwnProperties(value),\n    };\n  } else if (isEvent(value)) {\n    const newObj: {\n      [ownProps: string]: unknown;\n      type: string;\n      target: string;\n      currentTarget: string;\n      detail?: unknown;\n    } = {\n      type: value.type,\n      target: serializeEventTarget(value.target),\n      currentTarget: serializeEventTarget(value.currentTarget),\n      ...getOwnProperties(value),\n    };\n\n    if (typeof CustomEvent !== 'undefined' \u0026\u0026 isInstanceOf(value, CustomEvent)) {\n      newObj.detail = value.detail;\n    }\n\n    return newObj;\n  } else {\n    return value;\n  }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n  try {\n    return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n  } catch {\n    return '\u003cunknown\u003e';\n  }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n  if (typeof obj === 'object' \u0026\u0026 obj !== null) {\n    return Object.fromEntries(Object.entries(obj));\n  }\n  return {};\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record\u003cstring, unknown\u003e): string {\n  const keys = Object.keys(convertToPlainObject(exception));\n  keys.sort();\n\n  return !keys[0] ? '[object has no keys]' : keys.join(', ');\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n *\n * @deprecated This function is no longer used by the SDK and will be removed in a future major version.\n */\nexport function dropUndefinedKeys\u003cT\u003e(inputValue: T): T {\n  // This map keeps track of what already visited nodes map to.\n  // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n  // references as the input object.\n  const memoizationMap = new Map\u003cunknown, unknown\u003e();\n\n  // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n  return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys\u003cT\u003e(inputValue: T, memoizationMap: Map\u003cunknown, unknown\u003e): T {\n  // Early return for primitive values\n  if (inputValue === null || typeof inputValue !== 'object') {\n    return inputValue;\n  }\n\n  // Check memo map first for all object types\n  const memoVal = memoizationMap.get(inputValue);\n  if (memoVal !== undefined) {\n    return memoVal as T;\n  }\n\n  // handle arrays\n  if (Array.isArray(inputValue)) {\n    const returnValue: unknown[] = [];\n    // Store mapping to handle circular references\n    memoizationMap.set(inputValue, returnValue);\n\n    inputValue.forEach(value =\u003e {\n      returnValue.push(_dropUndefinedKeys(value, memoizationMap));\n    });\n\n    return returnValue as unknown as T;\n  }\n\n  if (isPojo(inputValue)) {\n    const returnValue: { [key: string]: unknown } = {};\n    // Store mapping to handle circular references\n    memoizationMap.set(inputValue, returnValue);\n\n    const keys = Object.keys(inputValue);\n\n    keys.forEach(key =\u003e {\n      const val = inputValue[key];\n      if (val !== undefined) {\n        returnValue[key] = _dropUndefinedKeys(val, memoizationMap);\n      }\n    });\n\n    return returnValue as T;\n  }\n\n  // For other object types, return as is\n  return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record\u003cstring, unknown\u003e {\n  // Plain objects have Object as constructor or no constructor\n  const constructor = (input as object).constructor;\n  return constructor === Object || constructor === undefined;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n  let objectified;\n  switch (true) {\n    // this will catch both undefined and null\n    case wat == undefined:\n      objectified = new String(wat);\n      break;\n\n    // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n    // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n    // an object in order to wrap it.\n    case typeof wat === 'symbol' || typeof wat === 'bigint':\n      objectified = Object(wat);\n      break;\n\n    // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n    case isPrimitive(wat):\n      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n      objectified = new (wat as any).constructor(wat);\n      break;\n\n    // by process of elimination, at this point we know that `wat` must already be an object\n    default:\n      objectified = wat;\n      break;\n  }\n  return objectified;\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nexport type RandomSafeContextRunner = \u003cT\u003e(callback: () =\u003e T) =\u003e T;\n\n// undefined = not yet resolved, null = no runner found, function = runner found\nlet RESOLVED_RUNNER: RandomSafeContextRunner | null | undefined;\n\n/**\n * Simple wrapper that allows SDKs to *secretly* set context wrapper to generate safe random IDs in cache components contexts\n */\nexport function withRandomSafeContext\u003cT\u003e(cb: () =\u003e T): T {\n  // Skips future symbol lookups if we've already resolved (or attempted to resolve) the runner once\n  if (RESOLVED_RUNNER !== undefined) {\n    return RESOLVED_RUNNER ? RESOLVED_RUNNER(cb) : cb();\n  }\n\n  const sym = Symbol.for('__SENTRY_SAFE_RANDOM_ID_WRAPPER__');\n  const globalWithSymbol: typeof GLOBAL_OBJ \u0026 { [sym]?: RandomSafeContextRunner } = GLOBAL_OBJ;\n\n  if (sym in globalWithSymbol \u0026\u0026 typeof globalWithSymbol[sym] === 'function') {\n    RESOLVED_RUNNER = globalWithSymbol[sym];\n    return RESOLVED_RUNNER(cb);\n  }\n\n  RESOLVED_RUNNER = null;\n  return cb();\n}\n\n/**\n * Identical to Math.random() but wrapped in withRandomSafeContext\n * to ensure safe random number generation in certain contexts (e.g., Next.js Cache Components).\n */\nexport function safeMathRandom(): number {\n  return withRandomSafeContext(() =\u003e Math.random());\n}\n\n/**\n * Identical to Date.now() but wrapped in withRandomSafeContext\n * to ensure safe time value generation in certain contexts (e.g., Next.js Cache Components).\n */\nexport function safeDateNow(): number {\n  return withRandomSafeContext(() =\u003e Date.now());\n}\n","import { isRegExp, isString, isVueViewModel } from './is';\nimport { getVueInternalName } from './stacktrace';\n\nexport { escapeStringForRegex } from '../vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n  if (typeof str !== 'string' || max === 0) {\n    return str;\n  }\n  return str.length \u003c= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n  let newLine = line;\n  const lineLength = newLine.length;\n  if (lineLength \u003c= 150) {\n    return newLine;\n  }\n  if (colno \u003e lineLength) {\n    // eslint-disable-next-line no-param-reassign\n    colno = lineLength;\n  }\n\n  let start = Math.max(colno - 60, 0);\n  if (start \u003c 5) {\n    start = 0;\n  }\n\n  let end = Math.min(start + 140, lineLength);\n  if (end \u003e lineLength - 5) {\n    end = lineLength;\n  }\n  if (end === lineLength) {\n    start = Math.max(end - 140, 0);\n  }\n\n  newLine = newLine.slice(start, end);\n  if (start \u003e 0) {\n    newLine = `'{snip} ${newLine}`;\n  }\n  if (end \u003c lineLength) {\n    newLine += ' {snip}';\n  }\n\n  return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\nexport function safeJoin(input: unknown[], delimiter?: string): string {\n  if (!Array.isArray(input)) {\n    return '';\n  }\n\n  const output = [];\n  // eslint-disable-next-line typescript/prefer-for-of\n  for (let i = 0; i \u003c input.length; i++) {\n    const value = input[i];\n    try {\n      // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n      // console warnings. This happens when a Vue template is rendered with\n      // an undeclared variable, which we try to stringify, ultimately causing\n      // Vue to issue another warning which repeats indefinitely.\n      // see: https://github.com/getsentry/sentry-javascript/pull/8981\n      if (isVueViewModel(value)) {\n        output.push(getVueInternalName(value));\n      } else {\n        output.push(String(value));\n      }\n    } catch {\n      output.push('[value cannot be serialized]');\n    }\n  }\n\n  return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n  value: string,\n  pattern: RegExp | string,\n  requireExactStringMatch: boolean = false,\n): boolean {\n  if (!isString(value)) {\n    return false;\n  }\n\n  if (isRegExp(pattern)) {\n    return pattern.test(value);\n  }\n  if (isString(pattern)) {\n    return requireExactStringMatch ? value === pattern : value.includes(pattern);\n  }\n\n  return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n  testString: string,\n  patterns: Array\u003cstring | RegExp\u003e = [],\n  requireExactStringMatch: boolean = false,\n): boolean {\n  return patterns.some(pattern =\u003e isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","import type { Event } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { Mechanism } from '../types-hoist/mechanism';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { addNonEnumerableProperty } from './object';\nimport { safeMathRandom, withRandomSafeContext } from './randomSafeContext';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n  randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n  msCrypto?: CryptoInternal;\n  crypto?: CryptoInternal;\n}\n\nfunction getCrypto(): CryptoInternal | undefined {\n  const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ \u0026 CryptoGlobal;\n  return gbl.crypto || gbl.msCrypto;\n}\n\nlet emptyUuid: string | undefined;\n\nfunction getRandomByte(): number {\n  return safeMathRandom() * 16;\n}\n\n/**\n * UUID4 generator\n * @param crypto Object that provides the crypto API.\n * @returns string Generated UUID4.\n */\nexport function uuid4(crypto = getCrypto()): string {\n  try {\n    if (crypto?.randomUUID) {\n      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n      return withRandomSafeContext(() =\u003e crypto.randomUUID!()).replace(/-/g, '');\n    }\n  } catch {\n    // some runtimes can crash invoking crypto\n    // https://github.com/getsentry/sentry-javascript/issues/8935\n  }\n\n  if (!emptyUuid) {\n    // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n    // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n    emptyUuid = ([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11;\n  }\n\n  return emptyUuid.replace(/[018]/g, c =\u003e\n    // eslint-disable-next-line no-bitwise\n    ((c as unknown as number) ^ ((getRandomByte() \u0026 15) \u003e\u003e ((c as unknown as number) / 4))).toString(16),\n  );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n  return event.exception?.values?.[0];\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n  const { message, event_id: eventId } = event;\n  if (message) {\n    return message;\n  }\n\n  const firstException = getFirstException(event);\n  if (firstException) {\n    if (firstException.type \u0026\u0026 firstException.value) {\n      return `${firstException.type}: ${firstException.value}`;\n    }\n    return firstException.type || firstException.value || eventId || '\u003cunknown\u003e';\n  }\n  return eventId || '\u003cunknown\u003e';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n  const exception = (event.exception = event.exception || {});\n  const values = (exception.values = exception.values || []);\n  const firstException = (values[0] = values[0] || {});\n  if (!firstException.value) {\n    firstException.value = value || '';\n  }\n  if (!firstException.type) {\n    firstException.type = type || 'Error';\n  }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial\u003cMechanism\u003e): void {\n  const firstException = getFirstException(event);\n  if (!firstException) {\n    return;\n  }\n\n  const defaultMechanism = { type: 'generic', handled: true };\n  const currentMechanism = firstException.mechanism;\n  firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n  if (newMechanism \u0026\u0026 'data' in newMechanism) {\n    const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n    firstException.mechanism.data = mergedData;\n  }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n  /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n  major?: number;\n  minor?: number;\n  patch?: number;\n  prerelease?: string;\n  buildmetadata?: string;\n}\n\nfunction _parseInt(input: string | undefined): number {\n  return parseInt(input || '', 10);\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n  const match = input.match(SEMVER_REGEXP) || [];\n  const major = _parseInt(match[1]);\n  const minor = _parseInt(match[2]);\n  const patch = _parseInt(match[3]);\n  return {\n    buildmetadata: match[5],\n    major: isNaN(major) ? undefined : major,\n    minor: isNaN(minor) ? undefined : minor,\n    patch: isNaN(patch) ? undefined : patch,\n    prerelease: match[4],\n  };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n  // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n  if (frame.lineno === undefined) {\n    return;\n  }\n\n  const maxLines = lines.length;\n  const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n  frame.pre_context = lines\n    .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n    .map((line: string) =\u003e snipLine(line, 0));\n\n  // We guard here to ensure this is not larger than the existing number of lines\n  const lineIndex = Math.min(maxLines - 1, sourceLine);\n\n  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n  frame.context_line = snipLine(lines[lineIndex]!, frame.colno || 0);\n\n  frame.post_context = lines\n    .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n    .map((line: string) =\u003e snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n  if (isAlreadyCaptured(exception)) {\n    return true;\n  }\n\n  try {\n    // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n    // `ExtraErrorData` integration\n    addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n  } catch {\n    // `exception` is a primitive, so we can't mark it seen\n  }\n\n  return false;\n}\n\n/**\n * Checks whether we've already captured the given exception (note: not an identical exception - the very object).\n * It is considered already captured if it has the `__sentry_captured__` property set to `true`.\n *\n * @internal Only considered for internal usage\n */\nexport function isAlreadyCaptured(exception: unknown): boolean | void {\n  try {\n    return (exception as { __sentry_captured__?: boolean }).__sentry_captured__;\n  } catch {} // eslint-disable-line no-empty\n}\n","import { safeDateNow, withRandomSafeContext } from './randomSafeContext';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n  /**\n   * The millisecond timestamp at which measurement began, measured in Unix time.\n   */\n  timeOrigin: number;\n  /**\n   * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n   */\n  now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport function dateTimestampInSeconds(): number {\n  return safeDateNow() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () =\u003e number {\n  const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ \u0026 { performance?: Performance };\n  // Some browser and environments don't have a performance or timeOrigin, so we fallback to\n  // using Date.now() to compute the starting time.\n  if (!performance?.now || !performance.timeOrigin) {\n    return dateTimestampInSeconds;\n  }\n\n  const timeOrigin = performance.timeOrigin;\n\n  // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n  // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n  //\n  // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n  // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n  // correct for this.\n  // See: https://github.com/getsentry/sentry-javascript/issues/2590\n  // See: https://github.com/mdn/content/issues/4713\n  // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n  return () =\u003e {\n    return (timeOrigin + withRandomSafeContext(() =\u003e performance.now())) / ONE_SECOND_IN_MS;\n  };\n}\n\nlet _cachedTimestampInSeconds: (() =\u003e number) | undefined;\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport function timestampInSeconds(): number {\n  // We store this in a closure so that we don't have to create a new function every time this is called.\n  const func = _cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc());\n  return func();\n}\n\n/**\n * Cached result of getBrowserTimeOrigin.\n */\nlet cachedTimeOrigin: number | null | undefined = null;\n\n/**\n * Gets the time origin and the mode used to determine it.\n *\n * Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n * performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n * data as reliable if they are within a reasonable threshold of the current time.\n *\n * TODO: move to `@sentry/browser-utils` package.\n */\nfunction getBrowserTimeOrigin(): number | undefined {\n  const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ \u0026 Window;\n  if (!performance?.now) {\n    return undefined;\n  }\n\n  const threshold = 300_000; // 5 minutes in milliseconds\n  const performanceNow = withRandomSafeContext(() =\u003e performance.now());\n  const dateNow = safeDateNow();\n\n  const timeOrigin = performance.timeOrigin;\n  if (typeof timeOrigin === 'number') {\n    const timeOriginDelta = Math.abs(timeOrigin + performanceNow - dateNow);\n    if (timeOriginDelta \u003c threshold) {\n      return timeOrigin;\n    }\n  }\n\n  // TODO: Remove all code related to `performance.timing.navigationStart` once we drop support for Safari 14.\n  // `performance.timeSince` is available in Safari 15.\n  // see: https://caniuse.com/mdn-api_performance_timeorigin\n\n  // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n  // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n  // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n  // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n  // Date API.\n  // eslint-disable-next-line deprecation/deprecation\n  const navigationStart = performance.timing?.navigationStart;\n  if (typeof navigationStart === 'number') {\n    const navigationStartDelta = Math.abs(navigationStart + performanceNow - dateNow);\n    if (navigationStartDelta \u003c threshold) {\n      return navigationStart;\n    }\n  }\n\n  // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to subtracting\n  // `performance.now()` from `Date.now()`.\n  return dateNow - performanceNow;\n}\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport function browserPerformanceTimeOrigin(): number | undefined {\n  if (cachedTimeOrigin === null) {\n    cachedTimeOrigin = getBrowserTimeOrigin();\n  }\n\n  return cachedTimeOrigin;\n}\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from './types-hoist/session';\nimport { uuid4 } from './utils/misc';\nimport { timestampInSeconds } from './utils/time';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit\u003cSessionContext, 'started' | 'status'\u003e): Session {\n  // Both timestamp and started are in seconds since the UNIX epoch.\n  const startingTime = timestampInSeconds();\n\n  const session: Session = {\n    sid: uuid4(),\n    init: true,\n    timestamp: startingTime,\n    started: startingTime,\n    duration: 0,\n    status: 'ok',\n    errors: 0,\n    ignoreDuration: false,\n    toJSON: () =\u003e sessionToJSON(session),\n  };\n\n  if (context) {\n    updateSession(session, context);\n  }\n\n  return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see Client.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n  if (context.user) {\n    if (!session.ipAddress \u0026\u0026 context.user.ip_address) {\n      session.ipAddress = context.user.ip_address;\n    }\n\n    if (!session.did \u0026\u0026 !context.did) {\n      session.did = context.user.id || context.user.email || context.user.username;\n    }\n  }\n\n  session.timestamp = context.timestamp || timestampInSeconds();\n\n  if (context.abnormal_mechanism) {\n    session.abnormal_mechanism = context.abnormal_mechanism;\n  }\n\n  if (context.ignoreDuration) {\n    session.ignoreDuration = context.ignoreDuration;\n  }\n  if (context.sid) {\n    // Good enough uuid validation. — Kamil\n    session.sid = context.sid.length === 32 ? context.sid : uuid4();\n  }\n  if (context.init !== undefined) {\n    session.init = context.init;\n  }\n  if (!session.did \u0026\u0026 context.did) {\n    session.did = `${context.did}`;\n  }\n  if (typeof context.started === 'number') {\n    session.started = context.started;\n  }\n  if (session.ignoreDuration) {\n    session.duration = undefined;\n  } else if (typeof context.duration === 'number') {\n    session.duration = context.duration;\n  } else {\n    const duration = session.timestamp - session.started;\n    session.duration = duration \u003e= 0 ? duration : 0;\n  }\n  if (context.release) {\n    session.release = context.release;\n  }\n  if (context.environment) {\n    session.environment = context.environment;\n  }\n  if (!session.ipAddress \u0026\u0026 context.ipAddress) {\n    session.ipAddress = context.ipAddress;\n  }\n  if (!session.userAgent \u0026\u0026 context.userAgent) {\n    session.userAgent = context.userAgent;\n  }\n  if (typeof context.errors === 'number') {\n    session.errors = context.errors;\n  }\n  if (context.status) {\n    session.status = context.status;\n  }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n *               this function will keep the previously set status, unless it was `'ok'` in which case\n *               it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude\u003cSessionStatus, 'ok'\u003e): void {\n  let context = {};\n  if (status) {\n    context = { status };\n  } else if (session.status === 'ok') {\n    context = { status: 'exited' };\n  }\n\n  updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n  return {\n    sid: `${session.sid}`,\n    init: session.init,\n    // Make sure that sec is converted to ms for date constructor\n    started: new Date(session.started * 1000).toISOString(),\n    timestamp: new Date(session.timestamp * 1000).toISOString(),\n    status: session.status,\n    errors: session.errors,\n    did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n    duration: session.duration,\n    abnormal_mechanism: session.abnormal_mechanism,\n    attrs: {\n      release: session.release,\n      environment: session.environment,\n      ip_address: session.ipAddress,\n      user_agent: session.userAgent,\n    },\n  };\n}\n","/**\n * Shallow merge two objects.\n * Does not mutate the passed in objects.\n * Undefined/empty values in the merge object will overwrite existing values.\n *\n * By default, this merges 2 levels deep.\n */\nexport function merge\u003cT\u003e(initialObj: T, mergeObj: T, levels = 2): T {\n  // If the merge value is not an object, or we have no merge levels left,\n  // we just set the value to the merge value\n  if (!mergeObj || typeof mergeObj !== 'object' || levels \u003c= 0) {\n    return mergeObj;\n  }\n\n  // If the merge object is an empty object, and the initial object is not undefined, we return the initial object\n  if (initialObj \u0026\u0026 Object.keys(mergeObj).length === 0) {\n    return initialObj;\n  }\n\n  // Clone object\n  const output = { ...initialObj };\n\n  // Merge values into output, resursively\n  for (const key in mergeObj) {\n    if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n      output[key] = merge(output[key], mergeObj[key], levels - 1);\n    }\n  }\n\n  return output;\n}\n","import { uuid4 } from './misc';\n\n/**\n * Generate a random, valid trace ID.\n */\nexport function generateTraceId(): string {\n  return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nexport function generateSpanId(): string {\n  return uuid4().substring(16);\n}\n","import type { Scope } from '../scope';\nimport type { Span } from '../types-hoist/span';\nimport { addNonEnumerableProperty } from '../utils/object';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\ntype ScopeWithMaybeSpan = Scope \u0026 {\n  [SCOPE_SPAN_FIELD]?: Span;\n};\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _setSpanForScope(scope: Scope, span: Span | undefined): void {\n  if (span) {\n    addNonEnumerableProperty(scope as ScopeWithMaybeSpan, SCOPE_SPAN_FIELD, span);\n  } else {\n    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n    delete (scope as ScopeWithMaybeSpan)[SCOPE_SPAN_FIELD];\n  }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _getSpanForScope(scope: ScopeWithMaybeSpan): Span | undefined {\n  return scope[SCOPE_SPAN_FIELD];\n}\n","/* eslint-disable max-lines */\nimport type { AttributeObject, RawAttribute, RawAttributes } from './attributes';\nimport type { Client } from './client';\nimport { DEBUG_BUILD } from './debug-build';\nimport { updateSession } from './session';\nimport type { Attachment } from './types-hoist/attachment';\nimport type { Breadcrumb } from './types-hoist/breadcrumb';\nimport type { Context, Contexts } from './types-hoist/context';\nimport type { DynamicSamplingContext } from './types-hoist/envelope';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { Extra, Extras } from './types-hoist/extra';\nimport type { Primitive } from './types-hoist/misc';\nimport type { RequestEventData } from './types-hoist/request';\nimport type { Session } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { Span } from './types-hoist/span';\nimport type { PropagationContext } from './types-hoist/tracing';\nimport type { User } from './types-hoist/user';\nimport { debug } from './utils/debug-logger';\nimport { isPlainObject } from './utils/is';\nimport { merge } from './utils/merge';\nimport { uuid4 } from './utils/misc';\nimport { generateTraceId } from './utils/propagationContext';\nimport { safeMathRandom } from './utils/randomSafeContext';\nimport { _getSpanForScope, _setSpanForScope } from './utils/spanOnScope';\nimport { truncate } from './utils/string';\nimport { dateTimestampInSeconds } from './utils/time';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * A context to be used for capturing an event.\n * This can either be a Scope, or a partial ScopeContext,\n * or a callback that receives the current scope and returns a new scope to use.\n */\nexport type CaptureContext = Scope | Partial\u003cScopeContext\u003e | ((scope: Scope) =\u003e Scope);\n\n/**\n * Data that can be converted to a Scope.\n */\nexport interface ScopeContext {\n  user: User;\n  level: SeverityLevel;\n  extra: Extras;\n  contexts: Contexts;\n  tags: { [key: string]: Primitive };\n  attributes?: RawAttributes\u003cRecord\u003cstring, unknown\u003e\u003e;\n  fingerprint: string[];\n  propagationContext: PropagationContext;\n  conversationId?: string;\n}\n\nexport interface SdkProcessingMetadata {\n  [key: string]: unknown;\n  requestSession?: {\n    status: 'ok' | 'errored' | 'crashed';\n  };\n  normalizedRequest?: RequestEventData;\n  dynamicSamplingContext?: Partial\u003cDynamicSamplingContext\u003e;\n  capturedSpanScope?: Scope;\n  capturedSpanIsolationScope?: Scope;\n  spanCountBeforeProcessing?: number;\n  ipAddress?: string;\n}\n\n/**\n * Normalized data of the Scope, ready to be used.\n */\nexport interface ScopeData {\n  eventProcessors: EventProcessor[];\n  breadcrumbs: Breadcrumb[];\n  user: User;\n  tags: { [key: string]: Primitive };\n  // TODO(v11): Make this a required field (could be subtly breaking if we did it today)\n  attributes?: RawAttributes\u003cRecord\u003cstring, unknown\u003e\u003e;\n  extra: Extras;\n  contexts: Contexts;\n  attachments: Attachment[];\n  propagationContext: PropagationContext;\n  sdkProcessingMetadata: SdkProcessingMetadata;\n  fingerprint: string[];\n  level?: SeverityLevel;\n  transactionName?: string;\n  span?: Span;\n  conversationId?: string;\n}\n\n/**\n * Holds additional event information.\n */\nexport class Scope {\n  /** Flag if notifying is happening. */\n  protected _notifyingListeners: boolean;\n\n  /** Callback for client to receive scope changes. */\n  protected _scopeListeners: Array\u003c(scope: Scope) =\u003e void\u003e;\n\n  /** Callback list that will be called during event processing. */\n  protected _eventProcessors: EventProcessor[];\n\n  /** Array of breadcrumbs. */\n  protected _breadcrumbs: Breadcrumb[];\n\n  /** User */\n  protected _user: User;\n\n  /** Tags */\n  protected _tags: { [key: string]: Primitive };\n\n  /** Attributes */\n  protected _attributes: RawAttributes\u003cRecord\u003cstring, unknown\u003e\u003e;\n\n  /** Extra */\n  protected _extra: Extras;\n\n  /** Contexts */\n  protected _contexts: Contexts;\n\n  /** Attachments */\n  protected _attachments: Attachment[];\n\n  /** Propagation Context for distributed tracing */\n  protected _propagationContext: PropagationContext;\n\n  /**\n   * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n   * sent to Sentry\n   */\n  protected _sdkProcessingMetadata: SdkProcessingMetadata;\n\n  /** Fingerprint */\n  protected _fingerprint?: string[];\n\n  /** Severity */\n  protected _level?: SeverityLevel;\n\n  /**\n   * Transaction Name\n   *\n   * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n   * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n   */\n  protected _transactionName?: string;\n\n  /** Session */\n  protected _session?: Session;\n\n  /** The client on this scope */\n  protected _client?: Client;\n\n  /** Contains the last event id of a captured event.  */\n  protected _lastEventId?: string;\n\n  /** Conversation ID */\n  protected _conversationId?: string;\n\n  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n  public constructor() {\n    this._notifyingListeners = false;\n    this._scopeListeners = [];\n    this._eventProcessors = [];\n    this._breadcrumbs = [];\n    this._attachments = [];\n    this._user = {};\n    this._tags = {};\n    this._attributes = {};\n    this._extra = {};\n    this._contexts = {};\n    this._sdkProcessingMetadata = {};\n    this._propagationContext = {\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom(),\n    };\n  }\n\n  /**\n   * Clone all data from this scope into a new scope.\n   */\n  public clone(): Scope {\n    const newScope = new Scope();\n    newScope._breadcrumbs = [...this._breadcrumbs];\n    newScope._tags = { ...this._tags };\n    newScope._attributes = { ...this._attributes };\n    newScope._extra = { ...this._extra };\n    newScope._contexts = { ...this._contexts };\n    if (this._contexts.flags) {\n      // We need to copy the `values` array so insertions on a cloned scope\n      // won't affect the original array.\n      newScope._contexts.flags = {\n        values: [...this._contexts.flags.values],\n      };\n    }\n\n    newScope._user = this._user;\n    newScope._level = this._level;\n    newScope._session = this._session;\n    newScope._transactionName = this._transactionName;\n    newScope._fingerprint = this._fingerprint;\n    newScope._eventProcessors = [...this._eventProcessors];\n    newScope._attachments = [...this._attachments];\n    newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n    newScope._propagationContext = { ...this._propagationContext };\n    newScope._client = this._client;\n    newScope._lastEventId = this._lastEventId;\n    newScope._conversationId = this._conversationId;\n\n    _setSpanForScope(newScope, _getSpanForScope(this));\n\n    return newScope;\n  }\n\n  /**\n   * Update the client assigned to this scope.\n   * Note that not every scope will have a client assigned - isolation scopes \u0026 the global scope will generally not have a client,\n   * as well as manually created scopes.\n   */\n  public setClient(client: Client | undefined): void {\n    this._client = client;\n  }\n\n  /**\n   * Set the ID of the last captured error event.\n   * This is generally only captured on the isolation scope.\n   */\n  public setLastEventId(lastEventId: string | undefined): void {\n    this._lastEventId = lastEventId;\n  }\n\n  /**\n   * Get the client assigned to this scope.\n   */\n  public getClient\u003cC extends Client\u003e(): C | undefined {\n    return this._client as C | undefined;\n  }\n\n  /**\n   * Get the ID of the last captured error event.\n   * This is generally only available on the isolation scope.\n   */\n  public lastEventId(): string | undefined {\n    return this._lastEventId;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public addScopeListener(callback: (scope: Scope) =\u003e void): void {\n    this._scopeListeners.push(callback);\n  }\n\n  /**\n   * Add an event processor that will be called before an event is sent.\n   */\n  public addEventProcessor(callback: EventProcessor): this {\n    this._eventProcessors.push(callback);\n    return this;\n  }\n\n  /**\n   * Set the user for this scope.\n   * Set to `null` to unset the user.\n   */\n  public setUser(user: User | null): this {\n    // If null is passed we want to unset everything, but still define keys,\n    // so that later down in the pipeline any existing values are cleared.\n    this._user = user || {\n      email: undefined,\n      id: undefined,\n      ip_address: undefined,\n      username: undefined,\n    };\n\n    if (this._session) {\n      updateSession(this._session, { user });\n    }\n\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Get the user from this scope.\n   */\n  public getUser(): User | undefined {\n    return this._user;\n  }\n\n  /**\n   * Set the conversation ID for this scope.\n   * Set to `null` to unset the conversation ID.\n   */\n  public setConversationId(conversationId: string | null | undefined): this {\n    this._conversationId = conversationId || undefined;\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Set an object that will be merged into existing tags on the scope,\n   * and will be sent as tags data with the event.\n   */\n  public setTags(tags: { [key: string]: Primitive }): this {\n    this._tags = {\n      ...this._tags,\n      ...tags,\n    };\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Set a single tag that will be sent as tags data with the event.\n   */\n  public setTag(key: string, value: Primitive): this {\n    return this.setTags({ [key]: value });\n  }\n\n  /**\n   * Sets attributes onto the scope.\n   *\n   * These attributes are currently applied to logs and metrics.\n   * In the future, they will also be applied to spans.\n   *\n   * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for\n   * more complex attribute types. We'll add this support in the future but already specify the wider type to\n   * avoid a breaking change in the future.\n   *\n   * @param newAttributes - The attributes to set on the scope. You can either pass in key-value pairs, or\n   * an object with a `value` and an optional `unit` (if applicable to your attribute).\n   *\n   * @example\n   * ```typescript\n   * scope.setAttributes({\n   *   is_admin: true,\n   *   payment_selection: 'credit_card',\n   *   render_duration: { value: 'render_duration', unit: 'ms' },\n   * });\n   * ```\n   */\n  public setAttributes\u003cT extends Record\u003cstring, unknown\u003e\u003e(newAttributes: RawAttributes\u003cT\u003e): this {\n    this._attributes = {\n      ...this._attributes,\n      ...newAttributes,\n    };\n\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Sets an attribute onto the scope.\n   *\n   * These attributes are currently applied to logs and metrics.\n   * In the future, they will also be applied to spans.\n   *\n   * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for\n   * more complex attribute types. We'll add this support in the future but already specify the wider type to\n   * avoid a breaking change in the future.\n   *\n   * @param key - The attribute key.\n   * @param value - the attribute value. You can either pass in a raw value, or an attribute\n   * object with a `value` and an optional `unit` (if applicable to your attribute).\n   *\n   * @example\n   * ```typescript\n   * scope.setAttribute('is_admin', true);\n   * scope.setAttribute('render_duration', { value: 'render_duration', unit: 'ms' });\n   * ```\n   */\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  public setAttribute\u003cT extends RawAttribute\u003cT\u003e extends { value: any } | { unit: any } ? AttributeObject : unknown\u003e(\n    key: string,\n    value: RawAttribute\u003cT\u003e,\n  ): this {\n    return this.setAttributes({ [key]: value });\n  }\n\n  /**\n   * Removes the attribute with the given key from the scope.\n   *\n   * @param key - The attribute key.\n   *\n   * @example\n   * ```typescript\n   * scope.removeAttribute('is_admin');\n   * ```\n   */\n  public removeAttribute(key: string): this {\n    if (key in this._attributes) {\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete this._attributes[key];\n      this._notifyScopeListeners();\n    }\n    return this;\n  }\n\n  /**\n   * Set an object that will be merged into existing extra on the scope,\n   * and will be sent as extra data with the event.\n   */\n  public setExtras(extras: Extras): this {\n    this._extra = {\n      ...this._extra,\n      ...extras,\n    };\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Set a single key:value extra entry that will be sent as extra data with the event.\n   */\n  public setExtra(key: string, extra: Extra): this {\n    this._extra = { ...this._extra, [key]: extra };\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Sets the fingerprint on the scope to send with the events.\n   * @param {string[]} fingerprint Fingerprint to group events in Sentry.\n   */\n  public setFingerprint(fingerprint: string[]): this {\n    this._fingerprint = fingerprint;\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Sets the level on the scope for future events.\n   */\n  public setLevel(level: SeverityLevel): this {\n    this._level = level;\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Sets the transaction name on the scope so that the name of e.g. taken server route or\n   * the page location is attached to future events.\n   *\n   * IMPORTANT: Calling this function does NOT change the name of the currently active\n   * root span. If you want to change the name of the active root span, use\n   * `Sentry.updateSpanName(rootSpan, 'new name')` instead.\n   *\n   * By default, the SDK updates the scope's transaction name automatically on sensible\n   * occasions, such as a page navigation or when handling a new request on the server.\n   */\n  public setTransactionName(name?: string): this {\n    this._transactionName = name;\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Sets context data with the given name.\n   * Data passed as context will be normalized. You can also pass `null` to unset the context.\n   * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.\n   */\n  public setContext(key: string, context: Context | null): this {\n    if (context === null) {\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete this._contexts[key];\n    } else {\n      this._contexts[key] = context;\n    }\n\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Set the session for the scope.\n   */\n  public setSession(session?: Session): this {\n    if (!session) {\n      delete this._session;\n    } else {\n      this._session = session;\n    }\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Get the session from the scope.\n   */\n  public getSession(): Session | undefined {\n    return this._session;\n  }\n\n  /**\n   * Updates the scope with provided data. Can work in three variations:\n   * - plain object containing updatable attributes\n   * - Scope instance that'll extract the attributes from\n   * - callback function that'll receive the current scope as an argument and allow for modifications\n   */\n  public update(captureContext?: CaptureContext): this {\n    if (!captureContext) {\n      return this;\n    }\n\n    const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n    const scopeInstance =\n      scopeToMerge instanceof Scope\n        ? scopeToMerge.getScopeData()\n        : isPlainObject(scopeToMerge)\n          ? (captureContext as ScopeContext)\n          : undefined;\n\n    const {\n      tags,\n      attributes,\n      extra,\n      user,\n      contexts,\n      level,\n      fingerprint = [],\n      propagationContext,\n      conversationId,\n    } = scopeInstance || {};\n\n    this._tags = { ...this._tags, ...tags };\n    this._attributes = { ...this._attributes, ...attributes };\n    this._extra = { ...this._extra, ...extra };\n    this._contexts = { ...this._contexts, ...contexts };\n\n    if (user \u0026\u0026 Object.keys(user).length) {\n      this._user = user;\n    }\n\n    if (level) {\n      this._level = level;\n    }\n\n    if (fingerprint.length) {\n      this._fingerprint = fingerprint;\n    }\n\n    if (propagationContext) {\n      this._propagationContext = propagationContext;\n    }\n\n    if (conversationId) {\n      this._conversationId = conversationId;\n    }\n\n    return this;\n  }\n\n  /**\n   * Clears the current scope and resets its properties.\n   * Note: The client will not be cleared.\n   */\n  public clear(): this {\n    // client is not cleared here on purpose!\n    this._breadcrumbs = [];\n    this._tags = {};\n    this._attributes = {};\n    this._extra = {};\n    this._user = {};\n    this._contexts = {};\n    this._level = undefined;\n    this._transactionName = undefined;\n    this._fingerprint = undefined;\n    this._session = undefined;\n    this._conversationId = undefined;\n    _setSpanForScope(this, undefined);\n    this._attachments = [];\n    this.setPropagationContext({\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom(),\n    });\n\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Adds a breadcrumb to the scope.\n   * By default, the last 100 breadcrumbs are kept.\n   */\n  public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n    const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n    // No data has been changed, so don't notify scope listeners\n    if (maxCrumbs \u003c= 0) {\n      return this;\n    }\n\n    const mergedBreadcrumb: Breadcrumb = {\n      timestamp: dateTimestampInSeconds(),\n      ...breadcrumb,\n      // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory\n      message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message,\n    };\n\n    this._breadcrumbs.push(mergedBreadcrumb);\n    if (this._breadcrumbs.length \u003e maxCrumbs) {\n      this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);\n      this._client?.recordDroppedEvent('buffer_overflow', 'log_item');\n    }\n\n    this._notifyScopeListeners();\n\n    return this;\n  }\n\n  /**\n   * Get the last breadcrumb of the scope.\n   */\n  public getLastBreadcrumb(): Breadcrumb | undefined {\n    return this._breadcrumbs[this._breadcrumbs.length - 1];\n  }\n\n  /**\n   * Clear all breadcrumbs from the scope.\n   */\n  public clearBreadcrumbs(): this {\n    this._breadcrumbs = [];\n    this._notifyScopeListeners();\n    return this;\n  }\n\n  /**\n   * Add an attachment to the scope.\n   */\n  public addAttachment(attachment: Attachment): this {\n    this._attachments.push(attachment);\n    return this;\n  }\n\n  /**\n   * Clear all attachments from the scope.\n   */\n  public clearAttachments(): this {\n    this._attachments = [];\n    return this;\n  }\n\n  /**\n   * Get the data of this scope, which should be applied to an event during processing.\n   */\n  public getScopeData(): ScopeData {\n    return {\n      breadcrumbs: this._breadcrumbs,\n      attachments: this._attachments,\n      contexts: this._contexts,\n      tags: this._tags,\n      attributes: this._attributes,\n      extra: this._extra,\n      user: this._user,\n      level: this._level,\n      fingerprint: this._fingerprint || [],\n      eventProcessors: this._eventProcessors,\n      propagationContext: this._propagationContext,\n      sdkProcessingMetadata: this._sdkProcessingMetadata,\n      transactionName: this._transactionName,\n      span: _getSpanForScope(this),\n      conversationId: this._conversationId,\n    };\n  }\n\n  /**\n   * Add data which will be accessible during event processing but won't get sent to Sentry.\n   */\n  public setSDKProcessingMetadata(newData: SdkProcessingMetadata): this {\n    this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n    return this;\n  }\n\n  /**\n   * Add propagation context to the scope, used for distributed tracing\n   */\n  public setPropagationContext(context: PropagationContext): this {\n    this._propagationContext = context;\n    return this;\n  }\n\n  /**\n   * Get propagation context from the scope, used for distributed tracing\n   */\n  public getPropagationContext(): PropagationContext {\n    return this._propagationContext;\n  }\n\n  /**\n   * Capture an exception for this scope.\n   *\n   * @returns {string} The id of the captured Sentry event.\n   */\n  public captureException(exception: unknown, hint?: EventHint): string {\n    const eventId = hint?.event_id || uuid4();\n\n    if (!this._client) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('No client configured on scope - will not capture exception!');\n      return eventId;\n    }\n\n    const syntheticException = new Error('Sentry syntheticException');\n\n    this._client.captureException(\n      exception,\n      {\n        originalException: exception,\n        syntheticException,\n        ...hint,\n        event_id: eventId,\n      },\n      this,\n    );\n\n    return eventId;\n  }\n\n  /**\n   * Capture a message for this scope.\n   *\n   * @returns {string} The id of the captured message.\n   */\n  public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n    const eventId = hint?.event_id || uuid4();\n\n    if (!this._client) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('No client configured on scope - will not capture message!');\n      return eventId;\n    }\n\n    const syntheticException = hint?.syntheticException ?? new Error(message);\n\n    this._client.captureMessage(\n      message,\n      level,\n      {\n        originalException: message,\n        syntheticException,\n        ...hint,\n        event_id: eventId,\n      },\n      this,\n    );\n\n    return eventId;\n  }\n\n  /**\n   * Capture a Sentry event for this scope.\n   *\n   * @returns {string} The id of the captured event.\n   */\n  public captureEvent(event: Event, hint?: EventHint): string {\n    const eventId = event.event_id || hint?.event_id || uuid4();\n\n    if (!this._client) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('No client configured on scope - will not capture event!');\n      return eventId;\n    }\n\n    this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n    return eventId;\n  }\n\n  /**\n   * This will be called on every set call.\n   */\n  protected _notifyScopeListeners(): void {\n    // We need this check for this._notifyingListeners to be able to work on scope during updates\n    // If this check is not here we'll produce endless recursion when something is done with the scope\n    // during the callback.\n    if (!this._notifyingListeners) {\n      this._notifyingListeners = true;\n      this._scopeListeners.forEach(callback =\u003e {\n        callback(this);\n      });\n      this._notifyingListeners = false;\n    }\n  }\n}\n","import { getGlobalSingleton } from './carrier';\nimport { Scope } from './scope';\n\n/** Get the default current scope. */\nexport function getDefaultCurrentScope(): Scope {\n  return getGlobalSingleton('defaultCurrentScope', () =\u003e new Scope());\n}\n\n/** Get the default isolation scope. */\nexport function getDefaultIsolationScope(): Scope {\n  return getGlobalSingleton('defaultIsolationScope', () =\u003e new Scope());\n}\n","const isActualPromise = (p: unknown) =\u003e\n  p instanceof Promise \u0026\u0026 !(p as unknown as ChainedPromiseLike\u003cunknown\u003e)[kChainedCopy];\n\ntype ChainedPromiseLike\u003cT\u003e = PromiseLike\u003cT\u003e \u0026 {\n  [kChainedCopy]: true;\n};\nconst kChainedCopy = Symbol('chained PromiseLike');\n\n/**\n * Copy the properties from a decorated promiselike object onto its chained\n * actual promise.\n */\nexport const chainAndCopyPromiseLike = \u003cV, T extends PromiseLike\u003cV\u003e\u003e(\n  original: T,\n  onSuccess: (value: V) =\u003e void,\n  onError: (e: unknown) =\u003e void,\n): T =\u003e {\n  const chained = original.then(\n    value =\u003e {\n      onSuccess(value);\n      return value;\n    },\n    err =\u003e {\n      onError(err);\n      throw err;\n    },\n  ) as T;\n\n  // if we're just dealing with \"normal\" Promise objects, return the chain\n  return isActualPromise(chained) \u0026\u0026 isActualPromise(original) ? chained : copyProps(original, chained);\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst copyProps = \u003cT extends Record\u003cstring, any\u003e\u003e(original: T, chained: T): T =\u003e {\n  let mutated = false;\n  //oxlint-disable-next-line guard-for-in\n  for (const key in original) {\n    if (key in chained) continue;\n    mutated = true;\n    const value = original[key];\n    if (typeof value === 'function') {\n      Object.defineProperty(chained, key, {\n        value: (...args: unknown[]) =\u003e value.apply(original, args),\n        enumerable: true,\n        configurable: true,\n        writable: true,\n      });\n    } else {\n      (chained as Record\u003cstring, unknown\u003e)[key] = value;\n    }\n  }\n\n  if (mutated) Object.assign(chained, { [kChainedCopy]: true });\n  return chained;\n};\n","import type { Client } from '../client';\nimport { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes';\nimport { Scope } from '../scope';\nimport { chainAndCopyPromiseLike } from '../utils/chain-and-copy-promiselike';\nimport { isThenable } from '../utils/is';\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport type { AsyncContextStrategy } from './types';\n\ninterface Layer {\n  client?: Client;\n  scope: Scope;\n}\n\n/**\n * This is an object that holds a stack of scopes.\n */\nexport class AsyncContextStack {\n  private readonly _stack: [Layer, ...Layer[]];\n  private _isolationScope: Scope;\n\n  public constructor(scope?: Scope, isolationScope?: Scope) {\n    let assignedScope;\n    if (!scope) {\n      assignedScope = new Scope();\n    } else {\n      assignedScope = scope;\n    }\n\n    let assignedIsolationScope;\n    if (!isolationScope) {\n      assignedIsolationScope = new Scope();\n    } else {\n      assignedIsolationScope = isolationScope;\n    }\n\n    // scope stack for domains or the process\n    this._stack = [{ scope: assignedScope }];\n    this._isolationScope = assignedIsolationScope;\n  }\n\n  /**\n   * Fork a scope for the stack.\n   */\n  public withScope\u003cT\u003e(callback: (scope: Scope) =\u003e T): T {\n    const scope = this._pushScope();\n\n    let maybePromiseResult: T;\n    try {\n      maybePromiseResult = callback(scope);\n    } catch (e) {\n      this._popScope();\n      throw e;\n    }\n\n    if (isThenable(maybePromiseResult)) {\n      return chainAndCopyPromiseLike(\n        maybePromiseResult as PromiseLike\u003cAwaited\u003ctypeof maybePromiseResult\u003e\u003e \u0026 Record\u003cstring, unknown\u003e,\n        () =\u003e this._popScope(),\n        () =\u003e this._popScope(),\n      ) as T;\n    }\n\n    this._popScope();\n    return maybePromiseResult;\n  }\n\n  /**\n   * Get the client of the stack.\n   */\n  public getClient\u003cC extends Client\u003e(): C | undefined {\n    return this.getStackTop().client as C;\n  }\n\n  /**\n   * Returns the scope of the top stack.\n   */\n  public getScope(): Scope {\n    return this.getStackTop().scope;\n  }\n\n  /**\n   * Get the isolation scope for the stack.\n   */\n  public getIsolationScope(): Scope {\n    return this._isolationScope;\n  }\n\n  /**\n   * Returns the topmost scope layer in the order domain \u003e local \u003e process.\n   */\n  public getStackTop(): Layer {\n    return this._stack[this._stack.length - 1] as Layer;\n  }\n\n  /**\n   * Push a scope to the stack.\n   */\n  private _pushScope(): Scope {\n    // We want to clone the content of prev scope\n    const scope = this.getScope().clone();\n    this._stack.push({\n      client: this.getClient(),\n      scope,\n    });\n    return scope;\n  }\n\n  /**\n   * Pop a scope from the stack.\n   */\n  private _popScope(): boolean {\n    if (this._stack.length \u003c= 1) return false;\n    return !!this._stack.pop();\n  }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack(): AsyncContextStack {\n  const registry = getMainCarrier();\n  const sentry = getSentryCarrier(registry);\n\n  return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope\u003cT\u003e(callback: (scope: Scope) =\u003e T): T {\n  return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope\u003cT\u003e(scope: Scope, callback: (scope: Scope) =\u003e T): T {\n  const stack = getAsyncContextStack();\n  return stack.withScope(() =\u003e {\n    stack.getStackTop().scope = scope;\n    return callback(scope);\n  });\n}\n\nfunction withIsolationScope\u003cT\u003e(callback: (isolationScope: Scope) =\u003e T): T {\n  return getAsyncContextStack().withScope(() =\u003e {\n    return callback(getAsyncContextStack().getIsolationScope());\n  });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nexport function getStackAsyncContextStrategy(): AsyncContextStrategy {\n  return {\n    withIsolationScope,\n    withScope,\n    withSetScope,\n    withSetIsolationScope: \u003cT\u003e(_isolationScope: Scope, callback: (isolationScope: Scope) =\u003e T) =\u003e {\n      return withIsolationScope(callback);\n    },\n    getCurrentScope: () =\u003e getAsyncContextStack().getScope(),\n    getIsolationScope: () =\u003e getAsyncContextStack().getIsolationScope(),\n  };\n}\n","import type { Carrier } from './../carrier';\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport { getStackAsyncContextStrategy } from './stackStrategy';\nimport type { AsyncContextStrategy } from './types';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n  // Get main carrier (global for every environment)\n  const registry = getMainCarrier();\n  const sentry = getSentryCarrier(registry);\n  sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nexport function getAsyncContextStrategy(carrier: Carrier): AsyncContextStrategy {\n  const sentry = getSentryCarrier(carrier);\n\n  if (sentry.acs) {\n    return sentry.acs;\n  }\n\n  // Otherwise, use the default one (stack)\n  return getStackAsyncContextStrategy();\n}\n","import { getAsyncContextStrategy } from './asyncContext';\nimport { getGlobalSingleton, getMainCarrier } from './carrier';\nimport type { Client } from './client';\nimport { Scope } from './scope';\nimport type { TraceContext } from './types-hoist/context';\nimport { generateSpanId } from './utils/propagationContext';\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current execution context.\n */\nexport function getIsolationScope(): Scope {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): Scope {\n  return getGlobalSingleton('globalScope', () =\u003e new Scope());\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n */\nexport function withScope\u003cT\u003e(callback: (scope: Scope) =\u003e T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope\u003cT\u003e(scope: Scope | undefined, callback: (scope: Scope) =\u003e T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope\u003cT\u003e(\n  ...rest: [callback: (scope: Scope) =\u003e T] | [scope: Scope | undefined, callback: (scope: Scope) =\u003e T]\n): T {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n\n  // If a scope is defined, we want to make this the active scope instead of the default one\n  if (rest.length === 2) {\n    const [scope, callback] = rest;\n\n    if (!scope) {\n      return acs.withScope(callback);\n    }\n\n    return acs.withSetScope(scope, callback);\n  }\n\n  return acs.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n */\nexport function withIsolationScope\u003cT\u003e(callback: (isolationScope: Scope) =\u003e T): T;\n/**\n * Set the provided isolation scope as active in the given callback. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * If you pass in `undefined` as a scope, it will fork a new isolation scope, the same as if no scope is passed.\n */\nexport function withIsolationScope\u003cT\u003e(isolationScope: Scope | undefined, callback: (isolationScope: Scope) =\u003e T): T;\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nexport function withIsolationScope\u003cT\u003e(\n  ...rest:\n    | [callback: (isolationScope: Scope) =\u003e T]\n    | [isolationScope: Scope | undefined, callback: (isolationScope: Scope) =\u003e T]\n): T {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n\n  // If a scope is defined, we want to make this the active scope instead of the default one\n  if (rest.length === 2) {\n    const [isolationScope, callback] = rest;\n\n    if (!isolationScope) {\n      return acs.withIsolationScope(callback);\n    }\n\n    return acs.withSetIsolationScope(isolationScope, callback);\n  }\n\n  return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient\u003cC extends Client\u003e(): C | undefined {\n  return getCurrentScope().getClient\u003cC\u003e();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nexport function getTraceContextFromScope(scope: Scope): TraceContext {\n  const propagationContext = scope.getPropagationContext();\n\n  const { traceId, parentSpanId, propagationSpanId } = propagationContext;\n\n  const traceContext: TraceContext = {\n    trace_id: traceId,\n    span_id: propagationSpanId || generateSpanId(),\n  };\n\n  if (parentSpanId) {\n    traceContext.parent_span_id = parentSpanId;\n  }\n\n  return traceContext;\n}\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Attributes that holds the sample rate that was locally applied to a span.\n * If this attribute is not defined, it means that the span inherited a sampling decision.\n *\n * NOTE: Is only defined on root spans.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Attribute holding the sample rate of the previous trace.\n * This is used to sample consistently across subsequent traces in the browser SDK.\n *\n * Note: Only defined on root spans, if opted into consistent sampling\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = 'sentry.previous_trace_sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/** The reason why an idle span finished. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';\n\n/** The unit of a measurement, which may be stored as a TimedEvent. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value';\n\n/**\n * A custom span name set by users guaranteed to be taken over any automatically\n * inferred name. This attribute is removed before the span is sent.\n *\n * @internal only meant for internal SDK usage\n * @hidden\n */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = 'sentry.custom_span_name';\n\n/**\n * The id of the profile that this span occurred in.\n */\nexport const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nexport const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nexport const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nexport const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nexport const SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\n/**\n * A span link attribute to mark the link as a special span link.\n *\n * Known values:\n * - `previous_trace`: The span links to the frontend root span of the previous trace.\n * - `next_trace`: The span links to the frontend root span of the next trace. (Not set by the SDK)\n *\n * Other values may be set as appropriate.\n * @see https://develop.sentry.dev/sdk/telemetry/traces/span-links/#link-types\n */\nexport const SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = 'sentry.link.type';\n\n/**\n * =============================================================================\n * GEN AI ATTRIBUTES\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n * =============================================================================\n */\n\n/**\n * The conversation ID for linking messages across API calls.\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n","import type { Span } from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\n\nexport const SPAN_STATUS_UNSET = 0;\nexport const SPAN_STATUS_OK = 1;\nexport const SPAN_STATUS_ERROR = 2;\n\n/**\n * Converts a HTTP status code into a sentry status with a message.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or internal_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nexport function getSpanStatusFromHttpCode(httpStatus: number): SpanStatus {\n  if (httpStatus \u003c 400 \u0026\u0026 httpStatus \u003e= 100) {\n    return { code: SPAN_STATUS_OK };\n  }\n\n  if (httpStatus \u003e= 400 \u0026\u0026 httpStatus \u003c 500) {\n    switch (httpStatus) {\n      case 401:\n        return { code: SPAN_STATUS_ERROR, message: 'unauthenticated' };\n      case 403:\n        return { code: SPAN_STATUS_ERROR, message: 'permission_denied' };\n      case 404:\n        return { code: SPAN_STATUS_ERROR, message: 'not_found' };\n      case 409:\n        return { code: SPAN_STATUS_ERROR, message: 'already_exists' };\n      case 413:\n        return { code: SPAN_STATUS_ERROR, message: 'failed_precondition' };\n      case 429:\n        return { code: SPAN_STATUS_ERROR, message: 'resource_exhausted' };\n      case 499:\n        return { code: SPAN_STATUS_ERROR, message: 'cancelled' };\n      default:\n        return { code: SPAN_STATUS_ERROR, message: 'invalid_argument' };\n    }\n  }\n\n  if (httpStatus \u003e= 500 \u0026\u0026 httpStatus \u003c 600) {\n    switch (httpStatus) {\n      case 501:\n        return { code: SPAN_STATUS_ERROR, message: 'unimplemented' };\n      case 503:\n        return { code: SPAN_STATUS_ERROR, message: 'unavailable' };\n      case 504:\n        return { code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' };\n      default:\n        return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n    }\n  }\n\n  return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n}\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nexport function setHttpStatus(span: Span, httpStatus: number): void {\n  span.setAttribute('http.response.status_code', httpStatus);\n\n  const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n  if (spanStatus.message !== 'unknown_error') {\n    span.setStatus(spanStatus);\n  }\n}\n","import type { Scope } from '../scope';\nimport type { Span } from '../types-hoist/span';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\ntype ScopeWeakRef = { deref(): Scope | undefined } | Scope;\n\ntype SpanWithScopes = Span \u0026 {\n  [SCOPE_ON_START_SPAN_FIELD]?: Scope;\n  [ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: ScopeWeakRef;\n};\n\n/** Wrap a scope with a WeakRef if available, falling back to a direct scope. */\nfunction wrapScopeWithWeakRef(scope: Scope): ScopeWeakRef {\n  try {\n    // @ts-expect-error - WeakRef is not available in all environments\n    const WeakRefClass = GLOBAL_OBJ.WeakRef;\n    if (typeof WeakRefClass === 'function') {\n      return new WeakRefClass(scope);\n    }\n  } catch {\n    // WeakRef not available or failed to create\n    // We'll fall back to a direct scope\n  }\n\n  return scope;\n}\n\n/** Try to unwrap a scope from a potential WeakRef wrapper. */\nfunction unwrapScopeFromWeakRef(scopeRef: ScopeWeakRef | undefined): Scope | undefined {\n  if (!scopeRef) {\n    return undefined;\n  }\n\n  if (typeof scopeRef === 'object' \u0026\u0026 'deref' in scopeRef \u0026\u0026 typeof scopeRef.deref === 'function') {\n    try {\n      return scopeRef.deref();\n    } catch {\n      return undefined;\n    }\n  }\n\n  // Fallback to a direct scope\n  return scopeRef as Scope;\n}\n\n/** Store the scope \u0026 isolation scope for a span, which can the be used when it is finished. */\nexport function setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {\n  if (span) {\n    addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));\n    // We don't wrap the scope with a WeakRef here because webkit aggressively garbage collects\n    // and scopes are not held in memory for long periods of time.\n    addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n  }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n * If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.\n */\nexport function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {\n  const spanWithScopes = span as SpanWithScopes;\n\n  return {\n    scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],\n    isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]),\n  };\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport { debug } from './debug-logger';\nimport { isString } from './is';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n  // Very liberal definition of what any incoming header might look like\n  baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial\u003cDynamicSamplingContext\u003e | undefined {\n  const baggageObject = parseBaggageHeader(baggageHeader);\n\n  if (!baggageObject) {\n    return undefined;\n  }\n\n  // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n  const dynamicSamplingContext = Object.entries(baggageObject).reduce\u003cRecord\u003cstring, string\u003e\u003e((acc, [key, value]) =\u003e {\n    if (key.startsWith(SENTRY_BAGGAGE_KEY_PREFIX)) {\n      const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n      acc[nonPrefixedKey] = value;\n    }\n    return acc;\n  }, {});\n\n  // Only return a dynamic sampling context object if there are keys in it.\n  // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n  if (Object.keys(dynamicSamplingContext).length \u003e 0) {\n    return dynamicSamplingContext as Partial\u003cDynamicSamplingContext\u003e;\n  } else {\n    return undefined;\n  }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n  // this also takes undefined for convenience and bundle size in other places\n  dynamicSamplingContext?: Partial\u003cDynamicSamplingContext\u003e,\n): string | undefined {\n  if (!dynamicSamplingContext) {\n    return undefined;\n  }\n\n  // Prefix all DSC keys with \"sentry-\" and put them into a new object\n  const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce\u003cRecord\u003cstring, string\u003e\u003e(\n    (acc, [dscKey, dscValue]) =\u003e {\n      if (dscValue) {\n        acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n      }\n      return acc;\n    },\n    {},\n  );\n\n  return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Take a baggage header and parse it into an object.\n */\nexport function parseBaggageHeader(\n  baggageHeader: string | string[] | number | null | undefined | boolean,\n): Record\u003cstring, string\u003e | undefined {\n  if (!baggageHeader || (!isString(baggageHeader) \u0026\u0026 !Array.isArray(baggageHeader))) {\n    return undefined;\n  }\n\n  if (Array.isArray(baggageHeader)) {\n    // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n    return baggageHeader.reduce\u003cRecord\u003cstring, string\u003e\u003e((acc, curr) =\u003e {\n      const currBaggageObject = baggageHeaderToObject(curr);\n      Object.entries(currBaggageObject).forEach(([key, value]) =\u003e {\n        acc[key] = value;\n      });\n      return acc;\n    }, {});\n  }\n\n  return baggageHeaderToObject(baggageHeader);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record\u003cstring, string\u003e {\n  return baggageHeader\n    .split(',')\n    .map(baggageEntry =\u003e {\n      const eqIdx = baggageEntry.indexOf('=');\n      if (eqIdx === -1) {\n        // Likely an invalid entry\n        return [];\n      }\n      const key = baggageEntry.slice(0, eqIdx);\n      const value = baggageEntry.slice(eqIdx + 1);\n      return [key, value].map(keyOrValue =\u003e {\n        try {\n          return decodeURIComponent(keyOrValue.trim());\n        } catch {\n          // We ignore errors here, e.g. if the value cannot be URL decoded.\n          // This will then be skipped in the next step\n          return;\n        }\n      });\n    })\n    .reduce\u003cRecord\u003cstring, string\u003e\u003e((acc, [key, value]) =\u003e {\n      if (key \u0026\u0026 value) {\n        acc[key] = value;\n      }\n      return acc;\n    }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nexport function objectToBaggageHeader(object: Record\u003cstring, string\u003e): string | undefined {\n  if (Object.keys(object).length === 0) {\n    // An empty baggage header is not spec compliant: We return undefined.\n    return undefined;\n  }\n\n  return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) =\u003e {\n    const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n    const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n    if (newBaggageHeader.length \u003e MAX_BAGGAGE_STRING_LENGTH) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n        );\n      return baggageHeader;\n    } else {\n      return newBaggageHeader;\n    }\n  }, '');\n}\n","import type { Client } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { DsnComponents, DsnLike, DsnProtocol } from '../types-hoist/dsn';\nimport { consoleSandbox, debug } from './debug-logger';\n\n/** Regular expression used to extract org ID from a DSN host. */\nconst ORG_ID_REGEX = /^o(\\d+)\\./;\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)((?:\\[[:.%\\w]+\\]|[\\w.-]+))(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n  return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n  const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n  return (\n    `${protocol}://${publicKey}${withPassword \u0026\u0026 pass ? `:${pass}` : ''}` +\n    `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n  );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n  const match = DSN_REGEX.exec(str);\n\n  if (!match) {\n    // This should be logged to the console\n    consoleSandbox(() =\u003e {\n      // eslint-disable-next-line no-console\n      console.error(`Invalid Sentry Dsn: ${str}`);\n    });\n    return undefined;\n  }\n\n  const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);\n  let path = '';\n  let projectId = lastPath;\n\n  const split = projectId.split('/');\n  if (split.length \u003e 1) {\n    path = split.slice(0, -1).join('/');\n    projectId = split.pop() as string;\n  }\n\n  if (projectId) {\n    const projectMatch = projectId.match(/^\\d+/);\n    if (projectMatch) {\n      projectId = projectMatch[0];\n    }\n  }\n\n  return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n  return {\n    protocol: components.protocol,\n    publicKey: components.publicKey || '',\n    pass: components.pass || '',\n    host: components.host,\n    port: components.port || '',\n    path: components.path || '',\n    projectId: components.projectId,\n  };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n  if (!DEBUG_BUILD) {\n    return true;\n  }\n\n  const { port, projectId, protocol } = dsn;\n\n  const requiredComponents: ReadonlyArray\u003ckeyof DsnComponents\u003e = ['protocol', 'publicKey', 'host', 'projectId'];\n  const hasMissingRequiredComponent = requiredComponents.find(component =\u003e {\n    if (!dsn[component]) {\n      debug.error(`Invalid Sentry Dsn: ${component} missing`);\n      return true;\n    }\n    return false;\n  });\n\n  if (hasMissingRequiredComponent) {\n    return false;\n  }\n\n  if (!projectId.match(/^\\d+$/)) {\n    debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n    return false;\n  }\n\n  if (!isValidProtocol(protocol)) {\n    debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n    return false;\n  }\n\n  if (port \u0026\u0026 isNaN(parseInt(port, 10))) {\n    debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n    return false;\n  }\n\n  return true;\n}\n\n/**\n * Extract the org ID from a DSN host.\n *\n * @param host The host from a DSN\n * @returns The org ID if found, undefined otherwise\n */\nexport function extractOrgIdFromDsnHost(host: string): string | undefined {\n  const match = host.match(ORG_ID_REGEX);\n\n  return match?.[1];\n}\n\n/**\n *  Returns the organization ID of the client.\n *\n *  The organization ID is extracted from the DSN. If the client options include a `orgId`, this will always take precedence.\n */\nexport function extractOrgIdFromClient(client: Client): string | undefined {\n  const options = client.getOptions();\n\n  const { host } = client.getDsn() || {};\n\n  let org_id: string | undefined;\n\n  if (options.orgId) {\n    org_id = String(options.orgId);\n  } else if (host) {\n    org_id = extractOrgIdFromDsnHost(host);\n  }\n\n  return org_id;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n  const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n  if (!components || !validateDsn(components)) {\n    return undefined;\n  }\n  return components;\n}\n","/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nexport function parseSampleRate(sampleRate: unknown): number | undefined {\n  if (typeof sampleRate === 'boolean') {\n    return Number(sampleRate);\n  }\n\n  const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n  if (typeof rate !== 'number' || isNaN(rate) || rate \u003c 0 || rate \u003e 1) {\n    return undefined;\n  }\n\n  return rate;\n}\n","import type { Client } from '../client';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { PropagationContext } from '../types-hoist/tracing';\nimport type { TraceparentData } from '../types-hoist/transaction';\nimport { debug } from '../utils/debug-logger';\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { extractOrgIdFromClient } from './dsn';\nimport { parseSampleRate } from './parseSampleRate';\nimport { generateSpanId, generateTraceId } from './propagationContext';\nimport { safeMathRandom } from './randomSafeContext';\n\n// oxlint-disable-next-line sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n  '^[ \\\\t]*' + // whitespace\n    '([0-9a-f]{32})?' + // trace_id\n    '-?([0-9a-f]{16})?' + // span_id\n    '-?([01])?' + // sampled\n    '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * This is terrible naming but the function has nothing to do with the W3C traceparent header.\n * It can only parse the `sentry-trace` header and extract the \"trace parent\" data.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n  if (!traceparent) {\n    return undefined;\n  }\n\n  const matches = traceparent.match(TRACEPARENT_REGEXP);\n  if (!matches) {\n    return undefined;\n  }\n\n  let parentSampled: boolean | undefined;\n  if (matches[3] === '1') {\n    parentSampled = true;\n  } else if (matches[3] === '0') {\n    parentSampled = false;\n  }\n\n  return {\n    traceId: matches[1],\n    parentSampled,\n    parentSpanId: matches[2],\n  };\n}\n\n/**\n * Create a propagation context from incoming headers or\n * creates a minimal new one if the headers are undefined.\n */\nexport function propagationContextFromHeaders(\n  sentryTrace: string | undefined,\n  baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n  const traceparentData = extractTraceparentData(sentryTrace);\n  const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n  if (!traceparentData?.traceId) {\n    return {\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom(),\n    };\n  }\n\n  const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);\n\n  // The sample_rand on the DSC needs to be generated based on traceparent + baggage.\n  if (dynamicSamplingContext) {\n    dynamicSamplingContext.sample_rand = sampleRand.toString();\n  }\n\n  const { traceId, parentSpanId, parentSampled } = traceparentData;\n\n  return {\n    traceId,\n    parentSpanId,\n    sampled: parentSampled,\n    dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n    sampleRand,\n  };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n  traceId: string | undefined = generateTraceId(),\n  spanId: string | undefined = generateSpanId(),\n  sampled?: boolean,\n): string {\n  let sampledString = '';\n  if (sampled !== undefined) {\n    sampledString = sampled ? '-1' : '-0';\n  }\n  return `${traceId}-${spanId}${sampledString}`;\n}\n\n/**\n * Creates a W3C traceparent header from the given trace and span ids.\n */\nexport function generateTraceparentHeader(\n  traceId: string | undefined = generateTraceId(),\n  spanId: string | undefined = generateSpanId(),\n  sampled?: boolean,\n): string {\n  return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;\n}\n\n/**\n * Given any combination of an incoming trace, generate a sample rand based on its defined semantics.\n *\n * Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n */\nfunction getSampleRandFromTraceparentAndDsc(\n  traceparentData: TraceparentData | undefined,\n  dsc: Partial\u003cDynamicSamplingContext\u003e | undefined,\n): number {\n  // When there is an incoming sample rand use it.\n  const parsedSampleRand = parseSampleRate(dsc?.sample_rand);\n  if (parsedSampleRand !== undefined) {\n    return parsedSampleRand;\n  }\n\n  // Otherwise, if there is an incoming sampling decision + sample rate, generate a sample rand that would lead to the same sampling decision.\n  const parsedSampleRate = parseSampleRate(dsc?.sample_rate);\n  if (parsedSampleRate \u0026\u0026 traceparentData?.parentSampled !== undefined) {\n    return traceparentData.parentSampled\n      ? // Returns a sample rand with positive sampling decision [0, sampleRate)\n        safeMathRandom() * parsedSampleRate\n      : // Returns a sample rand with negative sampling decision [sampleRate, 1)\n        parsedSampleRate + safeMathRandom() * (1 - parsedSampleRate);\n  } else {\n    // If nothing applies, return a random sample rand.\n    return safeMathRandom();\n  }\n}\n\n/**\n * Determines whether a new trace should be continued based on the provided baggage org ID and the client's `strictTraceContinuation` option.\n * If the trace should not be continued, a new trace will be started.\n *\n * The result is dependent on the `strictTraceContinuation` option in the client.\n * See https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation\n */\nexport function shouldContinueTrace(client: Client, baggageOrgId?: string): boolean {\n  const clientOrgId = extractOrgIdFromClient(client);\n\n  // Case: baggage orgID and Client orgID don't match - always start new trace\n  if (baggageOrgId \u0026\u0026 clientOrgId \u0026\u0026 baggageOrgId !== clientOrgId) {\n    debug.log(\n      `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`,\n    );\n    return false;\n  }\n\n  const strictTraceContinuation = client.getOptions().strictTraceContinuation || false; // default for `strictTraceContinuation` is `false`\n\n  if (strictTraceContinuation) {\n    // With strict continuation enabled, don't continue trace if:\n    // - Baggage has orgID, but Client doesn't have one\n    // - Client has orgID, but baggage doesn't have one\n    if ((baggageOrgId \u0026\u0026 !clientOrgId) || (!baggageOrgId \u0026\u0026 clientOrgId)) {\n      debug.log(\n        `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`,\n      );\n      return false;\n    }\n  }\n\n  return true;\n}\n","import { getAsyncContextStrategy } from '../asyncContext';\nimport { getMainCarrier } from '../carrier';\nimport { getCurrentScope } from '../currentScopes';\nimport {\n  SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n  SEMANTIC_ATTRIBUTE_SENTRY_OP,\n  SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n  SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { SentrySpan } from '../tracing/sentrySpan';\nimport { SPAN_STATUS_OK, SPAN_STATUS_UNSET } from '../tracing/spanstatus';\nimport { getCapturedScopesOnSpan } from '../tracing/utils';\nimport type { TraceContext } from '../types-hoist/context';\nimport type { SpanLink, SpanLinkJSON } from '../types-hoist/link';\nimport type { Span, SpanAttributes, SpanJSON, SpanOrigin, SpanTimeInput } from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { generateSpanId } from '../utils/propagationContext';\nimport { timestampInSeconds } from '../utils/time';\nimport { generateSentryTraceHeader, generateTraceparentHeader } from '../utils/tracing';\nimport { consoleSandbox } from './debug-logger';\nimport { _getSpanForScope } from './spanOnScope';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\nlet hasShownSpanDropWarning = false;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id \u0026 parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status \u0026 origin.\n */\nexport function spanToTransactionTraceContext(span: Span): TraceContext {\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n  const { data, op, parent_span_id, status, origin, links } = spanToJSON(span);\n\n  return {\n    parent_span_id,\n    span_id,\n    trace_id,\n    data,\n    op,\n    status,\n    origin,\n    links,\n  };\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n  const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n\n  // If the span is remote, we use a random/virtual span as span_id to the trace context,\n  // and the remote span as parent_span_id\n  const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n  const scope = getCapturedScopesOnSpan(span).scope;\n\n  const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;\n\n  return {\n    parent_span_id,\n    span_id,\n    trace_id,\n  };\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n  const { traceId, spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a Span to a W3C traceparent header.\n */\nexport function spanToTraceparentHeader(span: Span): string {\n  const { traceId, spanId } = span.spanContext();\n  const sampled = spanIsSampled(span);\n  return generateTraceparentHeader(traceId, spanId, sampled);\n}\n\n/**\n *  Converts the span links array to a flattened version to be sent within an envelope.\n *\n *  If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.\n */\nexport function convertSpanLinksForEnvelope(links?: SpanLink[]): SpanLinkJSON[] | undefined {\n  if (links \u0026\u0026 links.length \u003e 0) {\n    return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) =\u003e ({\n      span_id: spanId,\n      trace_id: traceId,\n      sampled: traceFlags === TRACE_FLAG_SAMPLED,\n      attributes,\n      ...restContext,\n    }));\n  } else {\n    return undefined;\n  }\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n  if (typeof input === 'number') {\n    return ensureTimestampInSeconds(input);\n  }\n\n  if (Array.isArray(input)) {\n    // See {@link HrTime} for the array-based time format\n    return input[0] + input[1] / 1e9;\n  }\n\n  if (input instanceof Date) {\n    return ensureTimestampInSeconds(input.getTime());\n  }\n\n  return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n  const isMs = timestamp \u003e 9999999999;\n  return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n */\n// Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n// This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n// And `spanToJSON` needs the Span class from `span.ts` to check here.\nexport function spanToJSON(span: Span): SpanJSON {\n  if (spanIsSentrySpan(span)) {\n    return span.getSpanJSON();\n  }\n\n  const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n  // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n  if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n    const { attributes, startTime, name, endTime, status, links } = span;\n\n    // In preparation for the next major of OpenTelemetry, we want to support\n    // looking up the parent span id according to the new API\n    // In OTel v1, the parent span id is accessed as `parentSpanId`\n    // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`\n    const parentSpanId =\n      'parentSpanId' in span\n        ? span.parentSpanId\n        : 'parentSpanContext' in span\n          ? (span.parentSpanContext as { spanId?: string } | undefined)?.spanId\n          : undefined;\n\n    return {\n      span_id,\n      trace_id,\n      data: attributes,\n      description: name,\n      parent_span_id: parentSpanId,\n      start_timestamp: spanTimeInputToSeconds(startTime),\n      // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n      timestamp: spanTimeInputToSeconds(endTime) || undefined,\n      status: getStatusMessage(status),\n      op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n      origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n      links: convertSpanLinksForEnvelope(links),\n    };\n  }\n\n  // Finally, at least we have `spanContext()`....\n  // This should not actually happen in reality, but we need to handle it for type safety.\n  return {\n    span_id,\n    trace_id,\n    start_timestamp: 0,\n    data: {},\n  };\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span: Span): span is OpenTelemetrySdkTraceBaseSpan {\n  const castSpan = span as Partial\u003cOpenTelemetrySdkTraceBaseSpan\u003e;\n  return !!castSpan.attributes \u0026\u0026 !!castSpan.startTime \u0026\u0026 !!castSpan.name \u0026\u0026 !!castSpan.endTime \u0026\u0026 !!castSpan.status;\n}\n\n/** Exported only for tests. */\nexport interface OpenTelemetrySdkTraceBaseSpan extends Span {\n  attributes: SpanAttributes;\n  startTime: SpanTimeInput;\n  name: string;\n  status: SpanStatus;\n  endTime: SpanTimeInput;\n  parentSpanId?: string;\n  links?: SpanLink[];\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSentrySpan(span: Span): span is SentrySpan {\n  return typeof (span as SentrySpan).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n  // We align our trace flags with the ones OpenTelemetry use\n  // So we also check for sampled the same way they do.\n  const { traceFlags } = span.spanContext();\n  return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nexport function getStatusMessage(status: SpanStatus | undefined): string | undefined {\n  if (!status || status.code === SPAN_STATUS_UNSET) {\n    return undefined;\n  }\n\n  if (status.code === SPAN_STATUS_OK) {\n    return 'ok';\n  }\n\n  return status.message || 'internal_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\ntype SpanWithPotentialChildren = Span \u0026 {\n  [CHILD_SPANS_FIELD]?: Set\u003cSpan\u003e;\n  [ROOT_SPAN_FIELD]?: Span;\n};\n\n/**\n * Adds an opaque child span reference to a span.\n */\nexport function addChildSpanToSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n  // We store the root span reference on the child span\n  // We need this for `getRootSpan()` to work\n  const rootSpan = span[ROOT_SPAN_FIELD] || span;\n  addNonEnumerableProperty(childSpan as SpanWithPotentialChildren, ROOT_SPAN_FIELD, rootSpan);\n\n  // We store a list of child spans on the parent span\n  // We need this for `getSpanDescendants()` to work\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].add(childSpan);\n  } else {\n    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n  }\n}\n\n/** This is only used internally by Idle Spans. */\nexport function removeChildSpanFromSpan(span: SpanWithPotentialChildren, childSpan: Span): void {\n  if (span[CHILD_SPANS_FIELD]) {\n    span[CHILD_SPANS_FIELD].delete(childSpan);\n  }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nexport function getSpanDescendants(span: SpanWithPotentialChildren): Span[] {\n  const resultSet = new Set\u003cSpan\u003e();\n\n  function addSpanChildren(span: SpanWithPotentialChildren): void {\n    // This exit condition is required to not infinitely loop in case of a circular dependency.\n    if (resultSet.has(span)) {\n      return;\n      // We want to ignore unsampled spans (e.g. non recording spans)\n    } else if (spanIsSampled(span)) {\n      resultSet.add(span);\n      const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n      for (const childSpan of childSpans) {\n        addSpanChildren(childSpan);\n      }\n    }\n  }\n\n  addSpanChildren(span);\n\n  return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nexport function getRootSpan(span: SpanWithPotentialChildren): Span {\n  return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.getActiveSpan) {\n    return acs.getActiveSpan();\n  }\n\n  return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n */\nexport function showSpanDropWarning(): void {\n  if (!hasShownSpanDropWarning) {\n    consoleSandbox(() =\u003e {\n      // eslint-disable-next-line no-console\n      console.warn(\n        '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.',\n      );\n    });\n    hasShownSpanDropWarning = true;\n  }\n}\n\n/**\n * Updates the name of the given span and ensures that the span name is not\n * overwritten by the Sentry SDK.\n *\n * Use this function instead of `span.updateName()` if you want to make sure that\n * your name is kept. For some spans, for example root `http.server` spans the\n * Sentry SDK would otherwise overwrite the span name with a high-quality name\n * it infers when the span ends.\n *\n * Use this function in server code or when your span is started on the server\n * and on the client (browser). If you only update a span name on the client,\n * you can also use `span.updateName()` the SDK does not overwrite the name.\n *\n * @param span - The span to update the name of.\n * @param name - The name to set on the span.\n */\nexport function updateSpanName(span: Span, name: string): void {\n  span.updateName(name);\n  span.setAttributes({\n    [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n    [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name,\n  });\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { addGlobalErrorInstrumentationHandler } from '../instrument/globalError';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from '../instrument/globalUnhandledRejection';\nimport { debug } from '../utils/debug-logger';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils';\nimport { SPAN_STATUS_ERROR } from './spanstatus';\n\nlet errorsInstrumented = false;\n\n/**  Only exposed for testing */\nexport function _resetErrorsInstrumented(): void {\n  errorsInstrumented = false;\n}\n\n/**\n * Ensure that global errors automatically set the active span status.\n */\nexport function registerSpanErrorInstrumentation(): void {\n  if (errorsInstrumented) {\n    return;\n  }\n\n  /**\n   * If an error or unhandled promise occurs, we mark the active root span as failed\n   */\n  function errorCallback(): void {\n    const activeSpan = getActiveSpan();\n    const rootSpan = activeSpan \u0026\u0026 getRootSpan(activeSpan);\n    if (rootSpan) {\n      const message = 'internal_error';\n      DEBUG_BUILD \u0026\u0026 debug.log(`[Tracing] Root span: ${message} -\u003e Global error occurred`);\n      rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message });\n    }\n  }\n\n  // The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n  // node.js default exit behaviour\n  errorCallback.tag = 'sentry_tracingErrorCallback';\n\n  errorsInstrumented = true;\n  addGlobalErrorInstrumentationHandler(errorCallback);\n  addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n","import { getClient } from '../currentScopes';\nimport type { CoreOptions } from '../types-hoist/options';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if span recording is currently enabled.\n *\n * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`\n * is defined in the SDK config. This function does not make any assumption about\n * sampling decisions, it only checks if the SDK is configured to record spans.\n *\n * Important: This function only determines if span recording is enabled. Trace\n * continuation and propagation is separately controlled and not covered by this function.\n * If this function returns `false`, traces can still be propagated (which is what\n * we refer to by \"Tracing without Performance\")\n * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/\n *\n * @param maybeOptions An SDK options object to be passed to this function.\n * If this option is not provided, the function will use the current client's options.\n */\nexport function hasSpansEnabled(\n  maybeOptions?: Pick\u003cCoreOptions, 'tracesSampleRate' | 'tracesSampler'\u003e | undefined,\n): boolean {\n  if (typeof __SENTRY_TRACING__ === 'boolean' \u0026\u0026 !__SENTRY_TRACING__) {\n    return false;\n  }\n\n  const options = maybeOptions || getClient()?.getOptions();\n  return (\n    !!options \u0026\u0026\n    // Note: This check is `!= null`, meaning \"nullish\". `0` is not \"nullish\", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)\n    (options.tracesSampleRate != null || !!options.tracesSampler)\n  );\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { debug } from './debug-logger';\nimport { isMatchingPattern } from './string';\n\nfunction logIgnoredSpan(droppedSpan: Pick\u003cSpanJSON, 'description' | 'op'\u003e): void {\n  debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \\`ignoreSpans\\`.`);\n}\n\n/**\n * Check if a span should be ignored based on the ignoreSpans configuration.\n */\nexport function shouldIgnoreSpan(\n  span: Pick\u003cSpanJSON, 'description' | 'op'\u003e,\n  ignoreSpans: Required\u003cClientOptions\u003e['ignoreSpans'],\n): boolean {\n  if (!ignoreSpans?.length || !span.description) {\n    return false;\n  }\n\n  for (const pattern of ignoreSpans) {\n    if (isStringOrRegExp(pattern)) {\n      if (isMatchingPattern(span.description, pattern)) {\n        DEBUG_BUILD \u0026\u0026 logIgnoredSpan(span);\n        return true;\n      }\n      continue;\n    }\n\n    if (!pattern.name \u0026\u0026 !pattern.op) {\n      continue;\n    }\n\n    const nameMatches = pattern.name ? isMatchingPattern(span.description, pattern.name) : true;\n    const opMatches = pattern.op ? span.op \u0026\u0026 isMatchingPattern(span.op, pattern.op) : true;\n\n    // This check here is only correct because we can guarantee that we ran `isMatchingPattern`\n    // for at least one of `nameMatches` and `opMatches`. So in contrary to how this looks,\n    // not both op and name actually have to match. This is the most efficient way to check\n    // for all combinations of name and op patterns.\n    if (nameMatches \u0026\u0026 opMatches) {\n      DEBUG_BUILD \u0026\u0026 logIgnoredSpan(span);\n      return true;\n    }\n  }\n\n  return false;\n}\n\n/**\n * Takes a list of spans, and a span that was dropped, and re-parents the child spans of the dropped span to the parent of the dropped span, if possible.\n * This mutates the spans array in place!\n */\nexport function reparentChildSpans(spans: SpanJSON[], dropSpan: SpanJSON): void {\n  const droppedSpanParentId = dropSpan.parent_span_id;\n  const droppedSpanId = dropSpan.span_id;\n\n  // This should generally not happen, as we do not apply this on root spans\n  // but to be safe, we just bail in this case\n  if (!droppedSpanParentId) {\n    return;\n  }\n\n  for (const span of spans) {\n    if (span.parent_span_id === droppedSpanId) {\n      span.parent_span_id = droppedSpanParentId;\n    }\n  }\n}\n\nfunction isStringOrRegExp(value: unknown): value is string | RegExp {\n  return typeof value === 'string' || value instanceof RegExp;\n}\n","export const DEFAULT_ENVIRONMENT = 'production';\nexport const DEV_ENVIRONMENT = 'development';\n","import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient } from '../currentScopes';\nimport type { Scope } from '../scope';\nimport {\n  SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n  SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n  SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage';\nimport { extractOrgIdFromClient } from '../utils/dsn';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\nimport { getCapturedScopesOnSpan } from './utils';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\ntype SpanWithMaybeDsc = Span \u0026 {\n  [FROZEN_DSC_FIELD]?: Partial\u003cDynamicSamplingContext\u003e | undefined;\n};\n\n/**\n * Freeze the given DSC on the given span.\n */\nexport function freezeDscOnSpan(span: Span, dsc: Partial\u003cDynamicSamplingContext\u003e): void {\n  const spanWithMaybeDsc = span as SpanWithMaybeDsc;\n  addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(trace_id: string, client: Client): DynamicSamplingContext {\n  const options = client.getOptions();\n\n  const { publicKey: public_key } = client.getDsn() || {};\n\n  // Instead of conditionally adding non-undefined values, we add them and then remove them if needed\n  // otherwise, the order of baggage entries changes, which \"breaks\" a bunch of tests etc.\n  const dsc: DynamicSamplingContext = {\n    environment: options.environment || DEFAULT_ENVIRONMENT,\n    release: options.release,\n    public_key,\n    trace_id,\n    org_id: extractOrgIdFromClient(client),\n  };\n\n  client.emit('createDsc', dsc);\n\n  return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nexport function getDynamicSamplingContextFromScope(client: Client, scope: Scope): Partial\u003cDynamicSamplingContext\u003e {\n  const propagationContext = scope.getPropagationContext();\n  return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly\u003cPartial\u003cDynamicSamplingContext\u003e\u003e {\n  const client = getClient();\n  if (!client) {\n    return {};\n  }\n\n  const rootSpan = getRootSpan(span);\n  const rootSpanJson = spanToJSON(rootSpan);\n  const rootSpanAttributes = rootSpanJson.data;\n  const traceState = rootSpan.spanContext().traceState;\n\n  // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n  // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n  const rootSpanSampleRate =\n    traceState?.get('sentry.sample_rate') ??\n    rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??\n    rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n\n  function applyLocalSampleRateToDsc(dsc: Partial\u003cDynamicSamplingContext\u003e): Partial\u003cDynamicSamplingContext\u003e {\n    if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n      dsc.sample_rate = `${rootSpanSampleRate}`;\n    }\n    return dsc;\n  }\n\n  // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n  const frozenDsc = (rootSpan as SpanWithMaybeDsc)[FROZEN_DSC_FIELD];\n  if (frozenDsc) {\n    return applyLocalSampleRateToDsc(frozenDsc);\n  }\n\n  // For OpenTelemetry, we freeze the DSC on the trace state\n  const traceStateDsc = traceState?.get('sentry.dsc');\n\n  // If the span has a DSC, we want it to take precedence\n  const dscOnTraceState = traceStateDsc \u0026\u0026 baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n  if (dscOnTraceState) {\n    return applyLocalSampleRateToDsc(dscOnTraceState);\n  }\n\n  // Else, we generate it from the span\n  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n\n  // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n  const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n  // after JSON conversion, txn.name becomes jsonSpan.description\n  const name = rootSpanJson.description;\n  if (source !== 'url' \u0026\u0026 name) {\n    dsc.transaction = name;\n  }\n\n  // How can we even land here with hasSpansEnabled() returning false?\n  // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n  // So we end up with an active span that is not sampled (neither positively nor negatively)\n  if (hasSpansEnabled()) {\n    dsc.sampled = String(spanIsSampled(rootSpan));\n    dsc.sample_rand =\n      // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n      // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n      traceState?.get('sentry.sample_rand') ??\n      // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n      getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n  }\n\n  applyLocalSampleRateToDsc(dsc);\n\n  client.emit('createDsc', dsc, rootSpan);\n\n  return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nexport function spanToBaggageHeader(span: Span): string | undefined {\n  const dsc = getDynamicSamplingContextFromSpan(span);\n  return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n","import type {\n  SentrySpanArguments,\n  Span,\n  SpanAttributes,\n  SpanAttributeValue,\n  SpanContextData,\n  SpanTimeInput,\n} from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport { generateSpanId, generateTraceId } from '../utils/propagationContext';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils';\n\n/**\n * A Sentry Span that is non-recording, meaning it will not be sent to Sentry.\n */\nexport class SentryNonRecordingSpan implements Span {\n  private _traceId: string;\n  private _spanId: string;\n\n  public constructor(spanContext: SentrySpanArguments = {}) {\n    this._traceId = spanContext.traceId || generateTraceId();\n    this._spanId = spanContext.spanId || generateSpanId();\n  }\n\n  /** @inheritdoc */\n  public spanContext(): SpanContextData {\n    return {\n      spanId: this._spanId,\n      traceId: this._traceId,\n      traceFlags: TRACE_FLAG_NONE,\n    };\n  }\n\n  /** @inheritdoc */\n  public end(_timestamp?: SpanTimeInput): void {}\n\n  /** @inheritdoc */\n  public setAttribute(_key: string, _value: SpanAttributeValue | undefined): this {\n    return this;\n  }\n\n  /** @inheritdoc */\n  public setAttributes(_values: SpanAttributes): this {\n    return this;\n  }\n\n  /** @inheritdoc */\n  public setStatus(_status: SpanStatus): this {\n    return this;\n  }\n\n  /** @inheritdoc */\n  public updateName(_name: string): this {\n    return this;\n  }\n\n  /** @inheritdoc */\n  public isRecording(): boolean {\n    return false;\n  }\n\n  /** @inheritdoc */\n  public addEvent(\n    _name: string,\n    _attributesOrStartTime?: SpanAttributes | SpanTimeInput,\n    _startTime?: SpanTimeInput,\n  ): this {\n    return this;\n  }\n\n  /** @inheritDoc */\n  public addLink(_link: unknown): this {\n    return this;\n  }\n\n  /** @inheritDoc */\n  public addLinks(_links: unknown[]): this {\n    return this;\n  }\n\n  /**\n   * This should generally not be used,\n   * but we need it for being compliant with the OTEL Span interface.\n   *\n   * @hidden\n   * @internal\n   */\n  public recordException(_exception: unknown, _time?: number | undefined): void {\n    // noop\n  }\n}\n","import type { Primitive } from '../types-hoist/misc';\nimport { isSyntheticEvent, isVueViewModel } from './is';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName, getVueInternalName } from './stacktrace';\n\ntype Prototype = { constructor?: (...args: unknown[]) =\u003e unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray\u003cT\u003e = { [key: string]: T };\n\ntype MemoFunc = [\n  // memoize\n  (obj: object) =\u003e boolean,\n  // unmemoize\n  (obj: object) =\u003e void,\n];\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normalized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n  try {\n    // since we're at the outermost level, we don't provide a key\n    return visit('', input, depth, maxProperties);\n  } catch (err) {\n    return { ERROR: `**non-serializable** (${err})` };\n  }\n}\n\n/** JSDoc */\nexport function normalizeToSize\u003cT\u003e(\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  object: { [key: string]: any },\n  // Default Node.js REPL depth\n  depth: number = 3,\n  // 100kB, as 200kB is max payload size, so half sounds reasonable\n  maxSize: number = 100 * 1024,\n): T {\n  const normalized = normalize(object, depth);\n\n  if (jsonSize(normalized) \u003e maxSize) {\n    return normalizeToSize(object, depth - 1, maxSize);\n  }\n\n  return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n  key: string,\n  value: unknown,\n  depth: number = +Infinity,\n  maxProperties: number = +Infinity,\n  memo = memoBuilder(),\n): Primitive | ObjOrArray\u003cunknown\u003e {\n  const [memoize, unmemoize] = memo;\n\n  // Get the simple cases out of the way first\n  if (\n    value == null || // this matches null and undefined -\u003e eqeq not eqeqeq\n    ['boolean', 'string'].includes(typeof value) ||\n    (typeof value === 'number' \u0026\u0026 Number.isFinite(value))\n  ) {\n    return value as Primitive;\n  }\n\n  const stringified = stringifyValue(key, value);\n\n  // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n  // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n  if (!stringified.startsWith('[object ')) {\n    return stringified;\n  }\n\n  // From here on, we can assert that `value` is either an object or an array.\n\n  // Do not normalize objects that we know have already been normalized. As a general rule, the\n  // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n  // have already been normalized.\n  if ((value as ObjOrArray\u003cunknown\u003e)['__sentry_skip_normalization__']) {\n    return value as ObjOrArray\u003cunknown\u003e;\n  }\n\n  // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n  // We keep a certain amount of depth.\n  // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n  const remainingDepth =\n    typeof (value as ObjOrArray\u003cunknown\u003e)['__sentry_override_normalization_depth__'] === 'number'\n      ? ((value as ObjOrArray\u003cunknown\u003e)['__sentry_override_normalization_depth__'] as number)\n      : depth;\n\n  // We're also done if we've reached the max depth\n  if (remainingDepth === 0) {\n    // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n    return stringified.replace('object ', '');\n  }\n\n  // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n  if (memoize(value)) {\n    return '[Circular ~]';\n  }\n\n  // If the value has a `toJSON` method, we call it to extract more information\n  const valueWithToJSON = value as unknown \u0026 { toJSON?: () =\u003e unknown };\n  if (valueWithToJSON \u0026\u0026 typeof valueWithToJSON.toJSON === 'function') {\n    try {\n      const jsonValue = valueWithToJSON.toJSON();\n      // We need to normalize the return value of `.toJSON()` in case it has circular references\n      return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n    } catch {\n      // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n    }\n  }\n\n  // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n  // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n  // property/entry, and keep track of the number of items we add to it.\n  const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray\u003cunknown\u003e;\n  let numAdded = 0;\n\n  // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n  // properties are non-enumerable and otherwise would get missed.\n  const visitable = convertToPlainObject(value as ObjOrArray\u003cunknown\u003e);\n\n  for (const visitKey in visitable) {\n    // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n    if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n      continue;\n    }\n\n    if (numAdded \u003e= maxProperties) {\n      normalized[visitKey] = '[MaxProperties ~]';\n      break;\n    }\n\n    // Recursively visit all the child nodes\n    const visitValue = visitable[visitKey];\n    normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n    numAdded++;\n  }\n\n  // Once we've visited all the branches, remove the parent from memo storage\n  unmemoize(value);\n\n  // Return accumulated values\n  return normalized;\n}\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n  key: unknown,\n  // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n  // our internal use, it'll do\n  value: Exclude\u003cunknown, string | number | boolean | null\u003e,\n): string {\n  try {\n    if (key === 'domain' \u0026\u0026 value \u0026\u0026 typeof value === 'object' \u0026\u0026 (value as { _events: unknown })._events) {\n      return '[Domain]';\n    }\n\n    if (key === 'domainEmitter') {\n      return '[DomainEmitter]';\n    }\n\n    // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n    // which won't throw if they are not present.\n\n    if (typeof global !== 'undefined' \u0026\u0026 value === global) {\n      return '[Global]';\n    }\n\n    // eslint-disable-next-line no-restricted-globals\n    if (typeof window !== 'undefined' \u0026\u0026 value === window) {\n      return '[Window]';\n    }\n\n    // eslint-disable-next-line no-restricted-globals\n    if (typeof document !== 'undefined' \u0026\u0026 value === document) {\n      return '[Document]';\n    }\n\n    if (isVueViewModel(value)) {\n      return getVueInternalName(value);\n    }\n\n    // React's SyntheticEvent thingy\n    if (isSyntheticEvent(value)) {\n      return '[SyntheticEvent]';\n    }\n\n    if (typeof value === 'number' \u0026\u0026 !Number.isFinite(value)) {\n      return `[${value}]`;\n    }\n\n    if (typeof value === 'function') {\n      return `[Function: ${getFunctionName(value)}]`;\n    }\n\n    if (typeof value === 'symbol') {\n      return `[${String(value)}]`;\n    }\n\n    // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n    if (typeof value === 'bigint') {\n      return `[BigInt: ${String(value)}]`;\n    }\n\n    // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n    // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n    // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n    // we can make sure that only plain objects come out that way.\n    const objName = getConstructorName(value);\n\n    // Handle HTML Elements\n    if (/^HTML(\\w*)Element$/.test(objName)) {\n      return `[HTMLElement: ${objName}]`;\n    }\n\n    return `[object ${objName}]`;\n  } catch (err) {\n    return `**non-serializable** (${err})`;\n  }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n  const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n  return prototype?.constructor ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n  // eslint-disable-next-line no-bitwise\n  return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n  return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n  const escapedBase = basePath\n    // Backslash to forward\n    .replace(/\\\\/g, '/')\n    // Escape RegExp special characters\n    .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$\u0026');\n\n  let newUrl = url;\n  try {\n    newUrl = decodeURI(url);\n  } catch {\n    // Sometime this breaks\n  }\n  return (\n    newUrl\n      .replace(/\\\\/g, '/')\n      .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n      // oxlint-disable-next-line sdk/no-regexp-constructor\n      .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n  );\n}\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder(): MemoFunc {\n  const inner = new WeakSet\u003cobject\u003e();\n  function memoize(obj: object): boolean {\n    if (inner.has(obj)) {\n      return true;\n    }\n    inner.add(obj);\n    return false;\n  }\n\n  function unmemoize(obj: object): void {\n    inner.delete(obj);\n  }\n  return [memoize, unmemoize];\n}\n","import { getSentryCarrier } from '../carrier';\nimport type { Attachment } from '../types-hoist/attachment';\nimport type { DataCategory } from '../types-hoist/datacategory';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport type {\n  AttachmentItem,\n  BaseEnvelopeHeaders,\n  BaseEnvelopeItemHeaders,\n  Envelope,\n  EnvelopeItemType,\n  EventEnvelopeHeaders,\n  SpanItem,\n} from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { SdkInfo } from '../types-hoist/sdkinfo';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope\u003cE extends Envelope\u003e(headers: E[0], items: E[1] = []): E {\n  return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope\u003cE extends Envelope\u003e(envelope: E, newItem: E[1][number]): E {\n  const [headers, items] = envelope;\n  return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem\u003cE extends Envelope\u003e(\n  envelope: Envelope,\n  callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) =\u003e boolean | void,\n): boolean {\n  const envelopeItems = envelope[1];\n\n  for (const envelopeItem of envelopeItems) {\n    const envelopeItemType = envelopeItem[0].type;\n    const result = callback(envelopeItem, envelopeItemType);\n\n    if (result) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n  return forEachEnvelopeItem(envelope, (_, type) =\u003e types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input: string): Uint8Array {\n  const carrier = getSentryCarrier(GLOBAL_OBJ);\n  return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input: Uint8Array): string {\n  const carrier = getSentryCarrier(GLOBAL_OBJ);\n  return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope): string | Uint8Array {\n  const [envHeaders, items] = envelope;\n  // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n  let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n  function append(next: string | Uint8Array): void {\n    if (typeof parts === 'string') {\n      parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];\n    } else {\n      parts.push(typeof next === 'string' ? encodeUTF8(next) : next);\n    }\n  }\n\n  for (const item of items) {\n    const [itemHeaders, payload] = item;\n\n    append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n    if (typeof payload === 'string' || payload instanceof Uint8Array) {\n      append(payload);\n    } else {\n      let stringifiedPayload: string;\n      try {\n        stringifiedPayload = JSON.stringify(payload);\n      } catch {\n        // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still\n        // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n        // performance impact but in this case a performance hit is better than throwing.\n        stringifiedPayload = JSON.stringify(normalize(payload));\n      }\n      append(stringifiedPayload);\n    }\n  }\n\n  return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n  const totalLength = buffers.reduce((acc, buf) =\u003e acc + buf.length, 0);\n\n  const merged = new Uint8Array(totalLength);\n  let offset = 0;\n  for (const buffer of buffers) {\n    merged.set(buffer, offset);\n    offset += buffer.length;\n  }\n\n  return merged;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(env: string | Uint8Array): Envelope {\n  let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n  function readBinary(length: number): Uint8Array {\n    const bin = buffer.subarray(0, length);\n    // Replace the buffer with the remaining data excluding trailing newline\n    buffer = buffer.subarray(length + 1);\n    return bin;\n  }\n\n  function readJson\u003cT\u003e(): T {\n    let i = buffer.indexOf(0xa);\n    // If we couldn't find a newline, we must have found the end of the buffer\n    if (i \u003c 0) {\n      i = buffer.length;\n    }\n\n    return JSON.parse(decodeUTF8(readBinary(i))) as T;\n  }\n\n  const envelopeHeader = readJson\u003cBaseEnvelopeHeaders\u003e();\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const items: [any, any][] = [];\n\n  while (buffer.length) {\n    const itemHeader = readJson\u003cBaseEnvelopeItemHeaders\u003e();\n    const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n    items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n  }\n\n  return [envelopeHeader, items];\n}\n\n/**\n * Creates envelope item for a single span\n */\nexport function createSpanEnvelopeItem(spanJson: Partial\u003cSpanJSON\u003e): SpanItem {\n  const spanHeaders: SpanItem[0] = {\n    type: 'span',\n  };\n\n  return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(attachment: Attachment): AttachmentItem {\n  const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n  return [\n    {\n      type: 'attachment',\n      length: buffer.length,\n      filename: attachment.filename,\n      content_type: attachment.contentType,\n      attachment_type: attachment.attachmentType,\n    },\n    buffer,\n  ];\n}\n\ntype OverriddenItemType = Exclude\u003cEnvelopeItemType, DataCategory\u003e;\n\n// Map of envelope item types to data categories where the category differs from the type.\n// Types that map to themselves (session, attachment, transaction, profile, feedback, span, metric) fall through.\nconst DATA_CATEGORY_OVERRIDES: Record\u003cOverriddenItemType, DataCategory\u003e = {\n  sessions: 'session',\n  event: 'error',\n  client_report: 'internal',\n  user_report: 'default',\n  profile_chunk: 'profile',\n  replay_event: 'replay',\n  replay_recording: 'replay',\n  check_in: 'monitor',\n  raw_security: 'security',\n  log: 'log_item',\n  trace_metric: 'metric',\n};\n\nfunction _isOverriddenType(type: EnvelopeItemType): type is OverriddenItemType {\n  return type in DATA_CATEGORY_OVERRIDES;\n}\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n  return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type;\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n  if (!metadataOrEvent?.sdk) {\n    return;\n  }\n  const { name, version } = metadataOrEvent.sdk;\n  return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n  event: Event,\n  sdkInfo: SdkInfo | undefined,\n  tunnel: string | undefined,\n  dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n  const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n  return {\n    event_id: event.event_id as string,\n    sent_at: new Date().toISOString(),\n    ...(sdkInfo \u0026\u0026 { sdk: sdkInfo }),\n    ...(!!tunnel \u0026\u0026 dsn \u0026\u0026 { dsn: dsnToString(dsn) }),\n    ...(dynamicSamplingContext \u0026\u0026 {\n      trace: dynamicSamplingContext,\n    }),\n  };\n}\n","import type { Client } from './client';\nimport { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext';\nimport type { SentrySpan } from './tracing/sentrySpan';\nimport type { LegacyCSPReport } from './types-hoist/csp';\nimport type { DsnComponents } from './types-hoist/dsn';\nimport type {\n  DynamicSamplingContext,\n  EventEnvelope,\n  EventItem,\n  RawSecurityEnvelope,\n  RawSecurityItem,\n  SessionEnvelope,\n  SessionItem,\n  SpanEnvelope,\n  SpanItem,\n} from './types-hoist/envelope';\nimport type { Event } from './types-hoist/event';\nimport type { SdkInfo } from './types-hoist/sdkinfo';\nimport type { SdkMetadata } from './types-hoist/sdkmetadata';\nimport type { Session, SessionAggregates } from './types-hoist/session';\nimport { dsnToString } from './utils/dsn';\nimport {\n  createEnvelope,\n  createEventEnvelopeHeaders,\n  createSpanEnvelopeItem,\n  getSdkMetadataForEnvelopeHeader,\n} from './utils/envelope';\nimport { uuid4 } from './utils/misc';\nimport { shouldIgnoreSpan } from './utils/should-ignore-span';\nimport { showSpanDropWarning, spanToJSON } from './utils/spanUtils';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n *\n * @internal, exported only for testing\n **/\nexport function _enhanceEventWithSdkInfo(event: Event, newSdkInfo?: SdkInfo): Event {\n  if (!newSdkInfo) {\n    return event;\n  }\n\n  const eventSdkInfo = event.sdk || {};\n\n  event.sdk = {\n    ...eventSdkInfo,\n    name: eventSdkInfo.name || newSdkInfo.name,\n    version: eventSdkInfo.version || newSdkInfo.version,\n    integrations: [...(event.sdk?.integrations || []), ...(newSdkInfo.integrations || [])],\n    packages: [...(event.sdk?.packages || []), ...(newSdkInfo.packages || [])],\n    settings:\n      event.sdk?.settings || newSdkInfo.settings\n        ? {\n            ...event.sdk?.settings,\n            ...newSdkInfo.settings,\n          }\n        : undefined,\n  };\n\n  return event;\n}\n\n/** Creates an envelope from a Session */\nexport function createSessionEnvelope(\n  session: Session | SessionAggregates,\n  dsn?: DsnComponents,\n  metadata?: SdkMetadata,\n  tunnel?: string,\n): SessionEnvelope {\n  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n  const envelopeHeaders = {\n    sent_at: new Date().toISOString(),\n    ...(sdkInfo \u0026\u0026 { sdk: sdkInfo }),\n    ...(!!tunnel \u0026\u0026 dsn \u0026\u0026 { dsn: dsnToString(dsn) }),\n  };\n\n  const envelopeItem: SessionItem =\n    'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n  return createEnvelope\u003cSessionEnvelope\u003e(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nexport function createEventEnvelope(\n  event: Event,\n  dsn?: DsnComponents,\n  metadata?: SdkMetadata,\n  tunnel?: string,\n): EventEnvelope {\n  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n  /*\n    Note: Due to TS, event.type may be `replay_event`, theoretically.\n    In practice, we never call `createEventEnvelope` with `replay_event` type,\n    and we'd have to adjust a looot of types to make this work properly.\n    We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n    So the safe choice is to really guard against the replay_event type here.\n  */\n  const eventType = event.type \u0026\u0026 event.type !== 'replay_event' ? event.type : 'event';\n\n  _enhanceEventWithSdkInfo(event, metadata?.sdk);\n\n  const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n  // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n  // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n  // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n  // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n  delete event.sdkProcessingMetadata;\n\n  const eventItem: EventItem = [{ type: eventType }, event];\n  return createEnvelope\u003cEventEnvelope\u003e(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nexport function createSpanEnvelope(spans: [SentrySpan, ...SentrySpan[]], client?: Client): SpanEnvelope {\n  function dscHasRequiredProps(dsc: Partial\u003cDynamicSamplingContext\u003e): dsc is DynamicSamplingContext {\n    return !!dsc.trace_id \u0026\u0026 !!dsc.public_key;\n  }\n\n  // For the moment we'll obtain the DSC from the first span in the array\n  // This might need to be changed if we permit sending multiple spans from\n  // different segments in one envelope\n  const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n  const dsn = client?.getDsn();\n  const tunnel = client?.getOptions().tunnel;\n\n  const headers: SpanEnvelope[0] = {\n    sent_at: new Date().toISOString(),\n    ...(dscHasRequiredProps(dsc) \u0026\u0026 { trace: dsc }),\n    ...(!!tunnel \u0026\u0026 dsn \u0026\u0026 { dsn: dsnToString(dsn) }),\n  };\n\n  const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};\n\n  const filteredSpans = ignoreSpans?.length\n    ? spans.filter(span =\u003e !shouldIgnoreSpan(spanToJSON(span), ignoreSpans))\n    : spans;\n  const droppedSpans = spans.length - filteredSpans.length;\n\n  if (droppedSpans) {\n    client?.recordDroppedEvent('before_send', 'span', droppedSpans);\n  }\n\n  const convertToSpanJSON = beforeSendSpan\n    ? (span: SentrySpan) =\u003e {\n        const spanJson = spanToJSON(span);\n        const processedSpan = beforeSendSpan(spanJson);\n\n        if (!processedSpan) {\n          showSpanDropWarning();\n          return spanJson;\n        }\n\n        return processedSpan;\n      }\n    : spanToJSON;\n\n  const items: SpanItem[] = [];\n  for (const span of filteredSpans) {\n    const spanJson = convertToSpanJSON(span);\n    if (spanJson) {\n      items.push(createSpanEnvelopeItem(spanJson));\n    }\n  }\n\n  return createEnvelope\u003cSpanEnvelope\u003e(headers, items);\n}\n\n/**\n * Create an Envelope from a CSP report.\n */\nexport function createRawSecurityEnvelope(\n  report: LegacyCSPReport,\n  dsn: DsnComponents,\n  tunnel?: string,\n  release?: string,\n  environment?: string,\n): RawSecurityEnvelope {\n  const envelopeHeaders = {\n    event_id: uuid4(),\n    ...(!!tunnel \u0026\u0026 dsn \u0026\u0026 { dsn: dsnToString(dsn) }),\n  };\n\n  const eventItem: RawSecurityItem = [\n    { type: 'raw_security', sentry_release: release, sentry_environment: environment },\n    report,\n  ];\n\n  return createEnvelope\u003cRawSecurityEnvelope\u003e(envelopeHeaders, [eventItem]);\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { Span } from '../types-hoist/span';\nimport { debug } from '../utils/debug-logger';\nimport { getRootSpan, spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Print a log message for a started span.\n */\nexport function logSpanStart(span: Span): void {\n  if (!DEBUG_BUILD) return;\n\n  const { description = '\u003c unknown name \u003e', op = '\u003c unknown op \u003e', parent_span_id: parentSpanId } = spanToJSON(span);\n  const { spanId } = span.spanContext();\n\n  const sampled = spanIsSampled(span);\n  const rootSpan = getRootSpan(span);\n  const isRootSpan = rootSpan === span;\n\n  const header = `[Tracing] Starting ${sampled ? 'sampled' : 'unsampled'} ${isRootSpan ? 'root ' : ''}span`;\n\n  const infoParts: string[] = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];\n\n  if (parentSpanId) {\n    infoParts.push(`parent ID: ${parentSpanId}`);\n  }\n\n  if (!isRootSpan) {\n    const { op, description } = spanToJSON(rootSpan);\n    infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);\n    if (op) {\n      infoParts.push(`root op: ${op}`);\n    }\n    if (description) {\n      infoParts.push(`root description: ${description}`);\n    }\n  }\n\n  debug.log(`${header}\n  ${infoParts.join('\\n  ')}`);\n}\n\n/**\n * Print a log message for an ended span.\n */\nexport function logSpanEnd(span: Span): void {\n  if (!DEBUG_BUILD) return;\n\n  const { description = '\u003c unknown name \u003e', op = '\u003c unknown op \u003e' } = spanToJSON(span);\n  const { spanId } = span.spanContext();\n  const rootSpan = getRootSpan(span);\n  const isRootSpan = rootSpan === span;\n\n  const msg = `[Tracing] Finishing \"${op}\" ${isRootSpan ? 'root ' : ''}span \"${description}\" with ID ${spanId}`;\n  debug.log(msg);\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport {\n  SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT,\n  SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE,\n} from '../semanticAttributes';\nimport type { Measurements, MeasurementUnit } from '../types-hoist/measurement';\nimport type { TimedEvent } from '../types-hoist/timedEvent';\nimport { debug } from '../utils/debug-logger';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils';\n\n/**\n * Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span\n * as the 4th parameter.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit, activeSpan = getActiveSpan()): void {\n  const rootSpan = activeSpan \u0026\u0026 getRootSpan(activeSpan);\n\n  if (rootSpan) {\n    DEBUG_BUILD \u0026\u0026 debug.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);\n    rootSpan.addEvent(name, {\n      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,\n      [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit as string,\n    });\n  }\n}\n\n/**\n * Convert timed events to measurements.\n */\nexport function timedEventsToMeasurements(events: TimedEvent[]): Measurements | undefined {\n  if (!events || events.length === 0) {\n    return undefined;\n  }\n\n  const measurements: Measurements = {};\n  events.forEach(event =\u003e {\n    const attributes = event.attributes || {};\n    const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT] as MeasurementUnit | undefined;\n    const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE] as number | undefined;\n\n    if (typeof unit === 'string' \u0026\u0026 typeof value === 'number') {\n      measurements[event.name] = { value, unit };\n    }\n  });\n\n  return measurements;\n}\n","import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { createSpanEnvelope } from '../envelope';\nimport {\n  SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,\n  SEMANTIC_ATTRIBUTE_PROFILE_ID,\n  SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n  SEMANTIC_ATTRIBUTE_SENTRY_OP,\n  SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n  SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../semanticAttributes';\nimport type { SpanEnvelope } from '../types-hoist/envelope';\nimport type { TransactionEvent } from '../types-hoist/event';\nimport type { SpanLink } from '../types-hoist/link';\nimport type {\n  SentrySpanArguments,\n  Span,\n  SpanAttributes,\n  SpanAttributeValue,\n  SpanContextData,\n  SpanJSON,\n  SpanOrigin,\n  SpanTimeInput,\n} from '../types-hoist/span';\nimport type { SpanStatus } from '../types-hoist/spanStatus';\nimport type { TimedEvent } from '../types-hoist/timedEvent';\nimport { debug } from '../utils/debug-logger';\nimport { generateSpanId, generateTraceId } from '../utils/propagationContext';\nimport {\n  convertSpanLinksForEnvelope,\n  getRootSpan,\n  getSpanDescendants,\n  getStatusMessage,\n  spanTimeInputToSeconds,\n  spanToJSON,\n  spanToTransactionTraceContext,\n  TRACE_FLAG_NONE,\n  TRACE_FLAG_SAMPLED,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { logSpanEnd } from './logSpans';\nimport { timedEventsToMeasurements } from './measurement';\nimport { getCapturedScopesOnSpan } from './utils';\n\nconst MAX_SPAN_COUNT = 1000;\n\n/**\n * Span contains all data about a span\n */\nexport class SentrySpan implements Span {\n  protected _traceId: string;\n  protected _spanId: string;\n  protected _parentSpanId?: string | undefined;\n  protected _sampled: boolean | undefined;\n  protected _name?: string | undefined;\n  protected _attributes: SpanAttributes;\n  protected _links?: SpanLink[];\n  /** Epoch timestamp in seconds when the span started. */\n  protected _startTime: number;\n  /** Epoch timestamp in seconds when the span ended. */\n  protected _endTime?: number | undefined;\n  /** Internal keeper of the status */\n  protected _status?: SpanStatus;\n  /** The timed events added to this span. */\n  protected _events: TimedEvent[];\n\n  /** if true, treat span as a standalone span (not part of a transaction) */\n  private _isStandaloneSpan?: boolean;\n\n  /**\n   * You should never call the constructor manually, always use `Sentry.startSpan()`\n   * or other span methods.\n   * @internal\n   * @hideconstructor\n   * @hidden\n   */\n  public constructor(spanContext: SentrySpanArguments = {}) {\n    this._traceId = spanContext.traceId || generateTraceId();\n    this._spanId = spanContext.spanId || generateSpanId();\n    this._startTime = spanContext.startTimestamp || timestampInSeconds();\n    this._links = spanContext.links;\n\n    this._attributes = {};\n    this.setAttributes({\n      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual',\n      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n      ...spanContext.attributes,\n    });\n\n    this._name = spanContext.name;\n\n    if (spanContext.parentSpanId) {\n      this._parentSpanId = spanContext.parentSpanId;\n    }\n    // We want to include booleans as well here\n    if ('sampled' in spanContext) {\n      this._sampled = spanContext.sampled;\n    }\n    if (spanContext.endTimestamp) {\n      this._endTime = spanContext.endTimestamp;\n    }\n\n    this._events = [];\n\n    this._isStandaloneSpan = spanContext.isStandalone;\n\n    // If the span is already ended, ensure we finalize the span immediately\n    if (this._endTime) {\n      this._onSpanEnded();\n    }\n  }\n\n  /** @inheritDoc */\n  public addLink(link: SpanLink): this {\n    if (this._links) {\n      this._links.push(link);\n    } else {\n      this._links = [link];\n    }\n    return this;\n  }\n\n  /** @inheritDoc */\n  public addLinks(links: SpanLink[]): this {\n    if (this._links) {\n      this._links.push(...links);\n    } else {\n      this._links = links;\n    }\n    return this;\n  }\n\n  /**\n   * This should generally not be used,\n   * but it is needed for being compliant with the OTEL Span interface.\n   *\n   * @hidden\n   * @internal\n   */\n  public recordException(_exception: unknown, _time?: number | undefined): void {\n    // noop\n  }\n\n  /** @inheritdoc */\n  public spanContext(): SpanContextData {\n    const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n    return {\n      spanId,\n      traceId,\n      traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n    };\n  }\n\n  /** @inheritdoc */\n  public setAttribute(key: string, value: SpanAttributeValue | undefined): this {\n    if (value === undefined) {\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete this._attributes[key];\n    } else {\n      this._attributes[key] = value;\n    }\n\n    return this;\n  }\n\n  /** @inheritdoc */\n  public setAttributes(attributes: SpanAttributes): this {\n    Object.keys(attributes).forEach(key =\u003e this.setAttribute(key, attributes[key]));\n    return this;\n  }\n\n  /**\n   * This should generally not be used,\n   * but we need it for browser tracing where we want to adjust the start time afterwards.\n   * USE THIS WITH CAUTION!\n   *\n   * @hidden\n   * @internal\n   */\n  public updateStartTime(timeInput: SpanTimeInput): void {\n    this._startTime = spanTimeInputToSeconds(timeInput);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public setStatus(value: SpanStatus): this {\n    this._status = value;\n    return this;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public updateName(name: string): this {\n    this._name = name;\n    this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');\n    return this;\n  }\n\n  /** @inheritdoc */\n  public end(endTimestamp?: SpanTimeInput): void {\n    // If already ended, skip\n    if (this._endTime) {\n      return;\n    }\n\n    this._endTime = spanTimeInputToSeconds(endTimestamp);\n    logSpanEnd(this);\n\n    this._onSpanEnded();\n  }\n\n  /**\n   * Get JSON representation of this span.\n   *\n   * @hidden\n   * @internal This method is purely for internal purposes and should not be used outside\n   * of SDK code. If you need to get a JSON representation of a span,\n   * use `spanToJSON(span)` instead.\n   */\n  public getSpanJSON(): SpanJSON {\n    return {\n      data: this._attributes,\n      description: this._name,\n      op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n      parent_span_id: this._parentSpanId,\n      span_id: this._spanId,\n      start_timestamp: this._startTime,\n      status: getStatusMessage(this._status),\n      timestamp: this._endTime,\n      trace_id: this._traceId,\n      origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined,\n      profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n      exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,\n      measurements: timedEventsToMeasurements(this._events),\n      is_segment: (this._isStandaloneSpan \u0026\u0026 getRootSpan(this) === this) || undefined,\n      segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,\n      links: convertSpanLinksForEnvelope(this._links),\n    };\n  }\n\n  /** @inheritdoc */\n  public isRecording(): boolean {\n    return !this._endTime \u0026\u0026 !!this._sampled;\n  }\n\n  /**\n   * @inheritdoc\n   */\n  public addEvent(\n    name: string,\n    attributesOrStartTime?: SpanAttributes | SpanTimeInput,\n    startTime?: SpanTimeInput,\n  ): this {\n    DEBUG_BUILD \u0026\u0026 debug.log('[Tracing] Adding an event to span:', name);\n\n    const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();\n    const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};\n\n    const event: TimedEvent = {\n      name,\n      time: spanTimeInputToSeconds(time),\n      attributes,\n    };\n\n    this._events.push(event);\n\n    return this;\n  }\n\n  /**\n   * This method should generally not be used,\n   * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.\n   * USE THIS WITH CAUTION!\n   * @internal\n   * @hidden\n   * @experimental\n   */\n  public isStandaloneSpan(): boolean {\n    return !!this._isStandaloneSpan;\n  }\n\n  /** Emit `spanEnd` when the span is ended. */\n  private _onSpanEnded(): void {\n    const client = getClient();\n    if (client) {\n      client.emit('spanEnd', this);\n    }\n\n    // A segment span is basically the root span of a local span tree.\n    // So for now, this is either what we previously refer to as the root span,\n    // or a standalone span.\n    const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);\n\n    if (!isSegmentSpan) {\n      return;\n    }\n\n    // if this is a standalone span, we send it immediately\n    if (this._isStandaloneSpan) {\n      if (this._sampled) {\n        sendSpanEnvelope(createSpanEnvelope([this], client));\n      } else {\n        DEBUG_BUILD \u0026\u0026\n          debug.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');\n        if (client) {\n          client.recordDroppedEvent('sample_rate', 'span');\n        }\n      }\n      return;\n    }\n\n    const transactionEvent = this._convertSpanToTransaction();\n    if (transactionEvent) {\n      const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n      scope.captureEvent(transactionEvent);\n    }\n  }\n\n  /**\n   * Finish the transaction \u0026 prepare the event to send to Sentry.\n   */\n  private _convertSpanToTransaction(): TransactionEvent | undefined {\n    // We can only convert finished spans\n    if (!isFullFinishedSpan(spanToJSON(this))) {\n      return undefined;\n    }\n\n    if (!this._name) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('Transaction has no name, falling back to `\u003cunlabeled transaction\u003e`.');\n      this._name = '\u003cunlabeled transaction\u003e';\n    }\n\n    const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n    const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;\n\n    if (this._sampled !== true) {\n      return undefined;\n    }\n\n    // The transaction span itself as well as any potential standalone spans should be filtered out\n    const finishedSpans = getSpanDescendants(this).filter(span =\u003e span !== this \u0026\u0026 !isStandaloneSpan(span));\n\n    const spans = finishedSpans.map(span =\u003e spanToJSON(span)).filter(isFullFinishedSpan);\n\n    const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n    // remove internal root span attributes we don't need to send.\n    /* eslint-disable @typescript-eslint/no-dynamic-delete */\n    delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n    spans.forEach(span =\u003e {\n      delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n    });\n    // eslint-enabled-next-line @typescript-eslint/no-dynamic-delete\n\n    const transaction: TransactionEvent = {\n      contexts: {\n        trace: spanToTransactionTraceContext(this),\n      },\n      spans:\n        // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here\n        // we do not use spans anymore after this point\n        spans.length \u003e MAX_SPAN_COUNT\n          ? spans.sort((a, b) =\u003e a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)\n          : spans,\n      start_timestamp: this._startTime,\n      timestamp: this._endTime,\n      transaction: this._name,\n      type: 'transaction',\n      sdkProcessingMetadata: {\n        capturedSpanScope,\n        capturedSpanIsolationScope,\n        dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n      },\n      request: normalizedRequest,\n      ...(source \u0026\u0026 {\n        transaction_info: {\n          source,\n        },\n      }),\n    };\n\n    const measurements = timedEventsToMeasurements(this._events);\n    const hasMeasurements = measurements \u0026\u0026 Object.keys(measurements).length;\n\n    if (hasMeasurements) {\n      DEBUG_BUILD \u0026\u0026\n        debug.log(\n          '[Measurements] Adding measurements to transaction event',\n          JSON.stringify(measurements, undefined, 2),\n        );\n      transaction.measurements = measurements;\n    }\n\n    return transaction;\n  }\n}\n\nfunction isSpanTimeInput(value: undefined | SpanAttributes | SpanTimeInput): value is SpanTimeInput {\n  return (value \u0026\u0026 typeof value === 'number') || value instanceof Date || Array.isArray(value);\n}\n\n// We want to filter out any incomplete SpanJSON objects\nfunction isFullFinishedSpan(input: Partial\u003cSpanJSON\u003e): input is SpanJSON {\n  return !!input.start_timestamp \u0026\u0026 !!input.timestamp \u0026\u0026 !!input.span_id \u0026\u0026 !!input.trace_id;\n}\n\n/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */\nfunction isStandaloneSpan(span: Span): boolean {\n  return span instanceof SentrySpan \u0026\u0026 span.isStandaloneSpan();\n}\n\n/**\n * Sends a `SpanEnvelope`.\n *\n * Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`,\n * the envelope will not be sent either.\n */\nfunction sendSpanEnvelope(envelope: SpanEnvelope): void {\n  const client = getClient();\n  if (!client) {\n    return;\n  }\n\n  const spanItems = envelope[1];\n  if (!spanItems || spanItems.length === 0) {\n    client.recordDroppedEvent('before_send', 'span');\n    return;\n  }\n\n  // sendEnvelope should not throw\n  // eslint-disable-next-line @typescript-eslint/no-floating-promises\n  client.sendEnvelope(envelope);\n}\n","import { chainAndCopyPromiseLike } from '../utils/chain-and-copy-promiselike';\nimport { isThenable } from '../utils/is';\n\n/* eslint-disable */\n// Vendor \"Awaited\" in to be TS 3.8 compatible\ntype AwaitedPromise\u003cT\u003e = T extends null | undefined\n  ? T // special case for `null | undefined` when not in `--strictNullChecks` mode\n  : T extends object \u0026 { then(onfulfilled: infer F, ...args: infer _): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped\n    ? F extends (value: infer V, ...args: infer _) =\u003e any // if the argument to `then` is callable, extracts the first argument\n      ? V // normally this would recursively unwrap, but this is not possible in TS3.8\n      : never // the argument to `then` was not callable\n    : T; // non-object or non-thenable\n/* eslint-enable */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function handleCallbackErrors\u003cFn extends () =\u003e Promise\u003cany\u003e, PromiseValue = AwaitedPromise\u003cReturnType\u003cFn\u003e\u003e\u003e(\n  fn: Fn,\n  onError: (error: unknown) =\u003e void,\n  onFinally?: () =\u003e void,\n  onSuccess?: (result: PromiseValue) =\u003e void,\n): ReturnType\u003cFn\u003e;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function handleCallbackErrors\u003cFn extends () =\u003e any\u003e(\n  fn: Fn,\n  onError: (error: unknown) =\u003e void,\n  onFinally?: () =\u003e void,\n  onSuccess?: (result: ReturnType\u003cFn\u003e) =\u003e void,\n): ReturnType\u003cFn\u003e;\n/**\n * Wrap a callback function with error handling.\n * If an error is thrown, it will be passed to the `onError` callback and re-thrown.\n *\n * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.\n *\n * If an `onFinally` callback is provided, this will be called when the callback has finished\n * - so if it returns a promise, once the promise resolved/rejected,\n * else once the callback has finished executing.\n * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.\n */\nexport function handleCallbackErrors\u003c\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Fn extends () =\u003e any,\n  ValueType = ReturnType\u003cFn\u003e,\n\u003e(\n  fn: Fn,\n  onError: (error: unknown) =\u003e void,\n  onFinally: () =\u003e void = () =\u003e {},\n  onSuccess: (result: ValueType | AwaitedPromise\u003cValueType\u003e) =\u003e void = () =\u003e {},\n): ValueType {\n  let maybePromiseResult: ReturnType\u003cFn\u003e;\n  try {\n    maybePromiseResult = fn();\n  } catch (e) {\n    onError(e);\n    onFinally();\n    throw e;\n  }\n\n  return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);\n}\n\n/**\n * Maybe handle a promise rejection.\n * This expects to be given a value that _may_ be a promise, or any other value.\n * If it is a promise, and it rejects, it will call the `onError` callback.\n *\n * For thenable objects with extra methods (like jQuery's jqXHR),\n * this function preserves those methods by wrapping the original thenable in a Proxy\n * that intercepts .then() calls to apply error handling while forwarding all other\n * properties to the original object.\n * This allows code like `startSpan(() =\u003e $.ajax(...)).abort()` to work correctly.\n */\nfunction maybeHandlePromiseRejection\u003cMaybePromise\u003e(\n  value: MaybePromise,\n  onError: (error: unknown) =\u003e void,\n  onFinally: () =\u003e void,\n  onSuccess: (result: MaybePromise | AwaitedPromise\u003cMaybePromise\u003e) =\u003e void,\n): MaybePromise {\n  if (isThenable(value)) {\n    return chainAndCopyPromiseLike(\n      value as MaybePromise \u0026 PromiseLike\u003cAwaited\u003ctypeof value\u003e\u003e \u0026 Record\u003cstring, unknown\u003e,\n      result =\u003e {\n        onFinally();\n        onSuccess(result as Awaited\u003cMaybePromise\u003e);\n      },\n      err =\u003e {\n        onError(err);\n        onFinally();\n      },\n    ) as MaybePromise;\n  }\n  // Non-thenable value - call callbacks immediately and return as-is\n  onFinally();\n  onSuccess(value);\n  return value;\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { CoreOptions } from '../types-hoist/options';\nimport type { SamplingContext } from '../types-hoist/samplingcontext';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { parseSampleRate } from '../utils/parseSampleRate';\n\n/**\n * Makes a sampling decision for the given options.\n *\n * Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n */\nexport function sampleSpan(\n  options: Pick\u003cCoreOptions, 'tracesSampleRate' | 'tracesSampler'\u003e,\n  samplingContext: SamplingContext,\n  sampleRand: number,\n): [sampled: boolean, sampleRate?: number, localSampleRateWasApplied?: boolean] {\n  // nothing to do if span recording is not enabled\n  if (!hasSpansEnabled(options)) {\n    return [false];\n  }\n\n  let localSampleRateWasApplied = undefined;\n\n  // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n  // work; prefer the hook if so\n  let sampleRate;\n  if (typeof options.tracesSampler === 'function') {\n    sampleRate = options.tracesSampler({\n      ...samplingContext,\n      inheritOrSampleWith: fallbackSampleRate =\u003e {\n        // If we have an incoming parent sample rate, we'll just use that one.\n        // The sampling decision will be inherited because of the sample_rand that was generated when the trace reached the incoming boundaries of the SDK.\n        if (typeof samplingContext.parentSampleRate === 'number') {\n          return samplingContext.parentSampleRate;\n        }\n\n        // Fallback if parent sample rate is not on the incoming trace (e.g. if there is no baggage)\n        // This is to provide backwards compatibility if there are incoming traces from older SDKs that don't send a parent sample rate or a sample rand. In these cases we just want to force either a sampling decision on the downstream traces via the sample rate.\n        if (typeof samplingContext.parentSampled === 'boolean') {\n          return Number(samplingContext.parentSampled);\n        }\n\n        return fallbackSampleRate;\n      },\n    });\n    localSampleRateWasApplied = true;\n  } else if (samplingContext.parentSampled !== undefined) {\n    sampleRate = samplingContext.parentSampled;\n  } else if (typeof options.tracesSampleRate !== 'undefined') {\n    sampleRate = options.tracesSampleRate;\n    localSampleRateWasApplied = true;\n  }\n\n  // Since this is coming from the user (or from a function provided by the user), who knows what we might get.\n  // (The only valid values are booleans or numbers between 0 and 1.)\n  const parsedSampleRate = parseSampleRate(sampleRate);\n\n  if (parsedSampleRate === undefined) {\n    DEBUG_BUILD \u0026\u0026\n      debug.warn(\n        `[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n          sampleRate,\n        )} of type ${JSON.stringify(typeof sampleRate)}.`,\n      );\n    return [false];\n  }\n\n  // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n  if (!parsedSampleRate) {\n    DEBUG_BUILD \u0026\u0026\n      debug.log(\n        `[Tracing] Discarding transaction because ${\n          typeof options.tracesSampler === 'function'\n            ? 'tracesSampler returned 0 or false'\n            : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n        }`,\n      );\n    return [false, parsedSampleRate, localSampleRateWasApplied];\n  }\n\n  // We always compare the sample rand for the current execution context against the chosen sample rate.\n  // Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n  const shouldSample = sampleRand \u003c parsedSampleRate;\n\n  // if we're not going to keep it, we're done\n  if (!shouldSample) {\n    DEBUG_BUILD \u0026\u0026\n      debug.log(\n        `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n          sampleRate,\n        )})`,\n      );\n  }\n\n  return [shouldSample, parsedSampleRate, localSampleRateWasApplied];\n}\n","/* eslint-disable max-lines */\n\nimport { getAsyncContextStrategy } from '../asyncContext';\nimport type { AsyncContextStrategy } from '../asyncContext/types';\nimport { getMainCarrier } from '../carrier';\nimport { getClient, getCurrentScope, getIsolationScope, withScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope } from '../scope';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { SentrySpanArguments, Span, SpanTimeInput } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { baggageHeaderToDynamicSamplingContext } from '../utils/baggage';\nimport { debug } from '../utils/debug-logger';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { parseSampleRate } from '../utils/parseSampleRate';\nimport { generateTraceId } from '../utils/propagationContext';\nimport { safeMathRandom } from '../utils/randomSafeContext';\nimport { _getSpanForScope, _setSpanForScope } from '../utils/spanOnScope';\nimport { addChildSpanToSpan, getRootSpan, spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';\nimport { propagationContextFromHeaders, shouldContinueTrace } from '../utils/tracing';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { logSpanStart } from './logSpans';\nimport { sampleSpan } from './sampling';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR } from './spanstatus';\nimport { setCapturedScopesOnSpan } from './utils';\n\nconst SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpan\u003cT\u003e(options: StartSpanOptions, callback: (span: Span) =\u003e T): T {\n  const acs = getAcs();\n  if (acs.startSpan) {\n    return acs.startSpan(options, callback);\n  }\n\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n  // We still need to fork a potentially passed scope, as we set the active span on it\n  // and we need to ensure that it is cleaned up properly once the span ends.\n  const customForkedScope = customScope?.clone();\n\n  return withScope(customForkedScope, () =\u003e {\n    // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n    const wrapper = getActiveSpanWrapper\u003cT\u003e(customParentSpan);\n\n    return wrapper(() =\u003e {\n      const scope = getCurrentScope();\n      const parentSpan = getParentSpan(scope, customParentSpan);\n\n      const shouldSkipSpan = options.onlyIfParent \u0026\u0026 !parentSpan;\n      const activeSpan = shouldSkipSpan\n        ? new SentryNonRecordingSpan()\n        : createChildOrRootSpan({\n            parentSpan,\n            spanArguments,\n            forceTransaction,\n            scope,\n          });\n\n      _setSpanForScope(scope, activeSpan);\n\n      return handleCallbackErrors(\n        () =\u003e callback(activeSpan),\n        () =\u003e {\n          // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n          const { status } = spanToJSON(activeSpan);\n          if (activeSpan.isRecording() \u0026\u0026 (!status || status === 'ok')) {\n            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n          }\n        },\n        () =\u003e {\n          activeSpan.end();\n        },\n      );\n    });\n  });\n}\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. Use `span.end()` to end the span.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpanManual\u003cT\u003e(options: StartSpanOptions, callback: (span: Span, finish: () =\u003e void) =\u003e T): T {\n  const acs = getAcs();\n  if (acs.startSpanManual) {\n    return acs.startSpanManual(options, callback);\n  }\n\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n  const customForkedScope = customScope?.clone();\n\n  return withScope(customForkedScope, () =\u003e {\n    // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n    const wrapper = getActiveSpanWrapper\u003cT\u003e(customParentSpan);\n\n    return wrapper(() =\u003e {\n      const scope = getCurrentScope();\n      const parentSpan = getParentSpan(scope, customParentSpan);\n\n      const shouldSkipSpan = options.onlyIfParent \u0026\u0026 !parentSpan;\n      const activeSpan = shouldSkipSpan\n        ? new SentryNonRecordingSpan()\n        : createChildOrRootSpan({\n            parentSpan,\n            spanArguments,\n            forceTransaction,\n            scope,\n          });\n\n      _setSpanForScope(scope, activeSpan);\n\n      return handleCallbackErrors(\n        // We pass the `finish` function to the callback, so the user can finish the span manually\n        // this is mainly here for historic purposes because previously, we instructed users to call\n        // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`\n        // or `finish` has the same effect and we simply leave it here to avoid breaking user code.\n        () =\u003e callback(activeSpan, () =\u003e activeSpan.end()),\n        () =\u003e {\n          // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n          const { status } = spanToJSON(activeSpan);\n          if (activeSpan.isRecording() \u0026\u0026 (!status || status === 'ok')) {\n            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n          }\n        },\n      );\n    });\n  });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getActiveSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * This function will always return a span,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startInactiveSpan(options: StartSpanOptions): Span {\n  const acs = getAcs();\n  if (acs.startInactiveSpan) {\n    return acs.startInactiveSpan(options);\n  }\n\n  const spanArguments = parseSentrySpanArguments(options);\n  const { forceTransaction, parentSpan: customParentSpan } = options;\n\n  // If `options.scope` is defined, we use this as as a wrapper,\n  // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n  const wrapper = options.scope\n    ? (callback: () =\u003e Span) =\u003e withScope(options.scope, callback)\n    : customParentSpan !== undefined\n      ? (callback: () =\u003e Span) =\u003e withActiveSpan(customParentSpan, callback)\n      : (callback: () =\u003e Span) =\u003e callback();\n\n  return wrapper(() =\u003e {\n    const scope = getCurrentScope();\n    const parentSpan = getParentSpan(scope, customParentSpan);\n\n    const shouldSkipSpan = options.onlyIfParent \u0026\u0026 !parentSpan;\n\n    if (shouldSkipSpan) {\n      return new SentryNonRecordingSpan();\n    }\n\n    return createChildOrRootSpan({\n      parentSpan,\n      spanArguments,\n      forceTransaction,\n      scope,\n    });\n  });\n}\n\n/**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from `\u003cmeta name=\"sentry-trace\"\u003e`\n * and `\u003cmeta name=\"baggage\"\u003e` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n */\nexport const continueTrace = \u003cV\u003e(\n  options: {\n    sentryTrace: Parameters\u003ctypeof propagationContextFromHeaders\u003e[0];\n    baggage: Parameters\u003ctypeof propagationContextFromHeaders\u003e[1];\n  },\n  callback: () =\u003e V,\n): V =\u003e {\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.continueTrace) {\n    return acs.continueTrace(options, callback);\n  }\n\n  const { sentryTrace, baggage } = options;\n\n  const client = getClient();\n  const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);\n  if (client \u0026\u0026 !shouldContinueTrace(client, incomingDsc?.org_id)) {\n    return startNewTrace(callback);\n  }\n\n  return withScope(scope =\u003e {\n    const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n    scope.setPropagationContext(propagationContext);\n    _setSpanForScope(scope, undefined);\n    return callback();\n  });\n};\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be\n * passed `null` to start an entirely new span tree.\n *\n * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,\n * spans started within the callback will not be attached to a parent span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan\u003cT\u003e(span: Span | null, callback: (scope: Scope) =\u003e T): T {\n  const acs = getAcs();\n  if (acs.withActiveSpan) {\n    return acs.withActiveSpan(span, callback);\n  }\n\n  return withScope(scope =\u003e {\n    _setSpanForScope(scope, span || undefined);\n    return callback(scope);\n  });\n}\n\n/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */\nexport function suppressTracing\u003cT\u003e(callback: () =\u003e T): T {\n  const acs = getAcs();\n\n  if (acs.suppressTracing) {\n    return acs.suppressTracing(callback);\n  }\n\n  return withScope(scope =\u003e {\n    // Note: We do not wait for the callback to finish before we reset the metadata\n    // the reason for this is that otherwise, in the browser this can lead to very weird behavior\n    // as there is only a single top scope, if the callback takes longer to finish,\n    // other, unrelated spans may also be suppressed, which we do not want\n    // so instead, we only suppress tracing synchronoysly in the browser\n    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n    const res = callback();\n    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: undefined });\n    return res;\n  });\n}\n\n/**\n * Starts a new trace for the duration of the provided callback. Spans started within the\n * callback will be part of the new trace instead of a potentially previously started trace.\n *\n * Important: Only use this function if you want to override the default trace lifetime and\n * propagation mechanism of the SDK for the duration and scope of the provided callback.\n * The newly created trace will also be the root of a new distributed trace, for example if\n * you make http requests within the callback.\n * This function might be useful if the operation you want to instrument should not be part\n * of a potentially ongoing trace.\n *\n * Default behavior:\n * - Server-side: A new trace is started for each incoming request.\n * - Browser: A new trace is started for each page our route. Navigating to a new route\n *            or page will automatically create a new trace.\n */\nexport function startNewTrace\u003cT\u003e(callback: () =\u003e T): T {\n  return withScope(scope =\u003e {\n    scope.setPropagationContext({\n      traceId: generateTraceId(),\n      sampleRand: safeMathRandom(),\n    });\n    DEBUG_BUILD \u0026\u0026 debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);\n    return withActiveSpan(null, callback);\n  });\n}\n\nfunction createChildOrRootSpan({\n  parentSpan,\n  spanArguments,\n  forceTransaction,\n  scope,\n}: {\n  parentSpan: SentrySpan | undefined;\n  spanArguments: SentrySpanArguments;\n  forceTransaction?: boolean;\n  scope: Scope;\n}): Span {\n  if (!hasSpansEnabled()) {\n    const span = new SentryNonRecordingSpan();\n\n    // If this is a root span, we ensure to freeze a DSC\n    // So we can have at least partial data here\n    if (forceTransaction || !parentSpan) {\n      const dsc = {\n        sampled: 'false',\n        sample_rate: '0',\n        transaction: spanArguments.name,\n        ...getDynamicSamplingContextFromSpan(span),\n      } satisfies Partial\u003cDynamicSamplingContext\u003e;\n      freezeDscOnSpan(span, dsc);\n    }\n\n    return span;\n  }\n\n  const isolationScope = getIsolationScope();\n\n  let span: Span;\n  if (parentSpan \u0026\u0026 !forceTransaction) {\n    span = _startChildSpan(parentSpan, scope, spanArguments);\n    addChildSpanToSpan(parentSpan, span);\n  } else if (parentSpan) {\n    // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n    const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n    const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n    const parentSampled = spanIsSampled(parentSpan);\n\n    span = _startRootSpan(\n      {\n        traceId,\n        parentSpanId,\n        ...spanArguments,\n      },\n      scope,\n      parentSampled,\n    );\n\n    freezeDscOnSpan(span, dsc);\n  } else {\n    const {\n      traceId,\n      dsc,\n      parentSpanId,\n      sampled: parentSampled,\n    } = {\n      ...isolationScope.getPropagationContext(),\n      ...scope.getPropagationContext(),\n    };\n\n    span = _startRootSpan(\n      {\n        traceId,\n        parentSpanId,\n        ...spanArguments,\n      },\n      scope,\n      parentSampled,\n    );\n\n    if (dsc) {\n      freezeDscOnSpan(span, dsc);\n    }\n  }\n\n  logSpanStart(span);\n\n  setCapturedScopesOnSpan(span, scope, isolationScope);\n\n  return span;\n}\n\n/**\n * This converts StartSpanOptions to SentrySpanArguments.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n */\nfunction parseSentrySpanArguments(options: StartSpanOptions): SentrySpanArguments {\n  const exp = options.experimental || {};\n  const initialCtx: SentrySpanArguments = {\n    isStandalone: exp.standalone,\n    ...options,\n  };\n\n  if (options.startTime) {\n    const ctx: SentrySpanArguments \u0026 { startTime?: SpanTimeInput } = { ...initialCtx };\n    ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n    delete ctx.startTime;\n    return ctx;\n  }\n\n  return initialCtx;\n}\n\nfunction getAcs(): AsyncContextStrategy {\n  const carrier = getMainCarrier();\n  return getAsyncContextStrategy(carrier);\n}\n\nfunction _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parentSampled?: boolean): SentrySpan {\n  const client = getClient();\n  const options: Partial\u003cClientOptions\u003e = client?.getOptions() || {};\n\n  const { name = '' } = spanArguments;\n\n  const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };\n\n  // we don't care about the decision for the moment; this is just a placeholder\n  client?.emit('beforeSampling', mutableSpanSamplingData, { decision: false });\n\n  // If hook consumers override the parentSampled flag, we will use that value instead of the actual one\n  const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;\n  const finalAttributes = mutableSpanSamplingData.spanAttributes;\n\n  const currentPropagationContext = scope.getPropagationContext();\n  const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[\n    SUPPRESS_TRACING_KEY\n  ]\n    ? [false]\n    : sampleSpan(\n        options,\n        {\n          name,\n          parentSampled: finalParentSampled,\n          attributes: finalAttributes,\n          parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate),\n        },\n        currentPropagationContext.sampleRand,\n      );\n\n  const rootSpan = new SentrySpan({\n    ...spanArguments,\n    attributes: {\n      [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n      [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:\n        sampleRate !== undefined \u0026\u0026 localSampleRateWasApplied ? sampleRate : undefined,\n      ...finalAttributes,\n    },\n    sampled,\n  });\n\n  if (!sampled \u0026\u0026 client) {\n    DEBUG_BUILD \u0026\u0026 debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');\n    client.recordDroppedEvent('sample_rate', 'transaction');\n  }\n\n  if (client) {\n    client.emit('spanStart', rootSpan);\n  }\n\n  return rootSpan;\n}\n\n/**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * This inherits the sampling decision from the parent span.\n */\nfunction _startChildSpan(parentSpan: Span, scope: Scope, spanArguments: SentrySpanArguments): Span {\n  const { spanId, traceId } = parentSpan.spanContext();\n  const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);\n\n  const childSpan = sampled\n    ? new SentrySpan({\n        ...spanArguments,\n        parentSpanId: spanId,\n        traceId,\n        sampled,\n      })\n    : new SentryNonRecordingSpan({ traceId });\n\n  addChildSpanToSpan(parentSpan, childSpan);\n\n  const client = getClient();\n  if (client) {\n    client.emit('spanStart', childSpan);\n    // If it has an endTimestamp, it's already ended\n    if (spanArguments.endTimestamp) {\n      client.emit('spanEnd', childSpan);\n    }\n  }\n\n  return childSpan;\n}\n\nfunction getParentSpan(scope: Scope, customParentSpan: Span | null | undefined): SentrySpan | undefined {\n  // always use the passed in span directly\n  if (customParentSpan) {\n    return customParentSpan as SentrySpan;\n  }\n\n  // This is different from `undefined` as it means the user explicitly wants no parent span\n  if (customParentSpan === null) {\n    return undefined;\n  }\n\n  const span = _getSpanForScope(scope) as SentrySpan | undefined;\n\n  if (!span) {\n    return undefined;\n  }\n\n  const client = getClient();\n  const options: Partial\u003cClientOptions\u003e = client ? client.getOptions() : {};\n  if (options.parentSpanIsAlwaysRootSpan) {\n    return getRootSpan(span) as SentrySpan;\n  }\n\n  return span;\n}\n\nfunction getActiveSpanWrapper\u003cT\u003e(parentSpan: Span | undefined | null): (callback: () =\u003e T) =\u003e T {\n  return parentSpan !== undefined\n    ? (callback: () =\u003e T) =\u003e {\n        return withActiveSpan(parentSpan, callback);\n      }\n    : (callback: () =\u003e T) =\u003e callback();\n}\n","import { getClient, getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport type { Span } from '../types-hoist/span';\nimport type { StartSpanOptions } from '../types-hoist/startSpanOptions';\nimport { debug } from '../utils/debug-logger';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span';\nimport { _setSpanForScope } from '../utils/spanOnScope';\nimport {\n  getActiveSpan,\n  getSpanDescendants,\n  removeChildSpanFromSpan,\n  spanTimeInputToSeconds,\n  spanToJSON,\n} from '../utils/spanUtils';\nimport { timestampInSeconds } from '../utils/time';\nimport { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan';\nimport { SentrySpan } from './sentrySpan';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK } from './spanstatus';\nimport { startInactiveSpan } from './trace';\n\nexport const TRACING_DEFAULTS = {\n  idleTimeout: 1_000,\n  finalTimeout: 30_000,\n  childSpanTimeout: 15_000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\nconst FINISH_REASON_CANCELLED = 'cancelled';\n\n// unused\nconst FINISH_REASON_DOCUMENT_HIDDEN = 'documentHidden';\n\n// unused in this file, but used in BrowserTracing\nconst FINISH_REASON_INTERRUPTED = 'interactionInterrupted';\n\ntype IdleSpanFinishReason =\n  | typeof FINISH_REASON_CANCELLED\n  | typeof FINISH_REASON_DOCUMENT_HIDDEN\n  | typeof FINISH_REASON_EXTERNAL_FINISH\n  | typeof FINISH_REASON_FINAL_TIMEOUT\n  | typeof FINISH_REASON_HEARTBEAT_FAILED\n  | typeof FINISH_REASON_IDLE_TIMEOUT\n  | typeof FINISH_REASON_INTERRUPTED;\n\ninterface IdleSpanOptions {\n  /**\n   * The time that has to pass without any span being created.\n   * If this time is exceeded, the idle span will finish.\n   */\n  idleTimeout: number;\n  /**\n   * The max. time an idle span may run.\n   * If this time is exceeded, the idle span will finish no matter what.\n   */\n  finalTimeout: number;\n  /**\n   * The max. time a child span may run.\n   * If the time since the last span was started exceeds this time, the idle span will finish.\n   */\n  childSpanTimeout?: number;\n  /**\n   * When set to `true`, will disable the idle timeout and child timeout\n   * until the `idleSpanEnableAutoFinish` hook is emitted for the idle span.\n   * The final timeout mechanism will not be affected by this option,\n   * meaning the idle span will definitely be finished when the final timeout is\n   * reached, no matter what this option is configured to.\n   *\n   * Defaults to `false`.\n   */\n  disableAutoFinish?: boolean;\n\n  /** Allows to configure a hook that is called when the idle span is ended, before it is processed. */\n  beforeSpanEnd?: (span: Span) =\u003e void;\n\n  /**\n   * If set to `true`, the idle span will be trimmed to the latest span end timestamp of its children.\n   *\n   * @default `true`.\n   */\n  trimIdleSpanEndTimestamp?: boolean;\n}\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nexport function startIdleSpan(startSpanOptions: StartSpanOptions, options: Partial\u003cIdleSpanOptions\u003e = {}): Span {\n  // Activities store a list of active spans\n  const activities = new Map\u003cstring, boolean\u003e();\n\n  // We should not use heartbeat if we finished a span\n  let _finished = false;\n\n  // Timer that tracks idleTimeout\n  let _idleTimeoutID: ReturnType\u003ctypeof setTimeout\u003e | undefined;\n\n  // Timer that tracks maxSpanTime for child spans\n  let _childSpanTimeoutID: ReturnType\u003ctypeof setTimeout\u003e | undefined;\n\n  // The reason why the span was finished\n  let _finishReason: IdleSpanFinishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n  let _autoFinishAllowed: boolean = !options.disableAutoFinish;\n\n  const _cleanupHooks: (() =\u003e void)[] = [];\n\n  const {\n    idleTimeout = TRACING_DEFAULTS.idleTimeout,\n    finalTimeout = TRACING_DEFAULTS.finalTimeout,\n    childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n    beforeSpanEnd,\n    trimIdleSpanEndTimestamp = true,\n  } = options;\n\n  const client = getClient();\n\n  if (!client || !hasSpansEnabled()) {\n    const span = new SentryNonRecordingSpan();\n\n    const dsc = {\n      sample_rate: '0',\n      sampled: 'false',\n      ...getDynamicSamplingContextFromSpan(span),\n    } satisfies Partial\u003cDynamicSamplingContext\u003e;\n    freezeDscOnSpan(span, dsc);\n\n    return span;\n  }\n\n  const scope = getCurrentScope();\n  const previousActiveSpan = getActiveSpan();\n  const span = _startIdleSpan(startSpanOptions);\n\n  // We patch span.end to ensure we can run some things before the span is ended\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  span.end = new Proxy(span.end, {\n    apply(target, thisArg, args: Parameters\u003cSpan['end']\u003e) {\n      if (beforeSpanEnd) {\n        beforeSpanEnd(span);\n      }\n\n      // If the span is non-recording, nothing more to do here...\n      // This is the case if tracing is enabled but this specific span was not sampled\n      if (thisArg instanceof SentryNonRecordingSpan) {\n        return;\n      }\n\n      // Just ensuring that this keeps working, even if we ever have more arguments here\n      const [definedEndTimestamp, ...rest] = args;\n      const timestamp = definedEndTimestamp || timestampInSeconds();\n      const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n      // Ensure we end with the last span timestamp, if possible\n      const spans = getSpanDescendants(span).filter(child =\u003e child !== span);\n\n      const spanJson = spanToJSON(span);\n\n      // If we have no spans, we just end, nothing else to do here\n      // Likewise, if users explicitly ended the span, we simply end the span without timestamp adjustment\n      if (!spans.length || !trimIdleSpanEndTimestamp) {\n        onIdleSpanEnded(spanEndTimestamp);\n        return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n      }\n\n      const ignoreSpans = client.getOptions().ignoreSpans;\n\n      const latestSpanEndTimestamp = spans?.reduce((acc: number | undefined, current) =\u003e {\n        const currentSpanJson = spanToJSON(current);\n        if (!currentSpanJson.timestamp) {\n          return acc;\n        }\n        // Ignored spans will get dropped later (in the client) but since we already adjust\n        // the idle span end timestamp here, we can already take to-be-ignored spans out of\n        // the calculation here.\n        if (ignoreSpans \u0026\u0026 shouldIgnoreSpan(currentSpanJson, ignoreSpans)) {\n          return acc;\n        }\n        return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;\n      }, undefined);\n\n      // In reality this should always exist here, but type-wise it may be undefined...\n      const spanStartTimestamp = spanJson.start_timestamp;\n\n      // The final endTimestamp should:\n      // * Never be before the span start timestamp\n      // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n      // * Otherwise be the passed end timestamp\n      // Final timestamp can never be after finalTimeout\n      const endTimestamp = Math.min(\n        spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n        Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n      );\n\n      onIdleSpanEnded(endTimestamp);\n      return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n    },\n  });\n\n  /**\n   * Cancels the existing idle timeout, if there is one.\n   */\n  function _cancelIdleTimeout(): void {\n    if (_idleTimeoutID) {\n      clearTimeout(_idleTimeoutID);\n      _idleTimeoutID = undefined;\n    }\n  }\n\n  /**\n   * Cancels the existing child span timeout, if there is one.\n   */\n  function _cancelChildSpanTimeout(): void {\n    if (_childSpanTimeoutID) {\n      clearTimeout(_childSpanTimeoutID);\n      _childSpanTimeoutID = undefined;\n    }\n  }\n\n  /**\n   * Restarts idle timeout, if there is no running idle timeout it will start one.\n   */\n  function _restartIdleTimeout(endTimestamp?: number): void {\n    _cancelIdleTimeout();\n    _idleTimeoutID = setTimeout(() =\u003e {\n      if (!_finished \u0026\u0026 activities.size === 0 \u0026\u0026 _autoFinishAllowed) {\n        _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n        span.end(endTimestamp);\n      }\n    }, idleTimeout);\n  }\n\n  /**\n   * Restarts child span timeout, if there is none running it will start one.\n   */\n  function _restartChildSpanTimeout(endTimestamp?: number): void {\n    _cancelChildSpanTimeout();\n    _idleTimeoutID = setTimeout(() =\u003e {\n      if (!_finished \u0026\u0026 _autoFinishAllowed) {\n        _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n        span.end(endTimestamp);\n      }\n    }, childSpanTimeout);\n  }\n\n  /**\n   * Start tracking a specific activity.\n   * @param spanId The span id that represents the activity\n   */\n  function _pushActivity(spanId: string): void {\n    _cancelIdleTimeout();\n    activities.set(spanId, true);\n\n    const endTimestamp = timestampInSeconds();\n    // We need to add the timeout here to have the real endtimestamp of the idle span\n    // Remember timestampInSeconds is in seconds, timeout is in ms\n    _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n  }\n\n  /**\n   * Remove an activity from usage\n   * @param spanId The span id that represents the activity\n   */\n  function _popActivity(spanId: string): void {\n    if (activities.has(spanId)) {\n      activities.delete(spanId);\n    }\n\n    if (activities.size === 0) {\n      const endTimestamp = timestampInSeconds();\n      // We need to add the timeout here to have the real endtimestamp of the idle span\n      // Remember timestampInSeconds is in seconds, timeout is in ms\n      _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n      _cancelChildSpanTimeout();\n    }\n  }\n\n  function onIdleSpanEnded(endTimestamp: number): void {\n    _finished = true;\n    activities.clear();\n\n    _cleanupHooks.forEach(cleanup =\u003e cleanup());\n\n    _setSpanForScope(scope, previousActiveSpan);\n\n    const spanJSON = spanToJSON(span);\n\n    const { start_timestamp: startTimestamp } = spanJSON;\n    // This should never happen, but to make TS happy...\n    if (!startTimestamp) {\n      return;\n    }\n\n    const attributes = spanJSON.data;\n    if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n      span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n    }\n\n    // Set span status to 'ok' if it hasn't been explicitly set to an error status\n    const currentStatus = spanJSON.status;\n    if (!currentStatus || currentStatus === 'unknown') {\n      span.setStatus({ code: SPAN_STATUS_OK });\n    }\n\n    debug.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n    const childSpans = getSpanDescendants(span).filter(child =\u003e child !== span);\n\n    let discardedSpans = 0;\n    childSpans.forEach(childSpan =\u003e {\n      // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n      if (childSpan.isRecording()) {\n        childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n        childSpan.end(endTimestamp);\n        DEBUG_BUILD \u0026\u0026\n          debug.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n      }\n\n      const childSpanJSON = spanToJSON(childSpan);\n      const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n      const spanStartedBeforeIdleSpanEnd = childStartTimestamp \u003c= endTimestamp;\n\n      // Add a delta with idle timeout so that we prevent false positives\n      const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n      const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp \u003c= timeoutWithMarginOfError;\n\n      if (DEBUG_BUILD) {\n        const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n        if (!spanStartedBeforeIdleSpanEnd) {\n          debug.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n        } else if (!spanEndedBeforeFinalTimeout) {\n          debug.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n        }\n      }\n\n      if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n        removeChildSpanFromSpan(span, childSpan);\n        discardedSpans++;\n      }\n    });\n\n    if (discardedSpans \u003e 0) {\n      span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n    }\n  }\n\n  _cleanupHooks.push(\n    client.on('spanStart', startedSpan =\u003e {\n      // If we already finished the idle span,\n      // or if this is the idle span itself being started,\n      // or if the started span has already been closed,\n      // we don't care about it for activity\n      if (\n        _finished ||\n        startedSpan === span ||\n        !!spanToJSON(startedSpan).timestamp ||\n        (startedSpan instanceof SentrySpan \u0026\u0026 startedSpan.isStandaloneSpan())\n      ) {\n        return;\n      }\n\n      const allSpans = getSpanDescendants(span);\n\n      // If the span that was just started is a child of the idle span, we should track it\n      if (allSpans.includes(startedSpan)) {\n        _pushActivity(startedSpan.spanContext().spanId);\n      }\n    }),\n  );\n\n  _cleanupHooks.push(\n    client.on('spanEnd', endedSpan =\u003e {\n      if (_finished) {\n        return;\n      }\n\n      _popActivity(endedSpan.spanContext().spanId);\n    }),\n  );\n\n  _cleanupHooks.push(\n    client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish =\u003e {\n      if (spanToAllowAutoFinish === span) {\n        _autoFinishAllowed = true;\n        _restartIdleTimeout();\n\n        if (activities.size) {\n          _restartChildSpanTimeout();\n        }\n      }\n    }),\n  );\n\n  // We only start the initial idle timeout if we are not delaying the auto finish\n  if (!options.disableAutoFinish) {\n    _restartIdleTimeout();\n  }\n\n  setTimeout(() =\u003e {\n    if (!_finished) {\n      span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n      _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n      span.end();\n    }\n  }, finalTimeout);\n\n  return span;\n}\n\nfunction _startIdleSpan(options: StartSpanOptions): Span {\n  const span = startInactiveSpan(options);\n\n  _setSpanForScope(getCurrentScope(), span);\n\n  DEBUG_BUILD \u0026\u0026 debug.log('[Tracing] Started span is an idle span');\n\n  return span;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst STATE_PENDING = 0;\nconst STATE_RESOLVED = 1;\nconst STATE_REJECTED = 2;\n\ntype State = typeof STATE_PENDING | typeof STATE_RESOLVED | typeof STATE_REJECTED;\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike\u003cvoid\u003e;\nexport function resolvedSyncPromise\u003cT\u003e(value: T | PromiseLike\u003cT\u003e): PromiseLike\u003cT\u003e;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise\u003cT\u003e(value?: T | PromiseLike\u003cT\u003e): PromiseLike\u003cT\u003e {\n  return new SyncPromise(resolve =\u003e {\n    resolve(value);\n  });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise\u003cT = never\u003e(reason?: any): PromiseLike\u003cT\u003e {\n  return new SyncPromise((_, reject) =\u003e {\n    reject(reason);\n  });\n}\n\ntype Executor\u003cT\u003e = (resolve: (value?: T | PromiseLike\u003cT\u003e | null) =\u003e void, reject: (reason?: any) =\u003e void) =\u003e void;\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nexport class SyncPromise\u003cT\u003e implements PromiseLike\u003cT\u003e {\n  private _state: State;\n  private _handlers: Array\u003c[boolean, (value: T) =\u003e void, (reason: any) =\u003e any]\u003e;\n  private _value: any;\n\n  public constructor(executor: Executor\u003cT\u003e) {\n    this._state = STATE_PENDING;\n    this._handlers = [];\n\n    this._runExecutor(executor);\n  }\n\n  /** @inheritdoc */\n  public then\u003cTResult1 = T, TResult2 = never\u003e(\n    onfulfilled?: ((value: T) =\u003e TResult1 | PromiseLike\u003cTResult1\u003e) | null,\n    onrejected?: ((reason: any) =\u003e TResult2 | PromiseLike\u003cTResult2\u003e) | null,\n  ): PromiseLike\u003cTResult1 | TResult2\u003e {\n    return new SyncPromise((resolve, reject) =\u003e {\n      this._handlers.push([\n        false,\n        result =\u003e {\n          if (!onfulfilled) {\n            // TODO: ¯\\_(ツ)_/¯\n            // TODO: FIXME\n            resolve(result as any);\n          } else {\n            try {\n              resolve(onfulfilled(result));\n            } catch (e) {\n              reject(e);\n            }\n          }\n        },\n        reason =\u003e {\n          if (!onrejected) {\n            reject(reason);\n          } else {\n            try {\n              resolve(onrejected(reason));\n            } catch (e) {\n              reject(e);\n            }\n          }\n        },\n      ]);\n      this._executeHandlers();\n    });\n  }\n\n  /** @inheritdoc */\n  public catch\u003cTResult = never\u003e(\n    onrejected?: ((reason: any) =\u003e TResult | PromiseLike\u003cTResult\u003e) | null,\n  ): PromiseLike\u003cT | TResult\u003e {\n    return this.then(val =\u003e val, onrejected);\n  }\n\n  /** @inheritdoc */\n  public finally\u003cTResult\u003e(onfinally?: (() =\u003e void) | null): PromiseLike\u003cTResult\u003e {\n    return new SyncPromise\u003cTResult\u003e((resolve, reject) =\u003e {\n      let val: TResult | any;\n      let isRejected: boolean;\n\n      return this.then(\n        value =\u003e {\n          isRejected = false;\n          val = value;\n          if (onfinally) {\n            onfinally();\n          }\n        },\n        reason =\u003e {\n          isRejected = true;\n          val = reason;\n          if (onfinally) {\n            onfinally();\n          }\n        },\n      ).then(() =\u003e {\n        if (isRejected) {\n          reject(val);\n          return;\n        }\n\n        resolve(val as unknown as any);\n      });\n    });\n  }\n\n  /** Excute the resolve/reject handlers. */\n  private _executeHandlers(): void {\n    if (this._state === STATE_PENDING) {\n      return;\n    }\n\n    const cachedHandlers = this._handlers.slice();\n    this._handlers = [];\n\n    cachedHandlers.forEach(handler =\u003e {\n      if (handler[0]) {\n        return;\n      }\n\n      if (this._state === STATE_RESOLVED) {\n        handler[1](this._value as unknown as any);\n      }\n\n      if (this._state === STATE_REJECTED) {\n        handler[2](this._value);\n      }\n\n      handler[0] = true;\n    });\n  }\n\n  /** Run the executor for the SyncPromise. */\n  private _runExecutor(executor: Executor\u003cT\u003e): void {\n    const setResult = (state: State, value?: T | PromiseLike\u003cT\u003e | any): void =\u003e {\n      if (this._state !== STATE_PENDING) {\n        return;\n      }\n\n      if (isThenable(value)) {\n        void (value as PromiseLike\u003cT\u003e).then(resolve, reject);\n        return;\n      }\n\n      this._state = state;\n      this._value = value;\n\n      this._executeHandlers();\n    };\n\n    const resolve = (value: unknown): void =\u003e {\n      setResult(STATE_RESOLVED, value);\n    };\n\n    const reject = (reason: unknown): void =\u003e {\n      setResult(STATE_REJECTED, reason);\n    };\n\n    try {\n      executor(resolve, reject);\n    } catch (e) {\n      reject(e);\n    }\n  }\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport { debug } from './utils/debug-logger';\nimport { isThenable } from './utils/is';\nimport { rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise';\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n  processors: EventProcessor[],\n  event: Event | null,\n  hint: EventHint,\n  index: number = 0,\n): PromiseLike\u003cEvent | null\u003e {\n  try {\n    const result = _notifyEventProcessors(event, hint, processors, index);\n    return isThenable(result) ? result : resolvedSyncPromise(result);\n  } catch (error) {\n    return rejectedSyncPromise(error);\n  }\n}\n\nfunction _notifyEventProcessors(\n  event: Event | null,\n  hint: EventHint,\n  processors: EventProcessor[],\n  index: number,\n): Event | null | PromiseLike\u003cEvent | null\u003e {\n  const processor = processors[index];\n\n  if (!event || !processor) {\n    return event;\n  }\n\n  const result = processor({ ...event }, hint);\n\n  DEBUG_BUILD \u0026\u0026 result === null \u0026\u0026 debug.log(`Event processor \"${processor.id || '?'}\" dropped event`);\n\n  if (isThenable(result)) {\n    return result.then(final =\u003e _notifyEventProcessors(final, hint, processors, index + 1));\n  }\n\n  return _notifyEventProcessors(result, hint, processors, index + 1);\n}\n","import type { DebugImage } from '../types-hoist/debugMeta';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { normalizeStackTracePath } from './stacktrace';\nimport { GLOBAL_OBJ } from './worldwide';\n\ntype StackString = string;\ntype CachedResult = [string, string];\n\nlet parsedStackResults: Record\u003cStackString, CachedResult\u003e | undefined;\nlet lastSentryKeysCount: number | undefined;\nlet lastNativeKeysCount: number | undefined;\nlet cachedFilenameDebugIds: Record\u003cstring, string\u003e | undefined;\n\n/**\n * Clears the cached debug ID mappings.\n * Useful for testing or when the global debug ID state changes.\n */\nexport function clearDebugIdCache(): void {\n  parsedStackResults = undefined;\n  lastSentryKeysCount = undefined;\n  lastNativeKeysCount = undefined;\n  cachedFilenameDebugIds = undefined;\n}\n\n/**\n * Returns a map of filenames to debug identifiers.\n * Supports both proprietary _sentryDebugIds and native _debugIds (e.g., from Vercel) formats.\n */\nexport function getFilenameToDebugIdMap(stackParser: StackParser): Record\u003cstring, string\u003e {\n  const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds;\n  const nativeDebugIdMap = GLOBAL_OBJ._debugIds;\n\n  if (!sentryDebugIdMap \u0026\u0026 !nativeDebugIdMap) {\n    return {};\n  }\n\n  const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : [];\n  const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : [];\n\n  // If the count of registered globals hasn't changed since the last call, we\n  // can just return the cached result.\n  if (\n    cachedFilenameDebugIds \u0026\u0026\n    sentryDebugIdKeys.length === lastSentryKeysCount \u0026\u0026\n    nativeDebugIdKeys.length === lastNativeKeysCount\n  ) {\n    return cachedFilenameDebugIds;\n  }\n\n  lastSentryKeysCount = sentryDebugIdKeys.length;\n  lastNativeKeysCount = nativeDebugIdKeys.length;\n\n  // Build a map of filename -\u003e debug_id from both sources\n  cachedFilenameDebugIds = {};\n\n  if (!parsedStackResults) {\n    parsedStackResults = {};\n  }\n\n  const processDebugIds = (debugIdKeys: string[], debugIdMap: Record\u003cstring, string\u003e): void =\u003e {\n    for (const key of debugIdKeys) {\n      const debugId = debugIdMap[key];\n      const result = parsedStackResults?.[key];\n\n      if (result \u0026\u0026 cachedFilenameDebugIds \u0026\u0026 debugId) {\n        // Use cached filename but update with current debug ID\n        cachedFilenameDebugIds[result[0]] = debugId;\n        // Update cached result with new debug ID\n        if (parsedStackResults) {\n          parsedStackResults[key] = [result[0], debugId];\n        }\n      } else if (debugId) {\n        const parsedStack = stackParser(key);\n\n        for (let i = parsedStack.length - 1; i \u003e= 0; i--) {\n          const stackFrame = parsedStack[i];\n          const filename = stackFrame?.filename;\n\n          if (filename \u0026\u0026 cachedFilenameDebugIds \u0026\u0026 parsedStackResults) {\n            cachedFilenameDebugIds[filename] = debugId;\n            parsedStackResults[key] = [filename, debugId];\n            break;\n          }\n        }\n      }\n    }\n  };\n\n  if (sentryDebugIdMap) {\n    processDebugIds(sentryDebugIdKeys, sentryDebugIdMap);\n  }\n\n  // Native _debugIds will override _sentryDebugIds if same file\n  if (nativeDebugIdMap) {\n    processDebugIds(nativeDebugIdKeys, nativeDebugIdMap);\n  }\n\n  return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nexport function getDebugImagesForResources(\n  stackParser: StackParser,\n  resource_paths: ReadonlyArray\u003cstring\u003e,\n): DebugImage[] {\n  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n  if (!filenameDebugIdMap) {\n    return [];\n  }\n\n  const images: DebugImage[] = [];\n  for (const path of resource_paths) {\n    const normalizedPath = normalizeStackTracePath(path);\n    if (normalizedPath \u0026\u0026 filenameDebugIdMap[normalizedPath]) {\n      images.push({\n        type: 'sourcemap',\n        code_file: path,\n        debug_id: filenameDebugIdMap[normalizedPath],\n      });\n    }\n  }\n\n  return images;\n}\n","import { getGlobalScope } from '../currentScopes';\nimport type { Scope, ScopeData } from '../scope';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport type { Breadcrumb } from '../types-hoist/breadcrumb';\nimport type { Event } from '../types-hoist/event';\nimport type { Span } from '../types-hoist/span';\nimport { merge } from './merge';\nimport { getRootSpan, spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n  const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n  // Apply general data\n  applyDataToEvent(event, data);\n\n  // We want to set the trace context for normal events only if there isn't already\n  // a trace context on the event. There is a product feature in place where we link\n  // errors with transaction and it relies on that.\n  if (span) {\n    applySpanToEvent(event, span);\n  }\n\n  applyFingerprintToEvent(event, fingerprint);\n  applyBreadcrumbsToEvent(event, breadcrumbs);\n  applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n  const {\n    extra,\n    tags,\n    attributes,\n    user,\n    contexts,\n    level,\n    sdkProcessingMetadata,\n    breadcrumbs,\n    fingerprint,\n    eventProcessors,\n    attachments,\n    propagationContext,\n    transactionName,\n    span,\n  } = mergeData;\n\n  mergeAndOverwriteScopeData(data, 'extra', extra);\n  mergeAndOverwriteScopeData(data, 'tags', tags);\n  mergeAndOverwriteScopeData(data, 'attributes', attributes);\n  mergeAndOverwriteScopeData(data, 'user', user);\n  mergeAndOverwriteScopeData(data, 'contexts', contexts);\n\n  data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n\n  if (level) {\n    data.level = level;\n  }\n\n  if (transactionName) {\n    data.transactionName = transactionName;\n  }\n\n  if (span) {\n    data.span = span;\n  }\n\n  if (breadcrumbs.length) {\n    data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n  }\n\n  if (fingerprint.length) {\n    data.fingerprint = [...data.fingerprint, ...fingerprint];\n  }\n\n  if (eventProcessors.length) {\n    data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n  }\n\n  if (attachments.length) {\n    data.attachments = [...data.attachments, ...attachments];\n  }\n\n  data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData\u003c\n  Prop extends 'extra' | 'tags' | 'attributes' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n  Data extends ScopeData,\n\u003e(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n  data[prop] = merge(data[prop], mergeVal, 1);\n}\n\n/** Exported only for tests */\nexport function mergeArray\u003cProp extends 'breadcrumbs' | 'fingerprint'\u003e(\n  event: Event,\n  prop: Prop,\n  mergeVal: ScopeData[Prop],\n): void {\n  const prevVal = event[prop];\n  // If we are not merging any new values,\n  // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n  if (!mergeVal.length \u0026\u0026 (!prevVal || prevVal.length)) {\n    return;\n  }\n\n  const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n  event[prop] = merged.length ? merged : undefined;\n}\n\n/**\n * Get the scope data for the current scope after merging with the\n * global scope and isolation scope.\n *\n * @param currentScope - The current scope.\n * @returns The scope data.\n */\nexport function getCombinedScopeData(isolationScope: Scope | undefined, currentScope: Scope | undefined): ScopeData {\n  const scopeData = getGlobalScope().getScopeData();\n  isolationScope \u0026\u0026 mergeScopeData(scopeData, isolationScope.getScopeData());\n  currentScope \u0026\u0026 mergeScopeData(scopeData, currentScope.getScopeData());\n  return scopeData;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n  const { extra, tags, user, contexts, level, transactionName } = data;\n\n  if (Object.keys(extra).length) {\n    event.extra = { ...extra, ...event.extra };\n  }\n\n  if (Object.keys(tags).length) {\n    event.tags = { ...tags, ...event.tags };\n  }\n\n  if (Object.keys(user).length) {\n    event.user = { ...user, ...event.user };\n  }\n\n  if (Object.keys(contexts).length) {\n    event.contexts = { ...contexts, ...event.contexts };\n  }\n\n  if (level) {\n    event.level = level;\n  }\n\n  // transaction events get their `transaction` from the root span name\n  if (transactionName \u0026\u0026 event.type !== 'transaction') {\n    event.transaction = transactionName;\n  }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n  const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n  event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n  event.sdkProcessingMetadata = {\n    ...event.sdkProcessingMetadata,\n    ...sdkProcessingMetadata,\n  };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n  event.contexts = {\n    trace: spanToTraceContext(span),\n    ...event.contexts,\n  };\n\n  event.sdkProcessingMetadata = {\n    dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n    ...event.sdkProcessingMetadata,\n  };\n\n  const rootSpan = getRootSpan(span);\n  const transactionName = spanToJSON(rootSpan).description;\n  if (transactionName \u0026\u0026 !event.transaction \u0026\u0026 event.type === 'transaction') {\n    event.transaction = transactionName;\n  }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n  // Make sure it's an array first and we actually have something in place\n  event.fingerprint = event.fingerprint\n    ? Array.isArray(event.fingerprint)\n      ? event.fingerprint\n      : [event.fingerprint]\n    : [];\n\n  // If we have something on the scope, then merge it with event\n  if (fingerprint) {\n    event.fingerprint = event.fingerprint.concat(fingerprint);\n  }\n\n  // If we have no data at all, remove empty array default\n  if (!event.fingerprint.length) {\n    delete event.fingerprint;\n  }\n}\n","import type { Client } from '../client';\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { notifyEventProcessors } from '../eventProcessors';\nimport type { CaptureContext, ScopeContext } from '../scope';\nimport { Scope } from '../scope';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { ClientOptions } from '../types-hoist/options';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { getFilenameToDebugIdMap } from './debug-ids';\nimport { addExceptionMechanism, uuid4 } from './misc';\nimport { normalize } from './normalize';\nimport { applyScopeDataToEvent, getCombinedScopeData } from './scopeData';\nimport { truncate } from './string';\nimport { resolvedSyncPromise } from './syncpromise';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n  | (CaptureContext \u0026 Partial\u003c{ [key in keyof EventHint]: never }\u003e)\n  | (EventHint \u0026 Partial\u003c{ [key in keyof ScopeContext]: never }\u003e);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n  options: ClientOptions,\n  event: Event,\n  hint: EventHint,\n  scope?: Scope,\n  client?: Client,\n  isolationScope?: Scope,\n): PromiseLike\u003cEvent | null\u003e {\n  const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n  const prepared: Event = {\n    ...event,\n    event_id: event.event_id || hint.event_id || uuid4(),\n    timestamp: event.timestamp || dateTimestampInSeconds(),\n  };\n  const integrations = hint.integrations || options.integrations.map(i =\u003e i.name);\n\n  applyClientOptions(prepared, options);\n  applyIntegrationsMetadata(prepared, integrations);\n\n  if (client) {\n    client.emit('applyFrameMetadata', event);\n  }\n\n  // Only put debug IDs onto frames for error events.\n  if (event.type === undefined) {\n    applyDebugIds(prepared, options.stackParser);\n  }\n\n  // If we have scope given to us, use it as the base for further modifications.\n  // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n  const finalScope = getFinalScope(scope, hint.captureContext);\n\n  if (hint.mechanism) {\n    addExceptionMechanism(prepared, hint.mechanism);\n  }\n\n  const clientEventProcessors = client ? client.getEventProcessors() : [];\n\n  // This should be the last thing called, since we want that\n  // {@link Scope.addEventProcessor} gets the finished prepared event.\n  // Merge scope data together\n  const data = getCombinedScopeData(isolationScope, finalScope);\n\n  const attachments = [...(hint.attachments || []), ...data.attachments];\n  if (attachments.length) {\n    hint.attachments = attachments;\n  }\n\n  applyScopeDataToEvent(prepared, data);\n\n  const eventProcessors = [\n    ...clientEventProcessors,\n    // Run scope event processors _after_ all other processors\n    ...data.eventProcessors,\n  ];\n\n  // Skip event processors for internal exceptions to prevent recursion\n  // oxlint-disable-next-line typescript/prefer-optional-chain\n  const isInternalException = hint.data \u0026\u0026 (hint.data as { __sentry__: boolean }).__sentry__ === true;\n  const result = isInternalException\n    ? resolvedSyncPromise(prepared)\n    : notifyEventProcessors(eventProcessors, prepared, hint);\n\n  return result.then(evt =\u003e {\n    if (evt) {\n      // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n      // file names (e.g.the RewriteFrames integration) the filename -\u003e debug ID relationship isn't destroyed.\n      // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n      // any new data\n      applyDebugMeta(evt);\n    }\n\n    if (typeof normalizeDepth === 'number' \u0026\u0026 normalizeDepth \u003e 0) {\n      return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n    }\n    return evt;\n  });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n *\n * Only exported for tests.\n *\n * @param event event instance to be enhanced\n */\nexport function applyClientOptions(event: Event, options: ClientOptions): void {\n  const { environment, release, dist, maxValueLength } = options;\n\n  // empty strings do not make sense for environment, release, and dist\n  // so we handle them the same as if they were not provided\n  event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n\n  if (!event.release \u0026\u0026 release) {\n    event.release = release;\n  }\n\n  if (!event.dist \u0026\u0026 dist) {\n    event.dist = dist;\n  }\n\n  const request = event.request;\n  if (request?.url \u0026\u0026 maxValueLength) {\n    request.url = truncate(request.url, maxValueLength);\n  }\n\n  if (maxValueLength) {\n    event.exception?.values?.forEach(exception =\u003e {\n      if (exception.value) {\n        // Truncates error messages\n        exception.value = truncate(exception.value, maxValueLength);\n      }\n    });\n  }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n  // Build a map of filename -\u003e debug_id\n  const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n  event.exception?.values?.forEach(exception =\u003e {\n    exception.stacktrace?.frames?.forEach(frame =\u003e {\n      if (frame.filename) {\n        frame.debug_id = filenameDebugIdMap[frame.filename];\n      }\n    });\n  });\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n  // Extract debug IDs and filenames from the stack frames on the event.\n  const filenameDebugIdMap: Record\u003cstring, string\u003e = {};\n  event.exception?.values?.forEach(exception =\u003e {\n    exception.stacktrace?.frames?.forEach(frame =\u003e {\n      if (frame.debug_id) {\n        if (frame.abs_path) {\n          filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n        } else if (frame.filename) {\n          filenameDebugIdMap[frame.filename] = frame.debug_id;\n        }\n        delete frame.debug_id;\n      }\n    });\n  });\n\n  if (Object.keys(filenameDebugIdMap).length === 0) {\n    return;\n  }\n\n  // Fill debug_meta information\n  event.debug_meta = event.debug_meta || {};\n  event.debug_meta.images = event.debug_meta.images || [];\n  const images = event.debug_meta.images;\n  Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) =\u003e {\n    images.push({\n      type: 'sourcemap',\n      code_file: filename,\n      debug_id,\n    });\n  });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n  if (integrationNames.length \u003e 0) {\n    event.sdk = event.sdk || {};\n    event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n  }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n  if (!event) {\n    return null;\n  }\n\n  const normalized: Event = {\n    ...event,\n    ...(event.breadcrumbs \u0026\u0026 {\n      breadcrumbs: event.breadcrumbs.map(b =\u003e ({\n        ...b,\n        ...(b.data \u0026\u0026 {\n          data: normalize(b.data, depth, maxBreadth),\n        }),\n      })),\n    }),\n    ...(event.user \u0026\u0026 {\n      user: normalize(event.user, depth, maxBreadth),\n    }),\n    ...(event.contexts \u0026\u0026 {\n      contexts: normalize(event.contexts, depth, maxBreadth),\n    }),\n    ...(event.extra \u0026\u0026 {\n      extra: normalize(event.extra, depth, maxBreadth),\n    }),\n  };\n\n  // event.contexts.trace stores information about a Transaction. Similarly,\n  // event.spans[] stores information about child Spans. Given that a\n  // Transaction is conceptually a Span, normalization should apply to both\n  // Transactions and Spans consistently.\n  // For now the decision is to skip normalization of Transactions and Spans,\n  // so this block overwrites the normalized event to add back the original\n  // Transaction information prior to normalization.\n  if (event.contexts?.trace \u0026\u0026 normalized.contexts) {\n    normalized.contexts.trace = event.contexts.trace;\n\n    // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n    if (event.contexts.trace.data) {\n      normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n    }\n  }\n\n  // event.spans[].data may contain circular/dangerous data so we need to normalize it\n  if (event.spans) {\n    normalized.spans = event.spans.map(span =\u003e {\n      return {\n        ...span,\n        ...(span.data \u0026\u0026 {\n          data: normalize(span.data, depth, maxBreadth),\n        }),\n      };\n    });\n  }\n\n  // event.contexts.flags (FeatureFlagContext) stores context for our feature\n  // flag integrations. It has a greater nesting depth than our other typed\n  // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want\n  // to skip this in case of conflicting, user-provided context.\n  if (event.contexts?.flags \u0026\u0026 normalized.contexts) {\n    normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n  }\n\n  return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n  if (!captureContext) {\n    return scope;\n  }\n\n  const finalScope = scope ? scope.clone() : new Scope();\n  finalScope.update(captureContext);\n  return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n  hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n  if (!hint) {\n    return undefined;\n  }\n\n  // If you pass a Scope or `() =\u003e Scope` as CaptureContext, we just return this as captureContext\n  if (hintIsScopeOrFunction(hint)) {\n    return { captureContext: hint };\n  }\n\n  if (hintIsScopeContext(hint)) {\n    return {\n      captureContext: hint,\n    };\n  }\n\n  return hint;\n}\n\nfunction hintIsScopeOrFunction(hint: CaptureContext | EventHint): hint is Scope | ((scope: Scope) =\u003e Scope) {\n  return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n  'user',\n  'level',\n  'extra',\n  'contexts',\n  'tags',\n  'fingerprint',\n  'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial\u003cScopeContext\u003e | EventHint): hint is Partial\u003cScopeContext\u003e {\n  return Object.keys(hint).some(key =\u003e captureContextKeys.includes(key as ScopeContextProperty));\n}\n","import { getClient, getCurrentScope, getIsolationScope, withIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { CaptureContext } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { startNewTrace } from './tracing/trace';\nimport type { CheckIn, FinishedCheckIn, MonitorConfig } from './types-hoist/checkin';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { Extra, Extras } from './types-hoist/extra';\nimport type { Primitive } from './types-hoist/misc';\nimport type { Session, SessionContext } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { User } from './types-hoist/user';\nimport { debug } from './utils/debug-logger';\nimport { isThenable } from './utils/is';\nimport { uuid4 } from './utils/misc';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { getCombinedScopeData } from './utils/scopeData';\nimport { timestampInSeconds } from './utils/time';\nimport { GLOBAL_OBJ } from './utils/worldwide';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(exception: unknown, hint?: ExclusiveEventHintOrCaptureContext): string {\n  return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | SeverityLevel): string {\n  // This is necessary to provide explicit scopes upgrade, without changing the original\n  // arity of the `captureMessage(message, level)` method.\n  const level = typeof captureContext === 'string' ? captureContext : undefined;\n  const hint = typeof captureContext !== 'string' ? { captureContext } : undefined;\n  return getCurrentScope().captureMessage(message, level, hint);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n  return getCurrentScope().captureEvent(event, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\nexport function setContext(name: string, context: { [key: string]: unknown } | null): void {\n  getIsolationScope().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): void {\n  getIsolationScope().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): void {\n  getIsolationScope().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n  getIsolationScope().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): void {\n  getIsolationScope().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): void {\n  getIsolationScope().setUser(user);\n}\n\n/**\n * Sets the conversation ID for the current isolation scope.\n *\n * @param conversationId The conversation ID to set. Pass `null` or `undefined` to unset the conversation ID.\n */\nexport function setConversationId(conversationId: string | null | undefined): void {\n  getIsolationScope().setConversationId(conversationId);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nexport function lastEventId(): string | undefined {\n  return getIsolationScope().lastEventId();\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n  const scope = getCurrentScope();\n  const client = getClient();\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('Cannot capture check-in. No client defined.');\n  } else if (!client.captureCheckIn) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('Cannot capture check-in. Client does not support sending check-ins.');\n  } else {\n    return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n  }\n\n  return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param callback Callback to be monitored\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor\u003cT\u003e(\n  monitorSlug: CheckIn['monitorSlug'],\n  callback: () =\u003e T,\n  upsertMonitorConfig?: MonitorConfig,\n): T {\n  function runCallback(): T {\n    const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n    const now = timestampInSeconds();\n\n    function finishCheckIn(status: FinishedCheckIn['status']): void {\n      captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n    }\n    // Default behavior without isolateTrace\n    let maybePromiseResult: T;\n    try {\n      maybePromiseResult = callback();\n    } catch (e) {\n      finishCheckIn('error');\n      throw e;\n    }\n\n    if (isThenable(maybePromiseResult)) {\n      return maybePromiseResult.then(\n        r =\u003e {\n          finishCheckIn('ok');\n          return r;\n        },\n        e =\u003e {\n          finishCheckIn('error');\n          throw e;\n        },\n      ) as T;\n    }\n    finishCheckIn('ok');\n\n    return maybePromiseResult;\n  }\n\n  return withIsolationScope(() =\u003e (upsertMonitorConfig?.isolateTrace ? startNewTrace(runCallback) : runCallback()));\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise\u003cboolean\u003e {\n  const client = getClient();\n  if (client) {\n    return client.flush(timeout);\n  }\n  DEBUG_BUILD \u0026\u0026 debug.warn('Cannot flush events. No client defined.');\n  return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise\u003cboolean\u003e {\n  const client = getClient();\n  if (client) {\n    return client.close(timeout);\n  }\n  DEBUG_BUILD \u0026\u0026 debug.warn('Cannot flush events and disable SDK. No client defined.');\n  return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n  return !!getClient();\n}\n\n/** If the SDK is initialized \u0026 enabled. */\nexport function isEnabled(): boolean {\n  const client = getClient();\n  return client?.getOptions().enabled !== false \u0026\u0026 !!client?.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n  getIsolationScope().addEventProcessor(callback);\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n  const isolationScope = getIsolationScope();\n\n  const { user } = getCombinedScopeData(isolationScope, getCurrentScope());\n\n  // Will fetch userAgent if called from browser sdk\n  const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n  const session = makeSession({\n    user,\n    ...(userAgent \u0026\u0026 { userAgent }),\n    ...context,\n  });\n\n  // End existing session if there's one\n  const currentSession = isolationScope.getSession();\n  if (currentSession?.status === 'ok') {\n    updateSession(currentSession, { status: 'exited' });\n  }\n\n  endSession();\n\n  // Afterwards we set the new session on the scope\n  isolationScope.setSession(session);\n\n  return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n  const isolationScope = getIsolationScope();\n  const currentScope = getCurrentScope();\n\n  const session = currentScope.getSession() || isolationScope.getSession();\n  if (session) {\n    closeSession(session);\n  }\n  _sendSessionUpdate();\n\n  // the session is over; take it off of the scope\n  isolationScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n  const isolationScope = getIsolationScope();\n  const client = getClient();\n  const session = isolationScope.getSession();\n  if (session \u0026\u0026 client) {\n    client.captureSession(session);\n  }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n *            Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n  // both send the update and pull the session from the scope\n  if (end) {\n    endSession();\n    return;\n  }\n\n  // only send the update\n  _sendSessionUpdate();\n}\n","import type { ReportDialogOptions } from './report-dialog';\nimport type { DsnComponents, DsnLike } from './types-hoist/dsn';\nimport type { SdkInfo } from './types-hoist/sdkinfo';\nimport { dsnToString, makeDsn } from './utils/dsn';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n  const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n  const port = dsn.port ? `:${dsn.port}` : '';\n  return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n  return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n  const params: Record\u003cstring, string\u003e = {\n    sentry_version: SENTRY_API_VERSION,\n  };\n\n  if (dsn.publicKey) {\n    // We send only the minimum set of required information. See\n    // https://github.com/getsentry/sentry-javascript/issues/2572.\n    params.sentry_key = dsn.publicKey;\n  }\n\n  if (sdkInfo) {\n    params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n  }\n\n  return new URLSearchParams(params).toString();\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(dsn: DsnComponents, tunnel?: string, sdkInfo?: SdkInfo): string {\n  return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(dsnLike: DsnLike, dialogOptions: ReportDialogOptions): string {\n  const dsn = makeDsn(dsnLike);\n  if (!dsn) {\n    return '';\n  }\n\n  const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n  let encodedOptions = `dsn=${dsnToString(dsn)}`;\n  for (const key in dialogOptions) {\n    if (key === 'dsn') {\n      continue;\n    }\n\n    if (key === 'onClose') {\n      continue;\n    }\n\n    if (key === 'user') {\n      const user = dialogOptions.user;\n      if (!user) {\n        continue;\n      }\n      if (user.name) {\n        encodedOptions += `\u0026name=${encodeURIComponent(user.name)}`;\n      }\n      if (user.email) {\n        encodedOptions += `\u0026email=${encodeURIComponent(user.email)}`;\n      }\n    } else {\n      encodedOptions += `\u0026${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n    }\n  }\n\n  return `${endpoint}?${encodedOptions}`;\n}\n","import type { Client } from './client';\nimport { getClient } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { Integration, IntegrationFn } from './types-hoist/integration';\nimport type { CoreOptions } from './types-hoist/options';\nimport { debug } from './utils/debug-logger';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n  [key: string]: Integration;\n};\n\ntype IntegrationWithDefaultInstance = Integration \u0026 { isDefaultInstance?: true };\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n  const integrationsByName: { [key: string]: Integration } = {};\n\n  integrations.forEach((currentInstance: IntegrationWithDefaultInstance) =\u003e {\n    const { name } = currentInstance;\n\n    const existingInstance: IntegrationWithDefaultInstance | undefined = integrationsByName[name];\n\n    // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n    // default instance to overwrite an existing user instance\n    if (existingInstance \u0026\u0026 !existingInstance.isDefaultInstance \u0026\u0026 currentInstance.isDefaultInstance) {\n      return;\n    }\n\n    integrationsByName[name] = currentInstance;\n  });\n\n  return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(\n  options: Pick\u003cCoreOptions, 'defaultIntegrations' | 'integrations'\u003e,\n): Integration[] {\n  const defaultIntegrations = options.defaultIntegrations || [];\n  const userIntegrations = options.integrations;\n\n  // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n  defaultIntegrations.forEach((integration: IntegrationWithDefaultInstance) =\u003e {\n    integration.isDefaultInstance = true;\n  });\n\n  let integrations: Integration[];\n\n  if (Array.isArray(userIntegrations)) {\n    integrations = [...defaultIntegrations, ...userIntegrations];\n  } else if (typeof userIntegrations === 'function') {\n    const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n    integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n  } else {\n    integrations = defaultIntegrations;\n  }\n\n  return filterDuplicates(integrations);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(client: Client, integrations: Integration[]): IntegrationIndex {\n  const integrationIndex: IntegrationIndex = {};\n\n  integrations.forEach((integration: Integration | undefined) =\u003e {\n    // guard against empty provided integrations\n    if (integration) {\n      setupIntegration(client, integration, integrationIndex);\n    }\n  });\n\n  return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nexport function afterSetupIntegrations(client: Client, integrations: Integration[]): void {\n  for (const integration of integrations) {\n    // guard against empty provided integrations\n    if (integration?.afterAllSetup) {\n      integration.afterAllSetup(client);\n    }\n  }\n}\n\n/** Setup a single integration.  */\nexport function setupIntegration(client: Client, integration: Integration, integrationIndex: IntegrationIndex): void {\n  if (integrationIndex[integration.name]) {\n    DEBUG_BUILD \u0026\u0026 debug.log(`Integration skipped because it was already installed: ${integration.name}`);\n    return;\n  }\n  integrationIndex[integration.name] = integration;\n\n  // `setupOnce` is only called the first time\n  if (!installedIntegrations.includes(integration.name) \u0026\u0026 typeof integration.setupOnce === 'function') {\n    integration.setupOnce();\n    installedIntegrations.push(integration.name);\n  }\n\n  // `setup` is run for each client\n  if (integration.setup \u0026\u0026 typeof integration.setup === 'function') {\n    integration.setup(client);\n  }\n\n  if (typeof integration.preprocessEvent === 'function') {\n    const callback = integration.preprocessEvent.bind(integration) as typeof integration.preprocessEvent;\n    client.on('preprocessEvent', (event, hint) =\u003e callback(event, hint, client));\n  }\n\n  if (typeof integration.processEvent === 'function') {\n    const callback = integration.processEvent.bind(integration) as typeof integration.processEvent;\n\n    const processor = Object.assign((event: Event, hint: EventHint) =\u003e callback(event, hint, client), {\n      id: integration.name,\n    });\n\n    client.addEventProcessor(processor);\n  }\n\n  DEBUG_BUILD \u0026\u0026 debug.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nexport function addIntegration(integration: Integration): void {\n  const client = getClient();\n\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n    return;\n  }\n\n  client.addIntegration(integration);\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nexport function defineIntegration\u003cFn extends IntegrationFn\u003e(fn: Fn): (...args: Parameters\u003cFn\u003e) =\u003e Integration {\n  return fn;\n}\n","import type { DurationUnit, FractionUnit, InformationUnit } from './types-hoist/measurement';\n\nexport type RawAttributes\u003cT\u003e = T \u0026 ValidatedAttributes\u003cT\u003e;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RawAttribute\u003cT\u003e = T extends { value: any } | { unit: any } ? AttributeObject : T;\n\nexport type Attributes = Record\u003cstring, TypedAttributeValue\u003e;\n\nexport type AttributeValueType = string | number | boolean | Array\u003cstring\u003e | Array\u003cnumber\u003e | Array\u003cboolean\u003e;\n\ntype AttributeTypeMap = {\n  string: string;\n  integer: number;\n  double: number;\n  boolean: boolean;\n  'string[]': Array\u003cstring\u003e;\n  'integer[]': Array\u003cnumber\u003e;\n  'double[]': Array\u003cnumber\u003e;\n  'boolean[]': Array\u003cboolean\u003e;\n};\n\n/* Generates a type from the AttributeTypeMap like:\n  | { value: string; type: 'string' }\n  | { value: number; type: 'integer' }\n  | { value: number; type: 'double' }\n */\ntype AttributeUnion = {\n  [K in keyof AttributeTypeMap]: {\n    value: AttributeTypeMap[K];\n    type: K;\n  };\n}[keyof AttributeTypeMap];\n\nexport type TypedAttributeValue = AttributeUnion \u0026 { unit?: AttributeUnit };\n\nexport type AttributeObject = {\n  value: unknown;\n  unit?: AttributeUnit;\n};\n\n// Unfortunately, we loose type safety if we did something like Exclude\u003cMeasurementUnit, string\u003e\n// so therefore we unionize between the three supported unit categories.\ntype AttributeUnit = DurationUnit | InformationUnit | FractionUnit;\n\n/* If an attribute has either a 'value' or 'unit' property, we use the ValidAttributeObject type. */\nexport type ValidatedAttributes\u003cT\u003e = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [K in keyof T]: T[K] extends { value: any } | { unit: any } ? AttributeObject : unknown;\n};\n\n/**\n * Type-guard: The attribute object has the shape the official attribute object (value, type, unit).\n * https://develop.sentry.dev/sdk/telemetry/scopes/#setting-attributes\n */\nexport function isAttributeObject(maybeObj: unknown): maybeObj is AttributeObject {\n  return (\n    typeof maybeObj === 'object' \u0026\u0026\n    maybeObj != null \u0026\u0026\n    !Array.isArray(maybeObj) \u0026\u0026\n    Object.keys(maybeObj).includes('value')\n  );\n}\n\n/**\n * Converts an attribute value to a typed attribute value.\n *\n * For now, we intentionally only support primitive values and attribute objects with primitive values.\n * If @param useFallback is true, we stringify non-primitive values to a string attribute value. Otherwise\n * we return `undefined` for unsupported values.\n *\n * @param value - The value of the passed attribute.\n * @param useFallback - If true, unsupported values will be stringified to a string attribute value.\n *                      Defaults to false. In this case, `undefined` is returned for unsupported values.\n * @returns The typed attribute.\n */\nexport function attributeValueToTypedAttributeValue(\n  rawValue: unknown,\n  useFallback?: boolean | 'skip-undefined',\n): TypedAttributeValue | void {\n  const { value, unit } = isAttributeObject(rawValue) ? rawValue : { value: rawValue, unit: undefined };\n  const attributeValue = getTypedAttributeValue(value);\n  const checkedUnit = unit \u0026\u0026 typeof unit === 'string' ? { unit } : {};\n  if (attributeValue) {\n    return { ...attributeValue, ...checkedUnit };\n  }\n\n  if (!useFallback || (useFallback === 'skip-undefined' \u0026\u0026 value === undefined)) {\n    return;\n  }\n\n  // Fallback: stringify the value\n  // TODO(v11): be smarter here and use String constructor if stringify fails\n  // (this is a breaking change for already existing attribute values)\n  let stringValue = '';\n  try {\n    stringValue = JSON.stringify(value) ?? '';\n  } catch {\n    // Do nothing\n  }\n  return {\n    value: stringValue,\n    type: 'string',\n    ...checkedUnit,\n  };\n}\n\n/**\n * Serializes raw attributes to typed attributes as expected in our envelopes.\n *\n * @param attributes The raw attributes to serialize.\n * @param fallback   If true, unsupported values will be stringified to a string attribute value.\n *                   Defaults to false. In this case, `undefined` is returned for unsupported values.\n *\n * @returns The serialized attributes.\n */\nexport function serializeAttributes\u003cT\u003e(\n  attributes: RawAttributes\u003cT\u003e | undefined,\n  fallback: boolean | 'skip-undefined' = false,\n): Attributes {\n  const serializedAttributes: Attributes = {};\n  for (const [key, value] of Object.entries(attributes ?? {})) {\n    const typedValue = attributeValueToTypedAttributeValue(value, fallback);\n    if (typedValue) {\n      serializedAttributes[key] = typedValue;\n    }\n  }\n  return serializedAttributes;\n}\n\n/**\n * NOTE: We intentionally do not return anything for non-primitive values:\n *  - array support will come in the future but if we stringify arrays now,\n *    sending arrays (unstringified) later will be a subtle breaking change.\n *  - Objects are not supported yet and product support is still TBD.\n *  - We still keep the type signature for TypedAttributeValue wider to avoid a\n *    breaking change once we add support for non-primitive values.\n *  - Once we go back to supporting arrays and stringifying all other values,\n *    we already implemented the serialization logic here:\n *    https://github.com/getsentry/sentry-javascript/pull/18165\n */\nfunction getTypedAttributeValue(value: unknown): TypedAttributeValue | void {\n  const primitiveType =\n    typeof value === 'string'\n      ? 'string'\n      : typeof value === 'boolean'\n        ? 'boolean'\n        : typeof value === 'number' \u0026\u0026 !Number.isNaN(value)\n          ? Number.isInteger(value)\n            ? 'integer'\n            : 'double'\n          : null;\n  if (primitiveType) {\n    // @ts-expect-error - TS complains because {@link TypedAttributeValue} is strictly typed to\n    // avoid setting the wrong `type` on the attribute value.\n    // In this case, getPrimitiveType already does the check but TS doesn't know that.\n    // The \"clean\" alternative is to return an object per `typeof value` case\n    // but that would require more bundle size\n    // Therefore, we ignore it.\n    return { value, type: primitiveType };\n  }\n}\n","const SEQUENCE_ATTR_KEY = 'sentry.timestamp.sequence';\n\nlet _sequenceNumber = 0;\nlet _previousTimestampMs: number | undefined;\n\n/**\n * Returns the `sentry.timestamp.sequence` attribute entry for a serialized telemetry item.\n *\n * The sequence number starts at 0 and increments by 1 for each item captured.\n * It resets to 0 when the current item's integer millisecond timestamp differs\n * from the previous item's integer millisecond timestamp.\n *\n * @param timestampInSeconds - The timestamp of the telemetry item in seconds.\n */\nexport function getSequenceAttribute(timestampInSeconds: number): {\n  key: string;\n  value: { value: number; type: 'integer' };\n} {\n  const nowMs = Math.floor(timestampInSeconds * 1000);\n\n  if (_previousTimestampMs !== undefined \u0026\u0026 nowMs !== _previousTimestampMs) {\n    _sequenceNumber = 0;\n  }\n\n  const value = _sequenceNumber;\n  _sequenceNumber++;\n  _previousTimestampMs = nowMs;\n\n  return {\n    key: SEQUENCE_ATTR_KEY,\n    value: { value, type: 'integer' },\n  };\n}\n\n/**\n * Resets the sequence number state. Only exported for testing purposes.\n */\nexport function _INTERNAL_resetSequenceNumber(): void {\n  _sequenceNumber = 0;\n  _previousTimestampMs = undefined;\n}\n","import type { Client } from '../client';\nimport { getTraceContextFromScope, withScope } from '../currentScopes';\nimport type { Scope } from '../scope';\nimport {\n  getDynamicSamplingContextFromScope,\n  getDynamicSamplingContextFromSpan,\n} from '../tracing/dynamicSamplingContext';\nimport type { TraceContext } from '../types-hoist/context';\nimport type { DynamicSamplingContext } from '../types-hoist/envelope';\nimport { getActiveSpan, spanToTraceContext } from './spanUtils';\n\n/** Extract trace information from scope */\nexport function _getTraceInfoFromScope(\n  client: Client,\n  scope: Scope | undefined,\n): [dynamicSamplingContext: Partial\u003cDynamicSamplingContext\u003e | undefined, traceContext: TraceContext | undefined] {\n  if (!scope) {\n    return [undefined, undefined];\n  }\n\n  return withScope(scope, () =\u003e {\n    const span = getActiveSpan();\n    const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);\n    const dynamicSamplingContext = span\n      ? getDynamicSamplingContextFromSpan(span)\n      : getDynamicSamplingContextFromScope(client, scope);\n    return [dynamicSamplingContext, traceContext];\n  });\n}\n","import type { LogSeverityLevel } from '../types-hoist/log';\n\n/**\n * Maps a log severity level to a log severity number.\n *\n * @see LogSeverityLevel\n */\nexport const SEVERITY_TEXT_TO_SEVERITY_NUMBER: Partial\u003cRecord\u003cLogSeverityLevel, number\u003e\u003e = {\n  trace: 1,\n  debug: 5,\n  info: 9,\n  warn: 13,\n  error: 17,\n  fatal: 21,\n};\n","import type { DsnComponents } from '../types-hoist/dsn';\nimport type { LogContainerItem, LogEnvelope } from '../types-hoist/envelope';\nimport type { SerializedLog } from '../types-hoist/log';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport { dsnToString } from '../utils/dsn';\nimport { createEnvelope } from '../utils/envelope';\n\n/**\n * Creates a log container envelope item for a list of logs.\n *\n * @param items - The logs to include in the envelope.\n * @returns The created log container envelope item.\n */\nexport function createLogContainerEnvelopeItem(items: Array\u003cSerializedLog\u003e): LogContainerItem {\n  return [\n    {\n      type: 'log',\n      item_count: items.length,\n      content_type: 'application/vnd.sentry.items.log+json',\n    },\n    {\n      items,\n    },\n  ];\n}\n\n/**\n * Creates an envelope for a list of logs.\n *\n * Logs from multiple traces can be included in the same envelope.\n *\n * @param logs - The logs to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nexport function createLogEnvelope(\n  logs: Array\u003cSerializedLog\u003e,\n  metadata?: SdkMetadata,\n  tunnel?: string,\n  dsn?: DsnComponents,\n): LogEnvelope {\n  const headers: LogEnvelope[0] = {};\n\n  if (metadata?.sdk) {\n    headers.sdk = {\n      name: metadata.sdk.name,\n      version: metadata.sdk.version,\n    };\n  }\n\n  if (!!tunnel \u0026\u0026 !!dsn) {\n    headers.dsn = dsnToString(dsn);\n  }\n\n  return createEnvelope\u003cLogEnvelope\u003e(headers, [createLogContainerEnvelopeItem(logs)]);\n}\n","import { serializeAttributes } from '../attributes';\nimport { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Log, SerializedLog } from '../types-hoist/log';\nimport { consoleSandbox, debug } from '../utils/debug-logger';\nimport { isParameterizedString } from '../utils/is';\nimport { getCombinedScopeData } from '../utils/scopeData';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { getSequenceAttribute } from '../utils/timestampSequence';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from './constants';\nimport { createLogEnvelope } from './envelope';\n\nconst MAX_LOG_BUFFER_SIZE = 100;\n\n/**\n * Sets a log attribute if the value exists and the attribute key is not already present.\n *\n * @param logAttributes - The log attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setLogAttribute(\n  logAttributes: Record\u003cstring, unknown\u003e,\n  key: string,\n  value: unknown,\n  setEvenIfPresent = true,\n): void {\n  if (value \u0026\u0026 (!logAttributes[key] || setEvenIfPresent)) {\n    logAttributes[key] = value;\n  }\n}\n\n/**\n * Captures a serialized log event and adds it to the log buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedLog - The serialized log event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedLog(client: Client, serializedLog: SerializedLog): void {\n  const bufferMap = _getBufferMap();\n  const logBuffer = _INTERNAL_getLogBuffer(client);\n\n  if (logBuffer === undefined) {\n    bufferMap.set(client, [serializedLog]);\n  } else {\n    if (logBuffer.length \u003e= MAX_LOG_BUFFER_SIZE) {\n      _INTERNAL_flushLogsBuffer(client, logBuffer);\n      bufferMap.set(client, [serializedLog]);\n    } else {\n      bufferMap.set(client, [...logBuffer, serializedLog]);\n    }\n  }\n}\n\n/**\n * Captures a log event and sends it to Sentry.\n *\n * @param log - The log event to capture.\n * @param scope - A scope. Uses the current scope if not provided.\n * @param client - A client. Uses the current client if not provided.\n * @param captureSerializedLog - A function to capture the serialized log.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureLog(\n  beforeLog: Log,\n  currentScope = getCurrentScope(),\n  captureSerializedLog: (client: Client, log: SerializedLog) =\u003e void = _INTERNAL_captureSerializedLog,\n): void {\n  const client = currentScope?.getClient() ?? getClient();\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('No client available to capture log.');\n    return;\n  }\n\n  const { release, environment, enableLogs = false, beforeSendLog } = client.getOptions();\n  if (!enableLogs) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('logging option not enabled, log will not be captured.');\n    return;\n  }\n\n  const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n\n  const processedLogAttributes = {\n    ...beforeLog.attributes,\n  };\n\n  const {\n    user: { id, email, username },\n    attributes: scopeAttributes = {},\n  } = getCombinedScopeData(getIsolationScope(), currentScope);\n\n  setLogAttribute(processedLogAttributes, 'user.id', id, false);\n  setLogAttribute(processedLogAttributes, 'user.email', email, false);\n  setLogAttribute(processedLogAttributes, 'user.name', username, false);\n\n  setLogAttribute(processedLogAttributes, 'sentry.release', release);\n  setLogAttribute(processedLogAttributes, 'sentry.environment', environment);\n\n  const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n  setLogAttribute(processedLogAttributes, 'sentry.sdk.name', name);\n  setLogAttribute(processedLogAttributes, 'sentry.sdk.version', version);\n\n  const replay = client.getIntegrationByName\u003c\n    Integration \u0026 {\n      getReplayId: (onlyIfSampled?: boolean) =\u003e string;\n      getRecordingMode: () =\u003e 'session' | 'buffer' | undefined;\n    }\n  \u003e('Replay');\n\n  const replayId = replay?.getReplayId(true);\n  setLogAttribute(processedLogAttributes, 'sentry.replay_id', replayId);\n\n  if (replayId \u0026\u0026 replay?.getRecordingMode() === 'buffer') {\n    // We send this so we can identify cases where the replayId is attached but the replay itself might not have been sent to Sentry\n    setLogAttribute(processedLogAttributes, 'sentry._internal.replay_is_buffering', true);\n  }\n\n  const beforeLogMessage = beforeLog.message;\n  if (isParameterizedString(beforeLogMessage)) {\n    const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;\n    if (__sentry_template_values__?.length) {\n      processedLogAttributes['sentry.message.template'] = __sentry_template_string__;\n    }\n    __sentry_template_values__.forEach((param, index) =\u003e {\n      processedLogAttributes[`sentry.message.parameter.${index}`] = param;\n    });\n  }\n\n  const span = _getSpanForScope(currentScope);\n  // Add the parent span ID to the log attributes for trace context\n  setLogAttribute(processedLogAttributes, 'sentry.trace.parent_span_id', span?.spanContext().spanId);\n\n  const processedLog = { ...beforeLog, attributes: processedLogAttributes };\n\n  client.emit('beforeCaptureLog', processedLog);\n\n  // We need to wrap this in `consoleSandbox` to avoid recursive calls to `beforeSendLog`\n  const log = beforeSendLog ? consoleSandbox(() =\u003e beforeSendLog(processedLog)) : processedLog;\n  if (!log) {\n    client.recordDroppedEvent('before_send', 'log_item', 1);\n    DEBUG_BUILD \u0026\u0026 debug.warn('beforeSendLog returned null, log will not be captured.');\n    return;\n  }\n\n  const { level, message, attributes: logAttributes = {}, severityNumber } = log;\n\n  const timestamp = timestampInSeconds();\n  const sequenceAttr = getSequenceAttribute(timestamp);\n\n  const serializedLog: SerializedLog = {\n    timestamp,\n    level,\n    body: message,\n    trace_id: traceContext?.trace_id,\n    severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],\n    attributes: {\n      ...serializeAttributes(scopeAttributes),\n      ...serializeAttributes(logAttributes, true),\n      [sequenceAttr.key]: sequenceAttr.value,\n    },\n  };\n\n  captureSerializedLog(client, serializedLog);\n\n  client.emit('afterCaptureLog', log);\n}\n\n/**\n * Flushes the logs buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushLogsBuffer(client: Client, maybeLogBuffer?: Array\u003cSerializedLog\u003e): void {\n  const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];\n  if (logBuffer.length === 0) {\n    return;\n  }\n\n  const clientOptions = client.getOptions();\n  const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n  // Clear the log buffer after envelopes have been constructed.\n  _getBufferMap().set(client, []);\n\n  client.emit('flushLogs');\n\n  // sendEnvelope should not throw\n  // eslint-disable-next-line @typescript-eslint/no-floating-promises\n  client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the log buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the log buffer for.\n * @returns The log buffer for the given client.\n */\nexport function _INTERNAL_getLogBuffer(client: Client): Array\u003cSerializedLog\u003e | undefined {\n  return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap(): WeakMap\u003cClient, Array\u003cSerializedLog\u003e\u003e {\n  // The reference to the Client \u003c\u003e LogBuffer map is stored on the carrier to ensure it's always the same\n  return getGlobalSingleton('clientToLogBufferMap', () =\u003e new WeakMap\u003cClient, Array\u003cSerializedLog\u003e\u003e());\n}\n","import type { DsnComponents } from '../types-hoist/dsn';\nimport type { MetricContainerItem, MetricEnvelope } from '../types-hoist/envelope';\nimport type { SerializedMetric } from '../types-hoist/metric';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport { dsnToString } from '../utils/dsn';\nimport { createEnvelope } from '../utils/envelope';\n\n/**\n * Creates a metric container envelope item for a list of metrics.\n *\n * @param items - The metrics to include in the envelope.\n * @returns The created metric container envelope item.\n */\nexport function createMetricContainerEnvelopeItem(items: Array\u003cSerializedMetric\u003e): MetricContainerItem {\n  return [\n    {\n      type: 'trace_metric',\n      item_count: items.length,\n      content_type: 'application/vnd.sentry.items.trace-metric+json',\n    } as MetricContainerItem[0],\n    {\n      items,\n    },\n  ];\n}\n\n/**\n * Creates an envelope for a list of metrics.\n *\n * Metrics from multiple traces can be included in the same envelope.\n *\n * @param metrics - The metrics to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nexport function createMetricEnvelope(\n  metrics: Array\u003cSerializedMetric\u003e,\n  metadata?: SdkMetadata,\n  tunnel?: string,\n  dsn?: DsnComponents,\n): MetricEnvelope {\n  const headers: MetricEnvelope[0] = {};\n\n  if (metadata?.sdk) {\n    headers.sdk = {\n      name: metadata.sdk.name,\n      version: metadata.sdk.version,\n    };\n  }\n\n  if (!!tunnel \u0026\u0026 !!dsn) {\n    headers.dsn = dsnToString(dsn);\n  }\n\n  return createEnvelope\u003cMetricEnvelope\u003e(headers, [createMetricContainerEnvelopeItem(metrics)]);\n}\n","import { type RawAttributes, serializeAttributes } from '../attributes';\nimport { getGlobalSingleton } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope, getIsolationScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { Scope } from '../scope';\nimport type { Integration } from '../types-hoist/integration';\nimport type { Metric, SerializedMetric } from '../types-hoist/metric';\nimport type { User } from '../types-hoist/user';\nimport { debug } from '../utils/debug-logger';\nimport { getCombinedScopeData } from '../utils/scopeData';\nimport { _getSpanForScope } from '../utils/spanOnScope';\nimport { timestampInSeconds } from '../utils/time';\nimport { getSequenceAttribute } from '../utils/timestampSequence';\nimport { _getTraceInfoFromScope } from '../utils/trace-info';\nimport { createMetricEnvelope } from './envelope';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n  metricAttributes: Record\u003cstring, unknown\u003e,\n  key: string,\n  value: unknown,\n  setEvenIfPresent = true,\n): void {\n  if (value \u0026\u0026 (setEvenIfPresent || !(key in metricAttributes))) {\n    metricAttributes[key] = value;\n  }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void {\n  const bufferMap = _getBufferMap();\n  const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n  if (metricBuffer === undefined) {\n    bufferMap.set(client, [serializedMetric]);\n  } else {\n    if (metricBuffer.length \u003e= MAX_METRIC_BUFFER_SIZE) {\n      _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n      bufferMap.set(client, [serializedMetric]);\n    } else {\n      bufferMap.set(client, [...metricBuffer, serializedMetric]);\n    }\n  }\n}\n\n/**\n * Options for capturing a metric internally.\n */\nexport interface InternalCaptureMetricOptions {\n  /**\n   * The scope to capture the metric with.\n   */\n  scope?: Scope;\n\n  /**\n   * A function to capture the serialized metric.\n   */\n  captureSerializedMetric?: (client: Client, metric: SerializedMetric) =\u003e void;\n}\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric: Metric, client: Client, user: User): Metric {\n  const { release, environment } = client.getOptions();\n\n  const processedMetricAttributes = {\n    ...beforeMetric.attributes,\n  };\n\n  // Add user attributes\n  setMetricAttribute(processedMetricAttributes, 'user.id', user.id, false);\n  setMetricAttribute(processedMetricAttributes, 'user.email', user.email, false);\n  setMetricAttribute(processedMetricAttributes, 'user.name', user.username, false);\n\n  // Add Sentry metadata\n  setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n  setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n  // Add SDK metadata\n  const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n  setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n  setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n  // Add replay metadata\n  const replay = client.getIntegrationByName\u003c\n    Integration \u0026 {\n      getReplayId: (onlyIfSampled?: boolean) =\u003e string;\n      getRecordingMode: () =\u003e 'session' | 'buffer' | undefined;\n    }\n  \u003e('Replay');\n\n  const replayId = replay?.getReplayId(true);\n  setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n  if (replayId \u0026\u0026 replay?.getRecordingMode() === 'buffer') {\n    setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n  }\n\n  return {\n    ...beforeMetric,\n    attributes: processedMetricAttributes,\n  };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(\n  metric: Metric,\n  client: Client,\n  currentScope: Scope,\n  scopeAttributes: RawAttributes\u003cRecord\u003cstring, unknown\u003e\u003e | undefined,\n): SerializedMetric {\n  // Get trace context\n  const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n  const span = _getSpanForScope(currentScope);\n  const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n  const spanId = span ? span.spanContext().spanId : undefined;\n\n  const timestamp = timestampInSeconds();\n  const sequenceAttr = getSequenceAttribute(timestamp);\n\n  return {\n    timestamp,\n    trace_id: traceId ?? '',\n    span_id: spanId,\n    name: metric.name,\n    type: metric.type,\n    unit: metric.unit,\n    value: metric.value,\n    attributes: {\n      ...serializeAttributes(scopeAttributes),\n      ...serializeAttributes(metric.attributes, 'skip-undefined'),\n      [sequenceAttr.key]: sequenceAttr.value,\n    },\n  };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void {\n  const currentScope = options?.scope ?? getCurrentScope();\n  const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n  const client = currentScope?.getClient() ?? getClient();\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('No client available to capture metric.');\n    return;\n  }\n\n  const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n  // todo(v11): Remove the experimental flag\n  // eslint-disable-next-line deprecation/deprecation\n  const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n  if (!metricsEnabled) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('metrics option not enabled, metric will not be captured.');\n    return;\n  }\n\n  // Enrich metric with contextual attributes\n  const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);\n  const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);\n\n  client.emit('processMetric', enrichedMetric);\n\n  // todo(v11): Remove the experimental `beforeSendMetric`\n  // eslint-disable-next-line deprecation/deprecation\n  const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n  const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n  if (!processedMetric) {\n    DEBUG_BUILD \u0026\u0026 debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n    return;\n  }\n\n  const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);\n\n  DEBUG_BUILD \u0026\u0026 debug.log('[Metric]', serializedMetric);\n\n  captureSerializedMetric(client, serializedMetric);\n\n  client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nexport function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array\u003cSerializedMetric\u003e): void {\n  const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n  if (metricBuffer.length === 0) {\n    return;\n  }\n\n  const clientOptions = client.getOptions();\n  const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n  // Clear the metric buffer after envelopes have been constructed.\n  _getBufferMap().set(client, []);\n\n  client.emit('flushMetrics');\n\n  // sendEnvelope should not throw\n  // eslint-disable-next-line @typescript-eslint/no-floating-promises\n  client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nexport function _INTERNAL_getMetricBuffer(client: Client): Array\u003cSerializedMetric\u003e | undefined {\n  return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap(): WeakMap\u003cClient, Array\u003cSerializedMetric\u003e\u003e {\n  // The reference to the Client \u003c\u003e MetricBuffer map is stored on the carrier to ensure it's always the same\n  return getGlobalSingleton('clientToMetricBufferMap', () =\u003e new WeakMap\u003cClient, Array\u003cSerializedMetric\u003e\u003e());\n}\n","/**\n * Calls `unref` on a timer, if the method is available on @param timer.\n *\n * `unref()` is used to allow processes to exit immediately, even if the timer\n * is still running and hasn't resolved yet.\n *\n * Use this in places where code can run on browser or server, since browsers\n * do not support `unref`.\n */\nexport function safeUnref(timer: ReturnType\u003ctypeof setTimeout\u003e): ReturnType\u003ctypeof setTimeout\u003e {\n  if (typeof timer === 'object' \u0026\u0026 typeof timer.unref === 'function') {\n    timer.unref();\n  }\n  return timer;\n}\n","import { rejectedSyncPromise, resolvedSyncPromise } from './syncpromise';\nimport { safeUnref } from './timer';\n\nexport interface PromiseBuffer\u003cT\u003e {\n  // exposes the internal array so tests can assert on the state of it.\n  // XXX: this really should not be public api.\n  $: PromiseLike\u003cT\u003e[];\n  add(taskProducer: () =\u003e PromiseLike\u003cT\u003e): PromiseLike\u003cT\u003e;\n  drain(timeout?: number): PromiseLike\u003cboolean\u003e;\n}\n\nexport const SENTRY_BUFFER_FULL_ERROR = Symbol.for('SentryBufferFullError');\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer\u003cT\u003e(limit: number = 100): PromiseBuffer\u003cT\u003e {\n  const buffer: Set\u003cPromiseLike\u003cT\u003e\u003e = new Set();\n\n  function isReady(): boolean {\n    return buffer.size \u003c limit;\n  }\n\n  /**\n   * Remove a promise from the queue.\n   *\n   * @param task Can be any PromiseLike\u003cT\u003e\n   * @returns Removed promise.\n   */\n  function remove(task: PromiseLike\u003cT\u003e): void {\n    buffer.delete(task);\n  }\n\n  /**\n   * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n   *\n   * @param taskProducer A function producing any PromiseLike\u003cT\u003e; In previous versions this used to be `task:\n   *        PromiseLike\u003cT\u003e`, but under that model, Promises were instantly created on the call-site and their executor\n   *        functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n   *        requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n   *        limit check.\n   * @returns The original promise.\n   */\n  function add(taskProducer: () =\u003e PromiseLike\u003cT\u003e): PromiseLike\u003cT\u003e {\n    if (!isReady()) {\n      return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);\n    }\n\n    // start the task and add its promise to the queue\n    const task = taskProducer();\n    buffer.add(task);\n    void task.then(\n      () =\u003e remove(task),\n      () =\u003e remove(task),\n    );\n    return task;\n  }\n\n  /**\n   * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n   *\n   * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n   * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n   * `true`.\n   * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n   * `false` otherwise\n   */\n  function drain(timeout?: number): PromiseLike\u003cboolean\u003e {\n    if (!buffer.size) {\n      return resolvedSyncPromise(true);\n    }\n\n    // We want to resolve even if one of the promises rejects\n    const drainPromise = Promise.allSettled(Array.from(buffer)).then(() =\u003e true);\n\n    if (!timeout) {\n      return drainPromise;\n    }\n\n    const promises = [\n      drainPromise,\n      new Promise\u003cboolean\u003e(resolve =\u003e safeUnref(setTimeout(() =\u003e resolve(false), timeout))),\n    ];\n\n    return Promise.race(promises);\n  }\n\n  return {\n    get $(): PromiseLike\u003cT\u003e[] {\n      return Array.from(buffer);\n    },\n    add,\n    drain,\n  };\n}\n","import type { DataCategory } from '../types-hoist/datacategory';\nimport type { TransportMakeRequestResponse } from '../types-hoist/transport';\nimport { safeDateNow } from './randomSafeContext';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record\u003cstring, number\u003e;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = safeDateNow()): number {\n  const headerDelay = parseInt(`${header}`, 10);\n  if (!isNaN(headerDelay)) {\n    return headerDelay * 1000;\n  }\n\n  const headerDate = Date.parse(`${header}`);\n  if (!isNaN(headerDate)) {\n    return headerDate - now;\n  }\n\n  return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, dataCategory: DataCategory): number {\n  return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, dataCategory: DataCategory, now: number = safeDateNow()): boolean {\n  return disabledUntil(limits, dataCategory) \u003e now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n  limits: RateLimits,\n  { statusCode, headers }: TransportMakeRequestResponse,\n  now: number = safeDateNow(),\n): RateLimits {\n  const updatedRateLimits: RateLimits = {\n    ...limits,\n  };\n\n  // \"The name is case-insensitive.\"\n  // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n  const rateLimitHeader = headers?.['x-sentry-rate-limits'];\n  const retryAfterHeader = headers?.['retry-after'];\n\n  if (rateLimitHeader) {\n    /**\n     * rate limit headers are of the form\n     *     \u003cheader\u003e,\u003cheader\u003e,..\n     * where each \u003cheader\u003e is of the form\n     *     \u003cretry_after\u003e: \u003ccategories\u003e: \u003cscope\u003e: \u003creason_code\u003e: \u003cnamespaces\u003e\n     * where\n     *     \u003cretry_after\u003e is a delay in seconds\n     *     \u003ccategories\u003e is the event type(s) (error, transaction, etc) being rate limited and is of the form\n     *         \u003ccategory\u003e;\u003ccategory\u003e;...\n     *     \u003cscope\u003e is what's being limited (org, project, or key) - ignored by SDK\n     *     \u003creason_code\u003e is an arbitrary string like \"org_quota\" - ignored by SDK\n     *     \u003cnamespaces\u003e Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n     *         Only present if rate limit applies to the metric_bucket data category.\n     */\n    for (const limit of rateLimitHeader.trim().split(',')) {\n      const [retryAfter, categories, , , namespaces] = limit.split(':', 5) as [string, ...string[]];\n      const headerDelay = parseInt(retryAfter, 10);\n      const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n      if (!categories) {\n        updatedRateLimits.all = now + delay;\n      } else {\n        for (const category of categories.split(';')) {\n          if (category === 'metric_bucket') {\n            // namespaces will be present when category === 'metric_bucket'\n            if (!namespaces || namespaces.split(';').includes('custom')) {\n              updatedRateLimits[category] = now + delay;\n            }\n          } else {\n            updatedRateLimits[category] = now + delay;\n          }\n        }\n      }\n    }\n  } else if (retryAfterHeader) {\n    updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n  } else if (statusCode === 429) {\n    updatedRateLimits.all = now + 60 * 1000;\n  }\n\n  return updatedRateLimits;\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { EventDropReason } from '../types-hoist/clientreport';\nimport type { Envelope, EnvelopeItem } from '../types-hoist/envelope';\nimport type {\n  InternalBaseTransportOptions,\n  Transport,\n  TransportMakeRequestResponse,\n  TransportRequestExecutor,\n} from '../types-hoist/transport';\nimport { debug } from '../utils/debug-logger';\nimport {\n  createEnvelope,\n  envelopeContainsItemType,\n  envelopeItemTypeToDataCategory,\n  forEachEnvelopeItem,\n  serializeEnvelope,\n} from '../utils/envelope';\nimport { makePromiseBuffer, type PromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from '../utils/promisebuffer';\nimport { isRateLimited, type RateLimits, updateRateLimits } from '../utils/ratelimit';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n  options: InternalBaseTransportOptions,\n  makeRequest: TransportRequestExecutor,\n  buffer: PromiseBuffer\u003cTransportMakeRequestResponse\u003e = makePromiseBuffer(\n    options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n  ),\n): Transport {\n  let rateLimits: RateLimits = {};\n  const flush = (timeout?: number): PromiseLike\u003cboolean\u003e =\u003e buffer.drain(timeout);\n\n  function send(envelope: Envelope): PromiseLike\u003cTransportMakeRequestResponse\u003e {\n    const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n    // Drop rate limited items from envelope\n    forEachEnvelopeItem(envelope, (item, type) =\u003e {\n      const dataCategory = envelopeItemTypeToDataCategory(type);\n      if (isRateLimited(rateLimits, dataCategory)) {\n        options.recordDroppedEvent('ratelimit_backoff', dataCategory);\n      } else {\n        filteredEnvelopeItems.push(item);\n      }\n    });\n\n    // Skip sending if envelope is empty after filtering out rate limited events\n    if (filteredEnvelopeItems.length === 0) {\n      return Promise.resolve({});\n    }\n\n    const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as (typeof envelope)[1]);\n\n    // Creates client report for each item in an envelope\n    const recordEnvelopeLoss = (reason: EventDropReason): void =\u003e {\n      // Don't record outcomes for client reports - we don't want to create a feedback loop if client reports themselves fail to send\n      if (envelopeContainsItemType(filteredEnvelope, ['client_report'])) {\n        DEBUG_BUILD \u0026\u0026 debug.warn(`Dropping client report. Will not send outcomes (reason: ${reason}).`);\n        return;\n      }\n      forEachEnvelopeItem(filteredEnvelope, (item, type) =\u003e {\n        options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type));\n      });\n    };\n\n    const requestTask = (): PromiseLike\u003cTransportMakeRequestResponse\u003e =\u003e\n      makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(\n        response =\u003e {\n          // Handle 413 Content Too Large\n          // Loss of envelope content is expected so we record a send_error client report\n          // https://develop.sentry.dev/sdk/expected-features/#dealing-with-network-failures\n          if (response.statusCode === 413) {\n            DEBUG_BUILD \u0026\u0026\n              debug.error(\n                'Sentry responded with status code 413. Envelope was discarded due to exceeding size limits.',\n              );\n            recordEnvelopeLoss('send_error');\n            return response;\n          }\n\n          // We don't want to throw on NOK responses, but we want to at least log them\n          if (\n            DEBUG_BUILD \u0026\u0026\n            response.statusCode !== undefined \u0026\u0026\n            (response.statusCode \u003c 200 || response.statusCode \u003e= 300)\n          ) {\n            debug.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n          }\n\n          rateLimits = updateRateLimits(rateLimits, response);\n          return response;\n        },\n        error =\u003e {\n          recordEnvelopeLoss('network_error');\n          DEBUG_BUILD \u0026\u0026 debug.error('Encountered error running transport request:', error);\n          throw error;\n        },\n      );\n\n    return buffer.add(requestTask).then(\n      result =\u003e result,\n      error =\u003e {\n        if (error === SENTRY_BUFFER_FULL_ERROR) {\n          DEBUG_BUILD \u0026\u0026 debug.error('Skipped sending event because buffer is full.');\n          recordEnvelopeLoss('queue_overflow');\n          return Promise.resolve({});\n        } else {\n          throw error;\n        }\n      },\n    );\n  }\n\n  return {\n    send,\n    flush,\n  };\n}\n","import type { ClientReport } from '../types-hoist/clientreport';\nimport type { ClientReportEnvelope, ClientReportItem } from '../types-hoist/envelope';\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n  discarded_events: ClientReport['discarded_events'],\n  dsn?: string,\n  timestamp?: number,\n): ClientReportEnvelope {\n  const clientReportItem: ClientReportItem = [\n    { type: 'client_report' },\n    {\n      timestamp: timestamp || dateTimestampInSeconds(),\n      discarded_events,\n    },\n  ];\n  return createEnvelope\u003cClientReportEnvelope\u003e(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import type { Event } from '../types-hoist/event';\n\n/**\n * Get a list of possible event messages from a Sentry event.\n */\nexport function getPossibleEventMessages(event: Event): string[] {\n  const possibleMessages: string[] = [];\n\n  if (event.message) {\n    possibleMessages.push(event.message);\n  }\n\n  try {\n    // @ts-expect-error Try catching to save bundle size\n    const lastException = event.exception.values[event.exception.values.length - 1];\n    if (lastException?.value) {\n      possibleMessages.push(lastException.value);\n      if (lastException.type) {\n        possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n      }\n    }\n  } catch {\n    // ignore errors here\n  }\n\n  return possibleMessages;\n}\n","import { SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID } from '../semanticAttributes';\nimport type { TransactionEvent } from '../types-hoist/event';\nimport type { SpanJSON } from '../types-hoist/span';\n\n/**\n * Converts a transaction event to a span JSON object.\n */\nexport function convertTransactionEventToSpanJson(event: TransactionEvent): SpanJSON {\n  const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {};\n\n  return {\n    data: data ?? {},\n    description: event.transaction,\n    op,\n    parent_span_id,\n    span_id: span_id ?? '',\n    start_timestamp: event.start_timestamp ?? 0,\n    status,\n    timestamp: event.timestamp,\n    trace_id: trace_id ?? '',\n    origin,\n    profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,\n    exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,\n    measurements: event.measurements,\n    is_segment: true,\n  };\n}\n\n/**\n * Converts a span JSON object to a transaction event.\n */\nexport function convertSpanJsonToTransactionEvent(span: SpanJSON): TransactionEvent {\n  return {\n    type: 'transaction',\n    timestamp: span.timestamp,\n    start_timestamp: span.start_timestamp,\n    transaction: span.description,\n    contexts: {\n      trace: {\n        trace_id: span.trace_id,\n        span_id: span.span_id,\n        parent_span_id: span.parent_span_id,\n        op: span.op,\n        status: span.status,\n        origin: span.origin,\n        data: {\n          ...span.data,\n          ...(span.profile_id \u0026\u0026 { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }),\n          ...(span.exclusive_time \u0026\u0026 { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time }),\n        },\n      },\n    },\n    measurements: span.measurements,\n  };\n}\n","/* eslint-disable max-lines */\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { getCurrentScope, getIsolationScope, getTraceContextFromScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { afterSetupIntegrations, setupIntegration, setupIntegrations } from './integration';\nimport { _INTERNAL_flushLogsBuffer } from './logs/internal';\nimport { _INTERNAL_flushMetricsBuffer } from './metrics/internal';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base';\nimport type { Breadcrumb, BreadcrumbHint, FetchBreadcrumbHint, XhrBreadcrumbHint } from './types-hoist/breadcrumb';\nimport type { CheckIn, MonitorConfig } from './types-hoist/checkin';\nimport type { EventDropReason, Outcome } from './types-hoist/clientreport';\nimport type { DataCategory } from './types-hoist/datacategory';\nimport type { DsnComponents } from './types-hoist/dsn';\nimport type { DynamicSamplingContext, Envelope } from './types-hoist/envelope';\nimport type { ErrorEvent, Event, EventHint, EventType, TransactionEvent } from './types-hoist/event';\nimport type { EventProcessor } from './types-hoist/eventprocessor';\nimport type { FeedbackEvent } from './types-hoist/feedback';\nimport type { Integration } from './types-hoist/integration';\nimport type { Log } from './types-hoist/log';\nimport type { Metric } from './types-hoist/metric';\nimport type { Primitive } from './types-hoist/misc';\nimport type { ClientOptions } from './types-hoist/options';\nimport type { ParameterizedString } from './types-hoist/parameterize';\nimport type { RequestEventData } from './types-hoist/request';\nimport type { SdkMetadata } from './types-hoist/sdkmetadata';\nimport type { Session, SessionAggregates } from './types-hoist/session';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { Span, SpanAttributes, SpanContextData, SpanJSON } from './types-hoist/span';\nimport type { StartSpanOptions } from './types-hoist/startSpanOptions';\nimport type { Transport, TransportMakeRequestResponse } from './types-hoist/transport';\nimport { createClientReportEnvelope } from './utils/clientreport';\nimport { debug } from './utils/debug-logger';\nimport { dsnToString, makeDsn } from './utils/dsn';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils/envelope';\nimport { getPossibleEventMessages } from './utils/eventUtils';\nimport { isParameterizedString, isPlainObject, isPrimitive, isThenable } from './utils/is';\nimport { merge } from './utils/merge';\nimport { checkOrSetAlreadyCaught, uuid4 } from './utils/misc';\nimport { parseSampleRate } from './utils/parseSampleRate';\nimport { prepareEvent } from './utils/prepareEvent';\nimport { makePromiseBuffer, type PromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from './utils/promisebuffer';\nimport { safeMathRandom } from './utils/randomSafeContext';\nimport { reparentChildSpans, shouldIgnoreSpan } from './utils/should-ignore-span';\nimport { showSpanDropWarning } from './utils/spanUtils';\nimport { rejectedSyncPromise } from './utils/syncpromise';\nimport { safeUnref } from './utils/timer';\nimport { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson } from './utils/transactionEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\nconst MISSING_RELEASE_FOR_SESSION_ERROR = 'Discarded session because of missing or non-string release';\n\nconst INTERNAL_ERROR_SYMBOL = Symbol.for('SentryInternalError');\nconst DO_NOT_SEND_EVENT_SYMBOL = Symbol.for('SentryDoNotSendEventError');\n\n// Default interval for flushing logs and metrics (5 seconds)\nconst DEFAULT_FLUSH_INTERVAL = 5000;\n\ninterface InternalError {\n  message: string;\n  [INTERNAL_ERROR_SYMBOL]: true;\n}\n\ninterface DoNotSendEventError {\n  message: string;\n  [DO_NOT_SEND_EVENT_SYMBOL]: true;\n}\n\nfunction _makeInternalError(message: string): InternalError {\n  return {\n    message,\n    [INTERNAL_ERROR_SYMBOL]: true,\n  };\n}\n\nfunction _makeDoNotSendEventError(message: string): DoNotSendEventError {\n  return {\n    message,\n    [DO_NOT_SEND_EVENT_SYMBOL]: true,\n  };\n}\n\nfunction _isInternalError(error: unknown): error is InternalError {\n  return !!error \u0026\u0026 typeof error === 'object' \u0026\u0026 INTERNAL_ERROR_SYMBOL in error;\n}\n\nfunction _isDoNotSendEventError(error: unknown): error is DoNotSendEventError {\n  return !!error \u0026\u0026 typeof error === 'object' \u0026\u0026 DO_NOT_SEND_EVENT_SYMBOL in error;\n}\n\n/**\n * Sets up weight-based flushing for logs or metrics.\n * This helper function encapsulates the common pattern of:\n * 1. Tracking accumulated weight of items\n * 2. Flushing when weight exceeds threshold (800KB)\n * 3. Flushing after timeout period from the first item\n *\n * Uses closure variables to track weight and timeout state.\n */\nfunction setupWeightBasedFlushing\u003c\n  T,\n  AfterCaptureHook extends 'afterCaptureLog' | 'afterCaptureMetric',\n  FlushHook extends 'flushLogs' | 'flushMetrics',\n\u003e(\n  client: Client,\n  afterCaptureHook: AfterCaptureHook,\n  flushHook: FlushHook,\n  estimateSizeFn: (item: T) =\u003e number,\n  flushFn: (client: Client) =\u003e void,\n): void {\n  // Track weight and timeout in closure variables\n  let weight = 0;\n  let flushTimeout: ReturnType\u003ctypeof setTimeout\u003e | undefined;\n  let isTimerActive = false;\n\n  // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n  client.on(flushHook, () =\u003e {\n    weight = 0;\n    clearTimeout(flushTimeout);\n    isTimerActive = false;\n  });\n\n  // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n  client.on(afterCaptureHook, (item: T) =\u003e {\n    weight += estimateSizeFn(item);\n\n    // We flush the buffer if it exceeds 0.8 MB\n    // The weight is a rough estimate, so we flush way before the payload gets too big.\n    if (weight \u003e= 800_000) {\n      flushFn(client);\n    } else if (!isTimerActive) {\n      // Only start timer if one isn't already running.\n      // This prevents flushing being delayed by items that arrive close to the timeout limit\n      // and thus resetting the flushing timeout and delaying items being flushed.\n      isTimerActive = true;\n      // Use safeUnref so the timer doesn't prevent the process from exiting\n      flushTimeout = safeUnref(\n        setTimeout(() =\u003e {\n          flushFn(client);\n          // Note: isTimerActive is reset by the flushHook handler above, not here,\n          // to avoid race conditions when new items arrive during the flush.\n        }, DEFAULT_FLUSH_INTERVAL),\n      );\n    }\n  });\n\n  client.on('flush', () =\u003e {\n    flushFn(client);\n  });\n}\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link Client._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends Client\u003cNodeOptions\u003e {\n *   public constructor(options: NodeOptions) {\n *     super(options);\n *   }\n *\n *   // ...\n * }\n */\nexport abstract class Client\u003cO extends ClientOptions = ClientOptions\u003e {\n  /** Options passed to the SDK. */\n  protected readonly _options: O;\n\n  /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n  protected readonly _dsn?: DsnComponents;\n\n  protected readonly _transport?: Transport;\n\n  /** Array of set up integrations. */\n  protected _integrations: IntegrationIndex;\n\n  /** Number of calls being processed */\n  protected _numProcessing: number;\n\n  protected _eventProcessors: EventProcessor[];\n\n  /** Holds flushable  */\n  protected _outcomes: { [key: string]: number };\n\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  protected _hooks: Record\u003cstring, Set\u003cFunction\u003e\u003e;\n\n  protected _promiseBuffer: PromiseBuffer\u003cunknown\u003e;\n\n  /**\n   * Initializes this client instance.\n   *\n   * @param options Options for the client.\n   */\n  protected constructor(options: O) {\n    this._options = options;\n    this._integrations = {};\n    this._numProcessing = 0;\n    this._outcomes = {};\n    this._hooks = {};\n    this._eventProcessors = [];\n    this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE);\n\n    if (options.dsn) {\n      this._dsn = makeDsn(options.dsn);\n    } else {\n      DEBUG_BUILD \u0026\u0026 debug.warn('No DSN provided, client will not send events.');\n    }\n\n    if (this._dsn) {\n      const url = getEnvelopeEndpointWithUrlEncodedAuth(\n        this._dsn,\n        options.tunnel,\n        options._metadata ? options._metadata.sdk : undefined,\n      );\n      this._transport = options.transport({\n        tunnel: this._options.tunnel,\n        recordDroppedEvent: this.recordDroppedEvent.bind(this),\n        ...options.transportOptions,\n        url,\n      });\n    }\n\n    // Backfill enableLogs option from _experiments.enableLogs\n    // TODO(v11): Remove or change default value\n    // eslint-disable-next-line deprecation/deprecation\n    this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs;\n\n    // Setup log flushing with weight and timeout tracking\n    if (this._options.enableLogs) {\n      setupWeightBasedFlushing(this, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);\n    }\n\n    // todo(v11): Remove the experimental flag\n    // eslint-disable-next-line deprecation/deprecation\n    const enableMetrics = this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true;\n\n    // Setup metric flushing with weight and timeout tracking\n    if (enableMetrics) {\n      setupWeightBasedFlushing(\n        this,\n        'afterCaptureMetric',\n        'flushMetrics',\n        estimateMetricSizeInBytes,\n        _INTERNAL_flushMetricsBuffer,\n      );\n    }\n  }\n\n  /**\n   * Captures an exception event and sends it to Sentry.\n   *\n   * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.\n   */\n  public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {\n    const eventId = uuid4();\n\n    // ensure we haven't captured this very object before\n    if (checkOrSetAlreadyCaught(exception)) {\n      DEBUG_BUILD \u0026\u0026 debug.log(ALREADY_SEEN_ERROR);\n      return eventId;\n    }\n\n    const hintWithEventId = {\n      event_id: eventId,\n      ...hint,\n    };\n\n    this._process(\n      () =\u003e\n        this.eventFromException(exception, hintWithEventId)\n          .then(event =\u003e this._captureEvent(event, hintWithEventId, scope))\n          .then(res =\u003e res),\n      'error',\n    );\n\n    return hintWithEventId.event_id;\n  }\n\n  /**\n   * Captures a message event and sends it to Sentry.\n   *\n   * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.\n   */\n  public captureMessage(\n    message: ParameterizedString,\n    level?: SeverityLevel,\n    hint?: EventHint,\n    currentScope?: Scope,\n  ): string {\n    const hintWithEventId = {\n      event_id: uuid4(),\n      ...hint,\n    };\n\n    const eventMessage = isParameterizedString(message) ? message : String(message);\n    const isMessage = isPrimitive(message);\n    const promisedEvent = isMessage\n      ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n      : this.eventFromException(message, hintWithEventId);\n\n    this._process(\n      () =\u003e promisedEvent.then(event =\u003e this._captureEvent(event, hintWithEventId, currentScope)),\n      isMessage ? 'unknown' : 'error',\n    );\n\n    return hintWithEventId.event_id;\n  }\n\n  /**\n   * Captures a manually created event and sends it to Sentry.\n   *\n   * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.\n   */\n  public captureEvent(event: Event, hint?: EventHint, currentScope?: Scope): string {\n    const eventId = uuid4();\n\n    // ensure we haven't captured this very object before\n    if (hint?.originalException \u0026\u0026 checkOrSetAlreadyCaught(hint.originalException)) {\n      DEBUG_BUILD \u0026\u0026 debug.log(ALREADY_SEEN_ERROR);\n      return eventId;\n    }\n\n    const hintWithEventId = {\n      event_id: eventId,\n      ...hint,\n    };\n\n    const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n    const capturedSpanScope: Scope | undefined = sdkProcessingMetadata.capturedSpanScope;\n    const capturedSpanIsolationScope: Scope | undefined = sdkProcessingMetadata.capturedSpanIsolationScope;\n    const dataCategory = getDataCategoryByType(event.type);\n\n    this._process(\n      () =\u003e this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope),\n      dataCategory,\n    );\n\n    return hintWithEventId.event_id;\n  }\n\n  /**\n   * Captures a session.\n   */\n  public captureSession(session: Session): void {\n    this.sendSession(session);\n    // After sending, we set init false to indicate it's not the first occurrence\n    updateSession(session, { init: false });\n  }\n\n  /**\n   * Create a cron monitor check in and send it to Sentry. This method is not available on all clients.\n   *\n   * @param checkIn An object that describes a check in.\n   * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n   * to create a monitor automatically when sending a check in.\n   * @param scope An optional scope containing event metadata.\n   * @returns A string representing the id of the check in.\n   */\n  public captureCheckIn?(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string;\n\n  /**\n   * Get the current Dsn.\n   */\n  public getDsn(): DsnComponents | undefined {\n    return this._dsn;\n  }\n\n  /**\n   * Get the current options.\n   */\n  public getOptions(): O {\n    return this._options;\n  }\n\n  /**\n   * Get the SDK metadata.\n   * @see SdkMetadata\n   */\n  public getSdkMetadata(): SdkMetadata | undefined {\n    return this._options._metadata;\n  }\n\n  /**\n   * Returns the transport that is used by the client.\n   * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n   */\n  public getTransport(): Transport | undefined {\n    return this._transport;\n  }\n\n  /**\n   * Wait for all events to be sent or the timeout to expire, whichever comes first.\n   *\n   * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will\n   *   cause the client to wait until all events are sent before resolving the promise.\n   * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n   * still events in the queue when the timeout is reached.\n   */\n  // @ts-expect-error - PromiseLike is a subset of Promise\n  public async flush(timeout?: number): PromiseLike\u003cboolean\u003e {\n    const transport = this._transport;\n    if (!transport) {\n      return true;\n    }\n\n    this.emit('flush');\n\n    const clientFinished = await this._isClientDoneProcessing(timeout);\n    const transportFlushed = await transport.flush(timeout);\n\n    return clientFinished \u0026\u0026 transportFlushed;\n  }\n\n  /**\n   * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.\n   *\n   * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause\n   *   the client to wait until all events are sent before disabling itself.\n   * @returns {Promise\u003cboolean\u003e} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if\n   * it doesn't.\n   */\n  // @ts-expect-error - PromiseLike is a subset of Promise\n  public async close(timeout?: number): PromiseLike\u003cboolean\u003e {\n    _INTERNAL_flushLogsBuffer(this);\n    const result = await this.flush(timeout);\n    this.getOptions().enabled = false;\n    this.emit('close');\n    return result;\n  }\n\n  /**\n   * Get all installed event processors.\n   */\n  public getEventProcessors(): EventProcessor[] {\n    return this._eventProcessors;\n  }\n\n  /**\n   * Adds an event processor that applies to any event processed by this client.\n   */\n  public addEventProcessor(eventProcessor: EventProcessor): void {\n    this._eventProcessors.push(eventProcessor);\n  }\n\n  /**\n   * Initialize this client.\n   * Call this after the client was set on a scope.\n   */\n  public init(): void {\n    if (\n      this._isEnabled() ||\n      // Force integrations to be setup even if no DSN was set when we have\n      // Spotlight enabled. This is particularly important for browser as we\n      // don't support the `spotlight` option there and rely on the users\n      // adding the `spotlightBrowserIntegration()` to their integrations which\n      // wouldn't get initialized with the check below when there's no DSN set.\n      this._options.integrations.some(({ name }) =\u003e name.startsWith('Spotlight'))\n    ) {\n      this._setupIntegrations();\n    }\n  }\n\n  /**\n   * Gets an installed integration by its name.\n   *\n   * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed.\n   */\n  public getIntegrationByName\u003cT extends Integration = Integration\u003e(integrationName: string): T | undefined {\n    return this._integrations[integrationName] as T | undefined;\n  }\n\n  /**\n   * Add an integration to the client.\n   * This can be used to e.g. lazy load integrations.\n   * In most cases, this should not be necessary,\n   * and you're better off just passing the integrations via `integrations: []` at initialization time.\n   * However, if you find the need to conditionally load \u0026 add an integration, you can use `addIntegration` to do so.\n   */\n  public addIntegration(integration: Integration): void {\n    const isAlreadyInstalled = this._integrations[integration.name];\n\n    // This hook takes care of only installing if not already installed\n    setupIntegration(this, integration, this._integrations);\n    // Here we need to check manually to make sure to not run this multiple times\n    if (!isAlreadyInstalled) {\n      afterSetupIntegrations(this, [integration]);\n    }\n  }\n\n  /**\n   * Send a fully prepared event to Sentry.\n   */\n  public sendEvent(event: Event, hint: EventHint = {}): void {\n    this.emit('beforeSendEvent', event, hint);\n\n    let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n    for (const attachment of hint.attachments || []) {\n      env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));\n    }\n\n    // sendEnvelope should not throw\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.sendEnvelope(env).then(sendResponse =\u003e this.emit('afterSendEvent', event, sendResponse));\n  }\n\n  /**\n   * Send a session or session aggregrates to Sentry.\n   */\n  public sendSession(session: Session | SessionAggregates): void {\n    // Backfill release and environment on session\n    const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options;\n    if ('aggregates' in session) {\n      const sessionAttrs = session.attrs || {};\n      if (!sessionAttrs.release \u0026\u0026 !clientReleaseOption) {\n        DEBUG_BUILD \u0026\u0026 debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n        return;\n      }\n      sessionAttrs.release = sessionAttrs.release || clientReleaseOption;\n      sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;\n      session.attrs = sessionAttrs;\n    } else {\n      if (!session.release \u0026\u0026 !clientReleaseOption) {\n        DEBUG_BUILD \u0026\u0026 debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n        return;\n      }\n      session.release = session.release || clientReleaseOption;\n      session.environment = session.environment || clientEnvironmentOption;\n    }\n\n    this.emit('beforeSendSession', session);\n\n    const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n    // sendEnvelope should not throw\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.sendEnvelope(env);\n  }\n\n  /**\n   * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).\n   */\n  public recordDroppedEvent(reason: EventDropReason, category: DataCategory, count: number = 1): void {\n    if (this._options.sendClientReports) {\n      // We want to track each category (error, transaction, session, replay_event) separately\n      // but still keep the distinction between different type of outcomes.\n      // We could use nested maps, but it's much easier to read and type this way.\n      // A correct type for map-based implementation if we want to go that route\n      // would be `Partial\u003cRecord\u003cSentryRequestType, Partial\u003cRecord\u003cOutcome, number\u003e\u003e\u003e\u003e`\n      // With typescript 4.1 we could even use template literal types\n      const key = `${reason}:${category}`;\n      DEBUG_BUILD \u0026\u0026 debug.log(`Recording outcome: \"${key}\"${count \u003e 1 ? ` (${count} times)` : ''}`);\n      this._outcomes[key] = (this._outcomes[key] || 0) + count;\n    }\n  }\n\n  /* eslint-disable @typescript-eslint/unified-signatures */\n  /**\n   * Register a callback for whenever a span is started.\n   * Receives the span as argument.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'spanStart', callback: (span: Span) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback before span sampling runs. Receives a `samplingDecision` object argument with a `decision`\n   * property that can be used to make a sampling decision that will be enforced, before any span sampling runs.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'beforeSampling',\n    callback: (\n      samplingData: {\n        spanAttributes: SpanAttributes;\n        spanName: string;\n        parentSampled?: boolean;\n        parentSampleRate?: number;\n        parentContext?: SpanContextData;\n      },\n      samplingDecision: { decision: boolean },\n    ) =\u003e void,\n  ): void;\n\n  /**\n   * Register a callback for after a span is ended.\n   * NOTE: The span cannot be mutated anymore in this callback.\n   * Receives the span as argument.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'spanEnd', callback: (span: Span) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for when an idle span is allowed to auto-finish.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'idleSpanEnableAutoFinish', callback: (span: Span) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for transaction start and finish.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback that runs when stack frame metadata should be applied to an event.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'applyFrameMetadata', callback: (event: Event) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for before sending an event.\n   * This is called right before an event is sent and should not be used to mutate the event.\n   * Receives an Event \u0026 EventHint as arguments.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint | undefined) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for before sending a session or session aggregrates..\n   * Receives the session/aggregate as second argument.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'beforeSendSession', callback: (session: Session | SessionAggregates) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for preprocessing an event,\n   * before it is passed to (global) event processors.\n   * Receives an Event \u0026 EventHint as arguments.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint | undefined) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for postprocessing an event,\n   * after it was passed to (global) event processors, before it is being sent.\n   * Receives an Event \u0026 EventHint as arguments.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'postprocessEvent', callback: (event: Event, hint?: EventHint | undefined) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback for when an event has been sent.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'afterSendEvent',\n    callback: (event: Event, sendResponse: TransportMakeRequestResponse) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * Register a callback before a breadcrumb is added.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback when a DSC (Dynamic Sampling Context) is created.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) =\u003e void): () =\u003e void;\n\n  /**\n   * Register a callback when a Feedback event has been prepared.\n   * This should be used to mutate the event. The options argument can hint\n   * about what kind of mutation it expects.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'beforeSendFeedback',\n    callback: (feedback: FeedbackEvent, options?: { includeReplay?: boolean }) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * Register a callback when the feedback widget is opened in a user's browser\n   */\n  public on(hook: 'openFeedbackWidget', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook for the browser tracing integrations to trigger a span start for a page load.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'startPageLoadSpan',\n    callback: (\n      options: StartSpanOptions,\n      traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n    ) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook for the browser tracing integrations to trigger the end of a page load span.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'endPageloadSpan', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook for the browser tracing integrations to trigger after the pageload span was started.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'afterStartPageLoadSpan', callback: (span: Span) =\u003e void): () =\u003e void;\n\n  /**\n   * A hook for triggering right before a navigation span is started.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'beforeStartNavigationSpan',\n    callback: (options: StartSpanOptions, navigationOptions?: { isRedirect?: boolean }) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook for browser tracing integrations to trigger a span for a navigation.\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'startNavigationSpan',\n    callback: (options: StartSpanOptions, navigationOptions?: { isRedirect?: boolean }) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook for GraphQL client integration to enhance a span with request data.\n   * @returns A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'beforeOutgoingRequestSpan',\n    callback: (span: Span, hint: XhrBreadcrumbHint | FetchBreadcrumbHint) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook for GraphQL client integration to enhance a breadcrumb with request data.\n   * @returns A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'beforeOutgoingRequestBreadcrumb',\n    callback: (breadcrumb: Breadcrumb, hint: XhrBreadcrumbHint | FetchBreadcrumbHint) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook that is called when the client is flushing\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'flush', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when the client is closing\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'close', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called before a log is captured. This hooks runs before `beforeSendLog` is fired.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'beforeCaptureLog', callback: (log: Log) =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called after a log is captured\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'afterCaptureLog', callback: (log: Log) =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when the client is flushing logs\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'flushLogs', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called after capturing a metric. This hooks runs after `beforeSendMetric` is fired.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'afterCaptureMetric', callback: (metric: Metric) =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when the client is flushing metrics\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'flushMetrics', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when a metric is processed before it is captured and before the `beforeSendMetric` callback is fired.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'processMetric', callback: (metric: Metric) =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when a http server request is started.\n   * This hook is called after request isolation, but before the request is processed.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(\n    hook: 'httpServerRequest',\n    callback: (request: unknown, response: unknown, normalizedRequest: RequestEventData) =\u003e void,\n  ): () =\u003e void;\n\n  /**\n   * A hook that is called when the UI Profiler should start profiling.\n   *\n   * This hook is called when running `Sentry.uiProfiler.startProfiler()`.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'startUIProfiler', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * A hook that is called when the UI Profiler should stop profiling.\n   *\n   * This hook is called when running `Sentry.uiProfiler.stopProfiler()`.\n   *\n   * @returns {() =\u003e void} A function that, when executed, removes the registered callback.\n   */\n  public on(hook: 'stopUIProfiler', callback: () =\u003e void): () =\u003e void;\n\n  /**\n   * Register a hook on this client.\n   */\n  public on(hook: string, callback: unknown): () =\u003e void {\n    const hookCallbacks = (this._hooks[hook] = this._hooks[hook] || new Set());\n\n    // Wrap the callback in a function so that registering the same callback instance multiple\n    // times results in the callback being called multiple times.\n    // @ts-expect-error - The `callback` type is correct and must be a function due to the\n    // individual, specific overloads of this function.\n    // eslint-disable-next-line @typescript-eslint/ban-types\n    const uniqueCallback: Function = (...args: unknown[]) =\u003e callback(...args);\n\n    hookCallbacks.add(uniqueCallback);\n\n    // This function returns a callback execution handler that, when invoked,\n    // deregisters a callback. This is crucial for managing instances where callbacks\n    // need to be unregistered to prevent self-referencing in callback closures,\n    // ensuring proper garbage collection.\n    return () =\u003e {\n      hookCallbacks.delete(uniqueCallback);\n    };\n  }\n\n  /** Fire a hook whenever a span starts. */\n  public emit(hook: 'spanStart', span: Span): void;\n\n  /** A hook that is called every time before a span is sampled. */\n  public emit(\n    hook: 'beforeSampling',\n    samplingData: {\n      spanAttributes: SpanAttributes;\n      spanName: string;\n      parentSampled?: boolean;\n      parentSampleRate?: number;\n      parentContext?: SpanContextData;\n    },\n    samplingDecision: { decision: boolean },\n  ): void;\n\n  /** Fire a hook whenever a span ends. */\n  public emit(hook: 'spanEnd', span: Span): void;\n\n  /**\n   * Fire a hook indicating that an idle span is allowed to auto finish.\n   */\n  public emit(hook: 'idleSpanEnableAutoFinish', span: Span): void;\n\n  /**\n   * Fire a hook event for envelope creation and sending. Expects to be given an envelope as the\n   * second argument.\n   */\n  public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n  /**\n   * Fire a hook indicating that stack frame metadata should be applied to the event passed to the hook.\n   */\n  public emit(hook: 'applyFrameMetadata', event: Event): void;\n\n  /**\n   * Fire a hook event before sending an event.\n   * This is called right before an event is sent and should not be used to mutate the event.\n   * Expects to be given an Event \u0026 EventHint as the second/third argument.\n   */\n  public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n  /**\n   * Fire a hook event before sending a session/aggregates.\n   * Expects to be given the prepared session/aggregates as second argument.\n   */\n  public emit(hook: 'beforeSendSession', session: Session | SessionAggregates): void;\n\n  /**\n   * Fire a hook event to process events before they are passed to (global) event processors.\n   * Expects to be given an Event \u0026 EventHint as the second/third argument.\n   */\n  public emit(hook: 'preprocessEvent', event: Event, hint?: EventHint): void;\n\n  /**\n   * Fire a hook event to process a user on an event before it is sent to Sentry, after all other processors have run.\n   * Expects to be given an Event \u0026 EventHint as the second/third argument.\n   */\n  public emit(hook: 'postprocessEvent', event: Event, hint?: EventHint): void;\n\n  /**\n   * Fire a hook event after sending an event. Expects to be given an Event as the\n   * second argument.\n   */\n  public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse): void;\n\n  /**\n   * Fire a hook for when a breadcrumb is added. Expects the breadcrumb as second argument.\n   */\n  public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n  /**\n   * Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.\n   */\n  public emit(hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void;\n\n  /**\n   * Fire a hook event for after preparing a feedback event. Events to be given\n   * a feedback event as the second argument, and an optional options object as\n   * third argument.\n   */\n  public emit(hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay?: boolean }): void;\n\n  /**\n   * Fire a hook event for when the feedback widget is opened in a user's browser\n   */\n  public emit(hook: 'openFeedbackWidget'): void;\n\n  /**\n   * Emit a hook event for browser tracing integrations to trigger a span start for a page load.\n   */\n  public emit(\n    hook: 'startPageLoadSpan',\n    options: StartSpanOptions,\n    traceOptions?: { sentryTrace?: string | undefined; baggage?: string | undefined },\n  ): void;\n\n  /**\n   * Emit a hook event for browser tracing integrations to trigger the end of a page load span.\n   */\n  public emit(hook: 'endPageloadSpan'): void;\n\n  /**\n   * Emit a hook event for browser tracing integrations to trigger aafter the pageload span was started.\n   */\n  public emit(hook: 'afterStartPageLoadSpan', span: Span): void;\n\n  /**\n   * Emit a hook event for triggering right before a navigation span is started.\n   */\n  public emit(\n    hook: 'beforeStartNavigationSpan',\n    options: StartSpanOptions,\n    navigationOptions?: { isRedirect?: boolean },\n  ): void;\n\n  /**\n   * Emit a hook event for browser tracing integrations to trigger a span for a navigation.\n   */\n  public emit(\n    hook: 'startNavigationSpan',\n    options: StartSpanOptions,\n    navigationOptions?: { isRedirect?: boolean },\n  ): void;\n\n  /**\n   * Emit a hook event for GraphQL client integration to enhance a span with request data.\n   */\n  public emit(hook: 'beforeOutgoingRequestSpan', span: Span, hint: XhrBreadcrumbHint | FetchBreadcrumbHint): void;\n\n  /**\n   * Emit a hook event for GraphQL client integration to enhance a breadcrumb with request data.\n   */\n  public emit(\n    hook: 'beforeOutgoingRequestBreadcrumb',\n    breadcrumb: Breadcrumb,\n    hint: XhrBreadcrumbHint | FetchBreadcrumbHint,\n  ): void;\n\n  /**\n   * Emit a hook event for client flush\n   */\n  public emit(hook: 'flush'): void;\n\n  /**\n   * Emit a hook event for client close\n   */\n  public emit(hook: 'close'): void;\n\n  /**\n   * Emit a hook event for client before capturing a log. This hooks runs before `beforeSendLog` is fired.\n   */\n  public emit(hook: 'beforeCaptureLog', log: Log): void;\n\n  /**\n   * Emit a hook event for client after capturing a log.\n   */\n  public emit(hook: 'afterCaptureLog', log: Log): void;\n\n  /**\n   * Emit a hook event for client flush logs\n   */\n  public emit(hook: 'flushLogs'): void;\n\n  /**\n   * Emit a hook event for client after capturing a metric.\n   */\n  public emit(hook: 'afterCaptureMetric', metric: Metric): void;\n\n  /**\n   * Emit a hook event for client flush metrics\n   */\n  public emit(hook: 'flushMetrics'): void;\n\n  /**\n   *\n   * Emit a hook event for client to process a metric before it is captured.\n   * This hook is called before the `beforeSendMetric` callback is fired.\n   */\n  public emit(hook: 'processMetric', metric: Metric): void;\n\n  /**\n   * Emit a hook event for client when a http server request is started.\n   * This hook is called after request isolation, but before the request is processed.\n   */\n  public emit(\n    hook: 'httpServerRequest',\n    request: unknown,\n    response: unknown,\n    normalizedRequest: RequestEventData,\n  ): void;\n\n  /**\n   * Emit a hook event for starting the UI Profiler.\n   */\n  public emit(hook: 'startUIProfiler'): void;\n\n  /**\n   * Emit a hook event for stopping the UI Profiler.\n   */\n  public emit(hook: 'stopUIProfiler'): void;\n\n  /**\n   * Emit a hook that was previously registered via `on()`.\n   */\n  public emit(hook: string, ...rest: unknown[]): void {\n    const callbacks = this._hooks[hook];\n    if (callbacks) {\n      callbacks.forEach(callback =\u003e callback(...rest));\n    }\n  }\n\n  /**\n   * Send an envelope to Sentry.\n   */\n  // @ts-expect-error - PromiseLike is a subset of Promise\n  public async sendEnvelope(envelope: Envelope): PromiseLike\u003cTransportMakeRequestResponse\u003e {\n    this.emit('beforeEnvelope', envelope);\n\n    if (this._isEnabled() \u0026\u0026 this._transport) {\n      try {\n        return await this._transport.send(envelope);\n      } catch (reason) {\n        DEBUG_BUILD \u0026\u0026 debug.error('Error while sending envelope:', reason);\n        return {};\n      }\n    }\n\n    DEBUG_BUILD \u0026\u0026 debug.error('Transport disabled');\n    return {};\n  }\n\n  /**\n   * Disposes of the client and releases all resources.\n   *\n   * Subclasses should override this method to clean up their own resources.\n   * After calling dispose(), the client should not be used anymore.\n   */\n  public dispose(): void {\n    // Base class has no cleanup logic - subclasses implement their own\n  }\n\n  /* eslint-enable @typescript-eslint/unified-signatures */\n\n  /** Setup integrations for this client. */\n  protected _setupIntegrations(): void {\n    const { integrations } = this._options;\n    this._integrations = setupIntegrations(this, integrations);\n    afterSetupIntegrations(this, integrations);\n  }\n\n  /** Updates existing session based on the provided event */\n  protected _updateSessionFromEvent(session: Session, event: Event): void {\n    // initially, set `crashed` based on the event level and update from exceptions if there are any later on\n    let crashed = event.level === 'fatal';\n    let errored = false;\n    const exceptions = event.exception?.values;\n\n    if (exceptions) {\n      errored = true;\n      // reset crashed to false if there are exceptions, to ensure `mechanism.handled` is respected.\n      crashed = false;\n\n      for (const ex of exceptions) {\n        if (ex.mechanism?.handled === false) {\n          crashed = true;\n          break;\n        }\n      }\n    }\n\n    // A session is updated and that session update is sent in only one of the two following scenarios:\n    // 1. Session with non terminal status and 0 errors + an error occurred -\u003e Will set error count to 1 and send update\n    // 2. Session with non terminal status and 1 error + a crash occurred -\u003e Will set status crashed and send update\n    const sessionNonTerminal = session.status === 'ok';\n    const shouldUpdateAndSend = (sessionNonTerminal \u0026\u0026 session.errors === 0) || (sessionNonTerminal \u0026\u0026 crashed);\n\n    if (shouldUpdateAndSend) {\n      updateSession(session, {\n        ...(crashed \u0026\u0026 { status: 'crashed' }),\n        errors: session.errors || Number(errored || crashed),\n      });\n      this.captureSession(session);\n    }\n  }\n\n  /**\n   * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n   * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n   *\n   * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n   * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n   * `true`.\n   * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n   * `false` otherwise\n   */\n  protected async _isClientDoneProcessing(timeout?: number): Promise\u003cboolean\u003e {\n    let ticked = 0;\n\n    while (!timeout || ticked \u003c timeout) {\n      await new Promise(resolve =\u003e setTimeout(resolve, 1));\n\n      if (!this._numProcessing) {\n        return true;\n      }\n      ticked++;\n    }\n\n    return false;\n  }\n\n  /** Determines whether this SDK is enabled and a transport is present. */\n  protected _isEnabled(): boolean {\n    return this.getOptions().enabled !== false \u0026\u0026 this._transport !== undefined;\n  }\n\n  /**\n   * Adds common information to events.\n   *\n   * The information includes release and environment from `options`,\n   * breadcrumbs and context (extra, tags and user) from the scope.\n   *\n   * Information that is already present in the event is never overwritten. For\n   * nested objects, such as the context, keys are merged.\n   *\n   * @param event The original event.\n   * @param hint May contain additional information about the original exception.\n   * @param currentScope A scope containing event metadata.\n   * @returns A new event with more information.\n   */\n  protected _prepareEvent(\n    event: Event,\n    hint: EventHint,\n    currentScope: Scope,\n    isolationScope: Scope,\n  ): PromiseLike\u003cEvent | null\u003e {\n    const options = this.getOptions();\n    const integrations = Object.keys(this._integrations);\n    if (!hint.integrations \u0026\u0026 integrations?.length) {\n      hint.integrations = integrations;\n    }\n\n    this.emit('preprocessEvent', event, hint);\n\n    if (!event.type) {\n      isolationScope.setLastEventId(event.event_id || hint.event_id);\n    }\n\n    return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt =\u003e {\n      if (evt === null) {\n        return evt;\n      }\n\n      this.emit('postprocessEvent', evt, hint);\n\n      evt.contexts = {\n        trace: { ...evt.contexts?.trace, ...getTraceContextFromScope(currentScope) },\n        ...evt.contexts,\n      };\n\n      const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\n\n      evt.sdkProcessingMetadata = {\n        dynamicSamplingContext,\n        ...evt.sdkProcessingMetadata,\n      };\n\n      return evt;\n    });\n  }\n\n  /**\n   * Processes the event and logs an error in case of rejection\n   * @param event\n   * @param hint\n   * @param scope\n   */\n  protected _captureEvent(\n    event: Event,\n    hint: EventHint = {},\n    currentScope = getCurrentScope(),\n    isolationScope = getIsolationScope(),\n  ): PromiseLike\u003cstring | undefined\u003e {\n    if (DEBUG_BUILD \u0026\u0026 isErrorEvent(event)) {\n      debug.log(`Captured error event \\`${getPossibleEventMessages(event)[0] || '\u003cunknown\u003e'}\\``);\n    }\n\n    return this._processEvent(event, hint, currentScope, isolationScope).then(\n      finalEvent =\u003e {\n        return finalEvent.event_id;\n      },\n      reason =\u003e {\n        if (DEBUG_BUILD) {\n          if (_isDoNotSendEventError(reason)) {\n            debug.log(reason.message);\n          } else if (_isInternalError(reason)) {\n            debug.warn(reason.message);\n          } else {\n            debug.warn(reason);\n          }\n        }\n        return undefined;\n      },\n    );\n  }\n\n  /**\n   * Processes an event (either error or message) and sends it to Sentry.\n   *\n   * This also adds breadcrumbs and context information to the event. However,\n   * platform specific meta data (such as the User's IP address) must be added\n   * by the SDK implementor.\n   *\n   *\n   * @param event The event to send to Sentry.\n   * @param hint May contain additional information about the original exception.\n   * @param currentScope A scope containing event metadata.\n   * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n   */\n  protected _processEvent(\n    event: Event,\n    hint: EventHint,\n    currentScope: Scope,\n    isolationScope: Scope,\n  ): PromiseLike\u003cEvent\u003e {\n    const options = this.getOptions();\n    const { sampleRate } = options;\n\n    const isTransaction = isTransactionEvent(event);\n    const isError = isErrorEvent(event);\n    const eventType = event.type || 'error';\n    const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n    // 1.0 === 100% events are sent\n    // 0.0 === 0% events are sent\n    // Sampling for transaction happens somewhere else\n    const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n    if (isError \u0026\u0026 typeof parsedSampleRate === 'number' \u0026\u0026 safeMathRandom() \u003e parsedSampleRate) {\n      this.recordDroppedEvent('sample_rate', 'error');\n      return rejectedSyncPromise(\n        _makeDoNotSendEventError(\n          `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n        ),\n      );\n    }\n\n    const dataCategory = getDataCategoryByType(event.type);\n\n    return this._prepareEvent(event, hint, currentScope, isolationScope)\n      .then(prepared =\u003e {\n        if (prepared === null) {\n          this.recordDroppedEvent('event_processor', dataCategory);\n          throw _makeDoNotSendEventError('An event processor returned `null`, will not send event.');\n        }\n\n        const isInternalException = (hint.data as { __sentry__: boolean })?.__sentry__ === true;\n        if (isInternalException) {\n          return prepared;\n        }\n\n        const result = processBeforeSend(this, options, prepared, hint);\n        return _validateBeforeSendResult(result, beforeSendLabel);\n      })\n      .then(processedEvent =\u003e {\n        if (processedEvent === null) {\n          this.recordDroppedEvent('before_send', dataCategory);\n          if (isTransaction) {\n            const spans = event.spans || [];\n            // the transaction itself counts as one span, plus all the child spans that are added\n            const spanCount = 1 + spans.length;\n            this.recordDroppedEvent('before_send', 'span', spanCount);\n          }\n          throw _makeDoNotSendEventError(`${beforeSendLabel} returned \\`null\\`, will not send event.`);\n        }\n\n        const session = currentScope.getSession() || isolationScope.getSession();\n        if (isError \u0026\u0026 session) {\n          this._updateSessionFromEvent(session, processedEvent);\n        }\n\n        if (isTransaction) {\n          const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0;\n          const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n          const droppedSpanCount = spanCountBefore - spanCountAfter;\n          if (droppedSpanCount \u003e 0) {\n            this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n          }\n        }\n\n        // None of the Sentry built event processor will update transaction name,\n        // so if the transaction name has been changed by an event processor, we know\n        // it has to come from custom event processor added by a user\n        const transactionInfo = processedEvent.transaction_info;\n        if (isTransaction \u0026\u0026 transactionInfo \u0026\u0026 processedEvent.transaction !== event.transaction) {\n          const source = 'custom';\n          processedEvent.transaction_info = {\n            ...transactionInfo,\n            source,\n          };\n        }\n\n        this.sendEvent(processedEvent, hint);\n        return processedEvent;\n      })\n      .then(null, reason =\u003e {\n        if (_isDoNotSendEventError(reason) || _isInternalError(reason)) {\n          throw reason;\n        }\n\n        this.captureException(reason, {\n          mechanism: {\n            handled: false,\n            type: 'internal',\n          },\n          data: {\n            __sentry__: true,\n          },\n          originalException: reason,\n        });\n        throw _makeInternalError(\n          `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n        );\n      });\n  }\n\n  /**\n   * Occupies the client with processing and event\n   */\n  protected _process\u003cT\u003e(taskProducer: () =\u003e PromiseLike\u003cT\u003e, dataCategory: DataCategory): void {\n    this._numProcessing++;\n\n    void this._promiseBuffer.add(taskProducer).then(\n      value =\u003e {\n        this._numProcessing--;\n        return value;\n      },\n      reason =\u003e {\n        this._numProcessing--;\n\n        if (reason === SENTRY_BUFFER_FULL_ERROR) {\n          this.recordDroppedEvent('queue_overflow', dataCategory);\n        }\n\n        return reason;\n      },\n    );\n  }\n\n  /**\n   * Clears outcomes on this client and returns them.\n   */\n  protected _clearOutcomes(): Outcome[] {\n    const outcomes = this._outcomes;\n    this._outcomes = {};\n    return Object.entries(outcomes).map(([key, quantity]) =\u003e {\n      const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n      return {\n        reason,\n        category,\n        quantity,\n      };\n    });\n  }\n\n  /**\n   * Sends client reports as an envelope.\n   */\n  protected _flushOutcomes(): void {\n    DEBUG_BUILD \u0026\u0026 debug.log('Flushing outcomes...');\n\n    const outcomes = this._clearOutcomes();\n\n    if (outcomes.length === 0) {\n      DEBUG_BUILD \u0026\u0026 debug.log('No outcomes to send');\n      return;\n    }\n\n    // This is really the only place where we want to check for a DSN and only send outcomes then\n    if (!this._dsn) {\n      DEBUG_BUILD \u0026\u0026 debug.log('No dsn provided, will not send outcomes');\n      return;\n    }\n\n    DEBUG_BUILD \u0026\u0026 debug.log('Sending outcomes:', outcomes);\n\n    const envelope = createClientReportEnvelope(outcomes, this._options.tunnel \u0026\u0026 dsnToString(this._dsn));\n\n    // sendEnvelope should not throw\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.sendEnvelope(envelope);\n  }\n\n  /**\n   * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n   */\n  public abstract eventFromException(_exception: unknown, _hint?: EventHint): PromiseLike\u003cEvent\u003e;\n\n  /**\n   * Creates an {@link Event} from primitive inputs to `captureMessage`.\n   */\n  public abstract eventFromMessage(\n    _message: ParameterizedString,\n    _level?: SeverityLevel,\n    _hint?: EventHint,\n  ): PromiseLike\u003cEvent\u003e;\n}\n\nfunction getDataCategoryByType(type: EventType | 'replay_event' | undefined): DataCategory {\n  return type === 'replay_event' ? 'replay' : type || 'error';\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n  beforeSendResult: PromiseLike\u003cEvent | null\u003e | Event | null,\n  beforeSendLabel: string,\n): PromiseLike\u003cEvent | null\u003e | Event | null {\n  const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n  if (isThenable(beforeSendResult)) {\n    return beforeSendResult.then(\n      event =\u003e {\n        if (!isPlainObject(event) \u0026\u0026 event !== null) {\n          throw _makeInternalError(invalidValueError);\n        }\n        return event;\n      },\n      e =\u003e {\n        throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`);\n      },\n    );\n  } else if (!isPlainObject(beforeSendResult) \u0026\u0026 beforeSendResult !== null) {\n    throw _makeInternalError(invalidValueError);\n  }\n  return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n  client: Client,\n  options: ClientOptions,\n  event: Event,\n  hint: EventHint,\n): PromiseLike\u003cEvent | null\u003e | Event | null {\n  const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options;\n  let processedEvent = event;\n\n  if (isErrorEvent(processedEvent) \u0026\u0026 beforeSend) {\n    return beforeSend(processedEvent, hint);\n  }\n\n  if (isTransactionEvent(processedEvent)) {\n    // Avoid processing if we don't have to\n    if (beforeSendSpan || ignoreSpans) {\n      // 1. Process root span\n      const rootSpanJson = convertTransactionEventToSpanJson(processedEvent);\n\n      // 1.1 If the root span should be ignored, drop the whole transaction\n      if (ignoreSpans?.length \u0026\u0026 shouldIgnoreSpan(rootSpanJson, ignoreSpans)) {\n        // dropping the whole transaction!\n        return null;\n      }\n\n      // 1.2 If a `beforeSendSpan` callback is defined, process the root span\n      if (beforeSendSpan) {\n        const processedRootSpanJson = beforeSendSpan(rootSpanJson);\n        if (!processedRootSpanJson) {\n          showSpanDropWarning();\n        } else {\n          // update event with processed root span values\n          processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));\n        }\n      }\n\n      // 2. Process child spans\n      if (processedEvent.spans) {\n        const processedSpans: SpanJSON[] = [];\n\n        const initialSpans = processedEvent.spans;\n\n        for (const span of initialSpans) {\n          // 2.a If the child span should be ignored, reparent it to the root span\n          if (ignoreSpans?.length \u0026\u0026 shouldIgnoreSpan(span, ignoreSpans)) {\n            reparentChildSpans(initialSpans, span);\n            continue;\n          }\n\n          // 2.b If a `beforeSendSpan` callback is defined, process the child span\n          if (beforeSendSpan) {\n            const processedSpan = beforeSendSpan(span);\n            if (!processedSpan) {\n              showSpanDropWarning();\n              processedSpans.push(span);\n            } else {\n              processedSpans.push(processedSpan);\n            }\n          } else {\n            processedSpans.push(span);\n          }\n        }\n\n        const droppedSpans = processedEvent.spans.length - processedSpans.length;\n        if (droppedSpans) {\n          client.recordDroppedEvent('before_send', 'span', droppedSpans);\n        }\n\n        processedEvent.spans = processedSpans;\n      }\n    }\n\n    if (beforeSendTransaction) {\n      if (processedEvent.spans) {\n        // We store the # of spans before processing in SDK metadata,\n        // so we can compare it afterwards to determine how many spans were dropped\n        const spanCountBefore = processedEvent.spans.length;\n        processedEvent.sdkProcessingMetadata = {\n          ...event.sdkProcessingMetadata,\n          spanCountBeforeProcessing: spanCountBefore,\n        };\n      }\n      return beforeSendTransaction(processedEvent as TransactionEvent, hint);\n    }\n  }\n\n  return processedEvent;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n  return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n  return event.type === 'transaction';\n}\n\n/**\n * Estimate the size of a metric in bytes.\n *\n * @param metric - The metric to estimate the size of.\n * @returns The estimated size of the metric in bytes.\n */\nfunction estimateMetricSizeInBytes(metric: Metric): number {\n  let weight = 0;\n\n  // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n  if (metric.name) {\n    weight += metric.name.length * 2;\n  }\n\n  // Add weight for number\n  weight += 8;\n\n  return weight + estimateAttributesSizeInBytes(metric.attributes);\n}\n\n/**\n * Estimate the size of a log in bytes.\n *\n * @param log - The log to estimate the size of.\n * @returns The estimated size of the log in bytes.\n */\nfunction estimateLogSizeInBytes(log: Log): number {\n  let weight = 0;\n\n  // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n  if (log.message) {\n    weight += log.message.length * 2;\n  }\n\n  return weight + estimateAttributesSizeInBytes(log.attributes);\n}\n\n/**\n * Estimate the size of attributes in bytes.\n *\n * @param attributes - The attributes object to estimate the size of.\n * @returns The estimated size of the attributes in bytes.\n */\nfunction estimateAttributesSizeInBytes(attributes: Record\u003cstring, unknown\u003e | undefined): number {\n  if (!attributes) {\n    return 0;\n  }\n\n  let weight = 0;\n\n  Object.values(attributes).forEach(value =\u003e {\n    if (Array.isArray(value)) {\n      weight += value.length * estimatePrimitiveSizeInBytes(value[0]);\n    } else if (isPrimitive(value)) {\n      weight += estimatePrimitiveSizeInBytes(value);\n    } else {\n      // For objects values, we estimate the size of the object as 100 bytes\n      weight += 100;\n    }\n  });\n\n  return weight;\n}\n\nfunction estimatePrimitiveSizeInBytes(value: Primitive): number {\n  if (typeof value === 'string') {\n    return value.length * 2;\n  } else if (typeof value === 'number') {\n    return 8;\n  } else if (typeof value === 'boolean') {\n    return 4;\n  }\n\n  return 0;\n}\n","import type { SerializedCheckIn } from './types-hoist/checkin';\nimport type { DsnComponents } from './types-hoist/dsn';\nimport type { CheckInEnvelope, CheckInItem, DynamicSamplingContext } from './types-hoist/envelope';\nimport type { SdkMetadata } from './types-hoist/sdkmetadata';\nimport { dsnToString } from './utils/dsn';\nimport { createEnvelope } from './utils/envelope';\n\n/**\n * Create envelope from check in item.\n */\nexport function createCheckInEnvelope(\n  checkIn: SerializedCheckIn,\n  dynamicSamplingContext?: Partial\u003cDynamicSamplingContext\u003e,\n  metadata?: SdkMetadata,\n  tunnel?: string,\n  dsn?: DsnComponents,\n): CheckInEnvelope {\n  const headers: CheckInEnvelope[0] = {\n    sent_at: new Date().toISOString(),\n  };\n\n  if (metadata?.sdk) {\n    headers.sdk = {\n      name: metadata.sdk.name,\n      version: metadata.sdk.version,\n    };\n  }\n\n  if (!!tunnel \u0026\u0026 !!dsn) {\n    headers.dsn = dsnToString(dsn);\n  }\n\n  if (dynamicSamplingContext) {\n    headers.trace = dynamicSamplingContext as DynamicSamplingContext;\n  }\n\n  const item = createCheckInEnvelopeItem(checkIn);\n  return createEnvelope\u003cCheckInEnvelope\u003e(headers, [item]);\n}\n\nfunction createCheckInEnvelopeItem(checkIn: SerializedCheckIn): CheckInItem {\n  const checkInHeaders: CheckInItem[0] = {\n    type: 'check_in',\n  };\n  return [checkInHeaders, checkIn];\n}\n","import type { ClientOptions } from '../types-hoist/options';\n\n/**\n * Takes the SDK metadata and adds the user-agent header to the transport options.\n * This ensures that the SDK sends the user-agent header with SDK name and version to\n * all requests made by the transport.\n *\n * @see https://develop.sentry.dev/sdk/overview/#user-agent\n */\nexport function addUserAgentToTransportHeaders(options: ClientOptions): void {\n  const sdkMetadata = options._metadata?.sdk;\n  const sdkUserAgent =\n    sdkMetadata?.name \u0026\u0026 sdkMetadata?.version ? `${sdkMetadata?.name}/${sdkMetadata?.version}` : undefined;\n\n  options.transportOptions = {\n    ...options.transportOptions,\n    headers: {\n      ...(sdkUserAgent \u0026\u0026 { 'user-agent': sdkUserAgent }),\n      ...options.transportOptions?.headers,\n    },\n  };\n}\n","import type { Client } from '../client';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { Extras } from '../types-hoist/extra';\nimport type { Mechanism } from '../types-hoist/mechanism';\nimport type { ParameterizedString } from '../types-hoist/parameterize';\nimport type { SeverityLevel } from '../types-hoist/severity';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { isError, isErrorEvent, isParameterizedString, isPlainObject } from './is';\nimport { addExceptionMechanism, addExceptionTypeValue } from './misc';\nimport { normalizeToSize } from './normalize';\nimport { extractExceptionKeysForMessage } from './object';\n\n/**\n * Extracts stack frames from the error.stack string\n */\nexport function parseStackFrames(stackParser: StackParser, error: Error): StackFrame[] {\n  return stackParser(error.stack || '', 1);\n}\n\nfunction hasSentryFetchUrlHost(error: unknown): error is Error \u0026 { __sentry_fetch_url_host__: string } {\n  return isError(error) \u0026\u0026 '__sentry_fetch_url_host__' in error \u0026\u0026 typeof error.__sentry_fetch_url_host__ === 'string';\n}\n\n/**\n * Enhances the error message with the hostname for better Sentry error reporting.\n * This allows third-party packages to still match on the original error message,\n * while Sentry gets the enhanced version with context.\n *\n * Only used internally\n * @hidden\n */\nexport function _enhanceErrorWithSentryInfo\u003cT extends Error\u003e(error: T): string {\n  // If the error has a __sentry_fetch_url_host__ property (added by fetch instrumentation),\n  // enhance the error message with the hostname.\n  if (hasSentryFetchUrlHost(error)) {\n    return `${error.message} (${error.__sentry_fetch_url_host__})`;\n  }\n\n  return error.message;\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nexport function exceptionFromError(stackParser: StackParser, error: Error): Exception {\n  const exception: Exception = {\n    type: error.name || error.constructor.name,\n    value: _enhanceErrorWithSentryInfo(error),\n  };\n\n  const frames = parseStackFrames(stackParser, error);\n  if (frames.length) {\n    exception.stacktrace = { frames };\n  }\n\n  return exception;\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj: Record\u003cstring, unknown\u003e): Error | undefined {\n  for (const prop in obj) {\n    if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n      const value = obj[prop];\n      if (value instanceof Error) {\n        return value;\n      }\n    }\n  }\n\n  return undefined;\n}\n\nfunction getMessageForObject(exception: Record\u003cstring, unknown\u003e): string {\n  if ('name' in exception \u0026\u0026 typeof exception.name === 'string') {\n    let message = `'${exception.name}' captured as exception`;\n\n    if ('message' in exception \u0026\u0026 typeof exception.message === 'string') {\n      message += ` with message '${exception.message}'`;\n    }\n\n    return message;\n  } else if ('message' in exception \u0026\u0026 typeof exception.message === 'string') {\n    return exception.message;\n  }\n\n  const keys = extractExceptionKeysForMessage(exception);\n\n  // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n  // We still want to try to get a decent message for these cases\n  if (isErrorEvent(exception)) {\n    return `Event \\`ErrorEvent\\` captured as exception with message \\`${exception.message}\\``;\n  }\n\n  const className = getObjectClassName(exception);\n\n  return `${\n    className \u0026\u0026 className !== 'Object' ? `'${className}'` : 'Object'\n  } captured as exception with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n  try {\n    const prototype: unknown | null = Object.getPrototypeOf(obj);\n    return prototype ? prototype.constructor.name : undefined;\n  } catch {\n    // ignore errors here\n  }\n}\n\nfunction getException(\n  client: Client,\n  mechanism: Mechanism,\n  exception: unknown,\n  hint?: EventHint,\n): [Error, Extras | undefined] {\n  if (isError(exception)) {\n    return [exception, undefined];\n  }\n\n  // Mutate this!\n  mechanism.synthetic = true;\n\n  if (isPlainObject(exception)) {\n    const normalizeDepth = client?.getOptions().normalizeDepth;\n    const extras = { ['__serialized__']: normalizeToSize(exception, normalizeDepth) };\n\n    const errorFromProp = getErrorPropertyFromObject(exception);\n    if (errorFromProp) {\n      return [errorFromProp, extras];\n    }\n\n    const message = getMessageForObject(exception);\n    const ex = hint?.syntheticException || new Error(message);\n    ex.message = message;\n\n    return [ex, extras];\n  }\n\n  // This handles when someone does: `throw \"something awesome\";`\n  // We use synthesized Error here so we can extract a (rough) stack trace.\n  const ex = hint?.syntheticException || new Error(exception as string);\n  ex.message = `${exception}`;\n\n  return [ex, undefined];\n}\n\n/**\n * Builds and Event from a Exception\n * @hidden\n */\nexport function eventFromUnknownInput(\n  client: Client,\n  stackParser: StackParser,\n  exception: unknown,\n  hint?: EventHint,\n): Event {\n  const providedMechanism: Mechanism | undefined = hint?.data \u0026\u0026 (hint.data as { mechanism: Mechanism }).mechanism;\n  const mechanism: Mechanism = providedMechanism || {\n    handled: true,\n    type: 'generic',\n  };\n\n  const [ex, extras] = getException(client, mechanism, exception, hint);\n\n  const event: Event = {\n    exception: {\n      values: [exceptionFromError(stackParser, ex)],\n    },\n  };\n\n  if (extras) {\n    event.extra = extras;\n  }\n\n  addExceptionTypeValue(event, undefined, undefined);\n  addExceptionMechanism(event, mechanism);\n\n  return {\n    ...event,\n    event_id: hint?.event_id,\n  };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n  stackParser: StackParser,\n  message: ParameterizedString,\n  level: SeverityLevel = 'info',\n  hint?: EventHint,\n  attachStacktrace?: boolean,\n): Event {\n  const event: Event = {\n    event_id: hint?.event_id,\n    level,\n  };\n\n  if (attachStacktrace \u0026\u0026 hint?.syntheticException) {\n    const frames = parseStackFrames(stackParser, hint.syntheticException);\n    if (frames.length) {\n      event.exception = {\n        values: [\n          {\n            value: message,\n            stacktrace: { frames },\n          },\n        ],\n      };\n      addExceptionMechanism(event, { synthetic: true });\n    }\n  }\n\n  if (isParameterizedString(message)) {\n    const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n    event.logentry = {\n      message: __sentry_template_string__,\n      params: __sentry_template_values__,\n    };\n    return event;\n  }\n\n  event.message = message;\n  return event;\n}\n","import { createCheckInEnvelope } from './checkin';\nimport { Client } from './client';\nimport { getIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Scope } from './scope';\nimport { registerSpanErrorInstrumentation } from './tracing';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base';\nimport { addUserAgentToTransportHeaders } from './transports/userAgent';\nimport type { CheckIn, MonitorConfig, SerializedCheckIn } from './types-hoist/checkin';\nimport type { Event, EventHint } from './types-hoist/event';\nimport type { ClientOptions } from './types-hoist/options';\nimport type { ParameterizedString } from './types-hoist/parameterize';\nimport type { SeverityLevel } from './types-hoist/severity';\nimport type { BaseTransportOptions, Transport } from './types-hoist/transport';\nimport { debug } from './utils/debug-logger';\nimport { eventFromMessage, eventFromUnknownInput } from './utils/eventbuilder';\nimport { uuid4 } from './utils/misc';\nimport { makePromiseBuffer } from './utils/promisebuffer';\nimport { resolvedSyncPromise } from './utils/syncpromise';\nimport { _getTraceInfoFromScope } from './utils/trace-info';\n\nexport interface ServerRuntimeClientOptions extends ClientOptions\u003cBaseTransportOptions\u003e {\n  platform?: string;\n  runtime?: { name: string; version?: string };\n  serverName?: string;\n}\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nexport class ServerRuntimeClient\u003c\n  O extends ClientOptions \u0026 ServerRuntimeClientOptions = ServerRuntimeClientOptions,\n\u003e extends Client\u003cO\u003e {\n  /**\n   * Creates a new Edge SDK instance.\n   * @param options Configuration options for this SDK.\n   */\n  public constructor(options: O) {\n    // Server clients always support tracing\n    registerSpanErrorInstrumentation();\n\n    addUserAgentToTransportHeaders(options);\n\n    super(options);\n\n    this._setUpMetricsProcessing();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public eventFromException(exception: unknown, hint?: EventHint): PromiseLike\u003cEvent\u003e {\n    const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint);\n    event.level = 'error';\n\n    return resolvedSyncPromise(event);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public eventFromMessage(\n    message: ParameterizedString,\n    level: SeverityLevel = 'info',\n    hint?: EventHint,\n  ): PromiseLike\u003cEvent\u003e {\n    return resolvedSyncPromise(\n      eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n    );\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {\n    setCurrentRequestSessionErroredOrCrashed(hint);\n    return super.captureException(exception, hint, scope);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string {\n    // If the event is of type Exception, then a request session should be captured\n    const isException = !event.type \u0026\u0026 event.exception?.values \u0026\u0026 event.exception.values.length \u003e 0;\n    if (isException) {\n      setCurrentRequestSessionErroredOrCrashed(hint);\n    }\n\n    return super.captureEvent(event, hint, scope);\n  }\n\n  /**\n   * Create a cron monitor check in and send it to Sentry.\n   *\n   * @param checkIn An object that describes a check in.\n   * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n   * to create a monitor automatically when sending a check in.\n   */\n  public captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n    const id = 'checkInId' in checkIn \u0026\u0026 checkIn.checkInId ? checkIn.checkInId : uuid4();\n    if (!this._isEnabled()) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('SDK not enabled, will not capture check-in.');\n      return id;\n    }\n\n    const options = this.getOptions();\n    const { release, environment, tunnel } = options;\n\n    const serializedCheckIn: SerializedCheckIn = {\n      check_in_id: id,\n      monitor_slug: checkIn.monitorSlug,\n      status: checkIn.status,\n      release,\n      environment,\n    };\n\n    if ('duration' in checkIn) {\n      serializedCheckIn.duration = checkIn.duration;\n    }\n\n    if (monitorConfig) {\n      serializedCheckIn.monitor_config = {\n        schedule: monitorConfig.schedule,\n        checkin_margin: monitorConfig.checkinMargin,\n        max_runtime: monitorConfig.maxRuntime,\n        timezone: monitorConfig.timezone,\n        failure_issue_threshold: monitorConfig.failureIssueThreshold,\n        recovery_threshold: monitorConfig.recoveryThreshold,\n      };\n    }\n\n    const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope);\n    if (traceContext) {\n      serializedCheckIn.contexts = {\n        trace: traceContext,\n      };\n    }\n\n    const envelope = createCheckInEnvelope(\n      serializedCheckIn,\n      dynamicSamplingContext,\n      this.getSdkMetadata(),\n      tunnel,\n      this.getDsn(),\n    );\n\n    DEBUG_BUILD \u0026\u0026 debug.log('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n    // sendEnvelope should not throw\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    this.sendEnvelope(envelope);\n\n    return id;\n  }\n\n  /**\n   * Disposes of the client and releases all resources.\n   *\n   * This method clears all internal state to allow the client to be garbage collected.\n   * It clears hooks, event processors, integrations, transport, and other internal references.\n   *\n   * Call this method after flushing to allow the client to be garbage collected.\n   * After calling dispose(), the client should not be used anymore.\n   *\n   * Subclasses should override this method to clean up their own resources and call `super.dispose()`.\n   */\n  public override dispose(): void {\n    DEBUG_BUILD \u0026\u0026 debug.log('Disposing client...');\n\n    for (const hookName of Object.keys(this._hooks)) {\n      this._hooks[hookName]?.clear();\n    }\n\n    this._hooks = {};\n    this._eventProcessors.length = 0;\n    this._integrations = {};\n    this._outcomes = {};\n    (this as unknown as { _transport?: Transport })._transport = undefined;\n    this._promiseBuffer = makePromiseBuffer(DEFAULT_TRANSPORT_BUFFER_SIZE);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  protected _prepareEvent(\n    event: Event,\n    hint: EventHint,\n    currentScope: Scope,\n    isolationScope: Scope,\n  ): PromiseLike\u003cEvent | null\u003e {\n    if (this._options.platform) {\n      event.platform = event.platform || this._options.platform;\n    }\n\n    if (this._options.runtime) {\n      event.contexts = {\n        ...event.contexts,\n        runtime: event.contexts?.runtime || this._options.runtime,\n      };\n    }\n\n    if (this._options.serverName) {\n      event.server_name = event.server_name || this._options.serverName;\n    }\n\n    return super._prepareEvent(event, hint, currentScope, isolationScope);\n  }\n\n  /**\n   * Process a server-side metric before it is captured.\n   */\n  private _setUpMetricsProcessing(): void {\n    this.on('processMetric', metric =\u003e {\n      if (this._options.serverName) {\n        metric.attributes = {\n          'server.address': this._options.serverName,\n          ...metric.attributes,\n        };\n      }\n    });\n  }\n}\n\nfunction setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void {\n  const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;\n  if (requestSession) {\n    // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular\n    // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the\n    // original isolation scope that the http integration stored away.\n    const isHandledException = eventHint?.mechanism?.handled ?? true;\n    // A request session can go from \"errored\" -\u003e \"crashed\" but not \"crashed\" -\u003e \"errored\".\n    // Crashed (unhandled exception) is worse than errored (handled exception).\n    if (isHandledException \u0026\u0026 requestSession.status !== 'crashed') {\n      requestSession.status = 'errored';\n    } else if (!isHandledException) {\n      requestSession.status = 'crashed';\n    }\n  }\n}\n","import type { Client } from './client';\nimport { getCurrentScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ClientOptions } from './types-hoist/options';\nimport { consoleSandbox, debug } from './utils/debug-logger';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass\u003cF extends Client, O extends ClientOptions\u003e = new (options: O) =\u003e F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind\u003cF extends Client, O extends ClientOptions\u003e(\n  clientClass: ClientClass\u003cF, O\u003e,\n  options: O,\n): Client {\n  if (options.debug === true) {\n    if (DEBUG_BUILD) {\n      debug.enable();\n    } else {\n      // use `console.warn` rather than `debug.warn` since by non-debug bundles have all `debug.x` statements stripped\n      consoleSandbox(() =\u003e {\n        // eslint-disable-next-line no-console\n        console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n      });\n    }\n  }\n  const scope = getCurrentScope();\n  scope.update(options.initialScope);\n\n  const client = new clientClass(options);\n  setCurrentClient(client);\n  client.init();\n  return client;\n}\n\n/**\n * Make the given client the current client.\n */\nexport function setCurrentClient(client: Client): void {\n  getCurrentScope().setClient(client);\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { Envelope } from '../types-hoist/envelope';\nimport type { InternalBaseTransportOptions, Transport, TransportMakeRequestResponse } from '../types-hoist/transport';\nimport { debug } from '../utils/debug-logger';\nimport { envelopeContainsItemType } from '../utils/envelope';\nimport { parseRetryAfterHeader } from '../utils/ratelimit';\nimport { safeUnref } from '../utils/timer';\n\nexport const MIN_DELAY = 100; // 100 ms\nexport const START_DELAY = 5_000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\nexport interface OfflineStore {\n  push(env: Envelope): Promise\u003cvoid\u003e;\n  unshift(env: Envelope): Promise\u003cvoid\u003e;\n  shift(): Promise\u003cEnvelope | undefined\u003e;\n}\n\nexport type CreateOfflineStore = (options: OfflineTransportOptions) =\u003e OfflineStore;\n\nexport interface OfflineTransportOptions extends InternalBaseTransportOptions {\n  /**\n   * A function that creates the offline store instance.\n   */\n  createStore?: CreateOfflineStore;\n\n  /**\n   * Flush the offline store shortly after startup.\n   *\n   * Defaults: false\n   */\n  flushAtStartup?: boolean;\n\n  /**\n   * Called before an event is stored.\n   *\n   * Return false to drop the envelope rather than store it.\n   *\n   * @param envelope The envelope that failed to send.\n   * @param error The error that occurred.\n   * @param retryDelay The current retry delay in milliseconds.\n   * @returns Whether the envelope should be stored.\n   */\n  shouldStore?: (envelope: Envelope, error: Error, retryDelay: number) =\u003e boolean | Promise\u003cboolean\u003e;\n\n  /**\n   * Should an attempt be made to send the envelope to Sentry.\n   *\n   * If this function is supplied and returns false, `shouldStore` will be called to determine if the envelope should be stored.\n   *\n   * @param envelope The envelope that will be sent.\n   * @returns Whether we should attempt to send the envelope\n   */\n  shouldSend?: (envelope: Envelope) =\u003e boolean | Promise\u003cboolean\u003e;\n}\n\ntype Timer = number | { unref?: () =\u003e void };\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nexport function makeOfflineTransport\u003cTO\u003e(\n  createTransport: (options: TO) =\u003e Transport,\n): (options: TO \u0026 OfflineTransportOptions) =\u003e Transport {\n  function log(...args: unknown[]): void {\n    DEBUG_BUILD \u0026\u0026 debug.log('[Offline]:', ...args);\n  }\n\n  return options =\u003e {\n    const transport = createTransport(options);\n\n    if (!options.createStore) {\n      throw new Error('No `createStore` function was provided');\n    }\n\n    const store = options.createStore(options);\n\n    let retryDelay = START_DELAY;\n    let flushTimer: Timer | undefined;\n\n    function shouldQueue(env: Envelope, error: Error, retryDelay: number): boolean | Promise\u003cboolean\u003e {\n      // We want to drop client reports because they can be generated when we retry sending events while offline.\n      if (envelopeContainsItemType(env, ['client_report'])) {\n        return false;\n      }\n\n      if (options.shouldStore) {\n        return options.shouldStore(env, error, retryDelay);\n      }\n\n      return true;\n    }\n\n    function flushIn(delay: number): void {\n      if (flushTimer) {\n        clearTimeout(flushTimer as ReturnType\u003ctypeof setTimeout\u003e);\n      }\n\n      // We need to unref the timer in node.js, otherwise the node process never exit.\n      flushTimer = safeUnref(\n        setTimeout(async () =\u003e {\n          flushTimer = undefined;\n\n          const found = await store.shift();\n          if (found) {\n            log('Attempting to send previously queued event');\n\n            // We should to update the sent_at timestamp to the current time.\n            found[0].sent_at = new Date().toISOString();\n\n            void send(found, true).catch(e =\u003e {\n              log('Failed to retry sending', e);\n            });\n          }\n        }, delay),\n      ) as Timer;\n    }\n\n    function flushWithBackOff(): void {\n      if (flushTimer) {\n        return;\n      }\n\n      flushIn(retryDelay);\n\n      retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n    }\n\n    async function send(envelope: Envelope, isRetry: boolean = false): Promise\u003cTransportMakeRequestResponse\u003e {\n      // We queue all replay envelopes to avoid multiple replay envelopes being sent at the same time. If one fails, we\n      // need to retry them in order.\n      if (!isRetry \u0026\u0026 envelopeContainsItemType(envelope, ['replay_event', 'replay_recording'])) {\n        await store.push(envelope);\n        flushIn(MIN_DELAY);\n        return {};\n      }\n\n      try {\n        if (options.shouldSend \u0026\u0026 (await options.shouldSend(envelope)) === false) {\n          throw new Error('Envelope not sent because `shouldSend` callback returned false');\n        }\n\n        const result = await transport.send(envelope);\n\n        let delay = MIN_DELAY;\n\n        if (result) {\n          // If there's a retry-after header, use that as the next delay.\n          if (result.headers?.['retry-after']) {\n            delay = parseRetryAfterHeader(result.headers['retry-after']);\n          } else if (result.headers?.['x-sentry-rate-limits']) {\n            delay = 60_000; // 60 seconds\n          } // If we have a server error, return now so we don't flush the queue.\n          else if ((result.statusCode || 0) \u003e= 400) {\n            return result;\n          }\n        }\n\n        flushIn(delay);\n        retryDelay = START_DELAY;\n        return result;\n      } catch (e) {\n        if (await shouldQueue(envelope, e as Error, retryDelay)) {\n          // If this envelope was a retry, we want to add it to the front of the queue so it's retried again first.\n          if (isRetry) {\n            await store.unshift(envelope);\n          } else {\n            await store.push(envelope);\n          }\n          flushWithBackOff();\n          log('Error sending. Event queued.', e as Error);\n          return {};\n        } else {\n          throw e;\n        }\n      }\n    }\n\n    if (options.flushAtStartup) {\n      flushWithBackOff();\n    }\n\n    return {\n      send,\n      flush: timeout =\u003e {\n        // If there's no timeout, we should attempt to flush the offline queue.\n        if (timeout === undefined) {\n          retryDelay = START_DELAY;\n          flushIn(MIN_DELAY);\n        }\n\n        return transport.flush(timeout);\n      },\n    };\n  };\n}\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from '../api';\nimport type { Envelope, EnvelopeItemType, EventItem } from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { BaseTransportOptions, Transport, TransportMakeRequestResponse } from '../types-hoist/transport';\nimport { dsnFromString } from '../utils/dsn';\nimport { createEnvelope, forEachEnvelopeItem } from '../utils/envelope';\n\ninterface MatchParam {\n  /** The envelope to be sent */\n  envelope: Envelope;\n  /**\n   * A function that returns an event from the envelope if one exists. You can optionally pass an array of envelope item\n   * types to filter by - only envelopes matching the given types will be multiplexed.\n   * Allowed values are: 'event', 'transaction', 'profile', 'replay_event'\n   *\n   * @param types Defaults to ['event']\n   */\n  getEvent(types?: EnvelopeItemType[]): Event | undefined;\n}\n\ntype RouteTo = { dsn: string; release: string };\ntype Matcher = (param: MatchParam) =\u003e (string | RouteTo)[];\n\n/**\n * Key used in event.extra to provide routing information for the multiplexed transport.\n * Should contain an array of `{ dsn: string, release?: string }` objects.\n */\nexport const MULTIPLEXED_TRANSPORT_EXTRA_KEY = 'MULTIPLEXED_TRANSPORT_EXTRA_KEY';\n\n/**\n * Gets an event from an envelope.\n *\n * This is only exported for use in the tests\n */\nexport function eventFromEnvelope(env: Envelope, types: EnvelopeItemType[]): Event | undefined {\n  let event: Event | undefined;\n\n  forEachEnvelopeItem(env, (item, type) =\u003e {\n    if (types.includes(type)) {\n      event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n    }\n    // bail out if we found an event\n    return !!event;\n  });\n\n  return event;\n}\n\n/**\n * Creates a transport that overrides the release on all events.\n */\nfunction makeOverrideReleaseTransport\u003cTO extends BaseTransportOptions\u003e(\n  createTransport: (options: TO) =\u003e Transport,\n  release: string,\n): (options: TO) =\u003e Transport {\n  return options =\u003e {\n    const transport = createTransport(options);\n\n    return {\n      ...transport,\n      send: async (envelope: Envelope): Promise\u003cTransportMakeRequestResponse\u003e =\u003e {\n        const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']);\n\n        if (event) {\n          event.release = release;\n        }\n        return transport.send(envelope);\n      },\n    };\n  };\n}\n\n/** Overrides the DSN in the envelope header  */\nfunction overrideDsn(envelope: Envelope, dsn: string): Envelope {\n  return createEnvelope(\n    dsn\n      ? {\n          ...envelope[0],\n          dsn,\n        }\n      : envelope[0],\n    envelope[1],\n  );\n}\n\n/**\n * Creates a transport that can send events to different DSNs depending on the envelope contents.\n *\n * If no matcher is provided, the transport will look for routing information in\n * `event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY]`, which should contain\n * an array of `{ dsn: string, release?: string }` objects.\n */\nexport function makeMultiplexedTransport\u003cTO extends BaseTransportOptions\u003e(\n  createTransport: (options: TO) =\u003e Transport,\n  matcher?: Matcher,\n): (options: TO) =\u003e Transport {\n  return options =\u003e {\n    const fallbackTransport = createTransport(options);\n    const otherTransports: Map\u003cstring, Transport\u003e = new Map();\n\n    // Use provided matcher or default to simple multiplexed transport behavior\n    const actualMatcher: Matcher =\n      matcher ||\n      (args =\u003e {\n        const event = args.getEvent();\n        if (\n          event?.extra?.[MULTIPLEXED_TRANSPORT_EXTRA_KEY] \u0026\u0026\n          Array.isArray(event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY])\n        ) {\n          return event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY];\n        }\n        return [];\n      });\n\n    function getTransport(dsn: string, release: string | undefined): [string, Transport] | undefined {\n      // We create a transport for every unique dsn/release combination as there may be code from multiple releases in\n      // use at the same time\n      const key = release ? `${dsn}:${release}` : dsn;\n\n      let transport = otherTransports.get(key);\n\n      if (!transport) {\n        const validatedDsn = dsnFromString(dsn);\n        if (!validatedDsn) {\n          return undefined;\n        }\n        const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);\n\n        transport = release\n          ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url })\n          : createTransport({ ...options, url });\n\n        otherTransports.set(key, transport);\n      }\n\n      return [dsn, transport];\n    }\n\n    async function send(envelope: Envelope): Promise\u003cTransportMakeRequestResponse\u003e {\n      function getEvent(types?: EnvelopeItemType[]): Event | undefined {\n        const eventTypes: EnvelopeItemType[] = types?.length ? types : ['event'];\n        return eventFromEnvelope(envelope, eventTypes);\n      }\n\n      const transports = actualMatcher({ envelope, getEvent })\n        .map(result =\u003e {\n          if (typeof result === 'string') {\n            return getTransport(result, undefined);\n          } else {\n            return getTransport(result.dsn, result.release);\n          }\n        })\n        .filter((t): t is [string, Transport] =\u003e !!t);\n\n      // If we have no transports to send to, use the fallback transport\n      // Don't override the DSN in the header for the fallback transport. '' is falsy\n      const transportsWithFallback: [string, Transport][] = transports.length ? transports : [['', fallbackTransport]];\n\n      const results = (await Promise.all(\n        transportsWithFallback.map(([dsn, transport]) =\u003e transport.send(overrideDsn(envelope, dsn))),\n      )) as [TransportMakeRequestResponse, ...TransportMakeRequestResponse[]];\n\n      return results[0];\n    }\n\n    async function flush(timeout: number | undefined): Promise\u003cboolean\u003e {\n      const allTransports = [...otherTransports.values(), fallbackTransport];\n      const results = await Promise.all(allTransports.map(transport =\u003e transport.flush(timeout)));\n      return results.every(r =\u003e r);\n    }\n\n    return {\n      send,\n      flush,\n    };\n  };\n}\n","import { DEBUG_BUILD } from '../../debug-build';\nimport { debug } from '../debug-logger';\n\n/**\n * Registry tracking which AI provider modules should skip instrumentation wrapping.\n *\n * This prevents duplicate spans when a higher-level integration (like LangChain)\n * already instruments AI providers at a higher abstraction level.\n */\nconst SKIPPED_AI_PROVIDERS = new Set\u003cstring\u003e();\n\n/**\n * Mark AI provider modules to skip instrumentation wrapping.\n *\n * This prevents duplicate spans when a higher-level integration (like LangChain)\n * already instruments AI providers at a higher abstraction level.\n *\n * @internal\n * @param modules - Array of npm module names to skip (e.g., '@anthropic-ai/sdk', 'openai')\n *\n * @example\n * ```typescript\n * // In LangChain integration\n * _INTERNAL_skipAiProviderWrapping(['@anthropic-ai/sdk', 'openai', '@google/generative-ai']);\n * ```\n */\nexport function _INTERNAL_skipAiProviderWrapping(modules: string[]): void {\n  modules.forEach(module =\u003e {\n    SKIPPED_AI_PROVIDERS.add(module);\n    DEBUG_BUILD \u0026\u0026 debug.log(`AI provider \"${module}\" wrapping will be skipped`);\n  });\n}\n\n/**\n * Check if an AI provider module should skip instrumentation wrapping.\n *\n * @internal\n * @param module - The npm module name (e.g., '@anthropic-ai/sdk', 'openai')\n * @returns true if wrapping should be skipped\n *\n * @example\n * ```typescript\n * // In AI provider instrumentation\n * if (_INTERNAL_shouldSkipAiProviderWrapping('@anthropic-ai/sdk')) {\n *   return Reflect.construct(Original, args); // Don't instrument\n * }\n * ```\n */\nexport function _INTERNAL_shouldSkipAiProviderWrapping(module: string): boolean {\n  return SKIPPED_AI_PROVIDERS.has(module);\n}\n\n/**\n * Clear all AI provider skip registrations.\n *\n * This is automatically called at the start of Sentry.init() to ensure a clean state\n * between different client initializations.\n *\n * @internal\n */\nexport function _INTERNAL_clearAiProviderSkips(): void {\n  SKIPPED_AI_PROVIDERS.clear();\n  DEBUG_BUILD \u0026\u0026 debug.log('Cleared AI provider skip registrations');\n}\n","export const FALSY_ENV_VALUES = new Set(['false', 'f', 'n', 'no', 'off', '0']);\nexport const TRUTHY_ENV_VALUES = new Set(['true', 't', 'y', 'yes', 'on', '1']);\n\nexport type StrictBoolCast = {\n  strict: true;\n};\n\nexport type LooseBoolCast = {\n  strict?: false;\n};\n\nexport type BoolCastOptions = StrictBoolCast | LooseBoolCast;\n\nexport function envToBool(value: unknown, options?: LooseBoolCast): boolean;\nexport function envToBool(value: unknown, options: StrictBoolCast): boolean | null;\nexport function envToBool(value: unknown, options?: BoolCastOptions): boolean | null;\n/**\n * A helper function which casts an ENV variable value to `true` or `false` using the constants defined above.\n * In strict mode, it may return `null` if the value doesn't match any of the predefined values.\n *\n * @param value The value of the env variable\n * @param options -- Only has `strict` key for now, which requires a strict match for `true` in TRUTHY_ENV_VALUES\n * @returns true/false if the lowercase value matches the predefined values above. If not, null in strict mode,\n *          and Boolean(value) in loose mode.\n */\nexport function envToBool(value: unknown, options?: BoolCastOptions): boolean | null {\n  const normalized = String(value).toLowerCase();\n\n  if (FALSY_ENV_VALUES.has(normalized)) {\n    return false;\n  }\n\n  if (TRUTHY_ENV_VALUES.has(normalized)) {\n    return true;\n  }\n\n  return options?.strict ? null : Boolean(value);\n}\n","import {\n  SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,\n  SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n  SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n  SEMANTIC_ATTRIBUTE_URL_FULL,\n} from '../semanticAttributes';\nimport type { SpanAttributes } from '../types-hoist/span';\n\ntype PartialURL = {\n  host?: string;\n  path?: string;\n  protocol?: string;\n  relative?: string;\n  search?: string;\n  hash?: string;\n};\n\ninterface URLwithCanParse extends URL {\n  canParse: (url: string, base?: string | URL | undefined) =\u003e boolean;\n}\n\n// A subset of the URL object that is valid for relative URLs\n// The URL object cannot handle relative URLs, so we need to handle them separately\ntype RelativeURL = {\n  isRelative: true;\n  pathname: URL['pathname'];\n  search: URL['search'];\n  hash: URL['hash'];\n};\n\ntype URLObject = RelativeURL | URL;\n\n// Curious about `thismessage:/`? See: https://www.rfc-editor.org/rfc/rfc2557.html\n//  \u003e When the methods above do not yield an absolute URI, a base URL\n//  \u003e of \"thismessage:/\" MUST be employed. This base URL has been\n//  \u003e defined for the sole purpose of resolving relative references\n//  \u003e within a multipart/related structure when no other base URI is\n//  \u003e specified.\n//\n// We need to provide a base URL to `parseStringToURLObject` because the fetch API gives us a\n// relative URL sometimes.\n//\n// This is the only case where we need to provide a base URL to `parseStringToURLObject`\n// because the relative URL is not valid on its own.\nconst DEFAULT_BASE_URL = 'thismessage:/';\n\n/**\n * Checks if the URL object is relative\n *\n * @param url - The URL object to check\n * @returns True if the URL object is relative, false otherwise\n */\nexport function isURLObjectRelative(url: URLObject): url is RelativeURL {\n  return 'isRelative' in url;\n}\n\n/**\n * Parses string to a URL object\n *\n * @param url - The URL to parse\n * @returns The parsed URL object or undefined if the URL is invalid\n */\nexport function parseStringToURLObject(url: string, urlBase?: string | URL | undefined): URLObject | undefined {\n  const isRelative = url.indexOf('://') \u003c= 0 \u0026\u0026 url.indexOf('//') !== 0;\n  const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : undefined);\n  try {\n    // Use `canParse` to short-circuit the URL constructor if it's not a valid URL\n    // This is faster than trying to construct the URL and catching the error\n    // Node 20+, Chrome 120+, Firefox 115+, Safari 17+\n    if ('canParse' in URL \u0026\u0026 !(URL as unknown as URLwithCanParse).canParse(url, base)) {\n      return undefined;\n    }\n\n    const fullUrlObject = new URL(url, base);\n    if (isRelative) {\n      // Because we used a fake base URL, we need to return a relative URL object.\n      // We cannot return anything about the origin, host, etc. because it will refer to the fake base URL.\n      return {\n        isRelative,\n        pathname: fullUrlObject.pathname,\n        search: fullUrlObject.search,\n        hash: fullUrlObject.hash,\n      };\n    }\n    return fullUrlObject;\n  } catch {\n    // empty body\n  }\n\n  return undefined;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlStringFromUrlObject(url: URLObject): string {\n  if (isURLObjectRelative(url)) {\n    return url.pathname;\n  }\n\n  const newUrl = new URL(url);\n  newUrl.search = '';\n  newUrl.hash = '';\n  if (['80', '443'].includes(newUrl.port)) {\n    newUrl.port = '';\n  }\n  if (newUrl.password) {\n    newUrl.password = '%filtered%';\n  }\n  if (newUrl.username) {\n    newUrl.username = '%filtered%';\n  }\n\n  return newUrl.toString();\n}\n\ntype PartialRequest = {\n  method?: string;\n};\n\nfunction getHttpSpanNameFromUrlObject(\n  urlObject: URLObject | undefined,\n  kind: 'server' | 'client',\n  request?: PartialRequest,\n  routeName?: string,\n): string {\n  const method = request?.method?.toUpperCase() ?? 'GET';\n  const route = routeName\n    ? routeName\n    : urlObject\n      ? kind === 'client'\n        ? getSanitizedUrlStringFromUrlObject(urlObject)\n        : urlObject.pathname\n      : '/';\n\n  return `${method} ${route}`;\n}\n\n/**\n * Takes a parsed URL object and returns a set of attributes for the span\n * that represents the HTTP request for that url. This is used for both server\n * and client http spans.\n *\n * Follows https://opentelemetry.io/docs/specs/semconv/http/.\n *\n * @param urlObject - see {@link parseStringToURLObject}\n * @param kind - The type of HTTP operation (server or client)\n * @param spanOrigin - The origin of the span\n * @param request - The request object, see {@link PartialRequest}\n * @param routeName - The name of the route, must be low cardinality\n * @returns The span name and attributes for the HTTP operation\n */\nexport function getHttpSpanDetailsFromUrlObject(\n  urlObject: URLObject | undefined,\n  kind: 'server' | 'client',\n  spanOrigin: string,\n  request?: PartialRequest,\n  routeName?: string,\n): [name: string, attributes: SpanAttributes] {\n  const attributes: SpanAttributes = {\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n    [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n  };\n\n  if (routeName) {\n    // This is based on https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name\n    attributes[kind === 'server' ? 'http.route' : 'url.template'] = routeName;\n    attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n  }\n\n  if (request?.method) {\n    attributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] = request.method.toUpperCase();\n  }\n\n  if (urlObject) {\n    if (urlObject.search) {\n      attributes['url.query'] = urlObject.search;\n    }\n    if (urlObject.hash) {\n      attributes['url.fragment'] = urlObject.hash;\n    }\n    if (urlObject.pathname) {\n      attributes['url.path'] = urlObject.pathname;\n      if (urlObject.pathname === '/') {\n        attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n      }\n    }\n\n    if (!isURLObjectRelative(urlObject)) {\n      attributes[SEMANTIC_ATTRIBUTE_URL_FULL] = urlObject.href;\n      if (urlObject.port) {\n        attributes['url.port'] = urlObject.port;\n      }\n      if (urlObject.protocol) {\n        attributes['url.scheme'] = urlObject.protocol;\n      }\n      if (urlObject.hostname) {\n        attributes[kind === 'server' ? 'server.address' : 'url.domain'] = urlObject.hostname;\n      }\n    }\n  }\n\n  return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not \u003ca/\u003e href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n  if (!url) {\n    return {};\n  }\n\n  const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n  if (!match) {\n    return {};\n  }\n\n  // coerce to undefined values to empty string so we don't get 'undefined'\n  const query = match[6] || '';\n  const fragment = match[8] || '';\n  return {\n    host: match[4],\n    path: match[5],\n    protocol: match[2],\n    search: query,\n    hash: fragment,\n    relative: match[5] + query + fragment, // everything minus origin\n  };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n  return (urlPath.split(/[?#]/, 1) as [string, ...string[]])[0];\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n  const { protocol, host, path } = url;\n\n  const filteredHost =\n    host\n      // Always filter out authority\n      ?.replace(/^.*@/, '[filtered]:[filtered]@')\n      // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n      // TODO: Use new URL global if it exists\n      .replace(/(:80)$/, '')\n      .replace(/(:443)$/, '') || '';\n\n  return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\n/**\n * Strips the content from a data URL, returning a placeholder with the MIME type.\n *\n * Data URLs can be very long (e.g. base64 encoded scripts for Web Workers),\n * with little valuable information, often leading to envelopes getting dropped due\n * to size limit violations. Therefore, we strip data URLs and replace them with a\n * placeholder.\n *\n * @param url - The URL to process\n * @param includeDataPrefix - If true, includes the first 10 characters of the data stream\n *                            for debugging (e.g., to identify magic bytes like WASM's AGFzbQ).\n *                            Defaults to true.\n * @returns For data URLs, returns a short format like `data:text/javascript;base64,SGVsbG8gV2... [truncated]`.\n *          For non-data URLs, returns the original URL unchanged.\n */\nexport function stripDataUrlContent(url: string, includeDataPrefix: boolean = true): string {\n  if (url.startsWith('data:')) {\n    // Match the MIME type (everything after 'data:' until the first ';' or ',')\n    const match = url.match(/^data:([^;,]+)/);\n    const mimeType = match ? match[1] : 'text/plain';\n    const isBase64 = url.includes(';base64,');\n\n    // Find where the actual data starts (after the comma)\n    const dataStart = url.indexOf(',');\n    let dataPrefix = '';\n    if (includeDataPrefix \u0026\u0026 dataStart !== -1) {\n      const data = url.slice(dataStart + 1);\n      // Include first 10 chars of data to help identify content (e.g., magic bytes)\n      dataPrefix = data.length \u003e 10 ? `${data.slice(0, 10)}... [truncated]` : data;\n    }\n\n    return `data:${mimeType}${isBase64 ? ',base64' : ''}${dataPrefix ? `,${dataPrefix}` : ''}`;\n  }\n  return url;\n}\n","import type { Client } from '../client';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport { isURLObjectRelative, parseStringToURLObject } from './url';\n\n/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nexport function isSentryRequestUrl(url: string, client: Client | undefined): boolean {\n  const dsn = client?.getDsn();\n  const tunnel = client?.getOptions().tunnel;\n  return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url: string, tunnel: string | undefined): boolean {\n  if (!tunnel) {\n    return false;\n  }\n\n  return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url: string, dsn: DsnComponents | undefined): boolean {\n  // Requests to Sentry's ingest endpoint must have a `sentry_key` in the query string\n  // This is equivalent to the public_key which is required in the DSN\n  // see https://develop.sentry.dev/sdk/overview/#parsing-the-dsn\n  // Therefore, a request to the same host and with a `sentry_key` in the query string\n  // can be considered a request to the ingest endpoint.\n  const urlParts = parseStringToURLObject(url);\n  if (!urlParts || isURLObjectRelative(urlParts)) {\n    return false;\n  }\n\n  return dsn ? urlParts.host.includes(dsn.host) \u0026\u0026 /(^|\u0026|\\?)sentry_key=/.test(urlParts.search) : false;\n}\n\nfunction removeTrailingSlash(str: string): string {\n  return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n","import type { ParameterizedString } from '../types-hoist/parameterize';\n\n/**\n * Tagged template function which returns parameterized representation of the message\n * For example: parameterize`This is a log statement with ${x} and ${y} params`, would return:\n * \"__sentry_template_string__\": 'This is a log statement with %s and %s params',\n * \"__sentry_template_values__\": ['first', 'second']\n *\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n *\n * @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.\n */\nexport function parameterize(strings: TemplateStringsArray, ...values: unknown[]): ParameterizedString {\n  const formatted = new String(String.raw(strings, ...values)) as ParameterizedString;\n  formatted.__sentry_template_string__ = strings.join('\\x00').replace(/%/g, '%%').replace(/\\0/g, '%s');\n  formatted.__sentry_template_values__ = values;\n  return formatted;\n}\n\n/**\n * Tagged template function which returns parameterized representation of the message.\n *\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n * @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.\n */\nexport const fmt = parameterize;\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from '../api';\nimport { debug } from './debug-logger';\nimport { makeDsn } from './dsn';\nimport { parseEnvelope } from './envelope';\n\nexport interface HandleTunnelRequestOptions {\n  /** Incoming request containing the Sentry envelope as its body */\n  request: Request;\n  /** Pre-parsed array of allowed DSN strings */\n  allowedDsns: Array\u003cstring\u003e;\n}\n\n/**\n * Core Sentry tunnel handler - framework agnostic.\n *\n * Validates the envelope DSN against allowed DSNs, then forwards the\n * envelope to the Sentry ingest endpoint.\n *\n * @returns A `Response` — either the upstream Sentry response on success, or an error response.\n */\nexport async function handleTunnelRequest(options: HandleTunnelRequestOptions): Promise\u003cResponse\u003e {\n  const { request, allowedDsns } = options;\n\n  if (allowedDsns.length === 0) {\n    return new Response('Tunnel not configured', { status: 500 });\n  }\n\n  const body = new Uint8Array(await request.arrayBuffer());\n\n  let envelopeHeader;\n  try {\n    [envelopeHeader] = parseEnvelope(body);\n  } catch {\n    return new Response('Invalid envelope', { status: 400 });\n  }\n\n  if (!envelopeHeader) {\n    return new Response('Invalid envelope: missing header', { status: 400 });\n  }\n\n  const dsn = envelopeHeader.dsn;\n  if (!dsn) {\n    return new Response('Invalid envelope: missing DSN', { status: 400 });\n  }\n\n  // SECURITY: Validate that the envelope DSN matches one of the allowed DSNs\n  // This prevents SSRF attacks where attackers send crafted envelopes\n  // with malicious DSNs pointing to arbitrary hosts\n  const isAllowed = allowedDsns.some(allowed =\u003e allowed === dsn);\n\n  if (!isAllowed) {\n    debug.warn(`Sentry tunnel: rejected request with unauthorized DSN (${dsn})`);\n    return new Response('DSN not allowed', { status: 403 });\n  }\n\n  const dsnComponents = makeDsn(dsn);\n  if (!dsnComponents) {\n    debug.warn(`Could not extract DSN Components from: ${dsn}`);\n    return new Response('Invalid DSN', { status: 403 });\n  }\n\n  const sentryIngestUrl = getEnvelopeEndpointWithUrlEncodedAuth(dsnComponents);\n\n  try {\n    return await fetch(sentryIngestUrl, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-sentry-envelope',\n      },\n      body,\n    });\n  } catch (error) {\n    debug.error('Sentry tunnel: failed to forward envelope', error);\n    return new Response('Failed to forward envelope to Sentry', { status: 500 });\n  }\n}\n","import type { Session, SessionAggregates } from '../types-hoist/session';\nimport type { User } from '../types-hoist/user';\n\n// By default, we want to infer the IP address, unless this is explicitly set to `null`\n// We do this after all other processing is done\n// If `ip_address` is explicitly set to `null` or a value, we leave it as is\n\n/**\n * @internal\n * @deprecated -- set ip inferral via via SDK metadata options on client instead.\n */\nexport function addAutoIpAddressToUser(objWithMaybeUser: { user?: User | null }): void {\n  if (objWithMaybeUser.user?.ip_address === undefined) {\n    objWithMaybeUser.user = {\n      ...objWithMaybeUser.user,\n      ip_address: '{{auto}}',\n    };\n  }\n}\n\n/**\n * @internal\n */\nexport function addAutoIpAddressToSession(session: Session | SessionAggregates): void {\n  if ('aggregates' in session) {\n    if (session.attrs?.['ip_address'] === undefined) {\n      session.attrs = {\n        ...session.attrs,\n        ip_address: '{{auto}}',\n      };\n    }\n  } else {\n    if (session.ipAddress === undefined) {\n      session.ipAddress = '{{auto}}';\n    }\n  }\n}\n","import type { CoreOptions } from '../types-hoist/options';\nimport { SDK_VERSION } from '../utils/version';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nexport function applySdkMetadata(options: CoreOptions, name: string, names = [name], source = 'npm'): void {\n  const sdk = ((options._metadata = options._metadata || {}).sdk = options._metadata.sdk || {});\n\n  if (!sdk.name) {\n    sdk.name = `sentry.javascript.${name}`;\n    sdk.packages = names.map(name =\u003e ({\n      name: `${source}:@sentry/${name}`,\n      version: SDK_VERSION,\n    }));\n    sdk.version = SDK_VERSION;\n  }\n}\n","import { getAsyncContextStrategy } from '../asyncContext';\nimport { getMainCarrier } from '../carrier';\nimport type { Client } from '../client';\nimport { getClient, getCurrentScope } from '../currentScopes';\nimport { isEnabled } from '../exports';\nimport type { Scope } from '../scope';\nimport { getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan } from '../tracing';\nimport type { Span } from '../types-hoist/span';\nimport type { SerializedTraceData } from '../types-hoist/tracing';\nimport { dynamicSamplingContextToSentryBaggageHeader } from './baggage';\nimport { debug } from './debug-logger';\nimport { getActiveSpan, spanToTraceHeader, spanToTraceparentHeader } from './spanUtils';\nimport { generateSentryTraceHeader, generateTraceparentHeader, TRACEPARENT_REGEXP } from './tracing';\n\n/**\n * Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation\n * context) and serializes it to `sentry-trace` and `baggage` values. These values can be used to propagate\n * a trace via our tracing Http headers or Html `\u003cmeta\u003e` tags.\n *\n * This function also applies some validation to the generated sentry-trace and baggage values to ensure that\n * only valid strings are returned.\n *\n * If (@param options.propagateTraceparent) is `true`, the function will also generate a `traceparent` value,\n * following the W3C traceparent header format.\n *\n * @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header\n * or meta tag name.\n */\nexport function getTraceData(\n  options: { span?: Span; scope?: Scope; client?: Client; propagateTraceparent?: boolean } = {},\n): SerializedTraceData {\n  const client = options.client || getClient();\n  if (!isEnabled() || !client) {\n    return {};\n  }\n\n  const carrier = getMainCarrier();\n  const acs = getAsyncContextStrategy(carrier);\n  if (acs.getTraceData) {\n    return acs.getTraceData(options);\n  }\n\n  const scope = options.scope || getCurrentScope();\n  const span = options.span || getActiveSpan();\n  const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);\n  const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);\n  const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);\n\n  const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);\n  if (!isValidSentryTraceHeader) {\n    debug.warn('Invalid sentry-trace data. Cannot generate trace data');\n    return {};\n  }\n\n  const traceData: SerializedTraceData = {\n    'sentry-trace': sentryTrace,\n    baggage,\n  };\n\n  if (options.propagateTraceparent) {\n    traceData.traceparent = span ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope);\n  }\n\n  return traceData;\n}\n\n/**\n * Get a sentry-trace header value for the given scope.\n */\nfunction scopeToTraceHeader(scope: Scope): string {\n  const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n  return generateSentryTraceHeader(traceId, propagationSpanId, sampled);\n}\n\nfunction scopeToTraceparentHeader(scope: Scope): string {\n  const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n  return generateTraceparentHeader(traceId, propagationSpanId, sampled);\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport type { CoreOptions as Options } from '../types-hoist/options';\nimport { debug } from './debug-logger';\nimport type { LRUMap } from './lru';\nimport { stringMatchesSomePattern } from './string';\n\nconst NOT_PROPAGATED_MESSAGE =\n  '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:';\n\n/**\n * Check if a given URL should be propagated to or not.\n * If no url is defined, or no trace propagation targets are defined, this will always return `true`.\n * You can also optionally provide a decision map, to cache decisions and avoid repeated regex lookups.\n */\nexport function shouldPropagateTraceForUrl(\n  url: string | undefined,\n  tracePropagationTargets: Options['tracePropagationTargets'],\n  decisionMap?: LRUMap\u003cstring, boolean\u003e,\n): boolean {\n  if (typeof url !== 'string' || !tracePropagationTargets) {\n    return true;\n  }\n\n  const cachedDecision = decisionMap?.get(url);\n  if (cachedDecision !== undefined) {\n    DEBUG_BUILD \u0026\u0026 !cachedDecision \u0026\u0026 debug.log(NOT_PROPAGATED_MESSAGE, url);\n    return cachedDecision;\n  }\n\n  const decision = stringMatchesSomePattern(url, tracePropagationTargets);\n  decisionMap?.set(url, decision);\n\n  DEBUG_BUILD \u0026\u0026 !decision \u0026\u0026 debug.log(NOT_PROPAGATED_MESSAGE, url);\n  return decision;\n}\n","import type { SerializedTraceData } from '../types-hoist/tracing';\nimport { getTraceData } from './traceData';\n\n/**\n * Returns a string of meta tags that represent the current trace data.\n *\n * You can use this to propagate a trace from your server-side rendered Html to the browser.\n * This function returns up to two meta tags, `sentry-trace` and `baggage`, depending on the\n * current trace data state.\n *\n * @example\n * Usage example:\n *\n * ```js\n * function renderHtml() {\n *   return `\n *     \u003chead\u003e\n *       ${getTraceMetaTags()}\n *     \u003c/head\u003e\n *   `;\n * }\n * ```\n *\n */\nexport function getTraceMetaTags(traceData?: SerializedTraceData): string {\n  return Object.entries(traceData || getTraceData())\n    .map(([key, value]) =\u003e `\u003cmeta name=\"${key}\" content=\"${value}\"/\u003e`)\n    .join('\\n');\n}\n","type DebouncedCallback = {\n  (): void | unknown;\n  flush: () =\u003e void | unknown;\n  cancel: () =\u003e void;\n};\ntype CallbackFunction = () =\u003e unknown;\ntype DebounceOptions = {\n  /** The max. time in ms to wait for the callback to be invoked. */\n  maxWait?: number;\n  /** This can be overwritten to use a different setTimeout implementation, e.g. to avoid triggering change detection in Angular  */\n  setTimeoutImpl?: typeof setTimeout;\n};\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n *          debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n *          was already invoked in the meantime, return @param func's return value.\n *          The debounced function has two additional properties:\n *          - `flush`: Invokes the debounced function immediately and returns its return value\n *          - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nexport function debounce(func: CallbackFunction, wait: number, options?: DebounceOptions): DebouncedCallback {\n  let callbackReturnValue: unknown;\n\n  let timerId: ReturnType\u003ctypeof setTimeout\u003e | undefined;\n  let maxTimerId: ReturnType\u003ctypeof setTimeout\u003e | undefined;\n\n  const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0;\n  const setTimeoutImpl = options?.setTimeoutImpl || setTimeout;\n\n  function invokeFunc(): unknown {\n    cancelTimers();\n    callbackReturnValue = func();\n    return callbackReturnValue;\n  }\n\n  function cancelTimers(): void {\n    timerId !== undefined \u0026\u0026 clearTimeout(timerId);\n    maxTimerId !== undefined \u0026\u0026 clearTimeout(maxTimerId);\n    timerId = maxTimerId = undefined;\n  }\n\n  function flush(): unknown {\n    if (timerId !== undefined || maxTimerId !== undefined) {\n      return invokeFunc();\n    }\n    return callbackReturnValue;\n  }\n\n  function debounced(): unknown {\n    if (timerId) {\n      clearTimeout(timerId);\n    }\n    timerId = setTimeoutImpl(invokeFunc, wait);\n\n    if (maxWait \u0026\u0026 maxTimerId === undefined) {\n      maxTimerId = setTimeoutImpl(invokeFunc, maxWait);\n    }\n\n    return callbackReturnValue;\n  }\n\n  debounced.cancel = cancelTimers;\n  debounced.flush = flush;\n  return debounced;\n}\n","import type { PolymorphicRequest } from '../types-hoist/polymorphics';\nimport type { RequestEventData } from '../types-hoist/request';\nimport type { WebFetchHeaders, WebFetchRequest } from '../types-hoist/webfetchapi';\n\n/**\n * Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.\n * The header keys will be lower case: e.g. A \"Content-Type\" header will be stored as \"content-type\".\n */\nexport function winterCGHeadersToDict(winterCGHeaders: WebFetchHeaders): Record\u003cstring, string\u003e {\n  const headers: Record\u003cstring, string\u003e = {};\n  try {\n    winterCGHeaders.forEach((value, key) =\u003e {\n      if (typeof value === 'string') {\n        // We check that value is a string even though it might be redundant to make sure prototype pollution is not possible.\n        headers[key] = value;\n      }\n    });\n  } catch {\n    // just return the empty headers\n  }\n\n  return headers;\n}\n\n/**\n * Convert common request headers to a simple dictionary.\n */\nexport function headersToDict(reqHeaders: Record\u003cstring, string | string[] | undefined\u003e): Record\u003cstring, string\u003e {\n  const headers: Record\u003cstring, string\u003e = Object.create(null);\n\n  try {\n    Object.entries(reqHeaders).forEach(([key, value]) =\u003e {\n      if (typeof value === 'string') {\n        headers[key] = value;\n      }\n    });\n  } catch {\n    // just return the empty headers\n  }\n\n  return headers;\n}\n\n/**\n * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.\n */\nexport function winterCGRequestToRequestData(req: WebFetchRequest): RequestEventData {\n  const headers = winterCGHeadersToDict(req.headers);\n\n  return {\n    method: req.method,\n    url: req.url,\n    query_string: extractQueryParamsFromUrl(req.url),\n    headers,\n    // TODO: Can we extract body data from the request?\n  };\n}\n\n/**\n * Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.\n * Instead of allowing `PolymorphicRequest` to be passed,\n * we want to be more specific and generally require a http.IncomingMessage-like object.\n */\nexport function httpRequestToRequestData(request: {\n  method?: string;\n  url?: string;\n  headers?: {\n    [key: string]: string | string[] | undefined;\n  };\n  protocol?: string;\n  socket?: {\n    encrypted?: boolean;\n    remoteAddress?: string;\n  };\n}): RequestEventData {\n  const headers = request.headers || {};\n\n  // Check for x-forwarded-host first, then fall back to host header\n  const forwardedHost = typeof headers['x-forwarded-host'] === 'string' ? headers['x-forwarded-host'] : undefined;\n  const host = forwardedHost || (typeof headers.host === 'string' ? headers.host : undefined);\n\n  // Check for x-forwarded-proto first, then fall back to existing protocol detection\n  const forwardedProto = typeof headers['x-forwarded-proto'] === 'string' ? headers['x-forwarded-proto'] : undefined;\n  const protocol = forwardedProto || request.protocol || (request.socket?.encrypted ? 'https' : 'http');\n\n  const url = request.url || '';\n\n  const absoluteUrl = getAbsoluteUrl({\n    url,\n    host,\n    protocol,\n  });\n\n  // This is non-standard, but may be sometimes set\n  // It may be overwritten later by our own body handling\n  const data = (request as PolymorphicRequest).body || undefined;\n\n  // This is non-standard, but may be set on e.g. Next.js or Express requests\n  const cookies = (request as PolymorphicRequest).cookies;\n\n  return {\n    url: absoluteUrl,\n    method: request.method,\n    query_string: extractQueryParamsFromUrl(url),\n    headers: headersToDict(headers),\n    cookies,\n    data,\n  };\n}\n\nfunction getAbsoluteUrl({\n  url,\n  protocol,\n  host,\n}: {\n  url?: string;\n  protocol: string;\n  host?: string;\n}): string | undefined {\n  if (url?.startsWith('http')) {\n    return url;\n  }\n\n  if (url \u0026\u0026 host) {\n    return `${protocol}://${host}${url}`;\n  }\n\n  return undefined;\n}\n\nconst SENSITIVE_HEADER_SNIPPETS = [\n  'auth',\n  'token',\n  'secret',\n  'session', // for the user_session cookie\n  'password',\n  'passwd',\n  'pwd',\n  'key',\n  'jwt',\n  'bearer',\n  'sso',\n  'saml',\n  'csrf',\n  'xsrf',\n  'credentials',\n  // Always treat cookie headers as sensitive in case individual key-value cookie pairs cannot properly be extracted\n  'set-cookie',\n  'cookie',\n];\n\nconst PII_HEADER_SNIPPETS = ['x-forwarded-', '-user'];\n\n/**\n * Converts incoming HTTP request or response headers to OpenTelemetry span attributes following semantic conventions.\n * Header names are converted to the format: http.\u003crequest|response\u003e.header.\u003ckey\u003e\n * where \u003ckey\u003e is the header name in lowercase with dashes converted to underscores.\n *\n * @param lifecycle - The lifecycle of the headers, either 'request' or 'response'\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-response-header\n *\n * @see https://getsentry.github.io/sentry-conventions/attributes/http/#http-request-header-key\n * @see https://getsentry.github.io/sentry-conventions/attributes/http/#http-response-header-key\n */\nexport function httpHeadersToSpanAttributes(\n  headers: Record\u003cstring, string | string[] | undefined\u003e,\n  sendDefaultPii: boolean = false,\n  lifecycle: 'request' | 'response' = 'request',\n): Record\u003cstring, string\u003e {\n  const spanAttributes: Record\u003cstring, string\u003e = {};\n\n  try {\n    Object.entries(headers).forEach(([key, value]) =\u003e {\n      if (value == null) {\n        return;\n      }\n\n      const lowerCasedHeaderKey = key.toLowerCase();\n      const isCookieHeader = lowerCasedHeaderKey === 'cookie' || lowerCasedHeaderKey === 'set-cookie';\n\n      if (isCookieHeader \u0026\u0026 typeof value === 'string' \u0026\u0026 value !== '') {\n        // Set-Cookie: single cookie with attributes (\"name=value; HttpOnly; Secure\")\n        // Cookie: multiple cookies separated by \"; \" (\"cookie1=value1; cookie2=value2\")\n        const isSetCookie = lowerCasedHeaderKey === 'set-cookie';\n        const semicolonIndex = value.indexOf(';');\n        const cookieString = isSetCookie \u0026\u0026 semicolonIndex !== -1 ? value.substring(0, semicolonIndex) : value;\n        const cookies = isSetCookie ? [cookieString] : cookieString.split('; ');\n\n        for (const cookie of cookies) {\n          // Split only at the first '=' to preserve '=' characters in cookie values\n          const equalSignIndex = cookie.indexOf('=');\n          const cookieKey = equalSignIndex !== -1 ? cookie.substring(0, equalSignIndex) : cookie;\n          const cookieValue = equalSignIndex !== -1 ? cookie.substring(equalSignIndex + 1) : '';\n\n          const lowerCasedCookieKey = cookieKey.toLowerCase();\n\n          addSpanAttribute(\n            spanAttributes,\n            lowerCasedHeaderKey,\n            lowerCasedCookieKey,\n            cookieValue,\n            sendDefaultPii,\n            lifecycle,\n          );\n        }\n      } else {\n        addSpanAttribute(spanAttributes, lowerCasedHeaderKey, '', value, sendDefaultPii, lifecycle);\n      }\n    });\n  } catch {\n    // Return empty object if there's an error\n  }\n\n  return spanAttributes;\n}\n\nfunction normalizeAttributeKey(key: string): string {\n  return key.replace(/-/g, '_');\n}\n\nfunction addSpanAttribute(\n  spanAttributes: Record\u003cstring, string\u003e,\n  headerKey: string,\n  cookieKey: string,\n  value: string | string[] | undefined,\n  sendPii: boolean,\n  lifecycle: 'request' | 'response',\n): void {\n  const headerValue = handleHttpHeader(cookieKey || headerKey, value, sendPii);\n  if (headerValue == null) {\n    return;\n  }\n\n  const normalizedKey = `http.${lifecycle}.header.${normalizeAttributeKey(headerKey)}${cookieKey ? `.${normalizeAttributeKey(cookieKey)}` : ''}`;\n  spanAttributes[normalizedKey] = headerValue;\n}\n\nfunction handleHttpHeader(\n  lowerCasedKey: string,\n  value: string | string[] | undefined,\n  sendPii: boolean,\n): string | undefined {\n  const isSensitive = sendPii\n    ? SENSITIVE_HEADER_SNIPPETS.some(snippet =\u003e lowerCasedKey.includes(snippet))\n    : [...PII_HEADER_SNIPPETS, ...SENSITIVE_HEADER_SNIPPETS].some(snippet =\u003e lowerCasedKey.includes(snippet));\n\n  if (isSensitive) {\n    return '[Filtered]';\n  } else if (Array.isArray(value)) {\n    return value.map(v =\u003e (v != null ? String(v) : v)).join(';');\n  } else if (typeof value === 'string') {\n    return value;\n  }\n\n  return undefined;\n}\n\n/** Extract the query params from an URL. */\nexport function extractQueryParamsFromUrl(url: string): string | undefined {\n  // url is path and query string\n  if (!url) {\n    return;\n  }\n\n  try {\n    // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n    // hostname as the base. Since the point here is just to grab the query string, it doesn't matter what we use.\n    const queryParams = new URL(url, 'http://s.io').search.slice(1);\n    return queryParams.length ? queryParams : undefined;\n  } catch {\n    return undefined;\n  }\n}\n","import { getClient, getIsolationScope } from './currentScopes';\nimport type { Breadcrumb, BreadcrumbHint } from './types-hoist/breadcrumb';\nimport { consoleSandbox } from './utils/debug-logger';\nimport { dateTimestampInSeconds } from './utils/time';\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n  const client = getClient();\n  const isolationScope = getIsolationScope();\n\n  if (!client) return;\n\n  const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n\n  if (maxBreadcrumbs \u003c= 0) return;\n\n  const timestamp = dateTimestampInSeconds();\n  const mergedBreadcrumb = { timestamp, ...breadcrumb };\n  const finalBreadcrumb = beforeBreadcrumb\n    ? consoleSandbox(() =\u003e beforeBreadcrumb(mergedBreadcrumb, hint))\n    : mergedBreadcrumb;\n\n  if (finalBreadcrumb === null) return;\n\n  if (client.emit) {\n    client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n  }\n\n  isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n","import type { Client } from '../client';\nimport { getClient } from '../currentScopes';\nimport { defineIntegration } from '../integration';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { getOriginalFunction } from '../utils/object';\n\nlet originalFunctionToString: () =\u003e void;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap\u003cClient, boolean\u003e();\n\nconst _functionToStringIntegration = (() =\u003e {\n  return {\n    name: INTEGRATION_NAME,\n    setupOnce() {\n      // eslint-disable-next-line @typescript-eslint/unbound-method\n      originalFunctionToString = Function.prototype.toString;\n\n      // intrinsics (like Function.prototype) might be immutable in some environments\n      // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n      try {\n        Function.prototype.toString = function (this: WrappedFunction, ...args: unknown[]): string {\n          const originalFunction = getOriginalFunction(this);\n          const context =\n            SETUP_CLIENTS.has(getClient() as Client) \u0026\u0026 originalFunction !== undefined ? originalFunction : this;\n          return originalFunctionToString.apply(context, args);\n        };\n      } catch {\n        // ignore errors here, just don't patch this\n      }\n    },\n    setup(client) {\n      SETUP_CLIENTS.set(client, true);\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n *   integrations: [\n *     functionToStringIntegration(),\n *   ],\n * });\n * ```\n */\nexport const functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n","import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getPossibleEventMessages } from '../utils/eventUtils';\nimport { getEventDescription } from '../utils/misc';\nimport { stringMatchesSomePattern } from '../utils/string';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n  /^Script error\\.?$/,\n  /^Javascript error: Script error\\.? on line 0$/,\n  /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n  /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n  /^Can't find variable: gmo$/, // Error from Google Search App https://issuetracker.google.com/issues/396043331\n  /^undefined is not an object \\(evaluating 'a\\.[A-Z]'\\)$/, // Random error that happens but not actionable or noticeable to end-users.\n  /can't redefine non-configurable property \"solana\"/, // Probably a browser extension or custom browser (Brave) throwing this error\n  /vv\\(\\)\\.getRestrictions is not a function/, // Error thrown by GTM, seemingly not affecting end-users\n  /Can't find variable: _AutofillCallbackHandler/, // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n  /Object Not Found Matching Id:\\d+, MethodName:simulateEvent/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n  /^Java exception was raised during method invocation$/, // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065)\n];\n\n/** Options for the EventFilters integration */\nexport interface EventFiltersOptions {\n  allowUrls: Array\u003cstring | RegExp\u003e;\n  denyUrls: Array\u003cstring | RegExp\u003e;\n  ignoreErrors: Array\u003cstring | RegExp\u003e;\n  ignoreTransactions: Array\u003cstring | RegExp\u003e;\n  ignoreInternal: boolean;\n  disableErrorDefaults: boolean;\n}\n\nconst INTEGRATION_NAME = 'EventFilters';\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n *   - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n *   - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n *   - Top level Sentry.init option (`ignoreTransactions`)\n *   - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n */\nexport const eventFiltersIntegration = defineIntegration((options: Partial\u003cEventFiltersOptions\u003e = {}) =\u003e {\n  let mergedOptions: Partial\u003cEventFiltersOptions\u003e | undefined;\n  return {\n    name: INTEGRATION_NAME,\n    setup(client) {\n      const clientOptions = client.getOptions();\n      mergedOptions = _mergeOptions(options, clientOptions);\n    },\n    processEvent(event, _hint, client) {\n      if (!mergedOptions) {\n        const clientOptions = client.getOptions();\n        mergedOptions = _mergeOptions(options, clientOptions);\n      }\n      return _shouldDropEvent(event, mergedOptions) ? null : event;\n    },\n  };\n});\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n *   - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n *   - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n *   - Top level Sentry.init option (`ignoreTransactions`)\n *   - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n *\n * @deprecated this integration was renamed and will be removed in a future major version.\n * Use `eventFiltersIntegration` instead.\n */\nexport const inboundFiltersIntegration = defineIntegration(((options: Partial\u003cEventFiltersOptions\u003e = {}) =\u003e {\n  return {\n    ...eventFiltersIntegration(options),\n    name: 'InboundFilters',\n  };\n}) satisfies IntegrationFn);\n\nfunction _mergeOptions(\n  internalOptions: Partial\u003cEventFiltersOptions\u003e = {},\n  clientOptions: Partial\u003cEventFiltersOptions\u003e = {},\n): Partial\u003cEventFiltersOptions\u003e {\n  return {\n    allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n    denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n    ignoreErrors: [\n      ...(internalOptions.ignoreErrors || []),\n      ...(clientOptions.ignoreErrors || []),\n      ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n    ],\n    ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n  };\n}\n\nfunction _shouldDropEvent(event: Event, options: Partial\u003cEventFiltersOptions\u003e): boolean {\n  if (!event.type) {\n    // Filter errors\n    if (_isIgnoredError(event, options.ignoreErrors)) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n        );\n      return true;\n    }\n    if (_isUselessError(event)) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n            event,\n          )}`,\n        );\n      return true;\n    }\n    if (_isDeniedUrl(event, options.denyUrls)) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n            event,\n          )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n        );\n      return true;\n    }\n    if (!_isAllowedUrl(event, options.allowUrls)) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n            event,\n          )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n        );\n      return true;\n    }\n  } else if (event.type === 'transaction') {\n    // Filter transactions\n\n    if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n      DEBUG_BUILD \u0026\u0026\n        debug.warn(\n          `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n        );\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array\u003cstring | RegExp\u003e): boolean {\n  if (!ignoreErrors?.length) {\n    return false;\n  }\n\n  return getPossibleEventMessages(event).some(message =\u003e stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array\u003cstring | RegExp\u003e): boolean {\n  if (!ignoreTransactions?.length) {\n    return false;\n  }\n\n  const name = event.transaction;\n  return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array\u003cstring | RegExp\u003e): boolean {\n  if (!denyUrls?.length) {\n    return false;\n  }\n  const url = _getEventFilterUrl(event);\n  return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array\u003cstring | RegExp\u003e): boolean {\n  if (!allowUrls?.length) {\n    return true;\n  }\n  const url = _getEventFilterUrl(event);\n  return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n  for (let i = frames.length - 1; i \u003e= 0; i--) {\n    const frame = frames[i];\n\n    if (frame \u0026\u0026 frame.filename !== '\u003canonymous\u003e' \u0026\u0026 frame.filename !== '[native code]') {\n      return frame.filename || null;\n    }\n  }\n\n  return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n  try {\n    // If there are linked exceptions or exception aggregates we only want to match against the top frame of the \"root\" (the main exception)\n    // The root always comes last in linked exceptions\n    const rootException = [...(event.exception?.values ?? [])]\n      .reverse()\n      .find(value =\u003e value.mechanism?.parent_id === undefined \u0026\u0026 value.stacktrace?.frames?.length);\n    const frames = rootException?.stacktrace?.frames;\n    return frames ? _getLastValidUrl(frames) : null;\n  } catch {\n    DEBUG_BUILD \u0026\u0026 debug.error(`Cannot extract url for event ${getEventDescription(event)}`);\n    return null;\n  }\n}\n\nfunction _isUselessError(event: Event): boolean {\n  // We only want to consider events for dropping that actually have recorded exception values.\n  if (!event.exception?.values?.length) {\n    return false;\n  }\n\n  return (\n    // No top-level message\n    !event.message \u0026\u0026\n    // There are no exception values that have a stacktrace, a non-generic-Error type or value\n    !event.exception.values.some(value =\u003e value.stacktrace || (value.type \u0026\u0026 value.type !== 'Error') || value.value)\n  );\n}\n","import type { ExtendedError } from '../types-hoist/error';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { StackParser } from '../types-hoist/stacktrace';\nimport { isInstanceOf } from './is';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n  exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) =\u003e Exception,\n  parser: StackParser,\n  key: string,\n  limit: number,\n  event: Event,\n  hint?: EventHint,\n): void {\n  if (!event.exception?.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n    return;\n  }\n\n  // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n  const originalException: Exception | undefined =\n    event.exception.values.length \u003e 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n  // We only create exception grouping if there is an exception in the event.\n  if (originalException) {\n    event.exception.values = aggregateExceptionsFromError(\n      exceptionFromErrorImplementation,\n      parser,\n      limit,\n      hint.originalException as ExtendedError,\n      key,\n      event.exception.values,\n      originalException,\n      0,\n    );\n  }\n}\n\nfunction aggregateExceptionsFromError(\n  exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) =\u003e Exception,\n  parser: StackParser,\n  limit: number,\n  error: ExtendedError,\n  key: string,\n  prevExceptions: Exception[],\n  exception: Exception,\n  exceptionId: number,\n): Exception[] {\n  if (prevExceptions.length \u003e= limit + 1) {\n    return prevExceptions;\n  }\n\n  let newExceptions = [...prevExceptions];\n\n  // Recursively call this function in order to walk down a chain of errors\n  if (isInstanceOf(error[key], Error)) {\n    applyExceptionGroupFieldsForParentException(exception, exceptionId, error);\n    const newException = exceptionFromErrorImplementation(parser, error[key] as Error);\n    const newExceptionId = newExceptions.length;\n    applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n    newExceptions = aggregateExceptionsFromError(\n      exceptionFromErrorImplementation,\n      parser,\n      limit,\n      error[key] as ExtendedError,\n      key,\n      [newException, ...newExceptions],\n      newException,\n      newExceptionId,\n    );\n  }\n\n  // This will create exception grouping for AggregateErrors\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n  if (isExceptionGroup(error)) {\n    error.errors.forEach((childError, i) =\u003e {\n      if (isInstanceOf(childError, Error)) {\n        applyExceptionGroupFieldsForParentException(exception, exceptionId, error);\n        const newException = exceptionFromErrorImplementation(parser, childError as Error);\n        const newExceptionId = newExceptions.length;\n        applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n        newExceptions = aggregateExceptionsFromError(\n          exceptionFromErrorImplementation,\n          parser,\n          limit,\n          childError as ExtendedError,\n          key,\n          [newException, ...newExceptions],\n          newException,\n          newExceptionId,\n        );\n      }\n    });\n  }\n\n  return newExceptions;\n}\n\nfunction isExceptionGroup(error: ExtendedError): error is ExtendedError \u0026 { errors: unknown[] } {\n  return Array.isArray(error.errors);\n}\n\nfunction applyExceptionGroupFieldsForParentException(\n  exception: Exception,\n  exceptionId: number,\n  error: ExtendedError,\n): void {\n  exception.mechanism = {\n    handled: true,\n    type: 'auto.core.linked_errors',\n    ...(isExceptionGroup(error) \u0026\u0026 { is_exception_group: true }),\n    ...exception.mechanism,\n    exception_id: exceptionId,\n  };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n  exception: Exception,\n  source: string,\n  exceptionId: number,\n  parentId: number | undefined,\n): void {\n  exception.mechanism = {\n    handled: true,\n    ...exception.mechanism,\n    type: 'chained',\n    source,\n    exception_id: exceptionId,\n    parent_id: parentId,\n  };\n}\n","import { defineIntegration } from '../integration';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { applyAggregateErrorsToEvent } from '../utils/aggregate-errors';\nimport { exceptionFromError } from '../utils/eventbuilder';\n\ninterface LinkedErrorsOptions {\n  key?: string;\n  limit?: number;\n}\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options: LinkedErrorsOptions = {}) =\u003e {\n  const limit = options.limit || DEFAULT_LIMIT;\n  const key = options.key || DEFAULT_KEY;\n\n  return {\n    name: INTEGRATION_NAME,\n    preprocessEvent(event, hint, client) {\n      const options = client.getOptions();\n\n      applyAggregateErrorsToEvent(exceptionFromError, options.stackParser, key, limit, event, hint);\n    },\n  };\n}) satisfies IntegrationFn;\n\nexport const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n","import type { Event } from './types-hoist/event';\nimport type { StackParser } from './types-hoist/stacktrace';\nimport { GLOBAL_OBJ } from './utils/worldwide';\n\n/** Keys are source filename/url, values are metadata objects. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst filenameMetadataMap = new Map\u003cstring, any\u003e();\n/** Set of stack strings that have already been parsed. */\nconst parsedStacks = new Set\u003cstring\u003e();\n\n/**\n * Builds a map of filenames to module metadata from the global _sentryModuleMetadata object.\n * This is useful for forwarding metadata from web workers to the main thread.\n *\n * @param parser - Stack parser to use for extracting filenames from stack traces\n * @returns A map of filename to metadata object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getFilenameToMetadataMap(parser: StackParser): Record\u003cstring, any\u003e {\n  if (!GLOBAL_OBJ._sentryModuleMetadata) {\n    return {};\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const filenameMap: Record\u003cstring, any\u003e = {};\n\n  for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n    const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n    const frames = parser(stack);\n\n    for (const frame of frames.reverse()) {\n      if (frame.filename) {\n        filenameMap[frame.filename] = metadata;\n        break;\n      }\n    }\n  }\n\n  return filenameMap;\n}\n\nfunction ensureMetadataStacksAreParsed(parser: StackParser): void {\n  if (!GLOBAL_OBJ._sentryModuleMetadata) {\n    return;\n  }\n\n  for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n    const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n\n    if (parsedStacks.has(stack)) {\n      continue;\n    }\n\n    // Ensure this stack doesn't get parsed again\n    parsedStacks.add(stack);\n\n    const frames = parser(stack);\n\n    // Go through the frames starting from the top of the stack and find the first one with a filename\n    for (const frame of frames.reverse()) {\n      if (frame.filename) {\n        // Save the metadata for this filename\n        filenameMetadataMap.set(frame.filename, metadata);\n        break;\n      }\n    }\n  }\n}\n\n/**\n * Retrieve metadata for a specific JavaScript file URL.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getMetadataForUrl(parser: StackParser, filename: string): any | undefined {\n  ensureMetadataStacksAreParsed(parser);\n  return filenameMetadataMap.get(filename);\n}\n\n/**\n * Adds metadata to stack frames.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\nexport function addMetadataToStackFrames(parser: StackParser, event: Event): void {\n  event.exception?.values?.forEach(exception =\u003e {\n    exception.stacktrace?.frames?.forEach(frame =\u003e {\n      if (!frame.filename || frame.module_metadata) {\n        return;\n      }\n\n      const metadata = getMetadataForUrl(parser, frame.filename);\n\n      if (metadata) {\n        frame.module_metadata = metadata;\n      }\n    });\n  });\n}\n\n/**\n * Strips metadata from stack frames.\n */\nexport function stripMetadataFromStackFrames(event: Event): void {\n  event.exception?.values?.forEach(exception =\u003e {\n    exception.stacktrace?.frames?.forEach(frame =\u003e {\n      delete frame.module_metadata;\n    });\n  });\n}\n","import { defineIntegration } from '../integration';\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata';\nimport type { EventItem } from '../types-hoist/envelope';\nimport { forEachEnvelopeItem } from '../utils/envelope';\n\n/**\n * Adds module metadata to stack frames.\n *\n * Metadata can be injected by the Sentry bundler plugins using the `moduleMetadata` config option.\n *\n * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events\n * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams\n * our sources\n */\nexport const moduleMetadataIntegration = defineIntegration(() =\u003e {\n  return {\n    name: 'ModuleMetadata',\n    setup(client) {\n      // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n      client.on('beforeEnvelope', envelope =\u003e {\n        forEachEnvelopeItem(envelope, (item, type) =\u003e {\n          if (type === 'event') {\n            const event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n\n            if (event) {\n              stripMetadataFromStackFrames(event);\n              item[1] = event;\n            }\n          }\n        });\n      });\n\n      client.on('applyFrameMetadata', event =\u003e {\n        // Only apply stack frame metadata to error events\n        if (event.type) {\n          return;\n        }\n\n        const stackParser = client.getOptions().stackParser;\n        addMetadataToStackFrames(stackParser, event);\n      });\n    },\n  };\n});\n","/**\n * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case.\n * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js\n * It had the following license:\n *\n * (The MIT License)\n *\n * Copyright (c) 2012-2014 Roman Shtylman \u003cshtylman@gmail.com\u003e\n * Copyright (c) 2015 Douglas Christopher Wilson \u003cdoug@somethingdoug.com\u003e\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Parses a cookie string\n */\nexport function parseCookie(str: string): Record\u003cstring, string\u003e {\n  const obj: Record\u003cstring, string\u003e = {};\n  let index = 0;\n\n  while (index \u003c str.length) {\n    const eqIdx = str.indexOf('=', index);\n\n    // no more cookie pairs\n    if (eqIdx === -1) {\n      break;\n    }\n\n    let endIdx = str.indexOf(';', index);\n\n    if (endIdx === -1) {\n      endIdx = str.length;\n    } else if (endIdx \u003c eqIdx) {\n      // backtrack on prior semicolon\n      index = str.lastIndexOf(';', eqIdx - 1) + 1;\n      continue;\n    }\n\n    const key = str.slice(index, eqIdx).trim();\n\n    // only assign once\n    if (undefined === obj[key]) {\n      let val = str.slice(eqIdx + 1, endIdx).trim();\n\n      // quoted values\n      if (val.charCodeAt(0) === 0x22) {\n        val = val.slice(1, -1);\n      }\n\n      try {\n        obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;\n      } catch {\n        obj[key] = val;\n      }\n    }\n\n    index = endIdx + 1;\n  }\n\n  return obj;\n}\n","// Vendored / modified from @sergiodxa/remix-utils\n\n// https://github.com/sergiodxa/remix-utils/blob/02af80e12829a53696bfa8f3c2363975cf59f55e/src/server/get-client-ip-address.ts\n// MIT License\n\n// Copyright (c) 2021 Sergio Xalambrí\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// The headers to check, in priority order\nexport const ipHeaderNames = [\n  'X-Client-IP',\n  'X-Forwarded-For',\n  'Fly-Client-IP',\n  'CF-Connecting-IP',\n  'Fastly-Client-Ip',\n  'True-Client-Ip',\n  'X-Real-IP',\n  'X-Cluster-Client-IP',\n  'X-Forwarded',\n  'Forwarded-For',\n  'Forwarded',\n  'X-Vercel-Forwarded-For',\n];\n\n/**\n * Get the IP address of the client sending a request.\n *\n * It receives a Request headers object and use it to get the\n * IP address from one of the following headers in order.\n *\n * If the IP address is valid, it will be returned. Otherwise, null will be\n * returned.\n *\n * If the header values contains more than one IP address, the first valid one\n * will be returned.\n */\nexport function getClientIPAddress(headers: { [key: string]: string | string[] | undefined }): string | null {\n  // Build a map of lowercase header names to their values for case-insensitive lookup\n  // This is needed because headers from different sources may have different casings\n  const lowerCaseHeaders: { [key: string]: string | string[] | undefined } = {};\n\n  for (const key of Object.keys(headers)) {\n    lowerCaseHeaders[key.toLowerCase()] = headers[key];\n  }\n\n  // This will end up being Array\u003cstring | string[] | undefined | null\u003e because of the various possible values a header\n  // can take\n  const headerValues = ipHeaderNames.map((headerName: string) =\u003e {\n    const rawValue = lowerCaseHeaders[headerName.toLowerCase()];\n    const value = Array.isArray(rawValue) ? rawValue.join(';') : rawValue;\n\n    if (headerName === 'Forwarded') {\n      return parseForwardedHeader(value);\n    }\n\n    return value?.split(',').map((v: string) =\u003e v.trim());\n  });\n\n  // Flatten the array and filter out any falsy entries\n  const flattenedHeaderValues = headerValues.reduce((acc: string[], val) =\u003e {\n    if (!val) {\n      return acc;\n    }\n\n    return acc.concat(val);\n  }, []);\n\n  // Find the first value which is a valid IP address, if any\n  const ipAddress = flattenedHeaderValues.find(ip =\u003e ip !== null \u0026\u0026 isIP(ip));\n\n  return ipAddress || null;\n}\n\nfunction parseForwardedHeader(value: string | null | undefined): string | null {\n  if (!value) {\n    return null;\n  }\n\n  for (const part of value.split(';')) {\n    if (part.startsWith('for=')) {\n      return part.slice(4);\n    }\n  }\n\n  return null;\n}\n\n//\n/**\n * Custom method instead of importing this from `net` package, as this only exists in node\n * Accepts:\n * 127.0.0.1\n * 192.168.1.1\n * 192.168.1.255\n * 255.255.255.255\n * 10.1.1.1\n * 0.0.0.0\n * 2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5\n *\n * Rejects:\n * 1.1.1.01\n * 30.168.1.255.1\n * 127.1\n * 192.168.1.256\n * -1.2.3.4\n * 1.1.1.1.\n * 3...3\n * 192.168.1.099\n */\nfunction isIP(str: string): boolean {\n  const regex =\n    /(?:^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$)|(?:^(?:(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|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\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/;\n  return regex.test(str);\n}\n","import { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { RequestEventData } from '../types-hoist/request';\nimport { parseCookie } from '../utils/cookie';\nimport { getClientIPAddress, ipHeaderNames } from '../vendor/getIpAddress';\n\ninterface RequestDataIncludeOptions {\n  cookies?: boolean;\n  data?: boolean;\n  headers?: boolean;\n  ip?: boolean;\n  query_string?: boolean;\n  url?: boolean;\n}\n\ntype RequestDataIntegrationOptions = {\n  /**\n   * Controls what data is pulled from the request and added to the event.\n   */\n  include?: RequestDataIncludeOptions;\n};\n\n// TODO(v11): Change defaults based on `sendDefaultPii`\nconst DEFAULT_INCLUDE: RequestDataIncludeOptions = {\n  cookies: true,\n  data: true,\n  headers: true,\n  query_string: true,\n  url: true,\n};\n\nconst INTEGRATION_NAME = 'RequestData';\n\nconst _requestDataIntegration = ((options: RequestDataIntegrationOptions = {}) =\u003e {\n  const include = {\n    ...DEFAULT_INCLUDE,\n    ...options.include,\n  };\n\n  return {\n    name: INTEGRATION_NAME,\n    processEvent(event, _hint, client) {\n      const { sdkProcessingMetadata = {} } = event;\n      const { normalizedRequest, ipAddress } = sdkProcessingMetadata;\n\n      const includeWithDefaultPiiApplied: RequestDataIncludeOptions = {\n        ...include,\n        ip: include.ip ?? client.getOptions().sendDefaultPii,\n      };\n\n      if (normalizedRequest) {\n        addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, includeWithDefaultPiiApplied);\n      }\n\n      return event;\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/core`\n * so it can be used in cross-platform SDKs like `@sentry/nextjs`.\n */\nexport const requestDataIntegration = defineIntegration(_requestDataIntegration);\n\n/**\n * Add already normalized request data to an event.\n * This mutates the passed in event.\n */\nfunction addNormalizedRequestDataToEvent(\n  event: Event,\n  req: RequestEventData,\n  // Data that should not go into `event.request` but is somehow related to requests\n  additionalData: { ipAddress?: string },\n  include: RequestDataIncludeOptions,\n): void {\n  event.request = {\n    ...event.request,\n    ...extractNormalizedRequestData(req, include),\n  };\n\n  if (include.ip) {\n    const ip = (req.headers \u0026\u0026 getClientIPAddress(req.headers)) || additionalData.ipAddress;\n    if (ip) {\n      event.user = {\n        ...event.user,\n        ip_address: ip,\n      };\n    }\n  }\n}\n\nfunction extractNormalizedRequestData(\n  normalizedRequest: RequestEventData,\n  include: RequestDataIncludeOptions,\n): RequestEventData {\n  const requestData: RequestEventData = {};\n  const headers = { ...normalizedRequest.headers };\n\n  if (include.headers) {\n    requestData.headers = headers;\n\n    // Remove the Cookie header in case cookie data should not be included in the event\n    if (!include.cookies) {\n      delete (headers as { cookie?: string }).cookie;\n    }\n\n    // Remove IP headers in case IP data should not be included in the event\n    if (!include.ip) {\n      ipHeaderNames.forEach(ipHeaderName =\u003e {\n        // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n        delete (headers as Record\u003cstring, unknown\u003e)[ipHeaderName];\n      });\n    }\n  }\n\n  requestData.method = normalizedRequest.method;\n\n  if (include.url) {\n    requestData.url = normalizedRequest.url;\n  }\n\n  if (include.cookies) {\n    const cookies = normalizedRequest.cookies || (headers?.cookie ? parseCookie(headers.cookie) : undefined);\n    requestData.cookies = cookies || {};\n  }\n\n  if (include.query_string) {\n    requestData.query_string = normalizedRequest.query_string;\n  }\n\n  if (include.data) {\n    requestData.data = normalizedRequest.data;\n  }\n\n  return requestData;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '../types-hoist/instrument';\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../utils/debug-logger';\nimport { fill } from '../utils/object';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) =\u003e void): void {\n  const type = 'console';\n  addHandler(type, handler);\n  maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n  if (!('console' in GLOBAL_OBJ)) {\n    return;\n  }\n\n  CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n    if (!(level in GLOBAL_OBJ.console)) {\n      return;\n    }\n\n    fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () =\u003e any): Function {\n      originalConsoleMethods[level] = originalConsoleMethod;\n\n      return function (...args: any[]): void {\n        const handlerData: HandlerDataConsole = { args, level };\n        triggerHandlers('console', handlerData);\n\n        const log = originalConsoleMethods[level];\n        log?.apply(GLOBAL_OBJ.console, args);\n      };\n    });\n  });\n}\n","import type { SeverityLevel } from '../types-hoist/severity';\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n  return (\n    level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n  ) as SeverityLevel;\n}\n","import { getClient, withScope } from '../currentScopes';\nimport { captureException } from '../exports';\nimport { addConsoleInstrumentationHandler } from '../instrument/console';\nimport { defineIntegration } from '../integration';\nimport type { CaptureContext } from '../scope';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { CONSOLE_LEVELS } from '../utils/debug-logger';\nimport { addExceptionMechanism } from '../utils/misc';\nimport { severityLevelFromString } from '../utils/severity';\nimport { safeJoin } from '../utils/string';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\ninterface CaptureConsoleOptions {\n  levels?: string[];\n\n  /**\n   * By default, Sentry will mark captured console messages as handled.\n   * Set this to `false` if you want to mark them as unhandled instead.\n   *\n   * @default true\n   */\n  handled?: boolean;\n}\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options: CaptureConsoleOptions = {}) =\u003e {\n  const levels = options.levels || CONSOLE_LEVELS;\n  const handled = options.handled ?? true;\n\n  return {\n    name: INTEGRATION_NAME,\n    setup(client) {\n      if (!('console' in GLOBAL_OBJ)) {\n        return;\n      }\n\n      addConsoleInstrumentationHandler(({ args, level }) =\u003e {\n        if (getClient() !== client || !levels.includes(level)) {\n          return;\n        }\n\n        consoleHandler(args, level, handled);\n      });\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Send Console API calls as Sentry Events.\n */\nexport const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\nfunction consoleHandler(args: unknown[], level: string, handled: boolean): void {\n  const severityLevel = severityLevelFromString(level);\n\n  /*\n    We create this error here already to attach a stack trace to captured messages,\n    if users set `attachStackTrace` to `true` in Sentry.init.\n    We do this here already because we want to minimize the number of Sentry SDK stack frames\n    within the error. Technically, Client.captureMessage will also do it but this happens several\n    stack frames deeper.\n  */\n  const syntheticException = new Error();\n\n  const captureContext: CaptureContext = {\n    level: severityLevelFromString(level),\n    extra: {\n      arguments: args,\n    },\n  };\n\n  withScope(scope =\u003e {\n    scope.addEventProcessor(event =\u003e {\n      event.logger = 'console';\n\n      addExceptionMechanism(event, {\n        handled,\n        type: 'auto.core.capture_console',\n      });\n\n      return event;\n    });\n\n    if (level === 'assert') {\n      if (!args[0]) {\n        const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n        scope.setExtra('arguments', args.slice(1));\n        scope.captureMessage(message, severityLevel, { captureContext, syntheticException });\n      }\n      return;\n    }\n\n    const error = args.find(arg =\u003e arg instanceof Error);\n    if (error) {\n      captureException(error, captureContext);\n      return;\n    }\n\n    const message = safeJoin(args, ' ');\n    scope.captureMessage(message, severityLevel, { captureContext, syntheticException });\n  });\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { Exception } from '../types-hoist/exception';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getFramesFromEvent } from '../utils/stacktrace';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() =\u003e {\n  let previousEvent: Event | undefined;\n\n  return {\n    name: INTEGRATION_NAME,\n    processEvent(currentEvent) {\n      // We want to ignore any non-error type events, e.g. transactions or replays\n      // These should never be deduped, and also not be compared against as _previousEvent.\n      if (currentEvent.type) {\n        return currentEvent;\n      }\n\n      // Juuust in case something goes wrong\n      try {\n        if (_shouldDropEvent(currentEvent, previousEvent)) {\n          DEBUG_BUILD \u0026\u0026 debug.warn('Event dropped due to being a duplicate of previously captured event.');\n          return null;\n        }\n      } catch {} // eslint-disable-line no-empty\n\n      return (previousEvent = currentEvent);\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Deduplication filter.\n */\nexport const dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nexport function _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n  if (!previousEvent) {\n    return false;\n  }\n\n  if (_isSameMessageEvent(currentEvent, previousEvent)) {\n    return true;\n  }\n\n  if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n    return true;\n  }\n\n  return false;\n}\n\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n  const currentMessage = currentEvent.message;\n  const previousMessage = previousEvent.message;\n\n  // If neither event has a message property, they were both exceptions, so bail out\n  if (!currentMessage \u0026\u0026 !previousMessage) {\n    return false;\n  }\n\n  // If only one event has a stacktrace, but not the other one, they are not the same\n  if ((currentMessage \u0026\u0026 !previousMessage) || (!currentMessage \u0026\u0026 previousMessage)) {\n    return false;\n  }\n\n  if (currentMessage !== previousMessage) {\n    return false;\n  }\n\n  if (!_isSameFingerprint(currentEvent, previousEvent)) {\n    return false;\n  }\n\n  if (!_isSameStacktrace(currentEvent, previousEvent)) {\n    return false;\n  }\n\n  return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n  const previousException = _getExceptionFromEvent(previousEvent);\n  const currentException = _getExceptionFromEvent(currentEvent);\n\n  if (!previousException || !currentException) {\n    return false;\n  }\n\n  if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n    return false;\n  }\n\n  if (!_isSameFingerprint(currentEvent, previousEvent)) {\n    return false;\n  }\n\n  if (!_isSameStacktrace(currentEvent, previousEvent)) {\n    return false;\n  }\n\n  return true;\n}\n\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n  let currentFrames = getFramesFromEvent(currentEvent);\n  let previousFrames = getFramesFromEvent(previousEvent);\n\n  // If neither event has a stacktrace, they are assumed to be the same\n  if (!currentFrames \u0026\u0026 !previousFrames) {\n    return true;\n  }\n\n  // If only one event has a stacktrace, but not the other one, they are not the same\n  if ((currentFrames \u0026\u0026 !previousFrames) || (!currentFrames \u0026\u0026 previousFrames)) {\n    return false;\n  }\n\n  currentFrames = currentFrames as StackFrame[];\n  previousFrames = previousFrames as StackFrame[];\n\n  // If number of frames differ, they are not the same\n  if (previousFrames.length !== currentFrames.length) {\n    return false;\n  }\n\n  // Otherwise, compare the two\n  for (let i = 0; i \u003c previousFrames.length; i++) {\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    const frameA = previousFrames[i]!;\n    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n    const frameB = currentFrames[i]!;\n\n    if (\n      frameA.filename !== frameB.filename ||\n      frameA.lineno !== frameB.lineno ||\n      frameA.colno !== frameB.colno ||\n      frameA.function !== frameB.function\n    ) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n  let currentFingerprint = currentEvent.fingerprint;\n  let previousFingerprint = previousEvent.fingerprint;\n\n  // If neither event has a fingerprint, they are assumed to be the same\n  if (!currentFingerprint \u0026\u0026 !previousFingerprint) {\n    return true;\n  }\n\n  // If only one event has a fingerprint, but not the other one, they are not the same\n  if ((currentFingerprint \u0026\u0026 !previousFingerprint) || (!currentFingerprint \u0026\u0026 previousFingerprint)) {\n    return false;\n  }\n\n  currentFingerprint = currentFingerprint as string[];\n  previousFingerprint = previousFingerprint as string[];\n\n  // Otherwise, compare the two\n  try {\n    return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n  } catch {\n    return false;\n  }\n}\n\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n  return event.exception?.values?.[0];\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Contexts } from '../types-hoist/context';\nimport type { ExtendedError } from '../types-hoist/error';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { debug } from '../utils/debug-logger';\nimport { isError, isPlainObject } from '../utils/is';\nimport { normalize } from '../utils/normalize';\nimport { addNonEnumerableProperty } from '../utils/object';\nimport { truncate } from '../utils/string';\n\nconst INTEGRATION_NAME = 'ExtraErrorData';\n\ninterface ExtraErrorDataOptions {\n  /**\n   * The object depth up to which to capture data on error objects.\n   */\n  depth: number;\n\n  /**\n   * Whether to capture error causes. Defaults to true.\n   *\n   * More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n   */\n  captureErrorCause: boolean;\n}\n\n/**\n * Extract additional data for from original exceptions.\n */\nconst _extraErrorDataIntegration = ((options: Partial\u003cExtraErrorDataOptions\u003e = {}) =\u003e {\n  const { depth = 3, captureErrorCause = true } = options;\n  return {\n    name: INTEGRATION_NAME,\n    processEvent(event, hint, client) {\n      const { maxValueLength } = client.getOptions();\n      return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength);\n    },\n  };\n}) satisfies IntegrationFn;\n\nexport const extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration);\n\nfunction _enhanceEventWithErrorData(\n  event: Event,\n  hint: EventHint = {},\n  depth: number,\n  captureErrorCause: boolean,\n  maxValueLength: number | undefined,\n): Event {\n  if (!hint.originalException || !isError(hint.originalException)) {\n    return event;\n  }\n  const exceptionName = (hint.originalException as ExtendedError).name || hint.originalException.constructor.name;\n\n  const errorData = _extractErrorData(hint.originalException as ExtendedError, captureErrorCause, maxValueLength);\n\n  if (errorData) {\n    const contexts: Contexts = {\n      ...event.contexts,\n    };\n\n    const normalizedErrorData = normalize(errorData, depth);\n\n    if (isPlainObject(normalizedErrorData)) {\n      // We mark the error data as \"already normalized\" here, because we don't want other normalization procedures to\n      // potentially truncate the data we just already normalized, with a certain depth setting.\n      addNonEnumerableProperty(normalizedErrorData, '__sentry_skip_normalization__', true);\n      contexts[exceptionName] = normalizedErrorData;\n    }\n\n    return {\n      ...event,\n      contexts,\n    };\n  }\n\n  return event;\n}\n\n/**\n * Extract extra information from the Error object\n */\nfunction _extractErrorData(\n  error: ExtendedError,\n  captureErrorCause: boolean,\n  maxValueLength: number | undefined,\n): Record\u003cstring, unknown\u003e | null {\n  // We are trying to enhance already existing event, so no harm done if it won't succeed\n  try {\n    const nativeKeys = [\n      'name',\n      'message',\n      'stack',\n      'line',\n      'column',\n      'fileName',\n      'lineNumber',\n      'columnNumber',\n      'toJSON',\n    ];\n\n    const extraErrorInfo: Record\u003cstring, unknown\u003e = {};\n\n    // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n    for (const key of Object.keys(error)) {\n      if (nativeKeys.indexOf(key) !== -1) {\n        continue;\n      }\n      const value = error[key];\n      extraErrorInfo[key] =\n        isError(value) || typeof value === 'string'\n          ? maxValueLength\n            ? truncate(`${value}`, maxValueLength)\n            : `${value}`\n          : value;\n    }\n\n    // Error.cause is a standard property that is non enumerable, we therefore need to access it separately.\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n    if (captureErrorCause \u0026\u0026 error.cause !== undefined) {\n      if (isError(error.cause)) {\n        const errorName = error.cause.name || error.cause.constructor.name;\n        extraErrorInfo.cause = { [errorName]: _extractErrorData(error.cause as ExtendedError, false, maxValueLength) };\n      } else {\n        extraErrorInfo.cause = error.cause;\n      }\n    }\n\n    // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n    if (typeof error.toJSON === 'function') {\n      const serializedError = error.toJSON() as Record\u003cstring, unknown\u003e;\n\n      for (const key of Object.keys(serializedError)) {\n        const value = serializedError[key];\n        extraErrorInfo[key] = isError(value) ? value.toString() : value;\n      }\n    }\n\n    return extraErrorInfo;\n  } catch (oO) {\n    DEBUG_BUILD \u0026\u0026 debug.error('Unable to extract extra data from the Error object:', oO);\n  }\n\n  return null;\n}\n","// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js\n//\n// Copyright Joyent, Inc.and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n/** JSDoc */\nfunction normalizeArray(parts: string[], allowAboveRoot?: boolean): string[] {\n  // if the path tries to go above the root, `up` ends up \u003e 0\n  let up = 0;\n  for (let i = parts.length - 1; i \u003e= 0; i--) {\n    const last = parts[i];\n    if (last === '.') {\n      parts.splice(i, 1);\n    } else if (last === '..') {\n      parts.splice(i, 1);\n      up++;\n    } else if (up) {\n      parts.splice(i, 1);\n      up--;\n    }\n  }\n\n  // if the path is allowed to go above the root, restore leading ..s\n  if (allowAboveRoot) {\n    for (; up--; up) {\n      parts.unshift('..');\n    }\n  }\n\n  return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\S+:\\\\|\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^/\\\\]+?|)(\\.[^./\\\\]*|))(?:[/\\\\]*)$/;\n/** JSDoc */\nfunction splitPath(filename: string): string[] {\n  // Truncate files names greater than 1024 characters to avoid regex dos\n  // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172\n  const truncated = filename.length \u003e 1024 ? `\u003ctruncated\u003e${filename.slice(-1024)}` : filename;\n  const parts = splitPathRe.exec(truncated);\n  return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nexport function resolve(...args: string[]): string {\n  let resolvedPath = '';\n  let resolvedAbsolute = false;\n\n  for (let i = args.length - 1; i \u003e= -1 \u0026\u0026 !resolvedAbsolute; i--) {\n    const path = i \u003e= 0 ? args[i] : '/';\n\n    // Skip empty entries\n    if (!path) {\n      continue;\n    }\n\n    resolvedPath = `${path}/${resolvedPath}`;\n    resolvedAbsolute = path.charAt(0) === '/';\n  }\n\n  // At this point the path should be resolved to a full absolute path, but\n  // handle relative paths to be safe (might happen when process.cwd() fails)\n\n  // Normalize the path\n  resolvedPath = normalizeArray(\n    resolvedPath.split('/').filter(p =\u003e !!p),\n    !resolvedAbsolute,\n  ).join('/');\n\n  return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr: string[]): string[] {\n  let start = 0;\n  for (; start \u003c arr.length; start++) {\n    if (arr[start] !== '') {\n      break;\n    }\n  }\n\n  let end = arr.length - 1;\n  for (; end \u003e= 0; end--) {\n    if (arr[end] !== '') {\n      break;\n    }\n  }\n\n  if (start \u003e end) {\n    return [];\n  }\n  return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nexport function relative(from: string, to: string): string {\n  /* eslint-disable no-param-reassign */\n  from = resolve(from).slice(1);\n  to = resolve(to).slice(1);\n  /* eslint-enable no-param-reassign */\n\n  const fromParts = trim(from.split('/'));\n  const toParts = trim(to.split('/'));\n\n  const length = Math.min(fromParts.length, toParts.length);\n  let samePartsLength = length;\n  for (let i = 0; i \u003c length; i++) {\n    if (fromParts[i] !== toParts[i]) {\n      samePartsLength = i;\n      break;\n    }\n  }\n\n  let outputParts = [];\n  for (let i = samePartsLength; i \u003c fromParts.length; i++) {\n    outputParts.push('..');\n  }\n\n  outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n  return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nexport function normalizePath(path: string): string {\n  const isPathAbsolute = isAbsolute(path);\n  const trailingSlash = path.slice(-1) === '/';\n\n  // Normalize the path\n  let normalizedPath = normalizeArray(\n    path.split('/').filter(p =\u003e !!p),\n    !isPathAbsolute,\n  ).join('/');\n\n  if (!normalizedPath \u0026\u0026 !isPathAbsolute) {\n    normalizedPath = '.';\n  }\n  if (normalizedPath \u0026\u0026 trailingSlash) {\n    normalizedPath += '/';\n  }\n\n  return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nexport function isAbsolute(path: string): boolean {\n  return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nexport function join(...args: string[]): string {\n  return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nexport function dirname(path: string): string {\n  const result = splitPath(path);\n  const root = result[0] || '';\n  let dir = result[1];\n\n  if (!root \u0026\u0026 !dir) {\n    // No dirname whatsoever\n    return '.';\n  }\n\n  if (dir) {\n    // It has a dirname, strip trailing slash\n    dir = dir.slice(0, dir.length - 1);\n  }\n\n  return root + dir;\n}\n\n/** JSDoc */\nexport function basename(path: string, ext?: string): string {\n  let f = splitPath(path)[2] || '';\n  if (ext \u0026\u0026 f.slice(ext.length * -1) === ext) {\n    f = f.slice(0, f.length - ext.length);\n  }\n  return f;\n}\n","import { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport type { Stacktrace } from '../types-hoist/stacktrace';\nimport { basename, relative } from '../utils/path';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\ntype StackFrameIteratee = (frame: StackFrame) =\u003e StackFrame;\n\nconst INTEGRATION_NAME = 'RewriteFrames';\n\ninterface RewriteFramesOptions {\n  /**\n   * Root path (the beginning of the path) that will be stripped from the frames' filename.\n   *\n   * This option has slightly different behaviour in the browser and on servers:\n   * - In the browser, the value you provide in `root` will be stripped from the beginning stack frames' paths (if the path started with the value).\n   * - On the server, the root value will only replace the beginning of stack frame filepaths, when the path is absolute. If no `root` value is provided and the path is absolute, the frame will be reduced to only the filename and the provided `prefix` option.\n   *\n   * Browser example:\n   * - Original frame: `'http://example.com/my/path/static/asset.js'`\n   * - `root: 'http://example.com/my/path'`\n   * - `assetPrefix: 'app://'`\n   * - Resulting frame: `'app:///static/asset.js'`\n   *\n   * Server example:\n   * - Original frame: `'/User/local/my/path/static/asset.js'`\n   * - `root: '/User/local/my/path'`\n   * - `assetPrefix: 'app://'`\n   * - Resulting frame: `'app:///static/asset.js'`\n   */\n  root?: string;\n\n  /**\n   * A custom prefix that stack frames will be prepended with.\n   *\n   * Default: `'app://'`\n   *\n   * This option has slightly different behaviour in the browser and on servers:\n   * - In the browser, the value you provide in `prefix` will prefix the resulting filename when the value you provided in `root` was applied. Effectively replacing whatever `root` matched in the beginning of the frame with `prefix`.\n   * - On the server, the prefix is applied to all stackframes with absolute paths. On Windows, the drive identifier (e.g. \"C://\") is replaced with the prefix.\n   */\n  prefix?: string;\n\n  /**\n   * Defines an iterator that is used to iterate through all of the stack frames for modification before being sent to Sentry.\n   * Setting this option will effectively disable both the `root` and the `prefix` options.\n   */\n  iteratee?: StackFrameIteratee;\n}\n\n/**\n * Rewrite event frames paths.\n */\nexport const rewriteFramesIntegration = defineIntegration((options: RewriteFramesOptions = {}) =\u003e {\n  const root = options.root;\n  const prefix = options.prefix || 'app:///';\n\n  const isBrowser = 'window' in GLOBAL_OBJ \u0026\u0026 !!GLOBAL_OBJ.window;\n\n  const iteratee: StackFrameIteratee = options.iteratee || generateIteratee({ isBrowser, root, prefix });\n\n  /** Process an exception event. */\n  function _processExceptionsEvent(event: Event): Event {\n    try {\n      return {\n        ...event,\n        exception: {\n          ...event.exception,\n          // The check for this is performed inside `process` call itself, safe to skip here\n          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n          values: event.exception!.values!.map(value =\u003e ({\n            ...value,\n            ...(value.stacktrace \u0026\u0026 { stacktrace: _processStacktrace(value.stacktrace) }),\n          })),\n        },\n      };\n    } catch {\n      return event;\n    }\n  }\n\n  /** Process a stack trace. */\n  function _processStacktrace(stacktrace?: Stacktrace): Stacktrace {\n    return {\n      ...stacktrace,\n      frames: stacktrace?.frames?.map(f =\u003e iteratee(f)),\n    };\n  }\n\n  return {\n    name: INTEGRATION_NAME,\n    processEvent(originalEvent) {\n      let processedEvent = originalEvent;\n\n      if (originalEvent.exception \u0026\u0026 Array.isArray(originalEvent.exception.values)) {\n        processedEvent = _processExceptionsEvent(processedEvent);\n      }\n\n      return processedEvent;\n    },\n  };\n});\n\n/**\n * Exported only for tests.\n */\nexport function generateIteratee({\n  isBrowser,\n  root,\n  prefix,\n}: {\n  isBrowser: boolean;\n  root?: string;\n  prefix: string;\n}): StackFrameIteratee {\n  return (frame: StackFrame) =\u003e {\n    if (!frame.filename) {\n      return frame;\n    }\n\n    // Determine if this is a Windows frame by checking for a Windows-style prefix such as `C:\\`\n    const isWindowsFrame =\n      /^[a-zA-Z]:\\\\/.test(frame.filename) ||\n      // or the presence of a backslash without a forward slash (which are not allowed on Windows)\n      (frame.filename.includes('\\\\') \u0026\u0026 !frame.filename.includes('/'));\n\n    // Check if the frame filename begins with `/`\n    const startsWithSlash = /^\\//.test(frame.filename);\n\n    if (isBrowser) {\n      if (root) {\n        const oldFilename = frame.filename;\n        if (oldFilename.indexOf(root) === 0) {\n          frame.filename = oldFilename.replace(root, prefix);\n        }\n      }\n    } else {\n      if (isWindowsFrame || startsWithSlash) {\n        const filename = isWindowsFrame\n          ? frame.filename\n              .replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix\n              .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n          : frame.filename;\n        const base = root ? relative(root, filename) : basename(filename);\n        frame.filename = `${prefix}${base}`;\n      }\n    }\n\n    return frame;\n  };\n}\n","// Based on Kamil Ogórek's work on:\n// https://github.com/supabase-community/sentry-integration-js\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable max-lines */\nimport { addBreadcrumb } from '../breadcrumbs';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { captureException } from '../exports';\nimport { defineIntegration } from '../integration';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes';\nimport { setHttpStatus, SPAN_STATUS_ERROR, SPAN_STATUS_OK, startSpan } from '../tracing';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { debug } from '../utils/debug-logger';\nimport { isPlainObject } from '../utils/is';\nimport { addExceptionMechanism } from '../utils/misc';\n\nconst AUTH_OPERATIONS_TO_INSTRUMENT = [\n  'reauthenticate',\n  'signInAnonymously',\n  'signInWithOAuth',\n  'signInWithIdToken',\n  'signInWithOtp',\n  'signInWithPassword',\n  'signInWithSSO',\n  'signOut',\n  'signUp',\n  'verifyOtp',\n];\n\nconst AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT = [\n  'createUser',\n  'deleteUser',\n  'listUsers',\n  'getUserById',\n  'updateUserById',\n  'inviteUserByEmail',\n];\n\nexport const FILTER_MAPPINGS = {\n  eq: 'eq',\n  neq: 'neq',\n  gt: 'gt',\n  gte: 'gte',\n  lt: 'lt',\n  lte: 'lte',\n  like: 'like',\n  'like(all)': 'likeAllOf',\n  'like(any)': 'likeAnyOf',\n  ilike: 'ilike',\n  'ilike(all)': 'ilikeAllOf',\n  'ilike(any)': 'ilikeAnyOf',\n  is: 'is',\n  in: 'in',\n  cs: 'contains',\n  cd: 'containedBy',\n  sr: 'rangeGt',\n  nxl: 'rangeGte',\n  sl: 'rangeLt',\n  nxr: 'rangeLte',\n  adj: 'rangeAdjacent',\n  ov: 'overlaps',\n  fts: '',\n  plfts: 'plain',\n  phfts: 'phrase',\n  wfts: 'websearch',\n  not: 'not',\n};\n\nexport const DB_OPERATIONS_TO_INSTRUMENT = ['select', 'insert', 'upsert', 'update', 'delete'];\n\ntype AuthOperationFn = (...args: unknown[]) =\u003e Promise\u003cunknown\u003e;\ntype AuthOperationName = (typeof AUTH_OPERATIONS_TO_INSTRUMENT)[number];\ntype AuthAdminOperationName = (typeof AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT)[number];\ntype PostgRESTQueryOperationFn = (...args: unknown[]) =\u003e PostgRESTFilterBuilder;\n\nexport interface SupabaseClientInstance {\n  auth: {\n    admin: Record\u003cAuthAdminOperationName, AuthOperationFn\u003e;\n  } \u0026 Record\u003cAuthOperationName, AuthOperationFn\u003e;\n}\n\nexport interface PostgRESTQueryBuilder {\n  [key: string]: PostgRESTQueryOperationFn;\n}\n\nexport interface PostgRESTFilterBuilder {\n  method: string;\n  headers: Record\u003cstring, string\u003e;\n  url: URL;\n  schema: string;\n  body: any;\n}\n\nexport interface SupabaseResponse {\n  status?: number;\n  error?: {\n    message: string;\n    code?: string;\n    details?: unknown;\n  };\n}\n\nexport interface SupabaseError extends Error {\n  code?: string;\n  details?: unknown;\n}\n\nexport interface SupabaseBreadcrumb {\n  type: string;\n  category: string;\n  message: string;\n  data?: {\n    query?: string[];\n    body?: Record\u003cstring, unknown\u003e;\n  };\n}\n\nexport interface SupabaseClientConstructor {\n  prototype: {\n    from: (table: string) =\u003e PostgRESTQueryBuilder;\n  };\n}\n\nexport interface PostgRESTProtoThenable {\n  then: \u003cT\u003e(\n    onfulfilled?: ((value: T) =\u003e T | PromiseLike\u003cT\u003e) | null,\n    onrejected?: ((reason: any) =\u003e T | PromiseLike\u003cT\u003e) | null,\n  ) =\u003e Promise\u003cT\u003e;\n}\n\ntype SentryInstrumented\u003cT\u003e = T \u0026 {\n  __SENTRY_INSTRUMENTED__?: boolean;\n};\n\nfunction markAsInstrumented\u003cT\u003e(fn: T): void {\n  try {\n    (fn as SentryInstrumented\u003cT\u003e).__SENTRY_INSTRUMENTED__ = true;\n  } catch {\n    // ignore errors here\n  }\n}\n\nfunction isInstrumented\u003cT\u003e(fn: T): boolean | undefined {\n  try {\n    return (fn as SentryInstrumented\u003cT\u003e).__SENTRY_INSTRUMENTED__;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Extracts the database operation type from the HTTP method and headers\n * @param method - The HTTP method of the request\n * @param headers - The request headers\n * @returns The database operation type ('select', 'insert', 'upsert', 'update', or 'delete')\n */\nexport function extractOperation(method: string, headers: Record\u003cstring, string\u003e = {}): string {\n  switch (method) {\n    case 'GET': {\n      return 'select';\n    }\n    case 'POST': {\n      if (headers['Prefer']?.includes('resolution=')) {\n        return 'upsert';\n      } else {\n        return 'insert';\n      }\n    }\n    case 'PATCH': {\n      return 'update';\n    }\n    case 'DELETE': {\n      return 'delete';\n    }\n    default: {\n      return '\u003cunknown-op\u003e';\n    }\n  }\n}\n\n/**\n * Translates Supabase filter parameters into readable method names for tracing\n * @param key - The filter key from the URL search parameters\n * @param query - The filter value from the URL search parameters\n * @returns A string representation of the filter as a method call\n */\nexport function translateFiltersIntoMethods(key: string, query: string): string {\n  if (query === '' || query === '*') {\n    return 'select(*)';\n  }\n\n  if (key === 'select') {\n    return `select(${query})`;\n  }\n\n  if (key === 'or' || key.endsWith('.or')) {\n    return `${key}${query}`;\n  }\n\n  const [filter, ...value] = query.split('.');\n\n  let method;\n  // Handle optional `configPart` of the filter\n  if (filter?.startsWith('fts')) {\n    method = 'textSearch';\n  } else if (filter?.startsWith('plfts')) {\n    method = 'textSearch[plain]';\n  } else if (filter?.startsWith('phfts')) {\n    method = 'textSearch[phrase]';\n  } else if (filter?.startsWith('wfts')) {\n    method = 'textSearch[websearch]';\n  } else {\n    method = (filter \u0026\u0026 FILTER_MAPPINGS[filter as keyof typeof FILTER_MAPPINGS]) || 'filter';\n  }\n\n  return `${method}(${key}, ${value.join('.')})`;\n}\n\nfunction instrumentAuthOperation(operation: AuthOperationFn, isAdmin = false): AuthOperationFn {\n  return new Proxy(operation, {\n    apply(target, thisArg, argumentsList) {\n      return startSpan(\n        {\n          name: `auth ${isAdmin ? '(admin) ' : ''}${operation.name}`,\n          attributes: {\n            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.supabase',\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db',\n            'db.system': 'postgresql',\n            'db.operation': `auth.${isAdmin ? 'admin.' : ''}${operation.name}`,\n          },\n        },\n        span =\u003e {\n          return Reflect.apply(target, thisArg, argumentsList)\n            .then((res: unknown) =\u003e {\n              if (res \u0026\u0026 typeof res === 'object' \u0026\u0026 'error' in res \u0026\u0026 res.error) {\n                span.setStatus({ code: SPAN_STATUS_ERROR });\n\n                captureException(res.error, {\n                  mechanism: {\n                    handled: false,\n                    type: 'auto.db.supabase.auth',\n                  },\n                });\n              } else {\n                span.setStatus({ code: SPAN_STATUS_OK });\n              }\n\n              span.end();\n              return res;\n            })\n            .catch((err: unknown) =\u003e {\n              span.setStatus({ code: SPAN_STATUS_ERROR });\n              span.end();\n\n              captureException(err, {\n                mechanism: {\n                  handled: false,\n                  type: 'auto.db.supabase.auth',\n                },\n              });\n\n              throw err;\n            })\n            .then(...argumentsList);\n        },\n      );\n    },\n  });\n}\n\nfunction instrumentSupabaseAuthClient(supabaseClientInstance: SupabaseClientInstance): void {\n  const auth = supabaseClientInstance.auth;\n\n  if (!auth || isInstrumented(supabaseClientInstance.auth)) {\n    return;\n  }\n\n  for (const operation of AUTH_OPERATIONS_TO_INSTRUMENT) {\n    const authOperation = auth[operation];\n\n    if (!authOperation) {\n      continue;\n    }\n\n    if (typeof supabaseClientInstance.auth[operation] === 'function') {\n      supabaseClientInstance.auth[operation] = instrumentAuthOperation(authOperation);\n    }\n  }\n\n  for (const operation of AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT) {\n    const authOperation = auth.admin[operation];\n\n    if (!authOperation) {\n      continue;\n    }\n\n    if (typeof supabaseClientInstance.auth.admin[operation] === 'function') {\n      supabaseClientInstance.auth.admin[operation] = instrumentAuthOperation(authOperation, true);\n    }\n  }\n\n  markAsInstrumented(supabaseClientInstance.auth);\n}\n\nfunction instrumentSupabaseClientConstructor(SupabaseClient: unknown): void {\n  if (isInstrumented((SupabaseClient as SupabaseClientConstructor).prototype.from)) {\n    return;\n  }\n\n  (SupabaseClient as SupabaseClientConstructor).prototype.from = new Proxy(\n    (SupabaseClient as SupabaseClientConstructor).prototype.from,\n    {\n      apply(target, thisArg, argumentsList) {\n        const rv = Reflect.apply(target, thisArg, argumentsList);\n        const PostgRESTQueryBuilder = (rv as PostgRESTQueryBuilder).constructor;\n\n        instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder as unknown as new () =\u003e PostgRESTQueryBuilder);\n\n        return rv;\n      },\n    },\n  );\n\n  markAsInstrumented((SupabaseClient as SupabaseClientConstructor).prototype.from);\n}\n\nfunction instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder: PostgRESTFilterBuilder['constructor']): void {\n  if (isInstrumented((PostgRESTFilterBuilder.prototype as unknown as PostgRESTProtoThenable).then)) {\n    return;\n  }\n\n  (PostgRESTFilterBuilder.prototype as unknown as PostgRESTProtoThenable).then = new Proxy(\n    (PostgRESTFilterBuilder.prototype as unknown as PostgRESTProtoThenable).then,\n    {\n      apply(target, thisArg, argumentsList) {\n        const operations = DB_OPERATIONS_TO_INSTRUMENT;\n        const typedThis = thisArg as PostgRESTFilterBuilder;\n        const operation = extractOperation(typedThis.method, typedThis.headers);\n\n        if (!operations.includes(operation)) {\n          return Reflect.apply(target, thisArg, argumentsList);\n        }\n\n        if (!typedThis?.url?.pathname || typeof typedThis.url.pathname !== 'string') {\n          return Reflect.apply(target, thisArg, argumentsList);\n        }\n\n        const pathParts = typedThis.url.pathname.split('/');\n        const table = pathParts.length \u003e 0 ? pathParts[pathParts.length - 1] : '';\n\n        const queryItems: string[] = [];\n        for (const [key, value] of typedThis.url.searchParams.entries()) {\n          // It's possible to have multiple entries for the same key, eg. `id=eq.7\u0026id=eq.3`,\n          // so we need to use array instead of object to collect them.\n          queryItems.push(translateFiltersIntoMethods(key, value));\n        }\n        const body: Record\u003cstring, unknown\u003e = Object.create(null);\n        if (isPlainObject(typedThis.body)) {\n          for (const [key, value] of Object.entries(typedThis.body)) {\n            body[key] = value;\n          }\n        }\n\n        // Adding operation to the beginning of the description if it's not a `select` operation\n        // For example, it can be an `insert` or `update` operation but the query can be `select(...)`\n        // For `select` operations, we don't need repeat it in the description\n        const description = `${operation === 'select' ? '' : `${operation}${body ? '(...) ' : ''}`}${queryItems.join(\n          ' ',\n        )} from(${table})`;\n\n        const attributes: Record\u003cstring, any\u003e = {\n          'db.table': table,\n          'db.schema': typedThis.schema,\n          'db.url': typedThis.url.origin,\n          'db.sdk': typedThis.headers['X-Client-Info'],\n          'db.system': 'postgresql',\n          'db.operation': operation,\n          [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.supabase',\n          [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db',\n        };\n\n        if (queryItems.length) {\n          attributes['db.query'] = queryItems;\n        }\n\n        if (Object.keys(body).length) {\n          attributes['db.body'] = body;\n        }\n\n        return startSpan(\n          {\n            name: description,\n            attributes,\n          },\n          span =\u003e {\n            return (Reflect.apply(target, thisArg, []) as Promise\u003cSupabaseResponse\u003e)\n              .then(\n                (res: SupabaseResponse) =\u003e {\n                  if (span) {\n                    if (res \u0026\u0026 typeof res === 'object' \u0026\u0026 'status' in res) {\n                      setHttpStatus(span, res.status || 500);\n                    }\n                    span.end();\n                  }\n\n                  if (res.error) {\n                    const err = new Error(res.error.message) as SupabaseError;\n                    if (res.error.code) {\n                      err.code = res.error.code;\n                    }\n                    if (res.error.details) {\n                      err.details = res.error.details;\n                    }\n\n                    const supabaseContext: Record\u003cstring, any\u003e = {};\n                    if (queryItems.length) {\n                      supabaseContext.query = queryItems;\n                    }\n                    if (Object.keys(body).length) {\n                      supabaseContext.body = body;\n                    }\n\n                    captureException(err, scope =\u003e {\n                      scope.addEventProcessor(e =\u003e {\n                        addExceptionMechanism(e, {\n                          handled: false,\n                          type: 'auto.db.supabase.postgres',\n                        });\n\n                        return e;\n                      });\n\n                      scope.setContext('supabase', supabaseContext);\n\n                      return scope;\n                    });\n                  }\n\n                  const breadcrumb: SupabaseBreadcrumb = {\n                    type: 'supabase',\n                    category: `db.${operation}`,\n                    message: description,\n                  };\n\n                  const data: Record\u003cstring, unknown\u003e = {};\n\n                  if (queryItems.length) {\n                    data.query = queryItems;\n                  }\n\n                  if (Object.keys(body).length) {\n                    data.body = body;\n                  }\n\n                  if (Object.keys(data).length) {\n                    breadcrumb.data = data;\n                  }\n\n                  addBreadcrumb(breadcrumb);\n\n                  return res;\n                },\n                (err: Error) =\u003e {\n                  // TODO: shouldn't we capture this error?\n                  if (span) {\n                    setHttpStatus(span, 500);\n                    span.end();\n                  }\n                  throw err;\n                },\n              )\n              .then(...argumentsList);\n          },\n        );\n      },\n    },\n  );\n\n  markAsInstrumented((PostgRESTFilterBuilder.prototype as unknown as PostgRESTProtoThenable).then);\n}\n\nfunction instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder: new () =\u003e PostgRESTQueryBuilder): void {\n  // We need to wrap _all_ operations despite them sharing the same `PostgRESTFilterBuilder`\n  // constructor, as we don't know which method will be called first, and we don't want to miss any calls.\n  for (const operation of DB_OPERATIONS_TO_INSTRUMENT) {\n    if (isInstrumented((PostgRESTQueryBuilder.prototype as Record\u003cstring, any\u003e)[operation])) {\n      continue;\n    }\n\n    type PostgRESTOperation = keyof Pick\u003cPostgRESTQueryBuilder, 'select' | 'insert' | 'upsert' | 'update' | 'delete'\u003e;\n    (PostgRESTQueryBuilder.prototype as Record\u003cstring, any\u003e)[operation as PostgRESTOperation] = new Proxy(\n      (PostgRESTQueryBuilder.prototype as Record\u003cstring, any\u003e)[operation as PostgRESTOperation],\n      {\n        apply(target, thisArg, argumentsList) {\n          const rv = Reflect.apply(target, thisArg, argumentsList);\n          const PostgRESTFilterBuilder = (rv as PostgRESTFilterBuilder).constructor;\n\n          DEBUG_BUILD \u0026\u0026 debug.log(`Instrumenting ${operation} operation's PostgRESTFilterBuilder`);\n\n          instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder);\n\n          return rv;\n        },\n      },\n    );\n\n    markAsInstrumented((PostgRESTQueryBuilder.prototype as Record\u003cstring, any\u003e)[operation]);\n  }\n}\n\nexport const instrumentSupabaseClient = (supabaseClient: unknown): void =\u003e {\n  if (!supabaseClient) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('Supabase integration was not installed because no Supabase client was provided.');\n    return;\n  }\n  const SupabaseClientConstructor =\n    supabaseClient.constructor === Function ? supabaseClient : supabaseClient.constructor;\n\n  instrumentSupabaseClientConstructor(SupabaseClientConstructor);\n  instrumentSupabaseAuthClient(supabaseClient as SupabaseClientInstance);\n};\n\nconst INTEGRATION_NAME = 'Supabase';\n\nconst _supabaseIntegration = ((supabaseClient: unknown) =\u003e {\n  return {\n    setupOnce() {\n      instrumentSupabaseClient(supabaseClient);\n    },\n    name: INTEGRATION_NAME,\n  };\n}) satisfies IntegrationFn;\n\nexport const supabaseIntegration = defineIntegration((options: { supabaseClient: any }) =\u003e {\n  return _supabaseIntegration(options.supabaseClient);\n}) satisfies IntegrationFn;\n","// Portable instrumentation for https://github.com/porsager/postgres\n// This can be used in any environment (Node.js, Cloudflare Workers, etc.)\n// without depending on OpenTelemetry module hooking.\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes';\nimport { SPAN_STATUS_ERROR, startSpanManual } from '../tracing';\nimport type { Span } from '../types-hoist/span';\nimport { debug } from '../utils/debug-logger';\nimport { getActiveSpan } from '../utils/spanUtils';\n\nconst SQL_OPERATION_REGEX = /^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i;\n\ntype PostgresConnectionContext = {\n  ATTR_DB_NAMESPACE?: string;\n  ATTR_SERVER_ADDRESS?: string;\n  ATTR_SERVER_PORT?: string;\n};\n\ninterface PostgresJsSqlInstrumentationOptions {\n  /**\n   * Whether to require a parent span for the instrumentation.\n   * If set to true, the instrumentation will only create spans if there is a parent span\n   * available in the current scope.\n   * @default true\n   */\n  requireParentSpan?: boolean;\n  /**\n   * Hook to modify the span before it is started.\n   * This can be used to set additional attributes or modify the span in any way.\n   */\n  requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) =\u003e void;\n}\n\nconst CONNECTION_CONTEXT_SYMBOL = Symbol('sentryPostgresConnectionContext');\n\n// Use the same Symbol.for() markers as the Node.js OTel instrumentation\n// so that both approaches recognize each other and prevent double-wrapping.\nconst INSTRUMENTED_MARKER = Symbol.for('sentry.instrumented.postgresjs');\n// Marker to track if a query was created from an instrumented sql instance.\n// This prevents double-spanning when both the wrapper and the Node.js Query.prototype\n// fallback patch are active simultaneously.\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n\n/**\n * Instruments a postgres.js `sql` instance with Sentry tracing.\n *\n * This is a portable instrumentation function that works in any environment\n * (Node.js, Cloudflare Workers, etc.) without depending on OpenTelemetry.\n *\n * @example\n * ```javascript\n * import postgres from 'postgres';\n * import * as Sentry from '@sentry/cloudflare'; // or '@sentry/deno'\n *\n * const sql = Sentry.instrumentPostgresJsSql(\n *   postgres({ host: 'localhost', database: 'mydb' })\n * );\n *\n * // All queries now create Sentry spans\n * await sql`SELECT * FROM users WHERE id = ${userId}`;\n * ```\n */\nexport function instrumentPostgresJsSql\u003cT\u003e(sql: T, options?: PostgresJsSqlInstrumentationOptions): T {\n  if (!sql || typeof sql !== 'function') {\n    DEBUG_BUILD \u0026\u0026 debug.warn('instrumentPostgresJsSql: provided value is not a valid postgres.js sql instance');\n    return sql;\n  }\n\n  return _instrumentSqlInstance(sql, { requireParentSpan: true, ...options }) as T;\n}\n\n/**\n * Instruments a sql instance by wrapping its query execution methods.\n */\nfunction _instrumentSqlInstance(\n  sql: unknown,\n  options: PostgresJsSqlInstrumentationOptions,\n  parentConnectionContext?: PostgresConnectionContext,\n): unknown {\n  // Check if already instrumented to prevent double-wrapping\n  // Using Symbol.for() ensures the marker survives proxying\n  if ((sql as Record\u003csymbol, unknown\u003e)[INSTRUMENTED_MARKER]) {\n    return sql;\n  }\n\n  // Wrap the sql function to intercept query creation\n  const proxiedSql: unknown = new Proxy(sql as (...args: unknown[]) =\u003e unknown, {\n    apply(target, thisArg, argumentsList: unknown[]) {\n      const query = Reflect.apply(target, thisArg, argumentsList);\n\n      if (query \u0026\u0026 typeof query === 'object' \u0026\u0026 'handle' in query) {\n        _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n      }\n\n      return query;\n    },\n    get(target, prop) {\n      const original = (target as unknown as Record\u003cstring | symbol, unknown\u003e)[prop];\n\n      if (typeof prop !== 'string' || typeof original !== 'function') {\n        return original;\n      }\n\n      // Wrap methods that return PendingQuery objects (unsafe, file)\n      if (prop === 'unsafe' || prop === 'file') {\n        return _wrapQueryMethod(original as (...args: unknown[]) =\u003e unknown, target, proxiedSql, options);\n      }\n\n      // Wrap begin and reserve (not savepoint to avoid duplicate spans)\n      if (prop === 'begin' || prop === 'reserve') {\n        return _wrapCallbackMethod(original as (...args: unknown[]) =\u003e unknown, target, proxiedSql, options);\n      }\n\n      return original;\n    },\n  });\n\n  // Use provided parent context if available, otherwise extract from sql.options\n  if (parentConnectionContext) {\n    (proxiedSql as Record\u003csymbol, unknown\u003e)[CONNECTION_CONTEXT_SYMBOL] = parentConnectionContext;\n  } else {\n    _attachConnectionContext(sql, proxiedSql as Record\u003csymbol, unknown\u003e);\n  }\n\n  // Mark both the original and proxy as instrumented to prevent double-wrapping\n  (sql as Record\u003csymbol, unknown\u003e)[INSTRUMENTED_MARKER] = true;\n  (proxiedSql as Record\u003csymbol, unknown\u003e)[INSTRUMENTED_MARKER] = true;\n\n  return proxiedSql;\n}\n\n/**\n * Wraps query-returning methods (unsafe, file) to ensure their queries are instrumented.\n */\nfunction _wrapQueryMethod(\n  original: (...args: unknown[]) =\u003e unknown,\n  target: unknown,\n  proxiedSql: unknown,\n  options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) =\u003e unknown {\n  return function (this: unknown, ...args: unknown[]): unknown {\n    const query = Reflect.apply(original, target, args);\n\n    if (query \u0026\u0026 typeof query === 'object' \u0026\u0026 'handle' in query) {\n      _wrapSingleQueryHandle(query as { handle: unknown; strings?: string[] }, proxiedSql, options);\n    }\n\n    return query;\n  };\n}\n\n/**\n * Wraps callback-based methods (begin, reserve) to recursively instrument Sql instances.\n * Note: These methods can also be used as tagged templates, which we pass through unchanged.\n *\n * Savepoint is not wrapped to avoid complex nested transaction instrumentation issues.\n * Queries within savepoint callbacks are still instrumented through the parent transaction's Sql instance.\n */\nfunction _wrapCallbackMethod(\n  original: (...args: unknown[]) =\u003e unknown,\n  target: unknown,\n  parentSqlInstance: unknown,\n  options: PostgresJsSqlInstrumentationOptions,\n): (...args: unknown[]) =\u003e unknown {\n  return function (this: unknown, ...args: unknown[]): unknown {\n    // Extract parent context to propagate to child instances\n    const parentContext = (parentSqlInstance as Record\u003csymbol, unknown\u003e)[CONNECTION_CONTEXT_SYMBOL] as\n      | PostgresConnectionContext\n      | undefined;\n\n    // Check if this is a callback-based call by verifying the last argument is a function\n    const isCallbackBased = typeof args[args.length - 1] === 'function';\n\n    if (!isCallbackBased) {\n      // Not a callback-based call - could be tagged template or promise-based\n      const result = Reflect.apply(original, target, args);\n      // If result is a Promise (e.g., reserve() without callback), instrument the resolved Sql instance\n      if (result \u0026\u0026 typeof (result as Promise\u003cunknown\u003e).then === 'function') {\n        return (result as Promise\u003cunknown\u003e).then((sqlInstance: unknown) =\u003e {\n          return _instrumentSqlInstance(sqlInstance, options, parentContext);\n        });\n      }\n      return result;\n    }\n\n    // Callback-based call: wrap the callback to instrument the Sql instance\n    const callback = (args.length === 1 ? args[0] : args[1]) as (sql: unknown) =\u003e unknown;\n    const wrappedCallback = function (sqlInstance: unknown): unknown {\n      const instrumentedSql = _instrumentSqlInstance(sqlInstance, options, parentContext);\n      return callback(instrumentedSql);\n    };\n\n    const newArgs = args.length === 1 ? [wrappedCallback] : [args[0], wrappedCallback];\n    return Reflect.apply(original, target, newArgs);\n  };\n}\n\n/**\n * Wraps a single query's handle method to create spans.\n */\nfunction _wrapSingleQueryHandle(\n  query: { handle: unknown; strings?: string[]; __sentryWrapped?: boolean },\n  sqlInstance: unknown,\n  options: PostgresJsSqlInstrumentationOptions,\n): void {\n  // Prevent double wrapping - check if the handle itself is already wrapped\n  if ((query.handle as { __sentryWrapped?: boolean })?.__sentryWrapped) {\n    return;\n  }\n\n  // Mark this query as coming from an instrumented sql instance.\n  // This prevents the Node.js Query.prototype fallback patch from double-spanning.\n  (query as Record\u003csymbol, unknown\u003e)[QUERY_FROM_INSTRUMENTED_SQL] = true;\n\n  const originalHandle = query.handle as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e;\n\n  // IMPORTANT: We must replace the handle function directly, not use a Proxy,\n  // because Query.then() internally calls this.handle(), which would bypass a Proxy wrapper.\n  const wrappedHandle = async function (this: unknown, ...args: unknown[]): Promise\u003cunknown\u003e {\n    if (!_shouldCreateSpans(options)) {\n      return originalHandle.apply(this, args);\n    }\n\n    const fullQuery = _reconstructQuery(query.strings);\n    const sanitizedSqlQuery = _sanitizeSqlQuery(fullQuery);\n\n    return startSpanManual(\n      {\n        name: sanitizedSqlQuery || 'postgresjs.query',\n        op: 'db',\n      },\n      (span: Span) =\u003e {\n        span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.postgresjs');\n\n        span.setAttributes({\n          'db.system.name': 'postgres',\n          'db.query.text': sanitizedSqlQuery,\n        });\n\n        const connectionContext = sqlInstance\n          ? ((sqlInstance as Record\u003csymbol, unknown\u003e)[CONNECTION_CONTEXT_SYMBOL] as\n              | PostgresConnectionContext\n              | undefined)\n          : undefined;\n\n        _setConnectionAttributes(span, connectionContext);\n\n        if (options.requestHook) {\n          try {\n            options.requestHook(span, sanitizedSqlQuery, connectionContext);\n          } catch (e) {\n            span.setAttribute('sentry.hook.error', 'requestHook failed');\n            DEBUG_BUILD \u0026\u0026 debug.error('Error in requestHook for PostgresJs instrumentation:', e);\n          }\n        }\n\n        const queryWithCallbacks = this as {\n          resolve: unknown;\n          reject: unknown;\n        };\n\n        queryWithCallbacks.resolve = new Proxy(queryWithCallbacks.resolve as (...args: unknown[]) =\u003e unknown, {\n          apply: (resolveTarget, resolveThisArg, resolveArgs: [{ command?: string }]) =\u003e {\n            try {\n              _setOperationName(span, sanitizedSqlQuery, resolveArgs?.[0]?.command);\n              span.end();\n            } catch (e) {\n              DEBUG_BUILD \u0026\u0026 debug.error('Error ending span in resolve callback:', e);\n            }\n\n            return Reflect.apply(resolveTarget, resolveThisArg, resolveArgs);\n          },\n        });\n\n        queryWithCallbacks.reject = new Proxy(queryWithCallbacks.reject as (...args: unknown[]) =\u003e unknown, {\n          apply: (rejectTarget, rejectThisArg, rejectArgs: { message?: string; code?: string; name?: string }[]) =\u003e {\n            try {\n              span.setStatus({\n                code: SPAN_STATUS_ERROR,\n                message: rejectArgs?.[0]?.message || 'unknown_error',\n              });\n\n              span.setAttribute('db.response.status_code', rejectArgs?.[0]?.code || 'unknown');\n              span.setAttribute('error.type', rejectArgs?.[0]?.name || 'unknown');\n\n              _setOperationName(span, sanitizedSqlQuery);\n              span.end();\n            } catch (e) {\n              DEBUG_BUILD \u0026\u0026 debug.error('Error ending span in reject callback:', e);\n            }\n            return Reflect.apply(rejectTarget, rejectThisArg, rejectArgs);\n          },\n        });\n\n        // Handle synchronous errors that might occur before promise is created\n        try {\n          return originalHandle.apply(this, args);\n        } catch (e) {\n          span.setStatus({\n            code: SPAN_STATUS_ERROR,\n            message: e instanceof Error ? e.message : 'unknown_error',\n          });\n          span.end();\n          throw e;\n        }\n      },\n    );\n  };\n\n  (wrappedHandle as { __sentryWrapped?: boolean }).__sentryWrapped = true;\n  query.handle = wrappedHandle;\n}\n\n/**\n * Determines whether a span should be created based on the current context.\n * If `requireParentSpan` is set to true in the options, a span will\n * only be created if there is a parent span available.\n */\nfunction _shouldCreateSpans(options: PostgresJsSqlInstrumentationOptions): boolean {\n  const hasParentSpan = getActiveSpan() !== undefined;\n  return hasParentSpan || !options.requireParentSpan;\n}\n\n/**\n * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.\n *\n * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:\n *   strings = [\"SELECT * FROM users WHERE id = \", \" AND name = \", \"\"]\n *   returns: \"SELECT * FROM users WHERE id = $1 AND name = $2\"\n *\n * @internal Exported for testing only\n */\nexport function _reconstructQuery(strings: string[] | undefined): string | undefined {\n  if (!strings?.length) {\n    return undefined;\n  }\n  if (strings.length === 1) {\n    return strings[0] || undefined;\n  }\n  // Join template parts with PostgreSQL placeholders ($1, $2, etc.)\n  return strings.reduce((acc, str, i) =\u003e (i === 0 ? str : `${acc}$${i}${str}`), '');\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * PostgreSQL $n placeholders are preserved per OTEL spec - they're parameterized queries,\n * not sensitive literals. Only actual values (strings, numbers, booleans) are sanitized.\n *\n * @internal Exported for testing only\n */\nexport function _sanitizeSqlQuery(sqlQuery: string | undefined): string {\n  if (!sqlQuery) {\n    return 'Unknown SQL Query';\n  }\n\n  return (\n    sqlQuery\n      // Remove comments first (they may contain newlines and extra spaces)\n      .replace(/--.*$/gm, '') // Single line comments (multiline mode)\n      .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '') // Multi-line comments\n      .replace(/;\\s*$/, '') // Remove trailing semicolons\n      // Collapse whitespace to a single space (after removing comments)\n      .replace(/\\s+/g, ' ')\n      .trim() // Remove extra spaces and trim\n      // Sanitize hex/binary literals before string literals\n      .replace(/\\bX'[0-9A-Fa-f]*'/gi, '?') // Hex string literals\n      .replace(/\\bB'[01]*'/gi, '?') // Binary string literals\n      // Sanitize string literals (handles escaped quotes)\n      .replace(/'(?:[^']|'')*'/g, '?')\n      // Sanitize hex numbers\n      .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n      // Sanitize boolean literals\n      .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n      // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n      .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n      .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n      .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n      .replace(/(?\u003c!\\$)-?\\b\\d+\\b/g, '?') // Integers (NOT $n placeholders)\n      // Collapse IN clauses for cardinality (both ? and $n variants)\n      .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n      .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n  );\n}\n\n/**\n * Sets connection context attributes on a span.\n */\nfunction _setConnectionAttributes(span: Span, connectionContext: PostgresConnectionContext | undefined): void {\n  if (!connectionContext) {\n    return;\n  }\n  if (connectionContext.ATTR_DB_NAMESPACE) {\n    span.setAttribute('db.namespace', connectionContext.ATTR_DB_NAMESPACE);\n  }\n  if (connectionContext.ATTR_SERVER_ADDRESS) {\n    span.setAttribute('server.address', connectionContext.ATTR_SERVER_ADDRESS);\n  }\n  if (connectionContext.ATTR_SERVER_PORT !== undefined) {\n    // Port is stored as string in PostgresConnectionContext for requestHook backwards compatibility,\n    // but semantic conventions expect port as a number for span attributes\n    const portNumber = parseInt(connectionContext.ATTR_SERVER_PORT, 10);\n    if (!isNaN(portNumber)) {\n      span.setAttribute('server.port', portNumber);\n    }\n  }\n}\n\n/**\n * Extracts DB operation name from SQL query and sets it on the span.\n */\nfunction _setOperationName(span: Span, sanitizedQuery: string | undefined, command?: string): void {\n  if (command) {\n    span.setAttribute('db.operation.name', command);\n    return;\n  }\n  // Fallback: extract operation from the SQL query\n  const operationMatch = sanitizedQuery?.match(SQL_OPERATION_REGEX);\n  if (operationMatch?.[1]) {\n    span.setAttribute('db.operation.name', operationMatch[1].toUpperCase());\n  }\n}\n\n/**\n * Extracts and stores connection context from sql.options.\n */\nfunction _attachConnectionContext(sql: unknown, proxiedSql: Record\u003csymbol, unknown\u003e): void {\n  const sqlInstance = sql as { options?: { host?: string[]; port?: number[]; database?: string } };\n  if (!sqlInstance.options || typeof sqlInstance.options !== 'object') {\n    return;\n  }\n\n  const opts = sqlInstance.options;\n  // postgres.js stores parsed options with host and port as arrays\n  // The library defaults to 'localhost' and 5432 if not specified, but we're defensive here\n  const host = opts.host?.[0] || 'localhost';\n  const port = opts.port?.[0] || 5432;\n\n  const connectionContext: PostgresConnectionContext = {\n    ATTR_DB_NAMESPACE: typeof opts.database === 'string' \u0026\u0026 opts.database !== '' ? opts.database : undefined,\n    ATTR_SERVER_ADDRESS: host,\n    ATTR_SERVER_PORT: String(port),\n  };\n\n  proxiedSql[CONNECTION_CONTEXT_SYMBOL] = connectionContext;\n}\n","import { defineIntegration } from '../integration';\nimport type { Event, EventHint } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { isError } from '../utils/is';\nimport { truncate } from '../utils/string';\n\ninterface ZodErrorsOptions {\n  key?: string;\n  /**\n   * Limits the number of Zod errors inlined in each Sentry event.\n   *\n   * @default 10\n   */\n  limit?: number;\n  /**\n   * Save full list of Zod issues as an attachment in Sentry\n   *\n   * @default false\n   */\n  saveZodIssuesAsAttachment?: boolean;\n}\n\nconst DEFAULT_LIMIT = 10;\nconst INTEGRATION_NAME = 'ZodErrors';\n\n/**\n * Simplified ZodIssue type definition\n */\ninterface ZodIssue {\n  path: (string | number)[];\n  message?: string;\n  expected?: unknown;\n  received?: unknown;\n  unionErrors?: unknown[];\n  keys?: unknown[];\n  invalid_literal?: unknown;\n}\n\ninterface ZodError extends Error {\n  issues: ZodIssue[];\n}\n\nfunction originalExceptionIsZodError(originalException: unknown): originalException is ZodError {\n  return (\n    isError(originalException) \u0026\u0026\n    originalException.name === 'ZodError' \u0026\u0026\n    Array.isArray((originalException as ZodError).issues)\n  );\n}\n\ntype SingleLevelZodIssue\u003cT extends ZodIssue\u003e = {\n  [P in keyof T]: T[P] extends string | number | undefined\n    ? T[P]\n    : T[P] extends unknown[]\n      ? string | undefined\n      : unknown;\n};\n\n/**\n * Formats child objects or arrays to a string\n * that is preserved when sent to Sentry.\n *\n * Without this, we end up with something like this in Sentry:\n *\n * [\n *  [Object],\n *  [Object],\n *  [Object],\n *  [Object]\n * ]\n */\nexport function flattenIssue(issue: ZodIssue): SingleLevelZodIssue\u003cZodIssue\u003e {\n  return {\n    ...issue,\n    path: 'path' in issue \u0026\u0026 Array.isArray(issue.path) ? issue.path.join('.') : undefined,\n    keys: 'keys' in issue ? JSON.stringify(issue.keys) : undefined,\n    unionErrors: 'unionErrors' in issue ? JSON.stringify(issue.unionErrors) : undefined,\n  };\n}\n\n/**\n * Takes ZodError issue path array and returns a flattened version as a string.\n * This makes it easier to display paths within a Sentry error message.\n *\n * Array indexes are normalized to reduce duplicate entries\n *\n * @param path ZodError issue path\n * @returns flattened path\n *\n * @example\n * flattenIssuePath([0, 'foo', 1, 'bar']) // -\u003e '\u003carray\u003e.foo.\u003carray\u003e.bar'\n */\nexport function flattenIssuePath(path: Array\u003cstring | number\u003e): string {\n  return path\n    .map(p =\u003e {\n      if (typeof p === 'number') {\n        return '\u003carray\u003e';\n      } else {\n        return p;\n      }\n    })\n    .join('.');\n}\n\n/**\n * Zod error message is a stringified version of ZodError.issues\n * This doesn't display well in the Sentry UI. Replace it with something shorter.\n */\nexport function formatIssueMessage(zodError: ZodError): string {\n  const errorKeyMap = new Set\u003cstring | number | symbol\u003e();\n  for (const iss of zodError.issues) {\n    const issuePath = flattenIssuePath(iss.path);\n    if (issuePath.length \u003e 0) {\n      errorKeyMap.add(issuePath);\n    }\n  }\n\n  const errorKeys = Array.from(errorKeyMap);\n  if (errorKeys.length === 0) {\n    // If there are no keys, then we're likely validating the root\n    // variable rather than a key within an object. This attempts\n    // to extract what type it was that failed to validate.\n    // For example, z.string().parse(123) would return \"string\" here.\n    let rootExpectedType = 'variable';\n    if (zodError.issues.length \u003e 0) {\n      const iss = zodError.issues[0];\n      if (iss !== undefined \u0026\u0026 'expected' in iss \u0026\u0026 typeof iss.expected === 'string') {\n        rootExpectedType = iss.expected;\n      }\n    }\n    return `Failed to validate ${rootExpectedType}`;\n  }\n  return `Failed to validate keys: ${truncate(errorKeys.join(', '), 100)}`;\n}\n\n/**\n * Applies ZodError issues to an event extra and replaces the error message\n */\nexport function applyZodErrorsToEvent(\n  limit: number,\n  saveZodIssuesAsAttachment: boolean = false,\n  event: Event,\n  hint: EventHint,\n): Event {\n  if (\n    !event.exception?.values ||\n    !hint.originalException ||\n    !originalExceptionIsZodError(hint.originalException) ||\n    hint.originalException.issues.length === 0\n  ) {\n    return event;\n  }\n\n  try {\n    const issuesToFlatten = saveZodIssuesAsAttachment\n      ? hint.originalException.issues\n      : hint.originalException.issues.slice(0, limit);\n    const flattenedIssues = issuesToFlatten.map(flattenIssue);\n\n    if (saveZodIssuesAsAttachment) {\n      // Sometimes having the full error details can be helpful.\n      // Attachments have much higher limits, so we can include the full list of issues.\n      if (!Array.isArray(hint.attachments)) {\n        hint.attachments = [];\n      }\n      hint.attachments.push({\n        filename: 'zod_issues.json',\n        data: JSON.stringify({\n          issues: flattenedIssues,\n        }),\n      });\n    }\n\n    return {\n      ...event,\n      exception: {\n        ...event.exception,\n        values: [\n          {\n            ...event.exception.values[0],\n            value: formatIssueMessage(hint.originalException),\n          },\n          ...event.exception.values.slice(1),\n        ],\n      },\n      extra: {\n        ...event.extra,\n        'zoderror.issues': flattenedIssues.slice(0, limit),\n      },\n    };\n  } catch (e) {\n    // Hopefully we never throw errors here, but record it\n    // with the event just in case.\n    return {\n      ...event,\n      extra: {\n        ...event.extra,\n        'zoderrors sentry integration parse error': {\n          message: 'an exception was thrown while processing ZodError within applyZodErrorsToEvent()',\n          error: e instanceof Error ? `${e.name}: ${e.message}\\n${e.stack}` : 'unknown',\n        },\n      },\n    };\n  }\n}\n\nconst _zodErrorsIntegration = ((options: ZodErrorsOptions = {}) =\u003e {\n  const limit = options.limit ?? DEFAULT_LIMIT;\n\n  return {\n    name: INTEGRATION_NAME,\n    processEvent(originalEvent, hint): Event {\n      const processedEvent = applyZodErrorsToEvent(limit, options.saveZodIssuesAsAttachment, originalEvent, hint);\n      return processedEvent;\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Sentry integration to process Zod errors, making them easier to work with in Sentry.\n */\nexport const zodErrorsIntegration = defineIntegration(_zodErrorsIntegration);\n","import { defineIntegration } from '../integration';\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata';\nimport type { EventItem } from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { forEachEnvelopeItem } from '../utils/envelope';\nimport { getFramesFromEvent } from '../utils/stacktrace';\n\ninterface Options {\n  /**\n   * Keys that have been provided in the Sentry bundler plugin via the the `applicationKey` option, identifying your bundles.\n   *\n   * - Webpack plugin: https://www.npmjs.com/package/@sentry/webpack-plugin#applicationkey\n   * - Vite plugin: https://www.npmjs.com/package/@sentry/vite-plugin#applicationkey\n   * - Esbuild plugin: https://www.npmjs.com/package/@sentry/esbuild-plugin#applicationkey\n   * - Rollup plugin: https://www.npmjs.com/package/@sentry/rollup-plugin#applicationkey\n   */\n  filterKeys: string[];\n\n  /**\n   * Defines how the integration should behave. \"Third-Party Stack Frames\" are stack frames that did not come from files marked with a matching bundle key.\n   *\n   * You can define the behaviour with one of 4 modes:\n   * - `drop-error-if-contains-third-party-frames`: Drop error events that contain at least one third-party stack frame.\n   * - `drop-error-if-exclusively-contains-third-party-frames`: Drop error events that exclusively contain third-party stack frames.\n   * - `apply-tag-if-contains-third-party-frames`: Keep all error events, but apply a `third_party_code: true` tag in case the error contains at least one third-party stack frame.\n   * - `apply-tag-if-exclusively-contains-third-party-frames`: Keep all error events, but apply a `third_party_code: true` tag in case the error contains exclusively third-party stack frames.\n   *\n   * If you chose the mode to only apply tags, the tags can then be used in Sentry to filter your issue stream by entering `!third_party_code:True` in the search bar.\n   */\n  behaviour:\n    | 'drop-error-if-contains-third-party-frames'\n    | 'drop-error-if-exclusively-contains-third-party-frames'\n    | 'apply-tag-if-contains-third-party-frames'\n    | 'apply-tag-if-exclusively-contains-third-party-frames';\n\n  /**\n   * @experimental\n   * If set to true, the integration will ignore frames that are internal to the Sentry SDK from the third-party frame detection.\n   * Note that enabling this option might lead to errors being misclassified as third-party errors.\n   */\n  ignoreSentryInternalFrames?: boolean;\n}\n\n/**\n * This integration allows you to filter out, or tag error events that do not come from user code marked with a bundle key via the Sentry bundler plugins.\n */\nexport const thirdPartyErrorFilterIntegration = defineIntegration((options: Options) =\u003e {\n  return {\n    name: 'ThirdPartyErrorsFilter',\n    setup(client) {\n      // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n      client.on('beforeEnvelope', envelope =\u003e {\n        forEachEnvelopeItem(envelope, (item, type) =\u003e {\n          if (type === 'event') {\n            const event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n\n            if (event) {\n              stripMetadataFromStackFrames(event);\n              item[1] = event;\n            }\n          }\n        });\n      });\n\n      client.on('applyFrameMetadata', event =\u003e {\n        // Only apply stack frame metadata to error events\n        if (event.type) {\n          return;\n        }\n\n        const stackParser = client.getOptions().stackParser;\n        addMetadataToStackFrames(stackParser, event);\n      });\n    },\n\n    processEvent(event) {\n      const frameKeys = getBundleKeysForAllFramesWithFilenames(event, options.ignoreSentryInternalFrames);\n\n      if (frameKeys) {\n        const arrayMethod =\n          options.behaviour === 'drop-error-if-contains-third-party-frames' ||\n          options.behaviour === 'apply-tag-if-contains-third-party-frames'\n            ? 'some'\n            : 'every';\n\n        const behaviourApplies = frameKeys[arrayMethod](keys =\u003e !keys.some(key =\u003e options.filterKeys.includes(key)));\n\n        if (behaviourApplies) {\n          const shouldDrop =\n            options.behaviour === 'drop-error-if-contains-third-party-frames' ||\n            options.behaviour === 'drop-error-if-exclusively-contains-third-party-frames';\n          if (shouldDrop) {\n            return null;\n          } else {\n            event.tags = {\n              ...event.tags,\n              third_party_code: true,\n            };\n          }\n        }\n      }\n\n      return event;\n    },\n  };\n});\n\n/**\n * Checks if a stack frame is a Sentry internal frame by strictly matching:\n * 1. The frame must be the last frame in the stack\n * 2. The filename must indicate the internal helpers file\n * 3. The context_line must contain the exact pattern \"fn.apply(this, wrappedArguments)\"\n * 4. The comment pattern \"Attempt to invoke user-land function\" must be present in pre_context\n *\n */\nfunction isSentryInternalFrame(frame: StackFrame, frameIndex: number): boolean {\n  // Only match the last frame (index 0 in reversed stack)\n  if (frameIndex !== 0 || !frame.context_line || !frame.filename) {\n    return false;\n  }\n\n  if (\n    !frame.filename.includes('sentry') ||\n    !frame.filename.includes('helpers') || // Filename would look something like this: 'node_modules/@sentry/browser/build/npm/esm/helpers.js'\n    !frame.context_line.includes(SENTRY_INTERNAL_FN_APPLY) // Must have context_line with the exact fn.apply pattern\n  ) {\n    return false;\n  }\n\n  // Check pre_context array for comment pattern\n  if (frame.pre_context) {\n    const len = frame.pre_context.length;\n    for (let i = 0; i \u003c len; i++) {\n      if (frame.pre_context[i]?.includes(SENTRY_INTERNAL_COMMENT)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n\nfunction getBundleKeysForAllFramesWithFilenames(\n  event: Event,\n  ignoreSentryInternalFrames?: boolean,\n): string[][] | undefined {\n  const frames = getFramesFromEvent(event);\n\n  if (!frames) {\n    return undefined;\n  }\n\n  return frames\n    .filter((frame, index) =\u003e {\n      // Exclude frames without a filename\n      if (!frame.filename) {\n        return false;\n      }\n      // Exclude frames without location info, since these are likely native code or built-ins.\n      // JS frames have lineno/colno, WASM frames have instruction_addr instead.\n      if (frame.lineno == null \u0026\u0026 frame.colno == null \u0026\u0026 frame.instruction_addr == null) {\n        return false;\n      }\n      // Optionally ignore Sentry internal frames\n      return !ignoreSentryInternalFrames || !isSentryInternalFrame(frame, index);\n    })\n    .map(frame =\u003e {\n      if (!frame.module_metadata) {\n        return [];\n      }\n      return Object.keys(frame.module_metadata)\n        .filter(key =\u003e key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX))\n        .map(key =\u003e key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length));\n    });\n}\n\nconst BUNDLER_PLUGIN_APP_KEY_PREFIX = '_sentryBundlerPluginAppKey:';\nconst SENTRY_INTERNAL_COMMENT = 'Attempt to invoke user-land function';\nconst SENTRY_INTERNAL_FN_APPLY = 'fn.apply(this, wrappedArguments)';\n","import { addBreadcrumb } from '../breadcrumbs';\nimport { getClient } from '../currentScopes';\nimport { addConsoleInstrumentationHandler } from '../instrument/console';\nimport { defineIntegration } from '../integration';\nimport type { ConsoleLevel } from '../types-hoist/instrument';\nimport { CONSOLE_LEVELS } from '../utils/debug-logger';\nimport { severityLevelFromString } from '../utils/severity';\nimport { safeJoin } from '../utils/string';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\ninterface ConsoleIntegrationOptions {\n  levels: ConsoleLevel[];\n}\n\ntype GlobalObjectWithUtil = typeof GLOBAL_OBJ \u0026 {\n  util: {\n    format: (...args: unknown[]) =\u003e string;\n  };\n};\n\nconst INTEGRATION_NAME = 'Console';\n\n/**\n * Captures calls to the `console` API as breadcrumbs in Sentry.\n *\n * By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,\n * `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which\n * levels are captured.\n *\n * @example\n *\n * ```js\n * Sentry.init({\n *   integrations: [Sentry.consoleIntegration({ levels: ['error', 'warn'] })],\n * });\n * ```\n */\nexport const consoleIntegration = defineIntegration((options: Partial\u003cConsoleIntegrationOptions\u003e = {}) =\u003e {\n  const levels = new Set(options.levels || CONSOLE_LEVELS);\n\n  return {\n    name: INTEGRATION_NAME,\n    setup(client) {\n      addConsoleInstrumentationHandler(({ args, level }) =\u003e {\n        if (getClient() !== client || !levels.has(level)) {\n          return;\n        }\n\n        addConsoleBreadcrumb(level, args);\n      });\n    },\n  };\n});\n\n/**\n * Capture a console breadcrumb.\n *\n * Exported just for tests.\n */\nexport function addConsoleBreadcrumb(level: ConsoleLevel, args: unknown[]): void {\n  const breadcrumb = {\n    category: 'console',\n    data: {\n      arguments: args,\n      logger: 'console',\n    },\n    level: severityLevelFromString(level),\n    message: formatConsoleArgs(args),\n  };\n\n  if (level === 'assert') {\n    if (args[0] === false) {\n      const assertionArgs = args.slice(1);\n      breadcrumb.message =\n        assertionArgs.length \u003e 0 ? `Assertion failed: ${formatConsoleArgs(assertionArgs)}` : 'Assertion failed';\n      breadcrumb.data.arguments = assertionArgs;\n    } else {\n      // Don't capture a breadcrumb for passed assertions\n      return;\n    }\n  }\n\n  addBreadcrumb(breadcrumb, {\n    input: args,\n    level,\n  });\n}\n\nfunction formatConsoleArgs(values: unknown[]): string {\n  return 'util' in GLOBAL_OBJ \u0026\u0026 typeof (GLOBAL_OBJ as GlobalObjectWithUtil).util.format === 'function'\n    ? (GLOBAL_OBJ as GlobalObjectWithUtil).util.format(...values)\n    : safeJoin(values, ' ');\n}\n","import { getCurrentScope } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { type Event } from '../types-hoist/event';\nimport { debug } from './debug-logger';\nimport { getActiveSpan, spanToJSON } from './spanUtils';\n\n/**\n * Ordered LRU cache for storing feature flags in the scope context. The name\n * of each flag in the buffer is unique, and the output of getAll() is ordered\n * from oldest to newest.\n */\n\nexport type FeatureFlag = { readonly flag: string; readonly result: boolean };\n\n/**\n * Max size of the LRU flag buffer stored in Sentry scope and event contexts.\n */\nexport const _INTERNAL_FLAG_BUFFER_SIZE = 100;\n\n/**\n * Max number of flag evaluations to record per span.\n */\nexport const _INTERNAL_MAX_FLAGS_PER_SPAN = 10;\n\nconst SPAN_FLAG_ATTRIBUTE_PREFIX = 'flag.evaluation.';\n\n/**\n * Copies feature flags that are in current scope context to the event context\n */\nexport function _INTERNAL_copyFlagsFromScopeToEvent(event: Event): Event {\n  const scope = getCurrentScope();\n  const flagContext = scope.getScopeData().contexts.flags;\n  const flagBuffer = flagContext ? flagContext.values : [];\n\n  if (!flagBuffer.length) {\n    return event;\n  }\n\n  if (event.contexts === undefined) {\n    event.contexts = {};\n  }\n  event.contexts.flags = { values: [...flagBuffer] };\n  return event;\n}\n\n/**\n * Inserts a flag into the current scope's context while maintaining ordered LRU properties.\n * Not thread-safe. After inserting:\n * - The flag buffer is sorted in order of recency, with the newest evaluation at the end.\n * - The names in the buffer are always unique.\n * - The length of the buffer never exceeds `maxSize`.\n *\n * @param name     Name of the feature flag to insert.\n * @param value    Value of the feature flag.\n * @param maxSize  Max number of flags the buffer should store. Default value should always be used in production.\n */\nexport function _INTERNAL_insertFlagToScope(\n  name: string,\n  value: unknown,\n  maxSize: number = _INTERNAL_FLAG_BUFFER_SIZE,\n): void {\n  const scopeContexts = getCurrentScope().getScopeData().contexts;\n  if (!scopeContexts.flags) {\n    scopeContexts.flags = { values: [] };\n  }\n  const flags = scopeContexts.flags.values;\n  _INTERNAL_insertToFlagBuffer(flags, name, value, maxSize);\n}\n\n/**\n * Exported for tests only. Currently only accepts boolean values (otherwise no-op).\n * Inserts a flag into a FeatureFlag array while maintaining the following properties:\n * - Flags are sorted in order of recency, with the newest evaluation at the end.\n * - The flag names are always unique.\n * - The length of the array never exceeds `maxSize`.\n *\n * @param flags      The buffer to insert the flag into.\n * @param name       Name of the feature flag to insert.\n * @param value      Value of the feature flag.\n * @param maxSize    Max number of flags the buffer should store. Default value should always be used in production.\n */\nexport function _INTERNAL_insertToFlagBuffer(\n  flags: FeatureFlag[],\n  name: string,\n  value: unknown,\n  maxSize: number,\n): void {\n  if (typeof value !== 'boolean') {\n    return;\n  }\n\n  if (flags.length \u003e maxSize) {\n    DEBUG_BUILD \u0026\u0026 debug.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`);\n    return;\n  }\n\n  // Check if the flag is already in the buffer - O(n)\n  const index = flags.findIndex(f =\u003e f.flag === name);\n\n  if (index !== -1) {\n    // The flag was found, remove it from its current position - O(n)\n    flags.splice(index, 1);\n  }\n\n  if (flags.length === maxSize) {\n    // If at capacity, pop the earliest flag - O(n)\n    flags.shift();\n  }\n\n  // Push the flag to the end - O(1)\n  flags.push({\n    flag: name,\n    result: value,\n  });\n}\n\n/**\n * Records a feature flag evaluation for the active span. This is a no-op for non-boolean values.\n * The flag and its value is stored in span attributes with the `flag.evaluation` prefix. Once the\n * unique flags for a span reaches maxFlagsPerSpan, subsequent flags are dropped.\n *\n * @param name             Name of the feature flag.\n * @param value            Value of the feature flag. Non-boolean values are ignored.\n * @param maxFlagsPerSpan  Max number of flags a buffer should store. Default value should always be used in production.\n */\nexport function _INTERNAL_addFeatureFlagToActiveSpan(\n  name: string,\n  value: unknown,\n  maxFlagsPerSpan: number = _INTERNAL_MAX_FLAGS_PER_SPAN,\n): void {\n  if (typeof value !== 'boolean') {\n    return;\n  }\n\n  const span = getActiveSpan();\n  if (!span) {\n    return;\n  }\n\n  const attributes = spanToJSON(span).data;\n\n  // If the flag already exists, always update it\n  if (`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}` in attributes) {\n    span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);\n    return;\n  }\n\n  // Else, add the flag to the span if we have not reached the max number of flags\n  const numOfAddedFlags = Object.keys(attributes).filter(key =\u003e key.startsWith(SPAN_FLAG_ATTRIBUTE_PREFIX)).length;\n  if (numOfAddedFlags \u003c maxFlagsPerSpan) {\n    span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);\n  }\n}\n","import { type Client } from '../../client';\nimport { defineIntegration } from '../../integration';\nimport { type Event, type EventHint } from '../../types-hoist/event';\nimport { type Integration, type IntegrationFn } from '../../types-hoist/integration';\nimport {\n  _INTERNAL_addFeatureFlagToActiveSpan,\n  _INTERNAL_copyFlagsFromScopeToEvent,\n  _INTERNAL_insertFlagToScope,\n} from '../../utils/featureFlags';\n\nexport interface FeatureFlagsIntegration extends Integration {\n  addFeatureFlag: (name: string, value: unknown) =\u003e void;\n}\n\n/**\n * Sentry integration for buffering feature flag evaluations manually with an API, and\n * capturing them on error events and spans.\n *\n * See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.\n *\n * @example\n * ```\n * import * as Sentry from '@sentry/browser';\n * import { type FeatureFlagsIntegration } from '@sentry/browser';\n *\n * // Setup\n * Sentry.init(..., integrations: [Sentry.featureFlagsIntegration()])\n *\n * // Verify\n * const flagsIntegration = Sentry.getClient()?.getIntegrationByName\u003cFeatureFlagsIntegration\u003e('FeatureFlags');\n * if (flagsIntegration) {\n *   flagsIntegration.addFeatureFlag('my-flag', true);\n * } else {\n *   // check your setup\n * }\n * Sentry.captureException(Exception('broke')); // 'my-flag' should be captured to this Sentry event.\n * ```\n */\nexport const featureFlagsIntegration = defineIntegration(() =\u003e {\n  return {\n    name: 'FeatureFlags',\n\n    processEvent(event: Event, _hint: EventHint, _client: Client): Event {\n      return _INTERNAL_copyFlagsFromScopeToEvent(event);\n    },\n\n    addFeatureFlag(name: string, value: unknown): void {\n      _INTERNAL_insertFlagToScope(name, value);\n      _INTERNAL_addFeatureFlagToActiveSpan(name, value);\n    },\n  };\n}) as IntegrationFn\u003cFeatureFlagsIntegration\u003e;\n","import type { Client } from '../../client';\nimport { defineIntegration } from '../../integration';\nimport type { Event, EventHint } from '../../types-hoist/event';\nimport type { IntegrationFn } from '../../types-hoist/integration';\nimport {\n  _INTERNAL_addFeatureFlagToActiveSpan,\n  _INTERNAL_copyFlagsFromScopeToEvent,\n  _INTERNAL_insertFlagToScope,\n} from '../../utils/featureFlags';\nimport { fill } from '../../utils/object';\n\ninterface GrowthBookLike {\n  isOn(this: GrowthBookLike, featureKey: string, ...rest: unknown[]): boolean;\n  getFeatureValue(this: GrowthBookLike, featureKey: string, defaultValue: unknown, ...rest: unknown[]): unknown;\n}\n\nexport type GrowthBookClassLike = new (...args: unknown[]) =\u003e GrowthBookLike;\n\n/**\n * Sentry integration for capturing feature flag evaluations from GrowthBook.\n *\n * Only boolean results are captured at this time.\n *\n * @example\n * ```typescript\n * import { GrowthBook } from '@growthbook/growthbook';\n * import * as Sentry from '@sentry/browser'; // or '@sentry/node'\n *\n * Sentry.init({\n *   dsn: 'your-dsn',\n *   integrations: [\n *     Sentry.growthbookIntegration({ growthbookClass: GrowthBook })\n *   ]\n * });\n * ```\n */\nexport const growthbookIntegration: IntegrationFn = defineIntegration(\n  ({ growthbookClass }: { growthbookClass: GrowthBookClassLike }) =\u003e {\n    return {\n      name: 'GrowthBook',\n\n      setupOnce() {\n        const proto = growthbookClass.prototype as GrowthBookLike;\n\n        // Type guard and wrap isOn\n        if (typeof proto.isOn === 'function') {\n          fill(proto, 'isOn', _wrapAndCaptureBooleanResult);\n        }\n\n        // Type guard and wrap getFeatureValue\n        if (typeof proto.getFeatureValue === 'function') {\n          fill(proto, 'getFeatureValue', _wrapAndCaptureBooleanResult);\n        }\n      },\n\n      processEvent(event: Event, _hint: EventHint, _client: Client): Event {\n        return _INTERNAL_copyFlagsFromScopeToEvent(event);\n      },\n    };\n  },\n);\n\nfunction _wrapAndCaptureBooleanResult(\n  original: (this: GrowthBookLike, ...args: unknown[]) =\u003e unknown,\n): (this: GrowthBookLike, ...args: unknown[]) =\u003e unknown {\n  return function (this: GrowthBookLike, ...args: unknown[]): unknown {\n    const flagName = args[0];\n    const result = original.apply(this, args);\n\n    if (typeof flagName === 'string' \u0026\u0026 typeof result === 'boolean') {\n      _INTERNAL_insertFlagToScope(flagName, result);\n      _INTERNAL_addFeatureFlagToActiveSpan(flagName, result);\n    }\n\n    return result;\n  };\n}\n","import type { Client } from '../client';\nimport { getCurrentScope, getIsolationScope } from '../currentScopes';\nimport { defineIntegration } from '../integration';\nimport { GEN_AI_CONVERSATION_ID_ATTRIBUTE } from '../semanticAttributes';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { Span } from '../types-hoist/span';\n\nconst INTEGRATION_NAME = 'ConversationId';\n\nconst _conversationIdIntegration = (() =\u003e {\n  return {\n    name: INTEGRATION_NAME,\n    setup(client: Client) {\n      client.on('spanStart', (span: Span) =\u003e {\n        const scopeData = getCurrentScope().getScopeData();\n        const isolationScopeData = getIsolationScope().getScopeData();\n\n        const conversationId = scopeData.conversationId || isolationScopeData.conversationId;\n\n        if (conversationId) {\n          span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, conversationId);\n        }\n      });\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Automatically applies conversation ID from scope to spans.\n *\n * This integration reads the conversation ID from the current or isolation scope\n * and applies it to spans when they start. This ensures the conversation ID is\n * available for all AI-related operations.\n */\nexport const conversationIdIntegration = defineIntegration(_conversationIdIntegration);\n","import { getClient } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Profiler, ProfilingIntegration } from './types-hoist/profiling';\nimport { debug } from './utils/debug-logger';\n\nfunction isProfilingIntegrationWithProfiler(\n  integration: ProfilingIntegration | undefined,\n): integration is ProfilingIntegration {\n  return (\n    !!integration \u0026\u0026\n    typeof integration['_profiler'] !== 'undefined' \u0026\u0026\n    typeof integration['_profiler']['start'] === 'function' \u0026\u0026\n    typeof integration['_profiler']['stop'] === 'function'\n  );\n}\n/**\n * Starts the Sentry continuous profiler.\n * This mode is exclusive with the transaction profiler and will only work if the profilesSampleRate is set to a falsy value.\n * In continuous profiling mode, the profiler will keep reporting profile chunks to Sentry until it is stopped, which allows for continuous profiling of the application.\n */\nfunction startProfiler(): void {\n  const client = getClient();\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('No Sentry client available, profiling is not started');\n    return;\n  }\n\n  const integration = client.getIntegrationByName\u003cProfilingIntegration\u003e('ProfilingIntegration');\n\n  if (!integration) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('ProfilingIntegration is not available');\n    return;\n  }\n\n  if (!isProfilingIntegrationWithProfiler(integration)) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('Profiler is not available on profiling integration.');\n    return;\n  }\n\n  integration._profiler.start();\n}\n\n/**\n * Stops the Sentry continuous profiler.\n * Calls to stop will stop the profiler and flush the currently collected profile data to Sentry.\n */\nfunction stopProfiler(): void {\n  const client = getClient();\n  if (!client) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('No Sentry client available, profiling is not started');\n    return;\n  }\n\n  const integration = client.getIntegrationByName\u003cProfilingIntegration\u003e('ProfilingIntegration');\n  if (!integration) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('ProfilingIntegration is not available');\n    return;\n  }\n\n  if (!isProfilingIntegrationWithProfiler(integration)) {\n    DEBUG_BUILD \u0026\u0026 debug.warn('Profiler is not available on profiling integration.');\n    return;\n  }\n\n  integration._profiler.stop();\n}\n\n/**\n * Profiler namespace for controlling the profiler in 'manual' mode.\n *\n * Requires the `nodeProfilingIntegration` from the `@sentry/profiling-node` package.\n */\nexport const profiler: Profiler = {\n  startProfiler,\n  stopProfiler,\n};\n","import { getClient } from './currentScopes';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from './semanticAttributes';\nimport { setHttpStatus, SPAN_STATUS_ERROR, startInactiveSpan } from './tracing';\nimport { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan';\nimport type { FetchBreadcrumbHint } from './types-hoist/breadcrumb';\nimport type { HandlerDataFetch } from './types-hoist/instrument';\nimport type { ResponseHookInfo } from './types-hoist/request';\nimport type { Span, SpanAttributes, SpanOrigin } from './types-hoist/span';\nimport { SENTRY_BAGGAGE_KEY_PREFIX } from './utils/baggage';\nimport { hasSpansEnabled } from './utils/hasSpansEnabled';\nimport { isInstanceOf, isRequest } from './utils/is';\nimport { getActiveSpan } from './utils/spanUtils';\nimport { getTraceData } from './utils/traceData';\nimport {\n  getSanitizedUrlStringFromUrlObject,\n  isURLObjectRelative,\n  parseStringToURLObject,\n  stripDataUrlContent,\n} from './utils/url';\n\ntype PolymorphicRequestHeaders =\n  | Record\u003cstring, string | undefined\u003e\n  | Array\u003c[string, string]\u003e\n  // the below is not precisely the Header type used in Request, but it'll pass duck-typing\n  | {\n      append: (key: string, value: string) =\u003e void;\n      get: (key: string) =\u003e string | null | undefined;\n    };\n\ninterface InstrumentFetchRequestOptions {\n  spanOrigin?: SpanOrigin;\n  propagateTraceparent?: boolean;\n  onRequestSpanEnd?: (span: Span, responseInformation: ResponseHookInfo) =\u003e void;\n}\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @deprecated pass an options object instead of the spanOrigin parameter\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n  handlerData: HandlerDataFetch,\n  shouldCreateSpan: (url: string) =\u003e boolean,\n  shouldAttachHeaders: (url: string) =\u003e boolean,\n  spans: Record\u003cstring, Span\u003e,\n  spanOrigin: SpanOrigin,\n): Span | undefined;\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n  handlerData: HandlerDataFetch,\n  shouldCreateSpan: (url: string) =\u003e boolean,\n  shouldAttachHeaders: (url: string) =\u003e boolean,\n  spans: Record\u003cstring, Span\u003e,\n  // eslint-disable-next-line @typescript-eslint/unified-signatures -- needed because the other overload is deprecated\n  instrumentFetchRequestOptions: InstrumentFetchRequestOptions,\n): Span | undefined;\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function instrumentFetchRequest(\n  handlerData: HandlerDataFetch,\n  shouldCreateSpan: (url: string) =\u003e boolean,\n  shouldAttachHeaders: (url: string) =\u003e boolean,\n  spans: Record\u003cstring, Span\u003e,\n  spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,\n): Span | undefined {\n  if (!handlerData.fetchData) {\n    return undefined;\n  }\n\n  const { method, url } = handlerData.fetchData;\n\n  const shouldCreateSpanResult = hasSpansEnabled() \u0026\u0026 shouldCreateSpan(url);\n\n  if (handlerData.endTimestamp) {\n    const spanId = handlerData.fetchData.__span;\n    if (!spanId) return;\n\n    const span = spans[spanId];\n\n    if (span) {\n      // Only end the span and call hooks if we're actually recording\n      if (shouldCreateSpanResult) {\n        endSpan(span, handlerData);\n        _callOnRequestSpanEnd(span, handlerData, spanOriginOrOptions);\n      }\n\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete spans[spanId];\n    }\n\n    return undefined;\n  }\n\n  // Backwards-compatible with the old signature. Needed to introduce the combined optional parameter\n  // to avoid API breakage for anyone calling this function with the optional spanOrigin parameter\n  // TODO (v11): remove this backwards-compatible code and only accept the options parameter\n  const { spanOrigin = 'auto.http.browser', propagateTraceparent = false } =\n    typeof spanOriginOrOptions === 'object' ? spanOriginOrOptions : { spanOrigin: spanOriginOrOptions };\n\n  const hasParent = !!getActiveSpan();\n\n  const span =\n    shouldCreateSpanResult \u0026\u0026 hasParent\n      ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin))\n      : new SentryNonRecordingSpan();\n\n  handlerData.fetchData.__span = span.spanContext().spanId;\n  spans[span.spanContext().spanId] = span;\n\n  if (shouldAttachHeaders(handlerData.fetchData.url)) {\n    const request: string | Request = handlerData.args[0];\n\n    // Shallow clone the options object to avoid mutating the original user-provided object\n    // Examples: users re-using same options object for multiple fetch calls, frozen objects\n    const options: { [key: string]: unknown } = { ...(handlerData.args[1] || {}) };\n\n    const headers = _addTracingHeadersToFetchRequest(\n      request,\n      options,\n      // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n      // we do not want to use the span as base for the trace headers,\n      // which means that the headers will be generated from the scope and the sampling decision is deferred\n      hasSpansEnabled() \u0026\u0026 hasParent ? span : undefined,\n      propagateTraceparent,\n    );\n    if (headers) {\n      // Ensure this is actually set, if no options have been passed previously\n      handlerData.args[1] = options;\n      options.headers = headers;\n    }\n  }\n\n  const client = getClient();\n\n  if (client) {\n    const fetchHint = {\n      input: handlerData.args,\n      response: handlerData.response,\n      startTimestamp: handlerData.startTimestamp,\n      endTimestamp: handlerData.endTimestamp,\n    } satisfies FetchBreadcrumbHint;\n\n    client.emit('beforeOutgoingRequestSpan', span, fetchHint);\n  }\n\n  return span;\n}\n\n/**\n * Calls the onRequestSpanEnd callback if it is defined.\n */\nexport function _callOnRequestSpanEnd(\n  span: Span,\n  handlerData: HandlerDataFetch,\n  spanOriginOrOptions?: SpanOrigin | InstrumentFetchRequestOptions,\n): void {\n  const onRequestSpanEnd =\n    typeof spanOriginOrOptions === 'object' \u0026\u0026 spanOriginOrOptions !== null\n      ? spanOriginOrOptions.onRequestSpanEnd\n      : undefined;\n\n  onRequestSpanEnd?.(span, {\n    headers: handlerData.response?.headers,\n    error: handlerData.error,\n  });\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n * exported only for testing purposes\n *\n * When we determine if we should add a baggage header, there are 3 cases:\n * 1. No previous baggage header -\u003e add baggage\n * 2. Previous baggage header has no sentry baggage values -\u003e add our baggage\n * 3. Previous baggage header has sentry baggage values -\u003e do nothing (might have been added manually by users)\n */\n// eslint-disable-next-line complexity -- yup it's this complicated :(\nexport function _addTracingHeadersToFetchRequest(\n  request: string | Request,\n  fetchOptionsObj: {\n    headers?:\n      | {\n          [key: string]: string[] | string | undefined;\n        }\n      | PolymorphicRequestHeaders;\n  },\n  span?: Span,\n  propagateTraceparent?: boolean,\n): PolymorphicRequestHeaders | undefined {\n  const traceHeaders = getTraceData({ span, propagateTraceparent });\n  const sentryTrace = traceHeaders['sentry-trace'];\n  const baggage = traceHeaders.baggage;\n  const traceparent = traceHeaders.traceparent;\n\n  // Nothing to do, when we return undefined here, the original headers will be used\n  if (!sentryTrace) {\n    return undefined;\n  }\n\n  const originalHeaders = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);\n\n  if (!originalHeaders) {\n    return { ...traceHeaders };\n  } else if (isHeaders(originalHeaders)) {\n    const newHeaders = new Headers(originalHeaders);\n\n    // We don't want to override manually added sentry headers\n    if (!newHeaders.get('sentry-trace')) {\n      newHeaders.set('sentry-trace', sentryTrace);\n    }\n\n    if (propagateTraceparent \u0026\u0026 traceparent \u0026\u0026 !newHeaders.get('traceparent')) {\n      newHeaders.set('traceparent', traceparent);\n    }\n\n    if (baggage) {\n      const prevBaggageHeader = newHeaders.get('baggage');\n\n      if (!prevBaggageHeader) {\n        newHeaders.set('baggage', baggage);\n      } else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) {\n        newHeaders.set('baggage', `${prevBaggageHeader},${baggage}`);\n      }\n    }\n\n    return newHeaders;\n  } else if (Array.isArray(originalHeaders)) {\n    const newHeaders = [...originalHeaders];\n\n    if (!originalHeaders.find(header =\u003e header[0] === 'sentry-trace')) {\n      newHeaders.push(['sentry-trace', sentryTrace]);\n    }\n\n    if (propagateTraceparent \u0026\u0026 traceparent \u0026\u0026 !originalHeaders.find(header =\u003e header[0] === 'traceparent')) {\n      newHeaders.push(['traceparent', traceparent]);\n    }\n\n    const prevBaggageHeaderWithSentryValues = originalHeaders.find(\n      header =\u003e header[0] === 'baggage' \u0026\u0026 baggageHeaderHasSentryBaggageValues(header[1]),\n    );\n\n    if (baggage \u0026\u0026 !prevBaggageHeaderWithSentryValues) {\n      // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n      // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n      newHeaders.push(['baggage', baggage]);\n    }\n\n    return newHeaders as PolymorphicRequestHeaders;\n  } else {\n    const existingSentryTraceHeader = 'sentry-trace' in originalHeaders ? originalHeaders['sentry-trace'] : undefined;\n    const existingTraceparentHeader = 'traceparent' in originalHeaders ? originalHeaders.traceparent : undefined;\n    const existingBaggageHeader = 'baggage' in originalHeaders ? originalHeaders.baggage : undefined;\n\n    const newBaggageHeaders: string[] = existingBaggageHeader\n      ? Array.isArray(existingBaggageHeader)\n        ? [...existingBaggageHeader]\n        : [existingBaggageHeader]\n      : [];\n\n    const prevBaggageHeaderWithSentryValues =\n      existingBaggageHeader \u0026\u0026\n      (Array.isArray(existingBaggageHeader)\n        ? existingBaggageHeader.find(headerItem =\u003e baggageHeaderHasSentryBaggageValues(headerItem))\n        : baggageHeaderHasSentryBaggageValues(existingBaggageHeader));\n\n    if (baggage \u0026\u0026 !prevBaggageHeaderWithSentryValues) {\n      newBaggageHeaders.push(baggage);\n    }\n\n    const newHeaders: {\n      'sentry-trace': string;\n      baggage: string | undefined;\n      traceparent?: string;\n    } = {\n      ...originalHeaders,\n      'sentry-trace': (existingSentryTraceHeader as string | undefined) ?? sentryTrace,\n      baggage: newBaggageHeaders.length \u003e 0 ? newBaggageHeaders.join(',') : undefined,\n    };\n\n    if (propagateTraceparent \u0026\u0026 traceparent \u0026\u0026 !existingTraceparentHeader) {\n      newHeaders.traceparent = traceparent;\n    }\n\n    return newHeaders;\n  }\n}\n\nfunction endSpan(span: Span, handlerData: HandlerDataFetch): void {\n  if (handlerData.response) {\n    setHttpStatus(span, handlerData.response.status);\n\n    const contentLength = handlerData.response?.headers?.get('content-length');\n\n    if (contentLength) {\n      const contentLengthNum = parseInt(contentLength);\n      if (contentLengthNum \u003e 0) {\n        span.setAttribute('http.response_content_length', contentLengthNum);\n      }\n    }\n  } else if (handlerData.error) {\n    span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n  }\n  span.end();\n}\n\nfunction baggageHeaderHasSentryBaggageValues(baggageHeader: string): boolean {\n  return baggageHeader.split(',').some(baggageEntry =\u003e baggageEntry.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX));\n}\n\nfunction isHeaders(headers: unknown): headers is Headers {\n  return typeof Headers !== 'undefined' \u0026\u0026 isInstanceOf(headers, Headers);\n}\n\nfunction getSpanStartOptions(\n  url: string,\n  method: string,\n  spanOrigin: SpanOrigin,\n): Parameters\u003ctypeof startInactiveSpan\u003e[0] {\n  // Data URLs need special handling because parseStringToURLObject treats them as \"relative\"\n  // (no \"://\"), causing getSanitizedUrlStringFromUrlObject to return just the pathname\n  // without the \"data:\" prefix, making later stripDataUrlContent calls ineffective.\n  // So for data URLs, we strip the content first and use that directly.\n  if (url.startsWith('data:')) {\n    const sanitizedUrl = stripDataUrlContent(url);\n    return {\n      name: `${method} ${sanitizedUrl}`,\n      attributes: getFetchSpanAttributes(url, undefined, method, spanOrigin),\n    };\n  }\n\n  const parsedUrl = parseStringToURLObject(url);\n  const sanitizedUrl = parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url;\n  return {\n    name: `${method} ${sanitizedUrl}`,\n    attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin),\n  };\n}\n\nfunction getFetchSpanAttributes(\n  url: string,\n  parsedUrl: ReturnType\u003ctypeof parseStringToURLObject\u003e,\n  method: string,\n  spanOrigin: SpanOrigin,\n): SpanAttributes {\n  const attributes: SpanAttributes = {\n    url: stripDataUrlContent(url),\n    type: 'fetch',\n    'http.method': method,\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n  };\n  if (parsedUrl) {\n    if (!isURLObjectRelative(parsedUrl)) {\n      attributes['http.url'] = stripDataUrlContent(parsedUrl.href);\n      attributes['server.address'] = parsedUrl.host;\n    }\n    if (parsedUrl.search) {\n      attributes['http.query'] = parsedUrl.search;\n    }\n    if (parsedUrl.hash) {\n      attributes['http.fragment'] = parsedUrl.hash;\n    }\n  }\n  return attributes;\n}\n","import { getClient, withIsolationScope } from './currentScopes';\nimport { captureException } from './exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from './semanticAttributes';\nimport { startSpanManual } from './tracing';\nimport { normalize } from './utils/normalize';\nimport { addNonEnumerableProperty } from './utils/object';\n\ninterface SentryTrpcMiddlewareOptions {\n  /** Whether to include procedure inputs in reported events. Defaults to `false`. */\n  attachRpcInput?: boolean;\n  forceTransaction?: boolean;\n}\n\nexport interface SentryTrpcMiddlewareArguments\u003cT\u003e {\n  path?: unknown;\n  type?: unknown;\n  next: () =\u003e T;\n  rawInput?: unknown;\n  getRawInput?: () =\u003e Promise\u003cunknown\u003e;\n}\n\nconst trpcCaptureContext = { mechanism: { handled: false, type: 'auto.rpc.trpc.middleware' } };\n\nfunction captureIfError(nextResult: unknown): void {\n  // TODO: Set span status based on what TRPCError was encountered\n  if (\n    typeof nextResult === 'object' \u0026\u0026\n    nextResult !== null \u0026\u0026\n    'ok' in nextResult \u0026\u0026\n    !nextResult.ok \u0026\u0026\n    'error' in nextResult\n  ) {\n    captureException(nextResult.error, trpcCaptureContext);\n  }\n}\n\ntype SentryTrpcMiddleware\u003cT\u003e = T extends Promise\u003cunknown\u003e ? T : Promise\u003cT\u003e;\n\n/**\n * Sentry tRPC middleware that captures errors and creates spans for tRPC procedures.\n */\nexport function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {\n  // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n  // @ts-ignore\n  return async function \u003cT\u003e(opts: SentryTrpcMiddlewareArguments\u003cT\u003e): SentryTrpcMiddleware\u003cT\u003e {\n    const { path, type, next, rawInput, getRawInput } = opts;\n\n    const client = getClient();\n    const clientOptions = client?.getOptions();\n\n    const trpcContext: Record\u003cstring, unknown\u003e = {\n      procedure_path: path,\n      procedure_type: type,\n    };\n\n    addNonEnumerableProperty(\n      trpcContext,\n      '__sentry_override_normalization_depth__',\n      1 + // 1 for context.input + the normal normalization depth\n        (clientOptions?.normalizeDepth ?? 5), // 5 is a sane depth\n    );\n\n    if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions?.sendDefaultPii) {\n      if (rawInput !== undefined) {\n        trpcContext.input = normalize(rawInput);\n      }\n\n      if (getRawInput !== undefined \u0026\u0026 typeof getRawInput === 'function') {\n        try {\n          const rawRes = await getRawInput();\n\n          trpcContext.input = normalize(rawRes);\n        } catch {\n          // noop\n        }\n      }\n    }\n\n    return withIsolationScope(scope =\u003e {\n      scope.setContext('trpc', trpcContext);\n      return startSpanManual(\n        {\n          name: `trpc/${path}`,\n          op: 'rpc.server',\n          attributes: {\n            [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',\n            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.rpc.trpc',\n          },\n          forceTransaction: !!options.forceTransaction,\n        },\n        async span =\u003e {\n          try {\n            const nextResult = await next();\n            captureIfError(nextResult);\n            span.end();\n            return nextResult;\n          } catch (e) {\n            captureException(e, trpcCaptureContext);\n            span.end();\n            throw e;\n          }\n        },\n      ) as SentryTrpcMiddleware\u003cT\u003e;\n    });\n  };\n}\n","/**\n * Safe error capture utilities for MCP server instrumentation\n *\n * Ensures error reporting never interferes with MCP server operation.\n * All capture operations are wrapped in try-catch to prevent side effects.\n */\n\nimport { getClient } from '../../currentScopes';\nimport { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { getActiveSpan } from '../../utils/spanUtils';\nimport type { McpErrorType } from './types';\n\n/**\n * Captures an error without affecting MCP server operation.\n *\n * The active span already contains all MCP context (method, tool, arguments, etc.)\n * @param error - Error to capture\n * @param errorType - Classification of error type for filtering\n * @param extraData - Additional context data to include\n */\nexport function captureError(error: Error, errorType?: McpErrorType, extraData?: Record\u003cstring, unknown\u003e): void {\n  try {\n    const client = getClient();\n    if (!client) {\n      return;\n    }\n\n    const activeSpan = getActiveSpan();\n    if (activeSpan?.isRecording()) {\n      activeSpan.setStatus({\n        code: SPAN_STATUS_ERROR,\n        message: 'internal_error',\n      });\n    }\n\n    captureException(error, {\n      mechanism: {\n        type: 'auto.ai.mcp_server',\n        handled: false,\n        data: {\n          error_type: errorType || 'handler_execution',\n          ...extraData,\n        },\n      },\n    });\n  } catch {\n    // noop\n  }\n}\n","/**\n * Handler method wrapping for MCP server instrumentation\n *\n * Provides automatic error capture and span correlation for tool, resource,\n * and prompt handlers.\n */\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { debug } from '../../utils/debug-logger';\nimport { fill } from '../../utils/object';\nimport { captureError } from './errorCapture';\nimport type { MCPHandler, MCPServerInstance } from './types';\n\n/**\n * Generic function to wrap MCP server method handlers\n * @internal\n * @param serverInstance - MCP server instance\n * @param methodName - Method name to wrap (tool, resource, prompt)\n */\nfunction wrapMethodHandler(serverInstance: MCPServerInstance, methodName: keyof MCPServerInstance): void {\n  fill(serverInstance, methodName, originalMethod =\u003e {\n    return function (this: MCPServerInstance, name: string, ...args: unknown[]) {\n      const handler = args[args.length - 1];\n\n      if (typeof handler !== 'function') {\n        return (originalMethod as (...args: unknown[]) =\u003e unknown).call(this, name, ...args);\n      }\n\n      const wrappedHandler = createWrappedHandler(handler as MCPHandler, methodName, name);\n      return (originalMethod as (...args: unknown[]) =\u003e unknown).call(this, name, ...args.slice(0, -1), wrappedHandler);\n    };\n  });\n}\n\n/**\n * Creates a wrapped handler with span correlation and error capture\n * @internal\n * @param originalHandler - Original handler function\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n * @returns Wrapped handler function\n */\nfunction createWrappedHandler(originalHandler: MCPHandler, methodName: keyof MCPServerInstance, handlerName: string) {\n  return function (this: unknown, ...handlerArgs: unknown[]): unknown {\n    try {\n      return createErrorCapturingHandler.call(this, originalHandler, methodName, handlerName, handlerArgs);\n    } catch (error) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('MCP handler wrapping failed:', error);\n      return originalHandler.apply(this, handlerArgs);\n    }\n  };\n}\n\n/**\n * Creates an error-capturing wrapper for handler execution\n * @internal\n * @param originalHandler - Original handler function\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n * @param handlerArgs - Handler arguments\n * @param extraHandlerData - Additional handler context\n * @returns Handler execution result\n */\nfunction createErrorCapturingHandler(\n  this: MCPServerInstance,\n  originalHandler: MCPHandler,\n  methodName: keyof MCPServerInstance,\n  handlerName: string,\n  handlerArgs: unknown[],\n): unknown {\n  try {\n    const result = originalHandler.apply(this, handlerArgs);\n\n    if (result \u0026\u0026 typeof result === 'object' \u0026\u0026 typeof (result as { then?: unknown }).then === 'function') {\n      return Promise.resolve(result).catch(error =\u003e {\n        captureHandlerError(error, methodName, handlerName);\n        throw error;\n      });\n    }\n\n    return result;\n  } catch (error) {\n    captureHandlerError(error as Error, methodName, handlerName);\n    throw error;\n  }\n}\n\n/**\n * Captures handler execution errors based on handler type\n * @internal\n * @param error - Error to capture\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n */\nfunction captureHandlerError(error: Error, methodName: keyof MCPServerInstance, handlerName: string): void {\n  try {\n    const extraData: Record\u003cstring, unknown\u003e = {};\n\n    if (methodName === 'tool') {\n      extraData.tool_name = handlerName;\n\n      if (\n        error.name === 'ProtocolValidationError' ||\n        error.message.includes('validation') ||\n        error.message.includes('protocol')\n      ) {\n        captureError(error, 'validation', extraData);\n      } else if (\n        error.name === 'ServerTimeoutError' ||\n        error.message.includes('timed out') ||\n        error.message.includes('timeout')\n      ) {\n        captureError(error, 'timeout', extraData);\n      } else {\n        captureError(error, 'tool_execution', extraData);\n      }\n    } else if (methodName === 'resource') {\n      extraData.resource_uri = handlerName;\n      captureError(error, 'resource_execution', extraData);\n    } else if (methodName === 'prompt') {\n      extraData.prompt_name = handlerName;\n      captureError(error, 'prompt_execution', extraData);\n    }\n  } catch (_captureErr) {\n    // noop\n  }\n}\n\n/**\n * Wraps tool handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nexport function wrapToolHandlers(serverInstance: MCPServerInstance): void {\n  wrapMethodHandler(serverInstance, 'tool');\n}\n\n/**\n * Wraps resource handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nexport function wrapResourceHandlers(serverInstance: MCPServerInstance): void {\n  wrapMethodHandler(serverInstance, 'resource');\n}\n\n/**\n * Wraps prompt handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nexport function wrapPromptHandlers(serverInstance: MCPServerInstance): void {\n  wrapMethodHandler(serverInstance, 'prompt');\n}\n\n/**\n * Wraps all MCP handler types (tool, resource, prompt) for span correlation\n * @param serverInstance - MCP server instance\n */\nexport function wrapAllMCPHandlers(serverInstance: MCPServerInstance): void {\n  wrapToolHandlers(serverInstance);\n  wrapResourceHandlers(serverInstance);\n  wrapPromptHandlers(serverInstance);\n}\n","/**\n * Essential MCP attribute constants for Sentry instrumentation\n *\n * Based on OpenTelemetry MCP semantic conventions\n * @see https://github.com/open-telemetry/semantic-conventions/blob/3097fb0af5b9492b0e3f55dc5f6c21a3dc2be8df/docs/gen-ai/mcp.md\n */\n\n// =============================================================================\n// CORE MCP ATTRIBUTES\n// =============================================================================\n\n/** The name of the request or notification method */\nexport const MCP_METHOD_NAME_ATTRIBUTE = 'mcp.method.name';\n\n/** JSON-RPC request identifier for the request. Unique within the MCP session. */\nexport const MCP_REQUEST_ID_ATTRIBUTE = 'mcp.request.id';\n\n/** Identifies the MCP session */\nexport const MCP_SESSION_ID_ATTRIBUTE = 'mcp.session.id';\n\n/** Transport method used for MCP communication */\nexport const MCP_TRANSPORT_ATTRIBUTE = 'mcp.transport';\n\n// =============================================================================\n// CLIENT ATTRIBUTES\n// =============================================================================\n\n/** Name of the MCP client application */\nexport const MCP_CLIENT_NAME_ATTRIBUTE = 'mcp.client.name';\n\n/** Display title of the MCP client application */\nexport const MCP_CLIENT_TITLE_ATTRIBUTE = 'mcp.client.title';\n\n/** Version of the MCP client application */\nexport const MCP_CLIENT_VERSION_ATTRIBUTE = 'mcp.client.version';\n\n// =============================================================================\n// SERVER ATTRIBUTES\n// =============================================================================\n\n/** Name of the MCP server application */\nexport const MCP_SERVER_NAME_ATTRIBUTE = 'mcp.server.name';\n\n/** Display title of the MCP server application */\nexport const MCP_SERVER_TITLE_ATTRIBUTE = 'mcp.server.title';\n\n/** Version of the MCP server application */\nexport const MCP_SERVER_VERSION_ATTRIBUTE = 'mcp.server.version';\n\n/** MCP protocol version used in the session */\nexport const MCP_PROTOCOL_VERSION_ATTRIBUTE = 'mcp.protocol.version';\n\n// =============================================================================\n// METHOD-SPECIFIC ATTRIBUTES\n// =============================================================================\n\n/** Name of the tool being called */\nexport const MCP_TOOL_NAME_ATTRIBUTE = 'mcp.tool.name';\n\n/** The resource URI being accessed */\nexport const MCP_RESOURCE_URI_ATTRIBUTE = 'mcp.resource.uri';\n\n/** Name of the prompt template */\nexport const MCP_PROMPT_NAME_ATTRIBUTE = 'mcp.prompt.name';\n\n// =============================================================================\n// TOOL RESULT ATTRIBUTES\n// =============================================================================\n\n/** Whether a tool execution resulted in an error */\nexport const MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE = 'mcp.tool.result.is_error';\n\n/** Number of content items in the tool result */\nexport const MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE = 'mcp.tool.result.content_count';\n\n/** Serialized content of the tool result */\nexport const MCP_TOOL_RESULT_CONTENT_ATTRIBUTE = 'mcp.tool.result.content';\n\n/** Prefix for tool result attributes that contain sensitive content */\nexport const MCP_TOOL_RESULT_PREFIX = 'mcp.tool.result';\n\n// =============================================================================\n// PROMPT RESULT ATTRIBUTES\n// =============================================================================\n\n/** Description of the prompt result */\nexport const MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE = 'mcp.prompt.result.description';\n\n/** Number of messages in the prompt result */\nexport const MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE = 'mcp.prompt.result.message_count';\n\n/** Role of the message in the prompt result (for single message results) */\nexport const MCP_PROMPT_RESULT_MESSAGE_ROLE_ATTRIBUTE = 'mcp.prompt.result.message_role';\n\n/** Content of the message in the prompt result (for single message results) */\nexport const MCP_PROMPT_RESULT_MESSAGE_CONTENT_ATTRIBUTE = 'mcp.prompt.result.message_content';\n\n/** Prefix for prompt result attributes that contain sensitive content */\nexport const MCP_PROMPT_RESULT_PREFIX = 'mcp.prompt.result';\n\n// =============================================================================\n// REQUEST ARGUMENT ATTRIBUTES\n// =============================================================================\n\n/** Prefix for MCP request argument prefix for each argument */\nexport const MCP_REQUEST_ARGUMENT = 'mcp.request.argument';\n\n// =============================================================================\n// LOGGING ATTRIBUTES\n// =============================================================================\n\n/** Log level for MCP logging operations */\nexport const MCP_LOGGING_LEVEL_ATTRIBUTE = 'mcp.logging.level';\n\n/** Logger name for MCP logging operations */\nexport const MCP_LOGGING_LOGGER_ATTRIBUTE = 'mcp.logging.logger';\n\n/** Data type of the logged message */\nexport const MCP_LOGGING_DATA_TYPE_ATTRIBUTE = 'mcp.logging.data_type';\n\n/** Log message content */\nexport const MCP_LOGGING_MESSAGE_ATTRIBUTE = 'mcp.logging.message';\n\n// =============================================================================\n// NETWORK ATTRIBUTES (OpenTelemetry Standard)\n// =============================================================================\n\n/** OSI transport layer protocol */\nexport const NETWORK_TRANSPORT_ATTRIBUTE = 'network.transport';\n\n/** The version of JSON RPC protocol used */\nexport const NETWORK_PROTOCOL_VERSION_ATTRIBUTE = 'network.protocol.version';\n\n/** Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name */\nexport const CLIENT_ADDRESS_ATTRIBUTE = 'client.address';\n\n/** Client port number */\nexport const CLIENT_PORT_ATTRIBUTE = 'client.port';\n\n// =============================================================================\n// SENTRY-SPECIFIC MCP ATTRIBUTE VALUES\n// =============================================================================\n\n/** Sentry operation value for MCP server spans */\nexport const MCP_SERVER_OP_VALUE = 'mcp.server';\n\n/**\n * Sentry operation value for client-to-server notifications\n * Following OpenTelemetry MCP semantic conventions\n */\nexport const MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE = 'mcp.notification.client_to_server';\n\n/**\n * Sentry operation value for server-to-client notifications\n * Following OpenTelemetry MCP semantic conventions\n */\nexport const MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE = 'mcp.notification.server_to_client';\n\n/** Sentry origin value for MCP function spans */\nexport const MCP_FUNCTION_ORIGIN_VALUE = 'auto.function.mcp_server';\n\n/** Sentry origin value for MCP notification spans */\nexport const MCP_NOTIFICATION_ORIGIN_VALUE = 'auto.mcp.notification';\n\n/** Sentry source value for MCP route spans */\nexport const MCP_ROUTE_SOURCE_VALUE = 'route';\n","/**\n * Message validation functions for MCP server instrumentation\n *\n * Provides JSON-RPC 2.0 message type validation and MCP server instance validation.\n */\n\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { debug } from '../../utils/debug-logger';\nimport type { JsonRpcNotification, JsonRpcRequest, JsonRpcResponse } from './types';\n\n/**\n * Validates if a message is a JSON-RPC request\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC request\n */\nexport function isJsonRpcRequest(message: unknown): message is JsonRpcRequest {\n  return (\n    typeof message === 'object' \u0026\u0026\n    message !== null \u0026\u0026\n    'jsonrpc' in message \u0026\u0026\n    (message as JsonRpcRequest).jsonrpc === '2.0' \u0026\u0026\n    'method' in message \u0026\u0026\n    'id' in message\n  );\n}\n\n/**\n * Validates if a message is a JSON-RPC notification\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC notification\n */\nexport function isJsonRpcNotification(message: unknown): message is JsonRpcNotification {\n  return (\n    typeof message === 'object' \u0026\u0026\n    message !== null \u0026\u0026\n    'jsonrpc' in message \u0026\u0026\n    (message as JsonRpcNotification).jsonrpc === '2.0' \u0026\u0026\n    'method' in message \u0026\u0026\n    !('id' in message)\n  );\n}\n\n/**\n * Validates if a message is a JSON-RPC response\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC response\n */\nexport function isJsonRpcResponse(message: unknown): message is JsonRpcResponse {\n  return (\n    typeof message === 'object' \u0026\u0026\n    message !== null \u0026\u0026\n    'jsonrpc' in message \u0026\u0026\n    (message as { jsonrpc: string }).jsonrpc === '2.0' \u0026\u0026\n    'id' in message \u0026\u0026\n    ('result' in message || 'error' in message)\n  );\n}\n\n/**\n * Validates MCP server instance with type checking\n * @param instance - Object to validate as MCP server instance\n * @returns True if instance has required MCP server methods\n */\nexport function validateMcpServerInstance(instance: unknown): boolean {\n  if (\n    typeof instance === 'object' \u0026\u0026\n    instance !== null \u0026\u0026\n    'resource' in instance \u0026\u0026\n    'tool' in instance \u0026\u0026\n    'prompt' in instance \u0026\u0026\n    'connect' in instance\n  ) {\n    return true;\n  }\n  DEBUG_BUILD \u0026\u0026 debug.warn('Did not patch MCP server. Interface is incompatible.');\n  return false;\n}\n\n/**\n * Check if the item is a valid content item\n * @param item - The item to check\n * @returns True if the item is a valid content item, false otherwise\n */\nexport function isValidContentItem(item: unknown): item is Record\u003cstring, unknown\u003e {\n  return item != null \u0026\u0026 typeof item === 'object';\n}\n","/**\n * Result extraction functions for MCP server instrumentation\n *\n * Handles extraction of attributes from tool and prompt execution results.\n */\n\nimport {\n  MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE,\n  MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE,\n  MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE,\n  MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE,\n} from './attributes';\nimport { isValidContentItem } from './validation';\n\n/**\n * Build attributes for tool result content items\n * @param content - Array of content items from tool result\n * @param includeContent - Whether to include actual content (text, URIs) or just metadata\n * @returns Attributes extracted from each content item\n */\nfunction buildAllContentItemAttributes(\n  content: unknown[],\n  includeContent: boolean,\n): Record\u003cstring, string | number | boolean\u003e {\n  const attributes: Record\u003cstring, string | number\u003e = {\n    [MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE]: content.length,\n  };\n\n  for (const [i, item] of content.entries()) {\n    if (!isValidContentItem(item)) {\n      continue;\n    }\n\n    const prefix = content.length === 1 ? 'mcp.tool.result' : `mcp.tool.result.${i}`;\n\n    if (typeof item.type === 'string') {\n      attributes[`${prefix}.content_type`] = item.type;\n    }\n\n    if (includeContent) {\n      const safeSet = (key: string, value: unknown): void =\u003e {\n        if (typeof value === 'string') {\n          attributes[`${prefix}.${key}`] = value;\n        }\n      };\n\n      safeSet('mime_type', item.mimeType);\n      safeSet('uri', item.uri);\n      safeSet('name', item.name);\n\n      if (typeof item.text === 'string') {\n        attributes[`${prefix}.content`] = item.text;\n      }\n\n      if (typeof item.data === 'string') {\n        attributes[`${prefix}.data_size`] = item.data.length;\n      }\n\n      const resource = item.resource;\n      if (isValidContentItem(resource)) {\n        safeSet('resource_uri', resource.uri);\n        safeSet('resource_mime_type', resource.mimeType);\n      }\n    }\n  }\n\n  return attributes;\n}\n\n/**\n * Extract tool result attributes for span instrumentation\n * @param result - Tool execution result\n * @param recordOutputs - Whether to include actual content or just metadata (counts, error status)\n * @returns Attributes extracted from tool result content\n */\nexport function extractToolResultAttributes(\n  result: unknown,\n  recordOutputs: boolean,\n): Record\u003cstring, string | number | boolean\u003e {\n  if (!isValidContentItem(result)) {\n    return {};\n  }\n\n  const attributes = Array.isArray(result.content) ? buildAllContentItemAttributes(result.content, recordOutputs) : {};\n\n  if (typeof result.isError === 'boolean') {\n    attributes[MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE] = result.isError;\n  }\n\n  return attributes;\n}\n\n/**\n * Extract prompt result attributes for span instrumentation\n * @param result - Prompt execution result\n * @param recordOutputs - Whether to include actual content or just metadata (counts)\n * @returns Attributes extracted from prompt result\n */\nexport function extractPromptResultAttributes(\n  result: unknown,\n  recordOutputs: boolean,\n): Record\u003cstring, string | number | boolean\u003e {\n  const attributes: Record\u003cstring, string | number | boolean\u003e = {};\n  if (!isValidContentItem(result)) {\n    return attributes;\n  }\n\n  if (recordOutputs \u0026\u0026 typeof result.description === 'string') {\n    attributes[MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE] = result.description;\n  }\n\n  if (Array.isArray(result.messages)) {\n    attributes[MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE] = result.messages.length;\n\n    if (recordOutputs) {\n      const messages = result.messages;\n      for (const [i, message] of messages.entries()) {\n        if (!isValidContentItem(message)) {\n          continue;\n        }\n\n        const prefix = messages.length === 1 ? 'mcp.prompt.result' : `mcp.prompt.result.${i}`;\n\n        const safeSet = (key: string, value: unknown): void =\u003e {\n          if (typeof value === 'string') {\n            const attrName = messages.length === 1 ? `${prefix}.message_${key}` : `${prefix}.${key}`;\n            attributes[attrName] = value;\n          }\n        };\n\n        safeSet('role', message.role);\n\n        if (isValidContentItem(message.content)) {\n          const content = message.content;\n          if (typeof content.text === 'string') {\n            const attrName = messages.length === 1 ? `${prefix}.message_content` : `${prefix}.content`;\n            attributes[attrName] = content.text;\n          }\n        }\n      }\n    }\n  }\n\n  return attributes;\n}\n","/**\n * Session data management for MCP server instrumentation\n *\n * Uses sessionId as the primary key for stateful transports. This handles the wrapper\n * transport pattern (e.g., NodeStreamableHTTPServerTransport wrapping WebStandardStreamableHTTPServerTransport)\n * where different methods may receive different `this` values but share the same sessionId.\n *\n * Falls back to WeakMap by transport instance for stateless transports (no sessionId).\n */\n\nimport type { MCPTransport, PartyInfo, SessionData } from './types';\n\n/**\n * Session-scoped data storage for stateful transports (with sessionId)\n * @internal Using sessionId as key handles wrapper transport patterns\n */\nconst sessionToSessionData = new Map\u003cstring, SessionData\u003e();\n\n/**\n * Transport-scoped data storage fallback for stateless transports (no sessionId)\n * @internal WeakMap allows automatic cleanup when transport is garbage collected\n */\nconst statelessSessionData = new WeakMap\u003cMCPTransport, SessionData\u003e();\n\n/**\n * Gets session data for a transport, checking sessionId first then fallback\n * @internal\n */\nfunction getSessionData(transport: MCPTransport): SessionData | undefined {\n  const sessionId = transport.sessionId;\n  if (sessionId) {\n    return sessionToSessionData.get(sessionId);\n  }\n  return statelessSessionData.get(transport);\n}\n\n/**\n * Sets session data for a transport, using sessionId when available\n * @internal\n */\nfunction setSessionData(transport: MCPTransport, data: SessionData): void {\n  const sessionId = transport.sessionId;\n  if (sessionId) {\n    sessionToSessionData.set(sessionId, data);\n  } else {\n    statelessSessionData.set(transport, data);\n  }\n}\n\n/**\n * Stores session data for a transport\n * @param transport - MCP transport instance\n * @param sessionData - Session data to store\n */\nexport function storeSessionDataForTransport(transport: MCPTransport, sessionData: SessionData): void {\n  // For stateful transports, always store (sessionId is the key)\n  // For stateless transports, also store (transport instance is the key)\n  setSessionData(transport, sessionData);\n}\n\n/**\n * Updates session data for a transport (merges with existing data)\n * @param transport - MCP transport instance\n * @param partialSessionData - Partial session data to merge with existing data\n */\nexport function updateSessionDataForTransport(transport: MCPTransport, partialSessionData: Partial\u003cSessionData\u003e): void {\n  const existingData = getSessionData(transport) || {};\n  setSessionData(transport, { ...existingData, ...partialSessionData });\n}\n\n/**\n * Retrieves client information for a transport\n * @param transport - MCP transport instance\n * @returns Client information if available\n */\nexport function getClientInfoForTransport(transport: MCPTransport): PartyInfo | undefined {\n  return getSessionData(transport)?.clientInfo;\n}\n\n/**\n * Retrieves protocol version for a transport\n * @param transport - MCP transport instance\n * @returns Protocol version if available\n */\nexport function getProtocolVersionForTransport(transport: MCPTransport): string | undefined {\n  return getSessionData(transport)?.protocolVersion;\n}\n\n/**\n * Retrieves full session data for a transport\n * @param transport - MCP transport instance\n * @returns Complete session data if available\n */\nexport function getSessionDataForTransport(transport: MCPTransport): SessionData | undefined {\n  return getSessionData(transport);\n}\n\n/**\n * Cleans up session data for a specific transport (when that transport closes)\n * @param transport - MCP transport instance\n */\nexport function cleanupSessionDataForTransport(transport: MCPTransport): void {\n  const sessionId = transport.sessionId;\n  if (sessionId) {\n    sessionToSessionData.delete(sessionId);\n  }\n  // Note: WeakMap entries are automatically cleaned up when transport is GC'd\n  // No explicit delete needed for statelessSessionData\n}\n","/**\n * Session and party info extraction functions for MCP server instrumentation\n *\n * Handles extraction of client/server info and session data from MCP messages.\n */\n\nimport {\n  CLIENT_ADDRESS_ATTRIBUTE,\n  CLIENT_PORT_ATTRIBUTE,\n  MCP_PROTOCOL_VERSION_ATTRIBUTE,\n  MCP_SERVER_NAME_ATTRIBUTE,\n  MCP_SERVER_TITLE_ATTRIBUTE,\n  MCP_SERVER_VERSION_ATTRIBUTE,\n  MCP_SESSION_ID_ATTRIBUTE,\n  MCP_TRANSPORT_ATTRIBUTE,\n  NETWORK_PROTOCOL_VERSION_ATTRIBUTE,\n  NETWORK_TRANSPORT_ATTRIBUTE,\n} from './attributes';\nimport {\n  getClientInfoForTransport,\n  getProtocolVersionForTransport,\n  getSessionDataForTransport,\n} from './sessionManagement';\nimport type { ExtraHandlerData, JsonRpcRequest, MCPTransport, PartyInfo, SessionData } from './types';\nimport { isValidContentItem } from './validation';\n\n/**\n * Extracts and validates PartyInfo from an unknown object\n * @param obj - Unknown object that might contain party info\n * @returns Validated PartyInfo object with only string properties\n */\nfunction extractPartyInfo(obj: unknown): PartyInfo {\n  const partyInfo: PartyInfo = {};\n\n  if (isValidContentItem(obj)) {\n    if (typeof obj.name === 'string') {\n      partyInfo.name = obj.name;\n    }\n    if (typeof obj.title === 'string') {\n      partyInfo.title = obj.title;\n    }\n    if (typeof obj.version === 'string') {\n      partyInfo.version = obj.version;\n    }\n  }\n\n  return partyInfo;\n}\n\n/**\n * Extracts session data from \"initialize\" requests\n * @param request - JSON-RPC \"initialize\" request containing client info and protocol version\n * @returns Session data extracted from request parameters including protocol version and client info\n */\nexport function extractSessionDataFromInitializeRequest(request: JsonRpcRequest): SessionData {\n  const sessionData: SessionData = {};\n  if (isValidContentItem(request.params)) {\n    if (typeof request.params.protocolVersion === 'string') {\n      sessionData.protocolVersion = request.params.protocolVersion;\n    }\n    if (request.params.clientInfo) {\n      sessionData.clientInfo = extractPartyInfo(request.params.clientInfo);\n    }\n  }\n  return sessionData;\n}\n\n/**\n * Extracts session data from \"initialize\" response\n * @param result - \"initialize\" response result containing server info and protocol version\n * @returns Partial session data extracted from response including protocol version and server info\n */\nexport function extractSessionDataFromInitializeResponse(result: unknown): Partial\u003cSessionData\u003e {\n  const sessionData: Partial\u003cSessionData\u003e = {};\n  if (isValidContentItem(result)) {\n    if (typeof result.protocolVersion === 'string') {\n      sessionData.protocolVersion = result.protocolVersion;\n    }\n    if (result.serverInfo) {\n      sessionData.serverInfo = extractPartyInfo(result.serverInfo);\n    }\n  }\n  return sessionData;\n}\n\n/**\n * Build client attributes from stored client info\n * @param transport - MCP transport instance\n * @returns Client attributes for span instrumentation\n */\nexport function getClientAttributes(transport: MCPTransport): Record\u003cstring, string\u003e {\n  const clientInfo = getClientInfoForTransport(transport);\n  const attributes: Record\u003cstring, string\u003e = {};\n\n  if (clientInfo?.name) {\n    attributes['mcp.client.name'] = clientInfo.name;\n  }\n  if (clientInfo?.title) {\n    attributes['mcp.client.title'] = clientInfo.title;\n  }\n  if (clientInfo?.version) {\n    attributes['mcp.client.version'] = clientInfo.version;\n  }\n\n  return attributes;\n}\n\n/**\n * Build client attributes from PartyInfo directly\n * @param clientInfo - Client party info\n * @returns Client attributes for span instrumentation\n */\nexport function buildClientAttributesFromInfo(clientInfo?: PartyInfo): Record\u003cstring, string\u003e {\n  const attributes: Record\u003cstring, string\u003e = {};\n\n  if (clientInfo?.name) {\n    attributes['mcp.client.name'] = clientInfo.name;\n  }\n  if (clientInfo?.title) {\n    attributes['mcp.client.title'] = clientInfo.title;\n  }\n  if (clientInfo?.version) {\n    attributes['mcp.client.version'] = clientInfo.version;\n  }\n\n  return attributes;\n}\n\n/**\n * Build server attributes from stored server info\n * @param transport - MCP transport instance\n * @returns Server attributes for span instrumentation\n */\nexport function getServerAttributes(transport: MCPTransport): Record\u003cstring, string\u003e {\n  const serverInfo = getSessionDataForTransport(transport)?.serverInfo;\n  const attributes: Record\u003cstring, string\u003e = {};\n\n  if (serverInfo?.name) {\n    attributes[MCP_SERVER_NAME_ATTRIBUTE] = serverInfo.name;\n  }\n  if (serverInfo?.title) {\n    attributes[MCP_SERVER_TITLE_ATTRIBUTE] = serverInfo.title;\n  }\n  if (serverInfo?.version) {\n    attributes[MCP_SERVER_VERSION_ATTRIBUTE] = serverInfo.version;\n  }\n\n  return attributes;\n}\n\n/**\n * Build server attributes from PartyInfo directly\n * @param serverInfo - Server party info\n * @returns Server attributes for span instrumentation\n */\nexport function buildServerAttributesFromInfo(serverInfo?: PartyInfo): Record\u003cstring, string\u003e {\n  const attributes: Record\u003cstring, string\u003e = {};\n\n  if (serverInfo?.name) {\n    attributes[MCP_SERVER_NAME_ATTRIBUTE] = serverInfo.name;\n  }\n  if (serverInfo?.title) {\n    attributes[MCP_SERVER_TITLE_ATTRIBUTE] = serverInfo.title;\n  }\n  if (serverInfo?.version) {\n    attributes[MCP_SERVER_VERSION_ATTRIBUTE] = serverInfo.version;\n  }\n\n  return attributes;\n}\n\n/**\n * Extracts client connection info from extra handler data\n * @param extra - Extra handler data containing connection info\n * @returns Client address and port information\n */\nexport function extractClientInfo(extra: ExtraHandlerData): {\n  address?: string;\n  port?: number;\n} {\n  return {\n    address:\n      extra?.requestInfo?.remoteAddress ||\n      extra?.clientAddress ||\n      extra?.request?.ip ||\n      extra?.request?.connection?.remoteAddress,\n    port: extra?.requestInfo?.remotePort || extra?.clientPort || extra?.request?.connection?.remotePort,\n  };\n}\n\n/**\n * Extracts transport types based on transport constructor name\n * @param transport - MCP transport instance\n * @returns Transport type mapping for span attributes\n */\nexport function getTransportTypes(transport: MCPTransport): { mcpTransport: string; networkTransport: string } {\n  if (!transport?.constructor) {\n    return { mcpTransport: 'unknown', networkTransport: 'unknown' };\n  }\n  const transportName = typeof transport.constructor?.name === 'string' ? transport.constructor.name : 'unknown';\n  let networkTransport = 'unknown';\n\n  const lowerTransportName = transportName.toLowerCase();\n  if (lowerTransportName.includes('stdio')) {\n    networkTransport = 'pipe';\n  } else if (lowerTransportName.includes('http') || lowerTransportName.includes('sse')) {\n    networkTransport = 'tcp';\n  }\n\n  return {\n    mcpTransport: transportName,\n    networkTransport,\n  };\n}\n\n/**\n * Build transport and network attributes\n * @param transport - MCP transport instance\n * @param extra - Optional extra handler data\n * @returns Transport attributes for span instrumentation\n * @note sessionId may be undefined during initial setup - session should be established by client during initialize flow\n */\nexport function buildTransportAttributes(\n  transport: MCPTransport,\n  extra?: ExtraHandlerData,\n): Record\u003cstring, string | number\u003e {\n  const sessionId = transport \u0026\u0026 'sessionId' in transport ? transport.sessionId : undefined;\n  const clientInfo = extra ? extractClientInfo(extra) : {};\n  const { mcpTransport, networkTransport } = getTransportTypes(transport);\n  const clientAttributes = getClientAttributes(transport);\n  const serverAttributes = getServerAttributes(transport);\n  const protocolVersion = getProtocolVersionForTransport(transport);\n\n  const attributes = {\n    ...(sessionId \u0026\u0026 { [MCP_SESSION_ID_ATTRIBUTE]: sessionId }),\n    ...(clientInfo.address \u0026\u0026 { [CLIENT_ADDRESS_ATTRIBUTE]: clientInfo.address }),\n    ...(clientInfo.port \u0026\u0026 { [CLIENT_PORT_ATTRIBUTE]: clientInfo.port }),\n    [MCP_TRANSPORT_ATTRIBUTE]: mcpTransport,\n    [NETWORK_TRANSPORT_ATTRIBUTE]: networkTransport,\n    [NETWORK_PROTOCOL_VERSION_ATTRIBUTE]: '2.0',\n    ...(protocolVersion \u0026\u0026 { [MCP_PROTOCOL_VERSION_ATTRIBUTE]: protocolVersion }),\n    ...clientAttributes,\n    ...serverAttributes,\n  };\n\n  return attributes;\n}\n","/**\n * Request-span correlation system for MCP server instrumentation\n *\n * Handles mapping requestId to span data for correlation with handler execution.\n *\n * Uses sessionId as the primary key for stateful transports. This handles the wrapper\n * transport pattern (e.g., NodeStreamableHTTPServerTransport wrapping WebStandardStreamableHTTPServerTransport)\n * where onmessage and send may receive different `this` values but share the same sessionId.\n *\n * Falls back to WeakMap by transport instance for stateless transports (no sessionId).\n */\n\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes';\nimport { extractPromptResultAttributes, extractToolResultAttributes } from './resultExtraction';\nimport { buildServerAttributesFromInfo, extractSessionDataFromInitializeResponse } from './sessionExtraction';\nimport type { MCPTransport, RequestId, RequestSpanMapValue, ResolvedMcpOptions } from './types';\n\n/**\n * Session-scoped correlation for stateful transports (with sessionId)\n * @internal Using sessionId as key handles wrapper transport patterns where\n * different transport objects share the same logical session\n */\nconst sessionToSpanMap = new Map\u003cstring, Map\u003cRequestId, RequestSpanMapValue\u003e\u003e();\n\n/**\n * Transport-scoped correlation fallback for stateless transports (no sessionId)\n * @internal WeakMap allows automatic cleanup when transport is garbage collected\n */\nconst statelessSpanMap = new WeakMap\u003cMCPTransport, Map\u003cRequestId, RequestSpanMapValue\u003e\u003e();\n\n/**\n * Gets or creates the span map for a transport, using sessionId when available\n * @internal\n * @param transport - MCP transport instance\n * @returns Span map for the transport/session\n */\nfunction getOrCreateSpanMap(transport: MCPTransport): Map\u003cRequestId, RequestSpanMapValue\u003e {\n  const sessionId = transport.sessionId;\n\n  if (sessionId) {\n    // Stateful transport - use sessionId as key (handles wrapper pattern)\n    let spanMap = sessionToSpanMap.get(sessionId);\n    if (!spanMap) {\n      spanMap = new Map();\n      sessionToSpanMap.set(sessionId, spanMap);\n    }\n    return spanMap;\n  }\n\n  // Stateless fallback - use transport instance as key\n  let spanMap = statelessSpanMap.get(transport);\n  if (!spanMap) {\n    spanMap = new Map();\n    statelessSpanMap.set(transport, spanMap);\n  }\n  return spanMap;\n}\n\n/**\n * Stores span context for later correlation with handler execution\n * @param transport - MCP transport instance\n * @param requestId - Request identifier\n * @param span - Active span to correlate\n * @param method - MCP method name\n */\nexport function storeSpanForRequest(transport: MCPTransport, requestId: RequestId, span: Span, method: string): void {\n  const spanMap = getOrCreateSpanMap(transport);\n  spanMap.set(requestId, {\n    span,\n    method,\n    // oxlint-disable-next-line sdk/no-unsafe-random-apis\n    startTime: Date.now(),\n  });\n}\n\n/**\n * Completes span with results and cleans up correlation\n * @param transport - MCP transport instance\n * @param requestId - Request identifier\n * @param result - Execution result for attribute extraction\n * @param options - Resolved MCP options\n */\nexport function completeSpanWithResults(\n  transport: MCPTransport,\n  requestId: RequestId,\n  result: unknown,\n  options: ResolvedMcpOptions,\n): void {\n  const spanMap = getOrCreateSpanMap(transport);\n  const spanData = spanMap.get(requestId);\n  if (spanData) {\n    const { span, method } = spanData;\n\n    if (method === 'initialize') {\n      const sessionData = extractSessionDataFromInitializeResponse(result);\n      const serverAttributes = buildServerAttributesFromInfo(sessionData.serverInfo);\n\n      const initAttributes: Record\u003cstring, string | number\u003e = {\n        ...serverAttributes,\n      };\n      if (sessionData.protocolVersion) {\n        initAttributes[MCP_PROTOCOL_VERSION_ATTRIBUTE] = sessionData.protocolVersion;\n      }\n\n      span.setAttributes(initAttributes);\n    } else if (method === 'tools/call') {\n      const toolAttributes = extractToolResultAttributes(result, options.recordOutputs);\n      span.setAttributes(toolAttributes);\n    } else if (method === 'prompts/get') {\n      const promptAttributes = extractPromptResultAttributes(result, options.recordOutputs);\n      span.setAttributes(promptAttributes);\n    }\n\n    span.end();\n    spanMap.delete(requestId);\n  }\n}\n\n/**\n * Cleans up pending spans for a specific transport (when that transport closes)\n * @param transport - MCP transport instance\n */\nexport function cleanupPendingSpansForTransport(transport: MCPTransport): void {\n  const sessionId = transport.sessionId;\n\n  // Try sessionId-based cleanup first (for stateful transports)\n  if (sessionId) {\n    const spanMap = sessionToSpanMap.get(sessionId);\n    if (spanMap) {\n      for (const [, spanData] of spanMap) {\n        spanData.span.setStatus({\n          code: SPAN_STATUS_ERROR,\n          message: 'cancelled',\n        });\n        spanData.span.end();\n      }\n      sessionToSpanMap.delete(sessionId);\n    }\n    return;\n  }\n\n  // Fallback to transport-based cleanup (for stateless transports)\n  const spanMap = statelessSpanMap.get(transport);\n  if (spanMap) {\n    for (const [, spanData] of spanMap) {\n      spanData.span.setStatus({\n        code: SPAN_STATUS_ERROR,\n        message: 'cancelled',\n      });\n      spanData.span.end();\n    }\n    spanMap.clear();\n    // Note: WeakMap entries are automatically cleaned up when transport is GC'd\n  }\n}\n","/**\n * Method configuration and request processing for MCP server instrumentation\n */\n\nimport {\n  MCP_PROMPT_NAME_ATTRIBUTE,\n  MCP_REQUEST_ARGUMENT,\n  MCP_RESOURCE_URI_ATTRIBUTE,\n  MCP_TOOL_NAME_ATTRIBUTE,\n} from './attributes';\nimport type { MethodConfig } from './types';\n\n/**\n * Configuration for MCP methods to extract targets and arguments\n * @internal Maps method names to their extraction configuration\n */\nconst METHOD_CONFIGS: Record\u003cstring, MethodConfig\u003e = {\n  'tools/call': {\n    targetField: 'name',\n    targetAttribute: MCP_TOOL_NAME_ATTRIBUTE,\n    captureArguments: true,\n    argumentsField: 'arguments',\n  },\n  'resources/read': {\n    targetField: 'uri',\n    targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n    captureUri: true,\n  },\n  'resources/subscribe': {\n    targetField: 'uri',\n    targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n  },\n  'resources/unsubscribe': {\n    targetField: 'uri',\n    targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n  },\n  'prompts/get': {\n    targetField: 'name',\n    targetAttribute: MCP_PROMPT_NAME_ATTRIBUTE,\n    captureName: true,\n    captureArguments: true,\n    argumentsField: 'arguments',\n  },\n};\n\n/**\n * Extracts target info from method and params based on method type\n * @param method - MCP method name\n * @param params - Method parameters\n * @returns Target name and attributes for span instrumentation\n */\nexport function extractTargetInfo(\n  method: string,\n  params: Record\u003cstring, unknown\u003e,\n): {\n  target?: string;\n  attributes: Record\u003cstring, string\u003e;\n} {\n  const config = METHOD_CONFIGS[method];\n  if (!config) {\n    return { attributes: {} };\n  }\n\n  const target =\n    config.targetField \u0026\u0026 typeof params?.[config.targetField] === 'string'\n      ? (params[config.targetField] as string)\n      : undefined;\n\n  return {\n    target,\n    attributes: target \u0026\u0026 config.targetAttribute ? { [config.targetAttribute]: target } : {},\n  };\n}\n\n/**\n * Extracts request arguments based on method type\n * @param method - MCP method name\n * @param params - Method parameters\n * @returns Arguments as span attributes with mcp.request.argument prefix\n */\nexport function getRequestArguments(method: string, params: Record\u003cstring, unknown\u003e): Record\u003cstring, string\u003e {\n  const args: Record\u003cstring, string\u003e = {};\n  const config = METHOD_CONFIGS[method];\n\n  if (!config) {\n    return args;\n  }\n\n  if (config.captureArguments \u0026\u0026 config.argumentsField \u0026\u0026 params?.[config.argumentsField]) {\n    const argumentsObj = params[config.argumentsField];\n    if (typeof argumentsObj === 'object' \u0026\u0026 argumentsObj !== null) {\n      for (const [key, value] of Object.entries(argumentsObj as Record\u003cstring, unknown\u003e)) {\n        args[`${MCP_REQUEST_ARGUMENT}.${key.toLowerCase()}`] = JSON.stringify(value);\n      }\n    }\n  }\n\n  if (config.captureUri \u0026\u0026 params?.uri) {\n    args[`${MCP_REQUEST_ARGUMENT}.uri`] = JSON.stringify(params.uri);\n  }\n\n  if (config.captureName \u0026\u0026 params?.name) {\n    args[`${MCP_REQUEST_ARGUMENT}.name`] = JSON.stringify(params.name);\n  }\n\n  return args;\n}\n","/**\n * Core attribute extraction and building functions for MCP server instrumentation\n */\n\nimport { isURLObjectRelative, parseStringToURLObject } from '../../utils/url';\nimport {\n  MCP_LOGGING_DATA_TYPE_ATTRIBUTE,\n  MCP_LOGGING_LEVEL_ATTRIBUTE,\n  MCP_LOGGING_LOGGER_ATTRIBUTE,\n  MCP_LOGGING_MESSAGE_ATTRIBUTE,\n  MCP_REQUEST_ID_ATTRIBUTE,\n  MCP_RESOURCE_URI_ATTRIBUTE,\n} from './attributes';\nimport { extractTargetInfo, getRequestArguments } from './methodConfig';\nimport type { JsonRpcNotification, JsonRpcRequest, McpSpanType } from './types';\n\n/**\n * Formats logging data for span attributes\n * @internal\n */\nfunction formatLoggingData(data: unknown): string {\n  return typeof data === 'string' ? data : JSON.stringify(data);\n}\n\n/**\n * Extracts additional attributes for specific notification types\n * @param method - Notification method name\n * @param params - Notification parameters\n * @param recordInputs - Whether to include actual content or just metadata\n * @returns Method-specific attributes for span instrumentation\n */\nexport function getNotificationAttributes(\n  method: string,\n  params: Record\u003cstring, unknown\u003e,\n  recordInputs?: boolean,\n): Record\u003cstring, string | number\u003e {\n  const attributes: Record\u003cstring, string | number\u003e = {};\n\n  switch (method) {\n    case 'notifications/cancelled':\n      if (params?.requestId) {\n        attributes['mcp.cancelled.request_id'] = String(params.requestId);\n      }\n      if (params?.reason) {\n        attributes['mcp.cancelled.reason'] = String(params.reason);\n      }\n      break;\n\n    case 'notifications/message':\n      if (params?.level) {\n        attributes[MCP_LOGGING_LEVEL_ATTRIBUTE] = String(params.level);\n      }\n      if (params?.logger) {\n        attributes[MCP_LOGGING_LOGGER_ATTRIBUTE] = String(params.logger);\n      }\n      if (params?.data !== undefined) {\n        attributes[MCP_LOGGING_DATA_TYPE_ATTRIBUTE] = typeof params.data;\n        if (recordInputs) {\n          attributes[MCP_LOGGING_MESSAGE_ATTRIBUTE] = formatLoggingData(params.data);\n        }\n      }\n      break;\n\n    case 'notifications/progress':\n      if (params?.progressToken) {\n        attributes['mcp.progress.token'] = String(params.progressToken);\n      }\n      if (typeof params?.progress === 'number') {\n        attributes['mcp.progress.current'] = params.progress;\n      }\n      if (typeof params?.total === 'number') {\n        attributes['mcp.progress.total'] = params.total;\n        if (typeof params?.progress === 'number') {\n          attributes['mcp.progress.percentage'] = (params.progress / params.total) * 100;\n        }\n      }\n      if (params?.message) {\n        attributes['mcp.progress.message'] = String(params.message);\n      }\n      break;\n\n    case 'notifications/resources/updated':\n      if (params?.uri) {\n        attributes[MCP_RESOURCE_URI_ATTRIBUTE] = String(params.uri);\n        const urlObject = parseStringToURLObject(String(params.uri));\n        if (urlObject \u0026\u0026 !isURLObjectRelative(urlObject)) {\n          attributes['mcp.resource.protocol'] = urlObject.protocol.replace(':', '');\n        }\n      }\n      break;\n\n    case 'notifications/initialized':\n      attributes['mcp.lifecycle.phase'] = 'initialization_complete';\n      attributes['mcp.protocol.ready'] = 1;\n      break;\n  }\n\n  return attributes;\n}\n\n/**\n * Build type-specific attributes based on message type\n * @param type - Span type (request or notification)\n * @param message - JSON-RPC message\n * @param params - Optional parameters for attribute extraction\n * @param recordInputs - Whether to capture input arguments in spans\n * @returns Type-specific attributes for span instrumentation\n */\nexport function buildTypeSpecificAttributes(\n  type: McpSpanType,\n  message: JsonRpcRequest | JsonRpcNotification,\n  params?: Record\u003cstring, unknown\u003e,\n  recordInputs?: boolean,\n): Record\u003cstring, string | number\u003e {\n  if (type === 'request') {\n    const request = message as JsonRpcRequest;\n    const targetInfo = extractTargetInfo(request.method, params || {});\n\n    return {\n      ...(request.id !== undefined \u0026\u0026 { [MCP_REQUEST_ID_ATTRIBUTE]: String(request.id) }),\n      ...targetInfo.attributes,\n      ...(recordInputs ? getRequestArguments(request.method, params || {}) : {}),\n    };\n  }\n\n  return getNotificationAttributes(message.method, params || {}, recordInputs);\n}\n\n// Re-export buildTransportAttributes for spans.ts\nexport { buildTransportAttributes } from './sessionExtraction';\n","/**\n * PII filtering for MCP server spans\n *\n * Removes network-level sensitive data when sendDefaultPii is false.\n * Input/output data (request arguments, tool/prompt results) is controlled\n * separately via recordInputs/recordOutputs options.\n */\nimport type { SpanAttributeValue } from '../../types-hoist/span';\nimport { CLIENT_ADDRESS_ATTRIBUTE, CLIENT_PORT_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE } from './attributes';\n\n/**\n * Network PII attributes that should be removed when sendDefaultPii is false\n * @internal\n */\nconst NETWORK_PII_ATTRIBUTES = new Set([CLIENT_ADDRESS_ATTRIBUTE, CLIENT_PORT_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE]);\n\n/**\n * Checks if an attribute key should be considered network PII.\n *\n * Returns true for:\n * - client.address (IP address)\n * - client.port (port number)\n * - mcp.resource.uri (potentially sensitive URIs)\n *\n * @param key - Attribute key to evaluate\n * @returns true if the attribute should be filtered out (is network PII), false if it should be preserved\n * @internal\n */\nfunction isNetworkPiiAttribute(key: string): boolean {\n  return NETWORK_PII_ATTRIBUTES.has(key);\n}\n\n/**\n * Removes network PII attributes from span data when sendDefaultPii is false\n * @param spanData - Raw span attributes\n * @param sendDefaultPii - Whether to include PII data\n * @returns Filtered span attributes\n */\nexport function filterMcpPiiFromSpanData(\n  spanData: Record\u003cstring, unknown\u003e,\n  sendDefaultPii: boolean,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  if (sendDefaultPii) {\n    return spanData as Record\u003cstring, SpanAttributeValue\u003e;\n  }\n\n  return Object.entries(spanData).reduce(\n    (acc, [key, value]) =\u003e {\n      if (!isNetworkPiiAttribute(key)) {\n        acc[key] = value as SpanAttributeValue;\n      }\n      return acc;\n    },\n    {} as Record\u003cstring, SpanAttributeValue\u003e,\n  );\n}\n","/**\n * Span creation and management functions for MCP server instrumentation\n *\n * Provides unified span creation following OpenTelemetry MCP semantic conventions and our opinitionated take on MCP.\n * Handles both request and notification spans with attribute extraction.\n */\n\nimport { getClient } from '../../currentScopes';\nimport {\n  SEMANTIC_ATTRIBUTE_SENTRY_OP,\n  SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n  SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n} from '../../semanticAttributes';\nimport { startSpan } from '../../tracing';\nimport { buildTransportAttributes, buildTypeSpecificAttributes } from './attributeExtraction';\nimport {\n  MCP_FUNCTION_ORIGIN_VALUE,\n  MCP_METHOD_NAME_ATTRIBUTE,\n  MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE,\n  MCP_NOTIFICATION_ORIGIN_VALUE,\n  MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE,\n  MCP_ROUTE_SOURCE_VALUE,\n  MCP_SERVER_OP_VALUE,\n} from './attributes';\nimport { extractTargetInfo } from './methodConfig';\nimport { filterMcpPiiFromSpanData } from './piiFiltering';\nimport type {\n  ExtraHandlerData,\n  JsonRpcNotification,\n  JsonRpcRequest,\n  McpSpanConfig,\n  MCPTransport,\n  ResolvedMcpOptions,\n} from './types';\n\n/**\n * Creates a span name based on the method and target\n * @internal\n * @param method - MCP method name\n * @param target - Optional target identifier\n * @returns Formatted span name\n */\nfunction createSpanName(method: string, target?: string): string {\n  return target ? `${method} ${target}` : method;\n}\n\n/**\n * Build Sentry-specific attributes based on span type\n * @internal\n * @param type - Span type configuration\n * @returns Sentry-specific attributes\n */\nfunction buildSentryAttributes(type: McpSpanConfig['type']): Record\u003cstring, string\u003e {\n  let op: string;\n  let origin: string;\n\n  switch (type) {\n    case 'request':\n      op = MCP_SERVER_OP_VALUE;\n      origin = MCP_FUNCTION_ORIGIN_VALUE;\n      break;\n    case 'notification-incoming':\n      op = MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE;\n      origin = MCP_NOTIFICATION_ORIGIN_VALUE;\n      break;\n    case 'notification-outgoing':\n      op = MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE;\n      origin = MCP_NOTIFICATION_ORIGIN_VALUE;\n      break;\n  }\n\n  return {\n    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n    [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: MCP_ROUTE_SOURCE_VALUE,\n  };\n}\n\n/**\n * Unified builder for creating MCP spans\n * @internal\n * @param config - Span configuration\n * @returns Created span\n */\nfunction createMcpSpan(config: McpSpanConfig): unknown {\n  const { type, message, transport, extra, callback, options } = config;\n  const { method } = message;\n  const params = message.params;\n\n  // Determine span name based on type and OTEL conventions\n  let spanName: string;\n  if (type === 'request') {\n    const targetInfo = extractTargetInfo(method, params || {});\n    spanName = createSpanName(method, targetInfo.target);\n  } else {\n    // For notifications, use method name directly per OpenTelemetry conventions\n    spanName = method;\n  }\n\n  const rawAttributes: Record\u003cstring, string | number\u003e = {\n    ...buildTransportAttributes(transport, extra),\n    [MCP_METHOD_NAME_ATTRIBUTE]: method,\n    ...buildTypeSpecificAttributes(type, message, params, options?.recordInputs),\n    ...buildSentryAttributes(type),\n  };\n\n  const client = getClient();\n  const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n  const attributes = filterMcpPiiFromSpanData(rawAttributes, sendDefaultPii) as Record\u003cstring, string | number\u003e;\n\n  return startSpan(\n    {\n      name: spanName,\n      forceTransaction: true,\n      attributes,\n    },\n    callback,\n  );\n}\n\n/**\n * Creates a span for incoming MCP notifications\n * @param jsonRpcMessage - Notification message\n * @param transport - MCP transport instance\n * @param extra - Extra handler data\n * @param options - Resolved MCP options\n * @param callback - Span execution callback\n * @returns Span execution result\n */\nexport function createMcpNotificationSpan(\n  jsonRpcMessage: JsonRpcNotification,\n  transport: MCPTransport,\n  extra: ExtraHandlerData,\n  options: ResolvedMcpOptions,\n  callback: () =\u003e unknown,\n): unknown {\n  return createMcpSpan({\n    type: 'notification-incoming',\n    message: jsonRpcMessage,\n    transport,\n    extra,\n    callback,\n    options,\n  });\n}\n\n/**\n * Creates a span for outgoing MCP notifications\n * @param jsonRpcMessage - Notification message\n * @param transport - MCP transport instance\n * @param options - Resolved MCP options\n * @param callback - Span execution callback\n * @returns Span execution result\n */\nexport function createMcpOutgoingNotificationSpan(\n  jsonRpcMessage: JsonRpcNotification,\n  transport: MCPTransport,\n  options: ResolvedMcpOptions,\n  callback: () =\u003e unknown,\n): unknown {\n  return createMcpSpan({\n    type: 'notification-outgoing',\n    message: jsonRpcMessage,\n    transport,\n    options,\n    callback,\n  });\n}\n\n/**\n * Builds span configuration for MCP server requests\n * @param jsonRpcMessage - Request message\n * @param transport - MCP transport instance\n * @param extra - Optional extra handler data\n * @param options - Resolved MCP options\n * @returns Span configuration object\n */\nexport function buildMcpServerSpanConfig(\n  jsonRpcMessage: JsonRpcRequest,\n  transport: MCPTransport,\n  extra?: ExtraHandlerData,\n  options?: ResolvedMcpOptions,\n): {\n  name: string;\n  op: string;\n  forceTransaction: boolean;\n  attributes: Record\u003cstring, string | number\u003e;\n} {\n  const { method } = jsonRpcMessage;\n  const params = jsonRpcMessage.params;\n\n  const targetInfo = extractTargetInfo(method, params || {});\n  const spanName = createSpanName(method, targetInfo.target);\n\n  const rawAttributes: Record\u003cstring, string | number\u003e = {\n    ...buildTransportAttributes(transport, extra),\n    [MCP_METHOD_NAME_ATTRIBUTE]: method,\n    ...buildTypeSpecificAttributes('request', jsonRpcMessage, params, options?.recordInputs),\n    ...buildSentryAttributes('request'),\n  };\n\n  const client = getClient();\n  const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n  const attributes = filterMcpPiiFromSpanData(rawAttributes, sendDefaultPii) as Record\u003cstring, string | number\u003e;\n\n  return {\n    name: spanName,\n    op: MCP_SERVER_OP_VALUE,\n    forceTransaction: true,\n    attributes,\n  };\n}\n","/**\n * Transport layer instrumentation for MCP server\n *\n * Handles message interception and response correlation.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports\n */\n\nimport { getIsolationScope, withIsolationScope } from '../../currentScopes';\nimport { startInactiveSpan, withActiveSpan } from '../../tracing';\nimport { fill } from '../../utils/object';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes';\nimport { cleanupPendingSpansForTransport, completeSpanWithResults, storeSpanForRequest } from './correlation';\nimport { captureError } from './errorCapture';\nimport {\n  buildClientAttributesFromInfo,\n  extractSessionDataFromInitializeRequest,\n  extractSessionDataFromInitializeResponse,\n} from './sessionExtraction';\nimport {\n  cleanupSessionDataForTransport,\n  storeSessionDataForTransport,\n  updateSessionDataForTransport,\n} from './sessionManagement';\nimport { buildMcpServerSpanConfig, createMcpNotificationSpan, createMcpOutgoingNotificationSpan } from './spans';\nimport type { ExtraHandlerData, MCPTransport, ResolvedMcpOptions, SessionData } from './types';\nimport { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isValidContentItem } from './validation';\n\n/**\n * Wraps transport.onmessage to create spans for incoming messages.\n * For \"initialize\" requests, extracts and stores client info and protocol version\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportOnMessage(transport: MCPTransport, options: ResolvedMcpOptions): void {\n  if (transport.onmessage) {\n    fill(transport, 'onmessage', originalOnMessage =\u003e {\n      return function (this: MCPTransport, message: unknown, extra?: unknown) {\n        if (isJsonRpcRequest(message)) {\n          const isInitialize = message.method === 'initialize';\n          let initSessionData: SessionData | undefined;\n\n          if (isInitialize) {\n            try {\n              initSessionData = extractSessionDataFromInitializeRequest(message);\n              storeSessionDataForTransport(this, initSessionData);\n            } catch {\n              // noop\n            }\n          }\n\n          const isolationScope = getIsolationScope().clone();\n\n          return withIsolationScope(isolationScope, () =\u003e {\n            const spanConfig = buildMcpServerSpanConfig(message, this, extra as ExtraHandlerData, options);\n            const span = startInactiveSpan(spanConfig);\n\n            // For initialize requests, add client info directly to span (works even for stateless transports)\n            if (isInitialize \u0026\u0026 initSessionData) {\n              span.setAttributes({\n                ...buildClientAttributesFromInfo(initSessionData.clientInfo),\n                ...(initSessionData.protocolVersion \u0026\u0026 {\n                  [MCP_PROTOCOL_VERSION_ATTRIBUTE]: initSessionData.protocolVersion,\n                }),\n              });\n            }\n\n            storeSpanForRequest(this, message.id, span, message.method);\n\n            return withActiveSpan(span, () =\u003e {\n              return (originalOnMessage as (...args: unknown[]) =\u003e unknown).call(this, message, extra);\n            });\n          });\n        }\n\n        if (isJsonRpcNotification(message)) {\n          return createMcpNotificationSpan(message, this, extra as ExtraHandlerData, options, () =\u003e {\n            return (originalOnMessage as (...args: unknown[]) =\u003e unknown).call(this, message, extra);\n          });\n        }\n\n        return (originalOnMessage as (...args: unknown[]) =\u003e unknown).call(this, message, extra);\n      };\n    });\n  }\n}\n\n/**\n * Wraps transport.send to handle outgoing messages and response correlation.\n * For \"initialize\" responses, extracts and stores protocol version and server info\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n * @param options - Resolved MCP options\n */\nexport function wrapTransportSend(transport: MCPTransport, options: ResolvedMcpOptions): void {\n  if (transport.send) {\n    fill(transport, 'send', originalSend =\u003e {\n      return async function (this: MCPTransport, ...args: unknown[]) {\n        const [message] = args;\n\n        if (isJsonRpcNotification(message)) {\n          return createMcpOutgoingNotificationSpan(message, this, options, () =\u003e {\n            return (originalSend as (...args: unknown[]) =\u003e unknown).call(this, ...args);\n          });\n        }\n\n        if (isJsonRpcResponse(message)) {\n          if (message.id !== null \u0026\u0026 message.id !== undefined) {\n            if (message.error) {\n              captureJsonRpcErrorResponse(message.error);\n            }\n\n            if (isValidContentItem(message.result)) {\n              if (message.result.protocolVersion || message.result.serverInfo) {\n                try {\n                  const serverData = extractSessionDataFromInitializeResponse(message.result);\n                  updateSessionDataForTransport(this, serverData);\n                } catch {\n                  // noop\n                }\n              }\n            }\n\n            completeSpanWithResults(this, message.id, message.result, options);\n          }\n        }\n\n        return (originalSend as (...args: unknown[]) =\u003e unknown).call(this, ...args);\n      };\n    });\n  }\n}\n\n/**\n * Wraps transport.onclose to clean up pending spans for this transport only\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportOnClose(transport: MCPTransport): void {\n  if (transport.onclose) {\n    fill(transport, 'onclose', originalOnClose =\u003e {\n      return function (this: MCPTransport, ...args: unknown[]) {\n        cleanupPendingSpansForTransport(this);\n        cleanupSessionDataForTransport(this);\n        return (originalOnClose as (...args: unknown[]) =\u003e unknown).call(this, ...args);\n      };\n    });\n  }\n}\n\n/**\n * Wraps transport error handlers to capture connection errors\n * @param transport - MCP transport instance to wrap\n */\nexport function wrapTransportError(transport: MCPTransport): void {\n  if (transport.onerror) {\n    fill(transport, 'onerror', (originalOnError: (error: Error) =\u003e void) =\u003e {\n      return function (this: MCPTransport, error: Error) {\n        captureTransportError(error);\n        return originalOnError.call(this, error);\n      };\n    });\n  }\n}\n\n/**\n * Captures JSON-RPC error responses for server-side errors.\n * @see https://www.jsonrpc.org/specification#error_object\n * @internal\n * @param errorResponse - JSON-RPC error response\n */\nfunction captureJsonRpcErrorResponse(errorResponse: unknown): void {\n  try {\n    if (errorResponse \u0026\u0026 typeof errorResponse === 'object' \u0026\u0026 'code' in errorResponse \u0026\u0026 'message' in errorResponse) {\n      const jsonRpcError = errorResponse as { code: number; message: string; data?: unknown };\n\n      const isServerError =\n        jsonRpcError.code === -32603 || (jsonRpcError.code \u003e= -32099 \u0026\u0026 jsonRpcError.code \u003c= -32000);\n\n      if (isServerError) {\n        const error = new Error(jsonRpcError.message);\n        error.name = `JsonRpcError_${jsonRpcError.code}`;\n\n        captureError(error, 'protocol');\n      }\n    }\n  } catch {\n    // noop\n  }\n}\n\n/**\n * Captures transport connection errors\n * @internal\n * @param error - Transport error\n */\nfunction captureTransportError(error: Error): void {\n  try {\n    captureError(error, 'transport');\n  } catch {\n    // noop\n  }\n}\n","import { getClient } from '../../currentScopes';\nimport { fill } from '../../utils/object';\nimport { wrapAllMCPHandlers } from './handlers';\nimport { wrapTransportError, wrapTransportOnClose, wrapTransportOnMessage, wrapTransportSend } from './transport';\nimport type { MCPServerInstance, McpServerWrapperOptions, MCPTransport, ResolvedMcpOptions } from './types';\nimport { validateMcpServerInstance } from './validation';\n\n/**\n * Tracks wrapped MCP server instances to prevent double-wrapping\n * @internal\n */\nconst wrappedMcpServerInstances = new WeakSet();\n\n/**\n * Wraps a MCP Server instance from the `@modelcontextprotocol/sdk` package with Sentry instrumentation.\n *\n * Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package.\n * Automatically instruments transport methods and handler functions for comprehensive monitoring.\n *\n * @example\n * ```typescript\n * import * as Sentry from '@sentry/core';\n * import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n * import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n *\n * // Default: inputs/outputs captured based on sendDefaultPii option\n * const server = Sentry.wrapMcpServerWithSentry(\n *   new McpServer({ name: \"my-server\", version: \"1.0.0\" })\n * );\n *\n * // Explicitly control input/output capture\n * const server = Sentry.wrapMcpServerWithSentry(\n *   new McpServer({ name: \"my-server\", version: \"1.0.0\" }),\n *   { recordInputs: true, recordOutputs: false }\n * );\n *\n * const transport = new StreamableHTTPServerTransport();\n * await server.connect(transport);\n * ```\n *\n * @param mcpServerInstance - MCP server instance to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns Instrumented server instance (same reference)\n */\nexport function wrapMcpServerWithSentry\u003cS extends object\u003e(mcpServerInstance: S, options?: McpServerWrapperOptions): S {\n  if (wrappedMcpServerInstances.has(mcpServerInstance)) {\n    return mcpServerInstance;\n  }\n\n  if (!validateMcpServerInstance(mcpServerInstance)) {\n    return mcpServerInstance;\n  }\n\n  const serverInstance = mcpServerInstance as MCPServerInstance;\n  const client = getClient();\n  const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n\n  const resolvedOptions: ResolvedMcpOptions = {\n    recordInputs: options?.recordInputs ?? sendDefaultPii,\n    recordOutputs: options?.recordOutputs ?? sendDefaultPii,\n  };\n\n  fill(serverInstance, 'connect', originalConnect =\u003e {\n    return async function (this: MCPServerInstance, transport: MCPTransport, ...restArgs: unknown[]) {\n      const result = await (originalConnect as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e).call(\n        this,\n        transport,\n        ...restArgs,\n      );\n\n      wrapTransportOnMessage(transport, resolvedOptions);\n      wrapTransportSend(transport, resolvedOptions);\n      wrapTransportOnClose(transport);\n      wrapTransportError(transport);\n\n      return result;\n    };\n  });\n\n  wrapAllMCPHandlers(serverInstance);\n\n  wrappedMcpServerInstances.add(mcpServerInstance);\n  return mcpServerInstance;\n}\n","import { getClient, getCurrentScope } from './currentScopes';\nimport type { EventHint } from './types-hoist/event';\nimport type { FeedbackEvent, SendFeedbackParams } from './types-hoist/feedback';\n\n/**\n * Send user feedback to Sentry.\n */\nexport function captureFeedback(\n  params: SendFeedbackParams,\n  hint: EventHint \u0026 { includeReplay?: boolean } = {},\n  scope = getCurrentScope(),\n): string {\n  const { message, name, email, url, source, associatedEventId, tags } = params;\n\n  const feedbackEvent: FeedbackEvent = {\n    contexts: {\n      feedback: {\n        contact_email: email,\n        name,\n        message,\n        url,\n        source,\n        associated_event_id: associatedEventId,\n      },\n    },\n    type: 'feedback',\n    level: 'info',\n    tags,\n  };\n\n  const client = scope?.getClient() || getClient();\n\n  if (client) {\n    client.emit('beforeSendFeedback', feedbackEvent, hint);\n  }\n\n  const eventId = scope.captureEvent(feedbackEvent, hint);\n\n  return eventId;\n}\n","import type { Scope } from '../scope';\nimport type { Log, LogSeverityLevel } from '../types-hoist/log';\nimport type { ParameterizedString } from '../types-hoist/parameterize';\nimport { _INTERNAL_captureLog } from './internal';\n\n/**\n * Capture a log with the given level.\n *\n * @param level - The level of the log.\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.\n * @param scope - The scope to capture the log with.\n * @param severityNumber - The severity number of the log.\n */\nfunction captureLog(\n  level: LogSeverityLevel,\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  scope?: Scope,\n  severityNumber?: Log['severityNumber'],\n): void {\n  _INTERNAL_captureLog({ level, message, attributes, severityNumber }, scope);\n}\n\n/**\n * Additional metadata to capture the log with.\n */\ninterface CaptureLogMetadata {\n  scope?: Scope;\n}\n\n/**\n * @summary Capture a log with the `trace` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.trace('User clicked submit button', {\n *   buttonId: 'submit-form',\n *   formId: 'user-profile',\n *   timestamp: Date.now()\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {\n *   userId: '123',\n *   sessionId: 'abc-xyz'\n * });\n * ```\n */\nexport function trace(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('trace', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `debug` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { component: 'Header', state: 'loading' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.debug('Component mounted', {\n *   component: 'UserProfile',\n *   props: { userId: 123 },\n *   renderTime: 150\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.debug(Sentry.logger.fmt`API request to ${endpoint} failed`, {\n *   statusCode: 404,\n *   requestId: 'req-123',\n *   duration: 250\n * });\n * ```\n */\nexport function debug(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('debug', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `info` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { feature: 'checkout', status: 'completed' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.info('User completed checkout', {\n *   orderId: 'order-123',\n *   amount: 99.99,\n *   paymentMethod: 'credit_card'\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.info(Sentry.logger.fmt`User ${user} updated profile picture`, {\n *   userId: 'user-123',\n *   imageSize: '2.5MB',\n *   timestamp: Date.now()\n * });\n * ```\n */\nexport function info(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('info', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `warn` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { browser: 'Chrome', version: '91.0' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.warn('Browser compatibility issue detected', {\n *   browser: 'Safari',\n *   version: '14.0',\n *   feature: 'WebRTC',\n *   fallback: 'enabled'\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.warn(Sentry.logger.fmt`API endpoint ${endpoint} is deprecated`, {\n *   recommendedEndpoint: '/api/v2/users',\n *   sunsetDate: '2024-12-31',\n *   clientVersion: '1.2.3'\n * });\n * ```\n */\nexport function warn(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('warn', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `error` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { error: 'NetworkError', url: '/api/data' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.error('Failed to load user data', {\n *   error: 'NetworkError',\n *   url: '/api/users/123',\n *   statusCode: 500,\n *   retryCount: 3\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.error(Sentry.logger.fmt`Payment processing failed for order ${orderId}`, {\n *   error: 'InsufficientFunds',\n *   amount: 100.00,\n *   currency: 'USD',\n *   userId: 'user-456'\n * });\n * ```\n */\nexport function error(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('error', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `fatal` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { appState: 'corrupted', sessionId: 'abc-123' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.fatal('Application state corrupted', {\n *   lastKnownState: 'authenticated',\n *   sessionId: 'session-123',\n *   timestamp: Date.now(),\n *   recoveryAttempted: true\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.fatal(Sentry.logger.fmt`Critical system failure in ${service}`, {\n *   service: 'payment-processor',\n *   errorCode: 'CRITICAL_FAILURE',\n *   affectedUsers: 150,\n *   timestamp: Date.now()\n * });\n * ```\n */\nexport function fatal(\n  message: ParameterizedString,\n  attributes?: Log['attributes'],\n  { scope }: CaptureLogMetadata = {},\n): void {\n  captureLog('fatal', message, attributes, scope);\n}\n\nexport { fmt } from '../utils/parameterize';\n","import { isPrimitive } from '../utils/is';\nimport { normalize } from '../utils/normalize';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\n\ntype GlobalObjectWithUtil = typeof GLOBAL_OBJ \u0026 {\n  util: {\n    format: (...args: unknown[]) =\u003e string;\n  };\n};\n\n/**\n * Formats the given values into a string.\n *\n * @param values - The values to format.\n * @param normalizeDepth - The depth to normalize the values.\n * @param normalizeMaxBreadth - The max breadth to normalize the values.\n * @returns The formatted string.\n */\nexport function formatConsoleArgs(values: unknown[], normalizeDepth: number, normalizeMaxBreadth: number): string {\n  return 'util' in GLOBAL_OBJ \u0026\u0026 typeof (GLOBAL_OBJ as GlobalObjectWithUtil).util.format === 'function'\n    ? (GLOBAL_OBJ as GlobalObjectWithUtil).util.format(...values)\n    : safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth);\n}\n\n/**\n * Joins the given values into a string.\n *\n * @param values - The values to join.\n * @param normalizeDepth - The depth to normalize the values.\n * @param normalizeMaxBreadth - The max breadth to normalize the values.\n * @returns The joined string.\n */\nexport function safeJoinConsoleArgs(values: unknown[], normalizeDepth: number, normalizeMaxBreadth: number): string {\n  return values\n    .map(value =\u003e\n      isPrimitive(value) ? String(value) : JSON.stringify(normalize(value, normalizeDepth, normalizeMaxBreadth)),\n    )\n    .join(' ');\n}\n\n/**\n * Checks if a string contains console substitution patterns like %s, %d, %i, %f, %o, %O, %c.\n *\n * @param str - The string to check\n * @returns true if the string contains console substitution patterns\n */\nexport function hasConsoleSubstitutions(str: string): boolean {\n  // Match console substitution patterns: %s, %d, %i, %f, %o, %O, %c\n  return /%[sdifocO]/.test(str);\n}\n\n/**\n * Creates template attributes for multiple console arguments.\n *\n * @param args - The console arguments\n * @returns An object with template and parameter attributes\n */\nexport function createConsoleTemplateAttributes(firstArg: unknown, followingArgs: unknown[]): Record\u003cstring, unknown\u003e {\n  const attributes: Record\u003cstring, unknown\u003e = {};\n\n  // Create template with placeholders for each argument\n  const template = new Array(followingArgs.length).fill('{}').join(' ');\n  attributes['sentry.message.template'] = `${firstArg} ${template}`;\n\n  // Add each argument as a parameter\n  followingArgs.forEach((arg, index) =\u003e {\n    attributes[`sentry.message.parameter.${index}`] = arg;\n  });\n\n  return attributes;\n}\n","import { getClient } from '../currentScopes';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { addConsoleInstrumentationHandler } from '../instrument/console';\nimport { defineIntegration } from '../integration';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes';\nimport type { ConsoleLevel } from '../types-hoist/instrument';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport { CONSOLE_LEVELS, debug } from '../utils/debug-logger';\nimport { _INTERNAL_captureLog } from './internal';\nimport { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from './utils';\n\ninterface CaptureConsoleOptions {\n  levels: ConsoleLevel[];\n}\n\nconst INTEGRATION_NAME = 'ConsoleLogs';\n\nconst DEFAULT_ATTRIBUTES = {\n  [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.log.console',\n};\n\nconst _consoleLoggingIntegration = ((options: Partial\u003cCaptureConsoleOptions\u003e = {}) =\u003e {\n  const levels = options.levels || CONSOLE_LEVELS;\n\n  return {\n    name: INTEGRATION_NAME,\n    setup(client) {\n      const { enableLogs, normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = client.getOptions();\n      if (!enableLogs) {\n        DEBUG_BUILD \u0026\u0026 debug.warn('`enableLogs` is not enabled, ConsoleLogs integration disabled');\n        return;\n      }\n\n      addConsoleInstrumentationHandler(({ args, level }) =\u003e {\n        if (getClient() !== client || !levels.includes(level)) {\n          return;\n        }\n\n        const firstArg = args[0];\n        const followingArgs = args.slice(1);\n\n        if (level === 'assert') {\n          if (!firstArg) {\n            const assertionMessage =\n              followingArgs.length \u003e 0\n                ? `Assertion failed: ${formatConsoleArgs(followingArgs, normalizeDepth, normalizeMaxBreadth)}`\n                : 'Assertion failed';\n            _INTERNAL_captureLog({ level: 'error', message: assertionMessage, attributes: DEFAULT_ATTRIBUTES });\n          }\n          return;\n        }\n\n        const isLevelLog = level === 'log';\n\n        const shouldGenerateTemplate =\n          args.length \u003e 1 \u0026\u0026 typeof args[0] === 'string' \u0026\u0026 !hasConsoleSubstitutions(args[0]);\n        const attributes = {\n          ...DEFAULT_ATTRIBUTES,\n          ...(shouldGenerateTemplate ? createConsoleTemplateAttributes(firstArg, followingArgs) : {}),\n        };\n\n        _INTERNAL_captureLog({\n          level: isLevelLog ? 'info' : level,\n          message: formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth),\n          severityNumber: isLevelLog ? 10 : undefined,\n          attributes,\n        });\n      });\n    },\n  };\n}) satisfies IntegrationFn;\n\n/**\n * Captures calls to the `console` API as logs in Sentry. Requires the `enableLogs` option to be enabled.\n *\n * @experimental This feature is experimental and may be changed or removed in future versions.\n *\n * By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,\n * `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which\n * levels are captured.\n *\n * @example\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n *\n * Sentry.init({\n *   enableLogs: true,\n *   integrations: [Sentry.consoleLoggingIntegration({ levels: ['error', 'warn'] })],\n * });\n * ```\n */\nexport const consoleLoggingIntegration = defineIntegration(_consoleLoggingIntegration);\n","import type { Scope } from '../scope';\nimport type { Metric, MetricType } from '../types-hoist/metric';\nimport { _INTERNAL_captureMetric } from './internal';\n\n/**\n * Options for capturing a metric.\n */\nexport interface MetricOptions {\n  /**\n   * The unit of the metric value.\n   */\n  unit?: string;\n\n  /**\n   * Arbitrary structured data that stores information about the metric.\n   */\n  attributes?: Metric['attributes'];\n\n  /**\n   * The scope to capture the metric with.\n   */\n  scope?: Scope;\n}\n\n/**\n * Capture a metric with the given type, name, and value.\n *\n * @param type - The type of the metric.\n * @param name - The name of the metric.\n * @param value - The value of the metric.\n * @param options - Options for capturing the metric.\n */\nfunction captureMetric(type: MetricType, name: string, value: number, options?: MetricOptions): void {\n  _INTERNAL_captureMetric(\n    { type, name, value, unit: options?.unit, attributes: options?.attributes },\n    { scope: options?.scope },\n  );\n}\n\n/**\n * @summary Increment a counter metric.\n *\n * @param name - The name of the counter metric.\n * @param value - The value to increment by (defaults to 1).\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.count('api.requests', 1, {\n *   attributes: {\n *     endpoint: '/api/users',\n *     method: 'GET',\n *     status: 200\n *   }\n * });\n * ```\n *\n * @example With custom value\n *\n * ```\n * Sentry.metrics.count('items.processed', 5, {\n *   attributes: {\n *     processor: 'batch-processor',\n *     queue: 'high-priority'\n *   }\n * });\n * ```\n */\nexport function count(name: string, value: number = 1, options?: MetricOptions): void {\n  captureMetric('counter', name, value, options);\n}\n\n/**\n * @summary Set a gauge metric to a specific value.\n *\n * @param name - The name of the gauge metric.\n * @param value - The current value of the gauge.\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.gauge('memory.usage', 1024, {\n *   unit: 'megabyte',\n *   attributes: {\n *     process: 'web-server',\n *     region: 'us-east-1'\n *   }\n * });\n * ```\n *\n * @example Without unit\n *\n * ```\n * Sentry.metrics.gauge('active.connections', 42, {\n *   attributes: {\n *     server: 'api-1',\n *     protocol: 'websocket'\n *   }\n * });\n * ```\n */\nexport function gauge(name: string, value: number, options?: MetricOptions): void {\n  captureMetric('gauge', name, value, options);\n}\n\n/**\n * @summary Record a value in a distribution metric.\n *\n * @param name - The name of the distribution metric.\n * @param value - The value to record in the distribution.\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.distribution('task.duration', 500, {\n *   unit: 'millisecond',\n *   attributes: {\n *     task: 'data-processing',\n *     priority: 'high'\n *   }\n * });\n * ```\n *\n * @example Without unit\n *\n * ```\n * Sentry.metrics.distribution('batch.size', 100, {\n *   attributes: {\n *     processor: 'batch-1',\n *     type: 'async'\n *   }\n * });\n * ```\n */\nexport function distribution(name: string, value: number, options?: MetricOptions): void {\n  captureMetric('distribution', name, value, options);\n}\n","import type { Client } from '../client';\nimport { getClient } from '../currentScopes';\nimport { _INTERNAL_captureLog } from '../logs/internal';\nimport { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from '../logs/utils';\nimport type { LogSeverityLevel } from '../types-hoist/log';\nimport { isPlainObject } from '../utils/is';\nimport { normalize } from '../utils/normalize';\n\n/**\n * Result of extracting structured attributes from console arguments.\n */\ninterface ExtractAttributesResult {\n  /**\n   * The log message to use for the log entry, typically constructed from the console arguments.\n   */\n  message?: string;\n\n  /**\n   * The parameterized template string which is added as `sentry.message.template` attribute if applicable.\n   */\n  messageTemplate?: string;\n\n  /**\n   * Remaining arguments to process as attributes with keys like `sentry.message.parameter.0`, `sentry.message.parameter.1`, etc.\n   */\n  messageParameters?: unknown[];\n\n  /**\n   * Additional attributes to add to the log.\n   */\n  attributes?: Record\u003cstring, unknown\u003e;\n}\n\n/**\n * Options for the Sentry Consola reporter.\n */\ninterface ConsolaReporterOptions {\n  /**\n   * Use this option to filter which levels should be captured. By default, all levels are captured.\n   *\n   * @example\n   * ```ts\n   * const sentryReporter = Sentry.createConsolaReporter({\n   *   // Only capture error and warn logs\n   *   levels: ['error', 'warn'],\n   * });\n   * consola.addReporter(sentryReporter);\n   * ```\n   */\n  levels?: Array\u003cLogSeverityLevel\u003e;\n\n  /**\n   * Optionally provide a specific Sentry client instance to use for capturing logs.\n   * If not provided, the current client will be retrieved using `getClient()`.\n   *\n   * This is useful when you want to use specific client options for log normalization\n   * or when working with multiple client instances.\n   *\n   * @example\n   * ```ts\n   * const sentryReporter = Sentry.createConsolaReporter({\n   *   client: myCustomClient,\n   * });\n   * ```\n   */\n  client?: Client;\n}\n\nexport interface ConsolaReporter {\n  log: (logObj: ConsolaLogObject) =\u003e void;\n}\n\n/**\n * Represents a log object that Consola reporters receive.\n *\n * This interface matches the structure of log objects passed to Consola reporters.\n * See: https://github.com/unjs/consola#custom-reporters\n *\n * @example\n * ```ts\n * const reporter = {\n *   log(logObj: ConsolaLogObject) {\n *     console.log(`[${logObj.type}] ${logObj.message || logObj.args?.join(' ')}`);\n *   }\n * };\n * consola.addReporter(reporter);\n * ```\n */\nexport interface ConsolaLogObject {\n  /**\n   * Allows additional custom properties to be set on the log object. These properties will be captured as log attributes.\n   *\n   * Additional properties are set when passing a single object with a `message` (`consola.[type]({ message: '', ... })`) or if the reporter is called directly\n   *\n   * @example\n   * ```ts\n   * const reporter = Sentry.createConsolaReporter();\n   * reporter.log({\n   *   type: 'info',\n   *   message: 'User action',\n   *   userId: 123,\n   *   sessionId: 'abc-123'\n   * });\n   * // Will create attributes: `userId` and `sessionId`\n   * ```\n   */\n  [key: string]: unknown;\n\n  /**\n   * The numeric log level (0-5) or null.\n   *\n   * Consola log levels:\n   * - 0: Fatal and Error\n   * - 1: Warnings\n   * - 2: Normal logs\n   * - 3: Informational logs, success, fail, ready, start, box, ...\n   * - 4: Debug logs\n   * - 5: Trace logs\n   * - null: Some special types like 'verbose'\n   *\n   * See: https://github.com/unjs/consola/blob/main/README.md#log-level\n   */\n  level?: number | null;\n\n  /**\n   * The log type/method name (e.g., 'error', 'warn', 'info', 'debug', 'trace', 'success', 'fail', etc.).\n   *\n   * Consola built-in types include:\n   * - Standard: silent, fatal, error, warn, log, info, success, fail, ready, start, box, debug, trace, verbose\n   * - Custom types can also be defined\n   *\n   * See: https://github.com/unjs/consola/blob/main/README.md#log-types\n   */\n  type?: string;\n\n  /**\n   * An optional tag/scope for the log entry.\n   *\n   * Tags are created using `consola.withTag('scope')` and help categorize logs.\n   *\n   * @example\n   * ```ts\n   * const scopedLogger = consola.withTag('auth');\n   * scopedLogger.info('User logged in'); // tag will be 'auth'\n   * ```\n   *\n   * See: https://github.com/unjs/consola/blob/main/README.md#withtagtag\n   */\n  tag?: string;\n\n  /**\n   * The raw arguments passed to the log method.\n   *\n   * These args are typically formatted into the final `message`. In Consola reporters, `message` is not provided. See: https://github.com/unjs/consola/issues/406#issuecomment-3684792551\n   *\n   * @example\n   * ```ts\n   * consola.info('Hello', 'world', { user: 'john' });\n   * // args = ['Hello', 'world', { user: 'john' }]\n   * ```\n   *\n   * @example\n   * ```ts\n   * // `message` is a reserved property in Consola\n   * consola.log({ message: 'Hello' });\n   * // args = ['Hello']\n   * ```\n   */\n  args?: unknown[];\n\n  /**\n   * The timestamp when the log was created.\n   *\n   * This is automatically set by Consola when the log is created.\n   */\n  date?: Date;\n\n  /**\n   * The formatted log message.\n   *\n   * When provided, this is the final formatted message. When not provided,\n   * the message should be constructed from the `args` array.\n   *\n   * Note: In reporters, `message` is typically undefined. It is primarily for\n   * `consola.[type]({ message: 'xxx' })` usage and is normalized into `args` before\n   * reporters receive the log object. See: https://github.com/unjs/consola/issues/406#issuecomment-3684792551\n   */\n  message?: string;\n}\n\nconst DEFAULT_CAPTURED_LEVELS: Array\u003cLogSeverityLevel\u003e = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n/**\n * Creates a new Sentry reporter for Consola that forwards logs to Sentry. Requires the `enableLogs` option to be enabled.\n *\n * **Note: This integration supports Consola v3.x only.** The reporter interface and log object structure\n * may differ in other versions of Consola.\n *\n * @param options - Configuration options for the reporter.\n * @returns A Consola reporter that can be added to consola instances.\n *\n * @example\n * ```ts\n * import * as Sentry from '@sentry/node';\n * import { consola } from 'consola';\n *\n * Sentry.init({\n *   enableLogs: true,\n * });\n *\n * const sentryReporter = Sentry.createConsolaReporter({\n *   // Optional: filter levels to capture\n *   levels: ['error', 'warn', 'info'],\n * });\n *\n * consola.addReporter(sentryReporter);\n *\n * // Now consola logs will be captured by Sentry\n * consola.info('This will be sent to Sentry');\n * consola.error('This error will also be sent to Sentry');\n * ```\n */\nexport function createConsolaReporter(options: ConsolaReporterOptions = {}): ConsolaReporter {\n  const levels = new Set(options.levels ?? DEFAULT_CAPTURED_LEVELS);\n  const providedClient = options.client;\n\n  return {\n    log(logObj: ConsolaLogObject) {\n      // We need to exclude certain known properties from being added as additional attributes\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      const { type, level, message: consolaMessage, args, tag, date: _date, ...rest } = logObj;\n\n      // Get client - use provided client or current client\n      const client = providedClient || getClient();\n      if (!client) {\n        return;\n      }\n\n      // Determine the log severity level\n      const logSeverityLevel = getLogSeverityLevel(type, level);\n\n      // Early exit if this level should not be captured\n      if (!levels.has(logSeverityLevel)) {\n        return;\n      }\n\n      const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = client.getOptions();\n\n      const attributes: Record\u003cstring, unknown\u003e = {};\n\n      // Build attributes\n      for (const [key, value] of Object.entries(rest)) {\n        attributes[key] = normalize(value, normalizeDepth, normalizeMaxBreadth);\n      }\n\n      attributes['sentry.origin'] = 'auto.log.consola';\n\n      if (tag) {\n        attributes['consola.tag'] = tag;\n      }\n\n      if (type) {\n        attributes['consola.type'] = type;\n      }\n\n      // Only add level if it's a valid number (not null/undefined)\n      if (level != null \u0026\u0026 typeof level === 'number') {\n        attributes['consola.level'] = level;\n      }\n\n      const extractionResult = processExtractedAttributes(\n        defaultExtractAttributes(args, normalizeDepth, normalizeMaxBreadth),\n        normalizeDepth,\n        normalizeMaxBreadth,\n      );\n\n      if (extractionResult?.attributes) {\n        Object.assign(attributes, extractionResult.attributes);\n      }\n\n      _INTERNAL_captureLog({\n        level: logSeverityLevel,\n        message:\n          extractionResult?.message ||\n          consolaMessage ||\n          (args \u0026\u0026 formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth)) ||\n          '',\n        attributes,\n      });\n    },\n  };\n}\n\n// Mapping from consola log types to Sentry log severity levels\nconst CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP: Record\u003cstring, LogSeverityLevel\u003e = {\n  // Consola built-in types\n  silent: 'trace',\n  fatal: 'fatal',\n  error: 'error',\n  warn: 'warn',\n  log: 'info',\n  info: 'info',\n  success: 'info',\n  fail: 'error',\n  ready: 'info',\n  start: 'info',\n  box: 'info',\n  debug: 'debug',\n  trace: 'trace',\n  verbose: 'debug',\n  // Custom types that might exist\n  critical: 'fatal',\n  notice: 'info',\n};\n\n// Mapping from consola log levels (numbers) to Sentry log severity levels\nconst CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP: Record\u003cnumber, LogSeverityLevel\u003e = {\n  0: 'fatal', // Fatal and Error\n  1: 'warn', // Warnings\n  2: 'info', // Normal logs\n  3: 'info', // Informational logs, success, fail, ready, start, ...\n  4: 'debug', // Debug logs\n  5: 'trace', // Trace logs\n};\n\n/**\n * Determines the log severity level from Consola type and level.\n *\n * @param type - The Consola log type (e.g., 'error', 'warn', 'info')\n * @param level - The Consola numeric log level (0-5) or null for some types like 'verbose'\n * @returns The corresponding Sentry log severity level\n */\nfunction getLogSeverityLevel(type?: string, level?: number | null): LogSeverityLevel {\n  // Handle special case for verbose logs (level can be null with infinite level in Consola)\n  if (type === 'verbose') {\n    return 'debug';\n  }\n\n  // Handle silent logs - these should be at trace level\n  if (type === 'silent') {\n    return 'trace';\n  }\n\n  // First try to map by type (more specific)\n  if (type) {\n    const mappedLevel = CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP[type];\n    if (mappedLevel) {\n      return mappedLevel;\n    }\n  }\n\n  // Fallback to level mapping (handle null level)\n  if (typeof level === 'number') {\n    const mappedLevel = CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[level];\n    if (mappedLevel) {\n      return mappedLevel;\n    }\n  }\n\n  // Default fallback\n  return 'info';\n}\n\n/**\n * Extracts structured attributes from console arguments. If the first argument is a plain object, its properties are extracted as attributes.\n */\nfunction defaultExtractAttributes(\n  args: unknown[] | undefined,\n  normalizeDepth: number,\n  normalizeMaxBreadth: number,\n): ExtractAttributesResult {\n  if (!args?.length) {\n    return { message: '' };\n  }\n\n  // Message looks like how consola logs the message to the console (all args stringified and joined)\n  const message = formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth);\n\n  const firstArg = args[0];\n\n  if (isPlainObject(firstArg)) {\n    // Remaining args start from index 2 i f we used second arg as message, otherwise from index 1\n    const remainingArgsStartIndex = typeof args[1] === 'string' ? 2 : 1;\n    const remainingArgs = args.slice(remainingArgsStartIndex);\n\n    return {\n      message,\n      // Object content from first arg is added as attributes\n      attributes: firstArg,\n      // Add remaining args as message parameters\n      messageParameters: remainingArgs,\n    };\n  } else {\n    const followingArgs = args.slice(1);\n\n    const shouldAddTemplateAttr =\n      followingArgs.length \u003e 0 \u0026\u0026 typeof firstArg === 'string' \u0026\u0026 !hasConsoleSubstitutions(firstArg);\n\n    return {\n      message,\n      messageTemplate: shouldAddTemplateAttr ? firstArg : undefined,\n      messageParameters: shouldAddTemplateAttr ? followingArgs : undefined,\n    };\n  }\n}\n\n/**\n * Processes extracted attributes by normalizing them and preparing message parameter attributes if a template is present.\n */\nfunction processExtractedAttributes(\n  extractionResult: ExtractAttributesResult,\n  normalizeDepth: number,\n  normalizeMaxBreadth: number,\n): { message: string | undefined; attributes: Record\u003cstring, unknown\u003e } {\n  const { message, attributes, messageTemplate, messageParameters } = extractionResult;\n\n  const messageParamAttributes: Record\u003cstring, unknown\u003e = {};\n\n  if (messageTemplate \u0026\u0026 messageParameters) {\n    const templateAttrs = createConsoleTemplateAttributes(messageTemplate, messageParameters);\n\n    for (const [key, value] of Object.entries(templateAttrs)) {\n      messageParamAttributes[key] = key.startsWith('sentry.message.parameter.')\n        ? normalize(value, normalizeDepth, normalizeMaxBreadth)\n        : value;\n    }\n  } else if (messageParameters \u0026\u0026 messageParameters.length \u003e 0) {\n    messageParameters.forEach((arg, index) =\u003e {\n      messageParamAttributes[`sentry.message.parameter.${index}`] = normalize(arg, normalizeDepth, normalizeMaxBreadth);\n    });\n  }\n\n  return {\n    message: message,\n    attributes: {\n      ...normalize(attributes, normalizeDepth, normalizeMaxBreadth),\n      ...messageParamAttributes,\n    },\n  };\n}\n","/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nexport const GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nexport const GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Stop sequences for the model request\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * The encoding format for the model request\n */\nexport const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nexport const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nexport const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nexport const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nexport const GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * Original length of messages array, used to indicate truncations had occured\n */\nexport const GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE = 'sentry.sdk_meta.gen_ai.input.messages.original_length';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_INPUT_MESSAGES_ATTRIBUTE = 'gen_ai.input.messages';\n\n/**\n * The model's response messages including text and tool calls\n * Only recorded when recordOutputs is enabled\n * Format: stringified array of message objects with role, parts, and finish_reason\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-output-messages\n */\nexport const GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE = 'gen_ai.output.messages';\n\n/**\n * The system instructions extracted from system messages\n * Only recorded when recordInputs is enabled\n * According to OpenTelemetry spec: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system-instructions\n */\nexport const GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE = 'gen_ai.system_instructions';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nexport const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nexport const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nexport const GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nexport const GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The conversation ID for linking messages across API calls\n * For OpenAI Assistants API: thread_id\n * For LangGraph: configurable.thread_id\n */\nexport const GEN_AI_CONVERSATION_ID_ATTRIBUTE = 'gen_ai.conversation.id';\n\n/**\n * The number of cache creation input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nexport const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nexport const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n/**\n * The span operation name for generating text\n */\nexport const GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE = 'gen_ai.generate_text';\n\n/**\n * The span operation name for streaming text\n */\nexport const GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream_text';\n\n/**\n * The span operation name for generating object\n */\nexport const GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE = 'gen_ai.generate_object';\n\n/**\n * The span operation name for streaming object\n */\nexport const GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE = 'gen_ai.stream_object';\n\n/**\n * The embeddings input\n * Only recorded when recordInputs is enabled\n */\nexport const GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE = 'gen_ai.embeddings.input';\n\n/**\n * The span operation name for embedding\n */\nexport const GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for embedding many\n */\nexport const GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE = 'gen_ai.embeddings';\n\n/**\n * The span operation name for reranking\n */\nexport const GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE = 'gen_ai.rerank';\n\n/**\n * The span operation name for executing a tool\n */\nexport const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = 'gen_ai.execute_tool';\n\n/**\n * The tool name for tool call spans\n */\nexport const GEN_AI_TOOL_NAME_ATTRIBUTE = 'gen_ai.tool.name';\n\n/**\n * The tool call ID\n */\nexport const GEN_AI_TOOL_CALL_ID_ATTRIBUTE = 'gen_ai.tool.call.id';\n\n/**\n * The tool type (e.g., 'function')\n */\nexport const GEN_AI_TOOL_TYPE_ATTRIBUTE = 'gen_ai.tool.type';\n\n/**\n * The tool input/arguments\n */\nexport const GEN_AI_TOOL_INPUT_ATTRIBUTE = 'gen_ai.tool.input';\n\n/**\n * The tool output/result\n */\nexport const GEN_AI_TOOL_OUTPUT_ATTRIBUTE = 'gen_ai.tool.output';\n\n/**\n * The description of the tool being used\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-description\n */\nexport const GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE = 'gen_ai.tool.description';\n\n// =============================================================================\n// OPENAI-SPECIFIC ATTRIBUTES\n// =============================================================================\n\n/**\n * The response ID from OpenAI\n */\nexport const OPENAI_RESPONSE_ID_ATTRIBUTE = 'openai.response.id';\n\n/**\n * The response model from OpenAI\n */\nexport const OPENAI_RESPONSE_MODEL_ATTRIBUTE = 'openai.response.model';\n\n/**\n * The response timestamp from OpenAI (ISO string)\n */\nexport const OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'openai.response.timestamp';\n\n/**\n * The number of completion tokens used\n */\nexport const OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = 'openai.usage.completion_tokens';\n\n/**\n * The number of prompt tokens used\n */\nexport const OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE = 'openai.usage.prompt_tokens';\n\n// =============================================================================\n// OPENAI OPERATIONS\n// =============================================================================\n\n/**\n * OpenAI API operations following OpenTelemetry semantic conventions\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#llm-request-spans\n */\nexport const OPENAI_OPERATIONS = {\n  CHAT: 'chat',\n  EMBEDDINGS: 'embeddings',\n} as const;\n\n// =============================================================================\n// ANTHROPIC AI OPERATIONS\n// =============================================================================\n\n/**\n * The response timestamp from Anthropic AI (ISO string)\n */\nexport const ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'anthropic.response.timestamp';\n","import type { ToolCallSpanContext } from './types';\n\n// Global map to track tool call IDs to their corresponding span contexts.\n// This allows us to capture tool errors and link them to the correct span\n// without keeping full Span objects (and their potentially large attributes) alive.\nexport const toolCallSpanContextMap = new Map\u003cstring, ToolCallSpanContext\u003e();\n\n// Operation sets for efficient mapping to OpenTelemetry semantic convention values\nexport const INVOKE_AGENT_OPS = new Set(['ai.generateText', 'ai.streamText', 'ai.generateObject', 'ai.streamObject']);\n\nexport const GENERATE_CONTENT_OPS = new Set([\n  'ai.generateText.doGenerate',\n  'ai.streamText.doStream',\n  'ai.generateObject.doGenerate',\n  'ai.streamObject.doStream',\n]);\n\nexport const EMBEDDINGS_OPS = new Set(['ai.embed.doEmbed', 'ai.embedMany.doEmbed']);\n\nexport const RERANK_OPS = new Set(['ai.rerank.doRerank']);\n\nexport const DO_SPAN_NAME_PREFIX: Record\u003cstring, string\u003e = {\n  'ai.embed.doEmbed': 'embeddings',\n  'ai.embedMany.doEmbed': 'embeddings',\n  'ai.rerank.doRerank': 'rerank',\n};\n","/**\n * Inline media content source, with a potentially very large base64\n * blob or data: uri.\n */\nexport type ContentMedia = Record\u003cstring, unknown\u003e \u0026\n  (\n    | {\n        media_type: string;\n        data: string;\n      }\n    | {\n        image_url: `data:${string}`;\n      }\n    | {\n        image_url: { url: `data:${string}` };\n      }\n    | {\n        type: 'blob' | 'base64';\n        content: string;\n      }\n    | {\n        b64_json: string;\n      }\n    | {\n        uri: `data:${string}`;\n      }\n    | {\n        type: 'input_audio';\n        input_audio: { data: string };\n      }\n    | {\n        type: 'file';\n        file: { file_data?: string };\n      }\n  );\n\n/**\n * Check if a content part is an OpenAI/Anthropic media source\n */\nexport function isContentMedia(part: unknown): part is ContentMedia {\n  if (!part || typeof part !== 'object') return false;\n\n  return (\n    isContentMediaSource(part) ||\n    hasInlineData(part) ||\n    hasImageUrl(part) ||\n    hasInputAudio(part) ||\n    hasFileData(part) ||\n    hasMediaTypeData(part) ||\n    hasVercelFileData(part) ||\n    hasVercelImageData(part) ||\n    hasBlobOrBase64Type(part) ||\n    hasB64Json(part) ||\n    hasImageGenerationResult(part) ||\n    hasDataUri(part)\n  );\n}\n\nfunction hasImageUrl(part: NonNullable\u003cunknown\u003e): boolean {\n  if (!('image_url' in part)) return false;\n  if (typeof part.image_url === 'string') return part.image_url.startsWith('data:');\n  return hasNestedImageUrl(part);\n}\n\nfunction hasNestedImageUrl(part: NonNullable\u003cunknown\u003e): part is { image_url: { url: string } } {\n  return (\n    'image_url' in part \u0026\u0026\n    !!part.image_url \u0026\u0026\n    typeof part.image_url === 'object' \u0026\u0026\n    'url' in part.image_url \u0026\u0026\n    typeof part.image_url.url === 'string' \u0026\u0026\n    part.image_url.url.startsWith('data:')\n  );\n}\n\nfunction isContentMediaSource(part: NonNullable\u003cunknown\u003e): boolean {\n  return 'type' in part \u0026\u0026 typeof part.type === 'string' \u0026\u0026 'source' in part \u0026\u0026 isContentMedia(part.source);\n}\n\nfunction hasInlineData(part: NonNullable\u003cunknown\u003e): part is { inlineData: { data?: string } } {\n  return (\n    'inlineData' in part \u0026\u0026\n    !!part.inlineData \u0026\u0026\n    typeof part.inlineData === 'object' \u0026\u0026\n    'data' in part.inlineData \u0026\u0026\n    typeof part.inlineData.data === 'string'\n  );\n}\n\nfunction hasInputAudio(part: NonNullable\u003cunknown\u003e): part is { type: 'input_audio'; input_audio: { data: string } } {\n  return (\n    'type' in part \u0026\u0026\n    part.type === 'input_audio' \u0026\u0026\n    'input_audio' in part \u0026\u0026\n    !!part.input_audio \u0026\u0026\n    typeof part.input_audio === 'object' \u0026\u0026\n    'data' in part.input_audio \u0026\u0026\n    typeof part.input_audio.data === 'string'\n  );\n}\n\nfunction hasFileData(part: NonNullable\u003cunknown\u003e): part is { type: 'file'; file: { file_data: string } } {\n  return (\n    'type' in part \u0026\u0026\n    part.type === 'file' \u0026\u0026\n    'file' in part \u0026\u0026\n    !!part.file \u0026\u0026\n    typeof part.file === 'object' \u0026\u0026\n    'file_data' in part.file \u0026\u0026\n    typeof part.file.file_data === 'string'\n  );\n}\n\nfunction hasMediaTypeData(part: NonNullable\u003cunknown\u003e): part is { media_type: string; data: string } {\n  return 'media_type' in part \u0026\u0026 typeof part.media_type === 'string' \u0026\u0026 'data' in part;\n}\n\n/**\n * Check for Vercel AI SDK file format: { type: \"file\", mediaType: \"...\", data: \"...\" }\n * Only matches base64/binary data, not HTTP/HTTPS URLs (which should be preserved).\n */\nfunction hasVercelFileData(part: NonNullable\u003cunknown\u003e): part is { type: 'file'; mediaType: string; data: string } {\n  return (\n    'type' in part \u0026\u0026\n    part.type === 'file' \u0026\u0026\n    'mediaType' in part \u0026\u0026\n    typeof part.mediaType === 'string' \u0026\u0026\n    'data' in part \u0026\u0026\n    typeof part.data === 'string' \u0026\u0026\n    // Only strip base64/binary data, not HTTP/HTTPS URLs which should be preserved as references\n    !part.data.startsWith('http://') \u0026\u0026\n    !part.data.startsWith('https://')\n  );\n}\n\n/**\n * Check for Vercel AI SDK image format: { type: \"image\", image: \"base64...\", mimeType?: \"...\" }\n * Only matches base64/data URIs, not HTTP/HTTPS URLs (which should be preserved).\n * Note: mimeType is optional in Vercel AI SDK image parts.\n */\nfunction hasVercelImageData(part: NonNullable\u003cunknown\u003e): part is { type: 'image'; image: string; mimeType?: string } {\n  return (\n    'type' in part \u0026\u0026\n    part.type === 'image' \u0026\u0026\n    'image' in part \u0026\u0026\n    typeof part.image === 'string' \u0026\u0026\n    // Only strip base64/data URIs, not HTTP/HTTPS URLs which should be preserved as references\n    !part.image.startsWith('http://') \u0026\u0026\n    !part.image.startsWith('https://')\n  );\n}\n\nfunction hasBlobOrBase64Type(part: NonNullable\u003cunknown\u003e): part is { type: 'blob' | 'base64'; content: string } {\n  return 'type' in part \u0026\u0026 (part.type === 'blob' || part.type === 'base64');\n}\n\nfunction hasB64Json(part: NonNullable\u003cunknown\u003e): part is { b64_json: string } {\n  return 'b64_json' in part;\n}\n\nfunction hasImageGenerationResult(part: NonNullable\u003cunknown\u003e): part is { type: 'image_generation'; result: string } {\n  return 'type' in part \u0026\u0026 'result' in part \u0026\u0026 part.type === 'image_generation';\n}\n\nfunction hasDataUri(part: NonNullable\u003cunknown\u003e): part is { uri: string } {\n  return 'uri' in part \u0026\u0026 typeof part.uri === 'string' \u0026\u0026 part.uri.startsWith('data:');\n}\n\nconst REMOVED_STRING = '[Blob substitute]';\n\nconst MEDIA_FIELDS = ['image_url', 'data', 'content', 'b64_json', 'result', 'uri', 'image'] as const;\n\n/**\n * Replace inline binary data in a single media content part with a placeholder.\n */\nexport function stripInlineMediaFromSingleMessage(part: ContentMedia): ContentMedia {\n  const strip = { ...part };\n  if (isContentMedia(strip.source)) {\n    strip.source = stripInlineMediaFromSingleMessage(strip.source);\n  }\n  if (hasInlineData(part)) {\n    strip.inlineData = { ...part.inlineData, data: REMOVED_STRING };\n  }\n  if (hasNestedImageUrl(part)) {\n    strip.image_url = { ...part.image_url, url: REMOVED_STRING };\n  }\n  if (hasInputAudio(part)) {\n    strip.input_audio = { ...part.input_audio, data: REMOVED_STRING };\n  }\n  if (hasFileData(part)) {\n    strip.file = { ...part.file, file_data: REMOVED_STRING };\n  }\n  for (const field of MEDIA_FIELDS) {\n    if (typeof strip[field] === 'string') strip[field] = REMOVED_STRING;\n  }\n  return strip;\n}\n","import { isContentMedia, stripInlineMediaFromSingleMessage } from './mediaStripping';\n\n/**\n * Default maximum size in bytes for GenAI messages.\n * Messages exceeding this limit will be truncated.\n */\nexport const DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT = 20000;\n\n/**\n * Message format used by OpenAI and Anthropic APIs.\n */\ntype ContentMessage = {\n  [key: string]: unknown;\n  content: string;\n};\n\n/**\n * One block inside OpenAI / Anthropic `content: [...]` arrays (text, image_url, etc.).\n */\ntype ContentArrayBlock = {\n  [key: string]: unknown;\n  type: string;\n};\n\n/**\n * Message format used by OpenAI and Anthropic APIs for media.\n */\ntype ContentArrayMessage = {\n  [key: string]: unknown;\n  content: ContentArrayBlock[];\n};\n\n/**\n * Message format used by Google GenAI API.\n * Parts can be strings or objects with a text property.\n */\ntype PartsMessage = {\n  [key: string]: unknown;\n  parts: Array\u003cTextPart | MediaPart\u003e;\n};\n\n/**\n * A part in a Google GenAI message that contains text.\n */\ntype TextPart = string | { text: string };\n\n/**\n * A part in a Google GenAI that contains media.\n */\ntype MediaPart = {\n  type: string;\n  content: string;\n};\n\n/**\n * One element of an array-based message: OpenAI/Anthropic `content[]` or Google `parts`.\n */\ntype ArrayMessageItem = TextPart | MediaPart | ContentArrayBlock;\n\n/**\n * Calculate the UTF-8 byte length of a string.\n */\nconst utf8Bytes = (text: string): number =\u003e {\n  return new TextEncoder().encode(text).length;\n};\n\n/**\n * Calculate the UTF-8 byte length of a value's JSON representation.\n */\nconst jsonBytes = (value: unknown): number =\u003e {\n  return utf8Bytes(JSON.stringify(value));\n};\n\n/**\n * Truncate a string to fit within maxBytes (inclusive) when encoded as UTF-8.\n * Uses binary search for efficiency with multi-byte characters.\n *\n * @param text - The string to truncate\n * @param maxBytes - Maximum byte length (inclusive, UTF-8 encoded)\n * @returns Truncated string whose UTF-8 byte length is at most maxBytes\n */\nfunction truncateTextByBytes(text: string, maxBytes: number): string {\n  if (utf8Bytes(text) \u003c= maxBytes) {\n    return text;\n  }\n\n  let low = 0;\n  let high = text.length;\n  let bestFit = '';\n\n  while (low \u003c= high) {\n    const mid = Math.floor((low + high) / 2);\n    const candidate = text.slice(0, mid);\n    const byteSize = utf8Bytes(candidate);\n\n    if (byteSize \u003c= maxBytes) {\n      bestFit = candidate;\n      low = mid + 1;\n    } else {\n      high = mid - 1;\n    }\n  }\n\n  return bestFit;\n}\n\n/**\n * Extract text content from a message item.\n * Handles plain strings and objects with a text property.\n *\n * @returns The text content\n */\nfunction getItemText(item: ArrayMessageItem): string {\n  if (typeof item === 'string') {\n    return item;\n  }\n  if ('text' in item \u0026\u0026 typeof item.text === 'string') {\n    return item.text;\n  }\n  return '';\n}\n\n/**\n * Create a new item with updated text content while preserving the original structure.\n *\n * @param item - Original item (string or object)\n * @param text - New text content\n * @returns New item with updated text\n */\nfunction withItemText(item: ArrayMessageItem, text: string): ArrayMessageItem {\n  if (typeof item === 'string') {\n    return text;\n  }\n  return { ...item, text };\n}\n\n/**\n * Check if a message has the OpenAI/Anthropic content format.\n */\nfunction isContentMessage(message: unknown): message is ContentMessage {\n  return (\n    message !== null \u0026\u0026\n    typeof message === 'object' \u0026\u0026\n    'content' in message \u0026\u0026\n    typeof (message as ContentMessage).content === 'string'\n  );\n}\n\n/**\n * Check if a message has the OpenAI/Anthropic content array format.\n */\nfunction isContentArrayMessage(message: unknown): message is ContentArrayMessage {\n  return message !== null \u0026\u0026 typeof message === 'object' \u0026\u0026 'content' in message \u0026\u0026 Array.isArray(message.content);\n}\n\n/**\n * Check if a message has the Google GenAI parts format.\n */\nfunction isPartsMessage(message: unknown): message is PartsMessage {\n  return (\n    message !== null \u0026\u0026\n    typeof message === 'object' \u0026\u0026\n    'parts' in message \u0026\u0026\n    Array.isArray((message as PartsMessage).parts) \u0026\u0026\n    (message as PartsMessage).parts.length \u003e 0\n  );\n}\n\n/**\n * Truncate a message with `content: string` format (OpenAI/Anthropic).\n *\n * @param message - Message with content property\n * @param maxBytes - Maximum byte limit\n * @returns Array with truncated message, or empty array if it doesn't fit\n */\nfunction truncateContentMessage(message: ContentMessage, maxBytes: number): unknown[] {\n  // Calculate overhead (message structure without content)\n  const emptyMessage = { ...message, content: '' };\n  const overhead = jsonBytes(emptyMessage);\n  const availableForContent = maxBytes - overhead;\n\n  if (availableForContent \u003c= 0) {\n    return [];\n  }\n\n  const truncatedContent = truncateTextByBytes(message.content, availableForContent);\n  return [{ ...message, content: truncatedContent }];\n}\n\n/**\n * Extracts the array items and their key from an array-based message.\n * Returns `null` key if neither `parts` nor `content` is a valid array.\n */\nfunction getArrayItems(message: PartsMessage | ContentArrayMessage): {\n  key: 'parts' | 'content' | null;\n  items: ArrayMessageItem[];\n} {\n  if ('parts' in message \u0026\u0026 Array.isArray(message.parts)) {\n    return { key: 'parts', items: message.parts };\n  }\n  if ('content' in message \u0026\u0026 Array.isArray(message.content)) {\n    return { key: 'content', items: message.content };\n  }\n  return { key: null, items: [] };\n}\n\n/**\n * Truncate a message with an array-based format.\n * Handles both `parts: [...]` (Google GenAI) and `content: [...]` (OpenAI/Anthropic multimodal).\n * Keeps as many complete items as possible, only truncating the first item if needed.\n *\n * @param message - Message with parts or content array\n * @param maxBytes - Maximum byte limit\n * @returns Array with truncated message, or empty array if it doesn't fit\n */\nfunction truncateArrayMessage(message: PartsMessage | ContentArrayMessage, maxBytes: number): unknown[] {\n  const { key, items } = getArrayItems(message);\n\n  if (key === null || items.length === 0) {\n    return [];\n  }\n\n  // Calculate overhead by creating empty text items\n  const emptyItems = items.map(item =\u003e withItemText(item, ''));\n  const overhead = jsonBytes({ ...message, [key]: emptyItems });\n  let remainingBytes = maxBytes - overhead;\n\n  if (remainingBytes \u003c= 0) {\n    return [];\n  }\n\n  // Include items until we run out of space\n  const includedItems: ArrayMessageItem[] = [];\n\n  for (const item of items) {\n    const text = getItemText(item);\n    const textSize = utf8Bytes(text);\n\n    if (textSize \u003c= remainingBytes) {\n      // Item fits: include it as-is\n      includedItems.push(item);\n      remainingBytes -= textSize;\n    } else if (includedItems.length === 0) {\n      // First item doesn't fit: truncate it\n      const truncated = truncateTextByBytes(text, remainingBytes);\n      if (truncated) {\n        includedItems.push(withItemText(item, truncated));\n      }\n      break;\n    } else {\n      // Subsequent item doesn't fit: stop here\n      break;\n    }\n  }\n\n  /* c8 ignore start\n   * for type safety only, algorithm guarantees SOME text included */\n  if (includedItems.length \u003c= 0) {\n    return [];\n  } else {\n    /* c8 ignore stop */\n    return [{ ...message, [key]: includedItems }];\n  }\n}\n\n/**\n * Truncate a single message to fit within maxBytes.\n *\n * Supports three message formats:\n * - OpenAI/Anthropic: `{ ..., content: string }`\n * - Vercel AI/OpenAI multimodal: `{ ..., content: Array\u003c{type, text?, ...}\u003e }`\n * - Google GenAI: `{ ..., parts: Array\u003cstring | {text: string} | non-text\u003e }`\n *\n * @param message - The message to truncate\n * @param maxBytes - Maximum byte limit for the message\n * @returns Array containing the truncated message, or empty array if truncation fails\n */\nfunction truncateSingleMessage(message: unknown, maxBytes: number): unknown[] {\n  if (!message) return [];\n\n  // Handle plain strings (e.g., embeddings input)\n  if (typeof message === 'string') {\n    const truncated = truncateTextByBytes(message, maxBytes);\n    return truncated ? [truncated] : [];\n  }\n\n  if (typeof message !== 'object') {\n    return [];\n  }\n\n  if (isContentMessage(message)) {\n    return truncateContentMessage(message, maxBytes);\n  }\n\n  if (isContentArrayMessage(message) || isPartsMessage(message)) {\n    return truncateArrayMessage(message, maxBytes);\n  }\n\n  // Unknown message format: cannot truncate safely\n  return [];\n}\n\n/**\n * Strip the inline media from message arrays.\n *\n * This returns a stripped message. We do NOT want to mutate the data in place,\n * because of course we still want the actual API/client to handle the media.\n */\nfunction stripInlineMediaFromMessages(messages: unknown[]): unknown[] {\n  const stripped = messages.map(message =\u003e {\n    let newMessage: Record\u003cstring, unknown\u003e | undefined = undefined;\n    if (!!message \u0026\u0026 typeof message === 'object') {\n      if (isContentArrayMessage(message)) {\n        newMessage = {\n          ...message,\n          content: stripInlineMediaFromMessages(message.content),\n        };\n      } else if ('content' in message \u0026\u0026 isContentMedia(message.content)) {\n        newMessage = {\n          ...message,\n          content: stripInlineMediaFromSingleMessage(message.content),\n        };\n      }\n      if (isPartsMessage(message)) {\n        newMessage = {\n          // might have to strip content AND parts\n          ...(newMessage ?? message),\n          parts: stripInlineMediaFromMessages(message.parts),\n        };\n      }\n      if (isContentMedia(newMessage)) {\n        newMessage = stripInlineMediaFromSingleMessage(newMessage);\n      } else if (isContentMedia(message)) {\n        newMessage = stripInlineMediaFromSingleMessage(message);\n      }\n    }\n    return newMessage ?? message;\n  });\n  return stripped;\n}\n\n/**\n * Truncate an array of messages to fit within a byte limit.\n *\n * Strategy:\n * - Always keeps only the last (newest) message\n * - Strips inline media from the message\n * - Truncates the message content if it exceeds the byte limit\n *\n * @param messages - Array of messages to truncate\n * @param maxBytes - Maximum total byte limit for the message\n * @returns Array containing only the last message (possibly truncated)\n *\n * @example\n * ```ts\n * const messages = [msg1, msg2, msg3, msg4]; // newest is msg4\n * const truncated = truncateMessagesByBytes(messages, 10000);\n * // Returns [msg4] (truncated if needed)\n * ```\n */\nfunction truncateMessagesByBytes(messages: unknown[], maxBytes: number): unknown[] {\n  // Early return for empty or invalid input\n  if (!Array.isArray(messages) || messages.length === 0) {\n    return messages;\n  }\n\n  // The result is always a single-element array that callers wrap with\n  // JSON.stringify([message]), so subtract the 2-byte array wrapper (\"[\"  and \"]\")\n  // to ensure the final serialized value stays under the limit.\n  const effectiveMaxBytes = maxBytes - 2;\n\n  // Always keep only the last message\n  const lastMessage = messages[messages.length - 1];\n\n  // Strip inline media from the single message\n  const stripped = stripInlineMediaFromMessages([lastMessage]);\n  const strippedMessage = stripped[0];\n\n  // Check if it fits\n  const messageBytes = jsonBytes(strippedMessage);\n  if (messageBytes \u003c= effectiveMaxBytes) {\n    return stripped;\n  }\n\n  // Truncate the single message if needed\n  return truncateSingleMessage(strippedMessage, effectiveMaxBytes);\n}\n\n/**\n * Truncate GenAI messages using the default byte limit.\n *\n * Convenience wrapper around `truncateMessagesByBytes` with the default limit.\n *\n * @param messages - Array of messages to truncate\n * @returns Truncated array of messages\n */\nexport function truncateGenAiMessages(messages: unknown[]): unknown[] {\n  return truncateMessagesByBytes(messages, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT);\n}\n\n/**\n * Truncate GenAI string input using the default byte limit.\n *\n * @param input - The string to truncate\n * @returns Truncated string\n */\nexport function truncateGenAiStringInput(input: string): string {\n  return truncateTextByBytes(input, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT);\n}\n","/**\n * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.)\n */\nimport { captureException } from '../../exports';\nimport { getClient } from '../../currentScopes';\nimport type { Span } from '../../types-hoist/span';\nimport { isThenable } from '../../utils/is';\nimport {\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from './gen-ai-attributes';\nimport { truncateGenAiMessages, truncateGenAiStringInput } from './messageTruncation';\n\nexport interface AIRecordingOptions {\n  recordInputs?: boolean;\n  recordOutputs?: boolean;\n}\n\n/**\n * Resolves AI recording options by falling back to the client's `sendDefaultPii` setting.\n * Precedence: explicit option \u003e sendDefaultPii \u003e false\n */\nexport function resolveAIRecordingOptions\u003cT extends AIRecordingOptions\u003e(options?: T): T \u0026 Required\u003cAIRecordingOptions\u003e {\n  const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n  return {\n    ...options,\n    recordInputs: options?.recordInputs ?? sendDefaultPii,\n    recordOutputs: options?.recordOutputs ?? sendDefaultPii,\n  } as T \u0026 Required\u003cAIRecordingOptions\u003e;\n}\n\n/**\n * Maps AI method paths to OpenTelemetry semantic convention operation names\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#llm-request-spans\n */\nexport function getFinalOperationName(methodPath: string): string {\n  if (methodPath.includes('messages')) {\n    return 'chat';\n  }\n  if (methodPath.includes('completions')) {\n    return 'text_completion';\n  }\n  // Google GenAI: models.generateContent* -\u003e generate_content (actually generates AI responses)\n  if (methodPath.includes('generateContent')) {\n    return 'generate_content';\n  }\n  // Anthropic: models.get/retrieve -\u003e models (metadata retrieval only)\n  if (methodPath.includes('models')) {\n    return 'models';\n  }\n  if (methodPath.includes('chat')) {\n    return 'chat';\n  }\n  return methodPath.split('.').pop() || 'unknown';\n}\n\n/**\n * Get the span operation for AI methods\n * Following Sentry's convention: \"gen_ai.{operation_name}\"\n */\nexport function getSpanOperation(methodPath: string): string {\n  return `gen_ai.${getFinalOperationName(methodPath)}`;\n}\n\n/**\n * Build method path from current traversal\n */\nexport function buildMethodPath(currentPath: string, prop: string): string {\n  return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param cachedInputTokens - The number of cached input tokens\n * @param cachedOutputTokens - The number of cached output tokens\n */\nexport function setTokenUsageAttributes(\n  span: Span,\n  promptTokens?: number,\n  completionTokens?: number,\n  cachedInputTokens?: number,\n  cachedOutputTokens?: number,\n): void {\n  if (promptTokens !== undefined) {\n    span.setAttributes({\n      [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n    });\n  }\n  if (completionTokens !== undefined) {\n    span.setAttributes({\n      [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n    });\n  }\n  if (\n    promptTokens !== undefined ||\n    completionTokens !== undefined ||\n    cachedInputTokens !== undefined ||\n    cachedOutputTokens !== undefined\n  ) {\n    /**\n     * Total input tokens in a request is the summation of `input_tokens`,\n     * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n     */\n    const totalTokens =\n      (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0);\n\n    span.setAttributes({\n      [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n    });\n  }\n}\n\n/**\n * Get the truncated JSON string for a string or array of strings.\n *\n * @param value - The string or array of strings to truncate\n * @returns The truncated JSON string\n */\nexport function getTruncatedJsonString\u003cT\u003e(value: T | T[]): string {\n  if (typeof value === 'string') {\n    // Some values are already JSON strings, so we don't need to duplicate the JSON parsing\n    return truncateGenAiStringInput(value);\n  }\n  if (Array.isArray(value)) {\n    // truncateGenAiMessages returns an array of strings, so we need to stringify it\n    const truncatedMessages = truncateGenAiMessages(value);\n    return JSON.stringify(truncatedMessages);\n  }\n  // value is an object, so we need to stringify it\n  return JSON.stringify(value);\n}\n\n/**\n * Extract system instructions from messages array.\n * Finds the first system message and formats it according to OpenTelemetry semantic conventions.\n *\n * @param messages - Array of messages to extract system instructions from\n * @returns systemInstructions (JSON string) and filteredMessages (without system message)\n */\nexport function extractSystemInstructions(messages: unknown[] | unknown): {\n  systemInstructions: string | undefined;\n  filteredMessages: unknown[] | unknown;\n} {\n  if (!Array.isArray(messages)) {\n    return { systemInstructions: undefined, filteredMessages: messages };\n  }\n\n  const systemMessageIndex = messages.findIndex(\n    msg =\u003e msg \u0026\u0026 typeof msg === 'object' \u0026\u0026 'role' in msg \u0026\u0026 (msg as { role: string }).role === 'system',\n  );\n\n  if (systemMessageIndex === -1) {\n    return { systemInstructions: undefined, filteredMessages: messages };\n  }\n\n  const systemMessage = messages[systemMessageIndex] as { role: string; content?: string | unknown };\n  const systemContent =\n    typeof systemMessage.content === 'string'\n      ? systemMessage.content\n      : systemMessage.content !== undefined\n        ? JSON.stringify(systemMessage.content)\n        : undefined;\n\n  if (!systemContent) {\n    return { systemInstructions: undefined, filteredMessages: messages };\n  }\n\n  const systemInstructions = JSON.stringify([{ type: 'text', content: systemContent }]);\n  const filteredMessages = [...messages.slice(0, systemMessageIndex), ...messages.slice(systemMessageIndex + 1)];\n\n  return { systemInstructions, filteredMessages };\n}\n\n/**\n * Creates a wrapped version of .withResponse() that replaces the data field\n * with the instrumented result while preserving metadata (response, request_id).\n */\nasync function createWithResponseWrapper\u003cT\u003e(\n  originalWithResponse: Promise\u003cunknown\u003e,\n  instrumentedPromise: Promise\u003cT\u003e,\n  mechanismType: string,\n): Promise\u003cunknown\u003e {\n  // Attach catch handler to originalWithResponse immediately to prevent unhandled rejection\n  // If instrumentedPromise rejects first, we still need this handled\n  const safeOriginalWithResponse = originalWithResponse.catch(error =\u003e {\n    captureException(error, {\n      mechanism: {\n        handled: false,\n        type: mechanismType,\n      },\n    });\n    throw error;\n  });\n\n  const instrumentedResult = await instrumentedPromise;\n  const originalWrapper = await safeOriginalWithResponse;\n\n  // Combine instrumented result with original metadata\n  if (originalWrapper \u0026\u0026 typeof originalWrapper === 'object' \u0026\u0026 'data' in originalWrapper) {\n    return {\n      ...originalWrapper,\n      data: instrumentedResult,\n    };\n  }\n  return instrumentedResult;\n}\n\n/**\n * Wraps a promise-like object to preserve additional methods (like .withResponse())\n * that AI SDK clients (OpenAI, Anthropic) attach to their APIPromise return values.\n *\n * Standard Promise methods (.then, .catch, .finally) are routed to the instrumented\n * promise to preserve Sentry's span instrumentation, while custom SDK methods are\n * forwarded to the original promise to maintain the SDK's API surface.\n */\nexport function wrapPromiseWithMethods\u003cR\u003e(\n  originalPromiseLike: Promise\u003cR\u003e,\n  instrumentedPromise: Promise\u003cR\u003e,\n  mechanismType: string,\n): Promise\u003cR\u003e {\n  // If the original result is not thenable, return the instrumented promise\n  if (!isThenable(originalPromiseLike)) {\n    return instrumentedPromise;\n  }\n\n  // Create a proxy that forwards Promise methods to instrumentedPromise\n  // and preserves additional methods from the original result\n  return new Proxy(originalPromiseLike, {\n    get(target: object, prop: string | symbol): unknown {\n      // For standard Promise methods (.then, .catch, .finally, Symbol.toStringTag),\n      // use instrumentedPromise to preserve Sentry instrumentation.\n      // For custom methods (like .withResponse()), use the original target.\n      const useInstrumentedPromise = prop in Promise.prototype || prop === Symbol.toStringTag;\n      const source = useInstrumentedPromise ? instrumentedPromise : target;\n\n      const value = Reflect.get(source, prop) as unknown;\n\n      // Special handling for .withResponse() to preserve instrumentation\n      // .withResponse() returns { data: T, response: Response, request_id: string }\n      if (prop === 'withResponse' \u0026\u0026 typeof value === 'function') {\n        return function wrappedWithResponse(this: unknown): unknown {\n          const originalWithResponse = (value as (...args: unknown[]) =\u003e unknown).call(target);\n          return createWithResponseWrapper(originalWithResponse, instrumentedPromise, mechanismType);\n        };\n      }\n\n      return typeof value === 'function' ? value.bind(source) : value;\n    },\n  }) as Promise\u003cR\u003e;\n}\n","/* eslint-disable max-lines */\n/**\n * AI SDK Telemetry Attributes\n * Based on https://ai-sdk.dev/docs/ai-sdk-core/telemetry#collected-data\n */\n\n// =============================================================================\n// COMMON ATTRIBUTES\n// =============================================================================\n\n/**\n * Common attribute for operation name across all functions and spans\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#collected-data\n */\nexport const OPERATION_NAME_ATTRIBUTE = 'operation.name';\n\n/**\n * Common attribute for AI operation ID across all functions and spans\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#collected-data\n */\nexport const AI_OPERATION_ID_ATTRIBUTE = 'ai.operationId';\n\n// =============================================================================\n// SHARED ATTRIBUTES\n// =============================================================================\n\n/**\n * `generateText` function - `ai.generateText` span\n * `streamText` function - `ai.streamText` span\n *\n * The prompt that was used when calling the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_PROMPT_ATTRIBUTE = 'ai.prompt';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The JSON schema version of the schema that was passed into the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_SCHEMA_ATTRIBUTE = 'ai.schema';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The name of the schema that was passed into the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_SCHEMA_NAME_ATTRIBUTE = 'ai.schema.name';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The description of the schema that was passed into the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_SCHEMA_DESCRIPTION_ATTRIBUTE = 'ai.schema.description';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The object that was generated (stringified JSON)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_RESPONSE_OBJECT_ATTRIBUTE = 'ai.response.object';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The object generation mode, e.g. `json`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_SETTINGS_MODE_ATTRIBUTE = 'ai.settings.mode';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The output type that was used, e.g. `object` or `no-schema`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_SETTINGS_OUTPUT_ATTRIBUTE = 'ai.settings.output';\n\n/**\n * `embed` function - `ai.embed.doEmbed` span\n * `embedMany` function - `ai.embedMany` span\n *\n * The values that were passed into the function (array)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embedmany-function\n */\nexport const AI_VALUES_ATTRIBUTE = 'ai.values';\n\n/**\n * `embed` function - `ai.embed.doEmbed` span\n * `embedMany` function - `ai.embedMany` span\n *\n * An array of JSON-stringified embeddings\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embedmany-function\n */\nexport const AI_EMBEDDINGS_ATTRIBUTE = 'ai.embeddings';\n\n// =============================================================================\n// GENERATETEXT FUNCTION - UNIQUE ATTRIBUTES\n// =============================================================================\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The text that was generated\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_RESPONSE_TEXT_ATTRIBUTE = 'ai.response.text';\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The tool calls that were made as part of the generation (stringified JSON)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'ai.response.toolCalls';\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The reason why the generation finished\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_RESPONSE_FINISH_REASON_ATTRIBUTE = 'ai.response.finishReason';\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The maximum number of steps that were set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_SETTINGS_MAX_STEPS_ATTRIBUTE = 'ai.settings.maxSteps';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * The format of the prompt\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_PROMPT_FORMAT_ATTRIBUTE = 'ai.prompt.format';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * The messages that were passed into the provider\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_PROMPT_MESSAGES_ATTRIBUTE = 'ai.prompt.messages';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * Array of stringified tool definitions\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_PROMPT_TOOLS_ATTRIBUTE = 'ai.prompt.tools';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * The stringified tool choice setting (JSON)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_PROMPT_TOOL_CHOICE_ATTRIBUTE = 'ai.prompt.toolChoice';\n\n// =============================================================================\n// STREAMTEXT FUNCTION - UNIQUE ATTRIBUTES\n// =============================================================================\n\n/**\n * `streamText` function - `ai.streamText.doStream` span\n *\n * The time it took to receive the first chunk in milliseconds\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_RESPONSE_MS_TO_FIRST_CHUNK_ATTRIBUTE = 'ai.response.msToFirstChunk';\n\n/**\n * `streamText` function - `ai.streamText.doStream` span\n *\n * The time it took to receive the finish part of the LLM stream in milliseconds\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_RESPONSE_MS_TO_FINISH_ATTRIBUTE = 'ai.response.msToFinish';\n\n/**\n * `streamText` function - `ai.streamText.doStream` span\n *\n * The average completion tokens per second\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_RESPONSE_AVG_COMPLETION_TOKENS_PER_SECOND_ATTRIBUTE = 'ai.response.avgCompletionTokensPerSecond';\n\n// =============================================================================\n// EMBED FUNCTION - UNIQUE ATTRIBUTES\n// =============================================================================\n\n/**\n * `embed` function - `ai.embed` span\n *\n * The value that was passed into the `embed` function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n */\nexport const AI_VALUE_ATTRIBUTE = 'ai.value';\n\n/**\n * `embed` function - `ai.embed` span\n *\n * A JSON-stringified embedding\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n */\nexport const AI_EMBEDDING_ATTRIBUTE = 'ai.embedding';\n\n// =============================================================================\n// BASIC LLM SPAN INFORMATION\n// =============================================================================\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The functionId that was set through `telemetry.functionId`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const RESOURCE_NAME_ATTRIBUTE = 'resource.name';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The id of the model\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_MODEL_ID_ATTRIBUTE = 'ai.model.id';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The provider of the model\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_MODEL_PROVIDER_ATTRIBUTE = 'ai.model.provider';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The request headers that were passed in through `headers`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_REQUEST_HEADERS_ATTRIBUTE = 'ai.request.headers';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * Provider specific metadata returned with the generation response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE = 'ai.response.providerMetadata';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The maximum number of retries that were set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'ai.settings.maxRetries';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of cached input tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE = 'ai.usage.cachedInputTokens';\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The functionId that was set through `telemetry.functionId`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE = 'ai.telemetry.functionId';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The metadata that was passed in through `telemetry.metadata`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_TELEMETRY_METADATA_ATTRIBUTE = 'ai.telemetry.metadata';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of completion tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = 'ai.usage.completionTokens';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of prompt tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nexport const AI_USAGE_PROMPT_TOKENS_ATTRIBUTE = 'ai.usage.promptTokens';\n\n// =============================================================================\n// CALL LLM SPAN INFORMATION\n// =============================================================================\n\n/**\n * Call LLM span information\n * Individual LLM call spans\n *\n * The model that was used to generate the response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const AI_RESPONSE_MODEL_ATTRIBUTE = 'ai.response.model';\n\n/**\n * Call LLM span information\n * Individual LLM call spans\n *\n * The id of the response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const AI_RESPONSE_ID_ATTRIBUTE = 'ai.response.id';\n\n/**\n * Call LLM span information\n * Individual LLM call spans\n *\n * The timestamp of the response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const AI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'ai.response.timestamp';\n\n// =============================================================================\n// SEMANTIC CONVENTIONS FOR GENAI OPERATIONS\n// =============================================================================\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The provider that was used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The model that was requested\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The temperature that was set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The maximum number of tokens that were set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The frequency penalty that was set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The presence penalty that was set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The topK parameter value that was set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The topP parameter value that was set\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The stop sequences\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE = 'gen_ai.request.stop_sequences';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The finish reasons that were returned by the provider\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The model that was used to generate the response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The id of the response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The number of prompt tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * Semantic Conventions for GenAI operations\n * Individual LLM call spans\n *\n * The number of completion tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#call-llm-span-information\n */\nexport const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n// =============================================================================\n// BASIC EMBEDDING SPAN INFORMATION\n// =============================================================================\n\n/**\n * Basic embedding span information\n * Embedding spans\n *\n * The number of tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-embedding-span-information\n */\nexport const AI_USAGE_TOKENS_ATTRIBUTE = 'ai.usage.tokens';\n\n// =============================================================================\n// TOOL CALL SPANS\n// =============================================================================\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The name of the tool\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nexport const AI_TOOL_CALL_NAME_ATTRIBUTE = 'ai.toolCall.name';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The id of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nexport const AI_TOOL_CALL_ID_ATTRIBUTE = 'ai.toolCall.id';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The parameters of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nexport const AI_TOOL_CALL_ARGS_ATTRIBUTE = 'ai.toolCall.args';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The result of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nexport const AI_TOOL_CALL_RESULT_ATTRIBUTE = 'ai.toolCall.result';\n\n// =============================================================================\n// SPAN ATTRIBUTE OBJECTS\n// =============================================================================\n\n/**\n * Attributes collected for `ai.generateText` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_GENERATE_TEXT_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_PROMPT: AI_PROMPT_ATTRIBUTE,\n  AI_RESPONSE_TEXT: AI_RESPONSE_TEXT_ATTRIBUTE,\n  AI_RESPONSE_TOOL_CALLS: AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  AI_RESPONSE_FINISH_REASON: AI_RESPONSE_FINISH_REASON_ATTRIBUTE,\n  AI_SETTINGS_MAX_STEPS: AI_SETTINGS_MAX_STEPS_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.generateText.doGenerate` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nexport const AI_GENERATE_TEXT_DO_GENERATE_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_PROMPT_FORMAT: AI_PROMPT_FORMAT_ATTRIBUTE,\n  AI_PROMPT_MESSAGES: AI_PROMPT_MESSAGES_ATTRIBUTE,\n  AI_PROMPT_TOOLS: AI_PROMPT_TOOLS_ATTRIBUTE,\n  AI_PROMPT_TOOL_CHOICE: AI_PROMPT_TOOL_CHOICE_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n  // Call LLM span information\n  AI_RESPONSE_MODEL: AI_RESPONSE_MODEL_ATTRIBUTE,\n  AI_RESPONSE_ID: AI_RESPONSE_ID_ATTRIBUTE,\n  AI_RESPONSE_TIMESTAMP: AI_RESPONSE_TIMESTAMP_ATTRIBUTE,\n  // Semantic Conventions for GenAI operations\n  GEN_AI_SYSTEM: GEN_AI_SYSTEM_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL: GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE: GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_MAX_TOKENS: GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY: GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_PRESENCE_PENALTY: GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_K: GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P: GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_REQUEST_STOP_SEQUENCES: GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE,\n  GEN_AI_RESPONSE_FINISH_REASONS: GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL: GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID: GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS: GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS: GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.streamText` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_STREAM_TEXT_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_PROMPT: AI_PROMPT_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.streamText.doStream` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nexport const AI_STREAM_TEXT_DO_STREAM_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_RESPONSE_MS_TO_FIRST_CHUNK: AI_RESPONSE_MS_TO_FIRST_CHUNK_ATTRIBUTE,\n  AI_RESPONSE_MS_TO_FINISH: AI_RESPONSE_MS_TO_FINISH_ATTRIBUTE,\n  AI_RESPONSE_AVG_COMPLETION_TOKENS_PER_SECOND: AI_RESPONSE_AVG_COMPLETION_TOKENS_PER_SECOND_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n  // Call LLM span information\n  AI_RESPONSE_MODEL: AI_RESPONSE_MODEL_ATTRIBUTE,\n  AI_RESPONSE_ID: AI_RESPONSE_ID_ATTRIBUTE,\n  AI_RESPONSE_TIMESTAMP: AI_RESPONSE_TIMESTAMP_ATTRIBUTE,\n  // Semantic Conventions for GenAI operations\n  GEN_AI_SYSTEM: GEN_AI_SYSTEM_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL: GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE: GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_MAX_TOKENS: GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY: GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_PRESENCE_PENALTY: GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_K: GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P: GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_REQUEST_STOP_SEQUENCES: GEN_AI_REQUEST_STOP_SEQUENCES_ATTRIBUTE,\n  GEN_AI_RESPONSE_FINISH_REASONS: GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL: GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID: GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS: GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS: GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.generateObject` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n */\nexport const AI_GENERATE_OBJECT_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_SCHEMA: AI_SCHEMA_ATTRIBUTE,\n  AI_SCHEMA_NAME: AI_SCHEMA_NAME_ATTRIBUTE,\n  AI_SCHEMA_DESCRIPTION: AI_SCHEMA_DESCRIPTION_ATTRIBUTE,\n  AI_RESPONSE_OBJECT: AI_RESPONSE_OBJECT_ATTRIBUTE,\n  AI_SETTINGS_MODE: AI_SETTINGS_MODE_ATTRIBUTE,\n  AI_SETTINGS_OUTPUT: AI_SETTINGS_OUTPUT_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.streamObject` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nexport const AI_STREAM_OBJECT_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_SCHEMA: AI_SCHEMA_ATTRIBUTE,\n  AI_SCHEMA_NAME: AI_SCHEMA_NAME_ATTRIBUTE,\n  AI_SCHEMA_DESCRIPTION: AI_SCHEMA_DESCRIPTION_ATTRIBUTE,\n  AI_RESPONSE_OBJECT: AI_RESPONSE_OBJECT_ATTRIBUTE,\n  AI_SETTINGS_MODE: AI_SETTINGS_MODE_ATTRIBUTE,\n  AI_SETTINGS_OUTPUT: AI_SETTINGS_OUTPUT_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS: AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS: AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.embed` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n */\nexport const AI_EMBED_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_VALUE: AI_VALUE_ATTRIBUTE,\n  AI_EMBEDDING: AI_EMBEDDING_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  // Basic embedding span information\n  AI_USAGE_TOKENS: AI_USAGE_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.embed.doEmbed` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embed-function\n */\nexport const AI_EMBED_DO_EMBED_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_VALUES: AI_VALUES_ATTRIBUTE,\n  AI_EMBEDDINGS: AI_EMBEDDINGS_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  // Basic embedding span information\n  AI_USAGE_TOKENS: AI_USAGE_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.embedMany` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#embedmany-function\n */\nexport const AI_EMBED_MANY_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_VALUES: AI_VALUES_ATTRIBUTE,\n  AI_EMBEDDINGS: AI_EMBEDDINGS_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n  // Basic embedding span information\n  AI_USAGE_TOKENS: AI_USAGE_TOKENS_ATTRIBUTE,\n} as const;\n\n/**\n * Attributes collected for `ai.toolCall` span\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nexport const AI_TOOL_CALL_SPAN_ATTRIBUTES = {\n  OPERATION_NAME: OPERATION_NAME_ATTRIBUTE,\n  AI_OPERATION_ID: AI_OPERATION_ID_ATTRIBUTE,\n  AI_TOOL_CALL_NAME: AI_TOOL_CALL_NAME_ATTRIBUTE,\n  AI_TOOL_CALL_ID: AI_TOOL_CALL_ID_ATTRIBUTE,\n  AI_TOOL_CALL_ARGS: AI_TOOL_CALL_ARGS_ATTRIBUTE,\n  AI_TOOL_CALL_RESULT: AI_TOOL_CALL_RESULT_ATTRIBUTE,\n  // Basic LLM span information\n  RESOURCE_NAME: RESOURCE_NAME_ATTRIBUTE,\n  AI_MODEL_ID: AI_MODEL_ID_ATTRIBUTE,\n  AI_MODEL_PROVIDER: AI_MODEL_PROVIDER_ATTRIBUTE,\n  AI_REQUEST_HEADERS: AI_REQUEST_HEADERS_ATTRIBUTE,\n  AI_SETTINGS_MAX_RETRIES: AI_SETTINGS_MAX_RETRIES_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID: AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TELEMETRY_METADATA: AI_TELEMETRY_METADATA_ATTRIBUTE,\n} as const;\n\n// =============================================================================\n// PROVIDER METADATA\n// =============================================================================\n\n/**\n * OpenAI Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/openai/src/openai-chat-language-model.ts#L397-L416\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/openai/src/responses/openai-responses-language-model.ts#L377C7-L384\n */\nexport interface OpenAiProviderMetadata {\n  /**\n   * The number of predicted output tokens that were accepted.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai#predicted-outputs\n   */\n  acceptedPredictionTokens?: number;\n\n  /**\n   * The number of predicted output tokens that were rejected.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai#predicted-outputs\n   */\n  rejectedPredictionTokens?: number;\n\n  /**\n   * The number of reasoning tokens that the model generated.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai#responses-models\n   */\n  reasoningTokens?: number;\n\n  /**\n   * The number of prompt tokens that were a cache hit.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai#responses-models\n   */\n  cachedPromptTokens?: number;\n\n  /**\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai#responses-models\n   *\n   * The ID of the response. Can be used to continue a conversation.\n   */\n  responseId?: string;\n}\n\n/**\n * Anthropic Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/anthropic\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/anthropic/src/anthropic-messages-language-model.ts#L346-L352\n */\ninterface AnthropicProviderMetadata {\n  /**\n   * The number of tokens that were used to create the cache.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#cache-control\n   */\n  cacheCreationInputTokens?: number;\n\n  /**\n   * The number of tokens that were read from the cache.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#cache-control\n   */\n  cacheReadInputTokens?: number;\n\n  /**\n   * Usage metrics for the Anthropic model.\n   */\n  usage?: {\n    input_tokens: number;\n    cache_creation_input_tokens?: number;\n    cache_read_input_tokens?: number;\n    cache_creation?: {\n      ephemeral_5m_input_tokens?: number;\n      ephemeral_1h_input_tokens?: number;\n    };\n    output_tokens?: number;\n    service_tier?: string;\n  };\n}\n\n/**\n * Amazon Bedrock Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/amazon-bedrock/src/bedrock-chat-language-model.ts#L263-L280\n */\ninterface AmazonBedrockProviderMetadata {\n  /**\n   * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseTrace.html\n   */\n  trace?: {\n    /**\n     * The guardrail trace object.\n     * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailTraceAssessment.html\n     *\n     * This was purposely left as unknown as it's a complex object. This can be typed in the future\n     * if the SDK decides to support bedrock in a more advanced way.\n     */\n    guardrail?: unknown;\n    /**\n     * The request's prompt router.\n     * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_PromptRouterTrace.html\n     */\n    promptRouter?: {\n      /**\n       * The ID of the invoked model.\n       */\n      invokedModelId?: string;\n    };\n  };\n  usage?: {\n    /**\n     * The number of tokens that were read from the cache.\n     * @see https://ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock#cache-points\n     */\n    cacheReadInputTokens?: number;\n\n    /**\n     * The number of tokens that were written to the cache.\n     * @see https://ai-sdk.dev/providers/ai-sdk-providers/amazon-bedrock#cache-points\n     */\n    cacheWriteInputTokens?: number;\n  };\n}\n\n/**\n * Google Generative AI Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai\n */\nexport interface GoogleGenerativeAIProviderMetadata {\n  /**\n   * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/google/src/google-generative-ai-prompt.ts#L28-L30\n   */\n  groundingMetadata: null | {\n    /**\n     * Array of search queries used to retrieve information\n     * @example [\"What's the weather in Chicago this weekend?\"]\n     *\n     * @see https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai#search-grounding\n     */\n    webSearchQueries: string[] | null;\n    /**\n     * Contains the main search result content used as an entry point\n     * The `renderedContent` field contains the formatted content\n     * @see https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai#search-grounding\n     */\n    searchEntryPoint?: {\n      renderedContent: string;\n    } | null;\n    /**\n     * Contains details about how specific response parts are supported by search results\n     * @see https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai#search-grounding\n     */\n    groundingSupports: Array\u003c{\n      /**\n       * Information about the grounded text segment.\n       */\n      segment: {\n        /**\n         * The start index of the text segment.\n         */\n        startIndex?: number | null;\n        /**\n         * The end index of the text segment.\n         */\n        endIndex?: number | null;\n        /**\n         * The actual text segment.\n         */\n        text?: string | null;\n      };\n      /**\n       * References to supporting search result chunks.\n       */\n      groundingChunkIndices?: number[] | null;\n      /**\n       * Confidence scores (0-1) for each supporting chunk.\n       */\n      confidenceScores?: number[] | null;\n    }\u003e | null;\n  };\n  /**\n   * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/google/src/google-generative-ai-language-model.ts#L620-L627\n   * @see https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-filters\n   */\n  safetyRatings?: null | unknown;\n}\n\n/**\n * DeepSeek Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/deepseek\n */\ninterface DeepSeekProviderMetadata {\n  /**\n   * The number of tokens that were cache hits.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/deepseek#cache-token-usage\n   */\n  promptCacheHitTokens?: number;\n\n  /**\n   * The number of tokens that were cache misses.\n   * @see https://ai-sdk.dev/providers/ai-sdk-providers/deepseek#cache-token-usage\n   */\n  promptCacheMissTokens?: number;\n}\n\n/**\n * Perplexity Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/perplexity\n */\ninterface PerplexityProviderMetadata {\n  /**\n   * Object containing citationTokens and numSearchQueries metrics\n   */\n  usage?: {\n    citationTokens?: number;\n    numSearchQueries?: number;\n  };\n  /**\n   * Array of image URLs when return_images is enabled.\n   *\n   * You can enable image responses by setting return_images: true in the provider options.\n   * This feature is only available to Perplexity Tier-2 users and above.\n   */\n  images?: Array\u003c{\n    imageUrl?: string;\n    originUrl?: string;\n    height?: number;\n    width?: number;\n  }\u003e;\n}\n\nexport interface ProviderMetadata {\n  openai?: OpenAiProviderMetadata;\n  azure?: OpenAiProviderMetadata; // v6: Azure Responses API uses 'azure' key instead of 'openai'\n  anthropic?: AnthropicProviderMetadata;\n  bedrock?: AmazonBedrockProviderMetadata;\n  google?: GoogleGenerativeAIProviderMetadata;\n  vertex?: GoogleGenerativeAIProviderMetadata; // v6: Google Vertex uses 'vertex' key instead of 'google'\n  deepseek?: DeepSeekProviderMetadata;\n  perplexity?: PerplexityProviderMetadata;\n}\n","import type { TraceContext } from '../../types-hoist/context';\nimport type { Span, SpanAttributes, SpanJSON } from '../../types-hoist/span';\nimport {\n  GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE,\n  GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE,\n  GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE,\n  GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE,\n  GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,\n  GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE,\n  GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n  GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE,\n  GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n  GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE,\n  GEN_AI_TOOL_NAME_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';\nimport { toolCallSpanContextMap } from './constants';\nimport type { TokenSummary, ToolCallSpanContext } from './types';\nimport { AI_PROMPT_ATTRIBUTE, AI_PROMPT_MESSAGES_ATTRIBUTE } from './vercel-ai-attributes';\n\n/**\n * Accumulates token data from a span to its parent in the token accumulator map.\n * This function extracts token usage from the current span and adds it to the\n * accumulated totals for its parent span.\n */\nexport function accumulateTokensForParent(span: SpanJSON, tokenAccumulator: Map\u003cstring, TokenSummary\u003e): void {\n  const parentSpanId = span.parent_span_id;\n  if (!parentSpanId) {\n    return;\n  }\n\n  const inputTokens = span.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];\n  const outputTokens = span.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE];\n\n  if (typeof inputTokens === 'number' || typeof outputTokens === 'number') {\n    const existing = tokenAccumulator.get(parentSpanId) || { inputTokens: 0, outputTokens: 0 };\n\n    if (typeof inputTokens === 'number') {\n      existing.inputTokens += inputTokens;\n    }\n    if (typeof outputTokens === 'number') {\n      existing.outputTokens += outputTokens;\n    }\n\n    tokenAccumulator.set(parentSpanId, existing);\n  }\n}\n\n/**\n * Applies accumulated token data to the `gen_ai.invoke_agent` span.\n * Only immediate children of the `gen_ai.invoke_agent` span are considered,\n * since aggregation will automatically occur for each parent span.\n */\nexport function applyAccumulatedTokens(\n  spanOrTrace: SpanJSON | TraceContext,\n  tokenAccumulator: Map\u003cstring, TokenSummary\u003e,\n): void {\n  const accumulated = tokenAccumulator.get(spanOrTrace.span_id);\n  if (!accumulated || !spanOrTrace.data) {\n    return;\n  }\n\n  if (accumulated.inputTokens \u003e 0) {\n    spanOrTrace.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = accumulated.inputTokens;\n  }\n  if (accumulated.outputTokens \u003e 0) {\n    spanOrTrace.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = accumulated.outputTokens;\n  }\n  if (accumulated.inputTokens \u003e 0 || accumulated.outputTokens \u003e 0) {\n    spanOrTrace.data['gen_ai.usage.total_tokens'] = accumulated.inputTokens + accumulated.outputTokens;\n  }\n}\n\n/**\n * Builds a map of tool name -\u003e description from all spans with available_tools.\n * This avoids O(n²) iteration and repeated JSON parsing.\n */\nfunction buildToolDescriptionMap(spans: SpanJSON[]): Map\u003cstring, string\u003e {\n  const toolDescriptions = new Map\u003cstring, string\u003e();\n\n  for (const span of spans) {\n    const availableTools = span.data[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE];\n    if (typeof availableTools !== 'string') {\n      continue;\n    }\n    try {\n      const tools = JSON.parse(availableTools) as Array\u003c{ name?: string; description?: string }\u003e;\n      for (const tool of tools) {\n        if (tool.name \u0026\u0026 tool.description \u0026\u0026 !toolDescriptions.has(tool.name)) {\n          toolDescriptions.set(tool.name, tool.description);\n        }\n      }\n    } catch {\n      // ignore parse errors\n    }\n  }\n\n  return toolDescriptions;\n}\n\n/**\n * Applies tool descriptions and accumulated tokens to spans in a single pass.\n *\n * - For `gen_ai.execute_tool` spans: looks up tool description from\n *   `gen_ai.request.available_tools` on sibling spans\n * - For `gen_ai.invoke_agent` spans: applies accumulated token data from children\n */\nexport function applyToolDescriptionsAndTokens(spans: SpanJSON[], tokenAccumulator: Map\u003cstring, TokenSummary\u003e): void {\n  // Build lookup map once to avoid O(n²) iteration and repeated JSON parsing\n  const toolDescriptions = buildToolDescriptionMap(spans);\n\n  for (const span of spans) {\n    if (span.op === 'gen_ai.execute_tool') {\n      const toolName = span.data[GEN_AI_TOOL_NAME_ATTRIBUTE];\n      if (typeof toolName === 'string') {\n        const description = toolDescriptions.get(toolName);\n        if (description) {\n          span.data[GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE] = description;\n        }\n      }\n    }\n\n    if (span.op === 'gen_ai.invoke_agent') {\n      applyAccumulatedTokens(span, tokenAccumulator);\n    }\n  }\n}\n\n/**\n * Get the span context associated with a tool call ID.\n */\nexport function _INTERNAL_getSpanContextForToolCallId(toolCallId: string): ToolCallSpanContext | undefined {\n  return toolCallSpanContextMap.get(toolCallId);\n}\n\n/**\n * Clean up the span mapping for a tool call ID\n */\nexport function _INTERNAL_cleanupToolCallSpanContext(toolCallId: string): void {\n  toolCallSpanContextMap.delete(toolCallId);\n}\n\n/**\n * Convert an array of tool strings to a JSON string\n */\nexport function convertAvailableToolsToJsonString(tools: unknown[]): string {\n  const toolObjects = tools.map(tool =\u003e {\n    if (typeof tool === 'string') {\n      try {\n        return JSON.parse(tool);\n      } catch {\n        return tool;\n      }\n    }\n    return tool;\n  });\n  return JSON.stringify(toolObjects);\n}\n\n/**\n * Filter out invalid entries in messages array\n * @param input - The input array to filter\n * @returns The filtered array\n */\nfunction filterMessagesArray(input: unknown[]): { role: string; content: string }[] {\n  return input.filter(\n    (m: unknown): m is { role: string; content: string } =\u003e\n      !!m \u0026\u0026 typeof m === 'object' \u0026\u0026 'role' in m \u0026\u0026 'content' in m,\n  );\n}\n\n/**\n * Normalize the user input (stringified object with prompt, system, messages) to messages array\n */\nexport function convertUserInputToMessagesFormat(userInput: string): { role: string; content: string }[] {\n  try {\n    const p = JSON.parse(userInput);\n    if (!!p \u0026\u0026 typeof p === 'object') {\n      let { messages } = p;\n      const { prompt, system } = p;\n      const result: { role: string; content: string }[] = [];\n\n      // prepend top-level system instruction if present\n      if (typeof system === 'string') {\n        result.push({ role: 'system', content: system });\n      }\n\n      // stringified messages array\n      if (typeof messages === 'string') {\n        try {\n          messages = JSON.parse(messages);\n        } catch {\n          // ignore parse errors\n        }\n      }\n\n      // messages array format: { messages: [...] }\n      if (Array.isArray(messages)) {\n        result.push(...filterMessagesArray(messages));\n        return result;\n      }\n\n      // prompt array format: { prompt: [...] }\n      if (Array.isArray(prompt)) {\n        result.push(...filterMessagesArray(prompt));\n        return result;\n      }\n\n      // prompt string format: { prompt: \"...\" }\n      if (typeof prompt === 'string') {\n        result.push({ role: 'user', content: prompt });\n      }\n\n      if (result.length \u003e 0) {\n        return result;\n      }\n    }\n    // eslint-disable-next-line no-empty\n  } catch {}\n  return [];\n}\n\n/**\n * Generate a request.messages JSON array from the prompt field in the\n * invoke_agent op\n */\nexport function requestMessagesFromPrompt(span: Span, attributes: SpanAttributes): void {\n  if (\n    typeof attributes[AI_PROMPT_ATTRIBUTE] === 'string' \u0026\u0026\n    !attributes[GEN_AI_INPUT_MESSAGES_ATTRIBUTE] \u0026\u0026\n    !attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]\n  ) {\n    // No messages array is present, so we need to convert the prompt to the proper messages format\n    // This is the case for ai.generateText spans\n    // The ai.prompt attribute is a stringified object with prompt, system, messages attributes\n    // The format of these is described in the vercel docs, for instance: https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-object#parameters\n    const userInput = attributes[AI_PROMPT_ATTRIBUTE];\n    const messages = convertUserInputToMessagesFormat(userInput);\n    if (messages.length) {\n      const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n      if (systemInstructions) {\n        span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n      }\n\n      const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;\n      const truncatedMessages = getTruncatedJsonString(filteredMessages);\n\n      span.setAttributes({\n        [AI_PROMPT_ATTRIBUTE]: truncatedMessages,\n        [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: truncatedMessages,\n        [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n      });\n    }\n  } else if (typeof attributes[AI_PROMPT_MESSAGES_ATTRIBUTE] === 'string') {\n    // In this case we already get a properly formatted messages array, this is the preferred way to get the messages\n    // This is the case for ai.generateText.doGenerate spans\n    try {\n      const messages = JSON.parse(attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]);\n      if (Array.isArray(messages)) {\n        const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n        if (systemInstructions) {\n          span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n        }\n\n        const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;\n        const truncatedMessages = getTruncatedJsonString(filteredMessages);\n\n        span.setAttributes({\n          [AI_PROMPT_MESSAGES_ATTRIBUTE]: truncatedMessages,\n          [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: truncatedMessages,\n          [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n        });\n      }\n      // eslint-disable-next-line no-empty\n    } catch {}\n  }\n}\n\n/**\n * Maps a Vercel AI span name to the corresponding Sentry op.\n */\nexport function getSpanOpFromName(name: string): string | undefined {\n  switch (name) {\n    case 'ai.generateText':\n    case 'ai.streamText':\n    case 'ai.generateObject':\n    case 'ai.streamObject':\n      return GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE;\n    case 'ai.generateText.doGenerate':\n      return GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE;\n    case 'ai.streamText.doStream':\n      return GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE;\n    case 'ai.generateObject.doGenerate':\n      return GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE;\n    case 'ai.streamObject.doStream':\n      return GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE;\n    case 'ai.embed.doEmbed':\n      return GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE;\n    case 'ai.embedMany.doEmbed':\n      return GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE;\n    case 'ai.rerank.doRerank':\n      return GEN_AI_RERANK_DO_RERANK_OPERATION_ATTRIBUTE;\n    case 'ai.toolCall':\n      return GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE;\n    default:\n      if (name.startsWith('ai.stream')) {\n        return 'ai.run';\n      }\n      return undefined;\n  }\n}\n","/* eslint-disable max-lines */\nimport type { Client } from '../../client';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport type { Event } from '../../types-hoist/event';\nimport type { Span, SpanAttributes, SpanAttributeValue, SpanJSON } from '../../types-hoist/span';\nimport { spanToJSON } from '../../utils/spanUtils';\nimport {\n  GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_TOOL_CALL_ID_ATTRIBUTE,\n  GEN_AI_TOOL_INPUT_ATTRIBUTE,\n  GEN_AI_TOOL_NAME_ATTRIBUTE,\n  GEN_AI_TOOL_OUTPUT_ATTRIBUTE,\n  GEN_AI_TOOL_TYPE_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport {\n  DO_SPAN_NAME_PREFIX,\n  EMBEDDINGS_OPS,\n  GENERATE_CONTENT_OPS,\n  INVOKE_AGENT_OPS,\n  RERANK_OPS,\n  toolCallSpanContextMap,\n} from './constants';\nimport type { TokenSummary } from './types';\nimport {\n  accumulateTokensForParent,\n  applyAccumulatedTokens,\n  applyToolDescriptionsAndTokens,\n  convertAvailableToolsToJsonString,\n  getSpanOpFromName,\n  requestMessagesFromPrompt,\n} from './utils';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\nimport {\n  AI_MODEL_ID_ATTRIBUTE,\n  AI_OPERATION_ID_ATTRIBUTE,\n  AI_PROMPT_MESSAGES_ATTRIBUTE,\n  AI_PROMPT_TOOLS_ATTRIBUTE,\n  AI_RESPONSE_FINISH_REASON_ATTRIBUTE,\n  AI_RESPONSE_OBJECT_ATTRIBUTE,\n  AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE,\n  AI_RESPONSE_TEXT_ATTRIBUTE,\n  AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  AI_SCHEMA_ATTRIBUTE,\n  AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE,\n  AI_TOOL_CALL_ARGS_ATTRIBUTE,\n  AI_TOOL_CALL_ID_ATTRIBUTE,\n  AI_TOOL_CALL_NAME_ATTRIBUTE,\n  AI_TOOL_CALL_RESULT_ATTRIBUTE,\n  AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE,\n  AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  AI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n  AI_USAGE_TOKENS_ATTRIBUTE,\n  AI_VALUES_ATTRIBUTE,\n  OPERATION_NAME_ATTRIBUTE,\n} from './vercel-ai-attributes';\n\n/**\n * Maps Vercel AI SDK operation names to OpenTelemetry semantic convention values\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#llm-request-spans\n */\nfunction mapVercelAiOperationName(operationName: string): string {\n  // Top-level pipeline operations map to invoke_agent\n  if (INVOKE_AGENT_OPS.has(operationName)) {\n    return 'invoke_agent';\n  }\n  // .do* operations are the actual LLM calls\n  if (GENERATE_CONTENT_OPS.has(operationName)) {\n    return 'generate_content';\n  }\n  if (EMBEDDINGS_OPS.has(operationName)) {\n    return 'embeddings';\n  }\n  if (RERANK_OPS.has(operationName)) {\n    return 'rerank';\n  }\n  if (operationName === 'ai.toolCall') {\n    return 'execute_tool';\n  }\n  // Return the original value for unknown operations\n  return operationName;\n}\n\n/**\n * Post-process spans emitted by the Vercel AI SDK.\n * This is supposed to be used in `client.on('spanStart', ...)\n */\nfunction onVercelAiSpanStart(span: Span): void {\n  const { data: attributes, description: name } = spanToJSON(span);\n\n  if (!name) {\n    return;\n  }\n\n  // Tool call spans\n  // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n  if (attributes[AI_TOOL_CALL_NAME_ATTRIBUTE] \u0026\u0026 attributes[AI_TOOL_CALL_ID_ATTRIBUTE] \u0026\u0026 name === 'ai.toolCall') {\n    processToolCallSpan(span, attributes);\n    return;\n  }\n\n  // V6+ Check if this is a Vercel AI span by checking if the operation ID attribute is present.\n  // V5+ Check if this is a Vercel AI span by name pattern.\n  if (!attributes[AI_OPERATION_ID_ATTRIBUTE] \u0026\u0026 !name.startsWith('ai.')) {\n    return;\n  }\n\n  processGenerateSpan(span, name, attributes);\n}\n\nfunction vercelAiEventProcessor(event: Event): Event {\n  if (event.type === 'transaction' \u0026\u0026 event.spans) {\n    // Map to accumulate token data by parent span ID\n    const tokenAccumulator: Map\u003cstring, TokenSummary\u003e = new Map();\n\n    // First pass: process all spans and accumulate token data\n    for (const span of event.spans) {\n      processEndedVercelAiSpan(span);\n\n      // Accumulate token data for parent spans\n      accumulateTokensForParent(span, tokenAccumulator);\n    }\n\n    // Second pass: apply tool descriptions and accumulated tokens\n    applyToolDescriptionsAndTokens(event.spans, tokenAccumulator);\n\n    // Also apply to root when it is the invoke_agent pipeline\n    const trace = event.contexts?.trace;\n    if (trace?.op === 'gen_ai.invoke_agent') {\n      applyAccumulatedTokens(trace, tokenAccumulator);\n    }\n  }\n\n  return event;\n}\n\n/**\n * Tool call structure from Vercel AI SDK\n * Note: V5/V6 use 'input' for arguments, V4 and earlier use 'args'\n */\ninterface VercelToolCall {\n  toolCallId: string;\n  toolName: string;\n  input?: Record\u003cstring, unknown\u003e | string; // V5/V6\n  args?: string; // V4 and earlier\n}\n\n/**\n * Normalize finish reason to match OpenTelemetry semantic conventions.\n * Valid values: \"stop\", \"length\", \"content_filter\", \"tool_call\", \"error\"\n *\n * Vercel AI SDK uses \"tool-calls\" (plural, with hyphen) which we map to \"tool_call\".\n */\nfunction normalizeFinishReason(finishReason: unknown): string {\n  if (typeof finishReason !== 'string') {\n    return 'stop';\n  }\n\n  // Map Vercel AI SDK finish reasons to OpenTelemetry semantic convention values\n  switch (finishReason) {\n    case 'tool-calls':\n      return 'tool_call';\n    case 'stop':\n    case 'length':\n    case 'content_filter':\n    case 'error':\n      return finishReason;\n    default:\n      // For unknown values, return as-is (schema allows arbitrary strings)\n      return finishReason;\n  }\n}\n\n/**\n * Build gen_ai.output.messages from ai.response.text and/or ai.response.toolCalls\n *\n * Format follows OpenTelemetry semantic conventions:\n * [{\"role\": \"assistant\", \"parts\": [...], \"finish_reason\": \"stop\"}]\n *\n * Parts can be:\n * - {\"type\": \"text\", \"content\": \"...\"}\n * - {\"type\": \"tool_call\", \"id\": \"...\", \"name\": \"...\", \"arguments\": \"...\"}\n */\nfunction buildOutputMessages(attributes: Record\u003cstring, unknown\u003e): void {\n  const responseText = attributes[AI_RESPONSE_TEXT_ATTRIBUTE];\n  const responseToolCalls = attributes[AI_RESPONSE_TOOL_CALLS_ATTRIBUTE];\n  const finishReason = attributes[AI_RESPONSE_FINISH_REASON_ATTRIBUTE];\n\n  // Skip if neither text nor tool calls are present\n  if (responseText == null \u0026\u0026 responseToolCalls == null) {\n    return;\n  }\n\n  const parts: Array\u003cRecord\u003cstring, unknown\u003e\u003e = [];\n\n  // Add text part if present\n  if (typeof responseText === 'string' \u0026\u0026 responseText.length \u003e 0) {\n    parts.push({\n      type: 'text',\n      content: responseText,\n    });\n  }\n\n  // Add tool call parts if present\n  if (responseToolCalls != null) {\n    try {\n      // Tool calls can be a string (JSON) or already parsed array\n      const toolCalls: VercelToolCall[] =\n        typeof responseToolCalls === 'string' ? JSON.parse(responseToolCalls) : responseToolCalls;\n\n      if (Array.isArray(toolCalls)) {\n        for (const toolCall of toolCalls) {\n          // V5/V6 use 'input', V4 and earlier use 'args'\n          const args = toolCall.input ?? toolCall.args;\n          parts.push({\n            type: 'tool_call',\n            id: toolCall.toolCallId,\n            name: toolCall.toolName,\n            // Handle undefined args: JSON.stringify(undefined) returns undefined, not a string,\n            // which would cause the property to be omitted from the final JSON output\n            arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {}),\n          });\n        }\n        // Only delete tool calls attribute if we successfully processed them\n        // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n        delete attributes[AI_RESPONSE_TOOL_CALLS_ATTRIBUTE];\n      }\n    } catch {\n      // Ignore parsing errors - tool calls attribute is preserved\n    }\n  }\n\n  // Only set output messages and delete text attribute if we have parts\n  if (parts.length \u003e 0) {\n    const outputMessage = {\n      role: 'assistant',\n      parts,\n      finish_reason: normalizeFinishReason(finishReason),\n    };\n\n    attributes[GEN_AI_OUTPUT_MESSAGES_ATTRIBUTE] = JSON.stringify([outputMessage]);\n\n    // Remove the text attribute since it's now captured in gen_ai.output.messages\n    // Note: tool calls attribute is deleted above only if successfully parsed\n    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n    delete attributes[AI_RESPONSE_TEXT_ATTRIBUTE];\n  }\n}\n\n/**\n * Post-process spans emitted by the Vercel AI SDK.\n */\nfunction processEndedVercelAiSpan(span: SpanJSON): void {\n  const { data: attributes, origin } = span;\n\n  if (origin !== 'auto.vercelai.otel') {\n    return;\n  }\n\n  // The Vercel AI SDK sets span status to raw error message strings.\n  // Any such value should be normalized to a SpanStatusType value. We pick internal_error as it is the most generic.\n  if (span.status \u0026\u0026 span.status !== 'ok') {\n    span.status = 'internal_error';\n  }\n\n  renameAttributeKey(attributes, AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE);\n  renameAttributeKey(attributes, AI_USAGE_PROMPT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE);\n  renameAttributeKey(attributes, AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE);\n\n  // Parent spans (ai.streamText, ai.streamObject, etc.) use inputTokens/outputTokens instead of promptTokens/completionTokens\n  renameAttributeKey(attributes, 'ai.usage.inputTokens', GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE);\n  renameAttributeKey(attributes, 'ai.usage.outputTokens', GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE);\n\n  // Embedding spans use ai.usage.tokens instead of promptTokens/completionTokens\n  renameAttributeKey(attributes, AI_USAGE_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE);\n\n  // AI SDK uses avgOutputTokensPerSecond, map to our expected attribute name\n  renameAttributeKey(attributes, 'ai.response.avgOutputTokensPerSecond', 'ai.response.avgCompletionTokensPerSecond');\n\n  // Input tokens is the sum of prompt tokens and cached input tokens\n  if (\n    typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === 'number' \u0026\u0026\n    typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE] === 'number'\n  ) {\n    attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] =\n      attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] + attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE];\n  }\n\n  // Compute total tokens from input + output (embeddings may only have input tokens)\n  if (typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === 'number') {\n    const outputTokens =\n      typeof attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] === 'number'\n        ? attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]\n        : 0;\n    attributes[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = outputTokens + attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];\n  }\n\n  // Convert the available tools array to a JSON string\n  if (attributes[AI_PROMPT_TOOLS_ATTRIBUTE] \u0026\u0026 Array.isArray(attributes[AI_PROMPT_TOOLS_ATTRIBUTE])) {\n    attributes[AI_PROMPT_TOOLS_ATTRIBUTE] = convertAvailableToolsToJsonString(\n      attributes[AI_PROMPT_TOOLS_ATTRIBUTE] as unknown[],\n    );\n  }\n\n  // Rename AI SDK attributes to standardized gen_ai attributes\n  // Map operation.name to OpenTelemetry semantic convention values\n  if (attributes[OPERATION_NAME_ATTRIBUTE]) {\n    const operationName = mapVercelAiOperationName(attributes[OPERATION_NAME_ATTRIBUTE] as string);\n    attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE] = operationName;\n    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n    delete attributes[OPERATION_NAME_ATTRIBUTE];\n  }\n  renameAttributeKey(attributes, AI_PROMPT_MESSAGES_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE);\n\n  // Build gen_ai.output.messages from response text and/or tool calls\n  // Note: buildOutputMessages also removes the source attributes when output is successfully generated\n  buildOutputMessages(attributes);\n\n  renameAttributeKey(attributes, AI_RESPONSE_OBJECT_ATTRIBUTE, 'gen_ai.response.object');\n  renameAttributeKey(attributes, AI_PROMPT_TOOLS_ATTRIBUTE, 'gen_ai.request.available_tools');\n\n  renameAttributeKey(attributes, AI_TOOL_CALL_ARGS_ATTRIBUTE, GEN_AI_TOOL_INPUT_ATTRIBUTE);\n  renameAttributeKey(attributes, AI_TOOL_CALL_RESULT_ATTRIBUTE, GEN_AI_TOOL_OUTPUT_ATTRIBUTE);\n\n  renameAttributeKey(attributes, AI_SCHEMA_ATTRIBUTE, 'gen_ai.request.schema');\n  renameAttributeKey(attributes, AI_MODEL_ID_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE);\n\n  // Map embedding input: ai.values → gen_ai.embeddings.input\n  // Vercel AI SDK JSON-stringifies each value individually, so we parse each element back.\n  // Single embed gets unwrapped to a plain value; batch embedMany stays as a JSON array.\n  if (Array.isArray(attributes[AI_VALUES_ATTRIBUTE])) {\n    const parsed = (attributes[AI_VALUES_ATTRIBUTE] as string[]).map(v =\u003e {\n      try {\n        return JSON.parse(v);\n      } catch {\n        return v;\n      }\n    });\n    attributes[GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE] = parsed.length === 1 ? parsed[0] : JSON.stringify(parsed);\n  }\n\n  addProviderMetadataToAttributes(attributes);\n\n  // Change attributes namespaced with `ai.X` to `vercel.ai.X`\n  for (const key of Object.keys(attributes)) {\n    if (key.startsWith('ai.')) {\n      renameAttributeKey(attributes, key, `vercel.${key}`);\n    }\n  }\n}\n\n/**\n * Renames an attribute key in the provided attributes object if the old key exists.\n * This function safely handles null and undefined values.\n */\nfunction renameAttributeKey(attributes: Record\u003cstring, unknown\u003e, oldKey: string, newKey: string): void {\n  if (attributes[oldKey] != null) {\n    attributes[newKey] = attributes[oldKey];\n    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n    delete attributes[oldKey];\n  }\n}\n\nfunction processToolCallSpan(span: Span, attributes: SpanAttributes): void {\n  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.vercelai.otel');\n  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.execute_tool');\n  span.setAttribute(GEN_AI_OPERATION_NAME_ATTRIBUTE, 'execute_tool');\n  renameAttributeKey(attributes, AI_TOOL_CALL_NAME_ATTRIBUTE, GEN_AI_TOOL_NAME_ATTRIBUTE);\n  renameAttributeKey(attributes, AI_TOOL_CALL_ID_ATTRIBUTE, GEN_AI_TOOL_CALL_ID_ATTRIBUTE);\n\n  // Store the span context in our global map using the tool call ID.\n  // This allows us to capture tool errors and link them to the correct span\n  // without retaining the full Span object in memory.\n  const toolCallId = attributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE];\n\n  if (typeof toolCallId === 'string') {\n    toolCallSpanContextMap.set(toolCallId, span.spanContext());\n  }\n\n  // https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-type\n  if (!attributes[GEN_AI_TOOL_TYPE_ATTRIBUTE]) {\n    span.setAttribute(GEN_AI_TOOL_TYPE_ATTRIBUTE, 'function');\n  }\n  const toolName = attributes[GEN_AI_TOOL_NAME_ATTRIBUTE];\n  if (toolName) {\n    span.updateName(`execute_tool ${toolName}`);\n  }\n}\n\nfunction processGenerateSpan(span: Span, name: string, attributes: SpanAttributes): void {\n  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.vercelai.otel');\n\n  const nameWthoutAi = name.replace('ai.', '');\n  span.setAttribute('ai.pipeline.name', nameWthoutAi);\n  span.updateName(nameWthoutAi);\n\n  const functionId = attributes[AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE];\n  if (functionId \u0026\u0026 typeof functionId === 'string') {\n    span.setAttribute('gen_ai.function_id', functionId);\n  }\n\n  requestMessagesFromPrompt(span, attributes);\n\n  if (attributes[AI_MODEL_ID_ATTRIBUTE] \u0026\u0026 !attributes[GEN_AI_RESPONSE_MODEL_ATTRIBUTE]) {\n    span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, attributes[AI_MODEL_ID_ATTRIBUTE]);\n  }\n  span.setAttribute('ai.streaming', name.includes('stream'));\n\n  // Set the op based on the span name\n  const op = getSpanOpFromName(name);\n  if (op) {\n    span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op);\n  }\n\n  // For invoke_agent pipeline spans, use 'invoke_agent' as the description\n  // to be consistent with other AI integrations (e.g. LangGraph)\n  if (INVOKE_AGENT_OPS.has(name)) {\n    if (functionId \u0026\u0026 typeof functionId === 'string') {\n      span.updateName(`invoke_agent ${functionId}`);\n    } else {\n      span.updateName('invoke_agent');\n    }\n    return;\n  }\n\n  const modelId = attributes[AI_MODEL_ID_ATTRIBUTE];\n  if (modelId) {\n    const doSpanPrefix = GENERATE_CONTENT_OPS.has(name) ? 'generate_content' : DO_SPAN_NAME_PREFIX[name];\n    if (doSpanPrefix) {\n      span.updateName(`${doSpanPrefix} ${modelId}`);\n    }\n  }\n}\n\n/**\n * Add event processors to the given client to process Vercel AI spans.\n */\nexport function addVercelAiProcessors(client: Client): void {\n  client.on('spanStart', onVercelAiSpanStart);\n  // Note: We cannot do this on `spanEnd`, because the span cannot be mutated anymore at this point\n  client.addEventProcessor(Object.assign(vercelAiEventProcessor, { id: 'VercelAiEventProcessor' }));\n}\n\nfunction addProviderMetadataToAttributes(attributes: SpanAttributes): void {\n  const providerMetadata = attributes[AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE] as string | undefined;\n  if (providerMetadata) {\n    try {\n      const providerMetadataObject = JSON.parse(providerMetadata) as ProviderMetadata;\n\n      // Handle OpenAI metadata (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n      const openaiMetadata: OpenAiProviderMetadata | undefined =\n        providerMetadataObject.openai ?? providerMetadataObject.azure;\n      if (openaiMetadata) {\n        setAttributeIfDefined(\n          attributes,\n          GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n          openaiMetadata.cachedPromptTokens,\n        );\n        setAttributeIfDefined(attributes, 'gen_ai.usage.output_tokens.reasoning', openaiMetadata.reasoningTokens);\n        setAttributeIfDefined(\n          attributes,\n          'gen_ai.usage.output_tokens.prediction_accepted',\n          openaiMetadata.acceptedPredictionTokens,\n        );\n        setAttributeIfDefined(\n          attributes,\n          'gen_ai.usage.output_tokens.prediction_rejected',\n          openaiMetadata.rejectedPredictionTokens,\n        );\n        if (!attributes['gen_ai.conversation.id']) {\n          setAttributeIfDefined(attributes, 'gen_ai.conversation.id', openaiMetadata.responseId);\n        }\n      }\n\n      if (providerMetadataObject.anthropic) {\n        const cachedInputTokens =\n          providerMetadataObject.anthropic.usage?.cache_read_input_tokens ??\n          providerMetadataObject.anthropic.cacheReadInputTokens;\n        setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, cachedInputTokens);\n\n        const cacheWriteInputTokens =\n          providerMetadataObject.anthropic.usage?.cache_creation_input_tokens ??\n          providerMetadataObject.anthropic.cacheCreationInputTokens;\n        setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, cacheWriteInputTokens);\n      }\n\n      if (providerMetadataObject.bedrock?.usage) {\n        setAttributeIfDefined(\n          attributes,\n          GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n          providerMetadataObject.bedrock.usage.cacheReadInputTokens,\n        );\n        setAttributeIfDefined(\n          attributes,\n          GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE,\n          providerMetadataObject.bedrock.usage.cacheWriteInputTokens,\n        );\n      }\n\n      if (providerMetadataObject.deepseek) {\n        setAttributeIfDefined(\n          attributes,\n          GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n          providerMetadataObject.deepseek.promptCacheHitTokens,\n        );\n        setAttributeIfDefined(\n          attributes,\n          'gen_ai.usage.input_tokens.cache_miss',\n          providerMetadataObject.deepseek.promptCacheMissTokens,\n        );\n      }\n    } catch {\n      // Ignore\n    }\n  }\n}\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(attributes: SpanAttributes, key: string, value: SpanAttributeValue | undefined): void {\n  if (value != null) {\n    attributes[key] = value;\n  }\n}\n","export const OPENAI_INTEGRATION_NAME = 'OpenAI';\n\n// https://platform.openai.com/docs/quickstart?api-mode=responses\n// https://platform.openai.com/docs/quickstart?api-mode=chat\n// https://platform.openai.com/docs/api-reference/conversations\nexport const INSTRUMENTED_METHODS = [\n  'responses.create',\n  'chat.completions.create',\n  'embeddings.create',\n  // Conversations API - for conversation state management\n  // https://platform.openai.com/docs/guides/conversation-state\n  'conversations.create',\n] as const;\nexport const RESPONSES_TOOL_CALL_EVENT_TYPES = [\n  'response.output_item.added',\n  'response.function_call_arguments.delta',\n  'response.function_call_arguments.done',\n  'response.output_item.done',\n] as const;\nexport const RESPONSE_EVENT_TYPES = [\n  'response.created',\n  'response.in_progress',\n  'response.failed',\n  'response.completed',\n  'response.incomplete',\n  'response.queued',\n  'response.output_text.delta',\n  ...RESPONSES_TOOL_CALL_EVENT_TYPES,\n] as const;\n","import type { Span } from '../../types-hoist/span';\nimport {\n  GEN_AI_CONVERSATION_ID_ATTRIBUTE,\n  GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE,\n  GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n  OPENAI_OPERATIONS,\n  OPENAI_RESPONSE_ID_ATTRIBUTE,\n  OPENAI_RESPONSE_MODEL_ATTRIBUTE,\n  OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE,\n  OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE,\n  OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { INSTRUMENTED_METHODS } from './constants';\nimport type {\n  ChatCompletionChunk,\n  InstrumentedMethod,\n  OpenAiChatCompletionObject,\n  OpenAIConversationObject,\n  OpenAICreateEmbeddingsObject,\n  OpenAIResponseObject,\n  ResponseStreamingEvent,\n} from './types';\n\n/**\n * Maps OpenAI method paths to OpenTelemetry semantic convention operation names\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#llm-request-spans\n */\nexport function getOperationName(methodPath: string): string {\n  if (methodPath.includes('chat.completions')) {\n    return OPENAI_OPERATIONS.CHAT;\n  }\n  if (methodPath.includes('responses')) {\n    return OPENAI_OPERATIONS.CHAT;\n  }\n  if (methodPath.includes('embeddings')) {\n    return OPENAI_OPERATIONS.EMBEDDINGS;\n  }\n  if (methodPath.includes('conversations')) {\n    return OPENAI_OPERATIONS.CHAT;\n  }\n  return methodPath.split('.').pop() || 'unknown';\n}\n\n/**\n * Get the span operation for OpenAI methods\n * Following Sentry's convention: \"gen_ai.{operation_name}\"\n */\nexport function getSpanOperation(methodPath: string): string {\n  return `gen_ai.${getOperationName(methodPath)}`;\n}\n\n/**\n * Check if a method path should be instrumented\n */\nexport function shouldInstrument(methodPath: string): methodPath is InstrumentedMethod {\n  return INSTRUMENTED_METHODS.includes(methodPath as InstrumentedMethod);\n}\n\n/**\n * Check if response is a Chat Completion object\n */\nexport function isChatCompletionResponse(response: unknown): response is OpenAiChatCompletionObject {\n  return (\n    response !== null \u0026\u0026\n    typeof response === 'object' \u0026\u0026\n    'object' in response \u0026\u0026\n    (response as Record\u003cstring, unknown\u003e).object === 'chat.completion'\n  );\n}\n\n/**\n * Check if response is a Responses API object\n */\nexport function isResponsesApiResponse(response: unknown): response is OpenAIResponseObject {\n  return (\n    response !== null \u0026\u0026\n    typeof response === 'object' \u0026\u0026\n    'object' in response \u0026\u0026\n    (response as Record\u003cstring, unknown\u003e).object === 'response'\n  );\n}\n\n/**\n * Check if response is an Embeddings API object\n */\nexport function isEmbeddingsResponse(response: unknown): response is OpenAICreateEmbeddingsObject {\n  if (response === null || typeof response !== 'object' || !('object' in response)) {\n    return false;\n  }\n  const responseObject = response as Record\u003cstring, unknown\u003e;\n  return (\n    responseObject.object === 'list' \u0026\u0026\n    typeof responseObject.model === 'string' \u0026\u0026\n    responseObject.model.toLowerCase().includes('embedding')\n  );\n}\n\n/**\n * Check if response is a Conversations API object\n * @see https://platform.openai.com/docs/api-reference/conversations\n */\nexport function isConversationResponse(response: unknown): response is OpenAIConversationObject {\n  return (\n    response !== null \u0026\u0026\n    typeof response === 'object' \u0026\u0026\n    'object' in response \u0026\u0026\n    (response as Record\u003cstring, unknown\u003e).object === 'conversation'\n  );\n}\n\n/**\n * Check if streaming event is from the Responses API\n */\nexport function isResponsesApiStreamEvent(event: unknown): event is ResponseStreamingEvent {\n  return (\n    event !== null \u0026\u0026\n    typeof event === 'object' \u0026\u0026\n    'type' in event \u0026\u0026\n    typeof (event as Record\u003cstring, unknown\u003e).type === 'string' \u0026\u0026\n    ((event as Record\u003cstring, unknown\u003e).type as string).startsWith('response.')\n  );\n}\n\n/**\n * Check if streaming event is a chat completion chunk\n */\nexport function isChatCompletionChunk(event: unknown): event is ChatCompletionChunk {\n  return (\n    event !== null \u0026\u0026\n    typeof event === 'object' \u0026\u0026\n    'object' in event \u0026\u0026\n    (event as Record\u003cstring, unknown\u003e).object === 'chat.completion.chunk'\n  );\n}\n\n/**\n * Add attributes for Chat Completion responses\n */\nexport function addChatCompletionAttributes(\n  span: Span,\n  response: OpenAiChatCompletionObject,\n  recordOutputs?: boolean,\n): void {\n  setCommonResponseAttributes(span, response.id, response.model, response.created);\n  if (response.usage) {\n    setTokenUsageAttributes(\n      span,\n      response.usage.prompt_tokens,\n      response.usage.completion_tokens,\n      response.usage.total_tokens,\n    );\n  }\n  if (Array.isArray(response.choices)) {\n    const finishReasons = response.choices\n      .map(choice =\u003e choice.finish_reason)\n      .filter((reason): reason is string =\u003e reason !== null);\n    if (finishReasons.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(finishReasons),\n      });\n    }\n\n    // Extract tool calls from all choices (only if recordOutputs is true)\n    if (recordOutputs) {\n      const toolCalls = response.choices\n        .map(choice =\u003e choice.message?.tool_calls)\n        .filter(calls =\u003e Array.isArray(calls) \u0026\u0026 calls.length \u003e 0)\n        .flat();\n\n      if (toolCalls.length \u003e 0) {\n        span.setAttributes({\n          [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls),\n        });\n      }\n    }\n  }\n}\n\n/**\n * Add attributes for Responses API responses\n */\nexport function addResponsesApiAttributes(span: Span, response: OpenAIResponseObject, recordOutputs?: boolean): void {\n  setCommonResponseAttributes(span, response.id, response.model, response.created_at);\n  if (response.status) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify([response.status]),\n    });\n  }\n  if (response.usage) {\n    setTokenUsageAttributes(\n      span,\n      response.usage.input_tokens,\n      response.usage.output_tokens,\n      response.usage.total_tokens,\n    );\n  }\n\n  // Extract function calls from output (only if recordOutputs is true)\n  if (recordOutputs) {\n    const responseWithOutput = response as OpenAIResponseObject \u0026 { output?: unknown[] };\n    if (Array.isArray(responseWithOutput.output) \u0026\u0026 responseWithOutput.output.length \u003e 0) {\n      // Filter for function_call type objects in the output array\n      const functionCalls = responseWithOutput.output.filter(\n        (item): unknown =\u003e\n          // oxlint-disable-next-line typescript/prefer-optional-chain\n          typeof item === 'object' \u0026\u0026 item !== null \u0026\u0026 (item as Record\u003cstring, unknown\u003e).type === 'function_call',\n      );\n\n      if (functionCalls.length \u003e 0) {\n        span.setAttributes({\n          [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls),\n        });\n      }\n    }\n  }\n}\n\n/**\n * Add attributes for Embeddings API responses\n */\nexport function addEmbeddingsAttributes(span: Span, response: OpenAICreateEmbeddingsObject): void {\n  span.setAttributes({\n    [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n    [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n  });\n\n  if (response.usage) {\n    setTokenUsageAttributes(span, response.usage.prompt_tokens, undefined, response.usage.total_tokens);\n  }\n}\n\n/**\n * Add attributes for Conversations API responses\n * @see https://platform.openai.com/docs/api-reference/conversations\n */\nexport function addConversationAttributes(span: Span, response: OpenAIConversationObject): void {\n  const { id, created_at } = response;\n\n  span.setAttributes({\n    [OPENAI_RESPONSE_ID_ATTRIBUTE]: id,\n    [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id,\n    // The conversation id is used to link messages across API calls\n    [GEN_AI_CONVERSATION_ID_ATTRIBUTE]: id,\n  });\n\n  if (created_at) {\n    span.setAttributes({\n      [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(created_at * 1000).toISOString(),\n    });\n  }\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param totalTokens - The number of total tokens\n */\nexport function setTokenUsageAttributes(\n  span: Span,\n  promptTokens?: number,\n  completionTokens?: number,\n  totalTokens?: number,\n): void {\n  if (promptTokens !== undefined) {\n    span.setAttributes({\n      [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: promptTokens,\n      [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n    });\n  }\n  if (completionTokens !== undefined) {\n    span.setAttributes({\n      [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: completionTokens,\n      [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n    });\n  }\n  if (totalTokens !== undefined) {\n    span.setAttributes({\n      [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n    });\n  }\n}\n\n/**\n * Set common response attributes\n * @param span - The span to add attributes to\n * @param id - The response id\n * @param model - The response model\n * @param timestamp - The response timestamp\n */\nexport function setCommonResponseAttributes(span: Span, id: string, model: string, timestamp: number): void {\n  span.setAttributes({\n    [OPENAI_RESPONSE_ID_ATTRIBUTE]: id,\n    [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id,\n  });\n  span.setAttributes({\n    [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: model,\n    [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: model,\n  });\n  span.setAttributes({\n    [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(timestamp * 1000).toISOString(),\n  });\n}\n\n/**\n * Extract conversation ID from request parameters\n * Supports both Conversations API and previous_response_id chaining\n * @see https://platform.openai.com/docs/guides/conversation-state\n */\nfunction extractConversationId(params: Record\u003cstring, unknown\u003e): string | undefined {\n  // Conversations API: conversation parameter (e.g., \"conv_...\")\n  if ('conversation' in params \u0026\u0026 typeof params.conversation === 'string') {\n    return params.conversation;\n  }\n  // Responses chaining: previous_response_id links to parent response\n  if ('previous_response_id' in params \u0026\u0026 typeof params.previous_response_id === 'string') {\n    return params.previous_response_id;\n  }\n  return undefined;\n}\n\n/**\n * Extract request parameters including model settings and conversation context\n */\nexport function extractRequestParameters(params: Record\u003cstring, unknown\u003e): Record\u003cstring, unknown\u003e {\n  const attributes: Record\u003cstring, unknown\u003e = {\n    [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: params.model ?? 'unknown',\n  };\n\n  if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n  if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n  if ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n  if ('presence_penalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = params.presence_penalty;\n  if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n  if ('encoding_format' in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format;\n  if ('dimensions' in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions;\n\n  // Capture conversation ID for linking messages across API calls\n  const conversationId = extractConversationId(params);\n  if (conversationId) {\n    attributes[GEN_AI_CONVERSATION_ID_ATTRIBUTE] = conversationId;\n  }\n\n  return attributes;\n}\n","import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { RESPONSE_EVENT_TYPES } from './constants';\nimport type {\n  ChatCompletionChunk,\n  ChatCompletionToolCall,\n  OpenAIResponseObject,\n  ResponseFunctionCall,\n  ResponseStreamingEvent,\n} from './types';\nimport {\n  isChatCompletionChunk,\n  isResponsesApiStreamEvent,\n  setCommonResponseAttributes,\n  setTokenUsageAttributes,\n} from './utils';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\ninterface StreamingState {\n  /** Types of events encountered in the stream. */\n  eventTypes: string[];\n  /** Collected response text fragments (for output recording). */\n  responseTexts: string[];\n  /** Reasons for finishing the response, as reported by the API. */\n  finishReasons: string[];\n  /** The response ID. */\n  responseId: string;\n  /** The model name. */\n  responseModel: string;\n  /** The timestamp of the response. */\n  responseTimestamp: number;\n  /** Number of prompt/input tokens used. */\n  promptTokens: number | undefined;\n  /** Number of completion/output tokens used. */\n  completionTokens: number | undefined;\n  /** Total number of tokens used (prompt + completion). */\n  totalTokens: number | undefined;\n  /**\n   * Accumulated tool calls from Chat Completion streaming, indexed by tool call index.\n   * @see https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming\n   */\n  chatCompletionToolCalls: Record\u003cnumber, ChatCompletionToolCall\u003e;\n  /**\n   * Accumulated function calls from Responses API streaming.\n   * @see https://platform.openai.com/docs/guides/function-calling?api-mode=responses#streaming\n   */\n  responsesApiToolCalls: Array\u003cResponseFunctionCall | unknown\u003e;\n}\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n *  @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls: ChatCompletionToolCall[], state: StreamingState): void {\n  for (const toolCall of toolCalls) {\n    const index = toolCall.index;\n    if (index === undefined || !toolCall.function) continue;\n\n    // Initialize tool call if this is the first chunk for this index\n    if (!(index in state.chatCompletionToolCalls)) {\n      state.chatCompletionToolCalls[index] = {\n        ...toolCall,\n        function: {\n          name: toolCall.function.name,\n          arguments: toolCall.function.arguments || '',\n        },\n      };\n    } else {\n      // Accumulate function arguments from subsequent chunks\n      const existingToolCall = state.chatCompletionToolCalls[index];\n      if (toolCall.function.arguments \u0026\u0026 existingToolCall?.function) {\n        existingToolCall.function.arguments += toolCall.function.arguments;\n      }\n    }\n  }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk: ChatCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n  state.responseId = chunk.id ?? state.responseId;\n  state.responseModel = chunk.model ?? state.responseModel;\n  state.responseTimestamp = chunk.created ?? state.responseTimestamp;\n\n  if (chunk.usage) {\n    // For stream responses, the input tokens remain constant across all events in the stream.\n    // Output tokens, however, are only finalized in the last event.\n    // Since we can't guarantee that the last event will include usage data or even be a typed event,\n    // we update the output token values on every event that includes them.\n    // This ensures that output token usage is always set, even if the final event lacks it.\n    state.promptTokens = chunk.usage.prompt_tokens;\n    state.completionTokens = chunk.usage.completion_tokens;\n    state.totalTokens = chunk.usage.total_tokens;\n  }\n\n  for (const choice of chunk.choices ?? []) {\n    if (recordOutputs) {\n      if (choice.delta?.content) {\n        state.responseTexts.push(choice.delta.content);\n      }\n\n      // Handle tool calls from delta\n      if (choice.delta?.tool_calls) {\n        processChatCompletionToolCalls(choice.delta.tool_calls, state);\n      }\n    }\n    if (choice.finish_reason) {\n      state.finishReasons.push(choice.finish_reason);\n    }\n  }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n  streamEvent: ResponseStreamingEvent | unknown | Error,\n  state: StreamingState,\n  recordOutputs: boolean,\n  span: Span,\n): void {\n  if (!(streamEvent \u0026\u0026 typeof streamEvent === 'object')) {\n    state.eventTypes.push('unknown:non-object');\n    return;\n  }\n  if (streamEvent instanceof Error) {\n    span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n    captureException(streamEvent, {\n      mechanism: {\n        handled: false,\n        type: 'auto.ai.openai.stream-response',\n      },\n    });\n    return;\n  }\n\n  if (!('type' in streamEvent)) return;\n  const event = streamEvent as ResponseStreamingEvent;\n\n  if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n    state.eventTypes.push(event.type);\n    return;\n  }\n\n  // Handle output text delta\n  if (recordOutputs) {\n    // Handle tool call events for Responses API\n    if (event.type === 'response.output_item.done' \u0026\u0026 'item' in event) {\n      state.responsesApiToolCalls.push(event.item);\n    }\n\n    if (event.type === 'response.output_text.delta' \u0026\u0026 'delta' in event \u0026\u0026 event.delta) {\n      state.responseTexts.push(event.delta);\n      return;\n    }\n  }\n\n  if ('response' in event) {\n    const { response } = event as { response: OpenAIResponseObject };\n    state.responseId = response.id ?? state.responseId;\n    state.responseModel = response.model ?? state.responseModel;\n    state.responseTimestamp = response.created_at ?? state.responseTimestamp;\n\n    if (response.usage) {\n      // For stream responses, the input tokens remain constant across all events in the stream.\n      // Output tokens, however, are only finalized in the last event.\n      // Since we can't guarantee that the last event will include usage data or even be a typed event,\n      // we update the output token values on every event that includes them.\n      // This ensures that output token usage is always set, even if the final event lacks it.\n      state.promptTokens = response.usage.input_tokens;\n      state.completionTokens = response.usage.output_tokens;\n      state.totalTokens = response.usage.total_tokens;\n    }\n\n    if (response.status) {\n      state.finishReasons.push(response.status);\n    }\n\n    if (recordOutputs \u0026\u0026 response.output_text) {\n      state.responseTexts.push(response.output_text);\n    }\n  }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @returns An async generator yielding each event from the input stream.\n */\nexport async function* instrumentStream\u003cT\u003e(\n  stream: AsyncIterable\u003cT\u003e,\n  span: Span,\n  recordOutputs: boolean,\n): AsyncGenerator\u003cT, void, unknown\u003e {\n  const state: StreamingState = {\n    eventTypes: [],\n    responseTexts: [],\n    finishReasons: [],\n    responseId: '',\n    responseModel: '',\n    responseTimestamp: 0,\n    promptTokens: undefined,\n    completionTokens: undefined,\n    totalTokens: undefined,\n    chatCompletionToolCalls: {},\n    responsesApiToolCalls: [],\n  };\n\n  try {\n    for await (const event of stream) {\n      if (isChatCompletionChunk(event)) {\n        processChatCompletionChunk(event as ChatCompletionChunk, state, recordOutputs);\n      } else if (isResponsesApiStreamEvent(event)) {\n        processResponsesApiEvent(event as ResponseStreamingEvent, state, recordOutputs, span);\n      }\n      yield event;\n    }\n  } finally {\n    setCommonResponseAttributes(span, state.responseId, state.responseModel, state.responseTimestamp);\n    setTokenUsageAttributes(span, state.promptTokens, state.completionTokens, state.totalTokens);\n\n    span.setAttributes({\n      [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n    });\n\n    if (state.finishReasons.length) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n      });\n    }\n\n    if (recordOutputs \u0026\u0026 state.responseTexts.length) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n      });\n    }\n\n    // Set tool calls attribute if any were accumulated\n    const chatCompletionToolCallsArray = Object.values(state.chatCompletionToolCalls);\n    const allToolCalls = [...chatCompletionToolCallsArray, ...state.responsesApiToolCalls];\n\n    if (allToolCalls.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(allToolCalls),\n      });\n    }\n\n    span.end();\n  }\n}\n","import { DEBUG_BUILD } from '../../debug-build';\nimport { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpan, startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport { debug } from '../../utils/debug-logger';\nimport {\n  GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_SYSTEM_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n  OPENAI_OPERATIONS,\n} from '../ai/gen-ai-attributes';\nimport {\n  extractSystemInstructions,\n  getTruncatedJsonString,\n  resolveAIRecordingOptions,\n  wrapPromiseWithMethods,\n  buildMethodPath,\n} from '../ai/utils';\nimport { instrumentStream } from './streaming';\nimport type {\n  ChatCompletionChunk,\n  InstrumentedMethod,\n  OpenAiOptions,\n  OpenAiResponse,\n  OpenAIStream,\n  ResponseStreamingEvent,\n} from './types';\nimport {\n  addChatCompletionAttributes,\n  addConversationAttributes,\n  addEmbeddingsAttributes,\n  addResponsesApiAttributes,\n  extractRequestParameters,\n  getOperationName,\n  getSpanOperation,\n  isChatCompletionResponse,\n  isConversationResponse,\n  isEmbeddingsResponse,\n  isResponsesApiResponse,\n  shouldInstrument,\n} from './utils';\n\n/**\n * Extract available tools from request parameters\n */\nfunction extractAvailableTools(params: Record\u003cstring, unknown\u003e): string | undefined {\n  const tools = Array.isArray(params.tools) ? params.tools : [];\n  const hasWebSearchOptions = params.web_search_options \u0026\u0026 typeof params.web_search_options === 'object';\n  const webSearchOptions = hasWebSearchOptions\n    ? [{ type: 'web_search_options', ...(params.web_search_options as Record\u003cstring, unknown\u003e) }]\n    : [];\n\n  const availableTools = [...tools, ...webSearchOptions];\n  if (availableTools.length === 0) {\n    return undefined;\n  }\n\n  try {\n    return JSON.stringify(availableTools);\n  } catch (error) {\n    DEBUG_BUILD \u0026\u0026 debug.error('Failed to serialize OpenAI tools:', error);\n    return undefined;\n  }\n}\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args: unknown[], methodPath: string): Record\u003cstring, unknown\u003e {\n  const attributes: Record\u003cstring, unknown\u003e = {\n    [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',\n    [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getOperationName(methodPath),\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.openai',\n  };\n\n  if (args.length \u003e 0 \u0026\u0026 typeof args[0] === 'object' \u0026\u0026 args[0] !== null) {\n    const params = args[0] as Record\u003cstring, unknown\u003e;\n\n    const availableTools = extractAvailableTools(params);\n    if (availableTools) {\n      attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = availableTools;\n    }\n\n    Object.assign(attributes, extractRequestParameters(params));\n  } else {\n    attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n  }\n\n  return attributes;\n}\n\n/**\n * Add response attributes to spans\n * This supports Chat Completion, Responses API, Embeddings, and Conversations API responses\n */\nfunction addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void {\n  if (!result || typeof result !== 'object') return;\n\n  const response = result as OpenAiResponse;\n\n  if (isChatCompletionResponse(response)) {\n    addChatCompletionAttributes(span, response, recordOutputs);\n    if (recordOutputs \u0026\u0026 response.choices?.length) {\n      const responseTexts = response.choices.map(choice =\u003e choice.message?.content || '');\n      span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(responseTexts) });\n    }\n  } else if (isResponsesApiResponse(response)) {\n    addResponsesApiAttributes(span, response, recordOutputs);\n    if (recordOutputs \u0026\u0026 response.output_text) {\n      span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.output_text });\n    }\n  } else if (isEmbeddingsResponse(response)) {\n    addEmbeddingsAttributes(span, response);\n  } else if (isConversationResponse(response)) {\n    addConversationAttributes(span, response);\n  }\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nfunction addRequestAttributes(span: Span, params: Record\u003cstring, unknown\u003e, operationName: string): void {\n  // Store embeddings input on a separate attribute and do not truncate it\n  if (operationName === OPENAI_OPERATIONS.EMBEDDINGS \u0026\u0026 'input' in params) {\n    const input = params.input;\n\n    // No input provided\n    if (input == null) {\n      return;\n    }\n\n    // Empty input string\n    if (typeof input === 'string' \u0026\u0026 input.length === 0) {\n      return;\n    }\n\n    // Empty array input\n    if (Array.isArray(input) \u0026\u0026 input.length === 0) {\n      return;\n    }\n\n    // Store strings as-is, arrays/objects as JSON\n    span.setAttribute(GEN_AI_EMBEDDINGS_INPUT_ATTRIBUTE, typeof input === 'string' ? input : JSON.stringify(input));\n    return;\n  }\n\n  const src = 'input' in params ? params.input : 'messages' in params ? params.messages : undefined;\n\n  if (!src) {\n    return;\n  }\n\n  if (Array.isArray(src) \u0026\u0026 src.length === 0) {\n    return;\n  }\n\n  const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n\n  if (systemInstructions) {\n    span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n  }\n\n  const truncatedInput = getTruncatedJsonString(filteredMessages);\n  span.setAttribute(GEN_AI_INPUT_MESSAGES_ATTRIBUTE, truncatedInput);\n\n  if (Array.isArray(filteredMessages)) {\n    span.setAttribute(GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, filteredMessages.length);\n  } else {\n    span.setAttribute(GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, 1);\n  }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod\u003cT extends unknown[], R\u003e(\n  originalMethod: (...args: T) =\u003e Promise\u003cR\u003e,\n  methodPath: InstrumentedMethod,\n  context: unknown,\n  options: OpenAiOptions,\n): (...args: T) =\u003e Promise\u003cR\u003e {\n  return function instrumentedMethod(...args: T): Promise\u003cR\u003e {\n    const requestAttributes = extractRequestAttributes(args, methodPath);\n    const model = (requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] as string) || 'unknown';\n    const operationName = getOperationName(methodPath);\n\n    const params = args[0] as Record\u003cstring, unknown\u003e | undefined;\n    const isStreamRequested = params \u0026\u0026 typeof params === 'object' \u0026\u0026 params.stream === true;\n\n    const spanConfig = {\n      name: `${operationName} ${model}`,\n      op: getSpanOperation(methodPath),\n      attributes: requestAttributes as Record\u003cstring, SpanAttributeValue\u003e,\n    };\n\n    if (isStreamRequested) {\n      let originalResult!: Promise\u003cR\u003e;\n\n      const instrumentedPromise = startSpanManual(spanConfig, (span: Span) =\u003e {\n        originalResult = originalMethod.apply(context, args);\n\n        if (options.recordInputs \u0026\u0026 params) {\n          addRequestAttributes(span, params, operationName);\n        }\n\n        // Return async processing\n        return (async () =\u003e {\n          try {\n            const result = await originalResult;\n            return instrumentStream(\n              result as OpenAIStream\u003cChatCompletionChunk | ResponseStreamingEvent\u003e,\n              span,\n              options.recordOutputs ?? false,\n            ) as unknown as R;\n          } catch (error) {\n            span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n            captureException(error, {\n              mechanism: {\n                handled: false,\n                type: 'auto.ai.openai.stream',\n                data: { function: methodPath },\n              },\n            });\n            span.end();\n            throw error;\n          }\n        })();\n      });\n\n      return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.openai');\n    }\n\n    // Non-streaming\n    let originalResult!: Promise\u003cR\u003e;\n\n    const instrumentedPromise = startSpan(spanConfig, (span: Span) =\u003e {\n      // Call synchronously to capture the promise\n      originalResult = originalMethod.apply(context, args);\n\n      if (options.recordInputs \u0026\u0026 params) {\n        addRequestAttributes(span, params, operationName);\n      }\n\n      return originalResult.then(\n        result =\u003e {\n          addResponseAttributes(span, result, options.recordOutputs);\n          return result;\n        },\n        error =\u003e {\n          captureException(error, {\n            mechanism: {\n              handled: false,\n              type: 'auto.ai.openai',\n              data: { function: methodPath },\n            },\n          });\n          throw error;\n        },\n      );\n    });\n\n    return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.openai');\n  };\n}\n\n/**\n * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy\u003cT extends object\u003e(target: T, currentPath = '', options: OpenAiOptions): T {\n  return new Proxy(target, {\n    get(obj: object, prop: string): unknown {\n      const value = (obj as Record\u003cstring, unknown\u003e)[prop];\n      const methodPath = buildMethodPath(currentPath, String(prop));\n\n      if (typeof value === 'function' \u0026\u0026 shouldInstrument(methodPath)) {\n        return instrumentMethod(value as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e, methodPath, obj, options);\n      }\n\n      if (typeof value === 'function') {\n        // Bind non-instrumented functions to preserve the original `this` context,\n        // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n        return value.bind(obj);\n      }\n\n      if (value \u0026\u0026 typeof value === 'object') {\n        return createDeepProxy(value, methodPath, options);\n      }\n\n      return value;\n    },\n  }) as T;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nexport function instrumentOpenAiClient\u003cT extends object\u003e(client: T, options?: OpenAiOptions): T {\n  return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n","export const ANTHROPIC_AI_INTEGRATION_NAME = 'Anthropic_AI';\n\n// https://docs.anthropic.com/en/api/messages\n// https://docs.anthropic.com/en/api/models-list\nexport const ANTHROPIC_AI_INSTRUMENTED_METHODS = [\n  'messages.create',\n  'messages.stream',\n  'messages.countTokens',\n  'models.get',\n  'completions.create',\n  'models.retrieve',\n  'beta.messages.create',\n] as const;\n","import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport type { SpanStatusType } from '../../types-hoist/spanStatus';\nimport {\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';\nimport { ANTHROPIC_AI_INSTRUMENTED_METHODS } from './constants';\nimport type { AnthropicAiInstrumentedMethod, AnthropicAiResponse } from './types';\n\n/**\n * Check if a method path should be instrumented\n */\nexport function shouldInstrument(methodPath: string): methodPath is AnthropicAiInstrumentedMethod {\n  return ANTHROPIC_AI_INSTRUMENTED_METHODS.includes(methodPath as AnthropicAiInstrumentedMethod);\n}\n\n/**\n * Set the messages and messages original length attributes.\n * Extracts system instructions before truncation.\n */\nexport function setMessagesAttribute(span: Span, messages: unknown): void {\n  if (Array.isArray(messages) \u0026\u0026 messages.length === 0) {\n    return;\n  }\n\n  const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n  if (systemInstructions) {\n    span.setAttributes({\n      [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions,\n    });\n  }\n\n  const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;\n  span.setAttributes({\n    [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: getTruncatedJsonString(filteredMessages),\n    [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n  });\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record\u003cstring, SpanStatusType\u003e = {\n  invalid_request_error: 'invalid_argument',\n  authentication_error: 'unauthenticated',\n  permission_error: 'permission_denied',\n  not_found_error: 'not_found',\n  request_too_large: 'failed_precondition',\n  rate_limit_error: 'resource_exhausted',\n  api_error: 'internal_error',\n  overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n  if (!errorType) {\n    return 'internal_error';\n  }\n  return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function handleResponseError(span: Span, response: AnthropicAiResponse): void {\n  if (response.error) {\n    span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\n\n    captureException(response.error, {\n      mechanism: {\n        handled: false,\n        type: 'auto.ai.anthropic.anthropic_error',\n      },\n    });\n  }\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nexport function messagesFromParams(params: Record\u003cstring, unknown\u003e): unknown[] {\n  const { system, messages, input } = params;\n\n  const systemMessages = typeof system === 'string' ? [{ role: 'system', content: params.system }] : [];\n\n  const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n  const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n  const userMessages = inputParamMessages ?? messagesParamMessages;\n\n  return [...systemMessages, ...userMessages];\n}\n","import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { setTokenUsageAttributes } from '../ai/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n  /** Collected response text fragments (for output recording). */\n  responseTexts: string[];\n  /** Reasons for finishing the response, as reported by the API. */\n  finishReasons: string[];\n  /** The response ID. */\n  responseId: string;\n  /** The model name. */\n  responseModel: string;\n  /** Number of prompt/input tokens used. */\n  promptTokens: number | undefined;\n  /** Number of completion/output tokens used. */\n  completionTokens: number | undefined;\n  /** Number of cache creation input tokens used. */\n  cacheCreationInputTokens: number | undefined;\n  /** Number of cache read input tokens used. */\n  cacheReadInputTokens: number | undefined;\n  /** Accumulated tool calls (finalized) */\n  toolCalls: Array\u003cRecord\u003cstring, unknown\u003e\u003e;\n  /** In-progress tool call blocks keyed by index */\n  activeToolBlocks: Record\u003c\n    number,\n    {\n      id?: string;\n      name?: string;\n      inputJsonParts: string[];\n    }\n  \u003e;\n}\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event: AnthropicAiStreamingEvent, span: Span): boolean {\n  if ('type' in event \u0026\u0026 typeof event.type === 'string') {\n    // If the event is an error, set the span status and capture the error\n    // These error events are not rejected by the API by default, but are sent as metadata of the response\n    if (event.type === 'error') {\n      span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });\n      captureException(event.error, {\n        mechanism: {\n          handled: false,\n          type: 'auto.ai.anthropic.anthropic_error',\n        },\n      });\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n  // The token counts shown in the usage field of the message_delta event are cumulative.\n  // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n  if (event.type === 'message_delta' \u0026\u0026 event.usage) {\n    if ('output_tokens' in event.usage \u0026\u0026 typeof event.usage.output_tokens === 'number') {\n      state.completionTokens = event.usage.output_tokens;\n    }\n  }\n\n  if (event.message) {\n    const message = event.message;\n\n    if (message.id) state.responseId = message.id;\n    if (message.model) state.responseModel = message.model;\n    if (message.stop_reason) state.finishReasons.push(message.stop_reason);\n\n    if (message.usage) {\n      if (typeof message.usage.input_tokens === 'number') state.promptTokens = message.usage.input_tokens;\n      if (typeof message.usage.cache_creation_input_tokens === 'number')\n        state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens;\n      if (typeof message.usage.cache_read_input_tokens === 'number')\n        state.cacheReadInputTokens = message.usage.cache_read_input_tokens;\n    }\n  }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n  if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n  if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n    state.activeToolBlocks[event.index] = {\n      id: event.content_block.id,\n      name: event.content_block.name,\n      inputJsonParts: [],\n    };\n  }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n  event: AnthropicAiStreamingEvent,\n  state: StreamingState,\n  recordOutputs: boolean,\n): void {\n  if (event.type !== 'content_block_delta' || !event.delta) return;\n\n  // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n  if (\n    typeof event.index === 'number' \u0026\u0026\n    'partial_json' in event.delta \u0026\u0026\n    typeof event.delta.partial_json === 'string'\n  ) {\n    const active = state.activeToolBlocks[event.index];\n    if (active) {\n      active.inputJsonParts.push(event.delta.partial_json);\n    }\n  }\n\n  // Accumulate streamed response text regardless of index\n  if (recordOutputs \u0026\u0026 typeof event.delta.text === 'string') {\n    state.responseTexts.push(event.delta.text);\n  }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event: AnthropicAiStreamingEvent, state: StreamingState): void {\n  if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n  const active = state.activeToolBlocks[event.index];\n  if (!active) return;\n\n  const raw = active.inputJsonParts.join('');\n  let parsedInput: unknown;\n\n  try {\n    parsedInput = raw ? JSON.parse(raw) : {};\n  } catch {\n    parsedInput = { __unparsed: raw };\n  }\n\n  state.toolCalls.push({\n    type: 'tool_use',\n    id: active.id,\n    name: active.name,\n    input: parsedInput,\n  });\n\n  // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n  delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n  event: AnthropicAiStreamingEvent,\n  state: StreamingState,\n  recordOutputs: boolean,\n  span: Span,\n): void {\n  if (!(event \u0026\u0026 typeof event === 'object')) {\n    return;\n  }\n\n  const isError = isErrorEvent(event, span);\n  if (isError) return;\n\n  handleMessageMetadata(event, state);\n\n  // Tool call events are sent via 3 separate events:\n  // - content_block_start (start of the tool call)\n  // - content_block_delta (delta aka input of the tool call)\n  // - content_block_stop (end of the tool call)\n  // We need to handle them all to capture the full tool call.\n  handleContentBlockStart(event, state);\n  handleContentBlockDelta(event, state, recordOutputs);\n  handleContentBlockStop(event, state);\n}\n\n/**\n * Finalizes span attributes when stream processing completes\n */\nfunction finalizeStreamSpan(state: StreamingState, span: Span, recordOutputs: boolean): void {\n  if (!span.isRecording()) {\n    return;\n  }\n\n  // Set common response attributes if available\n  if (state.responseId) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n    });\n  }\n  if (state.responseModel) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n    });\n  }\n\n  setTokenUsageAttributes(\n    span,\n    state.promptTokens,\n    state.completionTokens,\n    state.cacheCreationInputTokens,\n    state.cacheReadInputTokens,\n  );\n\n  span.setAttributes({\n    [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n  });\n\n  if (state.finishReasons.length \u003e 0) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n    });\n  }\n\n  if (recordOutputs \u0026\u0026 state.responseTexts.length \u003e 0) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n    });\n  }\n\n  // Set tool calls if any were captured\n  if (recordOutputs \u0026\u0026 state.toolCalls.length \u003e 0) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n    });\n  }\n\n  span.end();\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nexport async function* instrumentAsyncIterableStream(\n  stream: AsyncIterable\u003cAnthropicAiStreamingEvent\u003e,\n  span: Span,\n  recordOutputs: boolean,\n): AsyncGenerator\u003cAnthropicAiStreamingEvent, void, unknown\u003e {\n  const state: StreamingState = {\n    responseTexts: [],\n    finishReasons: [],\n    responseId: '',\n    responseModel: '',\n    promptTokens: undefined,\n    completionTokens: undefined,\n    cacheCreationInputTokens: undefined,\n    cacheReadInputTokens: undefined,\n    toolCalls: [],\n    activeToolBlocks: {},\n  };\n\n  try {\n    for await (const event of stream) {\n      processEvent(event, state, recordOutputs, span);\n      yield event;\n    }\n  } finally {\n    // Set common response attributes if available\n    if (state.responseId) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n      });\n    }\n    if (state.responseModel) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n      });\n    }\n\n    setTokenUsageAttributes(\n      span,\n      state.promptTokens,\n      state.completionTokens,\n      state.cacheCreationInputTokens,\n      state.cacheReadInputTokens,\n    );\n\n    span.setAttributes({\n      [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n    });\n\n    if (state.finishReasons.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n      });\n    }\n\n    if (recordOutputs \u0026\u0026 state.responseTexts.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n      });\n    }\n\n    // Set tool calls if any were captured\n    if (recordOutputs \u0026\u0026 state.toolCalls.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n      });\n    }\n\n    span.end();\n  }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nexport function instrumentMessageStream\u003cR extends { on: (...args: unknown[]) =\u003e void }\u003e(\n  stream: R,\n  span: Span,\n  recordOutputs: boolean,\n): R {\n  const state: StreamingState = {\n    responseTexts: [],\n    finishReasons: [],\n    responseId: '',\n    responseModel: '',\n    promptTokens: undefined,\n    completionTokens: undefined,\n    cacheCreationInputTokens: undefined,\n    cacheReadInputTokens: undefined,\n    toolCalls: [],\n    activeToolBlocks: {},\n  };\n\n  stream.on('streamEvent', (event: unknown) =\u003e {\n    processEvent(event as AnthropicAiStreamingEvent, state, recordOutputs, span);\n  });\n\n  // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n  // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n  stream.on('message', () =\u003e {\n    finalizeStreamSpan(state, span, recordOutputs);\n  });\n\n  stream.on('error', (error: unknown) =\u003e {\n    captureException(error, {\n      mechanism: {\n        handled: false,\n        type: 'auto.ai.anthropic.stream_error',\n      },\n    });\n\n    if (span.isRecording()) {\n      span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n      span.end();\n    }\n  });\n\n  return stream;\n}\n","import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpan, startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport {\n  ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_PROMPT_ATTRIBUTE,\n  GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_SYSTEM_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport {\n  buildMethodPath,\n  getFinalOperationName,\n  getSpanOperation,\n  resolveAIRecordingOptions,\n  setTokenUsageAttributes,\n  wrapPromiseWithMethods,\n} from '../ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming';\nimport type {\n  AnthropicAiInstrumentedMethod,\n  AnthropicAiOptions,\n  AnthropicAiResponse,\n  AnthropicAiStreamingEvent,\n  ContentBlock,\n} from './types';\nimport { handleResponseError, messagesFromParams, setMessagesAttribute, shouldInstrument } from './utils';\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args: unknown[], methodPath: string): Record\u003cstring, unknown\u003e {\n  const attributes: Record\u003cstring, unknown\u003e = {\n    [GEN_AI_SYSTEM_ATTRIBUTE]: 'anthropic',\n    [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath),\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.anthropic',\n  };\n\n  if (args.length \u003e 0 \u0026\u0026 typeof args[0] === 'object' \u0026\u0026 args[0] !== null) {\n    const params = args[0] as Record\u003cstring, unknown\u003e;\n    if (params.tools \u0026\u0026 Array.isArray(params.tools)) {\n      attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools);\n    }\n\n    attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown';\n    if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n    if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n    if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n    if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k;\n    if ('frequency_penalty' in params)\n      attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n    if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens;\n  } else {\n    if (methodPath === 'models.retrieve' || methodPath === 'models.get') {\n      // models.retrieve(model-id) and models.get(model-id)\n      attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0];\n    } else {\n      attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n    }\n  }\n\n  return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nfunction addPrivateRequestAttributes(span: Span, params: Record\u003cstring, unknown\u003e): void {\n  const messages = messagesFromParams(params);\n  setMessagesAttribute(span, messages);\n\n  if ('prompt' in params) {\n    span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });\n  }\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span: Span, response: AnthropicAiResponse): void {\n  // Messages.create\n  if ('content' in response) {\n    if (Array.isArray(response.content)) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content\n          .map((item: ContentBlock) =\u003e item.text)\n          .filter(text =\u003e !!text)\n          .join(''),\n      });\n\n      const toolCalls: Array\u003cContentBlock\u003e = [];\n\n      for (const item of response.content) {\n        if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n          toolCalls.push(item);\n        }\n      }\n      if (toolCalls.length \u003e 0) {\n        span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) });\n      }\n    }\n  }\n  // Completions.create\n  if ('completion' in response) {\n    span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion });\n  }\n  // Models.countTokens\n  if ('input_tokens' in response) {\n    span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) });\n  }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span: Span, response: AnthropicAiResponse): void {\n  if ('id' in response \u0026\u0026 'model' in response) {\n    span.setAttributes({\n      [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id,\n      [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n    });\n\n    if ('created' in response \u0026\u0026 typeof response.created === 'number') {\n      span.setAttributes({\n        [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(),\n      });\n    }\n    if ('created_at' in response \u0026\u0026 typeof response.created_at === 'number') {\n      span.setAttributes({\n        [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1000).toISOString(),\n      });\n    }\n\n    if ('usage' in response \u0026\u0026 response.usage) {\n      setTokenUsageAttributes(\n        span,\n        response.usage.input_tokens,\n        response.usage.output_tokens,\n        response.usage.cache_creation_input_tokens,\n        response.usage.cache_read_input_tokens,\n      );\n    }\n  }\n}\n\n/**\n * Add response attributes to spans\n */\nfunction addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void {\n  if (!response || typeof response !== 'object') return;\n\n  // capture error, do not add attributes if error (they shouldn't exist)\n  if ('type' in response \u0026\u0026 response.type === 'error') {\n    handleResponseError(span, response);\n    return;\n  }\n\n  // Private response attributes that are only recorded if recordOutputs is true.\n  if (recordOutputs) {\n    addContentAttributes(span, response);\n  }\n\n  // Add basic metadata attributes\n  addMetadataAttributes(span, response);\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(error: unknown, span: Span, methodPath: string): never {\n  captureException(error, {\n    mechanism: { handled: false, type: 'auto.ai.anthropic', data: { function: methodPath } },\n  });\n\n  if (span.isRecording()) {\n    span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n    span.end();\n  }\n  throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest\u003cT extends unknown[], R\u003e(\n  originalMethod: (...args: T) =\u003e R | Promise\u003cR\u003e,\n  target: (...args: T) =\u003e R | Promise\u003cR\u003e,\n  context: unknown,\n  args: T,\n  requestAttributes: Record\u003cstring, unknown\u003e,\n  operationName: string,\n  methodPath: string,\n  params: Record\u003cstring, unknown\u003e | undefined,\n  options: AnthropicAiOptions,\n  isStreamRequested: boolean,\n  isStreamingMethod: boolean,\n): R | Promise\u003cR\u003e {\n  const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n  const spanConfig = {\n    name: `${operationName} ${model}`,\n    op: getSpanOperation(methodPath),\n    attributes: requestAttributes as Record\u003cstring, SpanAttributeValue\u003e,\n  };\n\n  // messages.stream() always returns a sync MessageStream, even with stream: true param\n  if (isStreamRequested \u0026\u0026 !isStreamingMethod) {\n    let originalResult!: Promise\u003cR\u003e;\n\n    const instrumentedPromise = startSpanManual(spanConfig, (span: Span) =\u003e {\n      originalResult = originalMethod.apply(context, args) as Promise\u003cR\u003e;\n\n      if (options.recordInputs \u0026\u0026 params) {\n        addPrivateRequestAttributes(span, params);\n      }\n\n      return (async () =\u003e {\n        try {\n          const result = await originalResult;\n          return instrumentAsyncIterableStream(\n            result as AsyncIterable\u003cAnthropicAiStreamingEvent\u003e,\n            span,\n            options.recordOutputs ?? false,\n          ) as unknown as R;\n        } catch (error) {\n          return handleStreamingError(error, span, methodPath);\n        }\n      })();\n    });\n\n    return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n  } else {\n    return startSpanManual(spanConfig, span =\u003e {\n      try {\n        if (options.recordInputs \u0026\u0026 params) {\n          addPrivateRequestAttributes(span, params);\n        }\n        const messageStream = target.apply(context, args);\n        return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);\n      } catch (error) {\n        return handleStreamingError(error, span, methodPath);\n      }\n    });\n  }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod\u003cT extends unknown[], R\u003e(\n  originalMethod: (...args: T) =\u003e R | Promise\u003cR\u003e,\n  methodPath: AnthropicAiInstrumentedMethod,\n  context: unknown,\n  options: AnthropicAiOptions,\n): (...args: T) =\u003e R | Promise\u003cR\u003e {\n  return new Proxy(originalMethod, {\n    apply(target, thisArg, args: T): R | Promise\u003cR\u003e {\n      const requestAttributes = extractRequestAttributes(args, methodPath);\n      const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n      const operationName = getFinalOperationName(methodPath);\n\n      const params = typeof args[0] === 'object' ? (args[0] as Record\u003cstring, unknown\u003e) : undefined;\n      const isStreamRequested = Boolean(params?.stream);\n      const isStreamingMethod = methodPath === 'messages.stream';\n\n      if (isStreamRequested || isStreamingMethod) {\n        return handleStreamingRequest(\n          originalMethod,\n          target,\n          context,\n          args,\n          requestAttributes,\n          operationName,\n          methodPath,\n          params,\n          options,\n          isStreamRequested,\n          isStreamingMethod,\n        );\n      }\n\n      let originalResult!: Promise\u003cR\u003e;\n\n      const instrumentedPromise = startSpan(\n        {\n          name: `${operationName} ${model}`,\n          op: getSpanOperation(methodPath),\n          attributes: requestAttributes as Record\u003cstring, SpanAttributeValue\u003e,\n        },\n        span =\u003e {\n          originalResult = target.apply(context, args) as Promise\u003cR\u003e;\n\n          if (options.recordInputs \u0026\u0026 params) {\n            addPrivateRequestAttributes(span, params);\n          }\n\n          return originalResult.then(\n            result =\u003e {\n              addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs);\n              return result;\n            },\n            error =\u003e {\n              captureException(error, {\n                mechanism: {\n                  handled: false,\n                  type: 'auto.ai.anthropic',\n                  data: {\n                    function: methodPath,\n                  },\n                },\n              });\n              throw error;\n            },\n          );\n        },\n      );\n\n      return wrapPromiseWithMethods(originalResult, instrumentedPromise, 'auto.ai.anthropic');\n    },\n  }) as (...args: T) =\u003e R | Promise\u003cR\u003e;\n}\n\n/**\n * Create a deep proxy for Anthropic AI client instrumentation\n */\nfunction createDeepProxy\u003cT extends object\u003e(target: T, currentPath = '', options: AnthropicAiOptions): T {\n  return new Proxy(target, {\n    get(obj: object, prop: string): unknown {\n      const value = (obj as Record\u003cstring, unknown\u003e)[prop];\n      const methodPath = buildMethodPath(currentPath, String(prop));\n\n      if (typeof value === 'function' \u0026\u0026 shouldInstrument(methodPath)) {\n        return instrumentMethod(value as (...args: unknown[]) =\u003e unknown | Promise\u003cunknown\u003e, methodPath, obj, options);\n      }\n\n      if (typeof value === 'function') {\n        // Bind non-instrumented functions to preserve the original `this` context,\n        return value.bind(obj);\n      }\n\n      if (value \u0026\u0026 typeof value === 'object') {\n        return createDeepProxy(value, methodPath, options);\n      }\n\n      return value;\n    },\n  }) as T;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nexport function instrumentAnthropicAiClient\u003cT extends object\u003e(anthropicAiClient: T, options?: AnthropicAiOptions): T {\n  return createDeepProxy(anthropicAiClient, '', resolveAIRecordingOptions(options));\n}\n","export const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI';\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\nexport const GOOGLE_GENAI_INSTRUMENTED_METHODS = [\n  'models.generateContent',\n  'models.generateContentStream',\n  'chats.create',\n  'sendMessage',\n  'sendMessageStream',\n] as const;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\nexport const CHATS_CREATE_METHOD = 'chats.create';\nexport const CHAT_PATH = 'chat';\n","import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport {\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport type { GoogleGenAIResponse } from './types';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI events.\n */\ninterface StreamingState {\n  /** Collected response text fragments (for output recording). */\n  responseTexts: string[];\n  /** Reasons for finishing the response, as reported by the API. */\n  finishReasons: string[];\n  /** The response ID. */\n  responseId?: string;\n  /** The model name. */\n  responseModel?: string;\n  /** Number of prompt/input tokens used. */\n  promptTokens?: number;\n  /** Number of completion/output tokens used. */\n  completionTokens?: number;\n  /** Number of total tokens used. */\n  totalTokens?: number;\n  /** Accumulated tool calls (finalized) */\n  toolCalls: Array\u003cRecord\u003cstring, unknown\u003e\u003e;\n}\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean {\n  const feedback = chunk?.promptFeedback;\n  if (feedback?.blockReason) {\n    const message = feedback.blockReasonMessage ?? feedback.blockReason;\n    span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n    captureException(`Content blocked: ${message}`, {\n      mechanism: { handled: false, type: 'auto.ai.google_genai' },\n    });\n    return true;\n  }\n  return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void {\n  if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n  if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n  const usage = chunk.usageMetadata;\n  if (usage) {\n    if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n    if (typeof usage.candidatesTokenCount === 'number') state.completionTokens = usage.candidatesTokenCount;\n    if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n  }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void {\n  if (Array.isArray(chunk.functionCalls)) {\n    state.toolCalls.push(...chunk.functionCalls);\n  }\n\n  for (const candidate of chunk.candidates ?? []) {\n    if (candidate?.finishReason \u0026\u0026 !state.finishReasons.includes(candidate.finishReason)) {\n      state.finishReasons.push(candidate.finishReason);\n    }\n\n    for (const part of candidate?.content?.parts ?? []) {\n      if (recordOutputs \u0026\u0026 part.text) state.responseTexts.push(part.text);\n      if (part.functionCall) {\n        state.toolCalls.push({\n          type: 'function',\n          id: part.functionCall.id,\n          name: part.functionCall.name,\n          arguments: part.functionCall.args,\n        });\n      }\n    }\n  }\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void {\n  if (!chunk || isErrorChunk(chunk, span)) return;\n  handleResponseMetadata(chunk, state);\n  handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nexport async function* instrumentStream(\n  stream: AsyncIterable\u003cGoogleGenAIResponse\u003e,\n  span: Span,\n  recordOutputs: boolean,\n): AsyncGenerator\u003cGoogleGenAIResponse, void, unknown\u003e {\n  const state: StreamingState = {\n    responseTexts: [],\n    finishReasons: [],\n    toolCalls: [],\n  };\n\n  try {\n    for await (const chunk of stream) {\n      processChunk(chunk, state, recordOutputs, span);\n      yield chunk;\n    }\n  } finally {\n    const attrs: Record\u003cstring, SpanAttributeValue\u003e = {\n      [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n    };\n\n    if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId;\n    if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel;\n    if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens;\n    if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens;\n    if (state.totalTokens !== undefined) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens;\n\n    if (state.finishReasons.length) {\n      attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons);\n    }\n    if (recordOutputs \u0026\u0026 state.responseTexts.length) {\n      attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join('');\n    }\n    if (recordOutputs \u0026\u0026 state.toolCalls.length) {\n      attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls);\n    }\n\n    span.setAttributes(attrs);\n    span.end();\n  }\n}\n","import { GOOGLE_GENAI_INSTRUMENTED_METHODS } from './constants';\nimport type { GoogleGenAIIstrumentedMethod } from './types';\n\n/**\n * Check if a method path should be instrumented\n */\nexport function shouldInstrument(methodPath: string): methodPath is GoogleGenAIIstrumentedMethod {\n  // Check for exact matches first (like 'models.generateContent')\n  if (GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodPath as GoogleGenAIIstrumentedMethod)) {\n    return true;\n  }\n\n  // Check for method name matches (like 'sendMessage' from chat instances)\n  const methodName = methodPath.split('.').pop();\n  return GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodName as GoogleGenAIIstrumentedMethod);\n}\n\n/**\n * Check if a method is a streaming method\n */\nexport function isStreamingMethod(methodPath: string): boolean {\n  return methodPath.includes('Stream');\n}\n\n// Copied from https://googleapis.github.io/js-genai/release_docs/index.html\nexport type ContentListUnion = Content | Content[] | PartListUnion;\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\nexport type Content = {\n  parts?: Part[];\n  role?: string;\n};\nexport type PartUnion = Part | string;\nexport type Part = Record\u003cstring, unknown\u003e \u0026 {\n  inlineData?: {\n    data?: string;\n    displayName?: string;\n    mimeType?: string;\n  };\n  text?: string;\n};\nexport type PartListUnion = PartUnion[] | PartUnion;\n\n// our consistent span message shape\nexport type Message = Record\u003cstring, unknown\u003e \u0026 {\n  role: string;\n  content?: PartListUnion;\n  parts?: PartListUnion;\n};\n\n/**\n *\n */\nexport function contentUnionToMessages(content: ContentListUnion, role = 'user'): Message[] {\n  if (typeof content === 'string') {\n    return [{ role, content }];\n  }\n  if (Array.isArray(content)) {\n    return content.flatMap(content =\u003e contentUnionToMessages(content, role));\n  }\n  if (typeof content !== 'object' || !content) return [];\n  if ('role' in content \u0026\u0026 typeof content.role === 'string') {\n    return [content as Message];\n  }\n  if ('parts' in content) {\n    return [{ ...content, role } as Message];\n  }\n  return [{ role, content }];\n}\n","import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpan, startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport { handleCallbackErrors } from '../../utils/handleCallbackErrors';\nimport {\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_K_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_SYSTEM_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { truncateGenAiMessages } from '../ai/messageTruncation';\nimport {\n  buildMethodPath,\n  extractSystemInstructions,\n  getFinalOperationName,\n  getSpanOperation,\n  resolveAIRecordingOptions,\n} from '../ai/utils';\nimport { CHAT_PATH, CHATS_CREATE_METHOD, GOOGLE_GENAI_SYSTEM_NAME } from './constants';\nimport { instrumentStream } from './streaming';\nimport type {\n  Candidate,\n  ContentPart,\n  GoogleGenAIIstrumentedMethod,\n  GoogleGenAIOptions,\n  GoogleGenAIResponse,\n} from './types';\nimport type { ContentListUnion, ContentUnion, Message, PartListUnion } from './utils';\nimport { contentUnionToMessages, isStreamingMethod, shouldInstrument } from './utils';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nexport function extractModel(params: Record\u003cstring, unknown\u003e, context?: unknown): string {\n  if ('model' in params \u0026\u0026 typeof params.model === 'string') {\n    return params.model;\n  }\n\n  // Try to get model from chat context object (chat instance has model property)\n  if (context \u0026\u0026 typeof context === 'object') {\n    const contextObj = context as Record\u003cstring, unknown\u003e;\n\n    // Check for 'model' property (older versions, and streaming)\n    if ('model' in contextObj \u0026\u0026 typeof contextObj.model === 'string') {\n      return contextObj.model;\n    }\n\n    // Check for 'modelVersion' property (newer versions)\n    if ('modelVersion' in contextObj \u0026\u0026 typeof contextObj.modelVersion === 'string') {\n      return contextObj.modelVersion;\n    }\n  }\n\n  return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config: Record\u003cstring, unknown\u003e): Record\u003cstring, SpanAttributeValue\u003e {\n  const attributes: Record\u003cstring, SpanAttributeValue\u003e = {};\n\n  if ('temperature' in config \u0026\u0026 typeof config.temperature === 'number') {\n    attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = config.temperature;\n  }\n  if ('topP' in config \u0026\u0026 typeof config.topP === 'number') {\n    attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = config.topP;\n  }\n  if ('topK' in config \u0026\u0026 typeof config.topK === 'number') {\n    attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = config.topK;\n  }\n  if ('maxOutputTokens' in config \u0026\u0026 typeof config.maxOutputTokens === 'number') {\n    attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = config.maxOutputTokens;\n  }\n  if ('frequencyPenalty' in config \u0026\u0026 typeof config.frequencyPenalty === 'number') {\n    attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = config.frequencyPenalty;\n  }\n  if ('presencePenalty' in config \u0026\u0026 typeof config.presencePenalty === 'number') {\n    attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = config.presencePenalty;\n  }\n\n  return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nfunction extractRequestAttributes(\n  methodPath: string,\n  params?: Record\u003cstring, unknown\u003e,\n  context?: unknown,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  const attributes: Record\u003cstring, SpanAttributeValue\u003e = {\n    [GEN_AI_SYSTEM_ATTRIBUTE]: GOOGLE_GENAI_SYSTEM_NAME,\n    [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath),\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai',\n  };\n\n  if (params) {\n    attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel(params, context);\n\n    // Extract generation config parameters\n    if ('config' in params \u0026\u0026 typeof params.config === 'object' \u0026\u0026 params.config) {\n      const config = params.config as Record\u003cstring, unknown\u003e;\n      Object.assign(attributes, extractConfigAttributes(config));\n\n      // Extract available tools from config\n      if ('tools' in config \u0026\u0026 Array.isArray(config.tools)) {\n        const functionDeclarations = config.tools.flatMap(\n          (tool: { functionDeclarations: unknown[] }) =\u003e tool.functionDeclarations,\n        );\n        attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(functionDeclarations);\n      }\n    }\n  } else {\n    attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel({}, context);\n  }\n\n  return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n * Handles different parameter formats for different Google GenAI methods.\n */\nfunction addPrivateRequestAttributes(span: Span, params: Record\u003cstring, unknown\u003e): void {\n  const messages: Message[] = [];\n\n  // config.systemInstruction: ContentUnion\n  if (\n    'config' in params \u0026\u0026\n    params.config \u0026\u0026\n    typeof params.config === 'object' \u0026\u0026\n    'systemInstruction' in params.config \u0026\u0026\n    params.config.systemInstruction\n  ) {\n    messages.push(...contentUnionToMessages(params.config.systemInstruction as ContentUnion, 'system'));\n  }\n\n  // For chats.create: history contains the conversation history\n  if ('history' in params) {\n    messages.push(...contentUnionToMessages(params.history as PartListUnion, 'user'));\n  }\n\n  // For models.generateContent: ContentListUnion\n  if ('contents' in params) {\n    messages.push(...contentUnionToMessages(params.contents as ContentListUnion, 'user'));\n  }\n\n  // For chat.sendMessage: message can be PartListUnion\n  if ('message' in params) {\n    messages.push(...contentUnionToMessages(params.message as PartListUnion, 'user'));\n  }\n\n  if (Array.isArray(messages) \u0026\u0026 messages.length) {\n    const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n    if (systemInstructions) {\n      span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n    }\n\n    const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;\n    span.setAttributes({\n      [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n      [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: JSON.stringify(truncateGenAiMessages(filteredMessages as unknown[])),\n    });\n  }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nfunction addResponseAttributes(span: Span, response: GoogleGenAIResponse, recordOutputs?: boolean): void {\n  if (!response || typeof response !== 'object') return;\n\n  if (response.modelVersion) {\n    span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, response.modelVersion);\n  }\n\n  // Add usage metadata if present\n  if (response.usageMetadata \u0026\u0026 typeof response.usageMetadata === 'object') {\n    const usage = response.usageMetadata;\n    if (typeof usage.promptTokenCount === 'number') {\n      span.setAttributes({\n        [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: usage.promptTokenCount,\n      });\n    }\n    if (typeof usage.candidatesTokenCount === 'number') {\n      span.setAttributes({\n        [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: usage.candidatesTokenCount,\n      });\n    }\n    if (typeof usage.totalTokenCount === 'number') {\n      span.setAttributes({\n        [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: usage.totalTokenCount,\n      });\n    }\n  }\n\n  // Add response text if recordOutputs is enabled\n  if (recordOutputs \u0026\u0026 Array.isArray(response.candidates) \u0026\u0026 response.candidates.length \u003e 0) {\n    const responseTexts = response.candidates\n      .map((candidate: Candidate) =\u003e {\n        if (candidate.content?.parts \u0026\u0026 Array.isArray(candidate.content.parts)) {\n          return candidate.content.parts\n            .map((part: ContentPart) =\u003e (typeof part.text === 'string' ? part.text : ''))\n            .filter((text: string) =\u003e text.length \u003e 0)\n            .join('');\n        }\n        return '';\n      })\n      .filter((text: string) =\u003e text.length \u003e 0);\n\n    if (responseTexts.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: responseTexts.join(''),\n      });\n    }\n  }\n\n  // Add tool calls if recordOutputs is enabled\n  if (recordOutputs \u0026\u0026 response.functionCalls) {\n    const functionCalls = response.functionCalls;\n    if (Array.isArray(functionCalls) \u0026\u0026 functionCalls.length \u003e 0) {\n      span.setAttributes({\n        [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls),\n      });\n    }\n  }\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod\u003cT extends unknown[], R\u003e(\n  originalMethod: (...args: T) =\u003e R | Promise\u003cR\u003e,\n  methodPath: GoogleGenAIIstrumentedMethod,\n  context: unknown,\n  options: GoogleGenAIOptions,\n): (...args: T) =\u003e R | Promise\u003cR\u003e {\n  const isSyncCreate = methodPath === CHATS_CREATE_METHOD;\n\n  return new Proxy(originalMethod, {\n    apply(target, _, args: T): R | Promise\u003cR\u003e {\n      const params = args[0] as Record\u003cstring, unknown\u003e | undefined;\n      const requestAttributes = extractRequestAttributes(methodPath, params, context);\n      const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n      const operationName = getFinalOperationName(methodPath);\n\n      // Check if this is a streaming method\n      if (isStreamingMethod(methodPath)) {\n        // Use startSpanManual for streaming methods to control span lifecycle\n        return startSpanManual(\n          {\n            name: `${operationName} ${model}`,\n            op: getSpanOperation(methodPath),\n            attributes: requestAttributes,\n          },\n          async (span: Span) =\u003e {\n            try {\n              if (options.recordInputs \u0026\u0026 params) {\n                addPrivateRequestAttributes(span, params);\n              }\n              const stream = await target.apply(context, args);\n              return instrumentStream(stream, span, Boolean(options.recordOutputs)) as R;\n            } catch (error) {\n              span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n              captureException(error, {\n                mechanism: {\n                  handled: false,\n                  type: 'auto.ai.google_genai',\n                  data: { function: methodPath },\n                },\n              });\n              span.end();\n              throw error;\n            }\n          },\n        );\n      }\n      // Single span for both sync and async operations\n      return startSpan(\n        {\n          name: isSyncCreate ? `${operationName} ${model} create` : `${operationName} ${model}`,\n          op: getSpanOperation(methodPath),\n          attributes: requestAttributes,\n        },\n        (span: Span) =\u003e {\n          if (options.recordInputs \u0026\u0026 params) {\n            addPrivateRequestAttributes(span, params);\n          }\n\n          return handleCallbackErrors(\n            () =\u003e target.apply(context, args),\n            error =\u003e {\n              captureException(error, {\n                mechanism: { handled: false, type: 'auto.ai.google_genai', data: { function: methodPath } },\n              });\n            },\n            () =\u003e {},\n            result =\u003e {\n              // Only add response attributes for content-producing methods, not for chats.create\n              if (!isSyncCreate) {\n                addResponseAttributes(span, result, options.recordOutputs);\n              }\n            },\n          );\n        },\n      );\n    },\n  }) as (...args: T) =\u003e R | Promise\u003cR\u003e;\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy\u003cT extends object\u003e(target: T, currentPath = '', options: GoogleGenAIOptions): T {\n  return new Proxy(target, {\n    get: (t, prop, receiver) =\u003e {\n      const value = Reflect.get(t, prop, receiver);\n      const methodPath = buildMethodPath(currentPath, String(prop));\n\n      if (typeof value === 'function' \u0026\u0026 shouldInstrument(methodPath)) {\n        // Special case: chats.create is synchronous but needs both instrumentation AND result proxying\n        if (methodPath === CHATS_CREATE_METHOD) {\n          const instrumentedMethod = instrumentMethod(value as (...args: unknown[]) =\u003e unknown, methodPath, t, options);\n          return function instrumentedAndProxiedCreate(...args: unknown[]): unknown {\n            const result = instrumentedMethod(...args);\n            // If the result is an object (like a chat instance), proxy it too\n            if (result \u0026\u0026 typeof result === 'object') {\n              return createDeepProxy(result, CHAT_PATH, options);\n            }\n            return result;\n          };\n        }\n\n        return instrumentMethod(value as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e, methodPath, t, options);\n      }\n\n      if (typeof value === 'function') {\n        // Bind non-instrumented functions to preserve the original `this` context\n        return value.bind(t);\n      }\n\n      if (value \u0026\u0026 typeof value === 'object') {\n        return createDeepProxy(value, methodPath, options);\n      }\n\n      return value;\n    },\n  });\n}\n\n/**\n * Instrument a Google GenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends client object\n * @param client - The Google GenAI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/core';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nexport function instrumentGoogleGenAIClient\u003cT extends object\u003e(client: T, options?: GoogleGenAIOptions): T {\n  return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n","export const LANGCHAIN_INTEGRATION_NAME = 'LangChain';\nexport const LANGCHAIN_ORIGIN = 'auto.ai.langchain';\n\nexport const ROLE_MAP: Record\u003cstring, string\u003e = {\n  human: 'user',\n  ai: 'assistant',\n  assistant: 'assistant',\n  system: 'system',\n  function: 'function',\n  tool: 'tool',\n};\n","import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport type { SpanAttributeValue } from '../../types-hoist/span';\nimport {\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE,\n  GEN_AI_REQUEST_STREAM_ATTRIBUTE,\n  GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE,\n  GEN_AI_REQUEST_TOP_P_ATTRIBUTE,\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_ID_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_SYSTEM_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n  GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { isContentMedia, stripInlineMediaFromSingleMessage } from '../ai/mediaStripping';\nimport { truncateGenAiMessages } from '../ai/messageTruncation';\nimport { extractSystemInstructions } from '../ai/utils';\nimport { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants';\nimport type { LangChainLLMResult, LangChainMessage, LangChainSerialized } from './types';\n\n/**\n * Assigns an attribute only when the value is neither `undefined` nor `null`.\n *\n * We keep this tiny helper because call sites are repetitive and easy to miswrite.\n * It also preserves falsy-but-valid values like `0` and `\"\"`.\n */\nconst setIfDefined = (target: Record\u003cstring, SpanAttributeValue\u003e, key: string, value: unknown): void =\u003e {\n  if (value != null) target[key] = value as SpanAttributeValue;\n};\n\n/**\n * Like `setIfDefined`, but converts the value with `Number()` and skips only when the\n * result is `NaN`. This ensures numeric 0 makes it through (unlike truthy checks).\n */\nconst setNumberIfDefined = (target: Record\u003cstring, SpanAttributeValue\u003e, key: string, value: unknown): void =\u003e {\n  const n = Number(value);\n  if (!Number.isNaN(n)) target[key] = n;\n};\n\n/**\n * Converts a value to a string. Avoids double-quoted JSON strings where a plain\n * string is desired, but still handles objects/arrays safely.\n */\nfunction asString(v: unknown): string {\n  if (typeof v === 'string') return v;\n  try {\n    return JSON.stringify(v);\n  } catch {\n    return String(v);\n  }\n}\n\n/**\n * Converts message content to a string, stripping inline media (base64 images, audio, etc.)\n * from multimodal content before stringification so downstream media stripping can't miss it.\n *\n * @example\n * // String content passes through unchanged:\n * normalizeContent(\"Hello\") // =\u003e \"Hello\"\n *\n * // Multimodal array content — media is replaced with \"[Blob substitute]\" before JSON.stringify:\n * normalizeContent([\n *   { type: \"text\", text: \"What color?\" },\n *   { type: \"image_url\", image_url: { url: \"data:image/png;base64,iVBOR...\" } }\n * ])\n * // =\u003e '[{\"type\":\"text\",\"text\":\"What color?\"},{\"type\":\"image_url\",\"image_url\":{\"url\":\"[Blob substitute]\"}}]'\n *\n * // Without this, asString() would JSON.stringify the raw array and the base64 blob\n * // would end up in span attributes, since downstream stripping only works on objects.\n */\nfunction normalizeContent(v: unknown): string {\n  if (Array.isArray(v)) {\n    try {\n      const stripped = v.map(part =\u003e\n        part \u0026\u0026 typeof part === 'object' \u0026\u0026 isContentMedia(part) ? stripInlineMediaFromSingleMessage(part) : part,\n      );\n      return JSON.stringify(stripped);\n    } catch {\n      return String(v);\n    }\n  }\n  return asString(v);\n}\n\n/**\n * Normalizes a single role token to our canonical set.\n *\n * @param role Incoming role value (free-form, any casing)\n * @returns Canonical role: 'user' | 'assistant' | 'system' | 'function' | 'tool' | \u003cpassthrough\u003e\n */\nfunction normalizeMessageRole(role: string): string {\n  const normalized = role.toLowerCase();\n  return ROLE_MAP[normalized] ?? normalized;\n}\n\n/**\n * Infers a role from a LangChain message constructor name.\n *\n * Checks for substrings like \"System\", \"Human\", \"AI\", etc.\n */\nfunction normalizeRoleNameFromCtor(name: string): string {\n  if (name.includes('System')) return 'system';\n  if (name.includes('Human')) return 'user';\n  if (name.includes('AI') || name.includes('Assistant')) return 'assistant';\n  if (name.includes('Function')) return 'function';\n  if (name.includes('Tool')) return 'tool';\n  return 'user';\n}\n\n/**\n * Returns invocation params from a LangChain `tags` object.\n *\n * LangChain often passes runtime parameters (model, temperature, etc.) via the\n * `tags.invocation_params` bag. If `tags` is an array (LangChain sometimes uses\n * string tags), we return `undefined`.\n *\n * @param tags LangChain tags (string[] or record)\n * @returns The `invocation_params` object, if present\n */\nexport function getInvocationParams(tags?: string[] | Record\u003cstring, unknown\u003e): Record\u003cstring, unknown\u003e | undefined {\n  if (!tags || Array.isArray(tags)) return undefined;\n  return tags.invocation_params as Record\u003cstring, unknown\u003e | undefined;\n}\n\n/**\n * Normalizes a heterogeneous set of LangChain messages to `{ role, content }`.\n *\n * Why so many branches? LangChain messages can arrive in several shapes:\n *  - Message classes with `_getType()` (most reliable)\n *  - Classes with meaningful constructor names (e.g. `SystemMessage`)\n *  - Plain objects with `type`, or `{ role, content }`\n *  - Serialized format with `{ lc: 1, id: [...], kwargs: { content } }`\n * We preserve the prioritization to minimize behavioral drift.\n *\n * @param messages Mixed LangChain messages\n * @returns Array of normalized `{ role, content }`\n */\nexport function normalizeLangChainMessages(messages: LangChainMessage[]): Array\u003c{ role: string; content: string }\u003e {\n  return messages.map(message =\u003e {\n    // 1) Prefer _getType() when present\n    const maybeGetType = (message as { _getType?: () =\u003e string })._getType;\n    if (typeof maybeGetType === 'function') {\n      const messageType = maybeGetType.call(message);\n      return {\n        role: normalizeMessageRole(messageType),\n        content: normalizeContent(message.content),\n      };\n    }\n\n    // 2) Serialized LangChain format (lc: 1) - check before constructor name\n    // This is more reliable than constructor.name which can be lost during serialization\n    if (message.lc === 1 \u0026\u0026 message.kwargs) {\n      const id = message.id;\n      const messageType = Array.isArray(id) \u0026\u0026 id.length \u003e 0 ? id[id.length - 1] : '';\n      const role = typeof messageType === 'string' ? normalizeRoleNameFromCtor(messageType) : 'user';\n\n      return {\n        role: normalizeMessageRole(role),\n        content: normalizeContent(message.kwargs?.content),\n      };\n    }\n\n    // 3) Then objects with `type`\n    if (message.type) {\n      const role = String(message.type).toLowerCase();\n      return {\n        role: normalizeMessageRole(role),\n        content: normalizeContent(message.content),\n      };\n    }\n\n    // 4) Then objects with `{ role, content }` - check before constructor name\n    // Plain objects have constructor.name=\"Object\" which would incorrectly default to \"user\"\n    if (message.role) {\n      return {\n        role: normalizeMessageRole(String(message.role)),\n        content: normalizeContent(message.content),\n      };\n    }\n\n    // 5) Then try constructor name (SystemMessage / HumanMessage / ...)\n    // Only use this if we haven't matched a more specific case\n    const ctor = (message as { constructor?: { name?: string } }).constructor?.name;\n    if (ctor \u0026\u0026 ctor !== 'Object') {\n      return {\n        role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)),\n        content: normalizeContent(message.content),\n      };\n    }\n\n    // 6) Fallback: treat as user text\n    return {\n      role: 'user',\n      content: normalizeContent(message.content),\n    };\n  });\n}\n\n/**\n * Extracts request attributes common to both LLM and ChatModel invocations.\n *\n * Source precedence:\n * 1) `invocationParams` (highest)\n * 2) `langSmithMetadata`\n *\n * Numeric values are set even when 0 (e.g. `temperature: 0`), but skipped if `NaN`.\n */\nfunction extractCommonRequestAttributes(\n  serialized: LangChainSerialized,\n  invocationParams?: Record\u003cstring, unknown\u003e,\n  langSmithMetadata?: Record\u003cstring, unknown\u003e,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  const attrs: Record\u003cstring, SpanAttributeValue\u003e = {};\n\n  // Get kwargs if available (from constructor type)\n  const kwargs = 'kwargs' in serialized ? serialized.kwargs : undefined;\n\n  const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature;\n  setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, temperature);\n\n  const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens;\n  setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, maxTokens);\n\n  const topP = invocationParams?.top_p ?? kwargs?.top_p;\n  setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, topP);\n\n  const frequencyPenalty = invocationParams?.frequency_penalty;\n  setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, frequencyPenalty);\n\n  const presencePenalty = invocationParams?.presence_penalty;\n  setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, presencePenalty);\n\n  // LangChain uses `stream`. We only set the attribute if the key actually exists\n  // (some callbacks report `false` even on streamed requests, this stems from LangChain's callback handler).\n  if (invocationParams \u0026\u0026 'stream' in invocationParams) {\n    setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream));\n  }\n\n  return attrs;\n}\n\n/**\n * Small helper to assemble boilerplate attributes shared by both request extractors.\n * Always uses 'chat' as the operation type for all LLM and chat model operations.\n */\nfunction baseRequestAttributes(\n  system: unknown,\n  modelName: unknown,\n  serialized: LangChainSerialized,\n  invocationParams?: Record\u003cstring, unknown\u003e,\n  langSmithMetadata?: Record\u003cstring, unknown\u003e,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  return {\n    [GEN_AI_SYSTEM_ATTRIBUTE]: asString(system ?? 'langchain'),\n    [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'chat',\n    [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: asString(modelName),\n    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n    ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata),\n  };\n}\n\n/**\n * Extracts attributes for plain LLM invocations (string prompts).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n *   LangChain LLM operations are treated as chat operations.\n * - When `recordInputs` is true, string prompts are wrapped into `{role:\"user\"}`\n *   messages to align with the chat schema used elsewhere.\n */\nexport function extractLLMRequestAttributes(\n  llm: LangChainSerialized,\n  prompts: string[],\n  recordInputs: boolean,\n  invocationParams?: Record\u003cstring, unknown\u003e,\n  langSmithMetadata?: Record\u003cstring, unknown\u003e,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  const system = langSmithMetadata?.ls_provider;\n  const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n  const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n  if (recordInputs \u0026\u0026 Array.isArray(prompts) \u0026\u0026 prompts.length \u003e 0) {\n    setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, prompts.length);\n    const messages = prompts.map(p =\u003e ({ role: 'user', content: p }));\n    setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, asString(messages));\n  }\n\n  return attrs;\n}\n\n/**\n * Extracts attributes for ChatModel invocations (array-of-arrays of messages).\n *\n * - Operation is tagged as `chat` following OpenTelemetry semantic conventions.\n *   LangChain chat model operations are chat operations.\n * - We flatten LangChain's `LangChainMessage[][]` and normalize shapes into a\n *   consistent `{ role, content }` array when `recordInputs` is true.\n * - Provider system value falls back to `serialized.id?.[2]`.\n */\nexport function extractChatModelRequestAttributes(\n  llm: LangChainSerialized,\n  langChainMessages: LangChainMessage[][],\n  recordInputs: boolean,\n  invocationParams?: Record\u003cstring, unknown\u003e,\n  langSmithMetadata?: Record\u003cstring, unknown\u003e,\n): Record\u003cstring, SpanAttributeValue\u003e {\n  const system = langSmithMetadata?.ls_provider ?? llm.id?.[2];\n  const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n  const attrs = baseRequestAttributes(system, modelName, llm, invocationParams, langSmithMetadata);\n\n  if (recordInputs \u0026\u0026 Array.isArray(langChainMessages) \u0026\u0026 langChainMessages.length \u003e 0) {\n    const normalized = normalizeLangChainMessages(langChainMessages.flat());\n\n    const { systemInstructions, filteredMessages } = extractSystemInstructions(normalized);\n\n    if (systemInstructions) {\n      setIfDefined(attrs, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n    }\n\n    const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;\n    setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, filteredLength);\n\n    const truncated = truncateGenAiMessages(filteredMessages as unknown[]);\n    setIfDefined(attrs, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, asString(truncated));\n  }\n\n  return attrs;\n}\n\n/**\n * Scans generations for Anthropic-style `tool_use` items and records them.\n *\n * LangChain represents some provider messages (e.g., Anthropic) with a `message.content`\n * array that may include objects `{ type: 'tool_use', ... }`. We collect and attach\n * them as a JSON array on `gen_ai.response.tool_calls` for downstream consumers.\n */\nfunction addToolCallsAttributes(generations: LangChainMessage[][], attrs: Record\u003cstring, SpanAttributeValue\u003e): void {\n  const toolCalls: unknown[] = [];\n  const flatGenerations = generations.flat();\n\n  for (const gen of flatGenerations) {\n    const content = gen.message?.content;\n    if (Array.isArray(content)) {\n      for (const item of content) {\n        const t = item as { type: string };\n        if (t.type === 'tool_use') toolCalls.push(t);\n      }\n    }\n  }\n\n  if (toolCalls.length \u003e 0) {\n    setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, asString(toolCalls));\n  }\n}\n\n/**\n * Adds token usage attributes, supporting both OpenAI (`tokenUsage`) and Anthropic (`usage`) formats.\n * - Preserve zero values (0 tokens) by avoiding truthy checks.\n * - Compute a total for Anthropic when not explicitly provided.\n * - Include cache token metrics when present.\n */\nfunction addTokenUsageAttributes(\n  llmOutput: LangChainLLMResult['llmOutput'],\n  attrs: Record\u003cstring, SpanAttributeValue\u003e,\n): void {\n  if (!llmOutput) return;\n\n  const tokenUsage = llmOutput.tokenUsage as\n    | { promptTokens?: number; completionTokens?: number; totalTokens?: number }\n    | undefined;\n  const anthropicUsage = llmOutput.usage as\n    | {\n        input_tokens?: number;\n        output_tokens?: number;\n        cache_creation_input_tokens?: number;\n        cache_read_input_tokens?: number;\n      }\n    | undefined;\n\n  if (tokenUsage) {\n    setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, tokenUsage.promptTokens);\n    setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, tokenUsage.completionTokens);\n    setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, tokenUsage.totalTokens);\n  } else if (anthropicUsage) {\n    setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.input_tokens);\n    setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, anthropicUsage.output_tokens);\n\n    // Compute total when not provided by the provider.\n    const input = Number(anthropicUsage.input_tokens);\n    const output = Number(anthropicUsage.output_tokens);\n    const total = (Number.isNaN(input) ? 0 : input) + (Number.isNaN(output) ? 0 : output);\n    if (total \u003e 0) setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, total);\n\n    // Extra Anthropic cache metrics (present only when caching is enabled)\n    if (anthropicUsage.cache_creation_input_tokens !== undefined)\n      setNumberIfDefined(\n        attrs,\n        GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE,\n        anthropicUsage.cache_creation_input_tokens,\n      );\n    if (anthropicUsage.cache_read_input_tokens !== undefined)\n      setNumberIfDefined(attrs, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.cache_read_input_tokens);\n  }\n}\n\n/**\n * Extracts response-related attributes based on a `LangChainLLMResult`.\n *\n * - Records finish reasons when present on generations (e.g., OpenAI)\n * - When `recordOutputs` is true, captures textual response content and any\n *   tool calls.\n * - Also propagates model name (`model_name` or `model`), response `id`, and\n *   `stop_reason` (for providers that use it).\n */\nexport function extractLlmResponseAttributes(\n  llmResult: LangChainLLMResult,\n  recordOutputs: boolean,\n): Record\u003cstring, SpanAttributeValue\u003e | undefined {\n  if (!llmResult) return;\n\n  const attrs: Record\u003cstring, SpanAttributeValue\u003e = {};\n\n  if (Array.isArray(llmResult.generations)) {\n    const finishReasons = llmResult.generations\n      .flat()\n      .map(g =\u003e {\n        // v1 uses generationInfo.finish_reason\n        if (g.generationInfo?.finish_reason) {\n          return g.generationInfo.finish_reason;\n        }\n        // v0.3+ uses generation_info.finish_reason\n        if (g.generation_info?.finish_reason) {\n          return g.generation_info.finish_reason;\n        }\n        return null;\n      })\n      .filter((r): r is string =\u003e typeof r === 'string');\n\n    if (finishReasons.length \u003e 0) {\n      setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, asString(finishReasons));\n    }\n\n    // Tool calls metadata (names, IDs) are not PII, so capture them regardless of recordOutputs\n    addToolCallsAttributes(llmResult.generations as LangChainMessage[][], attrs);\n\n    if (recordOutputs) {\n      const texts = llmResult.generations\n        .flat()\n        .map(gen =\u003e gen.text ?? gen.message?.content)\n        .filter(t =\u003e typeof t === 'string');\n\n      if (texts.length \u003e 0) {\n        setIfDefined(attrs, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, asString(texts));\n      }\n    }\n  }\n\n  addTokenUsageAttributes(llmResult.llmOutput, attrs);\n\n  const llmOutput = llmResult.llmOutput;\n\n  // Extract from v1 generations structure if available\n  const firstGeneration = llmResult.generations?.[0]?.[0];\n  const v1Message = firstGeneration?.message;\n\n  // Provider model identifier: `model_name` (OpenAI-style) or `model` (others)\n  // v1 stores this in message.response_metadata.model_name\n  const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name;\n  if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, modelName);\n\n  // Response ID: v1 stores this in message.id\n  const responseId = llmOutput?.id ?? v1Message?.id;\n  if (responseId) {\n    setIfDefined(attrs, GEN_AI_RESPONSE_ID_ATTRIBUTE, responseId);\n  }\n\n  // Stop reason: v1 stores this in message.response_metadata.finish_reason\n  const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason;\n  if (stopReason) {\n    setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, asString(stopReason));\n  }\n\n  return attrs;\n}\n","import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport { startSpanManual } from '../../tracing/trace';\nimport type { Span, SpanAttributeValue } from '../../types-hoist/span';\nimport {\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_REQUEST_MODEL_ATTRIBUTE,\n  GEN_AI_TOOL_INPUT_ATTRIBUTE,\n  GEN_AI_TOOL_NAME_ATTRIBUTE,\n  GEN_AI_TOOL_OUTPUT_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { resolveAIRecordingOptions } from '../ai/utils';\nimport { LANGCHAIN_ORIGIN } from './constants';\nimport type {\n  LangChainCallbackHandler,\n  LangChainLLMResult,\n  LangChainMessage,\n  LangChainOptions,\n  LangChainSerialized,\n} from './types';\nimport {\n  extractChatModelRequestAttributes,\n  extractLLMRequestAttributes,\n  extractLlmResponseAttributes,\n  getInvocationParams,\n} from './utils';\n\n/**\n * Creates a Sentry callback handler for LangChain\n * Returns a plain object that LangChain will call via duck-typing\n *\n * This is a stateful handler that tracks spans across multiple LangChain executions.\n */\nexport function createLangChainCallbackHandler(options: LangChainOptions = {}): LangChainCallbackHandler {\n  const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options);\n\n  // Internal state - single instance tracks all spans\n  const spanMap = new Map\u003cstring, Span\u003e();\n\n  /**\n   * Exit a span and clean up\n   */\n  const exitSpan = (runId: string): void =\u003e {\n    const span = spanMap.get(runId);\n    if (span?.isRecording()) {\n      span.end();\n      spanMap.delete(runId);\n    }\n  };\n\n  /**\n   * Handler for LLM Start\n   * This handler will be called by LangChain's callback handler when an LLM event is detected.\n   */\n  const handler: LangChainCallbackHandler = {\n    // Required LangChain BaseCallbackHandler properties\n    lc_serializable: false,\n    lc_namespace: ['langchain_core', 'callbacks', 'sentry'],\n    lc_secrets: undefined,\n    lc_attributes: undefined,\n    lc_aliases: undefined,\n    lc_serializable_keys: undefined,\n    lc_id: ['langchain_core', 'callbacks', 'sentry'],\n    lc_kwargs: {},\n    name: 'SentryCallbackHandler',\n\n    // BaseCallbackHandlerInput boolean flags\n    ignoreLLM: false,\n    ignoreChain: false,\n    ignoreAgent: false,\n    ignoreRetriever: false,\n    ignoreCustomEvent: false,\n    raiseError: false,\n    awaitHandlers: true,\n\n    handleLLMStart(\n      llm: unknown,\n      prompts: string[],\n      runId: string,\n      _parentRunId?: string,\n      _extraParams?: Record\u003cstring, unknown\u003e,\n      tags?: string[],\n      metadata?: Record\u003cstring, unknown\u003e,\n      _runName?: string,\n    ) {\n      const invocationParams = getInvocationParams(tags);\n      const attributes = extractLLMRequestAttributes(\n        llm as LangChainSerialized,\n        prompts,\n        recordInputs,\n        invocationParams,\n        metadata,\n      );\n      const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE];\n      const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE];\n\n      startSpanManual(\n        {\n          name: `${operationName} ${modelName}`,\n          op: 'gen_ai.chat',\n          attributes: {\n            ...attributes,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat',\n          },\n        },\n        span =\u003e {\n          spanMap.set(runId, span);\n          return span;\n        },\n      );\n    },\n\n    // Chat Model Start Handler\n    handleChatModelStart(\n      llm: unknown,\n      messages: unknown,\n      runId: string,\n      _parentRunId?: string,\n      _extraParams?: Record\u003cstring, unknown\u003e,\n      tags?: string[],\n      metadata?: Record\u003cstring, unknown\u003e,\n      _runName?: string,\n    ) {\n      const invocationParams = getInvocationParams(tags);\n      const attributes = extractChatModelRequestAttributes(\n        llm as LangChainSerialized,\n        messages as LangChainMessage[][],\n        recordInputs,\n        invocationParams,\n        metadata,\n      );\n      const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE];\n      const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE];\n\n      startSpanManual(\n        {\n          name: `${operationName} ${modelName}`,\n          op: 'gen_ai.chat',\n          attributes: {\n            ...attributes,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat',\n          },\n        },\n        span =\u003e {\n          spanMap.set(runId, span);\n          return span;\n        },\n      );\n    },\n\n    // LLM End Handler - note: handleLLMEnd with capital LLM (used by both LLMs and chat models!)\n    handleLLMEnd(\n      output: unknown,\n      runId: string,\n      _parentRunId?: string,\n      _tags?: string[],\n      _extraParams?: Record\u003cstring, unknown\u003e,\n    ) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        const attributes = extractLlmResponseAttributes(output as LangChainLLMResult, recordOutputs);\n        if (attributes) {\n          span.setAttributes(attributes);\n        }\n        exitSpan(runId);\n      }\n    },\n\n    // LLM Error Handler - note: handleLLMError with capital LLM\n    handleLLMError(error: Error, runId: string) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n        exitSpan(runId);\n      }\n\n      captureException(error, {\n        mechanism: {\n          handled: false,\n          type: `${LANGCHAIN_ORIGIN}.llm_error_handler`,\n        },\n      });\n    },\n\n    // Chain Start Handler\n    handleChainStart(\n      chain: { name?: string },\n      inputs: Record\u003cstring, unknown\u003e,\n      runId: string,\n      _parentRunId?: string,\n      _tags?: string[],\n      _metadata?: Record\u003cstring, unknown\u003e,\n      _runType?: string,\n      runName?: string,\n    ) {\n      const chainName = runName || chain.name || 'unknown_chain';\n      const attributes: Record\u003cstring, SpanAttributeValue\u003e = {\n        [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',\n        'langchain.chain.name': chainName,\n      };\n\n      // Add inputs if recordInputs is enabled\n      if (recordInputs) {\n        attributes['langchain.chain.inputs'] = JSON.stringify(inputs);\n      }\n\n      startSpanManual(\n        {\n          name: `chain ${chainName}`,\n          op: 'gen_ai.invoke_agent',\n          attributes: {\n            ...attributes,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.invoke_agent',\n          },\n        },\n        span =\u003e {\n          spanMap.set(runId, span);\n          return span;\n        },\n      );\n    },\n\n    // Chain End Handler\n    handleChainEnd(outputs: unknown, runId: string) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        // Add outputs if recordOutputs is enabled\n        if (recordOutputs) {\n          span.setAttributes({\n            'langchain.chain.outputs': JSON.stringify(outputs),\n          });\n        }\n        exitSpan(runId);\n      }\n    },\n\n    // Chain Error Handler\n    handleChainError(error: Error, runId: string) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n        exitSpan(runId);\n      }\n\n      captureException(error, {\n        mechanism: {\n          handled: false,\n          type: `${LANGCHAIN_ORIGIN}.chain_error_handler`,\n        },\n      });\n    },\n\n    // Tool Start Handler\n    handleToolStart(tool: { name?: string }, input: string, runId: string, _parentRunId?: string) {\n      const toolName = tool.name || 'unknown_tool';\n      const attributes: Record\u003cstring, SpanAttributeValue\u003e = {\n        [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n        [GEN_AI_TOOL_NAME_ATTRIBUTE]: toolName,\n      };\n\n      // Add input if recordInputs is enabled\n      if (recordInputs) {\n        attributes[GEN_AI_TOOL_INPUT_ATTRIBUTE] = input;\n      }\n\n      startSpanManual(\n        {\n          name: `execute_tool ${toolName}`,\n          op: 'gen_ai.execute_tool',\n          attributes: {\n            ...attributes,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.execute_tool',\n          },\n        },\n        span =\u003e {\n          spanMap.set(runId, span);\n          return span;\n        },\n      );\n    },\n\n    // Tool End Handler\n    handleToolEnd(output: unknown, runId: string) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        // Add output if recordOutputs is enabled\n        if (recordOutputs) {\n          span.setAttributes({\n            [GEN_AI_TOOL_OUTPUT_ATTRIBUTE]: JSON.stringify(output),\n          });\n        }\n        exitSpan(runId);\n      }\n    },\n\n    // Tool Error Handler\n    handleToolError(error: Error, runId: string) {\n      const span = spanMap.get(runId);\n      if (span?.isRecording()) {\n        span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n        exitSpan(runId);\n      }\n\n      captureException(error, {\n        mechanism: {\n          handled: false,\n          type: `${LANGCHAIN_ORIGIN}.tool_error_handler`,\n        },\n      });\n    },\n\n    // LangChain BaseCallbackHandler required methods\n    copy() {\n      return handler;\n    },\n\n    toJSON() {\n      return {\n        lc: 1,\n        type: 'not_implemented',\n        id: handler.lc_id,\n      };\n    },\n\n    toJSONNotImplemented() {\n      return {\n        lc: 1,\n        type: 'not_implemented',\n        id: handler.lc_id,\n      };\n    },\n  };\n\n  return handler;\n}\n","export const LANGGRAPH_INTEGRATION_NAME = 'LangGraph';\nexport const LANGGRAPH_ORIGIN = 'auto.ai.langgraph';\n","import type { Span } from '../../types-hoist/span';\nimport {\n  GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n  GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n  GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n  GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n  GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE,\n  GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport type { LangChainMessage } from '../langchain/types';\nimport { normalizeLangChainMessages } from '../langchain/utils';\nimport type { CompiledGraph, LangGraphTool } from './types';\n\n/**\n * Extract tool calls from messages\n */\nexport function extractToolCalls(messages: Array\u003cRecord\u003cstring, unknown\u003e\u003e | null): unknown[] | null {\n  if (!messages || messages.length === 0) {\n    return null;\n  }\n\n  const toolCalls: unknown[] = [];\n\n  for (const message of messages) {\n    if (message \u0026\u0026 typeof message === 'object') {\n      const msgToolCalls = message.tool_calls;\n      if (msgToolCalls \u0026\u0026 Array.isArray(msgToolCalls)) {\n        toolCalls.push(...msgToolCalls);\n      }\n    }\n  }\n\n  return toolCalls.length \u003e 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nexport function extractTokenUsageFromMessage(message: LangChainMessage): {\n  inputTokens: number;\n  outputTokens: number;\n  totalTokens: number;\n} {\n  const msg = message as Record\u003cstring, unknown\u003e;\n  let inputTokens = 0;\n  let outputTokens = 0;\n  let totalTokens = 0;\n\n  // Extract from usage_metadata (newer format)\n  if (msg.usage_metadata \u0026\u0026 typeof msg.usage_metadata === 'object') {\n    const usage = msg.usage_metadata as Record\u003cstring, unknown\u003e;\n    if (typeof usage.input_tokens === 'number') {\n      inputTokens = usage.input_tokens;\n    }\n    if (typeof usage.output_tokens === 'number') {\n      outputTokens = usage.output_tokens;\n    }\n    if (typeof usage.total_tokens === 'number') {\n      totalTokens = usage.total_tokens;\n    }\n    return { inputTokens, outputTokens, totalTokens };\n  }\n\n  // Fallback: Extract from response_metadata.tokenUsage\n  if (msg.response_metadata \u0026\u0026 typeof msg.response_metadata === 'object') {\n    const metadata = msg.response_metadata as Record\u003cstring, unknown\u003e;\n    if (metadata.tokenUsage \u0026\u0026 typeof metadata.tokenUsage === 'object') {\n      const tokenUsage = metadata.tokenUsage as Record\u003cstring, unknown\u003e;\n      if (typeof tokenUsage.promptTokens === 'number') {\n        inputTokens = tokenUsage.promptTokens;\n      }\n      if (typeof tokenUsage.completionTokens === 'number') {\n        outputTokens = tokenUsage.completionTokens;\n      }\n      if (typeof tokenUsage.totalTokens === 'number') {\n        totalTokens = tokenUsage.totalTokens;\n      }\n    }\n  }\n\n  return { inputTokens, outputTokens, totalTokens };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nexport function extractModelMetadata(span: Span, message: LangChainMessage): void {\n  const msg = message as Record\u003cstring, unknown\u003e;\n\n  if (msg.response_metadata \u0026\u0026 typeof msg.response_metadata === 'object') {\n    const metadata = msg.response_metadata as Record\u003cstring, unknown\u003e;\n\n    if (metadata.model_name \u0026\u0026 typeof metadata.model_name === 'string') {\n      span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, metadata.model_name);\n    }\n\n    if (metadata.finish_reason \u0026\u0026 typeof metadata.finish_reason === 'string') {\n      span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, [metadata.finish_reason]);\n    }\n  }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nexport function extractToolsFromCompiledGraph(compiledGraph: CompiledGraph): unknown[] | null {\n  if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n    return null;\n  }\n\n  const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n  if (!tools || !Array.isArray(tools) || tools.length === 0) {\n    return null;\n  }\n\n  // Extract name, description, and schema from each tool's lc_kwargs\n  return tools.map((tool: LangGraphTool) =\u003e ({\n    name: tool.lc_kwargs?.name,\n    description: tool.lc_kwargs?.description,\n    schema: tool.lc_kwargs?.schema,\n  }));\n}\n\n/**\n * Set response attributes on the span\n */\nexport function setResponseAttributes(span: Span, inputMessages: LangChainMessage[] | null, result: unknown): void {\n  // Extract messages from result\n  const resultObj = result as { messages?: LangChainMessage[] } | undefined;\n  const outputMessages = resultObj?.messages;\n\n  if (!outputMessages || !Array.isArray(outputMessages)) {\n    return;\n  }\n\n  // Get new messages (delta between input and output)\n  const inputCount = inputMessages?.length ?? 0;\n  const newMessages = outputMessages.length \u003e inputCount ? outputMessages.slice(inputCount) : [];\n\n  if (newMessages.length === 0) {\n    return;\n  }\n\n  // Extract and set tool calls from new messages BEFORE normalization\n  // (normalization strips tool_calls, so we need to extract them first)\n  const toolCalls = extractToolCalls(newMessages as Array\u003cRecord\u003cstring, unknown\u003e\u003e);\n  if (toolCalls) {\n    span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, JSON.stringify(toolCalls));\n  }\n\n  // Normalize the new messages\n  const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n  span.setAttribute(GEN_AI_RESPONSE_TEXT_ATTRIBUTE, JSON.stringify(normalizedNewMessages));\n\n  // Accumulate token usage across all messages\n  let totalInputTokens = 0;\n  let totalOutputTokens = 0;\n  let totalTokens = 0;\n\n  // Extract metadata from messages\n  for (const message of newMessages) {\n    // Accumulate token usage\n    const tokens = extractTokenUsageFromMessage(message);\n    totalInputTokens += tokens.inputTokens;\n    totalOutputTokens += tokens.outputTokens;\n    totalTokens += tokens.totalTokens;\n\n    // Extract model metadata (last message's metadata wins for model/finish_reason)\n    extractModelMetadata(span, message);\n  }\n\n  // Set accumulated token usage on span\n  if (totalInputTokens \u003e 0) {\n    span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, totalInputTokens);\n  }\n  if (totalOutputTokens \u003e 0) {\n    span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, totalOutputTokens);\n  }\n  if (totalTokens \u003e 0) {\n    span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, totalTokens);\n  }\n}\n","import { captureException } from '../../exports';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport {\n  GEN_AI_AGENT_NAME_ATTRIBUTE,\n  GEN_AI_CONVERSATION_ID_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n  GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n  GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,\n  GEN_AI_OPERATION_NAME_ATTRIBUTE,\n  GEN_AI_PIPELINE_NAME_ATTRIBUTE,\n  GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE,\n  GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { truncateGenAiMessages } from '../ai/messageTruncation';\nimport { extractSystemInstructions, resolveAIRecordingOptions } from '../ai/utils';\nimport type { LangChainMessage } from '../langchain/types';\nimport { normalizeLangChainMessages } from '../langchain/utils';\nimport { startSpan } from '../trace';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphOptions } from './types';\nimport { extractToolsFromCompiledGraph, setResponseAttributes } from './utils';\n\n/**\n * Instruments StateGraph's compile method to create spans for agent creation and invocation\n *\n * Wraps the compile() method to:\n * - Create a `gen_ai.create_agent` span when compile() is called\n * - Automatically wrap the invoke() method on the returned compiled graph with a `gen_ai.invoke_agent` span\n *\n */\nexport function instrumentStateGraphCompile(\n  originalCompile: (...args: unknown[]) =\u003e CompiledGraph,\n  options: LangGraphOptions,\n): (...args: unknown[]) =\u003e CompiledGraph {\n  return new Proxy(originalCompile, {\n    apply(target, thisArg, args: unknown[]): CompiledGraph {\n      return startSpan(\n        {\n          op: 'gen_ai.create_agent',\n          name: 'create_agent',\n          attributes: {\n            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.create_agent',\n            [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'create_agent',\n          },\n        },\n        span =\u003e {\n          try {\n            const compiledGraph = Reflect.apply(target, thisArg, args);\n            const compileOptions = args.length \u003e 0 ? (args[0] as Record\u003cstring, unknown\u003e) : {};\n\n            // Extract graph name\n            if (compileOptions?.name \u0026\u0026 typeof compileOptions.name === 'string') {\n              span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, compileOptions.name);\n              span.updateName(`create_agent ${compileOptions.name}`);\n            }\n\n            // Instrument agent invoke method on the compiled graph\n            const originalInvoke = compiledGraph.invoke;\n            if (originalInvoke \u0026\u0026 typeof originalInvoke === 'function') {\n              compiledGraph.invoke = instrumentCompiledGraphInvoke(\n                originalInvoke.bind(compiledGraph) as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e,\n                compiledGraph,\n                compileOptions,\n                options,\n              ) as typeof originalInvoke;\n            }\n\n            return compiledGraph;\n          } catch (error) {\n            span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n            captureException(error, {\n              mechanism: {\n                handled: false,\n                type: 'auto.ai.langgraph.error',\n              },\n            });\n            throw error;\n          }\n        },\n      );\n    },\n  }) as (...args: unknown[]) =\u003e CompiledGraph;\n}\n\n/**\n * Instruments CompiledGraph's invoke method to create spans for agent invocation\n *\n * Creates a `gen_ai.invoke_agent` span when invoke() is called\n */\nfunction instrumentCompiledGraphInvoke(\n  originalInvoke: (...args: unknown[]) =\u003e Promise\u003cunknown\u003e,\n  graphInstance: CompiledGraph,\n  compileOptions: Record\u003cstring, unknown\u003e,\n  options: LangGraphOptions,\n): (...args: unknown[]) =\u003e Promise\u003cunknown\u003e {\n  return new Proxy(originalInvoke, {\n    apply(target, thisArg, args: unknown[]): Promise\u003cunknown\u003e {\n      return startSpan(\n        {\n          op: 'gen_ai.invoke_agent',\n          name: 'invoke_agent',\n          attributes: {\n            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,\n            [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'invoke_agent',\n          },\n        },\n        async span =\u003e {\n          try {\n            const graphName = compileOptions?.name;\n\n            if (graphName \u0026\u0026 typeof graphName === 'string') {\n              span.setAttribute(GEN_AI_PIPELINE_NAME_ATTRIBUTE, graphName);\n              span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, graphName);\n              span.updateName(`invoke_agent ${graphName}`);\n            }\n\n            // Extract thread_id from the config (second argument)\n            // LangGraph uses config.configurable.thread_id for conversation/session linking\n            const config = args.length \u003e 1 ? (args[1] as Record\u003cstring, unknown\u003e | undefined) : undefined;\n            const configurable = config?.configurable as Record\u003cstring, unknown\u003e | undefined;\n            const threadId = configurable?.thread_id;\n            if (threadId \u0026\u0026 typeof threadId === 'string') {\n              span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, threadId);\n            }\n\n            // Extract available tools from the graph instance\n            const tools = extractToolsFromCompiledGraph(graphInstance);\n            if (tools) {\n              span.setAttribute(GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, JSON.stringify(tools));\n            }\n\n            // Parse input messages\n            const recordInputs = options.recordInputs;\n            const recordOutputs = options.recordOutputs;\n            const inputMessages =\n              args.length \u003e 0 ? ((args[0] as { messages?: LangChainMessage[] } | null)?.messages ?? []) : [];\n\n            if (inputMessages \u0026\u0026 recordInputs) {\n              const normalizedMessages = normalizeLangChainMessages(inputMessages);\n              const { systemInstructions, filteredMessages } = extractSystemInstructions(normalizedMessages);\n\n              if (systemInstructions) {\n                span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);\n              }\n\n              const truncatedMessages = truncateGenAiMessages(filteredMessages as unknown[]);\n              const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;\n              span.setAttributes({\n                [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: JSON.stringify(truncatedMessages),\n                [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n              });\n            }\n\n            // Call original invoke\n            const result = await Reflect.apply(target, thisArg, args);\n\n            // Set response attributes\n            if (recordOutputs) {\n              setResponseAttributes(span, inputMessages ?? null, result);\n            }\n\n            return result;\n          } catch (error) {\n            span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n            captureException(error, {\n              mechanism: {\n                handled: false,\n                type: 'auto.ai.langgraph.error',\n              },\n            });\n            throw error;\n          }\n        },\n      );\n    },\n  }) as (...args: unknown[]) =\u003e Promise\u003cunknown\u003e;\n}\n\n/**\n * Directly instruments a StateGraph instance to add tracing spans\n *\n * This function can be used to manually instrument LangGraph StateGraph instances\n * in environments where automatic instrumentation is not available or desired.\n *\n * @param stateGraph - The StateGraph instance to instrument\n * @param options - Optional configuration for recording inputs/outputs\n *\n * @example\n * ```typescript\n * import { instrumentLangGraph } from '@sentry/cloudflare';\n * import { StateGraph } from '@langchain/langgraph';\n *\n * const graph = new StateGraph(MessagesAnnotation)\n *   .addNode('agent', mockLlm)\n *   .addEdge(START, 'agent')\n *   .addEdge('agent', END);\n *\n * instrumentLangGraph(graph, { recordInputs: true, recordOutputs: true });\n * const compiled = graph.compile({ name: 'my_agent' });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function instrumentLangGraph\u003cT extends { compile: (...args: any[]) =\u003e any }\u003e(\n  stateGraph: T,\n  options?: LangGraphOptions,\n): T {\n  stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, resolveAIRecordingOptions(options));\n\n  return stateGraph;\n}\n","import type { SeverityLevel } from '../types-hoist/severity';\n\n/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nexport function getBreadcrumbLogLevelFromHttpStatusCode(statusCode: number | undefined): SeverityLevel | undefined {\n  // NOTE: undefined defaults to 'info' in Sentry\n  if (statusCode === undefined) {\n    return undefined;\n  } else if (statusCode \u003e= 400 \u0026\u0026 statusCode \u003c 500) {\n    return 'warning';\n  } else if (statusCode \u003e= 500) {\n    return 'error';\n  } else {\n    return undefined;\n  }\n}\n","import type { ConsoleLevel } from '../types-hoist/instrument';\n\n/**\n * An error emitted by Sentry SDKs and related utilities.\n * @deprecated This class is no longer used and will be removed in a future version. Use `Error` instead.\n */\nexport class SentryError extends Error {\n  public logLevel: ConsoleLevel;\n\n  public constructor(\n    public message: string,\n    logLevel: ConsoleLevel = 'warn',\n  ) {\n    super(message);\n\n    this.logLevel = logLevel;\n  }\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { debug } from './debug-logger';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\ndeclare const EdgeRuntime: string | undefined;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n  try {\n    new ErrorEvent('');\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n  try {\n    // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n    // 1 argument required, but only 0 present.\n    // @ts-expect-error It really needs 1 argument, not 0.\n    new DOMError('');\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n  try {\n    new DOMException('');\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n  return 'history' in WINDOW \u0026\u0026 !!WINDOW.history;\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nexport const supportsFetch = _isFetchSupported;\n\nfunction _isFetchSupported(): boolean {\n  if (!('fetch' in WINDOW)) {\n    return false;\n  }\n\n  try {\n    new Headers();\n    // Deno requires a valid URL so '' cannot be used as an argument\n    new Request('data:,');\n    new Response();\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFunction(func: Function): boolean {\n  return func \u0026\u0026 /^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n  if (typeof EdgeRuntime === 'string') {\n    return true;\n  }\n\n  if (!_isFetchSupported()) {\n    return false;\n  }\n\n  // Fast path to avoid DOM I/O\n  // eslint-disable-next-line @typescript-eslint/unbound-method\n  if (isNativeFunction(WINDOW.fetch)) {\n    return true;\n  }\n\n  // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n  // so create a \"pure\" iframe to see if that has native fetch\n  let result = false;\n  const doc = WINDOW.document;\n  // eslint-disable-next-line deprecation/deprecation\n  if (doc \u0026\u0026 typeof (doc.createElement as unknown) === 'function') {\n    try {\n      const sandbox = doc.createElement('iframe');\n      sandbox.hidden = true;\n      doc.head.appendChild(sandbox);\n      if (sandbox.contentWindow?.fetch) {\n        // eslint-disable-next-line @typescript-eslint/unbound-method\n        result = isNativeFunction(sandbox.contentWindow.fetch);\n      }\n      doc.head.removeChild(sandbox);\n    } catch (err) {\n      DEBUG_BUILD \u0026\u0026 debug.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n    }\n  }\n\n  return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n  return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nexport function supportsReferrerPolicy(): boolean {\n  // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n  // (see https://caniuse.com/#feat=referrer-policy),\n  // it doesn't. And it throws an exception instead of ignoring this parameter...\n  // REF: https://github.com/getsentry/raven-js/issues/1233\n\n  if (!_isFetchSupported()) {\n    return false;\n  }\n\n  try {\n    new Request('_', {\n      referrerPolicy: 'origin' as ReferrerPolicy,\n    });\n    return true;\n  } catch {\n    return false;\n  }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { getClient } from '../currentScopes';\nimport type { HandlerDataFetch } from '../types-hoist/instrument';\nimport type { WebFetchHeaders } from '../types-hoist/webfetchapi';\nimport { isError, isRequest } from '../utils/is';\nimport { addNonEnumerableProperty, fill } from '../utils/object';\nimport { supportsNativeFetch } from '../utils/supports';\nimport { timestampInSeconds } from '../utils/time';\nimport { GLOBAL_OBJ } from '../utils/worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(\n  handler: (data: HandlerDataFetch) =\u003e void,\n  skipNativeFetchCheck?: boolean,\n): void {\n  const type = 'fetch';\n  addHandler(type, handler);\n  maybeInstrument(type, () =\u003e instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nexport function addFetchEndInstrumentationHandler(handler: (data: HandlerDataFetch) =\u003e void): void {\n  const type = 'fetch-body-resolved';\n  addHandler(type, handler);\n  maybeInstrument(type, () =\u003e instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved?: (response: Response) =\u003e void, skipNativeFetchCheck: boolean = false): void {\n  if (skipNativeFetchCheck \u0026\u0026 !supportsNativeFetch()) {\n    return;\n  }\n\n  fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () =\u003e void): () =\u003e void {\n    return function (...args: any[]): void {\n      // We capture the error right here and not in the Promise error callback because Safari (and probably other\n      // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n      // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n      //       it means the error, that was caused by your fetch call did not\n      //       have a stack trace, so the SDK backfilled the stack trace so\n      //       you can see which fetch call failed.\n      const virtualError = new Error();\n\n      const { method, url } = parseFetchArgs(args);\n      const handlerData: HandlerDataFetch = {\n        args,\n        fetchData: {\n          method,\n          url,\n        },\n        startTimestamp: timestampInSeconds() * 1000,\n        // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n        virtualError,\n        headers: getHeadersFromFetchArgs(args),\n      };\n\n      // if there is no callback, fetch is instrumented directly\n      if (!onFetchResolved) {\n        triggerHandlers('fetch', {\n          ...handlerData,\n        });\n      }\n\n      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n      return originalFetch.apply(GLOBAL_OBJ, args).then(\n        async (response: Response) =\u003e {\n          if (onFetchResolved) {\n            onFetchResolved(response);\n          } else {\n            triggerHandlers('fetch', {\n              ...handlerData,\n              endTimestamp: timestampInSeconds() * 1000,\n              response,\n            });\n          }\n\n          return response;\n        },\n        (error: Error) =\u003e {\n          triggerHandlers('fetch', {\n            ...handlerData,\n            endTimestamp: timestampInSeconds() * 1000,\n            error,\n          });\n\n          if (isError(error) \u0026\u0026 error.stack === undefined) {\n            // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n            //       it means the error, that was caused by your fetch call did not\n            //       have a stack trace, so the SDK backfilled the stack trace so\n            //       you can see which fetch call failed.\n            error.stack = virtualError.stack;\n            addNonEnumerableProperty(error, 'framesToPop', 1);\n          }\n\n          // We enhance fetch error messages with hostname information based on the configuration.\n          // Possible messages we handle here:\n          // * \"Failed to fetch\" (chromium)\n          // * \"Load failed\" (webkit)\n          // * \"NetworkError when attempting to fetch resource.\" (firefox)\n          const client = getClient();\n          const enhanceOption = client?.getOptions().enhanceFetchErrorMessages ?? 'always';\n          const shouldEnhance = enhanceOption !== false;\n\n          if (\n            shouldEnhance \u0026\u0026\n            error instanceof TypeError \u0026\u0026\n            (error.message === 'Failed to fetch' ||\n              error.message === 'Load failed' ||\n              error.message === 'NetworkError when attempting to fetch resource.')\n          ) {\n            try {\n              const url = new URL(handlerData.fetchData.url);\n              const hostname = url.host;\n\n              if (enhanceOption === 'always') {\n                // Modify the error message directly\n                error.message = `${error.message} (${hostname})`;\n              } else {\n                // Store hostname as non-enumerable property for Sentry-only enhancement\n                // This preserves the original error message for third-party packages\n                addNonEnumerableProperty(error, '__sentry_fetch_url_host__', hostname);\n              }\n            } catch {\n              // ignore it if errors happen here\n            }\n          }\n\n          // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n          //       it means the sentry.javascript SDK caught an error invoking your application code.\n          //       This is expected behavior and NOT indicative of a bug with sentry.javascript.\n          throw error;\n        },\n      );\n    };\n  });\n}\n\nasync function resolveResponse(res: Response | undefined, onFinishedResolving: () =\u003e void): Promise\u003cvoid\u003e {\n  if (res?.body) {\n    const body = res.body;\n    const responseReader = body.getReader();\n\n    // Define a maximum duration after which we just cancel\n    const maxFetchDurationTimeout = setTimeout(\n      () =\u003e {\n        body.cancel().then(null, () =\u003e {\n          // noop\n        });\n      },\n      90 * 1000, // 90s\n    );\n\n    let readingActive = true;\n    while (readingActive) {\n      let chunkTimeout;\n      try {\n        // abort reading if read op takes more than 5s\n        chunkTimeout = setTimeout(() =\u003e {\n          body.cancel().then(null, () =\u003e {\n            // noop on error\n          });\n        }, 5000);\n\n        // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n        const { done } = await responseReader.read();\n\n        clearTimeout(chunkTimeout);\n\n        if (done) {\n          onFinishedResolving();\n          readingActive = false;\n        }\n      } catch {\n        readingActive = false;\n      } finally {\n        clearTimeout(chunkTimeout);\n      }\n    }\n\n    clearTimeout(maxFetchDurationTimeout);\n\n    responseReader.releaseLock();\n    body.cancel().then(null, () =\u003e {\n      // noop on error\n    });\n  }\n}\n\nfunction streamHandler(response: Response): void {\n  // clone response for awaiting stream\n  let clonedResponseForResolving: Response;\n  try {\n    clonedResponseForResolving = response.clone();\n  } catch {\n    return;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-floating-promises\n  resolveResponse(clonedResponseForResolving, () =\u003e {\n    triggerHandlers('fetch-body-resolved', {\n      endTimestamp: timestampInSeconds() * 1000,\n      response,\n    });\n  });\n}\n\nfunction hasProp\u003cT extends string\u003e(obj: unknown, prop: T): obj is Record\u003cstring, string\u003e {\n  return !!obj \u0026\u0026 typeof obj === 'object' \u0026\u0026 !!(obj as Record\u003cstring, string\u003e)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n  if (typeof resource === 'string') {\n    return resource;\n  }\n\n  if (!resource) {\n    return '';\n  }\n\n  if (hasProp(resource, 'url')) {\n    return resource.url;\n  }\n\n  if (resource.toString) {\n    return resource.toString();\n  }\n\n  return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n  if (fetchArgs.length === 0) {\n    return { method: 'GET', url: '' };\n  }\n\n  if (fetchArgs.length === 2) {\n    const [resource, options] = fetchArgs as [FetchResource, object];\n\n    return {\n      url: getUrlFromResource(resource),\n      method: hasProp(options, 'method')\n        ? String(options.method).toUpperCase()\n        : // Request object as first argument\n          isRequest(resource) \u0026\u0026 hasProp(resource, 'method')\n          ? String(resource.method).toUpperCase()\n          : 'GET',\n    };\n  }\n\n  const arg = fetchArgs[0];\n  return {\n    url: getUrlFromResource(arg as FetchResource),\n    method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n  };\n}\n\nfunction getHeadersFromFetchArgs(fetchArgs: unknown[]): WebFetchHeaders | undefined {\n  const [requestArgument, optionsArgument] = fetchArgs;\n\n  try {\n    if (\n      typeof optionsArgument === 'object' \u0026\u0026\n      optionsArgument !== null \u0026\u0026\n      'headers' in optionsArgument \u0026\u0026\n      optionsArgument.headers\n    ) {\n      return new Headers(optionsArgument.headers as any);\n    }\n\n    if (isRequest(requestArgument)) {\n      return new Headers(requestArgument.headers);\n    }\n  } catch {\n    // noop\n  }\n\n  return;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser.  We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `debug` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader' | 'aws-lambda-layer';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n  return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' \u0026\u0026 !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n  // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n  /* __SENTRY_SDK_SOURCE__ */ return 'npm';\n}\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the `debug` singleton, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n  // explicitly check for browser bundles as those can be optimized statically\n  // by terser/rollup.\n  return (\n    !isBrowserBundle() \u0026\u0026\n    Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n  );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod: any, request: string): any {\n  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n  return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @param existingModule module to use for requiring\n * @returns possibly required module\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function loadModule\u003cT\u003e(moduleName: string, existingModule: any = module): T | undefined {\n  let mod: T | undefined;\n\n  try {\n    mod = dynamicRequire(existingModule, moduleName);\n  } catch {\n    // no-empty\n  }\n\n  if (!mod) {\n    try {\n      const { cwd } = dynamicRequire(existingModule, 'process');\n      mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`) as T;\n    } catch {\n      // no-empty\n    }\n  }\n\n  return mod;\n}\n","import { isNodeEnv } from './node';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/**\n * Returns true if we are in the browser.\n */\nexport function isBrowser(): boolean {\n  // eslint-disable-next-line no-restricted-globals\n  return typeof window !== 'undefined' \u0026\u0026 (!isNodeEnv() || isElectronNodeRenderer());\n}\n\ntype ElectronProcess = { type?: string };\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer(): boolean {\n  const process = (GLOBAL_OBJ as typeof GLOBAL_OBJ \u0026 { process?: ElectronProcess }).process;\n  return process?.type === 'renderer';\n}\n","/**\n * Replaces constructor functions in module exports, handling read-only properties,\n * and both default and named exports by wrapping them with the constructor.\n *\n * @param exports The module exports object to modify\n * @param exportName The name of the export to replace (e.g., 'GoogleGenAI', 'Anthropic', 'OpenAI')\n * @param wrappedConstructor The wrapped constructor function to replace the original with\n * @returns void\n */\nexport function replaceExports(\n  exports: { [key: string]: unknown },\n  exportName: string,\n  wrappedConstructor: unknown,\n): void {\n  const original = exports[exportName];\n\n  if (typeof original !== 'function') {\n    return;\n  }\n\n  // Replace the named export - handle read-only properties\n  try {\n    exports[exportName] = wrappedConstructor;\n  } catch {\n    // If direct assignment fails, override the property descriptor\n    Object.defineProperty(exports, exportName, {\n      value: wrappedConstructor,\n      writable: true,\n      configurable: true,\n      enumerable: true,\n    });\n  }\n\n  // Replace the default export if it points to the original constructor\n  if (exports.default === original) {\n    try {\n      exports.default = wrappedConstructor;\n    } catch {\n      Object.defineProperty(exports, 'default', {\n        value: wrappedConstructor,\n        writable: true,\n        configurable: true,\n        enumerable: true,\n      });\n    }\n  }\n}\n","// This code was originally forked from https://github.com/felixge/node-stack-trace\n// Since then it has been highly modified to fit our needs.\n\n// Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)//\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions://\n//\n//  The above copyright notice and this permission notice shall be included in\n//  all copies or substantial portions of the Software.//\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n//  THE SOFTWARE.\n\nimport type { StackLineParser, StackLineParserFn } from '../types-hoist/stacktrace';\nimport { normalizeStackTracePath, UNKNOWN_FUNCTION } from './stacktrace';\n\nexport type GetModuleFn = (filename: string | undefined) =\u003e string | undefined;\n\n/**\n * Does this filename look like it's part of the app code?\n */\nexport function filenameIsInApp(filename: string, isNative: boolean = false): boolean {\n  const isInternal =\n    isNative ||\n    (filename \u0026\u0026\n      // It's not internal if it's an absolute linux path\n      !filename.startsWith('/') \u0026\u0026\n      // It's not internal if it's an absolute windows path\n      !filename.match(/^[A-Z]:/) \u0026\u0026\n      // It's not internal if the path is starting with a dot\n      !filename.startsWith('.') \u0026\u0026\n      // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack\n      !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//)); // Schema from: https://stackoverflow.com/a/3641782\n\n  // in_app is all that's not an internal Node function or a module within node_modules\n  // note that isNative appears to return true even for node core libraries\n  // see https://github.com/getsentry/raven-node/issues/176\n\n  return !isInternal \u0026\u0026 filename !== undefined \u0026\u0026 !filename.includes('node_modules/');\n}\n\n/** Node Stack line parser */\nexport function node(getModule?: GetModuleFn): StackLineParserFn {\n  const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n  const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n  const DATA_URI_MATCH = /at (?:async )?(.+?) \\(data:(.*?),/;\n\n  return (line: string) =\u003e {\n    const dataUriMatch = line.match(DATA_URI_MATCH);\n    if (dataUriMatch) {\n      return {\n        filename: `\u003cdata:${dataUriMatch[2]}\u003e`,\n        function: dataUriMatch[1],\n      };\n    }\n\n    const lineMatch = line.match(FULL_MATCH);\n\n    if (lineMatch) {\n      let object: string | undefined;\n      let method: string | undefined;\n      let functionName: string | undefined;\n      let typeName: string | undefined;\n      let methodName: string | undefined;\n\n      if (lineMatch[1]) {\n        functionName = lineMatch[1];\n\n        let methodStart = functionName.lastIndexOf('.');\n        if (functionName[methodStart - 1] === '.') {\n          methodStart--;\n        }\n\n        if (methodStart \u003e 0) {\n          object = functionName.slice(0, methodStart);\n          method = functionName.slice(methodStart + 1);\n          const objectEnd = object.indexOf('.Module');\n          if (objectEnd \u003e 0) {\n            functionName = functionName.slice(objectEnd + 1);\n            object = object.slice(0, objectEnd);\n          }\n        }\n        typeName = undefined;\n      }\n\n      if (method) {\n        typeName = object;\n        methodName = method;\n      }\n\n      if (method === '\u003canonymous\u003e') {\n        methodName = undefined;\n        functionName = undefined;\n      }\n\n      if (functionName === undefined) {\n        methodName = methodName || UNKNOWN_FUNCTION;\n        functionName = typeName ? `${typeName}.${methodName}` : methodName;\n      }\n\n      let filename = normalizeStackTracePath(lineMatch[2]);\n      const isNative = lineMatch[5] === 'native';\n\n      if (!filename \u0026\u0026 lineMatch[5] \u0026\u0026 !isNative) {\n        filename = lineMatch[5];\n      }\n\n      const maybeDecodedFilename = filename ? _safeDecodeURI(filename) : undefined;\n      return {\n        filename: maybeDecodedFilename ?? filename,\n        module: maybeDecodedFilename \u0026\u0026 getModule?.(maybeDecodedFilename),\n        function: functionName,\n        lineno: _parseIntOrUndefined(lineMatch[3]),\n        colno: _parseIntOrUndefined(lineMatch[4]),\n        in_app: filenameIsInApp(filename || '', isNative),\n      };\n    }\n\n    if (line.match(FILENAME_MATCH)) {\n      return {\n        filename: line,\n      };\n    }\n\n    return undefined;\n  };\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/core so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n  return [90, node(getModule)];\n}\n\nfunction _parseIntOrUndefined(input: string | undefined): number | undefined {\n  return parseInt(input || '', 10) || undefined;\n}\n\nfunction _safeDecodeURI(filename: string): string | undefined {\n  try {\n    return decodeURI(filename);\n  } catch {\n    return undefined;\n  }\n}\n","import type { StackFrame } from '../types-hoist/stackframe';\nimport { filenameIsInApp } from './node-stack-trace';\nimport { UNKNOWN_FUNCTION } from './stacktrace';\n\ntype WatchdogReturn = {\n  /** Resets the watchdog timer */\n  poll: () =\u003e void;\n  /** Enables or disables the watchdog timer */\n  enabled: (state: boolean) =\u003e void;\n};\n\ntype CreateTimerImpl = () =\u003e { getTimeMs: () =\u003e number; reset: () =\u003e void };\n\n/**\n * A node.js watchdog timer\n * @param pollInterval The interval that we expect to get polled at\n * @param anrThreshold The threshold for when we consider ANR\n * @param callback The callback to call for ANR\n * @returns An object with `poll` and `enabled` functions {@link WatchdogReturn}\n */\nexport function watchdogTimer(\n  createTimer: CreateTimerImpl,\n  pollInterval: number,\n  anrThreshold: number,\n  callback: () =\u003e void,\n): WatchdogReturn {\n  const timer = createTimer();\n  let triggered = false;\n  let enabled = true;\n\n  setInterval(() =\u003e {\n    const diffMs = timer.getTimeMs();\n\n    if (triggered === false \u0026\u0026 diffMs \u003e pollInterval + anrThreshold) {\n      triggered = true;\n      if (enabled) {\n        callback();\n      }\n    }\n\n    if (diffMs \u003c pollInterval + anrThreshold) {\n      triggered = false;\n    }\n  }, 20);\n\n  return {\n    poll: () =\u003e {\n      timer.reset();\n    },\n    enabled: (state: boolean) =\u003e {\n      enabled = state;\n    },\n  };\n}\n\n// types copied from inspector.d.ts\ninterface Location {\n  scriptId: string;\n  lineNumber: number;\n  columnNumber?: number;\n}\n\ninterface CallFrame {\n  functionName: string;\n  location: Location;\n  url: string;\n}\n\n/**\n * Converts Debugger.CallFrame to Sentry StackFrame\n */\nexport function callFrameToStackFrame(\n  frame: CallFrame,\n  url: string | undefined,\n  getModuleFromFilename: (filename: string | undefined) =\u003e string | undefined,\n): StackFrame {\n  const filename = url ? url.replace(/^file:\\/\\//, '') : undefined;\n\n  // CallFrame row/col are 0 based, whereas StackFrame are 1 based\n  const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : undefined;\n  const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : undefined;\n\n  return {\n    filename,\n    module: getModuleFromFilename(filename),\n    function: frame.functionName || UNKNOWN_FUNCTION,\n    colno,\n    lineno,\n    in_app: filename ? filenameIsInApp(filename) : undefined,\n  };\n}\n","/** A simple Least Recently Used map */\nexport class LRUMap\u003cK, V\u003e {\n  private readonly _cache: Map\u003cK, V\u003e;\n\n  public constructor(private readonly _maxSize: number) {\n    this._cache = new Map\u003cK, V\u003e();\n  }\n\n  /** Get the current size of the cache */\n  public get size(): number {\n    return this._cache.size;\n  }\n\n  /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */\n  public get(key: K): V | undefined {\n    const value = this._cache.get(key);\n    if (value === undefined) {\n      return undefined;\n    }\n    // Remove and re-insert to update the order\n    this._cache.delete(key);\n    this._cache.set(key, value);\n    return value;\n  }\n\n  /** Insert an entry and evict an older entry if we've reached maxSize */\n  public set(key: K, value: V): void {\n    if (this._cache.size \u003e= this._maxSize) {\n      // keys() returns an iterator in insertion order so keys().next() gives us the oldest key\n      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n      const nextKey = this._cache.keys().next().value!;\n      this._cache.delete(nextKey);\n    }\n    this._cache.set(key, value);\n  }\n\n  /** Remove an entry and return the entry if it was in the cache */\n  public remove(key: K): V | undefined {\n    const value = this._cache.get(key);\n    if (value) {\n      this._cache.delete(key);\n    }\n    return value;\n  }\n\n  /** Clear all entries */\n  public clear(): void {\n    this._cache.clear();\n  }\n\n  /** Get all the keys */\n  public keys(): Array\u003cK\u003e {\n    return Array.from(this._cache.keys());\n  }\n\n  /** Get all the values */\n  public values(): Array\u003cV\u003e {\n    const values: V[] = [];\n    this._cache.forEach(value =\u003e values.push(value));\n    return values;\n  }\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\ndeclare const EdgeRuntime: string | undefined;\n\ninterface VercelRequestContextGlobal {\n  get?():\n    | {\n        waitUntil?: (task: Promise\u003cunknown\u003e) =\u003e void;\n      }\n    | undefined;\n}\n\n/**\n * Function that delays closing of a Vercel lambda until the provided promise is resolved.\n *\n * Vendored from https://www.npmjs.com/package/@vercel/functions\n */\nexport function vercelWaitUntil(task: Promise\u003cunknown\u003e): void {\n  // We only flush manually in Vercel Edge runtime\n  // In Node runtime, we use process.on('SIGTERM') instead\n  if (typeof EdgeRuntime !== 'string') {\n    return;\n  }\n  const vercelRequestContextGlobal: VercelRequestContextGlobal | undefined =\n    // @ts-expect-error This is not typed\n    GLOBAL_OBJ[Symbol.for('@vercel/request-context')];\n\n  const ctx = vercelRequestContextGlobal?.get?.();\n\n  if (ctx?.waitUntil) {\n    ctx.waitUntil(task);\n  }\n}\n","import { flush } from '../exports';\nimport { debug } from './debug-logger';\nimport { vercelWaitUntil } from './vercelWaitUntil';\nimport { GLOBAL_OBJ } from './worldwide';\n\ntype MinimalCloudflareContext = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  waitUntil(promise: Promise\u003cany\u003e): void;\n};\n\nasync function flushWithTimeout(timeout: number): Promise\u003cvoid\u003e {\n  try {\n    debug.log('Flushing events...');\n    await flush(timeout);\n    debug.log('Done flushing events');\n  } catch (e) {\n    debug.log('Error while flushing events:\\n', e);\n  }\n}\n\n/**\n *  Flushes the event queue with a timeout in serverless environments to ensure that events are sent to Sentry before the\n *  serverless function execution ends.\n *\n * The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.\n *\n * This function is aware of the following serverless platforms:\n * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).\n *               If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).\n * - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.\n * - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables\n *   and uses a regular `await flush()`.\n *\n *  @internal This function is supposed for internal Sentry SDK usage only.\n *  @hidden\n */\nexport async function flushIfServerless(\n  params: // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    | { timeout?: number; cloudflareWaitUntil?: (task: Promise\u003cany\u003e) =\u003e void }\n    | { timeout?: number; cloudflareCtx?: MinimalCloudflareContext } = {},\n): Promise\u003cvoid\u003e {\n  const { timeout = 2000 } = params;\n\n  if ('cloudflareWaitUntil' in params \u0026\u0026 typeof params?.cloudflareWaitUntil === 'function') {\n    params.cloudflareWaitUntil(flushWithTimeout(timeout));\n    return;\n  }\n\n  if ('cloudflareCtx' in params \u0026\u0026 typeof params.cloudflareCtx?.waitUntil === 'function') {\n    params.cloudflareCtx.waitUntil(flushWithTimeout(timeout));\n    return;\n  }\n\n  // Note: vercelWaitUntil only does something in Vercel Edge runtime\n  // In Node runtime, we use process.on('SIGTERM') instead\n  // @ts-expect-error This is not typed\n  if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {\n    // Vercel has a waitUntil equivalent that works without execution context\n    vercelWaitUntil(flushWithTimeout(timeout));\n    return;\n  }\n\n  if (typeof process === 'undefined') {\n    return;\n  }\n\n  const isServerless =\n    !!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions\n    !!process.env.LAMBDA_TASK_ROOT || // AWS Lambda\n    !!process.env.K_SERVICE || // Google Cloud Run\n    !!process.env.CF_PAGES || // Cloudflare Pages\n    !!process.env.VERCEL ||\n    !!process.env.NETLIFY;\n\n  if (isServerless) {\n    // Use regular flush for environments without a generic waitUntil mechanism\n    await flushWithTimeout(timeout);\n  }\n}\n","// Based on https://github.com/sindresorhus/escape-string-regexp but with modifications to:\n//   a) reduce the size by skipping the runtime type - checking\n//   b) ensure it gets down - compiled for old versions of Node(the published package only supports Node 14+).\n//\n// MIT License\n//\n// Copyright (c) Sindre Sorhus \u003csindresorhus@gmail.com\u003e (https://sindresorhus.com)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files(the \"Software\"), to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and\n// to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n// the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\n// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n  // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n  // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n  return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$\u0026').replace(/-/g, '\\\\x2d');\n}\n"],"version":3}
