PH-1: MVP личного ассистента — Gmail, Google Calendar, Telegram, WhatsApp #1

Merged
peppa-bot merged 6 commits from task/ph-1 into main 2026-11-28 12:22:37 +00:00
6124 changed files with 903230 additions and 5 deletions

6
.dockerignore Normal file
View File

@ -0,0 +1,6 @@
node_modules
dist
data
.git
.env
*.log

2
.gitignore vendored
View File

@ -2,3 +2,5 @@ node_modules/
.env
.env.local
.DS_Store
dist/
data/

14
.peppa/memory/ph-1.md Normal file
View File

@ -0,0 +1,14 @@
# Память: PH-1
## Команды
- Стек Node 22 + TS без фреймворка: pnpm test (node --test со снятием типов, test/**/*.test.ts), pnpm lint (biome), pnpm build (tsc → dist/, запуск node dist/src/server.js). Импорты с расширением .ts.
## Соглашения
- Тексты UI и бота — locales/{ru,kk,en}.json (ключи, в коде только t()); слова продукта — раздел PH-1 в docs/glossary.md.
## Решения
- PH-1: состояние в JSON-файле DATA_DIR/state.json (том data в deploy/compose.yml); секреты пробрасываются в compose явным списком ${NAME:-}.
- PH-1: Telegram-бот общий с другими проектами — при webhook или 409 от getUpdates режим только отправки (TELEGRAM_CHAT_ID), deleteWebhook не вызываем.
## Грабли
- Telegram Bot API на неверный ключ отвечает 404, а не 401. Моки внешних API — test/mocks.ts (mockGoogle, mockTelegram), подменяют fetch.

View File

@ -1 +1,23 @@
{"slug":"pr-hw1","key":"PH","name":"PR-HW1","peppaUrl":"https://peppa.telecom.quest"}
{
"slug": "pr-hw1",
"key": "PH",
"name": "PR-HW1",
"peppaUrl": "https://peppa.telecom.quest",
"checks": {
"install": "bash scripts/pnpm.sh install --frozen-lockfile",
"lint": "bash scripts/pnpm.sh lint",
"typecheck": "bash scripts/pnpm.sh typecheck",
"test": "bash scripts/pnpm.sh test",
"build": "bash scripts/pnpm.sh build"
},
"deploy": {
"compose": "deploy/compose.yml",
"service": "web",
"port": 3000,
"health": "/healthz",
"screenshots": [
"/",
"/how"
]
}
}

View File

@ -0,0 +1,79 @@
type Sender = {
send(record: any): Promise<any>;
sendBatch(batch: any): Promise<any>;
};
export type Producer = Sender & {
connect(): Promise<void>;
disconnect(): Promise<void>;
isIdempotent(): boolean;
transaction(): Promise<Transaction>;
[key: string]: any;
};
export type Transaction = Sender & {
sendOffsets(offsets: any): Promise<void>;
commit(): Promise<void>;
abort(): Promise<void>;
isActive(): boolean;
};
export type Consumer = {
connect(): Promise<void>;
disconnect(): Promise<void>;
subscribe(subscription: any): Promise<void>;
run(config?: any): Promise<void>;
[key: string]: any;
};
export declare class Kafka {
consumer(config: any): Consumer;
producer(config?: any): Producer;
[key: string]: any;
}
export interface Message {
key?: Buffer | string | null;
value: Buffer | string | null;
partition?: number;
headers?: Record<string, Buffer | string | (Buffer | string)[] | undefined>;
timestamp?: string;
}
export type KafkaMessage = {
[key: string]: any;
} & Message;
export type RecordMetadata = {
topicName: string;
partition: number;
errorCode: number;
offset?: string;
timestamp?: string;
baseOffset?: string;
logAppendTime?: string;
logStartOffset?: string;
};
export interface EachMessagePayload {
topic: string;
partition: number;
message: KafkaMessage;
heartbeat(): Promise<void>;
pause(): () => void;
}
export interface EachBatchPayload {
batch: any;
resolveOffset(offset: string): void;
heartbeat(): Promise<void>;
pause(): () => void;
commitOffsetsIfNecessary(offsets?: any): Promise<void>;
uncommittedOffsets(): any;
isRunning(): boolean;
isStale(): boolean;
}
export type EachMessageHandler = (payload: EachMessagePayload) => Promise<void>;
export type EachBatchHandler = (payload: EachBatchPayload) => Promise<void>;
export type ConsumerRunConfig = {
autoCommit?: boolean;
autoCommitInterval?: number | null;
autoCommitThreshold?: number | null;
eachBatchAutoResolve?: boolean;
partitionsConsumedConcurrently?: number;
eachBatch?: EachBatchHandler;
eachMessage?: EachMessageHandler;
};
export {};
//# sourceMappingURL=kafkajs-types.d.ts.map

View File

@ -0,0 +1,20 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const object = require('./object.js');
const weakRef = require('./weakRef.js');
const SCOPE_SPAN_FIELD = "_sentrySpan";
function _setSpanForScope(scope, span) {
if (span) {
object.addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, weakRef.makeWeakRef(span));
} else {
delete scope[SCOPE_SPAN_FIELD];
}
}
function _getSpanForScope(scope) {
return weakRef.derefWeakRef(scope[SCOPE_SPAN_FIELD]);
}
exports._getSpanForScope = _getSpanForScope;
exports._setSpanForScope = _setSpanForScope;
//# sourceMappingURL=spanOnScope.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"measurement.js","sources":["../../../src/tracing/measurement.ts"],"sourcesContent":["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/measurement';\nimport type { TimedEvent } from '../types/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 && getRootSpan(activeSpan);\n\n if (rootSpan) {\n DEBUG_BUILD && 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 => {\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' && typeof value === 'number') {\n measurements[event.name] = { value, unit };\n }\n });\n\n return measurements;\n}\n"],"names":["getActiveSpan","getRootSpan","DEBUG_BUILD","debug","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT"],"mappings":";;;;;;;AAcO,SAAS,eAAe,IAAA,EAAc,KAAA,EAAe,IAAA,EAAuB,UAAA,GAAaA,yBAAc,EAAS;AACrH,EAAA,MAAM,QAAA,GAAW,UAAA,IAAcC,qBAAA,CAAY,UAAU,CAAA;AAErD,EAAA,IAAI,QAAA,EAAU;AACZ,IAAAC,sBAAA,IAAeC,iBAAA,CAAM,IAAI,CAAA,gDAAA,EAAmD,IAAI,MAAM,KAAK,CAAA,CAAA,EAAI,IAAI,CAAA,CAAE,CAAA;AACrG,IAAA,QAAA,CAAS,SAAS,IAAA,EAAM;AAAA,MACtB,CAACC,8DAA2C,GAAG,KAAA;AAAA,MAC/C,CAACC,6DAA0C,GAAG;AAAA,KAC/C,CAAA;AAAA,EACH;AACF;AAKO,SAAS,0BAA0B,MAAA,EAAgD;AACxF,EAAA,IAAI,CAAC,MAAA,IAAU,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG;AAClC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAA6B,EAAC;AACpC,EAAA,MAAA,CAAO,QAAQ,CAAA,KAAA,KAAS;AACtB,IAAA,MAAM,UAAA,GAAa,KAAA,CAAM,UAAA,IAAc,EAAC;AACxC,IAAA,MAAM,IAAA,GAAO,WAAWA,6DAA0C,CAAA;AAClE,IAAA,MAAM,KAAA,GAAQ,WAAWD,8DAA2C,CAAA;AAEpE,IAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,OAAO,UAAU,QAAA,EAAU;AACzD,MAAA,YAAA,CAAa,KAAA,CAAM,IAAI,CAAA,GAAI,EAAE,OAAO,IAAA,EAAK;AAAA,IAC3C;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,YAAA;AACT;;;;;"}

View File

@ -0,0 +1 @@
{"version":3,"file":"version.js","sources":["../../../src/utils/version.ts"],"sourcesContent":["// 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"],"names":[],"mappings":"AAGO,MAAM,WAAA,GAA2D,SAAA;;;;"}

View File

@ -0,0 +1,112 @@
import { getCurrentScope, withScope } from '../currentScopes.js';
const ADD_LISTENER_METHODS = [
"addListener",
"on",
"once",
"prependListener",
"prependOnceListener",
"addEventListener"
];
const REMOVE_LISTENER_METHODS = ["removeListener", "off", "removeEventListener"];
const SCOPE_BOUND_LISTENERS = /* @__PURE__ */ Symbol("SentryScopeBoundListeners");
let registeringWrapper;
function isReentrantWrapperRegistration(listener) {
return registeringWrapper !== void 0 && (listener === registeringWrapper || listener.listener === registeringWrapper);
}
function bindScopeToEmitter(emitter, scope = getCurrentScope()) {
const ee = emitter;
if (getPatchMap(ee)) {
return emitter;
}
createPatchMap(ee);
for (const methodName of ADD_LISTENER_METHODS) {
if (typeof ee[methodName] !== "function") {
continue;
}
ee[methodName] = patchAddListener(ee, ee[methodName], scope);
}
for (const methodName of REMOVE_LISTENER_METHODS) {
if (typeof ee[methodName] !== "function") {
continue;
}
ee[methodName] = patchRemoveListener(ee, ee[methodName]);
}
if (typeof ee.removeAllListeners === "function") {
ee.removeAllListeners = patchRemoveAllListeners(ee, ee.removeAllListeners);
}
return emitter;
}
function bindListenerToScope(listener, scope) {
return function(...args) {
return withScope(scope, () => listener.apply(this, args));
};
}
function isBoundListener(listener) {
return typeof listener === "function";
}
function patchAddListener(ee, original, scope) {
return function(...args) {
const event = args[0];
const listener = args[1];
const rest = args.slice(2);
if (!isBoundListener(listener) || isReentrantWrapperRegistration(listener)) {
return original.apply(this, args);
}
const map = getPatchMap(ee) || createPatchMap(ee);
let listeners = map.get(event);
if (!listeners) {
listeners = /* @__PURE__ */ new WeakMap();
map.set(event, listeners);
}
let boundListener = listeners.get(listener);
if (!boundListener) {
boundListener = bindListenerToScope(listener, scope);
listeners.set(listener, boundListener);
}
const previous = registeringWrapper;
registeringWrapper = boundListener;
try {
return original.call(this, event, boundListener, ...rest);
} finally {
registeringWrapper = previous;
}
};
}
function patchRemoveListener(ee, original) {
return function(...args) {
const event = args[0];
const listener = args[1];
const rest = args.slice(2);
const boundListener = isBoundListener(listener) ? getPatchMap(ee)?.get(event)?.get(listener) : void 0;
if (!boundListener) {
return original.apply(this, args);
}
return original.call(this, event, boundListener, ...rest);
};
}
function patchRemoveAllListeners(ee, original) {
return function(...args) {
const map = getPatchMap(ee);
if (map) {
if (args.length === 0) {
createPatchMap(ee);
} else {
const event = args[0];
map.delete(event);
}
}
return original.apply(this, args);
};
}
function createPatchMap(ee) {
const map = /* @__PURE__ */ new Map();
ee[SCOPE_BOUND_LISTENERS] = map;
return map;
}
function getPatchMap(ee) {
return ee[SCOPE_BOUND_LISTENERS];
}
export { bindScopeToEmitter };
//# sourceMappingURL=bindScopeToEmitter.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"vue.d.ts","sourceRoot":"","sources":["../../../src/types/vue.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,YAAY;IAE3B,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,KAAK;IAGpB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB"}

View File

@ -0,0 +1,12 @@
import { context } from '@opentelemetry/api';
import { getScopesFromContext } from '@sentry/opentelemetry';
function setIsolationScope(isolationScope) {
const scopes = getScopesFromContext(context.active());
if (scopes) {
scopes.isolationScope = isolationScope;
}
}
export { setIsolationScope };
//# sourceMappingURL=scope.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"semconv.js","sources":["../../../../../../src/integrations/tracing/postgres/vendored/semconv.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-pg\n * - Upstream version: @opentelemetry/instrumentation-pg@0.70.0\n * - Trimmed to the (old) semantic conventions the SDK actually emits\n */\n\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n\n/**\n * Deprecated, use `server.address`, `server.port` attributes instead.\n *\n * @example \"Server=(localdb)\\\\v11.0;Integrated Security=true;\"\n *\n * @deprecated Replaced by `server.address` and `server.port`.\n */\nexport const ATTR_DB_CONNECTION_STRING = 'db.connection_string' as const;\n\n/**\n * Enum value \"postgresql\" for attribute `db.system`.\n */\nexport const DB_SYSTEM_VALUE_POSTGRESQL = 'postgresql' as const;\n"],"names":[],"mappings":"AAuBO,MAAM,yBAAA,GAA4B;AAKlC,MAAM,0BAAA,GAA6B;;;;"}

View File

@ -0,0 +1,4 @@
import { HttpModuleExport } from './types';
export declare const warning = "Double-wrapped http.client detected. Either disable spans in Sentry.httpIntegration, or disable the OpenTelemetry HTTP instrumentation. See: https://docs.sentry.io/platforms/javascript/guides/express/opentelemetry/custom-setup/#custom-http-instrumentation";
export declare const doubleWrapWarning: (http: HttpModuleExport) => void;
//# sourceMappingURL=double-wrap-warning.d.ts.map

View File

@ -0,0 +1,44 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.disableInstrumentations = exports.enableInstrumentations = void 0;
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
for (let i = 0, j = instrumentations.length; i < j; i++) {
const instrumentation = instrumentations[i];
if (tracerProvider) {
instrumentation.setTracerProvider(tracerProvider);
}
if (meterProvider) {
instrumentation.setMeterProvider(meterProvider);
}
if (loggerProvider && instrumentation.setLoggerProvider) {
instrumentation.setLoggerProvider(loggerProvider);
}
// instrumentations have been already enabled during creation
// so enable only if user prevented that by setting enabled to false
// this is to prevent double enabling but when calling register all
// instrumentations should be now enabled
if (!instrumentation.getConfig().enabled) {
instrumentation.enable();
}
}
}
exports.enableInstrumentations = enableInstrumentations;
/**
* Disable instrumentations
* @param instrumentations
*/
function disableInstrumentations(instrumentations) {
instrumentations.forEach(instrumentation => instrumentation.disable());
}
exports.disableInstrumentations = disableInstrumentations;
//# sourceMappingURL=autoLoaderUtils.js.map

View File

