@sentry/server-utils 11.19.0 → 11.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/build/cjs/chunks/config.js +28 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +6 -0
  4. package/build/cjs/index.js +424 -73
  5. package/build/cjs/index.js.map +1 -1
  6. package/build/esm/ai/tanstack-ai/constants.js +11 -0
  7. package/build/esm/ai/tanstack-ai/constants.js.map +1 -0
  8. package/build/esm/ai/tanstack-ai/index.js +206 -0
  9. package/build/esm/ai/tanstack-ai/index.js.map +1 -0
  10. package/build/esm/ai/tanstack-ai/utils.js +81 -0
  11. package/build/esm/ai/tanstack-ai/utils.js.map +1 -0
  12. package/build/esm/ai/vercel-ai/index.js +1 -12
  13. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  14. package/build/esm/index.js +2 -1
  15. package/build/esm/index.js.map +1 -1
  16. package/build/esm/integrations/nitro/captureTracingEvents.js +4 -3
  17. package/build/esm/integrations/nitro/captureTracingEvents.js.map +1 -1
  18. package/build/esm/integrations/nitro/index.js +2 -2
  19. package/build/esm/integrations/nitro/index.js.map +1 -1
  20. package/build/esm/integrations/openai-compatible.js.map +1 -1
  21. package/build/esm/integrations/tanstack-ai.js +59 -0
  22. package/build/esm/integrations/tanstack-ai.js.map +1 -0
  23. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +70 -42
  24. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  25. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +21 -16
  26. package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
  27. package/build/esm/orchestrion/channels.js +2 -0
  28. package/build/esm/orchestrion/channels.js.map +1 -1
  29. package/build/esm/orchestrion/config/index.js +2 -0
  30. package/build/esm/orchestrion/config/index.js.map +1 -1
  31. package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
  32. package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
  33. package/build/esm/package.json +1 -1
  34. package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
  35. package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
  36. package/build/types/ai/tanstack-ai/index.d.ts +18 -0
  37. package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
  38. package/build/types/ai/tanstack-ai/types.d.ts +127 -0
  39. package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
  40. package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
  41. package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
  42. package/build/types/ai/vercel-ai/index.d.ts +0 -6
  43. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  44. package/build/types/index.d.ts +2 -0
  45. package/build/types/index.d.ts.map +1 -1
  46. package/build/types/integrations/nitro/captureTracingEvents.d.ts +3 -1
  47. package/build/types/integrations/nitro/captureTracingEvents.d.ts.map +1 -1
  48. package/build/types/integrations/nitro/index.d.ts +6 -0
  49. package/build/types/integrations/nitro/index.d.ts.map +1 -1
  50. package/build/types/integrations/openai-compatible.d.ts.map +1 -1
  51. package/build/types/integrations/tanstack-ai.d.ts +18 -0
  52. package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
  53. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  54. package/build/types/orchestrion/channels.d.ts +1 -0
  55. package/build/types/orchestrion/channels.d.ts.map +1 -1
  56. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  57. package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
  58. package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
  59. package/package.json +3 -3
