diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json index a2256c9a2803..34bc67bc4f56 100644 --- a/.oxlintrc.base.json +++ b/.oxlintrc.base.json @@ -94,7 +94,8 @@ "files": ["**/src/**/*.ts", "**/src/**/*.tsx", "**/addon/**/*.ts"], "rules": { "sdk/no-unguarded-span-apis": "error", - "sdk/no-unguarded-debug-logs": "error" + "sdk/no-unguarded-debug-logs": "error", + "sdk/require-define-integration": "error" } }, { diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f3bcce60f59..d2a731c60c07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +## 11.20.0 + +### Important Changes + +- **feat(nestjs): Trace WebSocket messages on Nest 12 ([#26768](https://github.com/getsentry/sentry-javascript/pull/26768))** + +On Nest 12 and newer, the SDK now creates a `websocket` span for each WebSocket message a gateway handles, named `WS `. Each message starts its own trace. + +### Other Changes + +- feat(bundler-plugins): Add the call-site rewriter core ([#26101](https://github.com/getsentry/sentry-javascript/pull/26101)) +- feat(core): Add experimental minification-independent function fingerprint ([#26840](https://github.com/getsentry/sentry-javascript/pull/26840)) +- feat(core): Report library functions in integration options without a fingerprint ([#26898](https://github.com/getsentry/sentry-javascript/pull/26898)) +- fix(core): Clear pending idle span timers when the span ends ([#26938](https://github.com/getsentry/sentry-javascript/pull/26938)) +- fix(nestjs): Register SentryTracingInterceptor only once ([#26775](https://github.com/getsentry/sentry-javascript/pull/26775)) +- fix(nuxt): Avoid duplicate spans when Nitro tracing channels are on ([#26928](https://github.com/getsentry/sentry-javascript/pull/26928)) +- fix(server-utils): Sum Vercel AI reasoning tokens onto invoke_agent spans ([#26904](https://github.com/getsentry/sentry-javascript/pull/26904)) +- fix(tanstackstart-react): Report the TanStack Start SDK name with the Cloudflare Vite plugin ([#26925](https://github.com/getsentry/sentry-javascript/pull/26925)) + +
+ Internal Changes + +- chore(lint): Require integrations to be created with `defineIntegration` ([#26937](https://github.com/getsentry/sentry-javascript/pull/26937)) +- docs: Add a checklist for new major releases ([#26926](https://github.com/getsentry/sentry-javascript/pull/26926)) + +
+ +Work in this release was contributed by @faizansaiyed123. Thank you for your contribution! + ## 11.19.0 - docs(aws-lambda): Fix the Lambda layer link in the v11 migration guide ([#26912](https://github.com/getsentry/sentry-javascript/pull/26912)) diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/package.json b/dev-packages/e2e-tests/test-applications/nestjs-websockets/package.json index 9e500e740e84..ce6169c4698c 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/package.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/package.json @@ -2,19 +2,20 @@ "name": "nestjs-websockets", "version": "0.0.1", "private": true, + "type": "module", "scripts": { "build": "nest build", - "start": "nest start", + "start": "node --import ./dist/instrument.js dist/main.js", "test": "playwright test", "test:build": "pnpm install && pnpm build", "test:assert": "pnpm test" }, "dependencies": { - "@nestjs/common": "^11.0.0", - "@nestjs/core": "^11.0.0", - "@nestjs/platform-express": "^11.0.0", - "@nestjs/websockets": "^11.0.0", - "@nestjs/platform-socket.io": "^11.0.0", + "@nestjs/common": "12.5.1", + "@nestjs/core": "12.5.1", + "@nestjs/platform-express": "12.5.1", + "@nestjs/websockets": "12.5.1", + "@nestjs/platform-socket.io": "12.5.1", "@sentry/nestjs": "file:../../packed/sentry-nestjs-packed.tgz", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.1" @@ -22,9 +23,9 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@nestjs/cli": "^11.0.0", - "@types/node": "^18.19.1", + "@nestjs/cli": "^12.0.0", + "@types/node": "^22.0.0", "socket.io-client": "^4.0.0", - "typescript": "~5.0.0" + "typescript": "~5.9.0" } } diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.gateway.ts b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.gateway.ts index 08eb7475cea8..c995fdcefb5b 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.gateway.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.gateway.ts @@ -26,3 +26,16 @@ export class AppGateway { return { event: 'capture-response', data: { success: true } }; } } + +@WebSocketGateway({ namespace: '/events' }) +export class EventsGateway { + @SubscribeMessage('test-transaction') + handleTestTransaction() { + return { event: 'test-transaction-response', data: { success: true } }; + } + + @SubscribeMessage('test-transaction-error') + handleTestTransactionError() { + throw new Error('WebSocket handler failed'); + } +} diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.module.ts b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.module.ts index 96386d3cf29f..1a8841086dc8 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.module.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/app.module.ts @@ -1,8 +1,8 @@ import { Module } from '@nestjs/common'; import { APP_FILTER } from '@nestjs/core'; import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup'; -import { AppController } from './app.controller'; -import { AppGateway } from './app.gateway'; +import { AppController } from './app.controller.js'; +import { AppGateway, EventsGateway } from './app.gateway.js'; @Module({ imports: [SentryModule.forRoot()], @@ -13,6 +13,7 @@ import { AppGateway } from './app.gateway'; useClass: SentryGlobalFilter, }, AppGateway, + EventsGateway, ], }) export class AppModule {} diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/main.ts b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/main.ts index 71ce685f4d61..b9a3b365fa12 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/main.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/src/main.ts @@ -1,9 +1,10 @@ -// Import this first -import './instrument'; +// Loaded via `node --import ./dist/instrument.js` so Sentry's ESM instrumentation +// hooks register before any application module is linked. Kept here too so the +// file is part of the build output (ESM caches it, so it is not re-executed). +import './instrument.js'; -// Import other modules import { NestFactory } from '@nestjs/core'; -import { AppModule } from './app.module'; +import { AppModule } from './app.module.js'; const PORT = 3030; diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/tests/transactions.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tests/transactions.test.ts index 6cebef2405d2..a3040144fcf1 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/tests/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tests/transactions.test.ts @@ -1,5 +1,6 @@ import { expect, test } from '@playwright/test'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { io } from 'socket.io-client'; test('Sends an HTTP segment span', async ({ baseURL }) => { const spanPromise = waitForStreamedSpan('nestjs-websockets', span => { @@ -13,3 +14,89 @@ test('Sends an HTTP segment span', async ({ baseURL }) => { expect(getSpanOp(span)).toBe('http.server'); expect(span.status).toBe('ok'); }); + +test('Marks WebSocket segment spans as failed when the handler errors', async ({ baseURL }) => { + const socket = io(`${baseURL}/events`); + + try { + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); + + const spanPromise = waitForStreamedSpan('nestjs-websockets', span => { + return span.is_segment && span.name === 'WS /events test-transaction-error'; + }); + const exceptionPromise = new Promise(resolve => { + socket.once('exception', () => resolve()); + }); + + socket.emit('test-transaction-error', {}); + + const [span] = await Promise.all([spanPromise, exceptionPromise]); + + expect(span.is_segment).toBe(true); + expect(getSpanOp(span)).toBe('websocket'); + expect(span.name).toBe('WS /events test-transaction-error'); + expect(span.status).toBe('error'); + } finally { + socket.disconnect(); + } +}); + +test('Names WebSocket segment spans with the Socket.IO namespace and message pattern', async ({ baseURL }) => { + const socket = io(`${baseURL}/events`); + + try { + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); + + const spanPromise = waitForStreamedSpan('nestjs-websockets', span => { + return span.is_segment && span.name === 'WS /events test-transaction'; + }); + const responsePromise = new Promise(resolve => { + socket.once('test-transaction-response', () => resolve()); + }); + + socket.emit('test-transaction', {}); + + const [span] = await Promise.all([spanPromise, responsePromise]); + + expect(span.is_segment).toBe(true); + expect(getSpanOp(span)).toBe('websocket'); + expect(span.name).toBe('WS /events test-transaction'); + expect(span.attributes['websocket.event.name']).toEqual({ type: 'string', value: 'test-transaction' }); + expect(span.attributes['websocket.namespace']).toEqual({ type: 'string', value: '/events' }); + } finally { + socket.disconnect(); + } +}); + +test('Starts a new trace for each WebSocket message on the same connection', async ({ baseURL }) => { + const socket = io(`${baseURL}/events`); + + try { + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); + + const firstSpanPromise = waitForStreamedSpan('nestjs-websockets', span => { + return span.is_segment && span.name === 'WS /events test-transaction'; + }); + socket.emit('test-transaction', {}); + const firstSpan = await firstSpanPromise; + + const secondSpanPromise = waitForStreamedSpan('nestjs-websockets', span => { + return span.is_segment && span.name === 'WS /events test-transaction' && span.trace_id !== firstSpan.trace_id; + }); + socket.emit('test-transaction', {}); + const secondSpan = await secondSpanPromise; + + expect(secondSpan.trace_id).not.toBe(firstSpan.trace_id); + } finally { + socket.disconnect(); + } +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.build.json b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.build.json new file mode 100644 index 000000000000..ee15ab743183 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "tests", "dist"] +} diff --git a/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.json b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.json index cf79f029c781..e419606d3010 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-websockets/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "module": "commonjs", + "module": "NodeNext", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, @@ -17,6 +17,6 @@ "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false, - "moduleResolution": "Node16" + "moduleResolution": "NodeNext" } } diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/scenario-reasoning-tokens.mjs b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/scenario-reasoning-tokens.mjs new file mode 100644 index 000000000000..e23c93869077 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/scenario-reasoning-tokens.mjs @@ -0,0 +1,124 @@ +import * as Sentry from '@sentry/node'; +import { generateText, simulateReadableStream, stepCountIs, streamText, tool } from 'ai'; +import { MockLanguageModelV2 } from 'ai/test'; +import { z } from 'zod'; + +// `@ai-sdk/google` 2.x reports candidate-only `outputTokens` and a separate `reasoningTokens`, with the +// raw counts in `providerMetadata`. Two steps reason 80 and 100 tokens. +const STEPS = [ + { candidates: 20, thoughts: 80, finishReason: 'tool-calls' }, + { candidates: 20, thoughts: 100, finishReason: 'stop' }, +]; + +function usage({ candidates, thoughts }) { + return { + inputTokens: 10, + outputTokens: candidates, + totalTokens: 10 + candidates + thoughts, + reasoningTokens: thoughts, + }; +} + +function providerMetadata({ candidates, thoughts }) { + return { + google: { + usageMetadata: { + promptTokenCount: 10, + candidatesTokenCount: candidates, + thoughtsTokenCount: thoughts, + totalTokenCount: 10 + candidates + thoughts, + }, + }, + }; +} + +const tools = { + getWeather: tool({ + description: 'Get the current weather for a location', + inputSchema: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`, + }), +}; + +const toolCall = { + type: 'tool-call', + toolCallId: 'call-1', + toolName: 'getWeather', + input: JSON.stringify({ location: 'San Francisco' }), +}; + +async function run() { + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + let generateCalls = 0; + await generateText({ + model: new MockLanguageModelV2({ + doGenerate: async () => { + const step = STEPS[generateCalls++]; + return { + finishReason: step.finishReason, + usage: usage(step), + content: generateCalls === 1 ? [toolCall] : [{ type: 'text', text: 'Sunny, 72°F.' }], + warnings: [], + providerMetadata: providerMetadata(step), + }; + }, + }), + tools, + stopWhen: stepCountIs(5), + prompt: 'What is the weather in San Francisco?', + }); + + let streamCalls = 0; + const result = streamText({ + model: new MockLanguageModelV2({ + doStream: async () => { + const step = STEPS[streamCalls++]; + const content = + streamCalls === 1 + ? [toolCall] + : [ + { type: 'text-start', id: '0' }, + { type: 'text-delta', id: '0', delta: 'Sunny, 72°F.' }, + { type: 'text-end', id: '0' }, + ]; + return { + stream: simulateReadableStream({ + chunks: [ + { type: 'stream-start', warnings: [] }, + ...content, + { + type: 'finish', + finishReason: step.finishReason, + usage: usage(step), + providerMetadata: providerMetadata(step), + }, + ], + }), + }; + }, + }), + tools, + stopWhen: stepCountIs(5), + prompt: 'What is the weather in San Francisco?', + }); + for await (const _part of result.fullStream) { + void _part; + } + + // `@ai-sdk/openai` 2.x reports reasoning only in the usage, inside an output that includes it. + await generateText({ + model: new MockLanguageModelV2({ + doGenerate: async () => ({ + finishReason: 'stop', + usage: { inputTokens: 10, outputTokens: 50, totalTokens: 60, reasoningTokens: 30 }, + content: [{ type: 'text', text: 'Sunny.' }], + warnings: [], + providerMetadata: { openai: {} }, + }), + }), + prompt: 'What is the weather in San Francisco?', + }); + }); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts index 7c82eb3f9a91..86524a907587 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v5/test.ts @@ -14,10 +14,12 @@ import { GEN_AI_TOOL_NAME, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, SENTRY_OP, SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; +import { GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../../../packages/server-utils/src/ai/core/gen-ai-attributes'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; import { getStringAttributeValue } from '../../../../utils'; @@ -27,6 +29,57 @@ describe('Vercel AI integration (v5)', () => { cleanupChildProcesses(); }); + createEsmAndCjsTests( + __dirname, + 'scenario-reasoning-tokens.mjs', + 'instrument.mjs', + (createRunner, test) => { + test('records reasoning tokens on model calls and sums them onto invoke_agent spans', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai', + ); + const byOp = (op: string) => spans.filter(span => span.attributes[SENTRY_OP]?.value === op); + const tokens = (span: (typeof spans)[number]) => [ + span.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value, + span.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value, + ]; + + const sorted = (op: string) => + byOp(op) + .map(tokens) + .sort((a, b) => Number(a[0]) - Number(b[0])); + + // Each Google step's output gains its reasoning, which `@ai-sdk/google` 2.x reports separately. + expect(sorted(GEN_AI_GENERATE_CONTENT)).toEqual([ + [50, 30], + [100, 80], + [100, 80], + [120, 100], + [120, 100], + ]); + // One generateText and one streamText operation over the same two Google steps, then one OpenAI call. + expect(sorted(GEN_AI_INVOKE_AGENT)).toEqual([ + [50, 30], + [220, 180], + [220, 180], + ]); + }, + }) + .start() + .completed(); + }); + }, + { + additionalDependencies: { + ai: '5.0.30', + }, + }, + ); + createEsmAndCjsTests( __dirname, 'scenario.mjs', diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-reasoning-tokens.mjs b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-reasoning-tokens.mjs new file mode 100644 index 000000000000..a7e6e0b2f27d --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-reasoning-tokens.mjs @@ -0,0 +1,110 @@ +import * as Sentry from '@sentry/node'; +import { generateText, stepCountIs, streamText, tool } from 'ai'; +import { MockLanguageModelV3, simulateReadableStream } from 'ai/test'; +import { z } from 'zod'; + +// Two Gemini steps that reason 80 and 100 tokens. `providerMetadata` describes one step, so only the +// SDK's usage can give the operation its 180. +const STEPS = [ + { candidates: 20, thoughts: 80, finishReason: { unified: 'tool-calls', raw: 'tool_calls' } }, + { candidates: 20, thoughts: 100, finishReason: { unified: 'stop', raw: 'STOP' } }, +]; + +function usage({ candidates, thoughts }) { + return { + inputTokens: { total: 10, noCache: 10, cacheRead: 0, cacheWrite: undefined }, + outputTokens: { total: candidates + thoughts, text: candidates, reasoning: thoughts }, + }; +} + +function providerMetadata({ candidates, thoughts }) { + return { + google: { + usageMetadata: { + promptTokenCount: 10, + candidatesTokenCount: candidates, + thoughtsTokenCount: thoughts, + totalTokenCount: 10 + candidates + thoughts, + }, + }, + }; +} + +const tools = { + getWeather: tool({ + description: 'Get the current weather for a location', + inputSchema: z.object({ location: z.string() }), + execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`, + }), +}; + +const toolCall = { + type: 'tool-call', + toolCallId: 'call-1', + toolName: 'getWeather', + input: JSON.stringify({ location: 'San Francisco' }), +}; + +async function run() { + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + let generateCalls = 0; + await generateText({ + experimental_telemetry: { isEnabled: true }, + model: new MockLanguageModelV3({ + doGenerate: async () => { + const step = STEPS[generateCalls++]; + return { + finishReason: step.finishReason, + usage: usage(step), + content: generateCalls === 1 ? [toolCall] : [{ type: 'text', text: 'Sunny, 72°F.' }], + warnings: [], + providerMetadata: providerMetadata(step), + }; + }, + }), + tools, + stopWhen: stepCountIs(5), + prompt: 'What is the weather in San Francisco?', + }); + + let streamCalls = 0; + const result = streamText({ + experimental_telemetry: { isEnabled: true }, + model: new MockLanguageModelV3({ + doStream: async () => { + const step = STEPS[streamCalls++]; + const content = + streamCalls === 1 + ? [toolCall] + : [ + { type: 'text-start', id: '0' }, + { type: 'text-delta', id: '0', delta: 'Sunny, 72°F.' }, + { type: 'text-end', id: '0' }, + ]; + return { + stream: simulateReadableStream({ + chunks: [ + { type: 'stream-start', warnings: [] }, + ...content, + { + type: 'finish', + finishReason: step.finishReason, + usage: usage(step), + providerMetadata: providerMetadata(step), + }, + ], + }), + }; + }, + }), + tools, + stopWhen: stepCountIs(5), + prompt: 'What is the weather in San Francisco?', + }); + for await (const _part of result.fullStream) { + void _part; + } + }); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/suite.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/suite.ts index 3a003a71a45c..dbf87fdcc2d3 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/suite.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/suite.ts @@ -938,6 +938,46 @@ export function registerVercelAiGenerationTests(version: '6' | '7', vercelAiVers }, }, ); + createEsmTests( + __dirname, + 'scenario-reasoning-tokens.mjs', + 'instrument.mjs', + (createRunner, test) => { + test('sums reasoning tokens across steps onto invoke_agent spans', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai', + ); + const generateContent = spans.filter( + span => span.attributes[SENTRY_OP]?.value === GEN_AI_GENERATE_CONTENT, + ); + const stepReasoning = generateContent.map( + span => span.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value as number, + ); + expect(stepReasoning.sort((a, b) => a - b)).toEqual([80, 80, 100, 100]); + + // One generateText and one streamText operation, each over the same two steps. + const invokeAgents = spans.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_INVOKE_AGENT); + expect(invokeAgents).toHaveLength(2); + for (const invokeAgent of invokeAgents) { + expect(invokeAgent.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(220); + expect(invokeAgent.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value).toBe(180); + } + }, + }) + .start() + .completed(); + }); + }, + { + additionalDependencies: { + ai: vercelAiVersion, + }, + }, + ); createEsmTests( __dirname, 'scenario-embeddings.mjs', diff --git a/docs/cutting-a-major-branch.md b/docs/cutting-a-major-branch.md index dc8b6bde027e..24aacbb90232 100644 --- a/docs/cutting-a-major-branch.md +++ b/docs/cutting-a-major-branch.md @@ -22,3 +22,4 @@ Add `vX` to the `branches` filters of the workflows that gate on maintained majo - `.github/workflows/build.yml` — `push.branches` - `.github/workflows/enforce-license-compliance.yml` — `push.branches` **and** `pull_request.branches` +- `.github/workflows/ci-metadata.yml` — the `is_base_branch` check diff --git a/docs/new-major-release-checklist.md b/docs/new-major-release-checklist.md new file mode 100644 index 000000000000..6420c99cf38e --- /dev/null +++ b/docs/new-major-release-checklist.md @@ -0,0 +1,90 @@ +# New Major Release Checklist + +This page lists the tasks we do for each new major of the SDK. It is based on the v9, v10 and v11 majors. Most code +changes of a major are different each time. This list covers the tasks that repeat. + +In this page, `vN` is the new major and `vN-1` is the previous major (e.g. `v11` and `v10`). + +## Planning + +- [ ] Create a Linear project `Major Release: N.0 [JavaScript]` and collect the breaking changes in it. +- [ ] Find the new minimum versions for Node.js, TypeScript, browsers and frameworks. +- [ ] Go through the `TODO(vN)` comments in the code and decide which ones go into `vN`. Change the others to + `TODO(vN+1)`. +- [ ] Tell the company that we plan to ship `vN`, and open a public "What's coming in `vN`" GitHub issue (e.g. + [#22056](https://github.com/getsentry/sentry-javascript/issues/22056)). +- [ ] Tell the company in a Vanguard post that we intend to ship a new major (e.g. https://vanguard.getsentry.net/p/i58qqnlqusz61lla86djbaly) +- [ ] Make sure that the wizard installs `^N-1` and not the latest major, so that it does not install a prerelease + or an untested major (e.g. [getsentry/sentry-wizard#1303](https://github.com/getsentry/sentry-wizard/pull/1303)). +- [ ] Ship all deprecations in a `vN-1` minor before we remove the APIs in `vN`. + +## Starting the Major on `develop` + +- [ ] Cut the `vN-1` maintenance branch. See [Cutting a Maintenance Branch for a New Major](./cutting-a-major-branch.md). +- [ ] Start the migration guide. Move the current `MIGRATION.md` content to `docs/migration/vN-2-to-vN-1.md`, link it at + the top of `MIGRATION.md`, and add a new `Upgrading from N-1.x to N.x` section (e.g. [#22364](https://github.com/getsentry/sentry-javascript/pull/22364)). +- [ ] Update the `compatibleRuntimes` of the `aws-lambda-layer` target to the new minimum Node.js version + (e.g. [#23155](https://github.com/getsentry/sentry-javascript/pull/23155)). The layer name is `SentryNodeServerlessSDKv{{{major}}}`, so `vN` releases + publish a new layer and do not replace the `vN-1` layer. + +## Prereleases (alpha, beta) + +- [ ] Release alphas and betas as described in [Publishing a Release](./publishing-a-release.md). Craft publishes prerelease versions with the `next` npm tag, + so `latest` stays on `vN-1`. We do not publish Lambda layers for prereleases. The first `SentryNodeServerlessSDKvN` layer comes with `N.0.0`. +- [ ] Do not write a full changelog for a prerelease. Use this text, and link the migration guide at the prerelease tag: + + ```md + ## N.0.0-alpha.0 + + This is an alpha release of the upcoming major release of version N. + This release does not yet entail a comprehensive changelog as version N is not yet stable. + + For this release's iteration of the migration guide, see the [Migration Guide as per `N.0.0-alpha.0`](https://github.com/getsentry/sentry-javascript/blob/N.0.0-alpha.0/MIGRATION.md#upgrading-from-n-1x-to-nx). + + Please note that the migration guide is work in progress and subject to change. + ``` + +- [ ] Deploy pre-releases on our dog-fooding apps + - [ ] https://github.com/getsentry/sentry + - [ ] https://github.com/getsentry/gib-potato + - [ ] https://github.com/getsentry/sentry-docs + - [ ] https://github.com/getsentry/sentry-changelog + - [ ] https://github.com/getsentry/chartcuterie +- [ ] Prepare (but do not merge) these PRs: + - `sentry-docs`: the migration guide, setup guides, option changes and the new Lambda layer ARN. + - `sentry-wizard`: change the installed SDK range to `^N` (e.g. + [getsentry/sentry-wizard#1344](https://github.com/getsentry/sentry-wizard/pull/1344)) and update the wizard for the + new APIs if applicable (e.g. [getsentry/sentry-wizard#1346](https://github.com/getsentry/sentry-wizard/pull/1346)). + - `sentry`: the in-product onboarding snippets. + - `sentry` (loader frontend): make the loader settings UI support `vN` (e.g. + [getsentry/sentry#123892](https://github.com/getsentry/sentry/pull/123892)). + - `sentry` (loader backend): make `vN` a selectable loader version, but keep `N-1` as the default (e.g. + [getsentry/sentry#123893](https://github.com/getsentry/sentry/pull/123893)). + +## Release Day + +**Do these steps in this order.** + +- [ ] 1. On the `vN-1` branch, add `"tag": "vN-1"` to the `publishConfig` of **every** published package (e.g. + [#24619](https://github.com/getsentry/sentry-javascript/pull/24619)). If a package does not have it, the next + `vN-1` patch release moves `latest` back to `vN-1` for that package +- [ ] 2. If we released on the `vN-1` branch, sync its changelog back into `develop` (e.g. + [#24587](https://github.com/getsentry/sentry-javascript/pull/24587)). +- [ ] 3. Release `N.0.0`. +- [ ] 4. Make sure that `latest` points to `N.0.0` on npm and that the `SentryNodeServerlessSDKvN` Lambda layer + exists. +- [ ] 5. Merge the docs, wizard and onboarding PRs. +- [ ] 6. Merge the loader frontend PR. +- [ ] 7. When the loader frontend PR is deployed, merge the loader backend PR. If the backend goes first, users can + select `vN` in a UI that does not know its options yet. +- [ ] 8. Announce the release and close the "What's coming in `vN`" issue. +- [ ] 9. Pat yourself on the back for a job well done. + +## After the Release + +- [ ] When `vN` is stable, make it the default loader version (e.g. + [getsentry/sentry#125867](https://github.com/getsentry/sentry/pull/125867)). For v10 this was one month after the + release, for v11 one week. +- [ ] Retarget remaining `TODO(vN)` comments we did not get into the `vN` major to `vN+1`. +- [ ] Backport important fixes to the `vN-1` branch (see the `backport-pr` skill) for a certain time, decide the timespan with the team. +- [ ] Write a shipped Vanguard and include images representing your amazing sense of humor (e.g. https://vanguard.getsentry.net/p/uf8st8ud25xsxjjum7zjkieo). diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index 0380ff16fc0e..a4f75f2f2cf5 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -59,6 +59,11 @@ "import": "./build/esm/babel-plugin/index.js", "require": "./build/cjs/babel-plugin/index.js" }, + "./rewriter": { + "types": "./build/types/rewriter/index.d.ts", + "import": "./build/esm/rewriter/index.js", + "require": "./build/cjs/rewriter/index.js" + }, "./sentry-release-injection-file": { "import": "./sentry-release-injection-file.js", "require": "./sentry-release-injection-file.js" diff --git a/packages/bundler-plugins/rollup.npm.config.mjs b/packages/bundler-plugins/rollup.npm.config.mjs index 14a01bf06c1e..8db6b8b9bd47 100644 --- a/packages/bundler-plugins/rollup.npm.config.mjs +++ b/packages/bundler-plugins/rollup.npm.config.mjs @@ -12,6 +12,7 @@ export default makeNPMConfigVariants( 'src/webpack/index.ts', 'src/webpack/component-annotation-transform.ts', 'src/babel-plugin/index.ts', + 'src/rewriter/index.ts', ], packageSpecificConfig: { // This package only ever runs in Node, at build time. Without pinning the platform, rolldown diff --git a/packages/bundler-plugins/src/rewriter/arrays.ts b/packages/bundler-plugins/src/rewriter/arrays.ts new file mode 100644 index 000000000000..d2db7c3aa5f5 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/arrays.ts @@ -0,0 +1,31 @@ +import type { ArrayExpressionNode, BaseNode, IdentifierNode } from './ast'; +import type { RewriteState } from './rewriter'; + +/** + * Replace an array literal of identifiers with `build(names)`, where `names` + * holds each identifier once, in source order. An empty array is left alone. + * An array holding anything other than plain identifiers is left alone and + * recorded as skipped under `label`. + * + * @returns whether the array was replaced + */ +export function wrapArrayLiteral( + state: RewriteState, + arrayNode: BaseNode, + label: string, + build: (names: string[]) => string, +): boolean { + const elements = (arrayNode as ArrayExpressionNode).elements ?? []; + if (elements.length === 0) return false; + + if (!elements.every(element => element?.type === 'Identifier')) { + state.report.skipped.push(label); + return false; + } + + const names = [...new Set(elements.map(element => (element as IdentifierNode).name))]; + state.ms.overwrite(arrayNode.start, arrayNode.end, build(names)); + state.needsImport = true; + state.report.wrapped.push(label); + return true; +} diff --git a/packages/bundler-plugins/src/rewriter/ast.ts b/packages/bundler-plugins/src/rewriter/ast.ts new file mode 100644 index 000000000000..49bd57b584e0 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/ast.ts @@ -0,0 +1,215 @@ +// Minimal ESTree node shapes. Any parser that puts `start`/`end` offsets on +// every node fits (oxc, acorn, Rollup's `this.parse`). + +export interface BaseNode { + type: string; + start: number; + end: number; +} + +export interface ProgramBody { + body: BaseNode[]; + hashbang?: BaseNode | null; +} + +export interface IdentifierNode extends BaseNode { + name: string; +} + +/** An `Identifier` or, for `export { x as "name" }`, a string `Literal`. */ +export interface NameNode { + type: string; + name?: string; + value?: unknown; +} + +export interface CallExpressionNode extends BaseNode { + callee?: { type: string; name?: string; property?: { type: string; name?: string } }; + arguments?: BaseNode[]; +} + +export interface MemberExpressionNode extends BaseNode { + object?: { type: string; name?: string }; + property?: { type: string; name?: string }; +} + +export interface ClassDeclarationNode extends BaseNode { + id?: IdentifierNode | null; + superClass?: BaseNode | null; + decorators?: BaseNode[] | null; +} + +export interface ExportDefaultNode extends BaseNode { + declaration: BaseNode; +} + +export interface ExportSpecifierNode extends BaseNode { + local?: NameNode; + exported?: NameNode; + exportKind?: string; +} + +export interface ExportNamedNode extends BaseNode { + declaration?: BaseNode | null; + source?: (BaseNode & { value?: unknown }) | null; + specifiers?: ExportSpecifierNode[]; + exportKind?: string; +} + +export interface ExportAllNode extends BaseNode { + source?: { value?: unknown }; + exported?: NameNode | null; + exportKind?: string; +} + +export interface VariableDeclaratorNode { + id?: BaseNode | null; + init?: BaseNode | null; +} + +export interface VariableDeclarationNode extends BaseNode { + declarations?: VariableDeclaratorNode[]; +} + +export interface ImportSpecifierNode { + type: string; + imported?: NameNode; + local?: NameNode; + importKind?: string; +} + +export interface ImportDeclarationNode extends BaseNode { + source?: { value?: unknown }; + specifiers?: ImportSpecifierNode[]; + importKind?: string; +} + +export interface ArrayExpressionNode extends BaseNode { + elements?: Array; +} + +export interface PropertyNode extends BaseNode { + key?: NameNode; + value?: BaseNode; + computed?: boolean; +} + +/** The declaration a top-level statement makes, looking through `export` (`export const x = ...`). */ +export function declarationOf(node: BaseNode): BaseNode | null | undefined { + return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node; +} + +/** Whether `node` calls `methodName`, either bare (`fn()`) or as a member (`ns.fn()`). */ +export function isCallToMethod(node: BaseNode, methodName: string): boolean { + if (node.type !== 'CallExpression') return false; + const callee = (node as CallExpressionNode).callee; + if (!callee) return false; + if (callee.type === 'Identifier' && callee.name === methodName) return true; + return ( + callee.type === 'MemberExpression' && callee.property?.type === 'Identifier' && callee.property.name === methodName + ); +} + +export function isAnonymousFunctionOrClass(node: BaseNode): boolean { + if (node.type === 'ArrowFunctionExpression') return true; + const isFunctionOrClass = [ + 'FunctionExpression', + 'FunctionDeclaration', + 'ClassExpression', + 'ClassDeclaration', + ].includes(node.type); + return isFunctionOrClass && !(node as ClassDeclarationNode).id; +} + +/** `export type { X }` or `export { type X }`, which TypeScript erases. */ +export function isTypeOnlyExport(node: { exportKind?: string }): boolean { + return node.exportKind === 'type'; +} + +/** The name an export or import specifier refers to, for both `x` and `"x"`. */ +export function exportedName(node: NameNode | undefined): string | undefined { + if (node?.type === 'Identifier') return node.name; + if (node?.type === 'Literal' && typeof node.value === 'string') return node.value; + return undefined; +} + +/** + * The offset after the hashbang and the directive prologue (`'use server'`), + * where code may be inserted without changing what the module means. + */ +export function directivesEnd(ast: ProgramBody): number { + let end = ast.hashbang?.end ?? 0; + for (const node of ast.body) { + if (node.type !== 'ExpressionStatement' || typeof (node as { directive?: unknown }).directive !== 'string') break; + end = node.end; + } + return end; +} + +/** + * The binding names a declaration introduces, including names inside + * destructuring patterns. `undefined` for a declaration that binds no runtime + * value (`interface`, `type`). + */ +export function declaredNames(declaration: BaseNode): string[] | undefined { + switch (declaration.type) { + case 'ClassDeclaration': + case 'FunctionDeclaration': { + const name = (declaration as ClassDeclarationNode).id?.name; + return name ? [name] : undefined; + } + case 'VariableDeclaration': { + const names: string[] = []; + for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) { + collectPatternNames(declarator.id, names); + } + return names; + } + default: + return undefined; + } +} + +function collectPatternNames(pattern: BaseNode | null | undefined, names: string[]): void { + if (!pattern) return; + const node = pattern as BaseNode & { + name?: string; + properties?: Array; + elements?: Array; + left?: BaseNode; + argument?: BaseNode; + }; + switch (node.type) { + case 'Identifier': + if (node.name) names.push(node.name); + break; + case 'ObjectPattern': + for (const property of node.properties ?? []) { + collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, names); + } + break; + case 'ArrayPattern': + for (const element of node.elements ?? []) collectPatternNames(element, names); + break; + case 'AssignmentPattern': + collectPatternNames(node.left, names); + break; + case 'RestElement': + collectPatternNames(node.argument, names); + break; + } +} + +/** Visit `node` and every node below it, parents first. */ +export function walk(node: unknown, visit: (node: BaseNode) => void): void { + if (Array.isArray(node)) { + for (const child of node) walk(child, visit); + return; + } + if (!node || typeof node !== 'object' || typeof (node as BaseNode).type !== 'string') return; + + visit(node as BaseNode); + for (const value of Object.values(node)) { + if (value && typeof value === 'object') walk(value, visit); + } +} diff --git a/packages/bundler-plugins/src/rewriter/class-extends.ts b/packages/bundler-plugins/src/rewriter/class-extends.ts new file mode 100644 index 000000000000..4afce1447aee --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/class-extends.ts @@ -0,0 +1,104 @@ +import type { + BaseNode, + ClassDeclarationNode, + IdentifierNode, + ImportDeclarationNode, + MemberExpressionNode, + ProgramBody, +} from './ast'; +import { declarationOf } from './ast'; + +/** A base class, named by the module it is imported from and its export name. */ +export interface BaseClassRef { + module: string; + name: string; +} + +interface BaseBindings { + /** Local identifiers bound to the named import of the base class. */ + named: Set; + /** Local identifiers bound to a `* as ns` import of the base module. */ + namespaces: Set; +} + +/** + * Find top-level classes that (transitively, within this module) extend the + * given base class. A superclass must be a plain identifier (`extends Base`) + * or member access (`extends ns.Base`). + * + * Only same-file base chains are resolvable here; a base class imported from + * another module under a different name is invisible. + */ +export function findClassesExtending(ast: ProgramBody, base: BaseClassRef): Set { + const bases = collectBaseImports(ast, base); + if (bases.named.size === 0 && bases.namespaces.size === 0) { + return new Set(); + } + + // Every top-level class, including the `export class Foo {}` form. + const classes = new Map(); + for (const node of ast.body) { + const declaration = declarationOf(node); + if (declaration?.type !== 'ClassDeclaration') continue; + const classNode = declaration as ClassDeclarationNode; + if (classNode.id?.name) classes.set(classNode.id.name, classNode); + } + + const found = new Set(); + // Iterate to a fixed point so an indirect chain (A extends B extends Base) is + // fully resolved regardless of declaration order. + let changed = true; + while (changed) { + changed = false; + for (const [name, classNode] of classes) { + if (found.has(name)) continue; + if (extendsBase(classNode.superClass, base, bases, found)) { + found.add(name); + changed = true; + } + } + } + return found; +} + +function collectBaseImports(ast: ProgramBody, base: BaseClassRef): BaseBindings { + const named = new Set(); + const namespaces = new Set(); + for (const node of ast.body) { + if (node.type !== 'ImportDeclaration') continue; + const importNode = node as ImportDeclarationNode; + if (importNode.source?.value !== base.module || importNode.importKind === 'type') continue; + for (const specifier of importNode.specifiers ?? []) { + if (specifier.importKind === 'type') continue; + if (specifier.type === 'ImportSpecifier' && specifier.imported?.name === base.name && specifier.local?.name) { + named.add(specifier.local.name); + } else if (specifier.type === 'ImportNamespaceSpecifier' && specifier.local?.name) { + namespaces.add(specifier.local.name); + } + } + } + return { named, namespaces }; +} + +function extendsBase( + superClass: BaseNode | null | undefined, + base: BaseClassRef, + bases: BaseBindings, + detected: Set, +): boolean { + if (!superClass) return false; + if (superClass.type === 'Identifier') { + const name = (superClass as IdentifierNode).name; + return bases.named.has(name) || detected.has(name); + } + if (superClass.type === 'MemberExpression') { + const member = superClass as MemberExpressionNode; + return ( + member.object?.type === 'Identifier' && + !!member.object.name && + bases.namespaces.has(member.object.name) && + member.property?.name === base.name + ); + } + return false; +} diff --git a/packages/bundler-plugins/src/rewriter/exports.ts b/packages/bundler-plugins/src/rewriter/exports.ts new file mode 100644 index 000000000000..d8c651027861 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/exports.ts @@ -0,0 +1,361 @@ +import type { + BaseNode, + ClassDeclarationNode, + ExportDefaultNode, + ExportNamedNode, + ExportSpecifierNode, + IdentifierNode, + ImportDeclarationNode, + ProgramBody, + VariableDeclarationNode, +} from './ast'; +import { + declarationOf, + declaredNames, + exportedName, + isAnonymousFunctionOrClass, + isCallToMethod, + isTypeOnlyExport, +} from './ast'; +import type { RewriteState } from './rewriter'; + +/** Builds the expression that wraps `target`, e.g. `target => \`wrap(${target})\``. */ +export type WrapExpression = (target: string) => string; + +/** + * Handles one export specifier of a statement passed to {@link wrapSpecifierExports}. + * Returns the `Wrapped as Exported` pair to emit in its place, or `undefined` + * to keep the specifier as written. Statements the pair depends on go onto + * `prelude`, which is emitted before the rebuilt export. + */ +export type SpecifierWrapper = ( + specifier: ExportSpecifierNode, + sourceLiteral: string | undefined, + prelude: string[], +) => string | undefined; + +/** Specifier name a `export { default as X } from '...'` re-export uses for the source's default. */ +const DEFAULT_IMPORT = 'default'; + +/** Top-level class declarations, exported or not, by name. */ +export function collectTopLevelClasses(ast: ProgramBody): Map { + const classes = new Map(); + for (const node of ast.body) { + const declaration = declarationOf(node); + if (declaration?.type !== 'ClassDeclaration') continue; + const classNode = declaration as ClassDeclarationNode; + if (classNode.id?.name) classes.set(classNode.id.name, classNode); + } + return classes; +} + +/** Top-level value binding name → the statement that declares it. */ +export function collectDeclaringStatements(ast: ProgramBody): Map { + const statements = new Map(); + for (const node of ast.body) { + const declaration = declarationOf(node); + if (!declaration) continue; + const names = + declaration.type === 'ImportDeclaration' ? valueImportNames(declaration) : (declaredNames(declaration) ?? []); + for (const name of names) { + if (name) statements.set(name, node); + } + } + return statements; +} + +function valueImportNames(node: ImportDeclarationNode): (string | undefined)[] { + if (node.importKind === 'type') return []; + return (node.specifiers ?? []) + .filter(specifier => specifier.importKind !== 'type') + .map(specifier => specifier.local?.name); +} + +/** + * Top-level bindings already assigned the result of one of `wrapperNames` + * (`const X = wrap(...)`), so exporting one must not wrap it a second time. + */ +export function collectManuallyWrappedLocals(ast: ProgramBody, wrapperNames: readonly string[]): Set { + const locals = new Set(); + + for (const node of ast.body) { + const declaration = declarationOf(node); + if (declaration?.type !== 'VariableDeclaration') continue; + for (const declarator of (declaration as VariableDeclarationNode).declarations ?? []) { + const name = declarator.id?.type === 'Identifier' ? (declarator.id as IdentifierNode).name : undefined; + const init = declarator.init; + if (name && init && wrapperNames.some(wrapper => isCallToMethod(init, wrapper))) { + locals.add(name); + } + } + } + + return locals; +} + +/** The value export statements (`export const`, `export { }`) that export `name`. */ +export function findNamedExports(ast: ProgramBody, name: string): ExportNamedNode[] { + const found: ExportNamedNode[] = []; + for (const node of ast.body) { + if (node.type !== 'ExportNamedDeclaration' || isTypeOnlyExport(node as ExportNamedNode)) continue; + const exportNode = node as ExportNamedNode; + const exportsName = exportNode.declaration + ? !!declaredNames(exportNode.declaration)?.includes(name) + : (exportNode.specifiers ?? []).some( + specifier => !isTypeOnlyExport(specifier) && exportedName(specifier.exported) === name, + ); + if (exportsName) found.push(exportNode); + } + return found; +} + +/** + * Wrap a binding declared in this module and return the binding that holds the wrapper. + * + * The declaration is left exactly as written, so a class or function keeps its + * `Function.prototype.name`. Only the *export* has to become the wrapper, so the wrapper gets its + * own binding and the export is aliased to it. + */ +export function wrapLocalBinding( + state: RewriteState, + localName: string, + declaringNode: BaseNode, + wrap: WrapExpression, +): string { + const existing = state.wrappedLocals.get(localName); + if (existing) return existing; + + const wrappedName = `__SENTRY_WRAPPED_${localName}__`; + state.wrappedLocals.set(localName, wrappedName); + state.ms.appendLeft(declaringNode.end, `\nconst ${wrappedName} = ${wrap(localName)};\n`); + state.needsImport = true; + return wrappedName; +} + +/** + * Wrap `localName` where an inline export declares it (`export class X {}`, + * `export const x = ...`, `export function x() {}`). The `export` keyword is + * replaced by an export clause that aliases the name to the wrapper. Other + * names the same declaration exports are exported again, through their + * wrapper when a later call wraps them too. + * + * @returns whether the declaration exports `localName` + */ +export function wrapInlineExport( + state: RewriteState, + exportNode: ExportNamedNode, + localName: string, + wrap: WrapExpression, +): boolean { + const declaration = exportNode.declaration; + const names = declaration ? declaredNames(declaration) : undefined; + if (!declaration || !names?.includes(localName)) return false; + + wrapLocalBinding(state, localName, declaration, wrap); + const specifiers = names.map(name => { + const wrappedName = state.wrappedLocals.get(name); + return wrappedName ? `${wrappedName} as ${name}` : name; + }); + // In `@dec export class A {}` the decorators come before `export`, so the + // clause has to go before them. + const decoratorStart = (declaration as ClassDeclarationNode).decorators?.[0]?.start ?? exportNode.start; + const start = Math.min(decoratorStart, exportNode.start); + const decorators = state.ms.original.slice(start, exportNode.start); + // A second call for another name of this declaration overwrites the same range again. + state.ms.overwrite(start, declaration.start, `export { ${specifiers.join(', ')} };\n${decorators}`); + return true; +} + +/** + * Wrap the specifiers of an `export { ... }` statement that `wrapSpecifier` picks. + * + * Each such specifier is re-pointed at a binding holding the wrapper, which means rebuilding the + * statement; the other specifiers are carried over verbatim. A binding that lives in **another** + * module is first bound under a private name (see {@link wrapForeignExport}), since an import + * binding cannot be reassigned and the `from` form has no local binding at all. + */ +export function wrapSpecifierExports( + state: RewriteState, + node: ExportNamedNode, + wrapSpecifier: SpecifierWrapper, +): void { + const specifiers = node.specifiers ?? []; + if (specifiers.length === 0 || isTypeOnlyExport(node)) return; + + const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : undefined; + + const prelude: string[] = []; + const wrappedPairs: string[] = []; + const kept: string[] = []; + + for (const specifier of specifiers) { + const pair = isTypeOnlyExport(specifier) ? undefined : wrapSpecifier(specifier, sourceLiteral, prelude); + if (pair) { + wrappedPairs.push(pair); + } else { + kept.push(state.ms.original.slice(specifier.start, specifier.end)); + } + } + + if (wrappedPairs.length === 0) return; + + const statements = [...prelude, `export { ${wrappedPairs.join(', ')} };`]; + if (kept.length > 0) { + const clause = `export { ${kept.join(', ')} }`; + statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`); + } + state.ms.overwrite(node.start, node.end, statements.join('\n')); +} + +/** + * Wrap a binding that comes from another module: imported and re-exported + * (`sourceLiteral` undefined), or re-exported directly (`export { x } from`). + * Pushes the statements that bind the wrapper onto `prelude` and returns the + * pair to export. + */ +export function wrapForeignExport( + state: RewriteState, + localName: string, + exportedAs: string, + sourceLiteral: string | undefined, + prelude: string[], + wrap: WrapExpression, +): string { + let target = localName; + + if (sourceLiteral) { + target = `__SENTRY_REEXPORT_${exportedAs}__`; + prelude.push(importAs(localName, target, sourceLiteral)); + } + + const wrappedName = `__SENTRY_WRAPPED_${exportedAs}__`; + prelude.push(`const ${wrappedName} = ${wrap(target)};`); + state.needsImport = true; + return `${wrappedName} as ${exportedAs}`; +} + +/** + * Wrap `export default `. + * + * `export default Foo`, where `Foo` already has a wrapper binding (a class + * also exported by name), is re-pointed at that binding instead of wrapping + * twice. + */ +export function wrapDefaultExport(state: RewriteState, node: ExportDefaultNode, wrap: WrapExpression): void { + const decl = node.declaration; + + if (decl.type === 'Identifier') { + const wrappedName = state.wrappedLocals.get((decl as IdentifierNode).name); + if (wrappedName) { + state.ms.overwrite(decl.start, decl.end, wrappedName); + return; + } + } + + // Only the `export default` keywords are replaced, so parentheses around the expression stay. + const source = state.ms.original; + const keywordsEnd = exportDefaultKeywordsEnd(source, node.start); + const declaredName = + decl.type === 'ClassDeclaration' || decl.type === 'FunctionDeclaration' + ? (decl as ClassDeclarationNode).id?.name + : undefined; + + // As with `export { handler as default }`, the export is set in two steps: bound as-is where the + // original statement set it, then rebound at the end of the module to the wrapper, which sees + // methods added in between. See `wrapDefaultSpecifier`. + let wrapped = '__SENTRY_DEFAULT_EXPORT__'; + if (declaredName) { + // `export default class Handler {}`: the declaration stays, so `Handler` stays bound in the module. + state.ms.remove(node.start, decl.start); + state.ms.appendLeft(node.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`); + wrapped = declaredName; + } else if (isAnonymousFunctionOrClass(decl)) { + // As a property value, the class or function gets the name `default`, as `export default` gives it. + const hasSemicolon = source[node.end - 1] === ';'; + state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ = { default:'); + state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? ' }.default' : ' }.default;'); + } else { + state.ms.overwrite(node.start, keywordsEnd, 'var __SENTRY_DEFAULT_EXPORT__ ='); + } + state.ms.appendLeft(node.end, '\nexport { __SENTRY_DEFAULT_EXPORT__ as default };'); + state.ms.append(`\n__SENTRY_DEFAULT_EXPORT__ = ${wrap(wrapped)};`); + state.needsImport = true; +} + +/** + * Offset just past the `default` keyword of the `export default` statement at `start`. Comments can + * sit between `export`, `default` and the expression, and may themselves contain the word `default`. + */ +function exportDefaultKeywordsEnd(source: string, start: number): number { + let index = start + 'export'.length; + while (index < source.length && !source.startsWith('default', index)) { + if (source.startsWith('//', index)) { + const lineEnd = source.indexOf('\n', index); + index = lineEnd === -1 ? source.length : lineEnd; + } else if (source.startsWith('/*', index)) { + const commentEnd = source.indexOf('*/', index + 2); + index = commentEnd === -1 ? source.length : commentEnd + 2; + } else { + index++; + } + } + return index + 'default'.length; +} + +/** + * `export { handler as default }`, the form bundlers emit for a default export. The export is set + * in two steps. Right after `handler` is declared, it is bound to `handler` as-is, so a circular + * import that reads it during module evaluation gets the handler, as before the transform. At the + * end of the module, it is rebound to the wrapper, so a handler assigned or given methods later is + * wrapped as it ends up. The binding is a `var`: a read before `handler` is declared gets + * `undefined`, as it would from the bundler's own `var`, where a `const` would throw and stop the + * Worker from starting. + * + * @returns the pair to export in place of the specifier + */ +export function wrapDefaultSpecifier( + state: RewriteState, + localName: string, + declaringStatement: BaseNode | undefined, + wrap: WrapExpression, +): string { + // Same as `export default Foo`: re-point at the wrapper a named export already made. + const wrappedName = state.wrappedLocals.get(localName); + if (wrappedName) return `${wrappedName} as default`; + + if (declaringStatement) { + state.ms.appendLeft(declaringStatement.end, `\nvar __SENTRY_DEFAULT_EXPORT__ = ${localName};`); + } + state.ms.append(`\n${declaringStatement ? '' : 'var '}__SENTRY_DEFAULT_EXPORT__ = ${wrap(localName)};`); + state.needsImport = true; + return '__SENTRY_DEFAULT_EXPORT__ as default'; +} + +/** + * `export { default } from './handler'` and `export { x as default } from './handler'`. + * + * The original re-export is a live binding to the handler module's export, but the wrapper is not + * set until this module's body runs. A circular import that reads the default export before then + * gets `undefined` instead of the handler. The binding is a `var` so that the read does not throw, + * as a `const` would, and stop the Worker from starting. See `wrapDefaultSpecifier`. + * + * @returns the pair to export in place of the specifier + */ +export function wrapDefaultReexport( + state: RewriteState, + localName: string, + sourceLiteral: string, + prelude: string[], + wrap: WrapExpression, +): string { + const target = '__SENTRY_REEXPORT_default__'; + prelude.push(importAs(localName, target, sourceLiteral), `var __SENTRY_DEFAULT_EXPORT__ = ${wrap(target)};`); + state.needsImport = true; + return '__SENTRY_DEFAULT_EXPORT__ as default'; +} + +function importAs(importedName: string, localName: string, sourceLiteral: string): string { + return importedName === DEFAULT_IMPORT + ? `import ${localName} from ${sourceLiteral};` + : `import { ${importedName} as ${localName} } from ${sourceLiteral};`; +} diff --git a/packages/bundler-plugins/src/rewriter/imports.ts b/packages/bundler-plugins/src/rewriter/imports.ts new file mode 100644 index 000000000000..3d3a7de86743 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/imports.ts @@ -0,0 +1,28 @@ +import type { ImportDeclarationNode, ProgramBody } from './ast'; +import { directivesEnd, exportedName } from './ast'; +import type { RewriteState } from './rewriter'; + +/** Whether the module already binds `name` to the export of the same name from `module`. */ +export function hasImport(ast: ProgramBody, module: string, name: string): boolean { + return ast.body.some(node => { + if (node.type !== 'ImportDeclaration') return false; + const importNode = node as ImportDeclarationNode; + if (importNode.source?.value !== module || importNode.importKind === 'type') return false; + return (importNode.specifiers ?? []).some( + specifier => + specifier.type === 'ImportSpecifier' && + specifier.importKind !== 'type' && + exportedName(specifier.imported) === name && + specifier.local?.name === name, + ); + }); +} + +/** Adds an import statement after the hashbang and directives, once per module. */ +export function addImport(state: RewriteState, ast: ProgramBody, statement: string): void { + if (state.imports.has(statement)) return; + state.imports.add(statement); + + const position = directivesEnd(ast); + state.ms.appendLeft(position, position === 0 ? `${statement}\n` : `\n${statement}`); +} diff --git a/packages/bundler-plugins/src/rewriter/index.ts b/packages/bundler-plugins/src/rewriter/index.ts new file mode 100644 index 000000000000..ed44fbb9dd47 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/index.ts @@ -0,0 +1,9 @@ +export * from './ast'; +export * from './arrays'; +export * from './class-extends'; +export * from './exports'; +export * from './imports'; +export * from './module-shape'; +export * from './parse'; +export * from './report'; +export * from './rewriter'; diff --git a/packages/bundler-plugins/src/rewriter/module-shape.ts b/packages/bundler-plugins/src/rewriter/module-shape.ts new file mode 100644 index 000000000000..2b16b0f7ab77 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/module-shape.ts @@ -0,0 +1,176 @@ +import type { + BaseNode, + ClassDeclarationNode, + ExportAllNode, + ExportDefaultNode, + ExportNamedNode, + IdentifierNode, + ImportDeclarationNode, + MemberExpressionNode, + ProgramBody, +} from './ast'; +import { exportedName, isTypeOnlyExport } from './ast'; +import { langFromId, parseModule } from './parse'; + +/** Binding name used for a module's default export. */ +export const DEFAULT_EXPORT = 'default'; + +/** A resolved superclass reference: a bare identifier or a `ns.Member` expression. */ +export type SuperRef = { kind: 'identifier'; name: string } | { kind: 'member'; object: string; property: string }; + +/** The declarations of a single module that binding resolution needs. */ +export interface ModuleShape { + /** Top-level class names → their superclass reference (absent when the class has no `extends`). */ + classes: Map; + /** Local binding name → the import it came from (`imported` is `default` for a default import). */ + imports: Map; + /** Local binding name → module specifier, for `import * as ns from '...'`. */ + namespaces: Map; + /** Exported name → the re-export it came from, for `export { x as y } from '...'`. */ + reexports: Map; + /** Exported name → local binding name, for `export { x as y }` without a source. */ + localExports: Map; + /** Module specifiers of bare `export * from '...'` declarations. */ + starExports: string[]; + /** `export default ` — the local name it refers to. */ + defaultExportName?: string; + /** True when the module's default export is a class declaration/expression. */ + defaultExportIsClass?: boolean; + /** Superclass of an anonymous `export default class extends X`. */ + defaultExportSuper?: SuperRef; +} + +function emptyShape(): ModuleShape { + return { + classes: new Map(), + imports: new Map(), + namespaces: new Map(), + reexports: new Map(), + localExports: new Map(), + starExports: [], + }; +} + +/** Collect the shape of a module from its parsed AST. */ +export function shapeFromAst(ast: ProgramBody): ModuleShape { + const shape = emptyShape(); + + for (const node of ast.body) { + switch (node.type) { + case 'ClassDeclaration': + addAstClass(shape, node); + break; + case 'ImportDeclaration': + addAstImports(shape, node); + break; + case 'ExportNamedDeclaration': + addAstNamedExport(shape, node); + break; + case 'ExportDefaultDeclaration': { + const decl = (node as ExportDefaultNode).declaration; + if (decl.type === 'ClassDeclaration' || decl.type === 'ClassExpression') { + shape.defaultExportIsClass = true; + shape.defaultExportSuper = superRefFromNode((decl as ClassDeclarationNode).superClass); + // `export default class Foo {}` also binds `Foo` locally. + addAstClass(shape, decl); + } else if (decl.type === 'Identifier') { + shape.defaultExportName = (decl as IdentifierNode).name; + } + break; + } + case 'ExportAllDeclaration': { + const starNode = node as ExportAllNode; + // `export * as ns from '...'` binds a namespace object, not the individual exports. + const source = starNode.exported || isTypeOnlyExport(starNode) ? undefined : asString(starNode.source?.value); + if (source) shape.starExports.push(source); + break; + } + } + } + + return shape; +} + +/** + * Extract the module shape from unprocessed source, such as a sibling module + * read off disk. Returns `undefined` when the source does not parse. + */ +export function shapeFromSource(code: string, id: string): ModuleShape | undefined { + const lang = langFromId(id); + // A module read off disk may hold TypeScript or JSX whatever its id says, + // and `tsx` reads everything the other dialects do. + for (const candidate of lang === 'tsx' ? [lang] : [lang, 'tsx' as const]) { + try { + return shapeFromAst(parseModule(code, id, candidate)); + } catch { + // Try the next dialect. + } + } + return undefined; +} + +function superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined { + if (!superClass) return undefined; + + if (superClass.type === 'Identifier') { + return { kind: 'identifier', name: (superClass as IdentifierNode).name }; + } + + if (superClass.type === 'MemberExpression') { + const member = superClass as MemberExpressionNode; + const object = member.object?.type === 'Identifier' ? member.object.name : undefined; + const property = member.property?.name; + if (object && property) return { kind: 'member', object, property }; + } + + return undefined; +} + +function addAstClass(shape: ModuleShape, classNode: ClassDeclarationNode): void { + if (classNode.id?.name) shape.classes.set(classNode.id.name, superRefFromNode(classNode.superClass)); +} + +function addAstImports(shape: ModuleShape, node: ImportDeclarationNode): void { + const source = asString(node.source?.value); + // Type-only imports never contribute a runtime base class. + if (!source || node.importKind === 'type') return; + + for (const specifier of node.specifiers ?? []) { + const local = specifier.local?.name; + if (!local || specifier.importKind === 'type') continue; + + const imported = exportedName(specifier.imported); + if (specifier.type === 'ImportSpecifier' && imported) { + shape.imports.set(local, { source, imported }); + } else if (specifier.type === 'ImportDefaultSpecifier') { + shape.imports.set(local, { source, imported: DEFAULT_EXPORT }); + } else if (specifier.type === 'ImportNamespaceSpecifier') { + shape.namespaces.set(local, source); + } + } +} + +function addAstNamedExport(shape: ModuleShape, node: ExportNamedNode): void { + if (node.declaration?.type === 'ClassDeclaration') { + addAstClass(shape, node.declaration); + return; + } + if (isTypeOnlyExport(node)) return; + + const source = asString(node.source?.value); + for (const specifier of node.specifiers ?? []) { + const exported = exportedName(specifier.exported); + const local = exportedName(specifier.local); + if (!exported || !local || isTypeOnlyExport(specifier)) continue; + + if (source) { + shape.reexports.set(exported, { source, imported: local }); + } else { + shape.localExports.set(exported, local); + } + } +} + +function asString(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined; +} diff --git a/packages/bundler-plugins/src/rewriter/parse.ts b/packages/bundler-plugins/src/rewriter/parse.ts new file mode 100644 index 000000000000..1a83cf2e748f --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/parse.ts @@ -0,0 +1,83 @@ +import { stripUrlQueryAndFragment } from '@sentry/core'; +import type * as OxcParser from 'oxc-parser'; +import type { ProgramBody } from './ast'; + +export type ModuleLang = 'js' | 'jsx' | 'ts' | 'tsx'; + +/** Parses a module into an ESTree program. Throws when the code does not parse. */ +export type ModuleParser = (code: string, id: string) => ProgramBody; + +/** The part of a bundler's plugin context that can parse code. */ +export interface ParserContext { + meta?: { rolldownVersion?: string }; + parse?(input: string, options?: object | null): unknown; +} + +const PARSER_UNAVAILABLE_MESSAGE = + '[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. ' + + 'Modules that need it will not be auto-instrumented.'; + +// `undefined` while loading, `null` when it failed to load. +let oxc: typeof OxcParser | null | undefined; +let warnedParserUnavailable = false; + +// The import is dynamic so that a platform without an `oxc-parser` native +// binary gets a warning instead of a failed build. +const oxcLoaded: Promise = import('oxc-parser').then( + module => { + oxc = module; + return true; + }, + () => { + oxc = null; + return false; + }, +); + +/** Resolves once `oxc-parser` has loaded or failed to load, with whether it is available. */ +export function loadParser(): Promise { + return oxcLoaded; +} + +export function isParserLoading(): boolean { + return oxc === undefined; +} + +/** The source dialect a module id names by its extension. */ +export function langFromId(id: string): ModuleLang { + const extension = /\.([cm]?[jt]sx?)$/.exec(stripUrlQueryAndFragment(id))?.[1] ?? 'js'; + if (extension === 'tsx') return 'tsx'; + if (extension === 'jsx') return 'jsx'; + return extension.endsWith('ts') ? 'ts' : 'js'; +} + +/** + * The default {@link ModuleParser}, over `oxc-parser`. Throws when `oxc-parser` + * has not loaded; see {@link loadParser}. + */ +export function parseModule(code: string, id: string, lang: ModuleLang = langFromId(id)): ProgramBody { + if (!oxc) { + if (oxc === null && !warnedParserUnavailable) { + warnedParserUnavailable = true; + // eslint-disable-next-line no-console + console.warn(PARSER_UNAVAILABLE_MESSAGE); + } + throw new Error(oxc === null ? PARSER_UNAVAILABLE_MESSAGE : '`oxc-parser` has not loaded yet'); + } + + // `preserveParens: false` matches the AST Vite produces. + const { program, errors } = oxc.parseSync(id, code, { lang, sourceType: 'module', preserveParens: false }); + if (errors.length > 0) { + throw new Error(errors[0]?.message); + } + return program; +} + +/** + * A parser over Rolldown's own `this.parse`, which reads TypeScript when told + * the dialect. Rollup's `this.parse` cannot, so it is not used. + */ +export function bundlerParser(context: ParserContext | undefined): ModuleParser | undefined { + if (!context?.meta?.rolldownVersion || typeof context.parse !== 'function') return undefined; + return (code, id) => context.parse?.(code, { lang: langFromId(id), preserveParens: false }) as ProgramBody; +} diff --git a/packages/bundler-plugins/src/rewriter/report.ts b/packages/bundler-plugins/src/rewriter/report.ts new file mode 100644 index 000000000000..a190474ac257 --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/report.ts @@ -0,0 +1,18 @@ +/** What a rewrite did with the sites it found, by site label. */ +export interface RewriteReport { + wrapped: string[]; + /** Sites the rewrite could not wrap, for the user to wrap by hand. */ + skipped: string[]; + /** Sites the user already wrapped. */ + alreadyWrapped: string[]; +} + +export function createReport(): RewriteReport { + return { wrapped: [], skipped: [], alreadyWrapped: [] }; +} + +/** The warning for the skipped sites of a module, or `undefined` when none were skipped. */ +export function formatReport(report: RewriteReport, id: string): string | undefined { + if (report.skipped.length === 0) return undefined; + return `[Sentry] Could not auto-instrument ${report.skipped.join(' and ')} in ${id}.`; +} diff --git a/packages/bundler-plugins/src/rewriter/rewriter.ts b/packages/bundler-plugins/src/rewriter/rewriter.ts new file mode 100644 index 000000000000..47d29b1e62cf --- /dev/null +++ b/packages/bundler-plugins/src/rewriter/rewriter.ts @@ -0,0 +1,145 @@ +import { basename } from 'node:path'; +import MagicString, { type SourceMap } from 'magic-string'; +import type { ProgramBody } from './ast'; +import { + bundlerParser, + isParserLoading, + loadParser, + type ModuleParser, + parseModule, + type ParserContext, +} from './parse'; +import { createReport, formatReport, type RewriteReport } from './report'; + +/** The edits a rewrite makes to one module, shared by every rule that runs on it. */ +export interface RewriteState { + /** Positions are always relative to the original source. */ + ms: MagicString; + /** Set once the rewritten code references a binding the caller must import. */ + needsImport: boolean; + /** Local binding name → the binding that holds its wrapper. */ + wrappedLocals: Map; + /** Import statements already added to this module. */ + imports: Set; + report: RewriteReport; +} + +export function createRewriteState(code: string): RewriteState { + return { + ms: new MagicString(code), + needsImport: false, + wrappedLocals: new Map(), + imports: new Set(), + report: createReport(), + }; +} + +/** Which modules a rule runs on. Every given condition must hold. */ +export interface RuleInclude { + /** Tested against the full module id. */ + id?: RegExp; + /** Tested against the last path segment of the module id. */ + basename?: RegExp; + /** Substrings the source must contain, checked before parsing. */ + contains?: string[]; +} + +export interface RuleContext { + ast: ProgramBody; + code: string; + id: string; + state: RewriteState; +} + +export interface RewriteRule { + name: string; + include: RuleInclude; + apply(ctx: RuleContext): void | Promise; +} + +export interface RewriterOptions { + /** + * Defaults to Rolldown's `this.parse` when the transform gets a Rolldown + * plugin context, and to {@link parseModule} otherwise. + */ + parse?: ModuleParser; + /** Receives the warning for sites a rule could not wrap. */ + logger?: { warn(message: string): void }; +} + +export interface RewriteOutput { + code: string; + map: SourceMap; +} + +export interface CallSiteRewriter { + /** + * Runs every matching rule on one module. Returns `null` when nothing + * changed. The result is a promise only while `oxc-parser` is still + * loading, or when a rule's `apply` returns one. + * + * @param context the bundler's plugin context, for its parser + */ + transform(code: string, id: string, context?: ParserContext): RewriteOutput | null | Promise; +} + +export function createCallSiteRewriter(rules: RewriteRule[], options: RewriterOptions = {}): CallSiteRewriter { + const rewrite = ( + matching: RewriteRule[], + code: string, + id: string, + parse: ModuleParser, + ): RewriteOutput | null | Promise => { + let ast: ProgramBody; + try { + ast = parse(code, id); + } catch { + return null; + } + + const state = createRewriteState(code); + const ctx: RuleContext = { ast, code, id, state }; + const finish = (): RewriteOutput | null => { + const warning = formatReport(state.report, id); + if (warning) options.logger?.warn(warning); + if (!state.ms.hasChanged()) return null; + return { code: state.ms.toString(), map: state.ms.generateMap({ hires: true }) }; + }; + + const pending = applyRules(matching, ctx, 0); + return pending ? pending.then(finish) : finish(); + }; + + return { + transform(code, id, context) { + const matching = rules.filter(rule => matches(rule.include, code, id)); + if (matching.length === 0) return null; + + const parse = options.parse ?? bundlerParser(context) ?? parseModule; + // Rules may parse other modules with `parseModule`, so it has to be ready + // whichever parser reads this one. + if (isParserLoading()) { + return loadParser().then(() => rewrite(matching, code, id, parse)); + } + return rewrite(matching, code, id, parse); + }, + }; +} + +function matches(include: RuleInclude, code: string, id: string): boolean { + if (include.id && !include.id.test(id)) return false; + if (include.basename && !include.basename.test(basename(id))) return false; + if (include.contains && !include.contains.every(substring => code.includes(substring))) return false; + return true; +} + +/** Applies the rules in order, staying synchronous until a rule returns a promise. */ +function applyRules(rules: RewriteRule[], ctx: RuleContext, from: number): Promise | undefined { + for (let index = from; index < rules.length; index++) { + const pending = rules[index]?.apply(ctx); + if (pending instanceof Promise) { + return pending.then(() => applyRules(rules, ctx, index + 1)); + } + } + return undefined; +} diff --git a/packages/bundler-plugins/test/rewriter/arrays.test.ts b/packages/bundler-plugins/test/rewriter/arrays.test.ts new file mode 100644 index 000000000000..b73736994dcc --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/arrays.test.ts @@ -0,0 +1,68 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { type BaseNode, walk } from '../../src/rewriter/ast'; +import { wrapArrayLiteral } from '../../src/rewriter/arrays'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState, type RewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const build = (names: string[]): string => `wrap({ ${names.join(', ')} })`; + +/** Wraps the outermost array literal in `code`. */ +function wrapFirstArray(code: string): { output: string; result: boolean; state: RewriteState } { + const ast = parseModule(code, 'module.ts'); + let array: BaseNode | undefined; + walk(ast, node => { + if (!array && node.type === 'ArrayExpression') array = node; + }); + const state = createRewriteState(code); + const result = wrapArrayLiteral(state, array!, 'middleware', build); + const output = state.ms.toString(); + expect(() => parseModule(output, 'module.ts')).not.toThrow(); + return { output, result, state }; +} + +describe('wrapArrayLiteral', () => { + it('replaces an array of identifiers', () => { + const { output, result, state } = wrapFirstArray('f({ middleware: [a, b] });'); + expect(result).toBe(true); + expect(output).toBe('f({ middleware: wrap({ a, b }) });'); + expect(state.needsImport).toBe(true); + expect(state.report.wrapped).toEqual(['middleware']); + }); + + it('removes duplicates and a trailing comma', () => { + expect(wrapFirstArray('f([a, b, a,]);').output).toBe('f(wrap({ a, b }));'); + }); + + it('spans lines and comments', () => { + expect(wrapFirstArray('f([\n a, // first\n /* second */ b,\n]);').output).toBe('f(wrap({ a, b }));'); + }); + + it('leaves an empty array alone without a skip', () => { + const { output, result, state } = wrapFirstArray('f([]);'); + expect(result).toBe(false); + expect(output).toBe('f([]);'); + expect(state.report.skipped).toEqual([]); + }); + + it.each([ + ['a call', 'f([getMiddleware()]);'], + ['a nested array', 'f([a, [b]]);'], + ['a spread', 'f([...middlewares]);'], + ['a hole', 'f([a, , b]);'], + ['a member expression', 'f([ns.a]);'], + ])('skips an array holding %s', (_, code) => { + const { output, result, state } = wrapFirstArray(code); + expect(result).toBe(false); + expect(output).toBe(code); + expect(state.report.skipped).toEqual(['middleware']); + expect(state.needsImport).toBe(false); + }); + + it('is not confused by a `]` inside a string elsewhere', () => { + expect(wrapFirstArray("f([a], ']');").output).toBe("f(wrap({ a }), ']');"); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/ast.test.ts b/packages/bundler-plugins/test/rewriter/ast.test.ts new file mode 100644 index 000000000000..561c1522f925 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/ast.test.ts @@ -0,0 +1,124 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { + type BaseNode, + declaredNames, + directivesEnd, + exportedName, + type ExportNamedNode, + isAnonymousFunctionOrClass, + isCallToMethod, + isTypeOnlyExport, + walk, +} from '../../src/rewriter/ast'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +function firstStatement(code: string, id = 'module.ts'): BaseNode { + return parseModule(code, id).body[0]!; +} + +function expressionOf(code: string): BaseNode { + return (firstStatement(code) as BaseNode & { expression: BaseNode }).expression; +} + +describe('isCallToMethod', () => { + it('matches a bare call', () => { + expect(isCallToMethod(expressionOf('wrap(x);'), 'wrap')).toBe(true); + }); + + it('matches a member call', () => { + expect(isCallToMethod(expressionOf('Sentry.wrap(x);'), 'wrap')).toBe(true); + }); + + it('does not match another function or a non-call', () => { + expect(isCallToMethod(expressionOf('other(x);'), 'wrap')).toBe(false); + expect(isCallToMethod(expressionOf('wrap;'), 'wrap')).toBe(false); + }); +}); + +describe('isAnonymousFunctionOrClass', () => { + it.each([ + ['() => {}', true], + ['(function () {})', true], + ['(class {})', true], + ['(function named() {})', false], + ['(class Named {})', false], + ['({})', false], + ])('%s → %s', (code, expected) => { + expect(isAnonymousFunctionOrClass(expressionOf(`${code};`))).toBe(expected); + }); +}); + +describe('isTypeOnlyExport', () => { + it('detects `export type { X }`', () => { + expect(isTypeOnlyExport(firstStatement("export type { X } from './x';") as ExportNamedNode)).toBe(true); + }); + + it('detects an inline `type` specifier', () => { + const node = firstStatement("export { type X, Y } from './x';") as ExportNamedNode; + expect(isTypeOnlyExport(node)).toBe(false); + expect(node.specifiers!.map(isTypeOnlyExport)).toEqual([true, false]); + }); +}); + +describe('exportedName', () => { + it('reads identifier and string literal names', () => { + const node = firstStatement('export { a as b, c as "load" } from \'./x\';') as ExportNamedNode; + expect(node.specifiers!.map(specifier => exportedName(specifier.exported))).toEqual(['b', 'load']); + }); +}); + +describe('directivesEnd', () => { + it('is 0 without directives', () => { + expect(directivesEnd(parseModule('const a = 1;', 'module.js'))).toBe(0); + }); + + it('ends after the last directive', () => { + const code = '\'use strict\';\n"use server";\nconst a = 1;'; + expect(code.slice(0, directivesEnd(parseModule(code, 'module.js')))).toBe('\'use strict\';\n"use server";'); + }); + + it('ends after a hashbang', () => { + const code = '#!/usr/bin/env node\nconst a = 1;'; + expect(code.slice(0, directivesEnd(parseModule(code, 'module.js')))).toBe('#!/usr/bin/env node'); + }); + + it('ignores a string statement after other code', () => { + const code = "const a = 1;\n'use server';"; + expect(directivesEnd(parseModule(code, 'module.js'))).toBe(0); + }); +}); + +describe('declaredNames', () => { + it.each([ + ['export class A {}', ['A']], + ['export function a() {}', ['a']], + ['export const a = 1, b = 2;', ['a', 'b']], + ['export const { a, b: c, ...d } = x;', ['a', 'c', 'd']], + ['export const [a, [b], c = 1, ...d] = x;', ['a', 'b', 'c', 'd']], + ])('%s → %j', (code, expected) => { + expect(declaredNames((firstStatement(code) as ExportNamedNode).declaration!)).toEqual(expected); + }); + + it('is undefined for a declaration without a runtime binding', () => { + expect(declaredNames((firstStatement('export interface A {}') as ExportNamedNode).declaration!)).toBeUndefined(); + }); +}); + +describe('walk', () => { + it('visits nested nodes, parents first', () => { + const types: string[] = []; + walk(parseModule('f([a]);', 'module.js'), node => types.push(node.type)); + expect(types).toEqual([ + 'Program', + 'ExpressionStatement', + 'CallExpression', + 'Identifier', + 'ArrayExpression', + 'Identifier', + ]); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/class-extends.test.ts b/packages/bundler-plugins/test/rewriter/class-extends.test.ts new file mode 100644 index 000000000000..a9774c65ac46 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/class-extends.test.ts @@ -0,0 +1,70 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { findClassesExtending } from '../../src/rewriter/class-extends'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +const BASE = { module: 'cloudflare:workers', name: 'WorkerEntrypoint' }; + +function find(code: string): Set { + return findClassesExtending(parseModule(code, 'module.js'), BASE); +} + +describe('findClassesExtending', () => { + it('finds a class extending the named import', () => { + const code = [ + "import { WorkerEntrypoint } from 'cloudflare:workers';", + 'export class A extends WorkerEntrypoint {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('follows an aliased import', () => { + const code = ["import { WorkerEntrypoint as WE } from 'cloudflare:workers';", 'class A extends WE {}']; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('finds a class extending a namespace member', () => { + const code = [ + "import * as cf from 'cloudflare:workers';", + 'class A extends cf.WorkerEntrypoint {}', + 'class B extends cf.Other {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A'])); + }); + + it('resolves an indirect chain declared out of order', () => { + const code = [ + "import { WorkerEntrypoint } from 'cloudflare:workers';", + 'class C extends B {}', + 'class B extends A {}', + 'class A extends WorkerEntrypoint {}', + ]; + expect(find(code.join('\n'))).toEqual(new Set(['A', 'B', 'C'])); + }); + + it('ignores the same name imported from another module', () => { + const code = ["import { WorkerEntrypoint } from 'elsewhere';", 'class A extends WorkerEntrypoint {}']; + expect(find(code.join('\n'))).toEqual(new Set()); + }); + + it.each([ + "import type { WorkerEntrypoint as WE } from 'cloudflare:workers';", + "import { type WorkerEntrypoint as WE } from 'cloudflare:workers';", + "import type * as WE from 'cloudflare:workers';", + ])('ignores the type-only import `%s`', typeImport => { + const code = [ + typeImport, + 'const WE = class {};', + 'class A extends WE {}', + 'class B extends WE.WorkerEntrypoint {}', + ]; + expect(findClassesExtending(parseModule(code.join('\n'), 'module.ts'), BASE)).toEqual(new Set()); + }); + + it('ignores classes without the base import', () => { + expect(find('class A extends B {}')).toEqual(new Set()); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/exports.test.ts b/packages/bundler-plugins/test/rewriter/exports.test.ts new file mode 100644 index 000000000000..545a0437a3d5 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/exports.test.ts @@ -0,0 +1,408 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { ExportDefaultNode, ExportNamedNode, ProgramBody } from '../../src/rewriter/ast'; +import { exportedName } from '../../src/rewriter/ast'; +import { + collectDeclaringStatements, + collectManuallyWrappedLocals, + collectTopLevelClasses, + findNamedExports, + wrapDefaultExport, + wrapDefaultReexport, + wrapDefaultSpecifier, + wrapForeignExport, + wrapInlineExport, + wrapLocalBinding, + wrapSpecifierExports, +} from '../../src/rewriter/exports'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState, type RewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const wrap = (target: string): string => `wrap(${target})`; + +/** Runs `edit` on `code` and returns the result, which must still parse. */ +function rewrite(code: string, edit: (state: RewriteState, ast: ProgramBody) => void, id = 'module.ts'): string { + const ast = parseModule(code, id); + const state = createRewriteState(code); + edit(state, ast); + const output = state.ms.toString(); + expect(() => parseModule(output, id)).not.toThrow(); + return output; +} + +function defaultExportOf(ast: ProgramBody): ExportDefaultNode { + return ast.body.find(node => node.type === 'ExportDefaultDeclaration') as ExportDefaultNode; +} + +function namedExportsOf(ast: ProgramBody): ExportNamedNode[] { + return ast.body.filter(node => node.type === 'ExportNamedDeclaration') as ExportNamedNode[]; +} + +describe('collectors', () => { + const ast = parseModule( + [ + "import { imported } from './a';", + 'class Local {}', + 'export class Exported {}', + 'const handWrapped = wrap(Local);', + 'export const alsoHandWrapped = ns.wrap(Local), plain = 1;', + 'function fn() {}', + ].join('\n'), + 'module.js', + ); + + it('collects top-level classes, exported or not', () => { + expect([...collectTopLevelClasses(ast).keys()]).toEqual(['Local', 'Exported']); + }); + + it('maps each top-level binding to its declaring statement', () => { + const statements = collectDeclaringStatements(ast); + expect([...statements.keys()]).toEqual([ + 'imported', + 'Local', + 'Exported', + 'handWrapped', + 'alsoHandWrapped', + 'plain', + 'fn', + ]); + expect(statements.get('plain')).toBe(ast.body[4]); + }); + + it('maps destructured bindings to their declaring statement', () => { + const destructured = parseModule('const { a, b: [c, ...d] } = shared;', 'module.js'); + const statements = collectDeclaringStatements(destructured); + expect([...statements.keys()]).toEqual(['a', 'c', 'd']); + expect(statements.get('c')).toBe(destructured.body[0]); + }); + + it('skips type-only imports', () => { + const imports = parseModule("import type { a } from 'x';\nimport { type b, c } from 'y';", 'module.ts'); + expect([...collectDeclaringStatements(imports).keys()]).toEqual(['c']); + }); + + it('collects bindings assigned a call to a wrapper', () => { + expect(collectManuallyWrappedLocals(ast, ['wrap'])).toEqual(new Set(['handWrapped', 'alsoHandWrapped'])); + expect(collectManuallyWrappedLocals(ast, ['other'])).toEqual(new Set()); + }); +}); + +describe('findNamedExports', () => { + function find(code: string): string[] { + return findNamedExports(parseModule(code, 'module.ts'), 'load').map(node => code.slice(node.start, node.end)); + } + + it.each([ + 'export const load = () => {};', + 'export async function load() {}', + 'export let { load } = obj;', + 'export { load };', + 'export { other as load };', + 'export { other as "load" };', + "export { load } from './shared';", + ])('finds %s', code => { + expect(find(code)).toEqual([code]); + }); + + it.each([ + 'export const loader = () => {};', + 'export type { load };', + 'export { type load };', + 'export interface load {}', + 'const load = 1;', + 'export { load as other };', + ])('does not find %s', code => { + expect(find(code)).toEqual([]); + }); +}); + +describe('wrapLocalBinding', () => { + it('binds the wrapper after the declaration and reuses it', () => { + const output = rewrite('class A {}\nexport { A };', (state, ast) => { + expect(wrapLocalBinding(state, 'A', ast.body[0]!, wrap)).toBe('__SENTRY_WRAPPED_A__'); + expect(wrapLocalBinding(state, 'A', ast.body[0]!, wrap)).toBe('__SENTRY_WRAPPED_A__'); + expect(state.needsImport).toBe(true); + }); + expect(output).toBe('class A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n\nexport { A };'); + }); +}); + +describe('wrapInlineExport', () => { + it('wraps an exported class without renaming it', () => { + const output = rewrite('export class A {}', (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'A', wrap)).toBe(true); + }); + expect(output).toBe('export { __SENTRY_WRAPPED_A__ as A };\nclass A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n'); + }); + + it.each([ + ['@dec export class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\n@dec class A {}'], + ['export @dec class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\n@dec class A {}'], + ['export abstract class A {}', 'export { __SENTRY_WRAPPED_A__ as A };\nabstract class A {}'], + ])('keeps the class modifiers of `%s`', (code, expected) => { + const output = rewrite(code, (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'A', wrap)).toBe(true); + }); + expect(output).toBe(`${expected}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n`); + }); + + it('wraps an exported function', () => { + const output = rewrite('export async function load() {}', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('async function load() {}'); + expect(output).toContain('const __SENTRY_WRAPPED_load__ = wrap(load);'); + expect(output).toContain('export { __SENTRY_WRAPPED_load__ as load };'); + }); + + it('keeps the other names of the same declaration exported', () => { + const output = rewrite('export const load = () => {}, prerender = true;', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('const load = () => {}, prerender = true;'); + expect(output).toContain('export { __SENTRY_WRAPPED_load__ as load, prerender };'); + }); + + it('wraps two names of the same declaration', () => { + const output = rewrite('export const load = () => {}, actions = {};', (state, ast) => { + const node = namedExportsOf(ast)[0]!; + expect(wrapInlineExport(state, node, 'load', wrap)).toBe(true); + expect(wrapInlineExport(state, node, 'actions', wrap)).toBe(true); + }); + expect(output).toBe( + [ + 'export { __SENTRY_WRAPPED_load__ as load, __SENTRY_WRAPPED_actions__ as actions };', + 'const load = () => {}, actions = {};', + 'const __SENTRY_WRAPPED_load__ = wrap(load);', + '', + 'const __SENTRY_WRAPPED_actions__ = wrap(actions);', + '', + ].join('\n'), + ); + }); + + it('keeps TypeScript annotations', () => { + const output = rewrite('export const load: PageLoad = async () => ({});', (state, ast) => { + wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap); + }); + expect(output).toContain('const load: PageLoad = async () => ({});'); + }); + + it('returns false when the declaration does not declare the name', () => { + const output = rewrite('export const other = 1;', (state, ast) => { + expect(wrapInlineExport(state, namedExportsOf(ast)[0]!, 'load', wrap)).toBe(false); + }); + expect(output).toBe('export const other = 1;'); + }); +}); + +describe('wrapSpecifierExports', () => { + function wrapNamed(code: string, name: string): string { + return rewrite(code, (state, ast) => { + const declaring = collectDeclaringStatements(ast); + for (const node of namedExportsOf(ast)) { + wrapSpecifierExports(state, node, (specifier, sourceLiteral, prelude) => { + const exported = exportedName(specifier.exported); + const local = exportedName(specifier.local); + if (exported !== name || !local) return undefined; + if (sourceLiteral) return wrapForeignExport(state, local, exported, sourceLiteral, prelude, wrap); + return `${wrapLocalBinding(state, local, declaring.get(local)!, wrap)} as ${exported}`; + }); + } + }); + } + + it('re-points a local specifier and keeps the others', () => { + const output = wrapNamed('function load() {}\nconst other = 1;\nexport { load, other };', 'load'); + expect(output).toBe( + [ + 'function load() {}', + 'const __SENTRY_WRAPPED_load__ = wrap(load);', + '', + 'const other = 1;', + 'export { __SENTRY_WRAPPED_load__ as load };', + 'export { other };', + ].join('\n'), + ); + }); + + it('re-points an aliased specifier', () => { + const output = wrapNamed('const impl = () => {};\nexport { impl as load };', 'load'); + expect(output).toContain('const __SENTRY_WRAPPED_impl__ = wrap(impl);'); + expect(output).toContain('export { __SENTRY_WRAPPED_impl__ as load };'); + }); + + it('re-points a string literal export name', () => { + const output = wrapNamed('const impl = () => {};\nexport { impl as "load" };', 'load'); + expect(output).toContain('export { __SENTRY_WRAPPED_impl__ as load };'); + }); + + it('binds a re-export under a private name', () => { + const output = wrapNamed("export { load, other } from './shared';", 'load'); + expect(output).toBe( + [ + "import { load as __SENTRY_REEXPORT_load__ } from './shared';", + 'const __SENTRY_WRAPPED_load__ = wrap(__SENTRY_REEXPORT_load__);', + 'export { __SENTRY_WRAPPED_load__ as load };', + "export { other } from './shared';", + ].join('\n'), + ); + }); + + it('wraps an imported binding that is exported again', () => { + const output = wrapNamed("import { load } from './shared';\nexport { load };", 'load'); + expect(output).toContain("import { load } from './shared';\nconst __SENTRY_WRAPPED_load__ = wrap(load);"); + }); + + it('leaves type-only exports alone', () => { + const code = "export type { load } from './types';\nexport { type load as other } from './types';"; + expect(wrapNamed(code, 'load')).toBe(code); + }); + + it('leaves the statement alone when nothing matches', () => { + const code = 'const a = 1;\nexport { a };'; + expect(wrapNamed(code, 'load')).toBe(code); + }); +}); + +describe('wrapDefaultExport', () => { + function wrapDefault(code: string): string { + return rewrite(code, (state, ast) => wrapDefaultExport(state, defaultExportOf(ast), wrap), 'module.js'); + } + + it('wraps an object-literal default export', () => { + expect(wrapDefault('export default { fetch() {} };')).toBe( + [ + 'var __SENTRY_DEFAULT_EXPORT__ = { fetch() {} };', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_DEFAULT_EXPORT__);', + ].join('\n'), + ); + }); + + it('wraps a default export of an identifier', () => { + expect(wrapDefault('const handler = {};\nexport default handler;')).toContain( + 'var __SENTRY_DEFAULT_EXPORT__ = handler;', + ); + }); + + it('keeps a declared default class bound under its name', () => { + expect(wrapDefault('export default class Handler {}')).toBe( + [ + 'class Handler {}', + 'var __SENTRY_DEFAULT_EXPORT__ = Handler;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(Handler);', + ].join('\n'), + ); + }); + + it('keeps the name `default` for an anonymous class', () => { + expect(wrapDefault('export default class {}')).toBe( + [ + 'var __SENTRY_DEFAULT_EXPORT__ = { default: class {} }.default;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_DEFAULT_EXPORT__);', + ].join('\n'), + ); + }); + + it('wraps an anonymous function without a trailing semicolon', () => { + expect(wrapDefault('export default function () {}')).toContain( + 'var __SENTRY_DEFAULT_EXPORT__ = { default: function () {} }.default;', + ); + }); + + it.each([ + [ + 'a block comment', + 'export /* default handler */ default /* the default */ { fetch() {} };', + 'var __SENTRY_DEFAULT_EXPORT__ = /* the default */ { fetch() {} };', + ], + [ + 'a line comment', + 'export // default handler\ndefault { fetch() {} };', + 'var __SENTRY_DEFAULT_EXPORT__ = { fetch() {} };', + ], + ])('finds the `default` keyword past %s that names it', (_, code, expected) => { + expect(wrapDefault(code)).toContain(expected); + }); + + it('re-points the default export at an existing wrapper binding', () => { + const output = rewrite( + 'class A {}\nexport default A;', + (state, ast) => { + wrapLocalBinding(state, 'A', ast.body[0]!, wrap); + wrapDefaultExport(state, defaultExportOf(ast), wrap); + }, + 'module.js', + ); + expect(output).toBe('class A {}\nconst __SENTRY_WRAPPED_A__ = wrap(A);\n\nexport default __SENTRY_WRAPPED_A__;'); + }); +}); + +describe('wrapDefaultSpecifier', () => { + it('binds the default where the local is declared and wraps it at the end', () => { + const output = rewrite( + 'const handler = {};\nexport { handler as default };', + (state, ast) => { + const statement = collectDeclaringStatements(ast).get('handler'); + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, specifier => + wrapDefaultSpecifier(state, exportedName(specifier.local)!, statement, wrap), + ); + }, + 'module.js', + ); + expect(output).toBe( + [ + 'const handler = {};', + 'var __SENTRY_DEFAULT_EXPORT__ = handler;', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + '__SENTRY_DEFAULT_EXPORT__ = wrap(handler);', + ].join('\n'), + ); + }); + + it('declares the binding at the end when the local has no declaring statement', () => { + const output = rewrite( + 'export { handler as default };\nvar handler = {};', + (state, ast) => { + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, () => + wrapDefaultSpecifier(state, 'handler', undefined, wrap), + ); + }, + 'module.js', + ); + expect(output).toContain('var __SENTRY_DEFAULT_EXPORT__ = wrap(handler);'); + }); +}); + +describe('wrapDefaultReexport', () => { + it.each([ + ["export { default } from './handler';", "import __SENTRY_REEXPORT_default__ from './handler';"], + [ + "export { handler as default } from './handler';", + "import { handler as __SENTRY_REEXPORT_default__ } from './handler';", + ], + ])('wraps %s', (code, importStatement) => { + const output = rewrite( + code, + (state, ast) => { + wrapSpecifierExports(state, namedExportsOf(ast)[0]!, (specifier, sourceLiteral, prelude) => + wrapDefaultReexport(state, exportedName(specifier.local)!, sourceLiteral!, prelude, wrap), + ); + }, + 'module.js', + ); + expect(output).toBe( + [ + importStatement, + 'var __SENTRY_DEFAULT_EXPORT__ = wrap(__SENTRY_REEXPORT_default__);', + 'export { __SENTRY_DEFAULT_EXPORT__ as default };', + ].join('\n'), + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/imports.test.ts b/packages/bundler-plugins/test/rewriter/imports.test.ts new file mode 100644 index 000000000000..1b7e840201e1 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/imports.test.ts @@ -0,0 +1,58 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { addImport, hasImport } from '../../src/rewriter/imports'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createRewriteState } from '../../src/rewriter/rewriter'; + +beforeAll(async () => { + await loadParser(); +}); + +const IMPORT = "import { wrap } from 'sentry';"; + +function withImport(code: string): string { + const ast = parseModule(code, 'module.ts'); + const state = createRewriteState(code); + addImport(state, ast, IMPORT); + addImport(state, ast, IMPORT); + const output = state.ms.toString(); + expect(() => parseModule(output, 'module.ts')).not.toThrow(); + return output; +} + +describe('addImport', () => { + it('prepends the import once', () => { + expect(withImport('const foo = 1;')).toBe(`${IMPORT}\nconst foo = 1;`); + }); + + it("inserts after a 'use server' directive", () => { + expect(withImport("'use server';\nconst foo = 1;")).toBe(`'use server';\n${IMPORT}\nconst foo = 1;`); + }); + + it('inserts after a "use client" directive without a semicolon', () => { + expect(withImport('"use client"\nconst foo = 1;')).toBe(`"use client"\n${IMPORT}\nconst foo = 1;`); + }); + + it('inserts after several directives', () => { + expect(withImport("'use strict';\n'use server';\nconst foo = 1;")).toBe( + `'use strict';\n'use server';\n${IMPORT}\nconst foo = 1;`, + ); + }); + + it('inserts after a hashbang', () => { + expect(withImport('#!/usr/bin/env node\nconst foo = 1;')).toBe(`#!/usr/bin/env node\n${IMPORT}\nconst foo = 1;`); + }); +}); + +describe('hasImport', () => { + it.each([ + ["import { wrap } from 'sentry';", true], + ["import { other, wrap } from 'sentry';", true], + ["import { wrap as alias } from 'sentry';", false], + ["import { wrap } from 'elsewhere';", false], + ["import type { wrap } from 'sentry';", false], + ["import { type wrap } from 'sentry';", false], + ["import * as wrap from 'sentry';", false], + ])('%s → %s', (code, expected) => { + expect(hasImport(parseModule(code, 'module.ts'), 'sentry', 'wrap')).toBe(expected); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/module-shape.test.ts b/packages/bundler-plugins/test/rewriter/module-shape.test.ts new file mode 100644 index 000000000000..13ebf2981c69 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/module-shape.test.ts @@ -0,0 +1,118 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import { shapeFromAst, shapeFromSource } from '../../src/rewriter/module-shape'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +describe('shapeFromAst', () => { + it('collects classes with their superclass', () => { + const shape = shapeFromAst( + parseModule(['class A extends B {}', 'export class C extends ns.D {}', 'class E {}'].join('\n'), 'module.js'), + ); + expect(shape.classes).toEqual( + new Map([ + ['A', { kind: 'identifier', name: 'B' }], + ['C', { kind: 'member', object: 'ns', property: 'D' }], + ['E', undefined], + ]), + ); + }); + + it('collects named, default and namespace imports', () => { + const shape = shapeFromAst( + parseModule("import Def, { a as b, c } from 'm';\nimport * as ns from 'n';", 'module.js'), + ); + expect(shape.imports).toEqual( + new Map([ + ['Def', { source: 'm', imported: 'default' }], + ['b', { source: 'm', imported: 'a' }], + ['c', { source: 'm', imported: 'c' }], + ]), + ); + expect(shape.namespaces).toEqual(new Map([['ns', 'n']])); + }); + + it('collects local exports, re-exports and star exports', () => { + const shape = shapeFromAst( + parseModule( + [ + 'class A {}', + 'export { A as B };', + 'export { x as y, z as "w" } from \'./r\';', + "export * from './s';", + "export * as ns from './t';", + ].join('\n'), + 'module.js', + ), + ); + expect(shape.localExports).toEqual(new Map([['B', 'A']])); + expect(shape.reexports).toEqual( + new Map([ + ['y', { source: './r', imported: 'x' }], + ['w', { source: './r', imported: 'z' }], + ]), + ); + expect(shape.starExports).toEqual(['./s']); + }); + + it('records a declared default class', () => { + const shape = shapeFromAst(parseModule('export default class A extends B {}', 'module.js')); + expect(shape.defaultExportIsClass).toBe(true); + expect(shape.defaultExportSuper).toEqual({ kind: 'identifier', name: 'B' }); + expect(shape.classes.has('A')).toBe(true); + }); + + it('records an anonymous default class', () => { + const shape = shapeFromAst(parseModule('export default class extends B {}', 'module.js')); + expect(shape.defaultExportIsClass).toBe(true); + expect(shape.defaultExportSuper).toEqual({ kind: 'identifier', name: 'B' }); + }); + + it('records a default export of an identifier', () => { + const shape = shapeFromAst(parseModule('class A {}\nexport default A;', 'module.js')); + expect(shape.defaultExportName).toBe('A'); + expect(shape.defaultExportIsClass).toBeUndefined(); + }); +}); + +describe('shapeFromSource', () => { + it('reads generic and abstract TypeScript classes', () => { + const code = [ + "import { Agent } from 'agents';", + 'interface Props { name: string }', + 'export abstract class Base> extends Agent {', + ' private field?: T;', + '}', + ].join('\n'); + const shape = shapeFromSource(code, '/app/base.ts'); + expect(shape?.classes).toEqual(new Map([['Base', { kind: 'identifier', name: 'Agent' }]])); + expect(shape?.imports).toEqual(new Map([['Agent', { source: 'agents', imported: 'Agent' }]])); + }); + + it('skips type-only imports and exports', () => { + const code = [ + "import type { A } from './a';", + "import { type B, C } from './b';", + "export type { D } from './d';", + "export { type E, F } from './e';", + "export type * from './g';", + ].join('\n'); + const shape = shapeFromSource(code, '/app/mod.ts'); + expect([...shape!.imports.keys()]).toEqual(['C']); + expect([...shape!.reexports.keys()]).toEqual(['F']); + expect(shape!.starExports).toEqual([]); + }); + + it.each([ + ['TypeScript', "import { Agent } from 'agents';\nexport class Base extends Agent {}"], + ['JSX', "import { Agent } from 'agents';\nconst el =
;\nexport class Base extends Agent {}"], + ])('reads %s from a module whose id names JavaScript', (_, code) => { + expect(shapeFromSource(code, '/app/base.js')?.classes.get('Base')).toEqual({ kind: 'identifier', name: 'Agent' }); + }); + + it('returns undefined for code that does not parse', () => { + expect(shapeFromSource('this is ) not ( javascript', '/app/broken.js')).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parse.test.ts b/packages/bundler-plugins/test/rewriter/parse.test.ts new file mode 100644 index 000000000000..51765d09afd4 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parse.test.ts @@ -0,0 +1,69 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { bundlerParser, langFromId, loadParser, parseModule } from '../../src/rewriter/parse'; + +beforeAll(async () => { + await loadParser(); +}); + +describe('langFromId', () => { + it.each([ + ['/a/b.js', 'js'], + ['/a/b.mjs', 'js'], + ['/a/b.cjs', 'js'], + ['/a/b.jsx', 'jsx'], + ['/a/b.ts', 'ts'], + ['/a/b.mts', 'ts'], + ['/a/b.cts', 'ts'], + ['/a/b.tsx', 'tsx'], + ['/a/b.ts?v=123', 'ts'], + ['/a/b.tsx#hash', 'tsx'], + ['/a/b.svelte', 'js'], + ['virtual:module', 'js'], + ])('%s → %s', (id, lang) => { + expect(langFromId(id)).toBe(lang); + }); +}); + +describe('parseModule', () => { + it('returns an ESTree program with offsets', () => { + const code = 'export const a = 1;'; + const program = parseModule(code, 'a.js'); + const [statement] = program.body; + expect(statement).toMatchObject({ type: 'ExportNamedDeclaration', start: 0, end: code.length }); + }); + + it('parses TypeScript for a .ts id', () => { + expect(() => parseModule('const a: number = 1;', 'a.ts')).not.toThrow(); + }); + + it('rejects TypeScript for a .js id', () => { + expect(() => parseModule('const a: number = 1;', 'a.js')).toThrow(); + }); + + it('parses JSX for a .tsx id', () => { + expect(() => parseModule('const a =
;', 'a.tsx')).not.toThrow(); + }); + + it('throws on a syntax error', () => { + expect(() => parseModule('const a = (', 'a.js')).toThrow(); + }); +}); + +describe('bundlerParser', () => { + it("parses with Rolldown's `this.parse`, in the dialect the id names", () => { + const parse = vi.fn((input: string) => parseModule(input, 'module.ts')); + const parser = bundlerParser({ meta: { rolldownVersion: '1.2.11' }, parse }); + + parser!('const a: number = 1;', '/app/a.mts?v=1'); + expect(parse).toHaveBeenCalledWith('const a: number = 1;', { lang: 'ts', preserveParens: false }); + }); + + it('is undefined for Rollup, whose `this.parse` cannot read TypeScript', () => { + expect(bundlerParser({ meta: {}, parse: vi.fn() })).toBeUndefined(); + }); + + it('is undefined without a context or a parse function', () => { + expect(bundlerParser(undefined)).toBeUndefined(); + expect(bundlerParser({ meta: { rolldownVersion: '1.2.11' } })).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parser-loading.test.ts b/packages/bundler-plugins/test/rewriter/parser-loading.test.ts new file mode 100644 index 000000000000..ac20344c4ab0 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parser-loading.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest'; + +const { gate } = vi.hoisted(() => { + let release = (): void => {}; + const promise = new Promise(resolve => { + release = resolve; + }); + return { gate: { promise, release: () => release() } }; +}); + +vi.mock('oxc-parser', async importOriginal => { + await gate.promise; + return importOriginal(); +}); + +describe('the rewriter while `oxc-parser` loads', () => { + it('waits for it on the first transform and stays synchronous after', async () => { + const { createCallSiteRewriter, isParserLoading, wrapArrayLiteral, walk } = await import('../../src/rewriter'); + const rewriter = createCallSiteRewriter([ + { + name: 'arrays', + include: {}, + apply: ({ ast, state }) => + walk(ast, node => { + if (node.type === 'ArrayExpression') wrapArrayLiteral(state, node, 'array', names => names.join()); + }), + }, + ]); + + expect(isParserLoading()).toBe(true); + const pending = rewriter.transform('f([a]);', '/app/a.ts'); + expect(pending).toBeInstanceOf(Promise); + + gate.release(); + expect((await pending)?.code).toBe('f(a);'); + expect(isParserLoading()).toBe(false); + expect(rewriter.transform('f([b]);', '/app/b.ts')).toEqual(expect.objectContaining({ code: 'f(b);' })); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts b/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts new file mode 100644 index 000000000000..cc041c249195 --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/parser-unavailable.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('oxc-parser', () => { + throw new Error('Cannot find native binding.'); +}); + +const MESSAGE = + '[@sentry/bundler-plugins] Could not load `oxc-parser` for this platform. ' + + 'Modules that need it will not be auto-instrumented.'; + +describe('the rewriter without `oxc-parser`', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('leaves modules unchanged and warns once', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { createCallSiteRewriter, loadParser, shapeFromSource, wrapArrayLiteral, walk } = + await import('../../src/rewriter'); + const rewriter = createCallSiteRewriter([ + { + name: 'arrays', + include: {}, + apply: ({ ast, state }) => + walk(ast, node => { + if (node.type === 'ArrayExpression') wrapArrayLiteral(state, node, 'array', names => names.join()); + }), + }, + ]); + + // A transform that starts while the import is still pending waits for it. + expect(await rewriter.transform('f([a]);', '/app/a.ts')).toBeNull(); + await expect(loadParser()).resolves.toBe(false); + expect(rewriter.transform('f([b]);', '/app/b.ts')).toBeNull(); + expect(shapeFromSource('export class A {}', '/app/c.ts')).toBeUndefined(); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(MESSAGE); + }); + + it("still parses with Rolldown's `this.parse`", async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { createCallSiteRewriter, loadParser } = await import('../../src/rewriter'); + const { parseAst } = await import('rolldown/parseAst'); + await loadParser(); + + const rewriter = createCallSiteRewriter([ + { name: 'edit', include: {}, apply: ({ state }) => void state.ms.append('\n// edited') }, + ]); + const context = { meta: { rolldownVersion: '1.2.11' }, parse: parseAst }; + expect(rewriter.transform('const a: number = 1;', '/app/a.ts', context)).toEqual( + expect.objectContaining({ code: 'const a: number = 1;\n// edited' }), + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/report.test.ts b/packages/bundler-plugins/test/rewriter/report.test.ts new file mode 100644 index 000000000000..3d899b5c0e0c --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/report.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { createReport, formatReport } from '../../src/rewriter/report'; + +describe('formatReport', () => { + it('is undefined when nothing was skipped', () => { + const report = createReport(); + report.wrapped.push('a'); + expect(formatReport(report, '/app/a.ts')).toBeUndefined(); + }); + + it('names the skipped sites and the module', () => { + const report = createReport(); + report.skipped.push('requestMiddleware', 'functionMiddleware'); + expect(formatReport(report, '/app/start.ts')).toBe( + '[Sentry] Could not auto-instrument requestMiddleware and functionMiddleware in /app/start.ts.', + ); + }); +}); diff --git a/packages/bundler-plugins/test/rewriter/rewriter.test.ts b/packages/bundler-plugins/test/rewriter/rewriter.test.ts new file mode 100644 index 000000000000..935d0aad841f --- /dev/null +++ b/packages/bundler-plugins/test/rewriter/rewriter.test.ts @@ -0,0 +1,138 @@ +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { addImport } from '../../src/rewriter/imports'; +import { wrapArrayLiteral } from '../../src/rewriter/arrays'; +import { type BaseNode, walk } from '../../src/rewriter/ast'; +import { loadParser, parseModule } from '../../src/rewriter/parse'; +import { createCallSiteRewriter, type RewriteRule, type RuleContext } from '../../src/rewriter/rewriter'; +import { parseAst } from 'rolldown/parseAst'; + +beforeAll(async () => { + await loadParser(); +}); + +function wrapArrays(ctx: RuleContext): void { + walk(ctx.ast, node => { + if (node.type === 'ArrayExpression') { + wrapArrayLiteral(ctx.state, node, 'array', names => `wrap({ ${names.join(', ')} })`); + } + }); + if (ctx.state.needsImport) addImport(ctx.state, ctx.ast, "import { wrap } from 'sentry';"); +} + +const arrayRule: RewriteRule = { name: 'arrays', include: { id: /\.ts$/, contains: ['['] }, apply: wrapArrays }; + +describe('createCallSiteRewriter', () => { + it('rewrites a matching module with a source map', () => { + const result = createCallSiteRewriter([arrayRule]).transform('f([a]);', '/app/a.ts'); + expect(result).not.toBeInstanceOf(Promise); + const { code, map } = result as { code: string; map: { mappings: string } }; + expect(code).toBe("import { wrap } from 'sentry';\nf(wrap({ a }));"); + expect(map.mappings).not.toBe(''); + }); + + it('returns null when nothing changed', () => { + expect(createCallSiteRewriter([arrayRule]).transform('f([]);', '/app/a.ts')).toBeNull(); + }); + + it.each([ + ['the id does not match', 'f([a]);', '/app/a.css'], + ['the source lacks a substring', 'f(a);', '/app/a.ts'], + ])('does not parse when %s', (_, code, id) => { + const parse = vi.fn(parseModule); + expect(createCallSiteRewriter([arrayRule], { parse }).transform(code, id)).toBeNull(); + expect(parse).not.toHaveBeenCalled(); + }); + + it('matches on the basename', () => { + const rule: RewriteRule = { ...arrayRule, include: { basename: /^\+page\.ts$/ } }; + const rewriter = createCallSiteRewriter([rule]); + expect(rewriter.transform('f([a]);', '/app/routes/+page.ts')).not.toBeNull(); + expect(rewriter.transform('f([a]);', '/app/+page.ts/other.ts')).toBeNull(); + }); + + it('returns null when the module does not parse', () => { + expect(createCallSiteRewriter([arrayRule]).transform('f([a);', '/app/a.ts')).toBeNull(); + }); + + it('uses the given parser', () => { + const parse = vi.fn(parseModule); + createCallSiteRewriter([arrayRule], { parse }).transform('f([a]);', '/app/a.ts'); + expect(parse).toHaveBeenCalledWith('f([a]);', '/app/a.ts'); + }); + + it("parses with Rolldown's `this.parse` when the context is Rolldown's", () => { + const parse = vi.fn(parseAst); + const context = { meta: { rolldownVersion: '1.2.11' }, parse }; + const code = 'const a: string[] = [];\nf([a]);'; + + const result = createCallSiteRewriter([arrayRule]).transform(code, '/app/a.ts', context); + expect(parse).toHaveBeenCalledWith(code, { lang: 'ts', preserveParens: false }); + expect((result as { code: string }).code).toBe( + (createCallSiteRewriter([arrayRule]).transform(code, '/app/a.ts') as { code: string }).code, + ); + }); + + it("does not use Rollup's `this.parse`", () => { + const parse = vi.fn(); + createCallSiteRewriter([arrayRule]).transform('f([a]);', '/app/a.ts', { meta: {}, parse }); + expect(parse).not.toHaveBeenCalled(); + }); + + it('prefers the parser given in the options over the context', () => { + const parse = vi.fn(parseModule); + const contextParse = vi.fn(); + createCallSiteRewriter([arrayRule], { parse }).transform('f([a]);', '/app/a.ts', { + meta: { rolldownVersion: '1.2.11' }, + parse: contextParse, + }); + expect(parse).toHaveBeenCalled(); + expect(contextParse).not.toHaveBeenCalled(); + }); + + it('runs every matching rule on one parse and one set of edits', () => { + const parse = vi.fn(parseModule); + const second: RewriteRule = { + name: 'second', + include: {}, + apply: ({ state, ast }) => addImport(state, ast, "import 'second';"), + }; + const result = createCallSiteRewriter([arrayRule, second], { parse }).transform('f([a]);', '/app/a.ts'); + expect(parse).toHaveBeenCalledTimes(1); + expect((result as { code: string }).code).toBe("import { wrap } from 'sentry';\nimport 'second';\nf(wrap({ a }));"); + }); + + it('returns a promise once a rule is async, and runs the later rules after it', async () => { + const order: string[] = []; + const rules: RewriteRule[] = [ + { + name: 'async', + include: {}, + apply: async () => { + await Promise.resolve(); + order.push('async'); + }, + }, + { name: 'sync', include: {}, apply: ctx => (order.push('sync'), wrapArrays(ctx)) }, + ]; + const result = createCallSiteRewriter(rules).transform('f([a]);', '/app/a.ts'); + expect(result).toBeInstanceOf(Promise); + expect((await result)?.code).toContain('wrap({ a })'); + expect(order).toEqual(['async', 'sync']); + }); + + it('warns about skipped sites, also when nothing changed', () => { + const warn = vi.fn(); + const result = createCallSiteRewriter([arrayRule], { logger: { warn } }).transform('f([g()]);', '/app/a.ts'); + expect(result).toBeNull(); + expect(warn).toHaveBeenCalledWith('[Sentry] Could not auto-instrument array in /app/a.ts.'); + }); + + it('hands each rule the module', () => { + let seen: Partial = {}; + const rule: RewriteRule = { name: 'spy', include: {}, apply: ctx => void (seen = ctx) }; + createCallSiteRewriter([rule]).transform('const a = 1;', '/app/a.ts'); + expect(seen.code).toBe('const a = 1;'); + expect(seen.id).toBe('/app/a.ts'); + expect((seen.ast?.body[0] as BaseNode).type).toBe('VariableDeclaration'); + }); +}); diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index 968e97e64223..bf411b2ef359 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -167,10 +167,14 @@ export function addIntegration(integration: Integration): void { /** * Define an integration function that can be used to create an integration instance. * Note that this by design hides the implementation details of the integration, as they are considered internal. + * + * `config.libraryOptions` names the options that take functions from a library, such as router hooks, rather than + * user code. */ /*#__NO_SIDE_EFFECTS__*/ export function defineIntegration( fn: Fn, + config?: { libraryOptions?: ReadonlyArray[0]> & string> }, ): (...args: Parameters) => Integration & { name: ReturnType['name'] } { return (...args: Parameters) => { // Copied before the integration runs, so its writes into the object it was given aren't reported as the user's. @@ -178,6 +182,7 @@ export function defineIntegration( const integration = fn(...args) as ReturnType; // Always set, since a wrapper can return an inner integration that holds the options the wrapper forced. integration._options = options; + integration._libraryOptions = config?.libraryOptions; return integration; }; diff --git a/packages/core/src/integrations/reportSdkConfig.ts b/packages/core/src/integrations/reportSdkConfig.ts index 2efdcfabb2c7..286bcd1b1028 100644 --- a/packages/core/src/integrations/reportSdkConfig.ts +++ b/packages/core/src/integrations/reportSdkConfig.ts @@ -6,6 +6,7 @@ import { count } from '../metrics/public-api'; import { Scope } from '../scope'; import type { Integration, IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; +import { fingerprintFunction } from '../utils/fingerprintFunction'; import { fnv1a32 } from '../utils/hash'; import { isPlainObject } from '../utils/is'; import { isBrowser } from '../utils/isBrowser'; @@ -55,7 +56,7 @@ export const experimentalReportSdkConfigIntegration = defineIntegration(_experim // and unsupported values with fingerprints before hashing the config. function serialize(value: unknown, ancestors = new Set()): unknown { if (typeof value === 'function') { - return `[Function:${fnv1a32(Function.prototype.toString.call(value))}]`; + return `[Function:${fingerprintFunction(value as (...args: never[]) => unknown)}]`; } // JSON throws on bigints and omits symbols. @@ -123,7 +124,11 @@ function buildConfigAttributes(client: Client): Record { options.integrations = integrationsSetByUser.map(name => { const integration: (Integration & { isDefaultInstance?: true }) | undefined = client.getIntegrationByName(name); // A default instance kept by an `integrations` function got its options from the SDK, not the user. - return describeIntegration(name, integration?.isDefaultInstance ? undefined : integration?._options); + return describeIntegration( + name, + integration?.isDefaultInstance ? undefined : integration?._options, + integration?._libraryOptions, + ); }); } @@ -134,7 +139,7 @@ function buildConfigAttributes(client: Client): Record { if (Array.isArray(options.defaultIntegrations)) { // `getIntegrationsToSetup` flags these as default instances, but the user passed them. options.defaultIntegrations = options.defaultIntegrations.map((integration: Integration) => - describeIntegration(integration.name, integration._options), + describeIntegration(integration.name, integration._options, integration._libraryOptions), ); } @@ -173,7 +178,11 @@ function describeShape(value: unknown, ancestors = new Set()): unknown { return shape; } -function describeIntegration(name: string, options: unknown): { name: string; options?: unknown } { +function describeIntegration( + name: string, + options: unknown, + libraryOptions: readonly string[] = [], +): { name: string; options?: unknown } { if (options === undefined) { return { name }; } @@ -190,12 +199,21 @@ function describeIntegration(name: string, options: unknown): { name: string; op const described: Record = {}; for (const key of keys) { - described[key] = describeOptionValue(options[key]); + const value = options[key]; + described[key] = libraryOptions.includes(key) ? describeLibraryValue(value) : describeOptionValue(value); } return { name, options: described }; } +/** + * Library functions and objects change with the library build and the engine, not with the config, so only their kind + * is reported. Primitives are stable, so they are kept. + */ +function describeLibraryValue(value: unknown): unknown { + return typeof value === 'function' ? '[Function]' : redactObject(value); +} + // Options can hold live objects such as a router, a store or an SDK client, which carry URLs, app state or keys. // Arrays are kept, since lists like `levels` or `tracePropagationTargets` are configuration. function describeOptionValue(value: unknown): unknown { diff --git a/packages/core/src/tracing/idleSpan.ts b/packages/core/src/tracing/idleSpan.ts index 334e191e69a7..9972082c0112 100644 --- a/packages/core/src/tracing/idleSpan.ts +++ b/packages/core/src/tracing/idleSpan.ts @@ -105,6 +105,9 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti // Timer that tracks maxSpanTime for child spans let _childSpanTimeoutID: ReturnType | undefined; + // Timer that tracks finalTimeout + let _finalTimeoutID: ReturnType | undefined; + // The reason why the span was finished let _finishReason: IdleSpanFinishReason = FINISH_REASON_EXTERNAL_FINISH; @@ -290,6 +293,11 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti _finished = true; activities.clear(); + // A pending timer keeps the span and its children reachable until it fires + _cancelIdleTimeout(); + _cancelChildSpanTimeout(); + clearTimeout(_finalTimeoutID); + _cleanupHooks.forEach(cleanup => cleanup()); _setSpanForScope(scope, previousActiveSpan); @@ -411,7 +419,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti _restartIdleTimeout(); } - setTimeout(() => { + _finalTimeoutID = setTimeout(() => { if (!_finished) { span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' }); _finishReason = FINISH_REASON_FINAL_TIMEOUT; diff --git a/packages/core/src/types/integration.ts b/packages/core/src/types/integration.ts index 78e4824695ec..d42ea54cdbeb 100644 --- a/packages/core/src/types/integration.ts +++ b/packages/core/src/types/integration.ts @@ -12,6 +12,12 @@ export interface Integration { /** @internal Options captured for SDK configuration reporting. */ _options?: unknown; + /** + * @internal Options that hold functions from a library, such as router hooks, rather than user code. SDK + * configuration reporting leaves their fingerprints out, since those change with the library build, not the config. + */ + _libraryOptions?: readonly string[]; + /** * This hook is only called once, even if multiple clients are created. * It does not receives any arguments, and should only use for e.g. global monkey patching and similar things. diff --git a/packages/core/src/utils/fingerprintFunction.ts b/packages/core/src/utils/fingerprintFunction.ts new file mode 100644 index 000000000000..9eefa7812713 --- /dev/null +++ b/packages/core/src/utils/fingerprintFunction.ts @@ -0,0 +1,103 @@ +import { fnv1a32 } from './hash'; + +/** + * Keywords minifiers never rename and that change what a function does. + * Contextual words (`async`, `of`, `get`, `set`, `static`) are left out on purpose: minifiers may use them as names. + */ +const KEYWORDS = new Set( + 'break catch const continue default delete else finally for function if instanceof let new switch throw try var while await return typeof void in case this null true false undefined'.split( + ' ', + ), +); + +/** + * One alternative per kind of token: whitespace and comments, quoted string, backtick, spread, increment, a name (with + * an optional leading `.` or `?.` and a lookahead for a following `:`), regex literal, number, and any other character. + */ +const TOKEN = + /(?:\s|\/\/.*|\/\*[^]*?(?:\*\/|$))+|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`|\.\.\.|\+\+|--|(\??\.#?|#)?([A-Za-z_$][\w$]*)(?=(\s*:)?)|\/(?:[^/\\\n[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+\/\w*|\d[\w.]*|[^]/g; + +/** + * The rest of a template part, up to the closing backtick or the next `${`. + */ +const TEMPLATE = /(?:[^`\\$]|\\.|\$(?!\{))*(?:`|\$\{|$)/y; + +/** + * Tokens after which a `/` is a division rather than the start of a regex literal. + */ +const ENDS_VALUE = /(?:[\w$"'`)\]]|\+\+|--)$/; + +/** + * Matches the source text engines report for built-in and bound functions, which has no real body and is spelled + * differently by each engine. + */ +const NATIVE = /\{\s*\[native code\]\s*\}\s*$/; + +/** + * Fingerprints a function with every name a minifier can rename blanked out, so that a bundler renaming identifiers + * doesn't change the result. + * + * This is a regex-driven scan rather than a parser, kept small for bundle size. It only aims to be stable across + * builds made with the same minifier: inlined helpers, reordered operands, different quote or number spellings, and + * shorthand keys written out in full still change the result. Method names and shorthand keys are blanked like any + * other name, and a label at the start of a block is kept like an object key. + */ +export function fingerprintFunction(fn: (...args: never[]) => unknown): string { + let source: string; + try { + source = Function.prototype.toString.call(fn); + } catch { + return 'unknown'; + } + + if (NATIVE.test(source)) { + return 'native'; + } + + return fnv1a32(tokenize(source).join(' ')); +} + +/** + * Splits source into tokens, replacing every name that is not a keyword, a property or an object key with `_`. + */ +export function tokenize(src: string): string[] { + const tokens: string[] = []; + // `true` for each open `${`, `false` for each open `{`. + const braces: boolean[] = []; + let prev = ''; + let match; + TOKEN.lastIndex = 0; + + while ((match = TOKEN.exec(src))) { + let token = match[0]; + const ch = token[0] as string; + + if (ch <= ' ' || (ch === '/' && (token[1] === '/' || token[1] === '*'))) { + continue; + } + + if (ch === '`' || (ch === '}' && braces.pop())) { + TEMPLATE.lastIndex = TOKEN.lastIndex; + TEMPLATE.test(src); + token = src.slice(match.index, (TOKEN.lastIndex = TEMPLATE.lastIndex)); + if (token.endsWith('${')) { + braces.push(true); + } + } else if (ch === '{') { + braces.push(false); + } else if (match[2]) { + // Property names and object keys survive minification, every other name is anonymous. + if (!match[1] && !KEYWORDS.has(token) && !(match[3] && (prev === '{' || prev === ','))) { + token = '_'; + } + } else if (ch === '/' && token[1] && ENDS_VALUE.test(prev) && (!KEYWORDS.has(prev) || prev === 'this')) { + // A division, not a regex literal: emit the slash alone and rescan what follows. + token = ch; + TOKEN.lastIndex = match.index + 1; + } + + tokens.push((prev = token)); + } + + return tokens; +} diff --git a/packages/core/test/lib/integration.test.ts b/packages/core/test/lib/integration.test.ts index 1702650a52b1..d92ef6e087b6 100644 --- a/packages/core/test/lib/integration.test.ts +++ b/packages/core/test/lib/integration.test.ts @@ -881,4 +881,13 @@ describe('defineIntegration', () => { expect(wrapperIntegration({ sampleRate: 0.5 })._options).toEqual({ sampleRate: 0.5 }); }); + + it('records the options that take library functions', () => { + const routerIntegration = defineIntegration( + (_options: { useLocation?: () => void; shouldCreateSpan?: () => boolean } = {}) => ({ name: 'Router' }), + { libraryOptions: ['useLocation'] }, + ); + + expect(routerIntegration()._libraryOptions).toEqual(['useLocation']); + }); }); diff --git a/packages/core/test/lib/integrations/reportSdkConfig.test.ts b/packages/core/test/lib/integrations/reportSdkConfig.test.ts index 5e0114362da4..4e444314e3cd 100644 --- a/packages/core/test/lib/integrations/reportSdkConfig.test.ts +++ b/packages/core/test/lib/integrations/reportSdkConfig.test.ts @@ -226,6 +226,23 @@ describe('experimentalReportSdkConfigIntegration', () => { expect((payload.options as Record).initialScope).toMatch(/^\[Function:\w+\]$/); }); + it('reports callbacks that differ only in their local names as the same function', () => { + const report = (beforeSend: (event: unknown) => unknown): Record => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ beforeSend, integrations: [experimentalReportSdkConfigIntegration()] }), + }), + ).options as Record; + + const original = report(event => event); + const renamed = report(e => e); + const dropsEverything = report(() => null); + + expect(renamed.beforeSend).toBe(original.beforeSend); + expect(dropsEverything.beforeSend).not.toBe(original.beforeSend); + }); + it('reports the names of the default integrations the user passed', () => { const userOptions = captureOptionsSetByUser({ defaultIntegrations: [experimentalReportSdkConfigIntegration()], @@ -436,6 +453,62 @@ describe('experimentalReportSdkConfigIntegration', () => { }); }); + it('reports library functions in integration options without a fingerprint, unlike user callbacks', () => { + const routerIntegration = defineIntegration( + (_options: { useLocation?: () => unknown; shouldCreateSpan?: () => boolean } = {}) => ({ name: 'Router' }), + { libraryOptions: ['useLocation'] }, + ); + const reportRouter = (useLocation: () => unknown): Record => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ + integrations: [ + experimentalReportSdkConfigIntegration(), + routerIntegration({ useLocation, shouldCreateSpan: () => false }), + ], + }), + }), + ); + + const payload = reportRouter(() => 'react-router@6'); + + expect(payload.options).toEqual({ + integrations: [ + { name: 'ExperimentalReportSdkConfig' }, + { + name: 'Router', + options: { shouldCreateSpan: expect.stringMatching(/^\[Function:\w+\]$/), useLocation: '[Function]' }, + }, + ], + }); + expect(reportRouter(() => 'react-router@7')).toEqual(payload); + }); + + it('reports library objects as placeholders and keeps library primitives', () => { + const routerIntegration = defineIntegration( + (_options: { history?: unknown; routes?: unknown[]; version?: string; basename?: string } = {}) => ({ + name: 'Router', + }), + { libraryOptions: ['history', 'routes', 'version'] }, + ); + const userOptions = captureOptionsSetByUser({ + integrations: [ + experimentalReportSdkConfigIntegration(), + routerIntegration({ history: { length: 1 }, routes: ['/users'], version: '6.22.0', basename: '/app' }), + ], + }); + + const payload = reportConfig(getDefaultTestClientOptions({ dsn: 'https://username@domain/123', ...userOptions })); + + expect(payload.options).toEqual({ + integrations: [ + { name: 'ExperimentalReportSdkConfig' }, + { name: 'Router', options: { basename: '/app', history: '[Object]', routes: '[Object]', version: '6.22.0' } }, + ], + }); + }); + it('reports integration options as passed, even when the integration writes into them', () => { const mutatingIntegration = defineIntegration((options: { capture?: boolean } = {}) => { options.capture = false; diff --git a/packages/core/test/lib/tracing/idleSpan.test.ts b/packages/core/test/lib/tracing/idleSpan.test.ts index d9a37209a1d6..5c6a27a29a2e 100644 --- a/packages/core/test/lib/tracing/idleSpan.test.ts +++ b/packages/core/test/lib/tracing/idleSpan.test.ts @@ -695,6 +695,37 @@ describe('startIdleSpan', () => { }); }); + describe('pending timers', () => { + it('leaves no timer behind when the span ends via idle timeout', () => { + const timersBefore = vi.getTimerCount(); + + const idleSpan = startIdleSpan({ name: 'idle span' }); + vi.advanceTimersByTime(TRACING_DEFAULTS.idleTimeout); + + expect(spanToJSON(idleSpan).end_timestamp).toBeDefined(); + expect(vi.getTimerCount()).toBe(timersBefore); + }); + + it('leaves no timer behind when the span is ended externally', () => { + const timersBefore = vi.getTimerCount(); + + const idleSpan = startIdleSpan({ name: 'idle span' }); + idleSpan.end(); + + expect(vi.getTimerCount()).toBe(timersBefore); + }); + + it('leaves no timer behind when the span is ended externally with an open child span', () => { + const timersBefore = vi.getTimerCount(); + + const idleSpan = startIdleSpan({ name: 'idle span' }); + startInactiveSpan({ name: 'inner' }); + idleSpan.end(); + + expect(vi.getTimerCount()).toBe(timersBefore); + }); + }); + describe('child span timeout', () => { it('finishes when a child span exceed timeout', () => { const idleSpan = startIdleSpan({ name: 'idle span' }); diff --git a/packages/core/test/lib/utils/fingerprintFunction.test.ts b/packages/core/test/lib/utils/fingerprintFunction.test.ts new file mode 100644 index 000000000000..90dad6fbd5c6 --- /dev/null +++ b/packages/core/test/lib/utils/fingerprintFunction.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { fingerprintFunction, tokenize } from '../../../src/utils/fingerprintFunction'; + +const norm = (src: string): string => tokenize(src).join(' '); + +describe('fingerprintFunction', () => { + describe('stays the same when only minification changes', () => { + it.each([ + ['renamed locals and imports', 'e=>n(e)?null:e', 't=>r(t)?null:t'], + ['spread of a renamed local', 'e=>({...e.tags})', 't=>({...t.tags})'], + ['whitespace', 'e => e', 'e=>e'], + ['comments', 'e=>e // keep all\n', 'e=>/* keep */e'], + ['renamed ternary branches', '(a,b)=>a?b:a', '(x,y)=>x?y:x'], + ['renamed destructuring targets', '({event:e})=>e', '({event:t})=>t'], + ['renamed names in template substitutions', "e=>`'${n(e)}' and '${e}'`", "t=>`'${r(t)}' and '${t}'`"], + ['renamed names after a regex containing quotes', `e=>/["']/.test(e)?n("x"):r`, `t=>/["']/.test(t)?a("x"):o`], + ['renamed operands of a division', 'e=>e/n/r', 't=>t/a/o'], + ['renamed call arguments inside an object', 'e=>({a:f(x,y,z)})', 't=>({a:g(p,q,r)})'], + ['renamed array items inside an object', 'e=>({a:[x,y,z]})', 't=>({a:[p,q,r]})'], + ['renamed arrow parameters inside an object', 'e=>({a:(x,y,z)=>x})', 't=>({a:(p,q,r)=>p})'], + ])('%s', (_label, a, b) => { + expect(norm(a)).toBe(norm(b)); + }); + }); + + describe('changes when behavior changes', () => { + it.each([ + ['always null vs passthrough', '()=>null', 'e=>e'], + ['return null vs return event', 'function(e){return null}', 'function(e){return e}'], + ['return undefined vs return event', 'function(e){return undefined}', 'function(e){return e}'], + ['property', 'e=>e.exception?e:null', 'e=>e.message?e:null'], + ['optional chaining property', 'e=>e?.exception?e:null', 'e=>e?.message?e:null'], + ['string literal', `e=>e.type==="transaction"?null:e`, `e=>e.type==="error"?null:e`], + ['bracket key', `e=>e["exception"]?e:null`, `e=>e["message"]?e:null`], + ['template literal', 'e=>`${e.level}:drop`', 'e=>`${e.level}:keep`'], + ['regex literal', 'e=>/foo/.test(e.message)?null:e', 'e=>/bar/.test(e.message)?null:e'], + ['regex flags', 'e=>/foo/i.test(e)', 'e=>/foo/g.test(e)'], + ['number', 'e=>Math.random()<0.1?e:null', 'e=>Math.random()<1?e:null'], + ['branches swapped', 'e=>n(e)?null:e', 'e=>n(e)?e:null'], + ['throw vs return', 'e=>{throw e}', 'e=>{return e}'], + ['object key', 'e=>({level:e})', 'e=>({type:e})'], + ['private field', 'e=>e.#a', 'e=>e.#b'], + ['destructured key', 'e=>{const{exception:t}=e;return t}', 'e=>{const{message:t}=e;return t}'], + ['thrown object key', 'e=>{throw{level:e}}', 'e=>{throw{type:e}}'], + ['regex after a block', 'e=>{if(e){return e}/a/.test(e)}', 'e=>{if(e){return e}/b/.test(e)}'], + ])('%s', (_label, a, b) => { + expect(norm(a)).not.toBe(norm(b)); + }); + }); + + describe('tokenizer', () => { + it('tells a regex from a division', () => { + expect(norm('e=>e/2/1')).toBe('_ = > _ / 2 / 1'); + expect(norm('e=>/2/.test(e)')).toBe('_ = > /2/ .test ( _ )'); + }); + + it('keeps regex character classes containing slashes intact', () => { + expect(norm('e=>/[/]a/.test(e)')).toBe('_ = > /[/]a/ .test ( _ )'); + }); + + it('handles nested template literals and object literals in substitutions', () => { + expect(norm('e=>`a${`b${e}`}c${({k:e})}`')).toBe('_ = > `a${ `b${ _ }` }c${ ( { k : _ } ) }`'); + }); + + it('reads a regex inside a template substitution and a division after a template', () => { + expect(norm('e=>`${/a/.test(e)}`')).toBe('_ = > `${ /a/ .test ( _ ) }`'); + expect(norm('e=>`${e}`/2/e')).toBe('_ = > `${ _ }` / 2 / _'); + }); + + it('cannot tell a label at the start of a block from an object key', () => { + expect(norm('e=>{a:e}')).toBe('_ = > { a : _ }'); + }); + + it('survives unterminated input', () => { + expect(() => norm('e=>"abc')).not.toThrow(); + expect(() => norm('e=>`abc${')).not.toThrow(); + expect(() => norm('e=>/abc')).not.toThrow(); + expect(() => norm('e=>/* abc')).not.toThrow(); + expect(() => norm('}}}}')).not.toThrow(); + expect(() => norm('`a\\`')).not.toThrow(); + }); + + it('keeps spread and increments whole', () => { + expect(norm('a++ +b-- -c')).toBe('_ ++ + _ -- - _'); + expect(norm('f(...a,..b)')).toBe('_ ( ... _ , . .b )'); + }); + + it('keeps object keys next to calls and arrays, and in objects nested inside them', () => { + expect(norm('({a:f(x,y),b:[y,{c:z}]})')).toBe('( { a : _ ( _ , _ ) , b : [ _ , { c : _ } ] } )'); + }); + + it('does not mistake a ternary branch for an object key', () => { + expect(norm('f(x,a?b:c)')).toBe('_ ( _ , _ ? _ : _ )'); + }); + + it('keeps object keys but not shorthand keys or method names', () => { + expect(norm('e=>({a:1,b(){},c,...d})')).toBe('_ = > ( { a : 1 , _ ( ) { } , _ , ... _ } )'); + }); + + it('keeps `undefined` but no other global', () => { + expect(norm('e=>Math.now()===undefined')).toBe('_ = > _ .now ( ) = = = undefined'); + }); + + it('tells a regex from a division after keywords, operators and closing brackets', () => { + expect(norm('return/a/g')).toBe('return /a/g'); + expect(norm('this/a/g')).toBe('this / _ / _'); + expect(norm('(a)/b/c')).toBe('( _ ) / _ / _'); + expect(norm('e=>e++/2+n(e)')).toBe('_ = > _ ++ / 2 + _ ( _ )'); + expect(norm('e=>e--/2')).toBe('_ = > _ -- / 2'); + expect(norm('({}/2)')).toBe('( { } / 2 )'); + expect(norm('if(a){}/a/g')).toBe('if ( _ ) { } /a/g'); + expect(norm('e=>e?/a/.test(e):e')).toBe('_ = > _ ? /a/ .test ( _ ) : _'); + }); + }); + + it('marks built-in and bound functions as native', () => { + const bound = function (this: unknown): unknown { + return this; + }.bind(null); + + expect(fingerprintFunction(bound)).toBe('native'); + expect(fingerprintFunction(Math.max)).toBe('native'); + expect(fingerprintFunction(() => '{ [native code] }'.length)).not.toBe('native'); + }); + + it('fingerprints functions', () => { + expect(fingerprintFunction(e => e)).toBe(fingerprintFunction(t => t)); + expect(fingerprintFunction(() => null)).not.toBe(fingerprintFunction(e => e)); + }); +}); diff --git a/packages/eslint-plugin-sdk/src/index.js b/packages/eslint-plugin-sdk/src/index.js index e1f27895b734..e3d5e94786ef 100644 --- a/packages/eslint-plugin-sdk/src/index.js +++ b/packages/eslint-plugin-sdk/src/index.js @@ -20,5 +20,6 @@ module.exports = { 'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'), 'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'), 'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'), + 'require-define-integration': require('./rules/require-define-integration'), }, }; diff --git a/packages/eslint-plugin-sdk/src/rules/require-define-integration.js b/packages/eslint-plugin-sdk/src/rules/require-define-integration.js new file mode 100644 index 000000000000..80012088fd71 --- /dev/null +++ b/packages/eslint-plugin-sdk/src/rules/require-define-integration.js @@ -0,0 +1,189 @@ +'use strict'; + +/** + * @fileoverview Rule to require that integrations are created with `defineIntegration`. + * + * `defineIntegration` records the options an integration was created with on `_options`. An + * integration that returns its object directly works, but its options are never recorded. + * + * Oxlint offers no type information to JS plugins, so the rule looks for the shape of an integration + * instead: an object literal with a `name` and at least one integration hook. Such an object is fine + * when the function that builds it reaches `defineIntegration` within the same file, either because + * it is passed to it or because a function that is passed to it uses it. + */ + +const { splitPackagePath } = require('../utils/browser-facing'); + +const INTEGRATION_HOOKS = new Set([ + 'setupOnce', + 'beforeSetup', + 'setup', + 'afterAllSetup', + 'preprocessEvent', + 'processEvent', + 'processSpan', + 'processSegmentSpan', +]); + +/** + * Bundler and framework plugins are also `{ name, setup }` objects, so the files that define them are + * skipped. Paths are relative to `packages/`. + */ +const PLUGIN_PATHS = [ + /^bundler-plugins\//, + /^server-runtime-injection\//, + /^bun\/src\/plugin\.ts$/, + /^nitro\/src\/(?:module|orchestrion)\.ts$/, + /^node\/src\/bundler-plugin\//, + /^nuxt\/src\/runtime\/plugins\//, + /^server-utils\/src\/orchestrion\/bundler\//, + /^tanstackstart-react\/src\/vite\//, +]; + +const TRANSPARENT_WRAPPERS = new Set([ + 'TSSatisfiesExpression', + 'TSAsExpression', + 'TSNonNullExpression', + 'ParenthesizedExpression', +]); + +const FUNCTIONS = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration']); + +function isPluginFile(filename) { + const location = splitPackagePath(filename); + if (!location) { + return false; + } + + const path = `${location.pkg}/${location.path}`; + + return PLUGIN_PATHS.some(pattern => pattern.test(path)); +} + +function isDefineIntegrationCall(node) { + if (node.type !== 'CallExpression') { + return false; + } + + const callee = node.callee; + + return ( + (callee.type === 'Identifier' && callee.name === 'defineIntegration') || + (callee.type === 'MemberExpression' && !callee.computed && callee.property.name === 'defineIntegration') + ); +} + +function getPropertyName(property) { + if (property.type !== 'Property' || property.computed) { + return undefined; + } + + return property.key.type === 'Identifier' ? property.key.name : property.key.value; +} + +/** The name a function can be referred to by: its own, or the variable it is assigned to. */ +function getFunctionName(node) { + if (node.id) { + return node.id.name; + } + + let parent = node.parent; + while (parent && TRANSPARENT_WRAPPERS.has(parent.type)) { + parent = parent.parent; + } + + return parent?.type === 'VariableDeclarator' && parent.id.type === 'Identifier' ? parent.id.name : undefined; +} + +module.exports = { + meta: { + type: 'problem', + docs: { + description: 'Require integrations to be created with `defineIntegration`', + category: 'Possible Errors', + recommended: true, + }, + fixable: null, + schema: [], + messages: { + requireDefineIntegration: + 'Integrations must be created with `defineIntegration`. Without it, the options the integration was created with are not recorded.', + }, + }, + create: function (context) { + if (isPluginFile(context.getFilename())) { + return {}; + } + + /** Names used inside a `defineIntegration(...)` call. */ + const defined = new Set(); + /** Names used inside each named function, to follow helpers that build the object. */ + const usedByFunction = new Map(); + const candidates = []; + + /** Names of the functions around `node`, or `undefined` when it is inside `defineIntegration(...)`. */ + function getEnclosingFunctionNames(node) { + const names = []; + for (let parent = node.parent; parent; parent = parent.parent) { + if (isDefineIntegrationCall(parent)) { + return undefined; + } + + const name = FUNCTIONS.has(parent.type) ? getFunctionName(parent) : undefined; + if (name) { + names.push(name); + } + } + + return names; + } + + return { + Identifier(node) { + const functionNames = getEnclosingFunctionNames(node); + if (!functionNames) { + defined.add(node.name); + + return; + } + + for (const functionName of functionNames) { + if (!usedByFunction.has(functionName)) { + usedByFunction.set(functionName, new Set()); + } + usedByFunction.get(functionName).add(node.name); + } + }, + + ObjectExpression(node) { + const names = node.properties.map(getPropertyName); + if (!names.includes('name') || !names.some(name => INTEGRATION_HOOKS.has(name))) { + return; + } + + const functionNames = getEnclosingFunctionNames(node); + if (functionNames) { + candidates.push({ node, functionNames }); + } + }, + + 'Program:exit'() { + const pending = [...defined]; + while (pending.length) { + for (const name of usedByFunction.get(pending.pop()) || []) { + if (!defined.has(name)) { + defined.add(name); + pending.push(name); + } + } + } + + for (const { node, functionNames } of candidates) { + if (!functionNames.some(name => defined.has(name))) { + context.report({ node, messageId: 'requireDefineIntegration' }); + } + } + }, + }; + }, +}; diff --git a/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts b/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts new file mode 100644 index 000000000000..536f817354b3 --- /dev/null +++ b/packages/eslint-plugin-sdk/test/lib/rules/require-define-integration.test.ts @@ -0,0 +1,114 @@ +import { RuleTester } from 'eslint'; +import { describe, test } from 'vitest'; +// @ts-expect-error untyped module +import rule from '../../../src/rules/require-define-integration'; + +const errors = [{ messageId: 'requireDefineIntegration', type: 'ObjectExpression' }]; + +describe('require-define-integration', () => { + test('ruleTester', () => { + const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2020, + sourceType: 'module', + }, + }); + + ruleTester.run('require-define-integration', rule, { + valid: [ + { + code: "export const fooIntegration = defineIntegration(() => ({ name: 'Foo', setup() {} }));", + }, + { + code: "export const fooIntegration = core.defineIntegration(() => ({ name: 'Foo', setup() {} }));", + }, + { + code: ` + const _fooIntegration = () => { + return { name: 'Foo', setupOnce() {} }; + }; + export const fooIntegration = defineIntegration(_fooIntegration); + `, + }, + // The object is built by a helper of the function that is passed to `defineIntegration`. + { + code: ` + function buildFoo(options) { + return { name: 'Foo', processEvent: event => event }; + } + const _fooIntegration = options => buildFoo(options); + export const fooIntegration = defineIntegration(_fooIntegration); + `, + }, + { + code: ` + function buildFoo(options) { + return { name: 'Foo', setup() {} }; + } + export const fooIntegration = defineIntegration(options => buildFoo(options)); + `, + }, + // A factory that wraps the integration itself. + { + code: ` + export function createFooIntegration(name) { + return defineIntegration(() => ({ name, setup() {} })); + } + `, + }, + // No hook, so not an integration. + { + code: "export const foo = () => ({ name: 'Foo', handler() {} });", + }, + // No name, so not an integration. + { + code: 'export const foo = () => ({ setup() {} });', + }, + // Bundler plugins share the `{ name, setup }` shape. + { + filename: '/repo/packages/bundler-plugins/src/esbuild/index.ts', + code: "export const plugin = () => ({ name: 'sentry-esbuild-plugin', setup(build) {} });", + }, + ], + invalid: [ + { + code: "export const fooIntegration = () => ({ name: 'Foo', setup() {} });", + errors, + }, + { + code: ` + export function fooIntegration() { + return { name: 'Foo', setupOnce() {} }; + } + `, + errors, + }, + // The function is never passed to `defineIntegration`. + { + code: ` + const _fooIntegration = () => { + return { name: 'Foo', processSpan() {} }; + }; + export const fooIntegration = _fooIntegration; + `, + errors, + }, + // `defineIntegration` wraps another integration of the file, not this one. + { + code: ` + const _fooIntegration = () => ({ name: 'Foo', setup() {} }); + const _barIntegration = () => ({ name: 'Bar', setup() {} }); + export const fooIntegration = defineIntegration(_fooIntegration); + export const barIntegration = _barIntegration; + `, + errors, + }, + { + filename: '/repo/packages/node/src/integrations/foo.ts', + code: "export const fooIntegration = () => ({ name: 'Foo', afterAllSetup() {} });", + errors, + }, + ], + }); + }); +}); diff --git a/packages/feedback/src/modal/integration.tsx b/packages/feedback/src/modal/integration.tsx index d424cd1de813..3b4c7c81343d 100644 --- a/packages/feedback/src/modal/integration.tsx +++ b/packages/feedback/src/modal/integration.tsx @@ -1,5 +1,5 @@ import type { FeedbackFormData, FeedbackModalIntegration, IntegrationFn, User } from '@sentry/core'; -import { getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core'; +import { defineIntegration, getClient, getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core'; import { h, render } from 'preact'; import * as hooks from 'preact/hooks'; import { DOCUMENT } from '../constants'; @@ -19,7 +19,7 @@ function getUser(): User | undefined { return globalUser; } -export const feedbackModalIntegration = ((): FeedbackModalIntegration => { +const _feedbackModalIntegration = ((): FeedbackModalIntegration => { return { name: 'FeedbackModal' as const, setupOnce() {}, @@ -131,3 +131,7 @@ export const feedbackModalIntegration = ((): FeedbackModalIntegration => { }, }; }) satisfies IntegrationFn; + +export const feedbackModalIntegration = defineIntegration( + _feedbackModalIntegration, +) as typeof _feedbackModalIntegration; diff --git a/packages/feedback/src/screenshot/integration.ts b/packages/feedback/src/screenshot/integration.ts index 38c6349cd1a6..fdf1faf3081c 100644 --- a/packages/feedback/src/screenshot/integration.ts +++ b/packages/feedback/src/screenshot/integration.ts @@ -1,10 +1,11 @@ import type { Attachment, FeedbackScreenshotIntegration, IntegrationFn } from '@sentry/core'; +import { defineIntegration } from '@sentry/core'; import type { h as hType } from 'preact'; import type * as Hooks from 'preact/hooks'; import { DOCUMENT } from '../constants'; import { ScreenshotEditorFactory } from './components/ScreenshotEditor'; -export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => { +const _feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration => { return { name: 'FeedbackScreenshot' as const, setupOnce() {}, @@ -40,3 +41,7 @@ export const feedbackScreenshotIntegration = ((): FeedbackScreenshotIntegration }, }; }) satisfies IntegrationFn; + +export const feedbackScreenshotIntegration = defineIntegration( + _feedbackScreenshotIntegration, +) as typeof _feedbackScreenshotIntegration; diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index f255e293fcb4..d431397a0aa7 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -6,7 +6,7 @@ import { startSpan } from '@sentry/node'; import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils'; import { DEBUG_BUILD } from './debug-build'; import { isExpectedError } from './helpers'; -import type { ReflectWithMetadata } from './integrations/helpers'; +import type { ReflectWithMetadata } from './helpers'; import { copyReflectMetadata, getNestScheduleVersion, markSentryCronMethod } from './integrations/helpers'; /** diff --git a/packages/nestjs/src/helpers.ts b/packages/nestjs/src/helpers.ts index 56f9a5704b32..d443fcae538d 100644 --- a/packages/nestjs/src/helpers.ts +++ b/packages/nestjs/src/helpers.ts @@ -45,3 +45,14 @@ export function isWsOrRpcException(exception: unknown): boolean { return typeof exception.getError === 'function' && typeof exception.initMessage === 'function'; } + +/** + * The subset of `reflect-metadata`'s `Reflect` augmentation that NestJS + * relies on. Methods are optional because `reflect-metadata` may not be + * loaded; guard each before use. + */ +export interface ReflectWithMetadata { + getMetadataKeys?: (target: object) => unknown[]; + getMetadata?: (key: unknown, target: object) => unknown; + defineMetadata?: (key: unknown, value: unknown, target: object) => void; +} diff --git a/packages/nestjs/src/integrations/helpers.ts b/packages/nestjs/src/integrations/helpers.ts index dd759e13825a..1786d78e9823 100644 --- a/packages/nestjs/src/integrations/helpers.ts +++ b/packages/nestjs/src/integrations/helpers.ts @@ -16,7 +16,8 @@ import { isObjectLike, withActiveSpan, } from '@sentry/core'; -import type { CatchTarget, InjectableTarget, NextFunction, Observable, Subscription } from './types'; +import type { ReflectWithMetadata } from '../helpers'; +import type { CatchTarget, InjectableTarget, NextFunction } from './types'; /** A function of unknown signature, matching the methods/handlers we wrap. */ export type AnyFn = (this: unknown, ...args: unknown[]) => unknown; @@ -95,17 +96,6 @@ export function getNestScheduleVersion(cronOptions: object): string | undefined return NEST_SCHEDULE_VERSIONS.get(cronOptions); } -/** - * The subset of `reflect-metadata`'s `Reflect` augmentation that NestJS - * relies on. Methods are optional because `reflect-metadata` may not be - * loaded; guard each before use. - */ -export interface ReflectWithMetadata { - getMetadataKeys?: (target: object) => unknown[]; - getMetadata?: (key: unknown, target: object) => unknown; - defineMetadata?: (key: unknown, value: unknown, target: object) => void; -} - /** * Copy NestJS reflect-metadata from one object onto another so decorators * (param decorators, guards, `@EventPattern`, ...) that read it keep working @@ -224,25 +214,6 @@ export function getBullMQProcessSpanOptions(queueName: string | undefined): { }; } -/** - * Adds instrumentation to a js observable and attaches the span to an active - * parent span. - */ -export function instrumentObservable(observable: Observable, activeSpan: Span | undefined): void { - if (activeSpan) { - // eslint-disable-next-line @typescript-eslint/unbound-method - observable.subscribe = new Proxy(observable.subscribe, { - apply: (originalSubscribe, thisArgSubscribe, argsSubscribe) => { - return withActiveSpan(activeSpan, () => { - const subscription: Subscription = originalSubscribe.apply(thisArgSubscribe, argsSubscribe); - subscription.add(() => activeSpan.end()); - return subscription; - }); - }, - }); - } -} - /** * Proxies the next() call in a nestjs middleware to end the span when called */ diff --git a/packages/nestjs/src/integrations/types.ts b/packages/nestjs/src/integrations/types.ts index 626cdbafc1f6..2939566e977c 100644 --- a/packages/nestjs/src/integrations/types.ts +++ b/packages/nestjs/src/integrations/types.ts @@ -1,5 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ +import type { Observable } from '../observable'; + // Partial extract of FastifyRequest interface // https://github.com/fastify/fastify/blob/87f9f20687c938828f1138f91682d568d2a31e53/types/request.d.ts#L41 interface FastifyRequest { @@ -41,17 +43,6 @@ export interface MinimalNestJsApp { }) => void; } -export interface Subscription { - add(...args: any[]): void; -} - -/** - * A minimal interface for an Observable. - */ -export interface Observable { - subscribe(next?: (value: T) => void, error?: (err: any) => void, complete?: () => void): Subscription; -} - /** * A NestJS call handler. Used in interceptors to start the route execution. */ diff --git a/packages/nestjs/src/integrations/wrap-components.ts b/packages/nestjs/src/integrations/wrap-components.ts index 5a0dc965da98..827d3bb23460 100644 --- a/packages/nestjs/src/integrations/wrap-components.ts +++ b/packages/nestjs/src/integrations/wrap-components.ts @@ -1,8 +1,10 @@ import type { Span } from '@sentry/core'; import { getActiveSpan, isThenable, startInactiveSpan, startSpan, startSpanManual, withActiveSpan } from '@sentry/core'; import type { AnyFn } from './helpers'; -import { getMiddlewareSpanOptions, getNextProxy, instrumentObservable, isTargetPatched } from './helpers'; -import type { CallHandler, CatchTarget, InjectableTarget, MinimalNestJsExecutionContext, Observable } from './types'; +import type { Observable } from '../observable'; +import { instrumentObservable } from '../observable'; +import { getMiddlewareSpanOptions, getNextProxy, isTargetPatched } from './helpers'; +import type { CallHandler, CatchTarget, InjectableTarget, MinimalNestJsExecutionContext } from './types'; /** * Shared span-emitting logic for `@Injectable` diff --git a/packages/nestjs/src/integrations/wrap-handlers.ts b/packages/nestjs/src/integrations/wrap-handlers.ts index a9fcb58289d5..2602533dc054 100644 --- a/packages/nestjs/src/integrations/wrap-handlers.ts +++ b/packages/nestjs/src/integrations/wrap-handlers.ts @@ -8,7 +8,8 @@ import { withMonitor, } from '@sentry/core'; import { resolveCronMonitor } from './cron-monitoring'; -import type { AnyFn, ReflectWithMetadata } from './helpers'; +import type { ReflectWithMetadata } from '../helpers'; +import type { AnyFn } from './helpers'; import { getBullMQProcessSpanOptions, getEventSpanOptions, diff --git a/packages/nestjs/src/observable.ts b/packages/nestjs/src/observable.ts new file mode 100644 index 000000000000..b08e72734eaf --- /dev/null +++ b/packages/nestjs/src/observable.ts @@ -0,0 +1,86 @@ +import type { Span } from '@sentry/core'; +import { withActiveSpan } from '@sentry/core'; + +export interface Subscription { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + add(...args: any[]): void; +} + +/** + * A minimal interface for an Observable. + */ +export interface Observable { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + subscribe(next?: (value: T) => void, error?: (err: any) => void, complete?: () => void): Subscription; +} + +/** + * Adds instrumentation to a js observable and attaches the span to an active + * parent span. + */ +export function instrumentObservable( + observable: Observable, + activeSpan: Span | undefined, + onError?: (error: unknown) => void, +): void { + if (activeSpan) { + // eslint-disable-next-line @typescript-eslint/unbound-method + observable.subscribe = new Proxy(observable.subscribe, { + apply: (originalSubscribe, thisArgSubscribe, argsSubscribe) => { + return withActiveSpan(activeSpan, () => { + const subscribeArgs = onError ? withErrorCallback(argsSubscribe, onError) : argsSubscribe; + const subscription: Subscription = originalSubscribe.apply(thisArgSubscribe, subscribeArgs); + subscription.add(() => activeSpan.end()); + return subscription; + }); + }, + }); + } +} + +/** Returns `subscribe()` arguments whose error handler calls `onError` first. */ +function withErrorCallback(args: unknown[], onError: (error: unknown) => void): unknown[] { + const [observer] = args; + + // RxJS ignores the positional callbacks when it gets an observer object, so the object's `error` is the + // one that runs. Nest subscribes this way, with a Subscriber. + if (observer && typeof observer === 'object') { + return [wrapObserver(observer, onError), ...args.slice(1)]; + } + + const wrapped = [...args]; + wrapped[1] = wrapErrorHandler(args[1], onError); + return wrapped; +} + +function wrapObserver(observer: object, onError: (error: unknown) => void): object { + return new Proxy(observer, { + get(target, property) { + const value = Reflect.get(target, property, target); + if (property === 'error') { + return wrapErrorHandler(value, onError, target); + } + // A Subscriber's methods read its own private state, so they must run with the observer as `this`, + // not the proxy. + if ((property === 'next' || property === 'complete') && typeof value === 'function') { + return (...args: unknown[]) => Reflect.apply(value, target, args); + } + return value; + }, + }); +} + +function wrapErrorHandler( + errorHandler: unknown, + onError: (error: unknown) => void, + thisArg?: unknown, +): (this: unknown, error: unknown) => unknown { + return function (this: unknown, error: unknown): unknown { + onError(error); + // Without a handler, rethrowing lets RxJS report the error as unhandled, as it would without the wrapper. + if (typeof errorHandler !== 'function') { + throw error; + } + return Reflect.apply(errorHandler, thisArg ?? this, [error]); + }; +} diff --git a/packages/nestjs/src/setup.ts b/packages/nestjs/src/setup.ts index 49ade1e03d82..1c7c5cabfce3 100644 --- a/packages/nestjs/src/setup.ts +++ b/packages/nestjs/src/setup.ts @@ -8,9 +8,44 @@ import type { } from '@nestjs/common'; import { Catch, Global, HttpException, Injectable, Logger, Module } from '@nestjs/common'; import { APP_INTERCEPTOR, BaseExceptionFilter } from '@nestjs/core'; -import { captureException, debug, getDefaultIsolationScope, getIsolationScope, isObjectLike } from '@sentry/core'; -import type { Observable } from 'rxjs'; +import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { WEBSOCKET } from '@sentry/conventions/op'; +import { + captureException, + debug, + getDefaultIsolationScope, + getIsolationScope, + isObjectLike, + SPAN_STATUS_ERROR, + startNewTrace, + startSpanManual, + withIsolationScope, +} from '@sentry/core'; +import type { ReflectWithMetadata } from './helpers'; import { isExpectedError, isWsOrRpcException } from './helpers'; +import type { Observable as InstrumentedObservable } from './observable'; +import { instrumentObservable } from './observable'; + +// `@nestjs/websockets`' metadata key for the `@WebSocketGateway()` options. +const GATEWAY_OPTIONS = 'websockets:gateway_options'; + +// TODO: Import these from `@sentry/conventions` once getsentry/sentry-conventions#836 is released. +const WEBSOCKET_EVENT_NAME = 'websocket.event.name'; +const WEBSOCKET_NAMESPACE = 'websocket.namespace'; + +/** + * Socket.IO resolves regex and function namespaces to the concrete child namespace (e.g. `/tenant-42`), + * which would make span names high cardinality. + */ +function hasDynamicNamespace(context: ExecutionContext): boolean { + const R = Reflect as ReflectWithMetadata; + if (typeof R.getMetadata !== 'function') { + return false; + } + const options = R.getMetadata(GATEWAY_OPTIONS, context.getClass()); + const namespace = isObjectLike(options) ? options.namespace : undefined; + return namespace instanceof RegExp || typeof namespace === 'function'; +} // Partial extract of FastifyRequest interface // https://github.com/fastify/fastify/blob/87f9f20687c938828f1138f91682d568d2a31e53/types/request.d.ts#L41 @@ -47,7 +82,71 @@ class SentryTracingInterceptor implements NestInterceptor { /** * Intercepts HTTP requests to set the transaction name for Sentry tracing. */ - public intercept(context: ExecutionContext, next: CallHandler): Observable { + public intercept(context: ExecutionContext, next: CallHandler): ReturnType { + // Nest only applies global interceptors to WebSocket gateways from v12 on. + if (context.getType() === 'ws') { + const wsHost = context.switchToWs(); + const client = wsHost.getClient<{ nsp?: { name?: string } }>(); + const pattern = wsHost.getPattern(); + + if (!pattern) { + return next.handle(); + } + + const namespace = hasDynamicNamespace(context) ? undefined : client?.nsp?.name; + const transactionName = namespace ? `WS ${namespace} ${pattern}` : `WS ${pattern}`; + + return withIsolationScope(isolationScope => { + isolationScope.setTransactionName(transactionName); + + // Messages otherwise share the trace of their long-lived connection, and with Socket.IO's polling + // transport they would become children of the HTTP request that delivered them. + return startNewTrace(() => + startSpanManual( + { + name: transactionName, + attributes: { + [SENTRY_OP]: WEBSOCKET, + [SENTRY_ORIGIN]: 'auto.websocket.nestjs.interceptor', + [WEBSOCKET_EVENT_NAME]: pattern, + [WEBSOCKET_NAMESPACE]: namespace, + }, + }, + span => { + const markSpanAsFailed = (error: unknown): void => { + if (!isExpectedError(error)) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + } + }; + + try { + const observable = next.handle(); + const instrumentedObservable: InstrumentedObservable = observable; + + // Nest runs the handler on subscribe, after `intercept()` has returned. + // eslint-disable-next-line @typescript-eslint/unbound-method + instrumentedObservable.subscribe = new Proxy(instrumentedObservable.subscribe, { + apply: (originalSubscribe, thisArgSubscribe, argsSubscribe) => { + return withIsolationScope(isolationScope, () => + originalSubscribe.apply(thisArgSubscribe, argsSubscribe), + ); + }, + }); + + instrumentObservable(instrumentedObservable, span, markSpanAsFailed); + + return observable; + } catch (error) { + markSpanAsFailed(error); + span.end(); + throw error; + } + }, + ), + ); + }); + } + if (getIsolationScope() === getDefaultIsolationScope()) { debug.warn('Isolation scope is still the default isolation scope, skipping setting transactionName.'); return next.handle(); @@ -206,12 +305,6 @@ class SentryModule { public static forRoot(): DynamicModule { return { module: SentryModule, - providers: [ - { - provide: APP_INTERCEPTOR, - useClass: SentryTracingInterceptor, - }, - ], }; } } diff --git a/packages/nestjs/test/sentry-module.test.ts b/packages/nestjs/test/sentry-module.test.ts new file mode 100644 index 000000000000..31ef302677e2 --- /dev/null +++ b/packages/nestjs/test/sentry-module.test.ts @@ -0,0 +1,17 @@ +import 'reflect-metadata'; +import { APP_INTERCEPTOR } from '@nestjs/core'; +import { describe, expect, it } from 'vitest'; +import { SentryModule } from '../src/setup'; + +describe('SentryModule', () => { + it('registers the tracing interceptor once when imported with forRoot()', () => { + const staticProviders: unknown[] = Reflect.getMetadata('providers', SentryModule) ?? []; + const dynamicProviders: unknown[] = SentryModule.forRoot().providers ?? []; + + const interceptors = [...staticProviders, ...dynamicProviders].filter( + provider => (provider as { provide?: unknown }).provide === APP_INTERCEPTOR, + ); + + expect(interceptors).toHaveLength(1); + }); +}); diff --git a/packages/nestjs/test/sentry-tracing-interceptor.test.ts b/packages/nestjs/test/sentry-tracing-interceptor.test.ts new file mode 100644 index 000000000000..6f1a516e16c8 --- /dev/null +++ b/packages/nestjs/test/sentry-tracing-interceptor.test.ts @@ -0,0 +1,215 @@ +import 'reflect-metadata'; +import type { CallHandler, ExecutionContext } from '@nestjs/common'; +import { getDefaultIsolationScope, getIsolationScope, SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core'; +import type * as SentryCore from '@sentry/core'; +import { config, of, tap, throwError } from 'rxjs'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { SentryModule } from '../src/setup'; + +const mocks = vi.hoisted(() => ({ + isolationScope: { + setTransactionName: vi.fn(), + }, + defaultIsolationScope: {}, + debugWarn: vi.fn(), + inIsolationScope: false, + span: { + setStatus: vi.fn(), + end: vi.fn(), + }, +})); + +vi.mock('@sentry/core', async importOriginal => ({ + ...(await importOriginal()), + getDefaultIsolationScope: vi.fn(() => mocks.defaultIsolationScope), + getIsolationScope: vi.fn(() => mocks.isolationScope), + withIsolationScope: vi.fn((...args: unknown[]) => { + const callback = args[args.length - 1] as (scope: unknown) => unknown; + mocks.inIsolationScope = true; + try { + return callback(mocks.isolationScope); + } finally { + mocks.inIsolationScope = false; + } + }), + startNewTrace: vi.fn((callback: () => unknown) => callback()), + withActiveSpan: vi.fn((_span: unknown, callback: () => unknown) => callback()), + startSpanManual: vi.fn((_options: unknown, callback: (span: unknown) => unknown) => callback(mocks.span)), + debug: { + warn: mocks.debugWarn, + }, + captureException: vi.fn(), +})); + +type Interceptor = { + intercept: (context: ExecutionContext, next: CallHandler) => ReturnType; +}; + +function createInterceptor(): Interceptor { + const [provider] = Reflect.getMetadata('providers', SentryModule) as [{ useClass: new () => Interceptor }]; + + return new provider.useClass(); +} + +function createContext(client: unknown, pattern: unknown, gatewayClass: unknown = class {}): ExecutionContext { + return { + getType: vi.fn().mockReturnValue('ws'), + getClass: vi.fn().mockReturnValue(gatewayClass), + switchToWs: vi.fn().mockReturnValue({ + getClient: vi.fn().mockReturnValue(client), + getPattern: vi.fn().mockReturnValue(pattern), + }), + } as unknown as ExecutionContext; +} + +describe('SentryTracingInterceptor', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(getIsolationScope).mockReturnValue(mocks.isolationScope as never); + vi.mocked(getDefaultIsolationScope).mockReturnValue(mocks.defaultIsolationScope as never); + }); + + it('ends the WebSocket span if the handler throws', () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, 'message'); + const next = { + handle: vi.fn(() => { + throw new Error('handler failed'); + }), + } as unknown as CallHandler; + + expect(() => interceptor.intercept(context, next)).toThrow('handler failed'); + expect(mocks.span.setStatus).toHaveBeenCalledWith({ + code: SPAN_STATUS_ERROR, + message: 'internal_error', + }); + expect(mocks.span.end).toHaveBeenCalled(); + }); + + it('marks the WebSocket span as failed with the positional subscribe error callback', () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, 'message'); + const handlerError = new Error('handler failed'); + const errorHandler = vi.fn(); + const next = { handle: vi.fn(() => throwError(() => handlerError)) } as unknown as CallHandler; + + interceptor.intercept(context, next).subscribe(undefined, errorHandler); + + expect(errorHandler).toHaveBeenCalledWith(handlerError); + expect(mocks.span.setStatus).toHaveBeenCalledWith({ + code: SPAN_STATUS_ERROR, + message: 'internal_error', + }); + expect(mocks.span.end).toHaveBeenCalled(); + }); + + it('marks the WebSocket span as failed for observer objects without an error handler', async () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, 'message'); + const handlerError = new Error('handler failed'); + const errorHandler = vi.fn(); + const next = { handle: vi.fn(() => throwError(() => handlerError)) } as unknown as CallHandler; + + const unhandledError = new Promise(resolve => { + config.onUnhandledError = resolve; + }); + try { + // RxJS's typings reject this call shape, but callers can still pass it at runtime. RxJS ignores the positional + // callback when it gets an observer object. + (interceptor.intercept(context, next) as unknown as { subscribe: (...args: unknown[]) => unknown }).subscribe( + { next: vi.fn() }, + errorHandler, + ); + await expect(unhandledError).resolves.toBe(handlerError); + } finally { + config.onUnhandledError = null; + } + + expect(errorHandler).not.toHaveBeenCalled(); + expect(mocks.span.setStatus).toHaveBeenCalledWith({ + code: SPAN_STATUS_ERROR, + message: 'internal_error', + }); + expect(mocks.span.end).toHaveBeenCalled(); + }); + + it('does not mark the WebSocket span as failed for expected WsExceptions', () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, 'message'); + const wsException = Object.assign(new Error('Unauthorized'), { + getError: () => 'Unauthorized', + initMessage: () => undefined, + }); + const errorHandler = vi.fn(); + const next = { handle: vi.fn(() => throwError(() => wsException)) } as unknown as CallHandler; + + interceptor.intercept(context, next).subscribe({ error: errorHandler }); + + expect(errorHandler).toHaveBeenCalledWith(wsException); + expect(mocks.span.setStatus).not.toHaveBeenCalled(); + expect(mocks.span.end).toHaveBeenCalled(); + }); + + it.each([ + ['a regex', /^\/tenant-\d+$/], + ['a function', (_name: string, _auth: unknown, next: (err: null, ok: boolean) => void) => next(null, true)], + ])('omits the namespace for gateways with %s namespace', (_, namespace) => { + class DynamicGateway {} + Reflect.defineMetadata('websockets:gateway_options', { namespace }, DynamicGateway); + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/tenant-42' } }, 'message', DynamicGateway); + const next = { handle: vi.fn(() => of(undefined)) } as unknown as CallHandler; + + interceptor.intercept(context, next).subscribe(); + + expect(mocks.isolationScope.setTransactionName).toHaveBeenCalledWith('WS message'); + expect(startSpanManual).toHaveBeenCalledWith( + expect.objectContaining({ + attributes: expect.objectContaining({ 'websocket.event.name': 'message', 'websocket.namespace': undefined }), + }), + expect.any(Function), + ); + }); + + it('sets a transaction name without a namespace for other WebSocket adapters', () => { + const interceptor = createInterceptor(); + const context = createContext({}, 'message'); + const next = { handle: vi.fn(() => of(undefined)) } as unknown as CallHandler; + + interceptor.intercept(context, next).subscribe(); + + expect(mocks.isolationScope.setTransactionName).toHaveBeenCalledWith('WS message'); + }); + + it('passes through WebSocket contexts without a pattern', () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, undefined); + const next = { handle: vi.fn(() => of(undefined)) } as unknown as CallHandler; + + interceptor.intercept(context, next).subscribe(); + + expect(mocks.isolationScope.setTransactionName).not.toHaveBeenCalled(); + expect(next.handle).toHaveBeenCalledTimes(1); + }); + + it('names WebSocket transactions when the current isolation scope is the default scope', () => { + const interceptor = createInterceptor(); + const context = createContext({ nsp: { name: '/events' } }, 'message'); + const next = { + handle: vi.fn(() => { + expect(mocks.inIsolationScope).toBe(true); + return of(undefined).pipe( + tap(() => { + expect(mocks.inIsolationScope).toBe(true); + }), + ); + }), + } as unknown as CallHandler; + vi.mocked(getIsolationScope).mockReturnValue(mocks.defaultIsolationScope as never); + + interceptor.intercept(context, next).subscribe(); + + expect(mocks.isolationScope.setTransactionName).toHaveBeenCalledWith('WS /events message'); + expect(next.handle).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/nextjs/src/cloudflare/index.ts b/packages/nextjs/src/cloudflare/index.ts index ae2fa26a4e2b..561bac1d9fd8 100644 --- a/packages/nextjs/src/cloudflare/index.ts +++ b/packages/nextjs/src/cloudflare/index.ts @@ -3,10 +3,10 @@ import type { Context, TextMapGetter } from '@opentelemetry/api'; import { context, propagation, trace } from '@opentelemetry/api'; import type { CloudflareOptions } from '@sentry/cloudflare'; import { withSentry as withSentryCloudflare } from '@sentry/cloudflare'; -import type { Integration } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, + defineIntegration, extractTraceparentData, getRootSpan, GLOBAL_OBJ, @@ -52,7 +52,7 @@ class NextjsCloudflarePropagator extends NextSentryPropagator { } } -const nextjsIntegration = (): Integration => ({ +const nextjsIntegration = defineIntegration(() => ({ name: 'Nextjs', setup: client => { if ((client.getOptions() as CloudflareOptions).enableOpenTelemetrySetup) { @@ -72,7 +72,7 @@ const nextjsIntegration = (): Integration => ({ } }); }, -}); +})); /** * `withSentry` of `@sentry/cloudflare` for the Worker entry of a Next.js app, e.g. `.open-next/worker.js`. It adds the diff --git a/packages/node/src/integrations/http/httpServerIntegration.ts b/packages/node/src/integrations/http/httpServerIntegration.ts index 0000e54bc683..4b5a7ff81e24 100644 --- a/packages/node/src/integrations/http/httpServerIntegration.ts +++ b/packages/node/src/integrations/http/httpServerIntegration.ts @@ -1,7 +1,7 @@ import type { RequestOptions } from 'node:http'; import { context, createContextKey, propagation } from '@opentelemetry/api'; import type { Integration, IntegrationFn } from '@sentry/core'; -import { addNonEnumerableProperty, debug, getClient } from '@sentry/core'; +import { addNonEnumerableProperty, debug, defineIntegration, getClient } from '@sentry/core'; import type { HttpIncomingMessage, HttpServerResponse } from '@sentry/core/server'; import { getHttpServerSubscriptions, @@ -166,7 +166,7 @@ const _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => * * @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry */ -export const httpServerIntegration = _httpServerIntegration as ( +export const httpServerIntegration = defineIntegration(_httpServerIntegration) as ( options?: HttpServerIntegrationOptions, ) => Integration & { name: 'Http.Server'; diff --git a/packages/node/src/integrations/http/httpServerSpansIntegration.ts b/packages/node/src/integrations/http/httpServerSpansIntegration.ts index bf067c50e0da..1b657af7113f 100644 --- a/packages/node/src/integrations/http/httpServerSpansIntegration.ts +++ b/packages/node/src/integrations/http/httpServerSpansIntegration.ts @@ -38,6 +38,7 @@ import { } from '@sentry/core/server'; import { debug, + defineIntegration, safeCallback, getSpanStatusFromHttpCode, httpHeadersToSpanAttributes, @@ -279,7 +280,7 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions * This integration emits spans for incoming requests handled via the node `http` module. * It requires the `httpServerIntegration` to be present. */ -export const httpServerSpansIntegration = _httpServerSpansIntegration as ( +export const httpServerSpansIntegration = defineIntegration(_httpServerSpansIntegration) as ( options?: HttpServerSpansIntegrationOptions, ) => Integration & { name: 'Http.ServerSpans'; diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 5891d0c73710..95275cf3717a 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from 'node:fs'; import { Module } from 'node:module'; -import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; +import { defineIntegration, GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; import { collectInstalledModules } from '@sentry/server-utils'; type ModuleInfo = Record; @@ -50,7 +50,7 @@ const _modulesIntegration = (() => { * Adds the app's packages to the event. Versions injected at build time (e.g. by the Next.js SDK) are used as is. * Otherwise, it uses exact installed versions where they resolve from the entry file, and declared ranges for the rest. */ -export const modulesIntegration = _modulesIntegration; +export const modulesIntegration = defineIntegration(_modulesIntegration); function readFile(path: string): string | undefined { try { diff --git a/packages/nuxt/src/server/sdk.ts b/packages/nuxt/src/server/sdk.ts index 36e0f1179bea..5bc7e354a054 100644 --- a/packages/nuxt/src/server/sdk.ts +++ b/packages/nuxt/src/server/sdk.ts @@ -12,7 +12,7 @@ import { getClient, isClientClosed, } from '@sentry/core'; -import { init as initNode } from '@sentry/node'; +import { init as initNode, nitroIntegration } from '@sentry/node'; import { getNuxtBuildAssetsPath, getNuxtPublicFilePaths } from '../common/buildAssets'; import { DEBUG_BUILD } from '../common/debug-build'; import { @@ -60,9 +60,12 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { // runtime-flags module sets the global flag for the (usual) externalized case. const envFallback = isDevBuild || isNuxtDevRuntime() ? DEV_ENVIRONMENT : DEFAULT_ENVIRONMENT; + const userOptions = _INTERNAL_captureOptionsSetByUser(options); + const sentryOptions = { environment: options.environment ?? process.env.SENTRY_ENVIRONMENT ?? envFallback, - ..._INTERNAL_captureOptionsSetByUser(options), + ...userOptions, + integrations: withNuxtNitroIntegration(userOptions.integrations), ignoreSpans: [ ...(options.ignoreSpans || []), ...getBuildAssetRequestFilters(getNuxtBuildAssetsPath()), @@ -85,6 +88,31 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { return client; } +/** + * Swaps the default Nitro integration for one without middleware spans, storage spans and `Server-Timing` headers. + * The Nuxt SDK already covers these, so with Nitro's tracing channels on, each operation would get two spans. + * + * It wraps `integrations` and not `defaultIntegrations`, because only `initNode` resolves the defaults correctly + * (it also reads `SENTRY_TRACES_SAMPLE_RATE`). + */ +function withNuxtNitroIntegration( + userIntegrations: SentryNuxtServerOptions['integrations'], +): NonNullable { + // Keep the SDK spans, not the channel spans. Nitro v2 has no channels, and h3 does not tell which middleware ran. + const nuxtNitroIntegration = nitroIntegration({ middleware: false, storage: false, serverTiming: false }); + + return defaultIntegrations => { + const integrations = defaultIntegrations.map(integration => + // The spread keeps core's default-instance flag, so a `nitroIntegration` from the user still wins. + integration.name === nuxtNitroIntegration.name ? { ...integration, ...nuxtNitroIntegration } : integration, + ); + + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations ?? [])]; + }; +} + /** * Ignores files from `public/` that the HTTP integration's static asset filter misses, such as `.pdf` and `.txt` files. * Matches exact paths, because a route can share a prefix with a public dir. diff --git a/packages/nuxt/test/server/sdk.test.ts b/packages/nuxt/test/server/sdk.test.ts index 11c660e1dae7..5978d3f63597 100644 --- a/packages/nuxt/test/server/sdk.test.ts +++ b/packages/nuxt/test/server/sdk.test.ts @@ -152,6 +152,75 @@ describe('Nuxt Server SDK', () => { expect(callArgs?.defaultIntegrations).toBe(false); }); + describe('Nitro integration', () => { + it('keeps the integrations of a user `integrations` array', () => { + const checkoutIntegration = { name: 'CheckoutAnalytics' }; + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [checkoutIntegration], + }); + + expect(client?.getIntegrationByName('CheckoutAnalytics')).toBe(checkoutIntegration); + expect(client?.getIntegrationByName('Nitro')).toBeDefined(); + }); + + it('applies a user `integrations` function to the default integrations', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => defaults.filter(integration => integration.name !== 'Console'), + }); + + expect(client?.getIntegrationByName('Console')).toBeUndefined(); + expect(client?.getIntegrationByName('Nitro')).toBeDefined(); + }); + + it('uses a `nitroIntegration` from the user instead of its own', () => { + const userNitroIntegration = SentryNode.nitroIntegration({ serverTiming: false }); + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [userNitroIntegration], + }); + + expect(client?.getIntegrationByName('Nitro')).toBe(userNitroIntegration); + }); + + it('uses a `nitroIntegration` that a user `integrations` function puts before the defaults', () => { + const userNitroIntegration = SentryNode.nitroIntegration({ serverTiming: false }); + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => [userNitroIntegration, ...defaults], + }); + + expect(client?.getIntegrationByName('Nitro')).toBe(userNitroIntegration); + }); + + it('reports the integrations that a user `integrations` function adds and removes', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => [ + ...defaults.filter(integration => integration.name !== 'Console'), + { name: 'CheckoutAnalytics' }, + ], + }); + + expect(client?.getOptions()._metadata?.integrationsSetByUser).toEqual(['CheckoutAnalytics']); + expect(client?.getOptions()._metadata?.removedDefaultIntegrations).toEqual(['Console']); + }); + + it('adds no Nitro integration when the default integrations are off', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + defaultIntegrations: false, + }); + + expect(client).toBeDefined(); + expect(client?.getIntegrationByName('Nitro')).toBeUndefined(); + }); + }); + describe('environment option', () => { const originalEnv = process.env.SENTRY_ENVIRONMENT; diff --git a/packages/nuxt/test/server/tracingChannels.test.ts b/packages/nuxt/test/server/tracingChannels.test.ts new file mode 100644 index 000000000000..f29962fb3105 --- /dev/null +++ b/packages/nuxt/test/server/tracingChannels.test.ts @@ -0,0 +1,136 @@ +/** @vitest-environment node */ +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT, CACHE_REMOVE, HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op'; +import type { Client, StreamedSpanJSON } from '@sentry/core'; +import { createTransport, getCurrentScope, spanToJSON, startNewTrace, startSpan } from '@sentry/core'; +import { defineHandler, H3 } from 'nitro/h3'; +import type { Driver, Storage } from 'unstorage'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { wrapMiddlewareHandlerWithSentry } from '../../src/runtime/hooks/wrapMiddlewareHandler'; +import { createStoragePlugin } from '../../src/runtime/utils/instrumentStorage'; +import { init } from '../../src/server'; + +type TestStorage = Pick; + +/** + * Imports from the `h3` and `unstorage` versions of the installed Nitro v3, which publish the tracing channels. + * The `h3` and `unstorage` dependencies of this package are the Nitro v2 versions. Nothing checks `TModule`. + */ +const nitroRequire = createRequire(createRequire(import.meta.url).resolve('nitro/package.json')); +function importFromNitro(specifier: string): Promise { + return import(pathToFileURL(nitroRequire.resolve(specifier)).href); +} + +interface SpanSummary { + op: unknown; + name: string; + origin: unknown; + parentOp: unknown; +} + +function summarize(span: StreamedSpanJSON, spans: StreamedSpanJSON[]): SpanSummary { + const parent = spans.find(candidate => candidate.span_id === span.parent_span_id); + return { + op: span.attributes[SENTRY_OP], + name: span.name, + origin: span.attributes[SENTRY_ORIGIN], + parentOp: parent?.attributes[SENTRY_OP], + }; +} + +// Like a Nuxt app on Nitro v3 with `tracingChannel: true`. +// The subscribers stay on the process-wide channels, so all tests share one client. +describe('Nuxt server SDK with the Nitro v3 tracing channels on', () => { + let client: Client; + let app: H3; + const endedSpans: StreamedSpanJSON[] = []; + + /** Makes the `http.server` root span, as the HTTP integration of the runtime does in a real server. */ + async function request(path: string): Promise<{ response: Response; spans: SpanSummary[] }> { + const { response, traceId } = await startNewTrace(() => + startSpan({ name: 'GET', op: HTTP_SERVER }, async rootSpan => ({ + response: await app.request(path), + traceId: spanToJSON(rootSpan).trace_id, + })), + ); + + const spans = endedSpans.filter(span => span.trace_id === traceId); + return { response, spans: spans.map(span => summarize(span, spans)) }; + } + + beforeAll(async () => { + const { tracingPlugin } = await importFromNitro<{ tracingPlugin: () => (app: H3) => void }>('h3/tracing'); + const { createStorage } = await importFromNitro<{ createStorage: () => TestStorage }>('unstorage'); + const { default: memoryDriver } = await importFromNitro<{ default: () => Driver }>('unstorage/drivers/memory'); + const { withTracing } = await importFromNitro<{ withTracing: (storage: TestStorage) => TestStorage }>( + 'unstorage/tracing', + ); + + const nuxtClient = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + transport: () => createTransport({ recordDroppedEvent: () => undefined }, () => Promise.resolve({})), + }); + if (!nuxtClient) { + throw new Error('The Nuxt server SDK did not initialize.'); + } + client = nuxtClient; + client.on('spanEnd', span => endedSpans.push(spanToJSON(span))); + + const storage = createStorage(); + storage.mount('sessions', memoryDriver()); + createStoragePlugin(() => storage, ['sessions']); + const tracedStorage = withTracing(storage); + + app = new H3(); + tracingPlugin()(app); + app.use(defineHandler(wrapMiddlewareHandlerWithSentry(() => undefined, 'auth'))); + app.get('/api/sessions/:id', async event => { + const key = `sessions:${event.context.params?.id}`; + await tracedStorage.setItem(key, { user: 'ada' }); + const session = await tracedStorage.getItem(key); + await tracedStorage.removeItem(key); + return { session }; + }); + }); + + afterAll(async () => { + await client.close(); + getCurrentScope().setClient(undefined); + }); + + it('creates one span for a server middleware, from the SDK wrapper', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => span.op === MIDDLEWARE)).toEqual([ + { op: MIDDLEWARE, name: 'auth', origin: 'auto.middleware.nuxt', parentOp: HTTP_SERVER }, + ]); + }); + + it('creates one span for each storage call, from the SDK storage instrumentation', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => String(span.op).startsWith('cache.'))).toEqual([ + { op: CACHE_PUT, name: CACHE_PUT, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + { op: CACHE_GET, name: CACHE_GET, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + { op: CACHE_REMOVE, name: CACHE_REMOVE, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + ]); + }); + + it('keeps the handler span of the h3 channel, which has no SDK source', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => span.op === HANDLER)).toEqual([ + { op: HANDLER, name: 'GET /api/sessions/:id', origin: 'auto.http.nitro.h3', parentOp: HTTP_SERVER }, + ]); + }); + + it('sets no Server-Timing header on the response', async () => { + const { response } = await request('/api/sessions/42?include=profile'); + + expect(response.status).toBe(200); + expect(response.headers.get('Server-Timing')).toBeNull(); + }); +}); diff --git a/packages/react/src/react-router.ts b/packages/react/src/react-router.ts index 8a87e4904f29..a1351454fdf4 100644 --- a/packages/react/src/react-router.ts +++ b/packages/react/src/react-router.ts @@ -3,6 +3,7 @@ import type { Integration } from '@sentry/core'; import { defineIntegration } from '@sentry/core'; import { createRoutesFromChildren, matchRoutes, useLocation, useNavigationType } from 'react-router'; import type { ReactRouterOptions } from './reactrouter-compat-utils'; +import { REACT_ROUTER_LIBRARY_OPTIONS } from './reactrouter-compat-utils'; import { reactRouterBrowserTracingIntegration as reactRouterBrowserTracingIntegrationBase } from './reactrouter.compat'; // The routing wrappers (`wrapReactRouterRouting`, `wrapUseRoutes`, `wrapCreateBrowserRouter`, @@ -50,4 +51,5 @@ function _reactRouterBrowserTracingIntegration( */ export const reactRouterBrowserTracingIntegration: typeof _reactRouterBrowserTracingIntegration = defineIntegration( _reactRouterBrowserTracingIntegration, + { libraryOptions: REACT_ROUTER_LIBRARY_OPTIONS }, ); diff --git a/packages/react/src/reactrouter-compat-utils/index.ts b/packages/react/src/reactrouter-compat-utils/index.ts index 426c6747eff7..4d1e3a627f86 100644 --- a/packages/react/src/reactrouter-compat-utils/index.ts +++ b/packages/react/src/reactrouter-compat-utils/index.ts @@ -12,6 +12,7 @@ export { addResolvedRoutesToParent, processResolvedRoutes, updateNavigationSpan, + REACT_ROUTER_LIBRARY_OPTIONS, } from './instrumentation'; // Utility exports diff --git a/packages/react/src/reactrouter-compat-utils/instrumentation.tsx b/packages/react/src/reactrouter-compat-utils/instrumentation.tsx index f18a90a3fb07..1c9870456254 100644 --- a/packages/react/src/reactrouter-compat-utils/instrumentation.tsx +++ b/packages/react/src/reactrouter-compat-utils/instrumentation.tsx @@ -661,6 +661,17 @@ export function createV6CompatibleWrapCreateMemoryRouter< }; } +/** + * The options that take React Router's hooks and helpers rather than user code. + */ +export const REACT_ROUTER_LIBRARY_OPTIONS = [ + 'useEffect', + 'useLocation', + 'useNavigationType', + 'createRoutesFromChildren', + 'matchRoutes', +] as const; + /** * Creates a browser tracing integration that can be used with all React Router v6 compatible versions. */ diff --git a/packages/react/src/reactrouter.compat.tsx b/packages/react/src/reactrouter.compat.tsx index d7aaca5c76ed..83568f783ac4 100644 --- a/packages/react/src/reactrouter.compat.tsx +++ b/packages/react/src/reactrouter.compat.tsx @@ -8,6 +8,7 @@ import { createV6CompatibleWrapCreateBrowserRouter, createV6CompatibleWrapCreateMemoryRouter, createV6CompatibleWrapUseRoutes, + REACT_ROUTER_LIBRARY_OPTIONS, } from './reactrouter-compat-utils'; import type { CreateRouterFunction, Router, RouterState, UseRoutes } from './types'; @@ -25,6 +26,7 @@ function _reactRouterBrowserTracingIntegration( */ export const reactRouterBrowserTracingIntegration: typeof _reactRouterBrowserTracingIntegration = defineIntegration( _reactRouterBrowserTracingIntegration, + { libraryOptions: REACT_ROUTER_LIBRARY_OPTIONS }, ); /** diff --git a/packages/react/src/reactrouter.tsx b/packages/react/src/reactrouter.tsx index 83a0e5cbb6e1..fb5d97878180 100644 --- a/packages/react/src/reactrouter.tsx +++ b/packages/react/src/reactrouter.tsx @@ -82,6 +82,7 @@ function _reactRouterV4BrowserTracingIntegration( */ export const reactRouterV4BrowserTracingIntegration: typeof _reactRouterV4BrowserTracingIntegration = defineIntegration( _reactRouterV4BrowserTracingIntegration, + { libraryOptions: ['matchPath'] }, ); function _reactRouterV5BrowserTracingIntegration( @@ -119,6 +120,7 @@ function _reactRouterV5BrowserTracingIntegration( */ export const reactRouterV5BrowserTracingIntegration: typeof _reactRouterV5BrowserTracingIntegration = defineIntegration( _reactRouterV5BrowserTracingIntegration, + { libraryOptions: ['matchPath'] }, ); function instrumentReactRouter( diff --git a/packages/react/src/reactrouterv3.ts b/packages/react/src/reactrouterv3.ts index 87dcb323659f..043c80e889a8 100644 --- a/packages/react/src/reactrouterv3.ts +++ b/packages/react/src/reactrouterv3.ts @@ -109,6 +109,7 @@ function _reactRouterV3BrowserTracingIntegration( */ export const reactRouterV3BrowserTracingIntegration: typeof _reactRouterV3BrowserTracingIntegration = defineIntegration( _reactRouterV3BrowserTracingIntegration, + { libraryOptions: ['match'] }, ); /** diff --git a/packages/react/src/reactrouterv6.tsx b/packages/react/src/reactrouterv6.tsx index 14b5e5600a59..c5780734314c 100644 --- a/packages/react/src/reactrouterv6.tsx +++ b/packages/react/src/reactrouterv6.tsx @@ -8,6 +8,7 @@ import { createV6CompatibleWrapCreateBrowserRouter, createV6CompatibleWrapCreateMemoryRouter, createV6CompatibleWrapUseRoutes, + REACT_ROUTER_LIBRARY_OPTIONS, } from './reactrouter-compat-utils'; import type { CreateRouterFunction, Router, RouterState, UseRoutes } from './types'; @@ -25,6 +26,7 @@ function _reactRouterV6BrowserTracingIntegration( */ export const reactRouterV6BrowserTracingIntegration: typeof _reactRouterV6BrowserTracingIntegration = defineIntegration( _reactRouterV6BrowserTracingIntegration, + { libraryOptions: REACT_ROUTER_LIBRARY_OPTIONS }, ); /** diff --git a/packages/react/src/reactrouterv7.tsx b/packages/react/src/reactrouterv7.tsx index 23c0e349b615..5258fb612f2e 100644 --- a/packages/react/src/reactrouterv7.tsx +++ b/packages/react/src/reactrouterv7.tsx @@ -9,6 +9,7 @@ import { createV6CompatibleWrapCreateBrowserRouter, createV6CompatibleWrapCreateMemoryRouter, createV6CompatibleWrapUseRoutes, + REACT_ROUTER_LIBRARY_OPTIONS, } from './reactrouter-compat-utils'; import type { CreateRouterFunction, Router, RouterState, UseRoutes } from './types'; @@ -26,6 +27,7 @@ function _reactRouterV7BrowserTracingIntegration( */ export const reactRouterV7BrowserTracingIntegration: typeof _reactRouterV7BrowserTracingIntegration = defineIntegration( _reactRouterV7BrowserTracingIntegration, + { libraryOptions: REACT_ROUTER_LIBRARY_OPTIONS }, ); /** diff --git a/packages/remix/src/client/browserTracingIntegration.ts b/packages/remix/src/client/browserTracingIntegration.ts index f7b03fd8f91c..1949bfe9a71b 100644 --- a/packages/remix/src/client/browserTracingIntegration.ts +++ b/packages/remix/src/client/browserTracingIntegration.ts @@ -35,5 +35,7 @@ function _browserTracingIntegration(options: RemixBrowserTracingIntegrationOptio * Creates a browser tracing integration for Remix applications. * This integration will create pageload and navigation spans. */ -export const browserTracingIntegration: typeof _browserTracingIntegration = - defineIntegration(_browserTracingIntegration); +export const browserTracingIntegration: typeof _browserTracingIntegration = defineIntegration( + _browserTracingIntegration, + { libraryOptions: ['useEffect', 'useLocation', 'useMatches'] }, +); diff --git a/packages/server-utils/src/ai/vercel-ai/index.ts b/packages/server-utils/src/ai/vercel-ai/index.ts index a0324d52491e..01b6f1e01db7 100644 --- a/packages/server-utils/src/ai/vercel-ai/index.ts +++ b/packages/server-utils/src/ai/vercel-ai/index.ts @@ -92,18 +92,6 @@ export function getProviderMetadataAttributes(providerMetadata: unknown): Record return attributes; } -/** - * Usage attributes derived from `providerMetadata`, which describes only the last step of a call. - * They must not be written onto a span that reports usage aggregated across steps - * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures. - */ -export const LAST_STEP_ONLY_USAGE_KEYS = new Set([ - GEN_AI_USAGE_OUTPUT_TOKENS, - GEN_AI_USAGE_TOTAL_TOKENS, - GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, - GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, -]); - /** * Sets an attribute only if the value is not null or undefined. */ diff --git a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts index cf6edae6a546..40b9bb937850 100644 --- a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts +++ b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts @@ -28,14 +28,14 @@ type GlobalWithTraceChannels = typeof GLOBAL_OBJ & { /** * Captures tracing events emitted by Nitro tracing channels. */ -export function captureTracingEvents(): void { +export function captureTracingEvents(options: { middleware: boolean }): void { // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized. const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels; if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) { return; } - setupH3TracingChannels(); + setupH3TracingChannels(options); setupSrvxTracingChannels(); globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true; } @@ -98,7 +98,7 @@ function getParameterizedRoute(event: NitroH3Event): string | undefined { return routePath; } -function setupH3TracingChannels(): void { +function setupH3TracingChannels(options: { middleware: boolean }): void { // Bail if this is not available if (!diagnosticsChannel.tracingChannel) { return; @@ -107,6 +107,10 @@ function setupH3TracingChannels(): void { bindTracingChannelToSpan( diagnosticsChannel.tracingChannel('h3.request'), data => { + if (data.type === 'middleware' && !options.middleware) { + return undefined; + } + const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK; // The route lives on the request's `http.server` root span, so the route handler only gets a diff --git a/packages/server-utils/src/integrations/nitro/index.ts b/packages/server-utils/src/integrations/nitro/index.ts index 860d0993ef3e..1b9e8085eac4 100644 --- a/packages/server-utils/src/integrations/nitro/index.ts +++ b/packages/server-utils/src/integrations/nitro/index.ts @@ -7,6 +7,13 @@ import { captureServerTimingHeaders } from './setServerTimingHeaders'; const INTEGRATION_NAME = 'Nitro' as const; export interface NitroIntegrationOptions { + /** + * Create `middleware` spans for h3 middleware. + * + * @default true + */ + middleware?: boolean; + /** * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser * SDK can connect a pageload trace to the backend trace. @@ -24,12 +31,12 @@ export interface NitroIntegrationOptions { } const _nitroIntegration = ((options: NitroIntegrationOptions = {}) => { - const { serverTiming = true, storage = true } = options; + const { middleware = true, serverTiming = true, storage = true } = options; return { name: INTEGRATION_NAME, setupOnce() { - captureTracingEvents(); + captureTracingEvents({ middleware }); if (storage) { captureStorageEvents(); diff --git a/packages/server-utils/src/integrations/openai-compatible.ts b/packages/server-utils/src/integrations/openai-compatible.ts index d817702c1292..0b0b8c7aab5b 100644 --- a/packages/server-utils/src/integrations/openai-compatible.ts +++ b/packages/server-utils/src/integrations/openai-compatible.ts @@ -86,6 +86,7 @@ export function createOpenAiCompatibleIntegration { + // oxlint-disable-next-line sdk/require-define-integration -- callers pass the returned function to `defineIntegration` return { name: provider.integrationName, setup(client) { diff --git a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts index fc710a939650..d7741ee3968f 100644 --- a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts +++ b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts @@ -69,7 +69,7 @@ import { getEvaluationOutputMessages, resolveRecordingOption, } from '../../ai/core/utils'; -import { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai'; +import { getProviderMetadataAttributes } from '../../ai/vercel-ai'; import { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants'; import { bindTracingChannelToSpan } from '../../tracing-channel'; import { toExtractAnswers, toExtractFields, toExtractState } from './extract'; @@ -214,30 +214,20 @@ function getActiveSpanConversationId(): string | undefined { } /** - * `providerMetadata` is last-step only; drop derived usage on spans that report an aggregate. - * - * Reasoning goes only when it accompanies a recomputed output (Google), because dropping that - * output leaves the span's own count reasoning-exclusive and the documented subset relationship - * would not hold. A provider that reports reasoning against an already-inclusive output (OpenAI) - * keeps it. + * The `providerMetadata` attributes other than token counts. A partial-cost operation's cost covers + * only its last provider call, so it stays on the `generate_content` spans. */ -function dropLastStepOnlyUsage(providerAttributes: Record, type: ChannelEventType): void { - if (!ROOT_OPERATION_TYPES.has(type)) { - return; - } - const hasRecomputedOutput = GEN_AI_USAGE_OUTPUT_TOKENS in providerAttributes; - for (const key of LAST_STEP_ONLY_USAGE_KEYS) { - // oxlint-disable-next-line typescript/no-dynamic-delete - delete providerAttributes[key]; - } - if (hasRecomputedOutput) { +function getProviderOnlyAttributes(providerMetadata: unknown, type: ChannelEventType): Record { + const attributes = getProviderMetadataAttributes(providerMetadata); + for (const key of Object.values(TOKEN_ATTRIBUTES)) { // oxlint-disable-next-line typescript/no-dynamic-delete - delete providerAttributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]; + delete attributes[key]; } if (PARTIAL_COST_OPERATION_TYPES.has(type)) { // oxlint-disable-next-line typescript/no-dynamic-delete - delete providerAttributes[GEN_AI_COST_TOTAL_TOKENS]; + delete attributes[GEN_AI_COST_TOTAL_TOKENS]; } + return attributes; } /** Record tool name → description from an event's `tools`, so tool spans can backfill the description. */ @@ -471,16 +461,9 @@ export function streamedResultToChannelResult(final: StreamedModelCallResult): R * because the operation's completion promise settles only after every model-call stream has drained. */ function enrichInvokeAgentFromStream(span: Span, final: StreamedModelCallResult, recordOutputs: boolean): void { - const usage = isObjectLike(final.usage) ? final.usage : undefined; - if (usage) { - const input = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens); - const output = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens); - addTokensToSpan(span, GEN_AI_USAGE_INPUT_TOKENS, input); - addTokensToSpan(span, GEN_AI_USAGE_OUTPUT_TOKENS, output); - addTokensToSpan(span, GEN_AI_USAGE_TOTAL_TOKENS, tokenCount(usage.totalTokens) ?? sum(input, output)); - const { cacheRead, cacheWrite } = cacheTokens(usage); - addTokensToSpan(span, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead); - addTokensToSpan(span, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite); + const usage = modelCallUsage(final.usage, final.providerMetadata); + for (const key of TOKEN_KEYS) { + addTokensToSpan(span, TOKEN_ATTRIBUTES[key], usage[key]); } if (recordOutputs) { @@ -789,24 +772,15 @@ export function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void return; } - // `languageModelCall` results report usage as `{ total }` objects; top-level/step results report - // flat numbers. `tokenCount` handles both. v4 names tokens `promptTokens`/`completionTokens` - // (v5+ uses `inputTokens`/`outputTokens`); the fallbacks are `undefined`-inert on v5+. - const usage = isObjectLike(result.usage) ? result.usage : undefined; - if (usage) { - const inputTokens = tokenCount(usage.inputTokens) ?? tokenCount(usage.promptTokens) ?? tokenCount(usage.tokens); - const outputTokens = tokenCount(usage.outputTokens) ?? tokenCount(usage.completionTokens); - const totalTokens = tokenCount(usage.totalTokens) ?? sum(inputTokens, outputTokens); - if (inputTokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, inputTokens); - } - if (outputTokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, outputTokens); - } - if (totalTokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens); + const providerMetadata = result.providerMetadata; + const usage = ROOT_OPERATION_TYPES.has(type) + ? operationUsage(result, providerMetadata) + : modelCallUsage(result.usage, providerMetadata); + for (const key of TOKEN_KEYS) { + const value = usage[key]; + if (value !== undefined) { + span.setAttribute(TOKEN_ATTRIBUTES[key], value); } - setCacheTokens(span, usage); } // Match the OTel integration: finish reasons live on the model-call (`generate_content`) span, not @@ -826,13 +800,7 @@ export function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel); } - // Provider-specific cache/reasoning/prediction token breakdowns. The channel exposes `providerMetadata` - // as an object (the OTel path parses it from a string); both share `getProviderMetadataAttributes` so - // the emitted shape is identical. - const providerMetadata = (result as { providerMetadata?: unknown }).providerMetadata; - const providerAttributes = getProviderMetadataAttributes(providerMetadata); - dropLastStepOnlyUsage(providerAttributes, type); - span.setAttributes(providerAttributes); + span.setAttributes(getProviderOnlyAttributes(providerMetadata, type)); if (recordOutputs) { const outputMessages = getOutputMessages(type, result, finishReason, data.event); @@ -914,19 +882,86 @@ function tokenCount(value: unknown): number | undefined { } /** - * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`, - * v7 `inputTokens.{cacheRead,cacheWrite}`. + * Reasoning from the SDK's usage: v6+ for every provider, v5 only for OpenAI, whose output includes it. + * Other v5 providers don't say whether their output does, and Google's comes from `providerMetadata`. + */ +function reasoningTokens(usage: Record, providerMetadata: unknown): number | undefined { + const outputTokens = isObjectLike(usage.outputTokens) ? usage.outputTokens : undefined; + const outputTokenDetails = isObjectLike(usage.outputTokenDetails) ? usage.outputTokenDetails : undefined; + const reasoning = asNumber(outputTokens?.reasoning) ?? asNumber(outputTokenDetails?.reasoningTokens); + if (reasoning !== undefined) { + return reasoning; + } + const metadata = isObjectLike(providerMetadata) ? providerMetadata : undefined; + return metadata?.openai || metadata?.azure ? asNumber(usage.reasoningTokens) : undefined; +} + +interface TokenUsage { + input?: number; + output?: number; + total?: number; + cacheRead?: number; + cacheWrite?: number; + reasoning?: number; +} + +const TOKEN_ATTRIBUTES: Record = { + input: GEN_AI_USAGE_INPUT_TOKENS, + output: GEN_AI_USAGE_OUTPUT_TOKENS, + total: GEN_AI_USAGE_TOTAL_TOKENS, + cacheRead: GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, + cacheWrite: GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, + reasoning: GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, +}; + +const TOKEN_KEYS = Object.keys(TOKEN_ATTRIBUTES) as Array; + +/** + * One model call's final token counts: its usage (flat or `{ total }`, v4 `promptTokens`/`completionTokens`) + * corrected by its own `providerMetadata`. */ -function setCacheTokens(span: Span, usage: Record): void { - const { cacheRead, cacheWrite } = cacheTokens(usage); - if (cacheRead !== undefined) { - span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheRead); +function modelCallUsage(usage: unknown, providerMetadata: unknown): TokenUsage { + const derived = getProviderMetadataAttributes(providerMetadata); + const counts = isObjectLike(usage) ? usage : {}; + const input = tokenCount(counts.inputTokens) ?? tokenCount(counts.promptTokens) ?? tokenCount(counts.tokens); + const output = + asNumber(derived[GEN_AI_USAGE_OUTPUT_TOKENS]) ?? + tokenCount(counts.outputTokens) ?? + tokenCount(counts.completionTokens); + const { cacheRead, cacheWrite } = cacheTokens(counts); + return { + input, + output, + total: asNumber(derived[GEN_AI_USAGE_TOTAL_TOKENS]) ?? tokenCount(counts.totalTokens) ?? sum(input, output), + cacheRead: asNumber(derived[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]) ?? cacheRead, + cacheWrite: asNumber(derived[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]) ?? cacheWrite, + reasoning: reasoningTokens(counts, providerMetadata) ?? asNumber(derived[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]), + }; +} + +/** + * An operation's token counts, summed over its steps, which can use different providers. Every text + * operation from v4 on has `steps`; the others are a single model call. + */ +function operationUsage(result: Record, providerMetadata: unknown): TokenUsage { + const steps = Array.isArray(result.steps) ? result.steps.filter(isObjectLike) : []; + if (!steps.length) { + return modelCallUsage(result.usage, providerMetadata); } - if (cacheWrite !== undefined) { - span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWrite); + const total: TokenUsage = {}; + for (const step of steps) { + const stepUsage = modelCallUsage(step.usage, step.providerMetadata); + for (const key of TOKEN_KEYS) { + total[key] = sum(total[key], stepUsage[key]); + } } + return total; } +/** + * Cache token counts as the AI SDK normalizes them: v5 `cachedInputTokens`, v6 `inputTokenDetails`, + * v7 `inputTokens.{cacheRead,cacheWrite}`. + */ function cacheTokens(usage: Record): { cacheRead?: number; cacheWrite?: number } { const inputTokens = isObjectLike(usage.inputTokens) ? usage.inputTokens : undefined; const inputTokenDetails = isObjectLike(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined; diff --git a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts index 260ca9ffd3e8..3a034fdfa324 100644 --- a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts +++ b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.ts @@ -323,7 +323,7 @@ function bindOperation( }, // `streamText`/`streamObject` return synchronously, so their operation span would otherwise end // before the stream drains — losing the aggregate usage/output. Defer the end and await the result's - // completion promises (`totalUsage`/`text`/…, which resolve on drain), mirroring how v7's channel + // completion promises (`steps`/`text`/…, which resolve on drain), mirroring how v7's channel // defers the operation span on the SDK's total-usage promise. deferSpanEnd: ({ span, data, end }) => deferStreamTextOperationEnd(span, data, end), }, @@ -359,37 +359,35 @@ function deferStreamTextOperationEnd( const streamResult = data.result; void (async () => { try { - const [usage, text, objectOutcome, toolCalls, finishReason, response] = await Promise.all([ - streamResult.totalUsage ?? streamResult.usage, - streamResult.text, - // Settle `object` into an outcome so a validation failure can't short-circuit the usage read. - type === 'streamObject' - ? Promise.resolve(streamResult.object).then( - value => ({ value }), - (error: unknown) => ({ value: undefined, error }), - ) - : { value: undefined }, - streamResult.toolCalls, - streamResult.finishReason, - streamResult.response, - ]); + const [usage, text, objectOutcome, toolCalls, finishReason, response, steps, providerMetadata] = + await Promise.all([ + streamResult.usage, + streamResult.text, + // Settle `object` into an outcome so a validation failure can't short-circuit the usage read. + type === 'streamObject' + ? Promise.resolve(streamResult.object).then( + value => ({ value }), + (error: unknown) => ({ value: undefined, error }), + ) + : { value: undefined }, + streamResult.toolCalls, + streamResult.finishReason, + streamResult.response, + streamResult.steps, + streamResult.providerMetadata, + ]); + const result = { usage, toolCalls, finishReason, response, steps, providerMetadata }; if ('error' in objectOutcome) { // The model call itself succeeded, so keep its usage on the span; `beforeSpanEnd` skips // enrichment once `end(error)` marks the payload as errored. - message.result = { usage, toolCalls, finishReason, response }; + message.result = result; enrichSpanOnEnd(span, message); end(objectOutcome.error); return; } const object = objectOutcome.value; // Feed the resolved values back through the shared enrichment: `beforeSpanEnd` reads `data.result`. - data.result = { - usage, - text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object), - toolCalls, - finishReason, - response, - }; + data.result = { ...result, text: text ?? (isObjectLike(object) ? JSON.stringify(object) : object) }; end(); } catch (error) { end(error); @@ -399,9 +397,12 @@ function deferStreamTextOperationEnd( return true; } -/** A streamed result exposes its aggregates as promises (`totalUsage`/`usage`); a settled result does not. */ +/** + * A streamed result exposes its aggregates as promises; a settled result does not. Reading `totalUsage` + * would create a promise that rejects unobserved when the stream aborts. + */ function isStreamingResult(result: unknown): result is Record | undefined> { - return isObjectLike(result) && (isThenable(result.totalUsage) || isThenable(result.usage)); + return isObjectLike(result) && (isThenable(result.steps) || isThenable(result.usage)); } function isThenable(value: unknown): boolean { diff --git a/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts b/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts new file mode 100644 index 000000000000..56bd3d3e16ce --- /dev/null +++ b/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts @@ -0,0 +1,80 @@ +import { tracingChannel } from 'node:diagnostics_channel'; +import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { HANDLER, HTTP_SERVER } from '@sentry/conventions/op'; +import type { StreamedSpanJSON } from '@sentry/core'; +import { + createTransport, + getActiveSpan, + getCurrentScope, + initAndBind, + resolvedSyncPromise, + setAsyncContextStrategy, + spanToJSON, + startSpan, +} from '@sentry/core'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { setAsyncLocalStorageAsyncContextStrategy } from '../../../src/async-context'; +import { captureTracingEvents } from '../../../src/integrations/nitro/captureTracingEvents'; +import type { H3TracingRequestEvent } from '../../../src/integrations/nitro/nitroTypes'; +import { TestClient } from '../../mocks/client'; + +const h3RequestChannel = tracingChannel('h3.request'); + +function createH3Event(): H3TracingRequestEvent['event'] { + return { + url: new URL('https://shop.example.com/api/users/42?include=profile'), + req: { method: 'GET' }, + context: { matchedRoute: { route: '/api/users/:id' }, params: { id: '42' } }, + }; +} + +/** Publishes an `h3.request` event like h3's `tracingPlugin`, and returns the span that is active inside it. */ +function traceH3Request(type: H3TracingRequestEvent['type']): Promise { + return startSpan({ name: 'GET /api/users/42', op: HTTP_SERVER }, () => + h3RequestChannel.tracePromise( + async () => { + const activeSpan = getActiveSpan(); + return activeSpan && spanToJSON(activeSpan); + }, + { type, event: createH3Event() }, + ), + ); +} + +// The subscribers stay on the process-wide channel, so a file can set them up only once. +// That is why `middleware: true` has no test here. +describe('captureTracingEvents with `middleware: false`', () => { + beforeAll(() => { + setAsyncLocalStorageAsyncContextStrategy(); + initAndBind(TestClient, { + dsn: 'https://username@domain/123', + integrations: [], + sendClientReports: false, + stackParser: () => [], + tracesSampleRate: 1, + transport: () => createTransport({ recordDroppedEvent: () => undefined }, () => resolvedSyncPromise({})), + }); + + captureTracingEvents({ middleware: false }); + }); + + afterAll(() => { + getCurrentScope().setClient(undefined); + setAsyncContextStrategy(undefined); + }); + + it('starts no span for an h3 middleware', async () => { + const activeSpan = await traceH3Request('middleware'); + + expect(activeSpan?.name).toBe('GET /api/users/42'); + expect(activeSpan?.attributes[SENTRY_OP]).toBe(HTTP_SERVER); + }); + + it('still starts a handler span for an h3 route', async () => { + const activeSpan = await traceH3Request('route'); + + expect(activeSpan?.name).toBe('GET /api/users/:id'); + expect(activeSpan?.attributes[SENTRY_OP]).toBe(HANDLER); + expect(activeSpan?.attributes[SENTRY_ORIGIN]).toBe('auto.http.nitro.h3'); + }); +}); diff --git a/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts b/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts index 5888f97d8fcb..9cfd41fa812b 100644 --- a/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts +++ b/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts @@ -17,6 +17,16 @@ describe('nitroIntegration', () => { nitroIntegration().setupOnce!(); expect(captureTracingEvents).toHaveBeenCalledTimes(1); + expect(captureTracingEvents).toHaveBeenCalledWith({ middleware: true }); + expect(captureStorageEvents).toHaveBeenCalledTimes(1); + expect(captureServerTimingHeaders).toHaveBeenCalledTimes(1); + }); + + it('turns off h3 middleware spans when `middleware` is disabled', () => { + nitroIntegration({ middleware: false }).setupOnce!(); + + expect(captureTracingEvents).toHaveBeenCalledTimes(1); + expect(captureTracingEvents).toHaveBeenCalledWith({ middleware: false }); expect(captureStorageEvents).toHaveBeenCalledTimes(1); expect(captureServerTimingHeaders).toHaveBeenCalledTimes(1); }); diff --git a/packages/server-utils/test/integrations/vercel-ai/cache-tokens.test.ts b/packages/server-utils/test/integrations/vercel-ai/cache-tokens.test.ts index 30cf07a6cffa..f7dda8240c92 100644 --- a/packages/server-utils/test/integrations/vercel-ai/cache-tokens.test.ts +++ b/packages/server-utils/test/integrations/vercel-ai/cache-tokens.test.ts @@ -152,18 +152,38 @@ describe('Vercel AI SDK cache tokens', () => { expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(21); }); - it('keeps the aggregated SDK counts on a root operation over last-step providerMetadata', () => { + it('sums the counts of every step on a root operation over its last-step providerMetadata', () => { const data = runSpan('generateText', { - usage: { + usage: { inputTokens: 4500, inputTokenDetails: { cacheReadTokens: 3000, cacheWriteTokens: 0 }, outputTokens: 20 }, + totalUsage: { inputTokens: 9500, inputTokenDetails: { cacheReadTokens: 8000, cacheWriteTokens: 500 }, outputTokens: 40, }, + steps: [ + { + usage: { + inputTokens: 5000, + inputTokenDetails: { cacheReadTokens: 5000, cacheWriteTokens: 500 }, + outputTokens: 20, + }, + providerMetadata: { anthropic: { cacheReadInputTokens: 5000, cacheCreationInputTokens: 500 } }, + }, + { + usage: { + inputTokens: 4500, + inputTokenDetails: { cacheReadTokens: 3000, cacheWriteTokens: 0 }, + outputTokens: 20, + }, + providerMetadata: { anthropic: { cacheReadInputTokens: 3000, cacheCreationInputTokens: 0 } }, + }, + ], providerMetadata: { anthropic: { cacheReadInputTokens: 3000, cacheCreationInputTokens: 0 }, }, }); + expect(data[GEN_AI_USAGE_INPUT_TOKENS]).toBe(9500); expect(data[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]).toBe(8000); expect(data[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]).toBe(500); }); diff --git a/packages/server-utils/test/integrations/vercel-ai/gemini-reasoning-tokens.test.ts b/packages/server-utils/test/integrations/vercel-ai/gemini-reasoning-tokens.test.ts index 5869ba590603..1795c9de6c67 100644 --- a/packages/server-utils/test/integrations/vercel-ai/gemini-reasoning-tokens.test.ts +++ b/packages/server-utils/test/integrations/vercel-ai/gemini-reasoning-tokens.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { + GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, @@ -102,29 +103,145 @@ describe('Vercel AI Gemini reasoning tokens', () => { expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBeUndefined(); }); - // A top-level operation's span reports usage summed across every step, while `providerMetadata` - // describes the last step alone. Reasoning is gated with output and total: it is a subset of an - // output this span never recomputes, and nothing sums it across steps. - it('does not write last-step usage onto an invoke_agent span', () => { - const data = runSpan('generateText', { - usage: { inputTokens: 900, outputTokens: 350, totalTokens: 1250 }, - providerMetadata: REASONING_METADATA, + it('reads v7 model-call reasoning for any provider', () => { + const data = runSpan('languageModelCall', { + usage: { inputTokens: { total: 14 }, outputTokens: { total: 90, text: 30, reasoning: 60 } }, + providerMetadata: { xai: {} }, + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(90); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(60); + }); + + // `@ai-sdk/openai` 2.x reports reasoning only in the usage, not in `providerMetadata`. + it('reads v5 OpenAI model-call reasoning from the usage', () => { + const data = runSpan('languageModelCall', { + usage: { inputTokens: 14, outputTokens: 350, reasoningTokens: 200, totalTokens: 364 }, + providerMetadata: { openai: {} }, }); expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(350); - expect(data[GEN_AI_USAGE_TOTAL_TOKENS]).toBe(1250); - expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBeUndefined(); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(200); }); - // OpenAI reports reasoning against an `outputTokens` that already includes it, so there is no - // recomputed output to suppress and the subset relationship still holds on the aggregate span. - it('keeps OpenAI reasoning tokens on an invoke_agent span', () => { - const data = runSpan('generateText', { - usage: { inputTokens: 900, outputTokens: 350, totalTokens: 1250 }, - providerMetadata: { openai: { reasoningTokens: 120 } }, + it('ignores v5 reasoning from a provider whose output it may not be part of', () => { + const data = runSpan('languageModelCall', { + usage: { inputTokens: 14, outputTokens: 350, reasoningTokens: 200, totalTokens: 564 }, + providerMetadata: { xai: {} }, }); expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(350); - expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(120); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBeUndefined(); + }); + + it('records zero reasoning', () => { + const data = runSpan('languageModelCall', { + usage: { inputTokens: { total: 14 }, outputTokens: { total: 12, text: 12, reasoning: 0 } }, + }); + + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(0); + }); + + describe('invoke_agent spans', () => { + function googleStep(candidates: number, thoughts: number, usage: Record) { + return { + usage, + providerMetadata: { + google: { + usageMetadata: { + promptTokenCount: 10, + candidatesTokenCount: candidates, + thoughtsTokenCount: thoughts, + totalTokenCount: 10 + candidates + thoughts, + }, + }, + }, + }; + } + + // `providerMetadata` describes the last step alone, so each step is read on its own. + it('sums each step rather than reading the last step (v6+)', () => { + const steps = [ + googleStep(20, 80, { outputTokens: 100, outputTokenDetails: { reasoningTokens: 80 } }), + googleStep(20, 100, { outputTokens: 120, outputTokenDetails: { reasoningTokens: 100 } }), + ]; + const data = runSpan('generateText', { + usage: steps[1]!.usage, + totalUsage: { inputTokens: 20, outputTokens: 220, totalTokens: 240 }, + providerMetadata: steps[1]!.providerMetadata, + steps, + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(220); + expect(data[GEN_AI_USAGE_TOTAL_TOKENS]).toBe(240); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(180); + }); + + // `@ai-sdk/google` 2.x reports candidate-only `outputTokens` next to a separate `reasoningTokens`. + it('adds reasoning into the output of v5 Google steps', () => { + const steps = [ + googleStep(20, 80, { outputTokens: 20, reasoningTokens: 80 }), + googleStep(20, 100, { outputTokens: 20, reasoningTokens: 100 }), + ]; + const data = runSpan('generateText', { + totalUsage: { inputTokens: 20, outputTokens: 40, reasoningTokens: 180, totalTokens: 240 }, + providerMetadata: steps[1]!.providerMetadata, + steps, + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(220); + expect(data[GEN_AI_USAGE_TOTAL_TOKENS]).toBe(240); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(180); + }); + + // The v2 adapter's `outputTokens.total` is candidate-only, and the SDK totals it into `totalUsage`. + it('keeps total equal to input plus output over Google v2-adapter steps', () => { + const steps = [ + googleStep(20, 80, { inputTokens: { total: 10 }, outputTokens: { total: 20, reasoning: 80 } }), + googleStep(20, 100, { inputTokens: { total: 10 }, outputTokens: { total: 20, reasoning: 100 } }), + ]; + const data = runSpan('generateText', { + usage: steps[1]!.usage, + totalUsage: { inputTokens: 20, outputTokens: 40, totalTokens: 60 }, + providerMetadata: steps[1]!.providerMetadata, + steps, + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(220); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(180); + expect(data[GEN_AI_USAGE_TOTAL_TOKENS]).toBe( + (data[GEN_AI_USAGE_INPUT_TOKENS] as number) + (data[GEN_AI_USAGE_OUTPUT_TOKENS] as number), + ); + }); + + it('reads each step by its own provider', () => { + const openaiStep = { + usage: { outputTokens: 50, reasoningTokens: 30 }, + providerMetadata: { openai: {} }, + }; + const data = runSpan('generateText', { + totalUsage: { inputTokens: 20, outputTokens: 70, reasoningTokens: 110 }, + providerMetadata: openaiStep.providerMetadata, + steps: [googleStep(20, 80, { outputTokens: 20, reasoningTokens: 80 }), openaiStep], + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(150); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(110); + }); + + // v4 reports no reasoning in the usage, only in each step's `providerMetadata`. + it('sums v4 OpenAI reasoning from each step', () => { + const data = runSpan('generateText', { + usage: { promptTokens: 20, completionTokens: 300, totalTokens: 320 }, + providerMetadata: { openai: { reasoningTokens: 40 } }, + steps: [ + { usage: { promptTokens: 10, completionTokens: 200 }, providerMetadata: { openai: { reasoningTokens: 60 } } }, + { usage: { promptTokens: 10, completionTokens: 100 }, providerMetadata: { openai: { reasoningTokens: 40 } } }, + ], + }); + + expect(data[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(300); + expect(data[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]).toBe(100); + }); }); }); diff --git a/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts b/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts index 78081dfaacb4..1767fb315da8 100644 --- a/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts +++ b/packages/sveltekit/src/server-common/integrations/svelteKitSpans.ts @@ -1,5 +1,5 @@ -import type { Integration, SpanJSON, SpanOrigin, StreamedSpanJSON } from '@sentry/core'; -import { safeSetSpanJSONAttributes } from '@sentry/core'; +import type { SpanJSON, SpanOrigin, StreamedSpanJSON } from '@sentry/core'; +import { defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core'; import { SENTRY_DESCRIPTION, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { FUNCTION } from '@sentry/conventions/op'; @@ -8,7 +8,7 @@ import { FUNCTION } from '@sentry/conventions/op'; * (via Kit's tracing feature since 2.31.0) get the correct Sentry attributes * and data. */ -export function svelteKitSpansIntegration(): Integration { +export const svelteKitSpansIntegration = defineIntegration(() => { return { name: 'SvelteKitSpansEnhancement' as const, // Using preprocessEvent to ensure the processing happens before user-configured @@ -26,7 +26,7 @@ export function svelteKitSpansIntegration(): Integration { _enhanceKitSpanStreamed(span); }, }; -} +}); /** * Adds sentry-specific attributes and data to a span emitted by SvelteKit's native tracing (since 2.31.0) diff --git a/packages/tanstackstart-react/src/server/index.ts b/packages/tanstackstart-react/src/server/index.ts index ba40c0b8223d..66deef3616af 100644 --- a/packages/tanstackstart-react/src/server/index.ts +++ b/packages/tanstackstart-react/src/server/index.ts @@ -2,6 +2,7 @@ // can be removed once following issue is fixed: https://github.com/import-js/eslint-plugin-import/issues/703 /* eslint-disable import/export */ import type { Integration } from '@sentry/core'; +import { defineIntegration } from '@sentry/core'; export * from '@sentry/node'; @@ -17,12 +18,19 @@ export { createSentryTunnelRoute, registerSentryServerTunnelRoute, setTunnelRout * A no-op stub of the replay integration for the server. Router setup code is shared between client and server, * so this stub is needed to prevent build errors during SSR bundling. */ -export function replayIntegration(_options?: Record): Integration { +export const replayIntegration = defineIntegration((_options?: Record) => { return { name: 'Replay', setup() {}, }; -} +}); + +const _browserTracingIntegration = defineIntegration((_options?: Record) => { + return { + name: 'BrowserTracing', + setup() {}, + }; +}); /** * A no-op stub of the browser tracing integration for the server. Router setup code is shared between client and server, @@ -30,12 +38,9 @@ export function replayIntegration(_options?: Record): Integrati */ export function tanstackRouterBrowserTracingIntegration( _router: unknown, - _options?: Record, + options?: Record, ): Integration { - return { - name: 'BrowserTracing', - setup() {}, - }; + return _browserTracingIntegration(options); } /** diff --git a/packages/tanstackstart-react/src/server/wrapFetchWithSentry.ts b/packages/tanstackstart-react/src/server/wrapFetchWithSentry.ts index 9691f030c835..9a4bb26894bc 100644 --- a/packages/tanstackstart-react/src/server/wrapFetchWithSentry.ts +++ b/packages/tanstackstart-react/src/server/wrapFetchWithSentry.ts @@ -1,10 +1,12 @@ -import { getTraceMetaTags } from '@sentry/core'; +import { getClient, getTraceMetaTags, SDK_VERSION } from '@sentry/core'; import { flushIfServerless } from '@sentry/core/server'; import { captureException } from '@sentry/node'; import { updateSpanWithRouteParametrization } from './routeParametrization'; declare const __SENTRY_ROUTE_PATTERNS__: string[] | undefined; +const SDK_NAME = 'sentry.javascript.tanstackstart-react'; + export type ServerEntry = { // `opts` is forwarded verbatim to the wrapped handler, so this must accept whatever shape // the real framework entry uses (e.g. TanStack's `RequestOptions`). Under @@ -136,6 +138,13 @@ export function wrapFetchWithSentry(serverEntry: ServerEntry): ServerEntry { serverEntry.fetch = new Proxy(serverEntry.fetch, { async apply(target, thisArg, args) { try { + // With `sentryCloudflareVitePlugin()` of `@sentry/cloudflare/vite`, `@sentry/cloudflare` inits the client. + const sdk = getClient()?.getOptions()._metadata?.sdk; + if (sdk && sdk.name !== SDK_NAME) { + sdk.name = SDK_NAME; + sdk.packages = [{ name: 'npm:@sentry/tanstackstart-react', version: SDK_VERSION }, ...(sdk.packages || [])]; + } + const request: Request = args[0]; const url = new URL(request.url); const method = request.method || 'GET'; diff --git a/packages/tanstackstart-react/test/server/wrapFetchWithSentry.test.ts b/packages/tanstackstart-react/test/server/wrapFetchWithSentry.test.ts index 20983ba61f92..b5c9557f018d 100644 --- a/packages/tanstackstart-react/test/server/wrapFetchWithSentry.test.ts +++ b/packages/tanstackstart-react/test/server/wrapFetchWithSentry.test.ts @@ -1,3 +1,5 @@ +import type { Client } from '@sentry/core'; +import { getCurrentScope, SDK_VERSION } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; const flushIfServerlessSpy = vi.fn().mockResolvedValue(undefined); @@ -40,6 +42,29 @@ const { wrapFetchWithSentry } = await import('../../src/server/wrapFetchWithSent describe('wrapFetchWithSentry', () => { afterEach(() => { vi.clearAllMocks(); + getCurrentScope().setClient(undefined); + }); + + it('sets the TanStack Start SDK name on a client that another SDK inited', async () => { + const sdk = { + name: 'sentry.javascript.cloudflare', + packages: [{ name: 'npm:@sentry/cloudflare', version: SDK_VERSION }], + version: SDK_VERSION, + }; + getCurrentScope().setClient({ getOptions: () => ({ _metadata: { sdk } }) } as unknown as Client); + const serverEntry = wrapFetchWithSentry({ fetch: () => new Response('ok') }); + + await serverEntry.fetch(new Request('http://localhost:3000/page')); + await serverEntry.fetch(new Request('http://localhost:3000/_serverFn/abc123')); + + expect(sdk).toEqual({ + name: 'sentry.javascript.tanstackstart-react', + packages: [ + { name: 'npm:@sentry/tanstackstart-react', version: SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SDK_VERSION }, + ], + version: SDK_VERSION, + }); }); it('calls flushIfServerless after a regular request', async () => {