@ -0,0 +1,197 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';
import { stringify } from '../../utils/string.js';
import { SPAN_STATUS_ERROR } from '../spanstatus.js';
import { startSpan } from '../trace.js';
import { GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE, GEN_AI_INPUT_MESSAGES_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE } from '../ai/gen-ai-attributes.js';
import { resolveAIRecordingOptions, extractSystemInstructions, shouldEnableTruncation, getTruncatedJsonString } from '../ai/utils.js';
import { createLangChainCallbackHandler } from '../langchain/index.js';
import { _INTERNAL_mergeLangChainCallbackHandler, normalizeLangChainMessages } from '../langchain/utils.js';
import { LANGGRAPH_ORIGIN } from './constants.js';
import { extractLLMFromParams, extractAgentNameFromParams, wrapToolsWithSpans, extractToolsFromCompiledGraph, setResponseAttributes } from './utils.js';
let _insideCreateReactAgent = false;
const SENTRY_PATCHED = "__sentry_patched__";
function _INTERNAL_getLangGraphCreateAgentSpanOptions(agentName) {
const attributes = {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.create_agent",
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: "create_agent"
};
if (agentName) {
attributes[GEN_AI_AGENT_NAME_ATTRIBUTE] = agentName;
}
return {
op: "gen_ai.create_agent",
name: agentName ? `create_agent ${agentName}` : "create_agent",
attributes
};
}
function instrumentStateGraphCompile(originalCompile, options) {
if (Object.prototype.hasOwnProperty.call(originalCompile, SENTRY_PATCHED)) {
return originalCompile;
}
const sentryHandler = createLangChainCallbackHandler(options);
const wrapped = new Proxy(originalCompile, {
apply(target, thisArg, args) {
if (_insideCreateReactAgent) {
return Reflect.apply(target, thisArg, args);
}
return startSpan(_INTERNAL_getLangGraphCreateAgentSpanOptions(), (span) => {
try {
const compiledGraph = Reflect.apply(target, thisArg, args);
const compileOptions = args.length > 0 ? args[0] : {};
if (compileOptions?.name && typeof compileOptions.name === "string") {
span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, compileOptions.name);
span.updateName(`create_agent ${compileOptions.name}`);
}
const originalInvoke = compiledGraph.invoke;
if (originalInvoke && typeof originalInvoke === "function") {
compiledGraph.invoke = instrumentCompiledGraphInvoke(
originalInvoke.bind(compiledGraph),
compiledGraph,
compileOptions,
options,
void 0,
sentryHandler
);
}
return compiledGraph;
} catch (error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
throw error;
}
});
}
});
Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });
return wrapped;
}
function instrumentCompiledGraphInvoke(originalInvoke, graphInstance, compileOptions, options, llm, sentryCallbackHandler) {
return new Proxy(originalInvoke, {
apply(target, thisArg, args) {
const modelName = llm?.modelName ?? llm?.model;
return startSpan(
{
op: "gen_ai.invoke_agent",
name: "invoke_agent",
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,
[GEN_AI_OPERATION_NAME_ATTRIBUTE]: "invoke_agent"
}
},
async (span) => {
try {
const graphName = compileOptions?.name;
if (graphName && typeof graphName === "string") {
span.setAttribute(GEN_AI_PIPELINE_NAME_ATTRIBUTE, graphName);
span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, graphName);
span.updateName(`invoke_agent ${graphName}`);
}
if (modelName) {
span.setAttribute(GEN_AI_REQUEST_MODEL_ATTRIBUTE, modelName);
}
const config = args.length > 1 ? args[1] : void 0;
const configurable = config?.configurable;
const threadId = configurable?.thread_id;
if (threadId && typeof threadId === "string") {
span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, threadId);
}
if (sentryCallbackHandler) {
const invokeConfig = args[1] ?? {};
args[1] = invokeConfig;
const existingMetadata = invokeConfig.metadata ?? {};
invokeConfig.metadata = {
...existingMetadata,
__sentry_langgraph__: true,
...typeof graphName === "string" ? { lc_agent_name: graphName } : {}
};
invokeConfig.callbacks = _INTERNAL_mergeLangChainCallbackHandler(
invokeConfig.callbacks,
sentryCallbackHandler
);
}
const tools = extractToolsFromCompiledGraph(graphInstance);
if (tools) {
span.setAttribute(GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, JSON.stringify(tools));
}
const recordInputs = options.recordInputs;
const recordOutputs = options.recordOutputs;
const inputMessages = args.length > 0 ? args[0]?.messages ?? [] : [];
if (inputMessages && recordInputs) {
const normalizedMessages = normalizeLangChainMessages(inputMessages);
const { systemInstructions, filteredMessages } = extractSystemInstructions(normalizedMessages);
if (systemInstructions) {
span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE, systemInstructions);
}
const enableTruncation = shouldEnableTruncation(options.enableTruncation);
const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 0;
span.setAttributes({
[GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: enableTruncation ? getTruncatedJsonString(filteredMessages) : stringify(filteredMessages),
[GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength
});
}
const result = await Reflect.apply(target, thisArg, args);
if (recordOutputs) {
setResponseAttributes(span, inputMessages ?? null, result);
}
return result;
} catch (error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
throw error;
}
}
);
}
});
}
function instrumentCreateReactAgent(originalCreateReactAgent, options) {
if (Object.prototype.hasOwnProperty.call(originalCreateReactAgent, SENTRY_PATCHED)) {
return originalCreateReactAgent;
}
const resolvedOptions = resolveAIRecordingOptions(options);
const sentryHandler = createLangChainCallbackHandler(resolvedOptions);
const wrapped = new Proxy(originalCreateReactAgent, {
apply(target, thisArg, args) {
const llm = extractLLMFromParams(args);
const agentName = extractAgentNameFromParams(args);
const params = args[0];
if (params && Array.isArray(params.tools) && params.tools.length > 0) {
wrapToolsWithSpans(params.tools, resolvedOptions, agentName ?? void 0);
}
_insideCreateReactAgent = true;
let compiledGraph;
try {
compiledGraph = Reflect.apply(target, thisArg, args);
} finally {
_insideCreateReactAgent = false;
}
const originalInvoke = compiledGraph.invoke;
if (originalInvoke && typeof originalInvoke === "function") {
const compileOptions = {};
if (agentName) {
compileOptions.name = agentName;
}
compiledGraph.invoke = instrumentCompiledGraphInvoke(
originalInvoke.bind(compiledGraph),
compiledGraph,
compileOptions,
resolvedOptions,
llm,
sentryHandler
);
}
return compiledGraph;
}
});
Object.defineProperty(wrapped, SENTRY_PATCHED, { value: true, enumerable: false });
return wrapped;
}
function instrumentStateGraph(stateGraph, options) {
stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile, resolveAIRecordingOptions(options));
return stateGraph;
}
const instrumentLangGraph = instrumentStateGraph;
export { _INTERNAL_getLangGraphCreateAgentSpanOptions, instrumentCompiledGraphInvoke, instrumentCreateReactAgent, instrumentLangGraph, instrumentStateGraph, instrumentStateGraphCompile };
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,13 @@
export { MongooseLegacyCollection, StartMongooseLegacySpanOptions } from './mongoose-legacy-span';
export { startMongooseLegacySpan } from './mongoose-legacy-span';
/**
* Auto-instrument the [mongoose](https://www.npmjs.com/package/mongoose) library via its native
* `node:diagnostics_channel` tracing channels (mongoose >= 9.7).
*
* On older mongoose versions the channels are never published to, so this integration is inert and
* the IITM-based patcher (gated to `< 9.7.0`) handles instrumentation instead.
*/
export declare const mongooseIntegration: () => import("@sentry/core").Integration & {
name: string;
};
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AlwaysRecordSampler.js","sourceRoot":"","sources":["../../../src/sampler/AlwaysRecordSampler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAiB;IACzD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;KAC1E;IACD,OAAO;QACL,YAAY,CACV,OAAgB,EAChB,OAAe,EACf,QAAgB,EAChB,QAAkB,EAClB,UAAsB,EACtB,KAAa;YAEb,MAAM,MAAM,GAAG,QAAQ,CAAC,YAAY,CAClC,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,CACN,CAAC;YACF,IAAI,MAAM,CAAC,QAAQ,KAAK,gBAAgB,CAAC,UAAU,EAAE;gBACnD,OAAO;oBACL,QAAQ,EAAE,gBAAgB,CAAC,MAAM;oBACjC,UAAU,EAAE,MAAM,CAAC,UAAU;oBAC7B,UAAU,EAAE,MAAM,CAAC,UAAU;iBAC9B,CAAC;aACH;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,QAAQ;YACN,OAAO,uBAAuB,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC;QACvD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context, Link, Attributes, SpanKind } from '@opentelemetry/api';\nimport type { Sampler, SamplingResult } from '../Sampler';\nimport { SamplingDecision } from '../Sampler';\n\n/**\n * Creates a sampler that wraps a delegate and upgrades NOT_RECORD decisions to\n * RECORD, ensuring all spans are recorded without affecting the sampling rate.\n */\nexport function createAlwaysRecordSampler(delegate: Sampler): Sampler {\n if (!delegate) {\n throw new Error('createAlwaysRecordSampler requires a delegate sampler');\n }\n return {\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const result = delegate.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n if (result.decision === SamplingDecision.NOT_RECORD) {\n return {\n decision: SamplingDecision.RECORD,\n attributes: result.attributes,\n traceState: result.traceState,\n };\n }\n return result;\n },\n toString(): string {\n return `AlwaysRecordSampler{${delegate.toString()}}`;\n },\n };\n}\n"]}

View File

@ -0,0 +1,11 @@
import type { InstrumentationConfig } from '@opentelemetry/instrumentation';
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
export declare class AmqplibInstrumentation extends InstrumentationBase<InstrumentationConfig> {
constructor(config?: InstrumentationConfig);
protected init(): InstrumentationNodeModuleDefinition;
private patchConnect;
private unpatchConnect;
private patchChannelModel;
private unpatchChannelModel;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"semanticAttributes.d.ts","sourceRoot":"","sources":["../../src/semanticAttributes.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,eAAO,MAAM,0CAA0C,0BAA0B,CAAC;AAGlF,eAAO,MAAM,2CAA2C,6BAA6B,CAAC"}

View File

@ -0,0 +1,32 @@
import { Context } from '@opentelemetry/api';
import { SpanKind } from '@opentelemetry/api';
import { Sampler, SamplingResult } from '@opentelemetry/sdk-trace-base';
import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
import { Client, SpanAttributes } from '@sentry/core';
/**
* A custom OTEL sampler that uses Sentry sampling rates to make its decision
*/
export declare class SentrySampler implements Sampler {
private _client;
private _isSpanStreaming;
constructor(client: Client);
/** @inheritDoc */
shouldSample(context: Context, traceId: string, spanName: string, spanKind: SpanKind, spanAttributes: SpanAttributes, _links: unknown): SamplingResult;
/** Returns the sampler name or short description with the configuration. */
toString(): string;
}
/**
* Wrap a sampling decision with data that Sentry needs to work properly with it.
* If you pass `decision: undefined`, it will be treated as `NOT_RECORDING`, but in contrast to passing `NOT_RECORDING`
* it will not propagate this decision to downstream Sentry SDKs.
*/
export declare function wrapSamplingDecision({ decision, context, spanAttributes, sampleRand, downstreamTraceSampleRate, ignoredChildSpan, ignoredSegmentSpan, }: {
decision: SamplingDecision | undefined;
context: Context;
spanAttributes: SpanAttributes;
sampleRand?: number;
downstreamTraceSampleRate?: number;
ignoredChildSpan?: boolean;
ignoredSegmentSpan?: boolean;
}): SamplingResult;
//# sourceMappingURL=sampler.d.ts.map

View File

@ -0,0 +1,40 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const dsn = require('../utils/dsn.js');
const envelope = require('../utils/envelope.js');
const isBrowser = require('../utils/isBrowser.js');
function createMetricContainerEnvelopeItem(items, inferUserData) {
const inferSetting = inferUserData ? "auto" : "never";
return [
{
type: "trace_metric",
item_count: items.length,
content_type: "application/vnd.sentry.items.trace-metric+json"
},
{
version: 2,
...isBrowser.isBrowser() && {
ingest_settings: { infer_ip: inferSetting, infer_user_agent: inferSetting }
},
items
}
];
}
function createMetricEnvelope(metrics, metadata, tunnel, dsn$1, inferUserData) {
const headers = {};
if (metadata?.sdk) {
headers.sdk = {
name: metadata.sdk.name,
version: metadata.sdk.version
};
}
if (!!tunnel && !!dsn$1) {
headers.dsn = dsn.dsnToString(dsn$1);
}
return envelope.createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics, inferUserData)]);
}
exports.createMetricContainerEnvelopeItem = createMetricContainerEnvelopeItem;
exports.createMetricEnvelope = createMetricEnvelope;
//# sourceMappingURL=envelope.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"cookie.js","sources":["../../../src/utils/cookie.ts"],"sourcesContent":["/**\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 <shtylman@gmail.com>\n * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>\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<string, string> {\n const obj: Record<string, string> = {};\n let index = 0;\n\n while (index < 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 < 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"],"names":[],"mappings":";;AAiCO,SAAS,YAAY,GAAA,EAAqC;AAC/D,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,IAAI,KAAA,GAAQ,CAAA;AAEZ,EAAA,OAAO,KAAA,GAAQ,IAAI,MAAA,EAAQ;AACzB,IAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,OAAA,CAAQ,GAAA,EAAK,KAAK,CAAA;AAGpC,IAAA,IAAI,UAAU,EAAA,EAAI;AAChB,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,MAAA,GAAS,GAAA,CAAI,OAAA,CAAQ,GAAA,EAAK,KAAK,CAAA;AAEnC,IAAA,IAAI,WAAW,EAAA,EAAI;AACjB,MAAA,MAAA,GAAS,GAAA,CAAI,MAAA;AAAA,IACf,CAAA,MAAA,IAAW,SAAS,KAAA,EAAO;AAEzB,MAAA,KAAA,GAAQ,GAAA,CAAI,WAAA,CAAY,GAAA,EAAK,KAAA,GAAQ,CAAC,CAAA,GAAI,CAAA;AAC1C,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,MAAM,GAAA,CAAI,KAAA,CAAM,KAAA,EAAO,KAAK,EAAE,IAAA,EAAK;AAGzC,IAAA,IAAI,MAAA,KAAc,GAAA,CAAI,GAAG,CAAA,EAAG;AAC1B,MAAA,IAAI,MAAM,GAAA,CAAI,KAAA,CAAM,QAAQ,CAAA,EAAG,MAAM,EAAE,IAAA,EAAK;AAG5C,MAAA,IAAI,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA,KAAM,EAAA,EAAM;AAC9B,QAAA,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAAA,MACvB;AAEA,MAAA,IAAI;AACF,QAAA,GAAA,CAAI,GAAG,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,KAAM,CAAA,CAAA,GAAK,kBAAA,CAAmB,GAAG,CAAA,GAAI,GAAA;AAAA,MACjE,CAAA,CAAA,MAAQ;AACN,QAAA,GAAA,CAAI,GAAG,CAAA,GAAI,GAAA;AAAA,MACb;AAAA,IACF;AAEA,IAAA,KAAA,GAAQ,MAAA,GAAS,CAAA;AAAA,EACnB;AAEA,EAAA,OAAO,GAAA;AACT;;;;"}

