@sentry/server-utils 10.64.0 → 10.65.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.
- package/build/cjs/graphql/graphql-dc-subscriber.js +125 -0
- package/build/cjs/graphql/graphql-dc-subscriber.js.map +1 -0
- package/build/cjs/graphql/index.js +23 -0
- package/build/cjs/graphql/index.js.map +1 -0
- package/build/cjs/graphql/utils.js +86 -0
- package/build/cjs/graphql/utils.js.map +1 -0
- package/build/cjs/index.js +10 -11
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/amqplib.js +420 -0
- package/build/cjs/integrations/tracing-channel/amqplib.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/index.js +24 -0
- package/build/cjs/integrations/tracing-channel/express/index.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/instrumentation.js +173 -0
- package/build/cjs/integrations/tracing-channel/express/instrumentation.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/express/route.js +76 -0
- package/build/cjs/integrations/tracing-channel/express/route.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js +1 -1
- package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/google-genai.js +96 -0
- package/build/cjs/integrations/tracing-channel/google-genai.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/constants.js +26 -0
- package/build/cjs/integrations/tracing-channel/graphql/constants.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/index.js +66 -0
- package/build/cjs/integrations/tracing-channel/graphql/index.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/resolvers.js +168 -0
- package/build/cjs/integrations/tracing-channel/graphql/resolvers.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/graphql/spans.js +102 -0
- package/build/cjs/integrations/tracing-channel/graphql/spans.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/ioredis.js +14 -14
- package/build/cjs/integrations/tracing-channel/ioredis.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/mysql.js +1 -1
- package/build/cjs/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/openai.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/postgres-js.js +191 -0
- package/build/cjs/integrations/tracing-channel/postgres-js.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/postgres.js +5 -5
- package/build/cjs/integrations/tracing-channel/postgres.js.map +1 -1
- package/build/cjs/integrations/tracing-channel/redis.js +227 -0
- package/build/cjs/integrations/tracing-channel/redis.js.map +1 -0
- package/build/cjs/integrations/tracing-channel/vercel-ai.js +2 -2
- package/build/cjs/integrations/tracing-channel/vercel-ai.js.map +1 -1
- package/build/cjs/mongoose/mongoose-dc-subscriber.js +1 -1
- package/build/cjs/mongoose/mongoose-dc-subscriber.js.map +1 -1
- package/build/cjs/mysql2/index.js +23 -0
- package/build/cjs/mysql2/index.js.map +1 -0
- package/build/cjs/mysql2/mysql2-dc-subscriber.js +68 -0
- package/build/cjs/mysql2/mysql2-dc-subscriber.js.map +1 -0
- package/build/cjs/orchestrion/channels.js +13 -1
- package/build/cjs/orchestrion/channels.js.map +1 -1
- package/build/cjs/orchestrion/config/amqplib.js +81 -0
- package/build/cjs/orchestrion/config/amqplib.js.map +1 -0
- package/build/cjs/orchestrion/config/express.js +76 -0
- package/build/cjs/orchestrion/config/express.js.map +1 -0
- package/build/cjs/orchestrion/config/google-genai.js +38 -0
- package/build/cjs/orchestrion/config/google-genai.js.map +1 -0
- package/build/cjs/orchestrion/config/graphql.js +28 -0
- package/build/cjs/orchestrion/config/graphql.js.map +1 -0
- package/build/cjs/orchestrion/config/index.js +15 -2
- package/build/cjs/orchestrion/config/index.js.map +1 -1
- package/build/cjs/orchestrion/config/postgres.js +50 -0
- package/build/cjs/orchestrion/config/postgres.js.map +1 -0
- package/build/cjs/orchestrion/config/redis.js +76 -0
- package/build/cjs/orchestrion/config/redis.js.map +1 -0
- package/build/cjs/orchestrion/config/vercel-ai.js +18 -14
- package/build/cjs/orchestrion/config/vercel-ai.js.map +1 -1
- package/build/cjs/orchestrion/index.js +18 -1
- package/build/cjs/orchestrion/index.js.map +1 -1
- package/build/cjs/redis/index.js +23 -0
- package/build/cjs/redis/index.js.map +1 -0
- package/build/cjs/redis/redis-dc-subscriber.js +23 -35
- package/build/cjs/redis/redis-dc-subscriber.js.map +1 -1
- package/build/cjs/tracing-channel.js +7 -6
- package/build/cjs/tracing-channel.js.map +1 -1
- package/build/cjs/vercel-ai/util.js +123 -0
- package/build/cjs/vercel-ai/util.js.map +1 -0
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js +138 -74
- package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/cjs/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.js → vercel-ai-orchestrion-subscriber.js} +153 -23
- package/build/cjs/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -0
- package/build/esm/graphql/graphql-dc-subscriber.js +118 -0
- package/build/esm/graphql/graphql-dc-subscriber.js.map +1 -0
- package/build/esm/graphql/index.js +21 -0
- package/build/esm/graphql/index.js.map +1 -0
- package/build/esm/graphql/utils.js +81 -0
- package/build/esm/graphql/utils.js.map +1 -0
- package/build/esm/index.js +3 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/tracing-channel/amqplib.js +418 -0
- package/build/esm/integrations/tracing-channel/amqplib.js.map +1 -0
- package/build/esm/integrations/tracing-channel/anthropic.js +1 -1
- package/build/esm/integrations/tracing-channel/express/index.js +22 -0
- package/build/esm/integrations/tracing-channel/express/index.js.map +1 -0
- package/build/esm/integrations/tracing-channel/express/instrumentation.js +171 -0
- package/build/esm/integrations/tracing-channel/express/instrumentation.js.map +1 -0
- package/build/esm/integrations/tracing-channel/express/route.js +68 -0
- package/build/esm/integrations/tracing-channel/express/route.js.map +1 -0
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js +2 -2
- package/build/esm/integrations/tracing-channel/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing-channel/google-genai.js +94 -0
- package/build/esm/integrations/tracing-channel/google-genai.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/constants.js +14 -0
- package/build/esm/integrations/tracing-channel/graphql/constants.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/index.js +63 -0
- package/build/esm/integrations/tracing-channel/graphql/index.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/resolvers.js +164 -0
- package/build/esm/integrations/tracing-channel/graphql/resolvers.js.map +1 -0
- package/build/esm/integrations/tracing-channel/graphql/spans.js +96 -0
- package/build/esm/integrations/tracing-channel/graphql/spans.js.map +1 -0
- package/build/esm/integrations/tracing-channel/ioredis.js +15 -15
- package/build/esm/integrations/tracing-channel/ioredis.js.map +1 -1
- package/build/esm/integrations/tracing-channel/mysql.js +2 -2
- package/build/esm/integrations/tracing-channel/mysql.js.map +1 -1
- package/build/esm/integrations/tracing-channel/openai.js +1 -1
- package/build/esm/integrations/tracing-channel/openai.js.map +1 -1
- package/build/esm/integrations/tracing-channel/postgres-js.js +189 -0
- package/build/esm/integrations/tracing-channel/postgres-js.js.map +1 -0
- package/build/esm/integrations/tracing-channel/postgres.js +6 -6
- package/build/esm/integrations/tracing-channel/postgres.js.map +1 -1
- package/build/esm/integrations/tracing-channel/redis.js +225 -0
- package/build/esm/integrations/tracing-channel/redis.js.map +1 -0
- package/build/esm/integrations/tracing-channel/vercel-ai.js +1 -1
- package/build/esm/integrations/tracing-channel/vercel-ai.js.map +1 -1
- package/build/esm/mongoose/mongoose-dc-subscriber.js +2 -2
- package/build/esm/mongoose/mongoose-dc-subscriber.js.map +1 -1
- package/build/esm/mysql2/index.js +21 -0
- package/build/esm/mysql2/index.js.map +1 -0
- package/build/esm/mysql2/mysql2-dc-subscriber.js +62 -0
- package/build/esm/mysql2/mysql2-dc-subscriber.js.map +1 -0
- package/build/esm/orchestrion/channels.js +13 -1
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/amqplib.js +78 -0
- package/build/esm/orchestrion/config/amqplib.js.map +1 -0
- package/build/esm/orchestrion/config/express.js +73 -0
- package/build/esm/orchestrion/config/express.js.map +1 -0
- package/build/esm/orchestrion/config/google-genai.js +35 -0
- package/build/esm/orchestrion/config/google-genai.js.map +1 -0
- package/build/esm/orchestrion/config/graphql.js +25 -0
- package/build/esm/orchestrion/config/graphql.js.map +1 -0
- package/build/esm/orchestrion/config/index.js +15 -2
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/orchestrion/config/postgres.js +47 -0
- package/build/esm/orchestrion/config/postgres.js.map +1 -0
- package/build/esm/orchestrion/config/redis.js +73 -0
- package/build/esm/orchestrion/config/redis.js.map +1 -0
- package/build/esm/orchestrion/config/vercel-ai.js +18 -14
- package/build/esm/orchestrion/config/vercel-ai.js.map +1 -1
- package/build/esm/orchestrion/index.js +14 -2
- package/build/esm/orchestrion/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/redis/index.js +21 -0
- package/build/esm/redis/index.js.map +1 -0
- package/build/esm/redis/redis-dc-subscriber.js +24 -36
- package/build/esm/redis/redis-dc-subscriber.js.map +1 -1
- package/build/esm/tracing-channel.js +8 -7
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/esm/vercel-ai/util.js +116 -0
- package/build/esm/vercel-ai/util.js.map +1 -0
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js +112 -50
- package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.js → vercel-ai-orchestrion-subscriber.js} +153 -23
- package/build/esm/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -0
- package/build/types/graphql/graphql-dc-subscriber.d.ts +94 -0
- package/build/types/graphql/graphql-dc-subscriber.d.ts.map +1 -0
- package/build/types/graphql/index.d.ts +12 -0
- package/build/types/graphql/index.d.ts.map +1 -0
- package/build/types/graphql/utils.d.ts +40 -0
- package/build/types/graphql/utils.d.ts.map +1 -0
- package/build/types/index.d.ts +4 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/amqplib.d.ts +11 -0
- package/build/types/integrations/tracing-channel/amqplib.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/index.d.ts +18 -0
- package/build/types/integrations/tracing-channel/express/index.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/instrumentation.d.ts +4 -0
- package/build/types/integrations/tracing-channel/express/instrumentation.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/route.d.ts +28 -0
- package/build/types/integrations/tracing-channel/express/route.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/express/types.d.ts +64 -0
- package/build/types/integrations/tracing-channel/express/types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/google-genai.d.ts +12 -0
- package/build/types/integrations/tracing-channel/google-genai.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/constants.d.ts +12 -0
- package/build/types/integrations/tracing-channel/graphql/constants.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/graphql-types.d.ts +135 -0
- package/build/types/integrations/tracing-channel/graphql/graphql-types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/index.d.ts +28 -0
- package/build/types/integrations/tracing-channel/graphql/index.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/resolvers.d.ts +13 -0
- package/build/types/integrations/tracing-channel/graphql/resolvers.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/spans.d.ts +17 -0
- package/build/types/integrations/tracing-channel/graphql/spans.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/graphql/types.d.ts +25 -0
- package/build/types/integrations/tracing-channel/graphql/types.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/ioredis.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/mysql.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/openai.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/postgres-js.d.ts +26 -0
- package/build/types/integrations/tracing-channel/postgres-js.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/postgres.d.ts.map +1 -1
- package/build/types/integrations/tracing-channel/redis.d.ts +16 -0
- package/build/types/integrations/tracing-channel/redis.d.ts.map +1 -0
- package/build/types/integrations/tracing-channel/vercel-ai.d.ts +1 -1
- package/build/types/mongoose/mongoose-dc-subscriber.d.ts.map +1 -1
- package/build/types/mysql2/index.d.ts +11 -0
- package/build/types/mysql2/index.d.ts.map +1 -0
- package/build/types/mysql2/mysql2-dc-subscriber.d.ts +59 -0
- package/build/types/mysql2/mysql2-dc-subscriber.d.ts.map +1 -0
- package/build/types/orchestrion/channels.d.ts +34 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/amqplib.d.ts +66 -0
- package/build/types/orchestrion/config/amqplib.d.ts.map +1 -0
- package/build/types/orchestrion/config/express.d.ts +32 -0
- package/build/types/orchestrion/config/express.d.ts.map +1 -0
- package/build/types/orchestrion/config/google-genai.d.ts +30 -0
- package/build/types/orchestrion/config/google-genai.d.ts.map +1 -0
- package/build/types/orchestrion/config/graphql.d.ts +29 -0
- package/build/types/orchestrion/config/graphql.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/orchestrion/config/postgres.d.ts +9 -0
- package/build/types/orchestrion/config/postgres.d.ts.map +1 -0
- package/build/types/orchestrion/config/redis.d.ts +37 -0
- package/build/types/orchestrion/config/redis.d.ts.map +1 -0
- package/build/types/orchestrion/config/vercel-ai.d.ts +1 -0
- package/build/types/orchestrion/config/vercel-ai.d.ts.map +1 -1
- package/build/types/orchestrion/index.d.ts +31 -4
- package/build/types/orchestrion/index.d.ts.map +1 -1
- package/build/types/redis/index.d.ts +18 -0
- package/build/types/redis/index.d.ts.map +1 -0
- package/build/types/redis/redis-dc-subscriber.d.ts +0 -5
- package/build/types/redis/redis-dc-subscriber.d.ts.map +1 -1
- package/build/types/tracing-channel.d.ts +5 -0
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/build/types/vercel-ai/util.d.ts +32 -0
- package/build/types/vercel-ai/util.d.ts.map +1 -0
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts +6 -2
- package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.d.ts → vercel-ai-orchestrion-subscriber.d.ts} +1 -1
- package/build/types/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -0
- package/build/types-ts3.8/graphql/graphql-dc-subscriber.d.ts +94 -0
- package/build/types-ts3.8/graphql/index.d.ts +12 -0
- package/build/types-ts3.8/graphql/utils.d.ts +40 -0
- package/build/types-ts3.8/index.d.ts +4 -2
- package/build/types-ts3.8/integrations/tracing-channel/amqplib.d.ts +11 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/index.d.ts +18 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/instrumentation.d.ts +4 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/route.d.ts +28 -0
- package/build/types-ts3.8/integrations/tracing-channel/express/types.d.ts +64 -0
- package/build/types-ts3.8/integrations/tracing-channel/google-genai.d.ts +12 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/constants.d.ts +12 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/graphql-types.d.ts +135 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/index.d.ts +30 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/resolvers.d.ts +13 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/spans.d.ts +17 -0
- package/build/types-ts3.8/integrations/tracing-channel/graphql/types.d.ts +25 -0
- package/build/types-ts3.8/integrations/tracing-channel/postgres-js.d.ts +26 -0
- package/build/types-ts3.8/integrations/tracing-channel/redis.d.ts +16 -0
- package/build/types-ts3.8/integrations/tracing-channel/vercel-ai.d.ts +1 -1
- package/build/types-ts3.8/mysql2/index.d.ts +11 -0
- package/build/types-ts3.8/mysql2/mysql2-dc-subscriber.d.ts +59 -0
- package/build/types-ts3.8/orchestrion/channels.d.ts +34 -0
- package/build/types-ts3.8/orchestrion/config/amqplib.d.ts +66 -0
- package/build/types-ts3.8/orchestrion/config/express.d.ts +32 -0
- package/build/types-ts3.8/orchestrion/config/google-genai.d.ts +30 -0
- package/build/types-ts3.8/orchestrion/config/graphql.d.ts +29 -0
- package/build/types-ts3.8/orchestrion/config/postgres.d.ts +9 -0
- package/build/types-ts3.8/orchestrion/config/redis.d.ts +37 -0
- package/build/types-ts3.8/orchestrion/config/vercel-ai.d.ts +1 -0
- package/build/types-ts3.8/orchestrion/index.d.ts +33 -4
- package/build/types-ts3.8/redis/index.d.ts +18 -0
- package/build/types-ts3.8/redis/redis-dc-subscriber.d.ts +0 -5
- package/build/types-ts3.8/tracing-channel.d.ts +5 -0
- package/build/types-ts3.8/vercel-ai/util.d.ts +32 -0
- package/build/types-ts3.8/vercel-ai/vercel-ai-dc-subscriber.d.ts +6 -2
- package/build/types-ts3.8/vercel-ai/{vercel-ai-orchestrion-v6-subscriber.d.ts → vercel-ai-orchestrion-subscriber.d.ts} +1 -1
- package/package.json +2 -2
- package/build/cjs/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +0 -1
- package/build/esm/vercel-ai/vercel-ai-orchestrion-v6-subscriber.js.map +0 -1
- package/build/types/vercel-ai/vercel-ai-orchestrion-v6-subscriber.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-channel.js","sources":["../../src/tracing-channel.ts"],"sourcesContent":["import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ExclusiveEventHintOrCaptureContext, Span } from '@sentry/core';\nimport { debug, captureException, SPAN_STATUS_ERROR, getAsyncContextStrategy, getMainCarrier } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n /**\n * The current active span for the traced call.\n */\n _sentrySpan?: Span;\n\n /**\n * The context's active store value, used to restore the context for asyncStart continuations for callback-based tracing.\n */\n _sentryCallerStore?: unknown;\n};\n\n/*\n * A type patch so that we don't have to handle all subscription types.\n */\nexport interface SentryTracingChannel<TData extends object = object> extends Omit<\n TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>,\n 'subscribe' | 'unsubscribe'\n> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n}\n\nexport interface TracingChannelLifeCycleOptions<TData extends object = object> {\n /**\n * Invoked with the span and the channel context object once the traced operation completes\n * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup.\n */\n beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void;\n\n /**\n * Whether a thrown error is captured as a Sentry event. The span is always marked with error status regardless. Defaults to `false`.\n * You can alternatively pass a function that sets the ExclusiveEventHintOrCaptureContext on the captured error.\n * Set `true` for instrumentations that own the error boundary, (e.g: route handlers)\n * For database drivers, it is not recommended to set this at all.\n */\n captureError?: boolean | ((e: unknown) => ExclusiveEventHintOrCaptureContext);\n\n /**\n * Take ownership of *when* the span ends: return `true` and the helper won't end it on\n * `end`/`asyncEnd`. For results that settle out-of-band — e.g. a streamed `EventEmitter` that\n * completes via its own `'end'`/`'error'` events.\n *\n * Call `end` when it settles — `end()` on success, `end(error)` on failure. `end` owns *how* the span\n * ends (error status/attributes, `captureError`, `beforeSpanEnd`) and is idempotent. Default `false`\n * lets the helper end the span as usual.\n */\n deferSpanEnd?: (args: {\n span: Span;\n data: TracingChannelPayloadWithSpan<TData>;\n /** Ends the span: `end()` on success, `end(error)` on failure. Idempotent. */\n end: (error?: unknown) => void;\n }) => boolean;\n}\n\n/** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */\nexport interface TracingChannelBindingHandle<TData extends object = object> {\n /**\n * The tracing channel with the span bound into async context.\n */\n channel: SentryTracingChannel<TData>;\n\n /**\n * Tears down the binding: unsubscribes lifecycle handlers, when present, and unbinds the start store.\n * Idempotent, and a no-op when no async context binding was available.\n */\n unbind: () => void;\n}\n\nconst NOOP = (): void => {};\n\n/**\n * Bind a span and its lifecycle to a tracing channel so the span becomes the active async context\n * for the traced operation and is ended when the operation completes.\n *\n * `getSpan` may return `undefined` to opt a payload out entirely: nothing is bound, no span is\n * tracked, and the active context is left untouched. Use it for events that ride the same channel\n * but should reuse the enclosing span instead of opening (and ending) their own — e.g. an agent\n * loop's per-step events, where ending a freshly opened span would close the parent prematurely.\n */\nexport function bindTracingChannelToSpan<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: TracingChannelLifeCycleOptions<TData>,\n): TracingChannelBindingHandle<TData> {\n const handle = bindSpanToChannelStore(channel, getSpan);\n\n const beforeSpanEnd = opts?.beforeSpanEnd;\n const deferSpanEnd = opts?.deferSpanEnd;\n const getErrorHint = (e: unknown): ExclusiveEventHintOrCaptureContext => {\n if (typeof opts?.captureError === 'function') {\n return opts.captureError(e);\n }\n\n return {\n mechanism: {\n type: 'auto.diagnostic_channels.bind_span',\n handled: false,\n },\n };\n };\n\n // Apply Sentry error status + attributes (and capture, if configured) to a span. Shared by the\n // channel `error` lifecycle and the deferred `end` util so the two can't drift.\n const annotateSpanError = (span: Span, error: unknown): void => {\n if (opts?.captureError) {\n captureException(error, getErrorHint(error));\n }\n\n const { message, attributes } = getErrorInfo(error);\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n span.setAttributes(attributes);\n };\n\n // Creates an end fn for deferred handlers to use, ensures consistent span end behavior\n const makeDeferredEnd = (span: Span, data: TracingChannelPayloadWithSpan<TData>) => {\n let ended = false;\n\n return (error?: unknown): void => {\n if (ended) {\n return;\n }\n\n ended = true;\n if (error !== undefined) {\n annotateSpanError(span, error);\n }\n\n endBoundSpan(data, beforeSpanEnd);\n };\n };\n\n const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = {\n start: NOOP,\n asyncStart: NOOP,\n end(data) {\n // The operation settled synchronously (returned or threw)\n // Presence checks because caller can return `undefined` result or throw a falsy value.\n if ('error' in data || 'result' in data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n }\n },\n error(data) {\n // No span was bound for this payload (`getSpan` returned undefined), so there is nothing to\n // annotate and no instrumentation that owns capturing this error.\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n\n annotateSpanError(span, data.error);\n },\n asyncEnd(data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n },\n };\n\n handle.channel.subscribe(subscribers);\n\n return {\n channel: handle.channel,\n unbind: () => {\n handle.channel.unsubscribe(subscribers);\n handle.unbind();\n },\n };\n}\n\n/**\n * Bind a span into the channel's async context so it becomes active for the traced operation,\n * without managing its lifecycle. The primitive behind {@link bindTracingChannelToSpan}, which\n * layers span-ending and error handling on top.\n *\n * `getSpan` may return `undefined` to leave the active context untouched for that payload.\n */\nfunction bindSpanToChannelStore<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n): TracingChannelBindingHandle<TData> {\n // Grabs the tracing channel binding defined by the AsyncContext strategy implementation\n const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();\n\n // If no binding, then either the implementer doesn't support tracing channels or there is no active strategy\n // Failure mode here means we would still access the channel and potentially subscribe to it, but parenting will be off.\n if (!binding) {\n DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.');\n\n return {\n channel,\n unbind: NOOP,\n };\n }\n\n // Grab the ALS instance, we don't really care what is in it as long as the AsyncContext strategy can use its value to figure out parenting.\n const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>;\n\n // bindStore activates the ALS for the traced call; any getStore() inside it returns the value bound for that context.\n // 1. Produce: getStoreWithActiveSpan(span) clones the current scope, plants the span via _INTERNAL_setSpanForScope, and returns { scope, isolationScope }, the active context carrying our span.\n // 2. Bind: the courier hands that opaque value to channel.start.bindStore(asyncLocalStorage, producer), which runs the traced op inside asyncLocalStorage.run(value, …); it never inspects the value.\n // 3. Read: inside the op, Sentry's scope machinery calls getScopes() → asyncStorage.getStore() on that same ALS, so getCurrentScope/getIsolationScope/getActiveSpan resolve to the scope carrying our span.\n // 4. Nest: any child span started in the traced op parents to that active span.\n channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n // Stash the caller's store before we swap in the span store, so `asyncStart` can restore it for\n // callback-style channels (see `_sentryCallerStore`).\n data._sentryCallerStore = asyncLocalStorage.getStore();\n\n const span = getSpan(data);\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return data._sentryCallerStore as TData;\n }\n data._sentrySpan = span;\n\n return binding.getStoreWithActiveSpan(span) as TData;\n });\n\n // Restore the caller's context for the async continuation. Only callback-style channels `runStores`\n // `asyncStart` (so the callback runs inside this store). promise channels `publish` it, leaving this\n // inert, their continuation already inherits the caller's context natively.\n channel.asyncStart.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n return data._sentryCallerStore as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the stores\n channel.start.unbindStore(asyncLocalStorage);\n channel.asyncStart.unbindStore(asyncLocalStorage);\n },\n };\n}\n\nfunction endBoundSpan<TData extends object>(\n data: TracingChannelPayloadWithSpan<TData>,\n beforeSpanEnd: TracingChannelLifeCycleOptions<TData>['beforeSpanEnd'],\n): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n beforeSpanEnd?.(span, data);\n span.end();\n}\n\ntype ErrorInfo = {\n message: string | undefined;\n attributes: Record<string, string>;\n};\n\n/**\n * Best-effort message and attribute extraction for thrown/rejected values.\n */\nfunction getErrorInfo(error: unknown): ErrorInfo {\n const isObject = !!error && typeof error === 'object';\n const raw = isObject ? ('message' in error ? error.message : undefined) : error;\n\n // Leave the status message unset if not set (e.g. an `AggregateError` from\n // ECONNREFUSED, whose `.message` is empty). Otherwise cast to string.\n const message = raw ? String(raw) : undefined;\n const type = isObject && 'name' in error ? String(error.name) : 'unknown';\n\n return {\n message,\n attributes: {\n [ERROR_TYPE]: type,\n },\n };\n}\n"],"names":["captureException","SPAN_STATUS_ERROR","getAsyncContextStrategy","getMainCarrier","DEBUG_BUILD","debug","ERROR_TYPE"],"mappings":";;;;;;AA4EA,MAAM,OAAO,MAAY;AAAC,CAAA;AAWnB,SAAS,wBAAA,CACd,OAAA,EACA,OAAA,EACA,IAAA,EACoC;AACpC,EAAA,MAAM,MAAA,GAAS,sBAAA,CAAuB,OAAA,EAAS,OAAO,CAAA;AAEtD,EAAA,MAAM,gBAAgB,IAAA,EAAM,aAAA;AAC5B,EAAA,MAAM,eAAe,IAAA,EAAM,YAAA;AAC3B,EAAA,MAAM,YAAA,GAAe,CAAC,CAAA,KAAmD;AACvE,IAAA,IAAI,OAAO,IAAA,EAAM,YAAA,KAAiB,UAAA,EAAY;AAC5C,MAAA,OAAO,IAAA,CAAK,aAAa,CAAC,CAAA;AAAA,IAC5B;AAEA,IAAA,OAAO;AAAA,MACL,SAAA,EAAW;AAAA,QACT,IAAA,EAAM,oCAAA;AAAA,QACN,OAAA,EAAS;AAAA;AACX,KACF;AAAA,EACF,CAAA;AAIA,EAAA,MAAM,iBAAA,GAAoB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AA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAACC,qBAAU,GAAG;AAAA;AAChB,GACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"tracing-channel.js","sources":["../../src/tracing-channel.ts"],"sourcesContent":["import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\nimport type { ExclusiveEventHintOrCaptureContext, Span } from '@sentry/core';\nimport {\n debug,\n captureException,\n isObjectLike,\n SPAN_STATUS_ERROR,\n getAsyncContextStrategy,\n getMainCarrier,\n getActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build';\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\n\nexport type TracingChannelPayloadWithSpan<TData extends object> = TData & {\n /**\n * The current active span for the traced call.\n */\n _sentrySpan?: Span;\n\n /**\n * The context's active store value, used to restore the context for asyncStart continuations for callback-based tracing.\n */\n _sentryCallerStore?: unknown;\n};\n\n/*\n * A type patch so that we don't have to handle all subscription types.\n */\nexport interface SentryTracingChannel<TData extends object = object> extends Omit<\n TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>,\n 'subscribe' | 'unsubscribe'\n> {\n subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void;\n}\n\nexport interface TracingChannelLifeCycleOptions<TData extends object = object> {\n /**\n * Invoked with the span and the channel context object once the traced operation completes\n * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup.\n */\n beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void;\n\n /**\n * Whether a thrown error is captured as a Sentry event. The span is always marked with error status regardless. Defaults to `false`.\n * You can alternatively pass a function that sets the ExclusiveEventHintOrCaptureContext on the captured error.\n * Set `true` for instrumentations that own the error boundary, (e.g: route handlers)\n * For database drivers, it is not recommended to set this at all.\n */\n captureError?: boolean | ((e: unknown) => ExclusiveEventHintOrCaptureContext);\n\n /**\n * Take ownership of *when* the span ends: return `true` and the helper won't end it on\n * `end`/`asyncEnd`. For results that settle out-of-band — e.g. a streamed `EventEmitter` that\n * completes via its own `'end'`/`'error'` events.\n *\n * Call `end` when it settles — `end()` on success, `end(error)` on failure. `end` owns *how* the span\n * ends (error status/attributes, `captureError`, `beforeSpanEnd`) and is idempotent. Default `false`\n * lets the helper end the span as usual.\n */\n deferSpanEnd?: (args: {\n span: Span;\n data: TracingChannelPayloadWithSpan<TData>;\n /** Ends the span: `end()` on success, `end(error)` on failure. Idempotent. */\n end: (error?: unknown) => void;\n }) => boolean;\n\n /**\n * Apply span/scope binding only if there is a parent span, similar to returning `undefined` in the `getSpan` callback.\n * If you need to perform some conditional checking on the parent span before deciding, do it in the `getSpan` callback.\n */\n requiresParentSpan?: boolean;\n}\n\n/** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */\nexport interface TracingChannelBindingHandle<TData extends object = object> {\n /**\n * The tracing channel with the span bound into async context.\n */\n channel: SentryTracingChannel<TData>;\n\n /**\n * Tears down the binding: unsubscribes lifecycle handlers, when present, and unbinds the start store.\n * Idempotent, and a no-op when no async context binding was available.\n */\n unbind: () => void;\n}\n\nconst NOOP = (): void => {};\n\n/**\n * Bind a span and its lifecycle to a tracing channel so the span becomes the active async context\n * for the traced operation and is ended when the operation completes.\n *\n * `getSpan` may return `undefined` to opt a payload out entirely: nothing is bound, no span is\n * tracked, and the active context is left untouched. Use it for events that ride the same channel\n * but should reuse the enclosing span instead of opening (and ending) their own — e.g. an agent\n * loop's per-step events, where ending a freshly opened span would close the parent prematurely.\n */\nexport function bindTracingChannelToSpan<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: TracingChannelLifeCycleOptions<TData>,\n): TracingChannelBindingHandle<TData> {\n const handle = bindSpanToChannelStore(channel, getSpan, opts);\n\n const beforeSpanEnd = opts?.beforeSpanEnd;\n const deferSpanEnd = opts?.deferSpanEnd;\n const getErrorHint = (e: unknown): ExclusiveEventHintOrCaptureContext => {\n if (typeof opts?.captureError === 'function') {\n return opts.captureError(e);\n }\n\n return {\n mechanism: {\n type: 'auto.diagnostic_channels.bind_span',\n handled: false,\n },\n };\n };\n\n // Apply Sentry error status + attributes (and capture, if configured) to a span. Shared by the\n // channel `error` lifecycle and the deferred `end` util so the two can't drift.\n const annotateSpanError = (span: Span, error: unknown): void => {\n if (opts?.captureError) {\n captureException(error, getErrorHint(error));\n }\n\n const { message, attributes } = getErrorInfo(error);\n span.setStatus({ code: SPAN_STATUS_ERROR, message });\n span.setAttributes(attributes);\n };\n\n // Creates an end fn for deferred handlers to use, ensures consistent span end behavior\n const makeDeferredEnd = (span: Span, data: TracingChannelPayloadWithSpan<TData>) => {\n let ended = false;\n\n return (error?: unknown): void => {\n if (ended) {\n return;\n }\n\n ended = true;\n if (error !== undefined) {\n annotateSpanError(span, error);\n }\n\n endBoundSpan(data, beforeSpanEnd);\n };\n };\n\n const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = {\n start: NOOP,\n asyncStart: NOOP,\n end(data) {\n // The operation settled synchronously (returned or threw)\n // Presence checks because caller can return `undefined` result or throw a falsy value.\n if ('error' in data || 'result' in data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n }\n },\n error(data) {\n // No span was bound for this payload (`getSpan` returned undefined), so there is nothing to\n // annotate and no instrumentation that owns capturing this error.\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n\n annotateSpanError(span, data.error);\n },\n asyncEnd(data) {\n const span = data._sentrySpan;\n if (span && deferSpanEnd?.({ span, data, end: makeDeferredEnd(span, data) })) {\n return;\n }\n endBoundSpan(data, beforeSpanEnd);\n },\n };\n\n handle.channel.subscribe(subscribers);\n\n return {\n channel: handle.channel,\n unbind: () => {\n handle.channel.unsubscribe(subscribers);\n handle.unbind();\n },\n };\n}\n\n/**\n * Bind a span into the channel's async context so it becomes active for the traced operation,\n * without managing its lifecycle. The primitive behind {@link bindTracingChannelToSpan}, which\n * layers span-ending and error handling on top.\n *\n * `getSpan` may return `undefined` to leave the active context untouched for that payload.\n */\nfunction bindSpanToChannelStore<TData extends object>(\n channel: TracingChannel<TData, TData>,\n getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span | undefined,\n opts?: Pick<TracingChannelLifeCycleOptions, 'requiresParentSpan'>,\n): TracingChannelBindingHandle<TData> {\n // Grabs the tracing channel binding defined by the AsyncContext strategy implementation\n const binding = getAsyncContextStrategy(getMainCarrier()).getTracingChannelBinding?.();\n\n // If no binding, then either the implementer doesn't support tracing channels or there is no active strategy\n // Failure mode here means we would still access the channel and potentially subscribe to it, but parenting will be off.\n if (!binding) {\n DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.');\n\n return {\n channel,\n unbind: NOOP,\n };\n }\n\n // Grab the ALS instance, we don't really care what is in it as long as the AsyncContext strategy can use its value to figure out parenting.\n const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>;\n\n // bindStore activates the ALS for the traced call; any getStore() inside it returns the value bound for that context.\n // 1. Produce: getStoreWithActiveSpan(span) clones the current scope, plants the span via _INTERNAL_setSpanForScope, and returns { scope, isolationScope }, the active context carrying our span.\n // 2. Bind: the courier hands that opaque value to channel.start.bindStore(asyncLocalStorage, producer), which runs the traced op inside asyncLocalStorage.run(value, …); it never inspects the value.\n // 3. Read: inside the op, Sentry's scope machinery calls getScopes() → asyncStorage.getStore() on that same ALS, so getCurrentScope/getIsolationScope/getActiveSpan resolve to the scope carrying our span.\n // 4. Nest: any child span started in the traced op parents to that active span.\n channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n // Stash the caller's store before we swap in the span store, so `asyncStart` can restore it for\n // callback-style channels (see `_sentryCallerStore`).\n data._sentryCallerStore = asyncLocalStorage.getStore();\n\n const shouldGetSpan = !opts?.requiresParentSpan || getActiveSpan();\n const span = shouldGetSpan ? getSpan(data) : undefined;\n if (!span) {\n // Leave the active context untouched so nested operations keep parenting to the enclosing span.\n return data._sentryCallerStore as TData;\n }\n data._sentrySpan = span;\n\n return binding.getStoreWithActiveSpan(span) as TData;\n });\n\n // Restore the caller's context for the async continuation. Only callback-style channels `runStores`\n // `asyncStart` (so the callback runs inside this store). promise channels `publish` it, leaving this\n // inert, their continuation already inherits the caller's context natively.\n channel.asyncStart.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => {\n return data._sentryCallerStore as TData;\n });\n\n return {\n channel,\n unbind: () => {\n // Removes the stores\n channel.start.unbindStore(asyncLocalStorage);\n channel.asyncStart.unbindStore(asyncLocalStorage);\n },\n };\n}\n\nfunction endBoundSpan<TData extends object>(\n data: TracingChannelPayloadWithSpan<TData>,\n beforeSpanEnd: TracingChannelLifeCycleOptions<TData>['beforeSpanEnd'],\n): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n beforeSpanEnd?.(span, data);\n span.end();\n}\n\ntype ErrorInfo = {\n message: string | undefined;\n attributes: Record<string, string>;\n};\n\n/**\n * Best-effort message and attribute extraction for thrown/rejected values.\n */\nfunction getErrorInfo(error: unknown): ErrorInfo {\n const errorIsObject = isObjectLike(error);\n const raw = errorIsObject ? ('message' in error ? error.message : undefined) : error;\n\n // Leave the status message unset if not set (e.g. an `AggregateError` from\n // ECONNREFUSED, whose `.message` is empty). Otherwise cast to string.\n const message = raw ? String(raw) : undefined;\n const type = errorIsObject && 'name' in error ? String(error.name) : 'unknown';\n\n return {\n message,\n attributes: {\n [ERROR_TYPE]: type,\n },\n };\n}\n"],"names":["captureException","SPAN_STATUS_ERROR","getAsyncContextStrategy","getMainCarrier","DEBUG_BUILD","debug","getActiveSpan","isObjectLike","ERROR_TYPE"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AA,CAAM,YAAY,iBAAiB,CAAA;AAC3C,MAAA,OAAA,CAAQ,UAAA,CAAW,YAAY,iBAAiB,CAAA;AAAA,IAClD;AAAA,GACF;AACF;AAEA,SAAS,YAAA,CACP,MACA,aAAA,EACM;AACN,EAAA,MAAM,OAAO,IAAA,CAAK,WAAA;AAClB,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA;AAAA,EACF;AACA,EAAA,aAAA,GAAgB,MAAM,IAAI,CAAA;AAC1B,EAAA,IAAA,CAAK,GAAA,EAAI;AACX;AAUA,SAAS,aAAa,KAAA,EAA2B;AAC/C,EAAA,MAAM,aAAA,GAAgBC,kBAAa,KAAK,CAAA;AACxC,EAAA,MAAM,MAAM,aAAA,GAAiB,SAAA,IAAa,KAAA,GAAQ,KAAA,CAAM,UAAU,MAAA,GAAa,KAAA;AAI/E,EAAA,MAAM,OAAA,GAAU,GAAA,GAAM,MAAA,CAAO,GAAG,CAAA,GAAI,MAAA;AACpC,EAAA,MAAM,OAAO,aAAA,IAAiB,MAAA,IAAU,QAAQ,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,GAAI,SAAA;AAErE,EAAA,OAAO;AAAA,IACL,OAAA;AAAA,IACA,UAAA,EAAY;AAAA,MACV,CAACC,qBAAU,GAAG;AAAA;AAChB,GACF;AACF;;;;"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const core = require('@sentry/core');
|
|
4
|
+
|
|
5
|
+
function asString(value) {
|
|
6
|
+
return typeof value === "string" ? value : void 0;
|
|
7
|
+
}
|
|
8
|
+
function asNumber(value) {
|
|
9
|
+
return typeof value === "number" && !isNaN(value) ? value : void 0;
|
|
10
|
+
}
|
|
11
|
+
function sum(a, b) {
|
|
12
|
+
return a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
13
|
+
}
|
|
14
|
+
function safeStringify(value) {
|
|
15
|
+
if (typeof value === "string") {
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return JSON.stringify(value);
|
|
20
|
+
} catch {
|
|
21
|
+
return "[unserializable]";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function isReadableStream(value) {
|
|
25
|
+
return core.isObjectLike(value) && typeof value.pipeThrough === "function" && typeof value.getReader === "function";
|
|
26
|
+
}
|
|
27
|
+
function tapModelCallStream(stream, onFinal, onError) {
|
|
28
|
+
const reader = stream.getReader();
|
|
29
|
+
const state = { toolCalls: [] };
|
|
30
|
+
let text = "";
|
|
31
|
+
let settled = false;
|
|
32
|
+
const finalize = () => {
|
|
33
|
+
if (settled) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
settled = true;
|
|
37
|
+
if (text) {
|
|
38
|
+
state.text = text;
|
|
39
|
+
}
|
|
40
|
+
onFinal(state);
|
|
41
|
+
};
|
|
42
|
+
const fail = (error) => {
|
|
43
|
+
if (settled) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
settled = true;
|
|
47
|
+
onError(error);
|
|
48
|
+
};
|
|
49
|
+
return new ReadableStream({
|
|
50
|
+
async pull(controller) {
|
|
51
|
+
try {
|
|
52
|
+
const { done, value } = await reader.read();
|
|
53
|
+
if (done) {
|
|
54
|
+
finalize();
|
|
55
|
+
controller.close();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
text += accumulateChunk(state, value) ?? "";
|
|
59
|
+
controller.enqueue(value);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
fail(error);
|
|
62
|
+
controller.error(error);
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
cancel(reason) {
|
|
66
|
+
finalize();
|
|
67
|
+
return reader.cancel(reason);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
function accumulateChunk(state, chunk) {
|
|
72
|
+
if (!core.isObjectLike(chunk)) {
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
const {
|
|
76
|
+
type,
|
|
77
|
+
delta,
|
|
78
|
+
textDelta,
|
|
79
|
+
id,
|
|
80
|
+
modelId,
|
|
81
|
+
toolCallId,
|
|
82
|
+
toolName,
|
|
83
|
+
input,
|
|
84
|
+
args,
|
|
85
|
+
finishReason,
|
|
86
|
+
usage,
|
|
87
|
+
providerMetadata
|
|
88
|
+
} = chunk;
|
|
89
|
+
switch (type) {
|
|
90
|
+
case "text-delta": {
|
|
91
|
+
const textChunk = delta ?? textDelta;
|
|
92
|
+
return typeof textChunk === "string" ? textChunk : void 0;
|
|
93
|
+
}
|
|
94
|
+
case "tool-call":
|
|
95
|
+
state.toolCalls.push({ toolCallId, toolName, input: input ?? args });
|
|
96
|
+
return void 0;
|
|
97
|
+
case "response-metadata":
|
|
98
|
+
if (typeof id === "string") {
|
|
99
|
+
state.responseId = id;
|
|
100
|
+
}
|
|
101
|
+
if (typeof modelId === "string") {
|
|
102
|
+
state.responseModel = modelId;
|
|
103
|
+
}
|
|
104
|
+
return void 0;
|
|
105
|
+
case "finish":
|
|
106
|
+
state.finishReason = finishReason;
|
|
107
|
+
state.usage = usage;
|
|
108
|
+
if (providerMetadata !== void 0) {
|
|
109
|
+
state.providerMetadata = providerMetadata;
|
|
110
|
+
}
|
|
111
|
+
return void 0;
|
|
112
|
+
default:
|
|
113
|
+
return void 0;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
exports.asNumber = asNumber;
|
|
118
|
+
exports.asString = asString;
|
|
119
|
+
exports.isReadableStream = isReadableStream;
|
|
120
|
+
exports.safeStringify = safeStringify;
|
|
121
|
+
exports.sum = sum;
|
|
122
|
+
exports.tapModelCallStream = tapModelCallStream;
|
|
123
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.js","sources":["../../../src/vercel-ai/util.ts"],"sourcesContent":["/** Shared, state-free helpers for the Vercel AI (`ai`) channel subscribers, plus the streamed model-call tap. */\n\nimport { isObjectLike } from '@sentry/core';\n\n/** Narrow to a string, or `undefined` for anything else. */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Narrow to a finite number, or `undefined` for anything else (including `NaN`). */\nexport function asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && !isNaN(value) ? value : undefined;\n}\n\n/** Add two optional numbers, treating a missing operand as `0` but returning `undefined` when both are absent. */\nexport function sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/** Stringify a value, passing strings through and falling back to a placeholder on circular/unserializable input. */\nexport function safeStringify(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return '[unserializable]';\n }\n}\n\n/*\n * Streaming support for the `ai:telemetry` tracing channel.\n *\n * For a streamed model call (`doStream`) the SDK resolves the `languageModelCall` channel promise as\n * soon as it hands back the *unconsumed* stream — so `result.stream` is a `ReadableStream` and the\n * final usage / finish reason / output only arrive later, as the stream is drained (they ride the\n * stream's own `finish`/`text-delta`/`tool-call` chunks, never the channel context). The SDK\n * deliberately leaves `result` undefined on the `streamText`/`step` contexts and exposes the stream\n * only on the model call, expecting consumers to tap it themselves.\n * @see https://github.com/vercel/ai/pull/15660 (discussion: \"tee off and aggregate ourselves\")\n *\n * We replace `result.stream` with a passthrough that forwards every chunk untouched (so the SDK's own\n * consumption is unaffected) while accumulating the data we need, then hand the aggregate back once the\n * stream settles so the model-call span can be enriched and ended out-of-band.\n */\n\n/** The subset of a streamed provider chunk we read. Unknown chunk types are forwarded and ignored. */\ninterface StreamChunk {\n type?: unknown;\n delta?: unknown;\n // v4 text-delta chunks carry the text on `textDelta`; v5+ uses `delta`.\n textDelta?: unknown;\n id?: unknown;\n modelId?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n input?: unknown;\n args?: unknown;\n finishReason?: unknown;\n usage?: unknown;\n providerMetadata?: unknown;\n error?: unknown;\n}\n\n/** The aggregate handed back once a streamed model call finishes, in the shape `enrichSpanOnEnd` expects. */\nexport interface StreamedModelCallResult {\n text?: string;\n toolCalls: Array<Record<string, unknown>>;\n usage?: unknown;\n finishReason?: unknown;\n responseId?: string;\n responseModel?: string;\n providerMetadata?: unknown;\n}\n\n/** A minimal structural check — the streamed model call exposes a web `ReadableStream` on `result.stream`. */\nexport function isReadableStream(value: unknown): value is ReadableStream<unknown> {\n return (\n isObjectLike(value) &&\n typeof (value as { pipeThrough?: unknown }).pipeThrough === 'function' &&\n typeof (value as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * Wrap a streamed model call's `ReadableStream` so its chunks are observed as the SDK consumes them,\n * without altering what the SDK sees. Returns a replacement stream to swap onto `result.stream`.\n *\n * `onFinal` runs exactly once when the stream drains cleanly; `onError` runs exactly once if it errors\n * or is cancelled. Reading one source chunk per `pull` preserves the SDK's backpressure. The\n * `try/catch` around every read guarantees the owning span is always ended — a leaked open span on a\n * mid-stream failure would be worse than a slightly-less-enriched one.\n */\nexport function tapModelCallStream(\n stream: ReadableStream<unknown>,\n onFinal: (result: StreamedModelCallResult) => void,\n onError: (error: unknown) => void,\n): ReadableStream<unknown> {\n const reader = stream.getReader();\n const state: StreamedModelCallResult = { toolCalls: [] };\n let text = '';\n let settled = false;\n\n const finalize = (): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (text) {\n state.text = text;\n }\n onFinal(state);\n };\n\n const fail = (error: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n onError(error);\n };\n\n return new ReadableStream<unknown>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finalize();\n controller.close();\n\n return;\n }\n text += accumulateChunk(state, value) ?? '';\n controller.enqueue(value);\n } catch (error) {\n fail(error);\n controller.error(error);\n }\n },\n cancel(reason) {\n // Consumer stopped reading early (e.g. a `break` out of `for await`); close out the span with\n // whatever we have rather than leave it open. A non-error reason is a deliberate stop, not a failure.\n finalize();\n\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Fold a single streamed chunk into the running aggregate. Returns any text delta so the caller can\n * accumulate it (kept out of `state` until the end to avoid re-joining on every chunk).\n */\nfunction accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string | undefined {\n if (!isObjectLike(chunk)) {\n return undefined;\n }\n const {\n type,\n delta,\n textDelta,\n id,\n modelId,\n toolCallId,\n toolName,\n input,\n args,\n finishReason,\n usage,\n providerMetadata,\n } = chunk as StreamChunk;\n\n switch (type) {\n case 'text-delta': {\n const textChunk = delta ?? textDelta;\n return typeof textChunk === 'string' ? textChunk : undefined;\n }\n case 'tool-call':\n state.toolCalls.push({ toolCallId, toolName, input: input ?? args });\n\n return undefined;\n case 'response-metadata':\n if (typeof id === 'string') {\n state.responseId = id;\n }\n if (typeof modelId === 'string') {\n state.responseModel = modelId;\n }\n\n return undefined;\n case 'finish':\n state.finishReason = finishReason;\n state.usage = usage;\n if (providerMetadata !== undefined) {\n state.providerMetadata = providerMetadata;\n }\n\n return undefined;\n default:\n return undefined;\n }\n}\n"],"names":["isObjectLike"],"mappings":";;;;AAKO,SAAS,SAAS,KAAA,EAAoC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,MAAA;AAC7C;AAGO,SAAS,SAAS,KAAA,EAAoC;AAC3D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,KAAA,CAAM,KAAK,IAAI,KAAA,GAAQ,MAAA;AAC9D;AAGO,SAAS,GAAA,CAAI,GAAuB,CAAA,EAA2C;AACpF,EAAA,OAAO,MAAM,MAAA,IAAa,CAAA,KAAM,SAAY,MAAA,GAAA,CAAa,CAAA,IAAK,MAAM,CAAA,IAAK,CAAA,CAAA;AAC3E;AAGO,SAAS,cAAc,KAAA,EAAwB;AACpD,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KA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AA;AAAA,MACrB;AACA,MAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,QAAA,KAAA,CAAM,aAAA,GAAgB,OAAA;AAAA,MACxB;AAEA,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,QAAA;AACH,MAAA,KAAA,CAAM,YAAA,GAAe,YAAA;AACrB,MAAA,KAAA,CAAM,KAAA,GAAQ,KAAA;AACd,MAAA,IAAI,qBAAqB,MAAA,EAAW;AAClC,QAAA,KAAA,CAAM,gBAAA,GAAmB,gBAAA;AAAA,MAC3B;AAEA,MAAA,OAAO,MAAA;AAAA,IACT;AACE,MAAA,OAAO,MAAA;AAAA;AAEb;;;;;;;;;"}
|
|
@@ -4,6 +4,7 @@ const attributes = require('@sentry/conventions/attributes');
|
|
|
4
4
|
const op = require('@sentry/conventions/op');
|
|
5
5
|
const core = require('@sentry/core');
|
|
6
6
|
const tracingChannel = require('../tracing-channel.js');
|
|
7
|
+
const util = require('./util.js');
|
|
7
8
|
|
|
8
9
|
const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry";
|
|
9
10
|
const ORIGIN = "auto.vercelai.channel";
|
|
@@ -17,12 +18,20 @@ const VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = "vercel.ai.model.provider";
|
|
|
17
18
|
const VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = "vercel.ai.settings.maxRetries";
|
|
18
19
|
const operationIdByCallId = /* @__PURE__ */ new Map();
|
|
19
20
|
const toolDescriptionsByCallId = /* @__PURE__ */ new Map();
|
|
20
|
-
const
|
|
21
|
+
const invokeAgentSpanByCallId = /* @__PURE__ */ new Map();
|
|
22
|
+
const ROOT_OPERATION_TYPES = /* @__PURE__ */ new Set([
|
|
23
|
+
"generateText",
|
|
24
|
+
"streamText",
|
|
25
|
+
"generateObject",
|
|
26
|
+
"embed",
|
|
27
|
+
"embedMany",
|
|
28
|
+
"rerank"
|
|
29
|
+
]);
|
|
21
30
|
function clearOperationId(data) {
|
|
22
31
|
if (!ROOT_OPERATION_TYPES.has(data.type)) {
|
|
23
32
|
return;
|
|
24
33
|
}
|
|
25
|
-
const callId = asString(data.event.callId);
|
|
34
|
+
const callId = util.asString(data.event.callId);
|
|
26
35
|
if (callId) {
|
|
27
36
|
clearOperationCallId(callId);
|
|
28
37
|
}
|
|
@@ -30,6 +39,7 @@ function clearOperationId(data) {
|
|
|
30
39
|
function clearOperationCallId(callId) {
|
|
31
40
|
operationIdByCallId.delete(callId);
|
|
32
41
|
toolDescriptionsByCallId.delete(callId);
|
|
42
|
+
invokeAgentSpanByCallId.delete(callId);
|
|
33
43
|
}
|
|
34
44
|
function recordToolDescriptions(callId, tools) {
|
|
35
45
|
if (!callId || !Array.isArray(tools)) {
|
|
@@ -37,7 +47,7 @@ function recordToolDescriptions(callId, tools) {
|
|
|
37
47
|
}
|
|
38
48
|
let descriptions = toolDescriptionsByCallId.get(callId);
|
|
39
49
|
for (const tool of tools) {
|
|
40
|
-
if (
|
|
50
|
+
if (core.isObjectLike(tool) && typeof tool.name === "string" && typeof tool.description === "string") {
|
|
41
51
|
descriptions = descriptions ?? /* @__PURE__ */ new Map();
|
|
42
52
|
if (!descriptions.has(tool.name)) {
|
|
43
53
|
descriptions.set(tool.name, tool.description);
|
|
@@ -54,21 +64,16 @@ function resolveToolDescription(callId, toolName, tools) {
|
|
|
54
64
|
return fromMap;
|
|
55
65
|
}
|
|
56
66
|
if (Array.isArray(tools)) {
|
|
57
|
-
const match = tools.find((tool) =>
|
|
58
|
-
return
|
|
67
|
+
const match = tools.find((tool) => core.isObjectLike(tool) && tool.name === toolName);
|
|
68
|
+
return core.isObjectLike(match) ? util.asString(match.description) : void 0;
|
|
59
69
|
}
|
|
60
|
-
if (
|
|
70
|
+
if (core.isObjectLike(tools)) {
|
|
61
71
|
const tool = tools[toolName];
|
|
62
|
-
return
|
|
72
|
+
return core.isObjectLike(tool) ? util.asString(tool.description) : void 0;
|
|
63
73
|
}
|
|
64
74
|
return void 0;
|
|
65
75
|
}
|
|
66
|
-
let subscribed = false;
|
|
67
76
|
function subscribeVercelAiTracingChannel(tracingChannel$1, options = {}) {
|
|
68
|
-
if (subscribed) {
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
subscribed = true;
|
|
72
77
|
tracingChannel.bindTracingChannelToSpan(
|
|
73
78
|
tracingChannel$1(AI_SDK_TELEMETRY_TRACING_CHANNEL),
|
|
74
79
|
(data) => createSpanFromMessage(data, options),
|
|
@@ -78,20 +83,94 @@ function subscribeVercelAiTracingChannel(tracingChannel$1, options = {}) {
|
|
|
78
83
|
beforeSpanEnd: (span, data) => {
|
|
79
84
|
enrichSpanOnEnd(span, data, options);
|
|
80
85
|
clearOperationId(data);
|
|
81
|
-
}
|
|
86
|
+
},
|
|
87
|
+
// A streamed model call resolves before its stream is drained, so we tap the stream, keep the
|
|
88
|
+
// span open, and end it (via `end`) once the final usage/finish/output chunks arrive.
|
|
89
|
+
deferSpanEnd: ({ data, end }) => deferStreamedModelCallEnd(data, options, end)
|
|
82
90
|
}
|
|
83
91
|
);
|
|
84
92
|
}
|
|
93
|
+
function deferStreamedModelCallEnd(data, options, end) {
|
|
94
|
+
if (data.type !== "languageModelCall" || !core.isObjectLike(data.result)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
const result = data.result;
|
|
98
|
+
const stream = result.stream;
|
|
99
|
+
if (!util.isReadableStream(stream)) {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
const callId = util.asString(data.event.callId);
|
|
103
|
+
const { recordOutputs } = getRecordingOptions(data.event, options);
|
|
104
|
+
result.stream = util.tapModelCallStream(
|
|
105
|
+
stream,
|
|
106
|
+
(final) => {
|
|
107
|
+
data.result = { ...result, ...streamedResultToChannelResult(final) };
|
|
108
|
+
end();
|
|
109
|
+
enrichInvokeAgentFromStream(callId, final, recordOutputs);
|
|
110
|
+
},
|
|
111
|
+
(error) => end(error)
|
|
112
|
+
);
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
function streamedResultToChannelResult(final) {
|
|
116
|
+
const content = [];
|
|
117
|
+
if (final.text) {
|
|
118
|
+
content.push({ type: "text", text: final.text });
|
|
119
|
+
}
|
|
120
|
+
for (const toolCall of final.toolCalls) {
|
|
121
|
+
content.push({ type: "tool-call", ...toolCall });
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
content,
|
|
125
|
+
...final.usage !== void 0 ? { usage: final.usage } : {},
|
|
126
|
+
...final.finishReason !== void 0 ? { finishReason: final.finishReason } : {},
|
|
127
|
+
...final.providerMetadata !== void 0 ? { providerMetadata: final.providerMetadata } : {},
|
|
128
|
+
...final.responseId || final.responseModel ? {
|
|
129
|
+
response: {
|
|
130
|
+
...final.responseId ? { id: final.responseId } : {},
|
|
131
|
+
...final.responseModel ? { modelId: final.responseModel } : {}
|
|
132
|
+
}
|
|
133
|
+
} : {}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function enrichInvokeAgentFromStream(callId, final, recordOutputs) {
|
|
137
|
+
const span = callId ? invokeAgentSpanByCallId.get(callId) : void 0;
|
|
138
|
+
if (!span) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const usage = core.isObjectLike(final.usage) ? final.usage : void 0;
|
|
142
|
+
if (usage) {
|
|
143
|
+
const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
|
|
144
|
+
const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
|
|
145
|
+
addTokensToSpan(span, attributes.GEN_AI_USAGE_INPUT_TOKENS, input);
|
|
146
|
+
addTokensToSpan(span, attributes.GEN_AI_USAGE_OUTPUT_TOKENS, output);
|
|
147
|
+
addTokensToSpan(span, attributes.GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? util.sum(input, output));
|
|
148
|
+
}
|
|
149
|
+
if (recordOutputs) {
|
|
150
|
+
const parts = partsFromTextAndToolCalls(final.text, final.toolCalls);
|
|
151
|
+
const outputMessages = buildOutputMessages(parts, getFinishReason({ finishReason: final.finishReason }));
|
|
152
|
+
if (outputMessages) {
|
|
153
|
+
span.setAttribute(attributes.GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function addTokensToSpan(span, attribute, value) {
|
|
158
|
+
if (value === void 0) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const current = core.spanToJSON(span).data[attribute];
|
|
162
|
+
span.setAttribute(attribute, (typeof current === "number" ? current : 0) + value);
|
|
163
|
+
}
|
|
85
164
|
function createSpanFromMessage(data, channelOptions) {
|
|
86
165
|
const { type, event } = data;
|
|
87
166
|
if (type === "step" || !event || typeof event !== "object") {
|
|
88
167
|
return void 0;
|
|
89
168
|
}
|
|
90
169
|
const { recordInputs, enableTruncation } = getRecordingOptions(event, channelOptions);
|
|
91
|
-
const provider = asString(event.provider);
|
|
92
|
-
const modelId = asString(event.modelId);
|
|
93
|
-
const callId = asString(event.callId);
|
|
94
|
-
const maxRetries = asNumber(event.maxRetries);
|
|
170
|
+
const provider = util.asString(event.provider);
|
|
171
|
+
const modelId = util.asString(event.modelId);
|
|
172
|
+
const callId = util.asString(event.callId);
|
|
173
|
+
const maxRetries = util.asNumber(event.maxRetries);
|
|
95
174
|
if (recordInputs) {
|
|
96
175
|
recordToolDescriptions(callId, event.tools);
|
|
97
176
|
}
|
|
@@ -104,6 +183,7 @@ function createSpanFromMessage(data, channelOptions) {
|
|
|
104
183
|
switch (type) {
|
|
105
184
|
case "generateText":
|
|
106
185
|
case "streamText":
|
|
186
|
+
case "generateObject":
|
|
107
187
|
return buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncation, callId, type === "streamText");
|
|
108
188
|
case "languageModelCall":
|
|
109
189
|
return buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId);
|
|
@@ -114,7 +194,7 @@ function createSpanFromMessage(data, channelOptions) {
|
|
|
114
194
|
const input = type === "embedMany" ? event.values : event.value;
|
|
115
195
|
return startGenAiSpan(GEN_AI_EMBEDDINGS_OPERATION, modelId, {
|
|
116
196
|
...baseAttributes,
|
|
117
|
-
...recordInputs && input !== void 0 ? { [attributes.GEN_AI_EMBEDDINGS_INPUT]: safeStringify(input) } : {}
|
|
197
|
+
...recordInputs && input !== void 0 ? { [attributes.GEN_AI_EMBEDDINGS_INPUT]: util.safeStringify(input) } : {}
|
|
118
198
|
});
|
|
119
199
|
}
|
|
120
200
|
case "rerank":
|
|
@@ -131,18 +211,22 @@ function startGenAiSpan(operation, suffix, attributes$1) {
|
|
|
131
211
|
});
|
|
132
212
|
}
|
|
133
213
|
function buildInvokeAgentSpan(event, baseAttributes, recordInputs, enableTruncation, callId, isStream) {
|
|
134
|
-
const functionId = asString(event.functionId);
|
|
135
|
-
const operationId = asString(event.operationId) ?? (isStream ? "ai.streamText" : "ai.generateText");
|
|
214
|
+
const functionId = util.asString(event.functionId);
|
|
215
|
+
const operationId = util.asString(event.operationId) ?? (isStream ? "ai.streamText" : "ai.generateText");
|
|
136
216
|
if (callId) {
|
|
137
217
|
operationIdByCallId.set(callId, { operationId, isStream });
|
|
138
218
|
}
|
|
139
|
-
|
|
219
|
+
const span = startGenAiSpan(op.GEN_AI_INVOKE_AGENT_SPAN_OP, functionId, {
|
|
140
220
|
...baseAttributes,
|
|
141
221
|
[VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,
|
|
142
222
|
[attributes.GEN_AI_RESPONSE_STREAMING]: isStream,
|
|
143
223
|
...functionId ? { [attributes.GEN_AI_FUNCTION_ID]: functionId } : {},
|
|
144
224
|
...recordInputs ? buildInputMessageAttributes(event, enableTruncation) : {}
|
|
145
225
|
});
|
|
226
|
+
if (isStream && callId) {
|
|
227
|
+
invokeAgentSpanByCallId.set(callId, span);
|
|
228
|
+
}
|
|
229
|
+
return span;
|
|
146
230
|
}
|
|
147
231
|
function buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncation, callId, modelId) {
|
|
148
232
|
const parent = callId ? operationIdByCallId.get(callId) : void 0;
|
|
@@ -151,45 +235,45 @@ function buildModelCallSpan(event, baseAttributes, recordInputs, enableTruncatio
|
|
|
151
235
|
...baseAttributes,
|
|
152
236
|
[VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId,
|
|
153
237
|
...recordInputs ? buildInputMessageAttributes(event, enableTruncation) : {},
|
|
154
|
-
...recordInputs && Array.isArray(event.tools) ? { [attributes.GEN_AI_REQUEST_AVAILABLE_TOOLS]: safeStringify(event.tools) } : {}
|
|
238
|
+
...recordInputs && Array.isArray(event.tools) ? { [attributes.GEN_AI_REQUEST_AVAILABLE_TOOLS]: util.safeStringify(event.tools) } : {}
|
|
155
239
|
});
|
|
156
240
|
}
|
|
157
241
|
function buildToolSpan(event, recordInputs) {
|
|
158
|
-
const toolCall =
|
|
159
|
-
const toolName = asString(toolCall.toolName);
|
|
160
|
-
const toolCallId = asString(event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
242
|
+
const toolCall = core.isObjectLike(event.toolCall) ? event.toolCall : {};
|
|
243
|
+
const toolName = util.asString(toolCall.toolName);
|
|
244
|
+
const toolCallId = util.asString(event.toolCallId) ?? util.asString(toolCall.toolCallId);
|
|
161
245
|
const toolInput = toolCall.input ?? toolCall.args;
|
|
162
|
-
const description = recordInputs && toolName ? resolveToolDescription(asString(event.callId), toolName, event.tools) : void 0;
|
|
246
|
+
const description = recordInputs && toolName ? resolveToolDescription(util.asString(event.callId), toolName, event.tools) : void 0;
|
|
163
247
|
return startGenAiSpan(op.GEN_AI_EXECUTE_TOOL_SPAN_OP, toolName, {
|
|
164
248
|
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
|
|
165
249
|
[attributes.GEN_AI_TOOL_TYPE]: "function",
|
|
166
250
|
...toolName ? { [attributes.GEN_AI_TOOL_NAME]: toolName } : {},
|
|
167
251
|
...toolCallId ? { [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId } : {},
|
|
168
252
|
...description ? { [GEN_AI_TOOL_DESCRIPTION_ATTRIBUTE]: description } : {},
|
|
169
|
-
...recordInputs && toolInput !== void 0 ? { [attributes.GEN_AI_TOOL_INPUT]: safeStringify(toolInput) } : {}
|
|
253
|
+
...recordInputs && toolInput !== void 0 ? { [attributes.GEN_AI_TOOL_INPUT]: util.safeStringify(toolInput) } : {}
|
|
170
254
|
});
|
|
171
255
|
}
|
|
172
256
|
function enrichSpanOnEnd(span, data, channelOptions) {
|
|
173
257
|
const { type, result } = data;
|
|
174
|
-
if (!
|
|
258
|
+
if (!core.isObjectLike(result)) {
|
|
175
259
|
return;
|
|
176
260
|
}
|
|
177
261
|
const { recordOutputs } = getRecordingOptions(data.event, channelOptions);
|
|
178
262
|
if (type === "executeTool") {
|
|
179
263
|
if (recordOutputs) {
|
|
180
|
-
span.setAttribute(attributes.GEN_AI_TOOL_OUTPUT, safeStringify(result.output ?? result));
|
|
264
|
+
span.setAttribute(attributes.GEN_AI_TOOL_OUTPUT, util.safeStringify(result.output ?? result));
|
|
181
265
|
}
|
|
182
|
-
const output =
|
|
266
|
+
const output = core.isObjectLike(result.output) ? result.output : void 0;
|
|
183
267
|
if (output?.type === "tool-error") {
|
|
184
268
|
captureToolError(span, data, output.error);
|
|
185
269
|
}
|
|
186
270
|
return;
|
|
187
271
|
}
|
|
188
|
-
const usage =
|
|
272
|
+
const usage = core.isObjectLike(result.usage) ? result.usage : void 0;
|
|
189
273
|
if (usage) {
|
|
190
|
-
const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.tokens);
|
|
191
|
-
const outputTokens = tokenCount(usage.outputTokens);
|
|
192
|
-
const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens);
|
|
274
|
+
const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens);
|
|
275
|
+
const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens);
|
|
276
|
+
const totalTokens = tokenCount(usage.totalTokens) ?? util.sum(inputTokens, outputTokens);
|
|
193
277
|
if (inputTokens !== void 0) {
|
|
194
278
|
span.setAttribute(attributes.GEN_AI_USAGE_INPUT_TOKENS, inputTokens);
|
|
195
279
|
}
|
|
@@ -202,14 +286,14 @@ function enrichSpanOnEnd(span, data, channelOptions) {
|
|
|
202
286
|
}
|
|
203
287
|
const finishReason = getFinishReason(result);
|
|
204
288
|
if (finishReason && type === "languageModelCall") {
|
|
205
|
-
span.setAttribute(attributes.GEN_AI_RESPONSE_FINISH_REASONS, safeStringify([finishReason]));
|
|
289
|
+
span.setAttribute(attributes.GEN_AI_RESPONSE_FINISH_REASONS, util.safeStringify([finishReason]));
|
|
206
290
|
}
|
|
207
|
-
const response =
|
|
208
|
-
const responseId = asString(response?.id) ?? asString(result.responseId);
|
|
291
|
+
const response = core.isObjectLike(result.response) ? result.response : void 0;
|
|
292
|
+
const responseId = util.asString(response?.id) ?? util.asString(result.responseId);
|
|
209
293
|
if (responseId) {
|
|
210
294
|
span.setAttribute(attributes.GEN_AI_RESPONSE_ID, responseId);
|
|
211
295
|
}
|
|
212
|
-
const responseModel = asString(response?.modelId) ?? asString(data.event.modelId);
|
|
296
|
+
const responseModel = util.asString(response?.modelId) ?? util.asString(data.event.modelId);
|
|
213
297
|
if (responseModel) {
|
|
214
298
|
span.setAttribute(attributes.GEN_AI_RESPONSE_MODEL, responseModel);
|
|
215
299
|
}
|
|
@@ -235,30 +319,30 @@ function getFinishReason(result) {
|
|
|
235
319
|
if (typeof finishReason === "string") {
|
|
236
320
|
return finishReason;
|
|
237
321
|
}
|
|
238
|
-
return
|
|
322
|
+
return core.isObjectLike(finishReason) ? util.asString(finishReason.unified) : void 0;
|
|
239
323
|
}
|
|
240
324
|
function tokenCount(value) {
|
|
241
|
-
return asNumber(value) ?? (
|
|
325
|
+
return util.asNumber(value) ?? (core.isObjectLike(value) ? util.asNumber(value.total) : void 0);
|
|
242
326
|
}
|
|
243
327
|
function buildOutputMessages(parts, finishReason) {
|
|
244
328
|
if (!parts.length) {
|
|
245
329
|
return void 0;
|
|
246
330
|
}
|
|
247
|
-
return safeStringify([{ role: "assistant", parts, finish_reason: normalizeFinishReason(finishReason) }]);
|
|
331
|
+
return util.safeStringify([{ role: "assistant", parts, finish_reason: normalizeFinishReason(finishReason) }]);
|
|
248
332
|
}
|
|
249
333
|
function toolCallPart(toolCall) {
|
|
250
334
|
const args = toolCall.input ?? toolCall.args;
|
|
251
335
|
return {
|
|
252
336
|
type: "tool_call",
|
|
253
|
-
id: asString(toolCall.toolCallId),
|
|
254
|
-
name: asString(toolCall.toolName),
|
|
255
|
-
arguments: typeof args === "string" ? args : safeStringify(args ?? {})
|
|
337
|
+
id: util.asString(toolCall.toolCallId),
|
|
338
|
+
name: util.asString(toolCall.toolName),
|
|
339
|
+
arguments: typeof args === "string" ? args : util.safeStringify(args ?? {})
|
|
256
340
|
};
|
|
257
341
|
}
|
|
258
342
|
function partsFromContent(content) {
|
|
259
343
|
const parts = [];
|
|
260
344
|
for (const item of content) {
|
|
261
|
-
if (!
|
|
345
|
+
if (!core.isObjectLike(item)) {
|
|
262
346
|
continue;
|
|
263
347
|
}
|
|
264
348
|
if (item.type === "text" && typeof item.text === "string") {
|
|
@@ -276,7 +360,7 @@ function partsFromTextAndToolCalls(text, toolCalls) {
|
|
|
276
360
|
}
|
|
277
361
|
if (Array.isArray(toolCalls)) {
|
|
278
362
|
for (const toolCall of toolCalls) {
|
|
279
|
-
if (
|
|
363
|
+
if (core.isObjectLike(toolCall)) {
|
|
280
364
|
parts.push(toolCallPart(toolCall));
|
|
281
365
|
}
|
|
282
366
|
}
|
|
@@ -288,9 +372,9 @@ function captureToolError(span, data, error) {
|
|
|
288
372
|
code: core.SPAN_STATUS_ERROR,
|
|
289
373
|
message: error instanceof Error ? error.message : "tool_error"
|
|
290
374
|
});
|
|
291
|
-
const toolCall =
|
|
292
|
-
const toolName = asString(toolCall.toolName);
|
|
293
|
-
const toolCallId = asString(data.event.toolCallId) ?? asString(toolCall.toolCallId);
|
|
375
|
+
const toolCall = core.isObjectLike(data.event.toolCall) ? data.event.toolCall : {};
|
|
376
|
+
const toolName = util.asString(toolCall.toolName);
|
|
377
|
+
const toolCallId = util.asString(data.event.toolCallId) ?? util.asString(toolCall.toolCallId);
|
|
294
378
|
core.withScope((scope) => {
|
|
295
379
|
scope.setContext("trace", core.spanToTraceContext(span));
|
|
296
380
|
if (toolName) {
|
|
@@ -327,43 +411,23 @@ function resolveRecording(integrationOption, perCallOption, globalDefault) {
|
|
|
327
411
|
}
|
|
328
412
|
function buildInputMessageAttributes(event, enableTruncation) {
|
|
329
413
|
const attributes$1 = {};
|
|
330
|
-
const instructions = asString(event.instructions);
|
|
414
|
+
const instructions = util.asString(event.instructions);
|
|
331
415
|
if (instructions) {
|
|
332
|
-
attributes$1[core.GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE] = safeStringify([{ type: "text", content: instructions }]);
|
|
416
|
+
attributes$1[core.GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE] = util.safeStringify([{ type: "text", content: instructions }]);
|
|
333
417
|
}
|
|
334
418
|
const messages = event.messages ?? event.prompt;
|
|
335
419
|
if (messages !== void 0) {
|
|
336
|
-
attributes$1[attributes.GEN_AI_INPUT_MESSAGES] = enableTruncation ? core.getTruncatedJsonString(messages) : safeStringify(messages);
|
|
420
|
+
attributes$1[attributes.GEN_AI_INPUT_MESSAGES] = enableTruncation ? core.getTruncatedJsonString(messages) : util.safeStringify(messages);
|
|
337
421
|
attributes$1[core.GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE] = Array.isArray(messages) ? messages.length : 1;
|
|
338
422
|
}
|
|
339
423
|
return attributes$1;
|
|
340
424
|
}
|
|
341
|
-
function asString(value) {
|
|
342
|
-
return typeof value === "string" ? value : void 0;
|
|
343
|
-
}
|
|
344
|
-
function asNumber(value) {
|
|
345
|
-
return typeof value === "number" && !isNaN(value) ? value : void 0;
|
|
346
|
-
}
|
|
347
|
-
function sum(a, b) {
|
|
348
|
-
return a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
349
|
-
}
|
|
350
|
-
function isRecord(value) {
|
|
351
|
-
return typeof value === "object" && value !== null;
|
|
352
|
-
}
|
|
353
|
-
function safeStringify(value) {
|
|
354
|
-
if (typeof value === "string") {
|
|
355
|
-
return value;
|
|
356
|
-
}
|
|
357
|
-
try {
|
|
358
|
-
return JSON.stringify(value);
|
|
359
|
-
} catch {
|
|
360
|
-
return "[unserializable]";
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
425
|
|
|
426
|
+
exports.captureToolError = captureToolError;
|
|
364
427
|
exports.clearOperationCallId = clearOperationCallId;
|
|
365
428
|
exports.clearOperationId = clearOperationId;
|
|
366
429
|
exports.createSpanFromMessage = createSpanFromMessage;
|
|
367
430
|
exports.enrichSpanOnEnd = enrichSpanOnEnd;
|
|
431
|
+
exports.streamedResultToChannelResult = streamedResultToChannelResult;
|
|
368
432
|
exports.subscribeVercelAiTracingChannel = subscribeVercelAiTracingChannel;
|
|
369
433
|
//# sourceMappingURL=vercel-ai-dc-subscriber.js.map
|