@@ -0,0 +1,11 @@
1
+ // src/ai/tanstack-ai/constants.ts
2
+ const TANSTACK_AI_INTEGRATION_NAME = "TanStackAI";
3
+ const TANSTACK_AI_ORIGIN = "auto.ai.tanstack_ai";
4
+ /**
5
+ * Marks our middleware, so a `chat()` call that already has it does not get a second one.
6
+ * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.
7
+ */
8
+ const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for("sentry.tanstack-ai.middleware");
9
+ export { TANSTACK_AI_INTEGRATION_NAME, TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN };
10
+
11
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../../../../src/ai/tanstack-ai/constants.ts"],"sourcesContent":["export const TANSTACK_AI_INTEGRATION_NAME = 'TanStackAI' as const;\n\nexport const TANSTACK_AI_ORIGIN = 'auto.ai.tanstack_ai';\n\n/**\n * Marks our middleware, so a `chat()` call that already has it does not get a second one.\n * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.\n */\nexport const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for('sentry.tanstack-ai.middleware');\n"],"mappings":";AAAA,MAAa,+BAA+B;AAE5C,MAAa,qBAAqB;;;;;AAMlC,MAAa,+BAA+B,OAAO,IAAI,+BAA+B"}
@@ -0,0 +1,206 @@
1
+ import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from "../core/gen-ai-attributes.js";
2
+ import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
3
+ import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
4
+ import { getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, setOutputMessagesAttribute } from "../core/utils.js";
5
+ import { TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN } from "./constants.js";
6
+ import { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes } from "./utils.js";
7
+ import { GEN_AI_AGENT_NAME, GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
8
+ import { SPAN_STATUS_ERROR, captureException, getActiveSpan, startInactiveSpan, stringify, withActiveSpan } from "@sentry/core";
9
+ // src/ai/tanstack-ai/index.ts
10
+ const OUTPUT_CHUNK_TYPES = /* @__PURE__ */ new Set([
11
+ "TEXT_MESSAGE_CONTENT",
12
+ "TOOL_CALL_START",
13
+ "REASONING_MESSAGE_CONTENT"
14
+ ]);
15
+ /**
16
+ * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the
17
+ * `invoke_agent` span is the span that is active then, and the recording options are decided then.
18
+ * The middleware cannot make its spans active, so the spans of other work in the run do not nest
19
+ * below them.
20
+ */
21
+ function createTanstackAIMiddleware(options, call) {
22
+ const parentSpan = getActiveSpan() ?? null;
23
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
24
+ const streaming = call.outputSchema ? call.stream === true : call.stream !== false;
25
+ let agentSpan;
26
+ let chatSpan;
27
+ let outputText = "";
28
+ let outputToolCalls = [];
29
+ const toolCallNames = /* @__PURE__ */ new Map();
30
+ const toolSpans = /* @__PURE__ */ new Map();
31
+ const startSpan = (spanOptions) => {
32
+ const span = startInactiveSpan(spanOptions);
33
+ runGenAiSpanStart(options, span, call);
34
+ return span;
35
+ };
36
+ const endSpan = (span, status, error) => {
37
+ if (status) span.setStatus(status);
38
+ runGenAiSpanEnd(options, span, call, status ? { error } : {});
39
+ span.end();
40
+ };
41
+ const endChatSpan = (status, error) => {
42
+ if (chatSpan) {
43
+ endSpan(chatSpan, status, error);
44
+ chatSpan = void 0;
45
+ }
46
+ };
47
+ const endRun = (status, error) => {
48
+ if (!agentSpan) return;
49
+ for (const span of toolSpans.values()) endSpan(span, status, error);
50
+ toolSpans.clear();
51
+ endChatSpan(status, error);
52
+ endSpan(agentSpan, status, error);
53
+ agentSpan = void 0;
54
+ };
55
+ const startChatSpan = (ctx, config) => {
56
+ outputText = "";
57
+ outputToolCalls = [];
58
+ toolCallNames.clear();
59
+ return startSpan({
60
+ name: `chat ${ctx.model}`,
61
+ op: getGenAiSpanOp("chat"),
62
+ parentSpan: agentSpan,
63
+ attributes: {
64
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
65
+ [GEN_AI_OPERATION_NAME]: "chat",
66
+ [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
67
+ [GEN_AI_REQUEST_MODEL]: ctx.model,
68
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
69
+ [GEN_AI_RESPONSE_STREAMING]: streaming,
70
+ ...getRequestAttributes(config.modelOptions),
71
+ ...recordInputs && config.tools.length && ctx.phase !== "structuredOutput" ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(config.tools.map(({ name, description, inputSchema }) => ({
72
+ name,
73
+ description,
74
+ inputSchema
75
+ }))) } : {},
76
+ ...recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}
77
+ }
78
+ });
79
+ };
80
+ return {
81
+ name: "sentry",
82
+ [TANSTACK_AI_MIDDLEWARE_BRAND]: true,
83
+ onConfig(ctx, config) {
84
+ if (ctx.phase === "init" && !agentSpan) {
85
+ const agentName = ctx.subagentName;
86
+ agentSpan = startSpan({
87
+ name: agentName ? `invoke_agent ${agentName}` : "invoke_agent",
88
+ op: getGenAiSpanOp("invoke_agent"),
89
+ parentSpan,
90
+ attributes: {
91
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
92
+ [GEN_AI_OPERATION_NAME]: "invoke_agent",
93
+ [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
94
+ [GEN_AI_REQUEST_MODEL]: ctx.model,
95
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
96
+ [GEN_AI_RESPONSE_STREAMING]: streaming,
97
+ [GEN_AI_AGENT_NAME]: agentName,
98
+ ...recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}
99
+ }
100
+ });
101
+ }
102
+ if (!agentSpan || ctx.phase !== "beforeModel" && ctx.phase !== "structuredOutput") return;
103
+ endChatSpan({
104
+ code: SPAN_STATUS_ERROR,
105
+ message: "internal_error"
106
+ });
107
+ chatSpan = startChatSpan(ctx, config);
108
+ },
109
+ onChunk(ctx, chunk) {
110
+ if (!agentSpan) return;
111
+ if (chunk.type === "RUN_FINISHED" || chunk.type === "RUN_ERROR") {
112
+ const provider = getProviderName(ctx);
113
+ chatSpan?.setAttribute(GEN_AI_PROVIDER_NAME, provider);
114
+ agentSpan.setAttribute(GEN_AI_PROVIDER_NAME, provider);
115
+ }
116
+ if (chunk.type === "RUN_ERROR") {
117
+ endRun(getErrorStatus(ctx.signal), getRunError(chunk));
118
+ return;
119
+ }
120
+ if (chunk.type === "RUN_FINISHED" && chunk.outcome?.type === "interrupt") {
121
+ endRun();
122
+ return;
123
+ }
124
+ if (!chatSpan) return;
125
+ if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) recordTimeToFirstChunk(chatSpan);
126
+ if (chunk.type === "TEXT_MESSAGE_CONTENT" && recordOutputs && chunk.delta) outputText += chunk.delta;
127
+ else if (chunk.type === "TOOL_CALL_START" && chunk.toolCallId && chunk.toolCallName) toolCallNames.set(chunk.toolCallId, chunk.toolCallName);
128
+ else if (chunk.type === "TOOL_CALL_END" && recordOutputs && chunk.toolCallId) outputToolCalls.push({
129
+ id: chunk.toolCallId,
130
+ name: toolCallNames.get(chunk.toolCallId),
131
+ arguments: chunk.input ?? {}
132
+ });
133
+ else if (chunk.type === "RUN_FINISHED") {
134
+ const responseModel = chunk.model ?? ctx.callMetadata?.model;
135
+ const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;
136
+ const finishReason = chunk.finishReason ?? void 0;
137
+ if (finishReason) chatSpan.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));
138
+ for (const span of [chatSpan, agentSpan]) {
139
+ if (responseModel) span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
140
+ if (responseId) span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
141
+ if (recordOutputs) setOutputMessagesAttribute(span, {
142
+ responseText: outputText,
143
+ toolCalls: outputToolCalls,
144
+ finishReason
145
+ });
146
+ }
147
+ }
148
+ },
149
+ onInterruptBoundary(ctx) {
150
+ if (ctx.phase === "afterModel") endChatSpan();
151
+ },
152
+ onUsage(_ctx, usage) {
153
+ chatSpan?.setAttributes(getUsageAttributes(usage));
154
+ },
155
+ onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {
156
+ if (!agentSpan || tool && typeof tool.execute !== "function") return;
157
+ toolSpans.set(toolCallId, startSpan({
158
+ name: `execute_tool ${toolName}`,
159
+ op: getGenAiSpanOp("execute_tool"),
160
+ parentSpan: agentSpan,
161
+ attributes: {
162
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
163
+ [GEN_AI_OPERATION_NAME]: "execute_tool",
164
+ [GEN_AI_TOOL_NAME]: toolName,
165
+ [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,
166
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
167
+ [GEN_AI_TOOL_DESCRIPTION]: tool?.description,
168
+ ...recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}
169
+ }
170
+ }));
171
+ },
172
+ onAfterToolCall(ctx, { toolCallId, ok, result, error }) {
173
+ const span = toolSpans.get(toolCallId);
174
+ if (!span) return;
175
+ toolSpans.delete(toolCallId);
176
+ if (recordOutputs && ok && result !== void 0) span.setAttribute(GEN_AI_TOOL_CALL_RESULT, typeof result === "string" ? result : stringify(result));
177
+ if (ok) {
178
+ endSpan(span);
179
+ return;
180
+ }
181
+ const status = getErrorStatus(ctx.signal);
182
+ if (status.message === "internal_error") withActiveSpan(span, () => {
183
+ captureException(error, { mechanism: {
184
+ type: TANSTACK_AI_ORIGIN,
185
+ handled: false
186
+ } });
187
+ });
188
+ endSpan(span, status, error);
189
+ },
190
+ onFinish() {
191
+ endRun();
192
+ },
193
+ onAbort() {
194
+ endRun({
195
+ code: SPAN_STATUS_ERROR,
196
+ message: "cancelled"
197
+ });
198
+ },
199
+ onError(ctx, { error }) {
200
+ endRun(getErrorStatus(ctx.signal), error);
201
+ }
202
+ };
203
+ }
204
+ export { createTanstackAIMiddleware };
205
+
206
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/tanstack-ai/index.ts"],"sourcesContent":["import type { Span, SpanStatus } from '@sentry/core';\nimport {\n captureException,\n getActiveSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringify,\n withActiveSpan,\n} from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_STREAMING,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport { recordTimeToFirstChunk } from '../core/time-to-first-chunk';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, setOutputMessagesAttribute } from '../core/utils';\nimport { TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN } from './constants';\nimport type {\n TanstackAICallInfo,\n TanstackAIChatMiddleware,\n TanstackAIMiddlewareConfig,\n TanstackAIMiddlewareContext,\n} from './types';\nimport { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes } from './utils';\n\n/**\n * `call` is the options object of the `chat()` call. The recording options run when `chat()` is\n * called. The hooks run for every span (`invoke_agent`, `chat` and `execute_tool`) while the run is\n * read, which can be in another async context than the call. `onSpanEnd` gets the `error` of a\n * failed run or tool.\n */\nexport type TanstackAIOptions = GenAiCallOptions<TanstackAICallInfo> & GenAiSpanHooks<TanstackAICallInfo>;\n\n// The chunks that carry model output. The adapters send `RUN_STARTED` before the provider answers.\nconst OUTPUT_CHUNK_TYPES = new Set(['TEXT_MESSAGE_CONTENT', 'TOOL_CALL_START', 'REASONING_MESSAGE_CONTENT']);\n\n/**\n * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the\n * `invoke_agent` span is the span that is active then, and the recording options are decided then.\n * The middleware cannot make its spans active, so the spans of other work in the run do not nest\n * below them.\n */\nexport function createTanstackAIMiddleware(\n options: TanstackAIOptions,\n call: TanstackAICallInfo,\n): TanstackAIChatMiddleware {\n const parentSpan = getActiveSpan() ?? null;\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n // `ctx.streaming` is also true when `chat()` returns a promise, because `chat()` reads the same stream\n // inside. With `outputSchema`, `chat()` streams only with `stream: true`.\n const streaming = call.outputSchema ? call.stream === true : call.stream !== false;\n\n let agentSpan: Span | undefined;\n let chatSpan: Span | undefined;\n let outputText = '';\n let outputToolCalls: Array<{ id: string; name?: string; arguments: unknown }> = [];\n // `TOOL_CALL_END` has the arguments but not the name, which only `TOOL_CALL_START` has.\n const toolCallNames = new Map<string, string>();\n const toolSpans = new Map<string, Span>();\n\n const startSpan = (spanOptions: Parameters<typeof startInactiveSpan>[0]): Span => {\n const span = startInactiveSpan(spanOptions);\n runGenAiSpanStart(options, span, call);\n return span;\n };\n\n const endSpan = (span: Span, status?: SpanStatus, error?: unknown): void => {\n if (status) {\n span.setStatus(status);\n }\n runGenAiSpanEnd(options, span, call, status ? { error } : {});\n span.end();\n };\n\n const endChatSpan = (status?: SpanStatus, error?: unknown): void => {\n if (chatSpan) {\n endSpan(chatSpan, status, error);\n chatSpan = undefined;\n }\n };\n\n const endRun = (status?: SpanStatus, error?: unknown): void => {\n if (!agentSpan) {\n return;\n }\n for (const span of toolSpans.values()) {\n endSpan(span, status, error);\n }\n toolSpans.clear();\n endChatSpan(status, error);\n endSpan(agentSpan, status, error);\n agentSpan = undefined;\n };\n\n const startChatSpan = (ctx: TanstackAIMiddlewareContext, config: TanstackAIMiddlewareConfig): Span => {\n outputText = '';\n outputToolCalls = [];\n toolCallNames.clear();\n\n return startSpan({\n name: `chat ${ctx.model}`,\n op: getGenAiSpanOp('chat'),\n parentSpan: agentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'chat',\n [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),\n [GEN_AI_REQUEST_MODEL]: ctx.model,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_RESPONSE_STREAMING]: streaming,\n ...getRequestAttributes(config.modelOptions),\n // The `structuredOutput` call sends no tools, but its config still lists them.\n ...(recordInputs && config.tools.length && ctx.phase !== 'structuredOutput'\n ? {\n [GEN_AI_TOOL_DEFINITIONS]: stringify(\n config.tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),\n ),\n }\n : {}),\n // A middleware can send the provider other messages than the history of the run.\n ...(recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}),\n },\n });\n };\n\n return {\n name: 'sentry',\n [TANSTACK_AI_MIDDLEWARE_BRAND]: true,\n\n onConfig(ctx, config) {\n // `init` runs once per run, before `onStart` and before any tool can run.\n if (ctx.phase === 'init' && !agentSpan) {\n const agentName = ctx.subagentName;\n agentSpan = startSpan({\n name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent',\n op: getGenAiSpanOp('invoke_agent'),\n parentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),\n [GEN_AI_REQUEST_MODEL]: ctx.model,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_RESPONSE_STREAMING]: streaming,\n [GEN_AI_AGENT_NAME]: agentName,\n ...(recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}),\n },\n });\n }\n\n // `beforeModel` starts each model call of the agent loop. `structuredOutput` starts the\n // separate last call for `outputSchema`.\n if (!agentSpan || (ctx.phase !== 'beforeModel' && ctx.phase !== 'structuredOutput')) {\n return;\n }\n // A model call that completes ends its span at the `afterModel` boundary. A span that is still\n // open here is of a call that failed and that a middleware retried with `ctx.retry()`.\n endChatSpan({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n chatSpan = startChatSpan(ctx, config);\n },\n\n onChunk(ctx, chunk) {\n if (!agentSpan) {\n return;\n }\n if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {\n // TanStack sets the call metadata of the `structuredOutput` call only after `onConfig`.\n const provider = getProviderName(ctx);\n chatSpan?.setAttribute(GEN_AI_PROVIDER_NAME, provider);\n agentSpan.setAttribute(GEN_AI_PROVIDER_NAME, provider);\n }\n // A provider error ends the run with this chunk. `chat({ stream: false })` then throws and\n // stops reading, so TanStack calls no terminal hook.\n if (chunk.type === 'RUN_ERROR') {\n endRun(getErrorStatus(ctx.signal), getRunError(chunk));\n return;\n }\n // A run that stops at an interrupt ends with this chunk. For an interrupt at `beforeModel` or\n // `afterModel`, TanStack calls no terminal hook.\n if (chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt') {\n endRun();\n return;\n }\n if (!chatSpan) {\n return;\n }\n\n if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) {\n recordTimeToFirstChunk(chatSpan);\n }\n\n if (chunk.type === 'TEXT_MESSAGE_CONTENT' && recordOutputs && chunk.delta) {\n outputText += chunk.delta;\n } else if (chunk.type === 'TOOL_CALL_START' && chunk.toolCallId && chunk.toolCallName) {\n toolCallNames.set(chunk.toolCallId, chunk.toolCallName);\n } else if (chunk.type === 'TOOL_CALL_END' && recordOutputs && chunk.toolCallId) {\n outputToolCalls.push({\n id: chunk.toolCallId,\n name: toolCallNames.get(chunk.toolCallId),\n arguments: chunk.input ?? {},\n });\n } else if (chunk.type === 'RUN_FINISHED') {\n // An adapter can report these only in the `metadata.tanstack` of the chunk. TanStack copies\n // them into `callMetadata` before the middleware gets the chunk.\n const responseModel = chunk.model ?? ctx.callMetadata?.model;\n const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;\n const finishReason = chunk.finishReason ?? undefined;\n if (finishReason) {\n chatSpan.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));\n }\n // The agent span keeps the response of the last model call, which is the answer of the run.\n for (const span of [chatSpan, agentSpan]) {\n if (responseModel) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);\n }\n if (responseId) {\n span.setAttribute(GEN_AI_RESPONSE_ID, responseId);\n }\n if (recordOutputs) {\n setOutputMessagesAttribute(span, { responseText: outputText, toolCalls: outputToolCalls, finishReason });\n }\n }\n }\n },\n\n // Runs after each model call and before the tools it asked for, so the `chat` span does not\n // include the tools.\n onInterruptBoundary(ctx) {\n if (ctx.phase === 'afterModel') {\n endChatSpan();\n }\n },\n\n onUsage(_ctx, usage) {\n chatSpan?.setAttributes(getUsageAttributes(usage));\n },\n\n // The guards run after all `onBeforeToolCall` decisions and after the input check, so `args`\n // are the arguments that the tool gets.\n onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {\n // A client tool runs in the browser, not here.\n if (!agentSpan || (tool && typeof tool.execute !== 'function')) {\n return;\n }\n toolSpans.set(\n toolCallId,\n startSpan({\n name: `execute_tool ${toolName}`,\n op: getGenAiSpanOp('execute_tool'),\n parentSpan: agentSpan,\n attributes: {\n [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,\n [GEN_AI_CONVERSATION_ID]: ctx.threadId,\n [GEN_AI_TOOL_DESCRIPTION]: tool?.description,\n ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n }),\n );\n },\n\n onAfterToolCall(ctx, { toolCallId, ok, result, error }) {\n const span = toolSpans.get(toolCallId);\n if (!span) {\n return;\n }\n toolSpans.delete(toolCallId);\n\n if (recordOutputs && ok && result !== undefined) {\n span.setAttribute(GEN_AI_TOOL_CALL_RESULT, typeof result === 'string' ? result : stringify(result));\n }\n if (ok) {\n endSpan(span);\n return;\n }\n // TanStack fails each tool that did not start yet with an `Operation aborted` error.\n const status = getErrorStatus(ctx.signal);\n if (status.message === 'internal_error') {\n // TanStack gives a tool failure back to the model as the tool result, so the error handlers\n // of the app never see it.\n withActiveSpan(span, () => {\n captureException(error, { mechanism: { type: TANSTACK_AI_ORIGIN, handled: false } });\n });\n }\n endSpan(span, status, error);\n },\n\n onFinish() {\n endRun();\n },\n\n // Also for an abort from a middleware, which leaves the signal of the caller alone.\n onAbort() {\n endRun({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n },\n\n onError(ctx, { error }) {\n endRun(getErrorStatus(ctx.signal), error);\n },\n };\n}\n"],"mappings":";;;;;;;;;AAkDA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAwB;CAAmB;AAA2B,CAAC;;;;;;;AAQ3G,SAAgB,2BACd,SACA,MAC0B;CAC1B,MAAM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mB;MACnB,gCAAgC;MAChC,yBAAyB,IAAI;MAC7B,0BAA0B,MAAM;KACjC,GAAI,eAAe,GAAG,6BAA6B,UAAU,IAAI,EAAE,IAAI,CAAC;IAC1E;GACF,CAAC,CACH;EACF;EAEA,gBAAgB,KAAK,EAAE,YAAY,IAAI,QAAQ,SAAS;GACtD,MAAM,OAAO,UAAU,IAAI,UAAU;GACrC,IAAI,CAAC,MACH;GAEF,UAAU,OAAO,UAAU;GAE3B,IAAI,iBAAiB,MAAM,WAAW,KAAA,GACpC,KAAK,aAAa,yBAAyB,OAAO,WAAW,WAAW,SAAS,UAAU,MAAM,CAAC;GAEpG,IAAI,IAAI;IACN,QAAQ,IAAI;IACZ;GACF;GAEA,MAAM,SAAS,eAAe,IAAI,MAAM;GACxC,IAAI,OAAO,YAAY,kBAGrB,eAAe,YAAY;IACzB,iBAAiB,OAAO,EAAE,WAAW;KAAE,MAAM;KAAoB,SAAS;IAAM,EAAE,CAAC;GACrF,CAAC;GAEH,QAAQ,MAAM,QAAQ,KAAK;EAC7B;EAEA,WAAW;GACT,OAAO;EACT;EAGA,UAAU;GACR,OAAO;IAAE,MAAM;IAAmB,SAAS;GAAY,CAAC;EAC1D;EAEA,QAAQ,KAAK,EAAE,SAAS;GACtB,OAAO,eAAe,IAAI,MAAM,GAAG,KAAK;EAC1C;CACF;AACF"}
@@ -0,0 +1,81 @@
1
+ import { getTokenUsageAttributes } from "../core/utils.js";
2
+ import { GEN_AI_INPUT_MESSAGES, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS } from "@sentry/conventions/attributes";
3
+ import { stringify } from "@sentry/core";
4
+ // src/ai/tanstack-ai/utils.ts
5
+ /**
6
+ * `ctx.provider` is the adapter name, which for some adapters also names the API (for example
7
+ * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the
8
+ * first model call started.
9
+ */
10
+ function getProviderName(ctx) {
11
+ return ctx.callMetadata?.source?.provider ?? ctx.provider;
12
+ }
13
+ function getInputAttributes(messages, systemPrompts) {
14
+ return {
15
+ [GEN_AI_INPUT_MESSAGES]: stringify(messages.map(toGenAiMessage)),
16
+ [GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length ? stringify(systemPrompts.map((prompt) => ({
17
+ type: "text",
18
+ content: typeof prompt === "string" ? prompt : prompt.content
19
+ }))) : void 0
20
+ };
21
+ }
22
+ /**
23
+ * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in
24
+ * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,
25
+ * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.
26
+ */
27
+ function getRequestAttributes(modelOptions = {}) {
28
+ const pick = (...keys) => {
29
+ for (const key of keys) {
30
+ const value = modelOptions[key];
31
+ if (typeof value === "number") return value;
32
+ }
33
+ };
34
+ return {
35
+ [GEN_AI_REQUEST_TEMPERATURE]: pick("temperature"),
36
+ [GEN_AI_REQUEST_TOP_P]: pick("top_p", "topP"),
37
+ [GEN_AI_REQUEST_MAX_TOKENS]: pick("max_tokens", "maxTokens", "max_output_tokens", "maxOutputTokens")
38
+ };
39
+ }
40
+ function getUsageAttributes(usage) {
41
+ const attributes = getTokenUsageAttributes(usage.promptTokens, usage.completionTokens, usage.promptTokensDetails?.cacheWriteTokens, usage.promptTokensDetails?.cachedTokens, usage.totalTokens);
42
+ if (typeof usage.completionTokensDetails?.reasoningTokens === "number") attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;
43
+ return attributes;
44
+ }
45
+ function toGenAiMessage(message) {
46
+ const parts = [];
47
+ const { content } = message;
48
+ if (message.role === "tool") parts.push({
49
+ type: "tool_call_response",
50
+ id: message.toolCallId,
51
+ result: content
52
+ });
53
+ else if (typeof content === "string") parts.push({
54
+ type: "text",
55
+ content
56
+ });
57
+ else if (Array.isArray(content)) for (const part of content) parts.push(part.type === "text" ? {
58
+ type: "text",
59
+ content: part.content
60
+ } : { type: part.type });
61
+ for (const toolCall of message.toolCalls ?? []) parts.push({
62
+ type: "tool_call",
63
+ id: toolCall.id,
64
+ name: toolCall.function?.name,
65
+ arguments: toolCall.function?.arguments
66
+ });
67
+ return {
68
+ role: message.role,
69
+ parts
70
+ };
71
+ }
72
+ /** The error of a `RUN_ERROR` chunk. */
73
+ function getRunError(chunk) {
74
+ return chunk.error ?? {
75
+ message: chunk.message,
76
+ code: chunk.code
77
+ };
78
+ }
79
+ export { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes };
80
+
81
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/tanstack-ai/utils.ts"],"sourcesContent":["import { stringify } from '@sentry/core';\nimport {\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { getTokenUsageAttributes } from '../core/utils';\nimport type {\n TanstackAIChunk,\n TanstackAIMiddlewareContext,\n TanstackAIModelMessage,\n TanstackAISystemPrompt,\n TanstackAIUsage,\n} from './types';\n\n/**\n * `ctx.provider` is the adapter name, which for some adapters also names the API (for example\n * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the\n * first model call started.\n */\nexport function getProviderName(ctx: TanstackAIMiddlewareContext): string {\n return ctx.callMetadata?.source?.provider ?? ctx.provider;\n}\n\nexport function getInputAttributes(\n messages: ReadonlyArray<TanstackAIModelMessage>,\n systemPrompts: ReadonlyArray<TanstackAISystemPrompt>,\n): Record<string, string | undefined> {\n return {\n [GEN_AI_INPUT_MESSAGES]: stringify(messages.map(toGenAiMessage)),\n [GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length\n ? stringify(\n systemPrompts.map(prompt => ({\n type: 'text',\n content: typeof prompt === 'string' ? prompt : prompt.content,\n })),\n )\n : undefined,\n };\n}\n\n/**\n * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in\n * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,\n * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.\n */\nexport function getRequestAttributes(modelOptions: Record<string, unknown> = {}): Record<string, number | undefined> {\n const pick = (...keys: string[]): number | undefined => {\n for (const key of keys) {\n const value = modelOptions[key];\n if (typeof value === 'number') {\n return value;\n }\n }\n return undefined;\n };\n return {\n [GEN_AI_REQUEST_TEMPERATURE]: pick('temperature'),\n [GEN_AI_REQUEST_TOP_P]: pick('top_p', 'topP'),\n [GEN_AI_REQUEST_MAX_TOKENS]: pick('max_tokens', 'maxTokens', 'max_output_tokens', 'maxOutputTokens'),\n };\n}\n\nexport function getUsageAttributes(usage: TanstackAIUsage): Record<string, number> {\n const attributes = getTokenUsageAttributes(\n usage.promptTokens,\n usage.completionTokens,\n usage.promptTokensDetails?.cacheWriteTokens,\n usage.promptTokensDetails?.cachedTokens,\n usage.totalTokens,\n );\n if (typeof usage.completionTokensDetails?.reasoningTokens === 'number') {\n attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;\n }\n return attributes;\n}\n\nfunction toGenAiMessage(message: TanstackAIModelMessage): Record<string, unknown> {\n const parts: Array<Record<string, unknown>> = [];\n const { content } = message;\n\n if (message.role === 'tool') {\n parts.push({ type: 'tool_call_response', id: message.toolCallId, result: content });\n } else if (typeof content === 'string') {\n parts.push({ type: 'text', content });\n } else if (Array.isArray(content)) {\n for (const part of content) {\n // Media parts carry inline data or provider handles, so keep only their type.\n parts.push(part.type === 'text' ? { type: 'text', content: part.content } : { type: part.type });\n }\n }\n for (const toolCall of message.toolCalls ?? []) {\n parts.push({\n type: 'tool_call',\n id: toolCall.id,\n name: toolCall.function?.name,\n arguments: toolCall.function?.arguments,\n });\n }\n return { role: message.role, parts };\n}\n\n/** The error of a `RUN_ERROR` chunk. */\nexport function getRunError(chunk: TanstackAIChunk): { message?: string; code?: string } {\n return chunk.error ?? { message: chunk.message, code: chunk.code };\n}\n"],"mappings":";;;;;;;;;AAuBA,SAAgB,gBAAgB,KAA0C;CACxE,OAAO,IAAI,cAAc,QAAQ,YAAY,IAAI;AACnD;AAEA,SAAgB,mBACd,UACA,eACoC;CACpC,OAAO;GACJ,wBAAwB,UAAU,SAAS,IAAI,cAAc,CAAC;GAC9D,6BAA6B,cAAc,SACxC,UACE,cAAc,KAAI,YAAW;GAC3B,MAAM;GACN,SAAS,OAAO,WAAW,WAAW,SAAS,OAAO;EACxD,EAAE,CACJ,IACA,KAAA;CACN;AACF;;;;;;AAOA,SAAgB,qBAAqB,eAAwC,CAAC,GAAuC;CACnH,MAAM,QAAQ,GAAG,SAAuC;EACtD,KAAK,MAAM,OAAO,MAAM;GACtB,MAAM,QAAQ,aAAa;GAC3B,IAAI,OAAO,UAAU,UACnB,OAAO;EAEX;CAEF;CACA,OAAO;GACJ,6BAA6B,KAAK,aAAa;GAC/C,uBAAuB,KAAK,SAAS,MAAM;GAC3C,4BAA4B,KAAK,cAAc,aAAa,qBAAqB,iBAAiB;CACrG;AACF;AAEA,SAAgB,mBAAmB,OAAgD;CACjF,MAAM,aAAa,wBACjB,MAAM,cACN,MAAM,kBACN,MAAM,qBAAqB,kBAC3B,MAAM,qBAAqB,cAC3B,MAAM,WACR;CACA,IAAI,OAAO,MAAM,yBAAyB,oBAAoB,UAC5D,WAAW,wCAAwC,MAAM,wBAAwB;CAEnF,OAAO;AACT;AAEA,SAAS,eAAe,SAA0D;CAChF,MAAM,QAAwC,CAAC;CAC/C,MAAM,EAAE,YAAY;CAEpB,IAAI,QAAQ,SAAS,QACnB,MAAM,KAAK;EAAE,MAAM;EAAsB,IAAI,QAAQ;EAAY,QAAQ;CAAQ,CAAC;MAC7E,IAAI,OAAO,YAAY,UAC5B,MAAM,KAAK;EAAE,MAAM;EAAQ;CAAQ,CAAC;MAC/B,IAAI,MAAM,QAAQ,OAAO,GAC9B,KAAK,MAAM,QAAQ,SAEjB,MAAM,KAAK,KAAK,SAAS,SAAS;EAAE,MAAM;EAAQ,SAAS,KAAK;CAAQ,IAAI,EAAE,MAAM,KAAK,KAAK,CAAC;CAGnG,KAAK,MAAM,YAAY,QAAQ,aAAa,CAAC,GAC3C,MAAM,KAAK;EACT,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS,UAAU;EACzB,WAAW,SAAS,UAAU;CAChC,CAAC;CAEH,OAAO;EAAE,MAAM,QAAQ;EAAM;CAAM;AACrC;;AAGA,SAAgB,YAAY,OAA6D;CACvF,OAAO,MAAM,SAAS;EAAE,SAAS,MAAM;EAAS,MAAM,MAAM;CAAK;AACnE"}
@@ -43,22 +43,11 @@ function getProviderMetadataAttributes(providerMetadata) {
43
43
  return attributes;
44
44
  }
45
45
  /**
46
- * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.
47
- * They must not be written onto a span that reports usage aggregated across steps
48
- * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.
49
- */
50
- const LAST_STEP_ONLY_USAGE_KEYS = /* @__PURE__ */ new Set([
51
- GEN_AI_USAGE_OUTPUT_TOKENS,
52
- GEN_AI_USAGE_TOTAL_TOKENS,
53
- GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
54
- GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS
55
- ]);
56
- /**
57
46
  * Sets an attribute only if the value is not null or undefined.
58
47
  */
59
48
  function setAttributeIfDefined(attributes, key, value) {
60
49
  if (value != null) attributes[key] = value;
61
50
  }
62
- export { LAST_STEP_ONLY_USAGE_KEYS, getProviderMetadataAttributes };
51
+ export { getProviderMetadataAttributes };
63
52
 
64
53
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.\n * They must not be written onto a span that reports usage aggregated across steps\n * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.\n */\nexport const LAST_STEP_ONLY_USAGE_KEYS = new Set<string>([\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n]);\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,8BAA8B,kBAA4D;CACxG,MAAM,aAA8C,CAAC;CAErD,IAAI,CAAC,oBAAoB,OAAO,qBAAqB,UACnD,OAAO;CAET,MAAM,WAAW;CAGjB,MAAM,iBAAqD,SAAS,UAAU,SAAS;CACvF,IAAI,gBAAgB;EAClB,sBAAsB,YAAY,sCAAsC,eAAe,kBAAkB;EACzG,sBAAsB,YAAY,sCAAsC,eAAe,eAAe;EACtG,sBACE,YACA,kDACA,eAAe,wBACjB;EACA,sBACE,YACA,kDACA,eAAe,wBACjB;CACF;CAEA,IAAI,SAAS,WAAW;EACtB,MAAM,oBACJ,SAAS,UAAU,OAAO,2BAA2B,SAAS,UAAU;EAC1E,sBAAsB,YAAY,sCAAsC,iBAAiB;EAEzF,MAAM,wBACJ,SAAS,UAAU,OAAO,+BAA+B,SAAS,UAAU;EAC9E,sBAAsB,YAAY,0CAA0C,qBAAqB;CACnG;CAEA,IAAI,SAAS,SAAS,OAAO;EAC3B,sBACE,YACA,sCACA,SAAS,QAAQ,MAAM,oBACzB;EACA,sBACE,YACA,0CACA,SAAS,QAAQ,MAAM,qBACzB;CACF;CAEA,IAAI,SAAS,UAAU;EACrB,sBAAsB,YAAY,sCAAsC,SAAS,SAAS,oBAAoB;EAC9G,sBAAsB,YAAY,wCAAwC,SAAS,SAAS,qBAAqB;CACnH;CASA,MAAM,eAAe,SAAS,UAAU,SAAS,OAAA,EAAS;CAC1D,IAAI,eAAe,OAAO,YAAY,uBAAuB,YAAY,YAAY,qBAAqB,GAAG;EAC3G,WAAW,+BAA+B,YAAY,wBAAwB,KAAK,YAAY;EAC/F,sBAAsB,YAAY,2BAA2B,YAAY,eAAe;EACxF,sBAAsB,YAAY,sCAAsC,YAAY,kBAAkB;CACxG;CAGA,MAAM,cAAc,OAAO,SAAS,SAAS,IAAI;CACjD,IAAI,SAAS,SAAS,QAAQ,QAAQ,OAAO,SAAS,WAAW,GAC/D,WAAW,4BAA4B;CAGzC,OAAO;AACT;;;;;;AAOA,MAAa,4CAA4B,IAAI,IAAY;CACvD;CACA;CACA;CACA;AACF,CAAC;;;;AAKD,SAAS,sBACP,YACA,KACA,OACM;CACN,IAAI,SAAS,MACX,WAAW,OAAO;AAEtB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n"],"mappings":";;;;;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;AAKA,SAAS,sBACP,YACA,KACA,OACM;CACN,IAAI,SAAS,MACX,WAAW,OAAO;AAEtB"}
@@ -53,6 +53,7 @@ import { createFlueInstrumentation } from "./ai/flue/index.js";
53
53
  import { flueIntegration } from "./integrations/flue.js";
54
54
  import { piAiIntegration } from "./integrations/pi-ai.js";
55
55
  import { piDurableIntegration } from "./integrations/pi-durable.js";
56
+ import { tanstackAIIntegration } from "./integrations/tanstack-ai.js";
56
57
  import { mastraIntegration } from "./integrations/mastra.js";
57
58
  import { mcpServerIntegration } from "./integrations/mcp-server.js";
58
59
  import { instrumentTunnelServers, makeServeTunnelIntegration } from "./integrations/serveTunnel.js";
@@ -87,6 +88,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
87
88
  * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
88
89
  */
89
90
  const attachHapiErrorHandler = attachHapiErrorHandler$1;
90
- export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, collectInstalledModules, createFlueInstrumentation, createGetModuleFromFilename, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTunnelServer, instrumentTunnelServers, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
91
+ export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, collectInstalledModules, createFlueInstrumentation, createGetModuleFromFilename, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTunnelServer, instrumentTunnelServers, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tanstackAIIntegration, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
91
92
 
92
93
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel';\nexport { instrumentTunnelServer } from './utils/tunnelServer';\nexport { createGetModuleFromFilename } from './utils/module';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
1
+ {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport { tanstackAIIntegration } from './integrations/tanstack-ai';\nexport type { TanstackAIOptions } from './ai/tanstack-ai';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel';\nexport { instrumentTunnelServer } from './utils/tunnelServer';\nexport { createGetModuleFromFilename } from './utils/module';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
@@ -8,10 +8,10 @@ import { HANDLER, HTTP_SERVER, MIDDLEWARE } from "@sentry/conventions/op";
8
8
  /**
9
9
  * Captures tracing events emitted by Nitro tracing channels.
10
10
  */
11
- function captureTracingEvents() {
11
+ function captureTracingEvents(options) {
12
12
  const globalWithTraceChannels = GLOBAL_OBJ;
13
13
  if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) return;
14
- setupH3TracingChannels();
14
+ setupH3TracingChannels(options);
15
15
  setupSrvxTracingChannels();
16
16
  globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;
17
17
  }
@@ -54,9 +54,10 @@ function getParameterizedRoute(event) {
54
54
  if (!routePath || routePath === "/**") return;
55
55
  return routePath;
56
56
  }
57
- function setupH3TracingChannels() {
57
+ function setupH3TracingChannels(options) {
58
58
  if (!tracingChannel) return;
59
59
  bindTracingChannelToSpan(tracingChannel("h3.request"), (data) => {
60
+ if (data.type === "middleware" && !options.middleware) return;
60
61
  const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;
61
62
  if (data.type === "route" && hasHttpServerRootSpan()) {
62
63
  const matchedRoute = data.event.context?.matchedRoute?.route;
@@ -1 +1 @@
1
- {"version":3,"file":"captureTracingEvents.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/nitro/captureTracingEvents.ts"],"sourcesContent":["import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, SERVER_PORT } from '@sentry/conventions/attributes';\nimport { HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n getRootSpan,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n type Span,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes';\n\ntype GlobalWithTraceChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Captures tracing events emitted by Nitro tracing channels.\n */\nexport function captureTracingEvents(): void {\n // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized.\n const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels;\n if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n setupH3TracingChannels();\n setupSrvxTracingChannels();\n globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;\n}\n\n/**\n * Extracts the HTTP status code from a tracing channel result.\n * The result is the return value of the traced handler, which is a Response for srvx\n * and may or may not be a Response for h3.\n */\nfunction getResponseStatusCode(result: unknown): number | undefined {\n if (isObjectLike(result) && 'status' in result && typeof result.status === 'number') {\n return result.status;\n }\n return undefined;\n}\n\n/** Applies the HTTP status from the traced handler's result to the span, when present. */\nfunction applyResponseStatus(span: Span, data: TracingChannelPayloadWithSpan<{ result?: unknown }>): void {\n const statusCode = getResponseStatusCode(data.result);\n if (statusCode !== undefined) {\n setHttpStatus(span, statusCode);\n }\n}\n\n/**\n * Whether the request already has an `http.server` root span, created by the runtime's own HTTP\n * server instrumentation (Node `http`, `Bun.serve`, `Deno.serve`, Cloudflare's request wrapper).\n */\nfunction hasHttpServerRootSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && spanToJSON(getRootSpan(activeSpan)).attributes[SENTRY_OP] === HTTP_SERVER;\n}\n\n/**\n * The port the srvx server listens on. `options.port` is only the configured one, which is `0` for a\n * random port.\n */\nfunction getServerPort(server: SrvxRequestEvent['server']): number | undefined {\n const url = server.url ? parseStringToURLObject(server.url) : undefined;\n const port = url && 'port' in url ? Number(url.port) : undefined;\n return port || server.options.port || undefined;\n}\n\n/**\n * Extracts the parameterized route pattern from the h3 event context.\n */\nfunction getParameterizedRoute(event: NitroH3Event): string | undefined {\n const matchedRoute = event.context?.matchedRoute;\n if (!matchedRoute) {\n return undefined;\n }\n\n const routePath = matchedRoute.route;\n\n // Skip catch-all routes as they're not useful for transaction grouping\n if (!routePath || routePath === '/**') {\n return undefined;\n }\n\n return routePath;\n}\n\nfunction setupH3TracingChannels(): void {\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request'),\n data => {\n const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n // The route lives on the request's `http.server` root span, so the route handler only gets a\n // span that times the handler itself instead of yet another nested `http.server` span.\n if (data.type === 'route' && hasHttpServerRootSpan()) {\n const matchedRoute = data.event.context?.matchedRoute?.route;\n const span = startInactiveSpan({\n name: matchedRoute ? `${method} ${matchedRoute}` : method,\n attributes: {\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: HANDLER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n }\n\n const parsedUrl = parseStringToURLObject(data.event.url.href);\n const routePattern = getParameterizedRoute(data.event);\n\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.h3',\n { method: data.event.req.method },\n routePattern,\n );\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n const isUnparameterizedStreamedServerSpan =\n data.type !== 'middleware' &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n const span = startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan ? method : spanName,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: data.type === 'middleware' ? MIDDLEWARE : HTTP_SERVER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Update the root span with the parameterized route name. The root span is created before h3\n // resolves the route, so it initially has the raw URL.\n // Note: data.type is always 'middleware' here regardless of handler type, so we rely on\n // getParameterizedRoute() to filter out catch-all routes instead.\n const routePattern = getParameterizedRoute(data.event);\n if (routePattern) {\n setHttpServerSpanRouteAttribute(routePattern);\n }\n },\n },\n );\n}\n\nfunction setupSrvxTracingChannels(): void {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Store the parent span per-request so middleware and fetch share the same parent.\n // WeakMap ensures per-request isolation in concurrent environments and automatic cleanup.\n const requestParentSpans = new WeakMap<SrvxRequestEvent['request'], Span>();\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.request'),\n data => {\n // srvx only opens the request's `http.server` span when the runtime has not already created one.\n if (hasHttpServerRootSpan()) {\n return undefined;\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const client = getClient();\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.srvx',\n { method: data.request.method },\n undefined,\n client,\n );\n\n const headerAttributes = client\n ? httpHeadersToSpanAttributes(\n Object.fromEntries(data.request.headers.entries()),\n client.getDataCollectionOptions(),\n )\n : {};\n\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n // h3 renames this span via `setHttpServerSpanRouteAttribute` once it resolves the route.\n const isUnparameterizedStreamedServerSpan =\n !data.middleware &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n return startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan\n ? data.request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK\n : spanName,\n attributes: {\n ...urlAttributes,\n ...headerAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: data.middleware ? MIDDLEWARE : HTTP_SERVER,\n [SERVER_PORT]: getServerPort(data.server),\n },\n // Use the same parent span as middleware to make them siblings\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Clean up parent span reference after the fetch handler completes (success or error).\n requestParentSpans.delete(data.request);\n },\n },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.middleware'),\n data => {\n // For the first middleware, capture the current parent span per-request\n if (data.middleware?.index === 0) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n requestParentSpans.set(data.request, activeSpan);\n }\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const [, urlAttributes] = getHttpSpanDetailsFromUrlObject(parsedUrl, 'server', 'auto.http.nitro.srvx', {\n method: data.request.method,\n });\n\n // Create span as a child of the original parent, not the previous middleware\n return startInactiveSpan({\n name: `${data.middleware?.handler.name ?? 'unknown'} - ${data.request.method} ${data.request._url?.pathname}`,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: MIDDLEWARE,\n },\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n },\n },\n );\n}\n\n/**\n * Sets the parameterized route attributes on the span.\n */\nfunction setParameterizedRouteAttributes(span: Span, event: NitroH3Event): void {\n const matchedRoutePath = getParameterizedRoute(event);\n if (!matchedRoutePath) {\n return;\n }\n\n setHttpServerSpanRouteAttribute(matchedRoutePath);\n\n const rootSpan = getRootSpan(span);\n if (!rootSpan) {\n return;\n }\n\n const params = event.context?.params;\n\n if (isObjectLike(params)) {\n Object.entries(params).forEach(([key, value]) => {\n // Based on this convention: https://conventions.sentry.dev/attributes/url/#url-path-parameter-key\n rootSpan.setAttributes({\n [`url.path.parameter.${key}`]: String(value),\n [`params.${key}`]: String(value),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C,IAAI,CAAC,UACH;CAGF,MAAM,SAAS,MAAM,SAAS;CAE9B,IAAI,aAAa,MAAM,GACrB,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAE/C,SAAS,cAAc;IACpB,sBAAsB,QAAQ,OAAO,KAAK;IAC1C,UAAU,QAAQ,OAAO,KAAK;EACjC,CAAC;CACH,CAAC;AAEL"}
1
+ {"version":3,"file":"captureTracingEvents.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../../src/integrations/nitro/captureTracingEvents.ts"],"sourcesContent":["import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, SERVER_PORT } from '@sentry/conventions/attributes';\nimport { HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n getActiveSpan,\n getClient,\n getHttpSpanDetailsFromUrlObject,\n getRootSpan,\n GLOBAL_OBJ,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n type Span,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { bindTracingChannelToSpan, type TracingChannelPayloadWithSpan } from '../../tracing-channel';\nimport * as diagnosticsChannel from '../../utils/diagnosticsChannel';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\nimport type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes';\n\ntype GlobalWithTraceChannels = typeof GLOBAL_OBJ & {\n __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean;\n};\n\n/**\n * Captures tracing events emitted by Nitro tracing channels.\n */\nexport function captureTracingEvents(options: { middleware: boolean }): void {\n // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized.\n const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels;\n if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) {\n return;\n }\n\n setupH3TracingChannels(options);\n setupSrvxTracingChannels();\n globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true;\n}\n\n/**\n * Extracts the HTTP status code from a tracing channel result.\n * The result is the return value of the traced handler, which is a Response for srvx\n * and may or may not be a Response for h3.\n */\nfunction getResponseStatusCode(result: unknown): number | undefined {\n if (isObjectLike(result) && 'status' in result && typeof result.status === 'number') {\n return result.status;\n }\n return undefined;\n}\n\n/** Applies the HTTP status from the traced handler's result to the span, when present. */\nfunction applyResponseStatus(span: Span, data: TracingChannelPayloadWithSpan<{ result?: unknown }>): void {\n const statusCode = getResponseStatusCode(data.result);\n if (statusCode !== undefined) {\n setHttpStatus(span, statusCode);\n }\n}\n\n/**\n * Whether the request already has an `http.server` root span, created by the runtime's own HTTP\n * server instrumentation (Node `http`, `Bun.serve`, `Deno.serve`, Cloudflare's request wrapper).\n */\nfunction hasHttpServerRootSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && spanToJSON(getRootSpan(activeSpan)).attributes[SENTRY_OP] === HTTP_SERVER;\n}\n\n/**\n * The port the srvx server listens on. `options.port` is only the configured one, which is `0` for a\n * random port.\n */\nfunction getServerPort(server: SrvxRequestEvent['server']): number | undefined {\n const url = server.url ? parseStringToURLObject(server.url) : undefined;\n const port = url && 'port' in url ? Number(url.port) : undefined;\n return port || server.options.port || undefined;\n}\n\n/**\n * Extracts the parameterized route pattern from the h3 event context.\n */\nfunction getParameterizedRoute(event: NitroH3Event): string | undefined {\n const matchedRoute = event.context?.matchedRoute;\n if (!matchedRoute) {\n return undefined;\n }\n\n const routePath = matchedRoute.route;\n\n // Skip catch-all routes as they're not useful for transaction grouping\n if (!routePath || routePath === '/**') {\n return undefined;\n }\n\n return routePath;\n}\n\nfunction setupH3TracingChannels(options: { middleware: boolean }): void {\n // Bail if this is not available\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('h3.request'),\n data => {\n if (data.type === 'middleware' && !options.middleware) {\n return undefined;\n }\n\n const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n // The route lives on the request's `http.server` root span, so the route handler only gets a\n // span that times the handler itself instead of yet another nested `http.server` span.\n if (data.type === 'route' && hasHttpServerRootSpan()) {\n const matchedRoute = data.event.context?.matchedRoute?.route;\n const span = startInactiveSpan({\n name: matchedRoute ? `${method} ${matchedRoute}` : method,\n attributes: {\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: HANDLER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n }\n\n const parsedUrl = parseStringToURLObject(data.event.url.href);\n const routePattern = getParameterizedRoute(data.event);\n\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.h3',\n { method: data.event.req.method },\n routePattern,\n );\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n const isUnparameterizedStreamedServerSpan =\n data.type !== 'middleware' &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n const span = startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan ? method : spanName,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.h3',\n [SENTRY_OP]: data.type === 'middleware' ? MIDDLEWARE : HTTP_SERVER,\n },\n });\n\n setParameterizedRouteAttributes(span, data.event);\n\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Update the root span with the parameterized route name. The root span is created before h3\n // resolves the route, so it initially has the raw URL.\n // Note: data.type is always 'middleware' here regardless of handler type, so we rely on\n // getParameterizedRoute() to filter out catch-all routes instead.\n const routePattern = getParameterizedRoute(data.event);\n if (routePattern) {\n setHttpServerSpanRouteAttribute(routePattern);\n }\n },\n },\n );\n}\n\nfunction setupSrvxTracingChannels(): void {\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n // Store the parent span per-request so middleware and fetch share the same parent.\n // WeakMap ensures per-request isolation in concurrent environments and automatic cleanup.\n const requestParentSpans = new WeakMap<SrvxRequestEvent['request'], Span>();\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.request'),\n data => {\n // srvx only opens the request's `http.server` span when the runtime has not already created one.\n if (hasHttpServerRootSpan()) {\n return undefined;\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const client = getClient();\n const [spanName, urlAttributes] = getHttpSpanDetailsFromUrlObject(\n parsedUrl,\n 'server',\n 'auto.http.nitro.srvx',\n { method: data.request.method },\n undefined,\n client,\n );\n\n const headerAttributes = client\n ? httpHeadersToSpanAttributes(\n Object.fromEntries(data.request.headers.entries()),\n client.getDataCollectionOptions(),\n )\n : {};\n\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // Only applies to the http.server span; middleware spans keep their own naming.\n // h3 renames this span via `setHttpServerSpanRouteAttribute` once it resolves the route.\n const isUnparameterizedStreamedServerSpan =\n !data.middleware &&\n urlAttributes[SENTRY_SEGMENT_NAME_SOURCE] !== 'route' &&\n !!client &&\n hasSpanStreamingEnabled(client);\n\n return startInactiveSpan({\n name: isUnparameterizedStreamedServerSpan\n ? data.request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK\n : spanName,\n attributes: {\n ...urlAttributes,\n ...headerAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: data.middleware ? MIDDLEWARE : HTTP_SERVER,\n [SERVER_PORT]: getServerPort(data.server),\n },\n // Use the same parent span as middleware to make them siblings\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n\n // Clean up parent span reference after the fetch handler completes (success or error).\n requestParentSpans.delete(data.request);\n },\n },\n );\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<SrvxRequestEvent>('srvx.middleware'),\n data => {\n // For the first middleware, capture the current parent span per-request\n if (data.middleware?.index === 0) {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n requestParentSpans.set(data.request, activeSpan);\n }\n }\n\n const parsedUrl = data.request._url ? parseStringToURLObject(data.request._url.href) : undefined;\n const [, urlAttributes] = getHttpSpanDetailsFromUrlObject(parsedUrl, 'server', 'auto.http.nitro.srvx', {\n method: data.request.method,\n });\n\n // Create span as a child of the original parent, not the previous middleware\n return startInactiveSpan({\n name: `${data.middleware?.handler.name ?? 'unknown'} - ${data.request.method} ${data.request._url?.pathname}`,\n attributes: {\n ...urlAttributes,\n [SENTRY_ORIGIN]: 'auto.http.nitro.srvx',\n [SENTRY_OP]: MIDDLEWARE,\n },\n parentSpan: requestParentSpans.get(data.request) || undefined,\n });\n },\n {\n beforeSpanEnd(span, data) {\n applyResponseStatus(span, data);\n },\n },\n );\n}\n\n/**\n * Sets the parameterized route attributes on the span.\n */\nfunction setParameterizedRouteAttributes(span: Span, event: NitroH3Event): void {\n const matchedRoutePath = getParameterizedRoute(event);\n if (!matchedRoutePath) {\n return;\n }\n\n setHttpServerSpanRouteAttribute(matchedRoutePath);\n\n const rootSpan = getRootSpan(span);\n if (!rootSpan) {\n return;\n }\n\n const params = event.context?.params;\n\n if (isObjectLike(params)) {\n Object.entries(params).forEach(([key, value]) => {\n // Based on this convention: https://conventions.sentry.dev/attributes/url/#url-path-parameter-key\n rootSpan.setAttributes({\n [`url.path.parameter.${key}`]: String(value),\n [`params.${key}`]: String(value),\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;AA8BA,SAAgB,qBAAqB,SAAwC;CAE3E,MAAM,0BAA0B;CAChC,IAAI,wBAAwB,6CAC1B;CAGF,uBAAuB,OAAO;CAC9B,yBA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ACrB,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAE/C,SAAS,cAAc;IACpB,sBAAsB,QAAQ,OAAO,KAAK;IAC1C,UAAU,QAAQ,OAAO,KAAK;EACjC,CAAC;CACH,CAAC;AAEL"}
@@ -5,11 +5,11 @@ import { defineIntegration } from "@sentry/core";
5
5
  // src/integrations/nitro/index.ts
6
6
  const INTEGRATION_NAME = "Nitro";
7
7
  const _nitroIntegration = ((options = {}) => {
8
- const { serverTiming = true, storage = true } = options;
8
+ const { middleware = true, serverTiming = true, storage = true } = options;
9
9
  return {
10
10
  name: INTEGRATION_NAME,
11
11
  setupOnce() {
12
- captureTracingEvents();
12
+ captureTracingEvents({ middleware });
13
13
  if (storage) captureStorageEvents();
14
14
  if (serverTiming) captureServerTimingHeaders();
15
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/integrations/nitro/index.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { captureStorageEvents } from './captureStorageEvents';\nimport { captureTracingEvents } from './captureTracingEvents';\nimport { captureServerTimingHeaders } from './setServerTimingHeaders';\n\nconst INTEGRATION_NAME = 'Nitro' as const;\n\nexport interface NitroIntegrationOptions {\n /**\n * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser\n * SDK can connect a pageload trace to the backend trace.\n *\n * @default true\n */\n serverTiming?: boolean;\n\n /**\n * Create cache spans for unstorage operations.\n *\n * @default true\n */\n storage?: boolean;\n}\n\nconst _nitroIntegration = ((options: NitroIntegrationOptions = {}) => {\n const { serverTiming = true, storage = true } = options;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n captureTracingEvents();\n\n if (storage) {\n captureStorageEvents();\n }\n\n if (serverTiming) {\n captureServerTimingHeaders();\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Instruments a Nitro server via its `node:diagnostics_channel` tracing channels: HTTP server and\n * middleware spans (h3/srvx), cache spans (unstorage) and `Server-Timing` trace-propagation headers.\n * It subscribes to those channels, so it is inert unless a Nitro app (or a framework that enables the\n * same tracing channels) is running.\n *\n * Registered regardless of whether tracing is enabled, because trace propagation must work in\n * tracing-without-performance mode too; without tracing, the spans it starts are non-recording.\n * Error capture is handled by the `@sentry/nitro` runtime plugin's Nitro `error` hook.\n */\nexport const nitroIntegration = defineIntegration(_nitroIntegration);\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB;AAmBzB,MAAM,sBAAsB,UAAmC,CAAC,MAAM;CACpE,MAAM,EAAE,eAAe,MAAM,UAAU,SAAS;CAEhD,OAAO;EACL,MAAM;EACN,YAAY;GACV,qBAAqB;GAErB,IAAI,SACF,qBAAqB;GAGvB,IAAI,cACF,2BAA2B;EAE/B;CACF;AACF;;;;;;;;;;;AAYA,MAAa,mBAAmB,kBAAkB,iBAAiB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/integrations/nitro/index.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { captureStorageEvents } from './captureStorageEvents';\nimport { captureTracingEvents } from './captureTracingEvents';\nimport { captureServerTimingHeaders } from './setServerTimingHeaders';\n\nconst INTEGRATION_NAME = 'Nitro' as const;\n\nexport interface NitroIntegrationOptions {\n /**\n * Create `middleware` spans for h3 middleware.\n *\n * @default true\n */\n middleware?: boolean;\n\n /**\n * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser\n * SDK can connect a pageload trace to the backend trace.\n *\n * @default true\n */\n serverTiming?: boolean;\n\n /**\n * Create cache spans for unstorage operations.\n *\n * @default true\n */\n storage?: boolean;\n}\n\nconst _nitroIntegration = ((options: NitroIntegrationOptions = {}) => {\n const { middleware = true, serverTiming = true, storage = true } = options;\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n captureTracingEvents({ middleware });\n\n if (storage) {\n captureStorageEvents();\n }\n\n if (serverTiming) {\n captureServerTimingHeaders();\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Instruments a Nitro server via its `node:diagnostics_channel` tracing channels: HTTP server and\n * middleware spans (h3/srvx), cache spans (unstorage) and `Server-Timing` trace-propagation headers.\n * It subscribes to those channels, so it is inert unless a Nitro app (or a framework that enables the\n * same tracing channels) is running.\n *\n * Registered regardless of whether tracing is enabled, because trace propagation must work in\n * tracing-without-performance mode too; without tracing, the spans it starts are non-recording.\n * Error capture is handled by the `@sentry/nitro` runtime plugin's Nitro `error` hook.\n */\nexport const nitroIntegration = defineIntegration(_nitroIntegration);\n"],"mappings":";;;;;AAMA,MAAM,mBAAmB;AA0BzB,MAAM,sBAAsB,UAAmC,CAAC,MAAM;CACpE,MAAM,EAAE,aAAa,MAAM,eAAe,MAAM,UAAU,SAAS;CAEnE,OAAO;EACL,MAAM;EACN,YAAY;GACV,qBAAqB,EAAE,WAAW,CAAC;GAEnC,IAAI,SACF,qBAAqB;GAGvB,IAAI,cACF,2BAA2B;EAE/B;CACF;AACF;;;;;;;;;;;AAYA,MAAa,mBAAmB,kBAAkB,iBAAiB"}