View File

@ -0,0 +1,16 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0;
var HostDetector_1 = require("./HostDetector");
Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return HostDetector_1.hostDetector; } });
var OSDetector_1 = require("./OSDetector");
Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return OSDetector_1.osDetector; } });
var ProcessDetector_1 = require("./ProcessDetector");
Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return ProcessDetector_1.processDetector; } });
var ServiceInstanceIdDetector_1 = require("./ServiceInstanceIdDetector");
Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return ServiceInstanceIdDetector_1.serviceInstanceIdDetector; } });
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,4 @@
var sourceMapConsumer = {};
export { sourceMapConsumer as __exports };
//# sourceMappingURL=source-map-consumer.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"misc.d.ts","sourceRoot":"","sources":["../../../src/utils/misc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAMtD,UAAU,cAAc;IACtB,UAAU,CAAC,IAAI,MAAM,CAAC;CACvB;AAmBD;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,MAAM,6BAAc,GAAG,MAAM,CAqBlD;AAMD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAcxD;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAUvF;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,YAAY,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI,CAc3F;AAMD;;GAEG;AACH,UAAU,MAAM;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAYjD;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,cAAc,GAAE,MAAU,GAAG,IAAI,CAsBtG;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,CAcnE;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,OAAO,GAAG,OAAO,GAAG,IAAI,CAIpE"}

View File

@ -0,0 +1,67 @@
{
"name": "es-module-lexer",
"version": "3.0.5",
"description": "Lexes ES modules returning their import/export metadata",
"main": "dist/lexer.cjs",
"module": "dist/lexer.js",
"sideEffects": false,
"types": "types/lexer.d.ts",
"exports": {
".": {
"types": "./types/lexer.d.ts",
"module": "./dist/lexer.js",
"import": "./dist/lexer.js",
"require": "./dist/lexer.cjs"
},
"./js": {
"types": "./types/lexer.d.ts",
"default": "./dist/lexer.asm.js"
},
"./minimal": {
"types": "./types/lexer.minimal.d.ts",
"module": "./dist/lexer.minimal.js",
"import": "./dist/lexer.minimal.js",
"require": "./dist/lexer.minimal.cjs"
},
"./minimal/js": {
"types": "./types/lexer.minimal.d.ts",
"default": "./dist/lexer.minimal.asm.js"
}
},
"scripts": {
"build": "npm install -g chomp ; chomp build",
"test": "npm install -g chomp ; chomp test"
},
"author": "Guy Bedford",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.29.7",
"@babel/core": "^7.29.7",
"@babel/plugin-transform-modules-commonjs": "^7.29.7",
"@swc/cli": "^0.8.1",
"@swc/core": "^1.16.2",
"@types/node": "^26.4.1",
"kleur": "^4.1.5",
"mocha": "^11.8.0",
"terser": "^5.51.2",
"typescript": "^7.0.2"
},
"files": [
"dist",
"types"
],
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/guybedford/es-module-lexer.git"
},
"bugs": {
"url": "https://github.com/guybedford/es-module-lexer/issues"
},
"homepage": "https://github.com/guybedford/es-module-lexer#readme",
"directories": {
"lib": "lib",
"test": "test"
},
"keywords": []
}

View File

@ -0,0 +1,24 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const nodeCore = require('@sentry/node-core');
const instrumentation = require('./instrumentation.js');
const instrumentAnthropicAi = nodeCore.generateInstrumentOnce(
core.ANTHROPIC_AI_INTEGRATION_NAME,
(options) => new instrumentation.SentryAnthropicAiInstrumentation(options)
);
const _anthropicAIIntegration = ((options = {}) => {
return {
name: core.ANTHROPIC_AI_INTEGRATION_NAME,
options,
setupOnce() {
instrumentAnthropicAi(options);
}
};
});
const anthropicAIIntegration = core.defineIntegration(_anthropicAIIntegration);
exports.anthropicAIIntegration = anthropicAIIntegration;
exports.instrumentAnthropicAi = instrumentAnthropicAi;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,11 @@
import type { TransactionEvent } from '../types/event';
import type { SpanJSON } from '../types/span';
/**
* Converts a transaction event to a span JSON object.
*/
export declare function convertTransactionEventToSpanJson(event: TransactionEvent): SpanJSON;
/**
* Converts a span JSON object to a transaction event.
*/
export declare function convertSpanJsonToTransactionEvent(span: SpanJSON): TransactionEvent;
//# sourceMappingURL=transactionEvent.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"eventUtils.d.ts","sourceRoot":"","sources":["../../../src/utils/eventUtils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEvD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,SAAS,GAAG,OAAO,CAE5D;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,EAAE,CAqB/D"}

View File

@ -0,0 +1,9 @@
import type { ClientReport } from '../types/clientreport';
import type { ClientReportEnvelope } from '../types/envelope';
/**
* Creates client report envelope
* @param discarded_events An array of discard events
* @param dsn A DSN that can be set on the header. Optional.
*/
export declare function createClientReportEnvelope(discarded_events: ClientReport['discarded_events'], dsn?: string, timestamp?: number): ClientReportEnvelope;
//# sourceMappingURL=clientreport.d.ts.map

View File

@ -0,0 +1,6 @@
import type { Client } from '../../client';
/**
* Determines if span streaming is enabled for the given client
*/
export declare function hasSpanStreamingEnabled(client: Client): boolean;
//# sourceMappingURL=hasSpanStreamingEnabled.d.ts.map

View File

@ -0,0 +1,93 @@
import { IncomingHttpHeaders } from './header'
import Dispatcher from './dispatcher';
import { BodyInit, Headers } from './fetch'
export {
Interceptable,
MockInterceptor,
MockScope
}
/** The scope associated with a mock dispatch. */
declare class MockScope<TData extends object = object> {
constructor(mockDispatch: MockInterceptor.MockDispatch<TData>);
/** Delay a reply by a set amount of time in ms. */
delay(waitInMs: number): MockScope<TData>;
/** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */
persist(): MockScope<TData>;
/** Define a reply for a set amount of matching requests. */
times(repeatTimes: number): MockScope<TData>;
}
/** The interceptor for a Mock. */
declare class MockInterceptor {
constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]);
/** Mock an undici request with the defined reply. */
reply<TData extends object = object>(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback<TData>): MockScope<TData>;
reply<TData extends object = object>(
statusCode: number,
data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler<TData>,
responseOptions?: MockInterceptor.MockResponseOptions
): MockScope<TData>;
/** Mock an undici request by throwing the defined reply error. */
replyWithError<TError extends Error = Error>(error: TError): MockScope;
/** Set default reply headers on the interceptor for subsequent mocked replies. */
defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor;
/** Set default reply trailers on the interceptor for subsequent mocked replies. */
defaultReplyTrailers(trailers: Record<string, string>): MockInterceptor;
/** Set automatically calculated content-length header on subsequent mocked replies. */
replyContentLength(): MockInterceptor;
}
declare namespace MockInterceptor {
/** MockInterceptor options. */
export interface Options {
/** Path to intercept on. */
path: string | RegExp | ((path: string) => boolean);
/** Method to intercept on. Defaults to GET. */
method?: string | RegExp | ((method: string) => boolean);
/** Body to intercept on. */
body?: string | RegExp | ((body: string) => boolean);
/** Headers to intercept on. */
headers?: Record<string, string | RegExp | ((body: string) => boolean)> | ((headers: Record<string, string>) => boolean);
/** Query params to intercept on */
query?: Record<string, any>;
}
export interface MockDispatch<TData extends object = object, TError extends Error = Error> extends Options {
times: number | null;
persist: boolean;
consumed: boolean;
data: MockDispatchData<TData, TError>;
}
export interface MockDispatchData<TData extends object = object, TError extends Error = Error> extends MockResponseOptions {
error: TError | null;
statusCode?: number;
data?: TData | string;
}
export interface MockResponseOptions {
headers?: IncomingHttpHeaders;
trailers?: Record<string, string>;
}
export interface MockResponseCallbackOptions {
path: string;
method: string;
headers?: Headers | Record<string, string>;
origin?: string;
body?: BodyInit | Dispatcher.DispatchOptions['body'] | null;
maxRedirections?: number;
}
export type MockResponseDataHandler<TData extends object = object> = (
opts: MockResponseCallbackOptions
) => TData | Buffer | string;
export type MockReplyOptionsCallback<TData extends object = object> = (
opts: MockResponseCallbackOptions
) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions }
}
interface Interceptable extends Dispatcher {
/** Intercepts any matching requests that use the same origin as this mock client. */
intercept(options: MockInterceptor.Options): MockInterceptor;
}

View File

@ -0,0 +1 @@
{"version":3,"file":"Logger.js","sourceRoot":"","sources":["../../../src/types/Logger.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type { LogRecord } from './LogRecord';\nimport type { SeverityNumber } from './LogRecord';\n\nexport interface Logger {\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): void;\n\n /**\n * Will a log record with the given details get emitted?\n * This can be used to avoid expensive calculation of log record data.\n */\n enabled(options?: {\n context?: Context;\n severityNumber?: SeverityNumber;\n eventName?: string;\n }): boolean;\n}\n"]}

View File

@ -0,0 +1,26 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const ORIGIN = "auto.graphql.diagnostic_channel";
const SPAN_NAME_PARSE = "graphql.parse";
const SPAN_NAME_VALIDATE = "graphql.validate";
const SPAN_NAME_EXECUTE = "graphql.execute";
const SPAN_NAME_RESOLVE = "graphql.resolve";
const GRAPHQL_FIELD_NAME = "graphql.field.name";
const GRAPHQL_FIELD_PATH = "graphql.field.path";
const GRAPHQL_FIELD_TYPE = "graphql.field.type";
const GRAPHQL_PARENT_NAME = "graphql.parent.name";
const GRAPHQL_DATA_SYMBOL = /* @__PURE__ */ Symbol.for("opentelemetry.graphql_data");
const GRAPHQL_PATCHED_SYMBOL = /* @__PURE__ */ Symbol.for("opentelemetry.patched");
exports.GRAPHQL_DATA_SYMBOL = GRAPHQL_DATA_SYMBOL;
exports.GRAPHQL_FIELD_NAME = GRAPHQL_FIELD_NAME;
exports.GRAPHQL_FIELD_PATH = GRAPHQL_FIELD_PATH;
exports.GRAPHQL_FIELD_TYPE = GRAPHQL_FIELD_TYPE;
exports.GRAPHQL_PARENT_NAME = GRAPHQL_PARENT_NAME;
exports.GRAPHQL_PATCHED_SYMBOL = GRAPHQL_PATCHED_SYMBOL;
exports.ORIGIN = ORIGIN;
exports.SPAN_NAME_EXECUTE = SPAN_NAME_EXECUTE;
exports.SPAN_NAME_PARSE = SPAN_NAME_PARSE;
exports.SPAN_NAME_RESOLVE = SPAN_NAME_RESOLVE;
exports.SPAN_NAME_VALIDATE = SPAN_NAME_VALIDATE;
//# sourceMappingURL=constants.js.map

View File

@ -0,0 +1,3 @@
// This file is a compatibility shim for TypeScript compilers that do not
// support the package.json `exports` field for resolving subpath exports.
export * from './dist/op';

View File

@ -0,0 +1,42 @@
import { McpServerWrapperOptions } from './types';
/**
* Wraps an MCP Server instance with Sentry instrumentation.
*
* Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package (legacy `tool`/`resource`/`prompt` API)
* and `@modelcontextprotocol/server` version 2.x (`registerTool`/`registerResource`/`registerPrompt` API).
* Automatically instruments transport methods and handler functions for comprehensive monitoring.
*
* Both call orderings are supported: wrapping before or after registering tools, resources,
* and prompts. Sentry patches the registration methods for future handlers and retroactively
* wraps any already-registered ones. Wrapping at construction time is recommended by
* convention (consistent with other SDK integrations), but is not required.
*
* @example
* ```typescript
* import * as Sentry from '@sentry/core';
* import { McpServer } from '@modelcontextprotocol/server';
* import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
*
* // Wrap first, then register tools — this is the correct order
* const server = Sentry.wrapMcpServerWithSentry(
* new McpServer({ name: "my-server", version: "1.0.0" })
* );
*
* server.registerTool('my-tool', schema, handler);
*
* // Explicitly control input/output capture
* const server = Sentry.wrapMcpServerWithSentry(
* new McpServer({ name: "my-server", version: "1.0.0" }),
* { recordInputs: true, recordOutputs: false }
* );
*
* const transport = new NodeStreamableHTTPServerTransport();
* await server.connect(transport);
* ```
*
* @param mcpServerInstance - MCP server instance to instrument
* @param options - Optional configuration for recording inputs and outputs
* @returns Instrumented server instance (same reference)
*/
export declare function wrapMcpServerWithSentry<S extends object>(mcpServerInstance: S, options?: McpServerWrapperOptions): S;
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1,26 @@
import type { Attributes, AttributeValue } from '@opentelemetry/api';
type RawResourceAttribute = [string, AttributeValue | undefined];
/**
* Minimal Resource implementation that satisfies the OpenTelemetry Resource interface
* used by BasicTracerProvider, without depending on `@opentelemetry/resources`.
*/
declare class SentryResource {
private _attributes;
constructor(attributes: Attributes);
get attributes(): Attributes;
merge(other: SentryResource | null): SentryResource;
getRawAttributes(): RawResourceAttribute[];
}
/**
* Returns a Resource for use in Sentry's OpenTelemetry TracerProvider setup.
*
* Combines the default OTel SDK telemetry attributes with Sentry-specific
* service attributes, equivalent to what was previously done via:
* `defaultResource().merge(resourceFromAttributes({ ... }))`
*
* Respects OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES environment variables
* per the OpenTelemetry specification.
*/
export declare function getSentryResource(serviceNameFallback: string): SentryResource;
export {};
//# sourceMappingURL=resource.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"debounce.js","sources":["../../../src/utils/debounce.ts"],"sourcesContent":["type DebouncedCallback = {\n (): void | unknown;\n flush: () => void | unknown;\n cancel: () => void;\n};\ntype CallbackFunction = () => 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<typeof setTimeout> | undefined;\n let maxTimerId: ReturnType<typeof setTimeout> | 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 && clearTimeout(timerId);\n maxTimerId !== undefined && 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 && 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"],"names":[],"mappings":";;AA+BO,SAAS,QAAA,CAAS,IAAA,EAAwB,IAAA,EAAc,OAAA,EAA8C;AAC3G,EAAA,IAAI,mBAAA;AAEJ,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI,UAAA;AAEJ,EAAA,MAAM,OAAA,GAAU,SAAS,OAAA,GAAU,IAAA,CAAK,IAAI,OAAA,CAAQ,OAAA,EAAS,IAAI,CAAA,GAAI,CAAA;AACrE,EAAA,MAAM,cAAA,GAAiB,SAAS,cAAA,IAAkB,UAAA;AAElD,EAAA,SAAS,UAAA,GAAsB;AAC7B,IAAA,YAAA,EAAa;AACb,IAAA,mBAAA,GAAsB,IAAA,EAAK;AAC3B,IAAA,OAAO,mBAAA;AAAA,EACT;AAEA,EAAA,SAAS,YAAA,GAAqB;AAC5B,IAAA,OAAA,KAAY,MAAA,IAAa,aAAa,OAAO,CAAA;AAC7C,IAAA,UAAA,KAAe,MAAA,IAAa,aAAa,UAAU,CAAA;AACnD,IAAA,OAAA,GAAU,UAAA,GAAa,MAAA;AAAA,EACzB;AAEA,EAAA,SAAS,KAAA,GAAiB;AACxB,IAAA,IAAI,OAAA,KAAY,MAAA,IAAa,UAAA,KAAe,MAAA,EAAW;AACrD,MAAA,OAAO,UAAA,EAAW;AAAA,IACpB;AACA,IAAA,OAAO,mBAAA;AAAA,EACT;AAEA,EAAA,SAAS,SAAA,GAAqB;AAC5B,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,YAAA,CAAa,OAAO,CAAA;AAAA,IACtB;AACA,IAAA,OAAA,GAAU,cAAA,CAAe,YAAY,IAAI,CAAA;AAEzC,IAAA,IAAI,OAAA,IAAW,eAAe,MAAA,EAAW;AACvC,MAAA,UAAA,GAAa,cAAA,CAAe,YAAY,OAAO,CAAA;AAAA,IACjD;AAEA,IAAA,OAAO,mBAAA;AAAA,EACT;AAEA,EAAA,SAAA,CAAU,MAAA,GAAS,YAAA;AACnB,EAAA,SAAA,CAAU,KAAA,GAAQ,KAAA;AAClB,EAAA,OAAO,SAAA;AACT;;;;"}

View File

@ -0,0 +1,61 @@
import type { InstrumentationConfig } from '..';
export declare const mongodbConfig: ({
channelName: string;
module: {
versionRange: string;
filePath: string;
name: "mongodb";
};
functionQuery: {
expressionName: "insert" | "update" | "remove";
kind: "Callback";
};
} | {
channelName: string;
module: {
versionRange: string;
filePath: string;
name: "mongodb";
};
functionQuery: {
methodName: string;
kind: "Async";
functionName?: undefined;
};
} | {
channelName: string;
module: {
versionRange: string;
filePath: string;
name: "mongodb";
};
functionQuery: {
methodName: string;
kind: "Callback";
functionName?: undefined;
};
} | {
channelName: string;
module: {
versionRange: string;
filePath: string;
name: "mongodb";
};
functionQuery: {
functionName: string;
kind: "Callback";
methodName?: undefined;
};
})[];
export declare const mongodbChannels: {
readonly MONGODB_COMMAND: "orchestrion:mongodb:command";
readonly MONGODB_CHECKOUT: "orchestrion:mongodb:checkout";
readonly MONGODB_V3_INSERT: "orchestrion:mongodb:v3_insert";
readonly MONGODB_V3_UPDATE: "orchestrion:mongodb:v3_update";
readonly MONGODB_V3_REMOVE: "orchestrion:mongodb:v3_remove";
readonly MONGODB_V3_COMMAND: "orchestrion:mongodb:v3_command";
readonly MONGODB_V3_QUERY: "orchestrion:mongodb:v3_query";
readonly MONGODB_V3_GET_MORE: "orchestrion:mongodb:v3_get_more";
};
export declare const mongodbSubscribeInjection: InstrumentationConfig[];
//# sourceMappingURL=mongodb.d.ts.map

View File

@ -0,0 +1,6 @@
import { SeverityLevel } from '../types/severity';
/**
* Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.
*/
export declare function getBreadcrumbLogLevelFromHttpStatusCode(statusCode: number | undefined): SeverityLevel | undefined;
//# sourceMappingURL=breadcrumb-log-level.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"invalid-span-constants.js","sourceRoot":"","sources":["../../../src/trace/invalid-span-constants.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAGH,+CAA2C;AAE3C;;GAEG;AACU,QAAA,cAAc,GAAG,kBAAkB,CAAC;AAEjD;;GAEG;AACU,QAAA,eAAe,GAAG,kCAAkC,CAAC;AAElE;;GAEG;AACU,QAAA,oBAAoB,GAAgB;IAC/C,OAAO,EAAE,uBAAe;IACxB,MAAM,EAAE,sBAAc;IACtB,UAAU,EAAE,wBAAU,CAAC,IAAI;CAC5B,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { SpanContext } from './span_context';\nimport { TraceFlags } from './trace_flags';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_SPANID = '0000000000000000';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_TRACEID = '00000000000000000000000000000000';\n\n/**\n * @since 1.0.0\n */\nexport const INVALID_SPAN_CONTEXT: SpanContext = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n"]}

View File

@ -0,0 +1,7 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { noopDetector } from '../../NoopDetector';
export const osDetector = noopDetector;
//# sourceMappingURL=OSDetector.js.map

View File

@ -0,0 +1,137 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const attributes = require('../attributes.js');
const carrier = require('../carrier.js');
const currentScopes = require('../currentScopes.js');
const debugBuild = require('../debug-build.js');
const debugLogger = require('../utils/debug-logger.js');
const scopeData = require('../utils/scopeData.js');
const spanOnScope = require('../utils/spanOnScope.js');
const time = require('../utils/time.js');
const timestampSequence = require('../utils/timestampSequence.js');
const traceInfo = require('../utils/trace-info.js');
const envelope = require('./envelope.js');
const MAX_METRIC_BUFFER_SIZE = 1e3;
function setMetricAttribute(metricAttributes, key, value, setEvenIfPresent = true) {
if (value && (setEvenIfPresent || !(key in metricAttributes))) {
metricAttributes[key] = value;
}
}
function _INTERNAL_captureSerializedMetric(client, serializedMetric) {
const bufferMap = _getBufferMap();
const metricBuffer = _INTERNAL_getMetricBuffer(client);
if (metricBuffer === void 0) {
bufferMap.set(client, [serializedMetric]);
} else {
if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {
_INTERNAL_flushMetricsBuffer(client, metricBuffer);
bufferMap.set(client, [serializedMetric]);
} else {
bufferMap.set(client, [...metricBuffer, serializedMetric]);
}
}
}
function _enrichMetricAttributes(beforeMetric, client, user) {
const { release, environment } = client.getOptions();
const processedMetricAttributes = {
...beforeMetric.attributes
};
setMetricAttribute(processedMetricAttributes, "user.id", user.id, false);
setMetricAttribute(processedMetricAttributes, "user.email", user.email, false);
setMetricAttribute(processedMetricAttributes, "user.name", user.username, false);
setMetricAttribute(processedMetricAttributes, "sentry.release", release);
setMetricAttribute(processedMetricAttributes, "sentry.environment", environment);
const { name, version } = client.getSdkMetadata()?.sdk ?? {};
setMetricAttribute(processedMetricAttributes, "sentry.sdk.name", name);
setMetricAttribute(processedMetricAttributes, "sentry.sdk.version", version);
const replay = client.getIntegrationByName("Replay");
const replayId = replay?.getReplayId(true);
setMetricAttribute(processedMetricAttributes, "sentry.replay_id", replayId);
if (replayId && replay?.getRecordingMode() === "buffer") {
setMetricAttribute(processedMetricAttributes, "sentry._internal.replay_is_buffering", true);
}
return {
...beforeMetric,
attributes: processedMetricAttributes
};
}
function _buildSerializedMetric(metric, client, currentScope, scopeAttributes) {
const [, traceContext] = traceInfo._getTraceInfoFromScope(client, currentScope);
const span = spanOnScope._getSpanForScope(currentScope);
const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;
const spanId = span ? span.spanContext().spanId : void 0;
const timestamp = time.timestampInSeconds();
const sequenceAttr = timestampSequence.getSequenceAttribute(timestamp);
return {
timestamp,
trace_id: traceId ?? "",
span_id: spanId,
name: metric.name,
type: metric.type,
unit: metric.unit,
value: metric.value,
attributes: {
...attributes.serializeAttributes(scopeAttributes),
...attributes.serializeAttributes(metric.attributes, "skip-undefined"),
[sequenceAttr.key]: sequenceAttr.value
}
};
}
function _INTERNAL_captureMetric(beforeMetric, options) {
const currentScope = options?.scope ?? currentScopes.getCurrentScope();
const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;
const client = currentScope?.getClient() ?? currentScopes.getClient();
if (!client) {
debugBuild.DEBUG_BUILD && debugLogger.debug.warn("No client available to capture metric.");
return;
}
const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();
const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;
if (!metricsEnabled) {
debugBuild.DEBUG_BUILD && debugLogger.debug.warn("metrics option not enabled, metric will not be captured.");
return;
}
const { user, attributes: scopeAttributes } = scopeData.getCombinedScopeData(currentScopes.getIsolationScope(), currentScope);
const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);
client.emit("processMetric", enrichedMetric);
const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;
const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;
if (!processedMetric) {
debugBuild.DEBUG_BUILD && debugLogger.debug.log("`beforeSendMetric` returned `null`, will not send metric.");
return;
}
const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);
debugBuild.DEBUG_BUILD && debugLogger.debug.log("[Metric]", serializedMetric);
captureSerializedMetric(client, serializedMetric);
client.emit("afterCaptureMetric", processedMetric);
}
function _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {
const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];
if (metricBuffer.length === 0) {
return;
}
const clientOptions = client.getOptions();
const envelope$1 = envelope.createMetricEnvelope(
metricBuffer,
clientOptions._metadata,
clientOptions.tunnel,
client.getDsn(),
client.getDataCollectionOptions().userInfo
);
_getBufferMap().set(client, []);
client.emit("flushMetrics");
client.sendEnvelope(envelope$1);
}
function _INTERNAL_getMetricBuffer(client) {
return _getBufferMap().get(client);
}
function _getBufferMap() {
return carrier.getGlobalSingleton("clientToMetricBufferMap", () => /* @__PURE__ */ new WeakMap());
}
exports._INTERNAL_captureMetric = _INTERNAL_captureMetric;
exports._INTERNAL_captureSerializedMetric = _INTERNAL_captureSerializedMetric;
exports._INTERNAL_flushMetricsBuffer = _INTERNAL_flushMetricsBuffer;
exports._INTERNAL_getMetricBuffer = _INTERNAL_getMetricBuffer;
//# sourceMappingURL=internal.js.map

View File

@ -0,0 +1,407 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag, SpanStatusCode } from '@opentelemetry/api';
import { addHrTimes, millisToHrTime, hrTime, hrTimeDuration, isAttributeValue, isTimeInput, isTimeInputHrTime, otperformance, sanitizeAttributes, } from '@opentelemetry/core';
import { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';
import { ExceptionEventName } from './enums';
import { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';
/**
* This class represents a span.
*/
export class SpanImpl {
// Below properties are included to implement ReadableSpan for export
// purposes but are not intended to be written-to directly.
_spanContext;
kind;
parentSpanContext;
attributes = {};
links = [];
events = [];
startTime;
resource;
instrumentationScope;
_droppedAttributesCount = 0;
_droppedEventsCount = 0;
_droppedLinksCount = 0;
_attributesCount = 0;
name;
status = {
code: SpanStatusCode.UNSET,
};
endTime = [0, 0];
_ended = false;
_duration = [-1, -1];
_spanProcessor;
_spanLimits;
_attributeValueLengthLimit;
_recordEndMetrics;
_performanceStartTime;
_performanceOffset;
_startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts) {
const now = Date.now();
this._spanContext = opts.spanContext;
this._performanceStartTime = otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + otperformance.timeOrigin);
this._startTimeProvided = opts.startTime != null;
this._spanLimits = opts.spanLimits;
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit ?? 0;
this._spanProcessor = opts.spanProcessor;
this.name = opts.name;
this.parentSpanContext = opts.parentSpanContext;
this.kind = opts.kind;
if (opts.links) {
for (const link of opts.links) {
this.addLink(link);
}
}
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
this._recordEndMetrics = opts.recordEndMetrics;
if (opts.attributes != null) {
this.setAttributes(opts.attributes);
}
this._spanProcessor.onStart(this, opts.context);
}
spanContext() {
return this._spanContext;
}
setAttribute(key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!isAttributeValue(value)) {
diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const { attributeCountLimit } = this._spanLimits;
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
if (attributeCountLimit !== undefined &&
this._attributesCount >= attributeCountLimit &&
isNewKey) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
if (isNewKey) {
this._attributesCount++;
}
return this;
}
setAttributes(attributes) {
for (const key in attributes) {
if (Object.prototype.hasOwnProperty.call(attributes, key)) {
this.setAttribute(key, attributes[key]);
}
}
return this;
}
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
const { eventCountLimit } = this._spanLimits;
if (eventCountLimit === 0) {
diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (eventCountLimit !== undefined &&
this.events.length >= eventCountLimit) {
if (this._droppedEventsCount === 0) {
diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if (isTimeInput(attributesOrStartTime)) {
if (!isTimeInput(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
const sanitized = sanitizeAttributes(attributesOrStartTime);
const { attributePerEventCountLimit } = this._spanLimits;
const attributes = {};
let droppedAttributesCount = 0;
let eventAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerEventCountLimit !== undefined &&
eventAttributesCount >= attributePerEventCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
eventAttributesCount++;
}
this.events.push({
name,
attributes,
time: this._getTime(timeStamp),
droppedAttributesCount,
});
return this;
}
addLink(link) {
if (this._isSpanEnded())
return this;
const { linkCountLimit } = this._spanLimits;
if (linkCountLimit === 0) {
this._droppedLinksCount++;
return this;
}
if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {
if (this._droppedLinksCount === 0) {
diag.debug('Dropping extra links.');
}
this.links.shift();
this._droppedLinksCount++;
}
const { attributePerLinkCountLimit } = this._spanLimits;
const sanitized = sanitizeAttributes(link.attributes);
const attributes = {};
let droppedAttributesCount = 0;
let linkAttributesCount = 0;
for (const attr in sanitized) {
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
continue;
}
const attrVal = sanitized[attr];
if (attributePerLinkCountLimit !== undefined &&
linkAttributesCount >= attributePerLinkCountLimit) {
droppedAttributesCount++;
continue;
}
attributes[attr] = this._truncateToSize(attrVal);
linkAttributesCount++;
}
const processedLink = { context: link.context };
if (linkAttributesCount > 0) {
processedLink.attributes = attributes;
}
if (droppedAttributesCount > 0) {
processedLink.droppedAttributesCount = droppedAttributesCount;
}
this.links.push(processedLink);
return this;
}
addLinks(links) {
for (const link of links) {
this.addLink(link);
}
return this;
}
setStatus(status) {
if (this._isSpanEnded())
return this;
if (status.code === SpanStatusCode.UNSET)
return this;
if (this.status.code === SpanStatusCode.OK)
return this;
const newStatus = { code: status.code };
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (status.code === SpanStatusCode.ERROR) {
if (typeof status.message === 'string') {
newStatus.message = status.message;
}
else if (status.message != null) {
diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
}
}
this.status = newStatus;
return this;
}
updateName(name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
}
end(endTime) {
if (this._isSpanEnded()) {
diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
return;
}
this.endTime = this._getTime(endTime);
this._duration = hrTimeDuration(this.startTime, this.endTime);
if (this._duration[0] < 0) {
diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
}
if (this._droppedLinksCount > 0) {
diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
}
if (this._spanProcessor.onEnding) {
this._spanProcessor.onEnding(this);
}
this._recordEndMetrics?.();
this._ended = true;
this._spanProcessor.onEnd(this);
}
_getTime(inp) {
if (typeof inp === 'number' && inp <= otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return hrTime(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return millisToHrTime(inp);
}
if (inp instanceof Date) {
return millisToHrTime(inp.getTime());
}
if (isTimeInputHrTime(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return millisToHrTime(Date.now());
}
const msDuration = otperformance.now() - this._performanceStartTime;
return addHrTimes(this.startTime, millisToHrTime(msDuration));
}
isRecording() {
return this._ended === false;
}
recordException(exception, time) {
const attributes = {};
if (typeof exception === 'string') {
attributes[ATTR_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {
this.addEvent(ExceptionEventName, attributes, time);
}
else {
diag.warn(`Failed to record an exception ${exception}`);
}
}
get duration() {
return this._duration;
}
get ended() {
return this._ended;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
get droppedEventsCount() {
return this._droppedEventsCount;
}
get droppedLinksCount() {
return this._droppedLinksCount;
}
_isSpanEnded() {
if (this._ended) {
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
}
return this._ended;
}
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
_truncateToSize(value) {
const limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);
}
// Other types, no need to apply value length limit
return value;
}
[inspectCustom](depth, options, inspect) {
const payload = {
name: this.name,
kind: this.kind,
spanContext: this._spanContext,
parentSpanContext: this.parentSpanContext,
status: this.status,
startTime: this.startTime,
endTime: this.endTime,
duration: this._duration,
ended: this._ended,
attributes: this.attributes,
events: this.events,
links: this.links,
droppedAttributesCount: this._droppedAttributesCount,
droppedEventsCount: this._droppedEventsCount,
droppedLinksCount: this._droppedLinksCount,
instrumentationScope: this.instrumentationScope,
resource: { attributes: settledResourceAttributes(this.resource) },
};
return formatInspect('SpanImpl', payload, depth, options, inspect);
}
}
//# sourceMappingURL=Span.js.map

View File

@ -0,0 +1,21 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const rollupOTS4ktWb = require('../../vendored/@apm-js-collab/code-transformer-bundler-plugins/dist/esm/rollup-OTS4ktWb.js');
const index = require('../config/index.js');
const options = require('./options.js');
function sentryOrchestrionPlugin(options$1 = {}) {
const moduleNames = index.instrumentedModuleNames(options$1.instrumentations);
return {
...rollupOTS4ktWb.t(options.orchestrionTransformOptions(options$1)),
buildStart(rollupOptions) {
const externalizedModules = moduleNames.filter((name) => rollupOptions.external(name, void 0, false));
if (externalizedModules.length > 0) {
this.warn(options.externalizedModulesWarning(externalizedModules));
}
}
};
}
exports.sentryOrchestrionPlugin = sentryOrchestrionPlugin;
//# sourceMappingURL=rollup.js.map

View File

@ -0,0 +1,89 @@
import { defineIntegration, getClient, captureException, debug } from '@sentry/core';
import { isMainThread } from 'worker_threads';
import { DEBUG_BUILD } from '../debug-build.js';
import { logAndExitProcess } from '../utils/errorhandling.js';
const INTEGRATION_NAME = "OnUncaughtException";
const onUncaughtExceptionIntegration = defineIntegration((options = {}) => {
const optionsWithDefaults = {
exitEvenIfOtherHandlersAreRegistered: false,
...options
};
return {
name: INTEGRATION_NAME,
setup(client) {
if (!isMainThread) {
return;
}
global.process.on("uncaughtException", makeErrorHandler(client, optionsWithDefaults));
}
};
});
function makeErrorHandler(client, options) {
const timeout = 2e3;
let caughtFirstError = false;
let caughtSecondError = false;
let calledFatalError = false;
let firstError;
const clientOptions = client.getOptions();
return Object.assign(
(error) => {
let onFatalError = logAndExitProcess;
if (options.onFatalError) {
onFatalError = options.onFatalError;
} else if (clientOptions.onFatalError) {
onFatalError = clientOptions.onFatalError;
}
const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => {
return (
// as soon as we're using domains this listener is attached by node itself
listener.name !== "domainUncaughtExceptionClear" && // the handler we register in this integration
listener._errorHandler !== true
);
}).length;
const processWouldExit = userProvidedListenersCount === 0;
const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;
if (!caughtFirstError) {
firstError = error;
caughtFirstError = true;
if (getClient() === client) {
captureException(error, {
originalException: error,
captureContext: {
level: "fatal"
},
mechanism: {
handled: false,
type: "auto.node.onuncaughtexception"
}
});
}
if (!calledFatalError && shouldApplyFatalHandlingLogic) {
calledFatalError = true;
onFatalError(error);
}
} else {
if (shouldApplyFatalHandlingLogic) {
if (calledFatalError) {
DEBUG_BUILD && debug.warn(
"uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown"
);
logAndExitProcess(error);
} else if (!caughtSecondError) {
caughtSecondError = true;
setTimeout(() => {
if (!calledFatalError) {
calledFatalError = true;
onFatalError(firstError, error);
}
}, timeout);
}
}
}
},
{ _errorHandler: true }
);
}
export { makeErrorHandler, onUncaughtExceptionIntegration };
//# sourceMappingURL=onuncaughtexception.js.map

View File

@ -0,0 +1,18 @@
import type { Client } from '../../client';
import type { Scope } from '../../scope';
import type { HttpServerResponse } from './types';
/**
* Starts a session and tracks it in the context of a given isolation scope.
* When the passed response is finished, the session is put into a task and
* is aggregated with other sessions that may happen in a certain time window
* (sessionFlushingDelayMs).
*
* The sessions are always aggregated by the client that is on the current
* scope at the time of ending the response (if there is one).
*/
export declare function recordRequestSession(client: Client, { requestIsolationScope, response, sessionFlushingDelayMS, }: {
requestIsolationScope: Scope;
response: HttpServerResponse;
sessionFlushingDelayMS?: number;
}): void;
//# sourceMappingURL=record-request-session.d.ts.map

View File

@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0;
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const invalid_span_constants_1 = require("./invalid-span-constants");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
// Valid characters (0-9, a-f, A-F) are marked as 1.
const isHex = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
]);
function isValidHex(id, length) {
// As of 1.9.0 the id was allowed to be a non-string value,
// even though it was not possible in the types.
if (typeof id !== 'string' || id.length !== length)
return false;
let r = 0;
for (let i = 0; i < id.length; i += 4) {
r +=
(isHex[id.charCodeAt(i)] | 0) +
(isHex[id.charCodeAt(i + 1)] | 0) +
(isHex[id.charCodeAt(i + 2)] | 0) +
(isHex[id.charCodeAt(i + 3)] | 0);
}
return r === length;
}
/**
* @since 1.0.0
*/
function isValidTraceId(traceId) {
return isValidHex(traceId, 32) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
}
exports.isValidTraceId = isValidTraceId;
/**
* @since 1.0.0
*/
function isValidSpanId(spanId) {
return isValidHex(spanId, 16) && spanId !== invalid_span_constants_1.INVALID_SPANID;
}
exports.isValidSpanId = isValidSpanId;
/**
* Returns true if this {@link SpanContext} is valid.
* @return true if this {@link SpanContext} is valid.
*
* @since 1.0.0
*/
function isSpanContextValid(spanContext) {
return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId));
}
exports.isSpanContextValid = isSpanContextValid;
/**
* Wrap the given {@link SpanContext} in a new non-recording {@link Span}
*
* @param spanContext span context to be wrapped
* @returns a new non-recording {@link Span} with the provided context
*/
function wrapSpanContext(spanContext) {
return new NonRecordingSpan_1.NonRecordingSpan(spanContext);
}
exports.wrapSpanContext = wrapSpanContext;
//# sourceMappingURL=spancontext-utils.js.map

View File

@ -0,0 +1,34 @@
import { getMainCarrier } from '../carrier.js';
import { _setSpanForScope } from '../utils/spanOnScope.js';
import { safeUnref } from '../utils/timer.js';
import { getAsyncContextStrategy } from './index.js';
function waitForTracingChannelBinding(callback, retries = 1) {
const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();
if (binding) {
callback();
return;
}
if (!retries) {
return;
}
safeUnref(
setTimeout(() => {
waitForTracingChannelBinding(callback, retries - 1);
}, 1)
);
}
function _INTERNAL_createTracingChannelBinding(asyncLocalStorage, getScopes) {
return {
asyncLocalStorage,
getStoreWithActiveSpan: (span) => {
const { scope, isolationScope } = getScopes();
const activeScope = scope.clone();
_setSpanForScope(activeScope, span);
return { scope: activeScope, isolationScope };
}
};
}
export { _INTERNAL_createTracingChannelBinding, waitForTracingChannelBinding };
//# sourceMappingURL=tracing-channel-binding.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"feedback.js","sources":["../../src/feedback.ts"],"sourcesContent":["import { getClient, getCurrentScope } from './currentScopes';\nimport type { EventHint } from './types/event';\nimport type { FeedbackEvent, SendFeedbackParams } from './types/feedback';\n\n/**\n * Send user feedback to Sentry.\n */\nexport function captureFeedback(\n params: SendFeedbackParams,\n hint: EventHint & { 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"],"names":[],"mappings":";;AAOO,SAAS,gBACd,MAAA,EACA,IAAA,GAAgD,EAAC,EACjD,KAAA,GAAQ,iBAAgB,EAChB;AACR,EAAA,MAAM,EAAE,SAAS,IAAA,EAAM,KAAA,EAAO,KAAK,MAAA,EAAQ,iBAAA,EAAmB,MAAK,GAAI,MAAA;AAEvE,EAAA,MAAM,aAAA,GAA+B;AAAA,IACnC,QAAA,EAAU;AAAA,MACR,QAAA,EAAU;AAAA,QACR,aAAA,EAAe,KAAA;AAAA,QACf,IAAA;AAAA,QACA,OAAA;AAAA,QACA,GAAA;AAAA,QACA,MAAA;AAAA,QACA,mBAAA,EAAqB;AAAA;AACvB,KACF;AAAA,IACA,IAAA,EAAM,UAAA;AAAA,IACN,KAAA,EAAO,MAAA;AAAA,IACP;AAAA,GACF;AAEA,EAAA,MAAM,MAAA,GAAS,KAAA,EAAO,SAAA,EAAU,IAAK,SAAA,EAAU;AAE/C,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,MAAA,CAAO,IAAA,CAAK,oBAAA,EAAsB,aAAA,EAAe,IAAI,CAAA;AAAA,EACvD;AAEA,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,YAAA,CAAa,aAAA,EAAe,IAAI,CAAA;AAEtD,EAAA,OAAO,OAAA;AACT;;;;"}

View File

@ -0,0 +1 @@
{"version":3,"file":"chunk-D6vf50IK.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}

View File

@ -0,0 +1,67 @@
import { RequestOptions } from 'node:http';
import { HttpIncomingMessage, Integration } from '@sentry/core';
import { recordRequestSession } from '@sentry/core';
export { recordRequestSession };
interface WeakRefImpl<T> {
deref(): T | undefined;
}
type StartSpanCallback = (next: () => boolean) => boolean;
type RequestWithOptionalStartSpanCallback = HttpIncomingMessage & {
_startSpanCallback?: WeakRefImpl<StartSpanCallback>;
};
export interface HttpServerIntegrationOptions {
/**
* Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.
* Read more about Release Health: https://docs.sentry.io/product/releases/health/
*
* Defaults to `true`.
*/
sessions?: boolean;
/**
* Number of milliseconds until sessions tracked with `trackIncomingRequestsAsSessions` will be flushed as a session aggregate.
*
* Defaults to `60000` (60s).
*/
sessionFlushingDelayMS?: number;
/**
* Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.
* This can be useful for long running requests where the body is not needed and we want to avoid capturing it.
*
* @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the incoming request.
* @param request Contains the {@type RequestOptions} object used to make the incoming request.
*/
ignoreRequestBody?: (url: string, request: RequestOptions) => boolean;
/**
* Controls the maximum size of incoming HTTP request bodies attached to events.
*
* Available options:
* - 'none': No request bodies will be attached
* - 'small': Request bodies up to 1,000 bytes will be attached
* - 'medium': Request bodies up to 10,000 bytes will be attached (default)
* - 'always': Request bodies will always be attached
*
* Note that even with 'always' setting, bodies exceeding 1MB will never be attached
* for performance and security reasons.
*
* @default 'medium'
*/
maxRequestBodySize?: 'none' | 'small' | 'medium' | 'always';
}
/**
* Add a callback to the request object that will be called when the request is started.
* The callback will receive the next function to continue processing the request.
*/
export declare function addStartSpanCallback(request: RequestWithOptionalStartSpanCallback, callback: StartSpanCallback): void;
/**
* This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests
* handled via the node `http` module.
*
* This version uses OpenTelemetry for context propagation and span management.
*
* @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry
*/
export declare const httpServerIntegration: (options?: HttpServerIntegrationOptions) => Integration & {
name: "Http.Server";
setupOnce: () => void;
};
//# sourceMappingURL=httpServerIntegration.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"thread.d.ts","sourceRoot":"","sources":["../../../src/types/thread.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,YAAY;AACZ,MAAM,WAAW,MAAM;IACrB,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB"}

View File

@ -0,0 +1,38 @@
import { Client } from '../client';
import { DsnComponents, DsnLike } from '../types/dsn';
/**
* Renders the string representation of this Dsn.
*
* By default, this will render the public representation without the password
* component. To get the deprecated private representation, set `withPassword`
* to true.
*
* @param withPassword When set to true, the password will be included.
*/
export declare function dsnToString(dsn: DsnComponents, withPassword?: boolean): string;
/**
* Parses a Dsn from a given string.
*
* @param str A Dsn as string
* @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string
*/
export declare function dsnFromString(str: string): DsnComponents | undefined;
/**
* Extract the org ID from a DSN host.
*
* @param host The host from a DSN
* @returns The org ID if found, undefined otherwise
*/
export declare function extractOrgIdFromDsnHost(host: string): string | undefined;
/**
* Returns the organization ID of the client.
*
* The organization ID is extracted from the DSN. If the client options include a `orgId`, this will always take precedence.
*/
export declare function extractOrgIdFromClient(client: Client): string | undefined;
/**
* Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
* @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source
*/
export declare function makeDsn(from: DsnLike): DsnComponents | undefined;
//# sourceMappingURL=dsn.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../../../../src/tracing/google-genai/streaming.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AA+GnD;;;;GAIG;AACH,wBAAuB,gBAAgB,CACrC,MAAM,EAAE,aAAa,CAAC,mBAAmB,CAAC,EAC1C,IAAI,EAAE,IAAI,EACV,aAAa,EAAE,OAAO,GACrB,cAAc,CAAC,mBAAmB,EAAE,IAAI,EAAE,OAAO,CAAC,CAepD"}

View File

@ -0,0 +1 @@
{"version":3,"file":"errorhandling.d.ts","sourceRoot":"","sources":["../../../src/utils/errorhandling.ts"],"names":[],"mappings":"AAQA;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAoCtD"}

View File

@ -0,0 +1,55 @@
import { __exports as base64Vlq } from '../../../_virtual/base64-vlq.js';
import './base64.js';
import { __exports as base64$1 } from '../../../_virtual/base64.js';
var base64 = base64$1;
var VLQ_BASE_SHIFT = 5;
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
var VLQ_BASE_MASK = VLQ_BASE - 1;
var VLQ_CONTINUATION_BIT = VLQ_BASE;
function toVLQSigned(aValue) {
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative ? -shifted : shifted;
}
base64Vlq.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};
export { base64Vlq as default };
//# sourceMappingURL=base64-vlq.js.map

View File

@ -0,0 +1,81 @@
import { s as semifies$1 } from '../../../semifies/index.js';
import { t as transformer } from './transformer.js';
var __typeError = (msg) => {
throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
var _configs, _dcModule, _transformers, _customTransforms;
const semifies = semifies$1;
const { Transformer } = transformer;
class InstrumentationMatcher {
/**
* @param {object[]} configs - Array of instrumentation configuration objects.
* @param {string} [dcModule] - The diagnostics_channel module specifier to inject.
* Defaults to `'diagnostics_channel'`.
*/
constructor(configs, dcModule) {
__privateAdd(this, _configs, []);
__privateAdd(this, _dcModule, null);
__privateAdd(this, _transformers, {});
__privateAdd(this, _customTransforms, {});
__privateSet(this, _configs, configs);
__privateSet(this, _dcModule, dcModule || "diagnostics_channel");
}
/** Releases all cached transformers, freeing any associated resources. */
free() {
__privateSet(this, _transformers, {});
}
/**
* Registers a custom transform function under the given operator name.
*
* Custom transforms override built-in ones when an instrumentation config
* specifies the same `transform` value.
*
* @param {string} name - Operator name (e.g. `'traceSync'`).
* @param {Function} fn - Transform function `(state, node, parent, ancestry) => void`.
*/
addTransform(name, fn) {
__privateGet(this, _customTransforms)[name] = fn;
}
/**
* Returns a {@link Transformer} for the given module/file/version, or `undefined`
* if no registered config matches.
*
* Results are cached by a `moduleName/filePath@version` key.
*
* @param {string} moduleName - The npm package name (e.g. `'express'`).
* @param {string} version - The installed semver version string.
* @param {string} filePath - The relative file path within the package.
* @returns {import('./transformer').Transformer|undefined}
*/
getTransformer(moduleName, version, filePath) {
filePath = filePath.replace(/\\/g, "/");
const id = `${moduleName}/${filePath}@${version}`;
if (__privateGet(this, _transformers)[id]) return __privateGet(this, _transformers)[id];
const configs = __privateGet(this, _configs).filter(
({ module: mod }) => mod.name === moduleName && (typeof mod.filePath === "string" ? mod.filePath === filePath : mod.filePath.test(filePath)) && semifies(version, mod.versionRange)
);
if (configs.length === 0) return;
__privateGet(this, _transformers)[id] = new Transformer(
moduleName,
version,
filePath,
configs,
__privateGet(this, _dcModule),
__privateGet(this, _customTransforms)
);
return __privateGet(this, _transformers)[id];
}
}
_configs = new WeakMap();
_dcModule = new WeakMap();
_transformers = new WeakMap();
_customTransforms = new WeakMap();
var matcher = { InstrumentationMatcher };
export { matcher as m };
//# sourceMappingURL=matcher.js.map

View File

@ -0,0 +1,51 @@
/**
* Handler method wrapping for MCP server instrumentation
*
* Provides automatic error capture and span correlation for tool, resource,
* and prompt handlers.
*/
import type { MCPServerInstance } from './types';
/**
* Wraps tool handlers to associate them with request spans.
* Instruments both `tool` (legacy API) and `registerTool` (new API) if present.
* @param serverInstance - MCP server instance
*/
export declare function wrapToolHandlers(serverInstance: MCPServerInstance): void;
/**
* Wraps resource handlers to associate them with request spans.
* Instruments both `resource` (legacy API) and `registerResource` (new API) if present.
* @param serverInstance - MCP server instance
*/
export declare function wrapResourceHandlers(serverInstance: MCPServerInstance): void;
/**
* Wraps prompt handlers to associate them with request spans.
* Instruments both `prompt` (legacy API) and `registerPrompt` (new API) if present.
* @param serverInstance - MCP server instance
*/
export declare function wrapPromptHandlers(serverInstance: MCPServerInstance): void;
/**
* Wraps all MCP handler types for span correlation.
* Supports both the legacy API (`tool`, `resource`, `prompt`) and the newer API
* (`registerTool`, `registerResource`, `registerPrompt`), instrumenting whichever methods are present.
* @param serverInstance - MCP server instance
*/
export declare function wrapAllMCPHandlers(serverInstance: MCPServerInstance): void;
/**
* Retroactively wraps handlers on tools, resources, and prompts that were registered
* before `wrapMcpServerWithSentry` was called.
*
* The MCP SDK stores registered entries in private maps and invokes them via the entry's
* own property at call time — `executor` for tools, `readCallback` for resources, and
* `handler` for prompts. Replacing those properties
* in-place is therefore equivalent to having wrapped the original registration call.
*
* NOTE: This intentionally accesses private MCP SDK internals (`_registeredTools` etc.).
* The properties and their shapes are verified against @modelcontextprotocol/sdk source:
* https://github.com/modelcontextprotocol/typescript-sdk/blob/2c0c481cb9dbfd15c8613f765c940a5f5bace94d/packages/server/src/server/mcp.ts#L304
* When upgrading the MCP SDK, re-verify that these internal maps and their callable
* properties still exist and are invoked directly (not captured by closure at registration).
* All access is defensive — if a property is absent or not a function we skip silently.
* @internal
*/
export declare function wrapExistingHandlers(serverInstance: MCPServerInstance): void;
//# sourceMappingURL=handlers.d.ts.map

View File

@ -0,0 +1,83 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const diagnosticsChannel = require('node:diagnostics_channel');
const core = require('@sentry/core');
const debugBuild = require('../../../debug-build.js');
const channels = require('../../../orchestrion/channels.js');
const consumer = require('./consumer.js');
const spans = require('./spans.js');
function _interopNamespaceDefault(e) {
const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
if (e) {
for (const k in e) {
n[k] = e[k];
}
}
n.default = e;
return n;
}
const diagnosticsChannel__namespace = /*#__PURE__*/_interopNamespaceDefault(diagnosticsChannel);
const INTEGRATION_NAME = "Kafka";
function subscribeToProducer() {
const channel = diagnosticsChannel__namespace.tracingChannel(channels.CHANNELS.KAFKAJS_SEND_BATCH);
const subscribers = {
start(ctx) {
const spans$1 = [];
(ctx.arguments[0]?.topicMessages ?? []).forEach((topicMessage) => {
topicMessage.messages.forEach((message) => {
spans$1.push(spans.startProducerSpan(topicMessage.topic, message));
});
});
ctx._sentrySpans = spans$1;
},
error(ctx) {
if (ctx._sentrySpans) {
spans.applyErrorToSpans(ctx._sentrySpans, ctx.error);
}
},
asyncEnd(ctx) {
ctx._sentrySpans?.forEach((span) => span.end());
}
};
channel.subscribe(subscribers);
}
function subscribeToConsumer() {
const channel = diagnosticsChannel__namespace.tracingChannel(channels.CHANNELS.KAFKAJS_CONSUMER_RUN);
const subscribers = {
start(ctx) {
const config = ctx.arguments[0];
if (!config || typeof config !== "object") {
return;
}
if (typeof config.eachMessage === "function" && !consumer.isWrappedConsumerCallback(config.eachMessage)) {
config.eachMessage = consumer.wrapEachMessage(config.eachMessage);
}
if (typeof config.eachBatch === "function" && !consumer.isWrappedConsumerCallback(config.eachBatch)) {
config.eachBatch = consumer.wrapEachBatch(config.eachBatch);
}
}
};
channel.subscribe(subscribers);
}
const _kafkajsChannelIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
if (!diagnosticsChannel__namespace.tracingChannel) {
return;
}
debugBuild.DEBUG_BUILD && core.debug.log(
`[orchestrion:kafkajs] subscribing to channels "${channels.CHANNELS.KAFKAJS_SEND_BATCH}", "${channels.CHANNELS.KAFKAJS_CONSUMER_RUN}"`
);
subscribeToProducer();
subscribeToConsumer();
}
};
});
const kafkajsChannelIntegration = core.defineIntegration(_kafkajsChannelIntegration);
exports.kafkajsChannelIntegration = kafkajsChannelIntegration;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,80 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const debugBuild = require('../debug-build.js');
const debugLogger = require('../utils/debug-logger.js');
const envelope = require('../utils/envelope.js');
const promisebuffer = require('../utils/promisebuffer.js');
const ratelimit = require('../utils/ratelimit.js');
const DEFAULT_TRANSPORT_BUFFER_SIZE = 64;
function createTransport(options, makeRequest, buffer = promisebuffer.makePromiseBuffer(
options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE
)) {
let rateLimits = {};
const flush = (timeout) => buffer.drain(timeout);
function send(envelope$1) {
const filteredEnvelopeItems = [];
envelope.forEachEnvelopeItem(envelope$1, (item, type) => {
const dataCategory = envelope.envelopeItemTypeToDataCategory(type);
if (ratelimit.isRateLimited(rateLimits, dataCategory)) {
options.recordDroppedEvent("ratelimit_backoff", dataCategory);
} else {
filteredEnvelopeItems.push(item);
}
});
if (filteredEnvelopeItems.length === 0) {
return Promise.resolve({});
}
const filteredEnvelope = envelope.createEnvelope(envelope$1[0], filteredEnvelopeItems);
const recordEnvelopeLoss = (reason) => {
if (envelope.envelopeContainsItemType(filteredEnvelope, ["client_report"])) {
debugBuild.DEBUG_BUILD && debugLogger.debug.warn(`Dropping client report. Will not send outcomes (reason: ${reason}).`);
return;
}
envelope.forEachEnvelopeItem(filteredEnvelope, (item, type) => {
options.recordDroppedEvent(reason, envelope.envelopeItemTypeToDataCategory(type));
});
};
const requestTask = () => makeRequest({ body: envelope.serializeEnvelope(filteredEnvelope) }).then(
(response) => {
if (response.statusCode === 413) {
debugBuild.DEBUG_BUILD && debugLogger.debug.error(
"Sentry responded with status code 413. Envelope was discarded due to exceeding size limits."
);
recordEnvelopeLoss("send_error");
return response;
}
if (debugBuild.DEBUG_BUILD && response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) {
debugLogger.debug.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);
}
rateLimits = ratelimit.updateRateLimits(rateLimits, response);
return response;
},
(error) => {
recordEnvelopeLoss("network_error");
debugBuild.DEBUG_BUILD && debugLogger.debug.error("Encountered error running transport request:", error);
throw error;
}
);
return buffer.add(requestTask).then(
(result) => result,
(error) => {
if (error === promisebuffer.SENTRY_BUFFER_FULL_ERROR) {
debugBuild.DEBUG_BUILD && debugLogger.debug.error("Skipped sending event because buffer is full.");
recordEnvelopeLoss("queue_overflow");
return Promise.resolve({});
} else {
throw error;
}
}
);
}
return {
send,
flush
};
}
exports.DEFAULT_TRANSPORT_BUFFER_SIZE = DEFAULT_TRANSPORT_BUFFER_SIZE;
exports.createTransport = createTransport;
//# sourceMappingURL=base.js.map

View File

@ -0,0 +1,18 @@
import type { Context } from '@opentelemetry/api';
import type { ReadableSpan } from './export/ReadableSpan';
import type { Span } from './Span';
import type { SpanProcessor } from './SpanProcessor';
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
export declare class MultiSpanProcessor implements SpanProcessor {
private readonly _spanProcessors;
constructor(spanProcessors: SpanProcessor[]);
forceFlush(): Promise<void>;
onStart(span: Span, context: Context): void;
onEnding(span: Span): void;
onEnd(span: ReadableSpan): void;
shutdown(): Promise<void>;
}
//# sourceMappingURL=MultiSpanProcessor.d.ts.map

View File

@ -0,0 +1,5 @@
/**
* Checks and warns if a framework isn't wrapped by opentelemetry.
*/
export declare function ensureIsWrapped(maybeWrappedFunction: unknown, name: 'express' | 'connect' | 'fastify' | 'hapi' | 'koa' | 'hono'): void;
//# sourceMappingURL=ensureIsWrapped.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/vercel-ai/index.ts"],"sourcesContent":["import { defineIntegration, waitForTracingChannelBinding, type IntegrationFn } from '@sentry/core';\nimport { subscribeVercelAiTracingChannel } from './vercel-ai-dc-subscriber';\nimport * as dc from 'node:diagnostics_channel';\n\nexport interface VercelAiOptions {\n /**\n * Enable or disable input recording. Enabled if `dataCollection.genAI.inputs` (or the deprecated `sendDefaultPii` option) is `true`\n * or if you set `isEnabled` to `true` in your ai SDK method telemetry settings.\n * Integration-level options take precedence over global `dataCollection` config.\n */\n recordInputs?: boolean;\n\n /**\n * Enable or disable output recording. Enabled if `dataCollection.genAI.outputs` (or the deprecated `sendDefaultPii` option) is `true`\n * or if you set `isEnabled` to `true` in your ai SDK method telemetry settings.\n * Integration-level options take precedence over global `dataCollection` config.\n */\n recordOutputs?: boolean;\n\n /**\n * Enable or disable truncation of recorded input messages.\n * Defaults to `true`.\n */\n enableTruncation?: boolean;\n}\n\nconst _vercelAiIntegration = ((options: VercelAiOptions = {}) => {\n return {\n name: 'VercelAI' as const,\n setupOnce() {\n // Bail if this is not available\n if (!dc.tracingChannel) {\n return;\n }\n\n // Subscribe to the `ai` SDK's native telemetry tracing channel (ai >= 7).\n // This is a no-op on versions that don't publish to the channel, so it is always safe to call.\n waitForTracingChannelBinding(() => {\n subscribeVercelAiTracingChannel(dc.tracingChannel, options);\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Auto-instrument the `ai` SDK's native telemetry tracing channel (ai >= 7).\n */\nexport const vercelAiIntegration = defineIntegration(_vercelAiIntegration);\n"],"names":["dc","waitForTracingChannelBinding","subscribeVercelAiTracingChannel","defineIntegration"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,oBAAA,CAAA,CAAA,CAAA,CAAwB,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAA2B,EAAC,CAAA,CAAA,CAAA,CAAA,CAAM;AAC/D,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO;AAAA,CAAA,CAAA,CAAA,CACL,CAAA,CAAA,CAAA,CAAA,EAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACN,SAAA,CAAA,CAAA,CAAY;AAEV,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAACA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAG,cAAA,CAAA,CAAgB;AACtB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CACF;AAIA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,CAA6B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM;AACjC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAAC,oDAAA,CAAgCF,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAgB,OAAO,CAAA;AAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAC5D,CAAC,CAAA;AAAA,CAAA,CAAA,CAAA,CACH;AAAA,CAAA,CAAA,CACF;AACF,CAAA,CAAA;AAKO,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAsBG,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAkB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAoB,CAAA;;"}

View File

@ -0,0 +1,14 @@
import { FsInstrumentationConfig } from './vendored/types';
/**
* This integration will create spans for `fs` API operations, like reading and writing files.
*
* **WARNING:** This integration may add significant overhead to your application. Especially in scenarios with a lot of
* file I/O, like for example when running a framework dev server, including this integration can massively slow down
* your application.
*
* @param options Configuration for this integration.
*/
export declare const fsIntegration: (options?: FsInstrumentationConfig | undefined) => import("@sentry/core").Integration & {
name: "FileSystem";
};
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"meta.js","sources":["../../../src/utils/meta.ts"],"sourcesContent":["import type { SerializedTraceData } from '../types/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 * <head>\n * ${getTraceMetaTags()}\n * </head>\n * `;\n * }\n * ```\n *\n */\nexport function getTraceMetaTags(traceData?: SerializedTraceData): string {\n return (\n Object.entries(traceData || getTraceData())\n .map(([key, value]) => `<meta name=\"${key}\" content=\"${value}\"/>`)\n // Joined without whitespace on purpose: a separator between the tags becomes a text node when\n // injected into `<head>`, which breaks React 19 whole-document hydration (#21915).\n .join('')\n );\n}\n"],"names":[],"mappings":";;AAwBO,SAAS,iBAAiB,SAAA,EAAyC;AACxE,EAAA,OACE,OAAO,OAAA,CAAQ,SAAA,IAAa,cAAc,CAAA,CACvC,IAAI,CAAC,CAAC,KAAK,KAAK,CAAA,KAAM,eAAe,GAAG,CAAA,WAAA,EAAc,KAAK,CAAA,GAAA,CAAK,CAAA,CAGhE,KAAK,EAAE,CAAA;AAEd;;;;"}

View File

@ -0,0 +1,13 @@
import type { Exception } from '@opentelemetry/api';
import type { ErrorHandler } from './types';
/**
* Set the global error handler
* @param {ErrorHandler} handler
*/
export declare function setGlobalErrorHandler(handler: ErrorHandler): void;
/**
* Return the global error handler
* @param {Exception} ex
*/
export declare function globalErrorHandler(ex: Exception): void;
//# sourceMappingURL=global-error-handler.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"spanUtils.d.ts","sourceRoot":"","sources":["../../../src/utils/spanUtils.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAWnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,KAAK,EACV,sBAAsB,EACtB,IAAI,EACJ,cAAc,EACd,QAAQ,EAER,aAAa,EACb,gBAAgB,EACjB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAStD,eAAO,MAAM,eAAe,IAAM,CAAC;AACnC,eAAO,MAAM,kBAAkB,IAAM,CAAC;AAItC;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,IAAI,GAAG,YAAY,CActE;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,IAAI,GAAG,YAAY,CAe3D;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAIpD;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAI1D;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,GAAG,YAAY,EAAE,GAAG,SAAS,CAY1F;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,CAAC,EAAE,QAAQ,EAAE,GACjB,YAAY,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,CAWpE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,aAAa,GAAG,SAAS,GAAG,MAAM,CAe/E;AAUD;;GAEG;AAIH,wBAAgB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,QAAQ,CAmC/C;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,IAAI,GAAG,gBAAgB,CAoCnE;AAgBD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAAC,QAAQ,EAAE,gBAAgB,GAAG,sBAAsB,CASnG;AAOD,+BAA+B;AAC/B,MAAM,WAAW,6BAA8B,SAAQ,IAAI;IACzD,UAAU,EAAE,cAAc,CAAC;IAC3B,SAAS,EAAE,aAAa,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,UAAU,CAAC;IACnB,OAAO,EAAE,aAAa,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC;CACpB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,UAAU,CAE/D;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAKjD;AAED,yEAAyE;AACzE,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAUnF;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAO9E;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,UAAU,EAAE,cAAc,EAC1B,MAAM,EAAE,UAAU,GAAG,SAAS,GAC7B,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAMxC;AAED,QAAA,MAAM,iBAAiB,sBAAsB,CAAC;AAC9C,QAAA,MAAM,eAAe,oBAAoB,CAAC;AAE1C,KAAK,yBAAyB,GAAG,IAAI,GAAG;IACtC,CAAC,iBAAiB,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC,eAAe,CAAC,CAAC,EAAE,IAAI,CAAC;CAC1B,CAAC;AAEF;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,yBAAyB,EAAE,SAAS,EAAE,IAAI,GAAG,IAAI,CA8BzF;AAED,kDAAkD;AAClD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,yBAAyB,EAAE,SAAS,EAAE,IAAI,GAAG,IAAI,CAI9F;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,yBAAyB,GAAG,IAAI,EAAE,CAoB1E;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,gCAA0B,CAAC;AAEnD;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,yBAAyB,GAAG,IAAI,CAE7E;AAED;;GAEG;AACH,wBAAgB,aAAa,IAAI,IAAI,GAAG,SAAS,CAQhD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAU1C;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAM7D"}

View File

@ -0,0 +1,11 @@
/**
* EXPERIMENTAL: orchestrion-driven `dataloader` integration.
*
* Subscribes to the `orchestrion:dataloader:*` diagnostics_channels that the orchestrion code
* transform injects into `dataloader`'s constructor and prototype methods. Requires the orchestrion
* runtime hook or bundler plugin to be active.
*/
export declare const dataloaderChannelIntegration: () => import("@sentry/core").Integration & {
name: "Dataloader";
};
//# sourceMappingURL=dataloader.d.ts.map

View File

@ -0,0 +1,60 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0;
const version_1 = require("../version");
const semver_1 = require("./semver");
const major = version_1.VERSION.split('.')[0];
const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
const _global = (typeof globalThis === 'object'
? globalThis
: typeof self === 'object'
? self
: typeof window === 'object'
? window
: typeof global === 'object'
? global
: {});
function registerGlobal(type, instance, diag, allowOverride = false) {
var _a;
const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
version: version_1.VERSION,
});
if (!allowOverride && api[type]) {
// already registered an API of this type
const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== version_1.VERSION) {
// All registered APIs must be of the same version exactly
const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
return true;
}
exports.registerGlobal = registerGlobal;
function getGlobal(type) {
var _a, _b;
const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
exports.getGlobal = getGlobal;
function unregisterGlobal(type, diag) {
diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
}
exports.unregisterGlobal = unregisterGlobal;
//# sourceMappingURL=global-utils.js.map

View File

@ -0,0 +1,6 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
export {};
//# sourceMappingURL=SpanOptions.js.map

View File

@ -0,0 +1,4 @@
var base64 = {};
export { base64 as __exports };
//# sourceMappingURL=base64.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"prepareEvent.d.ts","sourceRoot":"","sources":["../../../src/utils/prepareEvent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAA2B,YAAY,EAAE,MAAM,cAAc,CAAC;AAGrG;;;;GAIG;AACH,MAAM,MAAM,kCAAkC,GAC1C,CAAC,cAAc,GAAG,OAAO,CAAC;KAAG,GAAG,IAAI,MAAM,SAAS,GAAG,KAAK;CAAE,CAAC,CAAC,GAC/D,CAAC,SAAS,GAAG,OAAO,CAAC;KAAG,GAAG,IAAI,MAAM,YAAY,GAAG,KAAK;CAAE,CAAC,CAAC,CAAC;AAElE;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,kCAAkC,GAAG,SAAS,GACnD,SAAS,GAAG,SAAS,CAiBvB"}

View File

@ -0,0 +1,75 @@
import { NET_PEER_NAME, DB_USER, DB_NAME, NET_PEER_PORT } from '@sentry/conventions/attributes';
import { ATTR_DB_CONNECTION_STRING } from './semconv.js';
function getConnectionAttributes(config) {
const { host, port, database, user } = getConfig(config);
const attrs = {
[ATTR_DB_CONNECTION_STRING]: getJDBCString(host, port, database),
// oxlint-disable-next-line typescript/no-deprecated
[DB_NAME]: database,
[DB_USER]: user,
// oxlint-disable-next-line typescript/no-deprecated
[NET_PEER_NAME]: host
};
const portNumber = parseInt(port, 10);
if (!isNaN(portNumber)) {
attrs[NET_PEER_PORT] = portNumber;
}
return attrs;
}
function getConfig(config) {
const { host, port, database, user } = config?.connectionConfig || config || {};
return { host, port, database, user };
}
function getJDBCString(host, port, database) {
let jdbcString = `jdbc:mysql://${host || "localhost"}`;
if (typeof port === "number") {
jdbcString += `:${port}`;
}
if (typeof database === "string") {
jdbcString += `/${database}`;
}
return jdbcString;
}
function getQueryText(query, format, values) {
const [querySql, queryValues] = typeof query === "string" ? [query, values] : [query.sql, hasValues(query) ? values || query.values : values];
try {
if (format && queryValues) {
return format(querySql, queryValues);
} else {
return querySql;
}
} catch {
return "Could not determine the query due to an error in formatting";
}
}
function hasValues(obj) {
return "values" in obj;
}
function getSpanName(query) {
const rawQuery = typeof query === "object" ? query.sql : query;
const firstSpace = rawQuery?.indexOf(" ");
if (typeof firstSpace === "number" && firstSpace !== -1) {
return rawQuery?.substring(0, firstSpace);
}
return rawQuery;
}
const once = (fn) => {
let called = false;
return (...args) => {
if (called) return;
called = true;
return fn(...args);
};
};
function getConnectionPrototypeToInstrument(connection) {
const connectionPrototype = connection.prototype;
const basePrototype = Object.getPrototypeOf(connectionPrototype);
if (typeof basePrototype?.query === "function" && typeof basePrototype?.execute === "function") {
return basePrototype;
}
return connectionPrototype;
}
export { getConnectionAttributes, getConnectionPrototypeToInstrument, getQueryText, getSpanName, once };
//# sourceMappingURL=utils.js.map

View File

@ -0,0 +1,17 @@
import type { Client } from './client';
import type { ClientOptions } from './types/options';
/** A class object that can instantiate Client objects. */
export type ClientClass<F extends Client, O extends ClientOptions> = new (options: O) => F;
/**
* Internal function to create a new SDK client instance. The client is
* installed and then bound to the current scope.
*
* @param clientClass The client class to instantiate.
* @param options Options to pass to the client.
*/
export declare function initAndBind<F extends Client, O extends ClientOptions>(clientClass: ClientClass<F, O>, options: O): Client;
/**
* Make the given client the current client.
*/
export declare function setCurrentClient(client: Client): void;
//# sourceMappingURL=sdk.d.ts.map

View File

@ -0,0 +1,17 @@
import { Client } from './client';
import { ClientOptions } from './types/options';
/** A class object that can instantiate Client objects. */
export type ClientClass<F extends Client, O extends ClientOptions> = new (options: O) => F;
/**
* Internal function to create a new SDK client instance. The client is
* installed and then bound to the current scope.
*
* @param clientClass The client class to instantiate.
* @param options Options to pass to the client.
*/
export declare function initAndBind<F extends Client, O extends ClientOptions>(clientClass: ClientClass<F, O>, options: O): Client;
/**
* Make the given client the current client.
*/
export declare function setCurrentClient(client: Client): void;
//# sourceMappingURL=sdk.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.1';\n"]}

View File

@ -0,0 +1 @@
{"version":3,"file":"semconv.d.ts","sourceRoot":"","sources":["../../../../../../src/integrations/tracing/knex/vendored/semconv.ts"],"names":[],"mappings":"AASA;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAG,cAAuB,CAAC;AAEzD,eAAO,MAAM,2BAA2B,EAAG,QAAiB,CAAC;AAE7D,eAAO,MAAM,+BAA+B,EAAG,YAAqB,CAAC"}

View File

@ -0,0 +1,31 @@
import type { InstrumentationConfig } from '../apmTypes';
/**
* Name shared by the `Program` injection configs (their `transform` field) and
* the custom transform registered on the bundler plugin (its `customTransforms`
* key). Any unique string works — it only has to match on both sides.
*
* Lives in this dependency-free leaf so the per-library config files can build
* their injection configs without importing the transform implementation (which
* pulls in `meriyah` and must never reach the runtime `--import` path).
*/
export declare const SUBSCRIBE_TRANSFORM_NAME = "sentrySubscribeOrchestrionChannel";
/**
* Turn a library's channel-publishing configs into the `Program`-matching
* injection configs that make each instrumented file self-register its channel
* subscriber (via the {@link SUBSCRIBE_TRANSFORM_NAME} custom transform).
*
* Emits one injection per distinct instrumented file (deduped by module
* matcher), so the subscribe snippet lands in exactly the files that receive
* channels and inherits their precise version ranges. `channelName` carries the
* package name (not a real channel — nothing is wrapped here) so the transform
* can look up which subscriber to import.
*
* Co-located with each library's config (e.g. `mysqlSubscribeInjection`) but
* kept OUT of `SENTRY_INSTRUMENTATIONS`: the runtime `--import` hook consumes
* that list and can't register the custom transform, and an unregistered
* `transform` makes the code-transformer drop the whole file. They are
* aggregated separately into `SUBSCRIBE_INJECTIONS` and only handed to a bundler
* plugin that opts in (and registers the transform).
*/
export declare function toSubscribeInjections(configs: InstrumentationConfig[]): InstrumentationConfig[];
//# sourceMappingURL=subscribe-injection.d.ts.map

View File

@ -0,0 +1 @@
{"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../../../../../../../src/integrations/tracing/firebase/otel/patches/functions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAa,MAAM,gCAAgC,CAAC;AAYhG,OAAO,KAAK,EAA8B,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAEpG;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,0BAA0B,EAAE,MAAM,EAAE,EACpC,IAAI,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAClC,MAAM,EAAE,mBAAmB,CAAC,SAAS,CAAC,GACrC,mCAAmC,CAqBrC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,GAAG,iBAAiB,EAC9E,WAAW,EAAE,MAAM,GAClB,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,EAAE,oBAAoB,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,CAgEtE"}

View File

@ -0,0 +1,94 @@
import { TracingChannel } from 'node:diagnostics_channel';
import { GraphqlDocumentNode } from './utils';
export declare const GRAPHQL_DC_CHANNEL_PARSE = "graphql:parse";
export declare const GRAPHQL_DC_CHANNEL_VALIDATE = "graphql:validate";
export declare const GRAPHQL_DC_CHANNEL_EXECUTE = "graphql:execute";
export declare const GRAPHQL_DC_CHANNEL_SUBSCRIBE = "graphql:subscribe";
export declare const GRAPHQL_DC_CHANNEL_RESOLVE = "graphql:resolve";
/** Context published on the sync-only `graphql:parse` channel. */
export interface GraphqlParseData {
source: string | {
body?: string;
};
result?: GraphqlDocumentNode;
error?: unknown;
}
/** Context published on the sync-only `graphql:validate` channel. */
export interface GraphqlValidateData {
document: GraphqlDocumentNode;
/** Validation errors returned by validation; an empty array means the document is valid. */
result?: ReadonlyArray<unknown>;
error?: unknown;
}
/**
* Context published on the `graphql:execute` and `graphql:subscribe` channels.
*
* `result` carries an `ExecutionResult` (or, for subscriptions, an async generator); GraphQL errors
* collected during execution surface on `result.errors` rather than as the channel's `error`
* lifecycle event, which only fires on an abrupt throw.
*/
export interface GraphqlOperationData {
document: GraphqlDocumentNode;
operationName?: string;
operationType?: string;
result?: unknown;
error?: unknown;
}
/**
* Context published on the per-field `graphql:resolve` channel.
*
* A resolver throw or rejection publishes the `error` lifecycle event here; the same failure also
* surfaces in the enclosing execution result.
*/
export interface GraphqlResolveData {
fieldName: string;
parentType: string;
fieldType: string;
fieldPath: string;
/** Whether the field is handled by graphql's default property resolver (vs. a user resolver). */
isDefaultResolver: boolean;
alias?: string;
args?: unknown;
result?: unknown;
error?: unknown;
}
/** Options controlling which graphql channels the subscriber emits spans for. */
export interface GraphqlDiagnosticChannelsOptions {
/**
* Do not create spans for resolvers. Resolver spans are per-field and can be very high volume.
* Defaults to `true`.
*/
ignoreResolveSpans?: boolean;
/**
* When resolver spans are enabled, do not create them for graphql's default property resolver
* (fields without a user-defined resolver), which are rarely interesting. Defaults to `true`.
*/
ignoreTrivialResolveSpans?: boolean;
/**
* Rename the enclosing root span to include the operation name(s), e.g.
* `GET /graphql` -> `GET /graphql (query GetUser)`. Defaults to `true`.
*/
useOperationNameForRootSpan?: boolean;
}
/**
* Platform-provided factory that creates a native tracing channel for the given name. The
* subscriber binds the span and its lifecycle onto the channel via `bindTracingChannelToSpan`,
* which propagates the active span through the runtime's async context.
*
* Node passes `node:diagnostics_channel`'s `tracingChannel` directly.
*/
export type GraphqlTracingChannelFactory = <T extends object>(name: string) => TracingChannel<T, T>;
/**
* Subscribe Sentry span handlers to graphql's diagnostics-channel events
* (`graphql:parse`, `:validate`, `:execute`, `:subscribe`), published by graphql >= 17.0.0.
*
* On older graphql versions the channels are never published to, so the subscribers are inert —
* there is no double-instrumentation against the vendored OTel patcher, which is gated to `< 17`.
*
* The per-field `graphql:resolve` channel is only subscribed when `ignoreResolveSpans` is `false`:
* resolver spans are per-field and can be extremely high-volume, so they are off by default (matching
* the legacy OTel path). When enabled, `ignoreTrivialResolveSpans` (default `true`) additionally skips
* graphql's default property resolver.
*/
export declare function subscribeGraphqlDiagnosticChannels(tracingChannel: GraphqlTracingChannelFactory, options?: GraphqlDiagnosticChannelsOptions): void;
//# sourceMappingURL=graphql-dc-subscriber.d.ts.map

View File

@ -0,0 +1,209 @@
// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license)
// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license)
/// <reference types="node" />
import { Blob } from 'buffer'
import { URL, URLSearchParams } from 'url'
import { ReadableStream } from 'stream/web'
import { FormData } from './formdata'
import Dispatcher from './dispatcher'
export type RequestInfo = string | URL | Request
export declare function fetch (
input: RequestInfo,
init?: RequestInit
): Promise<Response>
export type BodyInit =
| ArrayBuffer
| AsyncIterable<Uint8Array>
| Blob
| FormData
| Iterable<Uint8Array>
| NodeJS.ArrayBufferView
| URLSearchParams
| null
| string
export class BodyMixin {
readonly body: ReadableStream | null
readonly bodyUsed: boolean
readonly arrayBuffer: () => Promise<ArrayBuffer>
readonly blob: () => Promise<Blob>
/**
* @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments.
* It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows:
*
* @example
* ```js
* import { Busboy } from '@fastify/busboy'
* import { Readable } from 'node:stream'
*
* const response = await fetch('...')
* const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } })
*
* // handle events emitted from `busboy`
*
* Readable.fromWeb(response.body).pipe(busboy)
* ```
*/
readonly formData: () => Promise<FormData>
readonly json: () => Promise<unknown>
readonly text: () => Promise<string>
}
export interface SpecIterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
}
export interface SpecIterableIterator<T> extends SpecIterator<T> {
[Symbol.iterator](): SpecIterableIterator<T>;
}
export interface SpecIterable<T> {
[Symbol.iterator](): SpecIterator<T>;
}
export type HeadersInit = string[][] | Record<string, string | ReadonlyArray<string>> | Headers
export declare class Headers implements SpecIterable<[string, string]> {
constructor (init?: HeadersInit)
readonly append: (name: string, value: string) => void
readonly delete: (name: string) => void
readonly get: (name: string) => string | null
readonly has: (name: string) => boolean
readonly set: (name: string, value: string) => void
readonly getSetCookie: () => string[]
readonly forEach: (
callbackfn: (value: string, key: string, iterable: Headers) => void,
thisArg?: unknown
) => void
readonly keys: () => SpecIterableIterator<string>
readonly values: () => SpecIterableIterator<string>
readonly entries: () => SpecIterableIterator<[string, string]>
readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]>
}
export type RequestCache =
| 'default'
| 'force-cache'
| 'no-cache'
| 'no-store'
| 'only-if-cached'
| 'reload'
export type RequestCredentials = 'omit' | 'include' | 'same-origin'
type RequestDestination =
| ''
| 'audio'
| 'audioworklet'
| 'document'
| 'embed'
| 'font'
| 'image'
| 'manifest'
| 'object'
| 'paintworklet'
| 'report'
| 'script'
| 'sharedworker'
| 'style'
| 'track'
| 'video'
| 'worker'
| 'xslt'
export interface RequestInit {
method?: string
keepalive?: boolean
headers?: HeadersInit
body?: BodyInit | null
redirect?: RequestRedirect
integrity?: string
signal?: AbortSignal | null
credentials?: RequestCredentials
mode?: RequestMode
referrer?: string
referrerPolicy?: ReferrerPolicy
window?: null
dispatcher?: Dispatcher
duplex?: RequestDuplex
}
export type ReferrerPolicy =
| ''
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url';
export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'
export type RequestRedirect = 'error' | 'follow' | 'manual'
export type RequestDuplex = 'half'
export declare class Request extends BodyMixin {
constructor (input: RequestInfo, init?: RequestInit)
readonly cache: RequestCache
readonly credentials: RequestCredentials
readonly destination: RequestDestination
readonly headers: Headers
readonly integrity: string
readonly method: string
readonly mode: RequestMode
readonly redirect: RequestRedirect
readonly referrer: string
readonly referrerPolicy: ReferrerPolicy
readonly url: string
readonly keepalive: boolean
readonly signal: AbortSignal
readonly duplex: RequestDuplex
readonly clone: () => Request
}
export interface ResponseInit {
readonly status?: number
readonly statusText?: string
readonly headers?: HeadersInit
}
export type ResponseType =
| 'basic'
| 'cors'
| 'default'
| 'error'
| 'opaque'
| 'opaqueredirect'
export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308
export declare class Response extends BodyMixin {
constructor (body?: BodyInit, init?: ResponseInit)
readonly headers: Headers
readonly ok: boolean
readonly status: number
readonly statusText: string
readonly type: ResponseType
readonly url: string
readonly redirected: boolean
readonly clone: () => Response
static error (): Response
static json(data: any, init?: ResponseInit): Response
static redirect (url: string | URL, status: ResponseRedirectStatus): Response
}

View File

@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../../src/integrations/tracing/fastify/v3/utils.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,IAAI,EAAkB,KAAK,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE7F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D;;;;;;GAMG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,kBAAkB,EACzB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,cAAc,GAAE,UAAe,QAchC;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,kBAAkB,EAAE,GAAG,CAAC,EAAE,GAAG,QAkB3D;AAKD;;;;;;;;GAQG;AACH,wBAAgB,kCAAkC,CAAC,CAAC,EAClD,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACzB,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,KAAK,IAAI,EAC1C,oBAAoB,CAAC,EAAE,OAAO,GAC7B,OAAO,CAAC,CAAC,CAAC,CAAC;AACd,wBAAgB,kCAAkC,CAAC,CAAC,EAClD,OAAO,EAAE,MAAM,CAAC,EAChB,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,CAAC,KAAK,IAAI,EAC1C,oBAAoB,CAAC,EAAE,OAAO,GAC7B,CAAC,CAAC"}

View File

@ -0,0 +1,22 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0;
const api_1 = require("@opentelemetry/api");
const SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key SUPPRESS_TRACING');
function suppressTracing(context) {
return context.setValue(SUPPRESS_TRACING_KEY, true);
}
exports.suppressTracing = suppressTracing;
function unsuppressTracing(context) {
return context.deleteValue(SUPPRESS_TRACING_KEY);
}
exports.unsuppressTracing = unsuppressTracing;
function isTracingSuppressed(context) {
return context.getValue(SUPPRESS_TRACING_KEY) === true;
}
exports.isTracingSuppressed = isTracingSuppressed;
//# sourceMappingURL=suppress-tracing.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../../src/trace/attributes.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes, AttributeValue } from '../common/Attributes';\n\n/**\n * @deprecated please use {@link Attributes}\n * @since 1.0.0\n */\nexport type SpanAttributes = Attributes;\n\n/**\n * @deprecated please use {@link AttributeValue}\n * @since 1.0.0\n */\nexport type SpanAttributeValue = AttributeValue;\n"]}

View File

@ -0,0 +1 @@
{"version":3,"file":"internal-types.js","sources":["../../../../../../src/integrations/tracing/hapi/vendored/internal-types.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-hapi\n * - Upstream version: @opentelemetry/instrumentation-hapi@0.64.0\n * - Types vendored from @hapi/hapi as simplified interfaces\n */\n/* eslint-disable */\n\nimport type * as Hapi from './hapi-types';\n\nexport const HapiComponentName = '@hapi/hapi';\n\n/**\n * This symbol is used to mark a Hapi route handler or server extension handler as\n * already patched, since its possible to use these handlers multiple times\n * i.e. when allowing multiple versions of one plugin, or when registering a plugin\n * multiple times on different servers.\n */\nexport const handlerPatched: unique symbol = Symbol('hapi-handler-patched');\n\nexport type HapiServerRouteInputMethod = (route: HapiServerRouteInput) => void;\n\nexport type HapiServerRouteInput = PatchableServerRoute | PatchableServerRoute[];\n\nexport type PatchableServerRoute = Hapi.ServerRoute<any> & {\n [handlerPatched]?: boolean;\n};\n\nexport type HapiPluginObject<T> = Hapi.ServerRegisterPluginObject<T>;\n\nexport type HapiPluginInput<T> = HapiPluginObject<T> | Array<HapiPluginObject<T>>;\n\nexport type RegisterFunction<T> = (plugin: HapiPluginInput<T>, options?: Hapi.ServerRegisterOptions) => Promise<void>;\n\nexport type PatchableExtMethod = Hapi.Lifecycle.Method & {\n [handlerPatched]?: boolean;\n};\n\nexport type ServerExtDirectInput = [\n Hapi.ServerRequestExtType,\n Hapi.Lifecycle.Method,\n (Hapi.ServerExtOptions | undefined)?,\n];\n\nexport const HapiLayerType = {\n ROUTER: 'router',\n PLUGIN: 'plugin',\n EXT: 'server.ext',\n};\n\nexport const HapiLifecycleMethodNames = new Set([\n 'onPreAuth',\n 'onCredentials',\n 'onPostAuth',\n 'onPreHandler',\n 'onPostHandler',\n 'onPreResponse',\n 'onRequest',\n]);\n"],"names":[],"mappings":";;AAaO,MAAM,iBAAA,GAAoB;AAQ1B,MAAM,cAAA,0BAAuC,sBAAsB;AA0BnE,MAAM,aAAA,GAAgB;AAAA,EAC3B,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,GAAA,EAAK;AACP;AAEO,MAAM,wBAAA,uBAA+B,GAAA,CAAI;AAAA,EAC9C,WAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA;AACF,CAAC;;;;;;;"}

Some files were not shown because too many files have changed in this diff Show More