From de98a89e26f8a5b4a3e2716c0e3508d41d3f1e2b Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Tue, 10 Nov 2026 15:51:07 +0100 Subject: [PATCH 001/136] fix(ci): prune unused rimraf lockfile entries (#26247) **Why:** Removing rimraf in #26219 left two unused lockfile entries that pnpm prunes during installation, causing develop's lockfile stability check to fail. Commit the generated cleanup to restore CI. Co-authored-by: OpenAI Codex --- pnpm-lock.yaml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 96660d04a6d1..cf8b8ac67374 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16612,11 +16612,6 @@ packages: deprecated: Rimraf versions prior to v4 are no longer supported hasBin: true - rimraf@6.1.3: - resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==} - engines: {node: 20 || >=22} - hasBin: true - rolldown@1.2.16: resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -37827,11 +37822,6 @@ snapshots: dependencies: glob: 7.2.3 - rimraf@6.1.3: - dependencies: - glob: 13.0.6 - package-json-from-dist: 1.0.1 - rolldown@1.2.16: dependencies: '@oxc-project/types': 0.156.0 From 2c2688ce1dc2eeb366e940b32ad89d13b736057b Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Tue, 10 Nov 2026 15:54:36 +0100 Subject: [PATCH 002/136] fix(core): Forward client IP headers from the tunnel so Sentry SaaS records the visitor IP (#26177) Fixes #26154 Server tunnels sent the visitor IP to Sentry only as `X-Sentry-Forwarded-For`. Sentry SaaS replaces that header with the connecting IP, so events sent through a tunnel stored the server's IP. The tunnel now also passes through the incoming `CF-Connecting-IP`, `X-Vercel-Forwarded-For` and `X-Forwarded-For` headers, which SaaS keeps and prefers over it. A rewrite proxy sends the same headers. `X-Sentry-Forwarded-For` stays for self-hosted Relay. Tested against sentry.io (de region) with a Next.js handler mode app. Before the fix, a request behind Cloudflare and one with only `X-Forwarded-For` both stored the server IP. After the fix, both store the client IP. Behind a proxy that appends to `X-Forwarded-For`, a client can pick the first entry and so its stored IP. A rewrite proxy behaves the same, and events can already set `user.ip_address`. Not tested on Cloudflare Workers or Vercel Edge, which may change these headers on outgoing requests. Co-authored-by: Claude Opus 5.5 --- packages/core/src/utils/tunnelForward.ts | 15 ++++++++----- packages/core/test/lib/utils/tunnel.test.ts | 25 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/core/src/utils/tunnelForward.ts b/packages/core/src/utils/tunnelForward.ts index 9e3298d7e9f9..bb5ca0102c72 100644 --- a/packages/core/src/utils/tunnelForward.ts +++ b/packages/core/src/utils/tunnelForward.ts @@ -388,6 +388,12 @@ const FORWARDED_CLIENT_HEADERS = [ 'referer', ]; +/** + * Sentry SaaS replaces `X-Sentry-Forwarded-For` with the connecting IP, which is the tunnel server, but keeps these + * and prefers them. Passing them through keeps the client IP, as a rewrite proxy does. + */ +const FORWARDED_CLIENT_IP_HEADERS = ['cf-connecting-ip', 'x-vercel-forwarded-for', 'x-forwarded-for']; + /** * Reads the body up to the envelope header line. Returns the line and every byte read, or `undefined`. */ @@ -451,16 +457,13 @@ function forwardHeaders(request: Request): Record { // No `Content-Length`: some runtimes reject it on a streamed body (Next.js edge in dev). const headers: Record = { 'Content-Type': 'application/x-sentry-envelope' }; - // Relay would otherwise attribute the server's IP. Same precedence Relay uses. - const clientIp = - request.headers.get('cf-connecting-ip') || - request.headers.get('x-vercel-forwarded-for') || - request.headers.get('x-forwarded-for'); + // For self-hosted Relay, which honors this header. Same precedence Relay uses. + const clientIp = FORWARDED_CLIENT_IP_HEADERS.map(name => request.headers.get(name)).find(Boolean); if (clientIp) { headers['X-Sentry-Forwarded-For'] = clientIp; } - for (const name of FORWARDED_CLIENT_HEADERS) { + for (const name of [...FORWARDED_CLIENT_IP_HEADERS, ...FORWARDED_CLIENT_HEADERS]) { const value = request.headers.get(name); if (value) { headers[name] = value; diff --git a/packages/core/test/lib/utils/tunnel.test.ts b/packages/core/test/lib/utils/tunnel.test.ts index 887abaf56718..5ccef88e765a 100644 --- a/packages/core/test/lib/utils/tunnel.test.ts +++ b/packages/core/test/lib/utils/tunnel.test.ts @@ -399,6 +399,31 @@ describe('handleTunnelRequest', () => { ); }); + it('passes the client IP headers through unchanged, since Sentry SaaS replaces X-Sentry-Forwarded-For', async () => { + fetchMock.mockResolvedValueOnce(new Response('ok')); + const clientIpHeaders = { + 'cf-connecting-ip': '1.1.1.1', + 'x-vercel-forwarded-for': '3.3.3.3', + 'x-forwarded-for': '2.2.2.2, 10.0.0.1', + }; + + await handleTunnelRequest( + new Request('http://localhost/tunnel', { + method: 'POST', + body: `${JSON.stringify({ dsn: TEST_DSN })}\n`, + headers: { ...clientIpHeaders, 'content-length': '1' }, + }), + { allowedDsns: [TEST_DSN] }, + ); + + expect(fetchMock).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + headers: expect.objectContaining({ ...clientIpHeaders, 'X-Sentry-Forwarded-For': '1.1.1.1' }), + }), + ); + }); + it('forwards the client headers Relay reads the browser and allowed domains from', async () => { fetchMock.mockResolvedValueOnce(new Response('ok')); const clientHeaders = { From 9154110f618598f34ceb606987d022609543298f Mon Sep 17 00:00:00 2001 From: Andrei <168741329+andreiborza@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:08:52 +0100 Subject: [PATCH 003/136] ref(server-utils): Use shared stream state and endStreamSpan for Bedrock streams (#26192) ## What Bedrock ConverseStream and InvokeModelWithResponseStream spans now collect stream data into the shared stream state and end through `endStreamSpan`, like the other AI integrations. Stream spans now also get `gen_ai.response.streaming` and a total token count for all model families. ## Why The shared state is the base for recording Bedrock outputs in a later PR, and it makes Bedrock stream spans consistent with the other AI integrations. Extracted from #26118. --------- Co-authored-by: Claude Opus 5.5 --- .../suites/aws-serverless/bedrock/test.ts | 3 + .../aws-sdk/services/bedrock-runtime.ts | 219 ++++++++---------- .../test/integrations/aws-sdk-bedrock.test.ts | 84 ++++++- 3 files changed, 186 insertions(+), 120 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts index 24249bf2dcc8..c028dbc686d7 100644 --- a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts +++ b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts @@ -6,6 +6,7 @@ import { GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_STREAMING, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, SENTRY_OP, @@ -57,6 +58,7 @@ function assertStreamSpans(container: SerializedStreamedSpanContainer): void { const converseStreamSpan = container.items.find(span => span.name === `chat ${MODEL_ID}`); expect(converseStreamSpan!.status).toBe('ok'); expect(converseStreamSpan!.attributes[SENTRY_OP].value).toBe(GEN_AI_CHAT); + expect(converseStreamSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); expect(converseStreamSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12); expect(converseStreamSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8); expect(converseStreamSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["tool_use"]'); @@ -64,6 +66,7 @@ function assertStreamSpans(container: SerializedStreamedSpanContainer): void { const invokeStreamSpan = container.items.find(span => span.name === `generate_content ${MODEL_ID}`); expect(invokeStreamSpan!.status).toBe('ok'); expect(invokeStreamSpan!.attributes[SENTRY_OP].value).toBe(GEN_AI_GENERATE_CONTENT); + expect(invokeStreamSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); expect(invokeStreamSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15); expect(invokeStreamSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(9); expect(invokeStreamSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["end_turn"]'); diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts index c7ba139f9f48..538b5f99726c 100644 --- a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts @@ -9,13 +9,12 @@ import { GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, - GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, - GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op'; -import { getTokenUsageAttributes } from '../../../ai/core/utils'; +import type { StreamResponseState } from '../../../ai/core/utils'; +import { endStreamSpan, getTokenUsageAttributes } from '../../../ai/core/utils'; import { DEBUG_BUILD } from '../../../debug-build'; import { GEN_AI_OPERATION_NAME_VALUE_CHAT, @@ -280,7 +279,12 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { // Wrap and replace the response stream in place to process events into telemetry // before yielding to the user. - response.data.stream = wrapConverseStreamResponse(response.data.stream, span, response.request.abortSignal); + response.data.stream = instrumentStream( + response.data.stream as AsyncIterable, + span, + response.request.abortSignal, + processConverseStreamEvent, + ); } private _responseHookInvokeModel(response: NormalizedResponse, span: Span): void { @@ -367,7 +371,6 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { private _responseHookInvokeModelWithResponseStream(response: NormalizedResponse, span: Span): void { const stream = response.data?.body; const modelId = response.request.commandInput?.modelId; - const abortSignal = response.request.abortSignal; if (!stream) { span.end(); return; @@ -375,75 +378,73 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { // Resolved once: the model family is fixed for the whole stream, and for unrecognized families // the chunks don't need to be parsed at all. - const recordAttributes = typeof modelId === 'string' ? resolveStreamRecorder(modelId) : undefined; + const processChunk = typeof modelId === 'string' ? resolveStreamProcessor(modelId) : undefined; // Replace the original response body with our instrumented stream, deferring span.end() until the // entire stream is consumed. Downstream consumers still receive the full stream. - response.data.body = (async function* () { - try { - for await (const chunk of stream) { - if (recordAttributes) { - const parsedChunk = parseChunk(chunk?.chunk?.bytes); - if (parsedChunk) { - recordAttributes(parsedChunk, span); - } + response.data.body = instrumentStream( + stream as AsyncIterable<{ chunk?: { bytes?: Uint8Array } }>, + span, + response.request.abortSignal, + (item, state) => { + if (processChunk) { + const parsedChunk = parseChunk(item?.chunk?.bytes); + if (parsedChunk) { + processChunk(parsedChunk, state); } - yield chunk; } - } catch (error) { - setStreamErrorStatus(span, abortSignal); - throw error; - } finally { - span.end(); - } - })(); + }, + ); } } -function resolveStreamRecorder(modelId: string): ((parsedChunk: ParsedChunk, span: Span) => void) | undefined { - if (modelId.includes('amazon.titan')) return recordTitanAttributes; - if (modelId.includes('anthropic.claude')) return recordClaudeAttributes; - if (modelId.includes('amazon.nova')) return recordNovaAttributes; - if (modelId.includes('meta.llama')) return recordLlamaAttributes; - if (modelId.includes('cohere.command-r')) return recordCohereRAttributes; - if (modelId.includes('cohere.command')) return recordCohereAttributes; - if (modelId.includes('mistral')) return recordMistralAttributes; +type StreamProcessor = (parsedChunk: ParsedChunk, state: StreamResponseState) => void; + +function resolveStreamProcessor(modelId: string): StreamProcessor | undefined { + if (modelId.includes('amazon.titan')) return processTitanChunk; + if (modelId.includes('anthropic.claude')) return processClaudeChunk; + if (modelId.includes('amazon.nova')) return processNovaChunk; + if (modelId.includes('meta.llama')) return processLlamaChunk; + if (modelId.includes('cohere.command-r')) return processCohereRChunk; + if (modelId.includes('cohere.command')) return processCohereChunk; + if (modelId.includes('mistral')) return processMistralChunk; return undefined; } -async function* wrapConverseStreamResponse( - stream: AsyncIterable, +/** Collects the stream items into a state and sets the span attributes from it when the stream ends. */ +async function* instrumentStream( + stream: AsyncIterable, span: Span, abortSignal: AbortSignal | undefined, -): AsyncGenerator { + processItem: (item: T, state: StreamResponseState) => void, +): AsyncGenerator { + const state: StreamResponseState = { finishReasons: [], responseTexts: [], toolCalls: [] }; try { - let usage: TokenUsage | undefined; for await (const item of stream) { - setStopReason(span, item.messageStop?.stopReason); - usage = item.metadata?.usage; + processItem(item, state); yield item; } - span.setAttributes( - getTokenUsageAttributes( - // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input. - typeof usage?.inputTokens === 'number' - ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0) - : undefined, - usage?.outputTokens, - usage?.cacheWriteInputTokens, - usage?.cacheReadInputTokens, - ), - ); } catch (error) { - setStreamErrorStatus(span, abortSignal); + span.setStatus({ code: SPAN_STATUS_ERROR, message: abortSignal?.aborted ? 'cancelled' : 'internal_error' }); throw error; } finally { - span.end(); + endStreamSpan(span, state, false); } } -function setStreamErrorStatus(span: Span, abortSignal: AbortSignal | undefined): void { - span.setStatus({ code: SPAN_STATUS_ERROR, message: abortSignal?.aborted ? 'cancelled' : 'internal_error' }); +function processConverseStreamEvent(event: ConverseStreamOutput, state: StreamResponseState): void { + pushFinishReason(state, event.messageStop?.stopReason); + const usage = event.metadata?.usage; + if (usage) { + // With prompt caching, `inputTokens` leaves out cache reads and writes, which the conventions count as input. + state.promptTokens = + typeof usage.inputTokens === 'number' + ? usage.inputTokens + (usage.cacheReadInputTokens ?? 0) + (usage.cacheWriteInputTokens ?? 0) + : undefined; + state.completionTokens = usage.outputTokens; + state.cacheReadInputTokens = usage.cacheReadInputTokens; + state.cacheCreationInputTokens = usage.cacheWriteInputTokens; + } } function setStopReason(span: Span, stopReason: string | undefined): void { @@ -452,21 +453,9 @@ function setStopReason(span: Span, stopReason: string | undefined): void { } } -/** - * `getTokenUsageAttributes` is not used here: `message_start` carries only a placeholder output token count, - * so a total computed from it would be wrong. - */ -function setClaudeStreamInputTokens(span: Span, usage: ParsedChunk): void { - const cacheReadTokens = usage?.cache_read_input_tokens; - const cacheWriteTokens = usage?.cache_creation_input_tokens; - if (typeof usage?.input_tokens === 'number') { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens + (cacheReadTokens ?? 0) + (cacheWriteTokens ?? 0)); - } - if (typeof cacheReadTokens === 'number') { - span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheReadTokens); - } - if (typeof cacheWriteTokens === 'number') { - span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteTokens); +function pushFinishReason(state: StreamResponseState, reason: unknown): void { + if (typeof reason === 'string') { + state.finishReasons.push(reason); } } @@ -496,86 +485,82 @@ function parseChunk(bytes?: Uint8Array): ParsedChunk { } } -function recordNovaAttributes(parsedChunk: ParsedChunk, span: Span): void { - if (parsedChunk.metadata?.usage !== undefined) { - if (parsedChunk.metadata?.usage.inputTokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, parsedChunk.metadata.usage.inputTokens); - } - if (parsedChunk.metadata?.usage.outputTokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, parsedChunk.metadata.usage.outputTokens); - } +function processNovaChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + const usage = parsedChunk.metadata?.usage; + if (typeof usage?.inputTokens === 'number') { + state.promptTokens = usage.inputTokens; } - if (parsedChunk.messageStop?.stopReason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.messageStop.stopReason])); + if (typeof usage?.outputTokens === 'number') { + state.completionTokens = usage.outputTokens; } + pushFinishReason(state, parsedChunk.messageStop?.stopReason); } -function recordClaudeAttributes(parsedChunk: ParsedChunk, span: Span): void { - setClaudeStreamInputTokens(span, parsedChunk.message?.usage); - // `message_start` carries only a placeholder output count. The final count arrives in `message_delta`. - if (parsedChunk.usage?.output_tokens !== undefined) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, parsedChunk.usage.output_tokens); +function processClaudeChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + const inputUsage = parsedChunk.message?.usage; + if (typeof inputUsage?.cache_read_input_tokens === 'number') { + state.cacheReadInputTokens = inputUsage.cache_read_input_tokens; } - if (parsedChunk.delta?.stop_reason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.delta.stop_reason])); + if (typeof inputUsage?.cache_creation_input_tokens === 'number') { + state.cacheCreationInputTokens = inputUsage.cache_creation_input_tokens; } + if (typeof inputUsage?.input_tokens === 'number') { + // Anthropic's `input_tokens` leaves out cache reads and writes, which the conventions count as input. + state.promptTokens = + inputUsage.input_tokens + (state.cacheReadInputTokens ?? 0) + (state.cacheCreationInputTokens ?? 0); + } + // `message_start` carries only a placeholder output count. The final count arrives in `message_delta`. + if (typeof parsedChunk.usage?.output_tokens === 'number') { + state.completionTokens = parsedChunk.usage.output_tokens; + } + pushFinishReason(state, parsedChunk.delta?.stop_reason); } -function recordTitanAttributes(parsedChunk: ParsedChunk, span: Span): void { - if (parsedChunk.inputTextTokenCount !== undefined) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, parsedChunk.inputTextTokenCount); - } - if (parsedChunk.totalOutputTextTokenCount !== undefined) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, parsedChunk.totalOutputTextTokenCount); +function processTitanChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + if (typeof parsedChunk.inputTextTokenCount === 'number') { + state.promptTokens = parsedChunk.inputTextTokenCount; } - if (parsedChunk.completionReason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.completionReason])); + if (typeof parsedChunk.totalOutputTextTokenCount === 'number') { + state.completionTokens = parsedChunk.totalOutputTextTokenCount; } + pushFinishReason(state, parsedChunk.completionReason); } -function recordLlamaAttributes(parsedChunk: ParsedChunk, span: Span): void { - if (parsedChunk.prompt_token_count !== undefined) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, parsedChunk.prompt_token_count); +function processLlamaChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + if (typeof parsedChunk.prompt_token_count === 'number') { + state.promptTokens = parsedChunk.prompt_token_count; } - if (parsedChunk.generation_token_count !== undefined) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, parsedChunk.generation_token_count); - } - if (parsedChunk.stop_reason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.stop_reason])); + if (typeof parsedChunk.generation_token_count === 'number') { + state.completionTokens = parsedChunk.generation_token_count; } + pushFinishReason(state, parsedChunk.stop_reason); } /** * Bedrock adds the token counts to the last chunk of a stream. For models that send no counts of their own, * this is the only real count. */ -function recordInvocationMetrics(parsedChunk: ParsedChunk, span: Span): void { +function processInvocationMetrics(parsedChunk: ParsedChunk, state: StreamResponseState): void { const metrics = parsedChunk['amazon-bedrock-invocationMetrics']; if (typeof metrics?.inputTokenCount === 'number') { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, metrics.inputTokenCount); + state.promptTokens = metrics.inputTokenCount; } if (typeof metrics?.outputTokenCount === 'number') { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, metrics.outputTokenCount); + state.completionTokens = metrics.outputTokenCount; } } -function recordMistralAttributes(parsedChunk: ParsedChunk, span: Span): void { - recordInvocationMetrics(parsedChunk, span); - if (parsedChunk.outputs?.[0]?.stop_reason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.outputs[0].stop_reason])); - } +function processMistralChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + processInvocationMetrics(parsedChunk, state); + pushFinishReason(state, parsedChunk.outputs?.[0]?.stop_reason); } -function recordCohereAttributes(parsedChunk: ParsedChunk, span: Span): void { - recordInvocationMetrics(parsedChunk, span); - if (parsedChunk.generations?.[0]?.finish_reason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.generations[0].finish_reason])); - } +function processCohereChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + processInvocationMetrics(parsedChunk, state); + pushFinishReason(state, parsedChunk.generations?.[0]?.finish_reason); } -function recordCohereRAttributes(parsedChunk: ParsedChunk, span: Span): void { - recordInvocationMetrics(parsedChunk, span); - if (parsedChunk.finish_reason !== undefined) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([parsedChunk.finish_reason])); - } +function processCohereRChunk(parsedChunk: ParsedChunk, state: StreamResponseState): void { + processInvocationMetrics(parsedChunk, state); + pushFinishReason(state, parsedChunk.finish_reason); } diff --git a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts index a63e70d3324c..e7fbf41d50d0 100644 --- a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts +++ b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts @@ -4,6 +4,7 @@ import { GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, + GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, @@ -220,6 +221,58 @@ describe('BedrockRuntimeServiceExtension stream spans', () => { }).toEqual(expected); }); + it.each([ + { + family: 'Llama', + modelId: 'meta.llama3-8b-instruct-v1:0', + chunks: [ + { generation: 'Kawasaki', prompt_token_count: 12, generation_token_count: 1, stop_reason: null }, + { generation: '.', prompt_token_count: null, generation_token_count: 2, stop_reason: 'stop' }, + ], + expected: { input: 12, output: 2, total: 14, finishReasons: '["stop"]' }, + }, + { + family: 'Titan', + modelId: 'amazon.titan-text-express-v1', + chunks: [ + { outputText: 'Kawasaki', totalOutputTextTokenCount: null, completionReason: null, inputTextTokenCount: 5 }, + { outputText: '.', totalOutputTextTokenCount: 2, completionReason: 'FINISH', inputTextTokenCount: null }, + ], + expected: { input: 5, output: 2, total: 7, finishReasons: '["FINISH"]' }, + }, + { + family: 'Nova', + modelId: 'amazon.nova-lite-v1:0', + chunks: [ + { contentBlockDelta: { delta: { text: 'Kawasaki' }, contentBlockIndex: 0 } }, + { messageStop: { stopReason: 'end_turn' } }, + { metadata: { usage: { inputTokens: 7, outputTokens: 2 }, metrics: {}, trace: {} } }, + ], + expected: { input: 7, output: 2, total: 9, finishReasons: '["end_turn"]' }, + }, + ])('records token usage and finish reasons for a $family stream', async ({ modelId, chunks, expected }) => { + const span = startInactiveSpan({ name: 'bedrock' }); + const encoder = new TextEncoder(); + const data = { + body: (async function* () { + for (const chunk of chunks) { + yield { chunk: { bytes: encoder.encode(JSON.stringify(chunk)) } }; + } + })(), + }; + + respond(span, 'InvokeModelWithResponseStream', { modelId }, data); + await drain(data.body); + + const attributes = spanToJSON(span).attributes; + expect({ + input: attributes?.[GEN_AI_USAGE_INPUT_TOKENS], + output: attributes?.[GEN_AI_USAGE_OUTPUT_TOKENS], + total: attributes?.[GEN_AI_USAGE_TOTAL_TOKENS], + finishReasons: attributes?.[GEN_AI_RESPONSE_FINISH_REASONS], + }).toEqual(expected); + }); + it('ends an InvokeModelWithResponseStream span without a modelId when the stream is drained', async () => { const span = startInactiveSpan({ name: 'bedrock' }); const data = { body: (async function* () {})() }; @@ -291,6 +344,31 @@ describe('BedrockRuntimeServiceExtension token usage with prompt caching', () => expect(usageAttributes(span, EXPECTED_USAGE)).toEqual(EXPECTED_USAGE); }); + it('counts cache reads and writes in the total tokens for ConverseStream', async () => { + const span = startInactiveSpan({ name: 'bedrock' }); + const data = { + stream: (async function* () { + yield { + metadata: { + // The total comes from the cache-adjusted input, like for Converse, not from `totalTokens`. + usage: { + inputTokens: 20, + outputTokens: 50, + totalTokens: 70, + cacheReadInputTokens: 1800, + cacheWriteInputTokens: 300, + }, + }, + }; + })(), + }; + + respond(span, 'ConverseStream', { modelId: CLAUDE_MODEL_ID }, data); + await drain(data.stream); + + expect(usageAttributes(span, EXPECTED_USAGE)).toEqual(EXPECTED_USAGE); + }); + it('counts cache reads and writes as input tokens for Claude InvokeModel', () => { const span = startInactiveSpan({ name: 'bedrock' }); const body = encoder.encode( @@ -315,17 +393,17 @@ describe('BedrockRuntimeServiceExtension token usage with prompt caching', () => type: 'message_start', message: { id: 'msg_bdrk_01Fv2yWBqLQ8Pp4q9kJbDxXz', role: 'assistant', usage: CLAUDE_USAGE }, }; + const messageDelta = { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 50 } }; const data = { body: (async function* () { yield { chunk: { bytes: encoder.encode(JSON.stringify(messageStart)) } }; + yield { chunk: { bytes: encoder.encode(JSON.stringify(messageDelta)) } }; })(), }; respond(span, 'InvokeModelWithResponseStream', { modelId: CLAUDE_MODEL_ID }, data); await drain(data.body); - // The total waits for the final output count, which `message_start` does not carry. - const expected = { ...EXPECTED_INPUT_USAGE, [GEN_AI_USAGE_TOTAL_TOKENS]: undefined }; - expect(usageAttributes(span, expected)).toEqual(expected); + expect(usageAttributes(span, EXPECTED_USAGE)).toEqual(EXPECTED_USAGE); }); }); From 6b42ee7d58c469cfefca4dc09d9024d874fae499 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:55:21 +0100 Subject: [PATCH 004/136] feat(tanstackstart-react): Initialize the SDK when the Nitro server starts (#26224) **Why:** Nitro imports the server entry lazily, in the first request. Without `node --import`, an `import './instrument.server'` in `server.ts` runs `Sentry.init()` only after that request started, so every cold start loses its `http.server` span. This follows what `@sentry/nuxt` does since #24094: the Vite plugin finds `instrument.server.{ts,mts,js,mjs}` (project root, then `src/`), bundles it into the Nitro build and loads it from a Nitro plugin, which runs when the server starts. Like Nuxt, this is always on and has no option. Orchestrion already instruments the drivers at build time, so `--import` is no longer needed in production. In `vite dev` you still need it. Existing setups keep working. A `--import` preload or an import in `server.ts` now runs `init()` a second time. The first client wins, and the SDK logs that the preload or import can be removed (Nuxt logs the same). `init()` is also skipped while TanStack Start prerenders (`TSS_PRERENDERING`), which Nuxt does too. Otherwise the bundled config would send events from the build. The `tanstackstart-react` e2e app now starts without `--import`. The whole suite passes locally that way, including the ioredis and mysql spans. `tanstackstart-react-static` keeps `--import`, so it covers existing start commands. **How to review:** Start with `src/vite/serverInstrumentation.ts`, then `init()` in `src/server/sdk.ts`. **Unsure about:** The docs still tell people to copy `instrument.server.mjs` and preload it, or to import it in `server.ts`. They need a follow-up in sentry-docs, like the Nuxt migration note. Closes JS-4051 via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794297657.485969) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794297657.485969/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Claude Co-authored-by: Francesco Gringl-Novy Co-authored-by: Charly Gomez --- .../tanstackstart-react/package.json | 5 +- .../tests/first-request.test.ts | 57 ++++++++++++ docs/repeated-init.md | 1 + .../tanstackstart-react/src/server/sdk.ts | 21 ++++- .../src/vite/nitroSourceMaps.ts | 3 +- .../src/vite/sentryTanstackStart.ts | 3 + .../src/vite/serverInstrumentation.ts | 83 ++++++++++++++++++ .../test/server/sdk.test.ts | 41 +++++++++ .../test/vite/sentryTanstackStart.test.ts | 34 ++++++++ .../test/vite/serverInstrumentation.test.ts | 87 +++++++++++++++++++ 10 files changed, 331 insertions(+), 4 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/first-request.test.ts create mode 100644 packages/tanstackstart-react/src/vite/serverInstrumentation.ts create mode 100644 packages/tanstackstart-react/test/vite/serverInstrumentation.test.ts diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json index 14566ba22a7e..0eef79524818 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json @@ -4,9 +4,9 @@ "version": "0.0.1", "type": "module", "scripts": { - "build": "node start-mock-sentry-server.mjs & (vite build && cp instrument.server.mjs .output/server) > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; if [ $BUILD_EXIT -ne 0 ]; then cat .tmp_build_stdout; cat .tmp_build_stderr >&2; fi; exit $BUILD_EXIT", + "build": "node start-mock-sentry-server.mjs & vite build > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; if [ $BUILD_EXIT -ne 0 ]; then cat .tmp_build_stdout; cat .tmp_build_stderr >&2; fi; exit $BUILD_EXIT", "dev": "vite dev", - "start": "node --import ./.output/server/instrument.server.mjs .output/server/index.mjs", + "start": "node .output/server/index.mjs", "test": "playwright test", "clean": "npx rimraf node_modules pnpm-lock.yaml", "test:build": "pnpm install && pnpm build", @@ -36,6 +36,7 @@ "mysql": "^2.18.1" }, "devDependencies": { + "@sentry/conventions": "0.31.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@types/node": "^24.10.0", diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/first-request.test.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/first-request.test.ts new file mode 100644 index 000000000000..17c38dd591b8 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/first-request.test.ts @@ -0,0 +1,57 @@ +import { type ChildProcess, spawn } from 'node:child_process'; +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; + +const usesManagedTunnelRoute = + (process.env.E2E_TEST_TUNNEL_ROUTE_MODE ?? 'off') !== 'off' || process.env.E2E_TEST_CUSTOM_TUNNEL_ROUTE === '1'; + +test.skip(usesManagedTunnelRoute, 'Default e2e suites run only in the proxy variant'); +test.skip(process.env.TEST_ENV === 'development', 'Needs the production build'); + +// The server that Playwright starts has already handled requests, so this test starts one of its own. Nitro imports +// the server entry on the first request, so the SDK must be initialized before that. +const PORT = 3001; + +let server: ChildProcess | undefined; + +// Playwright skips `finally` blocks of a test that times out. +test.afterEach(() => { + server?.kill(); +}); + +test('Sends an http.server span for the first request of a server started without --import', async () => { + const serverProcess = spawn('node', ['.output/server/index.mjs'], { + env: { ...process.env, PORT: String(PORT) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + server = serverProcess; + + let output = ''; + await new Promise((resolve, reject) => { + const onData = (data: Buffer): void => { + output += data.toString(); + if (output.includes('Listening on')) { + resolve(); + } + }; + serverProcess.stdout.on('data', onData); + serverProcess.stderr.on('data', onData); + serverProcess.once('exit', code => reject(new Error(`Server exited with code ${code}:\n${output}`))); + }); + + const spanPromise = waitForStreamedSpan( + 'tanstackstart-react', + span => + !!span.is_segment && + getSpanOp(span) === HTTP_SERVER && + String(span.attributes[URL_FULL]?.value ?? '').includes(`localhost:${PORT}/`), + ); + + const response = await fetch(`http://localhost:${PORT}/`); + expect(response.status).toBe(200); + + const span = await spanPromise; + expect(span.attributes[URL_PATH]?.value).toBe('/'); +}); diff --git a/docs/repeated-init.md b/docs/repeated-init.md index f584225a858b..cd03851079c3 100644 --- a/docs/repeated-init.md +++ b/docs/repeated-init.md @@ -40,6 +40,7 @@ When `init()` replaces a client, nothing closes the old one: | Next.js server, Remix server, Astro server, Hono Node | Keeps the first client and returns it. Logs in debug mode only. | | Hono Bun and Deno | Keeps the first client and returns it. Warns with its own text. | | Nuxt server | Keeps the first client and returns it. Logs that a `--import` preload is no longer needed. | +| TanStack Start server | Keeps the first client and returns it. Logs that a `--import` preload is no longer needed. | | Cloudflare (default) | Keeps the first client of the isolate and returns it, unless that client is closed or closing. `cacheClient: false` makes a new client on each call, with no warning. | | Next.js edge | Warns, then replaces the client. Returns `void`. | | Next.js server and edge in a request of `withSentry` (Cloudflare) | Creates no client, because the client of `withSentry` handles the request. Returns `undefined`. | diff --git a/packages/tanstackstart-react/src/server/sdk.ts b/packages/tanstackstart-react/src/server/sdk.ts index 987f1105ebc5..dbd9ae9b4bd0 100644 --- a/packages/tanstackstart-react/src/server/sdk.ts +++ b/packages/tanstackstart-react/src/server/sdk.ts @@ -1,4 +1,4 @@ -import { applySdkMetadata } from '@sentry/core'; +import { _INTERNAL_getActiveClient as getActiveClient, applySdkMetadata, consoleSandbox, debug } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; import { _INTERNAL_installTunnelHooks as installTunnelHooks, @@ -10,6 +10,25 @@ import { * Initializes the server side of the TanStack Start React SDK */ export function init(options: NodeOptions): NodeClient | undefined { + // TanStack Start prerenders by running the server at build time. + if (process.env.TSS_PRERENDERING === 'true') { + debug.log('Detected a TanStack Start prerender build. Skipping Sentry server initialization.'); + return undefined; + } + + // The Nitro server build also runs `instrument.server` when it starts, so a `node --import` preload of it or an + // import of it in the server entry initializes the SDK a second time. The first init wins. + const activeClient = getActiveClient(); + if (activeClient) { + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.log( + '[Sentry] The Sentry server SDK is already initialized, skipping a second initialization. With Nitro, the server build loads `instrument.server` when the server starts, so a `node --import` preload of it or an import of it in the server entry is no longer needed and can be removed.', + ); + }); + return activeClient; + } + const sentryOptions: NodeOptions = { defaultIntegrations: [...getDefaultNodeIntegrations(options)], ...options, diff --git a/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts b/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts index f759cc125fc2..478c426f9ecb 100644 --- a/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts +++ b/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts @@ -152,7 +152,8 @@ function hasNitroSourceMapSetting(config: NitroSourceMapConfig | null | undefine ); } -function logDebug(debug: boolean | undefined, message: string): void { +/** Logs a message when the `debug` option is enabled. */ +export function logDebug(debug: boolean | undefined, message: string): void { if (debug) { // eslint-disable-next-line no-console console.log(`[Sentry] ${message}`); diff --git a/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts b/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts index a93360039525..d542af5be045 100644 --- a/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts +++ b/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts @@ -4,6 +4,7 @@ import type { Plugin } from 'vite'; import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware'; import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugin } from './nitroSourceMaps'; import { makeRoutePatternPlugin } from './routePatterns'; +import { makeServerInstrumentationPlugin } from './serverInstrumentation'; import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps'; import type { TunnelRouteOptions } from './tunnelRoute'; import { makeServerEntryTunnelPlugin, makeTunnelBasePathPlugin, makeTunnelRoutePlugin } from './tunnelRoute'; @@ -107,6 +108,8 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P return plugins; } + plugins.push(makeServerInstrumentationPlugin({ debug: options.debug })); + // Runs the orchestrion code transform over the server bundle so instrumented DB drivers get // `diagnostics_channel` publishers injected. Production-only: it force-bundles the instrumented // (CommonJS) deps via `ssr.noExternal`, which the `vite dev` SSR module runner can't evaluate. diff --git a/packages/tanstackstart-react/src/vite/serverInstrumentation.ts b/packages/tanstackstart-react/src/vite/serverInstrumentation.ts new file mode 100644 index 000000000000..cedddacaa96d --- /dev/null +++ b/packages/tanstackstart-react/src/vite/serverInstrumentation.ts @@ -0,0 +1,83 @@ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { Plugin } from 'vite'; +import { logDebug } from './nitroSourceMaps'; + +const FILE_NAMES = ['instrument.server.ts', 'instrument.server.mts', 'instrument.server.js', 'instrument.server.mjs']; +const DIRECTORIES = ['', 'src']; + +const NITRO_PLUGIN_ID = '#sentry/tanstackstart-server-instrumentation'; + +/** The parts of the Nitro instance that this plugin uses. */ +type Nitro = { + options: { + dev: boolean; + node: boolean; + preset: string; + rootDir: string; + plugins: string[]; + virtual: Record; + }; +}; + +/** Finds `instrument.server.{ts,mts,js,mjs}` in the project root or in `src/`. */ +export function findServerInstrumentationFile(root: string): string | undefined { + for (const directory of DIRECTORIES) { + for (const fileName of FILE_NAMES) { + const file = path.join(root, directory, fileName); + if (fs.existsSync(file)) { + return file; + } + } + } + return undefined; +} + +/** + * Bundles the server instrumentation file into the Nitro build and loads it from a Nitro plugin, which runs when the + * server starts. Nitro only imports the server entry in the first request, which is too late to trace that request. + */ +export function makeServerInstrumentationPlugin({ debug }: { debug?: boolean }): Plugin & { + nitro: { name: string; setup: (nitro: Nitro) => void }; +} { + return { + name: 'sentry-tanstackstart-server-instrumentation', + apply: 'build', + nitro: { + name: 'sentry-tanstackstart-server-instrumentation', + setup(nitro) { + if (nitro.options.dev) { + return; + } + + // The Node SDK must not end up in a worker or other runtime without Node.js, such as Cloudflare, where the + // Cloudflare SDK sets itself up. + if (nitro.options.node === false) { + logDebug( + debug, + `Not loading \`instrument.server\` in the Nitro server build, as the \`${nitro.options.preset}\` preset does not run Node.js.`, + ); + return; + } + + const file = findServerInstrumentationFile(nitro.options.rootDir); + if (!file) { + logDebug( + debug, + 'Found no `instrument.server.{ts,mts,js,mjs}` in the project root or in `src/`, so the SDK does not initialize itself when the server starts.', + ); + return; + } + + nitro.options.virtual[NITRO_PLUGIN_ID] = `import ${JSON.stringify(file)};\nexport default () => {};\n`; + // Before the plugins of the app, so they run with an initialized SDK. + nitro.options.plugins.unshift(NITRO_PLUGIN_ID); + + logDebug( + debug, + `Bundled \`${path.relative(nitro.options.rootDir, file)}\` into the Nitro server build. The SDK initializes itself when the server starts, no \`node --import\` needed.`, + ); + }, + }, + }; +} diff --git a/packages/tanstackstart-react/test/server/sdk.test.ts b/packages/tanstackstart-react/test/server/sdk.test.ts index 286058bbf512..5d8ded2de305 100644 --- a/packages/tanstackstart-react/test/server/sdk.test.ts +++ b/packages/tanstackstart-react/test/server/sdk.test.ts @@ -1,4 +1,5 @@ import * as SentryNode from '@sentry/node'; +import { originalConsoleMethods } from '@sentry/core'; import { SDK_VERSION } from '@sentry/node'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { init } from '../../src/server'; @@ -40,6 +41,46 @@ describe('TanStack Start React Server SDK', () => { expect(init({})).not.toBeUndefined(); }); + it('skips a second initialization and notifies that the `--import` preload is removable', () => { + // `consoleSandbox` calls the method recorded in `originalConsoleMethods`, so a spy on `console.log` misses it. + const logMock = vi.fn(); + const originalLog = originalConsoleMethods.log; + originalConsoleMethods.log = logMock; + + try { + const firstClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + const secondClient = init({ dsn: 'https://other@dsn.ingest.sentry.io/42' }); + + expect(nodeInit).toHaveBeenCalledTimes(1); + expect(secondClient).toBe(firstClient); + expect(SentryNode.getClient()).toBe(firstClient); + expect(logMock).toHaveBeenCalledWith(expect.stringContaining('already initialized')); + } finally { + originalConsoleMethods.log = originalLog; + } + }); + + it('initializes again after close()', async () => { + const firstClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + await SentryNode.close(); + + const secondClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + + expect(nodeInit).toHaveBeenCalledTimes(2); + expect(secondClient).not.toBe(firstClient); + }); + + it('skips initialization while TanStack Start prerenders', () => { + vi.stubEnv('TSS_PRERENDERING', 'true'); + + try { + expect(init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' })).toBeUndefined(); + expect(nodeInit).not.toHaveBeenCalled(); + } finally { + vi.unstubAllEnvs(); + } + }); + it('sets ignoreSpans to filter low-quality transactions', () => { init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); diff --git a/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts b/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts index c20de29b89bc..60091f7d93d4 100644 --- a/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts +++ b/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts @@ -2,6 +2,7 @@ import type { Plugin } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { makeAutoInstrumentMiddlewarePlugin } from '../../src/vite/autoInstrumentMiddleware'; import { sentryTanstackStart, type SentryTanstackStartOptions } from '../../src/vite/sentryTanstackStart'; +import { makeServerInstrumentationPlugin } from '../../src/vite/serverInstrumentation'; import { makeServerEntryTunnelPlugin, makeTunnelRoutePlugin } from '../../src/vite/tunnelRoute'; const mockSourceMapsConfigPlugin: Plugin = { @@ -34,6 +35,11 @@ const mockEnableNitroSourceMapsPlugin: Plugin = { apply: 'build', }; +const mockServerInstrumentationPlugin: Plugin = { + name: 'sentry-tanstackstart-server-instrumentation', + apply: 'build', +}; + const mockMiddlewarePlugin: Plugin = { name: 'sentry-tanstack-middleware-auto-instrument', apply: 'build', @@ -87,6 +93,10 @@ vi.mock('../../src/vite/nitroSourceMaps', () => ({ makeEnableNitroSourceMapsPlugin: vi.fn(() => mockEnableNitroSourceMapsPlugin), })); +vi.mock('../../src/vite/serverInstrumentation', () => ({ + makeServerInstrumentationPlugin: vi.fn(() => mockServerInstrumentationPlugin), +})); + vi.mock('../../src/vite/autoInstrumentMiddleware', () => ({ makeAutoInstrumentMiddlewarePlugin: vi.fn(() => mockMiddlewarePlugin), })); @@ -115,6 +125,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -158,6 +169,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -175,6 +187,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -192,6 +205,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -210,6 +224,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -228,6 +243,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -246,6 +262,7 @@ describe('sentryTanstackStart()', () => { mockRoutePatternPlugin, mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -281,6 +298,7 @@ describe('sentryTanstackStart()', () => { mockTunnelBasePathPlugin, mockServerEntryTunnelPlugin, mockTunnelRoutePlugin, + mockServerInstrumentationPlugin, mockOrchestrionPlugin, mockSourceMapsConfigPlugin, mockSentryVitePlugin, @@ -324,6 +342,22 @@ describe('sentryTanstackStart()', () => { }); }); + describe('server instrumentation', () => { + it('passes debug through to the server instrumentation plugin', () => { + sentryTanstackStart({ debug: true, sourcemaps: { disable: true } }); + + expect(makeServerInstrumentationPlugin).toHaveBeenCalledWith({ debug: true }); + }); + + it('does not add the server instrumentation plugin in development mode', () => { + process.env.NODE_ENV = 'development'; + + sentryTanstackStart({ sourcemaps: { disable: true } }); + + expect(makeServerInstrumentationPlugin).not.toHaveBeenCalled(); + }); + }); + describe('orchestrion build-time instrumentation', () => { it('adds the orchestrion plugin by default', () => { const plugins = sentryTanstackStart({ sourcemaps: { disable: true } }); diff --git a/packages/tanstackstart-react/test/vite/serverInstrumentation.test.ts b/packages/tanstackstart-react/test/vite/serverInstrumentation.test.ts new file mode 100644 index 000000000000..06eb5a131e4a --- /dev/null +++ b/packages/tanstackstart-react/test/vite/serverInstrumentation.test.ts @@ -0,0 +1,87 @@ +// @vitest-environment node +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { findServerInstrumentationFile, makeServerInstrumentationPlugin } from '../../src/vite/serverInstrumentation'; + +const NITRO_PLUGIN_ID = '#sentry/tanstackstart-server-instrumentation'; +const APP_PLUGIN = './server/plugins/app.ts'; + +describe('server instrumentation', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-tanstackstart-')); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + function writeFile(relativePath: string): string { + const file = path.join(root, relativePath); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, ''); + return file; + } + + /** Runs the Nitro module like `nitro/vite` does, and returns the Nitro options it changed. */ + function setup({ dev = false, node = true, preset = 'node-server' } = {}) { + const nitro = { options: { dev, node, preset, rootDir: root, plugins: [APP_PLUGIN], virtual: {} } }; + makeServerInstrumentationPlugin({}).nitro.setup(nitro); + return nitro.options; + } + + describe('findServerInstrumentationFile', () => { + it('finds the file in the root before the one in `src/`', () => { + writeFile('src/instrument.server.ts'); + const rootFile = writeFile('instrument.server.mjs'); + + expect(findServerInstrumentationFile(root)).toBe(rootFile); + }); + + it('finds the file in `src/`', () => { + const srcFile = writeFile('src/instrument.server.ts'); + + expect(findServerInstrumentationFile(root)).toBe(srcFile); + }); + + it('returns undefined without a server instrumentation file', () => { + writeFile('src/instrument.client.ts'); + + expect(findServerInstrumentationFile(root)).toBeUndefined(); + }); + }); + + describe('Nitro module', () => { + it('loads the file from a Nitro plugin that runs before the plugins of the app', () => { + const file = writeFile('instrument.server.mjs'); + + const { plugins, virtual } = setup(); + + expect(plugins).toEqual([NITRO_PLUGIN_ID, APP_PLUGIN]); + expect(virtual).toEqual({ [NITRO_PLUGIN_ID]: `import ${JSON.stringify(file)};\nexport default () => {};\n` }); + }); + + it('adds no plugin without a server instrumentation file', () => { + const { plugins, virtual } = setup(); + + expect(plugins).toEqual([APP_PLUGIN]); + expect(virtual).toEqual({}); + }); + + it.each([ + { label: 'Nitro dev', nitro: { dev: true } }, + { label: 'a Cloudflare preset', nitro: { node: false, preset: 'cloudflare-module' } }, + { label: 'another preset without Node.js', nitro: { node: false, preset: 'vercel-edge' } }, + ])('adds no plugin with $label', ({ nitro }) => { + writeFile('instrument.server.mjs'); + + const { plugins, virtual } = setup(nitro); + + expect(plugins).toEqual([APP_PLUGIN]); + expect(virtual).toEqual({}); + }); + }); +}); From aba9efbfb00d80af623e40bac6363ef5c7a8eb81 Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Tue, 10 Nov 2026 17:26:44 +0100 Subject: [PATCH 005/136] chore: Revert add catch-all rule for shared packages in CODEOWNERS (#25789) (#26255) This reverts commit a6aa2e286dfa1a4946ac507b0e37df46d26cbaba. --- .github/CODEOWNERS | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 148f6bbb4695..a6dc12f405db 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,6 +1,3 @@ -# Catch-all rule for shared packages -* @getsentry/team-javascript-sdks-browser @getsentry/team-javascript-sdks-server @getsentry/team-javascript-sdks-framework - # Browser, replay, feedback, and related packages /packages/browser/ @getsentry/team-javascript-sdks-browser /packages/browser-utils/ @getsentry/team-javascript-sdks-browser From b31ae895ec3209f10d0fba318d51601973bd49ab Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:31:14 -0500 Subject: [PATCH 006/136] docs(browser): Fix `enableLongAnimationFrame` default in JSDoc (#26256) **Why:** The JSDoc for `enableLongAnimationFrame` says `Default: false`, but `DEFAULT_BROWSER_TRACING_OPTIONS` sets it to `true`. This fixes only the comment and has no runtime change. It was split out from #26141, which was closed in favor of #26253. via @BYK. -- [View Session in Sentry](https://sentry.sentry.io/explore/conversations/agent%3Aaf6d95d56ac3e36093e1be6d251b295c/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <126780+BYK@users.noreply.github.com> --- packages/browser/src/tracing/browserTracingIntegration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/browser/src/tracing/browserTracingIntegration.ts b/packages/browser/src/tracing/browserTracingIntegration.ts index e21b40a86f27..3959d0ac4d0b 100644 --- a/packages/browser/src/tracing/browserTracingIntegration.ts +++ b/packages/browser/src/tracing/browserTracingIntegration.ts @@ -127,7 +127,7 @@ export interface BrowserTracingOptions { /** * If true, Sentry will capture long animation frames and add them to the corresponding transaction. * - * Default: false + * Default: true */ enableLongAnimationFrame: boolean; From 52948fa8a5f8d9c0274f4955813a062ba4d7435b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:08:39 -0500 Subject: [PATCH 007/136] fix(bundler-plugins): Keep uploading when a directory has no source maps (#26092) **Why:** The new `sentry` CLI throws a `ValidationError` for any directory that has no JS + source map pairs. `SentryCliAdapter.uploadSourcemaps` uploads directories one at a time, so the first empty directory stops the whole loop. `@sentry/nextjs` uploads `.next/server` first, so if server source maps are off, the client chunks that do have maps never get uploaded. The plugin only logs the error and the build passes, so this goes unnoticed. CLI 0.48+ stops reporting this error to Sentry, but it still throws, so the upload still stops without this change. The CLI check stays strict on purpose, because it catches build misconfiguration. The adapter now passes `allowEmpty: true`, collects the directories that uploaded 0 files, and logs a warning for each. In direct-upload mode, "Successfully uploaded" is logged only if at least one directory actually uploaded something. The staged-upload path already returns early with a warning when no artifact has a source map, so it is unchanged. Before: ``` [@sentry/nextjs - Node.js] Error: An error occurred. Couldn't finish all operations: ValidationError: Found 214 JS file(s) in '.next/server' but no companion .map files. [...] Pass --allow-empty to suppress. # .next/static/chunks is never uploaded ``` After: ``` [@sentry/nextjs - Node.js] Warning: No source maps found in ".next/server", so nothing was uploaded from it. This usually means source map generation is not enabled for this build output. Enable it so Sentry can un-minify stack traces from these files. [@sentry/nextjs - Node.js] Info: Successfully uploaded source maps to Sentry # .next/static/chunks is uploaded ``` **How to review:** Start with `src/core/cli.ts`, then the two call sites in `build-plugin-manager.ts`. `cli-contract.test.ts` runs the real CLI (now `sentry@^0.49.0` after #26200) against the mock server with one empty directory followed by one real directory. **Unsure about:** A directory that does not exist still throws and stops the loop; `allowEmpty` only covers existing directories without source maps. I left that case out of this PR. via **bete**, @betegon. -- [View Session in Sentry](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A667ad986d499815a40e93973/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Miguel Betegon Co-authored-by: bete <28983162+betegon@users.noreply.github.com> --- .../src/core/build-plugin-manager.ts | 25 +++++-- packages/bundler-plugins/src/core/cli.ts | 18 ++++- .../test/core/build-plugin-manager.test.ts | 67 +++++++++++++++++++ .../test/core/cli-contract.test.ts | 15 +++++ 4 files changed, 117 insertions(+), 8 deletions(-) diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 2e43f8adca09..e51934210948 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -575,7 +575,7 @@ export function createSentryBuildPluginManager( })), ); - await cliInstance.uploadSourcemaps(releaseName, uploadTargets); + warnAboutDirectoriesWithoutSourcemaps(logger, await cliInstance.uploadSourcemaps(releaseName, uploadTargets)); } if (options.release.setCommits !== false) { @@ -707,9 +707,9 @@ export function createSentryBuildPluginManager( return; } - await startSpan({ name: 'upload', scope: sentryScope }, async () => { + const emptyDirectories = await startSpan({ name: 'upload', scope: sentryScope }, async () => { const cliInstance = new SentryCliAdapter(options); - await cliInstance.uploadSourcemaps( + return cliInstance.uploadSourcemaps( options.release.name ?? 'undefined', pathsToUpload.map(directory => ({ directory, @@ -719,8 +719,11 @@ export function createSentryBuildPluginManager( ); }); - uploaded = true; - logger.info('Successfully uploaded source maps to Sentry'); + warnAboutDirectoriesWithoutSourcemaps(logger, emptyDirectories); + if (emptyDirectories.length < pathsToUpload.length) { + uploaded = true; + logger.info('Successfully uploaded source maps to Sentry'); + } } else { // Prepare artifacts in temp folder before uploading let globAssets: string | string[]; @@ -1060,3 +1063,15 @@ function canUploadSourceMaps(options: NormalizedOptions, logger: Logger, isDevMo return true; } } + +function warnAboutDirectoriesWithoutSourcemaps(logger: Logger, directories: string[]): void { + if (directories.length === 0) { + return; + } + const list = directories.map(directory => ` - ${directory}`).join('\n'); + logger.warn( + `No source maps found in the following directories, so nothing was uploaded from them:\n${list}\n` + + 'This usually means source map generation is not enabled for these build outputs. ' + + 'Enable it so Sentry can un-minify stack traces from these files.', + ); +} diff --git a/packages/bundler-plugins/src/core/cli.ts b/packages/bundler-plugins/src/core/cli.ts index 2e12bd16b40a..5ecc6603d78d 100644 --- a/packages/bundler-plugins/src/core/cli.ts +++ b/packages/bundler-plugins/src/core/cli.ts @@ -120,14 +120,20 @@ export class SentryCliAdapter { * array; the new `sourcemap upload` command takes a single directory, so we upload each target * separately. A client is created per project because project selection is bound at client * creation time. + * + * Empty directories must not abort the loop: `@sentry/nextjs` uploads `.next/server` first, and + * a server build without source maps would otherwise skip every client directory after it. + * + * @returns The directories that had no source maps to upload. */ - public async uploadSourcemaps(name: string, targets: UploadTarget[]): Promise { + public async uploadSourcemaps(name: string, targets: UploadTarget[]): Promise { const projects = getProjects(this.#options.project) ?? [undefined]; + const emptyDirectories = new Set(); for (const project of projects) { const sdk = this.#createClient(project); for (const target of targets) { - await sdk.sourcemap.upload({ + const result = (await sdk.sourcemap.upload({ directory: target.directory, release: name, dist: target.dist ?? this.#options.release.dist, @@ -135,9 +141,15 @@ export class SentryCliAdapter { ignore: serializeIgnore(target.ignore), ignoreFile: target.ignoreFile, urlPrefix: target.urlPrefix, - }); + allowEmpty: true, + })) as { filesUploaded?: number } | undefined; + if (result?.filesUploaded === 0) { + emptyDirectories.add(target.directory); + } } } + + return [...emptyDirectories]; } /** Inject debug IDs into the given build artifacts. */ diff --git a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts index e5105d55f4f8..d73caeb84443 100644 --- a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts +++ b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts @@ -345,6 +345,72 @@ describe('createSentryBuildPluginManager', () => { expect(mockPrepareBundleForDebugIdUpload).not.toHaveBeenCalled(); }); + it('keeps uploading the other directories when one has no source maps', async () => { + mockSourcemapUpload.mockResolvedValueOnce({ filesUploaded: 0 }).mockResolvedValueOnce({ filesUploaded: 4 }); + + const manager = createSentryBuildPluginManager( + { authToken: 't', org: 'o', project: 'p', release: { name: 'some-release-name' } }, + { buildTool: 'webpack', loggerPrefix: '[sentry-webpack-plugin]' }, + ); + const warnSpy = vi.spyOn(manager.logger, 'warn'); + const infoSpy = vi.spyOn(manager.logger, 'info'); + + const result = await manager.uploadSourcemaps(['.next/server', '.next/static/chunks'], { + prepareArtifacts: false, + }); + + expect(mockSourcemapUpload).toHaveBeenCalledTimes(2); + expect(mockSourcemapUpload).toHaveBeenCalledWith( + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + expect.objectContaining({ directory: '.next/server', allowEmpty: true }), + ); + expect(warnSpy).toHaveBeenCalledOnce(); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(' - .next/server\n')); + expect(infoSpy).toHaveBeenCalledWith('Successfully uploaded source maps to Sentry'); + expect(result).toEqual({ uploaded: true }); + + vi.restoreAllMocks(); + }); + + it('warns once and lists every directory without source maps', async () => { + mockSourcemapUpload + .mockResolvedValueOnce({ filesUploaded: 0 }) + .mockResolvedValueOnce({ filesUploaded: 0 }) + .mockResolvedValueOnce({ filesUploaded: 4 }); + + const manager = createSentryBuildPluginManager( + { authToken: 't', org: 'o', project: 'p', release: { name: 'some-release-name' } }, + { buildTool: 'webpack', loggerPrefix: '[sentry-webpack-plugin]' }, + ); + const warnSpy = vi.spyOn(manager.logger, 'warn'); + + await manager.uploadSourcemaps(['.next/server', '.next/edge', '.next/static/chunks'], { + prepareArtifacts: false, + }); + + expect(warnSpy).toHaveBeenCalledOnce(); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(' - .next/server\n - .next/edge\n')); + + vi.restoreAllMocks(); + }); + + it('does not report success when no directory has source maps', async () => { + mockSourcemapUpload.mockResolvedValue({ filesUploaded: 0 }); + + const manager = createSentryBuildPluginManager( + { authToken: 't', org: 'o', project: 'p', release: { name: 'some-release-name' } }, + { buildTool: 'webpack', loggerPrefix: '[sentry-webpack-plugin]' }, + ); + const infoSpy = vi.spyOn(manager.logger, 'info'); + + const result = await manager.uploadSourcemaps(['.next/server'], { prepareArtifacts: false }); + + expect(infoSpy).not.toHaveBeenCalledWith('Successfully uploaded source maps to Sentry'); + expect(result).toEqual({ uploaded: false }); + + vi.restoreAllMocks(); + }); + it('exits early when assets is an empty array', async () => { const manager = createSentryBuildPluginManager( { @@ -419,6 +485,7 @@ describe('createSentryBuildPluginManager', () => { ignore: undefined, ignoreFile: undefined, urlPrefix: undefined, + allowEmpty: true, }); }); diff --git a/packages/bundler-plugins/test/core/cli-contract.test.ts b/packages/bundler-plugins/test/core/cli-contract.test.ts index f6c1a1d4c50d..51ad7ab86ecd 100644 --- a/packages/bundler-plugins/test/core/cli-contract.test.ts +++ b/packages/bundler-plugins/test/core/cli-contract.test.ts @@ -195,6 +195,21 @@ describe('SentryCliAdapter against the real CLI', () => { expect(requestsSince(before)).toContain('POST /api/0/organizations/test-org/artifactbundle/assemble/'); }); + it('skips a directory without source maps and still uploads the next one', async () => { + const emptyDir = join(workDir, 'server'); + mkdirSync(emptyDir); + writeFileSync(join(emptyDir, 'page.js'), 'console.log("no map");\n'); + const before = recordedRequests(); + + const emptyDirectories = await createAdapter().uploadSourcemaps('1.0.0', [ + { directory: emptyDir }, + { directory: buildDir }, + ]); + + expect(emptyDirectories).toEqual([emptyDir]); + expect(requestsSince(before)).toContain('POST /api/0/organizations/test-org/artifactbundle/assemble/'); + }); + it('resolves the server url, or gives up quietly', async () => { const adapter = createAdapter(); From bcf7aea42e19f3191a1e7383da7e14a14ba1df5a Mon Sep 17 00:00:00 2001 From: Rola Abuhasna Date: Tue, 10 Nov 2026 18:40:38 +0100 Subject: [PATCH 008/136] fix(server-utils): Record Anthropic chat spans for thread and tool-runner streams on 1.2+ (#25931) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On `@anthropic-ai/sdk` 1.2.0+, streamed turns from `beta.messages.toolRunner({ stream: true })` and `beta.messages.thread().stream()` had no `gen_ai.chat` spans. Every tool runner runs over a thread since 1.2.0, including on Bedrock and Vertex. The thread calls `beta.messages.create()`, which opens our span, but parses the response through a new `APIPromise` our hook never sees, so the span never ended. This hooks `BetaMessageStream._start()`, matches each request to its stream by abort signal, and ends the span from the stream's events with usage and output. `instrumentMessageStream` now also ends the span on `end`, so aborted or truncated streams, `messages.stream()` included, no longer leave it open. An abort before the response is not marked as an error. Fixes #25816 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- .../tracing/anthropic/v1/instrument.mjs | 2 +- .../tracing/anthropic/v1/scenario-threads.mjs | 238 ++++++++++++++++++ .../suites/tracing/anthropic/v1/test.ts | 121 ++++++++- .../src/ai/anthropic-ai/streaming.ts | 9 + .../src/integrations/anthropic.ts | 61 ++++- .../src/orchestrion/config/anthropic-ai.ts | 8 + .../ai/lib/tracing/anthropic-ai-usage.test.ts | 57 ++++- 7 files changed, 491 insertions(+), 5 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/instrument.mjs index b5472310228b..f09ea5121842 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/instrument.mjs @@ -5,7 +5,7 @@ Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', tracesSampleRate: 1.0, - dataCollection: { genAI: { inputs: false, outputs: false } }, + dataCollection: { genAI: { inputs: false, outputs: process.env.RECORD_OUTPUTS === 'true' } }, transport: loggingTransport, // Registers Sentry as the global tracer provider, which is what 1.x traces itself through. enableOpenTelemetrySetup: process.env.OTEL_SETUP === 'true', diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs new file mode 100644 index 000000000000..c2286913e5ff --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs @@ -0,0 +1,238 @@ +import Anthropic from '@anthropic-ai/sdk'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +const MODEL = 'claude-3-haiku-20240307'; + +// The first turn calls the weather tool and the second answers. Ids are `msg__`, so each span can be told apart. +function reply(mode, turn) { + const id = `msg_${mode}_${turn}`; + return turn === 'tools' + ? { + id, + content: [{ type: 'tool_use', id: `toolu_${mode}`, name: 'weather', input: { city: 'Vienna' } }], + stop_reason: 'tool_use', + usage: { input_tokens: 10, output_tokens: 20 }, + } + : { + id, + content: [{ type: 'text', text: 'Sunny.' }], + stop_reason: 'end_turn', + usage: { input_tokens: 30, output_tokens: 5 }, + }; +} + +function streamEvents({ id, content, stop_reason, usage }) { + const events = [ + { + type: 'message_start', + message: { + id, + type: 'message', + role: 'assistant', + model: MODEL, + content: [], + usage: { input_tokens: usage.input_tokens }, + }, + }, + ]; + content.forEach((block, index) => { + if (block.type === 'tool_use') { + events.push( + { type: 'content_block_start', index, content_block: { ...block, input: {} } }, + { + type: 'content_block_delta', + index, + delta: { type: 'input_json_delta', partial_json: JSON.stringify(block.input) }, + }, + ); + } else { + events.push( + { type: 'content_block_start', index, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index, delta: { type: 'text_delta', text: block.text } }, + ); + } + events.push({ type: 'content_block_stop', index }); + }); + events.push( + { + type: 'message_delta', + delta: { stop_reason, stop_sequence: null }, + usage: { output_tokens: usage.output_tokens }, + }, + { type: 'message_stop' }, + ); + return events; +} + +let recoveredReplies = 0; + +function startMockAnthropicServer() { + const app = express(); + app.use(express.json()); + + app.post('/anthropic/v1/messages', (req, res) => { + const mode = req.headers['x-mode']; + if (mode === 'thread_stream_error') { + res.status(400).json({ type: 'error', error: { type: 'invalid_request_error', message: 'Bad thread' } }); + return; + } + const answersTool = req.body.messages.some( + message => Array.isArray(message.content) && message.content.some(block => block.type === 'tool_result'), + ); + // The server lost the thread, so the SDK replays the turn that continues it. + if (mode === 'thread_stream_recovered' && req.body.thread?.type === 'continue') { + res.status(404).json({ + type: 'error', + error: { type: 'not_found_error', message: 'Thread not found', details: { error_code: 'thread_not_found' } }, + }); + return; + } + if (mode === 'thread_stream_failed_signal_reuse' && !answersTool) { + res.status(400).json({ type: 'error', error: { type: 'invalid_request_error', message: 'Bad thread' } }); + return; + } + const message = + mode === 'thread_stream_recovered' + ? { ...reply(mode, 'final'), id: `msg_${mode}_${(recoveredReplies += 1)}` } + : reply(mode, answersTool ? 'final' : 'tools'); + + if (!req.body.stream) { + res.json({ type: 'message', role: 'assistant', model: MODEL, stop_sequence: null, ...message }); + return; + } + + res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); + // The body closes after the first tool input delta, without `message_stop`. + const events = mode === 'thread_stream_truncated' ? streamEvents(message).slice(0, 3) : streamEvents(message); + events.forEach((event, index) => { + setTimeout(() => { + res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`); + if (index === events.length - 1) { + res.end(); + } + }, index * 5); + }); + }); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +const tools = [ + { + name: 'weather', + description: 'Get the weather by city', + input_schema: { type: 'object', properties: { city: { type: 'string' } } }, + run: () => 'sunny', + }, +]; +const params = { model: MODEL, max_tokens: 100, messages: [{ role: 'user', content: 'Weather in Vienna?' }] }; + +async function streamFollowUp(client, signal) { + const answer = { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'sunny' }] }; + const followUp = await client.beta.messages.create( + { ...params, messages: [...params.messages, answer], stream: true }, + { signal }, + ); + for await (const _event of followUp) { + // consume + } +} + +const MODES = { + async runner_stream_eager(client) { + for await (const stream of client.beta.messages.toolRunner({ + ...params, + tools, + stream: true, + runToolsEagerly: true, + })) { + await stream.finalMessage(); + } + }, + async runner_stream(client) { + for await (const stream of client.beta.messages.toolRunner({ ...params, tools, stream: true })) { + await stream.finalMessage(); + } + }, + // How Bedrock and Vertex clients, which have no threads, run every tool runner. + async runner_stream_unthreaded(client) { + for await (const stream of client.beta.messages.toolRunner({ ...params, tools, stream: true, thread: false })) { + await stream.finalMessage(); + } + }, + async runner(client) { + for await (const _message of client.beta.messages.toolRunner({ ...params, tools })) { + // consume + } + }, + async thread_send(client) { + await client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).send(params.messages); + }, + async thread_stream(client) { + await client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages).finalMessage(); + }, + // A later request sent with a finished thread stream's signal is not that stream's request. + async thread_stream_signal_reuse(client) { + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); + await stream.finalMessage(); + await streamFollowUp(client, stream.controller.signal); + }, + async thread_stream_failed_signal_reuse(client) { + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); + await stream.finalMessage().catch(() => {}); + await streamFollowUp(client, stream.controller.signal); + }, + async thread_stream_abort(client) { + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); + stream.once('streamEvent', () => stream.abort()); + await stream.finalMessage().catch(() => {}); + }, + async thread_stream_abort_early(client) { + const stream = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }).stream(params.messages); + stream.abort(); + await stream.finalMessage().catch(() => {}); + }, + async thread_stream_truncated(client) { + await client.beta.messages + .thread({ model: MODEL, max_tokens: 100 }) + .stream(params.messages) + .finalMessage() + .catch(() => {}); + }, + async thread_stream_recovered(client) { + const thread = client.beta.messages.thread({ model: MODEL, max_tokens: 100 }); + await thread.stream(params.messages).finalMessage(); + await thread.stream([{ role: 'user', content: 'And tomorrow?' }]).finalMessage(); + }, + async thread_stream_error(client) { + await client.beta.messages + .thread({ model: MODEL, max_tokens: 100 }) + .stream(params.messages) + .finalMessage() + .catch(() => {}); + }, +}; + +async function run() { + const server = await startMockAnthropicServer(); + const baseURL = `http://localhost:${server.address().port}/anthropic`; + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + for (const [mode, call] of Object.entries(MODES)) { + await Sentry.startSpan({ name: mode }, () => + call(new Anthropic({ apiKey: 'mock-api-key', baseURL, maxRetries: 0, defaultHeaders: { 'x-mode': mode } })), + ); + } + }); + + await Sentry.flush(2000); + + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts index 48cf3bd9bde0..afda0052828f 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts @@ -3,11 +3,15 @@ import { GEN_AI_CONVERSATION_ID, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_STREAMING, + GEN_AI_RESPONSE_TEXT, + GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_TOOL_NAME, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, SENTRY_OP, SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; -import { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; +import { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; import { afterAll, describe, expect } from 'vitest'; import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../../../packages/server-utils/src/ai/core/gen-ai-attributes'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; @@ -116,6 +120,121 @@ describe('Anthropic integration (1.x)', () => { } }); + // Since 1.2, tool runners and `thread().stream()` send each turn through a thread, which parses the response itself. + createEsmAndCjsTests(__dirname, 'scenario-threads.mjs', 'instrument.mjs', (createRunner, test) => { + const MODES = [ + { mode: 'runner_stream_eager', streaming: true, turns: ['tools', 'final'] }, + { mode: 'runner_stream', streaming: true, turns: ['tools', 'final'] }, + { mode: 'runner_stream_unthreaded', streaming: true, turns: ['tools', 'final'] }, + { mode: 'runner', streaming: false, turns: ['tools', 'final'] }, + { mode: 'thread_send', streaming: false, turns: ['tools'] }, + { mode: 'thread_stream', streaming: true, turns: ['tools'] }, + { mode: 'thread_stream_signal_reuse', streaming: true, turns: ['tools', 'final'] }, + ]; + const FINAL_TURN_MODES = MODES.filter(({ turns }) => turns.includes('final')); + // Only the span's status is known for these. The stream is aborted on its first event or before the response, + // its body closes before `message_stop`, or the request fails. + const STATUS_ONLY_MODES = [ + { mode: 'thread_stream_abort', status: 'ok' }, + { mode: 'thread_stream_abort_early', status: 'ok' }, + { mode: 'thread_stream_truncated', status: 'ok' }, + { mode: 'thread_stream_error', status: 'error' }, + ]; + + describe.each([{}, { OTEL_SETUP: 'true' }])('with %j', env => { + // Every scenario run is a Node process, so the cases below share one run. + let run: Promise | undefined; + function getSpans(): Promise { + run ??= (async () => { + const runner = createRunner().withEnv({ ...env, RECORD_OUTPUTS: 'true' }); + const spansPromise = runner.collectStreamedSpansUntilSegment('main'); + await runner.start().completed(); + return spansPromise; + })(); + return run; + } + + async function chatSpansUnder(mode: string): Promise { + const spans = await getSpans(); + const modeSpan = spans.find(span => span.name === mode)!; + return spans.filter( + span => span.parent_span_id === modeSpan.span_id && span.attributes[SENTRY_OP]?.value === GEN_AI_CHAT, + ); + } + + test("emits one chat span per turn and none of the SDK's own spans", async () => { + const spans = await getSpans(); + + expect(spans.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_CHAT)).toHaveLength( + // Plus the failed request and the follow-up of `thread_stream_failed_signal_reuse`, and the three requests + // of `thread_stream_recovered`. + MODES.flatMap(({ turns }) => turns).length + STATUS_ONLY_MODES.length + 2 + 3, + ); + expect(spans.filter(span => span.name.startsWith('anthropic.'))).toEqual([]); + }); + + test.each(MODES)('nests one chat span per $mode turn under the caller', async ({ mode, turns }) => { + const chatSpans = await chatSpansUnder(mode); + + expect(chatSpans.map(span => span.attributes[GEN_AI_RESPONSE_ID]?.value).sort()).toEqual( + turns.map(turn => `msg_${mode}_${turn}`).sort(), + ); + }); + + test.each(MODES)('records the tool call of the first $mode turn', async ({ mode, streaming }) => { + const chatSpan = spanForCall(await chatSpansUnder(mode), `msg_${mode}_tools`); + + expect(chatSpan.status).toBe('ok'); + expect(chatSpan.attributes[GEN_AI_RESPONSE_STREAMING]?.value ?? false).toBe(streaming); + expect(chatSpan.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(10); + expect(chatSpan.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(20); + expect(JSON.parse(chatSpan.attributes[GEN_AI_RESPONSE_TOOL_CALLS]!.value as string)).toEqual([ + { type: 'tool_use', id: `toolu_${mode}`, name: 'weather', input: { city: 'Vienna' } }, + ]); + }); + + test.each(FINAL_TURN_MODES)('records the text of the final $mode turn', async ({ mode, streaming }) => { + const chatSpan = spanForCall(await chatSpansUnder(mode), `msg_${mode}_final`); + + expect(chatSpan.status).toBe('ok'); + expect(chatSpan.attributes[GEN_AI_RESPONSE_STREAMING]?.value ?? false).toBe(streaming); + expect(chatSpan.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(30); + expect(chatSpan.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(5); + expect(chatSpan.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('Sunny.'); + expect(chatSpan.attributes[GEN_AI_RESPONSE_TOOL_CALLS]).toBeUndefined(); + }); + + test.each(STATUS_ONLY_MODES)('ends the $mode chat span with status $status', async ({ mode, status }) => { + const chatSpans = await chatSpansUnder(mode); + + expect(chatSpans).toHaveLength(1); + expect(chatSpans[0]!.status).toBe(status); + }); + + // Deliberate. The rejected attempt was a real request that failed, like an http.client span that a retry + // recovers from. Hiding it would mean copying the SDK's private recovery rules: they replay only some error codes, + // only on a `continue`, and may change in any release, so a copy would silently hide real errors. + test('keeps an error span for the attempt of a turn the thread recovered from', async () => { + const chatSpans = await chatSpansUnder('thread_stream_recovered'); + + expect(chatSpans.map(span => [span.attributes[GEN_AI_RESPONSE_ID]?.value, span.status])).toEqual([ + ['msg_thread_stream_recovered_1', 'ok'], + [undefined, 'error'], + ['msg_thread_stream_recovered_2', 'ok'], + ]); + }); + + test("ends the span of a request sent with a failed stream's signal", async () => { + const chatSpans = await chatSpansUnder('thread_stream_failed_signal_reuse'); + const followUp = spanForCall(chatSpans, 'msg_thread_stream_failed_signal_reuse_final'); + + expect(chatSpans.map(span => span.status).sort()).toEqual(['error', 'ok']); + expect(followUp.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(5); + expect(followUp.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('Sunny.'); + }); + }); + }); + createEsmAndCjsTests(__dirname, 'scenario-session-tool-runner.mjs', 'instrument.mjs', (createRunner, test) => { for (const env of [{}, { OTEL_SETUP: 'true' }]) { test(`emits an execute_tool span for each tool a session runner runs with ${JSON.stringify(env)}`, async () => { diff --git a/packages/server-utils/src/ai/anthropic-ai/streaming.ts b/packages/server-utils/src/ai/anthropic-ai/streaming.ts index 1adc3413722d..9d0b1a3def11 100644 --- a/packages/server-utils/src/ai/anthropic-ai/streaming.ts +++ b/packages/server-utils/src/ai/anthropic-ai/streaming.ts @@ -287,6 +287,15 @@ export function instrumentMessageStream endStreamSpan(span, state, recordOutputs); }); + // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still + // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection. + stream.on('end', () => { + if (span.isRecording() && (stream as { aborted?: boolean }).aborted) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + } + endStreamSpan(span, state, recordOutputs); + }); + stream.on('error', (error: unknown) => { // Attaching this listener stops the stream error from being raised as an unhandled rejection, so // we capture it here to avoid swallowing it (e.g. for callers that don't await/iterate the stream). diff --git a/packages/server-utils/src/integrations/anthropic.ts b/packages/server-utils/src/integrations/anthropic.ts index c39ebcdfdeb2..ff9cc0c7440f 100644 --- a/packages/server-utils/src/integrations/anthropic.ts +++ b/packages/server-utils/src/integrations/anthropic.ts @@ -73,6 +73,7 @@ function instrumentAnthropic(options: AnthropicAiOptions): void { ); }, deferSpanEnd: ({ span, data, end }) => + wrapThreadStreamRequest(span, data, end, options) || wrapApiPromiseResponse( data.result, response => { @@ -82,7 +83,8 @@ function instrumentAnthropic(options: AnthropicAiOptions): void { } }, end, - ) || wrapStreamResult(span, data, stream, options), + ) || + wrapStreamResult(span, data, stream, options), }, ); } @@ -97,6 +99,15 @@ function instrumentAnthropic(options: AnthropicAiOptions): void { .end.subscribe(message => { instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options); }); + // On `start`, because `_start()` sends the first request before it returns. + diagnosticsChannel + .tracingChannel(CHANNELS.ANTHROPIC_THREAD_STREAM) + .start.subscribe(message => { + const stream = (message as OrchestrionChannelContext).self as ThreadStream | undefined; + if (isMessageStream(stream) && stream.controller?.signal) { + threadStreams.set(stream.controller.signal, stream); + } + }); } /** @@ -200,13 +211,59 @@ function isMessageStream(value: unknown): value is MessageStreamEmitter { return !!value && typeof (value as MessageStreamEmitter).on === 'function'; } +type ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } }; + +/** + * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a + * stream parses the response itself, so the `create()` result is never parsed and never ends its span. + */ +const threadStreams = new WeakMap(); + +/** + * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may + * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream. + */ +function wrapThreadStreamRequest( + span: Span, + data: OrchestrionChannelContext, + end: (error?: unknown) => void, + options: AnthropicAiOptions, +): boolean { + const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal; + const stream = signal && threadStreams.get(signal); + const request = data.result as { _responseProps?: () => Promise } | undefined; + // A finished stream sends no more requests, so a later call with its signal is the caller's own. + if (!stream || stream.ended || typeof request?._responseProps !== 'function') { + return false; + } + + const { recordOutputs } = resolveAIRecordingOptions(options); + // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on. + void request._responseProps().then( + () => { + // Only a rejected attempt is retried, so nothing else may claim this stream. + threadStreams.delete(signal); + instrumentMessageStream(stream, span, recordOutputs); + }, + error => { + // A caller abort is not a failed request. The stream still emits 'end', which ends the span as cancelled. + if (signal.aborted) { + instrumentMessageStream(stream, span, recordOutputs); + } else { + end(error); + } + }, + ); + return true; +} + /** * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`, * `false` for non-streaming results (which end via `beforeSpanEnd`). * * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends * the span when iteration finishes. - * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'` listeners that end the span. + * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span. */ function wrapStreamResult( span: Span, diff --git a/packages/server-utils/src/orchestrion/config/anthropic-ai.ts b/packages/server-utils/src/orchestrion/config/anthropic-ai.ts index f0a953e03ef1..422b3e367f78 100644 --- a/packages/server-utils/src/orchestrion/config/anthropic-ai.ts +++ b/packages/server-utils/src/orchestrion/config/anthropic-ai.ts @@ -38,6 +38,13 @@ export const anthropicAiConfig = [ module: { name: '@anthropic-ai/sdk', versionRange: '>=0.97.0 <2', filePath }, functionQuery: { className: 'SessionToolRunner' }, })), + // Thread and tool-runner streams parse the response of their `create()` call themselves, so the chat channel + // never sees that stream. + ...['lib/BetaMessageStream.js', 'lib/BetaMessageStream.mjs'].map(filePath => ({ + channelName: 'thread-stream', + module: { name: '@anthropic-ai/sdk', versionRange: '>=1.2.0 <2', filePath }, + functionQuery: { className: 'BetaMessageStream', methodName: '_start', kind: 'Sync' as const }, + })), ] satisfies InstrumentationConfig[]; export const anthropicAiModuleNames = getModuleNames(anthropicAiConfig); @@ -47,4 +54,5 @@ export const anthropicAiChannels = { ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream', ANTHROPIC_TOOL_RUNNER: 'orchestrion:@anthropic-ai/sdk:tool-runner', ANTHROPIC_SESSION_TOOL_RUNNER: 'orchestrion:@anthropic-ai/sdk:session-tool-runner', + ANTHROPIC_THREAD_STREAM: 'orchestrion:@anthropic-ai/sdk:thread-stream', } as const; diff --git a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts index c506fbcb9387..78569bc446ec 100644 --- a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts @@ -9,8 +9,9 @@ import { GEN_AI_USAGE_TOTAL_TOKENS, } from '@sentry/conventions/attributes'; import { EventEmitter } from 'node:events'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import type { Span } from '@sentry/core'; +import { SPAN_STATUS_ERROR } from '@sentry/core'; import { addResponseAttributes } from '../../../../src/ai/anthropic-ai'; import { instrumentAsyncIterableStream, instrumentMessageStream } from '../../../../src/ai/anthropic-ai/streaming'; import type { AnthropicAiStreamingEvent } from '../../../../src/ai/anthropic-ai/types'; @@ -271,3 +272,57 @@ describe.each(['async iterable', 'message stream'] as const)( }); }, ); + +describe('instrumentMessageStream', () => { + const messageStart = { + type: 'message_start', + message: { + id: 'msg_aborted', + type: 'message', + model: 'claude-sonnet-4-6', + role: 'assistant', + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 42, output_tokens: 1 }, + }, + }; + + it('ends an aborted stream once, as cancelled, with the usage streamed so far', () => { + const { span, attributes } = createMockSpan(); + const setStatus = vi.fn(); + const endSpy = vi.spyOn(span, 'end'); + Object.assign(span, { setStatus }); + const stream = instrumentMessageStream(Object.assign(new EventEmitter(), { aborted: true }), span, false); + + stream.emit('streamEvent', messageStart); + stream.emit('abort', new Error('Request was aborted.')); + stream.emit('end'); + stream.emit('end'); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + expect(endSpy).toHaveBeenCalledTimes(1); + expect(attributes).toEqual({ + [GEN_AI_RESPONSE_STREAMING]: true, + [GEN_AI_RESPONSE_ID]: 'msg_aborted', + [GEN_AI_RESPONSE_MODEL]: 'claude-sonnet-4-6', + [GEN_AI_USAGE_INPUT_TOKENS]: 42, + [GEN_AI_USAGE_TOTAL_TOKENS]: 42, + }); + }); + + it('leaves the status alone when the body closes early without an abort', () => { + const { span } = createMockSpan(); + const setStatus = vi.fn(); + const endSpy = vi.spyOn(span, 'end'); + Object.assign(span, { setStatus }); + const stream = instrumentMessageStream(Object.assign(new EventEmitter(), { aborted: false }), span, false); + + stream.emit('streamEvent', messageStart); + stream.emit('end'); + + expect(setStatus).not.toHaveBeenCalled(); + expect(endSpy).toHaveBeenCalledTimes(1); + }); +}); From e02e7457b9b6b75fe0ef2ce2d06f312454c0af07 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Tue, 10 Nov 2026 18:04:19 +0000 Subject: [PATCH 009/136] feat(bundler-plugins): Enable external source maps and delete them after upload in the esbuild plugin (#25648) Part of the stack for getsentry/sentry-javascript#25609. esbuild writes its output before `onEnd` runs and has no hook to drop an output, so the plugin sets `sourcemap: 'external'` when the setting is unset and deletes the maps after a successful upload: every map in the metafile when the plugin turned them on, and exactly the maps the upload read from disk when the user enabled them, which `uploadSourcemaps` now reports. When the upload fails all maps stay, with an error log. With `write: false` the setting is left alone, because nothing reaches the disk. The metafile lists outputs relative to `absWorkingDir`, while the upload globbed them from the process working directory, so builds with an `absWorkingDir` elsewhere uploaded nothing. The paths are now resolved against `absWorkingDir` first, and passed with forward slashes because glob reads backslashes as escapes. Integration fixtures cover `ignore` and `assets` on the staged path for esbuild. --- .../fixtures/esbuild/basic-cjs.test.ts | 1 + .../fixtures/esbuild/basic.test.ts | 1 + .../fixtures/esbuild/release-disabled.test.ts | 1 + .../esbuild/sourcemaps-assets-auto.config.js | 14 + .../esbuild/sourcemaps-assets-auto.test.ts | 33 +++ .../esbuild/sourcemaps-ignore-auto.config.js | 14 + .../esbuild/sourcemaps-ignore-auto.test.ts | 33 +++ .../src/core/build-plugin-manager.ts | 48 +++- .../src/core/debug-id-upload.ts | 7 +- packages/bundler-plugins/src/core/index.ts | 2 +- packages/bundler-plugins/src/esbuild/index.ts | 69 ++++- .../test/core/build-plugin-manager.test.ts | 45 ++- .../test/core/upload-staging.test.ts | 16 +- .../delete-sourcemaps-after-upload.test.ts | 263 ++++++++++++++++++ 14 files changed, 518 insertions(+), 29 deletions(-) create mode 100644 dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js create mode 100644 dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts create mode 100644 dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js create mode 100644 dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts create mode 100644 packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts index e91fb5ed133b..f07edbcb8c58 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic-cjs.test.ts @@ -35,6 +35,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { "sentry-cli-mock.json": "["release","create","CURRENT_SHA","--project","fake-project"], ["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts index e91fb5ed133b..f07edbcb8c58 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/basic.test.ts @@ -35,6 +35,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { "sentry-cli-mock.json": "["release","create","CURRENT_SHA","--project","fake-project"], ["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts index 64fdb039b963..7aac92da1976 100644 --- a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/release-disabled.test.ts @@ -34,6 +34,7 @@ test(import.meta.url, ({ runBundler, readOutputFiles, runFileInNode }) => { ", "sentry-cli-mock.json": "["release","set-commits","CURRENT_SHA","--auto"], ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], ", } `); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js new file mode 100644 index 000000000000..588483bf6eea --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.config.js @@ -0,0 +1,14 @@ +import * as esbuild from "esbuild"; +import { sentryEsbuildPlugin } from "@sentry/bundler-plugins/esbuild"; +import { sentryConfig } from "../configs/sourcemaps-assets-auto.config.js"; + +await esbuild.build({ + entryPoints: ["./src/entry1.js", "./src/entry2.js"], + bundle: true, + outdir: "./out/sourcemaps-assets-auto", + minify: false, + format: "esm", + splitting: true, + chunkNames: "[name]", + plugins: [sentryEsbuildPlugin(sentryConfig)], +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts new file mode 100644 index 000000000000..4751e8acc361 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-assets-auto.test.ts @@ -0,0 +1,33 @@ +import { expect } from "vitest"; +import { test } from "./utils"; + +test(import.meta.url, ({ runBundler, readOutputFiles }) => { + runBundler({ SENTRY_TEST_RECORD_UPLOADED_SOURCES: "1" }); + const files = readOutputFiles(); + + expect(Object.keys(files).sort()).toMatchInlineSnapshot(` + [ + "chunk.js", + "entry1.js", + "entry2.js", + "sentry-cli-mock.json", + "sentry-uploaded-sources.json", + ] + `); + expect(JSON.parse(files["sentry-uploaded-sources.json"]!)).toMatchInlineSnapshot(` + [ + [ + "sentry-debug-id-stub:_sentry-debug-id-injection-stub?sentry-module-id=00000000-0000-0000-0000-000000000000", + "../../src/entry1.js", + "../../src/entry1.js", + ], + ] + `); + expect(files["sentry-cli-mock.json"]).toMatchInlineSnapshot(` + "["release","create","CURRENT_SHA","--project","fake-project"], + ["release","set-commits","CURRENT_SHA","--auto"], + ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], + " + `); +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js new file mode 100644 index 000000000000..8737a7c03287 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.config.js @@ -0,0 +1,14 @@ +import * as esbuild from "esbuild"; +import { sentryEsbuildPlugin } from "@sentry/bundler-plugins/esbuild"; +import { sentryConfig } from "../configs/sourcemaps-ignore-auto.config.js"; + +await esbuild.build({ + entryPoints: ["./src/entry1.js", "./src/entry2.js"], + bundle: true, + outdir: "./out/sourcemaps-ignore-auto", + minify: false, + format: "esm", + splitting: true, + chunkNames: "[name]", + plugins: [sentryEsbuildPlugin(sentryConfig)], +}); diff --git a/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts new file mode 100644 index 000000000000..4751e8acc361 --- /dev/null +++ b/dev-packages/bundler-plugin-integration-tests/fixtures/esbuild/sourcemaps-ignore-auto.test.ts @@ -0,0 +1,33 @@ +import { expect } from "vitest"; +import { test } from "./utils"; + +test(import.meta.url, ({ runBundler, readOutputFiles }) => { + runBundler({ SENTRY_TEST_RECORD_UPLOADED_SOURCES: "1" }); + const files = readOutputFiles(); + + expect(Object.keys(files).sort()).toMatchInlineSnapshot(` + [ + "chunk.js", + "entry1.js", + "entry2.js", + "sentry-cli-mock.json", + "sentry-uploaded-sources.json", + ] + `); + expect(JSON.parse(files["sentry-uploaded-sources.json"]!)).toMatchInlineSnapshot(` + [ + [ + "sentry-debug-id-stub:_sentry-debug-id-injection-stub?sentry-module-id=00000000-0000-0000-0000-000000000000", + "../../src/entry1.js", + "../../src/entry1.js", + ], + ] + `); + expect(files["sentry-cli-mock.json"]).toMatchInlineSnapshot(` + "["release","create","CURRENT_SHA","--project","fake-project"], + ["release","set-commits","CURRENT_SHA","--auto"], + ["release","finalize","CURRENT_SHA"], + ["sourcemap","upload","-p","fake-project","--release","CURRENT_SHA","sentry-bundler-plugin-upload-path"], + " + `); +}); diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index e51934210948..b70b32664d01 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -41,6 +41,8 @@ export function _resetDeployedReleasesForTesting(): void { * before the bundler writes them to disk. The upload reads from this folder, so the bundler can * drop the source map assets from its own output. */ +export type UploadResult = { uploaded: boolean; uploadedSourceMapPaths: string[] }; + export type UploadStaging = { readonly dir: string; /** Number of artifacts written so far. */ @@ -127,11 +129,14 @@ export type SentryBuildPluginManager = { /** * Uploads sourcemaps using the "Debug ID" method. This function takes a list of build artifact paths that will be uploaded + * + * `uploadedSourceMapPaths` lists the source maps read from disk that were uploaded. It is empty + * when nothing was uploaded, in direct mode (`prepareArtifacts: false`) and for staged artifacts. */ uploadSourcemaps( buildArtifactPaths: string[], opts?: { prepareArtifacts?: boolean; staging?: UploadStaging }, - ): Promise<{ uploaded: boolean }>; + ): Promise; /** * Creates a staging folder that `uploadSourcemaps` uploads together with the build artifacts @@ -157,6 +162,11 @@ export type SentryBuildPluginManager = { * and none of `sourcemaps.ignore`. */ shouldUpload: UploadFilter; + /** + * Deletes source maps from the build output after their upload. A map that cannot be deleted + * goes to `errorHandler`, or fails the build when none is set. + */ + deleteFromOutput(sourceMapPaths: string[]): Promise; }; /** @@ -232,7 +242,7 @@ export function createSentryBuildPluginManager( createRelease: async () => { /* noop */ }, - uploadSourcemaps: async () => ({ uploaded: false }), + uploadSourcemaps: async () => ({ uploaded: false, uploadedSourceMapPaths: [] }), createUploadStaging: async () => ({ dir: '', count: 0, @@ -250,6 +260,9 @@ export function createSentryBuildPluginManager( decide: () => ({ enableHidden: false, deleteAfterUpload: false }), logDecision: () => undefined, shouldUpload: () => false, + deleteFromOutput: async () => { + /* noop */ + }, }, deleteArtifacts: async () => { /* noop */ @@ -655,16 +668,17 @@ export function createSentryBuildPluginManager( async uploadSourcemaps( buildArtifactPaths: string[], opts?: { prepareArtifacts?: boolean; staging?: UploadStaging }, - ): Promise<{ uploaded: boolean }> { + ): Promise { const staging = opts?.staging; if (!canUploadSourceMaps(options, logger, isDevMode)) { await staging?.discard(); - return { uploaded: false }; + return { uploaded: false, uploadedSourceMapPaths: [] }; } const assets = options.sourcemaps?.assets; let uploaded = false; + const preparedSourceMapPaths: string[] = []; await startSpan( // This is `forceTransaction`ed because this span is used in dashboards in the form of indexed transactions. @@ -766,7 +780,7 @@ export function createSentryBuildPluginManager( // Preparing the bundles can be a lot of work and doing it all at once has the potential of nuking the heap so // instead we do it with a maximum of 16 concurrent workers const preparationTasks = debugIdChunkFilePaths.map((chunkFilePath, chunkIndex) => async () => { - await prepareBundleForDebugIdUpload( + const prepared = await prepareBundleForDebugIdUpload( chunkFilePath, tmpUploadFolder, stagedCount + chunkIndex, @@ -774,6 +788,9 @@ export function createSentryBuildPluginManager( options.sourcemaps?.rewriteSources ?? defaultRewriteSourcesHook, options.sourcemaps?.resolveSourceMap, ); + if (prepared?.sourceMapPath !== undefined) { + preparedSourceMapPaths.push(prepared.sourceMapPath); + } }); const workers: Promise[] = []; const worker = async (): Promise => { @@ -862,7 +879,7 @@ export function createSentryBuildPluginManager( }, ); - return { uploaded }; + return { uploaded, uploadedSourceMapPaths: uploaded ? preparedSourceMapPaths.sort() : [] }; }, async createUploadStaging(): Promise { @@ -962,6 +979,25 @@ export function createSentryBuildPluginManager( }, logDecision, shouldUpload, + async deleteFromOutput(sourceMapPaths) { + try { + await Promise.all( + sourceMapPaths.map(async sourceMapPath => { + try { + await fs.promises.rm(sourceMapPath, { force: true }); + } catch (e) { + logger.error(`Could not delete source map ${sourceMapPath} from the build output.`); + throw e; + } + }), + ); + } catch (e) { + sentryScope.captureException('Error deleting source maps after upload'); + await safeFlushTelemetry(sentryClient); + // Throwing by default: a map left in the output could leak to production. + handleRecoverableError(e, true); + } + }, }, /** diff --git a/packages/bundler-plugins/src/core/debug-id-upload.ts b/packages/bundler-plugins/src/core/debug-id-upload.ts index cf402b5f476f..f7b5fc9e9ee1 100644 --- a/packages/bundler-plugins/src/core/debug-id-upload.ts +++ b/packages/bundler-plugins/src/core/debug-id-upload.ts @@ -20,6 +20,10 @@ export function createDebugIdUploadFunction({ sentryBuildPluginManager }: DebugI }; } +/** The source map of a prepared bundle. `sourceMapPath` is `undefined` for an inline map. */ +export type PreparedBundle = { sourceMapPath: string | undefined }; + +/** Resolves to `undefined` when the bundle was skipped. */ export async function prepareBundleForDebugIdUpload( bundleFilePath: string, uploadFolder: string, @@ -27,7 +31,7 @@ export async function prepareBundleForDebugIdUpload( logger: Logger, rewriteSourcesHook: RewriteSourcesHook, resolveSourceMapHook: ResolveSourceMapHook | undefined, -): Promise { +): Promise { let bundleContent: string; try { bundleContent = await fs.promises.readFile(bundleFilePath, 'utf8'); @@ -81,6 +85,7 @@ export async function prepareBundleForDebugIdUpload( } await writePreparedArtifact(uploadFolder, `${result.artifact.debugId}-${chunkIndex}`, result.artifact); + return { sourceMapPath }; } export type PreparedUploadArtifact = { diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts index f19fe4c5642a..b721b2ec47e7 100644 --- a/packages/bundler-plugins/src/core/index.ts +++ b/packages/bundler-plugins/src/core/index.ts @@ -110,7 +110,7 @@ export { generateModuleMetadataInjectorCode, } from './utils'; export { createSentryBuildPluginManager } from './build-plugin-manager'; -export type { SentryBuildPluginManager, UploadStaging } from './build-plugin-manager'; +export type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager'; export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload'; export { decideSourceMapHandling } from './sourcemap-settings'; export type { SourceMapDecision, SourceMapKind } from './sourcemap-settings'; diff --git a/packages/bundler-plugins/src/esbuild/index.ts b/packages/bundler-plugins/src/esbuild/index.ts index 136b4a20665a..51e5f126db8f 100644 --- a/packages/bundler-plugins/src/esbuild/index.ts +++ b/packages/bundler-plugins/src/esbuild/index.ts @@ -1,4 +1,4 @@ -import type { Options } from '../core'; +import type { Options, SourceMapDecision, SourceMapKind } from '../core'; import { createSentryBuildPluginManager, generateReleaseInjectorCode, @@ -48,6 +48,8 @@ interface EsbuildOnEndArgs { }; } +type EsbuildSourceMapSetting = boolean | 'inline' | 'external' | 'linked' | 'both' | undefined; + interface EsbuildInitialOptions { bundle?: boolean; inject?: string[]; @@ -56,6 +58,24 @@ interface EsbuildInitialOptions { write?: boolean; absWorkingDir?: string; logOverride?: Record; + sourcemap?: EsbuildSourceMapSetting; +} + +/** Maps esbuild's `sourcemap` setting onto the plugin's source map kinds. */ +function sourceMapKindFromEsbuildSetting(setting: EsbuildSourceMapSetting): SourceMapKind { + switch (setting) { + case undefined: + return 'unset'; + case false: + return 'off'; + case 'external': + return 'hidden'; + case 'inline': + case 'both': + return 'inline'; + default: + return 'visible'; + } } interface EsbuildPluginBuild { @@ -287,6 +307,16 @@ export function sentryEsbuildPlugin(userOptions: Options = {}): any { }); } + // With `write: false` nothing reaches the disk, so nothing can be uploaded or deleted. + const sourceMapKind = sourceMapKindFromEsbuildSetting(initialOptions.sourcemap); + const sourceMapDecision: SourceMapDecision = + initialOptions.write === false + ? { enableHidden: false, deleteAfterUpload: false } + : sentryBuildPluginManager.sourceMaps.decide(sourceMapKind); + if (sourceMapDecision.enableHidden) { + initialOptions.sourcemap = 'external'; + } + // Create release and optionally upload const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts(); const upload = createDebugIdUploadFunction({ sentryBuildPluginManager }); @@ -297,27 +327,44 @@ export function sentryEsbuildPlugin(userOptions: Options = {}): any { await sentryBuildPluginManager.createRelease(); if (sourcemapsEnabled) { - const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : []; + // The metafile lists outputs relative to `absWorkingDir`, not to the process. + const outputDir = initialOptions.absWorkingDir ?? process.cwd(); + const buildArtifacts = result.metafile + ? Object.keys(result.metafile.outputs).map(output => path.resolve(outputDir, output)) + : []; if (options.sourcemaps?.disable !== 'disable-upload') { - await upload(buildArtifacts); + // The upload globs the paths, and glob reads backslashes as escapes. + const { uploaded, uploadedSourceMapPaths } = await upload( + buildArtifacts.map(artifact => artifact.split(path.sep).join('/')), + ); + + // esbuild writes before `onEnd` runs, so the maps are deleted from disk + // afterwards instead of being dropped from the output like in other bundlers. + // A map the plugin turned on never stays in the output. A map the user + // enabled is only deleted once it was uploaded. + if (sourceMapDecision.deleteAfterUpload) { + const sourceMaps = + sourceMapKind === 'unset' + ? buildArtifacts.filter(artifact => artifact.endsWith('.map')) + : uploadedSourceMapPaths; + + if (uploaded) { + await sentryBuildPluginManager.sourceMaps.deleteFromOutput(sourceMaps); + } else if (sourceMaps.length > 0) { + logger.error('The source maps were not uploaded, so they stay in the build output.'); + } + } } else if (initialOptions.write === false) { logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.'); } else { // The upload routine (which stamps debug IDs into temp copies of the artifacts) is // skipped with `disable-upload`. esbuild has no hook to modify outputs before they are // written, so the emitted artifacts get stamped on disk instead. - const outputDir = initialOptions.absWorkingDir ?? process.cwd(); await Promise.all( buildArtifacts .filter(isJsFile) - .map(bundle => - addDebugIdToEmittedArtifacts( - path.resolve(outputDir, bundle), - logger, - options.sourcemaps?.resolveSourceMap, - ), - ), + .map(bundle => addDebugIdToEmittedArtifacts(bundle, logger, options.sourcemaps?.resolveSourceMap)), ); } } diff --git a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts index d73caeb84443..4ccd00652c0b 100644 --- a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts +++ b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts @@ -459,7 +459,7 @@ describe('createSentryBuildPluginManager', () => { vi.spyOn(fs.promises, 'stat').mockResolvedValue({ size: 10 } as fs.Stats); vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined as never); - mockPrepareBundleForDebugIdUpload.mockResolvedValue(undefined); + mockPrepareBundleForDebugIdUpload.mockResolvedValue({ sourceMapPath: '/app/dist/a.js.map' }); const manager = createSentryBuildPluginManager( { @@ -472,10 +472,11 @@ describe('createSentryBuildPluginManager', () => { { buildTool: 'webpack', loggerPrefix: '[sentry-webpack-plugin]' }, ); - await manager.uploadSourcemaps(['/unused']); + const result = await manager.uploadSourcemaps(['/unused']); // Should call prepare for each JS chunk discovered by glob expect(mockPrepareBundleForDebugIdUpload).toHaveBeenCalled(); + expect(result).toEqual({ uploaded: true, uploadedSourceMapPaths: ['/app/dist/a.js.map'] }); // Should upload from the temp folder, where debug IDs are already injected expect(mockSourcemapUpload).toHaveBeenCalledWith({ directory: '/tmp/sentry-upload-xyz', @@ -528,6 +529,46 @@ describe('createSentryBuildPluginManager', () => { }); }); + describe('sourceMaps.deleteFromOutput', () => { + const managerOptions = { + authToken: 't', + org: 'o', + project: 'p', + release: { name: 'some-release-name' }, + telemetry: false, + silent: true, + }; + const meta = { buildTool: 'esbuild', loggerPrefix: '[sentry-esbuild-plugin]' }; + + it('deletes the source maps', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm').mockResolvedValue(undefined); + const manager = createSentryBuildPluginManager(managerOptions, meta); + + await manager.sourceMaps.deleteFromOutput(['/app/dist/a.js.map', '/app/dist/b.js.map']); + + expect(rmSpy).toHaveBeenCalledWith('/app/dist/a.js.map', { force: true }); + expect(rmSpy).toHaveBeenCalledWith('/app/dist/b.js.map', { force: true }); + }); + + it('throws when a source map cannot be deleted', async () => { + const error = new Error('EBUSY'); + vi.spyOn(fs.promises, 'rm').mockRejectedValue(error); + const manager = createSentryBuildPluginManager(managerOptions, meta); + + await expect(manager.sourceMaps.deleteFromOutput(['/app/dist/a.js.map'])).rejects.toBe(error); + }); + + it('passes a failed delete to the error handler', async () => { + const error = new Error('EBUSY'); + vi.spyOn(fs.promises, 'rm').mockRejectedValue(error); + const errorHandler = vi.fn(); + const manager = createSentryBuildPluginManager({ ...managerOptions, errorHandler }, meta); + + await expect(manager.sourceMaps.deleteFromOutput(['/app/dist/a.js.map'])).resolves.toBeUndefined(); + expect(errorHandler).toHaveBeenCalledWith(error); + }); + }); + describe('injectDebugIds', () => { it('should call the CLI inject command for each build artifact path', async () => { mockSourcemapInject.mockResolvedValue(undefined); diff --git a/packages/bundler-plugins/test/core/upload-staging.test.ts b/packages/bundler-plugins/test/core/upload-staging.test.ts index 29437eff7c0e..de45e71fa16e 100644 --- a/packages/bundler-plugins/test/core/upload-staging.test.ts +++ b/packages/bundler-plugins/test/core/upload-staging.test.ts @@ -241,7 +241,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps([], { staging }); - expect(result).toEqual({ uploaded: true }); + expect(result).toEqual({ uploaded: true, uploadedSourceMapPaths: [] }); expect(mockSourcemapUpload).toHaveBeenCalledWith(expect.objectContaining({ directory: staging.dir })); expect(fs.existsSync(staging.dir)).toBe(false); }); @@ -273,7 +273,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps([path.join(tmpDir, '**/*.js')], { staging }); - expect(result).toEqual({ uploaded: true }); + expect(result).toEqual({ uploaded: true, uploadedSourceMapPaths: [] }); expect(uploadedFiles).toEqual([`${DEBUG_ID}-0.js`, `${DEBUG_ID}-0.js.map`]); expect(uploadedMaps).not.toContain('stale.ts'); }); @@ -332,7 +332,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps([], { staging }); - expect(result).toEqual({ uploaded: false }); + expect(result).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); expect(warnSpy).toHaveBeenCalledWith(expect.stringMatching(/matching sources/)); expect(mockSourcemapUpload).not.toHaveBeenCalled(); expect(fs.existsSync(staging.dir)).toBe(false); @@ -353,7 +353,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps([], { staging }); - expect(result).toEqual({ uploaded: false }); + expect(result).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); expect(mockSourcemapUpload).not.toHaveBeenCalled(); expect(fs.existsSync(staging.dir)).toBe(false); }); @@ -373,7 +373,7 @@ describe('createUploadStaging', () => { try { const result = await manager.uploadSourcemaps([], { staging }); - expect(result).toEqual({ uploaded: false }); + expect(result).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining(`sentry sourcemap upload ${staging.dir}`)); expect(fs.existsSync(staging.dir)).toBe(true); } finally { @@ -393,7 +393,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps(['.next/server'], { staging, prepareArtifacts: false }); - expect(result).toEqual({ uploaded: true }); + expect(result).toEqual({ uploaded: true, uploadedSourceMapPaths: [] }); expect(mockSourcemapUpload).toHaveBeenCalledTimes(2); expect(mockSourcemapUpload).toHaveBeenCalledWith(expect.objectContaining({ directory: '.next/server' })); expect(mockSourcemapUpload).toHaveBeenCalledWith(expect.objectContaining({ directory: staging.dir })); @@ -417,7 +417,7 @@ describe('createUploadStaging', () => { const result = await manager.uploadSourcemaps([], { prepareArtifacts: false }); - expect(result).toEqual({ uploaded: false }); + expect(result).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); expect(mockSourcemapUpload).not.toHaveBeenCalled(); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Didn't find any matching sources")); }); @@ -476,6 +476,6 @@ describe('sourceMaps', () => { const staging = await manager.createUploadStaging(); expect(await staging.stage({ code: '', mapSource: undefined, mapDir: '', chunkPath: 'a.js' })).toBe('skipped'); - expect(await manager.uploadSourcemaps([], { staging })).toEqual({ uploaded: false }); + expect(await manager.uploadSourcemaps([], { staging })).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); }); }); diff --git a/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts new file mode 100644 index 000000000000..75578262a922 --- /dev/null +++ b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts @@ -0,0 +1,263 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as esbuild from 'esbuild'; +import type { BuildOptions } from 'esbuild'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { sentryEsbuildPlugin } from '../../src/esbuild'; +import type { Options } from '../../src/core'; + +const { mockSourcemapUpload } = vi.hoisted(() => ({ mockSourcemapUpload: vi.fn() })); + +vi.mock('sentry', () => ({ + createSentrySDK: () => ({ + release: { create: vi.fn(), finalize: vi.fn(), 'set-commits': vi.fn(), deploy: vi.fn() }, + sourcemap: { upload: mockSourcemapUpload, inject: vi.fn() }, + run: vi.fn(), + }), +})); + +const DEBUG_ID_MARKER = /sentry-dbid-([0-9a-f-]{36})/; + +const credentials: Options = { + authToken: 't', + org: 'o', + project: 'p', + release: { name: 'test-release', create: false, finalize: false }, + telemetry: false, + silent: true, +}; + +type Upload = { directory: string; files: Record }; + +describe('sourcemaps.deleteSourcemapsAfterUpload (esbuild)', () => { + let tmpDir: string; + let entry: string; + let outDir: string; + let uploads: Upload[]; + + beforeEach(() => { + vi.clearAllMocks(); + uploads = []; + mockSourcemapUpload.mockImplementation(async ({ directory }: { directory: string }) => { + const files: Record = {}; + for (const file of fs.readdirSync(directory)) { + files[file] = fs.readFileSync(path.join(directory, file), 'utf8'); + } + uploads.push({ directory, files }); + }); + + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-esbuild-delete-maps-')); + entry = path.join(tmpDir, 'entry.js'); + outDir = path.join(tmpDir, 'dist'); + fs.writeFileSync(entry, 'export const answer = 42;\nconsole.log(answer);\n'); + }); + + afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + function build(pluginOptions: Options = {}, overrides: BuildOptions = {}) { + return esbuild.build({ + entryPoints: [entry], + bundle: true, + outdir: outDir, + absWorkingDir: tmpDir, + plugins: [sentryEsbuildPlugin({ ...credentials, ...pluginOptions })], + ...overrides, + }); + } + + function expectUploadedPair(upload: Upload, bundle: string): void { + const debugId = bundle.match(DEBUG_ID_MARKER)?.[1]; + expect(debugId).toBeDefined(); + expect(Object.keys(upload.files).sort()).toEqual([`${debugId}-0.js`, `${debugId}-0.js.map`]); + expect(JSON.parse(upload.files[`${debugId}-0.js.map`]!)).toMatchObject({ debug_id: debugId }); + expect(fs.existsSync(upload.directory)).toBe(false); + } + + it('enables external source maps, uploads them and deletes them when the setting is unset', async () => { + await build(); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + const bundle = fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8'); + expect(bundle).not.toContain('sourceMappingURL'); + + expect(uploads).toHaveLength(1); + expectUploadedPair(uploads[0]!, bundle); + }); + + it('switches linked source maps to external and deletes them when the option is true', async () => { + await build({ sourcemaps: { deleteSourcemapsAfterUpload: true } }, { sourcemap: true }); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + expect(fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')).not.toContain('sourceMappingURL'); + expect(uploads).toHaveLength(1); + }); + + it('keeps external source maps the user enabled', async () => { + await build({}, { sourcemap: 'external' }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(uploads).toHaveLength(1); + expectUploadedPair(uploads[0]!, fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')); + }); + + it('keeps linked source maps when the option is unset', async () => { + await build({}, { sourcemap: true }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')).toContain('//# sourceMappingURL=entry.js.map'); + }); + + it('enables external source maps but keeps them when the option is false', async () => { + await build({ sourcemaps: { deleteSourcemapsAfterUpload: false } }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')).not.toContain('sourceMappingURL'); + expect(uploads).toHaveLength(1); + }); + + function writeSplitBuild(): BuildOptions { + fs.writeFileSync(path.join(tmpDir, 'shared.js'), 'export const shared = 1;\n'); + fs.writeFileSync(path.join(tmpDir, 'other.js'), "import { shared } from './shared.js';\nconsole.log(shared);\n"); + fs.writeFileSync(path.join(tmpDir, 'style.css'), 'body { color: red; }\n'); + fs.writeFileSync(entry, "import { shared } from './shared.js';\nimport './style.css';\nconsole.log(shared);\n"); + return { entryPoints: [entry, path.join(tmpDir, 'other.js')], splitting: true, format: 'esm' }; + } + + it('deletes every map it turned on, also those of chunks that were not uploaded', async () => { + await build({}, writeSplitBuild()); + + const files = fs.readdirSync(outDir); + expect(files.filter(file => file.endsWith('.map'))).toEqual([]); + expect(files.filter(file => /^chunk-.*\.js$/.test(file))).toHaveLength(1); + expect(files).toContain('entry.css'); + expect(uploads).toHaveLength(1); + expect(Object.keys(uploads[0]!.files).filter(file => file.endsWith('.js'))).toHaveLength(2); + }); + + it('deletes only the maps it uploaded when the user enabled them', async () => { + await build({ sourcemaps: { deleteSourcemapsAfterUpload: true } }, { ...writeSplitBuild(), sourcemap: 'external' }); + + const files = fs.readdirSync(outDir); + expect(files).not.toContain('entry.js.map'); + expect(files).not.toContain('other.js.map'); + expect(files).toContain('entry.css.map'); + expect(files.filter(file => /^chunk-.*\.js\.map$/.test(file))).toHaveLength(1); + expect(uploads).toHaveLength(1); + expect(Object.keys(uploads[0]!.files).filter(file => file.endsWith('.js'))).toHaveLength(2); + }); + + it('does not upload chunks matched by `sourcemaps.ignore` and deletes the maps it turned on for them', async () => { + const vendor = path.join(tmpDir, 'vendor.js'); + fs.writeFileSync(vendor, 'console.log("vendor");\n'); + await build({ sourcemaps: { ignore: ['**/vendor.js'] } }, { entryPoints: [entry, vendor] }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'vendor.js']); + expect(uploads).toHaveLength(1); + const uploadedChunks = Object.entries(uploads[0]!.files).filter(([name]) => name.endsWith('.js')); + expect(uploadedChunks).toHaveLength(1); + expect(uploadedChunks[0]![1]).toContain('answer'); + }); + + it('keeps the maps the user enabled for chunks matched by `sourcemaps.ignore`', async () => { + const vendor = path.join(tmpDir, 'vendor.js'); + fs.writeFileSync(vendor, 'console.log("vendor");\n'); + await build( + { sourcemaps: { ignore: ['**/vendor.js'], deleteSourcemapsAfterUpload: true } }, + { entryPoints: [entry, vendor], sourcemap: 'external' }, + ); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'vendor.js', 'vendor.js.map']); + expect(uploads).toHaveLength(1); + }); + + it('warns when source maps are turned off', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await build({ silent: false }, { sourcemap: false }); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Source map generation is turned off')); + }); + + it('warns when source maps are inlined and keeps them', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await build({ silent: false, sourcemaps: { deleteSourcemapsAfterUpload: true } }, { sourcemap: 'inline' }); + + expect(fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')).toContain('sourceMappingURL=data:'); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Source maps are inlined')); + }); + + it('does not enable source maps when no upload can run', async () => { + await build({ authToken: undefined }); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + expect(uploads).toHaveLength(0); + }); + + it('leaves the source map setting alone and does not log when the build does not write', async () => { + const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined); + const result = await build({ silent: false }, { write: false }); + + expect(result.outputFiles?.map(file => path.basename(file.path))).toEqual(['entry.js']); + expect(uploads).toHaveLength(0); + expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining('Enabling hidden source maps')); + }); + + it('keeps the source maps the user enabled when the build does not write', async () => { + const rmSpy = vi.spyOn(fs.promises, 'rm'); + const result = await build( + { sourcemaps: { deleteSourcemapsAfterUpload: true } }, + { write: false, sourcemap: true }, + ); + + expect(result.outputFiles?.map(file => path.basename(file.path)).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(rmSpy).not.toHaveBeenCalledWith(expect.stringContaining('entry.js.map'), expect.anything()); + }); + + it('keeps the source maps when the upload fails', async () => { + mockSourcemapUpload.mockRejectedValue(new Error('upload failed')); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + await build({ silent: false }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('were not uploaded')); + }); + + it('fails the build when a source map cannot be deleted', async () => { + const error = new Error('EBUSY'); + const rm = fs.promises.rm; + vi.spyOn(fs.promises, 'rm').mockImplementation((file, options) => + String(file).endsWith('entry.js.map') ? Promise.reject(error) : rm(file, options), + ); + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); + + await expect(build({ silent: false }, { logLevel: 'silent' })).rejects.toThrow('EBUSY'); + + expect(uploads).toHaveLength(1); + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Could not delete source map')); + }); + + it('passes a failed delete to the error handler and finishes the build', async () => { + const error = new Error('EBUSY'); + const rm = fs.promises.rm; + vi.spyOn(fs.promises, 'rm').mockImplementation((file, options) => + String(file).endsWith('entry.js.map') ? Promise.reject(error) : rm(file, options), + ); + const errorHandler = vi.fn(); + + await build({ errorHandler }); + + expect(uploads).toHaveLength(1); + expect(errorHandler).toHaveBeenCalledWith(error); + }); + + it('leaves "disable-upload" builds untouched', async () => { + await build({ sourcemaps: { disable: 'disable-upload' } }, { sourcemap: true }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(uploads).toHaveLength(0); + }); +}); From 9face8ae7ba1144abab3742326383c3f36c44bc7 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Tue, 10 Nov 2026 16:29:10 -0500 Subject: [PATCH 010/136] fix(astro, cloudflare): Run the Cloudflare SDK on the server for Cloudflare Pages (#26188) This PR addresses a few issues I found while investigating some comments on #25999 ### CF Pages runs the browser SDK on the server This means it will immediately crash if we ship anything that assumes a server-side SDK is being used, this showed up when I tried to use the `serveTunnelIntegration` on the other PR, it doesn't exist on the client SDKs. This happens because we do not have an `exports` condition for `worker/workerd` like other SDKs. So `@sentry/astro` resolves to `index.client.js`. ```js // @sentry/astro exports["."]: no workerd entry, so workerd falls through to the client build { "node": "./build/esm/index.server.js", "browser": "./build/esm/index.client.js", "import": "./build/esm/index.client.js" } // @astrojs/cloudflare v12 SSR resolve conditions: no "node" vite.ssr.resolve.conditions.push("workerd", "worker"); ``` We had no E2E apps covering this so it never came up, also it doesn't happen while using `withSentry`. But a user trying to call `Sentry.init` from `@sentry/astro` will trigger the bug. I fixed this by adding a new `workerd/worker` export conditions that point to a new `index.worker.ts`, which rexports the cloudflare SDK and uses the `init` from there. There is a different way to fix it via vite plugins, but I preferred the more "standard" way here. --- ### Cloudflare Client Events are dropped if `withSentry` is not used This showed up while testing the first issue, the tests were timing out. This is because in CF pages, the `withSentry` wrapper is never used so our sends were never registered with `waitUntil`, so the `flush` returned early, cutting off the requests. I fixed this by making the `flush` wait for the previous sends until they are drained. Which also fixes the issue for every possible usage of `@sentry/cloudflare` that isn't wrapped by `withSentry`. ```ts // _registerWithInvocationWaitUntil const pending = Promise.resolve(promise).then(() => undefined, () => undefined); this._pendingEagerDrains.add(pending); void pending.then(() => this._pendingEagerDrains.delete(pending)); // flush(), after super.flush(timeout) await Promise.all(this._pendingEagerDrains); ``` There is no risk of hanging here because each send is already capped by 2 seconds. --- ### The Workers wrapper can shadow the `sentry.server.config` client Because of the first fix, we now have an order problem. A `withSentry` wrapper can override the client that was loaded from `sentry.server.config` which would break all events, since there is no DSN. The override happens because the wrapper runs first. It's not really an override, more of a "shadowing". This didn't happen before because the first client loaded from the browser bundle and so they never conflicted. The fix is to ensure the order loads the "correct" init first, which can be arbitrary. I did the following to de-risk the idea: - If no `sentry.server.config` file exists, then it is never added at the top of the import order. So the wrapper client is the only source. - If both `sentry.server.config` file exists along with a wrapper client, prefer the server file client. - The Astro worker `init` reads the bindings from `cloudflare:workers` and fills unset options the same way the wrap does, so an init without a `dsn` still picks up `SENTRY_DSN`. This only lives in the `workerd` entry since `cloudflare:workers` doesn't resolve elsewhere. I did think about applying (3) to the cloudflare SDK in general but that may break apps that run it under Node, so need to figure it out later. --- .../tests/runtime-entries.test.ts | 34 ++++++----- .../astro-5-cf-pages/.gitignore | 26 +++++++++ .../astro-5-cf-pages/astro.config.mjs | 18 ++++++ .../astro-5-cf-pages/package.json | 35 ++++++++++++ .../astro-5-cf-pages/playwright.config.mjs | 14 +++++ .../astro-5-cf-pages/pnpm-workspace.yaml | 5 ++ .../astro-5-cf-pages/sentry.client.config.js | 8 +++ .../astro-5-cf-pages/sentry.server.config.js | 9 +++ .../src/pages/api/request-error.ts | 8 +++ .../src/pages/api/test-error.ts | 7 +++ .../astro-5-cf-pages/src/pages/index.astro | 12 ++++ .../astro-5-cf-pages/start-event-proxy.mjs | 6 ++ .../tests/errors.server.test.ts | 51 +++++++++++++++++ .../astro-5-cf-pages/tests/tunnel.test.ts | 25 +++++++++ .../astro-5-cf-pages/tsconfig.json | 5 ++ .../astro-5-cf-pages/wrangler.jsonc | 7 +++ .../astro-5-cf-workers/package.json | 28 +++++++++- .../astro-5-cf-workers/playwright.config.mjs | 2 +- .../sentry.server.config.js | 18 +++++- .../src/pages/api/request-error.ts | 8 +++ .../tests/server-config.test.ts | 39 +++++++++++++ .../wrangler.server-config.jsonc | 11 ++++ packages/astro/package.json | 9 +++ packages/astro/rollup.npm.config.mjs | 3 + packages/astro/src/index.worker.ts | 8 +++ packages/astro/src/index.workerd.ts | 13 +++++ packages/astro/src/integration/cloudflare.ts | 19 +++---- packages/astro/src/integration/index.ts | 29 +++++++--- packages/astro/src/server/middleware.ts | 24 ++++---- .../astro/src/worker/cloudflareWorkers.d.ts | 6 ++ packages/astro/src/worker/sdk.ts | 32 +++++++++++ packages/astro/test/index.workerd.test.ts | 30 ++++++++++ .../astro/test/integration/cloudflare.test.ts | 56 +++++++++++++++++++ .../integration/cloudflareVitePlugin.test.ts | 18 +++++- packages/astro/test/server/middleware.test.ts | 33 ++++++----- packages/astro/test/worker/sdk.test.ts | 47 ++++++++++++++++ packages/astro/tsconfig.test.json | 2 +- packages/cloudflare/src/client.ts | 28 +++++++--- packages/cloudflare/src/index.ts | 3 +- .../src/wrapRequestHandlerWithInit.ts | 11 +++- packages/cloudflare/test/client.test.ts | 28 ++++++++++ packages/cloudflare/test/request.test.ts | 15 +++++ packages/core/src/server.ts | 5 +- packages/core/src/utils/flushIfServerless.ts | 35 ++++++++++++ .../test/lib/utils/flushIfServerless.test.ts | 46 ++++++++++++++- pnpm-lock.yaml | 3 + 46 files changed, 793 insertions(+), 86 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/.gitignore create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/astro.config.mjs create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/playwright.config.mjs create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/pnpm-workspace.yaml create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.client.config.js create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.server.config.js create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/request-error.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/test-error.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/index.astro create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/start-event-proxy.mjs create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/errors.server.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/tunnel.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tsconfig.json create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-pages/wrangler.jsonc create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-workers/src/pages/api/request-error.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-workers/tests/server-config.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/astro-5-cf-workers/wrangler.server-config.jsonc create mode 100644 packages/astro/src/index.worker.ts create mode 100644 packages/astro/src/index.workerd.ts create mode 100644 packages/astro/src/worker/cloudflareWorkers.d.ts create mode 100644 packages/astro/src/worker/sdk.ts create mode 100644 packages/astro/test/index.workerd.test.ts create mode 100644 packages/astro/test/worker/sdk.test.ts diff --git a/dev-packages/bundler-tests/tests/runtime-entries.test.ts b/dev-packages/bundler-tests/tests/runtime-entries.test.ts index 156102cc6765..09cd3694c53f 100644 --- a/dev-packages/bundler-tests/tests/runtime-entries.test.ts +++ b/dev-packages/bundler-tests/tests/runtime-entries.test.ts @@ -26,23 +26,14 @@ const BUILD_TIME_PATTERNS: RegExp[] = [ /\.wasm$/, ]; -const KNOWN_VIOLATIONS = new Set([ - // These root entries also re-export config-time code (`sentryAstro`, - // `withSentry`). They must keep it until v12 for backwards compatibility. - '@sentry/astro', - '@sentry/solidstart', - // Remix 3 has no bundler. Its asset server runs the orchestrion - // transform on browser modules at request time. - '@sentry/remix/v3', - '@sentry/remix/v3/node', -]); - type Format = 'esm' | 'cjs'; interface Case { specifier: string; conditions: string[]; formats: Format[]; + /** The entry reaches build-time tooling on purpose. Drop this when the test fails. */ + knownViolation?: true; } const NODE = ['node']; @@ -81,7 +72,11 @@ const CASES: Case[] = [ { specifier: '@sentry/sveltekit', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/sveltekit/opentelemetry-api', conditions: NODE, formats: BOTH }, - { specifier: '@sentry/astro', conditions: NODE, formats: BOTH }, + // The Node root entry also re-exports config-time code (`sentryAstro`). It must keep it until v12 + // for backwards compatibility. + { specifier: '@sentry/astro', conditions: NODE, formats: BOTH, knownViolation: true }, + { specifier: '@sentry/astro', conditions: WORKERD, formats: BOTH }, + { specifier: '@sentry/astro', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/astro/middleware', conditions: NODE, formats: BOTH }, { specifier: '@sentry/astro/import', conditions: NODE, formats: ESM }, @@ -93,10 +88,14 @@ const CASES: Case[] = [ { specifier: '@sentry/remix', conditions: ['worker'], formats: BOTH }, { specifier: '@sentry/remix/cloudflare', conditions: WORKERD, formats: BOTH }, { specifier: '@sentry/remix/import', conditions: NODE, formats: ESM }, - { specifier: '@sentry/remix/v3', conditions: NODE, formats: ESM }, - { specifier: '@sentry/remix/v3/node', conditions: NODE, formats: ESM }, + // Remix 3 has no bundler. Its asset server runs the orchestrion transform on browser modules at + // request time. + { specifier: '@sentry/remix/v3', conditions: NODE, formats: ESM, knownViolation: true }, + { specifier: '@sentry/remix/v3/node', conditions: NODE, formats: ESM, knownViolation: true }, - { specifier: '@sentry/solidstart', conditions: NODE, formats: BOTH }, + // The root entry also re-exports config-time code (`withSentry`). It must keep it until v12 for + // backwards compatibility. + { specifier: '@sentry/solidstart', conditions: NODE, formats: BOTH, knownViolation: true }, { specifier: '@sentry/tanstackstart-react', conditions: NODE, formats: BOTH }, { specifier: '@sentry/tanstackstart-react/import', conditions: NODE, formats: ESM }, @@ -217,14 +216,13 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom } describe('server runtime entries do not reach build-time tooling', () => { - for (const { specifier, conditions, formats } of CASES) { + for (const { specifier, conditions, formats, knownViolation } of CASES) { for (const format of formats) { const name = `${specifier} (${format}, conditions: ${conditions.join(', ')})`; - if (KNOWN_VIOLATIONS.has(specifier)) { + if (knownViolation) { test(`${name} is a known violation`, async () => { const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); - // Remove the entry from KNOWN_VIOLATIONS when this fails. expect(violations).not.toEqual([]); }); } else { diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/.gitignore b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/.gitignore new file mode 100644 index 000000000000..560782d47d98 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/.gitignore @@ -0,0 +1,26 @@ +# build output +dist/ + +# generated types +.astro/ + +# dependencies +node_modules/ + +# logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# environment variables +.env +.env.production + +# macOS-specific files +.DS_Store + +# jetbrains setting folder +.idea/ + +test-results diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/astro.config.mjs b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/astro.config.mjs new file mode 100644 index 000000000000..a3687388202b --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/astro.config.mjs @@ -0,0 +1,18 @@ +import cloudflare from '@astrojs/cloudflare'; +import sentry from '@sentry/astro/integration'; +// @ts-check +import { defineConfig } from 'astro/config'; + +// https://astro.build/config +export default defineConfig({ + integrations: [ + sentry({ + debug: true, + sourcemaps: { + disable: true, + }, + }), + ], + output: 'server', + adapter: cloudflare(), +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json new file mode 100644 index 000000000000..b679df6add37 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json @@ -0,0 +1,35 @@ +{ + "name": "astro-5-cf-pages", + "type": "module", + "version": "0.0.1", + "scripts": { + "dev": "astro dev", + "build": "astro build", + "preview": "wrangler pages dev ./dist --port 3030", + "test:build": "pnpm install && pnpm build", + "test:assert": "TEST_ENV=production playwright test", + "test:build:tunnel": "pnpm install && PUBLIC_E2E_TEST_TUNNEL=1 PUBLIC_E2E_TEST_DSN=http://public@localhost:3031/1337 pnpm build", + "test:assert:tunnel": "PUBLIC_E2E_TEST_TUNNEL=1 TEST_ENV=production playwright test tunnel" + }, + "dependencies": { + "@astrojs/cloudflare": "^12.6.12", + "@playwright/test": "1.64.1", + "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "@sentry/astro": "file:../../packed/sentry-astro-packed.tgz", + "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", + "astro": "^5.17.1" + }, + "devDependencies": { + "@sentry/conventions": "0.31.0", + "wrangler": "^4.63.0" + }, + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:tunnel", + "assert-command": "pnpm test:assert:tunnel", + "label": "astro-5-cf-pages (tunnel)" + } + ] + } +} diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/playwright.config.mjs new file mode 100644 index 000000000000..3cdf5850b613 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/playwright.config.mjs @@ -0,0 +1,14 @@ +import { getPlaywrightConfig } from '@sentry-internal/test-utils'; + +const testEnv = process.env.TEST_ENV; + +if (!testEnv) { + throw new Error('No test env defined'); +} + +const config = getPlaywrightConfig({ + startCommand: 'pnpm preview', + port: 3030, +}); + +export default config; diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/pnpm-workspace.yaml new file mode 100644 index 000000000000..dd39420094df --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/pnpm-workspace.yaml @@ -0,0 +1,5 @@ +allowBuilds: + esbuild: true + sharp: true + workerd: true +minimumReleaseAge: 0 diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.client.config.js b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.client.config.js new file mode 100644 index 000000000000..3426ab60f5bb --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.client.config.js @@ -0,0 +1,8 @@ +import * as Sentry from '@sentry/astro'; + +Sentry.init({ + dsn: import.meta.env.PUBLIC_E2E_TEST_DSN, + environment: 'qa', + tracesSampleRate: 1.0, + tunnel: import.meta.env.PUBLIC_E2E_TEST_TUNNEL ? true : 'http://localhost:3031/', // proxy server +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.server.config.js b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.server.config.js new file mode 100644 index 000000000000..c6ae7d0c506e --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/sentry.server.config.js @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/astro'; + +Sentry.init({ + dsn: import.meta.env.PUBLIC_E2E_TEST_DSN, + environment: 'qa', + tracesSampleRate: 1.0, + tunnel: 'http://localhost:3031/', // proxy server + integrations: import.meta.env.PUBLIC_E2E_TEST_TUNNEL ? [Sentry.serveTunnelIntegration()] : [], +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/request-error.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/request-error.ts new file mode 100644 index 000000000000..40006ef86fc6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/request-error.ts @@ -0,0 +1,8 @@ +import type { APIRoute } from 'astro'; + +export const prerender = false; + +// A distinct message per request, so the Dedupe integration doesn't drop repeats. +export const GET: APIRoute = ({ url }) => { + throw new Error(`API route error for request ${url.searchParams.get('request')}`); +}; diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/test-error.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/test-error.ts new file mode 100644 index 000000000000..24ac1b4d39ec --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/api/test-error.ts @@ -0,0 +1,7 @@ +import type { APIRoute } from 'astro'; + +export const prerender = false; + +export const GET: APIRoute = () => { + throw new Error('This is a test error from an API route'); +}; diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/index.astro b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/index.astro new file mode 100644 index 000000000000..04ff16ad28f8 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/src/pages/index.astro @@ -0,0 +1,12 @@ +--- +--- + + + + + Astro Cloudflare Pages + + +

Astro Cloudflare Pages

+ + diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/start-event-proxy.mjs new file mode 100644 index 000000000000..a5234f121768 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/start-event-proxy.mjs @@ -0,0 +1,6 @@ +import { startEventProxyServer } from '@sentry-internal/test-utils'; + +startEventProxyServer({ + port: 3031, + proxyServerName: 'astro-5-cf-pages', +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/errors.server.test.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/errors.server.test.ts new file mode 100644 index 000000000000..c0268cb3c8cd --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/errors.server.test.ts @@ -0,0 +1,51 @@ +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { HTTP_SERVER } from '@sentry/conventions/op'; + +// Several requests hit the same isolate, so later ones run with the client the first one cached. +test('captures an API route error with the Cloudflare-backed server SDK on every request', async ({ request }) => { + for (let i = 0; i < 4; i++) { + const errorEventPromise = waitForError('astro-5-cf-pages', errorEvent => { + return errorEvent?.exception?.values?.[0]?.value === `API route error for request ${i}`; + }); + + const spanPromise = waitForStreamedSpan('astro-5-cf-pages', span => { + return getSpanOp(span) === HTTP_SERVER && span.is_segment && span.name === 'GET /api/request-error'; + }); + + await request.get(`/api/request-error?request=${i}`); + + const errorEvent = await errorEventPromise; + const span = await spanPromise; + + expect(errorEvent).toMatchObject({ + contexts: { + trace: { + trace_id: span.trace_id, + span_id: span.span_id, + }, + }, + environment: 'qa', + exception: { + values: [ + { + mechanism: expect.objectContaining({ handled: false }), + type: 'Error', + value: `API route error for request ${i}`, + }, + ], + }, + request: { + method: 'GET', + url: expect.stringContaining(`/api/request-error?request=${i}`), + }, + sdk: { + name: 'sentry.javascript.astro', + packages: [ + { name: 'npm:@sentry/astro', version: expect.any(String) }, + { name: 'npm:@sentry/cloudflare', version: expect.any(String) }, + ], + }, + }); + } +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/tunnel.test.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/tunnel.test.ts new file mode 100644 index 000000000000..41aa41c9bcb3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tests/tunnel.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from '@playwright/test'; +import { isServerSpanAt, watchForTunnelSpan } from '@sentry-internal/test-utils'; + +test.skip(!process.env.PUBLIC_E2E_TEST_TUNNEL, 'Only runs in the tunnel variant'); + +const TUNNEL_PATH = /^\/[a-z0-9]{1,7}$/; + +// Several page loads hit the same isolate, so later ones run with the client the first one cached. +test('answers the managed tunnel on every request to the isolate, without tunnel spans', async ({ page }) => { + const raceTunnelSpan = watchForTunnelSpan('astro-5-cf-pages', isServerSpanAt(TUNNEL_PATH)); + + for (let i = 0; i < 3; i++) { + const tunnelResponsePromise = page.waitForResponse( + response => response.request().method() === 'POST' && TUNNEL_PATH.test(new URL(response.url()).pathname), + ); + + await page.goto('/'); + + expect((await tunnelResponsePromise).status()).toBe(200); + } + + expect( + await raceTunnelSpan(isServerSpanAt('/api/request-error'), () => page.request.get('/api/request-error?request=0')), + ).toBe('anchor'); +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tsconfig.json b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tsconfig.json new file mode 100644 index 000000000000..8bf91d3bb997 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "astro/tsconfigs/strict", + "include": [".astro/types.d.ts", "**/*"], + "exclude": ["dist"] +} diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/wrangler.jsonc new file mode 100644 index 000000000000..dd4dbea314ad --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/wrangler.jsonc @@ -0,0 +1,7 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "astro-5-cf-pages", + "pages_build_output_dir": "./dist", + "compatibility_date": "2025-12-01", + "compatibility_flags": ["nodejs_compat"], +} diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/package.json b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/package.json index f24bd3abf58e..948c68eb7ee4 100644 --- a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/package.json +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/package.json @@ -6,8 +6,15 @@ "dev": "astro dev", "build": "astro build", "preview": "wrangler dev --port 3030", + "preview:server-config": "wrangler dev --config wrangler.server-config.jsonc --port 3030", "test:build": "pnpm install && pnpm build", - "test:assert": "TEST_ENV=production playwright test" + "test:assert": "TEST_ENV=production playwright test", + "test:build:server-config": "pnpm install && PUBLIC_E2E_TEST_SERVER_CONFIG=1 pnpm build", + "test:assert:server-config": "PUBLIC_E2E_TEST_SERVER_CONFIG=1 TEST_ENV=production playwright test server-config", + "test:build:no-server-config": "pnpm install && rm sentry.server.config.js && pnpm build", + "test:assert:no-server-config": "TEST_ENV=production playwright test", + "test:build:server-config-no-dsn": "pnpm install && PUBLIC_E2E_TEST_SERVER_CONFIG=no-dsn pnpm build", + "test:assert:server-config-no-dsn": "PUBLIC_E2E_TEST_SERVER_CONFIG=no-dsn TEST_ENV=production playwright test server-config" }, "dependencies": { "@astrojs/cloudflare": "^12.6.12", @@ -19,5 +26,24 @@ }, "devDependencies": { "wrangler": "^4.63.0" + }, + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:server-config", + "assert-command": "pnpm test:assert:server-config", + "label": "astro-5-cf-workers (server-config)" + }, + { + "build-command": "pnpm test:build:no-server-config", + "assert-command": "pnpm test:assert:no-server-config", + "label": "astro-5-cf-workers (no-server-config)" + }, + { + "build-command": "pnpm test:build:server-config-no-dsn", + "assert-command": "pnpm test:assert:server-config-no-dsn", + "label": "astro-5-cf-workers (server-config-no-dsn)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/playwright.config.mjs index 3cdf5850b613..6bab0462468a 100644 --- a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/playwright.config.mjs +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/playwright.config.mjs @@ -7,7 +7,7 @@ if (!testEnv) { } const config = getPlaywrightConfig({ - startCommand: 'pnpm preview', + startCommand: process.env.PUBLIC_E2E_TEST_SERVER_CONFIG === '1' ? 'pnpm preview:server-config' : 'pnpm preview', port: 3030, }); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/sentry.server.config.js b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/sentry.server.config.js index afdc1e1f784e..346f1258cec7 100644 --- a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/sentry.server.config.js +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/sentry.server.config.js @@ -1,2 +1,16 @@ -// The Worker wrapper initializes Sentry from Wrangler bindings. -// Keep this file to prevent Astro from injecting its default Node SDK initialization. +import * as Sentry from '@sentry/astro'; + +// By default, the Worker wrapper initializes Sentry from Wrangler bindings and this file only +// prevents Astro from injecting its default Node SDK initialization. The `server-config` variants +// initialize from here instead: `1` without any `SENTRY_*` binding, `no-dsn` with the DSN coming +// from the `SENTRY_DSN` binding. +const serverConfigVariant = import.meta.env.PUBLIC_E2E_TEST_SERVER_CONFIG; + +if (serverConfigVariant) { + Sentry.init({ + dsn: serverConfigVariant === 'no-dsn' ? undefined : import.meta.env.PUBLIC_E2E_TEST_DSN, + environment: 'qa', + tracesSampleRate: 1.0, + tunnel: 'http://localhost:3031/', // proxy server + }); +} diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/src/pages/api/request-error.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/src/pages/api/request-error.ts new file mode 100644 index 000000000000..40006ef86fc6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/src/pages/api/request-error.ts @@ -0,0 +1,8 @@ +import type { APIRoute } from 'astro'; + +export const prerender = false; + +// A distinct message per request, so the Dedupe integration doesn't drop repeats. +export const GET: APIRoute = ({ url }) => { + throw new Error(`API route error for request ${url.searchParams.get('request')}`); +}; diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/tests/server-config.test.ts b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/tests/server-config.test.ts new file mode 100644 index 000000000000..6ac5e15b2dd3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/tests/server-config.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from '@playwright/test'; +import { waitForError } from '@sentry-internal/test-utils'; + +test.skip(!process.env.PUBLIC_E2E_TEST_SERVER_CONFIG, 'Only runs in the server-config variant'); + +// The Worker wrapper must not init a client from the (missing) bindings before `sentry.server.config` +// runs, or the isolate keeps that client and the user's options never apply. Several requests hit +// the same isolate to cover the cached client too. +test('initializes from sentry.server.config on every request to the isolate', async ({ request }) => { + for (let i = 0; i < 4; i++) { + const errorEventPromise = waitForError('astro-5-cf-workers', errorEvent => { + return errorEvent?.exception?.values?.[0]?.value === `API route error for request ${i}`; + }); + + await request.get(`/api/request-error?request=${i}`); + + const errorEvent = await errorEventPromise; + + expect(errorEvent).toMatchObject({ + environment: 'qa', + exception: { + values: [ + { + mechanism: expect.objectContaining({ handled: false }), + type: 'Error', + value: `API route error for request ${i}`, + }, + ], + }, + request: { + method: 'GET', + url: expect.stringContaining(`/api/request-error?request=${i}`), + }, + sdk: { + name: 'sentry.javascript.astro', + }, + }); + } +}); diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/wrangler.server-config.jsonc b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/wrangler.server-config.jsonc new file mode 100644 index 000000000000..8c2646bb998c --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-workers/wrangler.server-config.jsonc @@ -0,0 +1,11 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "astro-5-cf-workers", + "main": "dist/_worker.js/index.js", + "compatibility_date": "2025-12-01", + "compatibility_flags": ["nodejs_compat"], + "assets": { + "binding": "ASSETS", + "directory": "./dist", + }, +} diff --git a/packages/astro/package.json b/packages/astro/package.json index 6fe668e9ef76..9879b5bc9c10 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -27,6 +27,14 @@ "exports": { ".": { "types": "./build/types/index.types.d.ts", + "workerd": { + "import": "./build/esm/index.workerd.js", + "require": "./build/cjs/index.workerd.js" + }, + "worker": { + "import": "./build/esm/index.worker.js", + "require": "./build/cjs/index.worker.js" + }, "node": "./build/esm/index.server.js", "browser": "./build/esm/index.client.js", "import": "./build/esm/index.client.js", @@ -58,6 +66,7 @@ }, "dependencies": { "@sentry/browser": "11.12.0", + "@sentry/cloudflare": "11.12.0", "@sentry/core": "11.12.0", "@sentry/conventions": "^0.32.0", "@sentry/node": "11.12.0", diff --git a/packages/astro/rollup.npm.config.mjs b/packages/astro/rollup.npm.config.mjs index 07a25d8690b1..65e59feac11a 100644 --- a/packages/astro/rollup.npm.config.mjs +++ b/packages/astro/rollup.npm.config.mjs @@ -5,10 +5,13 @@ const variants = makeNPMConfigVariants( entrypoints: [ 'src/index.server.ts', 'src/index.client.ts', + 'src/index.worker.ts', + 'src/index.workerd.ts', 'src/index.integration.ts', 'src/integration/middleware/index.ts', ], packageSpecificConfig: { + external: ['cloudflare:workers'], output: { dynamicImportInCjs: true, exports: 'named', diff --git a/packages/astro/src/index.worker.ts b/packages/astro/src/index.worker.ts new file mode 100644 index 000000000000..2dde710a78af --- /dev/null +++ b/packages/astro/src/index.worker.ts @@ -0,0 +1,8 @@ +// The server entry for the `worker` condition, where the Node SDK can't run. `index.workerd` adds the Wrangler +// bindings on top for Cloudflare. +/* eslint-disable import/export */ +export * from '@sentry/cloudflare'; + +export { init } from './worker/sdk'; + +export { handleRequest } from './server/middleware'; diff --git a/packages/astro/src/index.workerd.ts b/packages/astro/src/index.workerd.ts new file mode 100644 index 000000000000..d355b15c2601 --- /dev/null +++ b/packages/astro/src/index.workerd.ts @@ -0,0 +1,13 @@ +import * as cloudflareWorkers from 'cloudflare:workers'; +import { setBindingsGetter } from './worker/sdk'; + +// `cloudflare:workers` only resolves in Cloudflare's own bundlers (wrangler, `@cloudflare/vite-plugin`), +// which all select the `workerd` export condition. Consumers of the generic `worker` condition keep +// getting `index.worker`, which has no such import and would otherwise fail to bundle. +// +// A namespace import keeps a missing `env` export (older runtimes) a missing property instead of a +// module linking error that would take the whole Worker down. +setBindingsGetter(() => cloudflareWorkers.env); + +// eslint-disable-next-line import/export +export * from './index.worker'; diff --git a/packages/astro/src/integration/cloudflare.ts b/packages/astro/src/integration/cloudflare.ts index 429504c6781a..d443ea897c4a 100644 --- a/packages/astro/src/integration/cloudflare.ts +++ b/packages/astro/src/integration/cloudflare.ts @@ -1,5 +1,6 @@ import type { AstroConfig } from 'astro'; import { builtinModules } from 'module'; +import { SERVER_INIT_IMPORT } from './serverInit'; // Derived from Astro's own config type rather than imported from `vite` directly: Astro bundles its // own Vite version, which differs across the Astro majors we support. A plugin typed against any @@ -42,20 +43,17 @@ export function sentryCloudflareNodeWarningPlugin(): VitePlugin { export const WORKER_ENTRY_IDS = ['astrojs-ssr-virtual-entry', 'virtual:cloudflare/worker-entry']; /** - * A Vite plugin that ensures the Sentry server config is loaded at the - * top level of the Cloudflare Worker entry module, rather than only being - * injected into SSR page modules via `injectScript('page-ssr', ...)`. - * - * Without this, Astro actions and API routes never call `Sentry.init()`, - * because `injectScript('page-ssr')` only adds the import to page components. - * - * Additionally, this plugin wraps the Worker's default export handler with - * `@sentry/cloudflare`'s `withSentry` to provide: + * A Vite plugin that wraps the Worker's default export handler with `@sentry/cloudflare`'s `withSentry` to provide: * - `setAsyncLocalStorageAsyncContextStrategy()` for proper async context * - Per-request isolation scopes via `wrapRequestHandler` * - Trace context propagation + * + * With `importServerInit`, it also imports the server init at the top of the Worker entry. The wrap inits a client + * from the Wrangler bindings on each request, and the isolate keeps the first client it gets. So the user's + * `Sentry.init()` has to run before that, or it gets back the bindings-only client and its options are ignored. + * This also runs the init for actions and API routes, which `injectScript('page-ssr')` doesn't reach. */ -export function sentryCloudflareVitePlugin(): VitePlugin { +export function sentryCloudflareVitePlugin({ importServerInit = false } = {}): VitePlugin { return { name: 'sentry-astro-cloudflare', enforce: 'post', @@ -77,6 +75,7 @@ export function sentryCloudflareVitePlugin(): VitePlugin { const originalExpr = defaultExportMatch[1]; const wrappedExport = `export default withSentry(() => undefined, ${originalExpr});`; const transformedCode = [ + ...(importServerInit ? [SERVER_INIT_IMPORT.trim()] : []), "import { withSentry } from '@sentry/cloudflare';", code.replace(defaultExportMatch[0], wrappedExport), ].join('\n'); diff --git a/packages/astro/src/integration/index.ts b/packages/astro/src/integration/index.ts index 36c6421b72d7..0df042e17afd 100644 --- a/packages/astro/src/integration/index.ts +++ b/packages/astro/src/integration/index.ts @@ -158,9 +158,9 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { // Wire up the orchestrion code transform so instrumented server-side dependencies (e.g. // `mysql`, `ioredis`) get `diagnostics_channel` publishers injected into the SSR bundle at // build time, with no manual plugin setup. The plugin opts out internally when - // `buildTimeInstrumentation` is `false`. Cloudflare Pages is skipped: it gets no - // `withSentry` wrap, so nothing would read the marker the injected snippets write, and - // keeping the transform off avoids bundling dead subscriber code. + // `buildTimeInstrumentation` is `false`. Cloudflare Pages doesn't get the transform yet, + // even though its production builds now have the `withSentry` wrap that would read the + // marker the injected snippets write. if (sdkEnabled.server && (!isCloudflare || isCloudflareWorkers) && !usesCloudflareVitePlugin) { updateConfig({ vite: { @@ -206,8 +206,10 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { if (isCloudflareWorkers && command !== 'dev') { // For Cloudflare Workers production builds, additionally use a Vite plugin to: - // 1. Import the server config at the Worker entry level (so Sentry.init() runs - // for ALL requests, not just SSR pages — covers actions and API routes) + // 1. Import the user's server config at the top of the Worker entry, so their Sentry.init() + // runs before the `withSentry` wrap inits a client from the bindings, and also for + // actions and API routes, not just SSR pages. Not the default init: it has no DSN, and + // running it first would keep the wrap from using the bindings' DSN. // 2. Wrap the default export with `withSentry` from @sentry/cloudflare for // per-request isolation, async context, and trace propagation // @@ -221,7 +223,10 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { vite: { plugins: usesCloudflareVitePlugin ? [sentryCloudflareNodeWarningPlugin()] - : [sentryCloudflareNodeWarningPlugin(), sentryCloudflareVitePlugin()], + : [ + sentryCloudflareNodeWarningPlugin(), + sentryCloudflareVitePlugin({ importServerInit: !!pathToServerInit }), + ], }, }); } else if (isCloudflare) { @@ -231,13 +236,19 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { updateConfig({ vite: { // A Pages build gets the same `withSentry` wrap as Workers, which answers managed tunnel requests. + // The user's server config has to run before that wrap here too, or the client with their tunnel + // and DSN never gets created. plugins: command !== 'dev' - ? [sentryCloudflareNodeWarningPlugin(), sentryCloudflareVitePlugin()] + ? [ + sentryCloudflareNodeWarningPlugin(), + sentryCloudflareVitePlugin({ importServerInit: !!pathToServerInit }), + ] : [sentryCloudflareNodeWarningPlugin()], ssr: { - // @sentry/node is required in case we have 2 different @sentry/node - // packages installed in the same project. + // Only matters in dev: `@astrojs/cloudflare` sets `ssr.noExternal: true` for production builds. + // Its dev server runs SSR in Node without the `workerd` condition, so `@sentry/astro` still + // resolves to the Node SDK there. `@sentry/node` stays listed in case a project has two copies. // Ref: https://github.com/getsentry/sentry-javascript/issues/10121 noExternal: ['@sentry/astro', '@sentry/node'], }, diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index 410fe0c9a8be..c50f53bdc4ac 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -14,15 +14,26 @@ import { HTTP_SERVER } from '@sentry/conventions/op'; import type { Span, SpanAttributes } from '@sentry/core'; import { addNonEnumerableProperty, + captureException, + continueTrace, + getActiveSpan, + getClient, + getCurrentScope, getIsolationScope, getRootSpan, + getTraceMetaTags, getUrlFragment, getUrlQuery, hasSpanStreamingEnabled, HTTP_SPAN_NAME_FALLBACK, + httpHeadersToSpanAttributes, objectify, + setHttpStatus, spanToJSON, + startSpan, + winterCGHeadersToDict, winterCGRequestToRequestData, + withIsolationScope, filterCollectedUrl, filterCollectedUrlQuery, } from '@sentry/core'; @@ -30,19 +41,6 @@ import { flushIfServerless, _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, } from '@sentry/core/server'; -import { - captureException, - continueTrace, - getActiveSpan, - getClient, - getCurrentScope, - getTraceMetaTags, - httpHeadersToSpanAttributes, - setHttpStatus, - startSpan, - winterCGHeadersToDict, - withIsolationScope, -} from '@sentry/node'; import { setHttpServerSpanRouteAttribute } from '@sentry/server-utils'; import type { APIContext, MiddlewareHandler, MiddlewareNext, RoutePart } from 'astro'; diff --git a/packages/astro/src/worker/cloudflareWorkers.d.ts b/packages/astro/src/worker/cloudflareWorkers.d.ts new file mode 100644 index 000000000000..2db71c38ee2b --- /dev/null +++ b/packages/astro/src/worker/cloudflareWorkers.d.ts @@ -0,0 +1,6 @@ +// `@cloudflare/workers-types` declares this module, but pulling it in would also add Workers globals +// that clash with the DOM lib the client half of this package is checked against. Only the export +// the SDK reads is declared here; the declaration is build-time only and never emitted. +declare module 'cloudflare:workers' { + export const env: unknown; +} diff --git a/packages/astro/src/worker/sdk.ts b/packages/astro/src/worker/sdk.ts new file mode 100644 index 000000000000..7d4672f6a558 --- /dev/null +++ b/packages/astro/src/worker/sdk.ts @@ -0,0 +1,32 @@ +import type { CloudflareClient, CloudflareOptions } from '@sentry/cloudflare'; +import { + _INTERNAL_getFinalOptions as getFinalOptions, + _INTERNAL_init as initCloudflareSdk, + setAsyncLocalStorageAsyncContextStrategy, +} from '@sentry/cloudflare'; +import { applySdkMetadata } from '@sentry/core'; + +let getBindings: (() => unknown) | undefined; + +/** + * Sets where `init` reads the Worker's bindings from. Only the `workerd` entry can import them. + */ +export function setBindingsGetter(getter: (() => unknown) | undefined): void { + getBindings = getter; +} + +/** + * Initializes the Sentry Astro SDK on Cloudflare Workers and Pages. + */ +export function init(options: CloudflareOptions): CloudflareClient | undefined { + // `withSentry` fills unset options from the bindings it gets per request. This init can run first, and the + // isolate keeps the first client, so it reads the same bindings to end up with the same options. + const opts = getFinalOptions({ ...options }, getBindings?.()); + + applySdkMetadata(opts, 'astro', ['astro', 'cloudflare']); + + // Pages has no `withSentry` wrap to install this, and the middleware's per-request isolation scopes depend on it. + setAsyncLocalStorageAsyncContextStrategy(); + + return initCloudflareSdk(opts); +} diff --git a/packages/astro/test/index.workerd.test.ts b/packages/astro/test/index.workerd.test.ts new file mode 100644 index 000000000000..b206bef21e55 --- /dev/null +++ b/packages/astro/test/index.workerd.test.ts @@ -0,0 +1,30 @@ +import { getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { setBindingsGetter } from '../src/worker/sdk'; + +describe('workerd entry point', () => { + afterEach(() => { + getMainCarrier().__SENTRY__ = undefined; + setBindingsGetter(undefined); + vi.resetModules(); + vi.doUnmock('cloudflare:workers'); + }); + + it('inits with the bindings from `cloudflare:workers`', async () => { + vi.doMock('cloudflare:workers', () => ({ env: { SENTRY_DSN: 'https://binding@dsn.ingest.sentry.io/1' } })); + + const { init } = await import('../src/index.workerd'); + + expect(init({ cacheClient: false })?.getOptions().dsn).toBe('https://binding@dsn.ingest.sentry.io/1'); + }); + + it('inits without bindings when `env` is missing', async () => { + vi.doMock('cloudflare:workers', () => ({ env: undefined })); + + const { init } = await import('../src/index.workerd'); + + expect(init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', cacheClient: false })?.getOptions().dsn).toBe( + 'https://public@dsn.ingest.sentry.io/1337', + ); + }); +}); diff --git a/packages/astro/test/integration/cloudflare.test.ts b/packages/astro/test/integration/cloudflare.test.ts index 32a5b1ff0793..40e233c8c282 100644 --- a/packages/astro/test/integration/cloudflare.test.ts +++ b/packages/astro/test/integration/cloudflare.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { sentryAstro } from '../../src/integration'; +import { sentryCloudflareVitePlugin } from '../../src/integration/cloudflare'; const getWranglerConfig = vi.hoisted(() => vi.fn()); @@ -78,6 +79,38 @@ describe('Cloudflare Pages vs Workers detection', () => { ); }); + it('imports the user server config at the Worker entry', async () => { + const integration = sentryAstro({ serverInitPath: 'sentry.server.config.js' }); + + // @ts-expect-error - the hook exists and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ + ...baseConfigHookObject, + config: { + // @ts-expect-error - we only need to pass what we actually use + adapter: { name: '@astrojs/cloudflare' }, + }, + command: 'build', + }); + + expect(sentryCloudflareVitePlugin).toHaveBeenCalledWith({ importServerInit: true }); + }); + + it('does not import the default server init at the Worker entry', async () => { + const integration = sentryAstro({}); + + // @ts-expect-error - the hook exists and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ + ...baseConfigHookObject, + config: { + // @ts-expect-error - we only need to pass what we actually use + adapter: { name: '@astrojs/cloudflare' }, + }, + command: 'build', + }); + + expect(sentryCloudflareVitePlugin).toHaveBeenCalledWith({ importServerInit: false }); + }); + it('adds Cloudflare Vite plugins when no wrangler config exists', async () => { getWranglerConfig.mockReturnValue(null); @@ -104,6 +137,29 @@ describe('Cloudflare Pages vs Workers detection', () => { }); describe('Cloudflare Pages (with pages_build_output_dir)', () => { + it('imports the user server config at the Worker entry', async () => { + getWranglerConfig.mockReturnValue({ + filename: 'wrangler.json', + content: JSON.stringify({ + pages_build_output_dir: './dist', + }), + }); + + const integration = sentryAstro({ serverInitPath: 'sentry.server.config.js' }); + + // @ts-expect-error - the hook exists and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ + ...baseConfigHookObject, + config: { + // @ts-expect-error - we only need to pass what we actually use + adapter: { name: '@astrojs/cloudflare' }, + }, + command: 'build', + }); + + expect(sentryCloudflareVitePlugin).toHaveBeenCalledWith({ importServerInit: true }); + }); + it('does not show warning for Pages project with wrangler.json', async () => { getWranglerConfig.mockReturnValue({ filename: 'wrangler.json', diff --git a/packages/astro/test/integration/cloudflareVitePlugin.test.ts b/packages/astro/test/integration/cloudflareVitePlugin.test.ts index 0464acd321e2..d72e74d6a962 100644 --- a/packages/astro/test/integration/cloudflareVitePlugin.test.ts +++ b/packages/astro/test/integration/cloudflareVitePlugin.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; import { sentryCloudflareVitePlugin } from '../../src/integration/cloudflare'; -function transform(code: string, id: string) { - const plugin = sentryCloudflareVitePlugin() as { transform: (code: string, id: string) => unknown }; +function transform(code: string, id: string, options?: { importServerInit?: boolean }) { + const plugin = sentryCloudflareVitePlugin(options) as { transform: (code: string, id: string) => unknown }; return plugin.transform(code, id); } @@ -42,6 +42,20 @@ describe('sentryCloudflareVitePlugin', () => { }); }); + it('imports the server init above the wrap when asked to', () => { + const code = ['const _exports = createExports(manifest);', 'export default _exports.default;'].join('\n'); + + expect(transform(code, '\0@astrojs-ssr-virtual-entry', { importServerInit: true })).toEqual({ + code: [ + 'import "virtual:@sentry/astro/server-init";', + "import { withSentry } from '@sentry/cloudflare';", + 'const _exports = createExports(manifest);', + 'export default withSentry(() => undefined, _exports.default);', + ].join('\n'), + map: null, + }); + }); + it('leaves other modules alone', () => { expect(transform('export default handler;', '/src/pages/index.astro')).toBeUndefined(); }); diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts index fd9f0dc2a139..2c4b625b86e9 100644 --- a/packages/astro/test/server/middleware.test.ts +++ b/packages/astro/test/server/middleware.test.ts @@ -3,7 +3,6 @@ import type { Client, Span } from '@sentry/core'; import * as SentryCore from '@sentry/core'; import * as SentryCoreServer from '@sentry/core/server'; -import * as SentryNode from '@sentry/node'; import type { APIContext } from 'astro'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { handleRequest, interpolateRouteFromUrlAndParams } from '../../src/server/middleware'; @@ -36,7 +35,7 @@ const STATIC_REQUEST_CONTEXT = { describe('sentryMiddleware with the managed tunnel', () => { it('answers tunnel requests without calling the rest of the middleware chain', async () => { - const getClientSpy = vi.spyOn(SentryNode, 'getClient').mockReturnValue({} as Client); + const getClientSpy = vi.spyOn(SentryCore, 'getClient').mockReturnValue({} as Client); const tunnelResponse = new Response('forwarded'); const matcherSpy = vi .spyOn(SentryCoreServer, '_INTERNAL_handleServedTunnelRequest') @@ -56,7 +55,7 @@ describe('sentryMiddleware with the managed tunnel', () => { }); describe('sentryMiddleware', () => { - const startSpanSpy = vi.spyOn(SentryNode, 'startSpan'); + const startSpanSpy = vi.spyOn(SentryCore, 'startSpan'); const getSpanMock = vi.fn(() => { return { @@ -83,7 +82,7 @@ describe('sentryMiddleware', () => { }; function mockClientWith(dataCollection: Partial): void { - vi.spyOn(SentryNode, 'getClient').mockImplementation( + vi.spyOn(SentryCore, 'getClient').mockImplementation( () => ({ getOptions: () => ({}), @@ -93,7 +92,7 @@ describe('sentryMiddleware', () => { } beforeEach(() => { - vi.spyOn(SentryNode, 'getCurrentScope').mockImplementation(() => { + vi.spyOn(SentryCore, 'getCurrentScope').mockImplementation(() => { return { setPropagationContext: vi.fn(), getSpan: getSpanMock, @@ -101,9 +100,9 @@ describe('sentryMiddleware', () => { getPropagationContext: () => ({}), } as any; }); - vi.spyOn(SentryNode, 'getActiveSpan').mockImplementation(getSpanMock); + vi.spyOn(SentryCore, 'getActiveSpan').mockImplementation(getSpanMock); mockClientWith({ userInfo: false }); - vi.spyOn(SentryNode, 'getTraceMetaTags').mockImplementation( + vi.spyOn(SentryCore, 'getTraceMetaTags').mockImplementation( () => ` @@ -171,7 +170,7 @@ describe('sentryMiddleware', () => { } beforeEach(() => { - vi.spyOn(SentryNode, 'getClient').mockImplementation( + vi.spyOn(SentryCore, 'getClient').mockImplementation( () => ({ getOptions: () => ({ traceLifecycle: 'stream' }), @@ -266,7 +265,7 @@ describe('sentryMiddleware', () => { }); it('throws and sends an error to sentry if `next()` throws', async () => { - const captureExceptionSpy = vi.spyOn(SentryNode, 'captureException'); + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); const middleware = handleRequest(); const ctx = { @@ -288,7 +287,7 @@ describe('sentryMiddleware', () => { }); it('throws and sends an error to sentry if response streaming throws', async () => { - const captureExceptionSpy = vi.spyOn(SentryNode, 'captureException'); + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); const middleware = handleRequest(); const ctx = { @@ -470,7 +469,7 @@ describe('sentryMiddleware', () => { }); it('injects routing tag into the HTML of a pageload response without Sentry being initialized', async () => { - vi.spyOn(SentryNode, 'getClient').mockImplementation(() => undefined); + vi.spyOn(SentryCore, 'getClient').mockImplementation(() => undefined); const middleware = handleRequest(); @@ -658,7 +657,7 @@ describe('sentryMiddleware', () => { }); describe('async context isolation', () => { - const withIsolationScopeSpy = vi.spyOn(SentryNode, 'withIsolationScope'); + const withIsolationScopeSpy = vi.spyOn(SentryCore, 'withIsolationScope'); afterEach(() => { vi.clearAllMocks(); withIsolationScopeSpy.mockRestore(); @@ -716,10 +715,10 @@ describe('sentryMiddleware', () => { }); describe('parametrized route resolution', () => { - const startSpanSpy = vi.spyOn(SentryNode, 'startSpan'); + const startSpanSpy = vi.spyOn(SentryCore, 'startSpan'); beforeEach(() => { - vi.spyOn(SentryNode, 'getCurrentScope').mockImplementation( + vi.spyOn(SentryCore, 'getCurrentScope').mockImplementation( () => ({ setPropagationContext: vi.fn(), @@ -728,15 +727,15 @@ describe('parametrized route resolution', () => { getPropagationContext: () => ({}), }) as any, ); - vi.spyOn(SentryNode, 'getActiveSpan').mockImplementation(() => undefined); - vi.spyOn(SentryNode, 'getClient').mockImplementation( + vi.spyOn(SentryCore, 'getActiveSpan').mockImplementation(() => undefined); + vi.spyOn(SentryCore, 'getClient').mockImplementation( () => ({ getOptions: () => ({}), getDataCollectionOptions: () => ({ httpHeaders: { request: false, response: false } }), }) as unknown as Client, ); - vi.spyOn(SentryNode, 'getTraceMetaTags').mockImplementation(() => ''); + vi.spyOn(SentryCore, 'getTraceMetaTags').mockImplementation(() => ''); }); afterEach(() => { diff --git a/packages/astro/test/worker/sdk.test.ts b/packages/astro/test/worker/sdk.test.ts new file mode 100644 index 000000000000..f5f2e4bbb6b3 --- /dev/null +++ b/packages/astro/test/worker/sdk.test.ts @@ -0,0 +1,47 @@ +import { CloudflareClient, SDK_VERSION } from '@sentry/cloudflare'; +import { getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { init, setBindingsGetter } from '../../src/worker/sdk'; + +describe('Sentry worker SDK', () => { + afterEach(() => { + getMainCarrier().__SENTRY__ = undefined; + setBindingsGetter(undefined); + }); + + it('initializes a Cloudflare client with Astro metadata', () => { + const client = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', cacheClient: false }); + + expect(client).toBeInstanceOf(CloudflareClient); + expect(client?.getOptions()._metadata?.sdk).toEqual({ + name: 'sentry.javascript.astro', + version: SDK_VERSION, + packages: [ + { name: 'npm:@sentry/astro', version: SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SDK_VERSION }, + ], + }); + }); + + it('fills options the user left unset from the bindings', () => { + setBindingsGetter(() => ({ + SENTRY_DSN: 'https://binding@dsn.ingest.sentry.io/1', + SENTRY_ENVIRONMENT: 'from-binding', + })); + + const client = init({ environment: 'from-options', cacheClient: false }); + + expect(client?.getOptions()).toMatchObject({ + dsn: 'https://binding@dsn.ingest.sentry.io/1', + environment: 'from-options', + }); + }); + + it('keeps the DSN the user passed over the binding', () => { + setBindingsGetter(() => ({ SENTRY_DSN: 'https://binding@dsn.ingest.sentry.io/1' })); + + const client = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', cacheClient: false }); + + expect(client?.getOptions().dsn).toBe('https://public@dsn.ingest.sentry.io/1337'); + }); +}); diff --git a/packages/astro/tsconfig.test.json b/packages/astro/tsconfig.test.json index da5a816712e3..e4039ad88d84 100644 --- a/packages/astro/tsconfig.test.json +++ b/packages/astro/tsconfig.test.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig.json", - "include": ["test/**/*"], + "include": ["test/**/*", "src/worker/cloudflareWorkers.d.ts"], "compilerOptions": { // should include all types from `./tsconfig.json` plus types for all test frameworks used diff --git a/packages/cloudflare/src/client.ts b/packages/cloudflare/src/client.ts index 8f3c1acea394..d39ea08837f6 100644 --- a/packages/cloudflare/src/client.ts +++ b/packages/cloudflare/src/client.ts @@ -39,6 +39,10 @@ export class CloudflareClient extends ServerRuntimeClient { // and must not each start their own eager transport flush. private _inBoundaryFlush = false; + // Eager drains still sending. Outside an instrumented invocation (e.g. Astro on Pages) they have no `waitUntil`, + // so `flush()` awaits them, or the response can end first and the runtime cancels their fetches. + private readonly _pendingEagerDrains = new Set>(); + /** * Whether this client is a cached, cross-invocation client (`cacheClient`). * Cached clients are never disposed at an invocation boundary, so their spans/events @@ -172,11 +176,17 @@ export class CloudflareClient extends ServerRuntimeClient { // envelopes on the `flush` emit) ride its own transport drain; without the flag each // of them would also start an eager drain and a `waitUntil` registration. this._inBoundaryFlush = true; + let flushed: boolean; try { - return await super.flush(timeout); + flushed = await super.flush(timeout); } finally { this._inBoundaryFlush = false; } + + // Each eager drain is bounded by its own transport flush timeout. + await Promise.all(this._pendingEagerDrains); + + return flushed; } /** @@ -321,9 +331,16 @@ export class CloudflareClient extends ServerRuntimeClient { * Attaches a promise to the `waitUntil` of the invocation that owns the current * async context, so the runtime keeps the send alive after the response is returned. * Outside any instrumented invocation (or where the context has no `waitUntil`, - * e.g. Astro prerendering) the send is fire-and-forget. + * e.g. Astro prerendering) only the next `flush()` waits for the send. */ private _registerWithInvocationWaitUntil(promise: PromiseLike): void { + const pending = Promise.resolve(promise).then( + () => undefined, + () => undefined, + ); + this._pendingEagerDrains.add(pending); + void pending.then(() => this._pendingEagerDrains.delete(pending)); + const invocationState = getInvocationState(); const waitUntil = invocationState && getInvocationWaitUntil(invocationState); if (!waitUntil) { @@ -331,12 +348,7 @@ export class CloudflareClient extends ServerRuntimeClient { } try { - waitUntil( - Promise.resolve(promise).then( - () => undefined, - () => undefined, - ), - ); + waitUntil(pending); } catch { // The owning invocation already ended; the send races isolate teardown either way. } diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts index 60a32d7c5bbf..53f571f5010a 100644 --- a/packages/cloudflare/src/index.ts +++ b/packages/cloudflare/src/index.ts @@ -130,7 +130,8 @@ export { _INTERNAL_wrapUnlessInstrumented } from './instrument'; export { sentryPagesPlugin } from './pages-plugin'; export { CloudflareClient } from './client'; -export { _INTERNAL_wrapRequestHandler, getDefaultIntegrations } from './sdk'; +export { _INTERNAL_wrapRequestHandler, getDefaultIntegrations, init as _INTERNAL_init } from './sdk'; +export { getFinalOptions as _INTERNAL_getFinalOptions } from './options'; export { httpServerIntegration } from './integrations/httpServer'; export { fetchIntegration } from './integrations/fetch'; diff --git a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts index ad401f761d1f..76470db655f4 100644 --- a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts +++ b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts @@ -2,7 +2,10 @@ import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/work import { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/conventions/attributes'; import type { SpanAttributes } from '@sentry/core'; import { getIsolationScope, safeCallback } from '@sentry/core'; -import { _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest } from '@sentry/core/server'; +import { + _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, + _INTERNAL_setScopeFlushedByRuntime as setScopeFlushedByRuntime, +} from '@sentry/core/server'; import { wrapServerRequestHandler } from '@sentry/server-utils/request-handler'; import { DEBUG_BUILD } from './debug-build'; import { getHttpServerRequestOptions } from './integrations/httpServer'; @@ -72,6 +75,12 @@ export function wrapRequestHandlerWithInit( const client = initSdk({ ...options, ctx: context }); isolationScope.setClient(client); + // This wrap flushes through `waitUntil` once the response is sent, so a framework's own `flushIfServerless()` + // (e.g. the Astro middleware on Pages) would only hold the response for a flush that is coming anyway. + if (waitUntil) { + setScopeFlushedByRuntime(isolationScope); + } + // Emit any orchestrion channel events deferred at module scope (e.g. a top-level // `const app = new Hono()` wrapped by build-time instrumentation): we're now in a // request, where workerd allows publish, and init() above has registered subscribers. diff --git a/packages/cloudflare/test/client.test.ts b/packages/cloudflare/test/client.test.ts index 27d0eae75835..808e131f15d8 100644 --- a/packages/cloudflare/test/client.test.ts +++ b/packages/cloudflare/test/client.test.ts @@ -497,6 +497,34 @@ describe('CloudflareClient', () => { expect(flushMock).toHaveBeenCalledTimes(1); }); + // The transport's drain hands its queued requests off and doesn't track them, so the transport drain inside + // `flush()` finds an empty queue while the eager drain's request is still in flight. + it('waits in flush() for a request an eager drain started outside any invocation', async () => { + let respond: () => void = () => undefined; + const fetch = vi.fn(() => new Promise(resolve => (respond = () => resolve(new Response(''))))); + const client = new CloudflareClient({ + ...MOCK_CLIENT_OPTIONS, + cacheClient: true, + transport: makeCloudflareTransport, + transportOptions: { fetch }, + }); + client.init(); + + client.captureMessage('foo'); + await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1)); + + const flushPromise = client.flush(2000); + const settled = await Promise.race([ + flushPromise.then(() => 'flushed'), + new Promise(resolve => setTimeout(() => resolve('pending'), 100)), + ]); + expect(settled).toBe('pending'); + + respond(); + await expect(flushPromise).resolves.toBe(true); + expect(fetch).toHaveBeenCalledTimes(1); + }); + it('does not register a waitUntil when no context is known', () => { const flushMock = vi.fn().mockResolvedValue(true); const client = makeEagerFlushClient(flushMock); diff --git a/packages/cloudflare/test/request.test.ts b/packages/cloudflare/test/request.test.ts index d05ad7420d44..aba83d5f66c3 100644 --- a/packages/cloudflare/test/request.test.ts +++ b/packages/cloudflare/test/request.test.ts @@ -4,6 +4,7 @@ import type { ExecutionContext } from '@cloudflare/workers-types'; import type { Event } from '@sentry/core'; import * as SentryCore from '@sentry/core'; +import { flushIfServerless } from '@sentry/core/server'; import { beforeAll, beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest'; import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels'; import type { CloudflareOptions } from '../src/client'; @@ -160,6 +161,20 @@ describe('withSentry', () => { expect(delta).toBe(1); }); + test("skips a framework's flushIfServerless() inside the request, since the wrap flushes after the response", async () => { + const cloudflareWaitUntil = vi.fn(); + + await wrapRequestHandler( + { options: MOCK_OPTIONS, request: new Request('https://example.com'), context: createMockExecutionContext() }, + async () => { + await flushIfServerless({ cloudflareWaitUntil }); + return new Response('test'); + }, + ); + + expect(cloudflareWaitUntil).not.toHaveBeenCalled(); + }); + describe('scope instrumentation', () => { test('adds cloud resource context', async () => { let sentryEvent: Event = {}; diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 76e802fdfe67..f7f74af63dee 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -39,7 +39,10 @@ export { getReleaseFromCommitEnv as _INTERNAL_getReleaseFromCommitEnv, readCommitEnvVar as _INTERNAL_readCommitEnvVar, } from './utils/commitEnv'; -export { flushIfServerless } from './utils/flushIfServerless'; +export { + flushIfServerless, + setScopeFlushedByRuntime as _INTERNAL_setScopeFlushedByRuntime, +} from './utils/flushIfServerless'; export { callFrameToStackFrame, watchdogTimer } from './utils/anr'; export { safeUnref as _INTERNAL_safeUnref } from './utils/timer'; export { patchHttpModuleClient } from './integrations/http/client-patch'; diff --git a/packages/core/src/utils/flushIfServerless.ts b/packages/core/src/utils/flushIfServerless.ts index 5ffd86612243..d5a63749eb34 100644 --- a/packages/core/src/utils/flushIfServerless.ts +++ b/packages/core/src/utils/flushIfServerless.ts @@ -1,4 +1,7 @@ +import { getIsolationScope } from '../currentScopes'; +import { getDefaultIsolationScope } from '../defaultScopes'; import { flush } from '../exports'; +import type { Scope } from '../scope'; import { debug } from './debug-logger'; import { vercelWaitUntil } from './vercelWaitUntil'; import { GLOBAL_OBJ } from './worldwide'; @@ -8,6 +11,32 @@ type MinimalCloudflareContext = { waitUntil(promise: Promise): void; }; +/** + * Marks a request's isolation scope whose events a runtime wrapper flushes once the response is sent. A shared symbol, + * so `flushIfServerless()` sees it without depending on the wrapper's package. + */ +const FLUSHED_BY_RUNTIME: unique symbol = Symbol.for('sentry.flushedByRuntime'); + +type ScopeRefsWithFlushedByRuntime = Scope['refs'] & { + [FLUSHED_BY_RUNTIME]?: boolean; +}; + +/** + * Tells `flushIfServerless()` to skip the flush for the request that owns `scope`, because a runtime wrapper (such as + * the Cloudflare `withSentry` wrap) flushes its events once the response is sent. Forked scopes keep the mark. + * + * The default isolation scope is shared by every request, so it is never marked. + * + * @internal + */ +export function setScopeFlushedByRuntime(scope: Scope): void { + if (scope === getDefaultIsolationScope()) { + return; + } + + (scope.refs as ScopeRefsWithFlushedByRuntime)[FLUSHED_BY_RUNTIME] = true; +} + async function flushWithTimeout(timeout: number): Promise { try { debug.log('Flushing events...'); @@ -31,6 +60,8 @@ async function flushWithTimeout(timeout: number): Promise { * - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables * and uses a regular `await flush()`. * + * It does nothing for a request whose scope is marked with `setScopeFlushedByRuntime()`. + * * @internal This function is supposed for internal Sentry SDK usage only. * @hidden */ @@ -41,6 +72,10 @@ export async function flushIfServerless( ): Promise { const { timeout = 2000 } = params; + if ((getIsolationScope().refs as ScopeRefsWithFlushedByRuntime)[FLUSHED_BY_RUNTIME]) { + return; + } + if ('cloudflareWaitUntil' in params && typeof params?.cloudflareWaitUntil === 'function') { params.cloudflareWaitUntil(flushWithTimeout(timeout)); return; diff --git a/packages/core/test/lib/utils/flushIfServerless.test.ts b/packages/core/test/lib/utils/flushIfServerless.test.ts index aa0314f183dc..4a60628a3ea4 100644 --- a/packages/core/test/lib/utils/flushIfServerless.test.ts +++ b/packages/core/test/lib/utils/flushIfServerless.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import * as flushModule from '../../../src/exports'; -import { flushIfServerless } from '../../../src/utils/flushIfServerless'; +import * as currentScopesModule from '../../../src/currentScopes'; +import { getDefaultIsolationScope } from '../../../src/defaultScopes'; +import { Scope } from '../../../src/scope'; +import { flushIfServerless, setScopeFlushedByRuntime } from '../../../src/utils/flushIfServerless'; import * as vercelWaitUntilModule from '../../../src/utils/vercelWaitUntil'; import { GLOBAL_OBJ } from '../../../src/utils/worldwide'; @@ -125,4 +128,45 @@ describe('flushIfServerless', () => { expect(flushMock).toHaveBeenCalledWith(0); }); + + test('skips the flush for a request whose scope a runtime wrapper flushes', async () => { + const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true); + const cloudflareWaitUntil = vi.fn(); + + global.process = { + ...originalProcess, + env: { + ...originalProcess.env, + CF_PAGES: '1', + }, + }; + + // The default async context strategy never forks the isolation scope, so the request's scope is mocked. + const requestScope = new Scope(); + setScopeFlushedByRuntime(requestScope); + vi.spyOn(currentScopesModule, 'getIsolationScope').mockReturnValue(requestScope.clone()); + + await flushIfServerless(); + await flushIfServerless({ cloudflareWaitUntil }); + + expect(cloudflareWaitUntil).not.toHaveBeenCalled(); + expect(flushMock).not.toHaveBeenCalled(); + }); + + test('does not mark the default isolation scope, which every request shares', async () => { + const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true); + + global.process = { + ...originalProcess, + env: { + ...originalProcess.env, + CF_PAGES: '1', + }, + }; + + setScopeFlushedByRuntime(getDefaultIsolationScope()); + await flushIfServerless(); + + expect(flushMock).toHaveBeenCalledWith(2000); + }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 506b1339f5f6..81ea1f3d7a5b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1005,6 +1005,9 @@ importers: '@sentry/bundler-plugins': specifier: 11.12.0 version: link:../bundler-plugins + '@sentry/cloudflare': + specifier: 11.12.0 + version: link:../cloudflare '@sentry/conventions': specifier: ^0.32.0 version: 0.32.0 From 44a908134b93148aca6dd038c0f035d452537c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Beteg=C3=B3n?= Date: Wed, 11 Nov 2026 07:36:25 +0100 Subject: [PATCH 011/136] feat(core): capture MCP OAuth client names per request (#24508) OAuth registration can identify a different application from MCP `clientInfo`, but transport `AuthInfo` has no standard client name. Add an opt-in `getOAuthClientName` resolver that records the registered name as `mcp.auth.client.name`, independently of `mcp.client.name`. For example, when a registered application named `Example Desktop` connects through a client identifying as `example-connector`, before the span contains only `mcp.client.name = "example-connector"`. After configuring the resolver, it also contains `mcp.auth.client.name = "Example Desktop"`. Resolve the name once per incoming request, including discovery and unsupported methods. The callback receives `clientId` and application-defined `extra` metadata when available and may read request-scoped authentication context. Only the returned name is recorded; resolver failures leave dispatch intact. Preserve the wrapper's existing first-explicit-value option behavior. Real HTTP coverage exercises both MCP SDK majors in ESM/CJS, concurrent requests, and missing identities. #25059 is merged; this branch is rebased on develop and imports `MCP_AUTH_CLIENT_NAME` from published `@sentry/conventions@0.27.0`. The conventions publication blocker is resolved. This identity distinction follows [MCP client registration](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration). Network metadata (#24506) and canonical attributes (#25060) remain separate changes. Validated the 48-project SDK build, formatting and lint, 151 MCP unit tests, and ten real MCP SDK v1/v2 integration tests after rebase. --- .../mcp-server-oauth-client/instrument.mjs | 8 ++ .../mcp-server-oauth-client/scenario-v1.mjs | 77 +++++++++++ .../mcp-server-oauth-client/scenario-v2.mjs | 75 ++++++++++ .../tracing/mcp-server-oauth-client/test.ts | 79 +++++++++++ .../test/core/build-plugin-manager.test.ts | 4 +- .../core/src/integrations/mcp-server/index.ts | 32 +++-- .../src/integrations/mcp-server/transport.ts | 29 +++- .../core/src/integrations/mcp-server/types.ts | 17 ++- .../mcp-server/oauthClient.test.ts | 129 ++++++++++++++++++ 9 files changed, 436 insertions(+), 14 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/instrument.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v1.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v2.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/test.ts create mode 100644 packages/core/test/lib/integrations/mcp-server/oauthClient.test.ts diff --git a/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/instrument.mjs new file mode 100644 index 000000000000..0b914a70f157 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/instrument.mjs @@ -0,0 +1,8 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + transport: loggingTransport, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v1.mjs b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v1.mjs new file mode 100644 index 000000000000..bf1d0d41cefa --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v1.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import { AsyncLocalStorage } from 'node:async_hooks'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'; +import { startSpan, wrapMcpServerWithSentry } from '@sentry/node'; + +const requestContext = new AsyncLocalStorage(); +let resolverCalls = 0; +const server = wrapMcpServerWithSentry(new McpServer({ name: 'test-server', version: '1.0.0' }), { + getOAuthClientName(authInfo) { + resolverCalls++; + return authInfo?.extra?.clientName ?? requestContext.getStore(); + }, +}); +server.registerTool('echo', {}, async () => ({ content: [{ type: 'text', text: 'ok' }] })); +const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: () => 'test-session', + enableJsonResponse: true, +}); + +async function request(id, method, clientName, contextName) { + const params = + method === 'initialize' + ? { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'protocol-v1', version: '1.0.0' } } + : {}; + const response = await requestContext.run(contextName, async () => { + await new Promise(resolve => setImmediate(resolve)); + return transport.handleRequest( + new Request('https://example.test/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2025-11-25', + ...(method !== 'initialize' && { 'Mcp-Session-Id': 'test-session' }), + }, + body: JSON.stringify({ jsonrpc: '2.0', id, method, params }), + }), + { + authInfo: clientName + ? { clientId: id, token: 'test-token', scopes: ['test-scope'], extra: { clientName } } + : undefined, + }, + ); + }); + if (id === undefined) { + assert.equal(response.status, 202); + return; + } + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.id, id); + if (method === 'resources/list') { + assert.equal(body.error.code, -32601); + } else { + assert.equal(body.error, undefined); + if (method === 'tools/list') { + assert.equal(body.result.tools[0].name, 'echo'); + } else { + assert.equal(body.result.protocolVersion, '2025-11-25'); + } + } +} + +startSpan({ name: 'oauth requests' }, async span => { + await server.connect(transport); + await request('discovery', 'initialize', 'Registered Discovery'); + await request(undefined, 'notifications/initialized', 'Notification Client'); + await Promise.all([ + request('context', 'tools/list', undefined, 'Registered Context'), + request('unsupported', 'resources/list', 'Registered Unsupported'), + request('missing', 'tools/list'), + ]); + assert.equal(resolverCalls, 4); + await server.close(); + span.setAttribute('test.responses.checked', true); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v2.mjs b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v2.mjs new file mode 100644 index 000000000000..0df551b95637 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/scenario-v2.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import { AsyncLocalStorage } from 'node:async_hooks'; +import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'; +import { startSpan, wrapMcpServerWithSentry } from '@sentry/node'; + +const requestContext = new AsyncLocalStorage(); +let resolverCalls = 0; +const handler = createMcpHandler(async () => { + await new Promise(resolve => setImmediate(resolve)); + const server = wrapMcpServerWithSentry(new McpServer({ name: 'test-server', version: '1.0.0' }), { + getOAuthClientName(authInfo) { + resolverCalls++; + return authInfo?.extra?.clientName ?? requestContext.getStore(); + }, + }); + server.registerTool('echo', {}, async () => ({ content: [{ type: 'text', text: 'ok' }] })); + return server; +}); + +async function request(id, method, clientName, contextName) { + const params = { + _meta: { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': {}, + ...(id !== 'missing' && { + 'io.modelcontextprotocol/clientInfo': { name: `protocol-${id}`, version: '1.0.0' }, + }), + }, + }; + const response = await requestContext.run(contextName, () => + handler.fetch( + new Request('https://example.test/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2026-07-28', + 'MCP-Method': method, + }, + body: JSON.stringify({ jsonrpc: '2.0', id, method, params }), + }), + { + authInfo: clientName + ? { clientId: id, token: 'test-token', scopes: ['test-scope'], extra: { clientName } } + : undefined, + }, + ), + ); + const body = await response.json(); + assert.equal(body.id, id); + if (method === 'resources/list') { + assert.equal(response.status, 404); + assert.equal(body.error.code, -32601); + } else { + assert.equal(response.status, 200); + assert.equal(body.error, undefined); + if (method === 'tools/list') { + assert.equal(body.result.tools[0].name, 'echo'); + } else { + assert.ok(body.result.supportedVersions.includes('2026-07-28')); + } + } +} + +startSpan({ name: 'oauth requests' }, async span => { + await Promise.all([ + request('discovery', 'server/discover', 'Registered Discovery'), + request('context', 'tools/list', undefined, 'Registered Context'), + request('unsupported', 'resources/list', 'Registered Unsupported'), + request('missing', 'tools/list'), + ]); + assert.equal(resolverCalls, 4); + await handler.close(); + span.setAttribute('test.responses.checked', true); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/test.ts b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/test.ts new file mode 100644 index 000000000000..186bb191e60d --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/mcp-server-oauth-client/test.ts @@ -0,0 +1,79 @@ +import { + MCP_AUTH_CLIENT_NAME, + MCP_CLIENT_NAME, + MCP_METHOD_NAME, + MCP_REQUEST_ID, + SENTRY_OP, +} from '@sentry/conventions/attributes'; +import { MCP_SERVER } from '@sentry/conventions/op'; +import { afterAll, describe, expect } from 'vitest'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +describe('MCP OAuth client attribution', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + for (const { version, expectedRequests, additionalDependencies } of [ + { + version: 'v1', + expectedRequests: [ + ['discovery', 'initialize', 'Registered Discovery', 'protocol-v1'], + ['context', 'tools/list', 'Registered Context', 'protocol-v1'], + ['unsupported', 'resources/list', 'Registered Unsupported', 'protocol-v1'], + ['missing', 'tools/list', undefined, 'protocol-v1'], + ], + additionalDependencies: { '@modelcontextprotocol/sdk': '1.30.0' }, + }, + { + version: 'v2', + expectedRequests: [ + ['discovery', 'server/discover', 'Registered Discovery', 'protocol-discovery'], + ['context', 'tools/list', 'Registered Context', 'protocol-context'], + ['unsupported', 'resources/list', 'Registered Unsupported', 'protocol-unsupported'], + ['missing', 'tools/list', undefined, undefined], + ], + }, + ]) { + createEsmAndCjsTests( + __dirname, + `scenario-${version}.mjs`, + 'instrument.mjs', + (createTestRunner, test) => { + test(`keeps ${version} OAuth identity request-local and separate from MCP identity`, async () => { + const runner = createTestRunner(); + const spansPromise = runner.collectStreamedSpans( + spans => + spans.some(span => span.is_segment && span.name === 'oauth requests') && + expectedRequests.every(([id]) => + spans.some( + span => + span.attributes[SENTRY_OP]?.value === MCP_SERVER && span.attributes[MCP_REQUEST_ID]?.value === id, + ), + ), + ); + + await runner.start().completed(); + + const spans = await spansPromise; + const root = spans.find(span => span.is_segment && span.name === 'oauth requests'); + expect(root?.attributes['test.responses.checked']?.value).toBe(true); + const requests = spans.filter( + span => span.attributes[SENTRY_OP]?.value === MCP_SERVER && span.attributes[MCP_REQUEST_ID], + ); + expect(requests).toHaveLength(expectedRequests.length); + expect( + requests.map(({ attributes }) => [ + attributes[MCP_REQUEST_ID]?.value, + attributes[MCP_METHOD_NAME]?.value, + attributes[MCP_AUTH_CLIENT_NAME]?.value, + attributes[MCP_CLIENT_NAME]?.value, + ]), + ).toEqual(expect.arrayContaining(expectedRequests)); + expect(JSON.stringify(spans)).not.toContain('Notification Client'); + }); + }, + { additionalDependencies }, + ); + } +}); diff --git a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts index 4ccd00652c0b..5349777dfc2b 100644 --- a/packages/bundler-plugins/test/core/build-plugin-manager.test.ts +++ b/packages/bundler-plugins/test/core/build-plugin-manager.test.ts @@ -367,7 +367,7 @@ describe('createSentryBuildPluginManager', () => { expect(warnSpy).toHaveBeenCalledOnce(); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(' - .next/server\n')); expect(infoSpy).toHaveBeenCalledWith('Successfully uploaded source maps to Sentry'); - expect(result).toEqual({ uploaded: true }); + expect(result).toEqual({ uploaded: true, uploadedSourceMapPaths: [] }); vi.restoreAllMocks(); }); @@ -406,7 +406,7 @@ describe('createSentryBuildPluginManager', () => { const result = await manager.uploadSourcemaps(['.next/server'], { prepareArtifacts: false }); expect(infoSpy).not.toHaveBeenCalledWith('Successfully uploaded source maps to Sentry'); - expect(result).toEqual({ uploaded: false }); + expect(result).toEqual({ uploaded: false, uploadedSourceMapPaths: [] }); vi.restoreAllMocks(); }); diff --git a/packages/core/src/integrations/mcp-server/index.ts b/packages/core/src/integrations/mcp-server/index.ts index af02f2703462..ebea8edd74f6 100644 --- a/packages/core/src/integrations/mcp-server/index.ts +++ b/packages/core/src/integrations/mcp-server/index.ts @@ -5,7 +5,7 @@ import type { MCPServerInstance, McpServerWrapperOptions, MCPTransport } from '. import { validateMcpServerInstance } from './validation'; /** - * Maps each wrapped MCP server instance to the mutable capture options that the transport + * Maps each wrapped MCP server instance to the mutable instrumentation options that the transport * instrumentation reads (per message). Prevents double-wrapping while still letting a later * `wrapMcpServerWithSentry` fill in options left unset by an earlier wrap — e.g. an auto-wrap at * construction installs no explicit options, so a manual override still applies. @@ -14,8 +14,8 @@ import { validateMcpServerInstance } from './validation'; const wrappedMcpServerOptions = new WeakMap(); /** - * Fill in capture options not explicitly set by an earlier wrap. Only unset fields are written, so - * the first explicit `recordInputs`/`recordOutputs` wins, but an auto-wrap that set neither still + * Fill in options not explicitly set by an earlier wrap. Only unset fields are written, so + * the first explicit value wins, but an auto-wrap that set no options still * yields to a later manual override. Mutating the stored object updates the live transport * instrumentation, which reads it per message. */ @@ -29,6 +29,9 @@ function applyMissingMcpOptions(target: McpServerWrapperOptions, source: McpServ if (target.recordOutputs === undefined && source.recordOutputs !== undefined) { target.recordOutputs = source.recordOutputs; } + if (target.getOAuthClientName === undefined && source.getOAuthClientName !== undefined) { + target.getOAuthClientName = source.getOAuthClientName; + } } function instrumentTransport(transport: MCPTransport, options: McpServerWrapperOptions): void { @@ -117,8 +120,8 @@ function interceptTransportStart(transport: MCPTransport, beforeStart: () => voi * convention (consistent with other SDK integrations), but is not required. * * Calling this more than once on the same instance never patches it twice. Options behave like a - * snapshot from the first *explicit* wrap: the first `recordInputs`/`recordOutputs` value set for a - * field wins, but a field left unset can still be filled by a later call. So when the SDK auto-wraps + * snapshot from the first *explicit* wrap: the first value set for each option wins, + * but a field left unset can still be filled by a later call. So when the SDK auto-wraps * the server at construction (via the `mcpServer` integration) with no explicit options, a later * manual `wrapMcpServerWithSentry(server, { recordInputs, recordOutputs })` still applies. * @@ -145,8 +148,19 @@ function interceptTransportStart(transport: MCPTransport, beforeStart: () => voi * await server.connect(transport); * ``` * + * @example + * ```typescript + * // Read application-defined metadata supplied by the authentication middleware. + * const server = Sentry.wrapMcpServerWithSentry(mcpServer, { + * getOAuthClientName: authInfo => { + * const name = authInfo?.extra?.clientName; + * return typeof name === 'string' ? name : undefined; + * }, + * }); + * ``` + * * @param mcpServerInstance - MCP server instance to instrument - * @param options - Optional configuration for recording inputs and outputs + * @param options - Optional configuration for recording inputs/outputs and OAuth client attribution * @returns Instrumented server instance (same reference) */ export function wrapMcpServerWithSentry(mcpServerInstance: S, options?: McpServerWrapperOptions): S { @@ -161,8 +175,8 @@ export function wrapMcpServerWithSentry(mcpServerInstance: S, } const serverInstance = mcpServerInstance as MCPServerInstance; - const captureOptions: McpServerWrapperOptions = { ...options }; - wrappedMcpServerOptions.set(mcpServerInstance, captureOptions); + const wrapperOptions: McpServerWrapperOptions = { ...options }; + wrappedMcpServerOptions.set(mcpServerInstance, wrapperOptions); fill(serverInstance, 'connect', originalConnect => { return async function (this: MCPServerInstance, transport: MCPTransport, ...restArgs: unknown[]) { @@ -173,7 +187,7 @@ export function wrapMcpServerWithSentry(mcpServerInstance: S, } isTransportInstrumented = true; - instrumentTransport(transport, captureOptions); + instrumentTransport(transport, wrapperOptions); }; const restoreStart = interceptTransportStart(transport, instrumentTransportOnce); diff --git a/packages/core/src/integrations/mcp-server/transport.ts b/packages/core/src/integrations/mcp-server/transport.ts index 7c41f300d1c8..df0703128aef 100644 --- a/packages/core/src/integrations/mcp-server/transport.ts +++ b/packages/core/src/integrations/mcp-server/transport.ts @@ -5,12 +5,14 @@ * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports */ -import { MCP_PROTOCOL_VERSION } from '@sentry/conventions/attributes'; +import { MCP_AUTH_CLIENT_NAME, MCP_PROTOCOL_VERSION } from '@sentry/conventions/attributes'; import { getClient, getIsolationScope, withIsolationScope } from '../../currentScopes'; +import { DEBUG_BUILD } from '../../debug-build'; import { withActiveSpan } from '../../tracing'; import { startInactiveSpan } from '../../tracing/trace'; import { isObjectLike } from '../../utils/is'; import { fill } from '../../utils/object'; +import { safeCallback } from '../../utils/safeCallback'; import { cleanupPendingSpansForTransport, completeSpanWithResults, storeSpanForRequest } from './correlation'; import { captureError, isJsonRpcServerError } from './errorCapture'; import { buildClientAttributesFromInfo, extractSessionDataFromInitializeRequest } from './sessionExtraction'; @@ -39,12 +41,31 @@ function resolveMcpOptions(options: McpServerWrapperOptions): ResolvedMcpOptions }; } +/** Resolves only the OAuth client name; optional telemetry must not interrupt MCP dispatch. */ +function resolveOAuthClientName(options: McpServerWrapperOptions, extra?: ExtraHandlerData): string | undefined { + if (!options.getOAuthClientName) { + return undefined; + } + + const name = safeCallback( + DEBUG_BUILD ? 'The `getOAuthClientName` callback threw an error:' : '', + () => { + const authInfo = extra?.authInfo; + return options.getOAuthClientName?.( + authInfo ? { clientId: authInfo.clientId, extra: authInfo.extra } : undefined, + ); + }, + () => undefined, + ); + return typeof name === 'string' && name ? name : undefined; +} + /** * Wraps transport.onmessage to create spans for incoming messages. * Stores client info and protocol version only for legacy initialize requests. * Modern request metadata is read directly when building each message's span. * @param transport - MCP transport instance to wrap - * @param options - MCP capture overrides + * @param options - MCP instrumentation options */ export function wrapTransportOnMessage(transport: MCPTransport, options: McpServerWrapperOptions): void { if (transport.onmessage) { @@ -71,6 +92,10 @@ export function wrapTransportOnMessage(transport: MCPTransport, options: McpServ return withIsolationScope(isolationScope, () => { const spanConfig = buildMcpServerSpanConfig(request, transport, extra as ExtraHandlerData, resolvedOptions); + const oauthClientName = resolveOAuthClientName(options, extra as ExtraHandlerData); + if (oauthClientName) { + spanConfig.attributes[MCP_AUTH_CLIENT_NAME] = oauthClientName; + } const span = startInactiveSpan(spanConfig); if (request.method === 'initialize' && messageSessionData) { diff --git a/packages/core/src/integrations/mcp-server/types.ts b/packages/core/src/integrations/mcp-server/types.ts index 88c17eaf7be4..5a7ed20c92c3 100644 --- a/packages/core/src/integrations/mcp-server/types.ts +++ b/packages/core/src/integrations/mcp-server/types.ts @@ -146,6 +146,7 @@ export interface MCPServerInstance { /** Client connection information for handlers */ export interface ExtraHandlerData { + authInfo?: McpAuthInfo; requestInfo?: { remoteAddress?: string; remotePort?: number }; clientAddress?: string; clientPort?: number; @@ -235,10 +236,24 @@ export type McpServerWrapperOptions = { recordInputs?: boolean; /** Whether to capture tool/prompt output results in spans. Defaults to `dataCollection.mcp.outputs`, then `dataCollection.genAI.outputs`. */ recordOutputs?: boolean; + /** + * Resolves the registered OAuth client name for each incoming MCP request, without caching. + * Receives transport authentication metadata when available; may also read an external request-scoped context. + * Return a name synchronously to record the Sentry extension `mcp.auth.client.name`, separately from `mcp.client.name`. + * Returning `undefined` or throwing omits the attribute. Tokens and other auth fields are not recorded. + * @see https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration + */ + getOAuthClientName?: (authInfo: McpAuthInfo | undefined) => string | undefined; }; +/** Transport authentication metadata available to the OAuth client name resolver, excluding the access token. */ +export interface McpAuthInfo { + clientId: string; + extra?: Record; +} + /** * Resolved options with defaults applied. Used internally. * @internal */ -export type ResolvedMcpOptions = Required; +export type ResolvedMcpOptions = Required>; diff --git a/packages/core/test/lib/integrations/mcp-server/oauthClient.test.ts b/packages/core/test/lib/integrations/mcp-server/oauthClient.test.ts new file mode 100644 index 000000000000..2d7946458e94 --- /dev/null +++ b/packages/core/test/lib/integrations/mcp-server/oauthClient.test.ts @@ -0,0 +1,129 @@ +import { MCP_AUTH_CLIENT_NAME, MCP_CLIENT_NAME } from '@sentry/conventions/attributes'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getCurrentScope } from '../../../../src/currentScopes'; +import { wrapMcpServerWithSentry } from '../../../../src/integrations/mcp-server'; +import type { McpServerWrapperOptions } from '../../../../src/integrations/mcp-server/types'; +import { SentrySpan } from '../../../../src/tracing/sentrySpan'; +import * as tracing from '../../../../src/tracing/trace'; +import { debug } from '../../../../src/utils/debug-logger'; +import { spanToJSON } from '../../../../src/utils/spanUtils'; +import { createMockClient, createMockMcpServer, createMockTransport } from './testUtils'; + +describe('MCP OAuth client attribution', () => { + let inactiveSpan: SentrySpan | undefined; + let transport: ReturnType; + const authInfo = { + token: 'test-access-token', + clientId: 'test-client-id', + scopes: ['tools:read'], + extra: { clientName: 'Example Desktop' }, + }; + + beforeEach(() => { + inactiveSpan = undefined; + transport = createMockTransport(); + getCurrentScope().setClient(createMockClient(false)); + vi.spyOn(tracing, 'startInactiveSpan').mockImplementation(options => { + inactiveSpan = new SentrySpan(options); + return inactiveSpan; + }); + }); + + afterEach(() => { + transport.onclose(); + getCurrentScope().setClient(undefined); + vi.restoreAllMocks(); + }); + + async function connect(options?: McpServerWrapperOptions) { + await wrapMcpServerWithSentry(createMockMcpServer(), options).connect(transport); + } + + it('passes only client metadata to the resolver and records only its returned name', async () => { + const getOAuthClientName = vi.fn(() => 'Example Desktop'); + await connect({ getOAuthClientName }); + transport.onmessage({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authInfo }); + await transport.send({ jsonrpc: '2.0', id: 1, result: { tools: [] } }); + + expect(getOAuthClientName).toHaveBeenCalledExactlyOnceWith({ + clientId: 'test-client-id', + extra: { clientName: 'Example Desktop' }, + }); + const attributes = spanToJSON(inactiveSpan!).attributes; + expect(attributes[MCP_AUTH_CLIENT_NAME]).toBe('Example Desktop'); + expect(attributes).not.toHaveProperty(MCP_CLIENT_NAME); + expect(JSON.stringify(attributes)).not.toContain('test-access-token'); + expect(JSON.stringify(attributes)).not.toContain('test-client-id'); + expect(JSON.stringify(attributes)).not.toContain('tools:read'); + }); + + it('accepts a resolver after auto-wrapping and preserves the first explicit resolver', async () => { + const server = wrapMcpServerWithSentry(createMockMcpServer()); + await server.connect(transport); + + const firstResolver = vi.fn(() => 'First Registered Client'); + const laterResolver = vi.fn(() => 'Later Registered Client'); + const options = { getOAuthClientName: firstResolver }; + wrapMcpServerWithSentry(server, options); + options.getOAuthClientName = laterResolver; + wrapMcpServerWithSentry(server, options); + + transport.onmessage({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authInfo }); + + expect(firstResolver).toHaveBeenCalledExactlyOnceWith({ + clientId: 'test-client-id', + extra: { clientName: 'Example Desktop' }, + }); + expect(laterResolver).not.toHaveBeenCalled(); + expect(spanToJSON(inactiveSpan!).attributes[MCP_AUTH_CLIENT_NAME]).toBe('First Registered Client'); + }); + + it('does not infer OAuth names from provider-specific metadata without a resolver', async () => { + await connect(); + transport.onmessage({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authInfo }); + expect(spanToJSON(inactiveSpan!).attributes).not.toHaveProperty(MCP_AUTH_CLIENT_NAME); + }); + + it('logs rejected resolvers without interrupting request dispatch', async () => { + const error = new Error('test resolver failure'); + const debugErrorSpy = vi.spyOn(debug, 'error').mockImplementation(() => undefined); + const onmessage = transport.onmessage; + const result = { result: 'dispatch completed' }; + onmessage.mockReturnValue(result); + await connect({ + getOAuthClientName: (() => Promise.reject(error)) as unknown as McpServerWrapperOptions['getOAuthClientName'], + }); + const message = { jsonrpc: '2.0', id: 1, method: 'resources/list' }; + const extra = { authInfo }; + + expect(transport.onmessage(message, extra)).toBe(result); + expect(onmessage).toHaveBeenCalledExactlyOnceWith(message, extra); + expect(spanToJSON(inactiveSpan!).attributes).not.toHaveProperty(MCP_AUTH_CLIENT_NAME); + await vi.waitFor(() => { + expect(debugErrorSpy).toHaveBeenCalledExactlyOnceWith('The `getOAuthClientName` callback threw an error:', error); + }); + }); + + it.each([ + [ + 'throws', + () => { + throw new Error('test resolver failure'); + }, + ], + ['returns a non-string from JavaScript', () => ({ token: 'test-access-token' })], + ])('preserves request dispatch when the resolver %s', async (_description, resolver) => { + const onmessage = transport.onmessage; + const result = { result: 'dispatch completed' }; + onmessage.mockReturnValue(result); + await wrapMcpServerWithSentry(createMockMcpServer(), { + getOAuthClientName: resolver as unknown as McpServerWrapperOptions['getOAuthClientName'], + }).connect(transport); + const message = { jsonrpc: '2.0', id: 1, method: 'resources/list' }; + const extra = { authInfo }; + + expect(transport.onmessage(message, extra)).toBe(result); + expect(onmessage).toHaveBeenCalledExactlyOnceWith(message, extra); + expect(spanToJSON(inactiveSpan!).attributes).not.toHaveProperty(MCP_AUTH_CLIENT_NAME); + }); +}); From 4ccdb35926daba0206d68379ebc25d7212562758 Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Wed, 11 Nov 2026 09:10:16 +0100 Subject: [PATCH 012/136] fix(cloudflare): Skip auto-instrument warning for TanStack Start tunnel shim (#26239) **Why:** With the TanStack Start tunnel enabled, the server entry is loaded through a stand-in module that only does `export * from "?sentry-tunnel-original"`. The Cloudflare auto-instrument plugin treats both modules as the entry. The classes get wrapped in the real one, but the stand-in has no named classes, so it printed a false "Could not auto-instrument" warning. The plugin now skips the warning when a module re-exports everything from its own file under a query. Closes #26204 Co-authored-by: Claude Opus 5.5 --- .../cloudflare/src/vite/autoInstrument.ts | 20 +++++++++-- .../test/vite/autoInstrument.test.ts | 34 +++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/cloudflare/src/vite/autoInstrument.ts b/packages/cloudflare/src/vite/autoInstrument.ts index 0a725d224a0e..9f9568e31cdf 100644 --- a/packages/cloudflare/src/vite/autoInstrument.ts +++ b/packages/cloudflare/src/vite/autoInstrument.ts @@ -2,7 +2,7 @@ import { basename, dirname, isAbsolute } from 'node:path'; import { createIdResolver, type ResolvedConfig } from 'vite'; import { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass'; import { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile'; -import { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform'; +import { applyAutoInstrumentTransforms, type BaseNode, type ClassWrapperKind, type ProgramBody } from './transform'; import { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig'; // Vite normalizes module IDs to posix separators even on Windows, while @@ -31,6 +31,20 @@ async function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: stri } } +/** + * Whether the module re-exports everything from another module of its own file, as the shim + * `@sentry/tanstackstart-react` loads for the server entry does (`export * from "?sentry-tunnel-original"`). + * That module is transformed as the entry too, and its classes are wrapped there. + */ +function reexportsAllFromSameFile(ast: ProgramBody, normalizedId: string): boolean { + return ast.body.some(node => { + if (node.type !== 'ExportAllDeclaration') return false; + const { exported, source } = node as BaseNode & { exported?: unknown; source?: { value?: unknown } }; + const value = source?.value; + return !exported && typeof value === 'string' && normalizePath(value.replace(/[?#].*$/, '')) === normalizedId; + }); +} + type TransformContext = ModuleResolver & { warn?(msg: string): void; environment?: Parameters>[0]; @@ -202,9 +216,9 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa const wrappedClasses = result?.wrappedClasses ?? new Set(); const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name)); - if (missing.length > 0) { + if (missing.length > 0 && !reexportsAllFromSameFile(ast, normalizedId)) { this.warn?.( - `[sentry] Could not auto-instrument ${missing.join(', ')}.` + + `[sentry] Could not auto-instrument ${missing.join(', ')}. ` + 'The worker entry has no export matching them. ' + 'Star re-exports (`export * from "./do"`) are not matched. ' + 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.', diff --git a/packages/cloudflare/test/vite/autoInstrument.test.ts b/packages/cloudflare/test/vite/autoInstrument.test.ts index 7212a8fe55c8..1a4d776e91ba 100644 --- a/packages/cloudflare/test/vite/autoInstrument.test.ts +++ b/packages/cloudflare/test/vite/autoInstrument.test.ts @@ -507,6 +507,40 @@ describe('sentryCloudflareAutoInstrumentPlugin', () => { expect(warnings).toHaveLength(1); expect(warnings[0]).toContain('MyDO'); }); + + it('does not warn for a shim that re-exports everything from a query variant of the entry', async () => { + const dir = writeTempDir({ + 'wrangler.toml': [ + 'main = "index.ts"', + '', + '[[durable_objects.bindings]]', + 'name = "MY_DO"', + 'class_name = "MyDO"', + ].join('\n'), + }); + const plugin = sentryCloudflareAutoInstrumentPlugin(); + plugin.configResolved({ root: dir }); + + const entry = join(dir, 'index.ts').replace(/\\/g, '/'); + const original = JSON.stringify(`${entry}?sentry-tunnel-original`); + const warnings: string[] = []; + const ctx = { parse: (c: string) => parseJS(c), warn: (msg: string) => warnings.push(msg) }; + + const originalResult = await plugin.transform.call( + ctx, + 'export class MyDO {}\nexport default { fetch() {} };', + `${entry}?sentry-tunnel-original`, + ); + const shimResult = await plugin.transform.call( + ctx, + `export * from ${original};\nexport { default } from ${original};`, + entry, + ); + + expect(originalResult.code).toContain('instrumentDurableObjectWithSentry('); + expect(shimResult.code).toContain('_INTERNAL_wrapUnlessInstrumented('); + expect(warnings).toEqual([]); + }); }); describe('wranglerConfigPath option', () => { From 29f738689d57e27aaae941fd82a0d168a3a50101 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:29:59 +0100 Subject: [PATCH 013/136] chore(ci): Add Warden gha-security-review and skill-scanner (#26269) **Why:** The org-wide Warden workflow (`getsentry/.github`) only runs `security-review` here. We have ~25 workflows, several of which drive AI agents (`auto-fix-issue`, `dependabot-auto-triage`, `track-framework-updates`, `optional-e2e`), plus ~20 agent skills managed via `agents.toml`. This adds a repo `warden.toml` that layers two more skills on top of the org base: `gha-security-review` (from `getsentry/skills`) for `.github/workflows/**` and `.github/actions/**`, and the already-vendored `skill-scanner` for `.agents/**`, `.claude/**`, `.cursor/**`, and `agents.toml`/`agents.lock`. sentry-dotnet and sentry-python run the same skills. `failOn = "high"` matches most getsentry repos; with `failCheck` and `requestChanges` left at their `false` defaults, findings are still reported only and never block merges. Each skill is scoped with explicit `paths` because repo-layer skills don't inherit the org `ignorePaths`. `model` is left unset so it inherits the org default; the org workflow only provides an OpenRouter key. **How to review:** Single config file. I validated it with `@sentry/warden@0.53.0` (`loadWardenConfig` + `resolveSkillConfigs`), and both skills resolve (local `skill-scanner`, remote `gha-security-review`). It hasn't run end-to-end in CI yet. Since this PR touches neither workflows nor skills, neither new skill should trigger on it. **Unsure about:** Whether `.cursor/**` (BUGBOT.md, environment.json) belongs in skill-scanner scope. I included it because it's agent instructions. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794381869.399109) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794381869.399109/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- warden.toml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 warden.toml diff --git a/warden.toml b/warden.toml new file mode 100644 index 000000000000..f5d73443fd83 --- /dev/null +++ b/warden.toml @@ -0,0 +1,27 @@ +# Repo-level Warden config, layered on top of the org base config in +# getsentry/.github/warden.toml (which already runs security-review). +# Repo skills do not inherit the org ignorePaths, so each skill is scoped +# with explicit paths. Model is left unset to inherit the org default. +version = 1 + +[defaults] +failOn = "high" +reportOn = "medium" + +[[skills]] +name = "gha-security-review" +remote = "getsentry/skills" +paths = [".github/workflows/**", ".github/actions/**"] + +[[skills.triggers]] +type = "pull_request" +actions = ["opened", "synchronize", "reopened"] + +[[skills]] +name = "skill-scanner" +incremental = true +paths = [".agents/**", ".claude/**", ".cursor/**", "agents.toml", "agents.lock"] + +[[skills.triggers]] +type = "pull_request" +actions = ["opened", "synchronize", "reopened"] From 3ba87742e6c23a3b81c282e97267d40c800f1908 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 03:59:31 -0500 Subject: [PATCH 014/136] feat(deps): Bump node-forge from 1.4.2 to 1.4.3 (#26267) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [node-forge](https://github.com/digitalbazaar/forge) from 1.4.2 to 1.4.3.
Changelog

Sourced from node-forge's changelog.

1.4.3 - 2026-11-03

Security

  • HIGH: X.509 certificate chain verification ignores name constraints.
    • pki.verifyCertificateChain() does not check the nameConstraints extension (RFC 5280 4.2.1.10). A non-critical nameConstraints extension in a CA certificate is ignored, so a name-constrained intermediate CA can issue certificates for names outside its permitted subtrees, or inside its excluded subtrees, and the chain verifies. Exploitation requires the private key of a name-constrained CA that chains to a trusted root. A critical nameConstraints extension is rejected as an unsupported critical extension.
    • Reported by @​bhaswanthc.
    • CVE ID: CVE-TBD
    • GHSA ID: GHSA-3cc4-3294-vgjf
  • MODERATE: TLS client crash on a handshake record without a session.
    • A TLS client throws an uncaught TypeError from process() when it receives a ServerHello while it has no session: after a close_notify alert or a call to close(), or before handshake() is called. A malicious server, or an on-path attacker, can terminate a Node.js process that passes socket data to process() without catching exceptions. Servers are not affected.
    • Reported by @​manus-use.
    • CVE ID: CVE-TBD
    • GHSA ID: GHSA-j8rw-jp99-435v
  • MODERATE: ReDoS in forge.http response header parsing.
    • forge.http trims response header and Set-Cookie values with a regular expression that takes quadratic time on a long run of whitespace followed by another character. A server, or an on-path attacker, can block a forge.http client for minutes with one large header.
    • Reported by @​manus-pi.
    • CVE ID: CVE-TBD
    • GHSA ID: GHSA-6cv4-p8m7-4r25
  • MODERATE: TLS client crash on an unsupported ServerHello compression method.
    • A TLS client accepts any compression method in the ServerHello, although it only offers no compression. An unknown method makes process() throw an uncaught Error at ServerHelloDone, before the server is authenticated. A malicious server, or an on-path attacker, can terminate a Node.js process that passes socket data to process() without catching exceptions, including through forge.tls.wrapSocket. Servers are not affected.
    • Reported by @​alienkeric.
    • CVE ID: CVE-TBD
    • GHSA ID: GHSA-w4xr-hqv8-ch44
  • LOW: Ed25519 signature verification accepts small-order public keys.
    • ed25519.verify() does not reject public keys of small order, such as the identity point. Under such a key, a signature with S = 0 and a small-order R verifies for many or, with the identity key, all messages, without any private key. Applications are affected only if

... (truncated)

Commits
  • 936b24d Release 1.4.3.
  • 4d8f79a Update changelog.
  • 1d9816d Check the ServerHello compression method.
  • 326a4d0 Trim forge.http header values in linear time.
  • 2cfaeb5 Ignore handshake messages on a TLS client without a session.
  • 6b23eae Complete nameConstraints enforcement.
  • 862aa5f Enforce nameConstraints in verifyCertificateChain().
  • 956f2b5 Document ed25519.verify() small-order key behavior.
  • 1b77e6f Reject small-order Ed25519 public keys in verify.
  • 2bd5146 Add GitHub usernames to credits.
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=node-forge&package-manager=npm_and_yarn&previous-version=1.4.2&new-version=1.4.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/getsentry/sentry-javascript/network/alerts).
--------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- pnpm-lock.yaml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 81ea1f3d7a5b..a86dd0246474 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14737,6 +14737,7 @@ packages: node-abort-controller@3.1.1: resolution: {integrity: sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==} + deprecated: This package is no longer needed on supported Node.js versions. Node.js 16+ includes AbortController and AbortSignal as built-in globals. All Node.js versions requiring this polyfill are end-of-life. Use the built-in globals instead. node-addon-api@3.2.1: resolution: {integrity: sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==} @@ -14770,8 +14771,8 @@ packages: resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - node-forge@1.4.2: - resolution: {integrity: sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==} + node-forge@1.4.3: + resolution: {integrity: sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==} engines: {node: '>= 6.13.0'} node-gyp-build-optional-packages@5.2.2: @@ -28025,7 +28026,7 @@ snapshots: http-shutdown: 1.2.2 jiti: 1.21.6 mlly: 1.8.2 - node-forge: 1.4.2 + node-forge: 1.4.3 pathe: 1.1.2 std-env: 3.10.0 ufo: 1.6.4 @@ -32300,7 +32301,7 @@ snapshots: google-p12-pem@3.1.4: dependencies: - node-forge: 1.4.2 + node-forge: 1.4.3 gopd@1.2.0: {} @@ -33741,7 +33742,7 @@ snapshots: h3: 1.15.11 http-shutdown: 1.2.2 jiti: 2.7.0 - node-forge: 1.4.2 + node-forge: 1.4.3 pathe: 2.0.3 std-env: 4.3.0 tinyclip: 0.1.15 @@ -35342,7 +35343,7 @@ snapshots: fetch-blob: 3.2.0 formdata-polyfill: 4.0.10 - node-forge@1.4.2: {} + node-forge@1.4.3: {} node-gyp-build-optional-packages@5.2.2: dependencies: @@ -38108,7 +38109,7 @@ snapshots: selfsigned@2.4.1: dependencies: '@types/node-forge': 1.3.11 - node-forge: 1.4.2 + node-forge: 1.4.3 semifies@1.0.0: {} From 291da8d8e2a1ff9b30ee79260bf187f07c29c42e Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Wed, 11 Nov 2026 04:03:36 -0500 Subject: [PATCH 015/136] chore(deps): Record the `node-abort-controller` deprecation in the lockfile (#26270) npm deprecated `node-abort-controller@3.1.1` yesterday, which broke `pnpm dedupe --check` on develop because the lockfile stores deprecation notices, fixed by adding the notice to the lockfile. From b31b20b492f808c6747c8c93d954639daae04e60 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:46:30 +0100 Subject: [PATCH 016/136] chore(ci): Assign 3 PR reviewers via workflow (#26268) **Why:** CODEOWNERS plus team auto-assignment requests every matching team, so a PR that touches several areas pings a lot of people. This workflow instead tops each PR up to exactly 3 human reviewers when it is opened, reopened, or marked ready for review. It picks people at random from the matching codeowner teams first, then fills from `@getsentry/team-javascript-sdks`. It never picks the author, `mydea`, or `stephanie-anderson`. Manually added reviewers count toward the 3. Bot reviewers don't. Once a PR has 3 reviewers, the workflow doesn't change anything. The workflow reads `.github/CODEOWNERS` as it is. **Before merging:** on the browser, server and framework sub-teams, turn off "Enable auto assignment" and turn on "Only notify requested team members". If auto assignment stays on, GitHub adds its own picks first, the workflow counts them, and it stops. GitHub will still add the code owner team requests to each PR. The notify setting keeps those from pinging the whole team. Depends on: * https://github.com/getsentry/security-as-code/pull/3904 * https://github.com/getsentry/security-as-code/pull/3903 **How to review:** Start with `scripts/assign-reviewers.js`. The workflow is a thin `github-script` wrapper. **Unsure about:** - The token comes from the existing `GITFLOW_APP_*` app because listing team members needs org `members: read`, which `GITHUB_TOKEN` can't get. Check that the app has `members: read` and `pull_requests: write`, or swap in another app. - If none of the 3 picks belongs to a matching codeowner team, that team may still be notified as a whole. This can happen when a PR touches 2 areas. - The `team-javascript-sdks` ruleset (required reviewers, 1 approval, `*`) may also request the whole team on its own. - The workflow uses `pull_request_target` so it also runs on fork PRs. It only checks out the base branch, so PR code never runs with the token. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794382310.154169) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794382310.154169/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .github/workflows/assign-reviewers.yml | 47 ++++++++ package.json | 2 +- scripts/assign-reviewers.mjs | 149 +++++++++++++++++++++++++ scripts/assign-reviewers.test.mjs | 80 +++++++++++++ 4 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/assign-reviewers.yml create mode 100644 scripts/assign-reviewers.mjs create mode 100644 scripts/assign-reviewers.test.mjs diff --git a/.github/workflows/assign-reviewers.yml b/.github/workflows/assign-reviewers.yml new file mode 100644 index 000000000000..27ee5aa7a31f --- /dev/null +++ b/.github/workflows/assign-reviewers.yml @@ -0,0 +1,47 @@ +name: 'PR: Assign reviewers' + +on: + # pull_request_target so this also runs for fork PRs. It only checks out the base branch, + # never the PR's code. + pull_request_target: + types: + - opened + - reopened + - ready_for_review + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + assign-reviewers: + name: Assign reviewers + runs-on: ubuntu-24.04 + if: github.event.pull_request.draft == false + steps: + # Listing team members needs org `members: read`, which GITHUB_TOKEN can't have. + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.GITFLOW_APP_ID }} + private-key: ${{ secrets.GITFLOW_APP_PRIVATE_KEY }} + + - name: Checkout base branch + uses: actions/checkout@v7 + with: + sparse-checkout: | + .github/CODEOWNERS + scripts/assign-reviewers.mjs + sparse-checkout-cone-mode: false + + - name: Assign reviewers + uses: actions/github-script@v9 + with: + github-token: ${{ steps.app-token.outputs.token }} + script: | + const { assignReviewers } = await import('${{ github.workspace }}/scripts/assign-reviewers.mjs'); + await assignReviewers({ github, context, core }); diff --git a/package.json b/package.json index 1b4cd4a2b19b..6f99f6deca66 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "dedupe-deps:fix": "pnpm dedupe", "postpublish": "nx run-many -t postpublish --parallel=1", "test": "nx run-many -t test --exclude=@sentry-internal/browser-integration-tests --exclude=@sentry-internal/bun-integration-tests --exclude=@sentry-internal/deno-integration-tests --exclude=@sentry-internal/e2e-tests --exclude=@sentry-internal/integration-shims --exclude=@sentry-internal/node-integration-tests --exclude=@sentry-internal/cloudflare-integration-tests --exclude=@sentry-internal/bundler-plugin-integration-tests", - "test:scripts": "vitest run scripts/*.test.ts", + "test:scripts": "vitest run scripts/*.test.ts scripts/*.test.mjs", "test:unit": "nx run-many -t test:unit --exclude=@sentry-internal/browser-integration-tests --exclude=@sentry-internal/bun-integration-tests --exclude=@sentry-internal/deno-integration-tests --exclude=@sentry-internal/e2e-tests --exclude=@sentry-internal/integration-shims --exclude=@sentry-internal/node-integration-tests --exclude=@sentry-internal/cloudflare-integration-tests --exclude=@sentry-internal/bundler-plugin-integration-tests", "test:update-snapshots": "nx run-many -t test:update-snapshots", "test:pr": "nx affected -t test --exclude=@sentry-internal/browser-integration-tests --exclude=@sentry-internal/bun-integration-tests --exclude=@sentry-internal/deno-integration-tests --exclude=@sentry-internal/e2e-tests --exclude=@sentry-internal/integration-shims --exclude=@sentry-internal/node-integration-tests --exclude=@sentry-internal/cloudflare-integration-tests --exclude=@sentry-internal/bundler-plugin-integration-tests", diff --git a/scripts/assign-reviewers.mjs b/scripts/assign-reviewers.mjs new file mode 100644 index 000000000000..02d934d201b3 --- /dev/null +++ b/scripts/assign-reviewers.mjs @@ -0,0 +1,149 @@ +import * as fs from 'fs'; + +const REQUIRED_REVIEWERS = 3; +const TEAM_SLUG = 'team-javascript-sdks'; +// Managers who are members (and code owners) of the SDK teams, but should never be auto-requested for review. +const NEVER_REQUEST = ['mydea', 'stephanie-anderson']; +const CODEOWNERS_PATH = '.github/CODEOWNERS'; + +function patternToRegExp(pattern) { + let p = pattern; + const anchored = p.startsWith('/') || p.slice(0, -1).includes('/'); + p = p.replace(/^\//, ''); + const directoryOnly = p.endsWith('/'); + p = p.replace(/\/$/, ''); + + const body = p + .split('/') + .map(segment => { + if (segment === '**') { + return '(?:.*)'; + } + return segment + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*/g, '[^/]*') + .replace(/\?/g, '[^/]'); + }) + .join('/') + .replace(/\(\?:\.\*\)\//g, '(?:.*/)?'); + + const prefix = anchored ? '^' : '^(?:.*/)?'; + const suffix = directoryOnly ? '/.*$' : '(?:/.*)?$'; + return new RegExp(prefix + body + suffix); +} + +export function parseCodeowners(content) { + return content + .split('\n') + .map(line => line.trim()) + .filter(line => line && !line.startsWith('#')) + .map(line => { + const [pattern, ...owners] = line.split(/\s+/); + return { regexp: patternToRegExp(pattern), owners }; + }); +} + +/** CODEOWNERS semantics: the last matching rule wins for each file. */ +export function getOwnersForFiles(rules, files) { + const owners = new Set(); + for (const file of files) { + const rule = rules.findLast(r => r.regexp.test(file)); + rule?.owners.forEach(owner => owners.add(owner)); + } + return [...owners]; +} + +function shuffle(items) { + const result = [...items]; + for (let i = result.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [result[i], result[j]] = [result[j], result[i]]; + } + return result; +} + +/** + * Picks reviewers to top the PR up to `REQUIRED_REVIEWERS`, preferring the codeowner pool and falling back + * to the whole team. Logins are compared case-insensitively, as GitHub does. + */ +export function pickReviewers({ existing, codeownerPool, teamPool, exclude }) { + const taken = new Set([...existing, ...exclude].map(login => login.toLowerCase())); + const picked = []; + + for (const pool of [codeownerPool, teamPool]) { + for (const login of shuffle(pool)) { + if (existing.length + picked.length >= REQUIRED_REVIEWERS) { + return picked; + } + if (!taken.has(login.toLowerCase())) { + taken.add(login.toLowerCase()); + picked.push(login); + } + } + } + + return picked; +} + +export async function assignReviewers({ github, context, core }) { + const { owner, repo } = context.repo; + const pull_number = context.payload.pull_request.number; + + const { data: currentPr } = await github.rest.pulls.get({ owner, repo, pull_number }); + if (currentPr.draft || currentPr.state !== 'open') { + core.info('PR is a draft or not open, skipping.'); + return; + } + + const author = currentPr.user.login; + const reviews = await github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number }); + // Requested reviewers drop off `requested_reviewers` once they submit a review, so count both. + // Bots (AI reviewers) don't count towards the required reviewers. + const existing = [ + ...new Set( + [...currentPr.requested_reviewers, ...reviews.map(r => r.user)] + .filter(user => user && user.type !== 'Bot' && user.login.toLowerCase() !== author.toLowerCase()) + .map(user => user.login), + ), + ]; + + if (existing.length >= REQUIRED_REVIEWERS) { + core.info(`PR already has ${existing.length} reviewers (${existing.join(', ')}), not changing anything.`); + return; + } + + const listTeamMembers = async team_slug => + (await github.paginate(github.rest.teams.listMembersInOrg, { org: owner, team_slug })).map(m => m.login); + + const files = (await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number })).map(f => f.filename); + const codeowners = getOwnersForFiles(parseCodeowners(fs.readFileSync(CODEOWNERS_PATH, 'utf8')), files); + + const codeownerPool = []; + for (const codeowner of codeowners) { + // `@org/team` or `@user`; email owners can't be requested as reviewers, so they are skipped. + const [, name, teamSlug] = codeowner.match(/^@([^/]+)(?:\/(.+))?$/) ?? []; + if (teamSlug && name.toLowerCase() === owner.toLowerCase()) { + codeownerPool.push(...(await listTeamMembers(teamSlug))); + } else if (name && !teamSlug) { + codeownerPool.push(name); + } + } + + const reviewers = pickReviewers({ + existing, + codeownerPool, + teamPool: await listTeamMembers(TEAM_SLUG), + exclude: [author, ...NEVER_REQUEST], + }); + + core.info(`Codeowners: ${codeowners.join(', ') || '(none)'}`); + core.info(`Existing reviewers: ${existing.join(', ') || '(none)'}`); + + if (!reviewers.length) { + core.info('No eligible reviewers left to request.'); + return; + } + + core.info(`Requesting reviews from: ${reviewers.join(', ')}`); + await github.rest.pulls.requestReviewers({ owner, repo, pull_number, reviewers }); +} diff --git a/scripts/assign-reviewers.test.mjs b/scripts/assign-reviewers.test.mjs new file mode 100644 index 000000000000..6f88a3702b1f --- /dev/null +++ b/scripts/assign-reviewers.test.mjs @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; + +import { getOwnersForFiles, parseCodeowners, pickReviewers } from './assign-reviewers.mjs'; + +const CODEOWNERS = ` +# comment +/packages/browser/ @getsentry/browser +/packages/node/ @getsentry/server +/packages/node/src/x.ts @someone +*.md @getsentry/docs +`; + +describe('getOwnersForFiles', () => { + const rules = parseCodeowners(CODEOWNERS); + + it('collects owners across all touched files', () => { + expect(getOwnersForFiles(rules, ['packages/browser/src/index.ts', 'packages/node/src/sdk.ts'])).toEqual([ + '@getsentry/browser', + '@getsentry/server', + ]); + }); + + it('uses the last matching rule for a file', () => { + expect(getOwnersForFiles(rules, ['packages/node/src/x.ts'])).toEqual(['@someone']); + }); + + it('matches unanchored patterns at any depth', () => { + expect(getOwnersForFiles(rules, ['packages/node/README.md'])).toEqual(['@getsentry/docs']); + }); + + it('does not match sibling directories that share a prefix', () => { + expect(getOwnersForFiles(rules, ['packages/browser-utils/src/index.ts', 'packages/nodejs/a.ts'])).toEqual([]); + }); +}); + +describe('pickReviewers', () => { + const teamPool = ['a', 'b', 'c', 'd', 'e', 'mydea']; + + it('picks only from the codeowner pool when it is large enough', () => { + const picked = pickReviewers({ + existing: [], + codeownerPool: ['x1', 'x2', 'x3', 'y1', 'y2', 'y3'], + teamPool, + exclude: [], + }); + expect(picked).toHaveLength(3); + picked.forEach(login => expect(['x1', 'x2', 'x3', 'y1', 'y2', 'y3']).toContain(login)); + }); + + it('fills up from the team when the codeowner pool is too small', () => { + const picked = pickReviewers({ existing: [], codeownerPool: ['x1'], teamPool, exclude: ['mydea'] }); + expect(picked).toHaveLength(3); + expect(picked[0]).toBe('x1'); + expect(picked).not.toContain('mydea'); + }); + + it('picks from the whole team when no codeowners match', () => { + const picked = pickReviewers({ existing: [], codeownerPool: [], teamPool: ['a', 'b', 'c'], exclude: [] }); + expect(picked.sort()).toEqual(['a', 'b', 'c']); + }); + + it('never picks the author, excluded people, or existing reviewers, case-insensitively', () => { + const picked = pickReviewers({ + existing: ['B'], + codeownerPool: ['A', 'b', 'Mydea'], + teamPool: ['a', 'c', 'd'], + exclude: ['a', 'mydea'], + }); + expect(picked.sort()).toEqual(['c', 'd']); + }); + + it('only tops up to the required number of reviewers', () => { + expect(pickReviewers({ existing: ['x', 'y'], codeownerPool: [], teamPool, exclude: [] })).toHaveLength(1); + expect(pickReviewers({ existing: ['x', 'y', 'z'], codeownerPool: [], teamPool, exclude: [] })).toEqual([]); + }); + + it('returns fewer reviewers when not enough people are eligible', () => { + expect(pickReviewers({ existing: [], codeownerPool: [], teamPool: ['a'], exclude: [] })).toEqual(['a']); + }); +}); From d6d803c006b5d176c8cd832581bc13182dbeb09e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 04:48:22 -0500 Subject: [PATCH 017/136] fix(bundler-plugins): Stop defaulting `url` to sentry.io (#26252) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** If neither `url` nor `SENTRY_URL` is set, the plugin passes `https://sentry.io` to the CLI. A self-hosted `sntrys_` org token records the server it came from, so the CLI refuses to send it to sentry.io. The build still passes, but nothing gets released or uploaded. With `url` left unset, the CLI uses the token's server for `sntrys_` tokens and sentry.io otherwise, so SaaS setups behave the same. **Before / After:** self-hosted `sntrys_` token created on `sentry.example.com`, with no `url` in the plugin config. Before: ``` [sentry-vite-plugin] Error: An error occurred. Couldn't finish all operations: HostScopeError: Credentials: https://sentry.io Refusing to route requests here because it doesn't match the host your Sentry credentials are for (https://sentry.example.com). To use this host, run: sentry auth login --url https://sentry.io To keep using your current credentials, remove this URL override. ``` After: ``` # no error: the release and source maps go to https://sentry.example.com ``` **How to review:** The fix is one line in `options-mapping.ts`. The new `cli-contract.test.ts` case runs the real CLI with a `sntrys_` token whose server is the mock server and no `url`. It fails with the error above before this change. **Unsure about:** `NormalizedOptions.url` is now `string | undefined`. It's internal, and only `cli.ts` and `telemetry.ts` read it. The telemetry check still treats an unset `url` as SaaS, which is today's behavior. via @betegon. -- [View Session in Sentry](https://sentry.sentry.io/explore/conversations/agent%3A497276480faf8cef7b74e6b05edf0932/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: bete <28983162+betegon@users.noreply.github.com> Co-authored-by: Miguel Betegón --- .../src/core/options-mapping.ts | 6 ++++-- .../src/core/sentry/telemetry.ts | 3 ++- packages/bundler-plugins/src/core/types.ts | 2 +- .../test/core/cli-contract.test.ts | 19 +++++++++++++++++++ .../test/core/option-mappings.test.ts | 4 ++-- .../test/core/sentry/telemetry.test.ts | 13 +++++++++++-- .../buildTimeOptionsBase.ts | 2 +- 7 files changed, 40 insertions(+), 9 deletions(-) diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index c190d3efc5cc..f775ce0c5ad3 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -15,7 +15,7 @@ export type NormalizedOptions = { org: string | undefined; project: string | string[] | undefined; authToken: string | undefined; - url: string; + url: string | undefined; headers: Record | undefined; debug: boolean; silent: boolean; @@ -101,7 +101,9 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption ? process.env['SENTRY_PROJECT'].split(',').map(p => p.trim()) : process.env['SENTRY_PROJECT']), authToken: userOptions.authToken ?? process.env['SENTRY_AUTH_TOKEN'], - url: userOptions.url ?? process.env['SENTRY_URL'] ?? SENTRY_SAAS_URL, + // No sentry.io default: the CLI then uses the server an `sntrys_` org token was issued for, and + // sentry.io otherwise. A default here would send self-hosted tokens to sentry.io. + url: userOptions.url ?? process.env['SENTRY_URL'], headers: userOptions.headers, debug: userOptions.debug ?? false, silent: userOptions.silent ?? false, diff --git a/packages/bundler-plugins/src/core/sentry/telemetry.ts b/packages/bundler-plugins/src/core/sentry/telemetry.ts index c9da77637d90..66953eb3cb1f 100644 --- a/packages/bundler-plugins/src/core/sentry/telemetry.ts +++ b/packages/bundler-plugins/src/core/sentry/telemetry.ts @@ -137,7 +137,8 @@ export function setTelemetryDataOnScope( } export async function allowedToSendTelemetry(options: NormalizedOptions): Promise { - const { telemetry, url } = options; + const { telemetry } = options; + const url = options.url ?? SENTRY_SAAS_URL; // `options.telemetry` defaults to true if (telemetry === false) { diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index 95fca5f937fb..7cf821a63937 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -42,7 +42,7 @@ export interface Options { * * This value can also be set via the `SENTRY_URL` environment variable. * - * @default "https://sentry.io" (correct value for SaaS customers) + * @default The server that a `sntrys_` organization auth token was created on, otherwise "https://sentry.io" */ url?: string; diff --git a/packages/bundler-plugins/test/core/cli-contract.test.ts b/packages/bundler-plugins/test/core/cli-contract.test.ts index 51ad7ab86ecd..dc53bf4427bd 100644 --- a/packages/bundler-plugins/test/core/cli-contract.test.ts +++ b/packages/bundler-plugins/test/core/cli-contract.test.ts @@ -22,6 +22,7 @@ import { startMockSentryServer } from '@sentry-internal/test-utils'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { SentryCliAdapter } from '../../src/core/cli'; import type { NormalizedOptions } from '../../src/core/options-mapping'; +import { normalizeUserOptions } from '../../src/core/options-mapping'; const PORT = 3037; @@ -123,6 +124,24 @@ describe('SentryCliAdapter against the real CLI', () => { ); }); + it('sends a self-hosted org token to its own server when no url is configured', async () => { + const claim = Buffer.from( + JSON.stringify({ + iat: 1, + url: `http://localhost:${PORT}`, + region_url: `http://localhost:${PORT}`, + org: 'test-org', + }), + ).toString('base64'); + const before = recordedRequests(); + + await new SentryCliAdapter( + normalizeUserOptions({ authToken: `sntrys_${claim}_secret`, org: 'test-org', project: 'test-project' }), + ).createRelease('1.0.0'); + + expect(requestsSince(before)).toContain('POST /api/0/organizations/test-org/releases/'); + }); + it('sends the configured headers with every request', async () => { const before = recordedRequestRecords(); diff --git a/packages/bundler-plugins/test/core/option-mappings.test.ts b/packages/bundler-plugins/test/core/option-mappings.test.ts index 1c1bbbe42b82..754facc27e1e 100644 --- a/packages/bundler-plugins/test/core/option-mappings.test.ts +++ b/packages/bundler-plugins/test/core/option-mappings.test.ts @@ -40,7 +40,7 @@ describe('normalizeUserOptions()', () => { metaFramework: undefined, }, }, - url: 'https://sentry.io', + url: undefined, }); }); @@ -97,7 +97,7 @@ describe('normalizeUserOptions()', () => { metaFramework: undefined, }, }, - url: 'https://sentry.io', + url: undefined, }); }); diff --git a/packages/bundler-plugins/test/core/sentry/telemetry.test.ts b/packages/bundler-plugins/test/core/sentry/telemetry.test.ts index 7de02ab79bc0..dafd19a7e6cb 100644 --- a/packages/bundler-plugins/test/core/sentry/telemetry.test.ts +++ b/packages/bundler-plugins/test/core/sentry/telemetry.test.ts @@ -21,12 +21,21 @@ describe('shouldSendTelemetry', () => { it('should return false if CLI returns a URL other than sentry.io', async () => { mockRun.mockResolvedValue({ config: { url: 'https://selfhostedSentry.io' } }); - expect(await allowedToSendTelemetry({ release: {} } as NormalizedOptions)).toBe(false); + expect(await allowedToSendTelemetry({ url: 'https://sentry.example.com', release: {} } as NormalizedOptions)).toBe( + false, + ); + }); + + it('should not ask the CLI when no url is configured', async () => { + expect(await allowedToSendTelemetry({ release: {} } as NormalizedOptions)).toBe(true); + expect(mockRun).not.toHaveBeenCalled(); }); it('should return true if CLI returns sentry.io as a URL', async () => { mockRun.mockResolvedValue({ config: { url: 'https://sentry.io' } }); - expect(await allowedToSendTelemetry({ release: {} } as NormalizedOptions)).toBe(true); + expect(await allowedToSendTelemetry({ url: 'https://sentry.example.com', release: {} } as NormalizedOptions)).toBe( + true, + ); }); }); diff --git a/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts b/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts index 1bf9505714f1..130e38c086bc 100644 --- a/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts +++ b/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts @@ -52,7 +52,7 @@ export interface BuildTimeOptionsBase { * * This value can also be set via the `SENTRY_URL` environment variable. * - * @default "https://sentry.io" + * @default The server that a `sntrys_` organization auth token was created on, otherwise "https://sentry.io" */ sentryUrl?: string; From 638bf22761490da63aff90e33d966d671ac54ade Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:02:23 +0100 Subject: [PATCH 018/136] fix(anthropic): End and mark messages.stream() span as cancelled on abort (#26236) **Why:** When a `messages.stream()` call is aborted, the Anthropic SDK's `MessageStream` emits only `abort` and then `end`. It never emits `message` or `error`. We only ended the span on `message` or `error`, so an aborted stream's span never ended and was never sent. The SDK always emits `end` last, so we now end the span there too. `endStreamSpan` does nothing if the span already ended. The span keeps whatever usage and response data streamed in before the abort. Inside `end`, an aborted stream (`stream.aborted`) is now marked `cancelled`, the same as Google GenAI when the caller's `abortSignal` fires. Only the caller's `stream.abort()` or request `signal` sets `aborted`. The SDK's request timeouts are only active until the response headers arrive, and they surface as `APIConnectionTimeoutError` on `error`, so they still record `internal_error`. We deliberately don't listen for `abort`. The SDK raises an unhandled rejection for an abort only when nothing listens for it, so an `abort` listener would silence that rejection for apps that abort a stream and never await it. `stream.aborted` exists in every supported SDK version (`>=0.19.2`). **How to review:** The `end` listener in `instrumentMessageStream` is the whole change. I also checked it by hand against the real `@anthropic-ai/sdk` `MessageStream`, aborting it mid-stream against a local SSE server without awaiting it. Uninstrumented and with this change, the app gets the same single unhandled rejection. With this change, the span also ends `cancelled` with the partial usage attached. **Note:** Under span streaming (the default), `getSimpleStatus` sends `cancelled` as `ok` and drops the status message, as it does for every cancelled span in the SDK. Static mode shows `cancelled`. An aborted span still differs from a completed one: it has no finish reason, and if it was aborted before the response, it has no response ID or usage. via **Rola Abuhasna**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0C848BQ509%3A1794305469.823259) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0C848BQ509%3A1794305469.823259/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Rola Abuhasna --- .../anthropic/scenario-stream-abort.mjs | 90 +++++++++++++++++++ .../suites/tracing/anthropic/test.ts | 25 ++++++ .../src/ai/anthropic-ai/streaming.ts | 11 ++- .../test/ai/lib/tracing/stream-errors.test.ts | 46 +++++++++- 4 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-stream-abort.mjs diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-stream-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-stream-abort.mjs new file mode 100644 index 000000000000..e0a4f90f0fbb --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-stream-abort.mjs @@ -0,0 +1,90 @@ +import Anthropic from '@anthropic-ai/sdk'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +function startMockAnthropicServer() { + const app = express(); + app.use(express.json()); + + app.post('/anthropic/v1/messages', (req, res) => { + // Never respond, so the caller aborts before the response arrives. + if (req.body.model === 'abort-before-response') { + return; + } + + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + // Send part of a message and keep the connection open, so the caller aborts mid-stream. + const events = [ + { + type: 'message_start', + message: { + id: 'msg_abort_midway_1', + type: 'message', + role: 'assistant', + model: req.body.model, + content: [], + usage: { input_tokens: 5 }, + }, + }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'This stream will ' } }, + ]; + for (const event of events) { + res.write(`event: ${event.type}\n`); + res.write(`data: ${JSON.stringify(event)}\n\n`); + } + }); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +async function run() { + const server = await startMockAnthropicServer(); + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + const client = new Anthropic({ + apiKey: 'mock-api-key', + baseURL: `http://localhost:${server.address().port}/anthropic`, + }); + + // 1) Abort before the response arrives + const beforeResponse = client.messages.stream({ + model: 'abort-before-response', + messages: [{ role: 'user', content: 'This will be aborted before the response' }], + }); + setTimeout(() => beforeResponse.abort(), 50); + try { + await beforeResponse.done(); + } catch { + // Abort expected + } + + // 2) Abort midway through streaming + const midway = client.messages.stream({ + model: 'abort-midway', + messages: [{ role: 'user', content: 'This will be aborted midway' }], + }); + midway.on('text', () => midway.abort()); + try { + await midway.done(); + } catch { + // Abort expected + } + }); + + await Sentry.flush(2000); + + server.closeAllConnections(); + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts index 8abd3e0c088e..87d1cd735458 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts @@ -476,6 +476,31 @@ describe('Anthropic integration', () => { }); }); + createEsmAndCjsTests(__dirname, 'scenario-stream-abort.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('sends messages.stream() spans that were aborted', async () => { + await createRunner() + .ignore('event') + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.anthropic'); + expect(spans).toHaveLength(2); + + // `cancelled` is sent as `ok` under span streaming. + const beforeResponseSpan = spans.find(span => span.name === 'chat abort-before-response'); + expect(beforeResponseSpan!.status).toBe('ok'); + + const midwaySpan = spans.find(span => span.name === 'chat abort-midway'); + expect(midwaySpan!.status).toBe('ok'); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('msg_abort_midway_1'); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT].value).toBe('This stream will '); + }, + }) + .start() + .completed(); + }); + }); + createEsmAndCjsTests(__dirname, 'scenario-errors.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { test('handles tool errors correctly', async () => { await createRunner() diff --git a/packages/server-utils/src/ai/anthropic-ai/streaming.ts b/packages/server-utils/src/ai/anthropic-ai/streaming.ts index 9d0b1a3def11..253ff094f829 100644 --- a/packages/server-utils/src/ai/anthropic-ai/streaming.ts +++ b/packages/server-utils/src/ai/anthropic-ai/streaming.ts @@ -258,7 +258,7 @@ export async function* instrumentAsyncIterableStream( /** * Instruments a MessageStream by registering event handlers and preserving the original stream API. */ -export function instrumentMessageStream void }>( +export function instrumentMessageStream void; aborted?: boolean }>( stream: R, span: Span, recordOutputs: boolean, @@ -312,5 +312,14 @@ export function instrumentMessageStream } }); + // An aborted stream emits only `abort` and `end`. We don't listen for `abort`: doing so would stop the SDK from + // raising an unhandled rejection when the caller never awaits the aborted stream. + stream.on('end', () => { + if (stream.aborted && span.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + } + endStreamSpan(span, state, recordOutputs); + }); + return stream; } diff --git a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts index d34dc3d4a1d3..30c37aec9ba5 100644 --- a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts @@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest'; import type { Span } from '@sentry/core'; import { SPAN_STATUS_ERROR } from '@sentry/core'; import { GEN_AI_RESPONSE_STREAMING, GEN_AI_USAGE_INPUT_TOKENS } from '@sentry/conventions/attributes'; -import { instrumentAsyncIterableStream } from '../../../../src/ai/anthropic-ai/streaming'; +import { EventEmitter } from 'node:events'; +import { instrumentAsyncIterableStream, instrumentMessageStream } from '../../../../src/ai/anthropic-ai/streaming'; import { instrumentStream as instrumentGoogleGenAIStream } from '../../../../src/ai/google-genai/streaming'; import type { GoogleGenAIResponse } from '../../../../src/ai/google-genai/types'; import { instrumentStream as instrumentOpenAIStream } from '../../../../src/ai/openai/streaming'; @@ -111,6 +112,49 @@ describe.each(providers)('$name stream errors', ({ instrument, chunks }) => { }); }); +describe('anthropic message stream aborts', () => { + it('leaves the status alone and ends the span once when the stream completes', () => { + const { span, setStatus } = createMockSpan(); + const end = vi.spyOn(span, 'end'); + const stream = Object.assign(new EventEmitter(), { aborted: false }); + instrumentMessageStream(stream, span, false); + + stream.emit('message', {}); + stream.emit('end'); + + expect(setStatus).not.toHaveBeenCalled(); + expect(end).toHaveBeenCalledTimes(1); + }); + + it('marks the span as cancelled and keeps the partial usage when the stream is aborted', () => { + const { span, attributes, setStatus } = createMockSpan(); + const stream = Object.assign(new EventEmitter(), { aborted: false }); + instrumentMessageStream(stream, span, false); + + stream.emit('streamEvent', { + type: 'message_start', + message: { id: 'msg_1', model: 'claude-sonnet-4-5', usage: { input_tokens: 8 } }, + }); + stream.aborted = true; + stream.emit('abort', new Error('Request was aborted.')); + stream.emit('end'); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + expect(span.isRecording()).toBe(false); + expect(attributes[GEN_AI_RESPONSE_STREAMING]).toBe(true); + expect(attributes[GEN_AI_USAGE_INPUT_TOKENS]).toBe(8); + }); + + it('does not listen for abort, so an unobserved abort still raises an unhandled rejection', () => { + const { span } = createMockSpan(); + const stream = new EventEmitter(); + instrumentMessageStream(stream, span, false); + + expect(stream.listenerCount('abort')).toBe(0); + }); +}); + describe('google-genai stream aborts', () => { const abortError = new DOMException('This operation was aborted', 'AbortError'); From 15f3d8d4a183fafd2a780ff521f215b0b6c0c6a1 Mon Sep 17 00:00:00 2001 From: whatever_kunaal <143793407+kunal649@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:40:23 +0530 Subject: [PATCH 019/136] fix(browser): Instrument empty-URL XHR and show the page URL in breadcrumbs (#26201) Why: `fetch('')` is instrumented, but `xhr.open('GET', '')` was not, and once an empty URL request is instrumented its breadcrumb shows `url: ""`. This PR fixes both * `xhr.ts` bailed on `!url`, which treats an empty string like an unparseable argument, so empty-URL XHRs got no breadcrumb and no span. It now only bails on `url === undefined`, so XHR matches fetch. * The fetch and XHR breadcrumb handlers now show the page URL for an empty URL instead of `""`. Query and fragment are stripped with `stripUrlQueryAndFragment`, so params like `?token=` from the page URL don't end up in breadcrumbs. Since an empty URL resolves to the page URL itself, the helper uses `location.href` directly instead of calling `new URL()` (bcoz its throws for hrefs like `about:srcdoc`). without a `location` object (e.g. workers), nothing changes. Only empty URLs are rewritten, _absolute_ and _relative_ URLs keep their current breadcrumb behaviour. How to review: Start with: * `packages/browser-utils/src/instrumentation/xhr.ts` * `packages/browser/src/integrations/breadcrumbs.ts` and the regression coverage in: * `packages/browser-utils/test/instrumentation/xhr.test.ts` * `packages/browser/test/integrations/breadcrumbs.test.ts` The key things to check are that only empty URLs are rewritten, and that the query and fragment are stripped from the page URL in all three breadcrumb paths (fetch, failed fetch, XHR). Unsure about: Whether relative URLs (like `/api/foo?x=1`) should also be resolved against `location.href` and stripped in breadcrumbs. I kept this limited to empty URLs so the change stays scoped, but yeah I'm happy to widen it. Ref [#13168](https://github.com/getsentry/sentry-javascript/issues/13168) --- .../browser-utils/src/instrumentation/xhr.ts | 2 +- .../test/instrumentation/xhr.test.ts | 27 +++- .../browser/src/integrations/breadcrumbs.ts | 11 +- .../test/integrations/breadcrumbs.test.ts | 126 +++++++++++++++++- 4 files changed, 158 insertions(+), 8 deletions(-) diff --git a/packages/browser-utils/src/instrumentation/xhr.ts b/packages/browser-utils/src/instrumentation/xhr.ts index 41dbe93a42ae..5973d130b51f 100644 --- a/packages/browser-utils/src/instrumentation/xhr.ts +++ b/packages/browser-utils/src/instrumentation/xhr.ts @@ -51,7 +51,7 @@ export function instrumentXHR(): void { const method = isString(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined; const url = parseXhrUrlArg(xhrOpenArgArray[1]); - if (!method || !url) { + if (!method || url === undefined) { return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); } diff --git a/packages/browser-utils/test/instrumentation/xhr.test.ts b/packages/browser-utils/test/instrumentation/xhr.test.ts index 91991a579439..9ab78118f15e 100644 --- a/packages/browser-utils/test/instrumentation/xhr.test.ts +++ b/packages/browser-utils/test/instrumentation/xhr.test.ts @@ -1,11 +1,28 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { addXhrInstrumentationHandler, instrumentXHR } from '../../src/instrumentation/xhr'; -import type { HandlerDataXhr } from '../../src/types'; +import type { HandlerDataXhr, SentryWrappedXMLHttpRequest } from '../../src/types'; import { WINDOW } from '../../src/types'; const win = WINDOW as typeof WINDOW & { XMLHttpRequest?: typeof XMLHttpRequest }; const originalXMLHttpRequest = win.XMLHttpRequest; +function openWithUrl(url: unknown): SentryWrappedXMLHttpRequest['__sentry_xhr_v3__'] { + class MockXMLHttpRequest { + public addEventListener(): void {} + public removeEventListener(): void {} + public open(_method: string, _url: string): void {} + public send(): void {} + public setRequestHeader(_header: string, _value: string): void {} + } + + win.XMLHttpRequest = MockXMLHttpRequest as unknown as typeof XMLHttpRequest; + instrumentXHR(); + + const xhr = new MockXMLHttpRequest(); + xhr.open('GET', url as string); + return (xhr as unknown as SentryWrappedXMLHttpRequest).__sentry_xhr_v3__; +} + describe('instrumentXHR', () => { afterEach(() => { win.XMLHttpRequest = originalXMLHttpRequest; @@ -16,6 +33,14 @@ describe('instrumentXHR', () => { expect(instrumentXHR).not.toThrow(); }); + it('instruments requests with an empty URL', () => { + expect(openWithUrl('')).toMatchObject({ method: 'GET', url: '' }); + }); + + it('does not instrument requests whose URL cannot be parsed', () => { + expect(openWithUrl(undefined)).toBeUndefined(); + }); + it('removes readystatechange event listener on readyState 4 when registered with addEventListener', () => { const addEventListenerSpy = vi.fn(); const removeEventListenerSpy = vi.fn(); diff --git a/packages/browser/src/integrations/breadcrumbs.ts b/packages/browser/src/integrations/breadcrumbs.ts index aa7f438d770e..1d2f3ab3ea5a 100644 --- a/packages/browser/src/integrations/breadcrumbs.ts +++ b/packages/browser/src/integrations/breadcrumbs.ts @@ -193,7 +193,7 @@ function _getXhrBreadcrumbHandler(client: Client): (handlerData: HandlerDataXhr) const data: XhrBreadcrumbData = { method, - url: filterCollectedUrl(url), + url: getBreadcrumbUrl(url, client), status_code, }; @@ -248,7 +248,7 @@ function _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFe const breadcrumb = { category: 'fetch', - data: { ...handlerData.fetchData, url: filterCollectedUrl(handlerData.fetchData.url) }, + data: { ...handlerData.fetchData, url: getBreadcrumbUrl(handlerData.fetchData.url, client) }, level: 'error', type: 'http', } satisfies Breadcrumb; @@ -260,7 +260,7 @@ function _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFe const response = handlerData.response as Response | undefined; const data: FetchBreadcrumbData = { ...handlerData.fetchData, - url: filterCollectedUrl(handlerData.fetchData.url), + url: getBreadcrumbUrl(handlerData.fetchData.url, client), status_code: response?.status, }; @@ -324,6 +324,11 @@ function _getHistoryBreadcrumbHandler(client: Client): (handlerData: HandlerData }; } +function getBreadcrumbUrl(url: string, client?: Client): string { + const pageUrl = url === '' ? WINDOW.location?.href : undefined; + return filterCollectedUrl(pageUrl ? (pageUrl.split('#')[0] ?? '') : url, client); +} + function _isEvent(event: unknown): event is Event { return !!event && !!(event as Record).target; } diff --git a/packages/browser/test/integrations/breadcrumbs.test.ts b/packages/browser/test/integrations/breadcrumbs.test.ts index 56df65c3a6ae..e65bdd213875 100644 --- a/packages/browser/test/integrations/breadcrumbs.test.ts +++ b/packages/browser/test/integrations/breadcrumbs.test.ts @@ -1,9 +1,16 @@ import * as SentryCore from '@sentry/core'; -import { describe, expect, it, vi } from 'vitest'; +import * as browserUtils from '@sentry/browser-utils'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { breadcrumbsIntegration, BrowserClient, flush } from '../../src'; import { getDefaultBrowserClientOptions } from '../helper/browser-client-options'; describe('Breadcrumbs', () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + SentryCore.getCurrentScope().setClient(undefined); + }); + it('Should add sentry breadcrumb', async () => { const client = new BrowserClient({ ...getDefaultBrowserClientOptions(), @@ -19,7 +26,120 @@ describe('Breadcrumbs', () => { client.captureMessage('test'); await flush(2000); - expect(addBreadcrumbSpy.mock.calls[0]?.[0]?.category).toEqual('sentry.event'); - expect(addBreadcrumbSpy.mock.calls[0]?.[0]?.message).toEqual('test'); + expect(addBreadcrumbSpy).toHaveBeenCalledWith( + expect.objectContaining({ + category: 'sentry.event', + message: 'test', + }), + expect.anything(), + ); + }); + + describe('empty request URLs', () => { + function setup() { + let fetchHandler: ((data: SentryCore.HandlerDataFetch) => void) | undefined; + let xhrHandler: ((data: browserUtils.HandlerDataXhr) => void) | undefined; + + vi.spyOn(SentryCore, 'addFetchInstrumentationHandler').mockImplementation(handler => { + fetchHandler = handler; + }); + vi.spyOn(browserUtils, 'addXhrInstrumentationHandler').mockImplementation(handler => { + xhrHandler = handler; + }); + const addBreadcrumbSpy = vi.spyOn(SentryCore, 'addBreadcrumb').mockImplementation(() => {}); + + const client = new BrowserClient({ + ...getDefaultBrowserClientOptions(), + dsn: 'https://username@domain/123', + integrations: [breadcrumbsIntegration()], + }); + SentryCore.setCurrentClient(client); + client.init(); + + return { addBreadcrumbSpy, fetchHandler: fetchHandler!, xhrHandler: xhrHandler! }; + } + + const pageHref = 'https://app.example.com/users/42?token=secret#section'; + const expectedBreadcrumbUrl = 'https://app.example.com/users/42?token=[Filtered]'; + + it('resolves an empty fetch URL against location.href, drops fragment, and filters query params', () => { + vi.stubGlobal('location', { href: pageHref }); + const { addBreadcrumbSpy, fetchHandler } = setup(); + + fetchHandler({ + fetchData: { method: 'GET', url: '' }, + args: [''], + startTimestamp: 1, + endTimestamp: 2, + response: { status: 200 } as Response, + }); + + expect(addBreadcrumbSpy).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ url: expectedBreadcrumbUrl }), + }), + expect.anything(), + ); + }); + + it('resolves an empty failed fetch URL against location.href, drops fragment, and filters query params', () => { + vi.stubGlobal('location', { href: pageHref }); + const { addBreadcrumbSpy, fetchHandler } = setup(); + + fetchHandler({ + fetchData: { method: 'GET', url: '' }, + args: [''], + startTimestamp: 1, + endTimestamp: 2, + error: new TypeError('Failed to fetch'), + }); + + expect(addBreadcrumbSpy).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ url: expectedBreadcrumbUrl }), + }), + expect.anything(), + ); + }); + + it('resolves an empty XHR URL against location.href, drops fragment, and filters query params', () => { + vi.stubGlobal('location', { href: pageHref }); + const { addBreadcrumbSpy, xhrHandler } = setup(); + + xhrHandler({ + xhr: { + [browserUtils.SENTRY_XHR_DATA_KEY]: { method: 'GET', url: '', status_code: 200, request_headers: {} }, + }, + startTimestamp: 1, + endTimestamp: 2, + } as browserUtils.HandlerDataXhr); + + expect(addBreadcrumbSpy).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ url: expectedBreadcrumbUrl }), + }), + expect.anything(), + ); + }); + + it('leaves non-empty URLs unchanged', () => { + vi.stubGlobal('location', { href: pageHref }); + const { addBreadcrumbSpy, fetchHandler } = setup(); + + fetchHandler({ + fetchData: { method: 'GET', url: '/api/users' }, + args: ['/api/users'], + startTimestamp: 1, + endTimestamp: 2, + response: { status: 200 } as Response, + }); + + expect(addBreadcrumbSpy).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ url: '/api/users' }), + }), + expect.anything(), + ); + }); }); }); From 20a5f1000ab5ef466070bed0ae0cce8426ab4124 Mon Sep 17 00:00:00 2001 From: "javascript-sdk-gitflow[bot]" <255134079+javascript-sdk-gitflow[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:16:41 -0500 Subject: [PATCH 020/136] chore: Add external contributor to CHANGELOG.md (#26275) This PR adds the external contributor to the CHANGELOG.md file, so that they are credited for their contribution. See #26201 Co-authored-by: s1gr1d <32902192+s1gr1d@users.noreply.github.com> --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cae8ddfbdbb1..7cf64b2291ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott +Work in this release was contributed by @kunal649. Thank you for your contribution! + ## 11.12.0 ### Important Changes From 92481191306228b666cc393cd95863298e2fdba7 Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Wed, 11 Nov 2026 11:25:25 +0100 Subject: [PATCH 021/136] fix(browser): Handle parentheses in function names in stack parsers (#26233) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Function names can be arbitrary strings. Emscripten, for example, names its bridge functions `methodCaller< (emscripten::val) => void>`. The Chrome parser treated the first ` (` as the start of the location, which garbled the filename and broke sourcemap resolution. The Firefox/Safari parser has an optional `(...)` group that strips legacy argument lists (`bar(1)@…`). That group could stretch across several parenthesised parts of a name and truncate it. This is the browser counterpart of #26216. **How to review:** Both fixes are regex tweaks in `stack-parsers.ts`. Chrome: a negative lookahead skips a `(` when a `) ` follows before the next `(` opens. Gecko: the argument group can no longer contain parentheses. The existing wasm test had locked in the broken output, so its expectations changed. Closes #26205 --------- Co-authored-by: Claude Opus 5.5 --- packages/browser/src/stack-parsers.ts | 6 +- .../browser/test/tracekit/chromium.test.ts | 61 ++++++++++++++++--- .../browser/test/tracekit/firefox.test.ts | 43 +++++++++++++ packages/browser/test/tracekit/safari.test.ts | 43 +++++++++++++ 4 files changed, 142 insertions(+), 11 deletions(-) diff --git a/packages/browser/src/stack-parsers.ts b/packages/browser/src/stack-parsers.ts index cb74bc1e6ce6..5259c650cf51 100644 --- a/packages/browser/src/stack-parsers.ts +++ b/packages/browser/src/stack-parsers.ts @@ -56,8 +56,10 @@ function createFrame(filename: string, func: string, lineno?: number, colno?: nu const chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; // This regex matches all the frames that have a function name. +// The negative lookahead skips a `(` that belongs to the function name rather than the location, +// e.g. `methodCaller< (emscripten::val) => void>`: there, a `) ` follows before the next `(` opens. const chromeRegex = - /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; + /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?![^(]*\) )(?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; const chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; @@ -117,7 +119,7 @@ export const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chromeSt // generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js // We need this specific case for now because we want no other regex to match. const geckoREgex = - /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; + /^\s*(.*?)(?:\(([^()]*)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; const geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; const gecko: StackLineParserFn = line => { diff --git a/packages/browser/test/tracekit/chromium.test.ts b/packages/browser/test/tracekit/chromium.test.ts index 9a1cbd0abbe9..5221b5bc4272 100644 --- a/packages/browser/test/tracekit/chromium.test.ts +++ b/packages/browser/test/tracekit/chromium.test.ts @@ -715,24 +715,24 @@ describe('Tracekit - Chrome Tests', () => { lineno: 2201, }, { - filename: - 'int) const, int, MyClass const*, int>::invoke(int (MyClass::* const&)(int) const, MyClass const*, int) (http://localhost:8001/main.wasm:wasm-function[152]:0x47df', - function: 'emscripten::internal::MethodInvoker::invoke(int (MyClass::* const&)(int) const, MyClass const*, int)', in_app: true, }, { - filename: 'int) const (http://localhost:8001/main.wasm:wasm-function[182]:0x540b', - function: 'MyClass::getAt', + filename: 'http://localhost:8001/main.wasm:wasm-function[182]:0x540b', + function: 'MyClass::getAt(int) const', in_app: true, }, { - filename: 'int) const (http://localhost:8001/main.wasm:wasm-function[186]:0x5637', - function: 'MyClass::foo', + filename: 'http://localhost:8001/main.wasm:wasm-function[186]:0x5637', + function: 'MyClass::foo(int) const', in_app: true, }, { - filename: 'int) const (http://localhost:8001/main.wasm:wasm-function[190]:0x5aeb', - function: 'MyClass::bar', + filename: 'http://localhost:8001/main.wasm:wasm-function[190]:0x5aeb', + function: 'MyClass::bar(int) const', in_app: true, }, ], @@ -790,4 +790,47 @@ describe('Tracekit - Chrome Tests', () => { value: 'Error from data-uri module', }); }); + + it('should parse function names containing parentheses', () => { + const EMSCRIPTEN_ERROR = { + message: "Cannot create property 'imageData' on boolean 'false'", + name: 'TypeError', + stack: `TypeError: Cannot create property 'imageData' on boolean 'false' + at Drawing.blitterFree (https://example.com/assets/main.js:273:13) + at methodCaller< (emscripten::val) => void> (https://example.com/assets/worker-BBxJRpa6.js:1:43074) + at wasmImports._emval_invoke (https://example.com/assets/emcc-runtime.js:1:52388)`, + }; + + const ex = exceptionFromError(parser, EMSCRIPTEN_ERROR); + + expect(ex).toStrictEqual({ + type: 'TypeError', + value: "Cannot create property 'imageData' on boolean 'false'", + stacktrace: { + frames: [ + { + filename: 'https://example.com/assets/emcc-runtime.js', + function: 'wasmImports._emval_invoke', + in_app: true, + lineno: 1, + colno: 52388, + }, + { + filename: 'https://example.com/assets/worker-BBxJRpa6.js', + function: 'methodCaller< (emscripten::val) => void>', + in_app: true, + lineno: 1, + colno: 43074, + }, + { + filename: 'https://example.com/assets/main.js', + function: 'Drawing.blitterFree', + in_app: true, + lineno: 273, + colno: 13, + }, + ], + }, + }); + }); }); diff --git a/packages/browser/test/tracekit/firefox.test.ts b/packages/browser/test/tracekit/firefox.test.ts index d4db33bcbc4f..2e2e5caa25de 100644 --- a/packages/browser/test/tracekit/firefox.test.ts +++ b/packages/browser/test/tracekit/firefox.test.ts @@ -392,4 +392,47 @@ describe('Tracekit - Firefox Tests', () => { value: 'this.props.raw[this.state.dataSource].rows is undefined', }); }); + + it('should parse function names containing parentheses', () => { + const EMSCRIPTEN_ERROR = { + message: 'test error', + name: 'Error', + stack: + 'methodCaller< (emscripten::val) => void>@https://example.com/assets/worker.js:1:43074\n' + + 'MyClass::bar(int) const@https://example.com/assets/main.js:2:10\n' + + 'emscripten::internal::MethodInvoker::invoke(int)@https://example.com/assets/main.js:3:20', + }; + + const ex = exceptionFromError(parser, EMSCRIPTEN_ERROR); + + expect(ex).toStrictEqual({ + type: 'Error', + value: 'test error', + stacktrace: { + frames: [ + { + filename: 'https://example.com/assets/main.js', + function: 'emscripten::internal::MethodInvoker::invoke', + in_app: true, + lineno: 3, + colno: 20, + }, + { + filename: 'https://example.com/assets/main.js', + function: 'MyClass::bar(int) const', + in_app: true, + lineno: 2, + colno: 10, + }, + { + filename: 'https://example.com/assets/worker.js', + function: 'methodCaller< (emscripten::val) => void>', + in_app: true, + lineno: 1, + colno: 43074, + }, + ], + }, + }); + }); }); diff --git a/packages/browser/test/tracekit/safari.test.ts b/packages/browser/test/tracekit/safari.test.ts index 62eafa35ef1f..bd60d022a8ef 100644 --- a/packages/browser/test/tracekit/safari.test.ts +++ b/packages/browser/test/tracekit/safari.test.ts @@ -356,4 +356,47 @@ describe('Tracekit - Safari Tests', () => { }, }); }); + + it('should parse function names containing parentheses', () => { + const EMSCRIPTEN_ERROR = { + message: 'test error', + name: 'Error', + stack: + 'methodCaller< (emscripten::val) => void>@https://example.com/assets/worker.js:1:43074\n' + + 'MyClass::bar(int) const@https://example.com/assets/main.js:2:10\n' + + 'emscripten::internal::MethodInvoker::invoke(int)@https://example.com/assets/main.js:3:20', + }; + + const ex = exceptionFromError(parser, EMSCRIPTEN_ERROR); + + expect(ex).toStrictEqual({ + type: 'Error', + value: 'test error', + stacktrace: { + frames: [ + { + filename: 'https://example.com/assets/main.js', + function: 'emscripten::internal::MethodInvoker::invoke', + in_app: true, + lineno: 3, + colno: 20, + }, + { + filename: 'https://example.com/assets/main.js', + function: 'MyClass::bar(int) const', + in_app: true, + lineno: 2, + colno: 10, + }, + { + filename: 'https://example.com/assets/worker.js', + function: 'methodCaller< (emscripten::val) => void>', + in_app: true, + lineno: 1, + colno: 43074, + }, + ], + }, + }); + }); }); From 9f5933693d81db0d9ebf416af8bdfc3c63af089b Mon Sep 17 00:00:00 2001 From: isaacs Date: Wed, 11 Nov 2026 11:26:11 +0100 Subject: [PATCH 022/136] feat(cloudflare): Instrument `trace` and `tailStream` handlers (#26250) `withSentry` and `WorkerEntrypoint` instrumentation covered `tail`, but not the other two tail handlers that workerd still supports. workerd calls `trace` only when a worker does not export `tail`. Streaming tail workers export `tailStream`. Errors thrown by either handler were not captured. `trace` now gets the same wrapper as `tail`. `tailStream` needs more: workerd calls it once with the onset event, then calls the function or object it returns for each later batch of events. The wrapper also wraps that return value, so each event handler call runs as its own invocation and captures its errors. The mechanism types are `auto.faas.cloudflare.trace` and `auto.faas.cloudflare.tail_stream`, to match the existing `auto.faas.cloudflare.tail`. Closes #24038 Closes JS-3573 --------- Co-authored-by: Claude Opus 5.5 --- .../suites/tail-stream/index-producer.ts | 5 + .../suites/tail-stream/index.ts | 19 ++ .../suites/tail-stream/instrument.server.ts | 5 + .../suites/tail-stream/test.ts | 25 ++ .../suites/tail-stream/vite.config.mts | 10 + .../tail-stream/wrangler-producer.jsonc | 8 + .../suites/tail-stream/wrangler.jsonc | 8 + .../instrumentations/worker/instrumentTail.ts | 146 ++++++++--- .../instrumentWorkerEntrypoint.test.ts | 45 +++- .../worker/instrumentTail.test.ts | 235 +++++++++++++++++- 10 files changed, 472 insertions(+), 34 deletions(-) create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc create mode 100644 dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts new file mode 100644 index 000000000000..4bc14ed89a89 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index-producer.ts @@ -0,0 +1,5 @@ +export default { + async fetch() { + return new Response('ok'); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts new file mode 100644 index 000000000000..70632becce3a --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/index.ts @@ -0,0 +1,19 @@ +interface Env { + PRODUCER: Fetcher; +} + +// Nothing is wrapped manually, the Vite plugin wraps the default export. +export default { + async fetch(_request, env) { + return env.PRODUCER.fetch('http://fake-host/'); + }, + // workerd calls `tailStream()` with the producer's onset event, then calls + // the returned object for the later events of that invocation. + tailStream() { + return { + outcome() { + throw new Error('Error from the tailStream outcome handler'); + }, + }; + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts new file mode 100644 index 000000000000..9de8aec879bb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/instrument.server.ts @@ -0,0 +1,5 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({ + dsn: env.SENTRY_DSN, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts new file mode 100644 index 000000000000..3d906ace27bb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/test.ts @@ -0,0 +1,25 @@ +import type { Event } from '@sentry/core'; +import { join } from 'path'; +import { expect, it } from 'vitest'; +import { createRunner } from '../../runner'; + +it('captures errors thrown by the handler that tailStream returns', async ({ signal }) => { + const runner = createRunner(__dirname) + // A tail consumer in another `wrangler dev` process does not receive + // streaming tail events, so the producer runs in the same process. + .withWranglerArgs('-c', join(__dirname, 'dist/cloudflare_tail_stream_producer/wrangler.json')) + .expect(envelope => { + const event = envelope[1][0]?.[1] as Event; + expect(event.exception?.values?.[0]).toEqual( + expect.objectContaining({ + type: 'Error', + value: 'Error from the tailStream outcome handler', + mechanism: { type: 'auto.faas.cloudflare.tail_stream', handled: false }, + }), + ); + }) + .start(signal); + + await runner.makeRequest('get', '/'); + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts new file mode 100644 index 000000000000..71ebb6c3e6fa --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/vite.config.mts @@ -0,0 +1,10 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [ + cloudflare({ auxiliaryWorkers: [{ configPath: './wrangler-producer.jsonc' }] }), + sentryCloudflareVitePlugin(), + ], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc new file mode 100644 index 000000000000..97e22bd98f7d --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler-producer.jsonc @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "cloudflare-tail-stream-producer", + "main": "index-producer.ts", + "compatibility_date": "2025-06-17", + "compatibility_flags": ["nodejs_compat"], + "streaming_tail_consumers": [{ "service": "cloudflare-tail-stream-consumer" }], +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc new file mode 100644 index 000000000000..0f4b2e593c3c --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tail-stream/wrangler.jsonc @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "cloudflare-tail-stream-consumer", + "main": "index.ts", + "compatibility_date": "2025-06-17", + "compatibility_flags": ["nodejs_compat"], + "services": [{ "binding": "PRODUCER", "service": "cloudflare-tail-stream-producer" }], +} diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts index 31ecd6674120..a303d417f169 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts @@ -1,4 +1,3 @@ -import type { TraceItem } from '@cloudflare/workers-types'; import type { AnyExportedHandler } from '../../types'; import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers'; import { captureException, withIsolationScope } from '@sentry/core'; @@ -10,13 +9,29 @@ import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; import { instrumentContext } from '../../utils/instrumentContext'; import { setInvocationState } from '../../utils/invocationContext'; +import { type UncheckedMethod } from '../../wrapMethodWithSentry'; import { instrumentEnv } from './instrumentEnv'; +type TailMethod = 'tail' | 'trace' | 'tailStream'; + +const TAIL_METHODS: TailMethod[] = ['tail', 'trace', 'tailStream']; + +const MECHANISM_TYPES: Record = { + tail: 'auto.faas.cloudflare.tail', + trace: 'auto.faas.cloudflare.trace', + tailStream: 'auto.faas.cloudflare.tail_stream', +}; + /** * Core tail handler logic - wraps execution with Sentry instrumentation. * Note: tail handlers don't create spans, just error capture. */ -function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext, fn: () => unknown): unknown { +function wrapTailHandler( + options: CloudflareOptions, + context: ExecutionContext, + method: TailMethod, + fn: () => unknown, +): unknown { return withIsolationScope(async isolationScope => { const waitUntil = context.waitUntil.bind(context); @@ -30,7 +45,7 @@ function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext, try { return await fn(); } catch (e) { - captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } }); + captureException(e, { mechanism: { handled: false, type: MECHANISM_TYPES[method] } }); throw e; } finally { waitUntil(flushAndDispose(client)); @@ -39,49 +54,116 @@ function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext, } /** - * Instruments a tail handler for ExportedHandler (env/ctx come from args). + * workerd calls `tailStream()` once with the onset event, then calls the + * function or object methods it returns for each later batch of events. + * Each of those calls runs as its own invocation. + */ +function wrapTailStreamEventHandler( + eventHandler: unknown, + options: CloudflareOptions, + context: ExecutionContext, +): unknown { + const wrap = (fn: UncheckedMethod, getThis: (thisArg: unknown) => unknown): UncheckedMethod => + new Proxy(fn, { + apply(target, thisArg, args) { + return wrapTailHandler(options, context, 'tailStream', () => Reflect.apply(target, getThis(thisArg), args)); + }, + }); + + if (typeof eventHandler === 'function') { + return wrap(eventHandler as UncheckedMethod, thisArg => thisArg); + } + + if (eventHandler && typeof eventHandler === 'object') { + const proxy: object = new Proxy(eventHandler, { + get(target, prop) { + // Getters and methods run with the raw object as `this`, so private + // fields work. workerd calls each method with the proxy as `this`. + // Rebinding it also keeps `this.helper()` in this invocation. + const value = Reflect.get(target, prop, target); + return typeof value === 'function' + ? wrap(value as UncheckedMethod, thisArg => (thisArg === proxy ? target : thisArg)) + : value; + }, + }); + return proxy; + } + + return eventHandler; +} + +function runTailMethod( + method: TailMethod, + options: CloudflareOptions, + context: ExecutionContext, + invoke: () => unknown, +): unknown { + if (method !== 'tailStream') { + return wrapTailHandler(options, context, method, invoke); + } + + return wrapTailHandler(options, context, method, async () => + wrapTailStreamEventHandler(await invoke(), options, context), + ); +} + +/** + * Instruments the `tail`, `trace` and `tailStream` handlers for + * ExportedHandler (env/ctx come from args). */ export function instrumentExportedHandlerTail( handler: T, optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined, ): void { - if (!('tail' in handler) || typeof handler.tail !== 'function') { - return; - } + for (const method of TAIL_METHODS) { + if (!(method in handler)) { + continue; + } - handler.tail = ensureInstrumented( - handler.tail, - original => - new Proxy(original, { - apply(target, thisArg, args: Parameters>) { - const [, env, ctx] = args; - const context = instrumentContext(ctx); - const options = getFinalOptions(optionsCallback(env), env); - args[1] = instrumentEnv(env, options); - args[2] = context; - - return wrapTailHandler(options, context, () => target.apply(thisArg, args)); - }, - }), - ); + const original = handler[method]; + if (typeof original !== 'function') { + continue; + } + + handler[method] = ensureInstrumented( + original, + original => + new Proxy(original, { + apply(target, thisArg, args: Parameters) { + const [, env, ctx] = args; + const context = instrumentContext(ctx); + const options = getFinalOptions(optionsCallback(env), env); + args[1] = instrumentEnv(env, options); + args[2] = context; + + return runTailMethod(method, options, context, () => target.apply(thisArg, args)); + }, + }), + ); + } } /** - * Instruments a tail method for WorkerEntrypoint (options/context already available). + * Instruments the `tail`, `trace` and `tailStream` methods for + * WorkerEntrypoint (options/context already available). */ export function instrumentWorkerEntrypointTail( instance: T, options: CloudflareOptions, context: ExecutionContext, ): void { - if (!instance.tail) { - return; - } + const methods = instance as Partial>; - const original = instance.tail.bind(instance); - instance.tail = new Proxy(original, { - apply(target, thisArg, args: [TraceItem[]]) { - return wrapTailHandler(options, context, () => Reflect.apply(target, thisArg, args)); - }, - }); + for (const method of TAIL_METHODS) { + const original = methods[method]; + if (!original) { + continue; + } + + methods[method] = new Proxy(original.bind(instance), { + apply(target, thisArg, args) { + return runTailMethod(method, options, context, () => Reflect.apply(target, thisArg, args)); + }, + }); + } } diff --git a/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts index 3c7f114099c0..875e03aab0db 100644 --- a/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts +++ b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts @@ -112,6 +112,49 @@ describe('instrumentWorkerEntrypoint', () => { expect(await response.text()).toBe('ok'); }); + it('captures and re-throws errors thrown by the trace method', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const TestClass = class extends WorkerEntrypoint { + trace() { + throw error; + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor), + [createMockExecutionContext(), {}], + ); + + await expect(obj.trace([])).rejects.toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.trace' }, + }); + }); + + it('captures and re-throws errors thrown by the event handler that tailStream returns', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const TestClass = class extends WorkerEntrypoint { + tailStream() { + return () => { + throw error; + }; + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor), + [createMockExecutionContext(), {}], + ); + + const eventHandler = await obj.tailStream({}); + await expect(eventHandler({})).rejects.toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.tail_stream' }, + }); + }); + it('Does not instrument ctx and env properties', () => { const mockContext = createMockExecutionContext(); const mockEnv = {}; @@ -529,7 +572,7 @@ describe('instrumentWorkerEntrypoint', () => { await obj.alarm(); await obj.webSocketMessage(); - expect(initAndBind).toHaveBeenCalledTimes(3); + expect(initAndBind).toHaveBeenCalledTimes(5); }); }); diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts index 014916e6f158..058cb435bebb 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentTail.test.ts @@ -1,7 +1,7 @@ // Note: These tests run the handler in Node.js, which has some differences to the cloudflare workers runtime. // Although this is not ideal, this is the best we can do until we have a better way to test cloudflare workers. -import type { ExecutionContext, TraceItem } from '@cloudflare/workers-types'; +import type { ExecutionContext, TailStream, TraceItem } from '@cloudflare/workers-types'; import type { Event } from '@sentry/core'; import * as SentryCore from '@sentry/core'; import { beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest'; @@ -275,3 +275,236 @@ describe('instrumentTail', () => { expect(flush).toHaveBeenCalledOnce(); }); }); + +describe('tail handler detection', () => { + test('does not add tail handlers to a handler whose proxy returns functions for unknown properties', () => { + const target = { fetch: () => new Response('ok') }; + const handler = new Proxy(target, { + get: (t, prop) => t[prop as keyof typeof t] ?? (() => undefined), + }); + + withSentry(() => ({}), handler); + + expect(Object.keys(target)).toEqual(['fetch']); + }); +}); + +describe('instrumentTrace', () => { + beforeEach(() => { + vi.clearAllMocks(); + resetSdk(); + }); + + test('creates a cloudflare client', async () => { + const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind'); + const handler = { + trace(_traces, _env, _context) { + return; + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + await wrappedHandler.trace?.(createMockTailEvent(), MOCK_ENV, createMockExecutionContext()); + + expect(initAndBindSpy).toHaveBeenCalledTimes(1); + expect(initAndBindSpy).toHaveBeenLastCalledWith(CloudflareClient, expect.any(Object)); + }); + + test('captures and re-throws errors thrown by the handler', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const handler = { + trace(_traces, _env, _context) { + throw error; + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + + let thrownError: unknown; + try { + await wrappedHandler.trace?.(createMockTailEvent(), MOCK_ENV, createMockExecutionContext()); + } catch (e) { + thrownError = e; + } + + expect(thrownError).toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.trace' }, + }); + }); +}); + +describe('instrumentTailStream', () => { + const onsetEvent = {} as TailStream.TailEvent; + const outcomeEvent = {} as TailStream.TailEvent; + + beforeEach(() => { + vi.clearAllMocks(); + resetSdk(); + }); + + test('captures and re-throws errors thrown by the handler', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const handler = { + tailStream(_event, _env, _context) { + throw error; + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + + let thrownError: unknown; + try { + await wrappedHandler.tailStream?.(onsetEvent, MOCK_ENV, createMockExecutionContext()); + } catch (e) { + thrownError = e; + } + + expect(thrownError).toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.tail_stream' }, + }); + }); + + test('passes events to the returned event handler with a client for each call', async () => { + const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind'); + const eventHandler = vi.fn(); + const handler = { + tailStream(_event, _env, _context) { + return eventHandler; + }, + } satisfies ExportedHandler; + + // A per-invocation client makes every instrumented call visible as its own init. + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN, cacheClient: false }), handler); + const returned = (await wrappedHandler.tailStream?.( + onsetEvent, + MOCK_ENV, + createMockExecutionContext(), + )) as TailStream.TailEventHandler; + await returned(outcomeEvent); + + expect(eventHandler).toHaveBeenCalledWith(outcomeEvent); + expect(initAndBindSpy).toHaveBeenCalledTimes(2); + }); + + test('captures and re-throws errors thrown by the returned event handler function', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const handler = { + tailStream(_event, _env, _context) { + return () => { + throw error; + }; + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + const returned = (await wrappedHandler.tailStream?.( + onsetEvent, + MOCK_ENV, + createMockExecutionContext(), + )) as TailStream.TailEventHandler; + + let thrownError: unknown; + try { + await returned(outcomeEvent); + } catch (e) { + thrownError = e; + } + + expect(thrownError).toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.tail_stream' }, + }); + }); + + test('supports getters that read private fields on the returned event handler object', async () => { + class Collector { + #count = 0; + + get outcome(): () => number { + return () => ++this.#count; + } + } + + const handler = { + tailStream(_event, _env, _context) { + return new Collector(); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + const returned = (await wrappedHandler.tailStream?.( + onsetEvent, + MOCK_ENV, + createMockExecutionContext(), + )) as unknown as Collector; + + await expect(returned.outcome.call(returned)).resolves.toBe(1); + }); + + test('does not start a nested invocation when an event handler method calls another method', async () => { + const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind'); + const handler = { + tailStream(_event, _env, _context) { + return { + outcome(this: { helper: () => void }) { + this.helper(); + }, + helper() {}, + }; + }, + } satisfies ExportedHandler; + + // A per-invocation client makes every instrumented call visible as its own init. + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN, cacheClient: false }), handler); + const returned = (await wrappedHandler.tailStream?.( + onsetEvent, + MOCK_ENV, + createMockExecutionContext(), + )) as TailStream.TailEventHandlerObject; + await returned.outcome?.(outcomeEvent); + + expect(initAndBindSpy).toHaveBeenCalledTimes(2); + }); + + test('captures and re-throws errors thrown by methods of the returned event handler object', async () => { + const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException'); + const error = new Error('test'); + const handler = { + tailStream(_event, _env, _context) { + return { + outcome() { + throw error; + }, + }; + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + const returned = (await wrappedHandler.tailStream?.( + onsetEvent, + MOCK_ENV, + createMockExecutionContext(), + )) as TailStream.TailEventHandlerObject; + + let thrownError: unknown; + try { + await returned.outcome?.(outcomeEvent); + } catch (e) { + thrownError = e; + } + + expect(thrownError).toBe(error); + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, { + mechanism: { handled: false, type: 'auto.faas.cloudflare.tail_stream' }, + }); + }); +}); From 23a97ce09d83ab04da337d800520dc3288215632 Mon Sep 17 00:00:00 2001 From: isaacs Date: Wed, 11 Nov 2026 11:29:08 +0100 Subject: [PATCH 023/136] fix(server-utils): Instrument deps excluded from the Vite dep optimizer (#26264) In `vite dev`, the id of a module that is not pre-bundled ends with `?v=`. `@apm-js-collab/code-transformer-bundler-plugins` 0.7.5 matched module paths exactly, so the orchestrion transform skipped packages that the user excluded from `optimizeDeps`. Version 0.7.6 removes the query before it matches. The bump adds 0.7.6 to `minimumReleaseAgeExclude`, because the release is only a few days old. A new unit test transforms an excluded package with a `?v=` id. It fails on 0.7.5 and passes on 0.7.6. The `cloudflare-vercelai-v7` e2e app now also runs its test in `vite dev`. The app uses Vite 7, so this covers the esbuild dep optimizer plugin, and it shows that `ai` sends `gen_ai.*` spans in dev. The test fails when `transformOptimizedDeps` is off. `vite dev` gets the DSN only with `CLOUDFLARE_INCLUDE_PROCESS_ENV=true`. Closes #25765 Co-authored-by: Claude Opus 5.5 --- .../cloudflare-vercelai-v7/package.json | 4 +-- .../playwright.config.ts | 3 +- packages/server-utils/package.json | 2 +- .../test/orchestrion/viteDepOptimizer.test.ts | 36 +++++++++++++++++++ pnpm-lock.yaml | 10 +++--- pnpm-workspace.yaml | 1 + 6 files changed, 47 insertions(+), 9 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/package.json index 929b0ce99e46..e02eb80aea8e 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/package.json +++ b/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/package.json @@ -3,12 +3,12 @@ "version": "0.0.0", "private": true, "scripts": { - "dev": "vite dev", + "dev": "CLOUDFLARE_INCLUDE_PROCESS_ENV=true vite dev", "build": "vite build", "preview": "vite preview --port 8787", "typecheck": "tsc --noEmit", "test:build": "pnpm install && pnpm build", - "test:assert": "pnpm test:prod", + "test:assert": "pnpm test:prod && pnpm test:dev", "test:prod": "TEST_ENV=production playwright test", "test:dev": "TEST_ENV=development playwright test" }, diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/playwright.config.ts b/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/playwright.config.ts index 5ac7a0e09e52..8b1e46f933e2 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/playwright.config.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-vercelai-v7/playwright.config.ts @@ -9,7 +9,8 @@ const APP_PORT = 8787; const config = getPlaywrightConfig( { - startCommand: `pnpm preview`, + // `vite dev` pre-bundles `ai` with the esbuild dependency optimizer of Vite 7. + startCommand: testEnv === 'development' ? `pnpm dev --port ${APP_PORT} --strictPort` : `pnpm preview`, port: APP_PORT, }, { diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index da3876156219..4f38b750f909 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -106,7 +106,7 @@ "@sentry/core": "11.12.0" }, "devDependencies": { - "@apm-js-collab/code-transformer-bundler-plugins": "^0.7.5", + "@apm-js-collab/code-transformer-bundler-plugins": "^0.7.6", "@neondatabase/serverless": "1.2.0", "@sentry-internal/rollup-utils": "11.12.0", "@types/node": "^20.19.0", diff --git a/packages/server-utils/test/orchestrion/viteDepOptimizer.test.ts b/packages/server-utils/test/orchestrion/viteDepOptimizer.test.ts index d8ca916ede5a..ffb71dfe7863 100644 --- a/packages/server-utils/test/orchestrion/viteDepOptimizer.test.ts +++ b/packages/server-utils/test/orchestrion/viteDepOptimizer.test.ts @@ -58,3 +58,39 @@ describe('sentryOrchestrionPlugin (vite) in the Rolldown dependency optimizer', expect(map.sources).toEqual(['../../fake-db/index.js']); }); }); + +describe('sentryOrchestrionPlugin (vite) on a dependency excluded from the dependency optimizer', () => { + let root: string; + let server: ViteDevServer; + + beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'orchestrion-dep-excluded-')); + const packageDir = join(root, 'node_modules', 'fake-db'); + mkdirSync(packageDir, { recursive: true }); + writeFileSync( + join(packageDir, 'package.json'), + JSON.stringify({ name: 'fake-db', version: '1.0.0', type: 'module' }), + ); + writeFileSync(join(packageDir, 'index.js'), 'export function query(sql) {\n return sql;\n}\n'); + + server = await createServer({ + root, + configFile: false, + logLevel: 'silent', + plugins: [sentryOrchestrionPlugin({ instrumentations, transformOptimizedDeps: true })], + server: { middlewareMode: true, ws: false, watch: null }, + environments: { ssr: { optimizeDeps: { exclude: ['fake-db'] } } }, + }); + }); + + afterAll(async () => { + await server.close(); + rmSync(root, { recursive: true, force: true }); + }); + + it('transforms the module when its id has the ?v= query of vite dev', async () => { + const result = await server.environments.ssr.transformRequest('/node_modules/fake-db/index.js?v=0123abcd'); + + expect(result?.code).toContain('orchestrion:fake-db:query'); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a86dd0246474..53e906c250c9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2145,8 +2145,8 @@ importers: version: link:../core devDependencies: '@apm-js-collab/code-transformer-bundler-plugins': - specifier: ^0.7.5 - version: 0.7.5(esbuild@0.28.1)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + specifier: ^0.7.6 + version: 0.7.6(esbuild@0.28.1)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) '@neondatabase/serverless': specifier: 1.2.0 version: 1.2.0 @@ -2726,8 +2726,8 @@ packages: zod: optional: true - '@apm-js-collab/code-transformer-bundler-plugins@0.7.5': - resolution: {integrity: sha512-/nmTAee5mBly9QiIQSGIKITv9TcEyLTQJFbYjfyWCEfYofxQgurMrT5fLDIRneSPqICucRTxgPMHmc6/q7cgfw==} + '@apm-js-collab/code-transformer-bundler-plugins@0.7.6': + resolution: {integrity: sha512-/IPQ3ype5bqvPzUvfuiM6KiHc4E9yfHmHXgUDO4YSlsmmL7kw+ejCKF2kfh41hlKMKSBAJ2evmehy398cuYVKg==} engines: {node: '>=18.0.0'} peerDependencies: esbuild: '*' @@ -19594,7 +19594,7 @@ snapshots: optionalDependencies: zod: 4.6.7 - '@apm-js-collab/code-transformer-bundler-plugins@0.7.5(esbuild@0.28.1)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': + '@apm-js-collab/code-transformer-bundler-plugins@0.7.6(esbuild@0.28.1)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': dependencies: '@apm-js-collab/code-transformer': 0.19.0 es-module-lexer: 2.1.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 75d66d27027b..977c5e288a27 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -127,3 +127,4 @@ minimumReleaseAgeExclude: - '@sentry/rrweb-types@2.46.0' - '@sentry/rrweb@2.46.0' - sentry@0.49.0 + - '@apm-js-collab/code-transformer-bundler-plugins@0.7.6' From 6045cab803f0f5c473ef551a3f01b6b8d3f1caed Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Wed, 11 Nov 2026 10:33:59 +0000 Subject: [PATCH 024/136] test(e2e): Assert source map stripping for Next.js and TanStack Start (#26265) Before the framework SDKs move from their own `filesToDeleteAfterUpload` globs to the plugin's `deleteSourcemapsAfterUpload`, the E2E tests should catch any source map left in the output. This adds the checks that were missing. - `nextjs-sourcemaps` gets two variants that use the SDK default (delete after upload), one with Turbopack and one with webpack. Both check that `.next/static` has no `.map` files and no `sourceMappingURL` comments. The base app keeps `deleteSourcemapsAfterUpload: false`. - `nextjs-app-dir` and `nextjs-pages-dir` read only the top level of `.next/static`, where there are no files, only folders, so their map check could never fail. They now search the whole folder. - `tanstackstart-react-sourcemaps` also checks `.output/public` for `sourceMappingURL` comments. - Gatsby has no E2E app. A unit case pins the current behaviour for `devtool: false`, which the SDK replaces with `hidden-source-map` and then deletes. --- .../nextjs-app-dir/assert-build.ts | 14 ++++++------- .../nextjs-pages-dir/assert-build.ts | 14 ++++++------- .../nextjs-sourcemaps/assert-build.ts | 13 ++++++++++++ .../nextjs-sourcemaps/next.config.js | 3 ++- .../nextjs-sourcemaps/package.json | 21 +++++++++++++++++-- .../assert-build.ts | 8 +++++++ packages/gatsby/test/gatsby-node.test.ts | 9 ++++++++ 7 files changed, 63 insertions(+), 19 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-app-dir/assert-build.ts b/dev-packages/e2e-tests/test-applications/nextjs-app-dir/assert-build.ts index 554c41fc3108..903ebdb3a358 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-app-dir/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-app-dir/assert-build.ts @@ -1,6 +1,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as assert from 'assert/strict'; +import { findSourceMapFiles } from '@sentry-internal/test-utils'; const nextPackageJson = require('next/package.json'); const nextjsVersion = nextPackageJson.version; @@ -41,12 +42,9 @@ const getLatestNextVersion = async () => { assert.match(buildStdout, /(λ|ƒ) \/server-component\/parameter\/\[\.\.\.parameters\]/); assert.match(buildStdout, /(λ|ƒ) \/server-component\/parameter\/\[parameter\]/); - // Read the contents of the directory - const files = fs.readdirSync(path.join(process.cwd(), '.next', 'static')); - const mapFiles = files.filter(file => path.extname(file) === '.map'); - if (mapFiles.length > 0) { - throw new Error( - 'Client bundle .map files found even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!', - ); - } + assert.deepEqual( + findSourceMapFiles({ outputDir: path.join('.next', 'static') }), + [], + 'Client bundle .map files found even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!', + ); })(); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-pages-dir/assert-build.ts b/dev-packages/e2e-tests/test-applications/nextjs-pages-dir/assert-build.ts index be7beeeb94e6..1ef943a854bb 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-pages-dir/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-pages-dir/assert-build.ts @@ -1,6 +1,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as assert from 'assert/strict'; +import { findSourceMapFiles } from '@sentry-internal/test-utils'; const nextPackageJson = require('next/package.json'); const nextjsVersion = nextPackageJson.version; @@ -33,12 +34,9 @@ const getLatestNextVersion = async () => { ); } - // Read the contents of the directory - const files = fs.readdirSync(path.join(process.cwd(), '.next', 'static')); - const mapFiles = files.filter(file => path.extname(file) === '.map'); - if (mapFiles.length > 0) { - throw new Error( - 'Client bundle .map files found even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!', - ); - } + assert.deepEqual( + findSourceMapFiles({ outputDir: path.join('.next', 'static') }), + [], + 'Client bundle .map files found even though `sourcemaps.deleteSourcemapsAfterUpload` option is set!', + ); })(); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts index 116dbd875baa..5a89846b0a92 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts @@ -7,6 +7,8 @@ import { getSourcemapSources, getChunkUploadPosts, getAssembleRequests, + findSourceMapFiles, + findSourceMappingUrlComments, } from '@sentry-internal/test-utils'; const requests = loadMockServerResults(); @@ -76,4 +78,15 @@ for (const req of assembleReqs) { assert.ok((req.assembleBody?.chunks?.length ?? 0) > 0, 'Expected assemble request to have chunk checksums'); } +// The browser loads everything under `.next/static`, so a map left there hands out the source. +if (process.env.E2E_DELETE_SOURCEMAPS) { + const staticDir = '.next/static'; + assert.deepEqual(findSourceMapFiles({ outputDir: staticDir }), [], `Expected no source maps in ${staticDir}`); + assert.deepEqual( + findSourceMappingUrlComments({ outputDir: staticDir }), + [], + `Expected no sourceMappingURL comments in ${staticDir}`, + ); +} + console.log('All sourcemap upload assertions passed!'); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/next.config.js b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/next.config.js index 69a0a61a9388..1c63cca05558 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/next.config.js +++ b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/next.config.js @@ -12,7 +12,8 @@ module.exports = withSentryConfig(nextConfig, { name: 'test-release', }, sourcemaps: { - deleteSourcemapsAfterUpload: false, + // The delete variants use the SDK default, which removes the client maps after the upload. + deleteSourcemapsAfterUpload: process.env.E2E_DELETE_SOURCEMAPS ? undefined : false, }, debug: true, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json index 993eef30d1ee..5cfb7891c838 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json @@ -3,10 +3,13 @@ "version": "0.1.0", "private": true, "scripts": { - "build": "node start-mock-sentry-server.mjs & next build > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; exit $BUILD_EXIT", + "build": "node start-mock-sentry-server.mjs & next build ${E2E_NEXT_WEBPACK:+--webpack} > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; exit $BUILD_EXIT", "clean": "npx rimraf node_modules pnpm-lock.yaml", "test:build": "pnpm install && pnpm build", - "test:assert": "pnpm ts-node --script-mode assert-build.ts" + "test:assert": "pnpm ts-node --script-mode assert-build.ts", + "test:build:delete": "pnpm install && E2E_DELETE_SOURCEMAPS=1 pnpm build", + "test:build:delete-webpack": "pnpm install && E2E_DELETE_SOURCEMAPS=1 E2E_NEXT_WEBPACK=1 pnpm build", + "test:assert:delete": "E2E_DELETE_SOURCEMAPS=1 pnpm test:assert" }, "dependencies": { "@sentry/nextjs": "file:../../packed/sentry-nextjs-packed.tgz", @@ -22,5 +25,19 @@ "@types/react": "^19", "@types/react-dom": "^19", "ts-node": "10.9.1" + }, + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:delete", + "assert-command": "pnpm test:assert:delete", + "label": "nextjs-sourcemaps (delete, turbopack)" + }, + { + "build-command": "pnpm test:build:delete-webpack", + "assert-command": "pnpm test:assert:delete", + "label": "nextjs-sourcemaps (delete, webpack)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts index bb92e6eb459b..b0070359e46f 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-build.ts @@ -6,6 +6,7 @@ import { findFilesWithForeignSourcemaps, findFilesWithMultipleDebugIds, findInjectedDebugIds, + findSourceMappingUrlComments, getArtifactBundles, getChunkUploadPosts, getDebugIdPairs, @@ -146,6 +147,13 @@ for (const outputDir of [CLIENT_OUTPUT, SERVER_OUTPUT]) { assert.deepEqual(sourceMapsIn(outputDir), [], `Expected no source maps in ${outputDir}`); } +// A surviving comment points browsers at a map that no longer exists. +assert.deepEqual( + findSourceMappingUrlComments({ outputDir: CLIENT_OUTPUT }), + [], + `Expected no sourceMappingURL comments in ${CLIENT_OUTPUT}`, +); + const clientChunkUrls = emittedJsFiles(CLIENT_OUTPUT).map( file => `/${path.relative(CLIENT_OUTPUT, file).split(path.sep).join('/')}`, ); diff --git a/packages/gatsby/test/gatsby-node.test.ts b/packages/gatsby/test/gatsby-node.test.ts index 4247cba110df..cb1a8f406b33 100644 --- a/packages/gatsby/test/gatsby-node.test.ts +++ b/packages/gatsby/test/gatsby-node.test.ts @@ -174,6 +174,15 @@ describe('onCreateWebpackConfig', () => { deleteSourceMaps: true, }, }, + { + name: 'replaces disabled source maps with hidden ones and deletes them', + initialConfig: { devtool: false }, + options: {}, + expected: { + devtool: 'hidden-source-map', + deleteSourceMaps: true, + }, + }, { name: 'explicit deleteSourcemapsAfterUpload true', initialConfig: { devtool: 'source-map' }, From 73c9cd7b970bda453f99c86482e45b0daabd8f19 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:34:57 +0100 Subject: [PATCH 025/136] test(e2e): Pin pi to 1.4.0 for node-flue (latest) (#26237) **Why:** `node-flue (latest)` fails before any test runs: `@flue/runtime` 2.3.0 (latest) does `import { Type } from "@earendil-works/pi-ai"`, its `^1.1.0` range now resolves to pi 1.5.x, and pi 1.5.0 dropped the `Type` re-export ([withastro/flue#912](https://github.com/withastro/flue/issues/912), still open). The pinned variant (Flue 2.0.5 / pi 0.83) is not affected. Same root cause as #26235 for `cloudflare-pi-durable`. The overrides use `@^1` selectors, so they only match the latest variant. I checked locally with pnpm 12.11.2: the pinned install still resolves pi 0.83.0, latest resolves pi-ai/pi-agent-core 1.4.0, and `vite build` passes again. Drop the override once Flue ships a fix. **Unsure about:** Pinning pi-agent-core too, so pi-ai doesn't end up duplicated (pi-agent-core 1.5.1 pins pi-ai 1.5.1 exactly). via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794311940.741409) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794311940.741409/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .../test-applications/node-flue/pnpm-workspace.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dev-packages/e2e-tests/test-applications/node-flue/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/node-flue/pnpm-workspace.yaml index 0e523a16e6f0..dc147be05267 100644 --- a/dev-packages/e2e-tests/test-applications/node-flue/pnpm-workspace.yaml +++ b/dev-packages/e2e-tests/test-applications/node-flue/pnpm-workspace.yaml @@ -4,3 +4,8 @@ allowBuilds: esbuild: true protobufjs: false minimumReleaseAge: 0 +# @flue/runtime 2.3.0 imports `Type` from pi-ai, which pi 1.5.0 stopped re-exporting +# (https://github.com/withastro/flue/issues/912). Scoped to ^1 so the pinned variant (pi 0.83) is untouched. +overrides: + '@earendil-works/pi-ai@^1': '1.4.0' + '@earendil-works/pi-agent-core@^1': '1.4.0' From 71da04969cbf6f03e7ecdec3ace79d09d6d2a9cd Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:42:26 +0100 Subject: [PATCH 026/136] fix(solidstart): Keep build-time tooling out of SolidStart 2 server bundles (#26277) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** The `solidstart-2` e2e test has been failing on `develop` since #26200 bumped the Sentry CLI to `^0.49.0`. The server entry of `@sentry/solidstart` still re-exports the deprecated SolidStart 1 `withSentry`. That pulls `@sentry/bundler-plugins`, and with it the CLI and `oxc-parser`, into the Nitro server graph. Starting with 0.48, the CLI ships as code-split ESM. Rolldown still emits its dynamic-import chunks after tree-shaking the code that imports them; Rollup doesn't. Nitro also traces `oxc-parser`'s native binding. For every SolidStart 2 app, the result is about 3.6 MB of unused build tooling in `.output/server` (5.3 MB → 1.7 MB with this change). The CLI chunk also carries the CLI's own debug IDs, which the app can't upload, and that's the assertion that fails. Removing the root `withSentry` export is breaking (#25915, v12), and lazy imports are off the table. So `sentrySolidStart()` now adds a `sentry-solidstart-runtime` export condition to server environments. The exports map resolves that condition to the existing server entry, which is the same as today's minus `withSentry`. SolidStart 1's `app.config.ts` never sets the condition, so it still gets `withSentry`. **How to review:** Start with the `exports` change in `package.json`, then `makeServerEntryPlugin`. Locally, `solidstart-2` (including the tunnel-basepath dev variant) and `solidstart` pass against CI tarballs. **Unsure about:** Whether a custom export condition is the shape we want here, versus living with the bloat until v12. The plugin only extends conditions that are already set, because Vite would otherwise replace its defaults. Nitro and SolidStart always set them for their server environments. Separately, the Rolldown behaviour seems worth an upstream issue. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794301479.516639) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794301479.516639/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- packages/solidstart/package.json | 4 ++ .../solidstart/src/vite/sentrySolidStart.ts | 27 +++++++++++- .../test/vite/sentrySolidStart.test.ts | 42 +++++++++++++++++-- 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index f83417543d25..8af383aeca29 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -30,6 +30,10 @@ "./package.json": "./package.json", ".": { "types": "./build/types/index.types.d.ts", + "sentry-solidstart-runtime": { + "import": "./build/esm/server/index.js", + "require": "./build/cjs/server/index.js" + }, "browser": { "import": "./build/esm/index.client.js", "require": "./build/cjs/index.client.js" diff --git a/packages/solidstart/src/vite/sentrySolidStart.ts b/packages/solidstart/src/vite/sentrySolidStart.ts index 13972bbf3748..b06b10523564 100644 --- a/packages/solidstart/src/vite/sentrySolidStart.ts +++ b/packages/solidstart/src/vite/sentrySolidStart.ts @@ -44,9 +44,9 @@ export type SentrySolidStartOptions = BuildTimeOptionsBase; export function sentrySolidStart(options: SentrySolidStartOptions = {}): Plugin[] { warnOnRemovedBuildOptions(options, ['unstable_sentryVitePluginOptions']); - const plugins: Plugin[] = [makeSentryNitroPlugin(options)]; + const plugins: Plugin[] = [makeSentryNitroPlugin(options), makeServerEntryPlugin()]; - // Only the Nitro plugin is dev-safe; its module handles `dev` itself. + // Only the Nitro and server entry plugins are dev-safe; the Nitro module handles `dev` itself. if (process.env.NODE_ENV === 'development') { return plugins; } @@ -62,6 +62,29 @@ export function sentrySolidStart(options: SentrySolidStartOptions = {}): Plugin[ return plugins; } +const SERVER_RUNTIME_CONDITION = 'sentry-solidstart-runtime'; + +/** + * Resolves `@sentry/solidstart` in server environments to the entry without the deprecated SolidStart 1 + * `withSentry`. Its build-time imports (Sentry CLI, oxc-parser) otherwise end up in the server output: + * Nitro traces their native files, and Rolldown still emits the CLI's dynamic-import chunks after + * tree-shaking the code that imports them. + */ +function makeServerEntryPlugin(): Plugin { + return { + name: 'sentry-solidstart-server-entry', + configEnvironment(name, config) { + // Vite concatenates the returned conditions onto these. If none are set yet, returning one would + // replace Vite's defaults, so leave resolution alone. + if (name === 'client' || config.consumer === 'client' || !config.resolve?.conditions) { + return; + } + + return { resolve: { conditions: [SERVER_RUNTIME_CONDITION] } }; + }, + }; +} + // Nitro's `NitroConfig` only matches `@sentry/nitro`'s when both resolve the same `nitro` install, // which is not guaranteed, so the key stays opaque rather than coupling the two copies. type ViteConfigWithNitro = UserConfig & { diff --git a/packages/solidstart/test/vite/sentrySolidStart.test.ts b/packages/solidstart/test/vite/sentrySolidStart.test.ts index cfd7bb1adabb..2228da8c5fae 100644 --- a/packages/solidstart/test/vite/sentrySolidStart.test.ts +++ b/packages/solidstart/test/vite/sentrySolidStart.test.ts @@ -1,7 +1,7 @@ // @vitest-environment node // Build-time plugin code, no DOM. `vite`'s runtime exports pull in esbuild, which cannot run under // jsdom's `TextEncoder`. -import type { Plugin, UserConfig } from 'vite'; +import type { EnvironmentOptions, Plugin, UserConfig } from 'vite'; import { mergeConfig } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { sentrySolidStart } from '../../src/vite/sentrySolidStart'; @@ -50,6 +50,7 @@ describe('sentrySolidStart()', () => { expect(names).toEqual([ 'sentry-solidstart-nitro', + 'sentry-solidstart-server-entry', // `sentryOrchestrionPlugin` spreads the upstream code-transformer plugin, which brings its name. 'code-transformer', 'sentry-solidstart-files-to-delete-after-upload', @@ -69,7 +70,7 @@ describe('sentrySolidStart()', () => { it('omits the source maps plugins when source maps are disabled', () => { const names = sentrySolidStart({ sourcemaps: { disable: true } }).map(plugin => plugin.name); - expect(names).toEqual(['sentry-solidstart-nitro', 'code-transformer']); + expect(names).toEqual(['sentry-solidstart-nitro', 'sentry-solidstart-server-entry', 'code-transformer']); }); // `'disable-upload'` still injects debug IDs, so the plugins have to run; the bundler plugin @@ -81,12 +82,45 @@ describe('sentrySolidStart()', () => { expect(names).toContain('sentry-solidstart-update-source-map-setting'); }); - it('only returns the nitro plugin in development', () => { + it('only returns the nitro and server entry plugins in development', () => { process.env.NODE_ENV = 'development'; const names = sentrySolidStart({ org: 'org', project: 'project' }).map(plugin => plugin.name); - expect(names).toEqual(['sentry-solidstart-nitro']); + expect(names).toEqual(['sentry-solidstart-nitro', 'sentry-solidstart-server-entry']); + }); + + describe('the server entry plugin', () => { + function callConfigEnvironmentHook(name: string, config: EnvironmentOptions): EnvironmentOptions | undefined { + const plugin = sentrySolidStart().find(p => p.name === 'sentry-solidstart-server-entry'); + const hook = plugin?.configEnvironment; + const handler = typeof hook === 'function' ? hook : hook?.handler; + return handler?.call({} as never, name, config, { command: 'build', mode: 'production' } as never) as + | EnvironmentOptions + | undefined; + } + + // `@sentry/solidstart`'s root server entry re-exports the deprecated `withSentry`, which would pull + // the build-time bundler plugins into the server bundle. + it('adds the runtime export condition to server environments', () => { + const config: EnvironmentOptions = { resolve: { conditions: ['solid', 'node'] } }; + + const merged = mergeConfig(config, callConfigEnvironmentHook('nitro', config) ?? {}); + + expect(merged.resolve?.conditions).toEqual(['solid', 'node', 'sentry-solidstart-runtime']); + }); + + it('leaves the client environment alone', () => { + expect(callConfigEnvironmentHook('client', { resolve: { conditions: ['browser'] } })).toBeUndefined(); + expect( + callConfigEnvironmentHook('custom', { consumer: 'client', resolve: { conditions: ['browser'] } }), + ).toBeUndefined(); + }); + + // Contributing conditions when none are set would replace Vite's defaults instead of extending them. + it('leaves environments without explicit conditions alone', () => { + expect(callConfigEnvironmentHook('ssr', {})).toBeUndefined(); + }); }); describe('the nitro plugin', () => { From 6ee26d61614266367937e23d270f4aab940ccd8c Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Wed, 11 Nov 2026 12:09:09 +0100 Subject: [PATCH 027/136] chore: Exempt Sentry packages from release-age checks (#26274) **Why:** Allow newly published `@sentry/*` packages and the unscoped `sentry` CLI immediately without adding a version-specific release-age exemption for each update. Remove the expired OpenTelemetry API exemption; other packages retain their existing release-age policy. --------- Co-authored-by: OpenAI Codex --- pnpm-workspace.yaml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 977c5e288a27..6645c646d04b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -120,11 +120,6 @@ allowBuilds: vue-demi: true workerd: true minimumReleaseAgeExclude: - - '@opentelemetry/api@1.10.0' - - '@sentry/conventions@0.32.0' - - '@sentry/rrdom@2.46.0' - - '@sentry/rrweb-snapshot@2.46.0' - - '@sentry/rrweb-types@2.46.0' - - '@sentry/rrweb@2.46.0' - - sentry@0.49.0 + - '@sentry/*' + - sentry - '@apm-js-collab/code-transformer-bundler-plugins@0.7.6' From 313b2f1799a6f7e04778d9f4e61a975376c1afea Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Wed, 11 Nov 2026 13:50:21 +0100 Subject: [PATCH 028/136] fix(ci): separate x64 and ARM64 dependency cache keys (#26282) **Why:** When an x64 dependency cache is missing, its key can prefix-match the ARM64 cache, restoring incompatible native bindings and breaking tests before they start. Include architecture in every cache key so x64 and ARM64 caches cannot match each other. Co-authored-by: OpenAI Codex --- .github/actions/install-dependencies/action.yml | 4 +--- .github/actions/restore-cache/action.yml | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/actions/install-dependencies/action.yml b/.github/actions/install-dependencies/action.yml index 052da6857343..098f48c191a5 100644 --- a/.github/actions/install-dependencies/action.yml +++ b/.github/actions/install-dependencies/action.yml @@ -22,9 +22,7 @@ runs: id: cache_dependencies with: path: ${{ env.CACHED_DEPENDENCY_PATHS }} - key: - ${{ steps.compute_lockfile_hash.outputs.hash }}${{ runner.arch != 'X64' && format('-{0}', runner.arch) || '' - }} + key: ${{ steps.compute_lockfile_hash.outputs.hash }}-${{ runner.arch }} - name: Install dependencies if: steps.cache_dependencies.outputs.cache-hit != 'true' diff --git a/.github/actions/restore-cache/action.yml b/.github/actions/restore-cache/action.yml index 372def6a0a7e..4112ad39ee54 100644 --- a/.github/actions/restore-cache/action.yml +++ b/.github/actions/restore-cache/action.yml @@ -17,7 +17,7 @@ runs: uses: actions/cache/restore@v6.1.0 with: path: ${{ env.CACHED_DEPENDENCY_PATHS }} - key: ${{ inputs.dependency_cache_key }}${{ runner.arch != 'X64' && format('-{0}', runner.arch) || '' }} + key: ${{ inputs.dependency_cache_key }}-${{ runner.arch }} - name: Restore build artifacts uses: actions/download-artifact@v7 From 1873c1df9fb4e1704e2a3545b3b8717f2db906a0 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:02:42 +0100 Subject: [PATCH 029/136] ci: Cache the Node.js install instead of fetching it in every job (#26287) **Why:** The runner images don't include the Node.js version pinned in `devEngines.runtime` (24.22.1). As a result, almost every CI job has `actions/setup-node` fetch its version manifest from `actions/node-versions` through the GitHub API, which costs 2 REST calls per job and counts against the repo's `GITHUB_TOKEN` limit. A full run has about 370 jobs, so at busy hours we run out. setup-node falls back to nodejs.org on its own, but steps without a fallback then fail with `API rate limit exceeded for installation`: Get CI Metadata (which fails the whole run), setup-bun, the optional E2E action, Size Check, Warden and Dependency Review. Restoring the install from the Actions cache lets setup-node find it locally, so it makes no API calls. On a cache miss, it behaves like today. **How to review:** Start with `.github/actions/setup-node/action.yml`. Everything else just swaps `actions/setup-node` with `node-version-file: 'package.json'` for the new action. Matrix jobs (`matrix.node`, `'24'`) and the E2E app's own Node setup are unchanged. **Unsure about:** Only `develop` saves the cache, so all PRs share one entry per architecture (about 47 MB each), because the repo cache is already at about 10.75 GB. PRs won't hit the cache until this has run once on `develop`. On that first run, parallel jobs race to save, so all but one log a non-fatal "unable to reserve cache" warning. caching may be slower than resolving this every time, but this is something we'll need to keep an eye on and evaluate when it runs. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794381869.399109) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794381869.399109/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .github/actions/prepare-e2e-test/action.yml | 4 +- .github/actions/setup-node/action.yml | 32 +++++++++ .github/actions/setup-node/resolve-node.sh | 8 +++ .github/workflows/build.yml | 72 ++++++--------------- .github/workflows/optional-e2e.yml | 4 +- 5 files changed, 60 insertions(+), 60 deletions(-) create mode 100644 .github/actions/setup-node/action.yml create mode 100755 .github/actions/setup-node/resolve-node.sh diff --git a/.github/actions/prepare-e2e-test/action.yml b/.github/actions/prepare-e2e-test/action.yml index 417877403d90..83510213a126 100644 --- a/.github/actions/prepare-e2e-test/action.yml +++ b/.github/actions/prepare-e2e-test/action.yml @@ -25,9 +25,7 @@ runs: # Uses the repo's root node pin for the steps before the app is copied (installing pnpm, `test:prepare`, # `test:validate`, `ci:copy-to-temp`). The app's own node version is set up after the copy below. - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun if: inputs.test-application == 'node-exports-test-app' || contains(inputs.test-application, 'bun') || inputs.runtime diff --git a/.github/actions/setup-node/action.yml b/.github/actions/setup-node/action.yml new file mode 100644 index 000000000000..77a4f3eb8db3 --- /dev/null +++ b/.github/actions/setup-node/action.yml @@ -0,0 +1,32 @@ +name: 'Set up Node' +description: 'Sets up the Node.js version of `devEngines.runtime` in the root package.json.' + +runs: + using: 'composite' + steps: + - name: Resolve Node.js version + id: node + run: sh "$GITHUB_ACTION_PATH/resolve-node.sh" + shell: sh + + # The runner images don't ship this exact version. Without the cache, `actions/setup-node` fetches its version + # manifest through the GitHub API in every job, which uses up the repository's `GITHUB_TOKEN` rate limit. + - name: Restore Node.js install + id: node-cache + uses: actions/cache/restore@v6.1.0 + with: + path: ${{ steps.node.outputs.cache-path }} + key: ${{ steps.node.outputs.cache-key }} + + - name: Set up Node + uses: actions/setup-node@v7 + with: + node-version: ${{ steps.node.outputs.version }} + + # Only `develop` saves, so PRs share one entry per architecture instead of each creating their own. + - name: Save Node.js install + if: steps.node-cache.outputs.cache-hit != 'true' && github.ref == 'refs/heads/develop' + uses: actions/cache/save@v6.1.0 + with: + path: ${{ steps.node.outputs.cache-path }} + key: ${{ steps.node.outputs.cache-key }} diff --git a/.github/actions/setup-node/resolve-node.sh b/.github/actions/setup-node/resolve-node.sh new file mode 100755 index 000000000000..a611890c4023 --- /dev/null +++ b/.github/actions/setup-node/resolve-node.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +version=$(jq -e -r '.devEngines.runtime.version' package.json) +cache_path="$RUNNER_TOOL_CACHE/node/$version" +cache_key="node-toolcache-$RUNNER_OS-$RUNNER_ARCH-$version" + +printf 'version=%s\ncache-path=%s\ncache-key=%s\n' "$version" "$cache_path" "$cache_key" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59211cdc3d6d..b4edd5327d78 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -92,9 +92,7 @@ jobs: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install Dependencies uses: ./.github/actions/install-dependencies @@ -206,9 +204,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore NX cache uses: actions/cache/restore@v6.1.0 with: @@ -245,9 +241,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore NX cache uses: actions/cache/restore@v6.1.0 with: @@ -302,9 +296,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -334,9 +326,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -382,9 +372,7 @@ jobs: - name: Install pnpm uses: ./.github/actions/install-pnpm - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install dependencies run: pnpm install --no-frozen-lockfile - name: Check that pnpm-lock.yaml is stable @@ -408,9 +396,7 @@ jobs: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install Dependencies uses: ./.github/actions/install-dependencies @@ -430,9 +416,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -488,9 +472,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -521,9 +503,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: @@ -548,9 +528,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: @@ -674,9 +652,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -737,9 +713,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -877,9 +851,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore caches uses: ./.github/actions/restore-cache with: @@ -965,9 +937,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Bun uses: oven-sh/setup-bun@v2 with: @@ -997,9 +967,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Set up Deno uses: denoland/setup-deno@v2.0.5 with: @@ -1039,9 +1007,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Restore NX cache uses: actions/cache/restore@v6.1.0 with: @@ -1209,9 +1175,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install pnpm uses: ./.github/actions/install-pnpm # Only install what the action needs diff --git a/.github/workflows/optional-e2e.yml b/.github/workflows/optional-e2e.yml index 0fc020c9b327..56d0013288fc 100644 --- a/.github/workflows/optional-e2e.yml +++ b/.github/workflows/optional-e2e.yml @@ -125,9 +125,7 @@ jobs: with: ref: ${{ env.HEAD_COMMIT }} - name: Set up Node - uses: actions/setup-node@v7 - with: - node-version-file: 'package.json' + uses: ./.github/actions/setup-node - name: Install pnpm uses: ./.github/actions/install-pnpm - name: Install action dependencies From b0d975d20b44a0ff421b5cf36e7a4d79f9742f2f Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Wed, 11 Nov 2026 14:35:39 +0100 Subject: [PATCH 030/136] fix(opentelemetry): Keep live context link when passing a scope to withScope (#26234) **Why:** With OpenTelemetry, `withScope(scope, cb)` replaced the scope's `WeakRef` context link with `cb`'s short-lived context. Once that context was garbage collected, `getActiveSpan(scope)` returned `undefined`, so new spans became root spans and errors got the wrong `span_id`. This happened on nearly every outgoing HTTP response because of `bindScopeToEmitter`. The fix keeps a link that is still alive. That's safe because `withSetScope` builds the callback context from the linked one, so both have the same active span. Closes #26217 Co-authored-by: Claude Opus 5.5 --- .../src/utils/buildContextWithSentryScopes.ts | 9 +++++++-- .../test/asyncContextStrategy.test.ts | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/opentelemetry/src/utils/buildContextWithSentryScopes.ts b/packages/opentelemetry/src/utils/buildContextWithSentryScopes.ts index 944c427bcd9b..6b27bd26a0cf 100644 --- a/packages/opentelemetry/src/utils/buildContextWithSentryScopes.ts +++ b/packages/opentelemetry/src/utils/buildContextWithSentryScopes.ts @@ -6,7 +6,7 @@ import { SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, } from '../constants'; -import { getScopesFromContext, setContextOnScope, setScopesOnContext } from './contextData'; +import { getContextFromScope, getScopesFromContext, setContextOnScope, setScopesOnContext } from './contextData'; /** * Merge Sentry scopes into an OpenTelemetry {@link Context} and apply trace-context adjustments @@ -38,7 +38,12 @@ export function buildContextWithSentryScopes(context: Context): Context { .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY); - setContextOnScope(newCurrentScope, ctx2); + // `withSetScope` derives `context` from the scope's linked context when that link is still alive, + // so it carries the same active span. Overwriting the link with the short-lived `ctx2` would make + // `getActiveSpan(scope)` lose the span once `ctx2` is garbage collected. + if (!scope || !getContextFromScope(scope)) { + setContextOnScope(newCurrentScope, ctx2); + } return ctx2; } diff --git a/packages/opentelemetry/test/asyncContextStrategy.test.ts b/packages/opentelemetry/test/asyncContextStrategy.test.ts index 38486117e36e..4071a2a6335e 100644 --- a/packages/opentelemetry/test/asyncContextStrategy.test.ts +++ b/packages/opentelemetry/test/asyncContextStrategy.test.ts @@ -1,16 +1,19 @@ import type { Scope } from '@sentry/core'; import { + getActiveSpan, getAsyncContextStrategy, getCurrentScope, getIsolationScope, getMainCarrier, Scope as ScopeClass, setAsyncContextStrategy, + startSpan, withIsolationScope, withScope, } from '@sentry/core'; import { afterAll, beforeEach, describe, expect, it, test } from 'vitest'; import { setOpenTelemetryContextAsyncContextStrategy } from '../src/asyncContextStrategy'; +import { getContextFromScope } from '../src/utils/contextData'; import { mockSdkInit } from './helpers/mockSdkInit'; describe('asyncContextStrategy', () => { @@ -397,6 +400,20 @@ describe('asyncContextStrategy', () => { done(); }); })); + + it('keeps the context link of a passed in scope that is still linked to a context', () => { + startSpan({ name: 'parent' }, parent => { + const scope = getCurrentScope(); + const linkedContext = getContextFromScope(scope); + expect(linkedContext).toBeDefined(); + + withScope(scope, () => { + expect(getActiveSpan()).toBe(parent); + }); + + expect(getContextFromScope(scope)).toBe(linkedContext); + }); + }); }); describe('withIsolationScope()', () => { From 187ee90a773aefec830d1f23a7915bf94c407c74 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Wed, 11 Nov 2026 08:40:56 -0500 Subject: [PATCH 031/136] feat(nextjs): Emit the tunnel route handler (#25424) This overhauls the tunnel implementation of Next.js by doing a few things: - Making the implementation use the same logic we have in the other frameworks/core, so it inherits: - The randomization is DSN based. - Proper forwarding for client IP and several headers. - Memory optimizations due to streaming the request/response. - We now spit a route file with the route, fully capitalizing on Sigrid's #25456 this means: - No need to have `omit` for the transport options. The way it works varies depeding on how the user deploys their application. ### On Conventional Servers/Platforms Our runtime patchers introduced in this stack handle the tunnel request, the user's Next.js app never handles any of these. ### On Vercel We utilize the two-hop idea we did in #25456 by writing a small idempotent app router file. The re-write rules move traffic to the new handler, and the file exports a `POST` handler for the route. ```ts // Generated by @sentry/nextjs for the managed tunnel on Vercel. export { POST } from '@sentry/nextjs/tunnel'; ``` Vercel applies certain rules and responds with 404 for tunnel requests that aren't present in re-writes or app router, so our runtime patchers will never trigger. Which is why this workaround was needed. For everyone else, the runtime patchers will work. --- .../nextjs-16-adapter/next.config.ts | 2 +- .../nextjs-16-adapter/proxy.ts | 3 +- .../tests/proxy-tunnel.test.ts | 10 +- .../instrumentation-client.ts | 3 +- .../nextjs-16-tunnel/next.config.ts | 8 +- .../nextjs-16-tunnel/package.json | 38 +-- .../nextjs-16-tunnel/sentry-dsn.ts | 9 +- .../nextjs-16-tunnel/sentry.edge.config.ts | 3 +- .../nextjs-16-tunnel/sentry.server.config.ts | 3 +- .../tests/tunnel-managed.test.ts | 109 ++++++++ .../tests/tunnel-route.test.ts | 232 +++++------------ .../edge/sentry-tunnel/route.ts | 13 - .../node/sentry-tunnel/route.ts | 1 - .../tunnel-middleware/middleware.ts | 16 ++ .../nextjs-16-tunnel/worker.ts | 6 +- packages/nextjs/src/client/index.ts | 21 +- packages/nextjs/src/client/tunnelRoute.ts | 58 ++--- packages/nextjs/src/cloudflare/index.ts | 14 +- .../devErrorSymbolicationEventProcessor.ts | 4 +- packages/nextjs/src/common/utils/basePath.ts | 13 + .../utils/dropMiddlewareTunnelRequests.ts | 116 +++++---- .../src/common/utils/tunnelPathnameMatch.ts | 49 ++-- .../turbopack/constructTurbopackConfig.ts | 1 + .../turbopack/generateValueInjectionRules.ts | 7 + packages/nextjs/src/config/types.ts | 30 +-- packages/nextjs/src/config/webpack.ts | 3 +- .../src/config/withSentryConfig/buildTime.ts | 7 +- .../getFinalConfigObjectUtils.ts | 76 ++---- .../src/config/withSentryConfig/tunnel.ts | 245 +++++++----------- packages/nextjs/src/edge/index.ts | 19 +- packages/nextjs/src/server/index.ts | 24 +- packages/nextjs/src/server/serverSpanHooks.ts | 2 +- packages/nextjs/src/tunnel/index.ts | 49 +--- packages/nextjs/test/clientSdk.test.ts | 54 +++- .../nextjs/test/cloudflare/withSentry.test.ts | 8 +- .../generateValueInjectionRules.test.ts | 27 +- .../webpack/constructWebpackConfig.test.ts | 23 +- .../test/config/withSentryConfig.test.ts | 6 +- .../config/withSentryConfig/buildTime.test.ts | 12 +- .../getFinalConfigObjectUtils.test.ts | 118 ++++----- .../config/withSentryConfig/tunnel.test.ts | 142 +++++++--- packages/nextjs/test/config/wrappers.test.ts | 6 +- packages/nextjs/test/edgeSdk.test.ts | 95 ++++++- packages/nextjs/test/serverSdk.test.ts | 96 ++++++- packages/nextjs/test/tunnel/index.test.ts | 52 ++-- .../dropMiddlewareTunnelRequests.test.ts | 135 ++++------ .../nextjs/test/utils/tunnelRoute.test.ts | 186 ++----------- 47 files changed, 1140 insertions(+), 1014 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-managed.test.ts delete mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/edge/sentry-tunnel/route.ts delete mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/node/sentry-tunnel/route.ts create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-middleware/middleware.ts create mode 100644 packages/nextjs/src/common/utils/basePath.ts diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/next.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/next.config.ts index 660eddbbfe1f..a71f436dd215 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/next.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/next.config.ts @@ -7,5 +7,5 @@ const nextConfig: NextConfig = { export default withSentryConfig(nextConfig, { silent: true, - tunnelRoute: '/monitoring', + tunnelRoute: true, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/proxy.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/proxy.ts index b5cda0cfaa92..23b61c572e9a 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/proxy.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/proxy.ts @@ -20,5 +20,6 @@ export async function proxy(request: NextRequest) { } export const config = { - matcher: ['/api/proxy-isolation', '/api/proxy-ok', '/monitoring'], + // Every path, so the proxy also runs for the tunnel path, which is derived from the DSN. + matcher: '/:path*', }; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/tests/proxy-tunnel.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/tests/proxy-tunnel.test.ts index 4c8807745ea0..2e0ddf911ba3 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/tests/proxy-tunnel.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/tests/proxy-tunnel.test.ts @@ -1,6 +1,7 @@ import { expect, test } from '@playwright/test'; import { HTTP_TARGET } from '@sentry/conventions/attributes'; import { waitForStreamedSpan, waitForStreamedSpans } from '@sentry-internal/test-utils'; +import { getTunnelPath } from '@sentry/nextjs'; test('drops the `Next.request` root span of tunnel requests through the proxy', async ({ request }) => { // The callback never returns true, so this promise is deliberately left unsettled. The assertions read the array. @@ -18,13 +19,14 @@ test('drops the `Next.request` root span of tunnel requests through the proxy', ); }); - const tunnelResponse = await request.post('/monitoring?o=123&p=456', { data: '{}' }); + // The SDK answers only a POST before the proxy. A GET reaches the proxy, like a tunnel request on Vercel, where the + // proxy runs outside of the server the SDK hooks into. + const tunnelPath = getTunnelPath(process.env.E2E_TEST_DSN); + const tunnelResponse = await request.get(tunnelPath!); expect(tunnelResponse.headers()['x-middleware-next']).toBe('1'); await request.get('/api/proxy-ok'); await proxyOkSpanPromise; - expect(segmentSpans.filter(span => String(span.attributes[HTTP_TARGET]?.value).startsWith('/monitoring'))).toEqual( - [], - ); + expect(segmentSpans.filter(span => String(span.attributes[HTTP_TARGET]?.value).startsWith(tunnelPath!))).toEqual([]); }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/instrumentation-client.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/instrumentation-client.ts index 84b61b956e4a..3762bb3d7d8c 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/instrumentation-client.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/instrumentation-client.ts @@ -4,7 +4,8 @@ import { SENTRY_DSN } from './sentry-dsn'; Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions dsn: SENTRY_DSN, - // No tunnel option - using tunnelRoute from withSentryConfig + // The other variants use the tunnelRoute of withSentryConfig + tunnel: process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'managed' ? true : undefined, tracesSampleRate: 1.0, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/next.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/next.config.ts index ac79f882a572..d060076a192c 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/next.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/next.config.ts @@ -1,9 +1,13 @@ import { withSentryConfig } from '@sentry/nextjs/config'; import type { NextConfig } from 'next'; -const nextConfig: NextConfig = {}; +// The managed variants serve the managed tunnel under a base path and with trailing slashes, without a tunnel route. +const tunnelMode = process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE; +const isManagedMode = tunnelMode === 'managed'; + +const nextConfig: NextConfig = isManagedMode ? { basePath: '/docs', trailingSlash: true } : {}; export default withSentryConfig(nextConfig, { silent: true, - tunnelRoute: true, + tunnelRoute: isManagedMode ? undefined : tunnelMode === 'path' ? '/monitoring' : true, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json index ca42dc5e99a1..7949f9a2312d 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json @@ -4,26 +4,25 @@ "private": true, "scripts": { "dev": " next dev", - "build": "_SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ next build > .tmp_build_stdout 2> .tmp_build_stderr || (cat .tmp_build_stdout && cat .tmp_build_stderr && exit 1)", + "build": "next build > .tmp_build_stdout 2> .tmp_build_stderr || (cat .tmp_build_stdout && cat .tmp_build_stderr && exit 1)", "clean": "npx rimraf node_modules pnpm-lock.yaml .tmp_dev_server_logs", - "dev:webpack": "_SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ next dev --webpack", - "build-webpack": "_SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ next build --webpack > .tmp_build_stdout 2> .tmp_build_stderr || (cat .tmp_build_stdout && cat .tmp_build_stderr && exit 1)", - "start": "_SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ next start", + "dev:webpack": "next dev --webpack", + "build-webpack": "next build --webpack > .tmp_build_stdout 2> .tmp_build_stderr || (cat .tmp_build_stdout && cat .tmp_build_stderr && exit 1)", + "start": "next start", "lint": "eslint", "test:prod": "TEST_ENV=production playwright test", - "test:dev": "TEST_ENV=development _SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ playwright test", - "test:dev-webpack": "TEST_ENV=development-webpack _SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ playwright test", + "test:dev": "TEST_ENV=development playwright test", + "test:dev-webpack": "TEST_ENV=development-webpack playwright test", "test:build": "pnpm install && pnpm build", "test:build-webpack": "pnpm install && pnpm build-webpack", - "test:build-handler": "pnpm install && cp -R tunnel-handler/node/sentry-tunnel app/ && pnpm build", - "test:build-handler-webpack": "pnpm install && cp -R tunnel-handler/edge/sentry-tunnel app/ && pnpm build-webpack", + "test:build-middleware-webpack": "pnpm install && rm proxy.ts && cp tunnel-middleware/middleware.ts middleware.ts && pnpm build-webpack", "test:build-canary": "pnpm install && pnpm add next@canary && pnpm build", "test:build-latest": "pnpm install && pnpm add next@latest && pnpm build", "test:build-latest-webpack": "pnpm install && pnpm add next@latest && pnpm build-webpack", "test:build-canary-webpack": "pnpm install && pnpm add next@canary && pnpm build-webpack", "test:assert": "pnpm test:prod && pnpm test:dev", "test:assert-webpack": "pnpm test:prod && pnpm test:dev-webpack", - "test:build:cloudflare": "pnpm install && _SENTRY_TUNNEL_DESTINATION_OVERRIDE=http://localhost:3031/ opennextjs-cloudflare build", + "test:build:cloudflare": "pnpm install && opennextjs-cloudflare build", "start:cloudflare": "opennextjs-cloudflare preview" }, "dependencies": { @@ -50,23 +49,28 @@ "variants": [ { "build-command": "pnpm test:build-webpack", - "label": "nextjs-16-tunnel (webpack)", + "label": "nextjs-16-tunnel (tunnelRoute: true, webpack)", "assert-command": "pnpm test:assert-webpack" }, { "build-command": "pnpm test:build", - "label": "nextjs-16-tunnel (turbopack)", + "label": "nextjs-16-tunnel (tunnelRoute: true, turbopack)", "assert-command": "pnpm test:assert" }, { - "build-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=handler pnpm test:build-handler", - "label": "nextjs-16-tunnel (handler, turbopack)", - "assert-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=handler pnpm test:assert" + "build-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=path pnpm test:build", + "label": "nextjs-16-tunnel (tunnelRoute path, turbopack)", + "assert-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=path pnpm test:assert" }, { - "build-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=handler pnpm test:build-handler-webpack", - "label": "nextjs-16-tunnel (handler, webpack, edge)", - "assert-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=handler pnpm test:assert-webpack" + "build-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=managed pnpm test:build", + "label": "nextjs-16-tunnel (managed, turbopack)", + "assert-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=managed pnpm test:assert" + }, + { + "build-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=managed pnpm test:build-middleware-webpack", + "label": "nextjs-16-tunnel (managed, webpack, edge middleware)", + "assert-command": "NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE=managed pnpm test:assert-webpack" } ], "optionalVariants": [ diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry-dsn.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry-dsn.ts index fa0ad467f9bc..1030f61fd5cb 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry-dsn.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry-dsn.ts @@ -1,6 +1,3 @@ -// The handler variants send the server events to the event proxy too, so the tests also see server spans. -export const SENTRY_DSN = - process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'handler' - ? 'http://public@localhost:3031/1337' - : // A fake but properly formatted Sentry SaaS DSN, because the rewrite mode tunnels only SaaS DSNs - 'https://public@o12345.ingest.us.sentry.io/67890'; +// The server forwards the tunnel requests to the host of the DSN, so the event proxy gets the browser events and the +// server spans. +export const SENTRY_DSN = 'http://public@localhost:3031/1337'; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.edge.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.edge.config.ts index 0333aa29412b..4a999c80e920 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.edge.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.edge.config.ts @@ -4,7 +4,8 @@ import { SENTRY_DSN } from './sentry-dsn'; Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions dsn: SENTRY_DSN, - // No tunnel option - using tunnelRoute from withSentryConfig + // Serves the managed tunnel of the managed variants + integrations: process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'managed' ? [Sentry.serveTunnelIntegration()] : [], tracesSampleRate: 1.0, // debug: true, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.server.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.server.config.ts index 0333aa29412b..4a999c80e920 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/sentry.server.config.ts @@ -4,7 +4,8 @@ import { SENTRY_DSN } from './sentry-dsn'; Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions dsn: SENTRY_DSN, - // No tunnel option - using tunnelRoute from withSentryConfig + // Serves the managed tunnel of the managed variants + integrations: process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'managed' ? [Sentry.serveTunnelIntegration()] : [], tracesSampleRate: 1.0, // debug: true, }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-managed.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-managed.test.ts new file mode 100644 index 000000000000..fc4d05998566 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-managed.test.ts @@ -0,0 +1,109 @@ +import { expect, test } from '@playwright/test'; +import { HTTP_REQUEST_METHOD, URL_FULL } from '@sentry/conventions/attributes'; +import { getSpanOp, waitForRequest, waitForStreamedSpan, waitForStreamedSpans } from '@sentry-internal/test-utils'; +import type { Event, SerializedStreamedSpan } from '@sentry/core'; + +test.skip(process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE !== 'managed', 'Only the managed variants use it'); + +const BASE_PATH = '/docs'; + +function getStringAttribute(span: SerializedStreamedSpan, key: string): string | undefined { + const attribute = span.attributes[key]; + return attribute?.type === 'string' ? attribute.value : undefined; +} + +// With `trailingSlash`, a POST to the path without the slash would get a redirect. +function isTunnelPath(pathname: string): boolean { + return /^\/docs\/[a-z0-9]+\/$/.test(pathname); +} + +test('sends the pageload span through the managed tunnel under the base path', async ({ page, baseURL }) => { + const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-tunnel', span => { + return getSpanOp(span) === 'pageload' && span.is_segment; + }); + const tunnelResponsePromise = page.waitForResponse( + response => + response.request().method() === 'POST' && + new URL(response.url()).origin === baseURL && + (response.request().postData() ?? '').includes('pageload'), + ); + + await page.goto(BASE_PATH); + + const tunnelResponse = await tunnelResponsePromise; + const pageloadSpan = await pageloadSpanPromise; + + expect(isTunnelPath(new URL(tunnelResponse.url()).pathname)).toBe(true); + expect(tunnelResponse.status()).toBe(200); + expect(pageloadSpan.status).toBe('ok'); +}); + +test('forwards events without the cookies of the browser', async ({ page, context, baseURL }) => { + await context.addCookies([{ name: 'session', value: '8f2c1d', url: baseURL }]); + const proxyRequestPromise = waitForRequest('nextjs-16-tunnel', ({ envelope }) => + envelope[1].some( + ([itemHeader, item]) => + itemHeader.type === 'event' && (item as Event).exception?.values?.[0]?.value === 'Tunnel managed cookie test', + ), + ); + + await page.goto(BASE_PATH); + await page.waitForFunction(() => typeof (window as { __SENTRY__?: unknown }).__SENTRY__ === 'object'); + const tunnelRequestPromise = page.waitForRequest( + request => + request.method() === 'POST' && + new URL(request.url()).origin === baseURL && + (request.postData() ?? '').includes('Tunnel managed cookie test'), + ); + await page.evaluate(() => { + setTimeout(() => { + throw new Error('Tunnel managed cookie test'); + }); + }); + + const tunnelRequest = await tunnelRequestPromise; + const proxyRequest = await proxyRequestPromise; + + expect(isTunnelPath(new URL(tunnelRequest.url()).pathname)).toBe(true); + expect((await tunnelRequest.allHeaders()).cookie).toBe('session=8f2c1d'); + expect(proxyRequest.rawProxyRequestHeaders.cookie).toBeUndefined(); + expect(proxyRequest.rawProxyRequestHeaders['content-type']).toBe('application/x-sentry-envelope'); +}); + +test('does not create server spans for tunnel requests', async ({ page, baseURL }) => { + // One listener, so it gets every span that the proxy received before the barrier span. + const spansBeforeBarrier: SerializedStreamedSpan[] = []; + const barrierSpanPromise = waitForStreamedSpans('nextjs-16-tunnel', spans => { + spansBeforeBarrier.push(...spans); + return spans.some(span => span.is_segment && span.name === 'GET /api/flush'); + }); + const pageloadTunnelResponsePromise = page.waitForResponse( + response => + response.request().method() === 'POST' && + new URL(response.url()).origin === baseURL && + (response.request().postData() ?? '').includes('pageload'), + ); + + await page.goto(BASE_PATH); + await pageloadTunnelResponsePromise; + // The first flush sends the tunnel spans, the second one the barrier span of the first flush. + await page.request.get(`${BASE_PATH}/api/flush`); + await page.request.get(`${BASE_PATH}/api/flush`); + await barrierSpanPromise; + + // The middleware span of the page request arrived, so the ones of the tunnel requests would have too. + expect(spansBeforeBarrier.some(span => span.name === 'middleware GET')).toBe(true); + + const postSpans = spansBeforeBarrier.filter( + span => + span.name.includes('POST') || + getStringAttribute(span, HTTP_REQUEST_METHOD) === 'POST' || + getStringAttribute(span, 'http.method') === 'POST', + ); + const ingestSpans = spansBeforeBarrier.filter( + span => + getSpanOp(span) === 'http.client' && !!getStringAttribute(span, URL_FULL)?.startsWith('http://localhost:3031/'), + ); + expect(postSpans).toEqual([]); + expect(ingestSpans).toEqual([]); +}); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-route.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-route.test.ts index e0c1b5e273ae..f75d167f9deb 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-route.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tests/tunnel-route.test.ts @@ -1,134 +1,70 @@ import { expect, test } from '@playwright/test'; -import { HTTP_REQUEST_METHOD, SERVER_ADDRESS, URL_FULL } from '@sentry/conventions/attributes'; +import { HTTP_REQUEST_METHOD, URL_FULL } from '@sentry/conventions/attributes'; import { getSpanOp, waitForRequest, waitForStreamedSpan, waitForStreamedSpans } from '@sentry-internal/test-utils'; import type { Event, SerializedStreamedSpan } from '@sentry/core'; +test.skip( + process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'managed', + 'The managed variants have no tunnel route, see tunnel-managed.test.ts', +); + function getStringAttribute(span: SerializedStreamedSpan, key: string): string | undefined { const attribute = span.attributes[key]; return attribute?.type === 'string' ? attribute.value : undefined; } -test('Tunnel route should proxy pageload span to Sentry', async ({ page }) => { - // Wait for the pageload span to be sent through the tunnel +// `tunnelRoute: '/monitoring'` in the `path` variant, `tunnelRoute: true` (the path derived from the DSN) otherwise. +function isTunnelPath(pathname: string): boolean { + return process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'path' + ? pathname === '/monitoring' + : /^\/[a-z0-9]{1,7}$/.test(pathname); +} + +test('sends the pageload span through the tunnel route', async ({ page, baseURL }) => { const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-tunnel', span => { return getSpanOp(span) === 'pageload' && span.name === '/' && span.is_segment; }); + const tunnelResponsePromise = page.waitForResponse( + response => + response.request().method() === 'POST' && + new URL(response.url()).origin === baseURL && + (response.request().postData() ?? '').includes('pageload'), + ); - // Navigate to the page await page.goto('/'); + const tunnelResponse = await tunnelResponsePromise; const pageloadSpan = await pageloadSpanPromise; - // Verify the pageload span was received successfully - expect(pageloadSpan).toBeDefined(); - expect(pageloadSpan.name).toBe('/'); - expect(getSpanOp(pageloadSpan)).toBe('pageload'); + expect(isTunnelPath(new URL(tunnelResponse.url()).pathname)).toBe(true); + expect(tunnelResponse.status()).toBe(200); expect(pageloadSpan.status).toBe('ok'); }); -test('Tunnel route should send multiple pageload spans consistently', async ({ page }) => { - // This test verifies that the tunnel route remains consistent across multiple page loads - // (important for Turbopack which could generate different tunnel routes for client/server) - - // First pageload +test('sends the pageload spans of every page load through the tunnel route', async ({ page }) => { const firstPageloadPromise = waitForStreamedSpan('nextjs-16-tunnel', span => { return getSpanOp(span) === 'pageload' && span.name === '/' && span.is_segment; }); await page.goto('/'); - const firstPageload = await firstPageloadPromise; - expect(firstPageload).toBeDefined(); - expect(firstPageload.name).toBe('/'); - expect(getSpanOp(firstPageload)).toBe('pageload'); - expect(firstPageload.status).toBe('ok'); + expect((await firstPageloadPromise).status).toBe('ok'); - // Second pageload (reload) const secondPageloadPromise = waitForStreamedSpan('nextjs-16-tunnel', span => { return getSpanOp(span) === 'pageload' && span.name === '/' && span.is_segment; }); await page.reload(); - const secondPageload = await secondPageloadPromise; - expect(secondPageload).toBeDefined(); - expect(secondPageload.name).toBe('/'); - expect(getSpanOp(secondPageload)).toBe('pageload'); - expect(secondPageload.status).toBe('ok'); + expect((await secondPageloadPromise).status).toBe('ok'); }); -test('Tunnel requests should not create middleware or fetch spans', async ({ page }) => { - // This test verifies that our span filtering logic works correctly - // The proxy runs on all routes, so we'll get a middleware span for `/` - // But we should NOT get middleware or fetch spans for the tunnel route itself - - // Accumulate every streamed span for the duration of the test. The callback never returns true, - // so this promise is deliberately left unsettled - the assertions below read the array instead. - const allSpans: SerializedStreamedSpan[] = []; - void waitForStreamedSpans('nextjs-16-tunnel', spans => { - allSpans.push(...spans); - return false; - }); - - // Wait for pageload span - const pageloadPromise = waitForStreamedSpan('nextjs-16-tunnel', span => { - return getSpanOp(span) === 'pageload' && span.is_segment; - }); - - await page.goto('/'); - const pageloadSpan = await pageloadPromise; - - // Trigger errors to force tunnel POST requests - await page - .evaluate(() => { - throw new Error('Test tunnel error 1'); - }) - .catch(() => { - // Expected to throw - }); - - await page - .evaluate(() => { - throw new Error('Test tunnel error 2'); - }) - .catch(() => { - // Expected to throw - }); - - // Wait for events to be sent through tunnel, and for the spans they would wrongly produce to arrive - await page.waitForTimeout(3000); - - // We should have received the pageload span - expect(pageloadSpan).toBeDefined(); - expect(getSpanOp(pageloadSpan)).toBe('pageload'); - - const middlewareSpans = allSpans.filter(span => getSpanOp(span) === 'middleware'); - - // We WILL have a middleware span for GET / (the pageload) - // But we should NOT have middleware spans for POST requests (tunnel route) - const postMiddlewareSpans = middlewareSpans.filter( - span => span.name.includes('POST') || getStringAttribute(span, HTTP_REQUEST_METHOD) === 'POST', - ); - - expect(postMiddlewareSpans).toHaveLength(0); - - // We should NOT have any fetch spans to Sentry ingest. Matched on the host attribute rather than a - // substring of the full URL, which would also match an arbitrary host with `sentry.io` elsewhere in it. - const sentryFetchSpans = allSpans.filter(span => { - const host = getStringAttribute(span, SERVER_ADDRESS) ?? ''; - return getSpanOp(span) === 'http.client' && (host === 'sentry.io' || host.endsWith('.sentry.io')); - }); - - expect(sentryFetchSpans).toHaveLength(0); -}); - -test('Tunnel requests are sent without the cookies of the browser', async ({ page, context, baseURL }) => { - test.skip(process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE === 'handler', 'The handler variants send the cookies'); +test('forwards events without the cookies of the browser', async ({ page, context, baseURL }) => { await context.addCookies([{ name: 'session', value: '8f2c1d', url: baseURL }]); const proxyRequestPromise = waitForRequest('nextjs-16-tunnel', ({ envelope }) => envelope[1].some( ([itemHeader, item]) => - itemHeader.type === 'event' && (item as Event).exception?.values?.[0]?.value === 'Tunnel cookie test', + itemHeader.type === 'event' && (item as Event).exception?.values?.[0]?.value === 'Tunnel route cookie test', ), ); @@ -138,89 +74,59 @@ test('Tunnel requests are sent without the cookies of the browser', async ({ pag request => request.method() === 'POST' && new URL(request.url()).origin === baseURL && - (request.postData() ?? '').includes('Tunnel cookie test'), + (request.postData() ?? '').includes('Tunnel route cookie test'), ); await page.evaluate(() => { setTimeout(() => { - throw new Error('Tunnel cookie test'); + throw new Error('Tunnel route cookie test'); }); }); const tunnelRequest = await tunnelRequestPromise; const proxyRequest = await proxyRequestPromise; - expect(await page.evaluate(() => document.cookie)).toBe('session=8f2c1d'); - expect((await tunnelRequest.allHeaders()).cookie).toBeUndefined(); + expect(isTunnelPath(new URL(tunnelRequest.url()).pathname)).toBe(true); + // The Vercel rewrite only matches envelope requests. + expect((await tunnelRequest.allHeaders())['content-type']).toBe('application/x-sentry-envelope'); + expect((await tunnelRequest.allHeaders()).cookie).toBe('session=8f2c1d'); expect(proxyRequest.rawProxyRequestHeaders.cookie).toBeUndefined(); + expect(proxyRequest.rawProxyRequestHeaders['content-type']).toBe('application/x-sentry-envelope'); }); -test.describe('Tunnel route handler', () => { - test.skip(process.env.NEXT_PUBLIC_E2E_TEST_TUNNEL_MODE !== 'handler', 'Only the handler variants use the handler'); - - test('forwards events without the cookies of the browser', async ({ page, context, baseURL }) => { - await context.addCookies([{ name: 'session', value: '8f2c1d', url: baseURL }]); - const proxyRequestPromise = waitForRequest('nextjs-16-tunnel', ({ envelope }) => - envelope[1].some( - ([itemHeader, item]) => - itemHeader.type === 'event' && - (item as Event).exception?.values?.[0]?.value === 'Tunnel route handler cookie test', - ), - ); - - await page.goto('/'); - await page.waitForFunction(() => typeof (window as { __SENTRY__?: unknown }).__SENTRY__ === 'object'); - const tunnelRequestPromise = page.waitForRequest( - request => - request.method() === 'POST' && - new URL(request.url()).origin === baseURL && - (request.postData() ?? '').includes('Tunnel route handler cookie test'), - ); - await page.evaluate(() => { - setTimeout(() => { - throw new Error('Tunnel route handler cookie test'); - }); - }); - - const tunnelRequest = await tunnelRequestPromise; - const proxyRequest = await proxyRequestPromise; - - expect(new URL(tunnelRequest.url()).search).toBe(''); - expect((await tunnelRequest.allHeaders()).cookie).toBe('session=8f2c1d'); - expect(proxyRequest.rawProxyRequestHeaders.cookie).toBeUndefined(); - expect(proxyRequest.rawProxyRequestHeaders['content-type']).toBe('application/x-sentry-envelope'); +test('does not create server spans for tunnel requests', async ({ page, baseURL }) => { + // One listener, so it gets every span that the proxy received before the barrier span. + const spansBeforeBarrier: SerializedStreamedSpan[] = []; + const barrierSpanPromise = waitForStreamedSpans('nextjs-16-tunnel', spans => { + spansBeforeBarrier.push(...spans); + return spans.some(span => span.is_segment && span.name === 'GET /api/flush'); }); + const pageloadTunnelResponsePromise = page.waitForResponse( + response => + response.request().method() === 'POST' && + new URL(response.url()).origin === baseURL && + (response.request().postData() ?? '').includes('pageload'), + ); - test('does not create server spans for tunnel requests', async ({ page, baseURL }) => { - // One listener, so it gets every span that the proxy received before the barrier span. - const spansBeforeBarrier: SerializedStreamedSpan[] = []; - const barrierSpanPromise = waitForStreamedSpans('nextjs-16-tunnel', spans => { - spansBeforeBarrier.push(...spans); - return spans.some(span => span.is_segment && span.name === 'GET /api/flush'); - }); - const pageloadTunnelResponsePromise = page.waitForResponse( - response => - response.request().method() === 'POST' && - new URL(response.url()).origin === baseURL && - (response.request().postData() ?? '').includes('pageload'), - ); - - await page.goto('/'); - await pageloadTunnelResponsePromise; - // Flush the edge client of the edge tunnel route (a 405 on the Node.js one), then the Node.js client twice: - // the first flush sends the tunnel spans, the second one the barrier span of the first flush. - await page.request.get('/sentry-tunnel'); - await page.request.get('/api/flush'); - await page.request.get('/api/flush'); - await barrierSpanPromise; - - const postSpans = spansBeforeBarrier.filter( - span => span.name.startsWith('POST') || getStringAttribute(span, HTTP_REQUEST_METHOD) === 'POST', - ); - const ingestSpans = spansBeforeBarrier.filter( - span => - getSpanOp(span) === 'http.client' && !!getStringAttribute(span, URL_FULL)?.startsWith('http://localhost:3031/'), - ); - expect(postSpans).toEqual([]); - expect(ingestSpans).toEqual([]); - }); + await page.goto('/'); + await pageloadTunnelResponsePromise; + // The first flush sends the tunnel spans, the second one the barrier span of the first flush. + await page.request.get('/api/flush'); + await page.request.get('/api/flush'); + await barrierSpanPromise; + + // The middleware span of the page request arrived, so the ones of the tunnel requests would have too. + expect(spansBeforeBarrier.some(span => span.name === 'middleware GET')).toBe(true); + + const postSpans = spansBeforeBarrier.filter( + span => + span.name.includes('POST') || + getStringAttribute(span, HTTP_REQUEST_METHOD) === 'POST' || + getStringAttribute(span, 'http.method') === 'POST', + ); + const ingestSpans = spansBeforeBarrier.filter( + span => + getSpanOp(span) === 'http.client' && !!getStringAttribute(span, URL_FULL)?.startsWith('http://localhost:3031/'), + ); + expect(postSpans).toEqual([]); + expect(ingestSpans).toEqual([]); }); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/edge/sentry-tunnel/route.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/edge/sentry-tunnel/route.ts deleted file mode 100644 index 4eeb13efd97f..000000000000 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/edge/sentry-tunnel/route.ts +++ /dev/null @@ -1,13 +0,0 @@ -import * as Sentry from '@sentry/nextjs'; -import { createSentryTunnelRoute } from '@sentry/nextjs/tunnel'; -import { SENTRY_DSN } from '@/sentry-dsn'; - -export const { POST } = createSentryTunnelRoute({ allowedDsns: [SENTRY_DSN] }); - -// Each edge route has its own SDK client, so the tests flush this one here. -export async function GET(): Promise { - await Sentry.flush(); - return new Response(null, { status: 204 }); -} - -export const runtime = 'edge'; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/node/sentry-tunnel/route.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/node/sentry-tunnel/route.ts deleted file mode 100644 index 23c975fb750d..000000000000 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-handler/node/sentry-tunnel/route.ts +++ /dev/null @@ -1 +0,0 @@ -export { POST } from '@sentry/nextjs/tunnel'; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-middleware/middleware.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-middleware/middleware.ts new file mode 100644 index 000000000000..49cfd8ee0af2 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/tunnel-middleware/middleware.ts @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/nextjs'; +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +export async function middleware(request: NextRequest) { + const tunnelResponse = Sentry.handleTunnelRequestIfMatched(request); + if (tunnelResponse) { + return tunnelResponse; + } + + return NextResponse.next(); +} + +export const config = { + matcher: '/:path*', +}; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/worker.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/worker.ts index 522d8c460dfd..43ae875d27cb 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/worker.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/worker.ts @@ -5,9 +5,9 @@ import handler from './.open-next/worker.js'; export default Sentry.withSentry( () => ({ environment: 'qa', // dynamic sampling bias to keep transactions - dsn: 'https://public@o12345.ingest.us.sentry.io/67890', - // Sends the server spans to the proxy server, so the tests see whether a tunnel request was sampled. - tunnel: 'http://localhost:3031/', + // Sends the server spans and the tunnel requests to the proxy server, so the tests see whether a tunnel request was + // sampled. + dsn: 'http://public@localhost:3031/1337', tracesSampleRate: 1.0, }), handler, diff --git a/packages/nextjs/src/client/index.ts b/packages/nextjs/src/client/index.ts index 9f1ed4e4f768..bd98c6a78a99 100644 --- a/packages/nextjs/src/client/index.ts +++ b/packages/nextjs/src/client/index.ts @@ -1,14 +1,21 @@ // import/export got a false positive, and affects most of our index barrel files // can be removed once following issue is fixed: https://github.com/import-js/eslint-plugin-import/issues/703 /* eslint-disable import/export */ -import type { Client, EventProcessor, Integration } from '@sentry/core'; -import { applySdkMetadata, consoleSandbox, getGlobalScope, GLOBAL_OBJ } from '@sentry/core'; +import type { BrowserTunnelOptions, Client, EventProcessor, Integration } from '@sentry/core'; +import { + _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, + applySdkMetadata, + consoleSandbox, + getGlobalScope, + GLOBAL_OBJ, +} from '@sentry/core'; import type { BrowserOptions } from '@sentry/react'; import { getDefaultIntegrations as getReactDefaultIntegrations, init as reactInit } from '@sentry/react'; import { DEBUG_BUILD } from '../common/debug-build'; import { devErrorSymbolicationEventProcessor } from '../common/devErrorSymbolicationEventProcessor'; import { getClientVercelEnv } from '../common/getVercelEnv'; import { isRedirectNavigationError } from '../common/nextNavigationErrorUtils'; +import { getInjectedBasePath } from '../common/utils/basePath'; import { browserTracingIntegration } from './browserTracingIntegration'; import { nextjsClientStackFrameNormalizationIntegration } from './clientNormalizationIntegration'; import { createNextRouteProvider } from './routing/routeProvider'; @@ -24,7 +31,6 @@ export { captureRouterTransitionStart } from './routing/appRouterRoutingInstrume const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewriteFramesAssetPrefixPath: string; _sentryAssetPrefix?: string; - _sentryBasePath?: string; _sentryRelease?: string; _experimentalThirdPartyOriginStackFrames?: string; }; @@ -55,6 +61,13 @@ export function init(options: BrowserOptions): Client | undefined { } satisfies BrowserOptions; applyTunnelRouteOption(opts); + // The managed tunnel is served under the app's `basePath` and `trailingSlash`, like every other route. Options the + // user set win. + const tunnelDefaults: BrowserTunnelOptions = { basePath: getInjectedBasePath() }; + if (process.env._sentryTrailingSlash) { + tunnelDefaults.trailingSlash = true; + } + opts.tunnel = applyBrowserTunnelDefaults(opts.tunnel, tunnelDefaults); applySdkMetadata(opts, 'nextjs', ['nextjs', 'react']); opts.ignoreSpans = [ @@ -104,7 +117,7 @@ function getDefaultIntegrations(options: BrowserOptions): Integration[] { globalWithInjectedValues._sentryRewriteFramesAssetPrefixPath || ''; const assetPrefix = process.env._sentryAssetPrefix || globalWithInjectedValues._sentryAssetPrefix; - const basePath = process.env._sentryBasePath || globalWithInjectedValues._sentryBasePath; + const basePath = getInjectedBasePath(); const experimentalThirdPartyOriginStackFrames = process.env._experimentalThirdPartyOriginStackFrames === 'true' || globalWithInjectedValues._experimentalThirdPartyOriginStackFrames === 'true'; diff --git a/packages/nextjs/src/client/tunnelRoute.ts b/packages/nextjs/src/client/tunnelRoute.ts index 72f2855e32ae..d09fa8e53e40 100644 --- a/packages/nextjs/src/client/tunnelRoute.ts +++ b/packages/nextjs/src/client/tunnelRoute.ts @@ -1,50 +1,24 @@ -import { debug, dsnFromString, GLOBAL_OBJ } from '@sentry/core'; import type { BrowserOptions } from '@sentry/react'; -import { DEBUG_BUILD } from '../common/debug-build'; -import type { TunnelRouteMode } from '../common/utils/tunnelPathnameMatch'; - -const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - _sentryRewritesTunnelPath?: string; - _sentryTunnelRouteMode?: TunnelRouteMode; -}; +import { getInjectedTunnelRoute } from '../common/utils/tunnelPathnameMatch'; /** - * Applies the `tunnel` option to the Next.js SDK options based on `withSentryConfig`'s `tunnelRoute` option. + * Sends events through the managed tunnel when `withSentryConfig` has a `tunnelRoute`, unless `Sentry.init` sets its + * own `tunnel`. A fixed path goes in as `path`, so the browser sends the envelope content type the Vercel rewrite + * matches, and gets the trailing slash Next.js would otherwise redirect a POST to. */ export function applyTunnelRouteOption(options: BrowserOptions): void { - const tunnelRouteOption = process.env._sentryRewritesTunnelPath || globalWithInjectedValues._sentryRewritesTunnelPath; - if (tunnelRouteOption && options.dsn) { - const dsnComponents = dsnFromString(options.dsn); - if (!dsnComponents) { - return; - } - - // The handler reads the DSN from the envelope, so it needs no query and no SaaS DSN. - const tunnelRouteMode = process.env._sentryTunnelRouteMode || globalWithInjectedValues._sentryTunnelRouteMode; - if (tunnelRouteMode === 'handler') { - options.tunnel = tunnelRouteOption; - DEBUG_BUILD && debug.log(`Tunneling events to "${tunnelRouteOption}"`); - return; - } + const tunnelRoute = getInjectedTunnelRoute(); + if (!tunnelRoute || options.tunnel) { + return; + } - const sentrySaasDsnMatch = dsnComponents.host.match(/^o(\d+)\.ingest(?:\.([a-z]{2}))?\.sentry\.io$/); - if (sentrySaasDsnMatch) { - const orgId = sentrySaasDsnMatch[1]; - const regionCode = sentrySaasDsnMatch[2]; - let tunnelPath = `${tunnelRouteOption}?o=${orgId}&p=${dsnComponents.projectId}`; - if (regionCode) { - tunnelPath += `&r=${regionCode}`; - } - options.tunnel = tunnelPath; - // The tunnel route is same-origin, so fetch would include credentials (cookies, HTTP authentication) that the - // tunnel does not need. - options.transportOptions = { - ...options.transportOptions, - fetchOptions: { credentials: 'omit', ...options.transportOptions?.fetchOptions }, - }; - DEBUG_BUILD && debug.log(`Tunneling events to "${tunnelPath}"`); - } else { - DEBUG_BUILD && debug.warn('Provided DSN is not a Sentry SaaS DSN. Will not tunnel events.'); - } + if (tunnelRoute === true) { + options.tunnel = true; + return; } + + options.tunnel = { + path: tunnelRoute, + trailingSlash: !!process.env._sentryTrailingSlash && !tunnelRoute.endsWith('/'), + }; } diff --git a/packages/nextjs/src/cloudflare/index.ts b/packages/nextjs/src/cloudflare/index.ts index 5c8b65007cd4..182c62276730 100644 --- a/packages/nextjs/src/cloudflare/index.ts +++ b/packages/nextjs/src/cloudflare/index.ts @@ -6,8 +6,14 @@ import { withSentry as withSentryCloudflare } from '@sentry/cloudflare'; import type { Integration } from '@sentry/core'; import { applySdkMetadata, extractTraceparentData, getRootSpan, GLOBAL_OBJ, spanToJSON } from '@sentry/core'; import { registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry'; +import { + _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, + _INTERNAL_setTunnelDefaults as setTunnelDefaults, +} from '@sentry/core/server'; import { ATTR_NEXT_SPAN_TYPE } from '../common/nextSpanAttributes'; +import { getInjectedBasePath } from '../common/utils/basePath'; import { isTunnelRouteSpan } from '../common/utils/dropMiddlewareTunnelRequests'; +import { getTunnelRouteServerOptions } from '../common/utils/tunnelPathnameMatch'; import { dropReactControlFlowErrorsEventProcessor } from '../common/utils/dropReactControlFlowErrors'; import { markAsyncContextOwnedByNextjsCloudflare } from '../common/utils/responseEnd'; import { NextSentryPropagator } from '../server/nextSentryPropagator'; @@ -57,7 +63,7 @@ const nextjsIntegration = (): Integration => ({ registerPrepareSpanScope(client); // `dropMiddlewareTunnelRequests` only marks spans of Next.js, which are children of the root span of `withSentry`. client.on('beforeSampling', samplingData => { - if (isTunnelRouteSpan(samplingData.spanAttributes)) { + if (isTunnelRouteSpan(samplingData.spanAttributes, client)) { samplingData.parentSampled = false; } }); @@ -74,6 +80,12 @@ export const withSentry: typeof withSentryCloudflare = (optionsCallback, handler return withSentryCloudflare(env => { const options: CloudflareOptions = { enableOpenTelemetrySetup: true, ...optionsCallback(env) }; + // Read per request: the global is set once `instrumentation` loads, which can be after the Worker entry. + setTunnelDefaults({ + basePath: getInjectedBasePath(), + tunnel: getTunnelRouteServerOptions(), + forward: forwardTunnelRequest, + }); options.ignoreSpans = [ ...(options.ignoreSpans || []), ...NEXTJS_SERVER_IGNORE_SPANS, diff --git a/packages/nextjs/src/common/devErrorSymbolicationEventProcessor.ts b/packages/nextjs/src/common/devErrorSymbolicationEventProcessor.ts index f70990a173e8..46d491457c74 100644 --- a/packages/nextjs/src/common/devErrorSymbolicationEventProcessor.ts +++ b/packages/nextjs/src/common/devErrorSymbolicationEventProcessor.ts @@ -3,6 +3,7 @@ import { debug, GLOBAL_OBJ, parseSemver, suppressTracing } from '@sentry/core'; import type { StackFrame } from 'stacktrace-parser'; import * as stackTraceParser from 'stacktrace-parser'; import { DEBUG_BUILD } from './debug-build'; +import { getInjectedBasePath } from './utils/basePath'; import { URL_FULL } from '@sentry/conventions/attributes'; type OriginalStackFrameResponse = { @@ -12,7 +13,6 @@ type OriginalStackFrameResponse = { }; const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - _sentryBasePath?: string; _sentryNextJsVersion: string | undefined; }; @@ -21,7 +21,7 @@ const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { * Returns only the base path when running in the browser (client-side) for relative URLs. */ function getDevServerBaseUrl(): string { - let basePath = process.env._sentryBasePath ?? globalWithInjectedValues._sentryBasePath ?? ''; + let basePath = getInjectedBasePath() ?? ''; // Prefix the basepath with a slash if it doesn't have one if (basePath !== '' && !basePath.match(/^\//)) { diff --git a/packages/nextjs/src/common/utils/basePath.ts b/packages/nextjs/src/common/utils/basePath.ts new file mode 100644 index 000000000000..b3dec3d72e9a --- /dev/null +++ b/packages/nextjs/src/common/utils/basePath.ts @@ -0,0 +1,13 @@ +import { GLOBAL_OBJ } from '@sentry/core'; + +const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { + _sentryBasePath?: string; +}; + +/** + * The app's `basePath`, which `withSentryConfig` injects. The client bundle reads it from `env`. On the server, + * `@sentry/nextjs` is external, so `env` isn't inlined there and it reads the injected global instead. + */ +export function getInjectedBasePath(): string | undefined { + return process.env._sentryBasePath || globalWithInjectedValues._sentryBasePath; +} diff --git a/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts b/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts index 8baa168fa031..596ff04d7a8d 100644 --- a/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts +++ b/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts @@ -1,19 +1,35 @@ import { HTTP_TARGET, URL_FULL, URL_PATH, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; -import type { ClientOptions, RawAttributes } from '@sentry/core'; -import { escapeStringForRegex, getClient, GLOBAL_OBJ, isSentryRequestUrl, type Span } from '@sentry/core'; +import type { Client, ClientOptions, RawAttributes } from '@sentry/core'; +import { + _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, + escapeStringForRegex, + getClient, + isSentryRequestUrl, + type Span, +} from '@sentry/core'; +import { _INTERNAL_getServedTunnel as getServedTunnel } from '@sentry/core/server'; import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_TYPE } from '../nextSpanAttributes'; import { getTunnelRouteRequestPattern, isPathnameUnderSentryTunnelRoute, TUNNEL_ROUTE_HANDLER_PATH, - type TunnelRouteMode, } from './tunnelPathnameMatch'; import { TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION } from '../span-attributes-with-logic-attached'; -const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - _sentryRewritesTunnelPath?: string; - _sentryTunnelRouteMode?: TunnelRouteMode; -}; +/** + * The paths of the managed tunnel the client serves, with the `basePath`: the ones derived from the DSNs, or the fixed + * one. + */ +function getServedTunnelPaths(client: Client | undefined): string[] { + const servedTunnel = getServedTunnel(client); + if (!servedTunnel) { + return []; + } + + const basePath = normalizeTunnelBasePath(servedTunnel.basePath); + + return servedTunnel.paths.map(path => `${basePath}${path}`); +} /** * Drops spans for tunnel requests from middleware, fetch instrumentation, or BaseServer.handleRequest. @@ -24,12 +40,12 @@ const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { export function dropMiddlewareTunnelRequests( span: Span, attrs: RawAttributes> | undefined, + client: Client | undefined = getClient(), ): void { // When the user brings their own OTel setup (enableOpenTelemetrySetup: false), we should not // mutate their spans with Sentry-internal attributes as it pollutes their tracing backends. if ( - (getClient()?.getOptions() as { enableOpenTelemetrySetup?: boolean } | undefined)?.enableOpenTelemetrySetup === - false + (client?.getOptions() as { enableOpenTelemetrySetup?: boolean } | undefined)?.enableOpenTelemetrySetup === false ) { return; } @@ -49,8 +65,8 @@ export function dropMiddlewareTunnelRequests( } // Check if this is either a tunnel route request or a Sentry ingest request - const isTunnel = isTunnelRouteSpan(attrs || {}); - const isSentry = isSentryRequestSpan(attrs || {}); + const isTunnel = isTunnelRouteSpan(attrs || {}, client); + const isSentry = isSentryRequestSpan(attrs || {}, client); if (isTunnel || isSentry) { // Mark the span to be dropped @@ -58,21 +74,24 @@ export function dropMiddlewareTunnelRequests( } } -function isSentryRequestSpan(attrs: RawAttributes>): boolean { +function isSentryRequestSpan(attrs: RawAttributes>, client: Client | undefined): boolean { const httpUrl = attrs[URL_FULL]; if (!httpUrl) { return false; } - return isSentryRequestUrl(httpUrl.toString(), getClient()); + return isSentryRequestUrl(httpUrl.toString(), client); } /** * Checks if a span's HTTP target matches the tunnel route. */ -export function isTunnelRouteSpan(spanAttributes: Record): boolean { - const tunnelPath = globalWithInjectedValues._sentryRewritesTunnelPath || process.env._sentryRewritesTunnelPath; - if (!tunnelPath) { +export function isTunnelRouteSpan( + spanAttributes: Record, + client: Client | undefined = getClient(), +): boolean { + const tunnelPaths = getServedTunnelPaths(client); + if (!tunnelPaths.length) { return false; } @@ -85,57 +104,42 @@ export function isTunnelRouteSpan(spanAttributes: Record): bool // Extract pathname from the target (e.g., "/tunnel?o=123&p=456" -> "/tunnel") const pathname = target.split('?')[0] || ''; - return isPathnameUnderSentryTunnelRoute(pathname, tunnelPath); + return tunnelPaths.some(tunnelPath => isPathnameUnderSentryTunnelRoute(pathname, tunnelPath)); } return false; } /** - * Returns `ignoreSpans` entries for the spans of incoming tunnel requests. + * Returns `ignoreSpans` entries for the spans of incoming requests to the tunnel the client serves. Call it after + * `init`, which sets up the served tunnel. * - * Span streaming checks `ignoreSpans` at span start, before `dropMiddlewareTunnelRequests` runs. The entries match only - * Next.js request spans, so other spans with the same path are kept. + * Span streaming checks `ignoreSpans` at span start, before `dropMiddlewareTunnelRequests` runs. Next.js sets only + * `http.target` then, which the `url.path` filters of the managed tunnel don't read. The entries match only Next.js + * request spans, so other spans with the same path are kept. */ -export function getTunnelRouteIgnoreSpans(): NonNullable { - const tunnelPath = globalWithInjectedValues._sentryRewritesTunnelPath || process.env._sentryRewritesTunnelPath; - if (!tunnelPath) { +export function getTunnelRouteIgnoreSpans(client: Client | undefined): NonNullable { + const tunnelPaths = getServedTunnelPaths(client); + if (!tunnelPaths.length) { return []; } - const tunnelRouteMode = - (globalWithInjectedValues._sentryTunnelRouteMode || process.env._sentryTunnelRouteMode) === 'handler' - ? 'handler' - : 'rewrite'; - const tunnelRequestIgnoreSpan = { - attributes: { - [ATTR_NEXT_SPAN_TYPE]: /^(?:BaseServer\.handleRequest|Middleware\.execute)$/, - // Next.js sets only `http.target` at span start. - // eslint-disable-next-line typescript/no-deprecated - [HTTP_TARGET]: getTunnelRouteRequestPattern(tunnelPath, tunnelRouteMode), - }, - }; - - // Since Next.js 16.4.3, a proxy invoked separately from the render runs under a `Next.request` root span. Its - // `http.target` is the pathname only, so the query of a rewrite-mode tunnel request can't be matched. - const proxyRootSpanIgnoreSpan = { - attributes: { - [ATTR_NEXT_SPAN_TYPE]: /^Next\.request$/, - // eslint-disable-next-line typescript/no-deprecated - [HTTP_TARGET]: new RegExp(`^${escapeStringForRegex(tunnelPath)}/?$`), + return [ + { + attributes: { + // Since Next.js 16.4.3, a proxy invoked separately from the render runs under a `Next.request` root span. + [ATTR_NEXT_SPAN_TYPE]: /^(?:BaseServer\.handleRequest|Middleware\.execute|Next\.request)$/, + // Next.js sets only `http.target` at span start. + // eslint-disable-next-line typescript/no-deprecated + [HTTP_TARGET]: getTunnelRouteRequestPattern(tunnelPaths), + }, }, - }; - - if (tunnelRouteMode !== 'handler') { - return [tunnelRequestIgnoreSpan, proxyRootSpanIgnoreSpan]; - } - - // On edge, the root span of a route handler has only `next.route`, with a `/route` suffix before Next.js 16. - const tunnelRouteHandlerIgnoreSpan = { - attributes: { - [ATTR_NEXT_SPAN_TYPE]: /^AppRouteRouteHandlers\.runHandler$/, - [ATTR_NEXT_ROUTE]: new RegExp(`^${escapeStringForRegex(TUNNEL_ROUTE_HANDLER_PATH)}(?:/route)?$`), + { + // On edge, the root span of a route handler has only `next.route`, with a `/route` suffix before Next.js 16. + attributes: { + [ATTR_NEXT_SPAN_TYPE]: /^AppRouteRouteHandlers\.runHandler$/, + [ATTR_NEXT_ROUTE]: new RegExp(`^${escapeStringForRegex(TUNNEL_ROUTE_HANDLER_PATH)}(?:/route)?$`), + }, }, - }; - return [tunnelRequestIgnoreSpan, proxyRootSpanIgnoreSpan, tunnelRouteHandlerIgnoreSpan]; + ]; } diff --git a/packages/nextjs/src/common/utils/tunnelPathnameMatch.ts b/packages/nextjs/src/common/utils/tunnelPathnameMatch.ts index 2c5dc8bb1dd1..fb20dfd787da 100644 --- a/packages/nextjs/src/common/utils/tunnelPathnameMatch.ts +++ b/packages/nextjs/src/common/utils/tunnelPathnameMatch.ts @@ -1,4 +1,9 @@ -import { escapeStringForRegex } from '@sentry/core'; +import type { ServerTunnelOptions } from '@sentry/core'; +import { escapeStringForRegex, GLOBAL_OBJ } from '@sentry/core'; + +const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { + _sentryTunnelRoute?: string; +}; /** * The path of the tunnel route handler (`app/sentry-tunnel/route.ts`). @@ -7,10 +12,31 @@ import { escapeStringForRegex } from '@sentry/core'; export const TUNNEL_ROUTE_HANDLER_PATH = '/sentry-tunnel'; /** - * `rewrite`: the tunnel route proxies requests to Sentry with all their headers. - * `handler`: the tunnel route goes to the tunnel route handler, which forwards only the envelope. + * The `tunnelRoute` of `withSentryConfig`, which `withSentryConfig` injects: the fixed tunnel path with the `basePath`, + * or `true` for the path derived from the DSN. The client bundle reads it from `env`. On the server, `@sentry/nextjs` is + * external, so `env` isn't inlined there and it reads the injected global instead. + */ +export function getInjectedTunnelRoute(): string | true | undefined { + const tunnelRoute = process.env._sentryTunnelRoute || globalWithInjectedValues._sentryTunnelRoute; + if (!tunnelRoute) { + return undefined; + } + + return tunnelRoute === 'true' ? true : tunnelRoute; +} + +/** + * The managed tunnel the `tunnelRoute` enables on the server, like `serveTunnelIntegration` with these options. A fixed + * path already has the `basePath`. */ -export type TunnelRouteMode = 'rewrite' | 'handler'; +export function getTunnelRouteServerOptions(): Omit | undefined { + const tunnelRoute = getInjectedTunnelRoute(); + if (!tunnelRoute) { + return undefined; + } + + return tunnelRoute === true ? {} : { path: tunnelRoute }; +} /** * Returns true when `pathname` is exactly the Sentry tunnel route or a sub-path @@ -22,16 +48,9 @@ export function isPathnameUnderSentryTunnelRoute(pathname: string, tunnelPath: s } /** - * Returns a pattern for the request targets (path and query) that the tunnel rewrite serves. - * It must never match more than the rewrite, see GHSA-mchm-gjx6-7h55. - * - * - `handler`: the path, with an optional trailing slash and any query. - * - `rewrite`: also exactly the query that `applyTunnelRouteOption` sends. A looser query match is unsafe, because - * Next.js reads the last value of a repeated param. + * Returns a pattern for the request targets (path and query) of the tunnel paths: a path, with an optional trailing + * slash and any query. It must never match more than the tunnel paths, see GHSA-mchm-gjx6-7h55. */ -export function getTunnelRouteRequestPattern(tunnelPath: string, tunnelRouteMode: TunnelRouteMode): RegExp { - const pathPattern = `^${escapeStringForRegex(tunnelPath)}/?`; - return tunnelRouteMode === 'handler' - ? new RegExp(`${pathPattern}(?:\\?|$)`) - : new RegExp(`${pathPattern}\\?o=\\d+&p=\\d+(?:&r=[a-z]{2})?$`); +export function getTunnelRouteRequestPattern(tunnelPaths: string[]): RegExp { + return new RegExp(`^(?:${tunnelPaths.map(escapeStringForRegex).join('|')})/?(?:\\?|$)`); } diff --git a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts index da0ca895c246..bd124eec37ba 100644 --- a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts +++ b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts @@ -59,6 +59,7 @@ export function constructTurbopackConfig({ nextJsVersion, tunnelRouteValues: getTunnelRouteInjectedValues(userNextConfig, userSentryOptions), vercelCronsConfig, + basePath: userNextConfig.basePath, }); for (const { matcher, rule } of valueInjectionRules) { diff --git a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts index 22c81f00102b..b334a096b1f1 100644 --- a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts +++ b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts @@ -13,11 +13,13 @@ export function generateValueInjectionRules({ nextJsVersion, tunnelRouteValues, vercelCronsConfig, + basePath, }: { routeManifest?: RouteManifest; nextJsVersion?: string; tunnelRouteValues?: TunnelRouteInjectedValues; vercelCronsConfig?: VercelCronsConfig; + basePath?: string; }): TurbopackMatcherWithRule[] { const rules: TurbopackMatcherWithRule[] = []; const isomorphicValues: Record = { ...tunnelRouteValues }; @@ -29,6 +31,11 @@ export function generateValueInjectionRules({ isomorphicValues._sentryNextJsVersion = nextJsVersion; } + // The server reads it to serve the managed tunnel under the base path. + if (basePath) { + isomorphicValues._sentryBasePath = basePath; + } + if (routeManifest) { clientValues._sentryRouteManifest = JSON.stringify(routeManifest); } diff --git a/packages/nextjs/src/config/types.ts b/packages/nextjs/src/config/types.ts index 7c990a480e51..d4a2da1c56a3 100644 --- a/packages/nextjs/src/config/types.ts +++ b/packages/nextjs/src/config/types.ts @@ -31,6 +31,8 @@ export type NextConfigObject = { assetPrefix?: string; // The root at which the nextjs app will be served (defaults to "/") basePath?: string; + // Whether URLs end with a slash, which Next.js redirects to for paths without one + trailingSlash?: boolean; // Config which will be available at runtime publicRuntimeConfig?: { [key: string]: unknown }; // File extensions that count as pages in the `pages/` directory @@ -282,31 +284,17 @@ export type SentryBuildOptions = Omit< /** * Tunnel Sentry requests through this route on the Next.js server, to circumvent ad-blockers blocking Sentry events - * from being sent. This option should be a path (for example: '/error-monitoring'). + * from being sent. It turns on the managed tunnel, like `tunnel: true` in the browser `Sentry.init` together with + * `serveTunnelIntegration()` in the server `Sentry.init`. * - * - Pass `true` to auto-generate a random, ad-blocker-resistant route for each build + * - Pass `true` to use the path derived from the DSN * - Pass a string path (e.g., '/monitoring') to use a custom route * - * By default, the tunnel route proxies each request to Sentry with its headers. To forward only the event payload, - * create `app/sentry-tunnel/route.ts` (or `src/app/sentry-tunnel/route.ts`, not in a route - * group) with: + * The server forwards only the event payload, for the DSN of the server SDK. A `tunnel` or `serveTunnelIntegration` + * you set in `Sentry.init` wins over this option. * - * ```ts - * export { POST } from '@sentry/nextjs/tunnel'; - * ``` - * - * This handler accepts the DSN of the server SDK, also a self-hosted one. For other DSNs, use - * `createSentryTunnelRoute` from the same import. - * - * Tunnel requests go through your middleware (`proxy.ts` / `middleware.ts`) like any other request. If your - * middleware redirects or blocks unauthenticated requests, exclude the tunnel route in its `matcher` so events - * can reach Sentry. Matchers have to be static, so use a fixed string route in that case rather than `true`. - * - * Without the route handler, the browser sends tunnel requests with `credentials: 'omit'`, so without cookies or HTTP - * authentication. If a layer in front of your app needs them (for example Vercel Deployment Protection or HTTP Basic authentication), set - * `transportOptions: { fetchOptions: { credentials: 'same-origin' } }` in `Sentry.init` of `instrumentation-client.ts`. - * - * NOTE: This feature only works with Next.js 11+ + * @deprecated Set `tunnel: true` in the browser `Sentry.init` and add `serveTunnelIntegration()` to the server + * `Sentry.init` instead. The server answers the tunnel requests, also on Vercel. */ tunnelRoute?: string | boolean; diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index b7c1efa5cb65..0b885b50a2a2 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -714,7 +714,8 @@ function addValueInjectionLoader({ // Having a release defined in dev-mode spams releases in Sentry so we only set one in non-dev mode // Only inject if release creation is not explicitly disabled (to maintain build determinism) SENTRY_RELEASE: releaseToInject && !buildContext.dev ? { id: releaseToInject } : undefined, - _sentryBasePath: buildContext.dev ? userNextConfig.basePath : undefined, + // The server reads it to serve the managed tunnel under the base path, dev symbolication to reach the dev server. + _sentryBasePath: userNextConfig.basePath, // This is used to determine version-based dev-symbolication behavior _sentryNextJsVersion: nextJsVersion, }; diff --git a/packages/nextjs/src/config/withSentryConfig/buildTime.ts b/packages/nextjs/src/config/withSentryConfig/buildTime.ts index 3dfe1648982a..4aeea9350852 100644 --- a/packages/nextjs/src/config/withSentryConfig/buildTime.ts +++ b/packages/nextjs/src/config/withSentryConfig/buildTime.ts @@ -33,7 +33,7 @@ export function setUpBuildTimeVariables( _sentryRewriteFramesAssetPrefixPath: assetPrefix ? new URL(assetPrefix, 'http://dogs.are.great').pathname.replace(/\/$/, '') : '', - ...getTunnelRouteInjectedValues(userNextConfig, userSentryOptions, projectDir), + ...getTunnelRouteInjectedValues(userNextConfig, userSentryOptions), }; if (userNextConfig.assetPrefix) { @@ -48,6 +48,11 @@ export function setUpBuildTimeVariables( buildTimeVariables._sentryBasePath = basePath; } + // Next redirects a POST to the tunnel path without the slash, so the browser posts to the one with it. + if (userNextConfig.trailingSlash) { + buildTimeVariables._sentryTrailingSlash = 'true'; + } + if (userNextConfig.assetPrefix) { buildTimeVariables._sentryAssetPrefix = userNextConfig.assetPrefix; } diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts index a90529b8d24d..813f24b58df7 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts @@ -10,16 +10,10 @@ import type { RouteManifest } from '../manifest/types'; import type { NextConfigObject, SentryBuildOptions } from '../types'; import { DEFAULT_PAGE_EXTENSIONS, requiresInstrumentationHook } from '../util'; import { getGitRevision, getInstrumentationClientFileContents } from './buildTime'; -import { - findTunnelRouteHandlerFile, - resolveTunnelRoute, - setUpTunnelHandlerRewrite, - setUpTunnelRewriteRules, -} from './tunnel'; +import { setUpManagedTunnelVercelRoute } from './tunnel'; let showedExportModeTunnelWarning = false; -let showedUnusedTunnelRouteHandlerWarning = false; -let showedTunnelRouteHandlerModeLog = false; +let showedDeprecatedTunnelRouteWarning = false; let showedExperimentalBuildModeWarning = false; const MISSING_INSTRUMENTATION_FILE_WARNING_SHOWN = '__SENTRY_MISSING_INSTRUMENTATION_FILE_WARNING_SHOWN__'; @@ -37,70 +31,36 @@ export function resolveReleaseName(userSentryOptions: SentryBuildOptions): strin } /** - * Applies tunnel-route rewrites, if configured. Uses handler mode if the project has a tunnel route handler file. + * Sets up the route of the managed tunnel on Vercel. A `tunnelRoute` turns on the managed tunnel at its path, or at + * the path derived from the DSN for `true`, which the client, server and edge SDKs read from the injected values. * - * Note: this mutates `userSentryOptions` (to store the resolved tunnel route) and `incomingUserNextConfigObject`. + * Note: this mutates `incomingUserNextConfigObject`. */ export function maybeSetUpTunnelRouteRewriteRules( incomingUserNextConfigObject: NextConfigObject, userSentryOptions: SentryBuildOptions, ): void { - if (userSentryOptions.tunnelRoute === undefined) { - maybeWarnAboutUnusedTunnelRouteHandler(incomingUserNextConfigObject, userSentryOptions.silent); - return; - } - - if (!userSentryOptions.tunnelRoute) { - return; - } - - if (incomingUserNextConfigObject.output === 'export') { - if (!showedExportModeTunnelWarning) { - showedExportModeTunnelWarning = true; - getBuildLogger(userSentryOptions.silent).warn( - '[@sentry/nextjs] The Sentry Next.js SDK `tunnelRoute` option will not work in combination with Next.js static exports. The `tunnelRoute` option uses server-side features that cannot be accessed in export mode. If you still want to tunnel Sentry events, set up your own tunnel: https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option', - ); - } - return; - } - - // Update the global options object to use the resolved value everywhere - const resolvedTunnelRoute = resolveTunnelRoute(userSentryOptions.tunnelRoute); - userSentryOptions.tunnelRoute = resolvedTunnelRoute || undefined; - - const tunnelRouteHandlerFile = findTunnelRouteHandlerFile(incomingUserNextConfigObject.pageExtensions); - if (!tunnelRouteHandlerFile) { - setUpTunnelRewriteRules(incomingUserNextConfigObject, resolvedTunnelRoute); - return; - } - - setUpTunnelHandlerRewrite(incomingUserNextConfigObject, resolvedTunnelRoute); - - if (!showedTunnelRouteHandlerModeLog) { - showedTunnelRouteHandlerModeLog = true; - getBuildLogger(userSentryOptions.silent).log( - `[@sentry/nextjs] The tunnel route sends events through ${tunnelRouteHandlerFile}. Only the event payload goes to Sentry.`, + // oxlint-disable-next-line typescript/no-deprecated -- reads the deprecated option to keep it working + const tunnelRoute = userSentryOptions.tunnelRoute; + if (tunnelRoute !== undefined && !showedDeprecatedTunnelRouteWarning) { + showedDeprecatedTunnelRouteWarning = true; + getBuildLogger(userSentryOptions.silent).warn( + '[@sentry/nextjs] The `tunnelRoute` option is deprecated. Set `tunnel: true` in the browser `Sentry.init` and add `serveTunnelIntegration()` to the server `Sentry.init` instead.', ); } -} -function maybeWarnAboutUnusedTunnelRouteHandler( - incomingUserNextConfigObject: NextConfigObject, - silent: boolean | undefined, -): void { - if (showedUnusedTunnelRouteHandlerWarning || incomingUserNextConfigObject.output === 'export') { + if (tunnelRoute === false || tunnelRoute === '') { return; } - const tunnelRouteHandlerFile = findTunnelRouteHandlerFile(incomingUserNextConfigObject.pageExtensions); - if (!tunnelRouteHandlerFile) { - return; + if (tunnelRoute && incomingUserNextConfigObject.output === 'export' && !showedExportModeTunnelWarning) { + showedExportModeTunnelWarning = true; + getBuildLogger(userSentryOptions.silent).warn( + '[@sentry/nextjs] The Sentry Next.js SDK `tunnelRoute` option will not work in combination with Next.js static exports. The `tunnelRoute` option uses server-side features that cannot be accessed in export mode. If you still want to tunnel Sentry events, set up your own tunnel: https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option', + ); } - showedUnusedTunnelRouteHandlerWarning = true; - getBuildLogger(silent).warn( - `[@sentry/nextjs] Found ${tunnelRouteHandlerFile}, but the \`tunnelRoute\` option is not set. Set \`tunnelRoute\` in \`withSentryConfig\` to send events through this route.`, - ); + setUpManagedTunnelVercelRoute(incomingUserNextConfigObject); } /** diff --git a/packages/nextjs/src/config/withSentryConfig/tunnel.ts b/packages/nextjs/src/config/withSentryConfig/tunnel.ts index d0b45bd6ec8c..031e76604aca 100644 --- a/packages/nextjs/src/config/withSentryConfig/tunnel.ts +++ b/packages/nextjs/src/config/withSentryConfig/tunnel.ts @@ -1,152 +1,11 @@ -import { _INTERNAL_safeMathRandom } from '@sentry/core'; import * as fs from 'fs'; import * as path from 'path'; -import { TUNNEL_ROUTE_HANDLER_PATH, type TunnelRouteMode } from '../../common/utils/tunnelPathnameMatch'; +import { TUNNEL_ROUTE_HANDLER_PATH } from '../../common/utils/tunnelPathnameMatch'; import type { NextConfigObject, SentryBuildOptions } from '../types'; import { DEFAULT_PAGE_EXTENSIONS } from '../util'; -/** The values that the client, server and edge bundles read to find the tunnel route. */ -export type TunnelRouteInjectedValues = - | { _sentryRewritesTunnelPath: string; _sentryTunnelRouteMode: TunnelRouteMode } - | Record; - -/** - * Generates a random tunnel route path that's less likely to be blocked by ad-blockers - */ -function generateRandomTunnelRoute(): string { - // Generate a random 8-character alphanumeric string - const randomString = _INTERNAL_safeMathRandom().toString(36).substring(2, 10); - return `/${randomString}`; -} - -/** - * Resolves the tunnel route based on the user's configuration and the environment. - * @param tunnelRoute - The user-provided tunnel route option - */ -export function resolveTunnelRoute(tunnelRoute: string | true): string { - if (process.env.__SENTRY_TUNNEL_ROUTE__) { - // Reuse cached value from previous build (server/client) - return process.env.__SENTRY_TUNNEL_ROUTE__; - } - - const resolvedTunnelRoute = typeof tunnelRoute === 'string' ? tunnelRoute : generateRandomTunnelRoute(); - - // Cache for subsequent builds (only during build time) - // Turbopack runs the config twice, so we need a shared context to avoid generating a new tunnel route for each build. - // env works well here - // https://linear.app/getsentry/issue/JS-549/adblock-plus-blocking-requests-to-sentry-and-monitoring-tunnel - if (resolvedTunnelRoute) { - process.env.__SENTRY_TUNNEL_ROUTE__ = resolvedTunnelRoute; - } - - return resolvedTunnelRoute; -} - -/** - * Injects rewrite rules into the Next.js config provided by the user to tunnel - * requests from the `tunnelPath` to Sentry. - * - * See https://nextjs.org/docs/api-reference/next.config.js/rewrites. - */ -export function setUpTunnelRewriteRules(userNextConfig: NextConfigObject, tunnelPath: string): void { - const originalRewrites = userNextConfig.rewrites; - // Allow overriding the tunnel destination for E2E tests via environment variable - const destinationOverride = process.env._SENTRY_TUNNEL_DESTINATION_OVERRIDE; - - // Make sure destinations are statically defined at build time - const destination = destinationOverride || 'https://o:orgid.ingest.sentry.io/api/:projectid/envelope/?hsts=0'; - const destinationWithRegion = - destinationOverride || 'https://o:orgid.ingest.:region.sentry.io/api/:projectid/envelope/?hsts=0'; - - // This function doesn't take any arguments at the time of writing but we future-proof - // here in case Next.js ever decides to pass some - userNextConfig.rewrites = async (...args: unknown[]) => { - const tunnelRouteRewrite = { - // Matched rewrite routes will look like the following: `[tunnelPath]?o=[orgid]&p=[projectid]` - // Nextjs will automatically convert `source` into a regex for us - source: `${tunnelPath}(/?)`, - has: [ - { - type: 'query', - key: 'o', // short for orgId - we keep it short so matching is harder for ad-blockers - value: '(?\\d*)', - }, - { - type: 'query', - key: 'p', // short for projectId - we keep it short so matching is harder for ad-blockers - value: '(?\\d*)', - }, - ], - destination, - }; - - const tunnelRouteRewriteWithRegion = { - // Matched rewrite routes will look like the following: `[tunnelPath]?o=[orgid]&p=[projectid]?r=[region]` - // Nextjs will automatically convert `source` into a regex for us - source: `${tunnelPath}(/?)`, - has: [ - { - type: 'query', - key: 'o', // short for orgId - we keep it short so matching is harder for ad-blockers - value: '(?\\d*)', - }, - { - type: 'query', - key: 'p', // short for projectId - we keep it short so matching is harder for ad-blockers - value: '(?\\d*)', - }, - { - type: 'query', - key: 'r', // short for region - we keep it short so matching is harder for ad-blockers - value: '(?[a-z]{2})', - }, - ], - destination: destinationWithRegion, - }; - - // Order of these is important, they get applied first to last. - const newRewrites = [tunnelRouteRewriteWithRegion, tunnelRouteRewrite]; - - if (typeof originalRewrites !== 'function') { - return newRewrites; - } - - // @ts-expect-error Expected 0 arguments but got 1 - this is from the future-proofing mentioned above, so we don't care about it - const originalRewritesResult = await originalRewrites(...args); - - if (Array.isArray(originalRewritesResult)) { - return [...newRewrites, ...originalRewritesResult]; - } else { - return { - ...originalRewritesResult, - beforeFiles: [...newRewrites, ...(originalRewritesResult.beforeFiles || [])], - }; - } - }; -} - -/** - * Injects a rewrite rule that sends requests from the `tunnelPath` to the tunnel route handler. - */ -export function setUpTunnelHandlerRewrite(userNextConfig: NextConfigObject, tunnelPath: string): void { - const originalRewrites = userNextConfig.rewrites; - // Next.js adds the `basePath` and an optional trailing slash. - const handlerRewrite = { source: tunnelPath, destination: TUNNEL_ROUTE_HANDLER_PATH }; - - // `beforeFiles`: a `public/` file or a page at the same path wins over an `afterFiles` rewrite. - userNextConfig.rewrites = async () => { - const originalRewritesResult = typeof originalRewrites === 'function' ? await originalRewrites() : []; - - if (Array.isArray(originalRewritesResult)) { - return { beforeFiles: [handlerRewrite], afterFiles: originalRewritesResult }; - } - - return { - ...originalRewritesResult, - beforeFiles: [handlerRewrite, ...(originalRewritesResult.beforeFiles || [])], - }; - }; -} +/** The values that the client, server and edge bundles read to enable the managed tunnel for the `tunnelRoute`. */ +export type TunnelRouteInjectedValues = { _sentryTunnelRoute: string } | Record; /** * Returns the tunnel route handler file relative to `projectDir` (for example `app/sentry-tunnel/route.ts`), or @@ -169,6 +28,21 @@ export function findTunnelRouteHandlerFile( .find(file => getStats(path.join(projectDir, file))?.isFile()); } +/** + * Returns true if the project has an App Router or Pages Router page at the tunnel route handler path. + */ +function hasTunnelRoutePage(pageExtensions: string[], projectDir: string): boolean { + const pageFiles = ['app', 'src/app'].map(dir => `${dir}${TUNNEL_ROUTE_HANDLER_PATH}/page`); + const pagesRouterFiles = ['pages', 'src/pages'].flatMap(dir => [ + `${dir}${TUNNEL_ROUTE_HANDLER_PATH}`, + `${dir}${TUNNEL_ROUTE_HANDLER_PATH}/index`, + ]); + + return [...pageFiles, ...pagesRouterFiles].some(file => + pageExtensions.some(extension => getStats(path.join(projectDir, `${file}.${extension}`))?.isFile()), + ); +} + function getStats(filePath: string): fs.Stats | undefined { try { return fs.statSync(filePath); @@ -178,25 +52,88 @@ function getStats(filePath: string): fs.Stats | undefined { } /** - * Returns the tunnel path that the client sends envelopes to, and the tunnel route mode. - * Returns no values if there is no tunnel route, or if it cannot work (static export). - * - * Call it after `maybeSetUpTunnelRouteRewriteRules`, which resolves `tunnelRoute: true` to a path. + * Returns the `tunnelRoute` for the client, server and edge bundles: the fixed path with the `basePath`, or `'true'` + * for the path derived from the DSN. Returns no values if there is no tunnel route, or if it cannot work (static + * export). */ export function getTunnelRouteInjectedValues( userNextConfig: NextConfigObject, userSentryOptions: SentryBuildOptions | undefined, - projectDir: string = process.cwd(), ): TunnelRouteInjectedValues { + // oxlint-disable-next-line typescript/no-deprecated -- reads the deprecated option to keep it working const tunnelRoute = userSentryOptions?.tunnelRoute; - if (typeof tunnelRoute !== 'string' || !tunnelRoute || userNextConfig.output === 'export') { + if (!tunnelRoute || userNextConfig.output === 'export') { return {}; } return { - _sentryRewritesTunnelPath: `${userNextConfig.basePath ?? ''}${tunnelRoute}`, - _sentryTunnelRouteMode: findTunnelRouteHandlerFile(userNextConfig.pageExtensions, projectDir) - ? 'handler' - : 'rewrite', + _sentryTunnelRoute: tunnelRoute === true ? 'true' : `${userNextConfig.basePath ?? ''}${tunnelRoute}`, + }; +} + +/** + * Makes the managed tunnel reachable on Vercel, which serves unknown paths without running the app. Writes the tunnel + * route handler if the app has none, and rewrites envelope requests on paths the app doesn't serve to it, so the + * derived path and a fixed one both reach it. + * + * Only runs in `next build` on Vercel, whose build checkout is thrown away afterwards. `vercel dev` sets `VERCEL` + * locally too, so `next dev` and development builds skip it to keep the file out of the repo. + */ +export function setUpManagedTunnelVercelRoute( + userNextConfig: NextConfigObject, + projectDir: string = process.cwd(), +): void { + // Next.js sets `NEXT_PHASE` only after it loads the config. + const isVercelBuild = + !!process.env.VERCEL && process.env.VERCEL_ENV !== 'development' && process.argv.includes('build'); + if (!isVercelBuild || userNextConfig.output === 'export') { + return; + } + + const pageExtensions = userNextConfig.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS; + // A route handler next to a page at the same path fails the build. + if (hasTunnelRoutePage(pageExtensions, projectDir)) { + return; + } + + if (!findTunnelRouteHandlerFile(pageExtensions, projectDir)) { + // A Pages Router app gets an `app` directory with only this route, next to its `pages` (or in `src`). + const appDir = + ['app', 'src/app'].find(dir => getStats(path.join(projectDir, dir))?.isDirectory()) ?? + (getStats(path.join(projectDir, 'src/pages'))?.isDirectory() ? 'src/app' : 'app'); + const extension = ['js', 'ts'].find(ext => pageExtensions.includes(ext)); + if (!extension) { + return; + } + + const routeDir = path.join(projectDir, appDir, TUNNEL_ROUTE_HANDLER_PATH); + fs.mkdirSync(routeDir, { recursive: true }); + fs.writeFileSync( + path.join(routeDir, `route.${extension}`), + "// Generated by @sentry/nextjs for the managed tunnel on Vercel.\nexport { POST } from '@sentry/nextjs/tunnel';\n", + ); + } + + const originalRewrites = userNextConfig.rewrites; + const tunnelRewrite = { + // Next.js adds the `basePath`. The content type keeps other requests out, and the handler forwards only envelopes + // for allowed DSNs. + source: '/:path*', + has: [{ type: 'header', key: 'content-type', value: 'application/x-sentry-envelope' }], + destination: TUNNEL_ROUTE_HANDLER_PATH, + }; + + // `afterFiles`: the app's own routes win. + userNextConfig.rewrites = async () => { + const originalRewritesResult = typeof originalRewrites === 'function' ? await originalRewrites() : []; + + if (Array.isArray(originalRewritesResult)) { + return { afterFiles: [...originalRewritesResult, tunnelRewrite] }; + } + + return { + ...originalRewritesResult, + afterFiles: [...(originalRewritesResult.afterFiles || []), tunnelRewrite], + }; }; } diff --git a/packages/nextjs/src/edge/index.ts b/packages/nextjs/src/edge/index.ts index 132d5f50aef0..cbbba7242fe3 100644 --- a/packages/nextjs/src/edge/index.ts +++ b/packages/nextjs/src/edge/index.ts @@ -15,7 +15,12 @@ import { } from '@sentry/core'; import type { VercelEdgeOptions } from '@sentry/vercel-edge'; import { getDefaultIntegrations, init as vercelEdgeInit } from '@sentry/vercel-edge'; +import { + _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, + _INTERNAL_setTunnelDefaults as setTunnelDefaults, +} from '@sentry/core/server'; import { DEBUG_BUILD } from '../common/debug-build'; +import { getInjectedBasePath } from '../common/utils/basePath'; import { ATTR_NEXT_SPAN_NAME, ATTR_NEXT_SPAN_TYPE } from '../common/nextSpanAttributes'; import { ATTR_NEXT_PAGES_API_ROUTE_TYPE, @@ -26,6 +31,7 @@ import { backfillHttpResponseStatusCode } from '../common/utils/backfillHttpResp import { backfillHttpServerStatus } from '../common/utils/backfillHttpServerStatus'; import { createLiveRootSpanAdapter } from '../common/utils/liveRootSpanAdapter'; import { dropMiddlewareTunnelRequests, getTunnelRouteIgnoreSpans } from '../common/utils/dropMiddlewareTunnelRequests'; +import { getTunnelRouteServerOptions } from '../common/utils/tunnelPathnameMatch'; import { maybeForkIsolationScopeForRootSpan } from '../common/utils/forkIsolationScopeForRootSpan'; import { getNormalizedRequestFromAttributes } from '../common/utils/getNormalizedRequestFromAttributes'; import { isBuild } from '../common/utils/isBuild'; @@ -66,7 +72,6 @@ export type EdgeOptions = VercelEdgeOptions; const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewriteFramesDistDir?: string; _sentryRelease?: string; - _sentryRewritesTunnelPath?: string; }; /** Inits the Sentry NextJS SDK on the Edge Runtime. */ @@ -110,10 +115,16 @@ export function init(options: VercelEdgeOptions = {}): void { const nextjsIgnoreSpans: NonNullable = [ // (set in `dropMiddlewareTunnelRequests` during `spanStart`) { attributes: { [TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION]: true } }, - ...getTunnelRouteIgnoreSpans(), ]; opts.ignoreSpans = [...(opts.ignoreSpans || []), ...nextjsIgnoreSpans]; + // Before `init`, which applies it to the managed tunnel of `serveTunnelIntegration` or `tunnelRoute`. + setTunnelDefaults({ + basePath: getInjectedBasePath(), + tunnel: getTunnelRouteServerOptions(), + forward: forwardTunnelRequest, + }); + // Before the Cloudflare check, so that the events of the client of `withSentry` get the tag too. try { // @ts-expect-error `process.turbopack` is a magic string that will be replaced by Next.js @@ -143,6 +154,8 @@ export function init(options: VercelEdgeOptions = {}): void { } const client = vercelEdgeInit(opts); + const clientOptions = client.getOptions(); + clientOptions.ignoreSpans = [...(clientOptions.ignoreSpans || []), ...getTunnelRouteIgnoreSpans(client)]; // Next.js's OTel instrumentation samples root spans before the Sentry middleware wrapper can set // `normalizedRequest` on the isolation scope. Seed it from span attributes so `tracesSampler` has access. @@ -169,7 +182,7 @@ export function init(options: VercelEdgeOptions = {}): void { const rootSpan = getRootSpan(span); const isRootSpan = span === rootSpan; - dropMiddlewareTunnelRequests(span, spanAttributes); + dropMiddlewareTunnelRequests(span, spanAttributes, client); // Next.js names the incoming-request span after the raw URL. With span streaming, span names have to // be low cardinality, so we replace it here at span start; the `next.route` hoisting below renames it diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index 3a1bf1ab9250..1d21332676c3 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -11,11 +11,22 @@ import { GLOBAL_OBJ, } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; -import { getDefaultIntegrations, httpIntegration, init as nodeInit } from '@sentry/node'; +import { + _INTERNAL_installTunnelHooks as installTunnelHooks, + getDefaultIntegrations, + httpIntegration, + init as nodeInit, +} from '@sentry/node'; +import { + _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, + _INTERNAL_setTunnelDefaults as setTunnelDefaults, +} from '@sentry/core/server'; import { DEBUG_BUILD } from '../common/debug-build'; +import { getInjectedBasePath } from '../common/utils/basePath'; import { devErrorSymbolicationEventProcessor } from '../common/devErrorSymbolicationEventProcessor'; import { dropReactControlFlowErrorsEventProcessor } from '../common/utils/dropReactControlFlowErrors'; import { getTunnelRouteIgnoreSpans } from '../common/utils/dropMiddlewareTunnelRequests'; +import { getTunnelRouteServerOptions } from '../common/utils/tunnelPathnameMatch'; import { isBuild } from '../common/utils/isBuild'; import { isAsyncContextOwnedByCloudflare, @@ -157,7 +168,14 @@ export function init(options: NodeOptions): NodeClient | undefined { ...cloudflareConfig, }; - opts.ignoreSpans = [...(opts.ignoreSpans || []), ...NEXTJS_SERVER_IGNORE_SPANS, ...getTunnelRouteIgnoreSpans()]; + opts.ignoreSpans = [...(opts.ignoreSpans || []), ...NEXTJS_SERVER_IGNORE_SPANS]; + + // Before `init`, which applies it to the managed tunnel of `serveTunnelIntegration` or `tunnelRoute`. + const tunnelRoute = getTunnelRouteServerOptions(); + setTunnelDefaults({ basePath: getInjectedBasePath(), tunnel: tunnelRoute, forward: forwardTunnelRequest }); + if (tunnelRoute) { + installTunnelHooks(); + } if (DEBUG_BUILD && opts.debug) { debug.enable(); @@ -181,6 +199,8 @@ export function init(options: NodeOptions): NodeClient | undefined { if (client) { addNextjsServerSpanHooks(client); + const clientOptions = client.getOptions(); + clientOptions.ignoreSpans = [...(clientOptions.ignoreSpans || []), ...getTunnelRouteIgnoreSpans(client)]; } else if (isOwnedByCloudflare) { setCloudflareWorkerRelease(opts.release); } diff --git a/packages/nextjs/src/server/serverSpanHooks.ts b/packages/nextjs/src/server/serverSpanHooks.ts index f243813d7a45..b1ad6f9991c5 100644 --- a/packages/nextjs/src/server/serverSpanHooks.ts +++ b/packages/nextjs/src/server/serverSpanHooks.ts @@ -168,7 +168,7 @@ export function handleOnSpanStart(span: Span, client: Client): void { const rootSpanAttributes = spanToJSON(rootSpan).attributes; const isRootSpan = span === rootSpan; - dropMiddlewareTunnelRequests(span, spanAttributes); + dropMiddlewareTunnelRequests(span, spanAttributes, client); // Next.js names the incoming-request span after the raw URL. With span streaming, span names have to // be low cardinality, so we replace it here at span start; the `next.route` hoisting below renames it diff --git a/packages/nextjs/src/tunnel/index.ts b/packages/nextjs/src/tunnel/index.ts index d86dd2d0a99d..14bba2e884aa 100644 --- a/packages/nextjs/src/tunnel/index.ts +++ b/packages/nextjs/src/tunnel/index.ts @@ -1,9 +1,9 @@ -import { dsnToString, getClient, handleTunnelRequest, makeDsn, suppressTracing } from '@sentry/core'; +import { handleTunnelRequest } from '@sentry/core'; export interface CreateSentryTunnelRouteOptions { /** - * The DSNs that the route accepts. It rejects envelopes for other DSNs with a 403. - * Defaults to the DSN of the server SDK. + * DSNs whose envelopes the route forwards, in addition to the DSN of the server SDK. It rejects envelopes for other + * DSNs with a 403. Defaults to the DSNs `serveTunnelIntegration` allows. */ allowedDsns?: string[]; } @@ -25,34 +25,24 @@ type TunnelRouteHandler = (request: Request) => Promise; * allowedDsns: ['https://public@o0.ingest.sentry.io/0'], * }); * ``` + * + * @deprecated Set `tunnel: true` in the browser `Sentry.init` and add `serveTunnelIntegration({ allowedDsns })` to the + * server `Sentry.init` instead. */ export function createSentryTunnelRoute(options: CreateSentryTunnelRouteOptions = {}): { POST: TunnelRouteHandler } { - const allowedDsnsFromOptions = options.allowedDsns?.length ? normalizeDsns(options.allowedDsns) : undefined; + const allowedDsns = options.allowedDsns?.length ? options.allowedDsns.map(dsn => dsn.trim()) : undefined; return { - POST: async request => { - // Read on each request, because the client can be set up after this module loads. - const allowedDsns = allowedDsnsFromOptions ?? getServerDsns(); - if (!allowedDsns.length) { - return new Response( - allowedDsnsFromOptions - ? 'Tunnel route has no valid DSN in allowedDsns.' - : 'Tunnel route requires Sentry server SDK initialized with a DSN, or pass allowedDsns explicitly.', - { status: 500 }, - ); - } - - // Like the SDK transports, so that the forward creates no spans, breadcrumbs or trace headers. - return suppressTracing(() => handleTunnelRequest(request, { allowedDsns })); - }, + POST: request => handleTunnelRequest(request, { allowedDsns }), }; } /** - * Route handler for the `tunnelRoute` of `withSentryConfig`. It forwards Sentry envelopes to Sentry, but not the - * request headers (such as cookies). + * Route handler of the managed tunnel on Vercel, which `withSentryConfig` writes to `app/sentry-tunnel/route.js` in + * Vercel builds. It forwards Sentry envelopes to Sentry, but not the request headers (such as cookies). * - * It accepts envelopes only for the DSN of the server SDK. For other DSNs, use `createSentryTunnelRoute`. + * It accepts envelopes for the DSN of the server SDK, and the DSNs `serveTunnelIntegration` allows. Your own + * `app/sentry-tunnel/route.ts` with it is used instead of the generated one. * * @example * ```ts @@ -60,17 +50,4 @@ export function createSentryTunnelRoute(options: CreateSentryTunnelRouteOptions * export { POST } from '@sentry/nextjs/tunnel'; * ``` */ -export const POST: TunnelRouteHandler = createSentryTunnelRoute().POST; - -function getServerDsns(): string[] { - const dsn = getClient()?.getDsn(); - return dsn ? [dsnToString(dsn)] : []; -} - -// The same form as the DSN in the envelope header, because `handleTunnelRequest` compares exact strings. -function normalizeDsns(dsns: string[]): string[] { - return dsns.flatMap(dsn => { - const dsnComponents = makeDsn(dsn.trim()); - return dsnComponents ? [dsnToString(dsnComponents)] : []; - }); -} +export const POST: TunnelRouteHandler = request => handleTunnelRequest(request); diff --git a/packages/nextjs/test/clientSdk.test.ts b/packages/nextjs/test/clientSdk.test.ts index 9f16580546c7..cf0b8eca9568 100644 --- a/packages/nextjs/test/clientSdk.test.ts +++ b/packages/nextjs/test/clientSdk.test.ts @@ -1,5 +1,5 @@ import type { Integration } from '@sentry/core'; -import { debug, getMainCarrier, GLOBAL_OBJ, SentryNonRecordingSpan, spanToJSON } from '@sentry/core'; +import { debug, getMainCarrier, getTunnelPath, GLOBAL_OBJ, SentryNonRecordingSpan, spanToJSON } from '@sentry/core'; import * as SentryReact from '@sentry/react'; import { close, getClient, getIsolationScope, WINDOW } from '@sentry/react'; import { JSDOM } from 'jsdom'; @@ -238,6 +238,58 @@ describe('Client init()', () => { }); }); + describe('managed tunnel', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("serves `tunnel: true` under the app's `basePath`", () => { + vi.stubEnv('_sentryBasePath', '/docs'); + + const client = init({ dsn: TEST_DSN, tunnel: true }); + + expect(client?.getOptions().tunnel).toBe(`/docs${getTunnelPath(TEST_DSN)}`); + }); + + it('keeps a `basePath` the user set', () => { + vi.stubEnv('_sentryBasePath', '/docs'); + + const client = init({ dsn: TEST_DSN, tunnel: { basePath: '/shop' } }); + + expect(client?.getOptions().tunnel).toBe(`/shop${getTunnelPath(TEST_DSN)}`); + }); + + it('keeps a `tunnel` URL as written', () => { + vi.stubEnv('_sentryBasePath', '/docs'); + + const client = init({ dsn: TEST_DSN, tunnel: '/monitoring' }); + + expect(client?.getOptions().tunnel).toBe('/monitoring'); + }); + + it('sends events to the fixed path of the `tunnelRoute`', () => { + vi.stubEnv('_sentryBasePath', '/docs'); + vi.stubEnv('_sentryTunnelRoute', '/docs/monitoring'); + + const client = init({ dsn: TEST_DSN }); + + expect(client?.getOptions().tunnel).toBe('/docs/monitoring'); + // The Vercel rewrite only matches envelope requests. + expect(client?.getOptions().transportOptions?.headers).toEqual({ + 'Content-Type': 'application/x-sentry-envelope', + }); + }); + + it("sends events to the path derived from the DSN under the app's `basePath` for `tunnelRoute: true`", () => { + vi.stubEnv('_sentryBasePath', '/docs'); + vi.stubEnv('_sentryTunnelRoute', 'true'); + + const client = init({ dsn: TEST_DSN }); + + expect(client?.getOptions().tunnel).toBe(`/docs${getTunnelPath(TEST_DSN)}`); + }); + }); + it('returns client from init', () => { expect(init({})).not.toBeUndefined(); }); diff --git a/packages/nextjs/test/cloudflare/withSentry.test.ts b/packages/nextjs/test/cloudflare/withSentry.test.ts index 46bc97e520be..d0a1904663f6 100644 --- a/packages/nextjs/test/cloudflare/withSentry.test.ts +++ b/packages/nextjs/test/cloudflare/withSentry.test.ts @@ -28,7 +28,7 @@ describe('withSentry', () => { getMainCarrier().__SENTRY__ = undefined; (GLOBAL_OBJ as typeof GLOBAL_OBJ & { __SENTRY_CLOUDFLARE_CLIENT__?: unknown }).__SENTRY_CLOUDFLARE_CLIENT__ = undefined; - delete (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewritesTunnelPath?: string })._sentryRewritesTunnelPath; + delete (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryTunnelRoute?: string })._sentryTunnelRoute; delete (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRelease?: string })._sentryRelease; vi.restoreAllMocks(); trace.disable(); @@ -186,8 +186,7 @@ describe('withSentry', () => { }); it('does not sample the request span of a request to the tunnel route', async () => { - (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewritesTunnelPath?: string })._sentryRewritesTunnelPath = - '/monitoring'; + (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryTunnelRoute?: string })._sentryTunnelRoute = '/monitoring'; const sampledByPath: Record = {}; const handler = withSentry(() => ({ dsn: DSN, tracesSampleRate: 1 }), { fetch: (request: Request) => { @@ -212,8 +211,7 @@ describe('withSentry', () => { }); it('does not sample the request span of a request to the tunnel route when a `tracesSampler` samples every span', async () => { - (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewritesTunnelPath?: string })._sentryRewritesTunnelPath = - '/monitoring'; + (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryTunnelRoute?: string })._sentryTunnelRoute = '/monitoring'; const sampledByPath: Record = {}; const handler = withSentry(() => ({ dsn: DSN, tracesSampler: () => 1 }), { fetch: (request: Request) => { diff --git a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts index d68c002f298b..7885f953ac51 100644 --- a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts +++ b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts @@ -306,9 +306,9 @@ describe('generateValueInjectionRules', () => { }); describe('with tunnel route values', () => { - it('injects the tunnel path and mode into the client and server bundles', () => { + it('injects the tunnel route into the client and server bundles', () => { const result = generateValueInjectionRules({ - tunnelRouteValues: { _sentryRewritesTunnelPath: '/monitoring', _sentryTunnelRouteMode: 'handler' }, + tunnelRouteValues: { _sentryTunnelRoute: '/monitoring' }, }); const injectedValues = result.map(({ matcher, rule }) => [ @@ -316,15 +316,11 @@ describe('generateValueInjectionRules', () => { (rule as { loaders: Array<{ options: { values: Record } }> }).loaders[0]?.options.values, ]); expect(injectedValues).toEqual([ - [ - '**/instrumentation-client.*', - { _sentryRewritesTunnelPath: '/monitoring', _sentryTunnelRouteMode: 'handler' }, - ], + ['**/instrumentation-client.*', { _sentryTunnelRoute: '/monitoring' }], [ '**/instrumentation.*', { - _sentryRewritesTunnelPath: '/monitoring', - _sentryTunnelRouteMode: 'handler', + _sentryTunnelRoute: '/monitoring', __SENTRY_SERVER_MODULES__: expect.any(Object), }, ], @@ -332,6 +328,21 @@ describe('generateValueInjectionRules', () => { }); }); + describe('with basePath', () => { + it('injects the base path into the client and server bundles', () => { + const result = generateValueInjectionRules({ basePath: '/docs' }); + + const injectedValues = result.map(({ matcher, rule }) => [ + matcher, + (rule as { loaders: Array<{ options: { values: Record } }> }).loaders[0]?.options.values, + ]); + expect(injectedValues).toEqual([ + ['**/instrumentation-client.*', { _sentryBasePath: '/docs' }], + ['**/instrumentation.*', { _sentryBasePath: '/docs', __SENTRY_SERVER_MODULES__: expect.any(Object) }], + ]); + }); + }); + describe('path resolution', () => { it('should call path.resolve with correct arguments', () => { const pathResolveSpy = vi.spyOn(path, 'resolve'); diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index 766a05f583c8..60d06c115a29 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -859,8 +859,29 @@ describe('constructWebpackConfigFunction()', () => { .flatMap(rule => rule.use ?? []) .find(loader => String(loader.loader).endsWith('valueInjectionLoader.js')); expect(valueInjectionLoader?.options).toMatchObject({ - values: { _sentryRewritesTunnelPath: '/monitoring', _sentryTunnelRouteMode: 'handler' }, + values: { _sentryTunnelRoute: '/monitoring' }, }); }); }); }); + +describe('basePath value injection', () => { + it.each([ + ['server', serverWebpackConfig, serverBuildContext], + ['edge', serverWebpackConfig, edgeBuildContext], + ])( + 'injects the base path into production %s builds', + async (_target, incomingWebpackConfig, incomingWebpackBuildContext) => { + const finalWebpackConfig = await materializeFinalWebpackConfig({ + exportedNextConfig: { ...userNextConfig, basePath: '/docs' }, + incomingWebpackConfig, + incomingWebpackBuildContext, + }); + + const valueInjectionLoader = finalWebpackConfig.module.rules + .flatMap(rule => rule.use ?? []) + .find(loader => String(loader.loader).endsWith('valueInjectionLoader.js')); + expect(valueInjectionLoader?.options).toMatchObject({ values: { _sentryBasePath: '/docs' } }); + }, + ); +}); diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index 9cec2cc71410..8960683f59cb 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -917,7 +917,7 @@ describe('withSentryConfig', () => { expect(finalConfig.productionBrowserSourceMaps).toBe(true); expect(sentryOptions.sourcemaps).toHaveProperty('deleteSourcemapsAfterUpload', true); - expect(finalConfig.rewrites).toBeInstanceOf(Function); + expect(finalConfig.env).toHaveProperty('_sentryTunnelRoute', '/custom-tunnel'); }); it('works correctly with custom release configuration', () => { @@ -1786,8 +1786,8 @@ describe('withSentryConfig', () => { '[@sentry/nextjs] The configured `useRunAfterProductionCompileHook` option is not compatible with your current Next.js version. This option is only supported on Next.js version 15.4.1 or later. Will not run source map and release management logic.', ); - // Ensure other functionality still works (tunnel route creates rewrites function) - expect(finalConfig.rewrites).toBeInstanceOf(Function); + // Ensure other functionality still works + expect(finalConfig.env).toHaveProperty('_sentryTunnelRoute', '/tunnel'); // Release name should be set (from git or environment) expect(finalConfig.env).toHaveProperty('_sentryRelease'); diff --git a/packages/nextjs/test/config/withSentryConfig/buildTime.test.ts b/packages/nextjs/test/config/withSentryConfig/buildTime.test.ts index b30f6f708855..a0f66a40e2a0 100644 --- a/packages/nextjs/test/config/withSentryConfig/buildTime.test.ts +++ b/packages/nextjs/test/config/withSentryConfig/buildTime.test.ts @@ -59,21 +59,15 @@ describe('setUpBuildTimeVariables', () => { }); describe('tunnel route', () => { - it('adds the tunnel path and the handler mode for a project with a tunnel route handler', () => { + it('adds the tunnel path with the base path', () => { const nextConfig = { basePath: '/docs' }; - setUpBuildTimeVariables( - nextConfig, - { tunnelRoute: '/monitoring' }, - undefined, - makeProject(['app/sentry-tunnel/route.ts']), - ); + setUpBuildTimeVariables(nextConfig, { tunnelRoute: '/monitoring' }, undefined, makeProject(['app/page.tsx'])); expect(nextConfig).toEqual({ basePath: '/docs', env: expect.objectContaining({ - _sentryRewritesTunnelPath: '/docs/monitoring', - _sentryTunnelRouteMode: 'handler', + _sentryTunnelRoute: '/docs/monitoring', }), }); }); diff --git a/packages/nextjs/test/config/withSentryConfig/getFinalConfigObjectUtils.test.ts b/packages/nextjs/test/config/withSentryConfig/getFinalConfigObjectUtils.test.ts index 9cdc46448750..21162b901a20 100644 --- a/packages/nextjs/test/config/withSentryConfig/getFinalConfigObjectUtils.test.ts +++ b/packages/nextjs/test/config/withSentryConfig/getFinalConfigObjectUtils.test.ts @@ -3,7 +3,11 @@ import type { NextConfigObject } from '../../../src/config/types'; import { warnIfMissingInstrumentationFile } from '../../../src/config/withSentryConfig/getFinalConfigObjectUtils'; import { makeProject, removeProjects } from './projectFixture'; -const HANDLER_REWRITE = { source: '/monitoring', destination: '/sentry-tunnel' }; +const TUNNEL_REWRITE = { + source: '/:path*', + has: [{ type: 'header', key: 'content-type', value: 'application/x-sentry-envelope' }], + destination: '/sentry-tunnel', +}; afterEach(() => { removeProjects(); @@ -18,11 +22,17 @@ describe('maybeSetUpTunnelRouteRewriteRules', () => { await import('../../../src/config/withSentryConfig/getFinalConfigObjectUtils'); }); + const originalArgv = process.argv; + beforeEach(() => { vi.restoreAllMocks(); // A fresh module per test, because the function logs each message only once. vi.resetModules(); - delete process.env.__SENTRY_TUNNEL_ROUTE__; + }); + + afterEach(() => { + vi.unstubAllEnvs(); + process.argv = originalArgv; }); async function setUp(files: string[]) { @@ -34,101 +44,73 @@ describe('maybeSetUpTunnelRouteRewriteRules', () => { return { maybeSetUpTunnelRouteRewriteRules, logSpy, warnSpy }; } - it('sets up the handler rewrite when the project has a tunnel route handler', async () => { - const { maybeSetUpTunnelRouteRewriteRules } = await setUp(['app/sentry-tunnel/route.ts']); + function stubVercelBuild(): void { + vi.stubEnv('VERCEL', '1'); + vi.stubEnv('VERCEL_ENV', 'production'); + process.argv = [...originalArgv.slice(0, 2), 'build']; + } + + it('sets up no rewrite outside of Vercel and warns once about the deprecated option', async () => { + const { maybeSetUpTunnelRouteRewriteRules, warnSpy } = await setUp(['app/page.tsx']); const nextConfig: NextConfigObject = {}; maybeSetUpTunnelRouteRewriteRules(nextConfig, { tunnelRoute: '/monitoring' }); - - await expect(nextConfig.rewrites?.()).resolves.toEqual({ beforeFiles: [HANDLER_REWRITE], afterFiles: [] }); - }); - - it('logs the tunnel route handler file once', async () => { - const { maybeSetUpTunnelRouteRewriteRules, logSpy } = await setUp(['app/sentry-tunnel/route.ts']); - - maybeSetUpTunnelRouteRewriteRules({}, { tunnelRoute: '/monitoring' }); maybeSetUpTunnelRouteRewriteRules({}, { tunnelRoute: '/monitoring' }); - expect(logSpy).toHaveBeenCalledTimes(1); - expect(logSpy).toHaveBeenCalledWith( - '[@sentry/nextjs] The tunnel route sends events through app/sentry-tunnel/route.ts. Only the event payload goes to Sentry.', - ); + expect(nextConfig.rewrites).toBeUndefined(); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('The `tunnelRoute` option is deprecated')); }); - it('sets up the external rewrite when the project has no tunnel route handler', async () => { - const { maybeSetUpTunnelRouteRewriteRules, logSpy } = await setUp(['app/page.tsx']); - const nextConfig: NextConfigObject = {}; + it.each([ + ['`tunnelRoute` is not set', {}], + ['`tunnelRoute` is `true`', { tunnelRoute: true }], + ['`tunnelRoute` is a path', { tunnelRoute: '/monitoring' }], + ])( + 'rewrites envelope requests to the tunnel route handler on Vercel when %s', + async (_description, sentryOptions) => { + stubVercelBuild(); + const { maybeSetUpTunnelRouteRewriteRules } = await setUp(['app/page.tsx']); + const nextConfig: NextConfigObject = {}; - maybeSetUpTunnelRouteRewriteRules(nextConfig, { tunnelRoute: '/monitoring' }); + maybeSetUpTunnelRouteRewriteRules(nextConfig, sentryOptions); - await expect(nextConfig.rewrites?.()).resolves.toEqual([ - { - source: '/monitoring(/?)', - has: [ - { type: 'query', key: 'o', value: '(?\\d*)' }, - { type: 'query', key: 'p', value: '(?\\d*)' }, - { type: 'query', key: 'r', value: '(?[a-z]{2})' }, - ], - destination: 'https://o:orgid.ingest.:region.sentry.io/api/:projectid/envelope/?hsts=0', - }, - { - source: '/monitoring(/?)', - has: [ - { type: 'query', key: 'o', value: '(?\\d*)' }, - { type: 'query', key: 'p', value: '(?\\d*)' }, - ], - destination: 'https://o:orgid.ingest.sentry.io/api/:projectid/envelope/?hsts=0', - }, - ]); - expect(logSpy).not.toHaveBeenCalled(); - }); + await expect(nextConfig.rewrites?.()).resolves.toEqual({ afterFiles: [TUNNEL_REWRITE] }); + }, + ); - it('does not log with `silent`', async () => { - const { maybeSetUpTunnelRouteRewriteRules, logSpy } = await setUp(['app/sentry-tunnel/route.ts']); + it('does not warn about the deprecated option when `tunnelRoute` is not set', async () => { + const { maybeSetUpTunnelRouteRewriteRules, warnSpy } = await setUp(['app/page.tsx']); - maybeSetUpTunnelRouteRewriteRules({}, { tunnelRoute: '/monitoring', silent: true }); + maybeSetUpTunnelRouteRewriteRules({}, {}); - expect(logSpy).not.toHaveBeenCalled(); + expect(warnSpy).not.toHaveBeenCalled(); }); - it('warns once when the project has a tunnel route handler but `tunnelRoute` is not set', async () => { - const { maybeSetUpTunnelRouteRewriteRules, warnSpy } = await setUp(['src/app/sentry-tunnel/route.tsx']); + it('sets up no rewrite on Vercel when `tunnelRoute` is `false`', async () => { + stubVercelBuild(); + const { maybeSetUpTunnelRouteRewriteRules } = await setUp(['app/page.tsx']); const nextConfig: NextConfigObject = {}; - maybeSetUpTunnelRouteRewriteRules(nextConfig, {}); - maybeSetUpTunnelRouteRewriteRules({}, {}); + maybeSetUpTunnelRouteRewriteRules(nextConfig, { tunnelRoute: false }); expect(nextConfig.rewrites).toBeUndefined(); - expect(warnSpy).toHaveBeenCalledTimes(1); - expect(warnSpy).toHaveBeenCalledWith( - '[@sentry/nextjs] Found src/app/sentry-tunnel/route.tsx, but the `tunnelRoute` option is not set. Set `tunnelRoute` in `withSentryConfig` to send events through this route.', - ); }); - it('sets up no rewrite for a static export with a tunnel route handler', async () => { - const { maybeSetUpTunnelRouteRewriteRules, logSpy, warnSpy } = await setUp(['app/sentry-tunnel/route.ts']); + it('sets up no rewrite for a static export and warns that `tunnelRoute` does not work there', async () => { + stubVercelBuild(); + const { maybeSetUpTunnelRouteRewriteRules, warnSpy } = await setUp(['app/page.tsx']); const nextConfig: NextConfigObject = { output: 'export' }; maybeSetUpTunnelRouteRewriteRules(nextConfig, { tunnelRoute: '/monitoring' }); expect(nextConfig.rewrites).toBeUndefined(); - expect(logSpy).not.toHaveBeenCalled(); - expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledTimes(2); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('The `tunnelRoute` option is deprecated')); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining('will not work in combination with Next.js static exports'), ); }); - - it.each([ - ['`tunnelRoute` is `false`', {}, { tunnelRoute: false }], - ['`tunnelRoute` is not set in a static export', { output: 'export' }, {}], - ])('does not warn about the tunnel route handler when %s', async (_description, nextConfig, sentryOptions) => { - const { maybeSetUpTunnelRouteRewriteRules, warnSpy } = await setUp(['app/sentry-tunnel/route.ts']); - - maybeSetUpTunnelRouteRewriteRules(nextConfig, sentryOptions); - - expect(warnSpy).not.toHaveBeenCalled(); - }); }); describe('warnIfMissingInstrumentationFile', () => { diff --git a/packages/nextjs/test/config/withSentryConfig/tunnel.test.ts b/packages/nextjs/test/config/withSentryConfig/tunnel.test.ts index cc39280aa7d0..e3bd97ed61fd 100644 --- a/packages/nextjs/test/config/withSentryConfig/tunnel.test.ts +++ b/packages/nextjs/test/config/withSentryConfig/tunnel.test.ts @@ -1,13 +1,19 @@ -import { afterEach, describe, expect, it } from 'vitest'; +import * as fs from 'fs'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { NextConfigObject } from '../../../src/config/types'; import { findTunnelRouteHandlerFile, getTunnelRouteInjectedValues, - setUpTunnelHandlerRewrite, + setUpManagedTunnelVercelRoute, } from '../../../src/config/withSentryConfig/tunnel'; import { makeProject, removeProjects } from './projectFixture'; -const HANDLER_REWRITE = { source: '/monitoring', destination: '/sentry-tunnel' }; +const TUNNEL_REWRITE = { + source: '/:path*', + has: [{ type: 'header', key: 'content-type', value: 'application/x-sentry-envelope' }], + destination: '/sentry-tunnel', +}; afterEach(() => { removeProjects(); @@ -58,78 +64,128 @@ describe('findTunnelRouteHandlerFile', () => { }); describe('getTunnelRouteInjectedValues', () => { - it('returns the handler mode when the project has a tunnel route handler', () => { - const projectDir = makeProject(['app/sentry-tunnel/route.ts']); + it('returns the fixed path with the basePath', () => { + expect(getTunnelRouteInjectedValues({ basePath: '/docs' }, { tunnelRoute: '/monitoring' })).toEqual({ + _sentryTunnelRoute: '/docs/monitoring', + }); + }); - expect(getTunnelRouteInjectedValues({}, { tunnelRoute: '/monitoring' }, projectDir)).toEqual({ - _sentryRewritesTunnelPath: '/monitoring', - _sentryTunnelRouteMode: 'handler', + it('returns `true` for the path derived from the DSN', () => { + expect(getTunnelRouteInjectedValues({ basePath: '/docs' }, { tunnelRoute: true })).toEqual({ + _sentryTunnelRoute: 'true', }); }); - it('returns the rewrite mode when the project has no tunnel route handler', () => { - const projectDir = makeProject(['app/page.tsx']); + it.each([ + ['`tunnelRoute` is not set', {}, {}], + ['`tunnelRoute` is `false`', {}, { tunnelRoute: false }], + ['`tunnelRoute` is an empty string', { basePath: '/docs' }, { tunnelRoute: '' }], + ['the app is a static export', { output: 'export' }, { tunnelRoute: '/monitoring' }], + ] as const)('returns no values when %s', (_description, nextConfig, sentryOptions) => { + expect(getTunnelRouteInjectedValues(nextConfig, sentryOptions)).toEqual({}); + }); +}); - expect(getTunnelRouteInjectedValues({}, { tunnelRoute: '/monitoring' }, projectDir)).toEqual({ - _sentryRewritesTunnelPath: '/monitoring', - _sentryTunnelRouteMode: 'rewrite', - }); +describe('setUpManagedTunnelVercelRoute', () => { + const originalArgv = process.argv; + + beforeEach(() => { + vi.stubEnv('VERCEL', '1'); + vi.stubEnv('VERCEL_ENV', 'production'); + process.argv = [...originalArgv.slice(0, 2), 'build']; }); - it('adds the basePath to the tunnel path', () => { - const projectDir = makeProject(['app/sentry-tunnel/route.ts']); + afterEach(() => { + vi.unstubAllEnvs(); + process.argv = originalArgv; + }); - expect(getTunnelRouteInjectedValues({ basePath: '/docs' }, { tunnelRoute: '/monitoring' }, projectDir)).toEqual({ - _sentryRewritesTunnelPath: '/docs/monitoring', - _sentryTunnelRouteMode: 'handler', - }); + function hasRouteFile(projectDir: string): boolean { + return fs.readdirSync(projectDir, { recursive: true }).some(entry => String(entry).includes('route')); + } + + it('writes the tunnel route handler and rewrites envelope requests to it', async () => { + const projectDir = makeProject(['app/page.tsx']); + const nextConfig: NextConfigObject = {}; + + setUpManagedTunnelVercelRoute(nextConfig, projectDir); + + expect(fs.readFileSync(path.join(projectDir, 'app/sentry-tunnel/route.js'), 'utf8')).toContain( + "export { POST } from '@sentry/nextjs/tunnel';", + ); + await expect(nextConfig.rewrites?.()).resolves.toEqual({ afterFiles: [TUNNEL_REWRITE] }); }); it.each([ - ['`tunnelRoute` is not set', {}, {}], - ['`tunnelRoute` is an empty string', { basePath: '/docs' }, { tunnelRoute: '' }], - ['`tunnelRoute` is still `true`', {}, { tunnelRoute: true }], - ['the app is a static export', { output: 'export' }, { tunnelRoute: '/monitoring' }], - ])('returns no values when %s', (_description, nextConfig, sentryOptions) => { - const projectDir = makeProject(['app/sentry-tunnel/route.ts']); + ['an App Router page', 'app/sentry-tunnel/page.tsx'], + ['an App Router page in `src`', 'src/app/sentry-tunnel/page.tsx'], + ['a Pages Router page', 'pages/sentry-tunnel.tsx'], + ['a Pages Router index page', 'src/pages/sentry-tunnel/index.js'], + ])('does nothing when the project has %s at the route path', (_description, file) => { + const projectDir = makeProject([file]); + const nextConfig: NextConfigObject = {}; - expect(getTunnelRouteInjectedValues(nextConfig, sentryOptions, projectDir)).toEqual({}); + setUpManagedTunnelVercelRoute(nextConfig, projectDir); + + expect(hasRouteFile(projectDir)).toBe(false); + expect(nextConfig.rewrites).toBeUndefined(); }); -}); -describe('setUpTunnelHandlerRewrite', () => { - it('adds the handler rewrite to `beforeFiles` when there are no user rewrites', async () => { + it.each([ + ['outside of Vercel', () => vi.stubEnv('VERCEL', '')], + ['in a Vercel development build', () => vi.stubEnv('VERCEL_ENV', 'development')], + ['outside of `next build`', () => (process.argv = [...originalArgv.slice(0, 2), 'dev'])], + ])('does nothing %s', (_description, setUp) => { + setUp(); + const projectDir = makeProject(['app/page.tsx']); const nextConfig: NextConfigObject = {}; - setUpTunnelHandlerRewrite(nextConfig, '/monitoring'); + setUpManagedTunnelVercelRoute(nextConfig, projectDir); + + expect(hasRouteFile(projectDir)).toBe(false); + expect(nextConfig.rewrites).toBeUndefined(); + }); + + it('does nothing for a static export', () => { + const projectDir = makeProject(['app/page.tsx']); + const nextConfig: NextConfigObject = { output: 'export' }; - await expect(nextConfig.rewrites?.()).resolves.toEqual({ beforeFiles: [HANDLER_REWRITE], afterFiles: [] }); + setUpManagedTunnelVercelRoute(nextConfig, projectDir); + + expect(hasRouteFile(projectDir)).toBe(false); + expect(nextConfig.rewrites).toBeUndefined(); }); - it('keeps user rewrites in array form as `afterFiles`', async () => { + it('appends the rewrite to the user rewrites in array form', async () => { const userRewrite = { source: '/blog/:slug', destination: '/news/:slug' }; const nextConfig: NextConfigObject = { rewrites: async () => [userRewrite] }; - setUpTunnelHandlerRewrite(nextConfig, '/monitoring'); + setUpManagedTunnelVercelRoute(nextConfig, makeProject(['app/page.tsx'])); - await expect(nextConfig.rewrites?.()).resolves.toEqual({ - beforeFiles: [HANDLER_REWRITE], - afterFiles: [userRewrite], - }); + await expect(nextConfig.rewrites?.()).resolves.toEqual({ afterFiles: [userRewrite, TUNNEL_REWRITE] }); }); - it('puts the handler rewrite before the user `beforeFiles` rewrites', async () => { - const userBeforeFilesRewrite = { source: '/old', destination: '/new' }; + it('appends the rewrite to the user `afterFiles` rewrites and keeps the other phases', async () => { + const userAfterFilesRewrite = { source: '/old', destination: '/new' }; const userFallbackRewrite = { source: '/:path*', destination: 'https://legacy.example.com/:path*' }; const nextConfig: NextConfigObject = { - rewrites: async () => ({ beforeFiles: [userBeforeFilesRewrite], fallback: [userFallbackRewrite] }), + rewrites: async () => ({ afterFiles: [userAfterFilesRewrite], fallback: [userFallbackRewrite] }), }; - setUpTunnelHandlerRewrite(nextConfig, '/monitoring'); + setUpManagedTunnelVercelRoute(nextConfig, makeProject(['app/page.tsx'])); await expect(nextConfig.rewrites?.()).resolves.toEqual({ - beforeFiles: [HANDLER_REWRITE, userBeforeFilesRewrite], + afterFiles: [userAfterFilesRewrite, TUNNEL_REWRITE], fallback: [userFallbackRewrite], }); }); + + it('keeps the tunnel route handler of the app', () => { + const projectDir = makeProject(['app/page.tsx', 'app/sentry-tunnel/route.ts']); + + setUpManagedTunnelVercelRoute({}, projectDir); + + expect(fs.readFileSync(path.join(projectDir, 'app/sentry-tunnel/route.ts'), 'utf8')).toBe(''); + expect(fs.existsSync(path.join(projectDir, 'app/sentry-tunnel/route.js'))).toBe(false); + }); }); diff --git a/packages/nextjs/test/config/wrappers.test.ts b/packages/nextjs/test/config/wrappers.test.ts index 9d121172eea9..973e097953a2 100644 --- a/packages/nextjs/test/config/wrappers.test.ts +++ b/packages/nextjs/test/config/wrappers.test.ts @@ -99,8 +99,8 @@ describe('data-fetching function wrappers should not create manual spans', () => describe('wrapMiddlewareWithSentry', () => { afterEach(() => { vi.clearAllMocks(); - if ('_sentryRewritesTunnelPath' in globalThis) { - delete (globalThis as any)._sentryRewritesTunnelPath; + if ('_sentryTunnelRoute' in globalThis) { + delete (globalThis as any)._sentryTunnelRoute; } }); @@ -144,7 +144,7 @@ describe('wrapMiddlewareWithSentry', () => { }); test('should run the middleware for requests to the tunnel route', async () => { - (globalThis as any)._sentryRewritesTunnelPath = '/monitoring'; + (globalThis as any)._sentryTunnelRoute = '/monitoring'; const mockReturnValue = { status: 200 }; const origFunction: EdgeRouteHandler = vi.fn(async (..._args) => mockReturnValue); diff --git a/packages/nextjs/test/edgeSdk.test.ts b/packages/nextjs/test/edgeSdk.test.ts index a3fb9dacc7b8..dde1de3cdff9 100644 --- a/packages/nextjs/test/edgeSdk.test.ts +++ b/packages/nextjs/test/edgeSdk.test.ts @@ -1,8 +1,21 @@ import type { Integration } from '@sentry/core'; -import { getGlobalScope, getMainCarrier, GLOBAL_OBJ, withIsolationScope } from '@sentry/core'; +import { + getClient, + getGlobalScope, + getMainCarrier, + getTunnelPath, + GLOBAL_OBJ, + shouldIgnoreSpan, + withIsolationScope, +} from '@sentry/core'; import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils'; import * as SentryVercelEdge from '@sentry/vercel-edge'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + _INTERNAL_resetTunnelDefaults, + handleTunnelRequestIfMatched, + serveTunnelIntegration, +} from '@sentry/core/server'; import { TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION } from '../src/common/span-attributes-with-logic-attached'; import { init } from '../src/edge'; @@ -11,6 +24,8 @@ import { init } from '../src/edge'; const vercelEdgeInit = vi.spyOn(SentryVercelEdge, 'init'); +const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337'; + function findIntegrationByName(integrations: Integration[] = [], name: string): Integration | undefined { return integrations.find(integration => integration.name === name); } @@ -89,6 +104,84 @@ describe('Edge init()', () => { expect(getGlobalScope().getScopeData().tags.turbopack).toBe(true); }); + describe('managed tunnel', () => { + const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { + _sentryBasePath?: string; + _sentryTunnelRoute?: string; + }; + const post = (path: string): Request => + new Request(`https://example.com${path}`, { method: 'POST', body: '{}', headers: { 'content-length': '2' } }); + + afterEach(() => { + delete globalWithInjectedValues._sentryBasePath; + delete globalWithInjectedValues._sentryTunnelRoute; + _INTERNAL_resetTunnelDefaults(); + }); + + it('serves the fixed path of the `tunnelRoute` without `serveTunnelIntegration`', () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = '/docs/monitoring'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN }); + + expect(handleTunnelRequestIfMatched(post('/docs/monitoring'))).toBeInstanceOf(Promise); + expect(handleTunnelRequestIfMatched(post(`/docs${getTunnelPath(TEST_DSN)}`))).toBeUndefined(); + fetchSpy.mockRestore(); + }); + + it("serves the path derived from the DSN under the app's `basePath` for `tunnelRoute: true`", () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = 'true'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN }); + + expect(handleTunnelRequestIfMatched(post(`/docs${getTunnelPath(TEST_DSN)}`))).toBeInstanceOf(Promise); + fetchSpy.mockRestore(); + }); + + it.each([ + ['`tunnelRoute: true`', () => ({ tunnelRoute: 'true', integrations: [] })], + ['`serveTunnelIntegration`', () => ({ tunnelRoute: undefined, integrations: [serveTunnelIntegration()] })], + ])('ignores the Next.js request spans of the tunnel path derived from the DSN with %s', (_description, setUp) => { + const { tunnelRoute, integrations } = setUp(); + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = tunnelRoute; + + init({ dsn: TEST_DSN, integrations }); + + const ignoreSpans = getClient()?.getOptions().ignoreSpans; + // Next.js sets only `http.target` at span start, e.g. for a proxy that runs outside of the server on Vercel. + const isIgnored = (spanType: string, target: string): boolean => + shouldIgnoreSpan( + { + description: 'middleware POST', + op: 'http.server', + attributes: { 'next.span_type': spanType, 'http.target': target }, + }, + ignoreSpans, + ); + const tunnelPath = `/docs${getTunnelPath(TEST_DSN)}`; + expect(isIgnored('Middleware.execute', tunnelPath)).toBe(true); + expect(isIgnored('Next.request', `${tunnelPath}/`)).toBe(true); + expect(isIgnored('BaseServer.handleRequest', tunnelPath)).toBe(true); + expect(isIgnored('Next.request', '/docs/pricing')).toBe(false); + }); + + it("serves the tunnel of `serveTunnelIntegration` under the app's `basePath`", () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN, integrations: [serveTunnelIntegration()] }); + + const tunnelPath = getTunnelPath(TEST_DSN); + expect(handleTunnelRequestIfMatched(post(`/docs${tunnelPath}`))).toBeInstanceOf(Promise); + expect(handleTunnelRequestIfMatched(post(`${tunnelPath}`))).toBeUndefined(); + fetchSpy.mockRestore(); + }); + }); + describe('integrations', () => { // Options passed by `@sentry/nextjs`'s `init` to `@sentry/vercel-edge`'s `init` after modifying them type ModifiedInitOptions = { integrations?: Integration[]; defaultIntegrations: Integration[] }; diff --git a/packages/nextjs/test/serverSdk.test.ts b/packages/nextjs/test/serverSdk.test.ts index 7ef42977be47..559cc23e3ca6 100644 --- a/packages/nextjs/test/serverSdk.test.ts +++ b/packages/nextjs/test/serverSdk.test.ts @@ -1,9 +1,21 @@ import type { Integration } from '@sentry/core'; -import { GLOBAL_OBJ, getMainCarrier, withIsolationScope } from '@sentry/core'; +import { + GLOBAL_OBJ, + getClient, + getMainCarrier, + getTunnelPath, + shouldIgnoreSpan, + withIsolationScope, +} from '@sentry/core'; import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils'; import { close, getCurrentScope, getGlobalScope } from '@sentry/node'; import * as SentryNode from '@sentry/node'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + _INTERNAL_resetTunnelDefaults, + handleTunnelRequestIfMatched, + serveTunnelIntegration, +} from '@sentry/core/server'; import { TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION } from '../src/common/span-attributes-with-logic-attached'; import { init } from '../src/server'; import type * as NextSentryPropagatorModule from '../src/server/nextSentryPropagator'; @@ -19,6 +31,8 @@ vi.mock('../src/server/nextSentryPropagator', async importOriginal => ({ const nodeInit = vi.spyOn(SentryNode, 'init'); +const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337'; + function findIntegrationByName(integrations: Integration[] = [], name: string): Integration | undefined { return integrations.find(integration => integration.name === name); } @@ -76,6 +90,7 @@ describe('Server init()', () => { nodeInit.mockReturnValueOnce({ on: vi.fn(), addEventProcessor: vi.fn(), + getOptions: () => ({}), traceProvider, } as unknown as ReturnType); @@ -88,6 +103,7 @@ describe('Server init()', () => { nodeInit.mockReturnValueOnce({ on: vi.fn(), addEventProcessor: vi.fn(), + getOptions: () => ({}), traceProvider: undefined, } as unknown as ReturnType); @@ -97,6 +113,84 @@ describe('Server init()', () => { }); }); + describe('managed tunnel', () => { + const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { + _sentryBasePath?: string; + _sentryTunnelRoute?: string; + }; + const post = (path: string): Request => + new Request(`https://example.com${path}`, { method: 'POST', body: '{}', headers: { 'content-length': '2' } }); + + afterEach(() => { + delete globalWithInjectedValues._sentryBasePath; + delete globalWithInjectedValues._sentryTunnelRoute; + _INTERNAL_resetTunnelDefaults(); + }); + + it('serves the fixed path of the `tunnelRoute` without `serveTunnelIntegration`', () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = '/docs/monitoring'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN }); + + expect(handleTunnelRequestIfMatched(post('/docs/monitoring'))).toBeInstanceOf(Promise); + expect(handleTunnelRequestIfMatched(post(`/docs${getTunnelPath(TEST_DSN)}`))).toBeUndefined(); + fetchSpy.mockRestore(); + }); + + it("serves the path derived from the DSN under the app's `basePath` for `tunnelRoute: true`", () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = 'true'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN }); + + expect(handleTunnelRequestIfMatched(post(`/docs${getTunnelPath(TEST_DSN)}`))).toBeInstanceOf(Promise); + fetchSpy.mockRestore(); + }); + + it.each([ + ['`tunnelRoute: true`', () => ({ tunnelRoute: 'true', integrations: [] })], + ['`serveTunnelIntegration`', () => ({ tunnelRoute: undefined, integrations: [serveTunnelIntegration()] })], + ])('ignores the Next.js request spans of the tunnel path derived from the DSN with %s', (_description, setUp) => { + const { tunnelRoute, integrations } = setUp(); + globalWithInjectedValues._sentryBasePath = '/docs'; + globalWithInjectedValues._sentryTunnelRoute = tunnelRoute; + + init({ dsn: TEST_DSN, integrations }); + + const ignoreSpans = getClient()?.getOptions().ignoreSpans; + // Next.js sets only `http.target` at span start, e.g. for a proxy that runs outside of the server on Vercel. + const isIgnored = (spanType: string, target: string): boolean => + shouldIgnoreSpan( + { + description: 'middleware POST', + op: 'http.server', + attributes: { 'next.span_type': spanType, 'http.target': target }, + }, + ignoreSpans, + ); + const tunnelPath = `/docs${getTunnelPath(TEST_DSN)}`; + expect(isIgnored('Middleware.execute', tunnelPath)).toBe(true); + expect(isIgnored('Next.request', `${tunnelPath}/`)).toBe(true); + expect(isIgnored('BaseServer.handleRequest', tunnelPath)).toBe(true); + expect(isIgnored('Next.request', '/docs/pricing')).toBe(false); + }); + + it("serves the tunnel of `serveTunnelIntegration` under the app's `basePath`", () => { + globalWithInjectedValues._sentryBasePath = '/docs'; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); + + init({ dsn: TEST_DSN, integrations: [serveTunnelIntegration()] }); + + const tunnelPath = getTunnelPath(TEST_DSN); + expect(handleTunnelRequestIfMatched(post(`/docs${tunnelPath}`))).toBeInstanceOf(Promise); + expect(handleTunnelRequestIfMatched(post(`${tunnelPath}`))).toBeUndefined(); + fetchSpy.mockRestore(); + }); + }); + it("doesn't reinitialize the node SDK if already initialized", () => { expect(nodeInit).toHaveBeenCalledTimes(0); init({}); diff --git a/packages/nextjs/test/tunnel/index.test.ts b/packages/nextjs/test/tunnel/index.test.ts index 516543a2b5a9..a6fd021e3417 100644 --- a/packages/nextjs/test/tunnel/index.test.ts +++ b/packages/nextjs/test/tunnel/index.test.ts @@ -1,15 +1,9 @@ -import type * as SentryCore from '@sentry/core'; -import { createEnvelope, makeDsn, serializeEnvelope } from '@sentry/core'; +import type { Client } from '@sentry/core'; +import { createEnvelope, getCurrentScope, makeDsn, serializeEnvelope } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { serveTunnelIntegration } from '@sentry/core/server'; import { createSentryTunnelRoute, POST } from '../../src/tunnel'; -const { mockGetClient } = vi.hoisted(() => ({ mockGetClient: vi.fn() })); - -vi.mock('@sentry/core', async importOriginal => ({ - ...(await importOriginal()), - getClient: mockGetClient, -})); - const SERVER_DSN = 'https://public@o1.ingest.sentry.io/1'; const BROWSER_DSN = 'https://browser@o1.ingest.sentry.io/2'; @@ -33,7 +27,8 @@ function createEnvelopeRequest(dsn: string): { request: Request; body: Uint8Arra } function useClientDsn(dsn: string | undefined): void { - mockGetClient.mockReturnValue(dsn ? { getDsn: () => makeDsn(dsn) } : undefined); + const client = dsn ? ({ getDsn: () => makeDsn(dsn), getOptions: () => ({}) } as unknown as Client) : undefined; + getCurrentScope().setClient(client); } let fetchSpy: ReturnType; @@ -75,9 +70,6 @@ describe('POST', () => { const response = await POST(request); expect(response.status).toBe(500); - await expect(response.text()).resolves.toBe( - 'Tunnel route requires Sentry server SDK initialized with a DSN, or pass allowedDsns explicitly.', - ); expect(fetchSpy).not.toHaveBeenCalled(); }); @@ -91,6 +83,22 @@ describe('POST', () => { expect(fetchSpy).not.toHaveBeenCalled(); }); + it('accepts the DSNs `serveTunnelIntegration` allows', async () => { + const integration = serveTunnelIntegration({ allowedDsns: [BROWSER_DSN] }); + const options = {}; + const client = { + getDsn: () => makeDsn(SERVER_DSN), + getOptions: () => options, + getIntegrationByName: () => integration, + } as unknown as Client; + integration.setup?.(client); + getCurrentScope().setClient(client); + + const response = await POST(createEnvelopeRequest(BROWSER_DSN).request); + + expect(response.status).toBe(200); + }); + it('does not accept DSNs from environment variables', async () => { useClientDsn(SERVER_DSN); vi.stubEnv('SENTRY_DSN', BROWSER_DSN); @@ -104,16 +112,18 @@ describe('POST', () => { }); describe('createSentryTunnelRoute', () => { - it('accepts only the DSNs in `allowedDsns`', async () => { + it('accepts the DSNs in `allowedDsns` and the server DSN', async () => { useClientDsn(SERVER_DSN); const { POST: handler } = createSentryTunnelRoute({ allowedDsns: [BROWSER_DSN] }); - const allowedResponse = await handler(createEnvelopeRequest(BROWSER_DSN).request); - const rejectedResponse = await handler(createEnvelopeRequest(SERVER_DSN).request); + const browserResponse = await handler(createEnvelopeRequest(BROWSER_DSN).request); + const serverResponse = await handler(createEnvelopeRequest(SERVER_DSN).request); + const otherResponse = await handler(createEnvelopeRequest('https://other@o2.ingest.sentry.io/3').request); - expect(allowedResponse.status).toBe(200); - expect(rejectedResponse.status).toBe(403); - expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(browserResponse.status).toBe(200); + expect(serverResponse.status).toBe(200); + expect(otherResponse.status).toBe(403); + expect(fetchSpy).toHaveBeenCalledTimes(2); }); it.each([ @@ -138,15 +148,13 @@ describe('createSentryTunnelRoute', () => { expect(response.status).toBe(200); }); - it('responds with 500 when no allowed DSN is valid', async () => { + it('responds with 500 when no allowed DSN is valid and the server SDK has no DSN', async () => { vi.spyOn(console, 'error').mockImplementation(() => undefined); - useClientDsn(SERVER_DSN); const { POST: handler } = createSentryTunnelRoute({ allowedDsns: ['not-a-dsn'] }); const response = await handler(createEnvelopeRequest(SERVER_DSN).request); expect(response.status).toBe(500); - await expect(response.text()).resolves.toBe('Tunnel route has no valid DSN in allowedDsns.'); expect(fetchSpy).not.toHaveBeenCalled(); }); }); diff --git a/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts b/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts index e5b506d02c81..d13bdfb0a84b 100644 --- a/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts +++ b/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts @@ -8,10 +8,18 @@ import { import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_TYPE } from '../../src/common/nextSpanAttributes'; import { TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION } from '../../src/common/span-attributes-with-logic-attached'; -const globalWithInjectedValues = global as typeof global & { - _sentryRewritesTunnelPath?: string; - _sentryTunnelRouteMode?: string; -}; +const served = vi.hoisted(() => ({ tunnel: undefined as { paths: string[]; basePath?: string } | undefined })); + +vi.mock('@sentry/core/server', async requireActual => { + return { + ...(await requireActual()), + _INTERNAL_getServedTunnel: () => served.tunnel, + }; +}); + +function serveTunnel(paths: string[], basePath?: string): void { + served.tunnel = { paths, basePath }; +} vi.mock('@sentry/core', async requireActual => { return { @@ -33,14 +41,13 @@ function createMockSpan(): { setAttribute: ReturnType; attributes: } beforeEach(() => { - globalWithInjectedValues._sentryRewritesTunnelPath = undefined; - globalWithInjectedValues._sentryTunnelRouteMode = undefined; + served.tunnel = undefined; }); describe('dropMiddlewareTunnelRequests', () => { describe('BaseServer.handleRequest spans', () => { it('marks BaseServer.handleRequest span for dropping when http.target matches tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -52,7 +59,7 @@ describe('dropMiddlewareTunnelRequests', () => { }); it('marks BaseServer.handleRequest span for dropping when http.target exactly matches tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -64,7 +71,7 @@ describe('dropMiddlewareTunnelRequests', () => { }); it('does not mark BaseServer.handleRequest span for dropping when http.target does not match tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -76,7 +83,7 @@ describe('dropMiddlewareTunnelRequests', () => { }); it('does not mark BaseServer.handleRequest span for dropping when http.target shares tunnel path prefix', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -99,7 +106,7 @@ describe('dropMiddlewareTunnelRequests', () => { }); it('handles BaseServer.handleRequest span with basePath prefix in http.target', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/basepath/monitoring'; + serveTunnel(['/basepath/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -113,7 +120,7 @@ describe('dropMiddlewareTunnelRequests', () => { describe('Middleware.execute spans', () => { it('marks middleware span for dropping when http.target matches tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -127,7 +134,7 @@ describe('dropMiddlewareTunnelRequests', () => { describe('Next.request spans', () => { it('marks the proxy root span for dropping when http.target matches tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -141,7 +148,7 @@ describe('dropMiddlewareTunnelRequests', () => { describe('unrelated spans', () => { it('does not process spans without matching span type or origin', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -160,7 +167,7 @@ describe('dropMiddlewareTunnelRequests', () => { getOptions: () => ({ enableOpenTelemetrySetup: false }), } as any); - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const span = createMockSpan(); dropMiddlewareTunnelRequests(span as any, { @@ -177,7 +184,10 @@ describe('dropMiddlewareTunnelRequests', () => { describe('getTunnelRouteIgnoreSpans', () => { function isIgnored(attributes: Record): boolean { - return shouldIgnoreSpan({ description: 'POST', op: 'http.server', attributes }, getTunnelRouteIgnoreSpans()); + return shouldIgnoreSpan( + { description: 'POST', op: 'http.server', attributes }, + getTunnelRouteIgnoreSpans(undefined), + ); } // Next.js sets the deprecated `http.target` on its request spans. @@ -187,73 +197,50 @@ describe('getTunnelRouteIgnoreSpans', () => { } it('returns no entries when there is no tunnel route', () => { - expect(getTunnelRouteIgnoreSpans()).toEqual([]); - }); - - it.each([ - ['BaseServer.handleRequest', '/monitoring?o=123&p=456'], - ['BaseServer.handleRequest', '/monitoring/?o=123&p=456&r=us'], - ['Middleware.execute', '/monitoring?o=123&p=456'], - ])('ignores a %s span for %s in rewrite mode', (spanType, target) => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - - expect(isIgnored(nextRequestSpanAttributes(spanType, target))).toBe(true); - }); - - it.each([ - '/monitoring', - '/monitoring?o=123', - '/monitoring?xo=123&p=456', - '/monitoring?o=123&p=456&o=abc', - '/monitoring?p=456&o=123', - '/monitoring/dashboard?o=123&p=456', - '/monitoring-dashboard?o=123&p=456', - '/api/monitoring?o=123&p=456', - ])('does not ignore a request span for %s in rewrite mode, which the rewrite does not serve', target => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - - expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', target))).toBe(false); + expect(getTunnelRouteIgnoreSpans(undefined)).toEqual([]); }); - it.each(['/monitoring', '/monitoring/', '/monitoring?cache=0'])( - 'ignores a request span for %s in handler mode', + it.each(['/docs/k3x9q2a', '/docs/k3x9q2a/', '/docs/f00ba7'])( + 'ignores a request span for the derived path %s', target => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; + serveTunnel(['/k3x9q2a', '/f00ba7'], '/docs'); - expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', target))).toBe(true); + expect(isIgnored(nextRequestSpanAttributes('Middleware.execute', target))).toBe(true); + expect(isIgnored(nextRequestSpanAttributes('Next.request', target))).toBe(true); }, ); + it('does not ignore a request span for a derived path outside of the base path', () => { + serveTunnel(['/k3x9q2a'], '/docs'); + + expect(isIgnored(nextRequestSpanAttributes('Next.request', '/k3x9q2a'))).toBe(false); + }); + it.each([ - ['rewrite', '/monitoring'], - ['rewrite', '/monitoring/'], - ['handler', '/monitoring'], - ] as const)('ignores a Next.request proxy root span in %s mode for %s', (mode, target) => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - globalWithInjectedValues._sentryTunnelRouteMode = mode; - - expect(isIgnored(nextRequestSpanAttributes('Next.request', target))).toBe(true); + ['BaseServer.handleRequest', '/monitoring'], + ['BaseServer.handleRequest', '/monitoring/'], + ['BaseServer.handleRequest', '/monitoring?cache=0'], + ['Middleware.execute', '/monitoring'], + ['Next.request', '/monitoring'], + ['Next.request', '/monitoring/'], + ])('ignores a %s span for %s', (spanType, target) => { + serveTunnel(['/monitoring']); + + expect(isIgnored(nextRequestSpanAttributes(spanType, target))).toBe(true); }); it.each(['/monitoring/dashboard', '/monitoring-dashboard', '/api/monitoring'])( - 'does not ignore a Next.request proxy root span for %s', + 'does not ignore a request span for %s', target => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); + expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', target))).toBe(false); expect(isIgnored(nextRequestSpanAttributes('Next.request', target))).toBe(false); }, ); - it('does not ignore a request span for a sub-path in handler mode', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; - - expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', '/monitoring/dashboard'))).toBe(false); - }); - it('does not ignore an outgoing request with the tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; + serveTunnel(['/monitoring']); const outgoingRequestAttributes = { [URL_PATH]: '/monitoring', @@ -266,10 +253,9 @@ describe('getTunnelRouteIgnoreSpans', () => { }); it.each(['/sentry-tunnel', '/sentry-tunnel/route'])( - 'ignores the route handler span with next.route %s in handler mode', + 'ignores the route handler span with next.route %s', nextRoute => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; + serveTunnel(['/monitoring']); expect( isIgnored({ [ATTR_NEXT_SPAN_TYPE]: 'AppRouteRouteHandlers.runHandler', [ATTR_NEXT_ROUTE]: nextRoute }), @@ -277,18 +263,9 @@ describe('getTunnelRouteIgnoreSpans', () => { }, ); - it('does not ignore the route handler span in rewrite mode', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/monitoring'; - globalWithInjectedValues._sentryTunnelRouteMode = 'rewrite'; - - expect( - isIgnored({ [ATTR_NEXT_SPAN_TYPE]: 'AppRouteRouteHandlers.runHandler', [ATTR_NEXT_ROUTE]: '/sentry-tunnel' }), - ).toBe(false); - }); - it('escapes regex characters in the tunnel path', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/a.b'; + serveTunnel(['/a.b']); - expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', '/axb?o=123&p=456'))).toBe(false); + expect(isIgnored(nextRequestSpanAttributes('BaseServer.handleRequest', '/axb'))).toBe(false); }); }); diff --git a/packages/nextjs/test/utils/tunnelRoute.test.ts b/packages/nextjs/test/utils/tunnelRoute.test.ts index 30dd3f840ba3..05ed6fdd4c22 100644 --- a/packages/nextjs/test/utils/tunnelRoute.test.ts +++ b/packages/nextjs/test/utils/tunnelRoute.test.ts @@ -1,193 +1,61 @@ import type { BrowserOptions } from '@sentry/react'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { applyTunnelRouteOption } from '../../src/client/tunnelRoute'; +const DSN = 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333'; + const globalWithInjectedValues = global as typeof global & { - _sentryRewritesTunnelPath?: string; - _sentryTunnelRouteMode?: string; + _sentryTunnelRoute?: string; }; beforeEach(() => { - vi.restoreAllMocks(); - globalWithInjectedValues._sentryRewritesTunnelPath = undefined; - globalWithInjectedValues._sentryTunnelRouteMode = undefined; -}); - -describe('applyTunnelRouteOption()', () => { - it('Correctly applies `tunnelRoute` option when conditions are met', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBe('/my-error-monitoring-route?o=2222222&p=3333333'); - }); - - it("Doesn't apply `tunnelRoute` when DSN is missing", () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - const options: any = { - // no dsn - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBeUndefined(); - }); - - it("Doesn't apply `tunnelRoute` when DSN is invalid", () => { - // Avoid polluting the test output with error messages - const mockConsoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); - - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - const options: any = { - dsn: 'invalidDsn', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBeUndefined(); - - mockConsoleError.mockRestore(); - }); - - it("Doesn't apply `tunnelRoute` option when `tunnelRoute` option wasn't injected", () => { - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBeUndefined(); - }); - - it("Doesn't `tunnelRoute` option when DSN is not a SaaS DSN", () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - const options: any = { - dsn: 'https://11111111111111111111111111111111@example.com/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBeUndefined(); - }); - - it('Correctly applies `tunnelRoute` option to region DSNs', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.us.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBe('/my-error-monitoring-route?o=2222222&p=3333333&r=us'); - }); + globalWithInjectedValues._sentryTunnelRoute = undefined; }); -describe('Random tunnel route generation', () => { - it('Works when tunnelRoute is true and generates random-looking paths', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/abc123def'; // Simulated random path - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBe('/abc123def?o=2222222&p=3333333'); - expect(options.tunnel).toMatch(/^\/[a-z0-9]+\?o=2222222&p=3333333$/); - }); - - it('Works with region DSNs when tunnelRoute is true', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/x7h9k2m'; // Simulated random path - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.eu.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBe('/x7h9k2m?o=2222222&p=3333333&r=eu'); - expect(options.tunnel).toMatch(/^\/[a-z0-9]+\?o=2222222&p=3333333&r=eu$/); - }); - - it('Does not apply tunnel when tunnelRoute is false', () => { - globalWithInjectedValues._sentryRewritesTunnelPath = undefined; - const options: any = { - dsn: 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333', - } as BrowserOptions; - - applyTunnelRouteOption(options); - - expect(options.tunnel).toBeUndefined(); - }); +afterEach(() => { + vi.unstubAllEnvs(); }); -describe('applyTunnelRouteOption() credentials', () => { - const SAAS_DSN = 'https://11111111111111111111111111111111@o2222222.ingest.sentry.io/3333333'; - - beforeEach(() => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - }); - - it("sends tunnel requests with `credentials: 'omit'`", () => { - const options: BrowserOptions = { dsn: SAAS_DSN }; - - applyTunnelRouteOption(options); - - expect(options.transportOptions).toEqual({ fetchOptions: { credentials: 'omit' } }); - }); - - it('keeps the fetch options of the user', () => { - const options: BrowserOptions = { - dsn: SAAS_DSN, - transportOptions: { bufferSize: 10, fetchOptions: { credentials: 'same-origin', priority: 'low' } }, - }; +describe('applyTunnelRouteOption()', () => { + it('sends events to the fixed path of the `tunnelRoute`', () => { + globalWithInjectedValues._sentryTunnelRoute = '/docs/monitoring'; + const options: BrowserOptions = { dsn: DSN }; applyTunnelRouteOption(options); - expect(options.transportOptions).toEqual({ - bufferSize: 10, - fetchOptions: { credentials: 'same-origin', priority: 'low' }, - }); + expect(options.tunnel).toEqual({ path: '/docs/monitoring', trailingSlash: false }); }); - it('does not change the transport options when the events are not tunneled', () => { - const options: BrowserOptions = { dsn: 'https://11111111111111111111111111111111@example.com/3333333' }; + it('sends events to the path derived from the DSN for `tunnelRoute: true`', () => { + globalWithInjectedValues._sentryTunnelRoute = 'true'; + const options: BrowserOptions = { dsn: DSN }; applyTunnelRouteOption(options); - expect(options.transportOptions).toBeUndefined(); + expect(options.tunnel).toBe(true); }); - it('does not change the transport options in handler mode', () => { - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; - const options: BrowserOptions = { dsn: SAAS_DSN }; + it('adds the trailing slash Next.js redirects to', () => { + vi.stubEnv('_sentryTrailingSlash', 'true'); + globalWithInjectedValues._sentryTunnelRoute = '/monitoring'; + const options: BrowserOptions = { dsn: DSN }; applyTunnelRouteOption(options); - expect(options.transportOptions).toBeUndefined(); + expect(options.tunnel).toEqual({ path: '/monitoring', trailingSlash: true }); }); -}); -describe('applyTunnelRouteOption() in handler mode', () => { - it.each([ - ['a SaaS DSN', 'https://11111111111111111111111111111111@o2222222.ingest.us.sentry.io/3333333'], - ['a self-hosted DSN', 'https://11111111111111111111111111111111@sentry.example.com/3333333'], - ])('tunnels %s to the tunnel path with no query', (_description, dsn) => { - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; - const options: BrowserOptions = { dsn }; + it('keeps the `tunnel` the user set', () => { + globalWithInjectedValues._sentryTunnelRoute = '/monitoring'; + const options: BrowserOptions = { dsn: DSN, tunnel: 'https://tunnel.example.com' }; applyTunnelRouteOption(options); - expect(options.tunnel).toBe('/my-error-monitoring-route'); + expect(options.tunnel).toBe('https://tunnel.example.com'); }); - it("Doesn't apply `tunnelRoute` when DSN is invalid", () => { - vi.spyOn(console, 'error').mockImplementation(() => {}); - globalWithInjectedValues._sentryRewritesTunnelPath = '/my-error-monitoring-route'; - globalWithInjectedValues._sentryTunnelRouteMode = 'handler'; - const options: BrowserOptions = { dsn: 'invalidDsn' }; + it('does not set a `tunnel` without a `tunnelRoute`', () => { + const options: BrowserOptions = { dsn: DSN }; applyTunnelRouteOption(options); From edae47ff279e151cc5088c8b4a5ea7a7895e7d8f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:19:33 +0100 Subject: [PATCH 032/136] feat(aws-serverless): Add HTTP request and response attributes to function.aws spans (#26226) **Why:** When a Lambda runs behind a Function URL, API Gateway, or ALB, its `function.aws` span only had `url.full` to say which request it handled. So two invocations of the same function (e.g. `/` and the browser's `/favicon.ico` fetch in #25813) looked like a duplicated trace. These spans now get the request attributes `http.server` spans have: `http.request.method`, `url.path`, `url.query`, `url.scheme`, `server.address`/`server.port`, `client.address` (gated by `dataCollection.userInfo`, like `http.server`), `user_agent.original`, `network.protocol.*`, `faas.trigger: http`, and `http.response.status_code` from the handler result. None of these are deprecated in `@sentry/conventions`, and no existing attribute is removed or changed. `http.route` is only set from route templates: the HTTP API `routeKey` (method prefix stripped) and the REST API `resource`. Function URLs and `$default` routes get no route. HTTP API payload format 1.0 also gets none, because it puts the raw path in `resource` for `$default`. The span name stays the function name so it stays low cardinality. **How to review:** Start with `httpEventAttributes.ts`. The handler change only passes the event through so the status code can be set when the span ends. **Unsure about:** The status code only comes from a non-streaming result's `statusCode`. For payload 2.0 a 200 is also inferred when the handler returns a value without one, since that's what AWS does. The span status isn't derived from the status code, because that would turn spans that are `ok` today into errors. The new e2e test hasn't been run locally. Refs #25813 via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794297679.791099) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794297679.791099/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .../aws-serverless/tests/npm.test.ts | 45 +++ .../aws-serverless/src/httpEventAttributes.ts | 188 ++++++++++++ .../aws-serverless/src/instrumentHandler.ts | 17 +- .../aws-serverless/src/requestSpanOptions.ts | 66 +---- .../test/httpEventAttributes.test.ts | 275 ++++++++++++++++++ .../test/instrumentHandler.test.ts | 20 ++ .../test/requestSpanOptions.test.ts | 37 --- 7 files changed, 545 insertions(+), 103 deletions(-) create mode 100644 packages/aws-serverless/src/httpEventAttributes.ts create mode 100644 packages/aws-serverless/test/httpEventAttributes.test.ts delete mode 100644 packages/aws-serverless/test/requestSpanOptions.test.ts diff --git a/dev-packages/e2e-tests/test-applications/aws-serverless/tests/npm.test.ts b/dev-packages/e2e-tests/test-applications/aws-serverless/tests/npm.test.ts index 35a262a25e64..aee8df255888 100644 --- a/dev-packages/e2e-tests/test-applications/aws-serverless/tests/npm.test.ts +++ b/dev-packages/e2e-tests/test-applications/aws-serverless/tests/npm.test.ts @@ -82,4 +82,49 @@ test.describe('NPM package', () => { assertLambdaTrace(spans, functionName); }); } + + test('adds HTTP attributes for Function URL events', async ({ lambdaClient }) => { + const functionName = 'NpmTracingEsm'; + const spansPromise = collectStreamedSpans('aws-serverless', spansOfTrace => + spansOfTrace.some(span => span.is_segment && span.attributes['url.path']?.value === '/users/123'), + ); + + await lambdaClient.send( + new InvokeCommand({ + FunctionName: functionName, + Payload: JSON.stringify({ + version: '2.0', + routeKey: '$default', + rawPath: '/users/123', + rawQueryString: 'page=2', + headers: { + host: 'abc123.lambda-url.us-east-1.on.aws', + 'user-agent': 'e2e-test', + 'x-forwarded-port': '443', + 'x-forwarded-proto': 'https', + }, + requestContext: { + domainName: 'abc123.lambda-url.us-east-1.on.aws', + http: { method: 'GET', path: '/users/123', protocol: 'HTTP/1.1', sourceIp: '198.51.100.7' }, + }, + }), + }), + ); + + const segmentSpan = (await spansPromise).find(span => span.is_segment); + + expect(segmentSpan?.name).toBe(functionName); + expect(segmentSpan?.attributes).toMatchObject({ + 'faas.trigger': { value: 'http', type: 'string' }, + 'http.request.method': { value: 'GET', type: 'string' }, + 'url.full': { value: 'https://abc123.lambda-url.us-east-1.on.aws/users/123?page=2', type: 'string' }, + 'url.path': { value: '/users/123', type: 'string' }, + 'url.query': { value: 'page=2', type: 'string' }, + 'url.scheme': { value: 'https', type: 'string' }, + 'server.address': { value: 'abc123.lambda-url.us-east-1.on.aws', type: 'string' }, + 'user_agent.original': { value: 'e2e-test', type: 'string' }, + 'network.protocol.version': { value: '1.1', type: 'string' }, + }); + expect(segmentSpan?.attributes['http.route']).toBeUndefined(); + }); }); diff --git a/packages/aws-serverless/src/httpEventAttributes.ts b/packages/aws-serverless/src/httpEventAttributes.ts new file mode 100644 index 000000000000..489550afaed1 --- /dev/null +++ b/packages/aws-serverless/src/httpEventAttributes.ts @@ -0,0 +1,188 @@ +import { + CLIENT_ADDRESS, + FAAS_TRIGGER, + HTTP_REQUEST_METHOD, + HTTP_RESPONSE_STATUS_CODE, + HTTP_ROUTE, + NETWORK_PROTOCOL_NAME, + NETWORK_PROTOCOL_VERSION, + SERVER_ADDRESS, + SERVER_PORT, + URL_FULL, + URL_PATH, + URL_QUERY, + URL_SCHEME, + USER_AGENT_ORIGINAL, +} from '@sentry/conventions/attributes'; +import type { Client, SpanAttributes } from '@sentry/core'; +import { filterCollectedUrl, filterCollectedUrlQuery, isPlainObject } from '@sentry/core'; +import { getClientIPAddress } from '@sentry/core/server'; + +type EventHeaders = Record; + +const DEFAULT_PORTS: Record = { http: '80', https: '443' }; + +interface HttpEventLike { + version?: string; + httpMethod?: string; + path?: string; + rawPath?: string; + rawQueryString?: string; + resource?: string; + routeKey?: string; + headers?: EventHeaders | null; + multiValueHeaders?: Record | null; + queryStringParameters?: Record | null; + multiValueQueryStringParameters?: Record | null; + requestContext?: { + domainName?: string; + protocol?: string; + elb?: unknown; + identity?: { sourceIp?: string; userAgent?: string }; + http?: { method?: string; path?: string; protocol?: string; sourceIp?: string; userAgent?: string }; + }; +} + +/** + * Builds the request attributes `http.server` spans have for invocations triggered by an HTTP event + * (Lambda Function URLs, API Gateway REST and HTTP APIs, ALB). + */ +export function getHttpRequestAttributes(event: unknown, client: Client | undefined): SpanAttributes { + const format = getPayloadFormat(event); + if (!format) { + return {}; + } + + const httpEvent = event as HttpEventLike; + const isV2 = format === '2.0'; + const requestContext = httpEvent.requestContext || {}; + const headers = getHeaders(httpEvent); + const { http, identity } = requestContext; + const scheme = getHeader(headers, 'x-forwarded-proto'); + const forwardedPort = getHeader(headers, 'x-forwarded-port'); + const port = Number(forwardedPort); + const path = isV2 ? httpEvent.rawPath || http?.path : httpEvent.path; + const query = isV2 ? httpEvent.rawQueryString : getQueryFromParameters(httpEvent, !!requestContext.elb); + // Like on `http.server` spans, a forwarding header wins: `sourceIp` is the address of whatever connected + // to AWS, which is a proxy such as CloudFront when there is one in front. + const clientAddress = client?.getDataCollectionOptions().userInfo + ? getClientIPAddress(headers) || http?.sourceIp || identity?.sourceIp || undefined + : undefined; + + return { + [FAAS_TRIGGER]: 'http', + [HTTP_REQUEST_METHOD]: (http?.method || httpEvent.httpMethod)?.toUpperCase(), + [HTTP_ROUTE]: isV2 ? getPayloadFormatV2Route(httpEvent) : getPayloadFormatV1Route(httpEvent), + [URL_FULL]: filterCollectedUrl(getFullUrl(scheme, getHeader(headers, 'host'), forwardedPort, path, query), client), + [URL_PATH]: path, + [URL_QUERY]: filterCollectedUrlQuery(query, client), + [URL_SCHEME]: scheme, + [SERVER_ADDRESS]: requestContext.domainName || getHeader(headers, 'host')?.replace(/:\d+$/, ''), + [SERVER_PORT]: Number.isInteger(port) && port > 0 ? port : undefined, + [CLIENT_ADDRESS]: clientAddress, + [USER_AGENT_ORIGINAL]: http?.userAgent || identity?.userAgent || getHeader(headers, 'user-agent'), + [NETWORK_PROTOCOL_NAME]: 'http', + [NETWORK_PROTOCOL_VERSION]: (http?.protocol || requestContext.protocol)?.match(/^HTTP\/(.+)$/i)?.[1], + }; +} + +/** + * Builds the response attributes for an invocation triggered by an HTTP event, based on what the handler returned. + */ +export function getHttpResponseAttributes(event: unknown, result: unknown): SpanAttributes { + const format = getPayloadFormat(event); + if (!format) { + return {}; + } + + const statusCode = isPlainObject(result) ? result.statusCode : undefined; + if (statusCode != null) { + // ALB also accepts the status code as a string. + const code = Number(statusCode); + return Number.isInteger(code) && code > 0 ? { [HTTP_RESPONSE_STATUS_CODE]: code } : {}; + } + + // For payload format 2.0 (Function URLs, HTTP APIs), Lambda answers with a 200 when the handler + // returns anything without a `statusCode`. Format 1.0 requires one, so we can't infer it there. + // https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html#http-api-develop-integrations-lambda.response + return format === '2.0' && result !== undefined ? { [HTTP_RESPONSE_STATUS_CODE]: 200 } : {}; +} + +// Payload format 1.0 is used by API Gateway REST APIs, HTTP APIs configured for it, and (in the same shape) ALB. +function getPayloadFormat(event: unknown): '1.0' | '2.0' | undefined { + if (!isPlainObject(event)) { + return undefined; + } + const httpEvent = event as HttpEventLike; + if (httpEvent.version === '2.0' && typeof httpEvent.requestContext?.http?.method === 'string') { + return '2.0'; + } + return typeof httpEvent.httpMethod === 'string' ? '1.0' : undefined; +} + +// `$default` is the catch-all route that Function URLs and HTTP API default stages use, not a route template. +function getPayloadFormatV2Route(event: HttpEventLike): string | undefined { + return event.routeKey && event.routeKey !== '$default' ? event.routeKey.replace(/^\S+\s+/, '') : undefined; +} + +// REST APIs send the route template (e.g. `/users/{id}`) as `resource`. HTTP APIs using payload format 1.0 +// (which, unlike REST APIs, set `version`) send the request path there for their catch-all `$default` route, +// so we can't tell a template from a raw path. ALB events have no route. +function getPayloadFormatV1Route(event: HttpEventLike): string | undefined { + return event.version === undefined ? event.resource : undefined; +} + +// ALB passes query parameters as sent, API Gateway decodes them. +function getQueryFromParameters(event: HttpEventLike, isEncoded: boolean): string | undefined { + const encode = isEncoded ? (value: string): string => value : encodeURIComponent; + const pairs: string[] = []; + + if (event.multiValueQueryStringParameters) { + for (const [key, values] of Object.entries(event.multiValueQueryStringParameters)) { + for (const value of values || []) { + pairs.push(`${encode(key)}=${encode(value)}`); + } + } + } else if (event.queryStringParameters) { + for (const [key, value] of Object.entries(event.queryStringParameters)) { + pairs.push(`${encode(key)}=${encode(value ?? '')}`); + } + } + + return pairs.length ? pairs.join('&') : undefined; +} + +function getFullUrl( + scheme: string | undefined, + host: string | undefined, + port: string | undefined, + path: string | undefined, + query: string | undefined, +): string | undefined { + if (!scheme || !host || !path) { + return undefined; + } + // Clients put non-default ports into the host header, which ALB passes through as is. + const portSuffix = port && port !== DEFAULT_PORTS[scheme] && !/:\d+$/.test(host) ? `:${port}` : ''; + return `${scheme}://${host}${portSuffix}${path}${query ? `?${query}` : ''}`; +} + +// ALB target groups with multi-value headers enabled send only `multiValueHeaders`. +function getHeaders(event: HttpEventLike): EventHeaders { + const headers: EventHeaders = { ...event.headers }; + for (const [name, values] of Object.entries(event.multiValueHeaders || {})) { + if (values?.length && getHeader(headers, name.toLowerCase()) === undefined) { + headers[name] = values.join(', '); + } + } + return headers; +} + +function getHeader(headers: EventHeaders, name: string): string | undefined { + for (const key in headers) { + if (key.toLowerCase() === name) { + return headers[key]; + } + } + return undefined; +} diff --git a/packages/aws-serverless/src/instrumentHandler.ts b/packages/aws-serverless/src/instrumentHandler.ts index c1b4fb2bf5b2..2c976550f5e6 100644 --- a/packages/aws-serverless/src/instrumentHandler.ts +++ b/packages/aws-serverless/src/instrumentHandler.ts @@ -21,6 +21,7 @@ import { continueTrace, debug, SPAN_STATUS_ERROR, startSpanManual } from '@sentr import { captureException } from '@sentry/node'; import type { Callback, Context, Handler, StreamifyHandler } from 'aws-lambda'; import { DEBUG_BUILD } from './debug-build'; +import { getHttpResponseAttributes } from './httpEventAttributes'; import { getRequestSpanOptions } from './requestSpanOptions'; import { AWS_HANDLER_HIGHWATERMARK_SYMBOL, AWS_HANDLER_STREAMING_SYMBOL, isStreamingHandler, wrapHandler } from './sdk'; import { getAwsTraceData, markEventUnhandled } from './utils'; @@ -122,7 +123,7 @@ function getPatchedHandler(original: Handler | StreamifyHandler, lambdaStartTime // the handler and see if the result is a Promise or not. In such a case, the callback is usually ignored. If // the handler happened to both call the callback and complete a returned Promise, whichever happens first will // win and the latter will be ignored. - const wrappedCallback = wrapCallback(callback, span); + const wrappedCallback = wrapCallback(callback, span, event); let maybePromise: Promise | undefined; try { @@ -139,7 +140,7 @@ function getPatchedHandler(original: Handler | StreamifyHandler, lambdaStartTime return maybePromise; } - return handlePromiseResult(span, maybePromise); + return handlePromiseResult(span, maybePromise, event); }), ); }; @@ -149,10 +150,15 @@ function captureLambdaError(err: Error | string): void { captureException(err, scope => markEventUnhandled(scope, 'auto.function.aws_serverless.otel')); } -function handlePromiseResult(span: Span, maybePromise: Promise | undefined): Promise | undefined { +function handlePromiseResult( + span: Span, + maybePromise: Promise | undefined, + event?: LambdaEvent, +): Promise | undefined { if (typeof maybePromise?.then === 'function') { return maybePromise.then( value => { + span.setAttributes(getHttpResponseAttributes(event, value)); endSpan(span, undefined); return value; }, @@ -165,15 +171,18 @@ function handlePromiseResult(span: Span, maybePromise: Promise | undefi } // Handle synchronous return values by ending the span + span.setAttributes(getHttpResponseAttributes(event, maybePromise)); endSpan(span, undefined); return maybePromise; } -function wrapCallback(original: Callback, span: Span): Callback { +function wrapCallback(original: Callback, span: Span, event: LambdaEvent): Callback { return function wrappedCallback(this: unknown, err, res) { DEBUG_BUILD && debug.log('executing wrapped lambda callback function'); if (err) { captureLambdaError(err); + } else { + span.setAttributes(getHttpResponseAttributes(event, res)); } endSpan(span, err); diff --git a/packages/aws-serverless/src/requestSpanOptions.ts b/packages/aws-serverless/src/requestSpanOptions.ts index f2843f6ac419..7ab0554abd06 100644 --- a/packages/aws-serverless/src/requestSpanOptions.ts +++ b/packages/aws-serverless/src/requestSpanOptions.ts @@ -28,26 +28,12 @@ import { SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, - URL_FULL, } from '@sentry/conventions/attributes'; import { FUNCTION_AWS } from '@sentry/conventions/op'; -import type { SpanAttributes, StartSpanOptions } from '@sentry/core'; -import { - getClient, - hasSpanStreamingEnabled, - SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK, - filterCollectedUrl, -} from '@sentry/core'; +import type { StartSpanOptions } from '@sentry/core'; +import { getClient, hasSpanStreamingEnabled, SERVERLESS_FUNCTION_SPAN_NAME_FALLBACK } from '@sentry/core'; import type { Context } from 'aws-lambda'; - -const DEFAULT_PORTS: Record = { http: '80', https: '443' }; - -interface ApiGatewayLikeEvent { - headers?: Record; - path?: string; - rawPath?: string; - queryStringParameters?: Record; -} +import { getHttpRequestAttributes } from './httpEventAttributes'; /** * Builds the options for the `function.aws` transaction started for each invocation. @@ -75,7 +61,7 @@ export function getRequestSpanOptions(event: unknown, context: Context, requestI [CLOUD_PLATFORM]: 'aws_lambda', [FAAS_NAME]: functionName, [FAAS_COLDSTART]: requestIsColdStart, - ...extractOtherEventFields(event), + ...getHttpRequestAttributes(event, client), }, }; } @@ -97,47 +83,3 @@ function extractAccountId(arn: string): string | undefined { } return undefined; } - -function extractOtherEventFields(event: unknown): SpanAttributes { - const answer: SpanAttributes = {}; - const fullUrl = extractFullUrl(event as ApiGatewayLikeEvent); - if (fullUrl) { - answer[URL_FULL] = filterCollectedUrl(fullUrl); - } - return answer; -} - -function extractFullUrl(event: ApiGatewayLikeEvent): string | undefined { - // API gateway encodes a lot of url information in various places to recompute this - const headers = event.headers; - if (!headers) { - return undefined; - } - // Helper function to deal with case variations (instead of making a tolower() copy of the headers) - function findAny(key1: string, key2: string): string | undefined { - return headers?.[key1] ?? headers?.[key2]; - } - const host = findAny('host', 'Host'); - const proto = findAny('x-forwarded-proto', 'X-Forwarded-Proto'); - const port = findAny('x-forwarded-port', 'X-Forwarded-Port'); - if (!(proto && host && (event.path || event.rawPath))) { - return undefined; - } - let answer = `${proto}://${host}`; - // Clients put non-default ports into the host header, which ALB passes through as is. - if (port && port !== DEFAULT_PORTS[proto] && !/:\d+$/.test(host)) { - answer += `:${port}`; - } - answer += event.path ?? event.rawPath; - if (event.queryStringParameters) { - let first = true; - for (const [key, value] of Object.entries(event.queryStringParameters)) { - answer += first ? '?' : '&'; - answer += encodeURIComponent(key); - answer += '='; - answer += encodeURIComponent(value ?? ''); - first = false; - } - } - return answer; -} diff --git a/packages/aws-serverless/test/httpEventAttributes.test.ts b/packages/aws-serverless/test/httpEventAttributes.test.ts new file mode 100644 index 000000000000..f9a415eb6f70 --- /dev/null +++ b/packages/aws-serverless/test/httpEventAttributes.test.ts @@ -0,0 +1,275 @@ +import { + CLIENT_ADDRESS, + FAAS_TRIGGER, + HTTP_REQUEST_METHOD, + HTTP_RESPONSE_STATUS_CODE, + HTTP_ROUTE, + NETWORK_PROTOCOL_NAME, + NETWORK_PROTOCOL_VERSION, + SERVER_ADDRESS, + SERVER_PORT, + URL_FULL, + URL_PATH, + URL_QUERY, + URL_SCHEME, + USER_AGENT_ORIGINAL, +} from '@sentry/conventions/attributes'; +import type { Client } from '@sentry/core'; +import { describe, expect, test } from 'vitest'; +import { getHttpRequestAttributes, getHttpResponseAttributes } from '../src/httpEventAttributes'; + +function makeClient(userInfo: boolean): Client { + return { + getDataCollectionOptions: () => ({ userInfo, urlQueryParams: true }), + } as unknown as Client; +} + +// https://docs.aws.amazon.com/lambda/latest/dg/urls-invocation.html#urls-payloads +const functionUrlEvent = { + version: '2.0', + routeKey: '$default', + rawPath: '/favicon.ico', + rawQueryString: 'size=32&theme=dark', + headers: { + host: 'abc123.lambda-url.us-east-1.on.aws', + 'user-agent': 'Mozilla/5.0', + 'x-forwarded-for': '198.51.100.7', + 'x-forwarded-port': '443', + 'x-forwarded-proto': 'https', + }, + requestContext: { + domainName: 'abc123.lambda-url.us-east-1.on.aws', + http: { + method: 'GET', + path: '/favicon.ico', + protocol: 'HTTP/1.1', + sourceIp: '198.51.100.7', + userAgent: 'Mozilla/5.0', + }, + routeKey: '$default', + }, + isBase64Encoded: false, +}; + +const httpApiV2Event = { + ...functionUrlEvent, + routeKey: 'GET /users/{id}', + rawPath: '/users/123', + rawQueryString: '', + requestContext: { + ...functionUrlEvent.requestContext, + domainName: 'api.example.com', + http: { ...functionUrlEvent.requestContext.http, path: '/users/123' }, + routeKey: 'GET /users/{id}', + }, +}; + +const restApiEvent = { + resource: '/users/{id}', + path: '/users/123', + httpMethod: 'POST', + headers: { + Host: 'abc123.execute-api.us-east-1.amazonaws.com', + 'User-Agent': 'curl/8.0', + 'X-Forwarded-Port': '443', + 'X-Forwarded-Proto': 'https', + }, + queryStringParameters: { tag: 'b', q: 'a b' }, + multiValueQueryStringParameters: { tag: ['a', 'b'], q: ['a b'] }, + requestContext: { + domainName: 'abc123.execute-api.us-east-1.amazonaws.com', + protocol: 'HTTP/1.1', + resourcePath: '/users/{id}', + identity: { sourceIp: '203.0.113.9', userAgent: 'curl/8.0' }, + }, +}; + +const httpApiV1Event = { + version: '1.0', + resource: '/users/123', + path: '/users/123', + httpMethod: 'GET', + headers: { host: 'api.example.com', 'x-forwarded-proto': 'https' }, + queryStringParameters: null, + multiValueQueryStringParameters: null, + requestContext: { + domainName: 'api.example.com', + protocol: 'HTTP/1.1', + resourcePath: '/users/123', + identity: { sourceIp: '203.0.113.9' }, + }, +}; + +const albEvent = { + httpMethod: 'GET', + path: '/search', + queryStringParameters: { q: 'a%20b' }, + headers: { + host: 'my-alb-123.us-east-1.elb.amazonaws.com:8080', + 'user-agent': 'curl/8.0', + 'x-forwarded-for': '192.0.2.44', + 'x-forwarded-port': '8080', + 'x-forwarded-proto': 'http', + }, + requestContext: { elb: { targetGroupArn: 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/tg/1' } }, + isBase64Encoded: false, +}; + +describe('getHttpRequestAttributes', () => { + test('sets HTTP attributes for a Function URL event', () => { + expect(getHttpRequestAttributes(functionUrlEvent, makeClient(true))).toEqual({ + [FAAS_TRIGGER]: 'http', + [HTTP_REQUEST_METHOD]: 'GET', + [HTTP_ROUTE]: undefined, + [URL_PATH]: '/favicon.ico', + [URL_QUERY]: 'size=32&theme=dark', + [URL_SCHEME]: 'https', + [SERVER_ADDRESS]: 'abc123.lambda-url.us-east-1.on.aws', + [SERVER_PORT]: 443, + [CLIENT_ADDRESS]: '198.51.100.7', + [URL_FULL]: 'https://abc123.lambda-url.us-east-1.on.aws/favicon.ico?size=32&theme=dark', + [USER_AGENT_ORIGINAL]: 'Mozilla/5.0', + [NETWORK_PROTOCOL_NAME]: 'http', + [NETWORK_PROTOCOL_VERSION]: '1.1', + }); + }); + + test('handles null headers', () => { + expect(getHttpRequestAttributes({ ...restApiEvent, headers: null }, makeClient(true))).toMatchObject({ + [HTTP_REQUEST_METHOD]: 'POST', + [URL_SCHEME]: undefined, + [CLIENT_ADDRESS]: '203.0.113.9', + }); + expect(getHttpRequestAttributes({ ...albEvent, headers: null }, makeClient(true))[CLIENT_ADDRESS]).toBeUndefined(); + }); + + test('reads multi-value headers of an ALB event', () => { + const { headers, ...event } = albEvent; + const multiValueHeaders = Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, [value]])); + expect(getHttpRequestAttributes({ ...event, multiValueHeaders }, makeClient(true))).toEqual( + getHttpRequestAttributes(albEvent, makeClient(true)), + ); + }); + + test.each([ + ['80', 'http://example.com/search?q=a%20b'], + ['8443', 'http://example.com:8443/search?q=a%20b'], + ])('adds x-forwarded-port %s to url.full only when it is not the default', (port, expected) => { + const event = { + ...albEvent, + headers: { ...albEvent.headers, host: 'example.com', 'x-forwarded-port': port }, + }; + expect(getHttpRequestAttributes(event, makeClient(true))[URL_FULL]).toBe(expected); + }); + + test('prefers a forwarded client address over the source IP', () => { + const event = { + ...restApiEvent, + headers: { ...restApiEvent.headers, 'X-Forwarded-For': '198.51.100.20, 130.176.0.1' }, + requestContext: { ...restApiEvent.requestContext, identity: { sourceIp: '130.176.0.1' } }, + }; + expect(getHttpRequestAttributes(event, makeClient(true))[CLIENT_ADDRESS]).toBe('198.51.100.20'); + }); + + test('omits client.address when user info is not collected', () => { + expect(getHttpRequestAttributes(functionUrlEvent, makeClient(false))[CLIENT_ADDRESS]).toBeUndefined(); + expect(getHttpRequestAttributes(functionUrlEvent, undefined)[CLIENT_ADDRESS]).toBeUndefined(); + }); + + test('takes the route template from an HTTP API route key', () => { + expect(getHttpRequestAttributes(httpApiV2Event, makeClient(true))).toMatchObject({ + [HTTP_ROUTE]: '/users/{id}', + [URL_PATH]: '/users/123', + [URL_QUERY]: undefined, + [SERVER_ADDRESS]: 'api.example.com', + }); + }); + + test('sets HTTP attributes for a REST API event', () => { + expect(getHttpRequestAttributes(restApiEvent, makeClient(true))).toEqual({ + [FAAS_TRIGGER]: 'http', + [HTTP_REQUEST_METHOD]: 'POST', + [HTTP_ROUTE]: '/users/{id}', + [URL_PATH]: '/users/123', + [URL_QUERY]: 'tag=a&tag=b&q=a%20b', + [URL_SCHEME]: 'https', + [SERVER_ADDRESS]: 'abc123.execute-api.us-east-1.amazonaws.com', + [SERVER_PORT]: 443, + [CLIENT_ADDRESS]: '203.0.113.9', + [URL_FULL]: 'https://abc123.execute-api.us-east-1.amazonaws.com/users/123?tag=a&tag=b&q=a%20b', + [USER_AGENT_ORIGINAL]: 'curl/8.0', + [NETWORK_PROTOCOL_NAME]: 'http', + [NETWORK_PROTOCOL_VERSION]: '1.1', + }); + }); + + test('does not use the resource of an HTTP API payload format 1.0 event as route', () => { + expect(getHttpRequestAttributes(httpApiV1Event, makeClient(true))).toMatchObject({ + [FAAS_TRIGGER]: 'http', + [HTTP_ROUTE]: undefined, + [URL_PATH]: '/users/123', + [URL_QUERY]: undefined, + }); + }); + + test('sets HTTP attributes for an ALB event without re-encoding the query', () => { + expect(getHttpRequestAttributes(albEvent, makeClient(true))).toEqual({ + [FAAS_TRIGGER]: 'http', + [HTTP_REQUEST_METHOD]: 'GET', + [HTTP_ROUTE]: undefined, + [URL_PATH]: '/search', + [URL_QUERY]: 'q=a%20b', + [URL_SCHEME]: 'http', + [SERVER_ADDRESS]: 'my-alb-123.us-east-1.elb.amazonaws.com', + [SERVER_PORT]: 8080, + [CLIENT_ADDRESS]: '192.0.2.44', + [URL_FULL]: 'http://my-alb-123.us-east-1.elb.amazonaws.com:8080/search?q=a%20b', + [USER_AGENT_ORIGINAL]: 'curl/8.0', + [NETWORK_PROTOCOL_NAME]: 'http', + [NETWORK_PROTOCOL_VERSION]: undefined, + }); + }); + + test.each([ + ['an empty object', {}], + ['an SQS event', { Records: [{ eventSource: 'aws:sqs' }] }], + ['a string', 'hello'], + ['null', null], + ])('sets no attributes for %s', (_name, event) => { + expect(getHttpRequestAttributes(event, makeClient(true))).toEqual({}); + }); +}); + +describe('getHttpResponseAttributes', () => { + test('uses the returned status code', () => { + expect(getHttpResponseAttributes(functionUrlEvent, { statusCode: 404, body: '' })).toEqual({ + [HTTP_RESPONSE_STATUS_CODE]: 404, + }); + expect(getHttpResponseAttributes(restApiEvent, { statusCode: 201 })).toEqual({ + [HTTP_RESPONSE_STATUS_CODE]: 201, + }); + }); + + test('accepts a string status code', () => { + expect(getHttpResponseAttributes(albEvent, { statusCode: '404' })).toEqual({ [HTTP_RESPONSE_STATUS_CODE]: 404 }); + expect(getHttpResponseAttributes(functionUrlEvent, { statusCode: 'oops' })).toEqual({}); + }); + + test('infers a 200 for payload format 2.0 results without a status code', () => { + expect(getHttpResponseAttributes(functionUrlEvent, 'hello')).toEqual({ [HTTP_RESPONSE_STATUS_CODE]: 200 }); + expect(getHttpResponseAttributes(functionUrlEvent, { message: 'hello' })).toEqual({ + [HTTP_RESPONSE_STATUS_CODE]: 200, + }); + }); + + test('does not infer a status code for payload format 1.0 or missing results', () => { + expect(getHttpResponseAttributes(restApiEvent, { body: 'hello' })).toEqual({}); + expect(getHttpResponseAttributes(albEvent, 'hello')).toEqual({}); + expect(getHttpResponseAttributes(functionUrlEvent, undefined)).toEqual({}); + }); + + test('sets no attributes for non-HTTP events', () => { + expect(getHttpResponseAttributes({ Records: [{ eventSource: 'aws:sqs' }] }, { statusCode: 200 })).toEqual({}); + expect(getHttpResponseAttributes(undefined, { statusCode: 200 })).toEqual({}); + }); +}); diff --git a/packages/aws-serverless/test/instrumentHandler.test.ts b/packages/aws-serverless/test/instrumentHandler.test.ts index 5bea12c73bb4..2554deff7e16 100644 --- a/packages/aws-serverless/test/instrumentHandler.test.ts +++ b/packages/aws-serverless/test/instrumentHandler.test.ts @@ -1,9 +1,11 @@ +import { HTTP_RESPONSE_STATUS_CODE } from '@sentry/conventions/attributes'; import type { Context, Handler } from 'aws-lambda'; import { beforeEach, describe, expect, test, vi } from 'vitest'; import { instrumentHandler } from '../src/instrumentHandler'; const mockSpan = { setStatus: vi.fn(), + setAttributes: vi.fn(), end: vi.fn(), }; @@ -81,4 +83,22 @@ describe('instrumentHandler', () => { expect(mockSpan.end).toHaveBeenCalledTimes(1); expect(mockSpan.setStatus).not.toHaveBeenCalled(); }); + + test('sets the HTTP response status code for HTTP events', async () => { + const event = { version: '2.0', rawPath: '/', requestContext: { http: { method: 'GET' } } }; + const handler: Handler = async () => ({ statusCode: 404 }); + + await instrumentHandler(handler)(event, fakeContext, () => {}); + expect(mockSpan.setAttributes).toHaveBeenCalledWith({ [HTTP_RESPONSE_STATUS_CODE]: 404 }); + }); + + test('sets the HTTP response status code when a callback-style handler calls back', async () => { + const event = { httpMethod: 'GET', path: '/' }; + const handler: Handler = (_event, _context, callback) => { + setTimeout(() => callback(null, { statusCode: 302 }), 10); + }; + + await instrumentHandler(handler)(event, fakeContext, () => {}); + expect(mockSpan.setAttributes).toHaveBeenCalledWith({ [HTTP_RESPONSE_STATUS_CODE]: 302 }); + }); }); diff --git a/packages/aws-serverless/test/requestSpanOptions.test.ts b/packages/aws-serverless/test/requestSpanOptions.test.ts deleted file mode 100644 index 03f7870e7db7..000000000000 --- a/packages/aws-serverless/test/requestSpanOptions.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { URL_FULL } from '@sentry/conventions/attributes'; -import type { Context } from 'aws-lambda'; -import { describe, expect, test } from 'vitest'; -import { getRequestSpanOptions } from '../src/requestSpanOptions'; - -const context = { - functionName: 'functionName', - awsRequestId: 'awsRequestId', - invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:functionName', -} as Context; - -function getUrlFull(headers: Record): unknown { - return getRequestSpanOptions({ headers, rawPath: '/users' }, context, false).attributes?.[URL_FULL]; -} - -describe('getRequestSpanOptions', () => { - test.each([ - ['https', '443'], - ['http', '80'], - ])('omits the default port for %s', (proto, port) => { - expect(getUrlFull({ host: 'example.com', 'x-forwarded-proto': proto, 'x-forwarded-port': port })).toBe( - `${proto}://example.com/users`, - ); - }); - - test('keeps a non-default port', () => { - expect(getUrlFull({ host: 'example.com', 'x-forwarded-proto': 'https', 'x-forwarded-port': '8443' })).toBe( - 'https://example.com:8443/users', - ); - }); - - test('does not add the port again when the host header has it', () => { - expect(getUrlFull({ host: 'example.com:8080', 'x-forwarded-proto': 'http', 'x-forwarded-port': '8080' })).toBe( - 'http://example.com:8080/users', - ); - }); -}); From f8eb5458428fc1a35fc591a0c852a7a9802b5ff1 Mon Sep 17 00:00:00 2001 From: Sigrid <32902192+s1gr1d@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:46:45 +0100 Subject: [PATCH 033/136] feat(sveltekit): Mark pageloads of prerendered pages (#26301) **Why:** Pageloads of pages prerendered during `vite build` look like they have no server instrumentation. Now these pages get an empty `sentry-cache-origin` meta tag, and the pageload gets `page.server_rendering.type: static`. Unlike Next.js (#25318), the pageload gets no link, because the SDK does not reliably send spans from the build. **Unsure about:** To leave out `ssr = false` shells, the server checks for `node_ids:` in Kit's boot script, which Kit writes only for server-rendered pages ([source](https://github.com/sveltejs/kit/blob/%40sveltejs/kit%403.2.0/packages/kit/src/runtime/server/page/render.js#L452-L467)). Example (with UI changes from https://github.com/getsentry/sentry/pull/130771 applied) or pre-rendered, static page: https://sentry-4x3dkn58u.sentry.dev/explore/traces/trace/97190404f66048bd89da29cc0a21304f/ image Linear: [JSSDK-37](https://linear.app/getsentry/issue/JSSDK-37/sveltekit-page-options) --- .../src/routes/prerendered-shell/+page.svelte | 1 + .../src/routes/prerendered-shell/+page.ts | 2 + .../sveltekit-2-static/tests/sdk.test.ts | 47 ++++++++++++--- .../src/routes/prerendered-shell/+page.svelte | 1 + .../src/routes/prerendered-shell/+page.ts | 2 + .../sveltekit-3/tests/prerender.test.ts | 59 +++++++++++++++--- .../src/client/svelte4BrowserTracing.ts | 2 + .../src/client/svelte5BrowserTracing.ts | 2 + .../sveltekit/src/client/traceMetaTags.ts | 10 ++++ .../sveltekit/src/common/traceMetaTags.ts | 5 ++ .../sveltekit/src/server-common/handle.ts | 18 +++++- .../client/browserTracingIntegration.test.ts | 32 +++++++++- .../test/client/svelte5BrowserTracing.test.ts | 29 ++++++++- .../test/server-common/handle.test.ts | 60 +++++++++++++++++-- 14 files changed, 242 insertions(+), 28 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.svelte create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.ts create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-3/src/routes/prerendered-shell/+page.svelte create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-3/src/routes/prerendered-shell/+page.ts create mode 100644 packages/sveltekit/src/client/traceMetaTags.ts create mode 100644 packages/sveltekit/src/common/traceMetaTags.ts diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.svelte b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.svelte new file mode 100644 index 000000000000..d3c9d3fe79fc --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.svelte @@ -0,0 +1 @@ +

Prerendered shell

diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.ts new file mode 100644 index 000000000000..ceccaaf67a21 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/src/routes/prerendered-shell/+page.ts @@ -0,0 +1,2 @@ +export const prerender = true; +export const ssr = false; diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts index 23bce25b7ec4..a8d4a59d790c 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts @@ -1,6 +1,11 @@ import { expect, test } from '@playwright/test'; +import { waitForTransaction } from '@sentry-internal/test-utils'; import { waitForInitialPageload } from './utils'; +function sentryMetaTagNames(html: string): string[] { + return [...html.matchAll(/ match[1] ?? ''); +} + test.describe('SDK-internal behavior', () => { test("Doesn't inject fetch proxy script for SvelteKit>=2.16.0", async ({ page }) => { await waitForInitialPageload(page, { route: '/' }); @@ -14,16 +19,40 @@ test.describe('SDK-internal behavior', () => { expect(proxyHandle).toBe('undefined'); }); - test("Doesn't add trace meta tags to prerendered pages", async ({ request }) => { - const prerenderedHtml = await (await request.get('/prerendered')).text(); - const ssrHtml = await (await request.get('/')).text(); + [ + { path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin'] }, + { path: '/prerendered-shell', kind: 'a prerendered client-side shell', expected: [] }, + { path: '/', kind: 'a server-rendered page', expected: ['sentry-trace', 'baggage'] }, + ].forEach(({ path, kind, expected }) => { + test(`Writes the expected Sentry meta tags into ${kind} (${path})`, async ({ request }) => { + const html = await (await request.get(path)).text(); + + expect(sentryMetaTagNames(html)).toEqual(expected); + }); + }); + + test('Marks the pageload of a prerendered page as statically rendered, without a link', async ({ page }) => { + const pageloadTxnPromise = waitForTransaction('sveltekit-2-static', txnEvent => { + return txnEvent?.transaction === '/prerendered' && txnEvent.contexts?.trace?.op === 'pageload'; + }); + + await page.goto('/prerendered'); + const pageloadTxn = await pageloadTxnPromise; + + expect(pageloadTxn.contexts?.trace?.data?.['page.server_rendering.type']).toBe('static'); + expect(pageloadTxn.contexts?.trace?.links).toBeUndefined(); + expect(pageloadTxn.contexts?.trace?.parent_span_id).toBeUndefined(); + }); + + test("Doesn't mark the pageload of a prerendered client-side shell", async ({ page }) => { + const pageloadTxnPromise = waitForTransaction('sveltekit-2-static', txnEvent => { + return txnEvent?.transaction === '/prerendered-shell' && txnEvent.contexts?.trace?.op === 'pageload'; + }); - expect(prerenderedHtml).toContain('Prerendered page'); - expect(prerenderedHtml).not.toContain('Prerendered shell diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/src/routes/prerendered-shell/+page.ts b/dev-packages/e2e-tests/test-applications/sveltekit-3/src/routes/prerendered-shell/+page.ts new file mode 100644 index 000000000000..ceccaaf67a21 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/src/routes/prerendered-shell/+page.ts @@ -0,0 +1,2 @@ +export const prerender = true; +export const ssr = false; diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts b/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts index 9e9a5bbf4be8..d030334c2188 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts @@ -1,14 +1,55 @@ import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; -test("Doesn't add trace meta tags to prerendered pages", async ({ request }) => { - const prerenderedHtml = await (await request.get('/prerendered')).text(); - const ssrHtml = await (await request.get('/')).text(); +function sentryMetaTagNames(html: string): string[] { + return [...html.matchAll(/ match[1] ?? ''); +} - expect(prerenderedHtml).toContain('Prerendered page'); - expect(prerenderedHtml).not.toContain(' { + test(`writes the expected Sentry meta tags into ${kind} (${path})`, async ({ request }) => { + const html = await (await request.get(path)).text(); - // SSR pages still get the meta tags - expect(ssrHtml).toContain(' { + const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { + return span.name === '/prerendered' && getSpanOp(span) === 'pageload' && span.is_segment; + }); + + await page.goto('/prerendered'); + const pageloadSpan = await pageloadSpanPromise; + + expect(pageloadSpan.attributes?.['page.server_rendering.type']).toEqual({ type: 'string', value: 'static' }); + expect(pageloadSpan.links).toBeUndefined(); + expect(pageloadSpan.parent_span_id).toBeUndefined(); +}); + +test("doesn't mark the pageload of a prerendered client-side shell", async ({ page }) => { + const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { + return span.name === '/prerendered-shell' && getSpanOp(span) === 'pageload' && span.is_segment; + }); + + await page.goto('/prerendered-shell'); + const pageloadSpan = await pageloadSpanPromise; + + expect(pageloadSpan.attributes?.['page.server_rendering.type']).toBeUndefined(); + expect(pageloadSpan.parent_span_id).toBeUndefined(); +}); + +test("doesn't mark the pageload of a server-rendered page, which continues the server trace", async ({ page }) => { + const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { + return span.name === '/' && getSpanOp(span) === 'pageload' && span.is_segment; + }); + + await page.goto('/'); + const pageloadSpan = await pageloadSpanPromise; + + expect(pageloadSpan.attributes?.['page.server_rendering.type']).toBeUndefined(); + expect(pageloadSpan.parent_span_id).toMatch(/^[a-f0-9]{16}$/); }); diff --git a/packages/sveltekit/src/client/svelte4BrowserTracing.ts b/packages/sveltekit/src/client/svelte4BrowserTracing.ts index 9dbb21336021..6ecafdc5cb1f 100644 --- a/packages/sveltekit/src/client/svelte4BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte4BrowserTracing.ts @@ -26,6 +26,7 @@ import type { Navigation, Page } from '@sveltejs/kit'; // eslint-disable-next-line typescript/no-deprecated import { navigating, page } from '$app/stores'; import type { Readable } from 'svelte/store'; +import { getServerRenderingAttributes } from './traceMetaTags'; /** * SvelteKit 2 / Svelte 4 browser tracing (`$app/stores`). Selected at build time, so it's only @@ -58,6 +59,7 @@ function _instrumentPageload(client: Client, pageStore: Readable): void { [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + ...getServerRenderingAttributes(), }, }); if (!pageloadSpan) { diff --git a/packages/sveltekit/src/client/svelte5BrowserTracing.ts b/packages/sveltekit/src/client/svelte5BrowserTracing.ts index b8388adc91b6..8930775c56b4 100644 --- a/packages/sveltekit/src/client/svelte5BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte5BrowserTracing.ts @@ -24,6 +24,7 @@ import { import { NAVIGATION, PAGELOAD, ROUTER } from '@sentry/conventions/op'; import type { Navigation } from '@sveltejs/kit'; import { getCurrentNavigation, onNavigationChange, onPageRouteChange } from './navigationState.svelte'; +import { getServerRenderingAttributes } from './traceMetaTags'; /** * SvelteKit 3 / Svelte 5 browser tracing (`$app/state` runes). Selected at build time, so it's only @@ -54,6 +55,7 @@ function _instrumentPageLoad(client: Client): void { [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + ...getServerRenderingAttributes(), }, }); diff --git a/packages/sveltekit/src/client/traceMetaTags.ts b/packages/sveltekit/src/client/traceMetaTags.ts new file mode 100644 index 000000000000..b8e09933acce --- /dev/null +++ b/packages/sveltekit/src/client/traceMetaTags.ts @@ -0,0 +1,10 @@ +import { PAGE_SERVER_RENDERING_TYPE } from '@sentry/conventions/attributes'; +import type { SpanAttributes } from '@sentry/core'; +import { WINDOW } from '@sentry/svelte'; +import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; + +/** Set at span start, so `tracesSampler` sees it. */ +export function getServerRenderingAttributes(): SpanAttributes { + const isPrerendered = !!WINDOW.document?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`); + return isPrerendered ? { [PAGE_SERVER_RENDERING_TYPE]: 'static' } : {}; +} diff --git a/packages/sveltekit/src/common/traceMetaTags.ts b/packages/sveltekit/src/common/traceMetaTags.ts new file mode 100644 index 000000000000..d6618a156999 --- /dev/null +++ b/packages/sveltekit/src/common/traceMetaTags.ts @@ -0,0 +1,5 @@ +/** + * Replaces the trace meta tags of pages prerendered during the build. Empty, unlike in Next.js: spans + * from the build are not reliably sent, so there is no origin to link. + */ +export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/sveltekit/src/server-common/handle.ts b/packages/sveltekit/src/server-common/handle.ts index 38291b226679..bb996f16f7ca 100644 --- a/packages/sveltekit/src/server-common/handle.ts +++ b/packages/sveltekit/src/server-common/handle.ts @@ -25,6 +25,7 @@ import { _INTERNAL_setTunnelDefaults as setTunnelDefaults, } from '@sentry/core/server'; import { getTunnelBasePath } from '../common/tunnel'; +import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; import type { Handle, ResolveOptions } from './handleTypes'; import { DEBUG_BUILD } from '../common/debug-build'; import { getTracePropagationData, sendErrorToSentry } from './utils'; @@ -83,7 +84,7 @@ export function addSentryCodeToPage(options: { injectFetchProxyScript: boolean; }): NonNullable { return ({ html }) => { - const metaTags = isSvelteKitBuilding() ? '' : getTraceMetaTags(); + const metaTags = getPageMetaTags(html); const headWithMetaTags = metaTags ? `\n${metaTags}` : ''; const headWithFetchScript = options.injectFetchProxyScript ? `\n` : ''; @@ -94,9 +95,20 @@ export function addSentryCodeToPage(options: { }; } +/** Trace meta tags written during the build would put one trace into the HTML of every visitor. */ +function getPageMetaTags(html: string): string { + if (!isSvelteKitBuilding()) { + return getTraceMetaTags(); + } + return isServerRenderedPage(html) ? `` : ''; +} + +/** Kit writes `node_ids` only for server-rendered pages, not for shells (`ssr = false`, SPA fallback). */ +function isServerRenderedPage(html: string): boolean { + return html.includes('node_ids:'); +} + /** - * Prerendered pages would bake one trace id and sampling decision into the HTML for every visitor. - * * `building` from `$app/environment` isn't available here (the SDK is loaded from node_modules at * runtime), so we rely on `_SENTRY_SVELTEKIT_BUILDING`, which our Vite plugin sets during `vite build` * and SvelteKit copies into the worker it prerenders in. diff --git a/packages/sveltekit/test/client/browserTracingIntegration.test.ts b/packages/sveltekit/test/client/browserTracingIntegration.test.ts index c27d9db8ddb6..89210d628788 100644 --- a/packages/sveltekit/test/client/browserTracingIntegration.test.ts +++ b/packages/sveltekit/test/client/browserTracingIntegration.test.ts @@ -9,7 +9,14 @@ import { writable } from 'svelte/store'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { navigating, page } from '$app/stores'; import { browserTracingIntegration } from '../../src/client'; -import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_OP, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { CACHE_ORIGIN_META_TAG_NAME } from '../../src/common/traceMetaTags'; +import { + PAGE_SERVER_RENDERING_TYPE, + SENTRY_SEGMENT_NAME_SOURCE, + SENTRY_OP, + URL_TEMPLATE, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; // we have to overwrite the global mock from `vitest.setup.ts` here to reset the // `navigating` store for each test. @@ -72,6 +79,7 @@ describe('browserTracingIntegration', () => { beforeEach(() => { createdRootSpan = undefined; navigatingStore = writable(); + document.head.innerHTML = ''; vi.clearAllMocks(); }); @@ -171,6 +179,28 @@ describe('browserTracingIntegration', () => { expect(scopeSetTransactionNameSpy).toHaveBeenLastCalledWith('testRoute/:id'); }); + it('marks the pageload of a prerendered page as statically rendered, without a link', async () => { + const marker = document.createElement('meta'); + marker.name = CACHE_ORIGIN_META_TAG_NAME; + marker.content = ''; + document.head.appendChild(marker); + + const integration = browserTracingIntegration(); + // @ts-expect-error - the fakeClient doesn't satisfy Client but that's fine + integration.afterAllSetup(fakeClient); + await vi.dynamicImportSettled(); + + expect(startBrowserTracingPageLoadSpanSpy).toHaveBeenCalledWith(fakeClient, { + name: '/', + attributes: { + [SENTRY_OP]: 'pageload', + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + [PAGE_SERVER_RENDERING_TYPE]: 'static', + }, + }); + }); + it("doesn't start a navigation span when `instrumentNavigation` is false", async () => { const integration = browserTracingIntegration({ instrumentNavigation: false, diff --git a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts index eca41882dd76..a2975a0bafa5 100644 --- a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts +++ b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts @@ -5,9 +5,16 @@ /* eslint-disable @typescript-eslint/unbound-method */ import type { Span } from '@sentry/core'; import * as SentrySvelte from '@sentry/svelte'; -import { SENTRY_SEGMENT_NAME_SOURCE, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { + PAGE_SERVER_RENDERING_TYPE, + SENTRY_OP, + SENTRY_SEGMENT_NAME_SOURCE, + URL_TEMPLATE, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { instrumentSvelteKitTracing } from '../../src/client/svelte5BrowserTracing'; +import { CACHE_ORIGIN_META_TAG_NAME } from '../../src/common/traceMetaTags'; // The Svelte 5 variant reads navigation state from rune-backed helpers (`navigationState.svelte.ts`), // which need the Svelte compiler. We mock them here so the variant's orchestration logic (fetch @@ -70,6 +77,7 @@ describe('svelte5 browser tracing', () => { navigationChangeCb = undefined; pageRouteChangeCb = undefined; createdRootSpan = undefined; + document.head.innerHTML = ''; // The variant wraps `window.fetch`; give it a resolvable fetch to wrap and reset each test. window.fetch = vi.fn().mockResolvedValue(undefined); }); @@ -97,6 +105,25 @@ describe('svelte5 browser tracing', () => { expect(setTransactionNameSpy).toHaveBeenCalledWith('/users/[id]'); }); + it('marks the pageload of a prerendered page as statically rendered, without a link', () => { + const marker = document.createElement('meta'); + marker.name = CACHE_ORIGIN_META_TAG_NAME; + marker.content = ''; + document.head.appendChild(marker); + + instrumentSvelteKitTracing(client, {}); + + expect(startPageLoadSpanSpy).toHaveBeenCalledWith(client, { + name: '/', + attributes: { + [SENTRY_OP]: 'pageload', + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + [PAGE_SERVER_RENDERING_TYPE]: 'static', + }, + }); + }); + it("doesn't upgrade the pageload span while the route id is still null", () => { instrumentSvelteKitTracing(client, {}); pageRouteChangeCb?.(null); diff --git a/packages/sveltekit/test/server-common/handle.test.ts b/packages/sveltekit/test/server-common/handle.test.ts index 9e55877cfdad..e7b703f08c44 100644 --- a/packages/sveltekit/test/server-common/handle.test.ts +++ b/packages/sveltekit/test/server-common/handle.test.ts @@ -553,6 +553,28 @@ describe('addSentryCodeToPage', () => { `; + const withBootScript = (startArgs: string): string => + html.replace( + '%sveltekit.body%', + `

Pricing

+ `, + ); + const serverRenderedHtml = withBootScript(`app, element, { + node_ids: [0, 4], + data: [null,{type:"data",data:{plans:3},uses:{}}], + form: null, + error: null + }`); + const clientShellHtml = withBootScript('app, element'); + it("Adds add meta tags and fetch proxy script if there's no active transaction", () => { const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: true }); const transformed = transformPageChunk({ html, done: true }); @@ -575,6 +597,15 @@ describe('addSentryCodeToPage', () => { }); }); + it('does not add the cache origin marker to a page rendered for a request', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false }); + + const transformed = transformPageChunk({ html: serverRenderedHtml, done: true }); + + expect(transformed).toContain(' { const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false }); const transformed = transformPageChunk({ html, done: true }) as string; @@ -585,18 +616,37 @@ describe('addSentryCodeToPage', () => { }); describe('while SvelteKit builds the app', () => { + beforeEach(() => { + vi.stubEnv('_SENTRY_SVELTEKIT_BUILDING', 'true'); + }); + afterEach(() => { vi.unstubAllEnvs(); }); - it("doesn't add meta tags but still adds the fetch proxy script if _SENTRY_SVELTEKIT_BUILDING is set", () => { - vi.stubEnv('_SENTRY_SVELTEKIT_BUILDING', 'true'); + it('replaces the trace meta tags of a server-rendered page with an empty cache origin marker', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false }); + + const transformed = transformPageChunk({ html: serverRenderedHtml, done: true }); + + expect(transformed).toBe( + serverRenderedHtml.replace('', '\n'), + ); + }); + + it('adds no meta tags to a client-side shell, such as an `ssr = false` page or the fallback page', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false }); + const transformed = transformPageChunk({ html: clientShellHtml, done: true }); + + expect(transformed).toBe(clientShellHtml); + }); + + it('still adds the fetch proxy script', () => { const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: true }); - const transformed = transformPageChunk({ html, done: true }) as string; - expect(transformed).not.toContain('${FETCH_PROXY_SCRIPT}`); }); }); From 0a1b5002f9e6fa23d6078f3179e7f6178d2d15bd Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:51:57 +0000 Subject: [PATCH 034/136] test(scripts): Pass compare fn to sort in assign-reviewers tests (#26303) **Why:** Oxlint flags `typescript/require-array-sort-compare` on the two bare `picked.sort()` calls in `scripts/assign-reviewers.test.mjs`. The test-file override that turns that rule off only matches `*.test.{ts,tsx,js,jsx}` and test dirs, so this `.mjs` test at the top of `scripts/` isn't covered. Passing `localeCompare` keeps the assertions the same and is the smallest fix. Adding `**/*.test.mjs` to the override would also work, but that turns off more rules than this one. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794408184.575459) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794408184.575459/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- scripts/assign-reviewers.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/assign-reviewers.test.mjs b/scripts/assign-reviewers.test.mjs index 6f88a3702b1f..7d7e8ad62af0 100644 --- a/scripts/assign-reviewers.test.mjs +++ b/scripts/assign-reviewers.test.mjs @@ -56,7 +56,7 @@ describe('pickReviewers', () => { it('picks from the whole team when no codeowners match', () => { const picked = pickReviewers({ existing: [], codeownerPool: [], teamPool: ['a', 'b', 'c'], exclude: [] }); - expect(picked.sort()).toEqual(['a', 'b', 'c']); + expect(picked.sort((a, b) => a.localeCompare(b))).toEqual(['a', 'b', 'c']); }); it('never picks the author, excluded people, or existing reviewers, case-insensitively', () => { @@ -66,7 +66,7 @@ describe('pickReviewers', () => { teamPool: ['a', 'c', 'd'], exclude: ['a', 'mydea'], }); - expect(picked.sort()).toEqual(['c', 'd']); + expect(picked.sort((a, b) => a.localeCompare(b))).toEqual(['c', 'd']); }); it('only tops up to the required number of reviewers', () => { From da4000bbaa168c910be92047f05612971793b42e Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Wed, 11 Nov 2026 15:52:29 +0100 Subject: [PATCH 035/136] fix(server-utils): Read GLOBAL_OBJ at call time in Nitro integration (#26300) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Since 11.10, `Sentry.init` throws on TanStack Start + Nitro server builds. Nitro's rolldown emits `@sentry/server-utils` before `@sentry/core`'s `worldwide` module, so module-level aliases of `GLOBAL_OBJ` capture `undefined` and `nitroIntegration().setupOnce()` crashes. Reading `GLOBAL_OBJ` at call time removes the evaluation-order dependency. All four module-level aliases are changed, since fixing only `captureTracingEvents` would move the crash to the next call in the same `setupOnce`. **Unsure about:** This hardens against the bad ordering but doesn't explain why the bundle order flipped in 11.10 (cycle, CJS interop, or duplicate core). That still needs a repro. No regression test, because the failure depends on bundler evaluation order, which a unit test can't reproduce meaningfully. Closes #26258 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../src/integrations/nitro/captureStorageEvents.ts | 5 +++-- .../src/integrations/nitro/captureTracingEvents.ts | 9 ++++----- .../src/integrations/nitro/setServerTimingHeaders.ts | 5 +++-- packages/server-utils/src/utils/runtime.ts | 6 +++--- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/server-utils/src/integrations/nitro/captureStorageEvents.ts b/packages/server-utils/src/integrations/nitro/captureStorageEvents.ts index 0e464947c37c..0ef64b4af6cc 100644 --- a/packages/server-utils/src/integrations/nitro/captureStorageEvents.ts +++ b/packages/server-utils/src/integrations/nitro/captureStorageEvents.ts @@ -25,8 +25,8 @@ import type { UnstorageTraceContext } from './nitroTypes'; const ORIGIN = 'auto.cache.nitro'; -const globalWithStorageChannels = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - __SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__: boolean; +type GlobalWithStorageChannels = typeof GLOBAL_OBJ & { + __SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__?: boolean; }; const TRACED_OPERATIONS = [ @@ -70,6 +70,7 @@ const CACHED_FN_HANDLERS_RE = /^nitro:(functions|handlers):/i; * Subscribes to unstorage tracing channels and creates Sentry spans for storage operations. */ export function captureStorageEvents(): void { + const globalWithStorageChannels = GLOBAL_OBJ as GlobalWithStorageChannels; if (globalWithStorageChannels.__SENTRY_NITRO_STORAGE_CHANNELS_INSTRUMENTED__) { return; } diff --git a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts index 938590229708..cf6edae6a546 100644 --- a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts +++ b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts @@ -21,17 +21,16 @@ import * as diagnosticsChannel from '../../utils/diagnosticsChannel'; import { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute'; import type { H3TracingRequestEvent, NitroH3Event, SrvxRequestEvent } from './nitroTypes'; -/** - * Global object with the trace channels - */ -const globalWithTraceChannels = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__: boolean; +type GlobalWithTraceChannels = typeof GLOBAL_OBJ & { + __SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__?: boolean; }; /** * Captures tracing events emitted by Nitro tracing channels. */ export function captureTracingEvents(): 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; } diff --git a/packages/server-utils/src/integrations/nitro/setServerTimingHeaders.ts b/packages/server-utils/src/integrations/nitro/setServerTimingHeaders.ts index de8ccb3bbb78..ee8677546c13 100644 --- a/packages/server-utils/src/integrations/nitro/setServerTimingHeaders.ts +++ b/packages/server-utils/src/integrations/nitro/setServerTimingHeaders.ts @@ -2,8 +2,8 @@ import { getTraceData, GLOBAL_OBJ } from '@sentry/core'; import * as diagnosticsChannel from '../../utils/diagnosticsChannel'; import type { H3TracingRequestEvent, NitroH3Event } from './nitroTypes'; -const globalWithServerTiming = GLOBAL_OBJ as typeof GLOBAL_OBJ & { - __SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__: boolean; +type GlobalWithServerTiming = typeof GLOBAL_OBJ & { + __SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__?: boolean; }; /** @@ -15,6 +15,7 @@ const globalWithServerTiming = GLOBAL_OBJ as typeof GLOBAL_OBJ & { * server records spans. */ export function captureServerTimingHeaders(): void { + const globalWithServerTiming = GLOBAL_OBJ as GlobalWithServerTiming; if (globalWithServerTiming.__SENTRY_NITRO_SERVER_TIMING_INSTRUMENTED__) { return; } diff --git a/packages/server-utils/src/utils/runtime.ts b/packages/server-utils/src/utils/runtime.ts index eb01caa69d0d..bad081759d41 100644 --- a/packages/server-utils/src/utils/runtime.ts +++ b/packages/server-utils/src/utils/runtime.ts @@ -1,15 +1,15 @@ import { GLOBAL_OBJ } from '@sentry/core'; -const globalWithRuntimes = GLOBAL_OBJ as typeof GLOBAL_OBJ & { Bun?: unknown; Deno?: unknown }; +type GlobalWithRuntimes = typeof GLOBAL_OBJ & { Bun?: unknown; Deno?: unknown }; /** Whether the SDK runs in Bun. */ export function isBun(): boolean { - return typeof globalWithRuntimes.Bun !== 'undefined'; + return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Bun !== 'undefined'; } /** Whether the SDK runs in Deno. */ export function isDeno(): boolean { - return typeof globalWithRuntimes.Deno !== 'undefined'; + return typeof (GLOBAL_OBJ as GlobalWithRuntimes).Deno !== 'undefined'; } /** Whether the SDK runs in Cloudflare Workers. */ From 2b878f11537aacc2343c2aa976bf1eea46034235 Mon Sep 17 00:00:00 2001 From: Francesco Gringl-Novy Date: Wed, 11 Nov 2026 16:24:53 +0100 Subject: [PATCH 036/136] fix(cloudflare): Have `@flue/runtime` provide its own namespace (#25935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve at runtime. `@sentry/cloudflare/vite` used to splice an `@flue/runtime` import into `@sentry/server-utils`'s Flue integration for that. Every orchestrion-instrumented module imports `@sentry/server-utils`, so that import closes a cycle through any instrumented package Flue loads at module scope. With pi-ai instrumented (the upcoming pi-ai integration, split out of #25869), a worker that reaches pi-ai first runs Flue's module-level `createModels()` before pi-ai's `ModelsImpl` exists. I reproduced it locally with `cloudflare-flue-send-to-sentry`: the worker fails at startup with `Cannot access 'ModelsImpl' before initialization`. Flue's entry is already transformed at build time, so it now publishes its own namespace through a self-import. There are now two ways to hand a package to an integration in a bundled worker. Which one to use depends on whether the app already imports the package: | | Self-provided (`selfProvidedModules`, new) | Provided-module plugin (existing) | |---|---|---| | Used for | `@flue/runtime` | `@mastra/observability` | | Use when | the app imports the package anyway, and it is in Sentry's orchestrion config | the app never imports the package; the integration needs it anyway | | Injected into | the package's own entry: `import * as ns from './index.mjs'` | Sentry's integration module: `import * as ns from '@mastra/observability'` | | Module graph | no new edge, so no cycle possible | adds the edge, which is what pulls the package into the bundle | Mastra can't switch to the self-provided path: apps don't import `@mastra/observability` (Mastra's observability is zero-config), so nothing would load it and it would never publish itself. Its splice has the same cycle shape (`@mastra/observability` imports `@mastra/core`, which is instrumented). That is harmless today because it only imports core subpaths that aren't transformed. If that changes, the splice can move into `@sentry/cloudflare`'s own module, out of `@sentry/server-utils`. `selfProvidedModules` is Cloudflare-only on purpose. On other bundlers, `flueIntegration` would then register Flue itself and clash with apps that call `instrument(Sentry.createFlueInstrumentation())`, as our Node docs say. The webpack loader doesn't pass the option. **How to review:** Start with `selfProvidedSnippet` in `moduleInjectedTransform.ts`; its comment shows the generated output. The rest is wiring, removing Flue's provided-module plugin, and comments. **Unsure about:** Whether the Mastra splice should move out of `@sentry/server-utils` now, before it can hit the same kind of cycle. I'd leave it until something actually triggers it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/cloudflare/src/vite/flueRuntime.ts | 20 ---- packages/cloudflare/src/vite/index.ts | 4 +- .../src/vite/providedModulePlugin.ts | 30 +++--- .../cloudflare/test/vite/flueRuntime.test.ts | 95 +++++++++++++------ .../test/vite/providedModulePlugin.test.ts | 19 ++-- .../server-utils/src/integrations/flue.ts | 9 +- .../bundler/moduleInjectedTransform.ts | 50 ++++++++-- .../src/orchestrion/bundler/options.ts | 11 ++- .../src/orchestrion/config/flue.ts | 2 +- .../moduleInjectedTransform.test.ts | 73 ++++++++++++++ 10 files changed, 220 insertions(+), 93 deletions(-) delete mode 100644 packages/cloudflare/src/vite/flueRuntime.ts diff --git a/packages/cloudflare/src/vite/flueRuntime.ts b/packages/cloudflare/src/vite/flueRuntime.ts deleted file mode 100644 index 004012a5f09f..000000000000 --- a/packages/cloudflare/src/vite/flueRuntime.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { ProvidedModulePlugin } from './providedModulePlugin'; -import { createProvidedModulePlugin } from './providedModulePlugin'; - -/** - * Splices a static `import * as … from '@flue/runtime'` into Sentry's own Flue integration module - * and exposes the namespace on the global orchestrion marker. - * - * Flue is registered rather than patched — `instrument()` writes into module-scope state — so - * instrumenting it needs that module's own binding, and no channel payload carries one. On Node the - * user passes it by calling `instrument()` themselves; a bundled worker has no `node_modules` to - * resolve from, so it is supplied at build time instead. - */ -export function sentryFlueRuntimeProviderPlugin(): ProvidedModulePlugin { - return createProvidedModulePlugin({ - name: 'sentry-cloudflare-flue-runtime-provider', - moduleName: '@flue/runtime', - identifier: '__SENTRY_FLUE_RUNTIME__', - integrationModule: 'flue', - }); -} diff --git a/packages/cloudflare/src/vite/index.ts b/packages/cloudflare/src/vite/index.ts index a0a4b91fecdc..9566f15aa85b 100644 --- a/packages/cloudflare/src/vite/index.ts +++ b/packages/cloudflare/src/vite/index.ts @@ -5,7 +5,6 @@ // expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself. import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument'; -import { sentryFlueRuntimeProviderPlugin } from './flueRuntime'; import { sentryMastraObservabilityProviderPlugin } from './mastraObservability'; /** @@ -91,9 +90,10 @@ export function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOp // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd. dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel', transformOptimizedDeps: true, + // `flueIntegration` needs Flue's own `instrument()`, which a bundled worker can't resolve. + selfProvidedModules: ['@flue/runtime'], }), sentryMastraObservabilityProviderPlugin(), - sentryFlueRuntimeProviderPlugin(), ...(options.autoInstrumentation !== false ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })] : []), diff --git a/packages/cloudflare/src/vite/providedModulePlugin.ts b/packages/cloudflare/src/vite/providedModulePlugin.ts index 1c63bd226741..fcd6b1ba1811 100644 --- a/packages/cloudflare/src/vite/providedModulePlugin.ts +++ b/packages/cloudflare/src/vite/providedModulePlugin.ts @@ -24,13 +24,13 @@ export interface ProvidedModulePlugin { } export interface ProvidedModulePluginOptions { - /** Vite plugin name, e.g. `sentry-cloudflare-flue-runtime-provider`. */ + /** Vite plugin name, e.g. `sentry-cloudflare-mastra-observability-provider`. */ name: string; - /** Bare specifier of the package to provide, e.g. `@flue/runtime`. */ + /** Bare specifier of the package to provide, e.g. `@mastra/observability`. */ moduleName: string; - /** Namespace binding the injected import uses, e.g. `__SENTRY_FLUE_RUNTIME__`. */ + /** Namespace binding the injected import uses, e.g. `__SENTRY_MASTRA_OBSERVABILITY__`. */ identifier: string; - /** Basename of the `@sentry/server-utils` integration module to inject into, e.g. `flue`. */ + /** Basename of the `@sentry/server-utils` integration module to inject into, e.g. `mastra`. */ integrationModule: string; } @@ -55,9 +55,7 @@ export function createIntegrationModuleMatcher(integrationModule: string): (id: function buildProviderSnippet({ moduleName, identifier }: ProvidedModulePluginOptions): string { const marker = 'globalThis.__SENTRY_ORCHESTRION__'; - // A getter, not an assignment: assigning reads the binding at injection time, so it stores - // `undefined` whenever the bundler evaluates Sentry's module before the provided package - // finished initializing. Enumerable so the entry shows up in `Object.keys` and a spread. + // A getter: Sentry's module can evaluate before the provided package has initialized. return ( `import * as ${identifier} from '${moduleName}';\n` + `(${marker} = ${marker} || {});\n` + @@ -68,14 +66,18 @@ function buildProviderSnippet({ moduleName, identifier }: ProvidedModulePluginOp } /** - * Build a Vite plugin that splices a static `import * as … from ''` into one of - * Sentry's own integration modules and exposes the namespace on the global orchestrion marker. + * Build a Vite plugin that hands a package to one of Sentry's integration modules in a bundled + * worker, which has no `node_modules` to resolve it from. For Mastra, this prepends roughly the + * following to `@sentry/server-utils/build/esm/integrations/mastra.js`: * - * Some packages are instrumented by registration rather than by patching, so instrumenting them - * needs a reference to that module's own binding and no channel payload carries one. On Node the - * integration resolves it itself; a bundled worker has no `node_modules` to resolve from, so the - * binding is supplied at build time instead. The import is static, lands in Sentry's module rather - * than the user's code, and is only emitted when the package actually resolves. + * ```js + * import * as __SENTRY_MASTRA_OBSERVABILITY__ from '@mastra/observability'; + * globalThis.__SENTRY_ORCHESTRION__.providedModules['@mastra/observability'] = __SENTRY_MASTRA_OBSERVABILITY__; // as a getter + * ``` + * + * Only for packages the app doesn't import itself: this import is what brings them into the bundle. + * A package the app loads anyway publishes itself instead (`selfProvidedModules`), which adds no + * edge to Sentry's module and so can't close a cycle. */ export function createProvidedModulePlugin(options: ProvidedModulePluginOptions): ProvidedModulePlugin { const isIntegrationModuleId = createIntegrationModuleMatcher(options.integrationModule); diff --git a/packages/cloudflare/test/vite/flueRuntime.test.ts b/packages/cloudflare/test/vite/flueRuntime.test.ts index 5b9d1d36d429..3f164c363ce7 100644 --- a/packages/cloudflare/test/vite/flueRuntime.test.ts +++ b/packages/cloudflare/test/vite/flueRuntime.test.ts @@ -1,41 +1,78 @@ -import { describe, expect, it, vi } from 'vitest'; -import { sentryFlueRuntimeProviderPlugin } from '../../src/vite/flueRuntime'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { sentryCloudflareVitePlugin } from '../../src/vite/index'; -const PROVIDER_PLUGIN = 'sentry-cloudflare-flue-runtime-provider'; -const FLUE_INTEGRATION_MODULE = '/app/node_modules/@sentry/server-utils/build/esm/integrations/flue.js'; +type TransformResult = { code: string } | null | undefined; +type TransformFn = (code: string, id: string, opts?: { ssr?: boolean }) => TransformResult | Promise; +type TestPlugin = { + name: string; + configResolved?: (config: unknown) => void; + buildStart?: (this: unknown) => void | Promise; + transform?: TransformFn | { handler: TransformFn }; +}; -describe('sentryFlueRuntimeProviderPlugin', () => { - it('injects `@flue/runtime` behind a getter', async () => { - // A getter, not an assignment: the bundler may evaluate Sentry's module before - // `@flue/runtime` is initialized, and assigning there would store `undefined`. - const plugin = sentryFlueRuntimeProviderPlugin(); - plugin.configResolved({ root: '/app' }); - const resolve = vi.fn(async () => ({ id: '/app/node_modules/@flue/runtime/dist/index.mjs' })); - await plugin.buildStart.call({ resolve, warn: vi.fn() }); +const FLUE_ENTRY = 'import { r as instrument } from "./instrumentation.mjs";\nexport { instrument };\n'; +const FLUE_IMPORT = /from\s*["']@flue\/runtime["']/; - const code = plugin.transform('export const x = 1;', FLUE_INTEGRATION_MODULE)?.code; +/** Runs every module through `sentryCloudflareVitePlugin()`'s transforms, in order, as an SSR build would. */ +async function createPipeline(root: string): Promise<(code: string, id: string) => Promise> { + const plugins = sentryCloudflareVitePlugin({ autoInstrumentation: false }) as TestPlugin[]; - expect(resolve).toHaveBeenCalledWith('@flue/runtime', '/app/noop.js'); - expect(code).toContain("import * as __SENTRY_FLUE_RUNTIME__ from '@flue/runtime';"); - expect(code).toContain('get() { return __SENTRY_FLUE_RUNTIME__; }'); - }); + for (const plugin of plugins) { + plugin.configResolved?.({ root, command: 'build', plugins, ssr: {} }); + // Every package the app could import resolves, so a plugin that probes for `@flue/runtime` finds it. + await plugin.buildStart?.call({ resolve: vi.fn(async (id: string) => ({ id })), warn: vi.fn() }); + } + + return async (source, id) => { + let code = source; + for (const { transform } of plugins) { + const handler = typeof transform === 'function' ? transform : transform?.handler; + const result = await handler?.call({}, code, id, { ssr: true }); + code = result?.code ?? code; + } + return code; + }; +} - it('injects nothing when the app has no @flue/runtime', async () => { - const plugin = sentryFlueRuntimeProviderPlugin(); - plugin.configResolved({ root: '/app' }); - await plugin.buildStart.call({ resolve: vi.fn(async () => null), warn: vi.fn() }); +describe('sentryCloudflareVitePlugin with @flue/runtime', () => { + let root: string; - expect(plugin.transform('export const x = 1;', FLUE_INTEGRATION_MODULE)).toBeUndefined(); + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'cf-flue-runtime-')); + const pkg = join(root, 'node_modules/@flue/runtime'); + mkdirSync(join(pkg, 'dist'), { recursive: true }); + writeFileSync( + join(pkg, 'package.json'), + JSON.stringify({ name: '@flue/runtime', version: '2.3.0', type: 'module' }), + ); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); }); -}); -describe('sentryCloudflareVitePlugin', () => { - it('always includes the Flue runtime provider plugin', () => { - expect(sentryCloudflareVitePlugin().map(plugin => plugin.name)).toContain(PROVIDER_PLUGIN); - // Not gated by auto-instrumentation: it injects into Sentry's own module, not the entry. - expect(sentryCloudflareVitePlugin({ autoInstrumentation: false }).map(plugin => plugin.name)).toContain( - PROVIDER_PLUGIN, + it("adds no @flue/runtime import to Sentry's Flue integration module", async () => { + // Every instrumented package imports `@sentry/server-utils`. An `@flue/runtime` edge from there + // closes a cycle through them, and Flue's module-level `createModels()` then runs before pi-ai's + // `ModelsImpl` is initialized ("Cannot access 'ModelsImpl' before initialization"). + const transform = await createPipeline(root); + const code = await transform( + 'export const flueIntegration = () => {};\n', + join(root, 'node_modules/@sentry/server-utils/build/esm/integrations/flue.js'), ); + + expect(code).not.toMatch(FLUE_IMPORT); + }); + + it('has the @flue/runtime entry publish its own namespace through a self-import', async () => { + const transform = await createPipeline(root); + const code = await transform(FLUE_ENTRY, join(root, 'node_modules/@flue/runtime/dist/index.mjs')); + + expect(code).toContain('import * as __SENTRY_SELF_PROVIDED__ from "./index.mjs";'); + expect(code).toContain('Object.defineProperty(globalThis.__SENTRY_ORCHESTRION__.providedModules, "@flue/runtime"'); + expect(code).not.toMatch(FLUE_IMPORT); }); }); diff --git a/packages/cloudflare/test/vite/providedModulePlugin.test.ts b/packages/cloudflare/test/vite/providedModulePlugin.test.ts index 5a138cde1a19..a36b07dd79fb 100644 --- a/packages/cloudflare/test/vite/providedModulePlugin.test.ts +++ b/packages/cloudflare/test/vite/providedModulePlugin.test.ts @@ -2,13 +2,13 @@ import { describe, expect, it, vi } from 'vitest'; import type { ProvidedModulePluginOptions } from '../../src/vite/providedModulePlugin'; import { createIntegrationModuleMatcher, createProvidedModulePlugin } from '../../src/vite/providedModulePlugin'; -const TARGET = '/app/node_modules/@sentry/server-utils/build/esm/integrations/flue.js'; +const TARGET = '/app/node_modules/@sentry/server-utils/build/esm/integrations/mastra.js'; const OPTIONS: ProvidedModulePluginOptions = { name: 'sentry-test-provider', moduleName: '@scope/pkg', identifier: '__SENTRY_TEST_PKG__', - integrationModule: 'flue', + integrationModule: 'mastra', }; /** A Rollup plugin context whose `resolve` answers however the test wants. */ @@ -39,37 +39,36 @@ async function start( } describe('createIntegrationModuleMatcher', () => { - const isFlueIntegrationModuleId = createIntegrationModuleMatcher('flue'); + const isMastraIntegrationModuleId = createIntegrationModuleMatcher('mastra'); it('matches the ESM integration module', () => { - expect(isFlueIntegrationModuleId(TARGET)).toBe(true); + expect(isMastraIntegrationModuleId(TARGET)).toBe(true); }); it('ignores a trailing query/hash Vite may append', () => { - expect(isFlueIntegrationModuleId(`${TARGET}?v=abc`)).toBe(true); + expect(isMastraIntegrationModuleId(`${TARGET}?v=abc`)).toBe(true); }); it('normalizes Windows separators', () => { expect( - isFlueIntegrationModuleId('C:\\app\\node_modules\\@sentry\\server-utils\\build\\esm\\integrations\\flue.js'), + isMastraIntegrationModuleId('C:\\app\\node_modules\\@sentry\\server-utils\\build\\esm\\integrations\\mastra.js'), ).toBe(true); }); it('does not match the CJS build (workers load ESM)', () => { - expect(isFlueIntegrationModuleId('/app/node_modules/@sentry/server-utils/build/cjs/integrations/flue.js')).toBe( + expect(isMastraIntegrationModuleId('/app/node_modules/@sentry/server-utils/build/cjs/integrations/mastra.js')).toBe( false, ); }); it('does not match another integration module', () => { - expect(isFlueIntegrationModuleId('/app/node_modules/@sentry/server-utils/build/esm/integrations/mastra.js')).toBe( + expect(isMastraIntegrationModuleId('/app/node_modules/@sentry/server-utils/build/esm/integrations/flue.js')).toBe( false, ); }); it('does not match the instrumented package itself', () => { - expect(isFlueIntegrationModuleId('/app/node_modules/@flue/runtime/dist/index.mjs')).toBe(false); - expect(createIntegrationModuleMatcher('mastra')('/app/node_modules/@mastra/core/dist/index.js')).toBe(false); + expect(isMastraIntegrationModuleId('/app/node_modules/@mastra/core/dist/index.js')).toBe(false); }); }); diff --git a/packages/server-utils/src/integrations/flue.ts b/packages/server-utils/src/integrations/flue.ts index dacf328d72ce..92fe234894a5 100644 --- a/packages/server-utils/src/integrations/flue.ts +++ b/packages/server-utils/src/integrations/flue.ts @@ -21,12 +21,9 @@ let registeredBinding: FlueInstrumentFn | undefined; /** * Register the instrumentation with Flue on the user's behalf, when the runtime binding is available. * - * Flue is registered rather than patched — `instrument()` writes into module-scope state — so this - * needs a reference to that module's own binding. In a bundled worker there is no `node_modules` to - * resolve one from, so `@sentry/cloudflare/vite` splices a static `@flue/runtime` import into this - * module at build time and stashes the namespace on the global marker. Outside that setup the marker - * is empty and this no-ops, leaving the user's own `instrument(Sentry.createFlueInstrumentation())` - * as the way in. + * Flue is registered rather than patched, so this needs `@flue/runtime`'s own `instrument()`. In a + * bundled worker, `@sentry/cloudflare/vite` has the package publish it on the global marker. + * Elsewhere this no-ops and users call `instrument(Sentry.createFlueInstrumentation())` themselves. */ const _flueIntegration = ((options: FlueOptions = {}) => { return { diff --git a/packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts b/packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts index 737d9be98f40..e027d8a209a1 100644 --- a/packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts +++ b/packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts @@ -76,17 +76,41 @@ function moduleInjectedSnippet( ? `import { ${bindings} } from ${JSON.stringify(importSpecifier)};` : `const { ${bindings} } = require(${JSON.stringify(importSpecifier)});`; - // `exportName` is itself an integration factory, invoked inside the arrow (`() => exportName()`), so - // `orchestrionModuleInjected`'s consumer still gets an Integration back from calling the stored - // thunk. The point of the arrow is to defer the read of the `exportName` binding to when that thunk - // runs (at `init()`), instead of reading it by reference the moment this snippet evaluates. A - // provided-module integration (e.g. `flueIntegration`) is imported back into its own instrumented - // package by `@sentry/*/vite`, so a direct reference here would close an import cycle and touch the - // binding in its TDZ ("Cannot access '…' before initialization"); deferring the read breaks that. + // The arrow defers reading `exportName` to `init()`. `@sentry/*/vite` imports some packages into + // their own integration module (e.g. Mastra's), and in that cycle a direct read would hit the TDZ. const args = exportName ? `${JSON.stringify(moduleName)}, () => ${exportName}()` : JSON.stringify(moduleName); return `${importStmt}\n${MODULE_INJECTED_SINK} = orchestrionModuleInjected(${args});`; } +/** + * Publishes the module's own namespace on `providedModules`. For `@flue/runtime`'s `dist/index.mjs`, + * this prepends roughly: + * + * ```js + * import * as __SENTRY_SELF_PROVIDED__ from "./index.mjs"; + * globalThis.__SENTRY_ORCHESTRION__.providedModules["@flue/runtime"] = __SENTRY_SELF_PROVIDED__; // as a getter + * ``` + * + * A self-import adds no edge to the module graph; importing the package into a Sentry module would + * close a cycle through every instrumented dependency, since those all import `@sentry/server-utils`. + */ +function selfProvidedSnippet(moduleName: string, filePath: string): string { + const marker = 'globalThis.__SENTRY_ORCHESTRION__'; + const self = `./${filePath.split('/').pop()}`; + return ( + `import * as __SENTRY_SELF_PROVIDED__ from ${JSON.stringify(self)};\n` + + `(${marker} = ${marker} || {});\n` + + `(${marker}.providedModules = ${marker}.providedModules || {});\n` + + `Object.defineProperty(${marker}.providedModules, ${JSON.stringify(moduleName)}, ` + + '{ configurable: true, enumerable: true, get() { return __SENTRY_SELF_PROVIDED__; } });' + ); +} + +export interface ModuleInjectedTransformsOptions { + /** Packages whose ESM entry publishes its own namespace on `providedModules`. */ + selfProvidedModules?: readonly string[]; +} + /** * The unified `customTransforms` every orchestrion bundler plugin (and the * webpack/Turbopack loader) applies: an override for orchestrion's built-in @@ -112,11 +136,12 @@ export function moduleInjectedTransforms( // absolute-path imports nor bare specifiers that don't resolve from the // importing file's location). importSpecifier?: string | (() => string | undefined), + { selfProvidedModules = [] }: ModuleInjectedTransformsOptions = {}, ): Record { const spliceModuleInjected = (state: unknown, program: unknown): void => { const { moduleType, module } = state as { moduleType?: string; - module?: { name?: string }; + module?: { name?: string; filePath?: string | RegExp }; }; const node = program as ProgramNode; @@ -134,8 +159,13 @@ export function moduleInjectedTransforms( const specifier = (typeof importSpecifier === 'function' ? importSpecifier() : importSpecifier) ?? DEFAULT_IMPORT_SPECIFIER; const exportName = subscriberExportForModule(moduleName); - const statements = parse(moduleInjectedSnippet(moduleName, exportName, moduleType === 'esm', specifier), { - module: moduleType === 'esm', + const esm = moduleType === 'esm'; + const selfProvided = + esm && typeof module?.filePath === 'string' && selfProvidedModules.includes(moduleName) + ? `${selfProvidedSnippet(moduleName, module.filePath)}\n` + : ''; + const statements = parse(selfProvided + moduleInjectedSnippet(moduleName, exportName, esm, specifier), { + module: esm, next: true, }).body as ProgramNode['body']; diff --git a/packages/server-utils/src/orchestrion/bundler/options.ts b/packages/server-utils/src/orchestrion/bundler/options.ts index 0d9aec844d59..cab3e9dd88a4 100644 --- a/packages/server-utils/src/orchestrion/bundler/options.ts +++ b/packages/server-utils/src/orchestrion/bundler/options.ts @@ -43,6 +43,12 @@ export type PluginOptions = { * @default false */ transformOptimizedDeps?: boolean; + /** + * Packages that publish their own namespace on `providedModules`, for integrations that register + * with a package instead of patching it. Opt-in, as apps that register it themselves would clash. + * Only for packages with a single ESM entry file, matched by a string `filePath`. + */ + selfProvidedModules?: string[]; }; /** @@ -89,7 +95,10 @@ export function orchestrionTransformOptions( ): CodeTransformerPluginOptions { return { instrumentations: [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])], - customTransforms: { ...options.customTransforms, ...moduleInjectedTransforms() }, + customTransforms: { + ...options.customTransforms, + ...moduleInjectedTransforms(undefined, { selfProvidedModules: options.selfProvidedModules }), + }, ...(options.dcModule && { dcModule: options.dcModule }), ...(injectDiagnostics && { injectDiagnostics: () => ORCHESTRION_BUNDLER_MARKER_BANNER }), }; diff --git a/packages/server-utils/src/orchestrion/config/flue.ts b/packages/server-utils/src/orchestrion/config/flue.ts index da6841a1ae9b..edf1f6d58cae 100644 --- a/packages/server-utils/src/orchestrion/config/flue.ts +++ b/packages/server-utils/src/orchestrion/config/flue.ts @@ -5,7 +5,7 @@ import { registrationOnly } from './registration-only'; * Flue publishes no diagnostics channels and needs none: it is instrumented by registering with * `instrument()`, not by patching call sites. Transforming the entry is only how the module's * integration gets registered at evaluation time, which is what installs it on a bundler-only SDK - * like `@sentry/cloudflare`. + * like `@sentry/cloudflare`. With `selfProvidedModules`, the entry also publishes its namespace. */ export const flueConfig = [ registrationOnly({ name: '@flue/runtime', versionRange: '>=2.0.0 <3.0.0', filePath: 'dist/index.mjs' }), diff --git a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts index 06fa8e34704d..2e60db9729c0 100644 --- a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts +++ b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts @@ -199,3 +199,76 @@ describe('module-injected transform', () => { expect(result!.code).not.toContain('require("@sentry/server-utils")'); }); }); + +describe('self-provided modules', () => { + let root: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'orch-self-provided-')); + makePackage(root, '@flue/runtime', '2.0.3', 'module', 'dist'); + makePackage(root, 'pg', '8.11.0', 'module'); + makePackage(root, 'ioredis', '5.11.0', 'commonjs', 'built'); + makePackage(root, '@mastra/core', '1.63.2', 'module', 'dist'); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + const FLUE_ENTRY = 'import { r as instrument } from "./instrumentation.mjs";\nexport { instrument };\n'; + + it('publishes the namespace through a self-import, before registering the integration', () => { + const t = createCodeTransformer(orchestrionTransformOptions({ selfProvidedModules: ['@flue/runtime'] })); + const code = t.transform(FLUE_ENTRY, join(root, 'node_modules/@flue/runtime/dist/index.mjs'))!.code; + + expect(code).toContain('import * as __SENTRY_SELF_PROVIDED__ from "./index.mjs";'); + expect(code).toContain('Object.defineProperty(globalThis.__SENTRY_ORCHESTRION__.providedModules, "@flue/runtime"'); + expect(code).toMatch(/get\(\)\s*\{\s*return __SENTRY_SELF_PROVIDED__;\s*\}/); + // Registering can run `setup()` right away, which reads the namespace. + expect(code.indexOf('providedModules, "@flue/runtime"')).toBeLessThan( + code.indexOf('orchestrionModuleInjected("@flue/runtime"'), + ); + }); + + it('publishes nothing for a module that is not listed', () => { + const t = createCodeTransformer(orchestrionTransformOptions({})); + const code = t.transform(FLUE_ENTRY, join(root, 'node_modules/@flue/runtime/dist/index.mjs'))!.code; + + expect(code).toContain('orchestrionModuleInjected("@flue/runtime"'); + expect(code).not.toContain('__SENTRY_SELF_PROVIDED__'); + expect(code).not.toContain('providedModules'); + }); + + it('publishes nothing from a CJS module', () => { + const t = createCodeTransformer(orchestrionTransformOptions({ selfProvidedModules: ['ioredis'] })); + const code = t.transform( + "'use strict';\nclass Redis {}\nmodule.exports = Redis;\n", + join(root, 'node_modules/ioredis/built/Redis.js'), + )!.code; + + expect(code).toContain('orchestrionModuleInjected("ioredis"'); + expect(code).not.toContain('__SENTRY_SELF_PROVIDED__'); + }); + + it('publishes once per file', () => { + const t = createCodeTransformer(orchestrionTransformOptions({ selfProvidedModules: ['pg'] })); + // `pg`'s `lib/client.js` is matched by both the `query` and `connect` configs. + const code = t.transform( + 'export class Client { query(){} connect(){} }\n', + join(root, 'node_modules/pg/lib/client.js'), + )!.code; + + expect(code.match(/import \* as __SENTRY_SELF_PROVIDED__ from "\.\/client\.js";/g)).toHaveLength(1); + }); + + it('publishes nothing from a module matched by a RegExp `filePath`, but still instruments it', () => { + const t = createCodeTransformer(orchestrionTransformOptions({ selfProvidedModules: ['@mastra/core'] })); + const code = t.transform( + 'export class Mastra { constructor() {} }\n', + join(root, 'node_modules/@mastra/core/dist/mastra-abc123.js'), + )!.code; + + expect(code).toContain('orchestrionModuleInjected("@mastra/core"'); + expect(code).not.toContain('__SENTRY_SELF_PROVIDED__'); + }); +}); From 86c59810b0c6a5a69cd589e7b2bb0be1d7fa06ae Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:31:20 +0100 Subject: [PATCH 037/136] feat(aws-serverless): Ignore static asset and preflight invocations by default (#26228) **Why:** When a browser opens a Lambda Function URL, it also fetches `/favicon.ico`. That shows up as a second `function.aws` trace that looks like a duplicate (#25813). `init()` now adds default `ignoreSpans` filters for the invocations `http.server` spans skip by default: GET requests for static assets and metadata files (the same list as `isStaticAssetRequest` in core), and OPTIONS/HEAD requests. Filters users pass in are kept. **How to review:** This is stacked on #26226 because the filters match on the `http.request.method` and `url.path` attributes added there. Retarget to `develop` once that one merges. **Unsure about:** Static asset filtering can be turned off with `ignoreStaticAssets: false`, the same as `http.server`. OPTIONS/HEAD are always skipped. The regex duplicates core's `isStaticAssetRequest` because `ignoreSpans` only takes patterns, not functions. Refs #25813 via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794297679.791099) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794297679.791099/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- packages/aws-serverless/src/init.ts | 39 ++++++++ .../aws-serverless/test/ignoreSpans.test.ts | 90 +++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 packages/aws-serverless/test/ignoreSpans.test.ts diff --git a/packages/aws-serverless/src/init.ts b/packages/aws-serverless/src/init.ts index 8c7c238265fa..5f3c0ad160ef 100644 --- a/packages/aws-serverless/src/init.ts +++ b/packages/aws-serverless/src/init.ts @@ -1,3 +1,5 @@ +import { HTTP_REQUEST_METHOD, URL_PATH } from '@sentry/conventions/attributes'; +import { FUNCTION_AWS } from '@sentry/conventions/op'; import type { Integration, Options } from '@sentry/core'; import { applySdkMetadata, debug, envToBool, getSDKSource } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; @@ -6,6 +8,23 @@ import { awsIntegration } from '@sentry/server-utils'; import { DEBUG_BUILD } from './debug-build'; import { awsLambdaIntegration } from './integration/awslambda'; +// Invocations `http.server` spans skip by default: CORS preflights and HEAD requests always, and GET requests for +// static assets (see `isStaticAssetRequest` in `@sentry/core`) unless `ignoreStaticAssets` is `false`. +const PREFLIGHT_AND_HEAD_INVOCATIONS: NonNullable = [ + { op: FUNCTION_AWS, attributes: { [HTTP_REQUEST_METHOD]: /^(OPTIONS|HEAD)$/ } }, +]; + +const STATIC_ASSET_INVOCATIONS: NonNullable = [ + { + op: FUNCTION_AWS, + attributes: { + [HTTP_REQUEST_METHOD]: /^GET$/, + [URL_PATH]: + /(\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)|^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml))$/, + }, + }, +]; + /** * Checks if proxy environment variables would interfere with the layer extension. * The layer extension uses localhost:9000, so we need to check if proxy settings would prevent this. @@ -60,6 +79,25 @@ export interface AwsServerlessOptions extends NodeOptions { * Can also be configured via the `SENTRY_LAYER_EXTENSION` environment variable. */ useLayerExtension?: boolean; + + /** + * Whether to skip spans for GET invocations of common static assets (favicon.ico, robots.txt, `.js`, images, etc.). + * CORS preflight (`OPTIONS`) and `HEAD` invocations are always skipped. + * + * @default `true` + */ + ignoreStaticAssets?: boolean; +} + +/** + * The `ignoreSpans` the SDK is initialized with: the user's own entries plus the default HTTP invocation filters. + */ +export function getIgnoreSpans(options: AwsServerlessOptions): NonNullable { + return [ + ...(options.ignoreSpans || []), + ...PREFLIGHT_AND_HEAD_INVOCATIONS, + ...(options.ignoreStaticAssets === false ? [] : STATIC_ASSET_INVOCATIONS), + ]; } /** @@ -83,6 +121,7 @@ export function init(options: AwsServerlessOptions = {}): NodeClient | undefined defaultIntegrations: getDefaultIntegrations(options), useLayerExtension, ...options, + ignoreSpans: getIgnoreSpans(options), }; if (opts.useLayerExtension) { diff --git a/packages/aws-serverless/test/ignoreSpans.test.ts b/packages/aws-serverless/test/ignoreSpans.test.ts new file mode 100644 index 000000000000..f4be5cdc4258 --- /dev/null +++ b/packages/aws-serverless/test/ignoreSpans.test.ts @@ -0,0 +1,90 @@ +import { HTTP_REQUEST_METHOD, URL_PATH } from '@sentry/conventions/attributes'; +import { FUNCTION_AWS } from '@sentry/conventions/op'; +import type { Envelope } from '@sentry/core'; +import { createTransport, parseEnvelope, resolvedSyncPromise, shouldIgnoreSpan } from '@sentry/core'; +import type { Context, Handler } from 'aws-lambda'; +import { beforeEach, describe, expect, test } from 'vitest'; +import { getIgnoreSpans, init } from '../src/init'; +import { instrumentHandler } from '../src/instrumentHandler'; + +const envelopes: Envelope[] = []; + +init({ + dsn: 'https://public@example.com/1', + tracesSampleRate: 1, + ignoreSpans: [{ op: FUNCTION_AWS, attributes: { [URL_PATH]: '/health' } }], + transport: () => + createTransport({ recordDroppedEvent: () => undefined }, request => { + envelopes.push(parseEnvelope(request.body)); + return resolvedSyncPromise({}); + }), +}); + +const context = { + awsRequestId: 'awsRequestId', + functionName: 'functionName', + functionVersion: '$LATEST', + invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:functionName', + logGroupName: 'logGroupName', + logStreamName: 'logStreamName', + getRemainingTimeInMillis: () => 3000, +} as Context; + +const handler = instrumentHandler((async () => ({ statusCode: 200 })) as Handler); + +async function invokeAndGetSentPaths(method: string, path: string): Promise { + envelopes.length = 0; + await (handler as any)( + { version: '2.0', routeKey: '$default', rawPath: path, requestContext: { http: { method, path } } }, + context, + () => {}, + ); + + return envelopes.flatMap(([, items]) => + items.flatMap(([header, payload]) => + header.type === 'span' + ? (payload as { items: { attributes?: Record }[] }).items.map( + span => span.attributes?.[URL_PATH]?.value, + ) + : [], + ), + ); +} + +describe('default ignoreSpans', () => { + beforeEach(() => { + envelopes.length = 0; + }); + + test.each(['/favicon.ico', '/robots.txt', '/assets/app.js'])('drops GET %s invocations', async path => { + expect(await invokeAndGetSentPaths('GET', path)).toEqual([]); + }); + + test.each(['OPTIONS', 'HEAD'])('drops %s invocations', async method => { + expect(await invokeAndGetSentPaths(method, '/users')).toEqual([]); + }); + + test('keeps other invocations', async () => { + expect(await invokeAndGetSentPaths('GET', '/')).toEqual(['/']); + expect(await invokeAndGetSentPaths('POST', '/favicon.ico')).toEqual(['/favicon.ico']); + }); + + test('keeps the ignoreSpans the user passed', async () => { + expect(await invokeAndGetSentPaths('GET', '/health')).toEqual([]); + }); +}); + +describe('getIgnoreSpans', () => { + const invocation = (method: string, path: string) => ({ + op: FUNCTION_AWS, + description: 'functionName', + attributes: { [HTTP_REQUEST_METHOD]: method, [URL_PATH]: path }, + }); + + test('keeps static asset invocations when ignoreStaticAssets is false', () => { + const ignoreSpans = getIgnoreSpans({ ignoreStaticAssets: false }); + + expect(shouldIgnoreSpan(invocation('GET', '/favicon.ico'), ignoreSpans)).toBe(false); + expect(shouldIgnoreSpan(invocation('OPTIONS', '/users'), ignoreSpans)).toBe(true); + }); +}); From fc01bd932ca0848857b2d6a914c66ce6391ef9ed Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Wed, 11 Nov 2026 12:27:05 -0500 Subject: [PATCH 038/136] chore: Switch to rolldown (#20775) Refreshed what we had in #18156 with the latest rolldown and let's see if we can get this one out. ### Benchmarks #### Individual SDKs > Clean `build` times on my machine, averaged over 3 runs, develop vs this branch: | Package | rollup 4.60.3 | rolldown 1.2.14 | Speedup | | --- | --- | --- | --- | | `@sentry/browser` (incl. CDN bundles) | 41.60s | 5.79s | 7.2x | | `@sentry/replay-internal` (incl. CDN bundles) | 4.04s | 1.37s | 2.9x | | `@sentry/node` | 1.49s | 0.72s | 2.1x | | `@sentry/core` | 1.28s | 0.69s | 1.9x | | `@sentry/nextjs`* | 1.76s | 1.40s | 1.3x | - NextJS SDK still uses rolldown to rebundle some files as part of the SDK buildtime configuration. This will need a separate PR. #### Full Build > Full monorepo build on my machine (clean, `--skip-nx-cache`), median of 4 runs, develop vs this branch on the same base. | | rollup 4.60.3 | rolldown 1.2.15 | Speedup | | --- | --- | --- | --- | | Full build (transpile + types + bundles) | 63.1s | 20.4s | 3.1x | | Transpile + bundles only | 59.1s | 16.9s | 3.5x | - No CI comparison due to cache state skew, but estimation put it at ~2min faster. --- .../replay/errors/captureMessage/subject.js | 5 + .../replay/errors/captureMessage/test.ts | 2 +- .../captureMessageAttachStacktrace/subject.js | 5 + .../captureMessageAttachStacktrace/test.ts | 2 +- .../nextjs-15/tests/route-handler.test.ts | 11 + .../nextjs-16/tests/worker-bundle.test.ts | 2 +- .../node-integration-tests/package.json | 2 +- .../suites/esbuild/app-init.ts | 14 + .../suites/esbuild/test.ts | 30 + dev-packages/rollup-utils/bundleHelpers.mjs | 65 ++- dev-packages/rollup-utils/index.mjs | 2 +- dev-packages/rollup-utils/npmHelpers.mjs | 68 ++- .../rollup-utils/plugins/bundlePlugins.mjs | 209 +++---- .../rollup-utils/plugins/make-esm-plugin.mjs | 7 +- .../rollup-utils/plugins/npmPlugins.mjs | 254 ++++++--- dev-packages/rollup-utils/utils.mjs | 67 ++- dev-packages/test-utils/package.json | 2 +- package.json | 7 +- packages/astro/package.json | 4 +- packages/aws-serverless/package.json | 6 +- packages/aws-serverless/rollup.npm.config.mjs | 2 +- packages/browser-utils/package.json | 4 +- packages/browser/package.json | 8 +- .../tracing/browserTracingIntegration.test.ts | 4 +- packages/bun/package.json | 4 +- packages/bundler-plugins/package.json | 4 +- .../bundler-plugins/rollup.npm.config.mjs | 12 +- packages/cloudflare/package.json | 4 +- packages/core/package.json | 4 +- packages/core/rollup.npm.config.mjs | 12 +- packages/core/src/index.ts | 4 +- packages/core/src/logs/public-api.ts | 10 +- packages/core/src/metrics/public-api.ts | 7 + packages/deno/package.json | 2 +- packages/deno/rollup.npm.config.mjs | 2 +- packages/effect/package.json | 4 +- packages/effect/src/errorReporter.ts | 6 +- packages/elysia/package.json | 4 +- packages/esbuild-plugin/package.json | 4 +- packages/feedback/package.json | 4 +- packages/feedback/rollup.bundle.config.mjs | 19 +- packages/feedback/rollup.npm.config.mjs | 17 +- packages/gatsby/package.json | 4 +- packages/google-cloud-serverless/package.json | 4 +- .../rollup.npm.config.mjs | 10 +- packages/hono/package.json | 4 +- packages/integration-shims/package.json | 2 +- packages/nestjs/package.json | 4 +- packages/nextjs/rollup.npm.config.mjs | 37 +- packages/nextjs/scripts/buildRollup.ts | 2 +- .../src/config/loaders/wrappingLoader.ts | 4 +- .../templates/routeHandlerWrapperTemplate.ts | 3 - .../templates/sentryInitWrapperTemplate.ts | 8 +- packages/nitro/package.json | 4 +- packages/node-native/package.json | 4 +- packages/node/package.json | 4 +- packages/node/rollup.anr-worker.config.mjs | 6 +- packages/node/rollup.npm.config.mjs | 32 +- packages/node/src/index.ts | 2 +- .../fs/vendored/instrumentation.ts | 10 +- packages/node/src/logs/exports.ts | 10 +- packages/nuxt/package.json | 6 +- packages/nuxt/rollup.module.config.mjs | 21 +- packages/opentelemetry/package.json | 4 +- packages/profiling-node/package.json | 4 +- packages/react-router/package.json | 4 +- packages/react/package.json | 4 +- packages/remix/package.json | 4 +- packages/remix/rollup.npm.config.mjs | 15 +- packages/remix/src/cloudflare/index.ts | 3 +- packages/remix/src/index.server.ts | 3 +- packages/replay-canvas/package.json | 4 +- packages/replay-canvas/src/canvas.ts | 2 +- packages/replay-canvas/test/canvas.test.ts | 4 +- packages/replay-internal/package.json | 4 +- .../replay-internal/rollup.npm.config.mjs | 8 +- packages/replay-worker/package.json | 7 +- .../replay-worker/rollup.examples.config.mjs | 39 +- .../replay-worker/rollup.worker.config.mjs | 68 +-- packages/replay-worker/tsconfig.build.json | 11 + packages/replay-worker/tsconfig.json | 5 +- packages/rollup-plugin/package.json | 4 +- .../server-runtime-injection/package.json | 4 +- .../rollup.npm.config.mjs | 54 +- packages/server-utils/package.json | 4 +- packages/server-utils/rollup.npm.config.mjs | 72 +-- packages/solid/package.json | 4 +- packages/solidstart/package.json | 4 +- packages/svelte/package.json | 4 +- packages/sveltekit/package.json | 4 +- packages/tanstackstart-react/package.json | 2 +- packages/vercel-edge/package.json | 4 +- packages/vercel-edge/rollup.npm.config.mjs | 16 +- packages/vite-plugin/package.json | 4 +- packages/vue/package.json | 4 +- packages/wasm/package.json | 8 +- packages/webpack-plugin/package.json | 4 +- pnpm-lock.yaml | 530 +++++++++++------- pnpm-workspace.yaml | 17 + 99 files changed, 1209 insertions(+), 813 deletions(-) create mode 100644 dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js create mode 100644 dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js create mode 100644 dev-packages/node-integration-tests/suites/esbuild/app-init.ts create mode 100644 packages/replay-worker/tsconfig.build.json diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js new file mode 100644 index 000000000000..acf8b119a5e8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/subject.js @@ -0,0 +1,5 @@ +// Called from a served script so the synthetic stacktrace keeps a frame with a URL. Frames from +// `page.evaluate` have none, and the SDK's own `captureMessage` frames are stripped. +window.captureTestMessage = () => { + window.Sentry.captureMessage('Some message'); +}; diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts index 90b867c117e3..fd63b05b4207 100644 --- a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessage/test.ts @@ -16,7 +16,7 @@ sentryTest( await waitForReplayRunning(page); const errorRequestPromise = waitForErrorRequest(page); - await page.evaluate(() => (window as any).Sentry.captureMessage('Some message')); + await page.evaluate(() => (window as any).captureTestMessage()); const event = envelopeRequestParser(await errorRequestPromise); await forceFlushReplay(); diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js new file mode 100644 index 000000000000..acf8b119a5e8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/subject.js @@ -0,0 +1,5 @@ +// Called from a served script so the synthetic stacktrace keeps a frame with a URL. Frames from +// `page.evaluate` have none, and the SDK's own `captureMessage` frames are stripped. +window.captureTestMessage = () => { + window.Sentry.captureMessage('Some message'); +}; diff --git a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts index d89371695436..c047f0fcaa7d 100644 --- a/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts +++ b/dev-packages/browser-integration-tests/suites/replay/errors/captureMessageAttachStacktrace/test.ts @@ -22,7 +22,7 @@ sentryTest( const errorRequestPromise = waitForErrorRequest(page); const replayRequestPromise = waitForReplayRequest(page, 0); - await page.evaluate(() => (window as any).Sentry.captureMessage('Some message')); + await page.evaluate(() => (window as any).captureTestMessage()); const event = envelopeRequestParser(await errorRequestPromise); await replayRequestPromise; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/route-handler.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/route-handler.test.ts index a033f1aa0eb5..a8bf7e9a146b 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/route-handler.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/route-handler.test.ts @@ -1,4 +1,5 @@ import test, { expect } from '@playwright/test'; +import fs from 'fs'; import { getSpanOp, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; test('Should create a span for node route handlers', async ({ request }) => { @@ -94,3 +95,13 @@ test('Should record exceptions and spans for faulty route handlers', async ({ re expect(routehandlerError.transaction).toContain('/route-handler/[xoxo]/error'); }); + +test('Should not give route handlers without a default export a default export', async ({ request }) => { + test.skip(process.env.TEST_ENV !== 'development', 'Next.js only checks for a default export in webpack dev mode'); + + const response = await request.get('/route-handler/static'); + expect(await response.json()).toStrictEqual({ name: 'Static' }); + + const devStdout = fs.readFileSync('.tmp_dev_server_logs', 'utf-8'); + expect(devStdout).not.toContain('Detected default export'); +}); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts index af16d1add37d..cb2039d442f4 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts @@ -56,7 +56,7 @@ function readOrchestrionPluginGraphSources(): string[] { const entrySource = fs.readFileSync(pluginEntry, 'utf8'); return [ entrySource, - ...[...entrySource.matchAll(/require\('(\.\.?\/[^']+)'\)/g)].map(([, specifier]) => + ...[...entrySource.matchAll(/require\(['"](\.\.?\/[^'"]+)['"]\)/g)].map(([, specifier]) => fs.readFileSync(path.resolve(path.dirname(pluginEntry), specifier), 'utf8'), ), ]; diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json index 4ccf59c17597..ed97e01a4bb1 100644 --- a/dev-packages/node-integration-tests/package.json +++ b/dev-packages/node-integration-tests/package.json @@ -12,7 +12,7 @@ "scripts": { "build": "pnpm run build:transpile && pnpm run build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "clean": "node scripts/clean.js", "lint": "oxlint . --type-aware", diff --git a/dev-packages/node-integration-tests/suites/esbuild/app-init.ts b/dev-packages/node-integration-tests/suites/esbuild/app-init.ts new file mode 100644 index 000000000000..5d84dc8e10e7 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/esbuild/app-init.ts @@ -0,0 +1,14 @@ +import * as Sentry from '@sentry/node'; + +// `Sentry.init()` synchronously calls `registerDiagnosticsChannelInjection()`, which reaches the +// vendored orchestrion transformer. That chain is split so a bundler can tree-shake it (see +// `makeCjsExportsSplitPlugin` in server-utils' rollup config); this asserts the split degrades to +// "no channel injection" rather than throwing when the bundler drops it. +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 0, + autoSessionTracking: false, +}); + +// eslint-disable-next-line no-console +console.log(`SENTRY_NODE_INITIALIZED client=${Boolean(Sentry.getClient())}`); diff --git a/dev-packages/node-integration-tests/suites/esbuild/test.ts b/dev-packages/node-integration-tests/suites/esbuild/test.ts index 1d1806f0b843..ea0c09a8aeba 100644 --- a/dev-packages/node-integration-tests/suites/esbuild/test.ts +++ b/dev-packages/node-integration-tests/suites/esbuild/test.ts @@ -32,4 +32,34 @@ describe('esbuild bundling', () => { rmSync(outDir, { recursive: true, force: true }); } }); + + test('@sentry/node survives init() when bundled to ESM with tree-shaking', async () => { + const outDir = mkdtempSync(join(tmpdir(), 'sentry-esbuild-esm-')); + const outfile = join(outDir, 'bundle.mjs'); + + try { + await build({ + entryPoints: [join(__dirname, 'app-init.ts')], + outfile, + platform: 'node', + format: 'esm', + bundle: true, + // `@sentry/server-utils` is `sideEffects: false`, so this is where a bundler is free to + // drop the vendored orchestrion transformer. + treeShaking: true, + logLevel: 'silent', + }); + + const result = spawnSync('node', [outfile], { encoding: 'utf-8' }); + + // Dropping the transformer must not take `init()` with it: reading a tree-shaken CJS + // container has to yield `undefined`, not throw on destructuring or on a call. + expect(result.stderr).not.toContain('Cannot destructure'); + expect(result.stderr).not.toContain('is not a function'); + expect(result.status).toBe(0); + expect(result.stdout).toContain('SENTRY_NODE_INITIALIZED client=true'); + } finally { + rmSync(outDir, { recursive: true, force: true }); + } + }); }); diff --git a/dev-packages/rollup-utils/bundleHelpers.mjs b/dev-packages/rollup-utils/bundleHelpers.mjs index 6ac5f6aff06d..04a6a8a68f77 100644 --- a/dev-packages/rollup-utils/bundleHelpers.mjs +++ b/dev-packages/rollup-utils/bundleHelpers.mjs @@ -1,48 +1,42 @@ /** - * Rollup config docs: https://rollupjs.org/guide/en/#big-list-of-options + * Rolldown config docs: https://rolldown.rs/reference/config-options */ -import { builtinModules } from 'module'; +import * as fs from 'fs'; +import * as path from 'path'; import deepMerge from 'deepmerge'; import { + makeBannerOptions, makeBrowserBuildPlugin, - makeCommonJSPlugin, - makeEsbuildPlugin, makeIsDebugBuildPlugin, - makeLicensePlugin, - makeNodeResolvePlugin, + makeMinifierOptions, makeRrwebBuildPlugin, makeSetSDKSourcePlugin, - makeTerserPlugin, } from './plugins/index.mjs'; -import { mergePlugins } from './utils.mjs'; +import { getNodeBuiltIns, mergePlugins, treeShakePreset } from './utils.mjs'; import { makeProductionReplacePlugin } from './plugins/npmPlugins.mjs'; const BUNDLE_VARIANTS = ['.js', '.min.js', '.debug.min.js']; +const packageDotJSON = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), './package.json'), { encoding: 'utf8' })); + export function makeBaseBundleConfig(options) { - const { bundleType, entrypoints, licenseTitle, outputFileBase, packageSpecificConfig, esbuild } = options; + const { bundleType, entrypoints, licenseTitle, outputFileBase, packageSpecificConfig } = options; - const nodeResolvePlugin = makeNodeResolvePlugin(); - const transpilePlugin = makeEsbuildPlugin(esbuild); const markAsBrowserBuildPlugin = makeBrowserBuildPlugin(true); - const licensePlugin = makeLicensePlugin(licenseTitle); + const banner = makeBannerOptions(licenseTitle, packageDotJSON.version); const rrwebBuildPlugin = makeRrwebBuildPlugin({ excludeIframe: false, excludeShadowDom: false, }); const productionReplacePlugin = makeProductionReplacePlugin(); - // The `commonjs` plugin is the `esModuleInterop` of the bundling world. When used with `transformMixedEsModules`, it - // will include all dependencies, imported or required, in the final bundle. (Without it, CJS modules aren't included - // at all, and without `transformMixedEsModules`, they're only included if they're imported, not if they're required.) - const commonJSPlugin = makeCommonJSPlugin({ transformMixedEsModules: true }); - // used by `@sentry/browser` const standAloneBundleConfig = { output: { + banner, format: 'iife', name: 'Sentry', intro: () => { @@ -50,7 +44,7 @@ export function makeBaseBundleConfig(options) { }, }, context: 'window', - plugins: [rrwebBuildPlugin, markAsBrowserBuildPlugin, licensePlugin], + plugins: [rrwebBuildPlugin, markAsBrowserBuildPlugin], }; // used by `@sentry/wasm` & pluggable integrations from core/browser (bundles which need to be combined with a stand-alone SDK bundle) @@ -61,7 +55,7 @@ export function makeBaseBundleConfig(options) { format: 'cjs', // code to add before the CJS wrapper - banner: '(function (__window) {', + banner: `${banner}\n(function (__window) {`, // code to add just inside the CJS wrapper, before any of the wrapped code intro: 'var exports = {};', @@ -84,30 +78,41 @@ export function makeBaseBundleConfig(options) { // code to add after the CJS wrapper footer: '}(window));', }, - plugins: [rrwebBuildPlugin, markAsBrowserBuildPlugin, licensePlugin], + plugins: [rrwebBuildPlugin, markAsBrowserBuildPlugin], }; const workerBundleConfig = { output: { + banner, format: 'esm', + minify: makeMinifierOptions(), }, - plugins: [commonJSPlugin, makeTerserPlugin(), licensePlugin], // Don't bundle any of Node's core modules - external: builtinModules, + external: getNodeBuiltIns(), }; const awsLambdaExtensionBundleConfig = { output: { format: 'esm', + minify: makeMinifierOptions(), }, - plugins: [commonJSPlugin, makeIsDebugBuildPlugin(true), makeTerserPlugin()], + plugins: [makeIsDebugBuildPlugin(true)], // Don't bundle any of Node's core modules - external: builtinModules, + external: getNodeBuiltIns(), }; // used by all bundles const sharedBundleConfig = { input: entrypoints, + + // Point at the package's tsconfig so rolldown picks up its TypeScript & JSX settings. + tsconfig: path.resolve(process.cwd(), './tsconfig.json'), + + // ES2020 is our floor: keeps `?.`/`??` native and downlevels everything newer. + transform: { + target: 'es2020', + }, + output: { // a file extension will be added to this base value when we specify either a minified or non-minified build entryFileNames: outputFileBase, @@ -116,8 +121,8 @@ export function makeBaseBundleConfig(options) { strict: false, esModule: false, }, - plugins: [productionReplacePlugin, transpilePlugin, nodeResolvePlugin], - treeshake: 'smallest', + plugins: [productionReplacePlugin], + treeshake: treeShakePreset('smallest'), }; const bundleTypeConfigMap = { @@ -147,7 +152,7 @@ export function makeBundleConfigVariants(baseConfig, options = {}) { const includeDebuggingPlugin = makeIsDebugBuildPlugin(true); const stripDebuggingPlugin = makeIsDebugBuildPlugin(false); - const terserPlugin = makeTerserPlugin(); + const minify = makeMinifierOptions(); const setSdkSourcePlugin = makeSetSDKSourcePlugin('cdn'); // The additional options to use for each variant we're going to create. @@ -162,15 +167,17 @@ export function makeBundleConfigVariants(baseConfig, options = {}) { '.min.js': { output: { entryFileNames: chunkInfo => `${baseConfig.output.entryFileNames(chunkInfo)}.min.js`, + minify, }, - plugins: [stripDebuggingPlugin, setSdkSourcePlugin, terserPlugin], + plugins: [stripDebuggingPlugin, setSdkSourcePlugin], }, '.debug.min.js': { output: { entryFileNames: chunkInfo => `${baseConfig.output.entryFileNames(chunkInfo)}.debug.min.js`, + minify, }, - plugins: [includeDebuggingPlugin, setSdkSourcePlugin, terserPlugin], + plugins: [includeDebuggingPlugin, setSdkSourcePlugin], }, }; diff --git a/dev-packages/rollup-utils/index.mjs b/dev-packages/rollup-utils/index.mjs index 2d8c9a2150bc..26ae2c0a1f96 100644 --- a/dev-packages/rollup-utils/index.mjs +++ b/dev-packages/rollup-utils/index.mjs @@ -4,4 +4,4 @@ export { plugins }; export * from './bundleHelpers.mjs'; export * from './npmHelpers.mjs'; -export { insertAt } from './utils.mjs'; +export { insertAt, treeShakePreset } from './utils.mjs'; diff --git a/dev-packages/rollup-utils/npmHelpers.mjs b/dev-packages/rollup-utils/npmHelpers.mjs index a6ded756d615..5eed20ae5aae 100644 --- a/dev-packages/rollup-utils/npmHelpers.mjs +++ b/dev-packages/rollup-utils/npmHelpers.mjs @@ -1,27 +1,25 @@ // @ts-check /** - * Rollup config docs: https://rollupjs.org/guide/en/#big-list-of-options + * Rolldown config docs: https://rolldown.rs/reference/config-options */ import * as fs from 'fs'; -import { builtinModules, isBuiltin } from 'module'; +import { isBuiltin } from 'module'; import * as path from 'path'; import { fileURLToPath } from 'url'; import deepMerge from 'deepmerge'; -import { defineConfig } from 'rollup'; +import { defineConfig } from 'rolldown'; import { makeDebugBuildStatementReplacePlugin, - makeEsbuildPlugin, makeEsmCjsReplacePlugin, - makeNodeResolvePlugin, makeProductionReplacePlugin, makeRrwebBuildPlugin, } from './plugins/index.mjs'; import { makePackageNodeEsm } from './plugins/make-esm-plugin.mjs'; -import { mergeExternals, mergePlugins } from './utils.mjs'; +import { getNodeBuiltIns, mergeExternals, mergePlugins } from './utils.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -97,12 +95,9 @@ export function makeBaseNPMConfig(options = {}) { entrypoints = ['src/index.ts'], hasBundles = false, packageSpecificConfig = {}, - esbuild = {}, bundledBuiltins = [], } = options; - const nodeResolvePlugin = makeNodeResolvePlugin(); - const transpilePlugin = makeEsbuildPlugin(esbuild); const debugBuildStatementReplacePlugin = makeDebugBuildStatementReplacePlugin(); const rrwebBuildPlugin = makeRrwebBuildPlugin({ excludeShadowDom: undefined, @@ -110,7 +105,7 @@ export function makeBaseNPMConfig(options = {}) { }); const deps = [ - ...builtinModules.filter(m => !bundledBuiltins.includes(m)), + ...getNodeBuiltIns(bundledBuiltins), ...Object.keys(packageDotJSON.dependencies || {}), ...Object.keys(packageDotJSON.peerDependencies || {}), ...Object.keys(packageDotJSON.optionalDependencies || {}), @@ -119,6 +114,31 @@ export function makeBaseNPMConfig(options = {}) { const defaultBaseConfig = { input: entrypoints, + // Point at the package's tsconfig so rolldown picks up its TypeScript & JSX settings. + tsconfig: path.resolve(process.cwd(), './tsconfig.json'), + + // NOTE: we deliberately leave `platform` unset so rolldown infers it from the output format + // ('node' for cjs, 'browser' for everything else). Every explicit value breaks something: + // 'node' injects `import "node:module"` into each runtime chunk, which webpack rejects for + // browser targets; 'neutral' rewrites `import.meta` to `{}`, so `createRequire(import.meta.url)` + // gets `undefined`. Node-only packages that need the node platform for both halves set it + // themselves (see server-utils and bundler-plugins). + + // ES2020 is our floor: keeps `?.`/`??` native and downlevels everything newer. Packages that + // need more (e.g. top-level await) raise it through `packageSpecificConfig`. + transform: { + target: 'es2020', + + // The inferred 'browser' platform defines `process.env.NODE_ENV`, which folds every + // `process.env.NODE_ENV !== 'development'` guard to a constant and lets DCE delete the + // branch behind it. That silently dropped the orchestrion and source-map plugins from the + // vite integrations' ESM output while the CJS half kept them. Mapping it to itself keeps + // the runtime lookup, so the guard is evaluated by the consumer as it always was. + define: { + 'process.env.NODE_ENV': 'process.env.NODE_ENV', + }, + }, + output: { // an appropriately-named directory will be added to this base value when we specify either a cjs or esm build dir: hasBundles ? 'build/npm' : 'build', @@ -130,6 +150,7 @@ export function makeBaseNPMConfig(options = {}) { // output individual files rather than one big bundle preserveModules: true, + preserveModulesRoot: 'src', // Don't hoist imports into entrypoints // should be ignored when `preserveModules` is used, @@ -139,8 +160,6 @@ export function makeBaseNPMConfig(options = {}) { // Allow wrappers or helper functions generated by rollup to use any ES2015 features generatedCode: { preset: 'es2015', - // With arrow functions, Node can't see `export *` exports when ESM code imports our CJS files. - arrowFunctions: false, }, // don't add `"use strict"` to the top of cjs files @@ -154,19 +173,17 @@ export function makeBaseNPMConfig(options = {}) { // get: () => are.great, // }); externalLiveBindings: false, - - // Don't call `Object.freeze` on the results of `import * as someModule from '...'` - // (We don't need it, so why waste the bytes?) - freeze: false, - - // Assume externals are ESM-shaped (`__esModule` + `.default`), which our own `@sentry/*` - // packages satisfy via `esModule: 'if-default-prop'`. This keeps `import * as x` a live - // reference to the real module rather than an `_interopNamespace` copy — instrumentation code - // relies on that to monkey-patch modules like `fs` in place. Packages that pull in bare-CJS - // third-party deps (no `.default`) override this per-module (see server-utils). - interop: 'esModule', }, + // NOTE: rolldown has no equivalent of rollup's `output.interop`. In the CJS build it wraps + // namespace imports of externals as `x = __toESM(require('x'))`, and `__toESM` returns a copy + // whose properties are getter-only forwarders. Reads pass through to the real module but writes + // do not, so code that monkey-patches a module in place has to default-import it (`import x + // from 'x'`, whose `.default` is the live `require()` result) rather than namespace-import it. + // Rolldown errors on a statically visible `ns.foo = ...` (ASSIGN_TO_IMPORT), but it cannot see a + // write made through a helper, and that one fails silently. See + // `packages/node/src/integrations/fs/vendored/instrumentation.ts`. + treeshake: { moduleSideEffects: (id, external) => { if (external === false && ignoreSideEffects.test(id)) { @@ -186,7 +203,7 @@ export function makeBaseNPMConfig(options = {}) { }, }, - plugins: [nodeResolvePlugin, transpilePlugin, debugBuildStatementReplacePlugin, rrwebBuildPlugin], + plugins: [debugBuildStatementReplacePlugin, rrwebBuildPlugin], // don't include imported modules from outside the package in the final output // also treat subpath exports (e.g. `@sentry/core/browser`) as external @@ -248,8 +265,7 @@ export function makeNPMConfigVariants(baseConfig, options = {}) { } return variantSpecificConfigs.map(variant => - // Plugin arrays must be merged in the right order or the build silently misbehaves - // (e.g. esbuild strips dev-mode marker comments before the replace plugin can act). + // Plugin arrays must be merged in the right order or the build silently misbehaves. deepMerge(baseConfig, variant, { customMerge: key => (key === 'plugins' ? mergePlugins : undefined), }), diff --git a/dev-packages/rollup-utils/plugins/bundlePlugins.mjs b/dev-packages/rollup-utils/plugins/bundlePlugins.mjs index 23aab90f4edf..d80dbf515cea 100644 --- a/dev-packages/rollup-utils/plugins/bundlePlugins.mjs +++ b/dev-packages/rollup-utils/plugins/bundlePlugins.mjs @@ -1,173 +1,146 @@ /** - * CommonJS plugin docs: https://github.com/rollup/plugins/tree/master/packages/commonjs - * License plugin docs: https://github.com/mjeanroy/rollup-plugin-license - * Replace plugin docs: https://github.com/rollup/plugins/tree/master/packages/replace - * Resolve plugin docs: https://github.com/rollup/plugins/tree/master/packages/node-resolve - * Terser plugin docs: https://github.com/TrySound/rollup-plugin-terser#options - * Terser docs: https://github.com/terser/terser#api-reference - * Typescript plugin docs: https://github.com/rollup/plugins/tree/master/packages/typescript/#readme + * Replace plugin docs: https://rolldown.rs/builtin-plugins/replace#replace-plugin + * Minifier options docs: https://rolldown.rs/options/output-options#output-minify */ import * as childProcess from 'child_process'; - -import commonjs from '@rollup/plugin-commonjs'; -import { nodeResolve } from '@rollup/plugin-node-resolve'; -import replace from '@rollup/plugin-replace'; -import terser from '@rollup/plugin-terser'; -import license from 'rollup-plugin-license'; +import { replacePlugin } from 'rolldown/plugins'; /** - * Create a plugin to add an identification banner to the top of stand-alone bundles. + * Build the identification banner that goes at the top of stand-alone bundles. + * + * Rolldown emits banners itself (`output.banner`), so unlike `rollup-plugin-license` this returns + * the banner text rather than a plugin, and ordering against the minifier is no longer our problem. * * @param title The title to use for the SDK, if not the package name - * @returns An instance of the `rollup-plugin-license` plugin + * @param version The version of the SDK */ -export function makeLicensePlugin(title) { +export function makeBannerOptions(title, version) { const commitHash = childProcess.execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).trim(); - const plugin = license({ - banner: { - content: `/*! <%= data.title %> <%= pkg.version %> (${commitHash}) | https://github.com/getsentry/sentry-javascript */`, - data: { title }, - }, - }); - - // give it a nicer name for later, when we'll need to sort the plugins - plugin.name = 'license'; - - return plugin; + return `/*! ${title} ${version} (${commitHash}) | https://github.com/getsentry/sentry-javascript */`; } /** * Create a plugin to set the value of the `__SENTRY_DEBUG__` magic string. * * @param includeDebugging Whether or not the resulting build should include log statements - * @returns An instance of the `@rollup/plugin-replace` plugin to do the replacement of the magic string with `true` or - * 'false` + * @returns A `rolldown` replace plugin instance to do the replacement of the magic string with `true` or `false` */ export function makeIsDebugBuildPlugin(includeDebugging) { - const plugin = replace({ - // TODO `preventAssignment` will default to true in version 5.x of the replace plugin, at which point we can get rid - // of this. (It actually makes no difference in this case whether it's true or false, since we never assign to - // `__SENTRY_DEBUG__`, but if we don't give it a value, it will spam with warnings.) - preventAssignment: true, - values: { + return replacePlugin( + { // Flags in current package - __DEBUG_BUILD__: includeDebugging, + __DEBUG_BUILD__: JSON.stringify(includeDebugging), // Flags in built monorepo dependencies, from which the bundle pulls - __SENTRY_DEBUG__: includeDebugging, + __SENTRY_DEBUG__: JSON.stringify(includeDebugging), + }, + { + // It makes no difference in this case whether it's true or false, since we never assign to + // `__SENTRY_DEBUG__`, but if we don't give it a value, it will spam with warnings. + preventAssignment: true, }, - }); - plugin.name = 'replace-debug-flags'; - return plugin; + ); } /** * Replaces the comment marker `/*! __SENTRY_SDK_SOURCE__ *\/` in core's `getSDKSource()` with a * `return '';` statement so the bundle reports the correct distribution channel. * - * The marker uses the `/*! ... *\/` legal-comment syntax so it survives esbuild's transpile - * (esbuild strips ordinary block comments). The plugin sort order in utils.mjs also pins - * this name before `esbuild`, in case it ever runs on un-transpiled source directly. + * The marker uses the `/*! ... *\/` legal-comment syntax so it survives rolldown's transpile + * (ordinary block comments are stripped). */ export function makeSetSDKSourcePlugin(sdkSource) { - const plugin = replace({ - preventAssignment: false, - delimiters: ['', ''], - values: { + return replacePlugin( + { '/*! __SENTRY_SDK_SOURCE__ */': `return ${JSON.stringify(sdkSource)};`, }, - }); - plugin.name = 'replace-sdk-source'; - return plugin; + { + preventAssignment: false, + delimiters: ['', ''], + }, + ); } /** * Create a plugin to set the value of the `__SENTRY_BROWSER_BUNDLE__` magic string. * * @param isBrowserBuild Whether or not the resulting build will be run in the browser - * @returns An instance of the `replace` plugin to do the replacement of the magic string with `true` or 'false` + * @returns A `rolldown` replace plugin instance to do the replacement of the magic string with `true` or `false` */ export function makeBrowserBuildPlugin(isBrowserBuild) { - const plugin = replace({ - // TODO This will be the default in the next version of the `replace` plugin - preventAssignment: true, - values: { - __SENTRY_BROWSER_BUNDLE__: isBrowserBuild, + return replacePlugin( + { + __SENTRY_BROWSER_BUNDLE__: JSON.stringify(!!isBrowserBuild), + // Bundled dependencies (e.g. Preact in the feedback bundles) branch on this, and there is no + // CommonJS plugin left to fold it away for us. + 'process.env.NODE_ENV': JSON.stringify('production'), }, - }); - plugin.name = 'replace-browser-bundle-flag'; - return plugin; + { + preventAssignment: true, + }, + ); } -// `terser` options reference: https://github.com/terser/terser#api-reference -// `rollup-plugin-terser` options reference: https://github.com/TrySound/rollup-plugin-terser#options - /** - * Create a plugin to perform minification using `terser`. + * Minifier settings for the bundle builds. * - * @returns An instance of the `terser` plugin + * Ported from the terser config the rollup build used. Terser's `mangle.reserved` maps onto + * rolldown's `mangle.reserved`, and `mangle.properties.regex`/`.reserved` onto the top-level + * `mangleProps.include`/`.reserved` (property mangling landed in rolldown 1.2.6). Note it is + * `minify.mangleProps`, not `minify.mangle.properties`: the latter is the oxc-level interface the + * reference docs describe, and rolldown silently ignores it. + * + * @returns {import('rolldown').OutputOptions['minify']} */ -export function makeTerserPlugin() { - return terser({ +export function makeMinifierOptions() { + return { mangle: { // `captureException` and `captureMessage` are public API methods and they don't need to be listed here, as the // mangler won't touch user-facing things, but `sentryWrapped` is not user-facing, and would be mangled during // minification. (We need it in its original form to correctly detect our internal frames for stripping.) All three // are all listed here just for the clarity's sake, as they are all used in the frames manipulation process. reserved: ['captureException', 'captureMessage', 'sentryWrapped'], - properties: { - // allow mangling of private field names... - regex: /^_[^_]/, - reserved: [ - // ...except for `_experiments`, which we want to remain usable from the outside - '_experiments', - // We want to keep some replay fields unmangled to enable integration tests to access them - '_replay', - '_canvas', - // We also can't mangle rrweb private fields when bundling rrweb in the replay CDN bundles - '_cssText', - // We want to keep the _integrations variable unmangled to send all installed integrations from replay - '_integrations', - // _meta is used to store metadata of replay network events - '_meta', - // We store SDK metadata in the options - '_metadata', - // Object we inject debug IDs into with bundler plugins - '_sentryDebugIds', - // These are used by instrument.ts in utils for identifying HTML elements & events - '_sentryCaptured', - '_sentryId', - // Keeps the frozen DSC on a Sentry Span - '_frozenDsc', - // These are used to keep span & scope relationships - '_sentryRootSpan', - '_sentryChildSpans', - '_sentrySpan', - '_sentryScope', - '_sentryIsolationScope', - // require-in-the-middle calls `Module._resolveFilename`. We cannot mangle this (AWS lambda layer bundle). - '_resolveFilename', - // Set on e.g. the shim feedbackIntegration to be able to detect it - '_isShim', - // Marker used to detect `beforeSendSpan` callbacks expecting the static span format - '_static', - // This is used in metadata integration - '_sentryModuleMetadata', - ], - }, }, - format: { - comments: false, + mangleProps: { + // allow mangling of private field names... + include: /^_[^_]/, + reserved: [ + // ...except for `_experiments`, which we want to remain usable from the outside + '_experiments', + // We want to keep some replay fields unmangled to enable integration tests to access them + '_replay', + '_canvas', + // We also can't mangle rrweb private fields when bundling rrweb in the replay CDN bundles + '_cssText', + // We want to keep the _integrations variable unmangled to send all installed integrations from replay + '_integrations', + // _meta is used to store metadata of replay network events + '_meta', + // We store SDK metadata in the options + '_metadata', + // Object we inject debug IDs into with bundler plugins + '_sentryDebugIds', + // These are used by instrument.ts in utils for identifying HTML elements & events + '_sentryCaptured', + '_sentryId', + // Keeps the frozen DSC on a Sentry Span + '_frozenDsc', + // These are used to keep span & scope relationships + '_sentryRootSpan', + '_sentryChildSpans', + '_sentrySpan', + '_sentryScope', + '_sentryIsolationScope', + // require-in-the-middle calls `Module._resolveFilename`. We cannot mangle this (AWS lambda layer bundle). + '_resolveFilename', + // Set on e.g. the shim feedbackIntegration to be able to detect it + '_isShim', + // Marker used to detect `beforeSendSpan` callbacks expecting the static span format + '_static', + // This is used in metadata integration + '_sentryModuleMetadata', + ], }, - }); + }; } - -// We don't pass these plugins any options which need to be calculated or changed by us, so no need to wrap them in -// another factory function, as they are themselves already factory functions. - -export function makeNodeResolvePlugin() { - return nodeResolve(); -} - -export { commonjs as makeCommonJSPlugin }; diff --git a/dev-packages/rollup-utils/plugins/make-esm-plugin.mjs b/dev-packages/rollup-utils/plugins/make-esm-plugin.mjs index ad18856c011a..908afc7cb157 100644 --- a/dev-packages/rollup-utils/plugins/make-esm-plugin.mjs +++ b/dev-packages/rollup-utils/plugins/make-esm-plugin.mjs @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import path from 'node:path'; /** * Outputs a package.json file with {type: module} in the root of the output directory so that Node @@ -11,9 +12,9 @@ export function makePackageNodeEsm() { // We need to keep the `sideEffects` value from the original package.json, // as e.g. webpack seems to depend on this // without this, tree shaking does not work as expected - const packageJSONPath = (await this.resolve('package.json')).id; - - const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, 'utf-8')); + const packageJSON = JSON.parse( + fs.readFileSync(path.resolve(process.cwd(), './package.json'), { encoding: 'utf8' }), + ); const sideEffects = packageJSON.sideEffects; // For module federation we need to keep the version of the package const version = packageJSON.version; diff --git a/dev-packages/rollup-utils/plugins/npmPlugins.mjs b/dev-packages/rollup-utils/plugins/npmPlugins.mjs index f17d102e012c..0b2b812d73f6 100644 --- a/dev-packages/rollup-utils/plugins/npmPlugins.mjs +++ b/dev-packages/rollup-utils/plugins/npmPlugins.mjs @@ -1,56 +1,10 @@ /** - * Rollup plugin hooks docs: https://rollupjs.org/guide/en/#build-hooks and - * https://rollupjs.org/guide/en/#output-generation-hooks - * - * esbuild plugin docs: https://github.com/egoist/rollup-plugin-esbuild - * Replace plugin docs: https://github.com/rollup/plugins/tree/master/packages/replace - */ - -import json from '@rollup/plugin-json'; -import replace from '@rollup/plugin-replace'; -import esbuild from 'rollup-plugin-esbuild'; - -/** - * Create a plugin to transpile TS/JSX syntax using `esbuild`. - * - * `target: 'es2020'` keeps ES2020-native syntax (`?.`, `??`, optional catch binding) and - * downlevels everything newer (logical assignment, numeric separators, class private - * fields, static class blocks, ...). - * - * `esbuildOptions` are forwarded to `rollup-plugin-esbuild` verbatim and can override - * any of the pinned defaults (e.g. JSX-related keys like `jsxFactory` / `jsxFragment` - * for packages that use a non-React pragma). + * Replace plugin docs: https://rolldown.rs/builtin-plugins/replace#replace-plugin */ -export function makeEsbuildPlugin(esbuildOptions = {}) { - const plugin = esbuild({ - // `.json` is handled by the JSON plugin further down the pipeline. - exclude: ['**/*.json'], - // ES2020 is our floor — keeps `?.`/`??` native, downlevels everything newer. - target: 'es2020', - // Don't read per-package tsconfig (they vary and can pull in unrelated settings). - // Pin only the compilerOptions that affect codegen. - tsconfig: false, - tsconfigRaw: { - compilerOptions: { - // Match the project tsconfig's effective behavior at target=es2020: class - // field initializers compile to `this.x = v` (set semantics), not via the - // `Object.defineProperty`-based `__publicField` helper esbuild emits by - // default. This is what tsc itself outputs at this target. - useDefineForClassFields: false, - }, - }, - sourceMap: true, - ...esbuildOptions, - }); - // Force a stable plugin name so the plugin sort order in utils.mjs can target it. - plugin.name = 'esbuild'; - return plugin; -} - -export function makeJsonPlugin() { - return json(); -} +import { builtinModules } from 'node:module'; +import * as nodePath from 'node:path'; +import { replacePlugin } from 'rolldown/plugins'; /** * Create a plugin which can be used to pause the build process at the given hook. @@ -107,24 +61,23 @@ export function makeDebuggerPlugin(hookName) { * a) evaluates to `true` * b) can easily be modified by our users' bundlers to evaluate to false, facilitating the treeshaking of logger code. * - * @returns A `@rollup/plugin-replace` instance. + * @returns A `rolldown` replace plugin instance. */ export function makeDebugBuildStatementReplacePlugin() { - const plugin = replace({ - preventAssignment: false, - values: { + return replacePlugin( + { __DEBUG_BUILD__: "(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)", }, - }); - plugin.name = 'replace-debug-build-statement'; - return plugin; + { + preventAssignment: true, + }, + ); } -// Markers use the `/*! ... */` legal-comment syntax so esbuild preserves them through -// transpile. We still run as a `transform` (per-module) hook rather than `renderChunk`: -// the block typically uses imports declared at the module top, and stripping it before -// rollup analyses module-graph imports lets those now-unused imports be tree-shaken away. -// The plugin sort order in utils.mjs pins this before `esbuild`. +// Markers use the `/*! ... */` legal-comment syntax so rolldown's transpile preserves them. +// We run as a `transform` (per-module) hook rather than `renderChunk`: the block typically uses +// imports declared at the module top, and stripping it before the module graph is analysed lets +// those now-unused imports be tree-shaken away. const REMOVE_DEV_BLOCK = /\/\*! rollup-include-development-only \*\/[\s\S]*?\/\*! rollup-include-development-only-end \*\/\s*/g; @@ -175,10 +128,179 @@ export function makeRrwebBuildPlugin({ excludeShadowDom, excludeIframe } = {}) { values['__RRWEB_EXCLUDE_IFRAME__'] = excludeIframe; } - const plugin = replace({ + return replacePlugin(values, { preventAssignment: true, - values, }); - plugin.name = 'replace-rrweb-build-flags'; - return plugin; +} + +// For packages that bundle CommonJS dependencies. Rolldown converts CommonJS natively, but not the +// vendored graph's `require()` of node builtins: those survive into the ESM build as rolldown's +// `__require` helper, which throws in every ESM runtime (plain Node ESM included, since `require` is +// not defined there). +// +// Neither knob rolldown offers fixes it. `platform: 'node'` makes `__require` a real +// `createRequire(import.meta.url)`, but that lands a static `node:module` import in the *shared* +// runtime chunk, which every module imports for `__toESM` - including entries that edge runtimes +// pull in (e.g. `@sentry/server-utils` from `@sentry/vercel-edge`), so edge and browser bundlers then fail to resolve `node:`. And +// evaluating `createRequire(import.meta.url)` at module scope crashes with ERR_INVALID_ARG_VALUE +// once a downstream bundler re-bundles our ESM to CJS (see node-integration-tests' `esbuild` suite). +// +// So do what `@rollup/plugin-commonjs` used to: turn each `require('')` into a static import. +// `preserveModules` gives every vendored file its own chunk, so the `node:` imports land only in +// the Node-only chunks that actually need them and never in the shared runtime chunk. +export function makeBuiltinRequireShimPlugin() { + let replaced = false; + + return { + name: 'builtin-require-shim', + renderChunk(code, _chunk, outputOptions) { + // The CJS variant has a real `require`; rolldown never emits the helper there. + if (outputOptions.format !== 'es' && outputOptions.format !== 'esm') return null; + + const imports = new Map(); + // Built per call: rolldown renders chunks concurrently, and a shared global regex would + // carry `lastIndex` across those calls and skip matches. + const rewritten = code.replace(/__require\("([^"]+)"\)/g, (_match, specifier) => { + const bare = specifier.replace(/^node:/, ''); + if (!builtinModules.includes(bare)) { + throw new Error( + `The vendored graph \`require()\`s "${specifier}", which is not a node builtin. This shim only knows how to hoist builtins into static imports - handle that dependency explicitly instead.`, + ); + } + + const identifier = `__sentryRequire_${bare.replace(/[^a-zA-Z0-9]/g, '_')}`; + imports.set(identifier, specifier); + + return identifier; + }); + + if (!imports.size) return null; + replaced = true; + + const preamble = [...imports].map(([identifier, specifier]) => `import ${identifier} from "${specifier}";`); + + return { code: `${preamble.join('\n')}\n${rewritten}` }; + }, + generateBundle(outputOptions) { + if (outputOptions.format !== 'es' && outputOptions.format !== 'esm') return; + + if (!replaced) { + throw new Error( + 'Expected rolldown to emit `__require(...)` calls for the vendored graph so they could be hoisted into static imports, but no chunk contained one. Rolldown likely changed how it compiles `require()` of externals - re-check this shim against the emitted chunks.', + ); + } + replaced = false; + }, + }; +} + +// Always vendor `debug`'s Node build. Its default entry picks browser vs node at require time, +// which drags the browser build into this server-only bundle, and the browser build's storage +// detection probes `localStorage` at import time, which on Node >= 26 emits an ExperimentalWarning +// that pollutes stderr and console breadcrumbs in every user app. `order: 'pre'` so this wins over +// rolldown's own resolution. +export function makeDebugNodeAliasPlugin() { + return { + name: 'debug-node-alias', + resolveId: { + order: 'pre', + handler(source, importer) { + return source === 'debug' ? this.resolve('debug/src/node.js', importer, { skipSelf: true }) : null; + }, + }, + }; +} + +// `esquery` publishes a `module` field, so rolldown resolves the CJS `require('esquery')` inside the +// vendored graph to its ESM build and then converts that namespace with `__toCommonJS`, handing the +// caller `{ default: fn }` instead of the function itself - `esquery.parse` ends up undefined and +// every orchestrion injection fails. `@rollup/plugin-commonjs` used to settle this with +// `requireReturnsDefault: 'auto'`. Point the CJS caller at the CJS build instead, which needs no +// interop guesswork at all. +export function makeEsqueryCjsAliasPlugin() { + return { + name: 'esquery-cjs-alias', + resolveId: { + order: 'pre', + handler(source, importer) { + return source === 'esquery' ? this.resolve('esquery/dist/esquery.min.js', importer, { skipSelf: true }) : null; + }, + }, + }; +} + +// Rolldown compiles each bundled CJS dependency into `var require_x = __commonJSMin(...)` and has +// consumers pull it in with `import { require_x } from './body.js'`. That named import is used, so +// nothing downstream can drop it - which dragged the whole build-time-only transformer chain +// (meriyah, astring, source-map: ~185 kB) into every consumer's runtime bundle. +// +// `@rollup/plugin-commonjs` split each CJS module in two: a tiny `_virtual` module holding the +// exports, and the body imported purely for its side effects. With the package's +// `sideEffects: false`, a downstream bundler is then free to drop the body. Reproduce that split so +// the emitted graph matches what rollup produced. +// +// The exports live in a mutable container rather than being merged into an object, because a CJS +// module's exports can be any value (esquery's is a function). +const CJS_INIT = /^var (require_[A-Za-z0-9_$]+) = \/\* @__PURE__ \*\/ __commonJSMin\(/m; + +/** + * @param splittable Matches the output file names of the CJS modules to split. Only modules whose loss a consumer can + * survive belong here, because a downstream bundler may drop their bodies. + */ +export function makeCjsExportsSplitPlugin(splittable) { + return { + name: 'cjs-exports-split', + generateBundle(outputOptions, bundle) { + if (outputOptions.format !== 'es' && outputOptions.format !== 'esm') return; + + const chunks = Object.values(bundle).filter(c => c.type === 'chunk'); + const split = new Map(); + + // Pass 1: every chunk that defines and exports a single CJS initializer gets a container. + for (const chunk of chunks) { + if (!splittable.test(chunk.fileName)) continue; + const match = CJS_INIT.exec(chunk.code); + if (!match) continue; + const name = match[1]; + if (!chunk.code.includes(`export { ${name} };`)) continue; + split.set(name, { body: chunk, container: `_virtual/_cjs/${name}.js` }); + } + if (!split.size) return; + + const relative = (fromFile, toFile) => { + const rel = nodePath.posix.relative(nodePath.posix.dirname(fromFile), toFile); + return rel.startsWith('.') ? rel : `./${rel}`; + }; + + for (const [name, { body, container }] of split) { + this.emitFile({ type: 'asset', fileName: container, source: 'var c = {};\nexport { c as __cjs };\n' }); + + // The body stops exporting the initializer and instead runs it into the container. Eager, + // like `@rollup/plugin-commonjs` with `strictRequires: false`, which this graph already + // relied on. + const bodyImport = `import { __cjs as ${name}__cjs } from "${relative(body.fileName, container)}";`; + const bodyCode = body.code.replace(`export { ${name} };`, `${name}__cjs.v = ${name}();`); + body.code = `${bodyImport}\n${bodyCode}`; + } + + // Pass 2: consumers import the body for side effects only and read the container. + for (const chunk of chunks) { + for (const [name, { body, container }] of split) { + if (chunk === body) continue; + const importRe = new RegExp(`^import \\{ ${name.replaceAll('$', '\\$')} \\} from "([^"]+)";$`, 'm'); + const found = importRe.exec(chunk.code); + if (!found) continue; + chunk.code = chunk.code + .replace( + found[0], + `import "${found[1]}";\nimport { __cjs as ${name}__cjs } from "${relative(chunk.fileName, container)}";`, + ) + // `?? {}` mirrors rollup's `_virtual` module, which held a plain `{}`. If a consumer + // drops the body, reads yield `undefined` rather than throwing on destructuring, so + // injection degrades to a caught warning exactly as it does on the rollup build. + .replaceAll(`${name}()`, `(${name}__cjs.v ?? {})`); + } + } + }, + }; } diff --git a/dev-packages/rollup-utils/utils.mjs b/dev-packages/rollup-utils/utils.mjs index 503a4876d223..048abbf5ac72 100644 --- a/dev-packages/rollup-utils/utils.mjs +++ b/dev-packages/rollup-utils/utils.mjs @@ -1,3 +1,5 @@ +import { builtinModules } from 'module'; + /** * Helper function to compensate for the fact that JS can't handle negative array indices very well */ @@ -33,36 +35,21 @@ export function mergeExternals(base, specific) { * Merge two arrays of plugins, making sure they're sorted in the correct order. * * Each entry in `order` is pinned for a real reason; `...` is where every other plugin lands. + * + * Rolldown's builtin plugins all report the same `name` (e.g. `builtin:replace`), so they can't be + * pinned individually and all land in `...`, where `Array.prototype.sort` keeps them in insertion + * order. That's fine: the transpile step they used to be ordered against is now part of rolldown + * itself and always runs first. */ export function mergePlugins(pluginsA, pluginsB) { const order = [ - // (transform) Strips `/*! rollup-include-development-only */` marker blocks. Must precede `esbuild` so the - // now-unused imports inside the block can be tree-shaken by rollup. + // (transform) Strips `/*! rollup-include-development-only */` marker blocks. Runs first so the + // now-unused imports inside the block can be tree-shaken. 'remove-dev-mode-blocks', - // (transform) Rewrites the `/*! __SENTRY_SDK_SOURCE__ */` comment marker in `getSDKSource()` for CDN builds. - // Comment-based → must precede `esbuild` (the marker uses `/*!` legal-comment syntax, but pinning is defensive). - 'replace-sdk-source', - // (transform) TS/JSX → JS, strips non-legal block comments, strips `declare const` lines. - 'esbuild', - // The identifier-based `replace-*` plugins below MUST run AFTER `esbuild`. Each of these identifiers is also - // declared in TS via `declare const __FOO__: ...;` lines. If the replace runs before esbuild, it rewrites the - // declaration's identifier into an expression and produces invalid TS. esbuild strips `declare const` lines, - // so by the time these plugins run the only remaining occurrences are real references. - 'replace-debug-build-statement', - 'replace-browser-bundle-flag', - 'replace-debug-flags', - 'replace-rrweb-build-flags', - // Every other plugin lands here — including additional identifier-based `replace-*` plugins (e.g. - // `replace-sdk-version`), which intentionally run AFTER `esbuild` for the same reason as the ones pinned above. + // (transform) Strips the marker blocks for the format we're not currently emitting. + 'remove-esm-cjs-mode-blocks', + // Every other plugin lands here, including the identifier-based `builtin:replace` instances. '...', - // (renderChunk) Minifies and strips comments (we use `comments: false`). Anything that contributes code to a - // chunk must run before this. - 'terser', - // (renderChunk) Prepends the license banner, which is a comment. Must run AFTER `terser`, otherwise terser - // would strip it. - 'license', - // (renderChunk) Captures the final chunk text as base64, so it must run last. - 'output-base64-worker-script', ]; const plugins = [...pluginsA, ...pluginsB]; plugins.sort((a, b) => { @@ -72,3 +59,33 @@ export function mergePlugins(pluginsA, pluginsB) { }); return plugins; } + +/** + * Rolldown has no `'smallest'` treeshake preset, so spell out what rollup's `'smallest'` meant. + * + * https://rolldown.rs/options/treeshake#treeshake + * https://rollupjs.org/configuration-options/#treeshake + */ +export function treeShakePreset(preset) { + if (preset === 'smallest') { + return { + propertyReadSideEffects: false, + moduleSideEffects: false, + unknownGlobalSideEffects: false, + }; + } + + return preset; +} + +/** + * List every Node.js builtin under both its bare name (`fs`) and its prefixed name (`node:fs`). + * + * Rollup normalised the `node:` prefix for us when matching externals; rolldown doesn't, so both + * spellings have to be listed explicitly. + */ +export function getNodeBuiltIns(excludeBuiltins = []) { + const excluded = new Set(excludeBuiltins); + + return builtinModules.flatMap(builtin => (excluded.has(builtin) ? [] : [builtin, `node:${builtin}`])); +} diff --git a/dev-packages/test-utils/package.json b/dev-packages/test-utils/package.json index 9a22c4458860..3d59752b2318 100644 --- a/dev-packages/test-utils/package.json +++ b/dev-packages/test-utils/package.json @@ -53,7 +53,7 @@ "build": "run-s build:transpile build:types", "build:tarball": "pnpm pack", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "clean": "node ../../scripts/rm.mjs ./node_modules ./build" }, diff --git a/package.json b/package.json index 6f99f6deca66..b7dcfa889a95 100644 --- a/package.json +++ b/package.json @@ -135,11 +135,6 @@ "`@sentry/sveltekit`: size-limit bundles its build output, which imports `@sentry/sveltekit/browser-tracing-variant`." ], "devDependencies": { - "@rollup/plugin-commonjs": "^25.0.7", - "@rollup/plugin-json": "^6.1.0", - "@rollup/plugin-node-resolve": "^16.0.3", - "@rollup/plugin-replace": "^5.0.5", - "@rollup/plugin-terser": "^1.0.2", "@sentry-internal/node-integration-tests": "workspace:*", "@sentry/eslint-plugin-sdk": "workspace:*", "@sentry/sveltekit": "workspace:*", @@ -160,8 +155,8 @@ "oxfmt": "^0.74.0", "oxlint": "^1.89.0", "oxlint-tsgolint": "^7.0.2004", + "rolldown": "^1.3.2", "rollup": "^4.60.3", - "rollup-plugin-esbuild": "^6.2.1", "rollup-plugin-license": "^3.7.1", "size-limit": "~12.1.0", "tslib": "^2.4.1", diff --git a/packages/astro/package.json b/packages/astro/package.json index 9879b5bc9c10..dbb68cdb564f 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -82,11 +82,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-astro-*.tgz", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index ba7a6e3ad6ab..08cb65b57c12 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -80,15 +80,15 @@ }, "scripts": { "build": "run-p build:transpile build:types", - "build:extension": "rollup -c rollup.lambda-extension.config.mjs && pnpm exec tsx scripts/buildLambdaExtension.ts", + "build:extension": "rolldown -c rollup.lambda-extension.config.mjs && pnpm exec tsx scripts/buildLambdaExtension.ts", "build:layer": "node ../../scripts/rm.mjs build/aws && pnpm exec tsx scripts/buildLambdaLayer.ts", "build:dev": "run-p build:transpile build:types", "build:transpile": "run-s build:transpile:npm build:extension", - "build:transpile:npm": "rollup -c rollup.npm.config.mjs", + "build:transpile:npm": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build dist-awslambda-layer coverage sentry-serverless-*.tgz", diff --git a/packages/aws-serverless/rollup.npm.config.mjs b/packages/aws-serverless/rollup.npm.config.mjs index 9c89af481558..347078fea463 100644 --- a/packages/aws-serverless/rollup.npm.config.mjs +++ b/packages/aws-serverless/rollup.npm.config.mjs @@ -9,7 +9,7 @@ function makeHandlerShimConfig() { const baseConfig = makeBaseNPMConfig({ entrypoints: ['src/run-lambda-handler.ts'], // Top-level await requires es2022. - esbuild: { target: 'es2022' }, + packageSpecificConfig: { transform: { target: 'es2022' } }, }); return { diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index 2266c22bce6c..224637a4f0d2 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -43,11 +43,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-browser-utils-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/browser/package.json b/packages/browser/package.json index 2ad0ed595d28..0147f5b3ef30 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -53,13 +53,13 @@ "scripts": { "build": "run-p build:transpile build:bundle build:types", "build:dev": "run-p build:transpile build:types", - "build:bundle": "rollup -c rollup.bundle.config.mjs", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:bundle": "rolldown -c rollup.bundle.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:bundle:watch", "build:dev:watch": "run-p build:transpile:watch", - "build:bundle:watch": "rollup -c rollup.bundle.config.mjs --watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:bundle:watch": "rolldown -c rollup.bundle.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage .rpt2_cache sentry-browser-*.tgz", diff --git a/packages/browser/test/tracing/browserTracingIntegration.test.ts b/packages/browser/test/tracing/browserTracingIntegration.test.ts index 0061ec0dde23..d8fe42557232 100644 --- a/packages/browser/test/tracing/browserTracingIntegration.test.ts +++ b/packages/browser/test/tracing/browserTracingIntegration.test.ts @@ -8,7 +8,6 @@ import { getCurrentScope, getDynamicSamplingContextFromSpan, getMainCarrier, - metrics, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, setCurrentClient, spanIsSampled, @@ -976,7 +975,6 @@ describe('browserTracingIntegration', () => { // so its hit/miss metric is emitted before this navigation span exists and lands on the trace // the page had before it was frozen. See the note on the pageshow handler. it('emits the bfcache metric on the pre-freeze trace, before the navigation span exists', () => { - const countSpy = vi.spyOn(metrics, 'count').mockImplementation(() => {}); const client = new BrowserClient( getDefaultBrowserClientOptions({ tracesSampleRate: 1, @@ -989,7 +987,7 @@ describe('browserTracingIntegration', () => { const traceIdBeforeRestore = getCurrentScope().getPropagationContext().traceId; let traceIdAtMetricTime: string | undefined; - countSpy.mockImplementation(() => { + client.on('processMetric', () => { traceIdAtMetricTime = getCurrentScope().getPropagationContext().traceId; }); diff --git a/packages/bun/package.json b/packages/bun/package.json index 627527189698..94c5d75ae932 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -56,11 +56,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-bun-*.tgz", diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index 9b4a5d7fba68..a4abe848d02c 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -75,11 +75,11 @@ "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", "build:version": "node -p \"'export const LIB_VERSION = ' + JSON.stringify(require('./package.json').version) + ';'\" > src/core/version.ts", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "prebuild": "pnpm run build:version", "precheck:types": "pnpm run build:version", diff --git a/packages/bundler-plugins/rollup.npm.config.mjs b/packages/bundler-plugins/rollup.npm.config.mjs index 19e511012dc3..14a01bf06c1e 100644 --- a/packages/bundler-plugins/rollup.npm.config.mjs +++ b/packages/bundler-plugins/rollup.npm.config.mjs @@ -14,16 +14,16 @@ export default makeNPMConfigVariants( 'src/babel-plugin/index.ts', ], packageSpecificConfig: { + // This package only ever runs in Node, at build time. Without pinning the platform, rolldown + // would infer 'browser' for the ESM half, which defines `process.env.NODE_ENV` as + // 'development' (silently disabling release creation and sourcemap upload) and drops the + // `import.meta.url` rewrite the `createRequire` calls in `./webpack` depend on. + platform: 'node', output: { // Multiple entry points with no single default export -> emit named exports - // so rollup doesn't warn. `preserveModules` (true by default in the base config) + // so the bundler doesn't warn. `preserveModules` (true by default in the base config) // keeps the per-submodule file layout the `exports` map points at. exports: 'named', - // The source default-imports CJS Node builtins (e.g. `import crypto from 'crypto'`). - // The shared base config's `interop: 'esModule'` would emit `require('crypto').default` - // in the CJS build (undefined for real CJS modules -> runtime crash). `auto` emits the - // interop helper so default-imported CJS builtins resolve correctly. - interop: 'auto', }, }, }), diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index d18f68c0f1c3..6cfe55eabbe4 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -86,11 +86,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-cloudflare-*.tgz", diff --git a/packages/core/package.json b/packages/core/package.json index ac304287cef9..1090e703e385 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -70,11 +70,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-core-*.tgz", diff --git a/packages/core/rollup.npm.config.mjs b/packages/core/rollup.npm.config.mjs index 47d28e630457..1b079d3deb74 100644 --- a/packages/core/rollup.npm.config.mjs +++ b/packages/core/rollup.npm.config.mjs @@ -2,8 +2,8 @@ import { readFileSync } from 'fs'; import { dirname, join } from 'path'; +import { replacePlugin } from 'rolldown/plugins'; import { fileURLToPath } from 'url'; -import replace from '@rollup/plugin-replace'; import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf-8')); @@ -23,12 +23,14 @@ const settings = { preserveModules: true, }, plugins: [ - replace({ - preventAssignment: true, - values: { + replacePlugin( + { __SENTRY_SDK_VERSION__: JSON.stringify(packageVersion), }, - }), + { + preventAssignment: true, + }, + ), ], }, }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 6efcccdc3b18..5e01bde701e6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -184,14 +184,14 @@ export { instrumentFetchRequest, _INTERNAL_getTracingHeadersForFetchRequest } fr export { captureFeedback } from './feedback'; export type { ReportDialogOptions } from './report-dialog'; export { _INTERNAL_captureLog, _INTERNAL_flushLogsBuffer, _INTERNAL_captureSerializedLog } from './logs/internal'; -export * as logger from './logs/public-api'; +export { logger } from './logs/public-api'; export { consoleLoggingIntegration } from './logs/console-integration'; export { _INTERNAL_captureMetric, _INTERNAL_flushMetricsBuffer, _INTERNAL_captureSerializedMetric, } from './metrics/internal'; -export * as metrics from './metrics/public-api'; +export { metrics } from './metrics/public-api'; export type { MetricOptions } from './metrics/public-api'; export { createConsolaReporter } from './integrations/consola'; export { SpanBuffer } from './tracing/spans/spanBuffer'; diff --git a/packages/core/src/logs/public-api.ts b/packages/core/src/logs/public-api.ts index 1261edc9da75..c37ce60fc88e 100644 --- a/packages/core/src/logs/public-api.ts +++ b/packages/core/src/logs/public-api.ts @@ -2,6 +2,7 @@ import type { Scope } from '../scope'; import type { Log, LogSeverityLevel } from '../types/log'; import type { ParameterizedString } from '../types/parameterize'; import { _INTERNAL_captureLog } from './internal'; +import { fmt } from '../utils/parameterize'; /** * Capture a log with the given level. @@ -243,4 +244,11 @@ export function fatal( captureLog('fatal', message, attributes, scope); } -export { fmt } from '../utils/parameterize'; +export { fmt }; + +/** + * The public logger API. + * + * A plain object rather than a module namespace so its methods can be spied on in tests. + */ +export const logger = { trace, debug, info, warn, error, fatal, fmt }; diff --git a/packages/core/src/metrics/public-api.ts b/packages/core/src/metrics/public-api.ts index 68b9695918af..ca0b4fab83a0 100644 --- a/packages/core/src/metrics/public-api.ts +++ b/packages/core/src/metrics/public-api.ts @@ -139,3 +139,10 @@ export function gauge(name: string, value: number, options?: MetricOptions): voi export function distribution(name: string, value: number, options?: MetricOptions): void { captureMetric('distribution', name, value, options); } + +/** + * The public metrics API. + * + * A plain object rather than a module namespace so its methods can be spied on in tests. + */ +export const metrics = { count, gauge, distribution }; diff --git a/packages/deno/package.json b/packages/deno/package.json index 941b026edfd4..93c30a70cd1f 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -40,7 +40,7 @@ "deno-types": "node ./scripts/download-deno-types.mjs", "build": "run-s build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "pnpm run deno-types && rollup -c rollup.npm.config.mjs", + "build:transpile": "pnpm run deno-types && rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", diff --git a/packages/deno/rollup.npm.config.mjs b/packages/deno/rollup.npm.config.mjs index 08ffaddf0bbe..ddfaf47224a3 100644 --- a/packages/deno/rollup.npm.config.mjs +++ b/packages/deno/rollup.npm.config.mjs @@ -1,4 +1,4 @@ -import { defineConfig } from 'rollup'; +import { defineConfig } from 'rolldown'; import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; const orchestrionRuntimeHooks = [ diff --git a/packages/effect/package.json b/packages/effect/package.json index 957ae27ada1b..5449957181e4 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -65,11 +65,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-effect-*.tgz", diff --git a/packages/effect/src/errorReporter.ts b/packages/effect/src/errorReporter.ts index 8accd462557c..197066e41fcf 100644 --- a/packages/effect/src/errorReporter.ts +++ b/packages/effect/src/errorReporter.ts @@ -9,9 +9,9 @@ import type * as LogLevel from 'effect/LogLevel'; // `effect/ErrorReporter` only exists in Effect v4, so it is read off the main entry instead of being imported // as a subpath. On Effect v3 the lookup yields `undefined` and no reporter is registered. The property is read -// through a separate binding because bundlers fail the build on `Effect.ErrorReporter` when the export is absent. -const effectExports = Effect as Record; -const ErrorReporter = effectExports.ErrorReporter as typeof EffectErrorReporter | undefined; +// with `Reflect.get` because bundlers fail the build on `Effect.ErrorReporter` when the export is absent, and +// an aliased property read gets folded back into exactly that member access by our own build. +const ErrorReporter = Reflect.get(Effect, 'ErrorReporter') as typeof EffectErrorReporter | undefined; const SEVERITY_TO_LEVEL: Record = { Fatal: 'fatal', diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 59d49157f95a..375ae8b5f19c 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -52,11 +52,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-elysia-*.tgz", diff --git a/packages/esbuild-plugin/package.json b/packages/esbuild-plugin/package.json index 2d6583d43c43..5c2075d58fe9 100644 --- a/packages/esbuild-plugin/package.json +++ b/packages/esbuild-plugin/package.json @@ -35,11 +35,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-esbuild-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/feedback/package.json b/packages/feedback/package.json index 6f1eac6bc092..8add18f47a1d 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -41,8 +41,8 @@ }, "scripts": { "build": "run-p build:transpile build:types build:bundle", - "build:transpile": "rollup -c rollup.npm.config.mjs", - "build:bundle": "rollup -c rollup.bundle.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", + "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:bundle:watch", diff --git a/packages/feedback/rollup.bundle.config.mjs b/packages/feedback/rollup.bundle.config.mjs index b3f54dfb2b85..67d78d9cb9b4 100644 --- a/packages/feedback/rollup.bundle.config.mjs +++ b/packages/feedback/rollup.bundle.config.mjs @@ -1,5 +1,12 @@ import { makeBaseBundleConfig, makeBundleConfigVariants } from '@sentry-internal/rollup-utils'; +// The widget's `.tsx` files import `h`/`Fragment` from preact directly and rely on the classic +// transform, the way the rollup build's esbuild `jsxFactory` override did. Rolldown would otherwise +// read `jsx: "react-jsx"` from tsconfig and pull in `preact/jsx-runtime`. +const preactJsx = { + transform: { jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' } }, +}; + export default [ // The core `feedback` bundle is built in the browser package // Sub-bundles are built here @@ -10,11 +17,7 @@ export default [ jsVersion: 'es6', licenseTitle: '@sentry/feedback', outputFileBase: () => 'bundles/feedback-screenshot', - esbuild: { - // The feedback widget uses preact, so override esbuild's React defaults. - jsxFactory: 'h', - jsxFragment: 'Fragment', - }, + packageSpecificConfig: preactJsx, }), ), ...makeBundleConfigVariants( @@ -24,11 +27,7 @@ export default [ jsVersion: 'es6', licenseTitle: '@sentry/feedback', outputFileBase: () => 'bundles/feedback-modal', - esbuild: { - // The feedback widget uses preact, so override esbuild's React defaults. - jsxFactory: 'h', - jsxFragment: 'Fragment', - }, + packageSpecificConfig: preactJsx, }), ), ]; diff --git a/packages/feedback/rollup.npm.config.mjs b/packages/feedback/rollup.npm.config.mjs index 03e8c739c9d6..f393c1cb11d2 100644 --- a/packages/feedback/rollup.npm.config.mjs +++ b/packages/feedback/rollup.npm.config.mjs @@ -7,15 +7,16 @@ export default makeNPMConfigVariants( output: { // set exports to 'named' or 'auto' so that rollup doesn't warn exports: 'named', - // set preserveModules to false because for feedback we actually want - // to bundle everything into one file. - preserveModules: false, + // preact is bundled, and `preserveModules` names its files by their pnpm store path + // (`node_modules/.pnpm/preact@x/...`), so emit them under `vendored/` instead. A single-file + // build would avoid that, but the CDN bundles that consume it tree-shake it much worse. + entryFileNames: info => `${info.name.replace(/^.*node_modules\//, 'vendored/')}.js`, }, - }, - esbuild: { - // The feedback widget uses preact, so override esbuild's React defaults. - jsxFactory: 'h', - jsxFragment: 'Fragment', + // The widget's `.tsx` files import `h`/`Fragment` from preact directly and rely on the + // classic transform, the way the rollup build's esbuild `jsxFactory` override did. Rolldown + // would otherwise read `jsx: "react-jsx"` from tsconfig, pull in `preact/jsx-runtime` and + // leave those imports dead. + transform: { jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' } }, }, }), ); diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index dbc5c2167159..7d1e21e41377 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -57,11 +57,11 @@ "build:dev": "pnpm run build", "build:plugin": "tsc -p tsconfig.plugin.json", "build:transpile": "run-p build:rollup build:plugin", - "build:rollup": "rollup -c rollup.npm.config.mjs", + "build:rollup": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage *.d.ts sentry-gatsby-*.tgz", diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index 84a2aa847a9b..bedb5fa1ec13 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -61,11 +61,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-google-cloud-*.tgz", diff --git a/packages/google-cloud-serverless/rollup.npm.config.mjs b/packages/google-cloud-serverless/rollup.npm.config.mjs index 9ffe2dab5427..e87b4a22a6e2 100644 --- a/packages/google-cloud-serverless/rollup.npm.config.mjs +++ b/packages/google-cloud-serverless/rollup.npm.config.mjs @@ -1,3 +1,11 @@ import { makeBaseNPMConfig, makeNPMConfigVariants, makeOrchestrionLoader } from '@sentry-internal/rollup-utils'; -export default [...makeNPMConfigVariants(makeBaseNPMConfig()), ...makeOrchestrionLoader('./build')]; +export default [ + ...makeNPMConfigVariants( + makeBaseNPMConfig({ + // Rolldown bundles `require()` calls, so the user-provided module this lazily requires has to be external. + packageSpecificConfig: { external: ['@google-cloud/common'] }, + }), + ), + ...makeOrchestrionLoader('./build'), +]; diff --git a/packages/hono/package.json b/packages/hono/package.json index a5b4a422bc51..27c1983ee59d 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -116,11 +116,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-hono-*.tgz", diff --git a/packages/integration-shims/package.json b/packages/integration-shims/package.json index 425aa2ab2042..fc36769f0de3 100644 --- a/packages/integration-shims/package.json +++ b/packages/integration-shims/package.json @@ -25,7 +25,7 @@ "private": true, "scripts": { "build": "run-p build:transpile build:types", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm run build", "build:watch": "run-p build:transpile:watch", diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index a13ac7133e23..be7431d73cff 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -73,13 +73,13 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core build:types:setup", "build:types:core": "tsc -p tsconfig.types.json", "build:types:setup": "tsc -p tsconfig.setup-types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts src/setup.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-nestjs-*.tgz ./*.d.ts ./*.d.ts.map", diff --git a/packages/nextjs/rollup.npm.config.mjs b/packages/nextjs/rollup.npm.config.mjs index 925a49507c0f..104dc8087894 100644 --- a/packages/nextjs/rollup.npm.config.mjs +++ b/packages/nextjs/rollup.npm.config.mjs @@ -21,6 +21,10 @@ export default [ packageSpecificConfig: { external: ['next/router', 'next/constants.js', 'next/headers', 'stacktrace-parser'], + output: { + virtualDirname: '_virtual/core', + }, + // Next.js and our users are more happy when our client code has the "use client" directive plugins: [ { @@ -53,8 +57,7 @@ export default [ packageSpecificConfig: { output: { - // Preserve the original file structure (i.e., so that everything is still relative to `src`) - entryFileNames: 'config/templates/[name].js', + virtualDirname: '_virtual/templates', // this is going to be add-on code, so it doesn't need the trappings of a full module (and in fact actively // shouldn't have them, lest they muck with the module to which we're adding it) @@ -71,6 +74,33 @@ export default [ '__SENTRY_WRAPPING_TARGET_FILE__', '__SENTRY_NEXTJS_REQUEST_ASYNC_STORAGE_SHIM__', ], + plugins: [ + { + name: 'sentry-fix-missing-serverComponentModule-import', + renderChunk(code, chunk) { + // Rolldown has a bug where it removes namespace imports for external modules even when they're still + // referenced in the code (specifically when there's a `declare const` with the same name in the source). + // We need to add back the missing import for serverComponentModule in the serverComponentWrapperTemplate. + if ( + chunk.facadeModuleId?.includes('serverComponentWrapperTemplate') && + code.includes('serverComponentModule') && + !code.includes('import * as serverComponentModule') + ) { + // Find the position after the last import statement to insert our missing import + const lastImportMatch = code.match(/^import[^;]*;/gm); + if (lastImportMatch) { + const lastImport = lastImportMatch[lastImportMatch.length - 1]; + const lastImportEnd = code.indexOf(lastImport) + lastImport.length; + return { + code: `${code.slice(0, lastImportEnd)} +import * as serverComponentModule from "__SENTRY_WRAPPING_TARGET_FILE__";${code.slice(lastImportEnd)}`, + }; + } + } + return null; + }, + }, + ], }, }), ), @@ -80,8 +110,7 @@ export default [ packageSpecificConfig: { output: { - // Preserve the original file structure (i.e., so that everything is still relative to `src`) - entryFileNames: 'config/loaders/[name].js', + virtualDirname: '_virtual/loaders', // make it so Rollup calms down about the fact that we're combining default and named exports exports: 'named', diff --git a/packages/nextjs/scripts/buildRollup.ts b/packages/nextjs/scripts/buildRollup.ts index a30dcc415702..c96b2db165a0 100644 --- a/packages/nextjs/scripts/buildRollup.ts +++ b/packages/nextjs/scripts/buildRollup.ts @@ -10,7 +10,7 @@ function run(cmd: string, options?: childProcess.ExecSyncOptions): string | Buff return childProcess.execSync(cmd, { stdio: 'inherit', ...options }); } -run('pnpm exec rollup -c rollup.npm.config.mjs'); +run('pnpm exec rolldown -c rollup.npm.config.mjs'); // Regardless of whether nextjs is using the CJS or ESM version of our SDK, we want the code from our templates to be in // ESM (since we'll be adding it onto page files which are themselves written in ESM), so copy the ESM versions of the diff --git a/packages/nextjs/src/config/loaders/wrappingLoader.ts b/packages/nextjs/src/config/loaders/wrappingLoader.ts index 8d6e619ac751..537957c91ad6 100644 --- a/packages/nextjs/src/config/loaders/wrappingLoader.ts +++ b/packages/nextjs/src/config/loaders/wrappingLoader.ts @@ -161,7 +161,9 @@ export default function wrappingLoader( if (wrappingTargetKind === 'server-component') { templateCode = serverComponentWrapperTemplateCode; } else { - templateCode = routeHandlerWrapperTemplateCode; + // Added here rather than in the template because the SDK build rewrites `export { default } from` in it, + // which would stop `wrapUserCode` from dropping the default for routes that don't have one. + templateCode = `${routeHandlerWrapperTemplateCode}\nexport { default } from '__SENTRY_WRAPPING_TARGET_FILE__';\n`; } if (nextjsRequestAsyncStorageModulePath !== undefined) { diff --git a/packages/nextjs/src/config/templates/routeHandlerWrapperTemplate.ts b/packages/nextjs/src/config/templates/routeHandlerWrapperTemplate.ts index 3a05c97d5f5c..0fcf00aa3705 100644 --- a/packages/nextjs/src/config/templates/routeHandlerWrapperTemplate.ts +++ b/packages/nextjs/src/config/templates/routeHandlerWrapperTemplate.ts @@ -60,9 +60,6 @@ function wrapHandler(handler: T, method: 'GET' | 'POST' | 'PUT' | 'PATCH' | ' // @ts-expect-error See above export * from '__SENTRY_WRAPPING_TARGET_FILE__'; -// @ts-expect-error This is the file we're wrapping -export { default } from '__SENTRY_WRAPPING_TARGET_FILE__'; - type RouteHandler = (...args: unknown[]) => unknown; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access diff --git a/packages/nextjs/src/config/templates/sentryInitWrapperTemplate.ts b/packages/nextjs/src/config/templates/sentryInitWrapperTemplate.ts index 3be1b07d6bc5..45ddaea4ba67 100644 --- a/packages/nextjs/src/config/templates/sentryInitWrapperTemplate.ts +++ b/packages/nextjs/src/config/templates/sentryInitWrapperTemplate.ts @@ -1,8 +1,10 @@ -// @ts-expect-error This will be replaced with the user's sentry config gile +// @ts-expect-error This will be replaced with the user's sentry config file import '__SENTRY_CONFIG_IMPORT_PATH__'; +// @ts-expect-error This is the file we're wrapping +import * as wrappingTargetModule from '__SENTRY_WRAPPING_TARGET_FILE__'; // @ts-expect-error This is the file we're wrapping export * from '__SENTRY_WRAPPING_TARGET_FILE__'; -// @ts-expect-error This is the file we're wrapping -export { default } from '__SENTRY_WRAPPING_TARGET_FILE__'; +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access +export default wrappingTargetModule.default; diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 754f8fb070ec..00c81795b0b2 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -51,12 +51,12 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core", "build:types:core": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:types:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:types:watch": "tsc -p tsconfig.types.json --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nitro-*.tgz", diff --git a/packages/node-native/package.json b/packages/node-native/package.json index 42be97d1c7ef..880063f1ea53 100644 --- a/packages/node-native/package.json +++ b/packages/node-native/package.json @@ -47,10 +47,10 @@ "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "lint:fix": "oxlint . --fix --type-aware", "build": "pnpm run build:types && pnpm run build:transpile", - "build:transpile": "pnpm exec rollup -c rollup.npm.config.mjs", + "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm clean && pnpm run build", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:watch": "run-p build:transpile:watch", "build:tarball": "pnpm pack" }, diff --git a/packages/node/package.json b/packages/node/package.json index c05a8ca5fb84..927ff23eb293 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -92,11 +92,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-node-*.tgz", diff --git a/packages/node/rollup.anr-worker.config.mjs b/packages/node/rollup.anr-worker.config.mjs index 4ef40909503f..224e0c71f6f6 100644 --- a/packages/node/rollup.anr-worker.config.mjs +++ b/packages/node/rollup.anr-worker.config.mjs @@ -17,8 +17,10 @@ export function createWorkerCodeBuilder(entry, outDir) { plugins: [ { name: 'output-base64-worker-script', - renderChunk(code) { - base64Code = Buffer.from(code).toString('base64'); + // `output.minify` runs after `renderChunk`, so only `generateBundle` sees the minified code. + generateBundle(_options, bundle) { + const chunk = Object.values(bundle).find(output => output.type === 'chunk'); + base64Code = Buffer.from(chunk.code).toString('base64'); }, }, ], diff --git a/packages/node/rollup.npm.config.mjs b/packages/node/rollup.npm.config.mjs index 45f7f66a6df4..b1262c0c1f50 100644 --- a/packages/node/rollup.npm.config.mjs +++ b/packages/node/rollup.npm.config.mjs @@ -1,4 +1,3 @@ -import replace from '@rollup/plugin-replace'; import { makeBaseNPMConfig, makeNPMConfigVariants, makeOrchestrionLoader } from '@sentry-internal/rollup-utils'; import { createWorkerCodeBuilder } from './rollup.anr-worker.config.mjs'; @@ -12,6 +11,23 @@ const [localVariablesWorkerConfig, getLocalVariablesBase64Code] = createWorkerCo 'build/esm/integrations/local-variables', ); +// The worker configs above only produce their base64 payload once their own `renderChunk` has run, +// so the placeholder values have to be read lazily. Rolldown's builtin replace plugin takes plain +// strings up front, which would capture the (still empty) payload at config time. +function makeLazyReplacePlugin(replacements, { delimiters: [delimiterStart, delimiterEnd] }) { + return { + name: 'lazy-replace-plugin', + renderChunk(code) { + const replaced = Object.entries(replacements).reduce( + (result, [key, getValue]) => result.split(`${delimiterStart}${key}${delimiterEnd}`).join(getValue()), + code, + ); + + return replaced === code ? null : { code: replaced }; + }, + }; +} + export default [ // The `@sentry/node/import` entry (`node --import @sentry/node/import app.js`), which registers // the orchestrion diagnostics-channel injection before the app loads. @@ -38,15 +54,13 @@ export default [ preserveModules: true, }, plugins: [ - replace({ - delimiters: ['###', '###'], - // removes some rollup warnings - preventAssignment: true, - values: { - AnrWorkerScript: () => getAnrBase64Code(), - LocalVariablesWorkerScript: () => getLocalVariablesBase64Code(), + makeLazyReplacePlugin( + { + AnrWorkerScript: getAnrBase64Code, + LocalVariablesWorkerScript: getLocalVariablesBase64Code, }, - }), + { delimiters: ['###', '###'] }, + ), ], }, }), diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 0e0250f6c432..5297b54a8c25 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -225,7 +225,7 @@ export { // oxlint-disable-next-line typescript/no-deprecated withStreamedSpan, } from '@sentry/core'; -export * as logger from './logs/exports'; +export { logger } from './logs/exports'; export { childProcessIntegration } from './integrations/childProcess'; export { consoleIntegration } from './integrations/console'; diff --git a/packages/node/src/integrations/fs/vendored/instrumentation.ts b/packages/node/src/integrations/fs/vendored/instrumentation.ts index b878fff7f79d..1c961cab894f 100644 --- a/packages/node/src/integrations/fs/vendored/instrumentation.ts +++ b/packages/node/src/integrations/fs/vendored/instrumentation.ts @@ -12,6 +12,10 @@ * - Completely reworked to no longer reference OpenTelemetry. * - The upstream `fs_error` span attribute (the error message) was replaced with the conventions-backed * `error.type` (the syscall error code, e.g. `ENOENT`). + * - `fs` is default-imported rather than namespace-imported. A namespace import is read-only in native ESM + * and compiles to a copied, getter-only namespace object in CJS, so patching it either throws or + * leaves the real module untouched. The default export is the module itself in both output + * formats, so patching it reaches every other consumer of `require('fs')` / `import 'fs'`. */ import { ERROR_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; @@ -25,17 +29,13 @@ import { suppressTracing, withActiveSpan, } from '@sentry/core'; -import * as fsNamespace from 'fs'; +import fs from 'fs'; import * as moduleNamespace from 'module'; import { promisify } from 'util'; import { CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS, SYNC_FUNCTIONS } from './constants'; import type { FMember, FPMember, FsInstrumentationConfig, GenericFunction } from './types'; import { indexFs } from './utils'; -// In native ESM, `import * as fs` is a read-only module namespace, so we patch the mutable `fs` object -// behind its default export instead. The CJS build has no `.default` and already gets the mutable object. -const fs = (fsNamespace as { default?: typeof fsNamespace }).default ?? fsNamespace; - // Deno before 2.8.2 has `syncBuiltinESMExports` only on the default export of `node:module`, so a named import fails to link. type SyncBuiltinESMExports = { syncBuiltinESMExports?: () => void }; const moduleExports = moduleNamespace as unknown as SyncBuiltinESMExports & { default?: SyncBuiltinESMExports }; diff --git a/packages/node/src/logs/exports.ts b/packages/node/src/logs/exports.ts index 166d8a8c6d01..c6a961f1c8b3 100644 --- a/packages/node/src/logs/exports.ts +++ b/packages/node/src/logs/exports.ts @@ -1,4 +1,5 @@ import { captureLog, type CaptureLogArgs } from './capture'; +import { fmt } from '@sentry/core'; /** * @summary Capture a log with the `trace` level. @@ -165,4 +166,11 @@ export function fatal(...args: CaptureLogArgs): void { captureLog('fatal', ...args); } -export { fmt } from '@sentry/core'; +export { fmt }; + +/** + * The public logger API. + * + * A plain object rather than a module namespace so its methods can be spied on in tests. + */ +export const logger = { trace, debug, info, warn, error, fatal, fmt }; diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 929362072016..66f481d1337d 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -82,12 +82,12 @@ "scripts": { "build": "run-s build:types build:transpile", "build:dev": "pnpm run build", - "build:nuxt-module": "rollup -c rollup.module.config.mjs && tsc -p tsconfig.module.json && node scripts/build-module-meta.mjs", - "build:transpile": "rollup -c rollup.npm.config.mjs && pnpm run build:nuxt-module", + "build:nuxt-module": "rolldown -c rollup.module.config.mjs && tsc -p tsconfig.module.json && node scripts/build-module-meta.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs && pnpm run build:nuxt-module", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-nuxt-*.tgz", diff --git a/packages/nuxt/rollup.module.config.mjs b/packages/nuxt/rollup.module.config.mjs index 991ea9c58fae..7dbe0155fe9a 100644 --- a/packages/nuxt/rollup.module.config.mjs +++ b/packages/nuxt/rollup.module.config.mjs @@ -1,26 +1,17 @@ import { readdirSync } from 'node:fs'; import { isAbsolute, join } from 'node:path'; -import esbuild from 'rollup-plugin-esbuild'; // The Nuxt module ships two kinds of output that live side by side in `build/module`: // - `module.mjs`: the module entry, bundled from `src/module.ts`. // - `runtime/**`: the files Nuxt injects into the consuming app, emitted one-to-one // (never bundled) because the app's own build re-processes them. -// This config replaces `@nuxt/module-builder` so the package builds with plain rollup + tsc +// This config replaces `@nuxt/module-builder` so the package builds with plain rolldown + tsc // and doesn't couple us to a build tool that consumes the TypeScript compiler API. // Anything that isn't a relative path is provided by the consuming app or Node at runtime // (this covers `@sentry/*`, `nuxt/app`, `#imports`, node builtins), so it stays external. const isExternal = id => !id.startsWith('.') && !isAbsolute(id) && !id.startsWith('\0'); -const transpile = esbuild({ - target: 'es2020', - // Don't read a per-package tsconfig; pin only what affects codegen. - tsconfig: false, - tsconfigRaw: { compilerOptions: { useDefineForClassFields: false } }, - sourceMap: false, -}); - function runtimeEntrypoints(dir = 'src/runtime', acc = []) { for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name); @@ -34,23 +25,27 @@ function runtimeEntrypoints(dir = 'src/runtime', acc = []) { return acc; } +// Don't read a per-package tsconfig; pin only what affects codegen. +const transpile = { tsconfig: false, transform: { target: 'es2020' } }; + export default [ { + ...transpile, input: 'src/module.ts', - output: { file: 'build/module/module.mjs', format: 'esm' }, + output: { file: 'build/module/module.mjs', format: 'esm', sourcemap: false }, external: isExternal, - plugins: [transpile], }, { + ...transpile, input: runtimeEntrypoints(), output: { dir: 'build/module/runtime', format: 'esm', + sourcemap: false, preserveModules: true, preserveModulesRoot: 'src/runtime', entryFileNames: '[name].js', }, external: isExternal, - plugins: [transpile], }, ]; diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index f9f56f10a29f..ade84ba7af2d 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -40,11 +40,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-opentelemetry-*.tgz", diff --git a/packages/profiling-node/package.json b/packages/profiling-node/package.json index 11845f0da407..02a916ccbf0a 100644 --- a/packages/profiling-node/package.json +++ b/packages/profiling-node/package.json @@ -39,10 +39,10 @@ "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "lint:fix": "oxlint . --fix --type-aware", "build": "pnpm run build:types && pnpm run build:transpile", - "build:transpile": "pnpm exec rollup -c rollup.npm.config.mjs", + "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm clean && pnpm run build", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:watch": "run-p build:transpile:watch", "build:tarball": "pnpm pack", "test:bundle": "node test-binaries.esbuild.js", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 8ecb1fc7ed3a..3c2290ca697e 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -85,12 +85,12 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core", "build:types:core": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-router-*.tgz", diff --git a/packages/react/package.json b/packages/react/package.json index c8212eee5e5f..42b6b8073a7c 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -91,11 +91,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts src/react-router.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-*.tgz", diff --git a/packages/remix/package.json b/packages/remix/package.json index c17460748d93..a95d66868c16 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -110,11 +110,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.server.ts src/index.client.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-remix-*.tgz", diff --git a/packages/remix/rollup.npm.config.mjs b/packages/remix/rollup.npm.config.mjs index 40b06766961c..1a1ad4fba91f 100644 --- a/packages/remix/rollup.npm.config.mjs +++ b/packages/remix/rollup.npm.config.mjs @@ -1,6 +1,4 @@ -/* eslint-disable import/no-named-as-default */ -import nodeResolve from '@rollup/plugin-node-resolve'; -import { defineConfig } from 'rollup'; +import { defineConfig } from 'rolldown'; import { makeBaseNPMConfig, makeNPMConfigVariants, makeOrchestrionLoader } from '@sentry-internal/rollup-utils'; // `external: /.*/` keeps the `remix` import a runtime resolution against the installed package. @@ -32,18 +30,11 @@ const v3ClientBundle = defineConfig({ // separate subscriber registries, and instrumentation would quietly do nothing. external: id => /diagnosticsChannelShim/.test(id) || id === 'remix' || id.startsWith('@remix-run/'), treeshake: { moduleSideEffects: false, propertyReadSideEffects: false }, - plugins: [nodeResolve({ browser: true, exportConditions: ['browser', 'import', 'default'] })], + platform: 'browser', + resolve: { conditionNames: ['browser', 'import', 'default'] }, // Emitted inside `build/esm/v3/`, not at `build/`: the one import it keeps is the relative path to // the channel shim, which only resolves from there. output: { file: 'build/esm/v3/client-bundle.js', format: 'esm' }, - onwarn(warning, warn) { - // `this` is undefined in the bundled output of some dependencies, and the graph has cycles. Both - // are harmless here and would otherwise bury real warnings. - if (warning.code === 'THIS_IS_UNDEFINED' || warning.code === 'CIRCULAR_DEPENDENCY') { - return; - } - warn(warning); - }, }); // We rely on esbuild's defaults for JSX (`jsx: 'transform'` = classic runtime, no diff --git a/packages/remix/src/cloudflare/index.ts b/packages/remix/src/cloudflare/index.ts index e012093aaf76..a7fa63ada474 100644 --- a/packages/remix/src/cloudflare/index.ts +++ b/packages/remix/src/cloudflare/index.ts @@ -11,7 +11,8 @@ export * from '@sentry/react'; export { captureRemixErrorBoundaryError } from '../client/errors'; export { withSentry } from '../client/performance'; -export { ErrorBoundary, browserTracingIntegration } from '../client'; +export { browserTracingIntegration } from '../client'; +export { ErrorBoundary } from '@sentry/react'; export { makeWrappedCreateRequestHandler, sentryHandleError }; export { generateSentryServerTimingHeader } from '../server/serverTimingTracePropagation'; diff --git a/packages/remix/src/index.server.ts b/packages/remix/src/index.server.ts index e40dd4978bb3..d5dbb1d9d5aa 100644 --- a/packages/remix/src/index.server.ts +++ b/packages/remix/src/index.server.ts @@ -1,5 +1,6 @@ export * from './server'; -export { captureRemixErrorBoundaryError, withSentry, ErrorBoundary, browserTracingIntegration } from './client'; +export { captureRemixErrorBoundaryError, withSentry, browserTracingIntegration } from './client'; +export { ErrorBoundary } from '@sentry/react'; export { createRemixRouteManifest } from './config/createRemixRouteManifest'; export type { CreateRemixRouteManifestOptions } from './config/createRemixRouteManifest'; diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index bb3ab0663a0e..52849b98859e 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -25,8 +25,8 @@ "sideEffects": false, "scripts": { "build": "run-p build:transpile build:types build:bundle", - "build:transpile": "rollup -c rollup.npm.config.mjs", - "build:bundle": "rollup -c rollup.bundle.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", + "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:bundle:watch", diff --git a/packages/replay-canvas/src/canvas.ts b/packages/replay-canvas/src/canvas.ts index 5f477d386324..14924e2782f7 100644 --- a/packages/replay-canvas/src/canvas.ts +++ b/packages/replay-canvas/src/canvas.ts @@ -1,7 +1,7 @@ import type { Integration, IntegrationFn } from '@sentry/core'; import { defineIntegration } from '@sentry/core'; import type { CanvasManagerInterface, CanvasManagerOptions } from '@sentry/replay'; -import { CanvasManager } from '@sentry/rrweb'; +import { CanvasManager } from '@sentry/rrweb/canvas-manager'; interface SnapshotOptions { skipRequestAnimationFrame?: boolean; diff --git a/packages/replay-canvas/test/canvas.test.ts b/packages/replay-canvas/test/canvas.test.ts index e02c284d2dac..ce75368f93c4 100644 --- a/packages/replay-canvas/test/canvas.test.ts +++ b/packages/replay-canvas/test/canvas.test.ts @@ -2,11 +2,11 @@ * @vitest-environment jsdom */ -import { CanvasManager } from '@sentry/rrweb'; +import { CanvasManager } from '@sentry/rrweb/canvas-manager'; import { beforeEach, expect, it, vi } from 'vitest'; import { _replayCanvasIntegration, replayCanvasIntegration } from '../src/canvas'; -vi.mock('@sentry/rrweb'); +vi.mock('@sentry/rrweb/canvas-manager'); beforeEach(() => { vi.clearAllMocks(); diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 3e2e9025981b..7ee227f62708 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -39,8 +39,8 @@ }, "scripts": { "build": "run-p build:transpile build:types build:bundle", - "build:transpile": "rollup -c rollup.npm.config.mjs", - "build:bundle": "rollup -c rollup.bundle.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", + "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:bundle:watch", diff --git a/packages/replay-internal/rollup.npm.config.mjs b/packages/replay-internal/rollup.npm.config.mjs index 4cf2b0263eac..47aa785d5ad1 100644 --- a/packages/replay-internal/rollup.npm.config.mjs +++ b/packages/replay-internal/rollup.npm.config.mjs @@ -1,5 +1,3 @@ -/* eslint-disable import/no-named-as-default */ -import nodeResolve from '@rollup/plugin-node-resolve'; import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; export default makeNPMConfigVariants( @@ -20,10 +18,12 @@ export default makeNPMConfigVariants( input: ['./src/worker-bundler.ts'], output: { file: `./build/npm/${format}/worker-bundler.js`, - strict: false, format, + minify: true, }, treeshake: false, - plugins: [nodeResolve()], + transform: { + target: 'es2020', + }, })), ); diff --git a/packages/replay-worker/package.json b/packages/replay-worker/package.json index 4786d75821dc..db0dd63e05c6 100644 --- a/packages/replay-worker/package.json +++ b/packages/replay-worker/package.json @@ -29,8 +29,8 @@ "private": true, "scripts": { "build": "run-p build:transpile build:types", - "build:transpile": "rollup -c rollup.worker.config.mjs", - "build:examples": "rollup -c rollup.examples.config.mjs", + "build:transpile": "rolldown -c rollup.worker.config.mjs", + "build:examples": "rolldown -c rollup.examples.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm run build", "build:watch": "run-p build:transpile:watch", @@ -57,6 +57,9 @@ "dependencies": { "fflate": "0.8.3" }, + "devDependencies": { + "@sentry-internal/rollup-utils": "11.12.0" + }, "engines": { "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" } diff --git a/packages/replay-worker/rollup.examples.config.mjs b/packages/replay-worker/rollup.examples.config.mjs index 7ca68e89556d..1067cf426eca 100644 --- a/packages/replay-worker/rollup.examples.config.mjs +++ b/packages/replay-worker/rollup.examples.config.mjs @@ -1,42 +1,35 @@ -import commonjs from '@rollup/plugin-commonjs'; -import resolve from '@rollup/plugin-node-resolve'; -import terser from '@rollup/plugin-terser'; -import { defineConfig } from 'rollup'; -import esbuild from 'rollup-plugin-esbuild'; -import { makeLicensePlugin } from '../../dev-packages/rollup-utils/plugins/index.mjs'; +import { plugins, treeShakePreset } from '@sentry-internal/rollup-utils'; +import { defineConfig } from 'rolldown'; -const licensePlugin = makeLicensePlugin('Sentry Replay Worker'); - -const esbuildPlugin = esbuild({ tsconfig: './tsconfig.json', target: 'es2020', sourceMap: false }); +const banner = plugins.makeBannerOptions('Sentry Replay Worker', process.env.npm_package_version); const config = defineConfig([ { input: ['./src/_worker.ts'], + tsconfig: './tsconfig.build.json', output: { file: './examples/worker.js', format: 'esm', + banner, + }, + transform: { + target: 'es2020', }, - treeshake: 'smallest', - plugins: [commonjs(), esbuildPlugin, resolve(), licensePlugin], + treeshake: treeShakePreset('smallest'), }, { input: ['./src/_worker.ts'], + tsconfig: './tsconfig.build.json', output: { file: './examples/worker.min.js', format: 'esm', + banner, + minify: true, + }, + transform: { + target: 'es2020', }, - treeshake: 'smallest', - plugins: [ - commonjs(), - esbuildPlugin, - resolve(), - terser({ - mangle: { - module: true, - }, - }), - licensePlugin, - ], + treeshake: treeShakePreset('smallest'), }, ]); diff --git a/packages/replay-worker/rollup.worker.config.mjs b/packages/replay-worker/rollup.worker.config.mjs index 36f18cb2a7e6..323772986beb 100644 --- a/packages/replay-worker/rollup.worker.config.mjs +++ b/packages/replay-worker/rollup.worker.config.mjs @@ -1,72 +1,66 @@ // inspired by https://justinribeiro.com/chronicle/2020/07/17/building-module-web-workers-for-cross-browser-compatibility-with-rollup/ -import commonjs from '@rollup/plugin-commonjs'; -import resolve from '@rollup/plugin-node-resolve'; -import terser from '@rollup/plugin-terser'; -import { defineConfig } from 'rollup'; -import esbuild from 'rollup-plugin-esbuild'; - -const esbuildPlugin = esbuild({ tsconfig: './tsconfig.json', target: 'es2020', sourceMap: false }); +import { treeShakePreset } from '@sentry-internal/rollup-utils'; +import { defineConfig } from 'rolldown'; +import { minifySync } from 'rolldown/utils'; const config = defineConfig([ { input: ['./src/index.ts'], - treeshake: 'smallest', + treeshake: treeShakePreset('smallest'), + tsconfig: './tsconfig.build.json', output: { dir: './build/esm', format: 'esm', + minify: true, + }, + transform: { + target: 'es2020', }, external: ['./worker'], - plugins: [ - esbuildPlugin, - terser({ - mangle: { - module: true, - }, - }), - ], }, { input: ['./src/_worker.ts'], + tsconfig: './tsconfig.build.json', output: { file: './build/esm/worker.ts', format: 'esm', + minify: true, + }, + treeshake: treeShakePreset('smallest'), + transform: { + target: 'es2020', }, - treeshake: 'smallest', plugins: [ - commonjs(), - esbuildPlugin, - resolve(), - terser({ - mangle: { - module: true, - }, - }), { name: 'worker-to-string', + // `output.minify` runs after `renderChunk`, so it only ever sees the wrapper below and + // leaves the worker inside it untouched - that shipped ~10 kB of unminified fflate in every + // Replay bundle. Minify here instead, before embedding. + // + // Embedded with `JSON.stringify` rather than a template literal because oxc's minifier + // emits string literals as backticks, which would terminate the literal early and silently + // produce an empty chunk. renderChunk(code) { - return `export default \`${code}\`;`; + const { code: minified } = minifySync('worker.js', code, { module: true }); + + return `export default ${JSON.stringify(minified)};`; }, }, ], }, { input: ['./src/_worker.ts'], + tsconfig: './tsconfig.build.json', output: { file: './build/esm/worker-bundler.js', format: 'esm', + minify: true, + }, + treeshake: treeShakePreset('smallest'), + transform: { + target: 'es2020', }, - treeshake: 'smallest', - plugins: [ - commonjs(), - esbuildPlugin, - resolve(), - terser({ - mangle: { - module: true, - }, - }), - ], }, ]); diff --git a/packages/replay-worker/tsconfig.build.json b/packages/replay-worker/tsconfig.build.json new file mode 100644 index 000000000000..24cce469ccc3 --- /dev/null +++ b/packages/replay-worker/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "esnext", + "lib": ["webworker", "scripthost"], + "esModuleInterop": true, + "target": "es2020", + "strictPropertyInitialization": false + }, + "include": ["src/**/*.ts"] +} diff --git a/packages/replay-worker/tsconfig.json b/packages/replay-worker/tsconfig.json index bfa37b859232..85dfc8da1d33 100644 --- a/packages/replay-worker/tsconfig.json +++ b/packages/replay-worker/tsconfig.json @@ -4,7 +4,10 @@ "lib": ["webworker", "scripthost"], "esModuleInterop": true, "target": "es2020", - "strictPropertyInitialization": false + "strictPropertyInitialization": false, + "inlineSourceMap": false, + "sourceMap": false, + "inlineSources": false }, "include": ["src/**/*.ts"] } diff --git a/packages/rollup-plugin/package.json b/packages/rollup-plugin/package.json index 20e4d90662b5..2b2f0b2241f1 100644 --- a/packages/rollup-plugin/package.json +++ b/packages/rollup-plugin/package.json @@ -36,11 +36,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-rollup-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/server-runtime-injection/package.json b/packages/server-runtime-injection/package.json index cf44f9bacc4d..7fa9b0c76d15 100644 --- a/packages/server-runtime-injection/package.json +++ b/packages/server-runtime-injection/package.json @@ -60,11 +60,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-server-runtime-injection-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/server-runtime-injection/rollup.npm.config.mjs b/packages/server-runtime-injection/rollup.npm.config.mjs index 49f2ddd2ba89..8257a4ca165a 100644 --- a/packages/server-runtime-injection/rollup.npm.config.mjs +++ b/packages/server-runtime-injection/rollup.npm.config.mjs @@ -1,9 +1,8 @@ import { builtinModules } from 'node:module'; import * as path from 'node:path'; -import commonjs from '@rollup/plugin-commonjs'; import license from 'rollup-plugin-license'; -import { defineConfig } from 'rollup'; -import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; +import { defineConfig } from 'rolldown'; +import { makeBaseNPMConfig, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; // The orchestrion runtime dependency chain (`@apm-js-collab/tracing-hooks` → // `@apm-js-collab/code-transformer` → meriyah/esquery/astring/…) is bundled into this package's @@ -25,30 +24,25 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollu // `SENTRY_INSTRUMENTATIONS`) stay external — the base config keeps them out of the bundle, so they // resolve from `node_modules` at runtime. // -// `requireReturnsDefault: 'auto'`: node-resolve prefers a dependency's ESM build even for CJS -// `require()`s inside the vendored graph. Default-export-only ESM (e.g. esquery) must then resolve -// to the default itself, not a `{ default }` namespace — CJS callers use it as -// `require('esquery').parse(...)`. -// -// `strictRequires: false`: the default `'auto'` wraps conditionally-required modules in lazy -// initializers exported as `__require` — an export name that downstream re-bundlers mishandle -// (Turbopack renames it, producing `.require is not a function` crashes in Next.js on Cloudflare). Hoisting is safe here: the vendored graph is closed (nothing -// optional/missing) and has no require cycles that depend on lazy evaluation. -const commonJSOptions = { transformMixedEsModules: true, requireReturnsDefault: 'auto', strictRequires: false }; -const commonJSPlugin = commonjs(commonJSOptions); - // Replace `debug` with `src/debug.ts`, which logs through the Sentry logger. `debug` and the // `supports-color` it loads read `process.env` at import time, which throws on Deno without env -// permission. `order: 'pre'` because the base config's node-resolve plugin sorts ahead of -// package-specific plugins and would otherwise resolve `debug` first. +// permission. `order: 'pre'` so it resolves `debug` before the base config's resolution does. +// The vendored callers `require('debug')`, and rolldown hands a `require()` of an ES module its +// namespace (`{ default }`), so a CJS module in between re-exports the default as `module.exports`. +const DEBUG_SHIM_ID = '\0debug-shim'; const debugShim = { name: 'debug-shim', resolveId: { order: 'pre', handler(source) { - return source === 'debug' ? path.join(import.meta.dirname, 'src/debug.ts') : null; + return source === 'debug' ? DEBUG_SHIM_ID : null; }, }, + load(id) { + return id === DEBUG_SHIM_ID + ? `module.exports = require(${JSON.stringify(path.join(import.meta.dirname, 'src/debug.ts'))}).default;` + : null; + }, }; // `ModulePatch` reads `process.env.TRACING_DUMP` after each module it transforms. On Deno without @@ -71,7 +65,7 @@ const guardTracingDump = { }, }; -// Bundling files from the repo-root `node_modules` moves rollup's common source ancestor up to the +// Bundling files from the repo-root `node_modules` moves the common source ancestor up to the // repo root, so `preserveModules` names our own files `packages/server-runtime-injection/src/...` — // strip that prefix to keep the `build/cjs/register.js` layout the `exports` map points at. A vendored // dependency is named by its path after the last `node_modules/`, because pnpm installs some of them @@ -82,7 +76,7 @@ const sanitizedFileNames = info => // The vendored dependencies (see above) are third-party code redistributed inside this package's // published `build/`, so their licenses require us to carry each one's copyright/permission notice -// (and, for Apache-2.0 deps like `@apm-js-collab/*`, the upstream NOTICE). Rollup strips per-file +// (and, for Apache-2.0 deps like `@apm-js-collab/*`, the upstream NOTICE). Bundling strips per-file // banners, so instead we aggregate them into a single `build/THIRD-PARTY-LICENSES.txt`. const thirdPartyLicensePlugin = license({ thirdParty: { @@ -93,9 +87,14 @@ const thirdPartyLicensePlugin = license({ }, }); +// Split so a downstream bundler that inlines this package can drop the parse/query/generate/sourcemap +// libraries. They are only reached through the `code-transformer` factory, whose failures surface as +// the "bundled into your application" warning in `register.ts` instead of a crash. +const SPLITTABLE_VENDORED = /vendored\/(meriyah|astring|source-map|esquery)\//; + const orchestrionRuntimeHooks = [ // The side-effecting `--import` entry SDKs reference via a `--import` flag. We pass it through - // rollup only to copy it to `build/import-hook.mjs` at the path the package.json `exports` map + // rolldown only to copy it to `build/import-hook.mjs` at the path the package.json `exports` map // expects; `external: /.*/` keeps every import (`@sentry/server-runtime-injection/register`) a // runtime resolution against the installed package. defineConfig({ @@ -116,15 +115,18 @@ export default [ // `import` condition, so the `build/cjs` copy is unused. entrypoints: ['src/register.ts', 'src/hook.mjs'], packageSpecificConfig: { - plugins: [debugShim, guardTracingDump, commonJSPlugin, thirdPartyLicensePlugin], + plugins: [ + debugShim, + guardTracingDump, + plugins.makeEsqueryCjsAliasPlugin(), + thirdPartyLicensePlugin, + plugins.makeBuiltinRequireShimPlugin(), + plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), + ], output: { exports: 'named', preserveModules: true, entryFileNames: sanitizedFileNames, - // The commonjs-converted vendored dependencies import Node builtins as default imports - // (`require('path')` → default import of `path`), and builtins have no `.default` in CJS — - // so builtins need `'default'` interop (the module itself is the default export). - interop: id => (id && (id.startsWith('node:') || builtinModules.includes(id)) ? 'default' : 'esModule'), // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which Deno // rejects and vite-node (Node 26) misresolves as a relative path. Emit them `node:`-prefixed. paths: Object.fromEntries(builtinModules.map(m => [m, `node:${m}`])), diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 4f38b750f909..0b8481af2e02 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -117,11 +117,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-server-utils-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/server-utils/rollup.npm.config.mjs b/packages/server-utils/rollup.npm.config.mjs index 74f172ec5215..cd81297a9da3 100644 --- a/packages/server-utils/rollup.npm.config.mjs +++ b/packages/server-utils/rollup.npm.config.mjs @@ -1,7 +1,6 @@ import { builtinModules } from 'node:module'; -import commonjs from '@rollup/plugin-commonjs'; import license from 'rollup-plugin-license'; -import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; +import { makeBaseNPMConfig, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; // The orchestrion build-time bundler-plugin chain (`@apm-js-collab/code-transformer-bundler-plugins` // → `@apm-js-collab/code-transformer` → meriyah/esquery/astring/…) is bundled into this package's @@ -19,50 +18,8 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollu // build-time and runtime transforms always ship the same `code-transformer` version, and so this // package has no `@apm-js-collab/*` install footprint at all. // -// `requireReturnsDefault: 'auto'`: node-resolve prefers a dependency's ESM build even for CJS -// `require()`s inside the vendored graph. Default-export-only ESM (e.g. esquery) must then resolve -// to the default itself, not a `{ default }` namespace — CJS callers use it as -// `require('esquery').parse(...)`. -// -// `strictRequires: false`: the default `'auto'` wraps conditionally-required modules (e.g. -// `debug`'s browser/node split) in lazy initializers exported as `__require` — an export name that -// downstream re-bundlers mishandle (Turbopack renames it, producing `.require is not a function` -// crashes in Next.js on Cloudflare). Hoisting is safe here: the vendored graph is closed (nothing -// optional/missing) and has no require cycles that depend on lazy evaluation. -const commonJSOptions = { transformMixedEsModules: true, requireReturnsDefault: 'auto', strictRequires: false }; -const commonJSPlugin = commonjs(commonJSOptions); - -// Always vendor `debug`'s Node build. Its default entry picks browser vs node at require time, -// which drags the browser build into this server-only bundle — and, hoisted by -// `strictRequires: false`, the browser build's storage detection probes `localStorage` at import -// time, which on Node >= 26 emits an ExperimentalWarning that pollutes stderr and console -// breadcrumbs in every user app. `order: 'pre'` because the base config's node-resolve plugin -// sorts ahead of package-specific plugins and would otherwise resolve `debug` first. -const debugNodeAlias = { - name: 'debug-node-alias', - resolveId: { - order: 'pre', - handler(source, importer) { - return source === 'debug' ? this.resolve('debug/src/node.js', importer, { skipSelf: true }) : null; - }, - }, -}; - -// This package only runs in Node, but rollup's default CJS replacement for `import.meta.url` -// picks browser behavior whenever a `document` global exists, and jsdom/happy-dom define -// `document` while tests run in Node. Always emit the unconditional Node form instead. -const importMetaUrlNodeShim = { - name: 'import-meta-url-node-shim', - resolveImportMeta(property, { format }) { - if (property === 'url' && format === 'cjs') { - return "require('node:url').pathToFileURL(__filename).href"; - } - return null; - }, -}; - -// Bundling files from the repo-root `node_modules` moves rollup's common source ancestor up to the -// repo root, so `preserveModules` names our own files `packages/server-utils/src/...` — strip that +// Bundling files from the repo-root `node_modules` moves the common source ancestor up to the repo +// root, so `preserveModules` names our own files `packages/server-utils/src/...` — strip that // prefix to keep the `build/cjs/index.js` layout the `exports` map points at. A vendored dependency // is named by its path after the last `node_modules/`, because pnpm installs some of them in nested // or `.pnpm` folders. And npm never packs `node_modules` directories, so the vendored dependencies @@ -76,7 +33,9 @@ const sanitizedFileNames = info => // banners, so instead we aggregate them into a single `build/THIRD-PARTY-LICENSES.txt`. The default // template emits each dependency's license text AND its NOTICE text, which covers the MIT/ISC/BSD // notice requirement and the Apache-2.0 §4(d) NOTICE requirement. Only bundled (non-external) -// packages are collected — our own `@sentry/*` deps stay external and are excluded. +// packages are collected — our own `@sentry/*` deps stay external and are excluded. The plugin only +// uses hooks rolldown implements (`renderChunk` / `generateBundle` plus `this.getModuleIds()`), so +// it keeps working unchanged on rolldown. // // Both the CJS and ESM build variants run this and bundle the same dependency set, so each writes // the same file; the last write wins and the content is identical. @@ -89,6 +48,12 @@ const thirdPartyLicensePlugin = license({ }, }); +// Only the parse/query/generate/sourcemap libraries are split. They are reached exclusively through +// the lazily-invoked `code-transformer` factory, which is called inside a try/catch, so a consumer +// that drops them degrades to "no channel injection" instead of throwing. Everything else (notably +// `debug`, whose export is called at module-evaluation time) must stay non-droppable. +const SPLITTABLE_VENDORED = /vendored\/(meriyah|astring|source-map|esquery)\//; + export default [ ...makeNPMConfigVariants( makeBaseNPMConfig({ @@ -111,18 +76,19 @@ export default [ 'src/orchestrion/bundler/bun.ts', ], packageSpecificConfig: { - plugins: [debugNodeAlias, commonJSPlugin, importMetaUrlNodeShim, thirdPartyLicensePlugin], + plugins: [ + plugins.makeDebugNodeAliasPlugin(), + plugins.makeEsqueryCjsAliasPlugin(), + thirdPartyLicensePlugin, + plugins.makeBuiltinRequireShimPlugin(), + plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), + ], output: { // set exports to 'named' or 'auto' so that rollup doesn't warn exports: 'named', // set preserveModules to true because we don't want to bundle everything into one file. preserveModules: true, entryFileNames: sanitizedFileNames, - // The repo default `interop: 'esModule'` dereferences `.default` on default imports of - // externals. The commonjs-converted vendored dependencies import Node builtins that way - // (e.g. `require('path')` → default import of `path`), and builtins have no `.default` in - // CJS — so builtins need `'default'` interop (the module itself is the default export). - interop: id => (id && (id.startsWith('node:') || builtinModules.includes(id)) ? 'default' : 'esModule'), // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which // Deno rejects outright and vite-node (Node 26) misresolves as a relative path. Emit them // `node:`-prefixed. diff --git a/packages/solid/package.json b/packages/solid/package.json index 7f18e19a00a5..feba8ad958da 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -86,13 +86,13 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core build:types:routers", "build:types:core": "tsc -p tsconfig.types.json", "build:types:routers": "tsc -p tsconfig.routers-types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts src/solidrouter.ts src/tanstackrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-solid-*.tgz ./*.d.ts ./*.d.ts.map", diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 8af383aeca29..f6a5a45db176 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -112,13 +112,13 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core build:types:subexports", "build:types:core": "tsc -p tsconfig.types.json", "build:types:subexports": "tsc -p tsconfig.subexports-types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts src/solidrouter.client.ts src/solidrouter.server.ts src/solidrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-solidstart-*.tgz ./*.d.ts ./*.d.ts.map ./client ./server", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 61b3407e0d08..92bc2f35b584 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -50,11 +50,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-svelte-*.tgz", diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index f026ed28ecac..7e7b9b592573 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -96,11 +96,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-sveltekit-*.tgz", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 4d37a6c2b220..72be6bceca15 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -69,7 +69,7 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index 38e8a8cdee21..d6e3e219e5cc 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -44,11 +44,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-vercel-edge-*.tgz", diff --git a/packages/vercel-edge/rollup.npm.config.mjs b/packages/vercel-edge/rollup.npm.config.mjs index ae01f43703d0..c0daf542b1e7 100644 --- a/packages/vercel-edge/rollup.npm.config.mjs +++ b/packages/vercel-edge/rollup.npm.config.mjs @@ -1,5 +1,5 @@ -import replace from '@rollup/plugin-replace'; -import { makeBaseNPMConfig, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; +import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; +import { replacePlugin } from 'rolldown/plugins'; export default makeNPMConfigVariants( makeBaseNPMConfig({ @@ -11,14 +11,14 @@ export default makeNPMConfigVariants( preserveModules: false, }, plugins: [ - plugins.makeCommonJSPlugin({ transformMixedEsModules: true }), // Needed because various modules in the OTEL toolchain use CJS (require-in-the-middle, shimmer, etc..) - plugins.makeJsonPlugin(), // Needed because `require-in-the-middle` imports json via require - replace({ - preventAssignment: true, - values: { + replacePlugin( + { 'process.argv0': JSON.stringify(''), // needed because otel relies on process.argv0 for the default service name, but that api is not available in the edge runtime. }, - }), + { + preventAssignment: true, + }, + ), { // This plugin is needed because otel imports `performance` from `perf_hooks` and also uses it via the `performance` global. // It also imports `inspect` and `promisify` from node's `util` which are not available in the edge runtime so we need to define a polyfill. diff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.json index a4ef92c17501..0a4a7f8ad4f8 100644 --- a/packages/vite-plugin/package.json +++ b/packages/vite-plugin/package.json @@ -35,11 +35,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-vite-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/vue/package.json b/packages/vue/package.json index df142fabed23..a56781b71fe1 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -69,13 +69,13 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "run-p build:transpile build:types", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core build:types:router", "build:types:core": "tsc -p tsconfig.types.json", "build:types:router": "tsc -p tsconfig.router-types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "circularDepCheck": "madge --circular src/index.ts src/tanstackrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-vue-*.tgz", diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 4efc34984d58..425d0597a608 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -40,14 +40,14 @@ }, "scripts": { "build": "run-p build:transpile build:bundle build:types", - "build:bundle": "rollup --config rollup.bundle.config.mjs", + "build:bundle": "rolldown --config rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:bundle:watch": "rollup --config rollup.bundle.config.mjs --watch", + "build:bundle:watch": "rolldown --config rollup.bundle.config.mjs --watch", "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 0bb38704aba4..207a41039015 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -40,11 +40,11 @@ "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", - "build:transpile": "rollup -c rollup.npm.config.mjs", + "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rollup -c rollup.npm.config.mjs --watch", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-webpack-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 53e906c250c9..cf346db61233 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -174,21 +174,6 @@ importers: .: devDependencies: - '@rollup/plugin-commonjs': - specifier: ^25.0.7 - version: 25.0.8(rollup@4.62.3) - '@rollup/plugin-json': - specifier: ^6.1.0 - version: 6.1.0(rollup@4.62.3) - '@rollup/plugin-node-resolve': - specifier: ^16.0.3 - version: 16.0.3(rollup@4.62.3) - '@rollup/plugin-replace': - specifier: ^5.0.5 - version: 5.0.7(rollup@4.62.3) - '@rollup/plugin-terser': - specifier: ^1.0.2 - version: 1.0.2(rollup@4.62.3) '@sentry-internal/node-integration-tests': specifier: workspace:* version: link:dev-packages/node-integration-tests @@ -249,12 +234,12 @@ importers: oxlint-tsgolint: specifier: ^7.0.2004 version: 7.0.2004 + rolldown: + specifier: ^1.3.2 + version: 1.3.2 rollup: specifier: ^4.60.3 version: 4.62.3 - rollup-plugin-esbuild: - specifier: ^6.2.1 - version: 6.2.1(esbuild@0.28.1)(rollup@4.62.3)(supports-color@10.0.0) rollup-plugin-license: specifier: ^3.7.1 version: 3.7.1(picomatch@4.0.7)(rollup@4.62.3) @@ -1181,7 +1166,7 @@ importers: version: 20.19.43 rolldown: specifier: ^1.0.0 - version: 1.2.16 + version: 1.3.2 vite: specifier: ^8.3.6 version: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@8.1.1))(sass@1.72.0)(stylus@0.59.0(supports-color@8.1.1))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) @@ -1739,7 +1724,7 @@ importers: dependencies: '@nuxt/kit': specifier: ^4.6.0 - version: 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.152.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + version: 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.152.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) '@sentry/browser': specifier: 11.12.0 version: link:../browser @@ -1773,7 +1758,7 @@ importers: version: 4.20260519.1 '@nuxt/nitro-server': specifier: ^3.21.11 - version: 3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + version: 3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) '@nuxt/schema': specifier: ^3.21.11 version: 3.21.11 @@ -1791,13 +1776,13 @@ importers: version: 3.0.260311-beta(@azure/storage-blob@12.31.0(supports-color@10.0.0))(chokidar@5.0.0)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(lru-cache@11.4.0)(miniflare@4.20260426.0)(mongodb@7.1.0(@aws-sdk/credential-providers@3.983.0)(socks@2.8.7))(mysql2@3.23.3(@types/node@20.19.43))(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) nitropack: specifier: ^2.13.4 - version: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + version: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) nuxi: specifier: ^3.25.1 version: 3.25.1 nuxt: specifier: 3.21.11 - version: 3.21.11(724864ca76bc73825b6249c96f34efd5) + version: 3.21.11(054c80f87937459bdf21125c1fade606) unstorage: specifier: ^1.17.5 version: 1.17.5(@azure/storage-blob@12.31.0(supports-color@10.0.0))(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.11.1(supports-color@10.0.0)) @@ -2090,6 +2075,10 @@ importers: fflate: specifier: 0.8.3 version: 0.8.3 + devDependencies: + '@sentry-internal/rollup-utils': + specifier: 11.12.0 + version: link:../../dev-packages/rollup-utils packages/rollup-plugin: dependencies: @@ -2250,7 +2239,7 @@ importers: version: 1.0.0(solid-js@1.9.18) '@solidjs/start': specifier: ^1.3.2 - version: 1.3.2(1649c7f604f12e5f9af57e229fd2f3f2) + version: 1.3.2(904a000150746b01a4f8678acf4cebc4) '@solidjs/testing-library': specifier: 0.8.5 version: 0.8.5(@solidjs/router@1.0.0(solid-js@1.9.18))(solid-js@1.9.18) @@ -2265,13 +2254,13 @@ importers: version: 20.19.43 nitropack: specifier: ^2.13.4 - version: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + version: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) solid-js: specifier: ^1.9.18 version: 1.9.18 vinxi: specifier: ^0.5.11 - version: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) + version: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) vite: specifier: ^8.3.6 version: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) @@ -4481,15 +4470,24 @@ packages: '@emnapi/core@1.4.5': resolution: {integrity: sha512-XsLw1dEOpkSX/WucdqUhPWP7hDxSvZiY+fsUC14h+FtQ2Ifni4znbBt8punRX+Uj2JG/uDb8nEHVKvrVlvdZ5Q==} + '@emnapi/core@2.0.0-beta.2': + resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==} + '@emnapi/runtime@1.11.3': resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} '@emnapi/runtime@1.4.5': resolution: {integrity: sha512-++LApOtY0pEEz1zrd9vy1/zXVaVJJ/EbAF3u0fXIzPJEDtnITsBGbbK0EkM72amhl/R5b+5xx0Y/QhcVOpuulg==} + '@emnapi/runtime@2.0.0-beta.2': + resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==} + '@emnapi/wasi-threads@1.0.4': resolution: {integrity: sha512-PJR+bOmMOPH8AtcTGAyYNiuJ3/Fcoj2XN/gBEWzDIKh254XO+mM9XoXHk5GNEhodxeMznbg7BlRojVbKN+gC6g==} + '@emnapi/wasi-threads@2.2.0': + resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} + '@es-joy/jsdoccomment@0.50.2': resolution: {integrity: sha512-YAdE/IJSpwbOTiaURNCKECdAwqrJuFiZhylmesBcIRawtYKnBR2wxPhoIewMg+Yu+QuYvHfJNReWpoxGBKOChA==} engines: {node: '>=18'} @@ -6093,6 +6091,13 @@ packages: '@napi-rs/wasm-runtime@0.2.4': resolution: {integrity: sha512-9zESzOO5aDByvhIAsOy9TbpZ0Ur2AJbUI7UT73kcUTS2mxAMHOBaa1st/jAymNoCtvrit99kkzT1FZuXVcgfIQ==} + '@napi-rs/wasm-runtime@1.2.6': + resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 + '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + '@neondatabase/serverless@1.2.0': resolution: {integrity: sha512-tnaqgixUengZQNd9ZrS3ytQfamJzLKY8QxgqWQTNHHtB+KrFQWk77JTbbpg4RD+J3qE4eO2lVytvGDX5Kj6FdQ==} engines: {node: '>=19.0.0'} @@ -6854,6 +6859,9 @@ packages: '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + '@oxc-project/types@0.158.0': + resolution: {integrity: sha512-xZ66qA4WmLbTLlxH3mqMd8f9UKbaOzOT0ATwFf4DH/14pMgpUrtqtjyYzOQmgfl2a0iRAAMbQ9G1th/67jRzGw==} + '@oxc-transform/binding-android-arm-eabi@0.143.0': resolution: {integrity: sha512-Rufrk7btlzkIAofJyrm3COzSrn4iNYOnHNYOahBDQly/PgleJv6QIVCHsPTqC6qfX/EJNoAeNshALvVfKSTY5A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7712,36 +7720,72 @@ packages: cpu: [arm] os: [android] + '@rolldown/binding-android-arm-eabi@1.3.2': + resolution: {integrity: sha512-kqR2xcygEx3WwDY69LsKeyf7SVmx4yzMtKZRknyaHieVJdRvvnAM97L0Gq6tUFc9T2YXcW/Ghij2+Um6He0LTw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + '@rolldown/binding-android-arm64@1.2.16': resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] + '@rolldown/binding-android-arm64@1.3.2': + resolution: {integrity: sha512-gXM4GAAvvIZA7qUuSCQS+Zz91H2fagKa5MNppUdjzysJ8LXMWm9D/gQj4nfOKo6okquDQ5pkjsuo2SUMXNW0Rw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + '@rolldown/binding-darwin-arm64@1.2.16': resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] + '@rolldown/binding-darwin-arm64@1.3.2': + resolution: {integrity: sha512-OBs5hp3W+LwMEUmDMMMnu08ncG0t6DDgnFU+6TAucKtAfNgerYLZSr2jtREKb/JuPQ1J7bJnWIgKKkxvjuAw1g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + '@rolldown/binding-darwin-x64@1.2.16': resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] + '@rolldown/binding-darwin-x64@1.3.2': + resolution: {integrity: sha512-X0VGYd4v/gdjfa/IP6uHuMhofPoUDYvK/byk3bC0jQ1pKKgt6RZ4B4puMqP0AHkjmIHAsxA471mM6AxZ39IaTA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + '@rolldown/binding-freebsd-x64@1.2.16': resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] + '@rolldown/binding-freebsd-x64@1.3.2': + resolution: {integrity: sha512-mr04K4cp9J/fj9fknrX8e4QvI/V48Sp+4v64PoLwhoirIH8b8L8EBrF/0bTjV1It2IL91hoNG13GblnWLglkxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] + '@rolldown/binding-linux-arm-gnueabihf@1.3.2': + resolution: {integrity: sha512-VgWy02HU9Tiy6tU8U+kF3Fd4TQwTNdIBvs2MlgViP1ksMtAnQQTIPAj0ZsJzIQXKIOugqQSpqxQgELJ3fkuL5w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + '@rolldown/binding-linux-arm64-gnu@1.2.16': resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7749,6 +7793,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-arm64-gnu@1.3.2': + resolution: {integrity: sha512-0wloJFYqV844gv6boiERbHpErxbxHbmlgnMX5VxP1Ux+DLBqGrUOn0cIpBmCZEcTITes3QUelxya4u8c9ziQvQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-arm64-musl@1.2.16': resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7756,6 +7807,13 @@ packages: os: [linux] libc: [musl] + '@rolldown/binding-linux-arm64-musl@1.3.2': + resolution: {integrity: sha512-Kys8wgFQy8H8vua0MNpC0akMBFoNO8455RHk2yycBM0iayMIAtVAL6xmV9TWAkehFgrrlImTL2fZdX5LXfYtAA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + '@rolldown/binding-linux-ppc64-gnu@1.2.16': resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7763,6 +7821,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-ppc64-gnu@1.3.2': + resolution: {integrity: sha512-L8eej7+/StRxUHHOPsOVl7Fzx/3tumuGB4hGQZKT73xRI16KZhaSJr0gi3C3WBjNRxeJRKKps2UD4lQukP+oBw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-s390x-gnu@1.2.16': resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7770,6 +7835,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-s390x-gnu@1.3.2': + resolution: {integrity: sha512-MV5CEb/nV8neQOj7l6945q1vy62HXtWO8zPDvfySPusoUzdBoLoJ/DfXXwaYThGTXZCniF+5bCf253WTPPK7Yw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-x64-gnu@1.2.16': resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7777,6 +7849,13 @@ packages: os: [linux] libc: [glibc] + '@rolldown/binding-linux-x64-gnu@1.3.2': + resolution: {integrity: sha512-3qssvvVvkwQookZ1/1avlKWc5orAR85vgKdzDd5noZS8nnHiI/ejOAEt0xfNYvtBBF7/DZmP8dANWkRBJVOBCA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + '@rolldown/binding-linux-x64-musl@1.2.16': resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7784,24 +7863,54 @@ packages: os: [linux] libc: [musl] + '@rolldown/binding-linux-x64-musl@1.3.2': + resolution: {integrity: sha512-rJqoFTm/bCZFKKgaT4NzWn/TuJkFDToZ/rzYFnYVBL28jH1nIfg6snx2mDri30nal9H+wcYfKpoPR9jrMQgQQg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + '@rolldown/binding-openharmony-arm64@1.2.16': resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] + '@rolldown/binding-openharmony-arm64@1.3.2': + resolution: {integrity: sha512-ozdbCjHfh0N//wJNExjJlSlcDaeIKo8k1ktzkLUyESr2Gu/Qw7nBYxKe3jgtoaxda570vg10WdYosre82263hQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.3.2': + resolution: {integrity: sha512-p5VA6Vk/2cXZPVWf+dDbuE0dkhrcoAo6pISTJmzUnsSdQqNJdusyR8lZgHku095+r27zrYISNLZnJoqrcePW0A==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + cpu: [wasm32] + '@rolldown/binding-win32-arm64-msvc@1.2.16': resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] + '@rolldown/binding-win32-arm64-msvc@1.3.2': + resolution: {integrity: sha512-XDb2U14Orf4r76SwzvJ7avePL00w4gHBmi1Ig4B/itYFEUTmYMNDHVU0dcYuBa0LgNBqyREoJOrQKxQlyYJA7A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + '@rolldown/binding-win32-x64-msvc@1.2.16': resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] + '@rolldown/binding-win32-x64-msvc@1.3.2': + resolution: {integrity: sha512-lEsKzKJqIUDZVCBhS4lkZuyQUhV1oRg5UHkI72qlOAqJn7qEXcoVdTridFS7PHNWdZknBl95EAF/4P1Xv0K1eQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} @@ -7827,15 +7936,6 @@ packages: rollup: optional: true - '@rollup/plugin-commonjs@25.0.8': - resolution: {integrity: sha512-ZEZWTK5n6Qde0to4vS9Mr5x/0UZoqCxPVR9KRUjU4kA2sO7GEUn1fop0DAwpO6z0Nw/kJON9bDmSxdWxO/TT1A==} - engines: {node: '>=14.0.0'} - peerDependencies: - rollup: ^2.68.0||^3.0.0||^4.0.0 - peerDependenciesMeta: - rollup: - optional: true - '@rollup/plugin-commonjs@28.0.1': resolution: {integrity: sha512-+tNWdlWKbpB3WgBN7ijjYkq9X5uhjmcvyjEght4NmH5fAU++zfQzAJ6wumLS+dNcvwEZhKx2Z+skY8m7v0wGSA==} engines: {node: '>=16.0.0 || 14 >= 14.17'} @@ -7892,15 +7992,6 @@ packages: rollup: optional: true - '@rollup/plugin-replace@5.0.7': - resolution: {integrity: sha512-PqxSfuorkHz/SPpyngLyg5GCEkOcee9M1bkxiVDr41Pd61mqP1PLOoDPbpl44SB2mQGKwV/In74gqQmGITOhEQ==} - engines: {node: '>=14.0.0'} - peerDependencies: - rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 - peerDependenciesMeta: - rollup: - optional: true - '@rollup/plugin-replace@6.0.3': resolution: {integrity: sha512-J4RZarRvQAm5IF0/LwUUg+obsm+xZhYnbMXmXROyoSE1ATJe3oXSb9L5MMppdxP2ylNSjv6zFBwKYjcKMucVfA==} engines: {node: '>=14.0.0'} @@ -8636,6 +8727,9 @@ packages: resolution: {integrity: sha512-w071DSzP94YfN6XiWhOxnLpYT3uqtxJBDYdh6Jdjzt+Ce6DNspJsPQgpC7rbts/B8tEkq0LHoYuIF/O5Jh5rPg==} engines: {node: '>=18'} + '@tybys/wasm-util@0.10.4': + resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} + '@tybys/wasm-util@0.9.0': resolution: {integrity: sha512-6+7nlbMVX/PVDCwaIQ8nTOPveOcFLSt8GcXdx8hD0bt39uWxYT88uXzqTd4fTvqta7oeUJqudepapKNt2DYJFw==} @@ -12411,9 +12505,6 @@ packages: resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} engines: {node: '>= 0.4'} - get-tsconfig@4.14.0: - resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} - getopts@2.3.0: resolution: {integrity: sha512-5eDf9fuSXwxBL6q5HX+dhDj+dslFGWzU5thZ9kNKUkcPtaPdatmUFKwHFrLb/uf/WpA4BHET+AX3Scl56cAjpA==} @@ -16543,9 +16634,6 @@ packages: resolve-pathname@2.2.0: resolution: {integrity: sha512-bAFz9ld18RzJfddgrO2e/0S2O81710++chRMUxHjXOYKF6jTAMrUNZrEZ1PvV0zlhfjidm08iRPdTLPno1FuRg==} - resolve-pkg-maps@1.0.0: - resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} - resolve-url-loader@5.0.0: resolution: {integrity: sha512-uZtduh8/8srhBoMx//5bwqjQ+rfYOUq8zC9NrMUGtjBiGTtFJM42s58/36+hTqeqINcnYe08Nj3LkK9lW4N8Xg==} engines: {node: '>=12'} @@ -16621,18 +16709,16 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rolldown@1.3.2: + resolution: {integrity: sha512-EFHqbVkXiYZA6akmYm2bvJhNbEGdUwAResRhYwl/BO8QhB5KxsG+t3RVHJSIOy5jBEb0XCACvrIGnnl6Z8sMGA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + rollup-plugin-copy-assets@2.0.3: resolution: {integrity: sha512-ETShhQGb9SoiwcNrvb3BhUNSGR89Jao0+XxxfzzLW1YsUzx8+rMO4z9oqWWmo6OHUmfNQRvqRj0cAyPkS9lN9w==} peerDependencies: rollup: '>=1.1.2' - rollup-plugin-esbuild@6.2.1: - resolution: {integrity: sha512-jTNOMGoMRhs0JuueJrJqbW8tOwxumaWYq+V5i+PD+8ecSCVkuX27tGW7BXqDgoULQ55rO7IdNxPcnsWtshz3AA==} - engines: {node: '>=14.18.0'} - peerDependencies: - esbuild: '>=0.18.0' - rollup: ^1.20.0 || ^2.0.0 || ^3.0.0 || ^4.0.0 - rollup-plugin-license@3.7.1: resolution: {integrity: sha512-FcGXUbAmPvRSLxjVdjp/r/MUtKBlttVQd+ApUyvKfREnsoAfAZA6Ic2fE1Tz4RL0f9XqEQU9UIRNUMdtQtliDw==} engines: {node: '>=14.0.0'} @@ -18100,10 +18186,6 @@ packages: resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} engines: {node: '>= 0.8'} - unplugin-utils@0.2.5: - resolution: {integrity: sha512-gwXJnPRewT4rT7sBi/IvxKTjsms7jX7QIDLOClApuZwR49SXbrB1z2NLUZ+vDHyqCj/n58OzRRqaW+B8OZi8vg==} - engines: {node: '>=18.12.0'} - unplugin-utils@0.3.2: resolution: {integrity: sha512-xVToRh2CTmLk2HnEG7ac4rl1MJTT3RFkpS8B++/SnB0kXvuaavD+n3m/vrzyWQOdJNSZQACnbz01pnppbwV5BA==} engines: {node: '>=20.19.0'} @@ -23072,17 +23154,17 @@ snapshots: '@discoveryjs/json-ext@0.5.7': {} - '@dxup/nuxt@0.5.6(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(esbuild@0.28.1)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': + '@dxup/nuxt@0.5.6(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(esbuild@0.28.1)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': dependencies: '@dxup/unimport': 0.1.2 - '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) '@vue/compiler-dom': 3.5.44 chokidar: 5.0.0 knitwork: 1.3.0 magic-string: 1.1.0 pathe: 2.0.3 tinyglobby: 0.2.17 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) transitivePeerDependencies: - '@farmfe/core' - '@nuxt/schema' @@ -23342,6 +23424,12 @@ snapshots: '@emnapi/wasi-threads': 1.0.4 tslib: 2.8.1 + '@emnapi/core@2.0.0-beta.2': + dependencies: + '@emnapi/wasi-threads': 2.2.0 + tslib: 2.8.1 + optional: true + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 @@ -23351,10 +23439,20 @@ snapshots: dependencies: tslib: 2.8.1 + '@emnapi/runtime@2.0.0-beta.2': + dependencies: + tslib: 2.8.1 + optional: true + '@emnapi/wasi-threads@1.0.4': dependencies: tslib: 2.8.1 + '@emnapi/wasi-threads@2.2.0': + dependencies: + tslib: 2.8.1 + optional: true + '@es-joy/jsdoccomment@0.50.2': dependencies: '@types/estree': 1.0.9 @@ -24717,6 +24815,13 @@ snapshots: '@emnapi/runtime': 1.4.5 '@tybys/wasm-util': 0.9.0 + '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@tybys/wasm-util': 0.10.4 + optional: true + '@neondatabase/serverless@1.2.0': {} '@nestjs/common@10.4.22(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@10.0.0)': @@ -24885,9 +24990,9 @@ snapshots: '@nuxt/devalue@2.0.2': {} - '@nuxt/devtools-kit@3.4.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': + '@nuxt/devtools-kit@3.4.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))': dependencies: - '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) execa: 8.0.1 vite: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) transitivePeerDependencies: @@ -24913,11 +25018,11 @@ snapshots: pkg-types: 2.4.0 semver: 7.8.5 - '@nuxt/devtools@3.4.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@nuxt/schema@3.21.11)(confbox@0.2.4)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2))': + '@nuxt/devtools@3.4.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@nuxt/schema@3.21.11)(confbox@0.2.4)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2))': dependencies: - '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@nuxt/devtools-kit': 3.4.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@nuxt/devtools-wizard': 3.4.4 - '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) '@vue/devtools-core': 8.2.1(vue@3.5.44(typescript@7.0.2)) '@vue/devtools-kit': 8.2.1 birpc: 4.2.0 @@ -24945,7 +25050,7 @@ snapshots: tinyglobby: 0.2.17 unstorage: 1.17.5(@azure/storage-blob@12.31.0(supports-color@10.0.0))(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.11.1(supports-color@10.0.0)) vite: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) - vite-plugin-inspect: 11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vite-plugin-inspect: 11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) vite-plugin-vue-tracer: 1.5.0(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2)) which: 6.0.1 ws: 8.22.2 @@ -25009,7 +25114,7 @@ snapshots: transitivePeerDependencies: - magicast - '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': + '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': dependencies: consola: 3.4.2 defu: 6.1.7 @@ -25027,7 +25132,7 @@ snapshots: std-env: 4.3.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - unctx: 3.0.1(magic-string@0.30.21)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + unctx: 3.0.1(magic-string@0.30.21)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) verkit: 0.5.0 optionalDependencies: '@nuxt/schema': 3.21.11 @@ -25037,12 +25142,12 @@ snapshots: jiti: 2.7.0 mlly: 1.8.2 oxc-parser: 0.143.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - magic-string - unplugin - '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': + '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': dependencies: consola: 3.4.2 defu: 6.1.7 @@ -25060,7 +25165,7 @@ snapshots: std-env: 4.3.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - unctx: 3.0.1(magic-string@1.1.0)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + unctx: 3.0.1(magic-string@1.1.0)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) verkit: 0.5.0 optionalDependencies: '@nuxt/schema': 3.21.11 @@ -25070,12 +25175,12 @@ snapshots: jiti: 2.7.0 mlly: 1.8.2 oxc-parser: 0.143.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - magic-string - unplugin - '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.152.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': + '@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@1.1.0)(mlly@1.8.2)(oxc-parser@0.152.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))': dependencies: consola: 3.4.2 defu: 6.1.7 @@ -25093,7 +25198,7 @@ snapshots: std-env: 4.3.0 tinyexec: 1.3.1 tinyglobby: 0.2.17 - unctx: 3.0.1(magic-string@1.1.0)(oxc-parser@0.152.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + unctx: 3.0.1(magic-string@1.1.0)(oxc-parser@0.152.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) verkit: 0.5.0 optionalDependencies: '@nuxt/schema': 3.21.11 @@ -25103,12 +25208,12 @@ snapshots: jiti: 2.7.0 mlly: 1.8.2 oxc-parser: 0.152.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - magic-string - unplugin - '@nuxt/nitro-server@3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': + '@nuxt/nitro-server@3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': dependencies: '@nuxt/devalue': 2.0.2 '@nuxt/kit': 3.21.11(magicast@0.5.5) @@ -25122,11 +25227,11 @@ snapshots: escape-string-regexp: 5.0.0 exsolve: 1.2.0 h3: 1.15.11 - impound: 1.1.6(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + impound: 1.1.6(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) klona: 2.0.6 mocked-exports: 0.1.1 - nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.143.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - nuxt: 3.21.11(724864ca76bc73825b6249c96f34efd5) + nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.143.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + nuxt: 3.21.11(054c80f87937459bdf21125c1fade606) ohash: 2.0.12 pathe: 2.0.3 pkg-types: 2.4.0 @@ -25182,7 +25287,7 @@ snapshots: - webpack - xml2js - '@nuxt/nitro-server@3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': + '@nuxt/nitro-server@3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': dependencies: '@nuxt/devalue': 2.0.2 '@nuxt/kit': 3.21.11(magicast@0.5.5) @@ -25196,11 +25301,11 @@ snapshots: escape-string-regexp: 5.0.0 exsolve: 1.2.0 h3: 1.15.11 - impound: 1.1.6(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + impound: 1.1.6(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) klona: 2.0.6 mocked-exports: 0.1.1 - nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - nuxt: 3.21.11(724864ca76bc73825b6249c96f34efd5) + nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + nuxt: 3.21.11(054c80f87937459bdf21125c1fade606) ohash: 2.0.12 pathe: 2.0.3 pkg-types: 2.4.0 @@ -25273,7 +25378,7 @@ snapshots: rc9: 3.1.0 std-env: 4.3.0 - '@nuxt/vite-builder@3.21.11(@types/node@20.19.43)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(magicast@0.5.5)(meow@13.2.0)(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(optionator@0.9.4)(oxlint@1.89.0(oxlint-tsgolint@7.0.2004))(rolldown@1.2.16)(rollup-plugin-visualizer@6.0.11(rolldown@1.2.16)(rollup@4.62.3))(rollup@4.62.3)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(vue@3.5.44(typescript@7.0.2))(yaml@2.9.0)': + '@nuxt/vite-builder@3.21.11(@types/node@20.19.43)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(magicast@0.5.5)(meow@13.2.0)(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(optionator@0.9.4)(oxlint@1.89.0(oxlint-tsgolint@7.0.2004))(rolldown@1.3.2)(rollup-plugin-visualizer@6.0.11(rolldown@1.3.2)(rollup@4.62.3))(rollup@4.62.3)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(vue@3.5.44(typescript@7.0.2))(yaml@2.9.0)': dependencies: '@nuxt/kit': 3.21.11(magicast@0.5.5) '@rollup/plugin-replace': 6.0.3(rollup@4.62.3) @@ -25293,7 +25398,7 @@ snapshots: magic-string: 0.30.21 mlly: 1.8.2 mocked-exports: 0.1.1 - nuxt: 3.21.11(724864ca76bc73825b6249c96f34efd5) + nuxt: 3.21.11(054c80f87937459bdf21125c1fade606) nypm: 0.6.9 ohash: 2.0.12 pathe: 2.0.3 @@ -25310,8 +25415,8 @@ snapshots: vue: 3.5.44(typescript@7.0.2) vue-bundle-renderer: 2.3.2 optionalDependencies: - rolldown: 1.2.16 - rollup-plugin-visualizer: 6.0.11(rolldown@1.2.16)(rollup@4.62.3) + rolldown: 1.3.2 + rollup-plugin-visualizer: 6.0.11(rolldown@1.3.2)(rollup@4.62.3) transitivePeerDependencies: - '@biomejs/biome' - '@types/node' @@ -25629,6 +25734,8 @@ snapshots: '@oxc-project/types@0.156.0': {} + '@oxc-project/types@0.158.0': {} + '@oxc-transform/binding-android-arm-eabi@0.143.0': optional: true @@ -26314,48 +26421,100 @@ snapshots: '@rolldown/binding-android-arm-eabi@1.2.16': optional: true + '@rolldown/binding-android-arm-eabi@1.3.2': + optional: true + '@rolldown/binding-android-arm64@1.2.16': optional: true + '@rolldown/binding-android-arm64@1.3.2': + optional: true + '@rolldown/binding-darwin-arm64@1.2.16': optional: true + '@rolldown/binding-darwin-arm64@1.3.2': + optional: true + '@rolldown/binding-darwin-x64@1.2.16': optional: true + '@rolldown/binding-darwin-x64@1.3.2': + optional: true + '@rolldown/binding-freebsd-x64@1.2.16': optional: true + '@rolldown/binding-freebsd-x64@1.3.2': + optional: true + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': optional: true + '@rolldown/binding-linux-arm-gnueabihf@1.3.2': + optional: true + '@rolldown/binding-linux-arm64-gnu@1.2.16': optional: true + '@rolldown/binding-linux-arm64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-arm64-musl@1.2.16': optional: true + '@rolldown/binding-linux-arm64-musl@1.3.2': + optional: true + '@rolldown/binding-linux-ppc64-gnu@1.2.16': optional: true + '@rolldown/binding-linux-ppc64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-s390x-gnu@1.2.16': optional: true + '@rolldown/binding-linux-s390x-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-x64-gnu@1.2.16': optional: true + '@rolldown/binding-linux-x64-gnu@1.3.2': + optional: true + '@rolldown/binding-linux-x64-musl@1.2.16': optional: true + '@rolldown/binding-linux-x64-musl@1.3.2': + optional: true + '@rolldown/binding-openharmony-arm64@1.2.16': optional: true + '@rolldown/binding-openharmony-arm64@1.3.2': + optional: true + + '@rolldown/binding-wasm32-wasi@1.3.2': + dependencies: + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) + optional: true + '@rolldown/binding-win32-arm64-msvc@1.2.16': optional: true + '@rolldown/binding-win32-arm64-msvc@1.3.2': + optional: true + '@rolldown/binding-win32-x64-msvc@1.2.16': optional: true + '@rolldown/binding-win32-x64-msvc@1.3.2': + optional: true + '@rolldown/pluginutils@1.0.1': {} '@rollup/plugin-alias@6.0.0(rollup@4.62.3)': @@ -26374,17 +26533,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@rollup/plugin-commonjs@25.0.8(rollup@4.62.3)': - dependencies: - '@rollup/pluginutils': 5.2.0(rollup@4.62.3) - commondir: 1.0.1 - estree-walker: 2.0.2 - glob: 8.1.0 - is-reference: 1.2.1 - magic-string: 0.30.21 - optionalDependencies: - rollup: 4.62.3 - '@rollup/plugin-commonjs@28.0.1(rollup@4.62.3)': dependencies: '@rollup/pluginutils': 5.2.0(rollup@4.62.3) @@ -26448,13 +26596,6 @@ snapshots: optionalDependencies: rollup: 4.62.3 - '@rollup/plugin-replace@5.0.7(rollup@4.62.3)': - dependencies: - '@rollup/pluginutils': 5.2.0(rollup@4.62.3) - magic-string: 0.30.21 - optionalDependencies: - rollup: 4.62.3 - '@rollup/plugin-replace@6.0.3(rollup@4.62.3)': dependencies: '@rollup/pluginutils': 5.2.0(rollup@4.62.3) @@ -27075,11 +27216,11 @@ snapshots: dependencies: solid-js: 1.9.18 - '@solidjs/start@1.3.2(1649c7f604f12e5f9af57e229fd2f3f2)': + '@solidjs/start@1.3.2(904a000150746b01a4f8678acf4cebc4)': dependencies: '@tanstack/server-functions-plugin': 1.121.21(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) - '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) - '@vinxi/server-components': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) + '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) + '@vinxi/server-components': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) cookie-es: 2.0.1 defu: 6.1.7 error-stack-parser: 2.1.4 @@ -27091,7 +27232,7 @@ snapshots: source-map-js: 1.2.2 terracotta: 1.0.5(solid-js@1.9.18) tinyglobby: 0.2.17 - vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) + vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) vite-plugin-solid: 2.11.14(@testing-library/jest-dom@6.9.1)(solid-js@1.9.18)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - '@testing-library/jest-dom' @@ -27417,6 +27558,11 @@ snapshots: '@ts-graphviz/ast': 2.0.7 '@ts-graphviz/common': 2.1.5 + '@tybys/wasm-util@0.10.4': + dependencies: + tslib: 2.8.1 + optional: true + '@tybys/wasm-util@0.9.0': dependencies: tslib: 2.8.1 @@ -28033,7 +28179,7 @@ snapshots: untun: 0.1.3 uqr: 0.1.3 - '@vinxi/plugin-directives@0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0))': + '@vinxi/plugin-directives@0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0))': dependencies: '@babel/parser': 7.29.9 acorn: 8.18.0 @@ -28044,18 +28190,18 @@ snapshots: magicast: 0.2.11 recast: 0.23.11 tslib: 2.8.1 - vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) + vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) - '@vinxi/server-components@0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0))': + '@vinxi/server-components@0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0))': dependencies: - '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) + '@vinxi/plugin-directives': 0.5.1(vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0)) acorn: 8.18.0 acorn-loose: 8.4.0 acorn-typescript: 1.4.13(acorn@8.18.0) astring: 1.9.0 magicast: 0.2.11 recast: 0.23.11 - vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) + vinxi: 0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0) '@vitejs/plugin-vue-jsx@5.1.6(supports-color@10.0.0)(vite@7.3.7(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2))': dependencies: @@ -32134,10 +32280,6 @@ snapshots: es-errors: 1.3.0 get-intrinsic: 1.3.0 - get-tsconfig@4.14.0: - dependencies: - resolve-pkg-maps: 1.0.0 - getopts@2.3.0: {} giget@2.0.0: @@ -32827,12 +32969,12 @@ snapshots: import-meta-resolve@4.2.0: {} - impound@1.1.6(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + impound@1.1.6(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@jridgewell/trace-mapping': 0.3.31 es-module-lexer: 2.1.0 pathe: 2.0.3 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 transitivePeerDependencies: - '@farmfe/core' @@ -34878,7 +35020,7 @@ snapshots: ocache: 0.1.4 ofetch: 2.0.0-alpha.3 ohash: 2.0.12 - rolldown: 1.2.16 + rolldown: 1.3.2 srvx: 0.11.22 unenv: 2.0.0-rc.24 unstorage: 2.0.0-alpha.7(@azure/storage-blob@12.31.0(supports-color@10.0.0))(chokidar@5.0.0)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.11.1(supports-color@10.0.0))(lru-cache@11.4.0)(mongodb@7.1.0(@aws-sdk/credential-providers@3.983.0)(socks@2.8.7))(ofetch@2.0.0-alpha.3) @@ -34931,7 +35073,7 @@ snapshots: ocache: 0.1.4 ofetch: 2.0.0-alpha.3 ohash: 2.0.12 - rolldown: 1.2.16 + rolldown: 1.3.2 srvx: 0.11.22 unenv: 2.0.0-rc.24 unstorage: 2.0.0-alpha.7(@azure/storage-blob@12.31.0(supports-color@10.0.0))(chokidar@5.0.0)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.11.1(supports-color@10.0.0))(lru-cache@11.4.0)(mongodb@7.1.0(@aws-sdk/credential-providers@3.983.0)(socks@2.8.7))(ofetch@2.0.0-alpha.3) @@ -34972,7 +35114,7 @@ snapshots: - sqlite3 - uploadthing - nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.143.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.143.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.62.3) @@ -35025,7 +35167,7 @@ snapshots: pretty-bytes: 7.1.0 radix3: 1.1.2 rollup: 4.62.3 - rollup-plugin-visualizer: 6.0.11(rolldown@1.2.16)(rollup@4.62.3) + rollup-plugin-visualizer: 6.0.11(rolldown@1.3.2)(rollup@4.62.3) scule: 1.3.0 semver: 7.8.5 serve-placeholder: 2.0.2 @@ -35037,7 +35179,7 @@ snapshots: uncrypto: 0.1.3 unctx: 2.5.0 unenv: 2.0.0-rc.24 - unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 unstorage: 1.17.5(@azure/storage-blob@12.31.0(supports-color@10.0.0))(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.10.1(supports-color@10.0.0)) untyped: 2.0.0 @@ -35081,7 +35223,7 @@ snapshots: - vite - webpack - nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.62.3) @@ -35134,7 +35276,7 @@ snapshots: pretty-bytes: 7.1.0 radix3: 1.1.2 rollup: 4.62.3 - rollup-plugin-visualizer: 6.0.11(rolldown@1.2.16)(rollup@4.62.3) + rollup-plugin-visualizer: 6.0.11(rolldown@1.3.2)(rollup@4.62.3) scule: 1.3.0 semver: 7.8.5 serve-placeholder: 2.0.2 @@ -35146,7 +35288,7 @@ snapshots: uncrypto: 0.1.3 unctx: 2.5.0 unenv: 2.0.0-rc.24 - unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 unstorage: 1.17.5(@azure/storage-blob@12.31.0(supports-color@10.0.0))(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.10.1(supports-color@10.0.0)) untyped: 2.0.0 @@ -35190,7 +35332,7 @@ snapshots: - vite - webpack - nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + nitropack@2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.62.3) @@ -35243,7 +35385,7 @@ snapshots: pretty-bytes: 7.1.0 radix3: 1.1.2 rollup: 4.62.3 - rollup-plugin-visualizer: 6.0.11(rolldown@1.2.16)(rollup@4.62.3) + rollup-plugin-visualizer: 6.0.11(rolldown@1.3.2)(rollup@4.62.3) scule: 1.3.0 semver: 7.8.5 serve-placeholder: 2.0.2 @@ -35255,7 +35397,7 @@ snapshots: uncrypto: 0.1.3 unctx: 2.5.0 unenv: 2.0.0-rc.24 - unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 unstorage: 1.17.5(@azure/storage-blob@12.31.0(supports-color@10.0.0))(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(ioredis@5.10.1(supports-color@10.0.0)) untyped: 2.0.0 @@ -35513,16 +35655,16 @@ snapshots: nuxi@3.25.1: {} - nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5): + nuxt@3.21.11(054c80f87937459bdf21125c1fade606): dependencies: - '@dxup/nuxt': 0.5.6(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(esbuild@0.28.1)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + '@dxup/nuxt': 0.5.6(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(esbuild@0.28.1)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) '@nuxt/cli': 3.37.0(@nuxt/schema@3.21.11)(@parcel/watcher@2.5.6)(cac@6.7.14)(commander@14.0.3)(magicast@0.5.5)(supports-color@10.0.0) - '@nuxt/devtools': 3.4.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@nuxt/schema@3.21.11)(confbox@0.2.4)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2)) + '@nuxt/devtools': 3.4.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@nuxt/schema@3.21.11)(confbox@0.2.4)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vue@3.5.44(typescript@7.0.2)) '@nuxt/kit': 3.21.11(magicast@0.5.5) - '@nuxt/nitro-server': 3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + '@nuxt/nitro-server': 3.21.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(encoding@0.1.13)(esbuild@0.28.1)(ioredis@5.11.1(supports-color@10.0.0))(magicast@0.5.5)(mysql2@3.23.3(@types/node@20.19.43))(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(srvx@0.11.22)(supports-color@10.0.0)(typescript@7.0.2)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) '@nuxt/schema': 3.21.11 '@nuxt/telemetry': 2.8.0(@nuxt/kit@3.21.11(magicast@0.5.5)) - '@nuxt/vite-builder': 3.21.11(@types/node@20.19.43)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(magicast@0.5.5)(meow@13.2.0)(nuxt@3.21.11(724864ca76bc73825b6249c96f34efd5))(optionator@0.9.4)(oxlint@1.89.0(oxlint-tsgolint@7.0.2004))(rolldown@1.2.16)(rollup-plugin-visualizer@6.0.11(rolldown@1.2.16)(rollup@4.62.3))(rollup@4.62.3)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(vue@3.5.44(typescript@7.0.2))(yaml@2.9.0) + '@nuxt/vite-builder': 3.21.11(@types/node@20.19.43)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(magicast@0.5.5)(meow@13.2.0)(nuxt@3.21.11(054c80f87937459bdf21125c1fade606))(optionator@0.9.4)(oxlint@1.89.0(oxlint-tsgolint@7.0.2004))(rolldown@1.3.2)(rollup-plugin-visualizer@6.0.11(rolldown@1.3.2)(rollup@4.62.3))(rollup@4.62.3)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(vue@3.5.44(typescript@7.0.2))(yaml@2.9.0) '@unhead/vue': 2.1.17(vue@3.5.44(typescript@7.0.2)) '@vue/shared': 3.5.44 c12: 3.3.4(magicast@0.5.5) @@ -35539,7 +35681,7 @@ snapshots: h3: 1.15.11 hookable: 5.5.3 ignore: 7.0.14 - impound: 1.1.6(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + impound: 1.1.6(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) jiti: 2.7.0 klona: 2.0.6 knitwork: 1.3.0 @@ -35553,7 +35695,7 @@ snapshots: oxc-minify: 0.143.0 oxc-parser: 0.143.0 oxc-transform: 0.143.0 - oxc-walker: 1.1.1(@oxc-project/types@0.152.0)(oxc-parser@0.143.0)(rolldown@1.2.16) + oxc-walker: 1.1.1(@oxc-project/types@0.152.0)(oxc-parser@0.143.0)(rolldown@1.3.2) pathe: 2.0.3 perfect-debounce: 2.1.0 pkg-types: 2.4.0 @@ -35566,8 +35708,8 @@ snapshots: ultrahtml: 1.7.0 uncrypto: 0.1.3 unctx: 2.5.0 - unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unimport: 6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-vue-router: 0.19.2(@vue/compiler-sfc@3.5.44)(vue-router@4.6.4(vue@3.5.44(typescript@7.0.2)))(vue@3.5.44(typescript@7.0.2)) untyped: 2.0.0 vue: 3.5.44(typescript@7.0.2) @@ -36042,11 +36184,11 @@ snapshots: '@oxc-transform/binding-win32-ia32-msvc': 0.143.0 '@oxc-transform/binding-win32-x64-msvc': 0.143.0 - oxc-walker@1.1.1(@oxc-project/types@0.152.0)(oxc-parser@0.143.0)(rolldown@1.2.16): + oxc-walker@1.1.1(@oxc-project/types@0.152.0)(oxc-parser@0.143.0)(rolldown@1.3.2): optionalDependencies: '@oxc-project/types': 0.152.0 oxc-parser: 0.143.0 - rolldown: 1.2.16 + rolldown: 1.3.2 oxfmt@0.74.0: dependencies: @@ -37742,8 +37884,6 @@ snapshots: resolve-pathname@2.2.0: {} - resolve-pkg-maps@1.0.0: {} - resolve-url-loader@5.0.0: dependencies: adjust-sourcemap-loader: 4.0.0 @@ -37847,21 +37987,32 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.16 '@rolldown/binding-win32-x64-msvc': 1.2.16 - rollup-plugin-copy-assets@2.0.3(rollup@4.62.3): + rolldown@1.3.2: dependencies: - fs-extra: 7.0.1 - rollup: 4.62.3 + '@oxc-project/types': 0.158.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.3.2 + '@rolldown/binding-android-arm64': 1.3.2 + '@rolldown/binding-darwin-arm64': 1.3.2 + '@rolldown/binding-darwin-x64': 1.3.2 + '@rolldown/binding-freebsd-x64': 1.3.2 + '@rolldown/binding-linux-arm-gnueabihf': 1.3.2 + '@rolldown/binding-linux-arm64-gnu': 1.3.2 + '@rolldown/binding-linux-arm64-musl': 1.3.2 + '@rolldown/binding-linux-ppc64-gnu': 1.3.2 + '@rolldown/binding-linux-s390x-gnu': 1.3.2 + '@rolldown/binding-linux-x64-gnu': 1.3.2 + '@rolldown/binding-linux-x64-musl': 1.3.2 + '@rolldown/binding-openharmony-arm64': 1.3.2 + '@rolldown/binding-wasm32-wasi': 1.3.2 + '@rolldown/binding-win32-arm64-msvc': 1.3.2 + '@rolldown/binding-win32-x64-msvc': 1.3.2 - rollup-plugin-esbuild@6.2.1(esbuild@0.28.1)(rollup@4.62.3)(supports-color@10.0.0): + rollup-plugin-copy-assets@2.0.3(rollup@4.62.3): dependencies: - debug: 4.4.3(supports-color@10.0.0) - es-module-lexer: 1.7.0 - esbuild: 0.28.1 - get-tsconfig: 4.14.0 + fs-extra: 7.0.1 rollup: 4.62.3 - unplugin-utils: 0.2.5 - transitivePeerDependencies: - - supports-color rollup-plugin-license@3.7.1(picomatch@4.0.7)(rollup@4.62.3): dependencies: @@ -37885,14 +38036,14 @@ snapshots: optionalDependencies: '@types/node': 14.18.63 - rollup-plugin-visualizer@6.0.11(rolldown@1.2.16)(rollup@4.62.3): + rollup-plugin-visualizer@6.0.11(rolldown@1.3.2)(rollup@4.62.3): dependencies: open: 8.4.2 picomatch: 4.0.7 source-map: 0.7.6 yargs: 17.7.3 optionalDependencies: - rolldown: 1.2.16 + rolldown: 1.3.2 rollup: 4.62.3 rollup@2.80.0: @@ -39372,26 +39523,26 @@ snapshots: magic-string: 0.30.21 unplugin: 2.3.11 - unctx@3.0.1(magic-string@0.30.21)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): + unctx@3.0.1(magic-string@0.30.21)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): optionalDependencies: magic-string: 0.30.21 oxc-parser: 0.143.0 - rolldown: 1.2.16 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + rolldown: 1.3.2 + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - unctx@3.0.1(magic-string@1.1.0)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): + unctx@3.0.1(magic-string@1.1.0)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): optionalDependencies: magic-string: 1.1.0 oxc-parser: 0.143.0 - rolldown: 1.2.16 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + rolldown: 1.3.2 + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - unctx@3.0.1(magic-string@1.1.0)(oxc-parser@0.152.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): + unctx@3.0.1(magic-string@1.1.0)(oxc-parser@0.152.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))): optionalDependencies: magic-string: 1.1.0 oxc-parser: 0.152.0 - rolldown: 1.2.16 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + rolldown: 1.3.2 + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) undefsafe@2.0.5: {} @@ -39457,7 +39608,7 @@ snapshots: dependencies: '@noble/hashes': 2.4.0 - unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: acorn: 8.18.0 escape-string-regexp: 5.0.0 @@ -39471,11 +39622,11 @@ snapshots: scule: 1.3.0 strip-literal: 4.0.0 tinyglobby: 0.2.17 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 optionalDependencies: oxc-parser: 0.143.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -39486,7 +39637,7 @@ snapshots: - vite - webpack - unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: acorn: 8.18.0 escape-string-regexp: 5.0.0 @@ -39500,11 +39651,11 @@ snapshots: scule: 1.3.0 strip-literal: 4.0.0 tinyglobby: 0.2.17 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 optionalDependencies: oxc-parser: 0.152.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -39515,7 +39666,7 @@ snapshots: - vite - webpack - unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + unimport@6.4.0(esbuild@0.28.1)(oxc-parser@0.152.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: acorn: 8.18.0 escape-string-regexp: 5.0.0 @@ -39529,11 +39680,11 @@ snapshots: scule: 1.3.0 strip-literal: 4.0.0 tinyglobby: 0.2.17 - unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) unplugin-utils: 0.3.2 optionalDependencies: oxc-parser: 0.152.0 - rolldown: 1.2.16 + rolldown: 1.3.2 transitivePeerDependencies: - '@farmfe/core' - '@rspack/core' @@ -39612,11 +39763,6 @@ snapshots: unpipe@1.0.0: {} - unplugin-utils@0.2.5: - dependencies: - pathe: 2.0.3 - picomatch: 4.0.7 - unplugin-utils@0.3.2: dependencies: pathe: 2.0.3 @@ -39654,26 +39800,26 @@ snapshots: picomatch: 4.0.7 webpack-virtual-modules: 0.6.2 - unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@jridgewell/remapping': 2.3.5 picomatch: 4.0.7 webpack-virtual-modules: 0.6.2 optionalDependencies: esbuild: 0.28.1 - rolldown: 1.2.16 + rolldown: 1.3.2 rollup: 4.62.3 vite: 6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) webpack: 5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3) - unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): + unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)): dependencies: '@jridgewell/remapping': 2.3.5 picomatch: 4.0.7 webpack-virtual-modules: 0.6.2 optionalDependencies: esbuild: 0.28.1 - rolldown: 1.2.16 + rolldown: 1.3.2 rollup: 4.62.3 vite: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) webpack: 5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3) @@ -39848,7 +39994,7 @@ snapshots: '@types/unist': 3.0.0 vfile-message: 4.0.3 - vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0): + vinxi@0.5.11(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(@types/node@20.19.43)(db0@0.3.4(mysql2@3.23.3(@types/node@20.19.43)))(debug@4.4.3(supports-color@10.0.0))(encoding@0.1.13)(ioredis@5.11.1(supports-color@10.0.0))(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(sass@1.72.0)(srvx@0.11.22)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(tsx@4.23.15)(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))(yaml@2.9.0): dependencies: '@babel/core': 7.29.7(supports-color@10.0.0) '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7(supports-color@10.0.0)) @@ -39869,7 +40015,7 @@ snapshots: hookable: 5.5.3 http-proxy: 1.18.1(debug@4.4.3(supports-color@10.0.0)) micromatch: 4.0.8 - nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.2.16)(srvx@0.11.22)(supports-color@10.0.0)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) + nitropack: 2.13.4(@azure/storage-blob@12.31.0(supports-color@10.0.0))(@parcel/watcher@2.5.6)(encoding@0.1.13)(mysql2@3.23.3(@types/node@20.19.43))(oxc-parser@0.152.0)(rolldown@1.3.2)(srvx@0.11.22)(supports-color@10.0.0)(vite@6.4.5(@types/node@20.19.43)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) node-fetch-native: 1.6.7 path-to-regexp: 6.3.0 pathe: 1.1.2 @@ -40002,7 +40148,7 @@ snapshots: oxlint: 1.89.0(oxlint-tsgolint@7.0.2004) typescript: 7.0.2 - vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vite-plugin-inspect@11.4.1(@nuxt/kit@4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))))(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: ansis: 4.3.1 error-stack-parser-es: 1.0.5 @@ -40015,7 +40161,7 @@ snapshots: vite: 8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) vite-dev-rpc: 2.0.0(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) optionalDependencies: - '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.2.16)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.2.16)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) + '@nuxt/kit': 4.6.4(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(giget@3.3.1)(jiti@2.7.0)(magic-string@0.30.21)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(unplugin@3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))) vite-plugin-solid@2.11.14(@testing-library/jest-dom@6.9.1)(solid-js@1.9.18)(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6645c646d04b..cb3f595a481f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -123,3 +123,20 @@ minimumReleaseAgeExclude: - '@sentry/*' - sentry - '@apm-js-collab/code-transformer-bundler-plugins@0.7.6' + - '@rolldown/binding-android-arm-eabi@1.3.2' + - '@rolldown/binding-android-arm64@1.3.2' + - '@rolldown/binding-darwin-arm64@1.3.2' + - '@rolldown/binding-darwin-x64@1.3.2' + - '@rolldown/binding-freebsd-x64@1.3.2' + - '@rolldown/binding-linux-arm-gnueabihf@1.3.2' + - '@rolldown/binding-linux-arm64-gnu@1.3.2' + - '@rolldown/binding-linux-arm64-musl@1.3.2' + - '@rolldown/binding-linux-ppc64-gnu@1.3.2' + - '@rolldown/binding-linux-s390x-gnu@1.3.2' + - '@rolldown/binding-linux-x64-gnu@1.3.2' + - '@rolldown/binding-linux-x64-musl@1.3.2' + - '@rolldown/binding-openharmony-arm64@1.3.2' + - '@rolldown/binding-wasm32-wasi@1.3.2' + - '@rolldown/binding-win32-arm64-msvc@1.3.2' + - '@rolldown/binding-win32-x64-msvc@1.3.2' + - rolldown@1.3.2 From c491307f4293d3ab375238cfad14cf3813e5d659 Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Wed, 11 Nov 2026 12:27:19 -0500 Subject: [PATCH 039/136] fix(browser): Send same-origin string tunnels as `application/x-sentry-envelope` (#26299) While writing the docs for the new tunnel API i realized we have a discrepency in behavior regarding the headers set on a tunnel request. **Before:** We set the `application/x-sentry-envelope` only if the user uses the new API options, so either `tunnel: true` or `tunnel: { path: '/monitor' }`. So the `tunnel: '/monitor'` option doesn't set that header. The reasoning is we were worried about breaking CORS preflight header checks by adding that header, which is still a valid concern however it would typically apply to requests to a different origin. Requests on the same origin wouldn't trigger a preflight check, so the header has no risk there. On all SDKs that doesn't really matter, but for Next.js it can break the tunnel if the user uses the new API directly with a fixed path like so: ```ts // instrument.client.ts Sentry.init({ tunnel: '/fixed-path' }); // instrument.server.ts Sentry.init({ integrations: [Sentry.serveTunnelIntegration()] }) ``` The way it works specifically on Next.js is that we match the route on vercel deployments using a re-write rule that targets any path with a `application/x-sentry-envelope` header, if the user uses the previous snippet the header is never sent so the tunnel never works. Our shipped PRs wouldn't trigger this issue on their own because the new docs don't recommend this yet. Our merged implementation actually ensures the header to applied, but by accident since we normalize to `tunnel: { path }` format which uses the new API. **After:** Now the distinction is different but more consistent, external URLs won't receive the header, while same origin requests will. This is a safer default. --- packages/browser/src/utils/managedTunnel.ts | 45 +++++++++++++++---- .../browser/test/utils/managedTunnel.test.ts | 30 +++++++++++-- 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/packages/browser/src/utils/managedTunnel.ts b/packages/browser/src/utils/managedTunnel.ts index 0a2a3644fd21..8d2329eeb35a 100644 --- a/packages/browser/src/utils/managedTunnel.ts +++ b/packages/browser/src/utils/managedTunnel.ts @@ -2,24 +2,34 @@ import type { BrowserTunnelOptions } from '@sentry/core'; import { debug, getTunnelPath, + isURLObjectRelative, makeDsn, _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, + parseStringToURLObject, } from '@sentry/core'; import { DEBUG_BUILD } from '../debug-build'; import type { BrowserOptions } from '../client'; +import { WINDOW } from '../helpers'; /** * Resolves `tunnel: true` or {@link BrowserTunnelOptions} to the managed tunnel's same-origin path. A string is left as - * written, so a tunnel the app serves itself gets the same requests as before. + * written, so a tunnel the app serves itself keeps its URL. */ export function resolveBrowserTunnelOption( options: BrowserOptions, ): Pick & { tunnel: string | undefined } { const { tunnel, dsn, transportOptions } = options; - if (!tunnel || typeof tunnel === 'string') { + if (!tunnel) { return { tunnel, transportOptions }; } + if (typeof tunnel === 'string') { + return { + tunnel, + transportOptions: isSameOrigin(tunnel) ? withEnvelopeContentType(transportOptions) : transportOptions, + }; + } + const tunnelOptions: BrowserTunnelOptions = tunnel === true ? {} : tunnel; const dsnComponents = dsn && makeDsn(dsn); const tunnelPath = tunnelOptions.path ?? (dsnComponents && getTunnelPath(dsnComponents)); @@ -32,12 +42,31 @@ export function resolveBrowserTunnelOption( DEBUG_BUILD && debug.log(`Tunneling events to "${resolvedTunnel}"`); + return { tunnel: resolvedTunnel, transportOptions: withEnvelopeContentType(transportOptions) }; +} + +/** + * Sends envelopes as `application/x-sentry-envelope`. CSRF protection (SvelteKit, Astro) rejects the default + * `text/plain` POST as a form submission, and the Next.js managed tunnel route on Vercel matches on this header. + * Cross-origin it would trigger a CORS preflight, so only same-origin tunnels get it. + */ +function withEnvelopeContentType( + transportOptions: BrowserOptions['transportOptions'], +): BrowserOptions['transportOptions'] { return { - tunnel: resolvedTunnel, - transportOptions: { - ...transportOptions, - // CSRF protection (SvelteKit, Astro) rejects the default `text/plain` POST to the tunnel as a form submission. - headers: { 'Content-Type': 'application/x-sentry-envelope', ...transportOptions?.headers }, - }, + ...transportOptions, + headers: { 'Content-Type': 'application/x-sentry-envelope', ...transportOptions?.headers }, }; } + +/** + * Whether the tunnel URL is on the page's origin. Unknown counts as cross-origin. + */ +function isSameOrigin(url: string): boolean { + const urlObject = parseStringToURLObject(url, WINDOW.location?.href); + if (!urlObject) { + return false; + } + + return isURLObjectRelative(urlObject) || urlObject.origin === WINDOW.location?.origin; +} diff --git a/packages/browser/test/utils/managedTunnel.test.ts b/packages/browser/test/utils/managedTunnel.test.ts index c7c288276d4a..fe859e915ac9 100644 --- a/packages/browser/test/utils/managedTunnel.test.ts +++ b/packages/browser/test/utils/managedTunnel.test.ts @@ -1,3 +1,7 @@ +/** + * @vitest-environment jsdom + */ + import { getTunnelPath } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { getClient, getCurrentScope, init } from '../../src'; @@ -43,8 +47,20 @@ describe('resolveBrowserTunnelOption', () => { expect(resolveBrowserTunnelOption({ dsn: DSN, tunnel: { path: '/monitor' } }).tunnel).toBe('/monitor'); }); - it.each(['https://proxy.example.com/tunnel', '/monitor'])( - 'keeps the string tunnel %s and its transport options untouched', + it.each(['/monitor', 'monitor', `${location.origin}/monitor`])( + 'sends to the same-origin string tunnel %s as application/x-sentry-envelope too', + tunnel => { + expect( + resolveBrowserTunnelOption({ dsn: DSN, tunnel, transportOptions: { headers: { 'X-Custom': '1' } } }), + ).toEqual({ + tunnel, + transportOptions: { headers: { 'Content-Type': 'application/x-sentry-envelope', 'X-Custom': '1' } }, + }); + }, + ); + + it.each(['https://proxy.example.com/tunnel', '//proxy.example.com/tunnel'])( + 'keeps the cross-origin string tunnel %s and its transport options untouched, so it needs no CORS preflight', tunnel => { const transportOptions = { headers: { 'x-custom': '1' } }; @@ -52,6 +68,14 @@ describe('resolveBrowserTunnelOption', () => { }, ); + it('lets a user content type override the envelope one', () => { + const transportOptions = { headers: { 'Content-Type': 'text/plain' } }; + + expect(resolveBrowserTunnelOption({ dsn: DSN, tunnel: '/monitor', transportOptions }).transportOptions).toEqual( + transportOptions, + ); + }); + it('turns the tunnel off without a valid DSN', () => { expect(resolveBrowserTunnelOption({ tunnel: true }).tunnel).toBeUndefined(); expect(resolveBrowserTunnelOption({ dsn: 'not-a-dsn', tunnel: true }).tunnel).toBeUndefined(); @@ -69,7 +93,7 @@ describe('init with `tunnel: true`', () => { expect(getClient()?.getOptions().tunnel).toBe(getTunnelPath(DSN)); }); - it('only sets the envelope content type for a managed tunnel', () => { + it('only sets the envelope content type for a same-origin tunnel', () => { const transport = vi.fn(makeFetchTransport); init({ dsn: DSN, tunnel: true, transport }); From 480d930c532f36fd28d1d1db17d13f66f8f1ffaf Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:19:41 +0100 Subject: [PATCH 040/136] chore(deno): Note that OTel setup defaulting to on is unintentional (#26310) --- packages/deno/src/sdk.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/deno/src/sdk.ts b/packages/deno/src/sdk.ts index 96af20a57b87..f003b462f5a7 100644 --- a/packages/deno/src/sdk.ts +++ b/packages/deno/src/sdk.ts @@ -134,6 +134,8 @@ function _init(options: DenoOptions, getDefaultIntegrationsImpl: (options: Optio // Set up OpenTelemetry compatibility to capture spans from libraries using @opentelemetry/api // Note: This is separate from Deno's native OTEL support and doesn't capture auto-instrumented spans + // TODO(v12): Default this to `false` (opt-in, like Cloudflare). Defaulting to `true` was an oversight from #17445, + // not a deliberate choice, but flipping it is a breaking change. if (options.enableOpenTelemetrySetup ?? true) { setupOpenTelemetryTracer(); } From 8832e97ce17b43584ff5588b27d13412814cd42b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:52:58 +0000 Subject: [PATCH 041/136] test(e2e): Run nestjs-12 on Bun, Deno and Cloudflare (#26283) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Runs the `nestjs-12` suite on Bun, Deno and Cloudflare (local workerd) as optional variants next to the required Node job, with the runtime variant setup from #24598. Each runtime inits its own SDK (`@sentry/bun`, `@sentry/deno` with `--preload=@sentry/deno/import`, `@sentry/cloudflare` via `instrument.server.ts`) and adds `nestIntegration()` from `@sentry/nestjs`. New tests cover parameterized route names, per-request isolation, incoming trace continuation, outgoing `fetch` with `sentry-trace`/`baggage`, and logs. They pass on all four runtimes with no `RUNTIME` branches. All four variants are green locally through `pnpm run test:run nestjs-12 [--variant …]`. Decisions that are hard to see in the diff: - **Bun** bundles the `nest build` output with `@sentry/bun/plugin` (`bun run` gets no diagnostics channel injection, see #24612). The variant pins **Bun 1.4.4**, because Bun 1.3.14 renames classes in bundles (`let X = class X {}` becomes `class X2`). Nest span names come from class names, so 6 span tests fail on 1.3.14 (`ExampleMiddleware2`, `ParseIntPipe2`). To allow the pin, `prepare-e2e-test` gets a `bun-version` input that works like `deno-version`. - **Cloudflare** bundles the same `nest build` output (tsc emits the decorator metadata Nest DI needs) with **Vite 8**. Rollup in Vite 7 renames the classes the same way. Nest boots in the first request through `httpServerHandler` from `cloudflare:node`. - Expected differences branch on `RUNTIME`, each with a comment: the SDK name; no `http.response.status_text` on Bun, because Bun's `node:http` leaves `statusMessage` unset; the `http.server` span attributes on Cloudflare, which `withSentry` builds from the `Request`; and the two cron tests on Cloudflare, which are skipped because workerd runs no timers outside a request, so `@nestjs/schedule` jobs never fire. - On current `develop`, the Deno audit findings (broken route names, broken outgoing fetch) no longer happen, and Cloudflare errors arrive through `SentryGlobalFilter`. The Sept 2026 audit's db-span findings don't apply here because `nestjs-12` has no database. **How to review:** Start with `nestjs-12/package.json` (variants, scripts), then `bun-build.mjs`, `workers/app.ts`, and the `RUNTIME` branches in `tests/spans.test.ts`. **Unsure about:** The variants start optional, and these SDK defects are still open, so this PR only refs #24844. The `RUNTIME` branches in `tests/spans.test.ts` call them out as known defects: - `getHttpSpanDetailsFromUrlObject` (core) sets `url.scheme` with a trailing colon (`http:`) and `url.port` as a string, on Cloudflare, `Bun.serve` and Nitro server spans. #26284 fixes that. The Cloudflare `http.server` span also has no `sentry.kind` or `http.response.status_text`, which nothing tracks yet. - Bun's `node:http` leaves `res.statusMessage` unset, so Bun `http.server` spans have no `http.response.status_text`. The SDK could fall back to the standard reason phrase. Not filed yet. - The CI default Bun is still 1.3.14, which renames bundled classes. #26289 proposes making 1.4.x the default, which would remove the per-variant `bun-version` input but could change other Bun apps' results. Refs #24844 via **Isaac Schlueter**. -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A6011a8eed2b7dc364fe22ff740bf6e29) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A6011a8eed2b7dc364fe22ff740bf6e29/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Isaac Schlueter --- .github/actions/prepare-e2e-test/action.yml | 5 +- .github/workflows/build.yml | 1 + .github/workflows/canary.yml | 1 + .github/workflows/optional-e2e.yml | 1 + dev-packages/e2e-tests/README.md | 7 +- .../test-applications/nestjs-12/.gitignore | 3 + .../test-applications/nestjs-12/bun-build.mjs | 23 ++++ .../test-applications/nestjs-12/deno.json | 6 + .../test-applications/nestjs-12/package.json | 29 ++++- .../nestjs-12/playwright.config.mjs | 11 +- .../nestjs-12/pnpm-workspace.yaml | 3 + .../nestjs-12/src/app.controller.ts | 31 ++++- .../nestjs-12/src/instrument.bun.ts | 14 +++ .../nestjs-12/src/instrument.deno.ts | 14 +++ .../nestjs-12/tests/constants.ts | 6 + .../nestjs-12/tests/cron-decorator.test.ts | 4 + .../nestjs-12/tests/request.test.ts | 110 ++++++++++++++++++ .../nestjs-12/tests/span-decorator.test.ts | 3 +- .../nestjs-12/tests/spans.test.ts | 26 ++++- .../nestjs-12/tsconfig.build.json | 11 +- .../nestjs-12/vite.config.ts | 10 ++ .../nestjs-12/workers/app.ts | 26 +++++ .../nestjs-12/workers/instrument.server.ts | 14 +++ .../nestjs-12/wrangler.jsonc | 7 ++ 24 files changed, 350 insertions(+), 16 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/bun-build.mjs create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/deno.json create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.bun.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.deno.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/tests/constants.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/tests/request.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/vite.config.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/workers/app.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/workers/instrument.server.ts create mode 100644 dev-packages/e2e-tests/test-applications/nestjs-12/wrangler.jsonc diff --git a/.github/actions/prepare-e2e-test/action.yml b/.github/actions/prepare-e2e-test/action.yml index 83510213a126..d81386521507 100644 --- a/.github/actions/prepare-e2e-test/action.yml +++ b/.github/actions/prepare-e2e-test/action.yml @@ -9,6 +9,9 @@ inputs: runtime: description: 'The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md.' default: '' + bun-version: + description: 'The Bun version to install, if the application needs Bun.' + default: '1.3.14' deno-version: description: 'The Deno version to install, if the application needs Deno.' default: 'v2.8.3' @@ -32,7 +35,7 @@ runs: == 'bun' uses: oven-sh/setup-bun@v2 with: - bun-version: '1.3.14' + bun-version: ${{ inputs.bun-version || '1.3.14' }} - name: Set up AWS SAM if: contains(inputs.test-application, 'aws-serverless') uses: aws-actions/setup-sam@v3 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b4edd5327d78..c88f378018a4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1084,6 +1084,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} # Installs Playwright while the app builds. Keep it right before the build: the runner sets up a background diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 422cecffa19c..8e29e056370e 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -101,6 +101,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} - name: Build E2E app diff --git a/.github/workflows/optional-e2e.yml b/.github/workflows/optional-e2e.yml index 56d0013288fc..eea799a5a5f9 100644 --- a/.github/workflows/optional-e2e.yml +++ b/.github/workflows/optional-e2e.yml @@ -79,6 +79,7 @@ jobs: with: test-application: ${{ matrix.test-application }} runtime: ${{ matrix.runtime }} + bun-version: ${{ matrix.bun-version }} deno-version: ${{ matrix.deno-version }} artifacts-run-id: ${{ inputs.build_run_id }} github-token: ${{ github.token }} diff --git a/dev-packages/e2e-tests/README.md b/dev-packages/e2e-tests/README.md index be2b94586ece..8c9d38ed0607 100644 --- a/dev-packages/e2e-tests/README.md +++ b/dev-packages/e2e-tests/README.md @@ -207,10 +207,13 @@ is the reference setup. replaces `vite.config.ts`. For a variant with `runtime`, the runner copies these files over the others in the temporary copy of the app, before the build. This needs no framework or bundler config. A build in the app folder itself does not get these files, so run a variant with `pnpm run test:run --variant `. -- **Deno version**: a variant can pin the Deno version, for example `"deno-version": "v2.9.0"`. +- **Bun and Deno versions**: a variant can pin the Bun or Deno version, for example `"bun-version": "1.4.4"` or + `"deno-version": "v2.9.0"`. - **Bun**: under `bun run` the SDK cannot inject diagnostics channels into packages that stay outside the build (for example Express behind `react-router-serve`), so those produce no spans on Bun. Where a test depends on them, branch - on `RUNTIME` and say why in a comment. + on `RUNTIME` and say why in a comment. An app that starts its own server can instead bundle it with + `@sentry/bun/plugin`, as `nestjs-12/bun-build.mjs` does. Bun 1.3 renames classes in bundles (`class Foo2`), which + changes span names taken from class names, so `nestjs-12` pins Bun 1.4 (see #26289). ```json "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/.gitignore b/dev-packages/e2e-tests/test-applications/nestjs-12/.gitignore index 4b56acfbebf4..644141630883 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/.gitignore +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/.gitignore @@ -1,5 +1,8 @@ # compiled output /dist +/dist-bun +/dist-cloudflare +/.wrangler /node_modules /build diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/bun-build.mjs b/dev-packages/e2e-tests/test-applications/nestjs-12/bun-build.mjs new file mode 100644 index 000000000000..904620f4c7c1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/bun-build.mjs @@ -0,0 +1,23 @@ +// Bundles the `nest build` output with `@sentry/bun/plugin`. Under `bun run` the SDK cannot inject +// diagnostics channels into packages, so only a bundled app gets the Nest and Express spans. +import { sentryBunPlugin } from '@sentry/bun/plugin'; +import { join } from 'node:path'; + +await Bun.build({ + entrypoints: [join(import.meta.dir, 'dist/main.js')], + target: 'bun', + outdir: join(import.meta.dir, 'dist-bun'), + // The bundler resolves Nest's optional `require` calls at build time. `@nestjs/websockets`, + // `class-transformer`, `class-validator` and `cache-manager` are not installed. `@nestjs/microservices` + // is installed for `RpcException`, but it loads transports (`kafkajs`, `@grpc/grpc-js`, ...) that are not. + external: [ + '@nestjs/microservices', + '@nestjs/microservices/*', + '@nestjs/websockets', + '@nestjs/websockets/*', + 'class-transformer', + 'class-validator', + 'cache-manager', + ], + plugins: [sentryBunPlugin({ telemetry: false })], +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/deno.json b/dev-packages/e2e-tests/test-applications/nestjs-12/deno.json new file mode 100644 index 000000000000..46456a69617a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/deno.json @@ -0,0 +1,6 @@ +{ + "imports": { + "@sentry/deno/import": "./node_modules/@sentry/deno/build/import.mjs" + }, + "nodeModulesDir": "manual" +} diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/package.json b/dev-packages/e2e-tests/test-applications/nestjs-12/package.json index 62908d591ad8..eb1002dc7ccd 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/package.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/package.json @@ -6,12 +6,17 @@ "scripts": { "build": "nest build", "start": "node --import ./dist/instrument.js dist/main.js", + "start:bun": "bun dist-bun/main.js", + "start:deno": "deno run -A --preload=@sentry/deno/import --preload=./dist/instrument.js dist/main.js", + "start:cloudflare": "wrangler dev --config ./dist-cloudflare/nestjs_12/wrangler.json --port 3030", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "clean": "npx rimraf node_modules pnpm-lock.yaml", "test": "playwright test", "test:build": "pnpm install && pnpm build", + "test:build:bun": "pnpm install && pnpm build && bun ./bun-build.mjs", + "test:build:cloudflare": "pnpm install && pnpm build && vite build", "test:build-latest": "pnpm install && pnpm add @nestjs/common@latest @nestjs/core@latest @nestjs/platform-express@latest @nestjs/microservices@latest && pnpm add -D @nestjs/cli@latest && pnpm build", "test:assert": "pnpm test" }, @@ -21,6 +26,9 @@ "@nestjs/microservices": "^12.0.0", "@nestjs/schedule": "^12.0.0", "@nestjs/platform-express": "^12.0.0", + "@sentry/bun": "file:../../packed/sentry-bun-packed.tgz", + "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", + "@sentry/deno": "file:../../packed/sentry-deno-packed.tgz", "@sentry/nestjs": "file:../../packed/sentry-nestjs-packed.tgz", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.1" @@ -32,13 +40,32 @@ "@nestjs/schematics": "^12.0.0", "@types/express": "^5.0.0", "@types/node": "^22.0.0", - "typescript": "~5.9.0" + "typescript": "~5.9.0", + "@cloudflare/vite-plugin": "^1.47.0", + "vite": "^8.1.5", + "wrangler": "^4.120.0" }, "sentryTest": { "optionalVariants": [ { "build-command": "pnpm test:build-latest", "label": "nestjs-12 (latest)" + }, + { + "runtime": "bun", + "bun-version": "1.4.4", + "build-command": "pnpm test:build:bun", + "label": "nestjs-12 (bun)" + }, + { + "runtime": "deno", + "deno-version": "v2.9.0", + "label": "nestjs-12 (deno)" + }, + { + "runtime": "cloudflare", + "build-command": "pnpm test:build:cloudflare", + "label": "nestjs-12 (cloudflare)" } ] } diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nestjs-12/playwright.config.mjs index 31f2b913b58b..93ba85a1b96c 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/playwright.config.mjs +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/playwright.config.mjs @@ -1,7 +1,14 @@ -import { getPlaywrightConfig } from '@sentry-internal/test-utils'; +import { getPlaywrightConfig, getRuntime } from '@sentry-internal/test-utils'; + +const startCommands = { + node: 'pnpm start', + bun: 'pnpm start:bun', + deno: 'pnpm start:deno', + cloudflare: 'pnpm start:cloudflare', +}; const config = getPlaywrightConfig({ - startCommand: `pnpm start`, + startCommand: startCommands[getRuntime()], }); export default config; diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/nestjs-12/pnpm-workspace.yaml index 50ece95aba3b..1531e7a16b42 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/pnpm-workspace.yaml +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/pnpm-workspace.yaml @@ -1,3 +1,6 @@ +allowBuilds: + esbuild: true + workerd: true minimumReleaseAge: 0 overrides: 'minimatch': '10.0.1' diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/src/app.controller.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/src/app.controller.ts index 06b29450d48b..7d400b68e77a 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/src/app.controller.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/src/app.controller.ts @@ -1,5 +1,5 @@ import { Controller, Get, Param, ParseIntPipe, UseFilters, UseGuards, UseInterceptors } from '@nestjs/common'; -import { flush } from '@sentry/nestjs'; +import * as Sentry from '@sentry/nestjs'; import { AppService } from './app.service.js'; import { AsyncInterceptor } from './async-example.interceptor.js'; import { ExampleInterceptor1 } from './example-1.interceptor.js'; @@ -84,7 +84,34 @@ export class AppController { @Get('flush') async flush() { - await flush(); + await Sentry.flush(); + } + + @Get('test-param/:param') + testParam(@Param('param') param: string) { + return { param }; + } + + @Get('test-isolation/:id') + async testIsolation(@Param('id') id: string) { + Sentry.setTag('isolation-id', id); + // Lets the concurrent requests of the isolation test overlap. + await new Promise(resolve => setTimeout(resolve, 200)); + Sentry.captureException(new Error(`Isolated error ${id}`)); + return {}; + } + + // The test runs a server on port 3040 that records the headers of the request. + @Get('test-outgoing-fetch') + async testOutgoingFetch() { + const response = await fetch('http://localhost:3040/outgoing'); + return { status: response.status }; + } + + @Get('test-log') + testLog() { + Sentry.logger.info('test-log', { route: 'test-log' }); + return {}; } @Get('example-exception-global-filter') diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.bun.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.bun.ts new file mode 100644 index 000000000000..1048a9b7acf9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.bun.ts @@ -0,0 +1,14 @@ +import * as Sentry from '@sentry/bun'; +import { nestIntegration } from '@sentry/nestjs'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, + // The cron job throws the same error on every run, which Dedupe would drop after the first run. + integrations: integrations => [ + ...integrations.filter(integration => integration.name !== 'Dedupe'), + nestIntegration(), + ], +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.deno.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.deno.ts new file mode 100644 index 000000000000..1715af8d8dae --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/src/instrument.deno.ts @@ -0,0 +1,14 @@ +import * as Sentry from '@sentry/deno'; +import { nestIntegration } from '@sentry/nestjs'; + +Sentry.init({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: process.env.E2E_TEST_DSN, + tunnel: `http://localhost:3031/`, // proxy server + tracesSampleRate: 1, + // The cron job throws the same error on every run, which Dedupe would drop after the first run. + integrations: integrations => [ + ...integrations.filter(integration => integration.name !== 'Dedupe'), + nestIntegration(), + ], +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/constants.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/constants.ts new file mode 100644 index 000000000000..1a00b860a5c1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/constants.ts @@ -0,0 +1,6 @@ +import { getRuntime } from '@sentry-internal/test-utils'; + +export const RUNTIME = getRuntime(); + +// Only Node inits `@sentry/nestjs`. Bun, Deno and Cloudflare init their runtime's own SDK. +export const SDK_NAME = RUNTIME === 'node' ? 'sentry.javascript.nestjs' : `sentry.javascript.${RUNTIME}`; diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/cron-decorator.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/cron-decorator.test.ts index 6892e8ca6da9..edc57831eb93 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/cron-decorator.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/cron-decorator.test.ts @@ -1,5 +1,9 @@ import { expect, test } from '@playwright/test'; import { waitForEnvelopeItem, waitForError } from '@sentry-internal/test-utils'; +import { RUNTIME } from './constants'; + +// workerd runs no timers outside a request, so `@nestjs/schedule` jobs never fire. Workers use Cron Triggers instead. +test.skip(RUNTIME === 'cloudflare', 'Nest cron jobs do not run on Cloudflare Workers.'); test('Cron job triggers send of in_progress envelope', async ({ baseURL }) => { const inProgressEnvelopePromise = waitForEnvelopeItem('nestjs-12', envelope => { diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/request.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/request.test.ts new file mode 100644 index 000000000000..efa31392d972 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/request.test.ts @@ -0,0 +1,110 @@ +import { expect, test } from '@playwright/test'; +import { + collectStreamedSpansUntilSegment, + getSpanOp, + waitForEnvelopeItem, + waitForError, +} from '@sentry-internal/test-utils'; +import type { SerializedLogContainer } from '@sentry/core'; +import type { IncomingHttpHeaders } from 'node:http'; +import { createServer } from 'node:http'; + +const APP_NAME = 'nestjs-12'; + +const TRACE_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; +const PARENT_SPAN_ID = 'bbbbbbbbbbbbbbbb'; + +test('Names the request span after the parameterized route', async ({ baseURL }) => { + const spansPromise = collectStreamedSpansUntilSegment(APP_NAME, 'GET /test-param/:param'); + + const response = await fetch(`${baseURL}/test-param/123`); + expect(await response.json()).toEqual({ param: '123' }); + + const segmentSpan = (await spansPromise).find(span => span.is_segment)!; + expect(segmentSpan.attributes).toMatchObject({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'http.route': { type: 'string', value: '/test-param/:param' }, + 'url.path': { type: 'string', value: '/test-param/123' }, + }); +}); + +test('Keeps the scope data of concurrent requests apart', async ({ baseURL }) => { + const ids = ['1', '2', '3']; + const errorPromises = ids.map(id => + waitForError(APP_NAME, event => event.exception?.values?.[0]?.value === `Isolated error ${id}`), + ); + + await Promise.all(ids.map(id => fetch(`${baseURL}/test-isolation/${id}`))); + + const errors = await Promise.all(errorPromises); + errors.forEach((error, index) => { + expect(error.tags?.['isolation-id']).toBe(ids[index]); + expect(error.transaction).toBe('GET /test-isolation/:id'); + }); + + const traceIds = errors.map(error => error.contexts?.trace?.trace_id); + expect(new Set(traceIds).size).toBe(ids.length); +}); + +test('Continues the trace of an incoming request', async ({ baseURL }) => { + const spansPromise = collectStreamedSpansUntilSegment( + APP_NAME, + span => span.name === 'GET /test-param/:param' && span.trace_id === TRACE_ID, + ); + + await fetch(`${baseURL}/test-param/continued`, { + headers: { + 'sentry-trace': `${TRACE_ID}-${PARENT_SPAN_ID}-1`, + baggage: `sentry-trace_id=${TRACE_ID},sentry-environment=qa,sentry-public_key=public,sentry-sampled=true`, + }, + }); + + const segmentSpan = (await spansPromise).find(span => span.is_segment)!; + expect(segmentSpan.trace_id).toBe(TRACE_ID); + expect(segmentSpan.parent_span_id).toBe(PARENT_SPAN_ID); +}); + +test('Propagates the trace to an outgoing fetch request', async ({ baseURL }) => { + let receivedHeaders: IncomingHttpHeaders | undefined; + const server = createServer((req, res) => { + receivedHeaders = req.headers; + res.end('ok'); + }); + await new Promise(resolve => server.listen(3040, resolve)); + + try { + const spansPromise = collectStreamedSpansUntilSegment(APP_NAME, 'GET /test-outgoing-fetch'); + + const response = await fetch(`${baseURL}/test-outgoing-fetch`); + expect(await response.json()).toEqual({ status: 200 }); + + const spans = await spansPromise; + const segmentSpan = spans.find(span => span.is_segment)!; + const fetchSpan = spans.find(span => getSpanOp(span) === 'http.client'); + + expect(fetchSpan).toBeDefined(); + expect(fetchSpan!.trace_id).toBe(segmentSpan.trace_id); + expect(fetchSpan!.attributes['http.request.method']).toEqual({ type: 'string', value: 'GET' }); + + expect(receivedHeaders?.['sentry-trace']).toBe(`${segmentSpan.trace_id}-${fetchSpan!.span_id}-1`); + expect(receivedHeaders?.baggage).toContain(`sentry-trace_id=${segmentSpan.trace_id}`); + expect(receivedHeaders?.baggage).toContain('sentry-environment=qa'); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('Sends logs', async ({ baseURL }) => { + const logPromise = waitForEnvelopeItem( + APP_NAME, + item => item[0].type === 'log' && (item[1] as SerializedLogContainer).items.some(log => log.body === 'test-log'), + ); + + await fetch(`${baseURL}/test-log`); + + const log = ((await logPromise)[1] as SerializedLogContainer).items.find(log => log.body === 'test-log')!; + expect(log.level).toBe('info'); + expect(log.trace_id).toMatch(/^[a-f0-9]{32}$/); + expect(log.attributes?.route).toEqual({ type: 'string', value: 'test-log' }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/span-decorator.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/span-decorator.test.ts index 8c3c62011f17..982e6855e20b 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/span-decorator.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/span-decorator.test.ts @@ -1,6 +1,7 @@ import { expect, test } from '@playwright/test'; import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { SDK_NAME } from './constants'; const APP_NAME = 'nestjs-12'; @@ -22,7 +23,7 @@ function tracedSpan(segmentSpan: SerializedStreamedSpan, name: string, op: strin 'sentry.is_localhost': segmentSpan.attributes['sentry.is_localhost'], 'sentry.segment.name': { type: 'string', value: segmentSpan.name }, 'sentry.segment.id': { type: 'string', value: segmentSpan.span_id }, - 'sentry.sdk.name': { type: 'string', value: 'sentry.javascript.nestjs' }, + 'sentry.sdk.name': { type: 'string', value: SDK_NAME }, 'sentry.sdk.version': { type: 'string', value: expect.any(String) }, 'sentry.environment': { type: 'string', value: 'qa' }, // CI builds the apps with a release, local runs have none. It comes from the client diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts index 462c13f7ceee..59babf206c1b 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts @@ -1,6 +1,7 @@ import { expect, test } from '@playwright/test'; import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { RUNTIME, SDK_NAME } from './constants'; const APP_NAME = 'nestjs-12'; @@ -23,7 +24,7 @@ function commonAttributes(segmentSpan: SerializedStreamedSpan): Record { status: 'ok', attributes: expect.objectContaining({ ...commonAttributes(segmentSpan), - 'sentry.origin': { type: 'string', value: 'auto.http.http_server' }, 'sentry.op': { type: 'string', value: 'http.server' }, 'sentry.segment.name.source': { type: 'string', value: 'route' }, 'sentry.sample_rate': { type: 'integer', value: 1 }, - 'sentry.kind': { type: 'string', value: 'server' }, 'http.request.method': { type: 'string', value: 'GET' }, 'http.route': { type: 'string', value: '/test-transaction' }, 'http.response.status_code': { type: 'integer', value: 200 }, - 'http.response.status_text': { type: 'string', value: 'OK' }, 'url.full': { type: 'string', value: 'http://localhost:3030/test-transaction' }, 'url.path': { type: 'string', value: '/test-transaction' }, - 'url.scheme': { type: 'string', value: 'http' }, 'server.address': { type: 'string', value: 'localhost' }, - 'server.port': { type: 'integer', value: 3030 }, 'user_agent.original': { type: 'string', value: 'node' }, + // On Cloudflare, `withSentry` creates the `http.server` span from the worker's `Request`, not from `node:http`. + // Known defects: `url.scheme` keeps the colon from `URL.protocol` and `url.port` is a string (see #26284), and + // the span has no `sentry.kind` or `http.response.status_text`. + ...(RUNTIME === 'cloudflare' + ? { + 'sentry.origin': { type: 'string', value: 'auto.http.cloudflare' }, + 'url.scheme': { type: 'string', value: 'http:' }, + 'url.port': { type: 'string', value: '3030' }, + } + : { + 'sentry.origin': { type: 'string', value: 'auto.http.http_server' }, + 'sentry.kind': { type: 'string', value: 'server' }, + 'url.scheme': { type: 'string', value: 'http' }, + 'server.port': { type: 'integer', value: 3030 }, + // Known defect: Bun's `node:http` leaves `statusMessage` unset when the app does not set it, and the SDK + // does not fall back to the standard reason phrase. + ...(RUNTIME === 'bun' ? {} : { 'http.response.status_text': { type: 'string', value: 'OK' } }), + }), }), }); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tsconfig.build.json b/dev-packages/e2e-tests/test-applications/nestjs-12/tsconfig.build.json index ee15ab743183..333a7af38a28 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/tsconfig.build.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tsconfig.build.json @@ -1,4 +1,13 @@ { "extends": "./tsconfig.json", - "exclude": ["node_modules", "test", "tests", "dist"] + "exclude": [ + "node_modules", + "test", + "tests", + "dist", + "workers", + "vite.config.ts", + "src/**/*.bun.ts", + "src/**/*.deno.ts" + ] } diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/vite.config.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/vite.config.ts new file mode 100644 index 000000000000..92fb98b92ddd --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/vite.config.ts @@ -0,0 +1,10 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +// Only the Cloudflare variant builds with Vite. It bundles the `nest build` output, which has the +// decorator metadata Nest needs for dependency injection. +export default defineConfig({ + build: { outDir: 'dist-cloudflare' }, + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/workers/app.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/workers/app.ts new file mode 100644 index 000000000000..bbb1f3e3c366 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/workers/app.ts @@ -0,0 +1,26 @@ +import { NestFactory } from '@nestjs/core'; +import { httpServerHandler } from 'cloudflare:node'; +import { AppModule } from '../dist/app.module.js'; + +const PORT = 3030; + +let listening: Promise | undefined; + +// workerd allows no I/O at module scope, so Nest boots in the first request. +async function bootstrap(): Promise { + const app = await NestFactory.create(AppModule); + await app.listen(PORT); +} + +const handler = httpServerHandler({ port: PORT }); + +export default { + async fetch(request, env, ctx) { + listening ??= bootstrap().catch(err => { + listening = undefined; + throw err; + }); + await listening; + return handler.fetch(request, env, ctx); + }, +}; diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/workers/instrument.server.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/workers/instrument.server.ts new file mode 100644 index 000000000000..51b271a9d499 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/workers/instrument.server.ts @@ -0,0 +1,14 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; +import { nestIntegration } from '@sentry/nestjs'; + +export default defineCloudflareOptions({ + environment: 'qa', // dynamic sampling bias to keep transactions + dsn: 'https://username@domain/123', + tunnel: 'http://localhost:3031/', // proxy server + tracesSampleRate: 1, + // The cron job throws the same error on every run, which Dedupe would drop after the first run. + integrations: integrations => [ + ...integrations.filter(integration => integration.name !== 'Dedupe'), + nestIntegration(), + ], +}); diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nestjs-12/wrangler.jsonc new file mode 100644 index 000000000000..3b1229c2fc53 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/wrangler.jsonc @@ -0,0 +1,7 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "nestjs-12", + "compatibility_date": "2026-06-29", + "compatibility_flags": ["nodejs_compat"], + "main": "./workers/app.ts", +} From 27bc7cbb46b222ce343c3177c87cd54443091091 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:52:59 +0000 Subject: [PATCH 042/136] fix(core): Set `url.scheme` without colon and `url.port` as a number (#26284) **Why:** `getHttpSpanDetailsFromUrlObject` copied `URL.protocol` and `URL.port` as they are, so spans got `url.scheme: 'https:'` and `url.port: '8080'` (a string). The Sentry conventions define `url.scheme` as the bare scheme (example `"https"`) and `url.port` as a number. Node `http.server` spans already send `url.scheme: 'http'` and an integer port. The helper builds the HTTP spans of Cloudflare `withSentry`, `Bun.serve`, Deno, Nitro and outgoing Node `http` requests, so their values change too: streamed `url.port` becomes `type: 'integer'`. The attribute keys stay the same, but saved queries on the old values stop matching, so the changelog gets an Important Changes entry. This is stacked on #26283 (merge that first). It also updates the `nestjs-12` Cloudflare `RUNTIME` branch from #26283: `url.scheme` is now the shared `'http'`, and `url.port` becomes `{ type: 'integer', value: 3030 }`. **How to review:** The fix is two lines in `packages/core/src/utils/url.ts`. The rest updates test expectations in core (including the outgoing `node:http` path), bun, cloudflare, `cloudflare-integration-tests`, and the `deno`, `cloudflare-mcp` and `nestjs-12` e2e apps. **Unsure about:** Key naming, not changed here: for `kind === 'server'`, the helper sets `url.port`, while Node server spans set `server.port` (OTel HTTP server spans use `server.port`). The helper already uses `server.address` for server spans, so `server.port` may be the better key there. That rename would change product-visible data, so it needs a separate decision. Refs #24844 via **Isaac Schlueter**. -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A6011a8eed2b7dc364fe22ff740bf6e29) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A6011a8eed2b7dc364fe22ff740bf6e29/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Isaac Schlueter --- CHANGELOG.md | 6 ++++ .../suites/public-api/startSpan/test.ts | 6 ++-- .../cloudflare-mcp/tests/index.test.ts | 4 +-- .../deno/tests/streamed/transactions.test.ts | 6 ++-- .../nestjs-12/tests/spans.test.ts | 8 ++--- .../bun/test/integrations/bunserver.test.ts | 20 +++++------ packages/cloudflare/test/request.test.ts | 2 +- packages/core/src/utils/url.ts | 4 +-- .../http/get-outgoing-span-data.test.ts | 4 +++ packages/core/test/lib/utils/url.test.ts | 34 +++++++++---------- 10 files changed, 51 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cf64b2291ae..f6f2a8fecca0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ Work in this release was contributed by @kunal649. Thank you for your contribution! +### Important Changes + +- **fix(core): Set `url.scheme` without colon and `url.port` as a number ([#26284](https://github.com/getsentry/sentry-javascript/pull/26284))** + + HTTP spans that the SDK builds from a `URL` now send `url.scheme` without the trailing colon (`https` instead of `https:`) and `url.port` as a number instead of a string, as the Sentry conventions define them and as Node `http.server` spans already do. This changes `http.server` spans from `@sentry/cloudflare`, `Bun.serve`, Deno and Nitro, and outgoing `node:http` client spans. Update saved queries, alerts and dashboards that filter on `url.scheme:"https:"` or on `url.port` as a string. + ## 11.12.0 ### Important Changes diff --git a/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts b/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts index adf52419022f..430e5baf0487 100644 --- a/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/public-api/startSpan/test.ts @@ -224,12 +224,12 @@ it('sends a streamed span envelope with correct spans for a manually started spa value: '/', }, 'url.port': { - type: 'string', - value: expect.stringMatching(/^\d{4,5}$/), + type: 'integer', + value: expect.any(Number), }, 'url.scheme': { type: 'string', - value: 'http:', + value: 'http', }, 'user_agent.original': { type: 'string', diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/index.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/index.test.ts index 8219b57bfe09..33971947b88a 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/index.test.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-mcp/tests/index.test.ts @@ -66,8 +66,8 @@ test('sends spans for MCP 2026-07-28 tool calls', async ({ baseURL }) => { expect(requestSpan.attributes['http.request.method']?.value).toBe('POST'); expect(requestSpan.attributes['url.path']?.value).toBe('/mcp'); expect(requestSpan.attributes['url.full']?.value).toBe(url); - expect(requestSpan.attributes['url.port']?.value).toBe('8787'); - expect(requestSpan.attributes['url.scheme']?.value).toBe('http:'); + expect(requestSpan.attributes['url.port']?.value).toBe(8787); + expect(requestSpan.attributes['url.scheme']?.value).toBe('http'); expect(requestSpan.attributes['server.address']?.value).toBe('localhost'); expect(requestSpan.attributes['http.request.body.size']?.value).toBe(341); expect(requestSpan.attributes['user_agent.original']?.value).toBe('node'); diff --git a/dev-packages/e2e-tests/test-applications/deno/tests/streamed/transactions.test.ts b/dev-packages/e2e-tests/test-applications/deno/tests/streamed/transactions.test.ts index 83bf22f3d6dc..484c5856fb06 100644 --- a/dev-packages/e2e-tests/test-applications/deno/tests/streamed/transactions.test.ts +++ b/dev-packages/e2e-tests/test-applications/deno/tests/streamed/transactions.test.ts @@ -139,12 +139,12 @@ const SEGMENT_SPAN = { value: '/test-sentry-span', }, 'url.port': { - type: 'string', - value: expect.any(String), + type: 'integer', + value: expect.any(Number), }, 'url.scheme': { type: 'string', - value: 'http:', + value: 'http', }, 'user.ip_address': { type: 'string', diff --git a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts index 59babf206c1b..ebf4cbe14fcf 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-12/tests/spans.test.ts @@ -123,19 +123,17 @@ test('Sends streamed spans for an API route', async ({ baseURL }) => { 'url.path': { type: 'string', value: '/test-transaction' }, 'server.address': { type: 'string', value: 'localhost' }, 'user_agent.original': { type: 'string', value: 'node' }, + 'url.scheme': { type: 'string', value: 'http' }, // On Cloudflare, `withSentry` creates the `http.server` span from the worker's `Request`, not from `node:http`. - // Known defects: `url.scheme` keeps the colon from `URL.protocol` and `url.port` is a string (see #26284), and - // the span has no `sentry.kind` or `http.response.status_text`. + // Known defect: the span has no `sentry.kind` or `http.response.status_text`. ...(RUNTIME === 'cloudflare' ? { 'sentry.origin': { type: 'string', value: 'auto.http.cloudflare' }, - 'url.scheme': { type: 'string', value: 'http:' }, - 'url.port': { type: 'string', value: '3030' }, + 'url.port': { type: 'integer', value: 3030 }, } : { 'sentry.origin': { type: 'string', value: 'auto.http.http_server' }, 'sentry.kind': { type: 'string', value: 'server' }, - 'url.scheme': { type: 'string', value: 'http' }, 'server.port': { type: 'integer', value: 3030 }, // Known defect: Bun's `node:http` leaves `statusMessage` unset when the app does not set it, and the SDK // does not fall back to the standard reason phrase. diff --git a/packages/bun/test/integrations/bunserver.test.ts b/packages/bun/test/integrations/bunserver.test.ts index 0eb88f86fd00..83e80405f642 100644 --- a/packages/bun/test/integrations/bunserver.test.ts +++ b/packages/bun/test/integrations/bunserver.test.ts @@ -263,8 +263,8 @@ describe('Bun Serve Integration', () => { 'url.query': 'id=123', 'url.path': '/users', 'url.full': `http://localhost:${port}/users?id=123`, - 'url.port': port.toString(), - 'url.scheme': 'http:', + 'url.port': port, + 'url.scheme': 'http', [SERVER_ADDRESS]: 'localhost', 'http.request.header.accept': ['*/*'], 'http.request.header.accept-encoding': ['gzip, deflate, br, zstd'], @@ -306,8 +306,8 @@ describe('Bun Serve Integration', () => { [SENTRY_SEGMENT_NAME_SOURCE]: 'route', 'url.path': '/', 'url.full': `http://localhost:${port}/`, - 'url.port': port.toString(), - 'url.scheme': 'http:', + 'url.port': port, + 'url.scheme': 'http', [SERVER_ADDRESS]: 'localhost', 'http.request.header.accept': ['*/*'], 'http.request.header.accept-encoding': ['gzip, deflate, br, zstd'], @@ -425,8 +425,8 @@ describe('Bun Serve Integration', () => { 'sentry.segment.name.source': 'url', 'url.path': '/api/test', 'url.full': `http://localhost:${port}/api/test`, - 'url.port': port.toString(), - 'url.scheme': 'http:', + 'url.port': port, + 'url.scheme': 'http', [SERVER_ADDRESS]: 'localhost', // HTTP headers as span attributes following OpenTelemetry semantic conventions 'http.request.header.user-agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'], @@ -504,8 +504,8 @@ describe('Bun Serve Integration', () => { [`${URL_PATH_PARAMETER_KEY_BASE}.id`]: '123', 'url.path': '/users/123', 'url.full': `http://localhost:${port}/users/123`, - 'url.port': port.toString(), - 'url.scheme': 'http:', + 'url.port': port, + 'url.scheme': 'http', [SERVER_ADDRESS]: 'localhost', }), name: 'GET /users/:id', @@ -567,8 +567,8 @@ describe('Bun Serve Integration', () => { [HTTP_ROUTE]: '/api/*', 'url.path': '/api/users/123', 'url.full': `http://localhost:${port}/api/users/123`, - 'url.port': port.toString(), - 'url.scheme': 'http:', + 'url.port': port, + 'url.scheme': 'http', [SERVER_ADDRESS]: 'localhost', }), name: 'GET /api/*', diff --git a/packages/cloudflare/test/request.test.ts b/packages/cloudflare/test/request.test.ts index aba83d5f66c3..f1ff999fe1ce 100644 --- a/packages/cloudflare/test/request.test.ts +++ b/packages/cloudflare/test/request.test.ts @@ -686,7 +686,7 @@ describe('withSentry', () => { 'server.address': 'example.com', 'network.protocol.name': 'http', 'network.protocol.version': '1.1', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'url.path': '/', 'sentry.sample_rate': 1, 'http.response.status_code': 200, diff --git a/packages/core/src/utils/url.ts b/packages/core/src/utils/url.ts index 3a0a5fca186c..47d1776a1346 100644 --- a/packages/core/src/utils/url.ts +++ b/packages/core/src/utils/url.ts @@ -243,10 +243,10 @@ export function getHttpSpanDetailsFromUrlObject( if (!isURLObjectRelative(urlObject)) { if (urlObject.port) { - attributes[URL_PORT] = urlObject.port; + attributes[URL_PORT] = Number(urlObject.port); } if (urlObject.protocol) { - attributes[URL_SCHEME] = urlObject.protocol; + attributes[URL_SCHEME] = urlObject.protocol.replace(/:$/, ''); } if (urlObject.hostname) { attributes[kind === 'server' ? SERVER_ADDRESS : URL_DOMAIN] = urlObject.hostname; diff --git a/packages/core/test/lib/integrations/http/get-outgoing-span-data.test.ts b/packages/core/test/lib/integrations/http/get-outgoing-span-data.test.ts index 9544365d2333..24040417902f 100644 --- a/packages/core/test/lib/integrations/http/get-outgoing-span-data.test.ts +++ b/packages/core/test/lib/integrations/http/get-outgoing-span-data.test.ts @@ -19,6 +19,8 @@ import { URL_DOMAIN, URL_FULL, URL_PATH, + URL_PORT, + URL_SCHEME, } from '@sentry/conventions/attributes'; function makeMockRequest(overrides: Partial> = {}): HttpClientRequest { @@ -146,6 +148,8 @@ describe('getOutgoingRequestSpanData', () => { it('includes non-standard port in the URL', () => { const result = getOutgoingRequestSpanData(makeMockRequest({ port: 3000 })); expect(result.attributes![URL_FULL]).toContain(':3000'); + expect(result.attributes![URL_SCHEME]).toBe('http'); + expect(result.attributes![URL_PORT]).toBe(3000); }); }); diff --git a/packages/core/test/lib/utils/url.test.ts b/packages/core/test/lib/utils/url.test.ts index ad491ea983a6..0d40064b2969 100644 --- a/packages/core/test/lib/utils/url.test.ts +++ b/packages/core/test/lib/utils/url.test.ts @@ -487,7 +487,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.fragment': 'section', 'url.full': 'https://example.com/api/users?q=test#section', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', }); }); @@ -501,7 +501,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://example.com/api/users', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'http.request.method': 'POST', }); }); @@ -522,7 +522,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://example.com/api/users', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'http.route': '/api/users/:id', }); }); @@ -537,7 +537,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/', 'url.full': 'https://example.com/', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', }); }); @@ -551,8 +551,8 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://example.com:8080/api/users', 'server.address': 'example.com', - 'url.scheme': 'https:', - 'url.port': '8080', + 'url.scheme': 'https', + 'url.port': 8080, }); }); @@ -566,8 +566,8 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://example.com:3000/api/users', 'server.address': 'example.com', - 'url.scheme': 'https:', - 'url.port': '3000', + 'url.scheme': 'https', + 'url.port': 3000, 'http.request.method': 'PUT', }); }); @@ -588,7 +588,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users/123', 'url.full': 'https://example.com/api/users/123', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'http.route': '/api/users/:id', 'http.request.method': 'PATCH', }); @@ -611,7 +611,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.query': 'q=test&page=1', 'url.full': 'https://example.com/api/search?q=test&page=1', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'http.route': '/api/search', }); }); @@ -633,7 +633,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.fragment': 'section-1', 'url.full': 'https://example.com/api/docs#section-1', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', 'http.route': '/api/docs', }); }); @@ -648,7 +648,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://user:pass@example.com/api/users', 'server.address': 'example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', }); }); @@ -662,8 +662,8 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://192.168.1.1:8080/api/users', 'server.address': '192.168.1.1', - 'url.scheme': 'https:', - 'url.port': '8080', + 'url.scheme': 'https', + 'url.port': 8080, }); }); @@ -677,8 +677,8 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/api/users', 'url.full': 'https://[2001:db8::1]:8080/api/users', 'server.address': '[2001:db8::1]', - 'url.scheme': 'https:', - 'url.port': '8080', + 'url.scheme': 'https', + 'url.port': 8080, }); }); @@ -692,7 +692,7 @@ describe('getHttpSpanDetailsFromUrlObject', () => { 'url.path': '/users', 'url.full': 'https://api.example.com/users', 'server.address': 'api.example.com', - 'url.scheme': 'https:', + 'url.scheme': 'https', }); }); }); From 36fcc6f2470f3bdad6eb9a97d4355746262aef9c Mon Sep 17 00:00:00 2001 From: Francesco Gringl-Novy Date: Thu, 12 Nov 2026 11:26:40 +0100 Subject: [PATCH 043/136] ref(server-utils): Extract pi-ai chat span helpers from pi-durable (#25932) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR only moves things around in preparation for follow up work. Functionally nothing should change and it should mostly be stamp-able. **Why:** Split out of #25869. The upcoming pi-ai integration creates the same `gen_ai.chat` span as pi-durable's `models` proxy does today, so the span logic moves to `ai/pi-ai/` first. That way it gets reviewed once, as a move, while pi-durable still uses it. No behavior change: the pi-durable unit tests pass unmodified (only a type import moved). **How to review:** `ai/pi-ai/chat.ts` is the body of the old `traceModelRequest`/`endChatSpan`, with the origin as a parameter. `getPiAiChatSpanOptions` returns the span options instead of starting the span, because pi-durable keeps the span active while the request is sent (`startSpanManual`), whereas a channel-based integration starts it inactive. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/server-utils/src/ai/pi-ai/chat.ts | 123 ++++++++++++++++++ packages/server-utils/src/ai/pi-ai/types.ts | 35 +++++ .../server-utils/src/ai/pi-durable/models.ts | 118 ++--------------- .../server-utils/src/ai/pi-durable/types.ts | 30 +---- .../test/ai/lib/tracing/pi-durable.test.ts | 2 +- 5 files changed, 169 insertions(+), 139 deletions(-) create mode 100644 packages/server-utils/src/ai/pi-ai/chat.ts create mode 100644 packages/server-utils/src/ai/pi-ai/types.ts diff --git a/packages/server-utils/src/ai/pi-ai/chat.ts b/packages/server-utils/src/ai/pi-ai/chat.ts new file mode 100644 index 000000000000..2e401efcba2e --- /dev/null +++ b/packages/server-utils/src/ai/pi-ai/chat.ts @@ -0,0 +1,123 @@ +import type { Span, StartSpanOptions } from '@sentry/core'; +import { + getCurrentScope, + getIsolationScope, + isURLObjectRelative, + parseStringToURLObject, + SPAN_STATUS_ERROR, + stringify, +} from '@sentry/core'; +import { + GEN_AI_CONVERSATION_ID, + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MAX_TOKENS, + GEN_AI_REQUEST_MODEL, + GEN_AI_REQUEST_REASONING_LEVEL, + GEN_AI_REQUEST_TEMPERATURE, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, + GEN_AI_RESPONSE_MODEL, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, + SENTRY_ORIGIN, + SERVER_ADDRESS, + SERVER_PORT, +} from '@sentry/conventions/attributes'; +import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import type { PiAiContext } from './messages'; +import { + piAiAssistantMessageToGenAiMessage, + piAiFinishReason, + piAiMessagesToGenAiMessages, + piAiSystemInstructions, + piAiToolDefinitions, +} from './messages'; +import type { PiAssistantMessage, PiModel, PiStreamOptions } from './types'; +import { setPiAiUsageAttributes } from './usage'; + +export interface PiAiChatRequest { + model: PiModel; + /** Absent for the deferred calls, which pass a handle in place of the request context. */ + context?: PiAiContext; + callOptions?: PiStreamOptions; + streaming: boolean; + origin: string; + recordInputs: boolean; +} + +/** + * The span options of the `gen_ai.chat` span of a pi-ai request. Returned rather than started so + * the caller picks whether the span is active while the request is sent. + */ +export function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptions { + const { model, context, callOptions, streaming, origin, recordInputs } = request; + const conversationId = + getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId; + + return { + name: model.id ? `chat ${model.id}` : 'chat', + op: GEN_AI_CHAT, + attributes: { + [SENTRY_ORIGIN]: origin, + [GEN_AI_OPERATION_NAME]: 'chat', + [GEN_AI_PROVIDER_NAME]: model.provider, + [GEN_AI_REQUEST_MODEL]: model.id, + [GEN_AI_CONVERSATION_ID]: conversationId, + [GEN_AI_RESPONSE_STREAMING]: streaming || undefined, + [GEN_AI_REQUEST_TEMPERATURE]: callOptions?.temperature, + [GEN_AI_REQUEST_MAX_TOKENS]: callOptions?.maxTokens, + [GEN_AI_REQUEST_REASONING_LEVEL]: callOptions?.reasoning, + ...getServerAttributes(model), + ...(recordInputs && context ? getRequestContentAttributes(context) : {}), + }, + }; +} + +/** + * Record the settled message of a pi-ai request on its span. pi-ai never rejects a request: a + * provider failure or an abort settles as a message with `stopReason` `error` or `aborted`. + */ +export function setPiAiResponseAttributes(span: Span, message: PiAssistantMessage, recordOutputs: boolean): void { + const { responseModel, model, responseId, stopReason, usage } = message; + + const finishReason = piAiFinishReason(stopReason); + const output = recordOutputs ? piAiAssistantMessageToGenAiMessage(message, finishReason) : undefined; + + span.setAttributes({ + [GEN_AI_RESPONSE_MODEL]: responseModel ?? model, + [GEN_AI_RESPONSE_ID]: responseId, + [GEN_AI_RESPONSE_FINISH_REASONS]: finishReason ? stringify([finishReason]) : undefined, + [GEN_AI_OUTPUT_MESSAGES]: output ? stringify([output], String) : undefined, + }); + + const failed = stopReason === 'error'; + setPiAiUsageAttributes(span, usage, failed || stopReason === 'deferred'); + + if (failed) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + } else if (stopReason === 'aborted') { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + } +} + +function getServerAttributes(model: PiModel): Record { + const url = model.baseUrl ? parseStringToURLObject(model.baseUrl) : undefined; + if (!url || isURLObjectRelative(url) || !url.hostname) { + return {}; + } + return { [SERVER_ADDRESS]: url.hostname, [SERVER_PORT]: url.port ? Number(url.port) : undefined }; +} + +function getRequestContentAttributes(context: PiAiContext): Record { + const messages = piAiMessagesToGenAiMessages(context.messages); + const tools = piAiToolDefinitions(context); + return { + [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context), + [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined, + [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined, + }; +} diff --git a/packages/server-utils/src/ai/pi-ai/types.ts b/packages/server-utils/src/ai/pi-ai/types.ts new file mode 100644 index 000000000000..f2355d1044d8 --- /dev/null +++ b/packages/server-utils/src/ai/pi-ai/types.ts @@ -0,0 +1,35 @@ +/** + * Structural subsets of the `@earendil-works/pi-ai` types the instrumentation reads. The SDK does + * not depend on the package, so only the fields used here are declared, and every one of them is + * treated as possibly absent at runtime. + */ + +import type { PiAiUsage } from './usage'; + +export interface PiAssistantMessage { + role?: string; + content?: unknown[]; + provider?: string; + model?: string; + responseModel?: string; + responseId?: string; + usage?: PiAiUsage; + stopReason?: string; + errorMessage?: string; +} + +export interface PiModel { + id?: string; + provider?: string; + baseUrl?: string; +} + +export interface PiStreamOptions { + temperature?: number; + maxTokens?: number; + reasoning?: string; +} + +export interface PiEventStream { + result(): Promise; +} diff --git a/packages/server-utils/src/ai/pi-durable/models.ts b/packages/server-utils/src/ai/pi-durable/models.ts index 196973159d70..07cf3a279165 100644 --- a/packages/server-utils/src/ai/pi-durable/models.ts +++ b/packages/server-utils/src/ai/pi-durable/models.ts @@ -1,48 +1,11 @@ -import type { Span } from '@sentry/core'; -import { - getCurrentScope, - getIsolationScope, - isThenable, - isURLObjectRelative, - parseStringToURLObject, - SPAN_STATUS_ERROR, - startSpanManual, - stringify, -} from '@sentry/core'; -import { - GEN_AI_CONVERSATION_ID, - GEN_AI_INPUT_MESSAGES, - GEN_AI_OPERATION_NAME, - GEN_AI_OUTPUT_MESSAGES, - GEN_AI_PROVIDER_NAME, - GEN_AI_REQUEST_MAX_TOKENS, - GEN_AI_REQUEST_MODEL, - GEN_AI_REQUEST_REASONING_LEVEL, - GEN_AI_REQUEST_TEMPERATURE, - GEN_AI_RESPONSE_FINISH_REASONS, - GEN_AI_RESPONSE_ID, - GEN_AI_RESPONSE_MODEL, - GEN_AI_RESPONSE_STREAMING, - GEN_AI_SYSTEM_INSTRUCTIONS, - GEN_AI_TOOL_DEFINITIONS, - SENTRY_ORIGIN, - SERVER_ADDRESS, - SERVER_PORT, -} from '@sentry/conventions/attributes'; -import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import { isThenable, SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core'; import type { GenAiOptions } from '../core/utils'; import { resolveAIRecordingOptions } from '../core/utils'; +import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../pi-ai/chat'; import type { PiAiContext } from '../pi-ai/messages'; -import { - piAiAssistantMessageToGenAiMessage, - piAiFinishReason, - piAiMessagesToGenAiMessages, - piAiSystemInstructions, - piAiToolDefinitions, -} from '../pi-ai/messages'; -import { setPiAiUsageAttributes } from '../pi-ai/usage'; +import type { PiAssistantMessage, PiEventStream, PiModel, PiStreamOptions } from '../pi-ai/types'; import { PI_DURABLE_ORIGIN } from './constants'; -import type { PiAssistantMessage, PiEventStream, PiModel, PiModels, PiStreamOptions } from './types'; +import type { PiModels } from './types'; type ModelCall = (model: PiModel, request: unknown, options?: unknown) => unknown; @@ -107,27 +70,9 @@ function traceModelRequest( ): unknown { // Read per request: `dataCollection.genAI` belongs to the current client, which can change. const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); - const conversationId = - getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId; return startSpanManual( - { - name: model.id ? `chat ${model.id}` : 'chat', - op: GEN_AI_CHAT, - attributes: { - [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN, - [GEN_AI_OPERATION_NAME]: 'chat', - [GEN_AI_PROVIDER_NAME]: model.provider, - [GEN_AI_REQUEST_MODEL]: model.id, - [GEN_AI_CONVERSATION_ID]: conversationId, - ...getServerAttributes(model), - ...(streaming ? { [GEN_AI_RESPONSE_STREAMING]: true } : {}), - [GEN_AI_REQUEST_TEMPERATURE]: callOptions?.temperature, - [GEN_AI_REQUEST_MAX_TOKENS]: callOptions?.maxTokens, - [GEN_AI_REQUEST_REASONING_LEVEL]: callOptions?.reasoning, - ...(recordInputs && context ? getRequestContentAttributes(context) : {}), - }, - }, + getPiAiChatSpanOptions({ model, context, callOptions, streaming, origin: PI_DURABLE_ORIGIN, recordInputs }), span => { let result: unknown; try { @@ -152,7 +97,10 @@ function traceModelRequest( return result; } (settled as Promise).then( - message => endChatSpan(span, message, recordOutputs), + message => { + setPiAiResponseAttributes(span, message, recordOutputs); + span.end(); + }, () => { span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); span.end(); @@ -163,51 +111,3 @@ function traceModelRequest( }, ); } - -function getServerAttributes(model: PiModel): Record { - const url = model.baseUrl ? parseStringToURLObject(model.baseUrl) : undefined; - if (!url || isURLObjectRelative(url) || !url.hostname) { - return {}; - } - return { [SERVER_ADDRESS]: url.hostname, ...(url.port ? { [SERVER_PORT]: Number(url.port) } : {}) }; -} - -function getRequestContentAttributes(context: PiAiContext): Record { - const messages = piAiMessagesToGenAiMessages(context.messages); - const tools = piAiToolDefinitions(context); - return { - [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context), - [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined, - [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined, - }; -} - -function endChatSpan(span: Span, message: PiAssistantMessage, recordOutputs: boolean): void { - const responseModel = message.responseModel ?? message.model; - if (responseModel) { - span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel); - } - if (message.responseId) { - span.setAttribute(GEN_AI_RESPONSE_ID, message.responseId); - } - - const finishReason = piAiFinishReason(message.stopReason); - if (finishReason) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason])); - } - - const failed = message.stopReason === 'error'; - setPiAiUsageAttributes(span, message.usage, failed || message.stopReason === 'deferred'); - - const output = recordOutputs ? piAiAssistantMessageToGenAiMessage(message, finishReason) : undefined; - if (output) { - span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([output], String)); - } - - if (failed) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - } else if (message.stopReason === 'aborted') { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); - } - span.end(); -} diff --git a/packages/server-utils/src/ai/pi-durable/types.ts b/packages/server-utils/src/ai/pi-durable/types.ts index c4ec68ceef8c..e4b79f7fcd42 100644 --- a/packages/server-utils/src/ai/pi-durable/types.ts +++ b/packages/server-utils/src/ai/pi-durable/types.ts @@ -5,35 +5,7 @@ */ import type { PiAiContext } from '../pi-ai/messages'; -import type { PiAiUsage } from '../pi-ai/usage'; - -export interface PiAssistantMessage { - role?: string; - content?: unknown[]; - provider?: string; - model?: string; - responseModel?: string; - responseId?: string; - usage?: PiAiUsage; - stopReason?: string; - errorMessage?: string; -} - -export interface PiModel { - id?: string; - provider?: string; - baseUrl?: string; -} - -export interface PiStreamOptions { - temperature?: number; - maxTokens?: number; - reasoning?: string; -} - -export interface PiEventStream { - result(): Promise; -} +import type { PiAssistantMessage, PiEventStream, PiModel, PiStreamOptions } from '../pi-ai/types'; /** * The `Models` methods that send a model request. Everything else passes through untouched. The diff --git a/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts b/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts index e7bd701485cf..ef8c7aeeff31 100644 --- a/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts @@ -52,7 +52,6 @@ import { createRuns, startRun } from '../../../../src/ai/pi-durable/runs'; import { instrumentTool, markBuiltInTool } from '../../../../src/ai/pi-durable/tools'; import type { PiCommitChange, - PiEventStream, PiHarnessOptions, PiLiveState, PiModels, @@ -64,6 +63,7 @@ import type { PiToolExecutionApi, PiToolExecutionResult, } from '../../../../src/ai/pi-durable/types'; +import type { PiEventStream } from '../../../../src/ai/pi-ai/types'; import { ANTHROPIC_AI_INTEGRATION_NAME } from '../../../../src/ai/anthropic-ai/constants'; import { GOOGLE_GENAI_INTEGRATION_NAME } from '../../../../src/ai/google-genai/constants'; import { OPENAI_INTEGRATION_NAME } from '../../../../src/ai/openai/constants'; From 363bb227d7c51a06129121506dfba72ee255d631 Mon Sep 17 00:00:00 2001 From: Francesco Gringl-Novy Date: Thu, 12 Nov 2026 11:26:40 +0100 Subject: [PATCH 044/136] feat(server-utils): Add pi-ai integration (#25937) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** pi-ai had no instrumentation of its own. Only Flue and pi-durable traced its requests, each with its own chat spans. This adds a `piAiIntegration` that traces every pi-ai request, so direct users are covered and both frameworks can later drop their chat-span code. The version range starts at 0.80 because Flue 2.0–2.2 depend on pi-ai 0.83–0.87. It's **opt-in** in this PR: Flue and pi-durable still record their own chat spans for the same requests, so enabling it next to them reports each call twice. The follow-up switches both frameworks over to it and enables it by default (it's on the coverage test's opt-in list until then). Split out of #25869, stacked on #25932, whose helpers it uses. **How to review:** Start with `integrations/pi-ai.ts` and `orchestrion/config/pi-ai.ts`. `complete*` awaits `stream*`, and `compat.stream` hands some models to a `Models` of its own, so a traced call can make another one synchronously. A depth counter gives only the outermost call a span. **Merge after #25935.** With pi-ai in the orchestrion config, the Cloudflare Flue worker crashes at startup (`Cannot access 'ModelsImpl' before initialization`) through the import cycle #25935 removes. **Release note:** > - **feat(server-utils): Add pi-ai integration** > > The new `piAiIntegration` traces requests sent with [pi-ai](https://github.com/earendil-works/pi) (`@earendil-works/pi-ai` >= 0.80) as `gen_ai.chat` spans, through `createModels()` or the standalone `stream`/`complete` functions. It is not enabled by default yet: add `Sentry.piAiIntegration()` to `integrations`. It needs the Sentry runtime hook or bundler plugin. > > Once pi-ai has sent a request, the `openai`, `@anthropic-ai/sdk`, `@google/genai` and Workers AI integrations stop recording requests for the rest of the process, because pi-ai sends its requests through those clients. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../node-suites/excludes.ts | 1 + .../suites/tracing/pi-ai/instrument.mjs | 10 + .../suites/tracing/pi-ai/scenario-compat.mjs | 12 + .../suites/tracing/pi-ai/scenario.mjs | 52 +++ .../suites/tracing/pi-ai/test.ts | 117 ++++++ packages/astro/src/index.server.ts | 1 + packages/aws-serverless/src/index.ts | 1 + packages/bun/src/index.ts | 1 + packages/cloudflare/src/index.ts | 1 + packages/deno/src/index.ts | 1 + packages/elysia/src/index.ts | 1 + packages/google-cloud-serverless/src/index.ts | 1 + packages/node/src/index.ts | 1 + .../server-utils/src/ai/pi-ai/constants.ts | 3 + packages/server-utils/src/index.ts | 1 + .../server-utils/src/integrations/pi-ai.ts | 112 ++++++ .../server-utils/src/orchestrion/channels.ts | 2 + .../src/orchestrion/config/index.ts | 2 + .../src/orchestrion/config/pi-ai.ts | 44 ++ .../test/integrations/pi-ai.test.ts | 380 ++++++++++++++++++ .../moduleInjectedTransform.test.ts | 3 +- 21 files changed, 746 insertions(+), 1 deletion(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-compat.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts create mode 100644 packages/server-utils/src/ai/pi-ai/constants.ts create mode 100644 packages/server-utils/src/integrations/pi-ai.ts create mode 100644 packages/server-utils/src/orchestrion/config/pi-ai.ts create mode 100644 packages/server-utils/test/integrations/pi-ai.test.ts diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts index 60d47967bd65..ff7e526ad3db 100644 --- a/dev-packages/bun-integration-tests/node-suites/excludes.ts +++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts @@ -120,6 +120,7 @@ export const NO_AUTO_INSTRUMENTATION = [ 'suites/tracing/openai/v6/test.ts', 'suites/tracing/openai/v7/test.ts', 'suites/tracing/orchestrion-lazy-registration/test.ts', + 'suites/tracing/pi-ai/test.ts', 'suites/tracing/pi-durable/test.ts', 'suites/tracing/postgres/test.ts', 'suites/tracing/postgresjs/test.ts', diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs new file mode 100644 index 000000000000..e0d424cdae71 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + transport: loggingTransport, + integrations: [Sentry.piAiIntegration()], +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-compat.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-compat.mjs new file mode 100644 index 000000000000..c8dd78e9a9ec --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-compat.mjs @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/node'; +import { complete, fauxAssistantMessage, registerFauxProvider, streamSimple } from '@earendil-works/pi-ai/compat'; + +// The standalone API dispatches to the providers registered with it. +const compat = registerFauxProvider({ provider: 'compat-faux', models: [{ id: 'compat-model' }] }); +compat.setResponses([fauxAssistantMessage('Hello.'), fauxAssistantMessage('Goodbye.')]); + +await Sentry.startSpan({ name: 'pi-ai-test' }, async () => { + const model = compat.getModel(); + await complete(model, { messages: [{ role: 'user', content: 'Hi.', timestamp: Date.now() }] }); + await streamSimple(model, { messages: [{ role: 'user', content: 'Bye.', timestamp: Date.now() }] }).result(); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario.mjs new file mode 100644 index 000000000000..2d7742fd6aa8 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario.mjs @@ -0,0 +1,52 @@ +import * as Sentry from '@sentry/node'; +import { Type } from '@earendil-works/pi-ai'; +import { createModels } from '@earendil-works/pi-ai/models'; +import { fauxAssistantMessage, fauxProvider, fauxToolCall } from '@earendil-works/pi-ai/providers/faux'; + +// `pi-ai`'s faux provider scripts model responses in-process. +const faux = fauxProvider({ provider: 'faux', models: [{ id: 'faux-model' }] }); +const models = createModels(); +models.setProvider(faux.provider); +faux.setResponses([ + fauxAssistantMessage(fauxToolCall('get_weather', { city: 'Berlin' }, { id: 'call_1' }), { stopReason: 'toolUse' }), + fauxAssistantMessage('It is sunny in Berlin.'), +]); + +const tools = [ + { + name: 'get_weather', + description: 'Get the current weather for a city.', + parameters: Type.Object({ city: Type.String() }), + }, +]; +const question = { role: 'user', content: 'What is the weather in Berlin?', timestamp: Date.now() }; + +await Sentry.startSpan({ name: 'pi-ai-test' }, async () => { + const model = faux.getModel(); + const events = models.streamSimple(model, { + systemPrompt: 'You are a weather assistant.', + messages: [question], + tools, + }); + for await (const _event of events) { + // Drained like an app consuming the stream. + } + const toolCall = await events.result(); + + await models.complete(model, { + systemPrompt: 'You are a weather assistant.', + messages: [ + question, + toolCall, + { + role: 'toolResult', + toolCallId: 'call_1', + toolName: 'get_weather', + content: [{ type: 'text', text: 'sunny' }], + isError: false, + timestamp: Date.now(), + }, + ], + tools, + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts new file mode 100644 index 000000000000..2eb62f82eaaa --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts @@ -0,0 +1,117 @@ +import type { SerializedStreamedSpan } from '@sentry/core'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MODEL, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import { afterAll, describe, expect } from 'vitest'; +import { supports } from '../../../utils'; +import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner'; + +/** The chat spans under `rootSpanId`, in request order, with what every pi-ai request reports. */ +function chatSpans(spans: SerializedStreamedSpan[], rootSpanId: string): SerializedStreamedSpan[] { + const chats = spans + .filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_CHAT) + .sort((a, b) => a.start_timestamp - b.start_timestamp); + for (const chat of chats) { + expect(chat.parent_span_id).toBe(rootSpanId); + expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai'); + expect(chat.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('chat'); + expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0); + expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0); + } + return chats; +} + +// `@earendil-works/pi-ai` declares `engines.node >= 22.19`. +describe.runIf(supports({ min: 22 }))('pi-ai integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + // `@earendil-works/pi-ai` is ESM-only, so there is no CJS variant of this scenario to run. + createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('traces the requests sent through a `Models` collection', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items; + const root = spans.find(span => span.is_segment)!; + expect(root.name).toBe('pi-ai-test'); + + // One span per request: `complete` awaits a `stream` of its own, and no provider SDK + // reports the request a second time. + const chats = chatSpans(spans, root.span_id); + expect(chats.map(chat => chat.name)).toEqual(['chat faux-model', 'chat faux-model']); + + const [toolCall, answer] = chats; + expect(toolCall!.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('faux'); + expect(toolCall!.attributes[GEN_AI_REQUEST_MODEL]?.value).toBe('faux-model'); + expect(toolCall!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); + expect(toolCall!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]?.value).toBe('You are a weather assistant.'); + expect(toolCall!.attributes[GEN_AI_TOOL_DEFINITIONS]?.value).toContain('get_weather'); + expect(toolCall!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["tool_call"]'); + expect(JSON.parse(String(toolCall!.attributes[GEN_AI_INPUT_MESSAGES]?.value))).toEqual([ + { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Berlin?' }] }, + ]); + expect(JSON.parse(String(toolCall!.attributes[GEN_AI_OUTPUT_MESSAGES]?.value))).toEqual([ + { + role: 'assistant', + parts: [{ type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Berlin"}' }], + finish_reason: 'tool_call', + }, + ]); + + expect(answer!.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined(); + expect(answer!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["stop"]'); + expect( + JSON.parse(String(answer!.attributes[GEN_AI_INPUT_MESSAGES]?.value)).map( + (message: { role: string }) => message.role, + ), + ).toEqual(['user', 'assistant', 'tool']); + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario-compat.mjs', 'instrument.mjs', (createRunner, test) => { + // `compat` loads pi-ai's model catalog with `import ... with { type: 'json' }`. Deno 2.8 drops + // the import attributes once any module hook is registered and compiles the JSON as JavaScript, + // which Deno 2.9 fixed. The SDK registers one for its runtime instrumentation. + test.runIf(supports({ runtimes: ['node', 'bun'] }))( + 'traces the requests sent through the standalone functions', + async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const root = container.items.find(span => span.is_segment)!; + const [completed, streamed] = chatSpans(container.items, root.span_id); + expect([completed!.name, streamed!.name]).toEqual(['chat compat-model', 'chat compat-model']); + + expect(completed!.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('compat-faux'); + expect(completed!.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined(); + expect(streamed!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); + expect(streamed!.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toContain('Goodbye.'); + }, + }) + .start() + .completed(); + }, + ); + }); +}); diff --git a/packages/astro/src/index.server.ts b/packages/astro/src/index.server.ts index f407a5723a5b..6517237ee08e 100644 --- a/packages/astro/src/index.server.ts +++ b/packages/astro/src/index.server.ts @@ -110,6 +110,7 @@ export { createFlueInstrumentation, instrumentPostgresJsSql, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/aws-serverless/src/index.ts b/packages/aws-serverless/src/index.ts index f7310775b554..d521547acf55 100644 --- a/packages/aws-serverless/src/index.ts +++ b/packages/aws-serverless/src/index.ts @@ -68,6 +68,7 @@ export { langChainIntegration, langGraphIntegration, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/bun/src/index.ts b/packages/bun/src/index.ts index 678df401163e..1d86a3a95767 100644 --- a/packages/bun/src/index.ts +++ b/packages/bun/src/index.ts @@ -92,6 +92,7 @@ export { langChainIntegration, langGraphIntegration, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts index 53f571f5010a..626f0531d5e4 100644 --- a/packages/cloudflare/src/index.ts +++ b/packages/cloudflare/src/index.ts @@ -194,6 +194,7 @@ export { neonIntegration, nitroIntegration, openAIIntegration, + piAiIntegration, piDurableIntegration, postgresIntegration, postgresJsIntegration, diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts index 4cf53f81d690..ffa1f3fd410c 100644 --- a/packages/deno/src/index.ts +++ b/packages/deno/src/index.ts @@ -177,6 +177,7 @@ export { langChainIntegration, langGraphIntegration, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/elysia/src/index.ts b/packages/elysia/src/index.ts index 107545f0cb43..b26b2409106f 100644 --- a/packages/elysia/src/index.ts +++ b/packages/elysia/src/index.ts @@ -69,6 +69,7 @@ export { langGraphIntegration, createFlueInstrumentation, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/google-cloud-serverless/src/index.ts b/packages/google-cloud-serverless/src/index.ts index 107674b83b95..a9040905f9c9 100644 --- a/packages/google-cloud-serverless/src/index.ts +++ b/packages/google-cloud-serverless/src/index.ts @@ -68,6 +68,7 @@ export { langChainIntegration, langGraphIntegration, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 5297b54a8c25..27c162b96f00 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -33,6 +33,7 @@ export { lruMemoizerIntegration, createFlueInstrumentation, mastraIntegration, + piAiIntegration, piDurableIntegration, mcpServerIntegration, SentryMastraExporter, diff --git a/packages/server-utils/src/ai/pi-ai/constants.ts b/packages/server-utils/src/ai/pi-ai/constants.ts new file mode 100644 index 000000000000..18fe024306c6 --- /dev/null +++ b/packages/server-utils/src/ai/pi-ai/constants.ts @@ -0,0 +1,3 @@ +export const PI_AI_INTEGRATION_NAME = 'PiAi' as const; + +export const PI_AI_ORIGIN = 'auto.ai.pi_ai'; diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 77c1fd37c2ea..a868b461654b 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -57,6 +57,7 @@ export { langChainIntegration } from './integrations/langchain'; export { langGraphIntegration } from './integrations/langgraph'; export { createFlueInstrumentation } from './ai/flue'; export { flueIntegration } from './integrations/flue'; +export { piAiIntegration } from './integrations/pi-ai'; export { piDurableIntegration } from './integrations/pi-durable'; export type { FlueOptions } from './ai/flue'; export { mastraIntegration } from './integrations/mastra'; diff --git a/packages/server-utils/src/integrations/pi-ai.ts b/packages/server-utils/src/integrations/pi-ai.ts new file mode 100644 index 000000000000..7ac0a34fd781 --- /dev/null +++ b/packages/server-utils/src/integrations/pi-ai.ts @@ -0,0 +1,112 @@ +import * as diagnosticsChannel from '../utils/diagnosticsChannel'; +import type { IntegrationFn, Span } from '@sentry/core'; +import { defineIntegration, isThenable, startInactiveSpan } from '@sentry/core'; +import type { GenAiOptions } from '../ai/core/utils'; +import { resolveAIRecordingOptions } from '../ai/core/utils'; +import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../ai/pi-ai/chat'; +import { PI_AI_INTEGRATION_NAME, PI_AI_ORIGIN } from '../ai/pi-ai/constants'; +import type { PiAiContext } from '../ai/pi-ai/messages'; +import { skipPiAiProviderIntegrations } from '../ai/pi-ai/providers'; +import type { PiEventStream, PiStreamOptions } from '../ai/pi-ai/types'; +import type { OrchestrionChannelContext } from '../orchestrion/types'; +import { CHANNELS } from '../orchestrion/channels'; +import { piAiModuleNames } from '../orchestrion/config/pi-ai'; +import { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation'; +import { bindTracingChannelToSpan } from '../tracing-channel'; + +export type PiAiOptions = GenAiOptions; + +const _piAiIntegration = ((options: PiAiOptions = {}) => { + return { + name: PI_AI_INTEGRATION_NAME, + setup(client) { + invokeOrchestrionInstrumentation(client, piAiModuleNames, instrumentPiAi, [options]); + }, + }; +}) satisfies IntegrationFn; + +function instrumentPiAi(options: PiAiOptions): void { + const streamChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_STREAM); + const completeChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_COMPLETE); + + // `complete` awaits `stream`, and the `compat` functions hand some models to a `Models` of their + // own, so a traced call can make another one synchronously. Only the outermost gets a span. + let depth = 0; + const startSpan = (data: OrchestrionChannelContext, streaming: boolean): Span | undefined => { + if (depth > 0) { + return undefined; + } + skipPiAiProviderIntegrations(); + const [model, context, callOptions] = data.arguments ?? []; + return startInactiveSpan( + getPiAiChatSpanOptions({ + model: model ?? {}, + // The deferred calls pass a handle here, which carries no request content. + context: context as PiAiContext | undefined, + callOptions: callOptions as PiStreamOptions | undefined, + streaming, + origin: PI_AI_ORIGIN, + recordInputs: resolveAIRecordingOptions(options).recordInputs, + }), + ); + }; + + const setResponse = (span: Span, message: unknown): void => { + if (message && typeof message === 'object') { + setPiAiResponseAttributes(span, message, resolveAIRecordingOptions(options).recordOutputs); + } + }; + + bindTracingChannelToSpan(streamChannel, data => startSpan(data, true), { + // The stream is returned before the request settles; its `result()` settles with the message. + deferSpanEnd: ({ span, data, end }) => { + const events = data.result as Partial | undefined; + const settled = 'error' in data || typeof events?.result !== 'function' ? undefined : events.result(); + if (!isThenable(settled)) { + return false; + } + settled.then(message => { + setResponse(span, message); + end(); + }, end); + return true; + }, + }); + + bindTracingChannelToSpan(completeChannel, data => startSpan(data, false), { + beforeSpanEnd: (span, data) => { + if (!('error' in data)) { + setResponse(span, data.result); + } + }, + }); + + for (const channel of [streamChannel, completeChannel]) { + channel.start.subscribe(() => { + depth++; + }); + channel.end.subscribe(() => { + depth--; + }); + } +} + +/** + * Traces the requests sent with pi-ai (`@earendil-works/pi-ai` >= 0.80.0 < 2) as `gen_ai.chat` spans, + * through `createModels()` or the standalone `stream` and `complete` functions. Needs the Sentry + * runtime hook (`--import`) or bundler plugin. + * + * Not enabled by default yet. Flue and pi-durable send their model calls through pi-ai and still + * report them as chat spans of their own, so enabling this alongside them reports each call twice. + * + * Once pi-ai has sent a request, the `openai`, `@anthropic-ai/sdk`, `@google/genai` and Workers AI + * integrations stop recording requests for the rest of the process, since pi-ai sends through them. + * + * @example + * ```javascript + * Sentry.init({ + * integrations: [Sentry.piAiIntegration()], + * }); + * ``` + */ +export const piAiIntegration = defineIntegration(_piAiIntegration); diff --git a/packages/server-utils/src/orchestrion/channels.ts b/packages/server-utils/src/orchestrion/channels.ts index f593fefe0ebd..44d91bbaef28 100644 --- a/packages/server-utils/src/orchestrion/channels.ts +++ b/packages/server-utils/src/orchestrion/channels.ts @@ -31,6 +31,7 @@ import { nodeCronChannels } from './config/node-cron'; import { nodeScheduleChannels } from './config/node-schedule'; import { openaiChannels } from './config/openai'; import { pgChannels } from './config/pg'; +import { piAiChannels } from './config/pi-ai'; import { piDurableChannels } from './config/pi-durable'; import { postgresJsChannels } from './config/postgres'; import { prismaChannels } from './config/prisma'; @@ -91,6 +92,7 @@ export const CHANNELS = { ...nodeScheduleChannels, ...openaiChannels, ...pgChannels, + ...piAiChannels, ...piDurableChannels, ...postgresJsChannels, ...prismaChannels, diff --git a/packages/server-utils/src/orchestrion/config/index.ts b/packages/server-utils/src/orchestrion/config/index.ts index 7636fbef80fc..6c5b11dc1d5e 100644 --- a/packages/server-utils/src/orchestrion/config/index.ts +++ b/packages/server-utils/src/orchestrion/config/index.ts @@ -24,6 +24,7 @@ import { langgraphConfig } from './langgraph'; import { lruMemoizerConfig } from './lru-memoizer'; import { flueConfig } from './flue'; import { mastraConfig } from './mastra'; +import { piAiConfig } from './pi-ai'; import { piDurableConfig } from './pi-durable'; import { mcpServerConfig } from './mcp-server'; import { mistralConfig } from './mistral'; @@ -99,6 +100,7 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [ ...nodeScheduleConfig, ...openaiConfig, ...pgConfig, + ...piAiConfig, ...piDurableConfig, ...postgresJsConfig, ...prismaConfig, diff --git a/packages/server-utils/src/orchestrion/config/pi-ai.ts b/packages/server-utils/src/orchestrion/config/pi-ai.ts new file mode 100644 index 000000000000..c42a4aca2937 --- /dev/null +++ b/packages/server-utils/src/orchestrion/config/pi-ai.ts @@ -0,0 +1,44 @@ +import type { InstrumentationConfig } from '../apmTypes'; + +import { getModuleNames } from './module-names'; + +const module = { name: '@earendil-works/pi-ai', versionRange: '>=0.80.0 <2.0.0' }; + +type Kind = 'Sync' | 'Async'; + +const modelsMethod = (methodName: string, channelName: string, kind: Kind): InstrumentationConfig => ({ + channelName, + module: { ...module, filePath: 'dist/models.js' }, + functionQuery: { className: 'ModelsImpl', methodName, kind }, +}); + +const compatFunction = (functionName: string, channelName: string, kind: Kind): InstrumentationConfig => ({ + channelName, + module: { ...module, filePath: 'dist/compat.js' }, + functionQuery: { functionName, kind }, +}); + +// `ModelsImpl` is what `createModels()` returns, and what Flue and pi-durable send their requests +// through; the `compat` functions are the standalone API. The `complete` functions only await the +// stream of their `stream` counterpart, and the integration leaves out that nested call, so the +// span of a request still tells whether its caller streamed it. `streamDeferred` and `fetchDeferred` +// fetch the answer of a request the provider parked. +export const piAiConfig = [ + modelsMethod('stream', 'stream', 'Sync'), + modelsMethod('streamSimple', 'stream', 'Sync'), + compatFunction('stream', 'stream', 'Sync'), + compatFunction('streamSimple', 'stream', 'Sync'), + modelsMethod('complete', 'complete', 'Async'), + modelsMethod('completeSimple', 'complete', 'Async'), + compatFunction('complete', 'complete', 'Async'), + compatFunction('completeSimple', 'complete', 'Async'), + modelsMethod('streamDeferred', 'stream', 'Sync'), + modelsMethod('fetchDeferred', 'complete', 'Async'), +] satisfies InstrumentationConfig[]; + +export const piAiModuleNames = getModuleNames(piAiConfig); + +export const piAiChannels = { + PI_AI_STREAM: 'orchestrion:@earendil-works/pi-ai:stream', + PI_AI_COMPLETE: 'orchestrion:@earendil-works/pi-ai:complete', +} as const; diff --git a/packages/server-utils/test/integrations/pi-ai.test.ts b/packages/server-utils/test/integrations/pi-ai.test.ts new file mode 100644 index 000000000000..a062e191a6e7 --- /dev/null +++ b/packages/server-utils/test/integrations/pi-ai.test.ts @@ -0,0 +1,380 @@ +import { tracingChannel } from 'node:diagnostics_channel'; +import type { Span } from '@sentry/core'; +import { + _INTERNAL_clearAiProviderSkips, + _INTERNAL_shouldSkipAiProviderWrapping, + _INTERNAL_skipAiProviderWrapping, + GLOBAL_OBJ, + setAsyncContextStrategy, + setCurrentClient, + spanToJSON, + spanToStaticSpanJSON, + startInactiveSpan, + startSpan, + withScope, +} from '@sentry/core'; +import { + GEN_AI_CONVERSATION_ID, + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MAX_TOKENS, + GEN_AI_REQUEST_MODEL, + GEN_AI_REQUEST_REASONING_LEVEL, + GEN_AI_REQUEST_TEMPERATURE, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, + GEN_AI_RESPONSE_MODEL, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, + SENTRY_STATUS_MESSAGE, + SERVER_ADDRESS, + SERVER_PORT, +} from '@sentry/conventions/attributes'; +import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { ANTHROPIC_AI_INTEGRATION_NAME } from '../../src/ai/anthropic-ai/constants'; +import { GOOGLE_GENAI_INTEGRATION_NAME } from '../../src/ai/google-genai/constants'; +import { OPENAI_INTEGRATION_NAME } from '../../src/ai/openai/constants'; +import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../../src/ai/pi-ai/chat'; +import { PI_AI_ORIGIN } from '../../src/ai/pi-ai/constants'; +import { setAsyncLocalStorageAsyncContextStrategy } from '../../src/async-context'; +import type { PiEventStream } from '../../src/ai/pi-ai/types'; +import { instrumentWorkersAiClient } from '../../src/ai/workers-ai'; +import { piAiIntegration } from '../../src/integrations/pi-ai'; +import { CHANNELS } from '../../src/orchestrion/channels'; +import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; + +const MODEL = { id: 'faux-model', provider: 'faux' }; +const ANSWER = { role: 'assistant', content: [{ type: 'text', text: 'Paris.' }], stopReason: 'stop' }; + +const streamChannel = tracingChannel(CHANNELS.PI_AI_STREAM); +const completeChannel = tracingChannel(CHANNELS.PI_AI_COMPLETE); + +// What the orchestrion transform turns the pi-ai entry points into. +function stream(send: () => unknown, ...args: unknown[]): PiEventStream { + return streamChannel.traceSync(send, { arguments: args }) as PiEventStream; +} + +function complete(send: () => Promise, ...args: unknown[]): Promise { + return completeChannel.tracePromise(send, { arguments: args }); +} + +function settlesWith(message: unknown): () => PiEventStream { + return () => ({ result: async () => message }) as PiEventStream; +} + +describe('piAiIntegration', () => { + let endedSpans: Span[]; + let client: TestClient; + + function useClient(options: Partial[0]> = {}): void { + client = new TestClient( + getDefaultTestClientOptions({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1, ...options }), + ); + setCurrentClient(client); + client.init(); + client.on('spanEnd', span => endedSpans.push(span)); + } + + beforeAll(() => { + setAsyncLocalStorageAsyncContextStrategy(); + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { runtime: ['@earendil-works/pi-ai'] }; + useClient(); + piAiIntegration().setup!(client); + }); + + afterAll(() => { + setAsyncContextStrategy(undefined); + delete GLOBAL_OBJ.__SENTRY_ORCHESTRION__; + }); + + beforeEach(() => { + _INTERNAL_clearAiProviderSkips(); + endedSpans = []; + useClient(); + }); + + it('ends a streamed span only once its result settles', async () => { + let settle!: (message: unknown) => void; + const result = new Promise(resolve => { + settle = resolve; + }); + + const events = stream(() => ({ result: () => result }), MODEL, { messages: [] }); + expect(endedSpans).toHaveLength(0); + + settle(ANSWER); + await events.result(); + expect(endedSpans).toHaveLength(1); + }); + + it.each([true, false])('traces a request with its options and response identity (streaming: %s)', async streaming => { + const message = { + ...ANSWER, + responseModel: 'faux-model-2026', + responseId: 'resp_1', + usage: { input: 10, output: 2, totalTokens: 12 }, + }; + const args = [ + { ...MODEL, baseUrl: 'https://api.example.com:8443/v1' }, + { messages: [{ role: 'user', content: 'Hi.' }] }, + { temperature: 0.2, maxTokens: 50, reasoning: 'low' }, + ]; + + await (streaming ? stream(settlesWith(message), ...args).result() : complete(async () => message, ...args)); + + const chat = spanToJSON(endedSpans[0]!); + expect(chat.name).toBe('chat faux-model'); + expect(chat.attributes).toMatchObject({ + [SENTRY_OP]: GEN_AI_CHAT, + [SENTRY_ORIGIN]: 'auto.ai.pi_ai', + [GEN_AI_PROVIDER_NAME]: 'faux', + [GEN_AI_REQUEST_MODEL]: 'faux-model', + [GEN_AI_RESPONSE_MODEL]: 'faux-model-2026', + [GEN_AI_RESPONSE_ID]: 'resp_1', + [SERVER_ADDRESS]: 'api.example.com', + [SERVER_PORT]: 8443, + [GEN_AI_REQUEST_TEMPERATURE]: 0.2, + [GEN_AI_REQUEST_MAX_TOKENS]: 50, + [GEN_AI_REQUEST_REASONING_LEVEL]: 'low', + [GEN_AI_INPUT_MESSAGES]: '[{"role":"user","parts":[{"type":"text","content":"Hi."}]}]', + [GEN_AI_OUTPUT_MESSAGES]: + '[{"role":"assistant","parts":[{"type":"text","content":"Paris."}],"finish_reason":"stop"}]', + [GEN_AI_RESPONSE_FINISH_REASONS]: '["stop"]', + [GEN_AI_USAGE_INPUT_TOKENS]: 10, + [GEN_AI_USAGE_OUTPUT_TOKENS]: 2, + }); + expect(chat.attributes[GEN_AI_RESPONSE_STREAMING]).toBe(streaming ? true : undefined); + }); + + // `streamDeferred` and `fetchDeferred` pass the handle of a parked request where the others pass it. + it('records no request content for a call that fetches a parked request', async () => { + await stream(settlesWith(ANSWER), MODEL, { id: 'handle_1' }, { signal: new AbortController().signal }).result(); + + const recorded = Object.keys(spanToJSON(endedSpans[0]!).attributes); + expect(recorded).not.toContain(GEN_AI_INPUT_MESSAGES); + expect(recorded).not.toContain(GEN_AI_SYSTEM_INSTRUCTIONS); + expect(recorded).not.toContain(GEN_AI_TOOL_DEFINITIONS); + }); + + // `complete` awaits the stream of `stream`, and the `compat` functions hand some models to a + // `Models` of their own: each is one request. + it('traces a call that makes another traced call as one request', async () => { + await complete(() => stream(settlesWith(ANSWER), MODEL, { messages: [] }).result(), MODEL, { messages: [] }); + await stream(() => stream(settlesWith(ANSWER), MODEL, { messages: [] }), MODEL, { messages: [] }).result(); + + expect(endedSpans.map(span => spanToJSON(span).attributes[GEN_AI_RESPONSE_STREAMING])).toEqual([undefined, true]); + }); + + it('traces requests after a nested one, and after one that threw', async () => { + expect(() => + stream(() => { + throw new Error('sync boom'); + }, MODEL), + ).toThrow('sync boom'); + await complete(() => stream(settlesWith(ANSWER), MODEL).result(), MODEL); + await complete(async () => ANSWER, MODEL); + + expect(endedSpans).toHaveLength(3); + }); + + it('parents the span to the active span and makes it active for the provider call', async () => { + let providerParent: string | undefined; + + await startSpan({ name: 'agent' }, async parent => { + await stream( + () => { + providerParent = startSpan({ name: 'provider' }, span => spanToJSON(span).parent_span_id); + return { result: async () => ANSWER }; + }, + MODEL, + { messages: [] }, + ).result(); + + const chat = endedSpans.map(span => spanToJSON(span)).find(span => span.attributes[SENTRY_OP] === GEN_AI_CHAT)!; + expect(chat.parent_span_id).toBe(parent.spanContext().spanId); + expect(providerParent).toBe(chat.span_id); + }); + }); + + it('sets the conversation id of the scope on the chat span', async () => { + await withScope(async scope => { + scope.setConversationId('harness:7'); + await complete(async () => ANSWER, MODEL, { messages: [] }); + }); + + expect(spanToJSON(endedSpans[0]!).attributes[GEN_AI_CONVERSATION_ID]).toBe('harness:7'); + }); + + // The provider parks the request and the caller fetches the answer later: only the fetch is billed. + it('records no usage for a request the provider parked, and the usage of its answer', async () => { + const parked = { role: 'assistant', content: [], stopReason: 'deferred', usage: { input: 0, totalTokens: 0 } }; + const answer = { ...ANSWER, usage: { input: 8, output: 2, totalTokens: 10 } }; + + await complete(async () => parked, MODEL, { messages: [] }); + await complete(async () => answer, MODEL, { id: 'handle_1' }); + + const [parkedChat, answerChat] = endedSpans.map(span => spanToJSON(span).attributes); + expect(parkedChat![GEN_AI_RESPONSE_FINISH_REASONS]).toBe('["deferred"]'); + expect(parkedChat![GEN_AI_USAGE_TOTAL_TOKENS]).toBeUndefined(); + expect(answerChat![GEN_AI_USAGE_TOTAL_TOKENS]).toBe(10); + }); + + it('marks a failed or aborted request with a fixed status message and maps a tool-calling stop', async () => { + const failed = { + role: 'assistant', + content: [], + stopReason: 'error', + errorMessage: '401 invalid x-api-key for user@example.com', + usage: { input: 0, output: 0, totalTokens: 0 }, + }; + const aborted = { role: 'assistant', content: [], stopReason: 'aborted' }; + const toolCall = { + role: 'assistant', + content: [{ type: 'toolCall', id: 'call_1', name: 'read', arguments: { path: 'a.txt' } }], + stopReason: 'toolUse', + }; + + await complete(async () => failed, MODEL, { messages: [] }); + await stream(settlesWith(aborted), MODEL, { messages: [] }).result(); + await complete(async () => toolCall, MODEL, { messages: [] }); + + const [chatFailed, , chatToolCall] = endedSpans.map(span => spanToJSON(span)); + expect(chatFailed!.status).toBe('error'); + expect(chatFailed!.attributes[SENTRY_STATUS_MESSAGE]).toBe('internal_error'); + expect(JSON.stringify(chatFailed!.attributes)).not.toContain('x-api-key'); + expect(chatFailed!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toBeUndefined(); + // Streamed span JSON reports a cancellation as `ok`; the static one keeps it. + expect(spanToStaticSpanJSON(endedSpans[1]!).status).toBe('cancelled'); + expect(chatToolCall!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toBe('["tool_call"]'); + expect(chatToolCall!.attributes[GEN_AI_OUTPUT_MESSAGES]).toContain('"finish_reason":"tool_call"'); + }); + + it('marks a rejected, throwing or broken request as errored and keeps the error', async () => { + await expect( + complete(async () => { + throw new Error('boom'); + }, MODEL), + ).rejects.toThrow('boom'); + expect(() => + stream(() => { + throw new Error('sync boom'); + }, MODEL), + ).toThrow('sync boom'); + const broken = stream(() => ({ result: () => Promise.reject(new Error('broken provider')) }), MODEL); + await expect(broken.result()).rejects.toThrow('broken provider'); + + expect(endedSpans.map(span => spanToJSON(span).status)).toEqual(['error', 'error', 'error']); + }); + + it('returns a result of another shape unchanged and ends its span', () => { + const events = { events: [] }; + + expect(stream(() => events, MODEL)).toBe(events); + + expect(endedSpans.map(span => spanToJSON(span).attributes[SENTRY_OP])).toEqual([GEN_AI_CHAT]); + }); + + describe('provider skip', () => { + it('skips the provider integrations on the first request, not at setup', async () => { + expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); + + await complete(async () => ANSWER, MODEL, { messages: [] }); + + expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); + expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); + expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); + }); + + // The registry is reset per client, so a one-shot call would be undone by the next `init()`. + it('applies the skip again after the registry is cleared', async () => { + await complete(async () => ANSWER, MODEL, { messages: [] }); + _INTERNAL_clearAiProviderSkips(); + expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); + + await complete(async () => ANSWER, MODEL, { messages: [] }); + + expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); + }); + + it('applies the skip to every provider when only some are already registered', async () => { + _INTERNAL_skipAiProviderWrapping([OPENAI_INTEGRATION_NAME]); + + await complete(async () => ANSWER, MODEL, { messages: [] }); + + expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); + expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); + }); + + // `createAI()` of `agents/models/pi-ai` sends pi-ai requests through the Workers AI binding. + it('reports a request sent through the Workers AI binding once', async () => { + const ai = instrumentWorkersAiClient({ + run: async (_model: string, _inputs: unknown, _options: unknown) => new Response('{}'), + gateway: () => ({}), + toMarkdown: async () => [], + }); + + await complete( + async () => { + await ai.run('@cf/moonshotai/kimi-k2.7-code', { messages: [] }, { returnRawResponse: true }); + return ANSWER; + }, + MODEL, + { messages: [] }, + ); + + expect(endedSpans.map(span => spanToJSON(span).name)).toEqual(['chat faux-model']); + }); + }); + + describe('content recording', () => { + const message = { + role: 'assistant', + content: [{ type: 'toolCall', id: 'call_1', name: 'get_weather', arguments: { city: 'Berlin' } }], + stopReason: 'toolUse', + }; + const context = { + messages: [ + { role: 'system', content: '', sections: { preamble: 'You help.' }, toolsAdded: [{ name: 'get_weather' }] }, + { role: 'user', content: 'Weather in Berlin?' }, + ], + }; + const CONTENT_ATTRIBUTES = [ + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, + ]; + + it('records nothing when inputs and outputs are off', () => { + const span = startInactiveSpan( + getPiAiChatSpanOptions({ model: MODEL, context, streaming: false, origin: PI_AI_ORIGIN, recordInputs: false }), + ); + setPiAiResponseAttributes(span, message, false); + span.end(); + + const recorded = Object.keys(spanToJSON(span).attributes); + for (const attribute of CONTENT_ATTRIBUTES) { + expect(recorded).not.toContain(attribute); + } + }); + + it('follows the data collection settings of the current client', async () => { + useClient({ dataCollection: { genAI: { inputs: false, outputs: false } } }); + + await complete(async () => message, MODEL, context); + + const recorded = endedSpans.flatMap(span => Object.keys(spanToJSON(span).attributes)); + for (const attribute of CONTENT_ATTRIBUTES) { + expect(recorded).not.toContain(attribute); + } + }); + }); +}); diff --git a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts index 2e60db9729c0..037639bc6b73 100644 --- a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts +++ b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts @@ -44,7 +44,8 @@ describe('channel integration definitions', () => { // `@nestjs/*` and `@remix-run/*` are covered by listeners in their own SDK packages. // Each cron monitor is billed, so bundler-only SDKs must not install crons integrations for every app. - const optIn = new Set(['cron', 'node-cron', 'node-schedule']); + // pi-ai would duplicate Flue's and pi-durable's own chat spans until they rely on it. + const optIn = new Set(['cron', 'node-cron', 'node-schedule', '@earendil-works/pi-ai']); const uncovered = [...configured].filter( name => !defined.has(name) && !optIn.has(name) && !name.startsWith('@nestjs/') && !name.startsWith('@remix-run/'), ); From a5d2d5cd9ede7d9803b3c9e151e3a34656b5ff1d Mon Sep 17 00:00:00 2001 From: Francesco Gringl-Novy Date: Thu, 12 Nov 2026 11:26:40 +0100 Subject: [PATCH 045/136] feat(server-utils): Enable pi-ai by default & use it for Flue & pi-durable (#25940) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Flue and pi-durable both send their model calls through pi-ai, and each had its own chat-span code (Flue's turn observations, pi-durable's `models` proxy). With `piAiIntegration` (#25937) enabled by default, pi-ai becomes the single source of `gen_ai.chat` spans, and ~1.1k lines of duplicated span code go away. Flue now hands its conversation id to the pi-ai span through the scope. Stack: #25932 → #25937 → this. #25935 must be merged before #25937 and this: without it, instrumenting pi-ai makes the Cloudflare Flue worker crash at startup. Supersedes #25869. **How to review:** The first commit is the switch. The second adds a one-time warning when Flue runs but pi-ai was not instrumented; it's separate so it can be dropped or split off. The next three scope the provider skip to pi-ai's own requests, make that warning runtime-specific, and keep the Flue and pi-durable recording options working on chat spans. The last two are cleanups: the active pi-ai span replaces the nesting counter, which also catches nested calls made after an `await`, and stale comments go. **Unsure about:** - Chat spans change origin from `auto.ai.flue` / `auto.ai.pi_durable` to `auto.ai.pi_ai`. - Flue's chat spans now need the runtime hook or bundler plugin; a manual-only `instrument(createFlueInstrumentation())` keeps agent and tool spans but loses chat spans, hence the warning. Setups following our docs are unaffected. - `flue.turn.purpose` (compaction vs. agent turn) is dropped, since pi-ai cannot see it. A possible follow-up is to record compaction the way getsentry/sentry-conventions#723 proposes, once it merges: Flue emits `compaction_start` (with a `manual`/`threshold`/`overflow` reason) and `compaction` observations, so it could open a `gen_ai.compact` span with the summarizing `gen_ai.chat` nested under it. - pi-durable records model calls only for a `models` object created with pi-ai's `createModels()`. **Release note:** > - **feat(server-utils): Add pi-ai integration** > > The new `piAiIntegration` traces requests sent with [pi-ai](https://github.com/earendil-works/pi) (`@earendil-works/pi-ai` >= 0.80) as `gen_ai.chat` spans, through `createModels()` or the standalone `stream`/`complete` functions. It is enabled by default and needs the Sentry runtime hook or bundler plugin. > > Requests pi-ai sends are reported once, as its `gen_ai.chat` span; direct calls to `openai`, `@anthropic-ai/sdk`, `@google/genai`, `@mistralai/mistralai` or Workers AI keep their own spans. > > Flue and pi-durable send their model calls through pi-ai, so their `gen_ai.chat` spans now come from this integration: > - Their origin changes from `auto.ai.flue` / `auto.ai.pi_durable` to `auto.ai.pi_ai`. Agent and tool spans keep their origin. > - Flue apps that only call `instrument(Sentry.createFlueInstrumentation())` need the runtime hook (`--import`) or bundler plugin for `gen_ai.chat` spans. Without it, the SDK logs a warning on the first model call. > - The `flue.turn.purpose` attribute is no longer set. > - `recordInputs` and `recordOutputs` on `createFlueInstrumentation()` and `piDurableIntegration()` keep applying to their `gen_ai.chat` spans. > - pi-durable records model calls only for a `models` object created with pi-ai's `createModels()`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- .../tests/flue.test.ts | 2 +- .../tests/pi-durable.test.ts | 4 +- .../node-flue/tests/flue.test.ts | 6 +- .../node-pi-durable/tests/pi-durable.test.ts | 6 +- .../suites/tracing/flue/scenario.mjs | 9 +- .../suites/tracing/flue/test.ts | 63 ++- .../suites/tracing/pi-ai/instrument.mjs | 1 - .../suites/tracing/pi-ai/scenario-bedrock.mjs | 92 +++++ .../tracing/pi-ai/scenario-provider-sdk.mjs | 76 ++++ .../suites/tracing/pi-ai/test.ts | 44 ++ .../suites/tracing/pi-durable/instrument.mjs | 3 + .../suites/tracing/pi-durable/test.ts | 103 ++--- .../server-utils/src/ai/flue/constants.ts | 12 +- packages/server-utils/src/ai/flue/index.ts | 130 +++--- packages/server-utils/src/ai/flue/types.ts | 44 +- packages/server-utils/src/ai/flue/utils.ts | 152 +------ packages/server-utils/src/ai/pi-ai/chat.ts | 13 +- .../server-utils/src/ai/pi-ai/providers.ts | 41 +- .../server-utils/src/ai/pi-ai/recording.ts | 31 ++ .../server-utils/src/ai/pi-durable/index.ts | 19 +- .../server-utils/src/ai/pi-durable/models.ts | 113 ----- .../server-utils/src/ai/pi-durable/types.ts | 24 +- .../server-utils/src/ai/workers-ai/index.ts | 14 +- .../src/integrations/anthropic.ts | 14 +- .../aws-sdk/services/bedrock-runtime.ts | 14 + .../src/integrations/google-genai.ts | 6 +- .../server-utils/src/integrations/index.ts | 2 + .../server-utils/src/integrations/mistral.ts | 7 +- .../server-utils/src/integrations/openai.ts | 13 +- .../server-utils/src/integrations/pi-ai.ts | 55 +-- .../src/integrations/pi-durable.ts | 7 +- .../config/channel-integration-definitions.ts | 1 + .../ai/lib/tracing/flue-pi-ai-warning.test.ts | 74 ++++ .../test/ai/lib/tracing/flue.test.ts | 386 +++--------------- .../test/ai/lib/tracing/pi-durable.test.ts | 375 ++--------------- .../test/integrations/pi-ai.test.ts | 187 +++++++-- .../moduleInjectedTransform.test.ts | 3 +- 37 files changed, 836 insertions(+), 1310 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-bedrock.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-provider-sdk.mjs create mode 100644 packages/server-utils/src/ai/pi-ai/recording.ts delete mode 100644 packages/server-utils/src/ai/pi-durable/models.ts create mode 100644 packages/server-utils/test/ai/lib/tracing/flue-pi-ai-warning.test.ts diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-flue-send-to-sentry/tests/flue.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-flue-send-to-sentry/tests/flue.test.ts index ac6c0dab180f..d7842f87eb3f 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-flue-send-to-sentry/tests/flue.test.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-flue-send-to-sentry/tests/flue.test.ts @@ -48,7 +48,7 @@ test('instruments a Flue agent with no manual instrument() call', async () => { await expect .poll(() => fetchSpanAttributes(traceId!, chat!.event_id!), EVENT_POLLING_OPTIONS) .toMatchObject({ - origin: 'auto.ai.flue', + origin: 'auto.ai.pi_ai', 'gen_ai.provider.name': 'openrouter', 'gen_ai.usage.input_tokens': expect.anything(), 'gen_ai.cost.total_tokens': expect.anything(), diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/tests/pi-durable.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/tests/pi-durable.test.ts index f27454078339..98b4d0f17519 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/tests/pi-durable.test.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/tests/pi-durable.test.ts @@ -53,7 +53,9 @@ test('traces a PiHarness prompt as invoke_agent with chat, execute_tool and prov // pi-ai sends the requests through `@anthropic-ai/sdk`, whose own integration must stay out so // each request is reported once. expect(spans.filter(span => String(span.attributes[SENTRY_ORIGIN]?.value).startsWith('auto.ai.'))).toEqual( - spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_durable'), + spans.filter(span => + ['auto.ai.pi_durable', 'auto.ai.pi_ai'].includes(String(span.attributes[SENTRY_ORIGIN]?.value)), + ), ); // One tool-calling response, then the answer. diff --git a/dev-packages/e2e-tests/test-applications/node-flue/tests/flue.test.ts b/dev-packages/e2e-tests/test-applications/node-flue/tests/flue.test.ts index a829a0ba282e..49c3197032d0 100644 --- a/dev-packages/e2e-tests/test-applications/node-flue/tests/flue.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-flue/tests/flue.test.ts @@ -33,11 +33,11 @@ test('captures the invoke_agent / chat / execute_tool hierarchy for a Flue turn' expect(invokeAgent?.attributes?.['gen_ai.operation.name']?.value).toBe('invoke_agent'); expect(invokeAgent?.attributes?.['gen_ai.agent.name']?.value).toBe('Hello'); - expect(chat?.attributes?.['sentry.origin']?.value).toBe('auto.ai.flue'); + expect(chat?.attributes?.['sentry.origin']?.value).toBe('auto.ai.pi_ai'); expect(chat?.attributes?.['gen_ai.provider.name']?.value).toBe('openrouter'); expect(typeof chat?.attributes?.['gen_ai.usage.input_tokens']?.value).toBe('number'); expect(typeof chat?.attributes?.['gen_ai.usage.output_tokens']?.value).toBe('number'); - // Flue computes cost itself; no provider SDK reports it. + // pi-ai computes cost itself; no provider SDK reports it. expect(typeof chat?.attributes?.['gen_ai.cost.total_tokens']?.value).toBe('number'); expect(executeTool?.attributes?.['gen_ai.tool.name']?.value).toBe('get_weather'); @@ -92,7 +92,7 @@ test('nests a manual span raised inside a tool under that tool span', async ({ b expect(manualSpan?.parent_span_id).toBe(executeTool?.span_id); }); -// Flue's `model` operation is wrapped so the turn span is active for it, which is what puts the +// The pi-ai integration makes the chat span active for the request it sends, which is what puts the // provider's HTTP call inside `chat` rather than beside it. test('nests the provider HTTP call inside the chat span', async ({ baseURL }) => { const spansPromise = collectStreamedSpans( diff --git a/dev-packages/e2e-tests/test-applications/node-pi-durable/tests/pi-durable.test.ts b/dev-packages/e2e-tests/test-applications/node-pi-durable/tests/pi-durable.test.ts index 3c18f1bc8cc3..42de516c91bc 100644 --- a/dev-packages/e2e-tests/test-applications/node-pi-durable/tests/pi-durable.test.ts +++ b/dev-packages/e2e-tests/test-applications/node-pi-durable/tests/pi-durable.test.ts @@ -52,14 +52,16 @@ test('traces a run as invoke_agent with chat, execute_tool and provider spans', // pi-ai sends the requests through `@anthropic-ai/sdk`, whose own integration must stay out so // each request is reported once. expect(spans.filter(span => String(span.attributes[SENTRY_ORIGIN]?.value).startsWith('auto.ai.'))).toEqual( - spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_durable'), + spans.filter(span => + ['auto.ai.pi_durable', 'auto.ai.pi_ai'].includes(String(span.attributes[SENTRY_ORIGIN]?.value)), + ), ); // One tool-calling response, then the answer. expect(chats.length).toBeGreaterThanOrEqual(2); for (const chat of chats) { expect(chat.parent_span_id).toBe(agent.span_id); - expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_durable'); + expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai'); expect(chat.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('openrouter'); expect(chat.attributes[GEN_AI_REQUEST_MODEL]?.value).toBe('anthropic/claude-haiku-4.5'); // pi-durable retries a provider error inside the run; such a request has no usage and no HTTP span diff --git a/dev-packages/node-integration-tests/suites/tracing/flue/scenario.mjs b/dev-packages/node-integration-tests/suites/tracing/flue/scenario.mjs index b71b000bf18f..ca4bde7c1f58 100644 --- a/dev-packages/node-integration-tests/suites/tracing/flue/scenario.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/flue/scenario.mjs @@ -4,10 +4,15 @@ import { start } from '@flue/runtime/node'; import { fauxAssistantMessage, fauxProvider, fauxToolCall } from '@earendil-works/pi-ai/providers/faux'; import * as v from 'valibot'; +const recording = process.env.FLUE_RECORDING === 'on'; +instrument( + Sentry.createFlueInstrumentation( + process.env.FLUE_RECORDING ? { recordInputs: recording, recordOutputs: recording } : undefined, + ), +); + // `pi-ai`'s faux provider scripts model responses in-process, so the run is deterministic and needs // no provider key or mock server. Two steps: a tool call, then the final answer. -instrument(Sentry.createFlueInstrumentation()); - const faux = fauxProvider({ provider: 'faux', models: [{ id: 'faux-model', cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 } }], diff --git a/dev-packages/node-integration-tests/suites/tracing/flue/test.ts b/dev-packages/node-integration-tests/suites/tracing/flue/test.ts index 83c73526b43e..68e5dc6eb8c0 100644 --- a/dev-packages/node-integration-tests/suites/tracing/flue/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/flue/test.ts @@ -40,9 +40,11 @@ describe.runIf(supports({ min: 22 }))('Flue integration', () => { expect(root.is_segment).toBe(true); // Counted rather than looked up: the interceptor skips the submission wrapper - // operation, so one dispatch opens exactly one agent span, and each turn and tool call - // is spanned once. `find` passes just as happily on a duplicate. - expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.flue')).toHaveLength(4); + // operation, so one dispatch opens exactly one agent span, and each tool call is spanned + // once. Each turn is spanned once by the pi-ai integration: a provider SDK reporting the + // same request would add a span. `find` passes just as happily on a duplicate. + expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.flue')).toHaveLength(2); + expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_ai')).toHaveLength(2); const agents = spans.filter(span => span.name === 'invoke_agent Hello'); const chats = spans.filter(span => span.name === 'chat faux-model'); @@ -62,17 +64,17 @@ describe.runIf(supports({ min: 22 }))('Flue integration', () => { expect(conversationId).toEqual(expect.any(String)); // Both turns, not just the first: they leave the provider by different paths (a tool - // call, then a final answer) and resolve their parent through separate tracker lookups. + // call, then a final answer). for (const chat of chats) { expect(chat.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT); - expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.flue'); + expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai'); expect(chat.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('chat'); expect(chat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); expect(chat.parent_span_id).toBe(agent.span_id); expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0); expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0); expect(chat.attributes[GEN_AI_USAGE_TOTAL_TOKENS]?.value).toBeGreaterThan(0); - // Flue computes cost itself; no provider SDK reports it. The faux provider prices + // pi-ai computes cost itself; no provider SDK reports it. The faux provider prices // every model at zero, so this only proves the attribute is mapped. expect(chat.attributes[GEN_AI_COST_TOTAL_TOKENS]?.value).toEqual(expect.any(Number)); } @@ -101,6 +103,55 @@ describe.runIf(supports({ min: 22 }))('Flue integration', () => { }); }); + // `instrument-with-pii.mjs` turns recording on and `instrument.mjs` off, so the options of the Flue + // instrumentation decide here. + createEsmTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('keeps message content off chat and tool spans when the Flue options turn recording off', async () => { + await createRunner() + .withEnv({ FLUE_RECORDING: 'off' }) + .expect({ + span: container => { + const chats = container.items.filter(span => span.name === 'chat faux-model'); + const tools = container.items.filter(span => span.name === 'execute_tool get_weather'); + expect(chats).toHaveLength(2); + expect(tools).toHaveLength(1); + for (const span of [...chats, ...tools]) { + for (const attribute of [ + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_CALL_ARGUMENTS, + GEN_AI_TOOL_CALL_RESULT, + ]) { + expect(span.attributes[attribute]).toBeUndefined(); + } + } + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('records message content on chat spans when the Flue options turn recording on', async () => { + await createRunner() + .withEnv({ FLUE_RECORDING: 'on' }) + .expect({ + span: container => { + const chats = container.items.filter(span => span.name === 'chat faux-model'); + expect(chats).toHaveLength(2); + for (const chat of chats) { + expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toEqual(expect.any(String)); + expect(chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toEqual(expect.any(String)); + } + }, + }) + .start() + .completed(); + }); + }); + createEsmTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { test('records the messages of the turns in the gen_ai conventions shape', async () => { await createRunner() diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs index e0d424cdae71..46a27dd03b74 100644 --- a/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/instrument.mjs @@ -6,5 +6,4 @@ Sentry.init({ release: '1.0', tracesSampleRate: 1.0, transport: loggingTransport, - integrations: [Sentry.piAiIntegration()], }); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-bedrock.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-bedrock.mjs new file mode 100644 index 000000000000..e4d88abd6cb3 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-bedrock.mjs @@ -0,0 +1,92 @@ +import * as Sentry from '@sentry/node'; +import { + bedrockConverseStreamApi, + setBedrockProviderModule, +} from '@earendil-works/pi-ai/api/bedrock-converse-stream.lazy'; +import { bedrockProviderModule } from '@earendil-works/pi-ai/bedrock-provider'; +import { createModels, createProvider } from '@earendil-works/pi-ai/models'; +import { EventStreamCodec } from '@smithy/core/event-streams'; +import { Buffer } from 'node:buffer'; +import { createServer } from 'node:http'; + +// pi-ai reads these when it builds its Bedrock client: no AWS credentials, and HTTP/1 to reach the +// mock server below. +process.env.AWS_BEDROCK_SKIP_AUTH = '1'; +process.env.AWS_BEDROCK_FORCE_HTTP1 = '1'; + +// pi-ai loads its Bedrock provider through an `import()` with a variable specifier, which a bundler +// such as the Bun build cannot follow. This is pi-ai's hook for registering it statically instead. +setBedrockProviderModule(bedrockProviderModule); + +// Bedrock streams responses in the binary AWS event stream format, which the SDK decodes and checks. +const codec = new EventStreamCodec( + bytes => Buffer.from(bytes).toString('utf8'), + text => Buffer.from(text), +); + +function event(eventType, payload) { + return codec.encode({ + headers: { + ':message-type': { type: 'string', value: 'event' }, + ':event-type': { type: 'string', value: eventType }, + ':content-type': { type: 'string', value: 'application/json' }, + }, + body: Buffer.from(JSON.stringify(payload)), + }); +} + +const server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.writeHead(200, { 'content-type': 'application/vnd.amazon.eventstream' }); + res.end( + Buffer.concat([ + event('messageStart', { role: 'assistant' }), + event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Hi.' } }), + event('contentBlockStop', { contentBlockIndex: 0 }), + event('messageStop', { stopReason: 'end_turn' }), + event('metadata', { usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 }, metrics: { latencyMs: 1 } }), + ]), + ); + }); +}); +await new Promise(resolve => server.listen(0, resolve)); +const baseUrl = `http://localhost:${server.address().port}`; + +const model = { + id: 'pi-bedrock-model', + name: 'pi-bedrock-model', + api: 'bedrock-converse-stream', + provider: 'amazon-bedrock', + baseUrl, + reasoning: false, + input: ['text'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 1000, + maxTokens: 100, +}; +const models = createModels(); +models.setProvider( + createProvider({ + id: 'amazon-bedrock', + name: 'Amazon Bedrock', + baseUrl, + auth: { apiKey: { name: 'Bedrock', resolve: async () => ({ auth: {}, source: 'mock' }) } }, + models: [model], + api: bedrockConverseStreamApi(), + }), +); +const context = { messages: [{ role: 'user', content: 'Hi.', timestamp: Date.now() }] }; + +const sendWithPiAi = async request => { + const { stopReason, errorMessage } = await request; + if (stopReason !== 'stop') { + throw new Error(`pi-ai request failed: ${errorMessage}`); + } +}; + +await Sentry.startSpan({ name: 'pi-ai-bedrock-test' }, async () => { + await sendWithPiAi(models.complete(model, context)); +}); + +server.close(); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-provider-sdk.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-provider-sdk.mjs new file mode 100644 index 000000000000..b9c189c406f2 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/scenario-provider-sdk.mjs @@ -0,0 +1,76 @@ +import * as Sentry from '@sentry/node'; +import { createServer } from 'node:http'; +import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy'; +import { createModels, createProvider } from '@earendil-works/pi-ai/models'; +import OpenAI from 'openai'; + +const COMPLETION = { + id: 'chatcmpl-mock', + object: 'chat.completion.chunk', + created: 1, + model: 'mock-model', + usage: { prompt_tokens: 3, completion_tokens: 2, total_tokens: 5 }, +}; + +const server = createServer((req, res) => { + let body = ''; + req.on('data', chunk => (body += chunk)); + req.on('end', () => { + if (JSON.parse(body).stream) { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + const choices = [{ index: 0, delta: { role: 'assistant', content: 'Hi.' }, finish_reason: 'stop' }]; + res.end(`data: ${JSON.stringify({ ...COMPLETION, choices })}\n\ndata: [DONE]\n\n`); + } else { + res.writeHead(200, { 'content-type': 'application/json' }); + const choices = [{ index: 0, message: { role: 'assistant', content: 'Hi.' }, finish_reason: 'stop' }]; + res.end(JSON.stringify({ ...COMPLETION, object: 'chat.completion', choices })); + } + }); +}); +await new Promise(resolve => server.listen(0, resolve)); +const baseUrl = `http://localhost:${server.address().port}/v1`; + +const model = { + id: 'pi-model', + name: 'pi-model', + api: 'openai-completions', + provider: 'mock', + baseUrl, + reasoning: false, + input: ['text'], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 1000, + maxTokens: 100, +}; +const models = createModels(); +models.setProvider( + createProvider({ + id: 'mock', + name: 'Mock', + baseUrl, + auth: { apiKey: { name: 'Mock', resolve: async () => ({ auth: { apiKey: 'mock-api-key' }, source: 'mock' }) } }, + models: [model], + api: openAICompletionsApi(), + }), +); +const context = { messages: [{ role: 'user', content: 'Hi.', timestamp: Date.now() }] }; +const openai = new OpenAI({ baseURL: baseUrl, apiKey: 'mock-api-key' }); +const callOpenAi = () => openai.chat.completions.create({ model: 'direct-model', messages: [] }); + +// pi-ai settles a failed request as a message instead of rejecting, and one that never reached the +// SDK would pass the test's assertion that the SDK reported nothing. +const sendWithPiAi = async request => { + const { stopReason, errorMessage } = await request; + if (stopReason !== 'stop') { + throw new Error(`pi-ai request failed: ${errorMessage}`); + } +}; + +await Sentry.startSpan({ name: 'pi-ai-provider-test' }, async () => { + await sendWithPiAi(models.complete(model, context)); + // A direct call after pi-ai has sent a request, and one alongside a request in flight. + await callOpenAi(); + await Promise.all([sendWithPiAi(models.stream(model, context).result()), callOpenAi()]); +}); + +server.close(); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts index 2eb62f82eaaa..995bcb7858fa 100644 --- a/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/pi-ai/test.ts @@ -88,6 +88,50 @@ describe.runIf(supports({ min: 22 }))('pi-ai integration', () => { }); }); + createEsmTests(__dirname, 'scenario-provider-sdk.mjs', 'instrument.mjs', (createRunner, test) => { + test('reports requests through a provider SDK once, and leaves direct calls to it alone', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_CHAT); + const namesFrom = (origin: string): (string | undefined)[] => + spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === origin).map(span => span.name); + + expect(namesFrom('auto.ai.pi_ai')).toEqual(['chat pi-model', 'chat pi-model']); + expect(namesFrom('auto.ai.openai')).toEqual(['chat direct-model', 'chat direct-model']); + expect(spans).toHaveLength(4); + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario-bedrock.mjs', 'instrument.mjs', (createRunner, test) => { + test('reports a Bedrock request once, as the chat span of pi-ai', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const chats = container.items.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_CHAT); + expect(chats.map(span => [span.name, span.attributes[SENTRY_ORIGIN]?.value])).toEqual([ + ['chat pi-bedrock-model', 'auto.ai.pi_ai'], + ]); + + // The AWS SDK call that pi-ai makes keeps its plain client span, under the chat span. + const awsCall = container.items.find(span => span.name === 'BedrockRuntime.ConverseStream'); + expect(awsCall?.attributes[SENTRY_OP]?.value).toBe('rpc'); + expect(awsCall?.attributes[SENTRY_ORIGIN]?.value).toBe('auto.rpc.aws_sdk'); + expect(awsCall?.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toBeUndefined(); + expect(awsCall?.parent_span_id).toBe(chats[0]?.span_id); + }, + }) + .start() + .completed(); + }); + }); + createEsmTests(__dirname, 'scenario-compat.mjs', 'instrument.mjs', (createRunner, test) => { // `compat` loads pi-ai's model catalog with `import ... with { type: 'json' }`. Deno 2.8 drops // the import attributes once any module hook is registered and compiles the JSON as JavaScript, diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/pi-durable/instrument.mjs index f1f018ef471a..f3aa606cec2d 100644 --- a/dev-packages/node-integration-tests/suites/tracing/pi-durable/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/instrument.mjs @@ -9,4 +9,7 @@ Sentry.init({ ...(process.env.PI_DURABLE_RECORDING === 'off' ? { dataCollection: { genAI: { inputs: false, outputs: false } } } : {}), + ...(process.env.PI_DURABLE_RECORDING === 'integration-off' + ? { integrations: [Sentry.piDurableIntegration({ recordInputs: false, recordOutputs: false })] } + : {}), }); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts index f26aa34b63d7..3a07efbaa997 100644 --- a/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts @@ -60,10 +60,12 @@ describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { const agent = spans.find(span => span.is_segment)!; expect(agent.name).toBe('invoke_agent'); expect(spans.filter(span => span.name === 'chat faux-model')).toHaveLength(2); - // One span per run, request and tool call: a tool wrapped twice would add a span. + // One span per run and tool call, and one per request from the pi-ai integration: a tool + // wrapped twice, or a request reported by a provider SDK too, would add a span. expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_durable')).toHaveLength( - 5, + 3, ); + expect(spans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.pi_ai')).toHaveLength(2); expect(agent.attributes[SENTRY_OP]?.value).toBe(GEN_AI_INVOKE_AGENT); expect(agent.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_durable'); @@ -77,7 +79,7 @@ describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { for (const chat of chats) { expect(chat.parent_span_id).toBe(agent.span_id); expect(chat.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT); - expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_durable'); + expect(chat.attributes[SENTRY_ORIGIN]?.value).toBe('auto.ai.pi_ai'); expect(chat.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('faux'); expect(chat.attributes[GEN_AI_REQUEST_MODEL]?.value).toBe('faux-model'); expect(chat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); @@ -188,50 +190,55 @@ describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { expect(errorSpanId).toBe(brokenToolSpanId); }); - test('records no message content when the client turns gen_ai recording off', async () => { - await createRunner() - .withEnv({ PI_DURABLE_RECORDING: 'off' }) - .unordered() - .expect({ - span: container => { - const spans = container.items; - expect(spans).toHaveLength(5); - for (const span of spans) { - for (const attribute of CONTENT_ATTRIBUTES) { - expect(span.attributes[attribute]).toBeUndefined(); + for (const [setting, recording] of [ + ['the client', 'off'], + ['`piDurableIntegration`', 'integration-off'], + ]) { + test(`records no message content when ${setting} turns gen_ai recording off`, async () => { + await createRunner() + .withEnv({ PI_DURABLE_RECORDING: recording }) + .unordered() + .expect({ + span: container => { + const spans = container.items; + expect(spans).toHaveLength(5); + for (const span of spans) { + for (const attribute of CONTENT_ATTRIBUTES) { + expect(span.attributes[attribute]).toBeUndefined(); + } } - } - const weather = spans.find(span => span.name === 'execute_tool get_weather')!; - expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.'); - expect( - spans.find(span => span.name === 'chat faux-model')!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value, - ).toBeGreaterThan(0); - }, - }) - .expect({ - span: container => { - expect(container.items).toHaveLength(2); - for (const span of container.items) { - for (const attribute of CONTENT_ATTRIBUTES) { - expect(span.attributes[attribute]).toBeUndefined(); + const weather = spans.find(span => span.name === 'execute_tool get_weather')!; + expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.'); + expect( + spans.find(span => span.name === 'chat faux-model')!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value, + ).toBeGreaterThan(0); + }, + }) + .expect({ + span: container => { + expect(container.items).toHaveLength(2); + for (const span of container.items) { + for (const attribute of CONTENT_ATTRIBUTES) { + expect(span.attributes[attribute]).toBeUndefined(); + } } - } - }, - }) - .expect({ - span: container => { - expect(container.items).toHaveLength(1); - expect(container.items[0]!.name).toBe('pi-durable-request'); - }, - }) - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('broken tool'); - }, - }) - .start() - .completed(); - }); + }, + }) + .expect({ + span: container => { + expect(container.items).toHaveLength(1); + expect(container.items[0]!.name).toBe('pi-durable-request'); + }, + }) + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('broken tool'); + }, + }) + .start() + .completed(); + }); + } }); createEsmTests(__dirname, 'scenario-tools.mjs', 'instrument.mjs', (createRunner, test) => { @@ -491,10 +498,8 @@ describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { }) .expect({ span: container => { - // 2. The provider threw: the generation faulted. - const chat = container.items.find(span => span.name === 'chat faux-model')!; - expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toBeUndefined(); - expect(chat.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error'); + // 2. The provider threw in front of pi-ai, so there is no request to report. + expect(container.items.find(span => span.name === 'chat faux-model')).toBeUndefined(); const agent = container.items.find(span => span.is_segment)!; expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error'); }, diff --git a/packages/server-utils/src/ai/flue/constants.ts b/packages/server-utils/src/ai/flue/constants.ts index 6a3bbaaefaa9..2f8a7bff4f6a 100644 --- a/packages/server-utils/src/ai/flue/constants.ts +++ b/packages/server-utils/src/ai/flue/constants.ts @@ -21,11 +21,9 @@ export const FLUE_INSTRUMENTATION_KEY = Symbol.for('sentry.flue.instrumentation' /** * The Flue execution operations we act on. * - * Only `AGENT` is spanned from the interceptor, and only at the outermost depth: Flue drives one - * LLM call through many `MODEL` operations (one per stream read), and its `AGENT` operation nests - * inside itself once per submission. The turn span is driven from the observation stream instead, - * where `turn_start`/`turn` are exactly one-to-one with a model call. `MODEL` and `TOOL` are - * intercepted only to make the already-open span active for the duration of the operation. + * Only `AGENT` is spanned from the interceptor, and only at the outermost depth: its operation nests + * inside itself once per submission. `TOOL` is intercepted to make the tool span `observe` opened + * active, and `MODEL` to hand the conversation to the pi-ai integration, which spans the model call. */ export const FLUE_OPERATION = { AGENT: 'agent', @@ -34,8 +32,8 @@ export const FLUE_OPERATION = { } as const; /** - * Cap on tracked turn and tool spans, matching `MAX_TRACKED_MASTRA_SPANS`. Both maps are keyed off - * an id that is only removed when the matching end observation arrives; a stream that is abandoned + * Cap on tracked tool spans and admissions, matching `MAX_TRACKED_MASTRA_SPANS`. Both maps are keyed + * off an id that is only removed when the matching end observation arrives; a run that is abandoned * mid-turn never emits one, so without a cap the map grows for the lifetime of the process. */ export const MAX_TRACKED_FLUE_SPANS = 1000; diff --git a/packages/server-utils/src/ai/flue/index.ts b/packages/server-utils/src/ai/flue/index.ts index 94db427df5ca..704dd0e95fc2 100644 --- a/packages/server-utils/src/ai/flue/index.ts +++ b/packages/server-utils/src/ai/flue/index.ts @@ -1,5 +1,6 @@ import type { Scope, Span } from '@sentry/core'; import { + consoleSandbox, continueTrace, getActiveSpan, getDefaultIsolationScope, @@ -8,6 +9,7 @@ import { startNewTrace, startSpan, withActiveSpan, + withScope, } from '@sentry/core'; import { GEN_AI_AGENT_NAME, @@ -17,19 +19,14 @@ import { } from '@sentry/conventions/attributes'; import type { GenAiOptions } from '../core/utils'; import { getGenAiSpanOp, resolveAIRecordingOptions } from '../core/utils'; -import { skipPiAiProviderIntegrations } from '../pi-ai/providers'; -import { isCloudflareWorkers } from '../../utils/runtime'; +import { getOrchestrionInjectedModules } from '../../orchestrion/detect'; +import { piAiModuleNames } from '../../orchestrion/config/pi-ai'; +import { setPiAiRecordingOptions } from '../pi-ai/recording'; +import { isBun, isCloudflareWorkers, isDeno } from '../../utils/runtime'; import { withCleanScopes } from '../../utils/withCleanScopes'; import { FLUE_INSTRUMENTATION_KEY, FLUE_OPERATION, FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants'; import type { SpanTracker } from './utils'; -import { - endToolSpan, - endTurnSpan, - recordRequestContent, - sentryTraceFromTraceparent, - startToolSpan, - startTurnSpan, -} from './utils'; +import { endToolSpan, sentryTraceFromTraceparent, startToolSpan } from './utils'; import type { FlueInstrumentation } from './types'; export type FlueOptions = GenAiOptions; @@ -39,6 +36,45 @@ interface Admission { span: Span | undefined; } +let checkedPiAiInstrumentation = false; + +/** + * `instrument()` works without Sentry's module hook or bundler plugin, but the pi-ai integration that + * spans Flue's model calls doesn't. Checked on the first model call, once pi-ai has loaded. + */ +function warnIfPiAiNotInstrumented(): void { + if (checkedPiAiInstrumentation) { + return; + } + checkedPiAiInstrumentation = true; + + const injected = getOrchestrionInjectedModules(); + if (piAiModuleNames.some(name => injected.includes(name))) { + return; + } + + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn( + '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' + + `Flue agents record agent and tool spans but no \`gen_ai.chat\` spans. ${getPiAiInstrumentationHint()}`, + ); + }); +} + +function getPiAiInstrumentationHint(): string { + if (isBun()) { + return 'Build your app with `sentryBunPlugin()` from `@sentry/bun/plugin`; `bun run` cannot instrument it.'; + } + if (isDeno()) { + return 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.'; + } + if (isCloudflareWorkers()) { + return 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.'; + } + return 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.'; +} + /** * Flue's Node coordinator runs every submission from one long-lived claim loop, started by the * first admission and keeping that call's async context for the life of the process. Left alone, @@ -46,8 +82,8 @@ interface Admission { * (https://github.com/withastro/flue/issues/813). */ function runInAdmissionContext(admission: Admission | undefined, next: () => T): T { - // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own, so - // there is no leaked context to undo there. + // Cloudflare runs each turn from a Durable Object alarm, which already starts a trace of its own, + // so there is no leaked context to undo there. if (isCloudflareWorkers()) { return next(); } @@ -68,31 +104,22 @@ function runInAdmissionContext(admission: Admission | undefined, next: () => * * - `interceptor` wraps agent execution, so the agent span is *active* for its duration and every * span opened underneath parents correctly. - * - `observe` opens and closes the turn span, because Flue's `turn_start`/`turn` events are the - * only one-to-one signal for a model call and `turn` is what carries usage and cost. + * - `observe` opens and closes the tool spans, and names the agent span. * - * Message content, tool arguments and tool results are gated on `recordInputs`/`recordOutputs`, - * which fall back to the current client's `dataCollection.genAI` settings and are read per event. + * Model calls get no span here: Flue sends them through pi-ai, whose integration reports each one + * as a `gen_ai.chat` span under the agent span. + * + * Tool arguments and results are gated on `recordInputs`/`recordOutputs`, which fall back to the + * current client's `dataCollection.genAI` settings and are read per event. The same options apply to + * the message content of the `gen_ai.chat` spans. */ export function createFlueInstrumentation(options: FlueOptions = {}): FlueInstrumentation { - // Flue drives the providers through `@earendil-works/pi-ai`, which sends its requests through the - // provider SDKs that Sentry instruments too (see `skipPiAiProviderIntegrations`). Left alone, their - // integrations report the same request a second time, as a second `gen_ai.chat` beside the turn's. - // - // The provider integrations are skipped on first use rather than here, for two reasons. - // Constructing the object proves nothing: if `instrument()` rejects it, suppressing the provider - // integrations would leave the app with no `gen_ai.chat` spans at all. And the registry is reset per - // client (`_setupIntegrations` clears it, and Cloudflare calls `init()` per request), so a one-shot - // call at module scope is wiped by the next `init()` and every later request double-reports. - const skipProviders = skipPiAiProviderIntegrations; - // Keyed by the agent operation's own id, which is what the observations carry. That keeps // concurrent runs apart and gives a delegated subagent its own span: Flue nests a second `agent` // operation inside the parent's for `task` delegation, and the nesting is not bounded at two. // A plain map: the entry is removed in a `finally`, so it is bounded by concurrent agent runs. const agentSpans = new Map(); // Capped, unlike the above: these are keyed off ids that only a matching end observation removes. - const turnSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS); const toolSpans: SpanTracker = new LRUMap(MAX_TRACKED_FLUE_SPANS); // Capped: a submission admitted here but run by another process never settles here. const admissions = new LRUMap(MAX_TRACKED_FLUE_SPANS); @@ -101,17 +128,24 @@ export function createFlueInstrumentation(options: FlueOptions = {}): FlueInstru key: FLUE_INSTRUMENTATION_KEY, interceptor: async (operation, ctx, next) => { - skipProviders(); - - // `observe` has already opened the span for this unit of work; make it active for the - // duration so whatever the tool or model call does lands inside it rather than beside it. + // `observe` has already opened the tool span; make it active for the duration so whatever the + // tool does lands inside it rather than beside it. if (operation?.type === FLUE_OPERATION.TOOL) { const toolSpan = operation.toolCallId ? toolSpans.get(operation.toolCallId) : undefined; return toolSpan ? withActiveSpan(toolSpan, next) : next(); } + // The `gen_ai.chat` span of the model call comes from the pi-ai integration, which reads the + // conversation and the recording options from the scope. if (operation?.type === FLUE_OPERATION.MODEL) { - const turnSpan = operation.turnId ? turnSpans.get(operation.turnId) : undefined; - return turnSpan ? withActiveSpan(turnSpan, next) : next(); + warnIfPiAiNotInstrumented(); + const { conversationId } = ctx; + return withScope(scope => { + if (conversationId) { + scope.setConversationId(conversationId); + } + setPiAiRecordingOptions(scope, options); + return next(); + }); } if (operation?.type !== FLUE_OPERATION.AGENT) { @@ -166,16 +200,14 @@ export function createFlueInstrumentation(options: FlueOptions = {}): FlueInstru }, observe: observation => { - skipProviders(); - // Resolved per observation, not once at construction: `resolveAIRecordingOptions` reads the // current client's `dataCollection.genAI`, and Cloudflare replaces the client per request, so // values captured at isolate load would be the wrong ones for every later request. const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); // Observations are emitted synchronously from inside the agent operation, so the active span - // here is the agent span the interceptor opened — turn and tool spans parent off it without - // any bookkeeping. + // here is the agent span the interceptor opened — tool spans parent off it without any + // bookkeeping. // // The agent operation that gets the span is the one the observations reference, and it knows // neither the agent's name nor the conversation: the submission wrapper carries the name, the @@ -206,17 +238,6 @@ export function createFlueInstrumentation(options: FlueOptions = {}): FlueInstru admissions.remove(observation.submissionId); } return; - case 'turn_start': - startTurnSpan(observation, turnSpans); - return; - case 'turn_request': - if (recordInputs) { - recordRequestContent(observation, turnSpans); - } - return; - case 'turn': - endTurnSpan(observation, turnSpans, recordOutputs); - return; case 'tool_start': startToolSpan(observation, toolSpans, recordInputs); return; @@ -228,17 +249,16 @@ export function createFlueInstrumentation(options: FlueOptions = {}): FlueInstru } }, - // Only the turn and tool spans are ended here. They come from `startInactiveSpan`, so nothing - // else will. The agent spans come from `startSpan`, which ends them when its callback settles — - // ending them here would stamp an early end time on work that is still running, and the later - // `end()` would be ignored. + // Only the tool spans are ended here. They come from `startInactiveSpan`, so nothing else will. + // The agent spans come from `startSpan`, which ends them when its callback settles — ending them + // here would stamp an early end time on work that is still running, and the later `end()` would + // be ignored. dispose: () => { - for (const span of [...turnSpans.values(), ...toolSpans.values()]) { + for (const span of toolSpans.values()) { span.end(); } agentSpans.clear(); admissions.clear(); - turnSpans.clear(); toolSpans.clear(); }, }; diff --git a/packages/server-utils/src/ai/flue/types.ts b/packages/server-utils/src/ai/flue/types.ts index 30850dea9949..21f88c26bb49 100644 --- a/packages/server-utils/src/ai/flue/types.ts +++ b/packages/server-utils/src/ai/flue/types.ts @@ -6,44 +6,8 @@ * `FlueExecutionContext` as of `@flue/runtime` 2.x. */ -import type { PiAiUsage } from '../pi-ai/usage'; - -/** Mirrors `ModelRequestInfo`. */ -export interface FlueModelRequestInfo { - requestedModel?: string; - /** Provider slug (`anthropic`, `openrouter`) — what `gen_ai.provider.name` wants. */ - providerId?: string; - temperature?: number; - maxTokens?: number; - reasoningLevel?: string; - serverAddress?: string; - serverPort?: number; -} - -/** Mirrors `ModelRequestInput` — the content half of `ModelRequest`, on `turn_request` only. */ -export interface FlueModelRequestInput { - systemPrompt?: string; - messages?: unknown[]; - tools?: unknown[]; -} - -/** `turn_request` carries `ModelRequest`, which is `ModelRequestInfo` plus the input. */ -export interface FlueModelRequest extends FlueModelRequestInfo { - input?: FlueModelRequestInput; -} - -/** Mirrors `ModelResponse`. */ -export interface FlueModelResponse { - responseId?: string; - responseModel?: string; - output?: unknown; - /** pi-ai's usage, which Flue passes through with its own cost figures. */ - usage?: PiAiUsage; - finishReason?: string; -} - /** - * Mirrors Flue's `errorInfo`, which it attaches to a failed tool or turn observation. Flue catches + * Mirrors Flue's `errorInfo`, which it attaches to a failed tool observation. Flue catches * the throw and turns it into a tool result, so this serialized form is the only trace of it. */ export interface FlueErrorInfo { @@ -62,7 +26,6 @@ export interface FlueObservation { agentName?: string; conversationId?: string; session?: string; - turnId?: string; taskId?: string; submissionId?: string; operationId?: string; @@ -70,14 +33,11 @@ export interface FlueObservation { toolCallId?: string; isError?: boolean; errorInfo?: FlueErrorInfo; - purpose?: string; durationMs?: number; - request?: FlueModelRequest; args?: unknown; result?: unknown; /** The tool result as the model sees it, on successful `tool` events. */ effectiveResult?: unknown; - response?: FlueModelResponse; } /** The execution unit an interceptor wraps. */ @@ -85,7 +45,6 @@ export interface FlueExecutionOperation { type: string; operationId?: string; operationKind?: string; - turnId?: string; toolCallId?: string; } @@ -101,7 +60,6 @@ export interface FlueExecutionContext { submissionId?: string; conversationId?: string; session?: string; - turnId?: string; taskId?: string; } diff --git a/packages/server-utils/src/ai/flue/utils.ts b/packages/server-utils/src/ai/flue/utils.ts index 399a2aec3580..307642e20cb3 100644 --- a/packages/server-utils/src/ai/flue/utils.ts +++ b/packages/server-utils/src/ai/flue/utils.ts @@ -9,36 +9,16 @@ import { } from '@sentry/core'; import { GEN_AI_CONVERSATION_ID, - GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, - GEN_AI_OUTPUT_MESSAGES, - GEN_AI_PROVIDER_NAME, - GEN_AI_REQUEST_MAX_TOKENS, - GEN_AI_REQUEST_MODEL, - GEN_AI_REQUEST_REASONING_LEVEL, - GEN_AI_REQUEST_TEMPERATURE, - GEN_AI_RESPONSE_FINISH_REASONS, - GEN_AI_RESPONSE_ID, - GEN_AI_RESPONSE_MODEL, - GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, - GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_NAME, - SERVER_ADDRESS, - SERVER_PORT, SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; import { getGenAiSpanOp } from '../core/utils'; -import { - piAiAssistantMessageToGenAiMessage, - piAiContentToString, - piAiFinishReason, - piAiMessagesToGenAiMessages, -} from '../pi-ai/messages'; -import { setPiAiUsageAttributes } from '../pi-ai/usage'; +import { piAiContentToString } from '../pi-ai/messages'; import { FLUE_ORIGIN, MAX_TRACKED_FLUE_SPANS } from './constants'; -import type { FlueErrorInfo, FlueModelRequestInfo, FlueObservation } from './types'; +import type { FlueErrorInfo, FlueObservation } from './types'; /** * Flue persists the incoming W3C `traceparent` at admission and replays it on the agent operation. @@ -108,85 +88,6 @@ function captureToolError(span: Span, errorInfo: FlueErrorInfo | undefined): voi }); } -export function startTurnSpan(observation: FlueObservation, turnSpans: SpanTracker): void { - const { turnId } = observation; - if (!turnId || turnSpans.get(turnId)) { - return; - } - - trackSpan( - turnSpans, - turnId, - startInactiveSpan({ - name: 'chat', - op: getGenAiSpanOp('chat'), - attributes: { - [SENTRY_ORIGIN]: FLUE_ORIGIN, - [GEN_AI_OPERATION_NAME]: 'chat', - [GEN_AI_CONVERSATION_ID]: observation.conversationId, - // No conventional attribute for this; it is the only way to tell a compaction turn from a - // user-facing one. - 'flue.turn.purpose': observation.purpose, - }, - }), - ); -} - -export function endTurnSpan(observation: FlueObservation, turnSpans: SpanTracker, recordOutputs: boolean): void { - const { turnId } = observation; - const span = turnId ? turnSpans.get(turnId) : undefined; - if (!span || !turnId) { - return; - } - turnSpans.remove(turnId); - - const requestedModel = observation.request?.requestedModel; - const responseModel = observation.response?.responseModel; - const model = responseModel ?? requestedModel; - if (model) { - span.updateName(`chat ${model}`); - } - if (requestedModel) { - span.setAttribute(GEN_AI_REQUEST_MODEL, requestedModel); - } - if (responseModel) { - span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel); - } - - // `providerId` is the slug (`anthropic`, `openrouter`); `providerName` is the display name. - const provider = observation.request?.providerId; - if (provider) { - span.setAttribute(GEN_AI_PROVIDER_NAME, provider); - } - - setRequestAttributes(span, observation.request); - - const responseId = observation.response?.responseId; - if (responseId) { - span.setAttribute(GEN_AI_RESPONSE_ID, responseId); - } - const finishReason = piAiFinishReason(observation.response?.finishReason); - if (finishReason) { - // Serialized, not a raw array: the conventions declare this attribute's value type as `string`, - // and that is what `ai/core`, Mastra, OpenAI and Vercel AI all write. - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason])); - } - - const output = recordOutputs - ? piAiAssistantMessageToGenAiMessage(observation.response?.output, finishReason) - : undefined; - if (output) { - span.setAttribute(GEN_AI_OUTPUT_MESSAGES, stringify([output])); - } - - setPiAiUsageAttributes(span, observation.response?.usage, observation.isError); - - if (observation.isError) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - } - span.end(); -} - /** * Tool spans hang off the agent invocation rather than the turn, matching how Flue's own * OpenTelemetry adapter projects them: siblings of `chat`, correlated to model output by tool call @@ -257,52 +158,3 @@ function toolResultForModel(observation: FlueObservation): string | undefined { } return result === undefined ? undefined : stringify(result); } - -/** - * `turn_request` is the only event carrying the request's content — the settled `turn` reports - * metadata alone — so input messages, system prompt and tool definitions are read from it. - */ -export function recordRequestContent(observation: FlueObservation, turnSpans: SpanTracker): void { - const { turnId } = observation; - const span = turnId ? turnSpans.get(turnId) : undefined; - const input = observation.request?.input; - if (!span || !input) { - return; - } - - if (input.systemPrompt) { - span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, input.systemPrompt); - } - const messages = piAiMessagesToGenAiMessages(input.messages); - if (messages.length) { - span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(messages)); - } - if (input.tools?.length) { - span.setAttribute(GEN_AI_TOOL_DEFINITIONS, stringify(input.tools)); - } -} - -/** - * Model-call tuning and the provider endpoint, all on the settled turn's `ModelRequestInfo`. These - * are the conventional attributes the other AI integrations in this package set. - */ -export function setRequestAttributes(span: Span, request: FlueModelRequestInfo | undefined): void { - if (!request) { - return; - } - - const attributes: Record = {}; - const set = (key: string, value: string | number | undefined): void => { - if (value !== undefined) { - attributes[key] = value; - } - }; - - set(GEN_AI_REQUEST_TEMPERATURE, request.temperature); - set(GEN_AI_REQUEST_MAX_TOKENS, request.maxTokens); - set(GEN_AI_REQUEST_REASONING_LEVEL, request.reasoningLevel); - set(SERVER_ADDRESS, request.serverAddress); - set(SERVER_PORT, request.serverPort); - - span.setAttributes(attributes); -} diff --git a/packages/server-utils/src/ai/pi-ai/chat.ts b/packages/server-utils/src/ai/pi-ai/chat.ts index 2e401efcba2e..c7f8b10dc511 100644 --- a/packages/server-utils/src/ai/pi-ai/chat.ts +++ b/packages/server-utils/src/ai/pi-ai/chat.ts @@ -28,6 +28,7 @@ import { SERVER_PORT, } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import { PI_AI_ORIGIN } from './constants'; import type { PiAiContext } from './messages'; import { piAiAssistantMessageToGenAiMessage, @@ -39,22 +40,18 @@ import { import type { PiAssistantMessage, PiModel, PiStreamOptions } from './types'; import { setPiAiUsageAttributes } from './usage'; -export interface PiAiChatRequest { +interface PiAiChatRequest { model: PiModel; /** Absent for the deferred calls, which pass a handle in place of the request context. */ context?: PiAiContext; callOptions?: PiStreamOptions; streaming: boolean; - origin: string; recordInputs: boolean; } -/** - * The span options of the `gen_ai.chat` span of a pi-ai request. Returned rather than started so - * the caller picks whether the span is active while the request is sent. - */ +/** The span options of the `gen_ai.chat` span of a pi-ai request. */ export function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptions { - const { model, context, callOptions, streaming, origin, recordInputs } = request; + const { model, context, callOptions, streaming, recordInputs } = request; const conversationId = getCurrentScope().getScopeData().conversationId ?? getIsolationScope().getScopeData().conversationId; @@ -62,7 +59,7 @@ export function getPiAiChatSpanOptions(request: PiAiChatRequest): StartSpanOptio name: model.id ? `chat ${model.id}` : 'chat', op: GEN_AI_CHAT, attributes: { - [SENTRY_ORIGIN]: origin, + [SENTRY_ORIGIN]: PI_AI_ORIGIN, [GEN_AI_OPERATION_NAME]: 'chat', [GEN_AI_PROVIDER_NAME]: model.provider, [GEN_AI_REQUEST_MODEL]: model.id, diff --git a/packages/server-utils/src/ai/pi-ai/providers.ts b/packages/server-utils/src/ai/pi-ai/providers.ts index 96bc6149f620..19d6e13278c3 100644 --- a/packages/server-utils/src/ai/pi-ai/providers.ts +++ b/packages/server-utils/src/ai/pi-ai/providers.ts @@ -1,30 +1,21 @@ -import { _INTERNAL_shouldSkipAiProviderWrapping, _INTERNAL_skipAiProviderWrapping } from '@sentry/core'; -import { ANTHROPIC_AI_INTEGRATION_NAME } from '../anthropic-ai/constants'; -import { GOOGLE_GENAI_INTEGRATION_NAME } from '../google-genai/constants'; -import { OPENAI_INTEGRATION_NAME } from '../openai/constants'; -import { WORKERS_AI_INTEGRATION_NAME } from '../workers-ai/constants'; +import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { _INTERNAL_shouldSkipAiProviderWrapping, getActiveSpan, spanToJSON } from '@sentry/core'; +import { PI_AI_ORIGIN } from './constants'; -// pi-ai sends its requests through the `openai`, `@anthropic-ai/sdk` and `@google/genai` clients, and -// on Cloudflare through the Workers AI binding (`createAI()` of `agents/models/pi-ai`). Left alone, -// those integrations report the same request a second time beside the `chat` span of the framework -// that sent it. Bedrock requests go through `@aws-sdk/client-bedrock-runtime`, which `awsIntegration` -// still reports; that one has no skip yet. -const PI_AI_PROVIDER_INTEGRATIONS = [ - OPENAI_INTEGRATION_NAME, - ANTHROPIC_AI_INTEGRATION_NAME, - GOOGLE_GENAI_INTEGRATION_NAME, - WORKERS_AI_INTEGRATION_NAME, -]; +/** + * Whether the active span is a pi-ai `chat` span, which means a provider SDK call being made is pi-ai + * sending its request. + */ +export function isInsidePiAiSpan(): boolean { + const span = getActiveSpan(); + return !!span && spanToJSON(span).attributes[SENTRY_ORIGIN] === PI_AI_ORIGIN; +} /** - * Stop the provider SDK integrations from reporting the requests pi-ai sends. The skip is - * process-wide: the provider SDKs do not know which of their calls pi-ai made. - * - * The registry is reset per client, so callers apply this on the first request instead of once at - * setup, or the next `init()` would undo it. + * Whether a provider integration should leave a call alone, because the integration driving the SDK + * reports it. LangChain and Vercel AI mark the providers they drive as skipped; pi-ai is detected per + * request, by its active span. */ -export function skipPiAiProviderIntegrations(): void { - if (!PI_AI_PROVIDER_INTEGRATIONS.every(provider => _INTERNAL_shouldSkipAiProviderWrapping(provider))) { - _INTERNAL_skipAiProviderWrapping(PI_AI_PROVIDER_INTEGRATIONS); - } +export function shouldSkipAiProviderSpan(integrationName: string): boolean { + return _INTERNAL_shouldSkipAiProviderWrapping(integrationName) || isInsidePiAiSpan(); } diff --git a/packages/server-utils/src/ai/pi-ai/recording.ts b/packages/server-utils/src/ai/pi-ai/recording.ts new file mode 100644 index 000000000000..2abe83246ca2 --- /dev/null +++ b/packages/server-utils/src/ai/pi-ai/recording.ts @@ -0,0 +1,31 @@ +import type { Scope } from '@sentry/core'; +import { getCurrentScope } from '@sentry/core'; +import type { GenAiOptions } from '../core/utils'; +import { resolveAIRecordingOptions } from '../core/utils'; + +const RECORDING_OPTIONS_KEY = 'piAiRecordingOptions'; + +/** + * Apply the recording options of an integration that sends its model calls through pi-ai, such as + * Flue, to the `gen_ai.chat` spans of the requests sent under `scope`. + */ +export function setPiAiRecordingOptions(scope: Scope, options: GenAiOptions): void { + scope.setSDKProcessingMetadata({ [RECORDING_OPTIONS_KEY]: options }); +} + +/** + * The recording options of a pi-ai request, read when it starts: its response can settle outside the + * scope it was sent from. An explicit `false` on either integration keeps the content out, since an + * opt-out must not depend on which integration it was set on. Otherwise the integration driving + * pi-ai comes first, then `piAiIntegration`, then `dataCollection.genAI`. + */ +export function resolvePiAiRecordingOptions(options: GenAiOptions): Required { + const driver = getCurrentScope().getScopeData().sdkProcessingMetadata[RECORDING_OPTIONS_KEY] as + | GenAiOptions + | undefined; + const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); + return { + recordInputs: options.recordInputs !== false && (driver?.recordInputs ?? recordInputs), + recordOutputs: options.recordOutputs !== false && (driver?.recordOutputs ?? recordOutputs), + }; +} diff --git a/packages/server-utils/src/ai/pi-durable/index.ts b/packages/server-utils/src/ai/pi-durable/index.ts index d2187aae394e..307d149e996e 100644 --- a/packages/server-utils/src/ai/pi-durable/index.ts +++ b/packages/server-utils/src/ai/pi-durable/index.ts @@ -10,9 +10,8 @@ import { } from '@sentry/core'; import { GEN_AI_CONVERSATION_ID } from '@sentry/conventions/attributes'; import type { GenAiOptions } from '../core/utils'; -import { skipPiAiProviderIntegrations } from '../pi-ai/providers'; +import { setPiAiRecordingOptions } from '../pi-ai/recording'; import { PI_DURABLE_ORIGIN, PI_TASK } from './constants'; -import { instrumentPiModels } from './models'; import type { PiRuns } from './runs'; import { createRuns, endRun, observeRunControl, readProviderSessionId, startRun, toSentryConversationId } from './runs'; import { instrumentTool, instrumentToolPhase } from './tools'; @@ -35,15 +34,15 @@ const INSTRUMENTED = Symbol.for('sentry.pi-durable.instrumented'); const RUNS = Symbol.for('sentry.pi-durable.runs'); /** - * Return pi-durable `HarnessOptions` whose model requests, task phases and tool calls are traced. - * The caller's `models` and `registry` objects are wrapped, never modified. The result has the - * caller's options as prototype: pi-durable reads `settings`, `env` and `conversationCreated` at - * every use, so they stay live, getters included. + * Return pi-durable `HarnessOptions` whose task phases and tool calls are traced. The caller's + * `registry` object is wrapped, never modified. The result has the caller's options as prototype: + * pi-durable reads `settings`, `env` and `conversationCreated` at every use, so they stay live, + * getters included. * * Spans: * - `gen_ai.invoke_agent` for each run, a new trace per run, or a child of the tool call that * created the conversation for a subagent; - * - `gen_ai.chat` for each model request, under its run; + * - `gen_ai.chat` for each model request, under its run, from `piAiIntegration`; * - `gen_ai.execute_tool` for each tool call, under its run. * * The scheduler starts task phases from whichever async context last woke it, often an unrelated @@ -61,9 +60,6 @@ export function instrumentPiDurableHarnessOptions( const runs = createRuns(); const own = (value: unknown): PropertyDescriptor => ({ value, enumerable: true, configurable: true, writable: true }); const instrumented: T = Object.create(harnessOptions, { - ...(harnessOptions.models - ? { models: own(instrumentPiModels(harnessOptions.models, options, skipPiAiProviderIntegrations)) } - : {}), ...(harnessOptions.registry ? { registry: own(instrumentRegistry(harnessOptions.registry, options, runs)) } : {}), // pi-durable passes failures of extension code here, such as a throwing hook, and keeps going. // Only an app that passed its own `onReport` gets a chance to handle them. @@ -142,6 +138,7 @@ function instrumentRegistry(registry: PiRegistryReader, options: PiDurableOption runs, wrapTool, isAbort, + options, ); const phases: Record = {}; for (const [name, phase] of Object.entries(definition.phases)) { @@ -197,6 +194,7 @@ function runPhase( runs: PiRuns, wrapTool: (tool: PiTool) => PiTool, isAbort: boolean, + options: PiDurableOptions, ): Promise { const { conversationId } = runtime; const isRunWork = kind === PI_TASK.GENERATION || kind === PI_TASK.TOOL; @@ -230,6 +228,7 @@ function runPhase( } } scope.setConversationId(sessionId ?? toSentryConversationId(runs, conversationId)); + setPiAiRecordingOptions(scope, options); try { return await phase(observed); } catch (error) { diff --git a/packages/server-utils/src/ai/pi-durable/models.ts b/packages/server-utils/src/ai/pi-durable/models.ts deleted file mode 100644 index 07cf3a279165..000000000000 --- a/packages/server-utils/src/ai/pi-durable/models.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { isThenable, SPAN_STATUS_ERROR, startSpanManual } from '@sentry/core'; -import type { GenAiOptions } from '../core/utils'; -import { resolveAIRecordingOptions } from '../core/utils'; -import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../pi-ai/chat'; -import type { PiAiContext } from '../pi-ai/messages'; -import type { PiAssistantMessage, PiEventStream, PiModel, PiStreamOptions } from '../pi-ai/types'; -import { PI_DURABLE_ORIGIN } from './constants'; -import type { PiModels } from './types'; - -type ModelCall = (model: PiModel, request: unknown, options?: unknown) => unknown; - -const STREAMING_METHODS = new Set(['stream', 'streamSimple', 'streamDeferred']); -const COMPLETE_METHODS = new Set(['complete', 'completeSimple', 'fetchDeferred']); -// These fetch the answer of a parked request; their second argument is a handle, not the request. -const DEFERRED_METHODS = new Set(['streamDeferred', 'fetchDeferred']); - -/** - * Wrap a pi-ai `Models` so every model request it sends gets a `gen_ai.chat` span. - * - * The proxy hands every other member through bound to the original, so a `Models` instance whose - * methods read `this` keeps working, and the caller's own object is never modified. - */ -export function instrumentPiModels(models: T, options: GenAiOptions, onRequest: () => void): T { - const wrapped = new Map(); - - return new Proxy(models, { - get(target, property) { - const value: unknown = Reflect.get(target, property, target); - if (typeof value !== 'function') { - return value; - } - - const cached = wrapped.get(property); - if (cached) { - return cached; - } - - const original = (value as ModelCall).bind(target); - const method = String(property); - const streaming = STREAMING_METHODS.has(method); - const deferred = DEFERRED_METHODS.has(method); - const instrumented = - streaming || COMPLETE_METHODS.has(method) - ? (model: PiModel, request: unknown, callOptions?: unknown): unknown => { - onRequest(); - return traceModelRequest( - model, - deferred ? undefined : (request as PiAiContext), - deferred ? undefined : (callOptions as PiStreamOptions | undefined), - streaming, - options, - () => original(model, request, callOptions), - ); - } - : original; - - wrapped.set(property, instrumented); - return instrumented; - }, - }); -} - -function traceModelRequest( - model: PiModel, - context: PiAiContext | undefined, - callOptions: PiStreamOptions | undefined, - streaming: boolean, - options: GenAiOptions, - send: () => unknown, -): unknown { - // Read per request: `dataCollection.genAI` belongs to the current client, which can change. - const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); - - return startSpanManual( - getPiAiChatSpanOptions({ model, context, callOptions, streaming, origin: PI_DURABLE_ORIGIN, recordInputs }), - span => { - let result: unknown; - try { - result = send(); - } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - span.end(); - throw error; - } - - // pi-ai never rejects a request: a provider failure or an abort settles as a message with - // `stopReason` `error` or `aborted`. The rejection handler only covers a broken provider. - let settled: unknown; - try { - settled = streaming ? (result as PiEventStream).result() : result; - } catch { - settled = undefined; - } - // A result of another shape must reach the caller unchanged, so its span ends without a response. - if (!isThenable(settled)) { - span.end(); - return result; - } - (settled as Promise).then( - message => { - setPiAiResponseAttributes(span, message, recordOutputs); - span.end(); - }, - () => { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - span.end(); - }, - ); - - return result; - }, - ); -} diff --git a/packages/server-utils/src/ai/pi-durable/types.ts b/packages/server-utils/src/ai/pi-durable/types.ts index e4b79f7fcd42..38c4557c8707 100644 --- a/packages/server-utils/src/ai/pi-durable/types.ts +++ b/packages/server-utils/src/ai/pi-durable/types.ts @@ -1,26 +1,9 @@ /** - * Structural subsets of the `@earendil-works/pi-durable` and `@earendil-works/pi-ai` types the - * instrumentation reads. The SDK does not depend on either package, so only the fields used here - * are declared, and every one of them is treated as possibly absent at runtime. + * Structural subsets of the `@earendil-works/pi-durable` types the instrumentation reads. The SDK + * does not depend on the package, so only the fields used here are declared, and every one of them + * is treated as possibly absent at runtime. */ -import type { PiAiContext } from '../pi-ai/messages'; -import type { PiAssistantMessage, PiEventStream, PiModel, PiStreamOptions } from '../pi-ai/types'; - -/** - * The `Models` methods that send a model request. Everything else passes through untouched. The - * deferred methods fetch the answer of a request the provider parked, so they take a handle in - * place of the request context. - */ -export interface PiModels { - stream?(model: PiModel, context: PiAiContext, options?: PiStreamOptions): PiEventStream; - streamSimple?(model: PiModel, context: PiAiContext, options?: PiStreamOptions): PiEventStream; - complete?(model: PiModel, context: PiAiContext, options?: PiStreamOptions): Promise; - completeSimple?(model: PiModel, context: PiAiContext, options?: PiStreamOptions): Promise; - streamDeferred?(model: PiModel, handle: unknown, options?: unknown): PiEventStream; - fetchDeferred?(model: PiModel, handle: unknown, options?: unknown): Promise; -} - export interface PiToolExecutionResult { /** The content blocks the tool returns for the model, in pi-durable 1.2.0 and later. */ output?: unknown[]; @@ -111,7 +94,6 @@ export interface PiRegistryReader { } export interface PiHarnessOptions { - models?: PiModels; registry?: PiRegistryReader; onReport?: (error: unknown) => void; } diff --git a/packages/server-utils/src/ai/workers-ai/index.ts b/packages/server-utils/src/ai/workers-ai/index.ts index ef49c2c4b89a..ff62c38a7048 100644 --- a/packages/server-utils/src/ai/workers-ai/index.ts +++ b/packages/server-utils/src/ai/workers-ai/index.ts @@ -1,14 +1,8 @@ import { SENTRY_OP } from '@sentry/conventions/attributes'; -import { - _INTERNAL_shouldSkipAiProviderWrapping, - getClient, - hasSpanStreamingEnabled, - SPAN_STATUS_ERROR, - startSpan, - startSpanManual, -} from '@sentry/core'; +import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, startSpanManual } from '@sentry/core'; import type { Span } from '@sentry/core'; import { isReadableStream, resolveAIRecordingOptions } from '../core/utils'; +import { shouldSkipAiProviderSpan } from '../pi-ai/providers'; import { WORKERS_AI_INTEGRATION_NAME } from './constants'; import { instrumentWorkersAiStream } from './streaming'; import type { WorkersAiOptions } from './types'; @@ -29,9 +23,7 @@ function instrumentRun( options: WorkersAiOptions & Required>, ): (...args: unknown[]) => Promise { return function instrumentedRun(...args: unknown[]): Promise { - // When another integration (e.g. Vercel AI via `workers-ai-provider`) is driving this binding, - // it records the spans itself and marks this provider as skipped; skip here to avoid double spans. - if (_INTERNAL_shouldSkipAiProviderWrapping(WORKERS_AI_INTEGRATION_NAME)) { + if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) { return originalRun.apply(context, args); } diff --git a/packages/server-utils/src/integrations/anthropic.ts b/packages/server-utils/src/integrations/anthropic.ts index ff9cc0c7440f..4dfbff811c52 100644 --- a/packages/server-utils/src/integrations/anthropic.ts +++ b/packages/server-utils/src/integrations/anthropic.ts @@ -1,14 +1,7 @@ import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; -import { - _INTERNAL_shouldSkipAiProviderWrapping, - defineIntegration, - getActiveSpan, - getClient, - hasSpanStreamingEnabled, - startInactiveSpan, -} from '@sentry/core'; +import { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core'; import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai'; @@ -16,6 +9,7 @@ import { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants'; import { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming'; import { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner'; import type { AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types'; +import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; import type { OrchestrionChannelContext } from '../orchestrion/types'; import { CHANNELS } from '../orchestrion/channels'; import { bindTracingChannelToSpan } from '../tracing-channel'; @@ -122,9 +116,7 @@ function createGenAiSpan( ): Span | undefined { const args = data.arguments ?? []; - // When LangChain (or another provider) is driving the SDK, it records the spans itself and marks this - // provider as skipped — mirror the OTel integration and don't double-instrument. - if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) { + if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) { return undefined; } diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts index 538b5f99726c..d834dc09c2e9 100644 --- a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts @@ -15,6 +15,7 @@ import { import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op'; import type { StreamResponseState } from '../../../ai/core/utils'; import { endStreamSpan, getTokenUsageAttributes } from '../../../ai/core/utils'; +import { isInsidePiAiSpan } from '../../../ai/pi-ai/providers'; import { DEBUG_BUILD } from '../../../debug-build'; import { GEN_AI_OPERATION_NAME_VALUE_CHAT, @@ -48,7 +49,16 @@ type ParsedChunk = any; const textDecoder = new TextDecoder(); export class BedrockRuntimeServiceExtension implements ServiceExtension { + // Requests pi-ai sends, which its own `gen_ai.chat` span already reports. They keep the plain AWS + // client span, without the model call on it. + private _piAiRequests: WeakSet = new WeakSet(); + public requestPreSpanHook(request: NormalizedRequest): RequestMetadata { + if (isInsidePiAiSpan()) { + this._piAiRequests.add(request); + return {}; + } + switch (request.commandName) { case 'Converse': return this._requestPreSpanHookConverse(request, false); @@ -64,6 +74,10 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { } public responseHook(response: NormalizedResponse, span: Span): void { + if (this._piAiRequests.has(response.request)) { + return; + } + const commandName = response.request.commandName; if (!span.isRecording()) { diff --git a/packages/server-utils/src/integrations/google-genai.ts b/packages/server-utils/src/integrations/google-genai.ts index c26b37da75e9..2170f040a4e5 100644 --- a/packages/server-utils/src/integrations/google-genai.ts +++ b/packages/server-utils/src/integrations/google-genai.ts @@ -2,7 +2,6 @@ import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventi import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span } from '@sentry/core'; import { - _INTERNAL_shouldSkipAiProviderWrapping, defineIntegration, getActiveSpan, getClient, @@ -17,6 +16,7 @@ import { extractRequestAttributes, resolveChatParams, } from '../ai/google-genai'; +import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; import { instrumentStream } from '../ai/google-genai/streaming'; import type { GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types'; import type { OrchestrionChannelContext } from '../orchestrion/types'; @@ -78,9 +78,7 @@ function createGenAiSpan( operation: string, options: GoogleGenAIOptions, ): Span | undefined { - // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks this - // provider as skipped; skip here to avoid double spans. - if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) { + if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) { return undefined; } diff --git a/packages/server-utils/src/integrations/index.ts b/packages/server-utils/src/integrations/index.ts index e70488a63351..11c90eb7855c 100644 --- a/packages/server-utils/src/integrations/index.ts +++ b/packages/server-utils/src/integrations/index.ts @@ -15,6 +15,7 @@ import { mongooseIntegration } from './mongoose'; import { lruMemoizerIntegration } from './lru-memoizer'; import { langChainIntegration } from './langchain'; import { langGraphIntegration } from './langgraph'; +import { piAiIntegration } from './pi-ai'; import { piDurableIntegration } from './pi-durable'; import { mastraIntegration } from './mastra'; import { mcpServerIntegration } from './mcp-server'; @@ -62,6 +63,7 @@ export function getTracingIntegrations(): Integration[] { langChainIntegration(), langGraphIntegration(), mastraIntegration(), + piAiIntegration(), piDurableIntegration(), vercelAIIntegration(), openAIIntegration(), diff --git a/packages/server-utils/src/integrations/mistral.ts b/packages/server-utils/src/integrations/mistral.ts index f916321bd31c..2092a689df77 100644 --- a/packages/server-utils/src/integrations/mistral.ts +++ b/packages/server-utils/src/integrations/mistral.ts @@ -1,13 +1,14 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; -import { _INTERNAL_shouldSkipAiProviderWrapping, defineIntegration, startInactiveSpan } from '@sentry/core'; +import { defineIntegration, startInactiveSpan } from '@sentry/core'; import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; import { addRequestAttributes, extractRequestAttributes } from '../ai/mistral'; import { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from '../ai/mistral/constants'; import { instrumentEventStream } from '../ai/mistral/streaming'; import type { MistralOptions } from '../ai/mistral/types'; import { addResponseAttributes, getSpanName } from '../ai/mistral/utils'; +import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; import type { OrchestrionChannelContext } from '../orchestrion/types'; import { CHANNELS } from '../orchestrion/channels'; import { mistralModuleNames } from '../orchestrion/config/mistral'; @@ -62,9 +63,7 @@ function createGenAiSpan( streaming: boolean, options: MistralOptions, ): Span | undefined { - // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks - // this provider as skipped; skip here to avoid double spans. - if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) { + if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) { return undefined; } diff --git a/packages/server-utils/src/integrations/openai.ts b/packages/server-utils/src/integrations/openai.ts index eaa02e867a5d..88e58a172b0c 100644 --- a/packages/server-utils/src/integrations/openai.ts +++ b/packages/server-utils/src/integrations/openai.ts @@ -1,19 +1,14 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; -import { - _INTERNAL_shouldSkipAiProviderWrapping, - defineIntegration, - getClient, - hasSpanStreamingEnabled, - startInactiveSpan, -} from '@sentry/core'; +import { defineIntegration, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core'; import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; import { addRequestAttributes, extractRequestAttributes } from '../ai/openai'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { instrumentStream } from '../ai/openai/streaming'; import type { OpenAiOptions } from '../ai/openai/types'; import { addResponseAttributes } from '../ai/openai/utils'; +import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; import type { OrchestrionChannelContext } from '../orchestrion/types'; import { CHANNELS } from '../orchestrion/channels'; import { bindTracingChannelToSpan } from '../tracing-channel'; @@ -73,9 +68,7 @@ function instrumentOpenai(options: OpenAiOptions): void { * Returning `undefined` opts the payload out so no span is opened. */ function createGenAiSpan(data: OrchestrionChannelContext, operation: string, options: OpenAiOptions): Span | undefined { - // When another provider (e.g. LangChain) is driving the SDK, it records the spans itself and marks this - // provider as skipped; skip here to avoid double spans. - if (_INTERNAL_shouldSkipAiProviderWrapping(INTEGRATION_NAME)) { + if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) { return undefined; } diff --git a/packages/server-utils/src/integrations/pi-ai.ts b/packages/server-utils/src/integrations/pi-ai.ts index 7ac0a34fd781..68bc1bdca1d0 100644 --- a/packages/server-utils/src/integrations/pi-ai.ts +++ b/packages/server-utils/src/integrations/pi-ai.ts @@ -2,11 +2,11 @@ import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span } from '@sentry/core'; import { defineIntegration, isThenable, startInactiveSpan } from '@sentry/core'; import type { GenAiOptions } from '../ai/core/utils'; -import { resolveAIRecordingOptions } from '../ai/core/utils'; import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../ai/pi-ai/chat'; -import { PI_AI_INTEGRATION_NAME, PI_AI_ORIGIN } from '../ai/pi-ai/constants'; +import { PI_AI_INTEGRATION_NAME } from '../ai/pi-ai/constants'; import type { PiAiContext } from '../ai/pi-ai/messages'; -import { skipPiAiProviderIntegrations } from '../ai/pi-ai/providers'; +import { isInsidePiAiSpan } from '../ai/pi-ai/providers'; +import { resolvePiAiRecordingOptions } from '../ai/pi-ai/recording'; import type { PiEventStream, PiStreamOptions } from '../ai/pi-ai/types'; import type { OrchestrionChannelContext } from '../orchestrion/types'; import { CHANNELS } from '../orchestrion/channels'; @@ -16,6 +16,8 @@ import { bindTracingChannelToSpan } from '../tracing-channel'; export type PiAiOptions = GenAiOptions; +type PiAiChannelContext = OrchestrionChannelContext & { _sentryRecordOutputs?: boolean }; + const _piAiIntegration = ((options: PiAiOptions = {}) => { return { name: PI_AI_INTEGRATION_NAME, @@ -26,18 +28,18 @@ const _piAiIntegration = ((options: PiAiOptions = {}) => { }) satisfies IntegrationFn; function instrumentPiAi(options: PiAiOptions): void { - const streamChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_STREAM); - const completeChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_COMPLETE); + const streamChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_STREAM); + const completeChannel = diagnosticsChannel.tracingChannel(CHANNELS.PI_AI_COMPLETE); - // `complete` awaits `stream`, and the `compat` functions hand some models to a `Models` of their - // own, so a traced call can make another one synchronously. Only the outermost gets a span. - let depth = 0; - const startSpan = (data: OrchestrionChannelContext, streaming: boolean): Span | undefined => { - if (depth > 0) { + const startSpan = (data: PiAiChannelContext, streaming: boolean): Span | undefined => { + // `complete` awaits `stream`, and the `compat` functions hand some models to a `Models` of their + // own, so a traced call can make another one. Only the outermost gets a span. + if (isInsidePiAiSpan()) { return undefined; } - skipPiAiProviderIntegrations(); const [model, context, callOptions] = data.arguments ?? []; + const { recordInputs, recordOutputs } = resolvePiAiRecordingOptions(options); + data._sentryRecordOutputs = recordOutputs; return startInactiveSpan( getPiAiChatSpanOptions({ model: model ?? {}, @@ -45,15 +47,14 @@ function instrumentPiAi(options: PiAiOptions): void { context: context as PiAiContext | undefined, callOptions: callOptions as PiStreamOptions | undefined, streaming, - origin: PI_AI_ORIGIN, - recordInputs: resolveAIRecordingOptions(options).recordInputs, + recordInputs, }), ); }; - const setResponse = (span: Span, message: unknown): void => { + const setResponse = (span: Span, data: PiAiChannelContext, message: unknown): void => { if (message && typeof message === 'object') { - setPiAiResponseAttributes(span, message, resolveAIRecordingOptions(options).recordOutputs); + setPiAiResponseAttributes(span, message, !!data._sentryRecordOutputs); } }; @@ -66,7 +67,7 @@ function instrumentPiAi(options: PiAiOptions): void { return false; } settled.then(message => { - setResponse(span, message); + setResponse(span, data, message); end(); }, end); return true; @@ -76,36 +77,22 @@ function instrumentPiAi(options: PiAiOptions): void { bindTracingChannelToSpan(completeChannel, data => startSpan(data, false), { beforeSpanEnd: (span, data) => { if (!('error' in data)) { - setResponse(span, data.result); + setResponse(span, data, data.result); } }, }); - - for (const channel of [streamChannel, completeChannel]) { - channel.start.subscribe(() => { - depth++; - }); - channel.end.subscribe(() => { - depth--; - }); - } } /** * Traces the requests sent with pi-ai (`@earendil-works/pi-ai` >= 0.80.0 < 2) as `gen_ai.chat` spans, * through `createModels()` or the standalone `stream` and `complete` functions. Needs the Sentry - * runtime hook (`--import`) or bundler plugin. - * - * Not enabled by default yet. Flue and pi-durable send their model calls through pi-ai and still - * report them as chat spans of their own, so enabling this alongside them reports each call twice. - * - * Once pi-ai has sent a request, the `openai`, `@anthropic-ai/sdk`, `@google/genai` and Workers AI - * integrations stop recording requests for the rest of the process, since pi-ai sends through them. + * runtime hook (`--import`) or bundler plugin. This includes the model calls of Flue and pi-durable + * agents, which send them through pi-ai. * * @example * ```javascript * Sentry.init({ - * integrations: [Sentry.piAiIntegration()], + * integrations: [Sentry.piAiIntegration({ recordInputs: true, recordOutputs: true })], * }); * ``` */ diff --git a/packages/server-utils/src/integrations/pi-durable.ts b/packages/server-utils/src/integrations/pi-durable.ts index a9bd9e1b6a99..f04214a7fb17 100644 --- a/packages/server-utils/src/integrations/pi-durable.ts +++ b/packages/server-utils/src/integrations/pi-durable.ts @@ -60,9 +60,8 @@ function instrumentPiDurable(options: PiDurableOptions): void { * channel injected into `Harness.open()` and to the `codingTool` channel injected into the built-in * tool factories, so it requires the Sentry runtime hook or bundler plugin. * - * Traces one `gen_ai.invoke_agent` span per run, with its model requests as `gen_ai.chat` and its - * tool calls as `gen_ai.execute_tool` children. From the first model request on, the `openai`, - * `@anthropic-ai/sdk`, `@google/genai` and Workers AI integrations stop reporting requests in the - * whole process, because pi-ai sends its requests through those clients. + * Traces one `gen_ai.invoke_agent` span per run, with its tool calls as `gen_ai.execute_tool` + * children. Its model requests become `gen_ai.chat` children through `piAiIntegration`, since + * pi-durable sends them through pi-ai. */ export const piDurableIntegration = defineIntegration(_piDurableIntegration); diff --git a/packages/server-utils/src/orchestrion/config/channel-integration-definitions.ts b/packages/server-utils/src/orchestrion/config/channel-integration-definitions.ts index 46cd69d31bf9..635734bf7cdf 100644 --- a/packages/server-utils/src/orchestrion/config/channel-integration-definitions.ts +++ b/packages/server-utils/src/orchestrion/config/channel-integration-definitions.ts @@ -50,6 +50,7 @@ export const CHANNEL_INTEGRATION_DEFINITIONS = [ { exportName: 'langGraphIntegration', modules: ['@langchain/langgraph'] }, { exportName: 'mastraIntegration', modules: ['@mastra/core'] }, { exportName: 'flueIntegration', modules: ['@flue/runtime'] }, + { exportName: 'piAiIntegration', modules: ['@earendil-works/pi-ai'] }, { exportName: 'piDurableIntegration', modules: ['@earendil-works/pi-durable'] }, { exportName: 'mcpServerIntegration', modules: ['@modelcontextprotocol/server', '@modelcontextprotocol/sdk'] }, { exportName: 'awsIntegration', modules: ['@aws-sdk/smithy-client', '@smithy/core', '@smithy/smithy-client'] }, diff --git a/packages/server-utils/test/ai/lib/tracing/flue-pi-ai-warning.test.ts b/packages/server-utils/test/ai/lib/tracing/flue-pi-ai-warning.test.ts new file mode 100644 index 000000000000..a7a5d3211d82 --- /dev/null +++ b/packages/server-utils/test/ai/lib/tracing/flue-pi-ai-warning.test.ts @@ -0,0 +1,74 @@ +import { GLOBAL_OBJ } from '@sentry/core'; +import type { MockInstance } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const MODEL_OP = { type: 'model' }; +const NOT_TRACED = + '[Sentry] Flue model calls are not being traced: `@earendil-works/pi-ai` was not instrumented, so ' + + 'Flue agents record agent and tool spans but no `gen_ai.chat` spans. '; + +/** A fresh module per test: the check runs once per process. */ +async function runModelCalls(count: number): Promise { + vi.resetModules(); + const { createFlueInstrumentation } = await import('../../../../src/ai/flue'); + const instrumentation = createFlueInstrumentation(); + for (let i = 0; i < count; i++) { + await instrumentation.interceptor(MODEL_OP, {}, async () => undefined); + } +} + +describe('Flue warning about uninstrumented pi-ai', () => { + let warn: MockInstance; + + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + + afterEach(() => { + delete GLOBAL_OBJ.__SENTRY_ORCHESTRION__; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('warns once when pi-ai was not instrumented', async () => { + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { runtime: ['@flue/runtime'] }; + + await runModelCalls(2); + + expect(warn).toHaveBeenCalledOnce(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining(NOT_TRACED)); + }); + + it.each([ + ['Node', {}, 'Load Sentry with `--import`, for example `node --import ./instrument.mjs app.mjs`.'], + [ + 'Bun', + { Bun: {} }, + 'Build your app with `sentryBunPlugin()` from `@sentry/bun/plugin`; `bun run` cannot instrument it.', + ], + ['Deno', { Deno: {} }, 'Run your app with `deno run --preload=npm:@sentry/deno/import app.ts`.'], + [ + 'Cloudflare', + { navigator: { userAgent: 'Cloudflare-Workers' } }, + 'Add `sentryCloudflareVitePlugin()` from `@sentry/cloudflare/vite` to your Vite config.', + ], + ])('gives only the fix for %s', async (_runtime, globals, fix) => { + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { runtime: ['@flue/runtime'] }; + Object.entries(globals).forEach(([name, value]) => vi.stubGlobal(name, value)); + + await runModelCalls(1); + + expect(warn).toHaveBeenCalledWith(NOT_TRACED + fix); + }); + + it.each([ + ['the runtime hook', { runtime: ['@earendil-works/pi-ai'] }], + ['a bundler plugin', { bundler: new Set(['@earendil-works/pi-ai']) }], + ])('stays quiet when %s instrumented pi-ai', async (_label, injected) => { + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = injected; + + await runModelCalls(1); + + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/server-utils/test/ai/lib/tracing/flue.test.ts b/packages/server-utils/test/ai/lib/tracing/flue.test.ts index e39ed3fd3bfb..42fd0fb0edad 100644 --- a/packages/server-utils/test/ai/lib/tracing/flue.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/flue.test.ts @@ -1,9 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'; import type { Event, Span } from '@sentry/core'; import { - _INTERNAL_clearAiProviderSkips, - _INTERNAL_shouldSkipAiProviderWrapping, - _INTERNAL_skipAiProviderWrapping, + getCurrentScope, getIsolationScope, getMainCarrier, Scope, @@ -15,58 +13,22 @@ import { withActiveSpan, withIsolationScope, } from '@sentry/core'; -import { ANTHROPIC_AI_INTEGRATION_NAME } from '../../../../src/ai/anthropic-ai/constants'; import { setAsyncLocalStorageAsyncContextStrategy } from '../../../../src/async-context'; import { createFlueInstrumentation } from '../../../../src/ai/flue'; -import { MAX_TRACKED_FLUE_SPANS } from '../../../../src/ai/flue/constants'; -import { GOOGLE_GENAI_INTEGRATION_NAME } from '../../../../src/ai/google-genai/constants'; -import type { FlueInstrumentation, FlueObservation } from '../../../../src/ai/flue/types'; -import { OPENAI_INTEGRATION_NAME } from '../../../../src/ai/openai/constants'; +import { resolvePiAiRecordingOptions } from '../../../../src/ai/pi-ai/recording'; +import type { FlueInstrumentation } from '../../../../src/ai/flue/types'; import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; const AGENT_OP = { type: 'agent', operationId: 'op_1' }; const AGENT_CTX = { agentName: 'Hello', submissionId: 'sub_1' }; const INNER_CTX = { conversationId: 'conv_1' }; -/** A settled turn as Flue reports it, with the field names `ModelRequestInfo`/`ModelResponse` use. */ -function turn(overrides: Partial = {}): FlueObservation { - return { - type: 'turn', - turnId: 'turn_1', - submissionId: 'sub_1', - operationId: 'op_1', - request: { - requestedModel: 'claude-haiku-4.5', - providerId: 'anthropic', - temperature: 0.7, - maxTokens: 1024, - reasoningLevel: 'high', - serverAddress: 'api.anthropic.com', - serverPort: 443, - }, - response: { - responseId: 'resp_1', - finishReason: 'stop', - usage: { - input: 924, - output: 57, - totalTokens: 981, - cacheRead: 0, - cacheWrite: 0, - cost: { input: 0.000924, output: 0.000275, total: 0.001199, cacheRead: 0, cacheWrite: 0 }, - }, - }, - ...overrides, - }; -} - describe('createFlueInstrumentation', () => { let endedSpans: Span[]; let client: TestClient; let instrumentation: FlueInstrumentation; beforeEach(() => { - _INTERNAL_clearAiProviderSkips(); getMainCarrier().__SENTRY__ = undefined; client = new TestClient( getDefaultTestClientOptions({ @@ -84,7 +46,6 @@ describe('createFlueInstrumentation', () => { }); afterEach(() => { - _INTERNAL_clearAiProviderSkips(); getMainCarrier().__SENTRY__ = undefined; }); @@ -103,55 +64,6 @@ describe('createFlueInstrumentation', () => { return endedSpans.map(span => spanToStaticSpanJSON(span)).find(json => json.description === description); } - // Flue drives the providers through `pi-ai`, which bundles the `openai` / `@anthropic-ai/sdk` / - // `@google/genai` clients those integrations patch, so their spans duplicate the turn span. - // Not at construction: if `instrument()` rejects the object, suppressing the provider - // integrations would leave the app with no `gen_ai.chat` spans at all. - it('skips raw provider wrapping on first use, not on construction', async () => { - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); - - await withAgent(() => undefined); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - }); - - // The registry is reset per client (`_setupIntegrations` clears it, and Cloudflare calls `init()` - // per request), so a one-shot call at construction is wiped by the next reset. - it('re-applies the provider skip after the registry is cleared', async () => { - await withAgent(() => undefined); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - - _INTERNAL_clearAiProviderSkips(); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); - - await withAgent(() => undefined); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - }); - - // The guard has to hold for every provider, not just the first: another integration may have - // registered a skip for one of them already, which would otherwise short-circuit the rest. - it('applies the skip to every provider when only some are already registered', async () => { - _INTERNAL_skipAiProviderWrapping([OPENAI_INTEGRATION_NAME]); - - await withAgent(() => undefined); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); - }); - - // A turn whose stream is abandoned never emits the settled `turn` that would remove it, so the - // tracker is capped. Eviction has to end the span it drops, or it is never sent. - it('ends the oldest chat span when the turn tracker overflows', async () => { - await withAgent(() => { - for (let i = 0; i <= MAX_TRACKED_FLUE_SPANS; i++) { - instrumentation.observe({ type: 'turn_start', turnId: `turn_${i}`, operationId: 'op_1' }, {}); - } - }); - - expect(endedSpans.filter(span => spanToStaticSpanJSON(span).data['sentry.op'] === 'gen_ai.chat')).toHaveLength(1); - }); - it('names agent spans `invoke_agent {name}` and sets the gen_ai op', async () => { await withAgent(() => undefined); @@ -166,10 +78,7 @@ describe('createFlueInstrumentation', () => { // the agent, and the conversation arrives on the observations that follow. it('sets the conversation id on the agent span from the observations', async () => { await withAgent(() => { - instrumentation.observe( - { type: 'turn_start', turnId: 'turn_1', operationId: 'op_1', conversationId: 'conv_1' }, - {}, - ); + instrumentation.observe({ type: 'turn_start', operationId: 'op_1', conversationId: 'conv_1' }, {}); }); expect(findSpan('invoke_agent Hello')?.data['gen_ai.conversation.id']).toBe('conv_1'); @@ -384,26 +293,42 @@ describe('createFlueInstrumentation', () => { }); it('does not span operations other than `agent`', async () => { - await instrumentation.interceptor({ type: 'model', turnId: 'turn_1' }, {}, async () => undefined); + await instrumentation.interceptor({ type: 'model' }, {}, async () => undefined); expect(endedSpans).toHaveLength(0); }); - // The `model` and `tool` operations open no span of their own; they make the span `observe` - // already opened active, so the provider's HTTP call and the tool's own work nest inside it - // rather than landing beside it as siblings of the agent invocation. - it('makes the turn span active for the model operation it wraps', async () => { - await withAgent(async () => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - await instrumentation.interceptor({ type: 'model', turnId: 'turn_1' }, {}, async () => { - startInactiveSpan({ name: 'provider request' }).end(); - }); - instrumentation.observe(turn(), {}); + // The model call's `gen_ai.chat` span comes from the pi-ai integration, which reads the + // conversation from the scope. + it('hands the conversation to the model operation it wraps through the scope', async () => { + let conversationId: string | undefined; + + await withAgent(() => + instrumentation.interceptor({ type: 'model' }, INNER_CTX, async () => { + conversationId = getCurrentScope().getScopeData().conversationId; + }), + ); + + expect(conversationId).toBe('conv_1'); + expect(getCurrentScope().getScopeData().conversationId).toBeUndefined(); + expect(endedSpans.map(span => spanToStaticSpanJSON(span).description)).toEqual(['invoke_agent Hello']); + }); + + it('hands its recording options to the model operation it wraps through the scope', async () => { + let recording: unknown; + + await createFlueInstrumentation({ recordInputs: false }).interceptor({ type: 'model' }, {}, async () => { + recording = resolvePiAiRecordingOptions({}); }); - expect(findSpan('provider request')?.parent_span_id).toBe(findSpan('chat claude-haiku-4.5')?.span_id); + expect(recording).toEqual({ recordInputs: false, recordOutputs: true }); + expect(resolvePiAiRecordingOptions({})).toEqual({ recordInputs: true, recordOutputs: true }); }); + // The `tool` operation opens no span of its own; it makes the span `observe` already opened + // active, so the tool's own work nests inside it rather than landing beside it as a sibling of + // the agent invocation. + it('makes the tool span active for the tool operation it wraps', async () => { await withAgent(async () => { instrumentation.observe( @@ -419,163 +344,9 @@ describe('createFlueInstrumentation', () => { expect(findSpan('tool work')?.parent_span_id).toBe(findSpan('execute_tool get_weather')?.span_id); }); - it('opens a chat span on turn_start and completes it from the settled turn', async () => { - await withAgent(() => { - instrumentation.observe( - { type: 'turn_start', turnId: 'turn_1', operationId: 'op_1', conversationId: 'conv_1' }, - {}, - ); - instrumentation.observe(turn(), {}); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json?.data['sentry.op']).toBe('gen_ai.chat'); - expect(json?.data['sentry.origin']).toBe('auto.ai.flue'); - expect(json?.data['gen_ai.request.model']).toBe('claude-haiku-4.5'); - expect(json?.data['gen_ai.provider.name']).toBe('anthropic'); - expect(json?.data['gen_ai.response.id']).toBe('resp_1'); - expect(json?.data['gen_ai.response.finish_reasons']).toBe('["stop"]'); - expect(json?.data['gen_ai.conversation.id']).toBe('conv_1'); - }); - - // Flue computes costs itself; the provider SDKs report none. - it('records token usage and Flue-computed cost on the chat span', async () => { - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe(turn(), {}); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json?.data['gen_ai.usage.input_tokens']).toBe(924); - expect(json?.data['gen_ai.usage.output_tokens']).toBe(57); - expect(json?.data['gen_ai.usage.total_tokens']).toBe(981); - expect(json?.data['gen_ai.cost.total_tokens']).toBe(0.001199); - }); - - // pi-ai keeps the cached tokens out of `input`; the conventions count them in. - it('counts cached tokens into the input tokens and their cost into the input cost', async () => { - const usage = { - input: 37, - output: 2, - cacheRead: 52, - cacheWrite: 38, - totalTokens: 129, - cost: { input: 0.000037, output: 0.00001, cacheRead: 0.0000052, cacheWrite: 0.0000475, total: 0.0000997 }, - }; - - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe(turn({ response: { ...turn().response, usage } }), {}); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json?.data['gen_ai.usage.input_tokens']).toBe(127); - expect(json?.data['gen_ai.usage.cache_read.input_tokens']).toBe(52); - expect(json?.data['gen_ai.usage.cache_creation.input_tokens']).toBe(38); - expect(json?.data['gen_ai.cost.input_tokens']).toBe(0.000037 + 0.0000052 + 0.0000475); - expect(json?.data['gen_ai.cost.total_tokens']).toBe(0.0000997); - }); - - it('reports a tool-calling turn with the finish reason of the conventions', async () => { - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe( - turn({ - response: { - ...turn().response, - finishReason: 'toolUse', - output: { - role: 'assistant', - content: [{ type: 'toolCall', id: 'c1', name: 'get_weather', arguments: { city: 'Berlin' } }], - }, - }, - }), - {}, - ); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json?.data['gen_ai.response.finish_reasons']).toBe('["tool_call"]'); - expect(json?.data['gen_ai.output.messages']).toBe( - '[{"role":"assistant","parts":[{"type":"tool_call","id":"c1","name":"get_weather","arguments":"{\\"city\\":\\"Berlin\\"}"}],"finish_reason":"tool_call"}]', - ); - }); - - it('records the model-call tuning and provider endpoint', async () => { - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1', purpose: 'agent' }, {}); - instrumentation.observe(turn(), {}); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json?.data['gen_ai.request.temperature']).toBe(0.7); - expect(json?.data['gen_ai.request.max_tokens']).toBe(1024); - expect(json?.data['gen_ai.request.reasoning.level']).toBe('high'); - expect(json?.data['server.address']).toBe('api.anthropic.com'); - expect(json?.data['server.port']).toBe(443); - // Distinguishes a compaction turn from a user-facing one. - expect(json?.data['flue.turn.purpose']).toBe('agent'); - }); - - it('marks a failed turn as errored', async () => { - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe(turn({ isError: true }), {}); - }); - - expect(findSpan('chat claude-haiku-4.5')?.status).toBe('internal_error'); - }); - - // A turn that fails before the provider bills anything reports every counter as 0; writing those - // reads as a real zero-cost call. - it('omits usage entirely when a failed turn produced no tokens', async () => { - const empty = { - input: 0, - output: 0, - totalTokens: 0, - cacheRead: 0, - cacheWrite: 0, - cost: { input: 0, output: 0, total: 0, cacheRead: 0, cacheWrite: 0 }, - }; - - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe(turn({ isError: true, response: { usage: empty } }), {}); - }); - - const json = findSpan('chat claude-haiku-4.5'); - expect(json).toBeDefined(); - expect(json?.data['gen_ai.usage.total_tokens']).toBeUndefined(); - expect(json?.data['gen_ai.cost.total_tokens']).toBeUndefined(); - }); - describe('content recording', () => { - const requestContent = { - type: 'turn_request', - turnId: 'turn_1', - request: { - requestedModel: 'claude-haiku-4.5', - input: { - systemPrompt: 'You are helpful.', - messages: [{ role: 'user', content: 'hi' }], - tools: [{ name: 'get_weather', description: 'weather', parameters: {} }], - }, - }, - } satisfies FlueObservation; - async function record(instr: FlueInstrumentation): Promise { await instr.interceptor(AGENT_OP, AGENT_CTX, async () => { - instr.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instr.observe(requestContent, {}); - instr.observe( - turn({ - response: { - ...turn().response, - output: { role: 'assistant', content: [{ type: 'text', text: 'It is sunny.' }] }, - }, - }), - {}, - ); instr.observe( { type: 'tool_start', @@ -601,18 +372,9 @@ describe('createFlueInstrumentation', () => { }); } - it('records messages, instructions, tool definitions, arguments and results by default', async () => { + it('records tool arguments and results by default', async () => { await record(instrumentation); - const chat = findSpan('chat claude-haiku-4.5'); - expect(chat?.data['gen_ai.system_instructions']).toBe('You are helpful.'); - // Mapped from pi-ai's message shape to the conventions, which is what Sentry renders. - expect(chat?.data['gen_ai.input.messages']).toBe('[{"role":"user","parts":[{"type":"text","content":"hi"}]}]'); - expect(chat?.data['gen_ai.output.messages']).toBe( - '[{"role":"assistant","parts":[{"type":"text","content":"It is sunny."}],"finish_reason":"stop"}]', - ); - expect(chat?.data['gen_ai.tool.definitions']).toContain('get_weather'); - const tool = findSpan('execute_tool get_weather'); expect(tool?.data['gen_ai.tool.call.arguments']).toBe('{"city":"Berlin"}'); expect(tool?.data['gen_ai.tool.call.result']).toBe('sunny'); @@ -692,53 +454,12 @@ describe('createFlueInstrumentation', () => { expect(findSpan('execute_tool get_weather')?.data['gen_ai.tool.call.result']).toBe(''); }); - it('maps a tool result in the request and a tool call in the response', async () => { - await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); - instrumentation.observe( - { - ...requestContent, - request: { - ...requestContent.request, - input: { - messages: [ - { role: 'user', content: 'Weather in Berlin?' }, - { - role: 'assistant', - content: [{ type: 'toolCall', id: 'c1', name: 'get_weather', arguments: { city: 'Berlin' } }], - }, - { - role: 'toolResult', - toolCallId: 'c1', - toolName: 'get_weather', - content: [{ type: 'text', text: 'sunny' }], - isError: false, - }, - ], - }, - }, - }, - {}, - ); - instrumentation.observe(turn(), {}); - }); - - expect( - JSON.parse(String(findSpan('chat claude-haiku-4.5')?.data['gen_ai.input.messages'])).map( - (message: { role: string }) => message.role, - ), - ).toEqual(['user', 'assistant', 'tool']); - }); - it('omits inputs when recordInputs is false but keeps outputs', async () => { await record(createFlueInstrumentation({ recordInputs: false })); - const chat = findSpan('chat claude-haiku-4.5'); - expect(chat?.data['gen_ai.input.messages']).toBeUndefined(); - expect(chat?.data['gen_ai.system_instructions']).toBeUndefined(); - expect(chat?.data['gen_ai.tool.definitions']).toBeUndefined(); - expect(chat?.data['gen_ai.output.messages']).toBeDefined(); - expect(findSpan('execute_tool get_weather')?.data['gen_ai.tool.call.arguments']).toBeUndefined(); + const tool = findSpan('execute_tool get_weather'); + expect(tool?.data['gen_ai.tool.call.arguments']).toBeUndefined(); + expect(tool?.data['gen_ai.tool.call.result']).toBeDefined(); }); // The client is replaced per request on Cloudflare, so options captured once at construction @@ -746,7 +467,7 @@ describe('createFlueInstrumentation', () => { it('follows the current client when it is replaced', async () => { const instr = createFlueInstrumentation(); await record(instr); - expect(findSpan('chat claude-haiku-4.5')?.data['gen_ai.input.messages']).toBeDefined(); + expect(findSpan('execute_tool get_weather')?.data['gen_ai.tool.call.arguments']).toBeDefined(); endedSpans.length = 0; const strict = new TestClient( @@ -763,18 +484,17 @@ describe('createFlueInstrumentation', () => { await record(instr); - const chat = findSpan('chat claude-haiku-4.5'); - expect(chat).toBeDefined(); - expect(chat?.data['gen_ai.input.messages']).toBeUndefined(); + const tool = findSpan('execute_tool get_weather'); + expect(tool).toBeDefined(); + expect(tool?.data['gen_ai.tool.call.arguments']).toBeUndefined(); }); it('omits outputs when recordOutputs is false but keeps inputs', async () => { await record(createFlueInstrumentation({ recordOutputs: false })); - const chat = findSpan('chat claude-haiku-4.5'); - expect(chat?.data['gen_ai.output.messages']).toBeUndefined(); - expect(chat?.data['gen_ai.input.messages']).toBeDefined(); - expect(findSpan('execute_tool get_weather')?.data['gen_ai.tool.call.result']).toBeUndefined(); + const tool = findSpan('execute_tool get_weather'); + expect(tool?.data['gen_ai.tool.call.result']).toBeUndefined(); + expect(tool?.data['gen_ai.tool.call.arguments']).toBeDefined(); }); }); @@ -878,19 +598,11 @@ describe('createFlueInstrumentation', () => { // for a re-entry of the first: it gets no span, and its conversation id lands on the first's span. it('keeps concurrent agent runs separate', async () => { const runA = instrumentation.interceptor({ type: 'agent', operationId: 'op_a' }, { agentName: 'A' }, async () => { - instrumentation.observe( - { type: 'turn_start', turnId: 'turn_a', operationId: 'op_a', conversationId: 'conv_a' }, - {}, - ); + instrumentation.observe({ type: 'agent_start', operationId: 'op_a', conversationId: 'conv_a' }, {}); // B starts while A is still open. await instrumentation.interceptor({ type: 'agent', operationId: 'op_b' }, { agentName: 'B' }, async () => { - instrumentation.observe( - { type: 'turn_start', turnId: 'turn_b', operationId: 'op_b', conversationId: 'conv_b' }, - {}, - ); - instrumentation.observe(turn({ turnId: 'turn_b', operationId: 'op_b' }), {}); + instrumentation.observe({ type: 'agent_start', operationId: 'op_b', conversationId: 'conv_b' }, {}); }); - instrumentation.observe(turn({ turnId: 'turn_a', operationId: 'op_a' }), {}); }); await runA; @@ -904,9 +616,8 @@ describe('createFlueInstrumentation', () => { expect(agentB?.data['gen_ai.conversation.id']).toBe('conv_b'); }); - it('ignores a settled turn or tool it never opened a span for', async () => { + it('ignores a settled tool it never opened a span for', async () => { await withAgent(() => { - instrumentation.observe(turn({ turnId: 'never_started' }), {}); instrumentation.observe({ type: 'tool', toolCallId: 'never_started', toolName: 'x' }, {}); }); @@ -915,18 +626,15 @@ describe('createFlueInstrumentation', () => { it('ends spans still open at dispose', async () => { await withAgent(() => { - instrumentation.observe({ type: 'turn_start', turnId: 'turn_1', operationId: 'op_1' }, {}); instrumentation.observe( { type: 'tool_start', toolCallId: 'call_1', toolName: 'get_weather', operationId: 'op_1' }, {}, ); }); - // Never settled, so the span keeps the unqualified name it opened with. - expect(findSpan('chat')).toBeUndefined(); + expect(findSpan('execute_tool get_weather')).toBeUndefined(); instrumentation.dispose(); - expect(findSpan('chat')).toBeDefined(); expect(findSpan('execute_tool get_weather')).toBeDefined(); }); }); diff --git a/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts b/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts index ef8c7aeeff31..da6d3b1b1475 100644 --- a/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/pi-durable.test.ts @@ -10,42 +10,23 @@ import { setCurrentClient, spanToJSON, spanToStaticSpanJSON, + startInactiveSpan, withScope, } from '@sentry/core'; import { GEN_AI_CONVERSATION_ID, - GEN_AI_INPUT_MESSAGES, - GEN_AI_OUTPUT_MESSAGES, - GEN_AI_PROVIDER_NAME, - GEN_AI_REQUEST_MAX_TOKENS, - GEN_AI_REQUEST_MODEL, - GEN_AI_REQUEST_REASONING_LEVEL, - GEN_AI_REQUEST_TEMPERATURE, - GEN_AI_RESPONSE_FINISH_REASONS, - GEN_AI_RESPONSE_ID, - GEN_AI_RESPONSE_MODEL, - GEN_AI_RESPONSE_STREAMING, - GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, - GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, - GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, - GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, - 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, SENTRY_STATUS_MESSAGE, - SERVER_ADDRESS, - SERVER_PORT, } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../src/ai/core/gen-ai-attributes'; import { endRunsOnClose, instrumentPiDurableHarnessOptions } from '../../../../src/ai/pi-durable'; +import { getPiAiChatSpanOptions } from '../../../../src/ai/pi-ai/chat'; import { MAX_TRACKED_PI_RUNS } from '../../../../src/ai/pi-durable/constants'; import type { PiRuns } from '../../../../src/ai/pi-durable/runs'; import { createRuns, startRun } from '../../../../src/ai/pi-durable/runs'; @@ -54,7 +35,6 @@ import type { PiCommitChange, PiHarnessOptions, PiLiveState, - PiModels, PiRegistryReader, PiSettlement, PiTask, @@ -63,16 +43,21 @@ import type { PiToolExecutionApi, PiToolExecutionResult, } from '../../../../src/ai/pi-durable/types'; -import type { PiEventStream } from '../../../../src/ai/pi-ai/types'; -import { ANTHROPIC_AI_INTEGRATION_NAME } from '../../../../src/ai/anthropic-ai/constants'; -import { GOOGLE_GENAI_INTEGRATION_NAME } from '../../../../src/ai/google-genai/constants'; -import { OPENAI_INTEGRATION_NAME } from '../../../../src/ai/openai/constants'; -import { instrumentWorkersAiClient } from '../../../../src/ai/workers-ai'; import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; const LIVE_DOC = { definition: { kind: 'pi.live' } }; -const MODEL = { id: 'faux-model', provider: 'faux' }; -const ANSWER = { role: 'assistant', content: [{ type: 'text', text: 'Paris.' }], stopReason: 'stop' }; + +// What `piAiIntegration` does for each model request pi-durable sends through pi-ai. +function sendModelRequest(): void { + startInactiveSpan( + getPiAiChatSpanOptions({ + model: { id: 'faux-model', provider: 'faux' }, + context: { messages: [] }, + streaming: false, + recordInputs: false, + }), + ).end(); +} describe('instrumentPiDurableHarnessOptions', () => { let endedSpans: Span[]; @@ -106,14 +91,17 @@ describe('instrumentPiDurableHarnessOptions', () => { }); it('wraps the options once and leaves the caller objects untouched', () => { - const models = { completeSimple: async () => ({}) }; - const options: PiHarnessOptions = { models }; + const registry: PiRegistryReader = { + snapshot: () => ({ task: () => undefined, tasks: () => [] }), + subscribe: () => () => undefined, + }; + const options: PiHarnessOptions = { registry }; const instrumented = instrumentPiDurableHarnessOptions(options); expect(instrumented).not.toBe(options); - expect(instrumented.models).not.toBe(models); - expect(options.models).toBe(models); + expect(instrumented.registry).not.toBe(registry); + expect(options.registry).toBe(registry); expect(instrumentPiDurableHarnessOptions(instrumented)).toBe(instrumented); }); @@ -121,7 +109,7 @@ describe('instrumentPiDurableHarnessOptions', () => { // assignments on the caller's options must reach it. it('keeps the options the caller changes later live', () => { let env = 'first'; - const options = { models: {}, settings: { toolExecution: 'sequential' } } as PiHarnessOptions & { + const options = { settings: { toolExecution: 'sequential' } } as PiHarnessOptions & { settings: unknown; env?: string; }; @@ -135,322 +123,18 @@ describe('instrumentPiDurableHarnessOptions', () => { expect(instrumented.env).toBe('second'); }); - it('hands members other than model requests through, bound to the original', () => { - class Models { - private _provider = 'faux'; - public getProvider(): string { - return this._provider; - } - } - - const instrumented = instrumentPiDurableHarnessOptions({ models: new Models() as PiModels }); - - expect((instrumented.models as unknown as Models).getProvider()).toBe('faux'); - expect(endedSpans).toHaveLength(0); - }); - - it('traces a streamed model request and skips the provider SDK integrations', async () => { - const message = { - ...ANSWER, - model: 'faux-model', - usage: { input: 10, output: 2, totalTokens: 12 }, - }; - const models: PiModels = { streamSimple: () => ({ result: async () => message }) }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.streamSimple!(MODEL, { - messages: [{ role: 'user', content: 'Capital of France?' }], - }).result(); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - const chat = spanToStaticSpanJSON(endedSpans[0]!); - expect(chat.description).toBe('chat faux-model'); - expect(chat.op).toBe(GEN_AI_CHAT); - expect(chat.data).toMatchObject({ - [GEN_AI_PROVIDER_NAME]: 'faux', - [GEN_AI_REQUEST_MODEL]: 'faux-model', - [GEN_AI_RESPONSE_STREAMING]: true, - [GEN_AI_RESPONSE_FINISH_REASONS]: '["stop"]', - [GEN_AI_USAGE_INPUT_TOKENS]: 10, - [GEN_AI_USAGE_OUTPUT_TOKENS]: 2, - }); - expect(chat.data[GEN_AI_INPUT_MESSAGES]).toBe( - '[{"role":"user","parts":[{"type":"text","content":"Capital of France?"}]}]', - ); - expect(chat.data[GEN_AI_OUTPUT_MESSAGES]).toBe( - '[{"role":"assistant","parts":[{"type":"text","content":"Paris."}],"finish_reason":"stop"}]', - ); - }); - - it.each([ - ['stream', true], - ['streamSimple', true], - ['streamDeferred', true], - ['complete', false], - ['completeSimple', false], - ['fetchDeferred', false], - ])('traces %s with the request options and the response identity', async (method, streaming) => { - const message = { ...ANSWER, responseModel: 'faux-model-2026', responseId: 'resp_1' }; - const models = { - [method]: streaming ? () => ({ result: async () => message }) : async () => message, - } as PiModels; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - const result = (instrumented.models as Record unknown>)[method]!( - { ...MODEL, baseUrl: 'https://api.example.com:8443/v1' }, - { messages: [{ role: 'user', content: 'Hi.' }] }, - { temperature: 0.2, maxTokens: 50, reasoning: 'low' }, - ); - await (streaming ? (result as PiEventStream).result() : result); - - const chat = spanToJSON(endedSpans[0]!); - expect(chat.name).toBe('chat faux-model'); - expect(chat.attributes[GEN_AI_RESPONSE_STREAMING]).toBe(streaming ? true : undefined); - expect(chat.attributes[GEN_AI_RESPONSE_MODEL]).toBe('faux-model-2026'); - expect(chat.attributes[GEN_AI_RESPONSE_ID]).toBe('resp_1'); - expect(chat.attributes[SERVER_ADDRESS]).toBe('api.example.com'); - expect(chat.attributes[SERVER_PORT]).toBe(8443); - // The deferred methods take a handle, not a request, so there is nothing to record. - const deferred = method.endsWith('Deferred'); - expect(chat.attributes[GEN_AI_REQUEST_TEMPERATURE]).toBe(deferred ? undefined : 0.2); - expect(chat.attributes[GEN_AI_REQUEST_MAX_TOKENS]).toBe(deferred ? undefined : 50); - expect(chat.attributes[GEN_AI_REQUEST_REASONING_LEVEL]).toBe(deferred ? undefined : 'low'); - expect(chat.attributes[GEN_AI_INPUT_MESSAGES]).toBe( - deferred ? undefined : '[{"role":"user","parts":[{"type":"text","content":"Hi."}]}]', - ); - }); - - it('sets the conversation id of the scope on the chat span itself', async () => { - const models: PiModels = { completeSimple: async () => ANSWER }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await withScope(async scope => { - scope.setConversationId('harness:7'); - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - }); - - expect(spanToJSON(endedSpans[0]!).attributes[GEN_AI_CONVERSATION_ID]).toBe('harness:7'); - }); - - it('counts the cached tokens of a response into its input tokens', async () => { - const message = { - ...ANSWER, - usage: { input: 37, output: 2, cacheRead: 52, cacheWrite: 38, reasoning: 1, totalTokens: 129 }, - }; - const models: PiModels = { completeSimple: async () => message }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - - expect(spanToJSON(endedSpans[0]!).attributes).toMatchObject({ - [GEN_AI_USAGE_INPUT_TOKENS]: 127, - [GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: 52, - [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: 38, - [GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: 1, - [GEN_AI_USAGE_TOTAL_TOKENS]: 129, - }); - }); - - // The provider parks the request and pi-durable fetches the answer later: only the fetch is billed. - it('records no usage for a request the provider parked, and the usage of its answer', async () => { - const parked = { - role: 'assistant', - content: [], - stopReason: 'deferred', - usage: { input: 0, output: 0, totalTokens: 0 }, - }; - const answer = { ...ANSWER, usage: { input: 8, output: 2, totalTokens: 10 } }; - const models: PiModels = { completeSimple: async () => parked, fetchDeferred: async () => answer }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - await instrumented.models!.fetchDeferred!(MODEL, { id: 'handle_1' }); - - const [parkedChat, answerChat] = endedSpans.map(span => spanToJSON(span).attributes); - expect(parkedChat![GEN_AI_RESPONSE_FINISH_REASONS]).toBe('["deferred"]'); - expect(parkedChat![GEN_AI_USAGE_TOTAL_TOKENS]).toBeUndefined(); - expect(answerChat![GEN_AI_USAGE_TOTAL_TOKENS]).toBe(10); - }); - - it('marks a failed request with a fixed status message and maps a tool-calling stop', async () => { - const failed = { - role: 'assistant', - content: [], - stopReason: 'error', - errorMessage: '401 invalid x-api-key for user@example.com', - usage: { input: 0, output: 0, totalTokens: 0 }, - }; - const toolCall = { - role: 'assistant', - content: [{ type: 'toolCall', id: 'call_1', name: 'read', arguments: { path: 'a.txt' } }], - stopReason: 'toolUse', - }; - const models: PiModels = { completeSimple: async () => failed, complete: async () => toolCall }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - await instrumented.models!.complete!(MODEL, { messages: [] }); - - const [chatFailed, chatToolCall] = endedSpans.map(span => spanToJSON(span)); - expect(chatFailed!.status).toBe('error'); - expect(chatFailed!.attributes[SENTRY_STATUS_MESSAGE]).toBe('internal_error'); - expect(JSON.stringify(chatFailed!.attributes)).not.toContain('x-api-key'); - expect(chatFailed!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toBeUndefined(); - expect(chatToolCall!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toBe('["tool_call"]'); - expect(chatToolCall!.attributes[GEN_AI_OUTPUT_MESSAGES]).toContain('"finish_reason":"tool_call"'); - }); - - it('marks a rejected or throwing request as errored and keeps the error', async () => { - const models: PiModels = { - completeSimple: async () => { - throw new Error('boom'); - }, - stream: () => { - throw new Error('sync boom'); - }, - }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await expect(instrumented.models!.completeSimple!(MODEL, { messages: [] })).rejects.toThrow('boom'); - expect(() => instrumented.models!.stream!(MODEL, { messages: [] })).toThrow('sync boom'); - - expect(endedSpans.map(span => spanToJSON(span).attributes[SENTRY_STATUS_MESSAGE])).toEqual([ - 'internal_error', - 'internal_error', - ]); - }); - - it('returns a result of another shape unchanged and ends its span', () => { - const stream = { events: [] }; - const models: PiModels = { - stream: () => stream as unknown as PiEventStream, - completeSimple: (() => 'parked') as unknown as PiModels['completeSimple'], - }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - expect(instrumented.models!.stream!(MODEL, { messages: [] })).toBe(stream); - expect(instrumented.models!.completeSimple!(MODEL, { messages: [] })).toBe('parked'); - - expect(endedSpans.map(span => spanToJSON(span).name)).toEqual(['chat faux-model', 'chat faux-model']); - }); - - it('reads the system prompt and the tools from the positional system messages', async () => { - const models: PiModels = { - streamSimple: () => ({ result: async () => ({ role: 'assistant', content: [], stopReason: 'stop' }) }), - }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - // pi-durable never sets `systemPrompt` or `tools`: it sends prompt sections and tool changes as - // system messages, and each request replays them. - await instrumented.models!.streamSimple!(MODEL, { - messages: [ - { - role: 'system', - content: '', - sections: { preamble: 'You help.' }, - toolsAdded: [{ name: 'read' }, { name: 'bash' }], - }, - { role: 'user', content: 'Hi.' }, - { role: 'system', content: '', sections: { mode: 'Plan only.' }, toolsRemoved: [{ name: 'bash' }] }, - ], - }).result(); - - const chat = spanToStaticSpanJSON(endedSpans[0]!); - expect(chat.data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBe('You help.\n\nPlan only.'); - expect(chat.data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"name":"read"}]'); - expect(chat.data[GEN_AI_INPUT_MESSAGES]).toBe('[{"role":"user","parts":[{"type":"text","content":"Hi."}]}]'); - }); - - describe('provider skip', () => { - const models: PiModels = { completeSimple: async () => ANSWER }; - - it('skips the provider integrations on the first request, not when the options are wrapped', async () => { - const instrumented = instrumentPiDurableHarnessOptions({ models }); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); - }); - - // The registry is reset per client, so a one-shot call would be undone by the next `init()`. - it('applies the skip again after the registry is cleared', async () => { - const instrumented = instrumentPiDurableHarnessOptions({ models }); - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - _INTERNAL_clearAiProviderSkips(); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - }); - - it('applies the skip to every provider when only some are already registered', async () => { - _INTERNAL_skipAiProviderWrapping([OPENAI_INTEGRATION_NAME]); - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); - }); - - // `createAI()` of `agents/models/pi-ai` sends pi-ai requests through the Workers AI binding. - it('reports a request sent through the Workers AI binding once', async () => { - const ai = instrumentWorkersAiClient({ - run: async (_model: string, _inputs: unknown, _options: unknown) => new Response('{}'), - gateway: () => ({}), - toMarkdown: async () => [], - }); - const models: PiModels = { - completeSimple: async () => { - await ai.run('@cf/moonshotai/kimi-k2.7-code', { messages: [] }, { returnRawResponse: true }); - return ANSWER; - }, - }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - - await instrumented.models!.completeSimple!(MODEL, { messages: [] }); - - expect(endedSpans.map(span => spanToStaticSpanJSON(span).description)).toEqual(['chat faux-model']); - }); - }); - describe('content recording', () => { const tool: PiTool = { name: 'get_weather', description: 'Get the weather.', execute: async () => ({ content: [{ type: 'text', text: 'sunny' }] }), }; - const message = { - role: 'assistant', - content: [{ type: 'toolCall', id: 'call_1', name: 'get_weather', arguments: { city: 'Berlin' } }], - stopReason: 'toolUse', - }; - const context = { - messages: [ - { role: 'system', content: '', sections: { preamble: 'You help.' }, toolsAdded: [{ name: 'get_weather' }] }, - { role: 'user', content: 'Weather in Berlin?' }, - ], - }; - it('records nothing when inputs and outputs are off', async () => { const options = { recordInputs: false, recordOutputs: false }; - const instrumented = instrumentPiDurableHarnessOptions( - { models: { completeSimple: async () => message } as PiModels }, - options, - ); - await instrumented.models!.completeSimple!(MODEL, context); await instrumentTool(tool, createRuns(), options).execute({ city: 'Berlin' }, { callId: 'call_1' }, undefined); - const [chat, execute] = endedSpans.map(span => spanToJSON(span).attributes); - expect(Object.keys(chat!)).not.toContain(GEN_AI_INPUT_MESSAGES); - expect(Object.keys(chat!)).not.toContain(GEN_AI_OUTPUT_MESSAGES); - expect(Object.keys(chat!)).not.toContain(GEN_AI_SYSTEM_INSTRUCTIONS); - expect(Object.keys(chat!)).not.toContain(GEN_AI_TOOL_DEFINITIONS); + const [execute] = endedSpans.map(span => spanToJSON(span).attributes); expect(Object.keys(execute!)).not.toContain(GEN_AI_TOOL_CALL_ARGUMENTS); expect(Object.keys(execute!)).not.toContain(GEN_AI_TOOL_CALL_RESULT); expect(execute![GEN_AI_TOOL_DESCRIPTION]).toBe('Get the weather.'); @@ -467,17 +151,10 @@ describe('instrumentPiDurableHarnessOptions', () => { setCurrentClient(strict); strict.init(); strict.on('spanEnd', span => endedSpans.push(span)); - const models: PiModels = { completeSimple: async () => message }; - const instrumented = instrumentPiDurableHarnessOptions({ models }); - await instrumented.models!.completeSimple!(MODEL, context); await instrumentTool(tool, createRuns(), {}).execute({ city: 'Berlin' }, { callId: 'call_1' }, undefined); const recorded = endedSpans.flatMap(span => Object.keys(spanToJSON(span).attributes)); - expect(recorded).not.toContain(GEN_AI_INPUT_MESSAGES); - expect(recorded).not.toContain(GEN_AI_OUTPUT_MESSAGES); - expect(recorded).not.toContain(GEN_AI_SYSTEM_INSTRUCTIONS); - expect(recorded).not.toContain(GEN_AI_TOOL_DEFINITIONS); expect(recorded).not.toContain(GEN_AI_TOOL_CALL_ARGUMENTS); expect(recorded).not.toContain(GEN_AI_TOOL_CALL_RESULT); }); @@ -958,14 +635,13 @@ describe('instrumentPiDurableHarnessOptions', () => { name: 'pi.generation', phases: { request: async (taskRecord, runtime, context) => { - await harness.models!.completeSimple!(MODEL, { messages: [] }); + sendModelRequest(); await settle.definition.phases.request!(taskRecord, runtime, context); }, }, }, }; const harness: PiHarnessOptions = instrumentPiDurableHarnessOptions({ - models: { completeSimple: async () => ANSWER }, registry: { snapshot: () => ({ task: () => task, tasks: () => [task] }), subscribe: () => () => undefined, @@ -1056,13 +732,12 @@ describe('instrumentPiDurableHarnessOptions', () => { name: 'app.title', phases: { request: async () => { - await harness.models!.completeSimple!(MODEL, { messages: [] }); + sendModelRequest(); }, }, }, }; const harness: PiHarnessOptions = instrumentPiDurableHarnessOptions({ - models: { completeSimple: async () => ANSWER }, registry: { snapshot: () => ({ task: () => task, tasks: () => [task] }), subscribe: () => () => undefined }, }); const runtime: PiTaskRuntime = { diff --git a/packages/server-utils/test/integrations/pi-ai.test.ts b/packages/server-utils/test/integrations/pi-ai.test.ts index a062e191a6e7..260ab4423de8 100644 --- a/packages/server-utils/test/integrations/pi-ai.test.ts +++ b/packages/server-utils/test/integrations/pi-ai.test.ts @@ -1,9 +1,6 @@ import { tracingChannel } from 'node:diagnostics_channel'; import type { Span } from '@sentry/core'; import { - _INTERNAL_clearAiProviderSkips, - _INTERNAL_shouldSkipAiProviderWrapping, - _INTERNAL_skipAiProviderWrapping, GLOBAL_OBJ, setAsyncContextStrategy, setCurrentClient, @@ -39,14 +36,15 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT } from '@sentry/conventions/op'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { ANTHROPIC_AI_INTEGRATION_NAME } from '../../src/ai/anthropic-ai/constants'; -import { GOOGLE_GENAI_INTEGRATION_NAME } from '../../src/ai/google-genai/constants'; -import { OPENAI_INTEGRATION_NAME } from '../../src/ai/openai/constants'; import { getPiAiChatSpanOptions, setPiAiResponseAttributes } from '../../src/ai/pi-ai/chat'; -import { PI_AI_ORIGIN } from '../../src/ai/pi-ai/constants'; +import { resolvePiAiRecordingOptions, setPiAiRecordingOptions } from '../../src/ai/pi-ai/recording'; import { setAsyncLocalStorageAsyncContextStrategy } from '../../src/async-context'; import type { PiEventStream } from '../../src/ai/pi-ai/types'; import { instrumentWorkersAiClient } from '../../src/ai/workers-ai'; +import { anthropicAIIntegration } from '../../src/integrations/anthropic'; +import { googleGenAIIntegration } from '../../src/integrations/google-genai'; +import { mistralAIIntegration } from '../../src/integrations/mistral'; +import { openAIIntegration } from '../../src/integrations/openai'; import { piAiIntegration } from '../../src/integrations/pi-ai'; import { CHANNELS } from '../../src/orchestrion/channels'; import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; @@ -85,9 +83,19 @@ describe('piAiIntegration', () => { beforeAll(() => { setAsyncLocalStorageAsyncContextStrategy(); - GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { runtime: ['@earendil-works/pi-ai'] }; + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { + runtime: ['@earendil-works/pi-ai', 'openai', '@anthropic-ai/sdk', '@google/genai', '@mistralai/mistralai'], + }; useClient(); - piAiIntegration().setup!(client); + for (const integration of [ + piAiIntegration(), + openAIIntegration(), + anthropicAIIntegration(), + googleGenAIIntegration(), + mistralAIIntegration(), + ]) { + integration.setup!(client); + } }); afterAll(() => { @@ -96,7 +104,6 @@ describe('piAiIntegration', () => { }); beforeEach(() => { - _INTERNAL_clearAiProviderSkips(); endedSpans = []; useClient(); }); @@ -173,6 +180,19 @@ describe('piAiIntegration', () => { expect(endedSpans.map(span => spanToJSON(span).attributes[GEN_AI_RESPONSE_STREAMING])).toEqual([undefined, true]); }); + it('traces a call that makes another traced call after an await as one request', async () => { + await complete( + async () => { + await Promise.resolve(); + return stream(settlesWith(ANSWER), MODEL, { messages: [] }).result(); + }, + MODEL, + { messages: [] }, + ); + + expect(endedSpans).toHaveLength(1); + }); + it('traces requests after a nested one, and after one that threw', async () => { expect(() => stream(() => { @@ -282,55 +302,95 @@ describe('piAiIntegration', () => { expect(endedSpans.map(span => spanToJSON(span).attributes[SENTRY_OP])).toEqual([GEN_AI_CHAT]); }); - describe('provider skip', () => { - it('skips the provider integrations on the first request, not at setup', async () => { - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); - - await complete(async () => ANSWER, MODEL, { messages: [] }); - - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); - }); + describe('provider SDK integrations', () => { + const spanNames = (): string[] => endedSpans.map(span => spanToJSON(span).name); + + describe.each([ + ['openai', CHANNELS.OPENAI_CHAT], + ['@anthropic-ai/sdk', CHANNELS.ANTHROPIC_CHAT], + ['@google/genai', CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT], + ['@mistralai/mistralai', CHANNELS.MISTRAL_CHAT], + ])('%s', (_module, channel) => { + const callSdk = (): Promise => + tracingChannel(channel).tracePromise(async () => ({}), { + arguments: [{ model: 'sdk-model', messages: [] }], + }); + + it('does not report a request pi-ai sends with `complete`', async () => { + await complete( + async () => { + await callSdk(); + return ANSWER; + }, + MODEL, + { messages: [] }, + ); + + expect(spanNames()).toEqual(['chat faux-model']); + }); - // The registry is reset per client, so a one-shot call would be undone by the next `init()`. - it('applies the skip again after the registry is cleared', async () => { - await complete(async () => ANSWER, MODEL, { messages: [] }); - _INTERNAL_clearAiProviderSkips(); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(false); + it('does not report a request pi-ai sends with `stream`', async () => { + const sent = { result: async () => ANSWER }; + await stream( + () => { + void callSdk(); + return sent as PiEventStream; + }, + MODEL, + { messages: [] }, + ).result(); + + expect(spanNames()).toEqual(['chat faux-model']); + }); - await complete(async () => ANSWER, MODEL, { messages: [] }); + it('reports a direct call made after a pi-ai request', async () => { + await complete(async () => ANSWER, MODEL, { messages: [] }); + await callSdk(); - expect(_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)).toBe(true); - }); + expect(spanNames()).toEqual(['chat faux-model', expect.stringContaining('sdk-model')]); + }); - it('applies the skip to every provider when only some are already registered', async () => { - _INTERNAL_skipAiProviderWrapping([OPENAI_INTEGRATION_NAME]); + it('reports a direct call made while a pi-ai request is in flight', async () => { + let settle!: (message: unknown) => void; + const request = complete(() => new Promise(resolve => (settle = resolve)), MODEL, { messages: [] }); - await complete(async () => ANSWER, MODEL, { messages: [] }); + await callSdk(); + expect(spanNames()).toEqual([expect.stringContaining('sdk-model')]); - expect(_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)).toBe(true); - expect(_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)).toBe(true); + settle(ANSWER); + await request; + }); }); // `createAI()` of `agents/models/pi-ai` sends pi-ai requests through the Workers AI binding. - it('reports a request sent through the Workers AI binding once', async () => { + describe('Workers AI binding', () => { const ai = instrumentWorkersAiClient({ run: async (_model: string, _inputs: unknown, _options: unknown) => new Response('{}'), gateway: () => ({}), toMarkdown: async () => [], }); + const callBinding = (): Promise => + ai.run('@cf/moonshotai/kimi-k2.7-code', { messages: [] }, { returnRawResponse: true }); + + it('does not report a request pi-ai sends', async () => { + await complete( + async () => { + await callBinding(); + return ANSWER; + }, + MODEL, + { messages: [] }, + ); + + expect(spanNames()).toEqual(['chat faux-model']); + }); - await complete( - async () => { - await ai.run('@cf/moonshotai/kimi-k2.7-code', { messages: [] }, { returnRawResponse: true }); - return ANSWER; - }, - MODEL, - { messages: [] }, - ); + it('reports a direct call made after a pi-ai request', async () => { + await complete(async () => ANSWER, MODEL, { messages: [] }); + await callBinding(); - expect(endedSpans.map(span => spanToJSON(span).name)).toEqual(['chat faux-model']); + expect(spanNames()).toEqual(['chat faux-model', expect.stringContaining('kimi-k2.7-code')]); + }); }); }); @@ -355,7 +415,7 @@ describe('piAiIntegration', () => { it('records nothing when inputs and outputs are off', () => { const span = startInactiveSpan( - getPiAiChatSpanOptions({ model: MODEL, context, streaming: false, origin: PI_AI_ORIGIN, recordInputs: false }), + getPiAiChatSpanOptions({ model: MODEL, context, streaming: false, recordInputs: false }), ); setPiAiResponseAttributes(span, message, false); span.end(); @@ -376,5 +436,44 @@ describe('piAiIntegration', () => { expect(recorded).not.toContain(attribute); } }); + + it('follows the options set on the scope, also for a response that settles outside of it', async () => { + let settle!: (answer: unknown) => void; + const result = new Promise(resolve => (settle = resolve)); + + const events = withScope(scope => { + setPiAiRecordingOptions(scope, { recordInputs: false, recordOutputs: false }); + return stream(() => ({ result: () => result }), MODEL, context); + }); + settle(message); + await events.result(); + + expect(endedSpans).toHaveLength(1); + const recorded = endedSpans.flatMap(span => Object.keys(spanToJSON(span).attributes)); + for (const attribute of CONTENT_ATTRIBUTES) { + expect(recorded).not.toContain(attribute); + } + }); + + it.each([ + // driver, piAiIntegration, dataCollection.genAI, expected + [undefined, undefined, undefined, true], + [undefined, undefined, false, false], + [undefined, true, false, true], + [undefined, false, true, false], + [true, undefined, false, true], + [false, undefined, true, false], + [false, true, true, false], + [true, false, true, false], + ])('resolves driver %s, pi-ai %s and client %s to %s', (driver, piAi, genAI, expected) => { + useClient({ dataCollection: { genAI: { inputs: genAI, outputs: genAI } } }); + + const resolved = withScope(scope => { + setPiAiRecordingOptions(scope, { recordInputs: driver, recordOutputs: driver }); + return resolvePiAiRecordingOptions({ recordInputs: piAi, recordOutputs: piAi }); + }); + + expect(resolved).toEqual({ recordInputs: expected, recordOutputs: expected }); + }); }); }); diff --git a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts index 037639bc6b73..2e60db9729c0 100644 --- a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts +++ b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts @@ -44,8 +44,7 @@ describe('channel integration definitions', () => { // `@nestjs/*` and `@remix-run/*` are covered by listeners in their own SDK packages. // Each cron monitor is billed, so bundler-only SDKs must not install crons integrations for every app. - // pi-ai would duplicate Flue's and pi-durable's own chat spans until they rely on it. - const optIn = new Set(['cron', 'node-cron', 'node-schedule', '@earendil-works/pi-ai']); + const optIn = new Set(['cron', 'node-cron', 'node-schedule']); const uncovered = [...configured].filter( name => !defined.has(name) && !optIn.has(name) && !name.startsWith('@nestjs/') && !name.startsWith('@remix-run/'), ); From 0612441a9aced2b7015063aa1df12f8863249387 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:29:38 +0100 Subject: [PATCH 046/136] chore(ci): Assign Junior PRs to their requester and skip them as reviewer (#26304) **Why:** Junior PRs are opened by `sentry-junior[bot]`, so the assign-reviewers workflow can pick the person who actually asked for the PR as a reviewer. These PRs also often end up unassigned. Junior only assigns the requester when they linked their GitHub account in Junior, which makes the attribution block say `via @login`. Most of the team hasn't linked an account, so it says `via **Slack Name**` and nobody gets assigned. There are two separate workflows. Both read the requesters from that attribution block through the shared `scripts/junior-requesters.mjs`: - New `PR: Assign Junior PRs to requester`: when Junior opens a PR, it assigns the requesters if the PR has no assignees yet. It also runs for drafts, since Junior opens its PRs as drafts. - `PR: Assign reviewers`: it treats the requesters like the author and never requests their review. `@login` is used as is. A Slack name is matched against the GitHub profile names of `@getsentry/team-javascript-sdks` members only, ignoring case and accents. A one-word profile name like `Sigrid` or `Andrei` matches on first name when only one member has it. Isaac's profile name is `isaacs`, so that one is a hardcoded mapping. With today's team profiles, every member's Slack name resolves. Requesters outside the team who haven't linked GitHub are logged and skipped. **How to review:** Start with `scripts/junior-requesters.mjs`. The `assign-reviewers` change is only the extra exclusion. **Unsure about:** - Name matching is best effort. If someone changes their GitHub display name, or a new teammate's name doesn't match, they'll need an entry in `JUNIOR_NAME_TO_LOGIN`. Linking GitHub in Junior also fixes it. - The new workflow reuses the `GITFLOW_APP_*` app, which needs to be allowed to add assignees. `pull_requests: write` should be enough for the issues assignees endpoint on PRs. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794409189.119759) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794409189.119759/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .github/workflows/assign-junior-prs.yml | 38 ++++++++ .github/workflows/assign-reviewers.yml | 1 + scripts/assign-reviewers.mjs | 8 +- scripts/assign-reviewers.test.mjs | 13 ++- scripts/github-test-utils.mjs | 45 +++++++++ scripts/junior-requesters.mjs | 123 ++++++++++++++++++++++++ scripts/junior-requesters.test.mjs | 88 +++++++++++++++++ 7 files changed, 313 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/assign-junior-prs.yml create mode 100644 scripts/github-test-utils.mjs create mode 100644 scripts/junior-requesters.mjs create mode 100644 scripts/junior-requesters.test.mjs diff --git a/.github/workflows/assign-junior-prs.yml b/.github/workflows/assign-junior-prs.yml new file mode 100644 index 000000000000..0b86f0577110 --- /dev/null +++ b/.github/workflows/assign-junior-prs.yml @@ -0,0 +1,38 @@ +name: 'PR: Assign Junior PRs to requester' + +on: + pull_request_target: + types: + - opened + +permissions: + contents: read + +jobs: + assign-requester: + name: Assign requester + runs-on: ubuntu-24.04 + if: github.event.pull_request.user.login == 'sentry-junior[bot]' + steps: + # Matching Slack names to GitHub users lists team members, which needs org `members: read`. + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.GITFLOW_APP_ID }} + private-key: ${{ secrets.GITFLOW_APP_PRIVATE_KEY }} + + - name: Checkout base branch + uses: actions/checkout@v7 + with: + sparse-checkout: | + scripts/junior-requesters.mjs + sparse-checkout-cone-mode: false + + - name: Assign requester + uses: actions/github-script@v9 + with: + github-token: ${{ steps.app-token.outputs.token }} + script: | + const { assignJuniorRequesters } = await import('${{ github.workspace }}/scripts/junior-requesters.mjs'); + await assignJuniorRequesters({ github, context, core }); diff --git a/.github/workflows/assign-reviewers.yml b/.github/workflows/assign-reviewers.yml index 27ee5aa7a31f..e8d11ae70c20 100644 --- a/.github/workflows/assign-reviewers.yml +++ b/.github/workflows/assign-reviewers.yml @@ -36,6 +36,7 @@ jobs: sparse-checkout: | .github/CODEOWNERS scripts/assign-reviewers.mjs + scripts/junior-requesters.mjs sparse-checkout-cone-mode: false - name: Assign reviewers diff --git a/scripts/assign-reviewers.mjs b/scripts/assign-reviewers.mjs index 02d934d201b3..ee6122f71d39 100644 --- a/scripts/assign-reviewers.mjs +++ b/scripts/assign-reviewers.mjs @@ -1,7 +1,8 @@ import * as fs from 'fs'; +import { getJuniorRequesters, TEAM_SLUG } from './junior-requesters.mjs'; + const REQUIRED_REVIEWERS = 3; -const TEAM_SLUG = 'team-javascript-sdks'; // Managers who are members (and code owners) of the SDK teams, but should never be auto-requested for review. const NEVER_REQUEST = ['mydea', 'stephanie-anderson']; const CODEOWNERS_PATH = '.github/CODEOWNERS'; @@ -96,6 +97,9 @@ export async function assignReviewers({ github, context, core }) { } const author = currentPr.user.login; + // Whoever asked Junior for the PR is its de facto author. + const requesters = await getJuniorRequesters({ github, core, pr: currentPr }); + const reviews = await github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number }); // Requested reviewers drop off `requested_reviewers` once they submit a review, so count both. // Bots (AI reviewers) don't count towards the required reviewers. @@ -133,7 +137,7 @@ export async function assignReviewers({ github, context, core }) { existing, codeownerPool, teamPool: await listTeamMembers(TEAM_SLUG), - exclude: [author, ...NEVER_REQUEST], + exclude: [author, ...requesters, ...NEVER_REQUEST], }); core.info(`Codeowners: ${codeowners.join(', ') || '(none)'}`); diff --git a/scripts/assign-reviewers.test.mjs b/scripts/assign-reviewers.test.mjs index 7d7e8ad62af0..5ff6877615e6 100644 --- a/scripts/assign-reviewers.test.mjs +++ b/scripts/assign-reviewers.test.mjs @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { getOwnersForFiles, parseCodeowners, pickReviewers } from './assign-reviewers.mjs'; +import { assignReviewers, getOwnersForFiles, parseCodeowners, pickReviewers } from './assign-reviewers.mjs'; +import { attribution, junior, setup } from './github-test-utils.mjs'; const CODEOWNERS = ` # comment @@ -78,3 +79,13 @@ describe('pickReviewers', () => { expect(pickReviewers({ existing: [], codeownerPool: [], teamPool: ['a'], exclude: [] })).toEqual(['a']); }); }); + +describe('assignReviewers', () => { + it('does not request a review from the requester of a Junior PR', async () => { + const { github, run } = setup(assignReviewers, { user: junior, body: attribution('**Alice Example**') }); + await run(); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: expect.arrayContaining(['b', 'c', 'd']) }), + ); + }); +}); diff --git a/scripts/github-test-utils.mjs b/scripts/github-test-utils.mjs new file mode 100644 index 000000000000..37857c50ea65 --- /dev/null +++ b/scripts/github-test-utils.mjs @@ -0,0 +1,45 @@ +import { vi } from 'vitest'; + +const profiles = { + a: { login: 'a', name: 'Alice Example' }, + b: { login: 'b', name: 'Bob Example' }, + c: { login: 'c', name: 'Carol Example' }, + d: { login: 'd', name: 'Dan Example' }, +}; + +export function setup(run, pr) { + const github = { + paginate: vi.fn(async method => (method === github.rest.teams.listMembersInOrg ? Object.values(profiles) : [])), + rest: { + pulls: { + get: vi.fn(async () => ({ + data: { + state: 'open', + draft: false, + assignees: [], + requested_reviewers: [], + base: { repo: { owner: { login: 'getsentry' } } }, + ...pr, + }, + })), + listReviews: vi.fn(), + listFiles: vi.fn(), + requestReviewers: vi.fn(), + }, + teams: { listMembersInOrg: vi.fn() }, + users: { getByUsername: vi.fn(async ({ username }) => ({ data: profiles[username] })) }, + issues: { addAssignees: vi.fn() }, + }, + }; + const context = { + repo: { owner: 'getsentry', repo: 'sentry-javascript' }, + payload: { pull_request: { number: 1 } }, + }; + const core = { info: vi.fn() }; + return { github, run: () => run({ github, context, core }) }; +} + +export const junior = { login: 'sentry-junior[bot]', type: 'Bot' }; + +export const attribution = labels => + `Body\n\n\nvia ${labels}.\n\n`; diff --git a/scripts/junior-requesters.mjs b/scripts/junior-requesters.mjs new file mode 100644 index 000000000000..af70ffbd7979 --- /dev/null +++ b/scripts/junior-requesters.mjs @@ -0,0 +1,123 @@ +export const TEAM_SLUG = 'team-javascript-sdks'; +const JUNIOR_LOGIN = 'sentry-junior[bot]'; +// Junior writes `via **Slack Name**` when the requester has no GitHub account linked in Junior. These people's +// GitHub profile name can't be matched to their Slack name. +const JUNIOR_NAME_TO_LOGIN = { + 'isaac schlueter': 'isaacs', +}; + +function normalizeName(name) { + return name + .normalize('NFKD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * Reads the requesters from the attribution block Junior adds to the bodies of PRs it opens. A requester is + * `@login` when they linked their GitHub account in Junior, otherwise `**Slack Name**`. Automation runs have no + * human requester and are skipped. + */ +export function parseJuniorRequesters(body) { + const block = body?.match( + /([\s\S]*?)/, + ); + if (!block) { + return []; + } + + return block[1] + .trim() + .replace(/\.$/, '') + .replace(/^via\s+/i, '') + .split(/,\s*(?=\*\*|@|\[?automation `|via\s)/i) + .map(label => label.trim().replace(/^via\s+/i, '')) + .map(label => { + const login = label.match(/^@([A-Za-z0-9][A-Za-z0-9_-]*)$/)?.[1]; + if (login) { + return { login }; + } + const name = label.match(/^\*\*(.+)\*\*$/)?.[1]; + return name ? { name: name.replaceAll('\\*', '*') } : undefined; + }) + .filter(Boolean); +} + +/** + * Maps a Slack name to a GitHub login by comparing it with the GitHub profile names of `members`. A single-word + * profile name (e.g. `Sigrid`) matches the first name, as long as only one member has it. + */ +export function resolveLoginByName(name, members) { + const normalized = normalizeName(name); + if (JUNIOR_NAME_TO_LOGIN[normalized]) { + return JUNIOR_NAME_TO_LOGIN[normalized]; + } + + const named = members.filter(m => m.name).map(m => ({ login: m.login, name: normalizeName(m.name) })); + const exact = named.filter(m => m.name === normalized); + if (exact.length === 1) { + return exact[0].login; + } + + const firstName = normalized.split(' ')[0]; + const byFirstName = named.filter(m => !m.name.includes(' ') && m.name === firstName); + return byFirstName.length === 1 ? byFirstName[0].login : undefined; +} + +/** + * Returns the GitHub logins of the people who asked Junior for this PR, or nothing for other PRs. Names are only + * matched against the SDK team, so a Slack name can't resolve to an unrelated GitHub user. + */ +export async function getJuniorRequesters({ github, core, pr }) { + if (pr.user.login !== JUNIOR_LOGIN) { + return []; + } + + let members; + const logins = []; + + for (const requester of parseJuniorRequesters(pr.body)) { + if (requester.login) { + logins.push(requester.login); + continue; + } + members ??= await Promise.all( + ( + await github.paginate(github.rest.teams.listMembersInOrg, { + org: pr.base.repo.owner.login, + team_slug: TEAM_SLUG, + }) + ).map(async ({ login }) => (await github.rest.users.getByUsername({ username: login })).data), + ); + const login = resolveLoginByName(requester.name, members); + if (login) { + logins.push(login); + } else { + core.info(`Could not map Junior requester "${requester.name}" to a GitHub user.`); + } + } + + return [...new Set(logins)]; +} + +export async function assignJuniorRequesters({ github, context, core }) { + const { owner, repo } = context.repo; + const pull_number = context.payload.pull_request.number; + + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }); + if (pr.assignees.length) { + core.info(`PR is already assigned to ${pr.assignees.map(a => a.login).join(', ')}, not changing anything.`); + return; + } + + const requesters = await getJuniorRequesters({ github, core, pr }); + if (!requesters.length) { + core.info('No Junior requesters to assign.'); + return; + } + + core.info(`Assigning PR to: ${requesters.join(', ')}`); + await github.rest.issues.addAssignees({ owner, repo, issue_number: pull_number, assignees: requesters }); +} diff --git a/scripts/junior-requesters.test.mjs b/scripts/junior-requesters.test.mjs new file mode 100644 index 000000000000..b1939151b75f --- /dev/null +++ b/scripts/junior-requesters.test.mjs @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest'; + +import { attribution, junior, setup } from './github-test-utils.mjs'; +import { assignJuniorRequesters, parseJuniorRequesters, resolveLoginByName } from './junior-requesters.mjs'; + +describe('parseJuniorRequesters', () => { + it('reads linked logins and Slack names', () => { + expect(parseJuniorRequesters(attribution('**Jan Peer Stöcklmair**, @BYK'))).toEqual([ + { name: 'Jan Peer Stöcklmair' }, + { login: 'BYK' }, + ]); + }); + + it('skips automation runs', () => { + expect( + parseJuniorRequesters( + attribution('[automation `sched_1`](https://junior-prod.sentry.dev/automations/sched_1) · Run ID `sched_1:1`'), + ), + ).toEqual([]); + }); + + it('returns nothing without an attribution block', () => { + expect(parseJuniorRequesters('Some body')).toEqual([]); + expect(parseJuniorRequesters(null)).toEqual([]); + }); +}); + +describe('resolveLoginByName', () => { + const members = [ + { login: 'mydea', name: 'Francesco Gringl-Novy' }, + { login: 'JPeer264', name: 'Jan Peer Stöcklmair' }, + { login: 's1gr1d', name: 'Sigrid' }, + { login: 'isaacs', name: 'isaacs' }, + { login: 'noname', name: null }, + ]; + + it('matches the full profile name, ignoring case and accents', () => { + expect(resolveLoginByName('francesco gringl-novy', members)).toBe('mydea'); + expect(resolveLoginByName('Jan Peer Stocklmair', members)).toBe('JPeer264'); + }); + + it('matches a single-word profile name to the first name', () => { + expect(resolveLoginByName('Sigrid Someone', members)).toBe('s1gr1d'); + }); + + it('does not match a first name that is ambiguous', () => { + expect(resolveLoginByName('Sigrid Someone', [...members, { login: 'other', name: 'Sigrid' }])).toBeUndefined(); + }); + + it('uses the manual mapping for names that cannot be matched', () => { + expect(resolveLoginByName('Isaac Schlueter', members)).toBe('isaacs'); + }); + + it('does not match unknown people', () => { + expect(resolveLoginByName('Francesco Someone', members)).toBeUndefined(); + }); +}); + +describe('assignJuniorRequesters', () => { + it('assigns a Junior PR to its requester', async () => { + const { github, run } = setup(assignJuniorRequesters, { + user: junior, + draft: true, + body: attribution('**Alice Example**'), + }); + await run(); + expect(github.rest.issues.addAssignees).toHaveBeenCalledWith(expect.objectContaining({ assignees: ['a'] })); + }); + + it('keeps existing assignees', async () => { + const { github, run } = setup(assignJuniorRequesters, { + user: junior, + assignees: [{ login: 'b' }], + body: attribution('@a'), + }); + await run(); + expect(github.rest.issues.addAssignees).not.toHaveBeenCalled(); + }); + + it('does not assign PRs opened by people', async () => { + const { github, run } = setup(assignJuniorRequesters, { + user: { login: 'b', type: 'User' }, + body: attribution('@a'), + }); + await run(); + expect(github.rest.issues.addAssignees).not.toHaveBeenCalled(); + }); +}); From 5e291eac8320d85d8250359ac96958c8e3d8049c Mon Sep 17 00:00:00 2001 From: Abdelrahman Awad Date: Thu, 12 Nov 2026 05:41:46 -0500 Subject: [PATCH 047/136] fix(browser): Accept managed tunnel options in the `BrowserClient` constructor (#26313) Since 11.10 `BrowserOptions` couldn't be passed to `new BrowserClient()` because only `init()` resolved the managed `tunnel`, fixed by accepting and resolving it in the client constructor. Unlike the issue diagnosis, the type should be widened in the spots that I did, otherwise some SDKs extending the type would fail to compile as well. I added type tests for spreading `BrowserOptions` into the constructor, and a unit test that `tunnel: true` resolves to the DSN path. closes #26306 --- packages/browser/src/client.ts | 13 ++++++++--- packages/browser/src/sdk.ts | 4 ++-- packages/browser/src/utils/managedTunnel.ts | 2 +- packages/browser/test/client-types.test-d.ts | 23 ++++++++++++++++++++ packages/browser/test/client.test.ts | 16 +++++++++++++- 5 files changed, 51 insertions(+), 7 deletions(-) create mode 100644 packages/browser/test/client-types.test-d.ts diff --git a/packages/browser/src/client.ts b/packages/browser/src/client.ts index 130187badbb5..5cc048a5bf80 100644 --- a/packages/browser/src/client.ts +++ b/packages/browser/src/client.ts @@ -16,6 +16,7 @@ import { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource, time import { eventFromException, eventFromMessage } from './eventbuilder'; import { WINDOW } from './helpers'; import type { BrowserTransportOptions } from './transports/types'; +import { resolveBrowserTunnelOption } from './utils/managedTunnel'; /** * A magic string that build tooling can leverage in order to inject a release value into the SDK. @@ -107,7 +108,12 @@ export type BrowserOptions = CoreOptions & * Configuration options for the Sentry Browser SDK Client class * @see BrowserClient for more information. */ -export type BrowserClientOptions = ClientOptions & BrowserSpecificOptions; +export type BrowserClientOptions = Omit & Pick; + +/** + * {@link BrowserClientOptions} after the client resolved the tunnel to a URL. + */ +export type ResolvedBrowserClientOptions = ClientOptions & BrowserSpecificOptions; /** * The Sentry Browser SDK Client. @@ -115,14 +121,15 @@ export type BrowserClientOptions = ClientOptions & Brow * @see BrowserOptions for documentation on configuration options. * @see SentryClient for usage documentation. */ -export class BrowserClient extends Client { +export class BrowserClient extends Client { /** * Creates a new Browser SDK instance. * * @param options Configuration options for this SDK. */ public constructor(options: BrowserClientOptions) { - const opts = applyDefaultOptions(options); + // `init()` already resolves the tunnel, but a client constructed by hand doesn't go through it. + const opts = applyDefaultOptions({ ...options, ...resolveBrowserTunnelOption(options) }); const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource(); applySdkMetadata(opts, 'browser', ['browser'], sdkSource); diff --git a/packages/browser/src/sdk.ts b/packages/browser/src/sdk.ts index 1425fe5c6829..770ce984b353 100644 --- a/packages/browser/src/sdk.ts +++ b/packages/browser/src/sdk.ts @@ -10,7 +10,7 @@ import { setNormalizeStringifier, stackParserFromStackParserOptions, } from '@sentry/core'; -import type { BrowserClientOptions, BrowserOptions } from './client'; +import type { BrowserOptions, ResolvedBrowserClientOptions } from './client'; import { BrowserClient } from './client'; import { breadcrumbsIntegration } from './integrations/breadcrumbs'; import { browserApiErrorsIntegration } from './integrations/browserapierrors'; @@ -116,7 +116,7 @@ export function init(options: BrowserOptions = {}): Client | undefined { defaultIntegrations, }); - const clientOptions: BrowserClientOptions = { + const clientOptions: ResolvedBrowserClientOptions = { ...options, ...resolveBrowserTunnelOption(options), enabled: shouldDisableBecauseIsBrowserExtenstion ? false : options.enabled, diff --git a/packages/browser/src/utils/managedTunnel.ts b/packages/browser/src/utils/managedTunnel.ts index 8d2329eeb35a..35b0ef9f959c 100644 --- a/packages/browser/src/utils/managedTunnel.ts +++ b/packages/browser/src/utils/managedTunnel.ts @@ -16,7 +16,7 @@ import { WINDOW } from '../helpers'; * written, so a tunnel the app serves itself keeps its URL. */ export function resolveBrowserTunnelOption( - options: BrowserOptions, + options: Pick, ): Pick & { tunnel: string | undefined } { const { tunnel, dsn, transportOptions } = options; if (!tunnel) { diff --git a/packages/browser/test/client-types.test-d.ts b/packages/browser/test/client-types.test-d.ts new file mode 100644 index 000000000000..7fd61088cadc --- /dev/null +++ b/packages/browser/test/client-types.test-d.ts @@ -0,0 +1,23 @@ +import { describe, expectTypeOf, it } from 'vitest'; +import type { BrowserOptions } from '../src'; +import { BrowserClient, defaultStackParser, makeFetchTransport } from '../src'; + +describe('BrowserClient options', () => { + const clientOnlyOptions = { integrations: [], stackParser: defaultStackParser, transport: makeFetchTransport }; + + it('accepts BrowserOptions spread into the constructor', () => { + const options: BrowserOptions = { dsn: 'https://public@dsn.ingest.sentry.io/1337', tunnel: '/tunnel' }; + + expectTypeOf(BrowserClient).toBeConstructibleWith({ ...options, ...clientOnlyOptions }); + }); + + it('accepts every tunnel form BrowserOptions accepts', () => { + expectTypeOf(BrowserClient).toBeConstructibleWith({ ...clientOnlyOptions, tunnel: '/tunnel' }); + expectTypeOf(BrowserClient).toBeConstructibleWith({ ...clientOnlyOptions, tunnel: true }); + expectTypeOf(BrowserClient).toBeConstructibleWith({ ...clientOnlyOptions, tunnel: { basePath: '/docs' } }); + }); + + it('exposes the resolved tunnel URL', () => { + expectTypeOf['tunnel']>().toEqualTypeOf(); + }); +}); diff --git a/packages/browser/test/client.test.ts b/packages/browser/test/client.test.ts index 7b1ae7d0d8ee..7b06dce86a93 100644 --- a/packages/browser/test/client.test.ts +++ b/packages/browser/test/client.test.ts @@ -4,8 +4,9 @@ import { getRouteProvider, resolveCurrentRoute, setRouteProvider } from '@sentry/browser-utils'; import * as SentryCore from '@sentry/core'; -import { debug, getCurrentScope, makeSession, setCurrentClient } from '@sentry/core'; +import { debug, getCurrentScope, getTunnelPath, makeSession, setCurrentClient } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { BrowserOptions } from '../src/client'; import { applyDefaultOptions, BrowserClient } from '../src/client'; import { WINDOW } from '../src/helpers'; import { getDefaultBrowserClientOptions } from './helper/browser-client-options'; @@ -129,6 +130,19 @@ describe('BrowserClient', () => { }); }); + describe('tunnel option', () => { + it('accepts BrowserOptions and resolves a managed tunnel to its URL', () => { + const options: BrowserOptions = { dsn: 'http://examplePublicKey@localhost/0', tunnel: true }; + const { integrations, stackParser, transport } = getDefaultBrowserClientOptions(); + client = new BrowserClient({ ...options, integrations, stackParser, transport }); + + expect(client.getOptions().tunnel).toBe(getTunnelPath(client.getDsn()!)); + expect(client.getOptions().transportOptions?.headers).toEqual({ + 'Content-Type': 'application/x-sentry-envelope', + }); + }); + }); + describe('session status on unhandled errors', () => { afterEach(() => { getCurrentScope().setSession(undefined); From 6bee2f2ccccdac123199d1b610c70a3bad5c8194 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:43:17 -0500 Subject: [PATCH 048/136] test(cloudflare): Run the SDK on the new module registry (#26212) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Starting November 17, 2026, Workers with a compatibility date of 2026-11-17 or later use the [new module registry](https://developers.cloudflare.com/changelog/post/2026-11-02-module-registry-default/) by default. This suite turns on `new_module_registry` by hand so we can check the SDK before then. It covers errors from the fetch handler, streamed spans, and Durable Object RPC tracing. The worker is built with `@cloudflare/vite-plugin` and `sentryCloudflareVitePlugin()`, so the auto-instrument transform and the Vite bundle run on the new registry too. After the 17th, the flag can be swapped for a `2026-11-17` compatibility date. **How to review:** The `/import-meta-resolve` test is a guard, not an SDK check. `import.meta.resolve` only exists on the new registry, so the suite fails if the flag stops applying and doesn't silently fall back to the legacy registry. I checked that it fails when the flag is removed. **Unsure about:** The Vite plugin bundles the worker, so this doesn't cover unbundled deploys that load `@sentry/cloudflare` as separate modules. via **Jan Peer Stöcklmair**. -- [View Session](https://junior-prod.sentry.dev/conversations/agent-dispatch%3Adispatch_2ca349b1f9c5aec0ff50f19e7a133f1e) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent-dispatch%3Adispatch_2ca349b1f9c5aec0ff50f19e7a133f1e/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Jan Peer Stöcklmair --- .../suites/new-module-registry/index.ts | 36 +++++++++++ .../new-module-registry/instrument.server.ts | 6 ++ .../suites/new-module-registry/test.ts | 60 +++++++++++++++++++ .../new-module-registry/vite.config.mts | 7 +++ .../suites/new-module-registry/wrangler.jsonc | 12 ++++ 5 files changed, 121 insertions(+) create mode 100644 dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts create mode 100644 dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts new file mode 100644 index 000000000000..21cd5c7e529e --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/index.ts @@ -0,0 +1,36 @@ +import * as Sentry from '@sentry/cloudflare'; +import { DurableObject } from 'cloudflare:workers'; + +interface Env { + SENTRY_DSN: string; + TEST_DURABLE_OBJECT: DurableObjectNamespace; +} + +export class TestDurableObject extends DurableObject { + async sayHello(name: string): Promise { + return `Hello, ${name}`; + } +} + +export default { + async fetch(request: Request, env: Env): Promise { + const { pathname } = new URL(request.url); + + // `import.meta.resolve` only exists with the new module registry. + if (pathname === '/import-meta-resolve') { + return new Response(typeof import.meta.resolve); + } + + if (pathname === '/error') { + throw new Error('Error with the new module registry'); + } + + if (pathname === '/durable-object') { + const stub = env.TEST_DURABLE_OBJECT.get(env.TEST_DURABLE_OBJECT.idFromName('test')); + return new Response(await stub.sayHello('world')); + } + + Sentry.startSpan({ name: 'test-span', op: 'test' }, () => {}); + return new Response('OK'); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts new file mode 100644 index 000000000000..e577550ae0b8 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/instrument.server.ts @@ -0,0 +1,6 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({ + dsn: env.SENTRY_DSN, + tracesSampleRate: 1.0, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts new file mode 100644 index 000000000000..295e7d7aac10 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/test.ts @@ -0,0 +1,60 @@ +import type { Event } from '@sentry/core'; +import { HTTP_SERVER, RPC } from '@sentry/conventions/op'; +import { expect, it } from 'vitest'; +import { createRunner } from '../../runner'; +import { getSpanOp, getSpansFromEnvelope } from '../../spanUtils'; + +it('runs the worker with the new module registry', async ({ signal }) => { + const runner = createRunner(__dirname).start(signal); + expect(await runner.makeRequest('get', '/import-meta-resolve')).toBe('function'); +}); + +it('captures errors thrown by the fetch handler', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect(envelope => { + const event = envelope[1]?.[0]?.[1] as Event; + expect(event.exception?.values?.[0]).toEqual({ + type: 'Error', + value: 'Error with the new module registry', + stacktrace: { frames: expect.any(Array) }, + mechanism: { type: 'auto.http.cloudflare', handled: false }, + }); + }) + .unordered() + .start(signal); + + await runner.makeRequest('get', '/error', { expectError: true }); + await runner.completed(); +}); + +it('sends the spans of the fetch handler', async ({ signal }) => { + const runner = createRunner(__dirname).start(signal); + const spansPromise = runner.collectStreamedSpans(spansOfTrace => spansOfTrace.length === 2); + + await runner.makeRequest('get', '/'); + + const spans = await spansPromise; + const segmentSpan = spans.find(span => span.is_segment); + const childSpan = spans.find(span => span.name === 'test-span'); + + expect(segmentSpan?.name).toBe('GET /'); + expect(getSpanOp(segmentSpan!)).toBe(HTTP_SERVER); + expect(childSpan?.parent_span_id).toBe(segmentSpan?.span_id); + expect(getSpanOp(childSpan!)).toBe('test'); +}); + +it('traces Durable Object RPC calls', async ({ signal }) => { + const runner = createRunner(__dirname) + .expect(envelope => { + const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment); + expect(segmentSpan?.name).toBe('sayHello'); + expect(getSpanOp(segmentSpan!)).toBe(RPC); + }) + .unordered() + .start(signal); + + const response = await runner.makeRequest('get', '/durable-object'); + expect(response).toBe('Hello, world'); + + await runner.completed(); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/vite.config.mts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc new file mode 100644 index 000000000000..85ceb154ea5c --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/new-module-registry/wrangler.jsonc @@ -0,0 +1,12 @@ +{ + "$schema": "../../node_modules/wrangler/config-schema.json", + "name": "new-module-registry", + "main": "index.ts", + "compatibility_date": "2025-06-17", + // `new_module_registry` becomes the default for compatibility dates from 2026-11-17 on. + "compatibility_flags": ["nodejs_compat", "new_module_registry"], + "durable_objects": { + "bindings": [{ "name": "TEST_DURABLE_OBJECT", "class_name": "TestDurableObject" }], + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["TestDurableObject"] }], +} From 359fbe4dc4a08b0a5c5a2cf740ee26feb7f9bb8f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:20:49 +0100 Subject: [PATCH 049/136] chore(dev-deps): Replace madge with oxlint import/no-cycle (#26317) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** madge has the biggest dev dependency tree we install (~45 packages drop out of the lockfile), and oxlint already ships `import/no-cycle` with the import plugin we have enabled. The rule now runs for every package's `src/` as part of `pnpm run lint`, with `ignoreTypes: true` to match the old `.madgerc` `skipTypeImports`. Parity check: I seeded each cycle shape in a package `src/` and ran madge and oxlint side by side. Both catch plain 2-cycles, 6-file cycles, `export * / export {} from` re-export cycles, and cycles through an `index.ts` barrel. Both ignore `import type`, inline `import { type X }`, and `export type {} from`. I also seeded a cycle in each of the 51 `src/` dirs (including nextjs/react, which override `plugins`), and every one of them was flagged. Coverage is broader than before: madge only walked from the entrypoints in each package's script, and 14 packages had no check at all. Linting every `src/` file found a real cycle madge never reached: `@sentry/nuxt` `vite/sourceMaps.ts` ↔ `vite/sentryVitePlugin.ts`, which is only reachable from `module.ts`. I fixed it by moving the two shared helpers and the `SourceMapSetting` type into `vite/sourceMapSettings.ts`. Behavior doesn't change. **How to review:** Start with `.oxlintrc.base.json` and the nuxt move. The rest removes madge's scripts, the CI step, `.madgerc`, a madge-specific comment in nextjs, and the lockfile entries. **Unsure about:** Two things madge flagged that oxlint doesn't: - cycles that go through a dynamic `import()`. These can't cause load-order bugs, and `src/` has no relative dynamic imports today. - CommonJS `require()` cycles. The only CJS `src/` is `eslint-plugin-sdk`, where `index.js` requires leaf rule files. I think both are fine to lose. Lint time stays about the same: ~9.3s for the full `pnpm run lint` locally, before and after. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .agents/skills/bump-conventions/SKILL.md | 1 - .agents/skills/upgrade-dep/SKILL.md | 1 - .github/workflows/build.yml | 2 - .madgerc | 7 - .oxlintrc.base.json | 7 + package.json | 2 - packages/angular/package.json | 1 - packages/astro/package.json | 1 - packages/aws-serverless/package.json | 1 - packages/browser/package.json | 1 - packages/bun/package.json | 1 - packages/cloudflare/package.json | 1 - packages/core/package.json | 1 - packages/deno/package.json | 1 - packages/effect/package.json | 1 - packages/elysia/package.json | 1 - packages/ember/package.json | 1 - packages/eslint-config-sdk/package.json | 3 +- packages/eslint-plugin-sdk/package.json | 3 +- packages/feedback/package.json | 1 - packages/gatsby/package.json | 1 - packages/google-cloud-serverless/package.json | 1 - packages/hono/package.json | 1 - packages/nestjs/package.json | 1 - packages/nextjs/package.json | 1 - packages/nextjs/src/config/webpack.ts | 2 - packages/node/package.json | 1 - packages/nuxt/package.json | 1 - packages/nuxt/src/vite/sentryVitePlugin.ts | 2 +- packages/nuxt/src/vite/sourceMapSettings.ts | 39 ++ packages/nuxt/src/vite/sourceMaps.ts | 47 +- .../test/vite/sourceMaps-nuxtHooks.test.ts | 3 +- packages/nuxt/test/vite/sourceMaps.test.ts | 8 +- packages/opentelemetry/package.json | 1 - packages/react-router/package.json | 1 - packages/react/package.json | 1 - packages/remix/package.json | 1 - packages/replay-canvas/package.json | 1 - packages/replay-internal/package.json | 1 - packages/solid/package.json | 1 - packages/solidstart/package.json | 1 - packages/svelte/package.json | 1 - packages/sveltekit/package.json | 1 - packages/tanstackstart-react/package.json | 1 - packages/vercel-edge/package.json | 1 - packages/vue/package.json | 1 - packages/wasm/package.json | 1 - pnpm-lock.yaml | 542 +----------------- 48 files changed, 62 insertions(+), 640 deletions(-) delete mode 100644 .madgerc create mode 100644 packages/nuxt/src/vite/sourceMapSettings.ts diff --git a/.agents/skills/bump-conventions/SKILL.md b/.agents/skills/bump-conventions/SKILL.md index 02a2f8dbe1d6..181859b2ee0a 100644 --- a/.agents/skills/bump-conventions/SKILL.md +++ b/.agents/skills/bump-conventions/SKILL.md @@ -50,7 +50,6 @@ After fixing, re-run `pnpm run build:dev` and confirm it passes before verifying ## 5. Final verification ```bash -pnpm run circularDepCheck pnpm run fix pnpm run test ``` diff --git a/.agents/skills/upgrade-dep/SKILL.md b/.agents/skills/upgrade-dep/SKILL.md index e8c88d65ab86..883ff7d743a7 100644 --- a/.agents/skills/upgrade-dep/SKILL.md +++ b/.agents/skills/upgrade-dep/SKILL.md @@ -44,7 +44,6 @@ pnpm install pnpm run build:dev pnpm run dedupe-deps:fix pnpm run fix -pnpm run circularDepCheck ``` ## Useful commands diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c88f378018a4..66d006e800c7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -338,8 +338,6 @@ jobs: run: pnpm run lint:es-compatibility - name: Lint types run: pnpm run lint:types - - name: Check for circular dependencies - run: pnpm run circularDepCheck - name: Check for dts files that reference stuff in the temporary build folder run: | if grep -r --include "*.d.ts" --exclude-dir ".nx" 'import("@sentry(-internal)?/[^/]*/build' .; then diff --git a/.madgerc b/.madgerc deleted file mode 100644 index b407c6b4b14f..000000000000 --- a/.madgerc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "detectiveOptions": { - "ts": { - "skipTypeImports": true - } - } -} diff --git a/.oxlintrc.base.json b/.oxlintrc.base.json index 3c42d69b4bb4..73a31b05f3b8 100644 --- a/.oxlintrc.base.json +++ b/.oxlintrc.base.json @@ -79,6 +79,13 @@ "sdk/no-unfiltered-url-attributes": "error" } }, + { + // Type-only imports are erased at build time, so they cannot cause load-order bugs. + "files": ["**/src/**"], + "rules": { + "import/no-cycle": ["error", { "ignoreTypes": true }] + } + }, { // The rule itself decides which files are browser-facing (see `no-unguarded-span-apis.js`); // oxlint resolves `files` globs relative to each package's own config, so scoping it to diff --git a/package.json b/package.json index b7dcfa889a95..1213b3037fcb 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,6 @@ "ci:print-build-artifact-paths": "node ./scripts/ci-print-build-artifact-paths.mjs", "changelog": "tsx ./scripts/get-commit-list.ts", "generate-changelog": "tsx ./scripts/generate-changelog.ts", - "circularDepCheck": "nx run-many -t circularDepCheck", "clean": "run-s clean:build clean:caches", "clean:build": "nx run-many -t clean", "clean:caches": "node scripts/rm.mjs eslintcache .nxcache .nx", @@ -148,7 +147,6 @@ "es-check": "^9.8.1", "esbuild": "^0.28.1", "jsdom": "^21.1.2", - "madge": "8.0.0", "nodemon": "^3.1.10", "npm-run-all2": "^6.2.0", "nx": "24.0.3", diff --git a/packages/angular/package.json b/packages/angular/package.json index 7cbba52f86ff..b82cf0a346db 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -50,7 +50,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "ng build --configuration production --watch", "build:tarball": "pnpm --dir build pack --pack-destination ..", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-angular-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/astro/package.json b/packages/astro/package.json index dbb68cdb564f..35edcf707e9a 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -88,7 +88,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-astro-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 08cb65b57c12..234f7fb9671a 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -90,7 +90,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build dist-awslambda-layer coverage sentry-serverless-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/browser/package.json b/packages/browser/package.json index 0147f5b3ef30..12f6ad0178a9 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -61,7 +61,6 @@ "build:bundle:watch": "rolldown -c rollup.bundle.config.mjs --watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage .rpt2_cache sentry-browser-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/bun/package.json b/packages/bun/package.json index 94c5d75ae932..c67587fc5ae6 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -62,7 +62,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-bun-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 6cfe55eabbe4..6e3c9a6f6c17 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -92,7 +92,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-cloudflare-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/core/package.json b/packages/core/package.json index 1090e703e385..b7a04e89fb46 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -76,7 +76,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-core-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/deno/package.json b/packages/deno/package.json index 93c30a70cd1f..d679b603ed89 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -43,7 +43,6 @@ "build:transpile": "pnpm run deno-types && rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build build-types build-test coverage node_modules/.deno sentry-deno-*.tgz", "prefix": "pnpm run deno-types", "prelint": "pnpm run deno-types", diff --git a/packages/effect/package.json b/packages/effect/package.json index 5449957181e4..027f62b528fa 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -71,7 +71,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-effect-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 375ae8b5f19c..b1155faaa1ba 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -58,7 +58,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-elysia-*.tgz", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", diff --git a/packages/ember/package.json b/packages/ember/package.json index 2304733a3e23..72b6c4588e57 100644 --- a/packages/ember/package.json +++ b/packages/ember/package.json @@ -30,7 +30,6 @@ "build:dev": "pnpm run build", "build:tarball": "pnpm pack", "build:watch": "rollup --config --watch", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs dist declarations *.tgz .turbo", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/eslint-config-sdk/package.json b/packages/eslint-config-sdk/package.json index 1291e9889f51..cae67cf6c337 100644 --- a/packages/eslint-config-sdk/package.json +++ b/packages/eslint-config-sdk/package.json @@ -40,7 +40,6 @@ }, "scripts": { "clean": "node ../../scripts/rm.mjs sentry-eslint-config-sdk-*.tgz", - "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.js" + "build:tarball": "pnpm pack" } } diff --git a/packages/eslint-plugin-sdk/package.json b/packages/eslint-plugin-sdk/package.json index 1c03e069239e..f64988146609 100644 --- a/packages/eslint-plugin-sdk/package.json +++ b/packages/eslint-plugin-sdk/package.json @@ -32,7 +32,6 @@ "lint:types": "oxlint src --type-aware --type-check", "test": "vitest run", "test:watch": "vitest --watch", - "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.js" + "build:tarball": "pnpm pack" } } diff --git a/packages/feedback/package.json b/packages/feedback/package.json index 8add18f47a1d..e5371a24a520 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -50,7 +50,6 @@ "build:transpile:watch": "pnpm run build:transpile --watch", "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build sentry-feedback-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index 7d1e21e41377..4688670fc83c 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -63,7 +63,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage *.d.ts sentry-gatsby-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index bedb5fa1ec13..952241680656 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -67,7 +67,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-google-cloud-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/hono/package.json b/packages/hono/package.json index 27c1983ee59d..fa00cbab3b52 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -122,7 +122,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-hono-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index be7431d73cff..3911d46931f6 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -81,7 +81,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts src/setup.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-nestjs-*.tgz ./*.d.ts ./*.d.ts.map", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 18be625fa5cf..79e75e7e5601 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -117,7 +117,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "nodemon --ext ts --watch src scripts/buildRollup.ts", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/edge/index.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-nextjs-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 0b885b50a2a2..8e39ba7e8a29 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -11,8 +11,6 @@ import { getBuildLogger } from './buildLogger'; import { externalizeOrchestrionRuntimePackages } from './diagnosticsChannelInjection'; import { getBuildPluginOptions, normalizePathForGlob } from './getBuildPluginOptions'; import type { RouteManifest } from './manifest/types'; -// Note: If you need to import a type from Webpack, do it in `types.ts` and export it from there. Otherwise, our -// circular dependency check thinks this file is importing from itself. See https://github.com/pahen/madge/issues/306. import type { BuildContext, EntryPropertyObject, diff --git a/packages/node/package.json b/packages/node/package.json index 927ff23eb293..b50fb2612159 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -98,7 +98,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-node-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 66f481d1337d..aabf71a69814 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -89,7 +89,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-nuxt-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nuxt/src/vite/sentryVitePlugin.ts b/packages/nuxt/src/vite/sentryVitePlugin.ts index 31ef7c97465d..3bea84089eb1 100644 --- a/packages/nuxt/src/vite/sentryVitePlugin.ts +++ b/packages/nuxt/src/vite/sentryVitePlugin.ts @@ -1,7 +1,7 @@ import type { Nuxt } from '@nuxt/schema'; import type { ConfigEnv, Plugin, UserConfig } from 'vite'; import type { SentryNuxtModuleOptions } from '../common/types'; -import { extractNuxtSourceMapSetting, validateDifferentSourceMapSettings } from './sourceMaps'; +import { extractNuxtSourceMapSetting, validateDifferentSourceMapSettings } from './sourceMapSettings'; /** * Creates a Vite plugin that adds the Sentry Vite plugin and validates source map settings. diff --git a/packages/nuxt/src/vite/sourceMapSettings.ts b/packages/nuxt/src/vite/sourceMapSettings.ts new file mode 100644 index 000000000000..a03899e4ce73 --- /dev/null +++ b/packages/nuxt/src/vite/sourceMapSettings.ts @@ -0,0 +1,39 @@ +/** A valid source map setting */ +export type SourceMapSetting = boolean | 'hidden' | 'inline'; + +/** Returns the Nuxt source map setting that applies to the given runtime. */ +export function extractNuxtSourceMapSetting( + nuxt: { options: { sourcemap?: SourceMapSetting | { server?: SourceMapSetting; client?: SourceMapSetting } } }, + runtime: 'client' | 'server' | undefined, +): SourceMapSetting | undefined { + if (!runtime) { + return undefined; + } else { + return typeof nuxt.options?.sourcemap === 'boolean' || typeof nuxt.options?.sourcemap === 'string' + ? nuxt.options.sourcemap + : nuxt.options?.sourcemap?.[runtime]; + } +} + +/** + * Validates that source map settings are consistent between Nuxt and Vite/Nitro configurations. + * Logs a warning if conflicting settings are detected. + */ +export function validateDifferentSourceMapSettings({ + nuxtSettingKey, + nuxtSettingValue, + otherSettingKey, + otherSettingValue, +}: { + nuxtSettingKey: string; + nuxtSettingValue?: SourceMapSetting; + otherSettingKey: string; + otherSettingValue?: SourceMapSetting; +}): void { + if (nuxtSettingValue !== otherSettingValue) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] Source map generation settings are conflicting. Sentry uses \`${nuxtSettingKey}: ${nuxtSettingValue}\`. However, a conflicting setting was discovered (\`${otherSettingKey}: ${otherSettingValue}\`). This setting was probably explicitly set in your configuration. Sentry won't override this setting but it may affect source maps generation and upload. Without source maps, code snippets on the Sentry Issues page will remain minified.`, + ); + } +} diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index 891a81602aac..7d1f11401eb9 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -13,15 +13,17 @@ import { withoutSourceMapDeletion, } from './sourceMapDeletion'; import { validateSourceMapsOptionsPlugin } from './sentryVitePlugin'; +import { + extractNuxtSourceMapSetting, + type SourceMapSetting, + validateDifferentSourceMapSettings, +} from './sourceMapSettings'; /** * Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps */ export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined; -/** A valid source map setting */ -export type SourceMapSetting = boolean | 'hidden' | 'inline'; - /** * Setup source maps for Sentry inside the Nuxt module during build time (in Vite for Nuxt and Rollup for Nitro). */ @@ -252,20 +254,6 @@ function resolveFilesToDeleteAfterUpload( Users only have to explicitly enable client source maps. Sentry only overwrites the base Nuxt source map settings as they propagate. */ -/** only exported for tests */ -export function extractNuxtSourceMapSetting( - nuxt: { options: { sourcemap?: SourceMapSetting | { server?: SourceMapSetting; client?: SourceMapSetting } } }, - runtime: 'client' | 'server' | undefined, -): SourceMapSetting | undefined { - if (!runtime) { - return undefined; - } else { - return typeof nuxt.options?.sourcemap === 'boolean' || typeof nuxt.options?.sourcemap === 'string' - ? nuxt.options.sourcemap - : nuxt.options?.sourcemap?.[runtime]; - } -} - /** only exported for testing */ export function changeNuxtSourceMapSettings( nuxt: Nuxt, @@ -381,31 +369,6 @@ export function validateNitroSourceMapSettings( } } -/** - * Validates that source map settings are consistent between Nuxt and Vite/Nitro configurations. - * Logs a warning if conflicting settings are detected. - * - * @internal Only exported for testing. - */ -export function validateDifferentSourceMapSettings({ - nuxtSettingKey, - nuxtSettingValue, - otherSettingKey, - otherSettingValue, -}: { - nuxtSettingKey: string; - nuxtSettingValue?: SourceMapSetting; - otherSettingKey: string; - otherSettingValue?: SourceMapSetting; -}): void { - if (nuxtSettingValue !== otherSettingValue) { - // eslint-disable-next-line no-console - console.warn( - `[Sentry] Source map generation settings are conflicting. Sentry uses \`${nuxtSettingKey}: ${nuxtSettingValue}\`. However, a conflicting setting was discovered (\`${otherSettingKey}: ${otherSettingValue}\`). This setting was probably explicitly set in your configuration. Sentry won't override this setting but it may affect source maps generation and upload. Without source maps, code snippets on the Sentry Issues page will remain minified.`, - ); - } -} - function logKeepEnabledSourceMapSetting( sentryNuxtModuleOptions: SentryNuxtModuleOptions, settingKey: string, diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index ac10b8a871df..682cb2cb43b0 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -5,7 +5,8 @@ import * as os from 'os'; import * as path from 'path'; import type { ConfigEnv, Plugin, UserConfig } from 'vite'; import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest'; -import { setupSourceMaps, type SourceMapSetting } from '../../src/vite/sourceMaps'; +import { setupSourceMaps } from '../../src/vite/sourceMaps'; +import type { SourceMapSetting } from '../../src/vite/sourceMapSettings'; const { mockSentryVitePlugin, mockSentryRollupPlugin, mockDeleteArtifacts, mockCreateSentryBuildPluginManager } = vi.hoisted(() => { diff --git a/packages/nuxt/test/vite/sourceMaps.test.ts b/packages/nuxt/test/vite/sourceMaps.test.ts index b767aa19d458..89b1c44acd10 100644 --- a/packages/nuxt/test/vite/sourceMaps.test.ts +++ b/packages/nuxt/test/vite/sourceMaps.test.ts @@ -2,14 +2,16 @@ import type { Nuxt } from '@nuxt/schema'; import * as path from 'path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SentryNuxtModuleOptions } from '../../src/common/types'; -import type { SourceMapSetting } from '../../src/vite/sourceMaps'; import { changeNuxtSourceMapSettings, - extractNuxtSourceMapSetting, getPluginOptions, - validateDifferentSourceMapSettings, validateNitroSourceMapSettings, } from '../../src/vite/sourceMaps'; +import { + extractNuxtSourceMapSetting, + type SourceMapSetting, + validateDifferentSourceMapSettings, +} from '../../src/vite/sourceMapSettings'; vi.mock('@sentry/core', async importOriginal => { const actual = await importOriginal(); diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index ade84ba7af2d..eccd9ad480ab 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -46,7 +46,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-opentelemetry-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 3c2290ca697e..28a24409af05 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -92,7 +92,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-router-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/react/package.json b/packages/react/package.json index 42b6b8073a7c..ef2fed1e5c57 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -97,7 +97,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts src/react-router.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/remix/package.json b/packages/remix/package.json index a95d66868c16..0414783c9d71 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -116,7 +116,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.server.ts src/index.client.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-remix-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index 52849b98859e..e707c2faa794 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -34,7 +34,6 @@ "build:transpile:watch": "pnpm run build:transpile --watch", "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 7ee227f62708..6aa218c5bc17 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -48,7 +48,6 @@ "build:transpile:watch": "pnpm run build:transpile --watch", "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", "format": "oxfmt \"src/**/*.ts\" \"test/**/*.ts\" --write", "format:check": "oxfmt \"src/**/*.ts\" \"test/**/*.ts\" --check", diff --git a/packages/solid/package.json b/packages/solid/package.json index feba8ad958da..beffefcbe1fa 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -94,7 +94,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts src/solidrouter.ts src/tanstackrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-solid-*.tgz ./*.d.ts ./*.d.ts.map", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index f6a5a45db176..2a3c3a23fc78 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -120,7 +120,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts src/solidrouter.client.ts src/solidrouter.server.ts src/solidrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-solidstart-*.tgz ./*.d.ts ./*.d.ts.map ./client ./server", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 92bc2f35b584..6ab1859aef63 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -56,7 +56,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-svelte-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 7e7b9b592573..55eb2ebf5a1d 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -102,7 +102,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-sveltekit-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 72be6bceca15..24051e4f3a3d 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -75,7 +75,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "nodemon --ext ts --watch src scripts/buildRollup.ts", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.client.ts src/index.server.ts src/index.types.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-tanstackstart-react-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index d6e3e219e5cc..ae8ec12e0f75 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -50,7 +50,6 @@ "build:dev:watch": "pnpm run build:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-vercel-edge-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/vue/package.json b/packages/vue/package.json index a56781b71fe1..240764978ed5 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -77,7 +77,6 @@ "build:dev:watch": "run-p build:transpile:watch", "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", - "circularDepCheck": "madge --circular src/index.ts src/tanstackrouter.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-vue-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 425d0597a608..2d6060a44850 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -51,7 +51,6 @@ "build:tarball": "pnpm pack", "test": "vitest run", "test:watch": "vitest --watch", - "circularDepCheck": "madge --circular src/index.ts", "clean": "node ../../scripts/rm.mjs build coverage sentry-wasm-*.tgz", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cf346db61233..8899373abc39 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -213,9 +213,6 @@ importers: jsdom: specifier: ^21.1.2 version: 21.1.2(supports-color@10.0.0) - madge: - specifier: 8.0.0 - version: 8.0.0(supports-color@10.0.0)(typescript@7.0.2) nodemon: specifier: ^3.1.10 version: 3.1.10 @@ -4361,10 +4358,6 @@ packages: '@deno/shim-deno@0.19.2': resolution: {integrity: sha512-q3VTHl44ad8T2Tw2SpeAvghdGOjlnLPDNO2cpOxwMrBE/PVas6geWpbpIgrM+czOCH0yejp0yi8OaTuB+NU40Q==} - '@dependents/detective-less@5.0.1': - resolution: {integrity: sha512-Y6+WUMsTFWE5jb20IFP4YGa5IrGY/+a/FbOSjDF/wz9gepU2hwCYSXRHP/vPwBvwcY3SVMASt4yXxbXNXigmZQ==} - engines: {node: '>=18'} - '@discoveryjs/json-ext@0.5.7': resolution: {integrity: sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==} engines: {node: '>=10.0.0'} @@ -8711,22 +8704,6 @@ packages: resolution: {integrity: sha512-HqmEUIGRJ5fSXchkVgR5F7qn48bDBzv0kWj/Kfu5e6uci4UlEeng4331LnBkWffb++Ei3FOVLxo8JJWMFBDMeQ==} engines: {node: '>= 10'} - '@ts-graphviz/adapter@2.0.6': - resolution: {integrity: sha512-kJ10lIMSWMJkLkkCG5gt927SnGZcBuG0s0HHswGzcHTgvtUe7yk5/3zTEr0bafzsodsOq5Gi6FhQeV775nC35Q==} - engines: {node: '>=18'} - - '@ts-graphviz/ast@2.0.7': - resolution: {integrity: sha512-e6+2qtNV99UT6DJSoLbHfkzfyqY84aIuoV8Xlb9+hZAjgpum8iVHprGeAMQ4rF6sKUAxrmY8rfF/vgAwoPc3gw==} - engines: {node: '>=18'} - - '@ts-graphviz/common@2.1.5': - resolution: {integrity: sha512-S6/9+T6x8j6cr/gNhp+U2olwo1n0jKj/682QVqsh7yXWV6ednHYqxFw0ZsY3LyzT0N8jaZ6jQY9YD99le3cmvg==} - engines: {node: '>=18'} - - '@ts-graphviz/core@2.0.7': - resolution: {integrity: sha512-w071DSzP94YfN6XiWhOxnLpYT3uqtxJBDYdh6Jdjzt+Ce6DNspJsPQgpC7rbts/B8tEkq0LHoYuIF/O5Jh5rPg==} - engines: {node: '>=18'} - '@tybys/wasm-util@0.10.4': resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} @@ -9027,12 +9004,6 @@ packages: typescript: optional: true - '@typescript-eslint/project-service@8.35.0': - resolution: {integrity: sha512-41xatqRwWZuhUMF/aZm2fcUsOFKNcG28xqRSS6ZVr9BVJtGExosLAm5A1OxTjRMagx8nJqva+P5zNIGt8RIgbQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/scope-manager@5.62.0': resolution: {integrity: sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -9041,12 +9012,6 @@ packages: resolution: {integrity: sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==} engines: {node: ^18.18.0 || >=20.0.0} - '@typescript-eslint/tsconfig-utils@8.35.0': - resolution: {integrity: sha512-04k/7247kZzFraweuEirmvUj+W3bJLI9fX6fbo1Qm2YykuBvEhRTPl8tcxlYO8kZZW+HIXfkZNoasVb8EV4jpA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/type-utils@5.62.0': resolution: {integrity: sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -9065,10 +9030,6 @@ packages: resolution: {integrity: sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==} engines: {node: ^18.18.0 || >=20.0.0} - '@typescript-eslint/types@8.35.0': - resolution: {integrity: sha512-0mYH3emanku0vHw2aRLNGqe7EXh9WHEhi7kZzscrMDf6IIRUQ5Jk4wp1QrledE/36KtdZrVfKnE32eZCf/vaVQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript-eslint/types@8.47.0': resolution: {integrity: sha512-nHAE6bMKsizhA2uuYZbEbmp5z2UpffNrPEqiKIeN7VsV6UY/roxanWfoRrf6x/k9+Obf+GQdkm0nPU+vnMXo9A==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -9091,12 +9052,6 @@ packages: typescript: optional: true - '@typescript-eslint/typescript-estree@8.35.0': - resolution: {integrity: sha512-F+BhnaBemgu1Qf8oHrxyw14wq6vbL8xwWKKMwTMwYIRmFFY/1n/9T/jpbobZL8vp7QyEUcC6xGrnAO4ua8Kp7w==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <5.9.0' - '@typescript-eslint/utils@5.62.0': resolution: {integrity: sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -9117,10 +9072,6 @@ packages: resolution: {integrity: sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==} engines: {node: ^18.18.0 || >=20.0.0} - '@typescript-eslint/visitor-keys@8.35.0': - resolution: {integrity: sha512-zTh2+1Y8ZpmeQaQVIc/ZZxsx8UzgKJyNg1PTvjzC7WMhPSVS8bfDX34k1SrwOf016qd5RU3az2UxUNue3IfQ5g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@typescript/typescript-aix-ppc64@7.0.2': resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} engines: {node: '>=16.20.0'} @@ -9756,16 +9707,10 @@ packages: resolution: {integrity: sha512-BJ8/l4R5LRE7hW9WdSuGYrLSHi2ynxeFpDFbH0K/CgNeY/tyhk+vO6TYxXC5r5CpUhNVX310xzPsN/H9lCdfOA==} engines: {node: '>=14'} - any-promise@1.3.0: - resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} - app-module-path@2.2.0: - resolution: {integrity: sha512-gkco+qxENJV+8vFcDiiFhuoSvRXb2a/QPqpSoWhVz829VNJfOTnELbBmPmNKFxf3xdNnw4DWCkzkDaavcX/1YQ==} - aproba@2.0.0: resolution: {integrity: sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==} @@ -9874,10 +9819,6 @@ packages: resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==} engines: {node: '>=20.19.0'} - ast-module-types@6.0.1: - resolution: {integrity: sha512-WHw67kLXYbZuHTmcdbIrVArCq5wxo6NEuj3hiYAWr8mwJeC+C2mMCIBIWCiDoCye/OF/xelc+teJ1ERoWmnEIA==} - engines: {node: '>=18'} - ast-types@0.13.3: resolution: {integrity: sha512-XTZ7xGML849LkQP86sWdQzfhwbt3YwIO6MqbX9mUNYY98VKaaVZP7YNNm70IpwecbkkxmfC5IYAzOQ/2p29zRA==} engines: {node: '>=4'} @@ -10642,10 +10583,6 @@ packages: resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} engines: {node: '>=16'} - commander@12.1.0: - resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} - engines: {node: '>=18'} - commander@14.0.3: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} @@ -10653,10 +10590,6 @@ packages: commander@2.20.3: resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} - commander@7.2.0: - resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} - engines: {node: '>= 10'} - commander@8.3.0: resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} engines: {node: '>= 12'} @@ -11085,10 +11018,6 @@ packages: resolution: {integrity: sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==} engines: {node: '>= 0.4'} - deep-extend@0.6.0: - resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} - engines: {node: '>=4.0.0'} - deep-is@0.1.3: resolution: {integrity: sha512-GtxAN4HvBachZzm4OnWqc45ESpUCMwkYcsjnsPs23FwJbsO+k4t0k9bQCgOmzIlpHO28+WPK/KRbRk0DDHuuDw==} @@ -11161,11 +11090,6 @@ packages: resolution: {integrity: sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==} engines: {node: '>= 0.6.0'} - dependency-tree@11.2.0: - resolution: {integrity: sha512-+C1H3mXhcvMCeu5i2Jpg9dc0N29TWTuT6vJD7mHLAfVmAbo9zW8NlkvQ1tYd3PDMab0IRQM0ccoyX68EZtx9xw==} - engines: {node: '>=18'} - hasBin: true - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -11188,49 +11112,6 @@ packages: detect-node@2.1.0: resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} - detective-amd@6.0.1: - resolution: {integrity: sha512-TtyZ3OhwUoEEIhTFoc1C9IyJIud3y+xYkSRjmvCt65+ycQuc3VcBrPRTMWoO/AnuCyOB8T5gky+xf7Igxtjd3g==} - engines: {node: '>=18'} - hasBin: true - - detective-cjs@6.0.1: - resolution: {integrity: sha512-tLTQsWvd2WMcmn/60T2inEJNhJoi7a//PQ7DwRKEj1yEeiQs4mrONgsUtEJKnZmrGWBBmE0kJ1vqOG/NAxwaJw==} - engines: {node: '>=18'} - - detective-es6@5.0.1: - resolution: {integrity: sha512-XusTPuewnSUdoxRSx8OOI6xIA/uld/wMQwYsouvFN2LAg7HgP06NF1lHRV3x6BZxyL2Kkoih4ewcq8hcbGtwew==} - engines: {node: '>=18'} - - detective-postcss@7.0.1: - resolution: {integrity: sha512-bEOVpHU9picRZux5XnwGsmCN4+8oZo7vSW0O0/Enq/TO5R2pIAP2279NsszpJR7ocnQt4WXU0+nnh/0JuK4KHQ==} - engines: {node: ^14.0.0 || >=16.0.0} - peerDependencies: - postcss: ^8.4.47 - - detective-sass@6.0.1: - resolution: {integrity: sha512-jSGPO8QDy7K7pztUmGC6aiHkexBQT4GIH+mBAL9ZyBmnUIOFbkfZnO8wPRRJFP/QP83irObgsZHCoDHZ173tRw==} - engines: {node: '>=18'} - - detective-scss@5.0.1: - resolution: {integrity: sha512-MAyPYRgS6DCiS6n6AoSBJXLGVOydsr9huwXORUlJ37K3YLyiN0vYHpzs3AdJOgHobBfispokoqrEon9rbmKacg==} - engines: {node: '>=18'} - - detective-stylus@5.0.1: - resolution: {integrity: sha512-Dgn0bUqdGbE3oZJ+WCKf8Dmu7VWLcmRJGc6RCzBgG31DLIyai9WAoEhYRgIHpt/BCRMrnXLbGWGPQuBUrnF0TA==} - engines: {node: '>=18'} - - detective-typescript@14.0.0: - resolution: {integrity: sha512-pgN43/80MmWVSEi5LUuiVvO/0a9ss5V7fwVfrJ4QzAQRd3cwqU1SfWGXJFcNKUqoD5cS+uIovhw5t/0rSeC5Mw==} - engines: {node: '>=18'} - peerDependencies: - typescript: ^5.4.4 - - detective-vue2@2.2.0: - resolution: {integrity: sha512-sVg/t6O2z1zna8a/UIV6xL5KUa2cMTQbdTIIvqNM0NIPswp52fe43Nwmbahzj3ww4D844u/vC2PYfiGLvD3zFA==} - engines: {node: '>=18'} - peerDependencies: - typescript: ^5.4.4 - deterministic-object-hash@2.0.2: resolution: {integrity: sha512-KxektNH63SrbfUyDiwXqRb1rLwKt33AmMv+5Nhsw1kqZ13SJBRTgZHtGbE+hH3a1mVW1cz+4pqSWVPAtLVXTzQ==} engines: {node: '>=18'} @@ -12251,11 +12132,6 @@ packages: file-uri-to-path@1.0.0: resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} - filing-cabinet@5.0.3: - resolution: {integrity: sha512-PlPcMwVWg60NQkhvfoxZs4wEHjhlOO/y7OAm4sKM60o1Z9nttRY4mcdQxp/iZ+kg/Vv6Hw1OAaTbYVM9DA9pYg==} - engines: {node: '>=18'} - hasBin: true - fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} @@ -12463,10 +12339,6 @@ packages: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} - get-amd-module-type@6.0.1: - resolution: {integrity: sha512-MtjsmYiCXcYDDrGqtNbeIYdAl85n+5mSv2r3FbzER/YV3ZILw4HNNIw34HuV5pyl0jzs6GFYU1VHVEefhgcNHQ==} - engines: {node: '>=18'} - get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} @@ -12479,9 +12351,6 @@ packages: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} - get-own-enumerable-property-symbols@3.0.2: - resolution: {integrity: sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==} - get-package-type@0.1.0: resolution: {integrity: sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==} engines: {node: '>=8.0.0'} @@ -12596,11 +12465,6 @@ packages: globrex@0.1.2: resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==} - gonzales-pe@4.3.0: - resolution: {integrity: sha512-otgSPpUmdWJ43VXyiNgEYE4luzHCL2pz4wQ0OnDluC6Eg4Ko3Vexy/SrSynglw/eR+OhkzmqFCZa/OFa/RgAOQ==} - engines: {node: '>=0.6.0'} - hasBin: true - google-auth-library@10.9.1: resolution: {integrity: sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==} engines: {node: '>=18'} @@ -13021,9 +12885,6 @@ packages: inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - ini@1.3.8: - resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} - ini@2.0.0: resolution: {integrity: sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==} engines: {node: '>=10'} @@ -13215,10 +13076,6 @@ packages: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} - is-obj@1.0.1: - resolution: {integrity: sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==} - engines: {node: '>=0.10.0'} - is-path-inside@3.0.3: resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} engines: {node: '>=8'} @@ -13258,10 +13115,6 @@ packages: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} - is-regexp@1.0.0: - resolution: {integrity: sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==} - engines: {node: '>=0.10.0'} - is-set@2.0.3: resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} engines: {node: '>= 0.4'} @@ -13306,13 +13159,6 @@ packages: resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} engines: {node: '>=18'} - is-url-superb@4.0.0: - resolution: {integrity: sha512-GI+WjezhPPcbM+tqE9LnmsY5qqjwHzTvjJ36wxYX5ujNXefSUJ/T17r5bqDV8yLhcgB59KTPNOc9O9cmHTPWsA==} - engines: {node: '>=10'} - - is-url@1.2.4: - resolution: {integrity: sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==} - is-weakmap@2.0.2: resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} engines: {node: '>= 0.4'} @@ -13998,16 +13844,6 @@ packages: resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} hasBin: true - madge@8.0.0: - resolution: {integrity: sha512-9sSsi3TBPhmkTCIpVQF0SPiChj1L7Rq9kU2KDG1o6v2XH9cCw086MopjVCD+vuoL5v8S77DTbVopTO8OUiQpIw==} - engines: {node: '>=18'} - hasBin: true - peerDependencies: - typescript: ^5.4.4 - peerDependenciesMeta: - typescript: - optional: true - magic-string-ast@1.0.3: resolution: {integrity: sha512-CvkkH1i81zl7mmb94DsRiFeG9V2fR2JeuK8yDgS8oiZSFa++wWLEgZ5ufEOyLHbvSbD1gTRKv9NdX69Rnvr9JA==} engines: {node: '>=20.19.0'} @@ -14498,19 +14334,9 @@ packages: mocked-exports@0.1.1: resolution: {integrity: sha512-aF7yRQr/Q0O2/4pIXm6PZ5G+jAd7QS4Yu8m+WEeEHGnbo+7mE36CbLSDQiXYV8bVL3NfmdeqPJct0tUlnjVSnA==} - module-definition@6.0.1: - resolution: {integrity: sha512-FeVc50FTfVVQnolk/WQT8MX+2WVcDnTGiq6Wo+/+lJ2ET1bRVi3HG3YlJUfqagNMc/kUlFSoR96AJkxGpKz13g==} - engines: {node: '>=18'} - hasBin: true - module-details-from-path@1.0.4: resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==} - module-lookup-amd@9.0.5: - resolution: {integrity: sha512-Rs5FVpVcBYRHPLuhHOjgbRhosaQYLtEo3JIeDIbmNo7mSssi1CTzwMh8v36gAzpbzLGXI9wB/yHh+5+3fY1QVw==} - engines: {node: '>=18'} - hasBin: true - moment@2.31.0: resolution: {integrity: sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==} @@ -14890,10 +14716,6 @@ packages: resolution: {integrity: sha512-JuKopr93W+WP+TaK5yoHJGpzPF9fpkH8Vcc9CXGE993BNeRKsb3L4Wy6FzL0VxkEa6U+8M4Ni0HEm9rMMnwurg==} engines: {node: '>=6'} - node-source-walk@7.0.1: - resolution: {integrity: sha512-3VW/8JpPqPvnJvseXowjZcirPisssnBuDikk6JIZ8jQzF7KJQX52iPFX4RYYxLycYH7IbMRSPUOga/esVjy5Yg==} - engines: {node: '>=18'} - nodemon@3.1.10: resolution: {integrity: sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw==} engines: {node: '>=10'} @@ -15414,10 +15236,6 @@ packages: parse-latin@7.0.0: resolution: {integrity: sha512-mhHgobPPua5kZ98EF4HWiH167JWBfl4pvAIXXdbaVohtK7a6YBOy56kvhCqduqyo/f3yrHFWmqmiMg/BkBkYYQ==} - parse-ms@2.1.0: - resolution: {integrity: sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA==} - engines: {node: '>=6'} - parse-node-version@1.0.1: resolution: {integrity: sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==} engines: {node: '>= 0.10'} @@ -16067,12 +15885,6 @@ packages: postcss-value-parser@4.2.0: resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} - postcss-values-parser@6.0.2: - resolution: {integrity: sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw==} - engines: {node: '>=10'} - peerDependencies: - postcss: ^8.2.9 - postcss@8.4.31: resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==} engines: {node: ^10 || ^12 || >=14} @@ -16117,11 +15929,6 @@ packages: preact-render-to-string: optional: true - precinct@12.2.0: - resolution: {integrity: sha512-NFBMuwIfaJ4SocE9YXPU/n4AcNSoFMVFjP72nvl3cx69j/ke61/hPOWFREVxLkFhhEGnA8ZuVfTqJBa+PK3b5w==} - engines: {node: '>=18'} - hasBin: true - preferred-pm@4.1.1: resolution: {integrity: sha512-rU+ZAv1Ur9jAUZtGPebQVQPzdGhNzaEiQ7VL9+cjsAWPHFYOccNXPNiev1CCDSOg/2j7UujM7ojNhpkuILEVNQ==} engines: {node: '>=18.12'} @@ -16159,10 +15966,6 @@ packages: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} - pretty-ms@7.0.1: - resolution: {integrity: sha512-973driJZvxiGOQ5ONsFhOF/DtzPMOMtgC11kCpUrPGMTgqp2q/1gwzCquocrN33is0VZ5GFHXZYMM9l6h67v2Q==} - engines: {node: '>=10'} - prisma@6.15.0: resolution: {integrity: sha512-E6RCgOt+kUVtjtZgLQDBJ6md2tDItLJNExwI0XJeBc1FKL+Vwb+ovxXxuok9r8oBgsOXBA33fGDuE/0qDdCWqQ==} engines: {node: '>=18.18'} @@ -16306,9 +16109,6 @@ packages: quickjs-wasi@3.6.2: resolution: {integrity: sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==} - quote-unquote@1.0.0: - resolution: {integrity: sha512-twwRO/ilhlG/FIgYeKGFqyHhoEhqgnKVkcmqMKi2r524gz3ZbDTcyFt38E9xjJI2vT+KbRNHVbnJ/e0I25Azwg==} - radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} @@ -16333,10 +16133,6 @@ packages: rc9@3.1.0: resolution: {integrity: sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==} - rc@1.2.8: - resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} - hasBin: true - react-dom@18.3.1: resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==} peerDependencies: @@ -16593,25 +16389,12 @@ packages: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} - requirejs-config-file@4.0.0: - resolution: {integrity: sha512-jnIre8cbWOyvr8a5F2KuqBnY+SDA4NXr/hzEZJG79Mxm2WiFQz2dzhC8ibtPJS7zkmBEl1mxSwp5HhC1W4qpxw==} - engines: {node: '>=10.13.0'} - - requirejs@2.3.7: - resolution: {integrity: sha512-DouTG8T1WanGok6Qjg2SXuCMzszOo0eHeH9hDZ5Y4x8Je+9JB38HdTLT4/VA8OaUhBa0JPVHJ0pyBkM1z+pDsw==} - engines: {node: '>=0.4.0'} - hasBin: true - requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} reselect@4.1.8: resolution: {integrity: sha512-ab9EmR80F/zQTMNeneUr4cv+jSwPJgIlvEmVwLerwrWVbpLlBuls9XHzIeTFy4cegU2NHBp3va0LKOzU5qFEYQ==} - resolve-dependency-path@4.0.1: - resolution: {integrity: sha512-YQftIIC4vzO9UMhO/sCgXukNyiwVRCVaxiWskCBy7Zpqkplm8kTAISZ8O1MoKW1ca6xzgLUBjZTcDgypXvXxiQ==} - engines: {node: '>=18'} - resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -16868,11 +16651,6 @@ packages: sass-embedded: optional: true - sass-lookup@6.1.0: - resolution: {integrity: sha512-Zx+lVyoWqXZxHuYWlTA17Z5sczJ6braNT2C7rmClw+c4E7r/n911Zwss3h1uHI9reR5AgHZyNHF7c2+VIp5AUA==} - engines: {node: '>=18'} - hasBin: true - sass@1.54.4: resolution: {integrity: sha512-3tmF16yvnBwtlPrNBHw/H907j8MlOX8aTBnlNX1yrKx24RKcJGPyLhFUwkoKBKesR3unP93/2z14Ll8NicwQUA==} engines: {node: '>=12.0.0'} @@ -17358,9 +17136,6 @@ packages: stream-slice@0.1.2: resolution: {integrity: sha512-QzQxpoacatkreL6jsxnVb7X5R/pGw9OUv2qWTYWnmLpg4NdN31snPy/f3TdQE1ZUXaThRvj1Zw4/OGg0ZkaLMA==} - stream-to-array@2.3.0: - resolution: {integrity: sha512-UsZtOYEn4tWU2RGLOXr/o/xjRBftZRlG3dEWoaHr8j4GuypJ3isitGbVyjQKAuMu+xbiop8q224TjiZWc4XTZA==} - streamx@2.22.1: resolution: {integrity: sha512-znKXEBxfatz2GBNK02kRnCXjV+AA4kjZIUxeWSr3UGirZMJfTE9uiwKHobnbgxWyL/JWro8tTq+vOqAK1/qbSA==} @@ -17411,10 +17186,6 @@ packages: stringify-entities@4.0.3: resolution: {integrity: sha512-BP9nNHMhhfcMbiuQKCqMjhDP5yBCAxsPu4pHFFzJ6Alo9dZgY4VLDPutXqIjpRiMoKdp7Av85Gr73Q5uH9k7+g==} - stringify-object@3.3.0: - resolution: {integrity: sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==} - engines: {node: '>=4'} - strip-ansi@6.0.1: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} @@ -17443,10 +17214,6 @@ packages: resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} engines: {node: '>=8'} - strip-json-comments@2.0.1: - resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} - engines: {node: '>=0.10.0'} - strip-json-comments@3.1.1: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} @@ -17496,11 +17263,6 @@ packages: stylus: '>=0.52.4' webpack: ^5.0.0 - stylus-lookup@6.1.0: - resolution: {integrity: sha512-5QSwgxAzXPMN+yugy61C60PhoANdItfdjSEZR8siFwz7yL9jTmV0UBKDCfn3K8GkGB4g0Y9py7vTCX8rFu4/pQ==} - engines: {node: '>=18'} - hasBin: true - stylus@0.59.0: resolution: {integrity: sha512-lQ9w/XIOH5ZHVNuNbWW8D822r+/wBSO/d6XvtyHLF7LW4KaCIDeVbvn5DF8fGCJAUCwVhVi/h6J0NUcnylUEjg==} hasBin: true @@ -17844,16 +17606,6 @@ packages: peerDependencies: typescript: '>=4.2.0' - ts-api-utils@2.1.0: - resolution: {integrity: sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==} - engines: {node: '>=18.12'} - peerDependencies: - typescript: '>=4.8.4' - - ts-graphviz@2.1.6: - resolution: {integrity: sha512-XyLVuhBVvdJTJr2FJJV2L1pc4MwSjMhcunRVgDE9k4wbb2ee7ORYnPewxMWUav12vxyfUM686MSGsqnVRIInuw==} - engines: {node: '>=18'} - ts-toolbelt@9.6.0: resolution: {integrity: sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w==} @@ -18889,10 +18641,6 @@ packages: resolution: {integrity: sha512-41TvKmDGVpm2iuH7o+DAOt06yyu/cSHpX3uzAwetzASvlNtVddgIjXIb2DfB/Wa20B1Jo86+1Dv1CraSU7hWdw==} engines: {node: 10.* || >= 12.*} - walkdir@0.4.1: - resolution: {integrity: sha512-3eBwRyEln6E1MSzcxcVpQIhRG8Q1jLvEqRmCZqS3dsfXEDR/AhOF4d+jHg1qvDCpYaVRZjENPQyrVxAkQqxPgQ==} - engines: {node: '>=6.0.0'} - warning@3.0.0: resolution: {integrity: sha512-jMBt6pUrKn5I+OGgtQ4YZLdhIeJmObddh6CsibPxyQ5yPZm1XExSyzC1LCNX7BzhxWgiHmizBWJTHJIjMjTQYQ==} @@ -23147,11 +22895,6 @@ snapshots: '@deno/shim-deno-test': 0.5.0 which: 4.0.0 - '@dependents/detective-less@5.0.1': - dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 7.0.1 - '@discoveryjs/json-ext@0.5.7': {} '@dxup/nuxt@0.5.6(@nuxt/schema@3.21.11)(confbox@0.2.4)(dotenv@17.4.2)(esbuild@0.28.1)(giget@3.3.1)(jiti@2.7.0)(mlly@1.8.2)(oxc-parser@0.143.0)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3))': @@ -27543,21 +27286,6 @@ snapshots: '@tootallnate/once@2.0.1': {} - '@ts-graphviz/adapter@2.0.6': - dependencies: - '@ts-graphviz/common': 2.1.5 - - '@ts-graphviz/ast@2.0.7': - dependencies: - '@ts-graphviz/common': 2.1.5 - - '@ts-graphviz/common@2.1.5': {} - - '@ts-graphviz/core@2.0.7': - dependencies: - '@ts-graphviz/ast': 2.0.7 - '@ts-graphviz/common': 2.1.5 - '@tybys/wasm-util@0.10.4': dependencies: tslib: 2.8.1 @@ -27908,15 +27636,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.35.0(supports-color@10.0.0)(typescript@5.8.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.35.0(typescript@5.8.3) - '@typescript-eslint/types': 8.35.0 - debug: 4.4.3(supports-color@10.0.0) - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/scope-manager@5.62.0': dependencies: '@typescript-eslint/types': 5.62.0 @@ -27927,10 +27646,6 @@ snapshots: '@typescript-eslint/types': 7.18.0 '@typescript-eslint/visitor-keys': 7.18.0 - '@typescript-eslint/tsconfig-utils@8.35.0(typescript@5.8.3)': - dependencies: - typescript: 5.8.3 - '@typescript-eslint/type-utils@5.62.0(eslint@8.57.0(supports-color@10.0.0))(supports-color@10.0.0)(typescript@7.0.2)': dependencies: '@typescript-eslint/typescript-estree': 5.62.0(supports-color@10.0.0)(typescript@7.0.2) @@ -27947,8 +27662,6 @@ snapshots: '@typescript-eslint/types@7.18.0': {} - '@typescript-eslint/types@8.35.0': {} - '@typescript-eslint/types@8.47.0': {} '@typescript-eslint/typescript-estree@5.62.0(supports-color@10.0.0)(typescript@7.0.2)': @@ -27980,22 +27693,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/typescript-estree@8.35.0(supports-color@10.0.0)(typescript@5.8.3)': - dependencies: - '@typescript-eslint/project-service': 8.35.0(supports-color@10.0.0)(typescript@5.8.3) - '@typescript-eslint/tsconfig-utils': 8.35.0(typescript@5.8.3) - '@typescript-eslint/types': 8.35.0 - '@typescript-eslint/visitor-keys': 8.35.0 - debug: 4.4.3(supports-color@10.0.0) - fast-glob: 3.3.3 - is-glob: 4.0.3 - minimatch: 9.0.9 - semver: 7.8.5 - ts-api-utils: 2.1.0(typescript@5.8.3) - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - '@typescript-eslint/utils@5.62.0(eslint@8.57.0(supports-color@10.0.0))(supports-color@10.0.0)(typescript@7.0.2)': dependencies: '@eslint-community/eslint-utils': 4.9.0(eslint@8.57.0(supports-color@10.0.0)) @@ -28032,11 +27729,6 @@ snapshots: '@typescript-eslint/types': 7.18.0 eslint-visitor-keys: 3.4.3 - '@typescript-eslint/visitor-keys@8.35.0': - dependencies: - '@typescript-eslint/types': 8.35.0 - eslint-visitor-keys: 4.2.1 - '@typescript/typescript-aix-ppc64@7.0.2': optional: true @@ -28826,15 +28518,11 @@ snapshots: ansis@4.3.1: {} - any-promise@1.3.0: {} - anymatch@3.1.3: dependencies: normalize-path: 3.0.0 picomatch: 2.3.2 - app-module-path@2.2.0: {} - aproba@2.0.0: {} archiver-utils@5.0.2: @@ -28975,8 +28663,6 @@ snapshots: '@babel/parser': 7.29.9 pathe: 2.0.3 - ast-module-types@6.0.1: {} - ast-types@0.13.3: {} ast-types@0.16.1: @@ -30070,15 +29756,11 @@ snapshots: commander@11.1.0: {} - commander@12.1.0: {} - commander@14.0.3: optional: true commander@2.20.3: {} - commander@7.2.0: {} - commander@8.3.0: {} commander@9.5.0: {} @@ -30541,8 +30223,6 @@ snapshots: which-collection: 1.0.2 which-typed-array: 1.1.19 - deep-extend@0.6.0: {} - deep-is@0.1.3: {} deepmerge-ts@7.1.5: {} @@ -30596,15 +30276,6 @@ snapshots: dependency-graph@0.11.0: {} - dependency-tree@11.2.0(supports-color@10.0.0): - dependencies: - commander: 12.1.0 - filing-cabinet: 5.0.3 - precinct: 12.2.0(supports-color@10.0.0) - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - dequal@2.0.3: {} destr@2.0.5: {} @@ -30617,62 +30288,6 @@ snapshots: detect-node@2.1.0: {} - detective-amd@6.0.1: - dependencies: - ast-module-types: 6.0.1 - escodegen: 2.1.0 - get-amd-module-type: 6.0.1 - node-source-walk: 7.0.1 - - detective-cjs@6.0.1: - dependencies: - ast-module-types: 6.0.1 - node-source-walk: 7.0.1 - - detective-es6@5.0.1: - dependencies: - node-source-walk: 7.0.1 - - detective-postcss@7.0.1(postcss@8.5.32): - dependencies: - is-url: 1.2.4 - postcss: 8.5.32 - postcss-values-parser: 6.0.2(postcss@8.5.32) - - detective-sass@6.0.1: - dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 7.0.1 - - detective-scss@5.0.1: - dependencies: - gonzales-pe: 4.3.0 - node-source-walk: 7.0.1 - - detective-stylus@5.0.1: {} - - detective-typescript@14.0.0(supports-color@10.0.0)(typescript@5.8.3): - dependencies: - '@typescript-eslint/typescript-estree': 8.35.0(supports-color@10.0.0)(typescript@5.8.3) - ast-module-types: 6.0.1 - node-source-walk: 7.0.1 - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - - detective-vue2@2.2.0(supports-color@10.0.0)(typescript@5.8.3): - dependencies: - '@dependents/detective-less': 5.0.1 - '@vue/compiler-sfc': 3.5.44 - detective-es6: 5.0.1 - detective-sass: 6.0.1 - detective-scss: 5.0.1 - detective-stylus: 5.0.1 - detective-typescript: 14.0.0(supports-color@10.0.0)(typescript@5.8.3) - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - deterministic-object-hash@2.0.2: dependencies: base-64: 1.0.0 @@ -31952,20 +31567,6 @@ snapshots: file-uri-to-path@1.0.0: {} - filing-cabinet@5.0.3: - dependencies: - app-module-path: 2.2.0 - commander: 12.1.0 - enhanced-resolve: 5.26.0 - module-definition: 6.0.1 - module-lookup-amd: 9.0.5 - resolve: 1.22.12 - resolve-dependency-path: 4.0.1 - sass-lookup: 6.1.0 - stylus-lookup: 6.1.0 - tsconfig-paths: 4.2.0 - typescript: 5.8.3 - fill-range@7.1.1: dependencies: to-regex-range: 5.0.1 @@ -32237,11 +31838,6 @@ snapshots: gensync@1.0.0-beta.2: {} - get-amd-module-type@6.0.1: - dependencies: - ast-module-types: 6.0.1 - node-source-walk: 7.0.1 - get-caller-file@2.0.5: {} get-east-asian-width@1.7.0: {} @@ -32259,8 +31855,6 @@ snapshots: hasown: 2.0.4 math-intrinsics: 1.1.0 - get-own-enumerable-property-symbols@3.0.2: {} - get-package-type@0.1.0: {} get-port-please@3.2.0: {} @@ -32409,10 +32003,6 @@ snapshots: globrex@0.1.2: {} - gonzales-pe@4.3.0: - dependencies: - minimist: 1.2.8 - google-auth-library@10.9.1(supports-color@10.0.0): dependencies: base64-js: 1.5.1 @@ -33004,8 +32594,6 @@ snapshots: inherits@2.0.4: {} - ini@1.3.8: {} - ini@2.0.0: {} ini@3.0.0: {} @@ -33209,8 +32797,6 @@ snapshots: is-number@7.0.0: {} - is-obj@1.0.1: {} - is-path-inside@3.0.3: {} is-path-inside@4.0.0: {} @@ -33244,8 +32830,6 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 - is-regexp@1.0.0: {} - is-set@2.0.3: {} is-shared-array-buffer@1.0.4: @@ -33281,10 +32865,6 @@ snapshots: is-unicode-supported@2.1.0: {} - is-url-superb@4.0.0: {} - - is-url@1.2.4: {} - is-weakmap@2.0.2: {} is-weakref@1.1.1: @@ -34030,25 +33610,6 @@ snapshots: lz-string@1.5.0: {} - madge@8.0.0(supports-color@10.0.0)(typescript@7.0.2): - dependencies: - chalk: 4.1.2 - commander: 7.2.0 - commondir: 1.0.1 - debug: 4.4.3(supports-color@10.0.0) - dependency-tree: 11.2.0(supports-color@10.0.0) - ora: 5.4.1 - pluralize: 8.0.0 - pretty-ms: 7.0.1 - rc: 1.2.8 - stream-to-array: 2.3.0 - ts-graphviz: 2.1.6 - walkdir: 0.4.1 - optionalDependencies: - typescript: 7.0.2 - transitivePeerDependencies: - - supports-color - magic-string-ast@1.0.3: dependencies: magic-string: 0.30.21 @@ -34711,20 +34272,8 @@ snapshots: mocked-exports@0.1.1: {} - module-definition@6.0.1: - dependencies: - ast-module-types: 6.0.1 - node-source-walk: 7.0.1 - module-details-from-path@1.0.4: {} - module-lookup-amd@9.0.5: - dependencies: - commander: 12.1.0 - glob: 7.2.3 - requirejs: 2.3.7 - requirejs-config-file: 4.0.0 - moment@2.31.0: {} mongodb-connection-string-url@2.6.0: @@ -35520,10 +35069,6 @@ snapshots: long-timeout: 0.1.1 sorted-array-functions: 1.3.0 - node-source-walk@7.0.1: - dependencies: - '@babel/parser': 7.29.9 - nodemon@3.1.10: dependencies: chokidar: 3.6.0 @@ -36063,7 +35608,7 @@ snapshots: bl: 4.1.0 chalk: 4.1.2 cli-cursor: 3.1.0 - cli-spinners: 2.9.2 + cli-spinners: 2.6.1 is-interactive: 1.0.0 is-unicode-supported: 0.1.0 log-symbols: 4.1.0 @@ -36386,8 +35931,6 @@ snapshots: unist-util-visit-children: 3.0.0 vfile: 6.0.3 - parse-ms@2.1.0: {} - parse-node-version@1.0.1: {} parse-statements@1.0.11: {} @@ -37217,13 +36760,6 @@ snapshots: postcss-value-parser@4.2.0: {} - postcss-values-parser@6.0.2(postcss@8.5.32): - dependencies: - color-name: 1.1.4 - is-url-superb: 4.0.0 - postcss: 8.5.32 - quote-unquote: 1.0.0 - postcss@8.4.31: dependencies: nanoid: 3.3.20 @@ -37254,26 +36790,6 @@ snapshots: preact@10.29.8: {} - precinct@12.2.0(supports-color@10.0.0): - dependencies: - '@dependents/detective-less': 5.0.1 - commander: 12.1.0 - detective-amd: 6.0.1 - detective-cjs: 6.0.1 - detective-es6: 5.0.1 - detective-postcss: 7.0.1(postcss@8.5.32) - detective-sass: 6.0.1 - detective-scss: 5.0.1 - detective-stylus: 5.0.1 - detective-typescript: 14.0.0(supports-color@10.0.0)(typescript@5.8.3) - detective-vue2: 2.2.0(supports-color@10.0.0)(typescript@5.8.3) - module-definition: 6.0.1 - node-source-walk: 7.0.1 - postcss: 8.5.32 - typescript: 5.8.3 - transitivePeerDependencies: - - supports-color - preferred-pm@4.1.1: dependencies: find-up-simple: 1.0.1 @@ -37308,10 +36824,6 @@ snapshots: ansi-styles: 5.2.0 react-is: 17.0.2 - pretty-ms@7.0.1: - dependencies: - parse-ms: 2.1.0 - prisma@6.15.0(magicast@0.3.5)(typescript@7.0.2): dependencies: '@prisma/config': 6.15.0(magicast@0.3.5) @@ -37441,8 +36953,6 @@ snapshots: quickjs-wasi@3.6.2: {} - quote-unquote@1.0.0: {} - radix3@1.1.2: {} randombytes@2.1.0: @@ -37475,13 +36985,6 @@ snapshots: defu: 6.1.7 destr: 2.0.5 - rc@1.2.8: - dependencies: - deep-extend: 0.6.0 - ini: 1.3.8 - minimist: 1.2.8 - strip-json-comments: 2.0.1 - react-dom@18.3.1(react@18.3.1): dependencies: loose-envify: 1.4.0 @@ -37851,19 +37354,10 @@ snapshots: require-from-string@2.0.2: {} - requirejs-config-file@4.0.0: - dependencies: - esprima: 4.0.1 - stringify-object: 3.3.0 - - requirejs@2.3.7: {} - requires-port@1.0.0: {} reselect@4.1.8: {} - resolve-dependency-path@4.0.1: {} - resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -38175,11 +37669,6 @@ snapshots: optionalDependencies: sass: 1.54.4 - sass-lookup@6.1.0: - dependencies: - commander: 12.1.0 - enhanced-resolve: 5.26.0 - sass@1.54.4: dependencies: chokidar: 3.6.0 @@ -38836,10 +38325,6 @@ snapshots: stream-slice@0.1.2: {} - stream-to-array@2.3.0: - dependencies: - any-promise: 1.3.0 - streamx@2.22.1: dependencies: fast-fifo: 1.3.2 @@ -38912,12 +38397,6 @@ snapshots: character-entities-html4: 2.1.0 character-entities-legacy: 3.0.0 - stringify-object@3.3.0: - dependencies: - get-own-enumerable-property-symbols: 3.0.2 - is-obj: 1.0.1 - is-regexp: 1.0.0 - strip-ansi@6.0.1: dependencies: ansi-regex: 5.0.1 @@ -38938,8 +38417,6 @@ snapshots: dependencies: min-indent: 1.0.1 - strip-json-comments@2.0.1: {} - strip-json-comments@3.1.1: {} strip-literal@4.0.0: @@ -38979,10 +38456,6 @@ snapshots: stylus: 0.59.0(supports-color@10.0.0) webpack: 5.76.1(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.15.5)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.4.31)(uglify-js@3.13.3) - stylus-lookup@6.1.0: - dependencies: - commander: 12.1.0 - stylus@0.59.0(supports-color@10.0.0): dependencies: '@adobe/css-tools': 4.4.3 @@ -39332,17 +38805,6 @@ snapshots: dependencies: typescript: 7.0.2 - ts-api-utils@2.1.0(typescript@5.8.3): - dependencies: - typescript: 5.8.3 - - ts-graphviz@2.1.6: - dependencies: - '@ts-graphviz/adapter': 2.0.6 - '@ts-graphviz/ast': 2.0.7 - '@ts-graphviz/common': 2.1.5 - '@ts-graphviz/core': 2.0.7 - ts-toolbelt@9.6.0: {} tsconfck@3.1.6(typescript@7.0.2): @@ -40485,8 +39947,6 @@ snapshots: matcher-collection: 2.0.1 minimatch: 3.1.5 - walkdir@0.4.1: {} - warning@3.0.0: dependencies: loose-envify: 1.4.0 From 3e2f711cdfa46e4b03a59a2fd3db86c7024065c5 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:02:00 +0100 Subject: [PATCH 050/136] test(nuxt): Add vue-router to Nuxt 5 E2E apps (#26323) **Why:** Nuxt 5 nightlies from `5.0.0-2611121215` on moved `vue-router` from `dependencies` to an optional peer dependency. Apps with a `pages/` directory now fail `nuxt build` with `Cannot find package 'vue-router'`. That breaks the required `E2E nuxt-5 (tunnel-basepath)` check, and with it every PR into `develop`, plus the optional `nuxt-5` and `nuxt-5-sourcemaps` variants. `nuxt-5-cloudflare` has no pages, so it still builds and is left unchanged. **How to review:** I reproduced the failure in a minimal pages app on `nuxt-nightly@5.0.0-2611121224-0568af6`. Adding `vue-router@^5.5.0` makes it build again. Older nightlies already shipped `vue-router@^5.5.0` as a dependency, so this range matches them too. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794484186.405239) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794484186.405239/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../e2e-tests/test-applications/nuxt-5-sourcemaps/package.json | 3 ++- dev-packages/e2e-tests/test-applications/nuxt-5/package.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json index e2d35fd304b3..af833ac3a1bf 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/package.json @@ -16,7 +16,8 @@ "dependencies": { "@sentry/nuxt": "file:../../packed/sentry-nuxt-packed.tgz", "nitro": "latest", - "nuxt": "npm:nuxt-nightly@5x" + "nuxt": "npm:nuxt-nightly@5x", + "vue-router": "^5.5.0" }, "devDependencies": { "@playwright/test": "1.64.1", diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json index 517736025e41..081e3a523b31 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -33,7 +33,8 @@ "mongoose": "^9.10.2", "ofetch": "^2.0.0-alpha.3", "nuxt": "npm:nuxt-nightly@5x", - "vue": "^3.5.41" + "vue": "^3.5.41", + "vue-router": "^5.5.0" }, "devDependencies": { "@playwright/test": "1.64.1", From 621a8010dd9dab270e6fb9bac71236abd936e9b6 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:11:59 +0000 Subject: [PATCH 051/136] chore(deps): Run yalc via pnpm dlx instead of a root devDependency (#26318) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** yalc is only used for local manual testing (nothing in CI calls it), and its last release is `1.0.0-pre.53` from 2021. Running it with `pnpm dlx` on demand removes it and the old deps that only it pulls in (`npm-packlist@2`, `yargs@16`, `ignore-walk`, …) from the lockfile, so every install stops paying for a tool most contributors never use. Test projects already needed their own yalc for `yalc add`; the docs now point to `pnpm dlx yalc add` too. The scripts don't pin a version: yalc hasn't released since 2021, so `latest` is effectively fixed. **How to review:** The 37 package script changes are identical. The lockfile diff only removes entries. I ran `yalc:publish` in 8 packages in parallel with an empty dlx cache, and all 8 published to the yalc store. Warm runs take well under a second per package. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794484186.405239) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794484186.405239/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- docs/using-yalc.md | 13 +--- package.json | 3 +- packages/angular/package.json | 2 +- packages/astro/package.json | 2 +- packages/aws-serverless/package.json | 2 +- packages/browser-utils/package.json | 2 +- packages/browser/package.json | 2 +- packages/bun/package.json | 2 +- packages/cloudflare/package.json | 2 +- packages/core/package.json | 2 +- packages/deno/package.json | 2 +- packages/effect/package.json | 2 +- packages/elysia/package.json | 2 +- packages/ember/package.json | 2 +- packages/feedback/package.json | 2 +- packages/gatsby/package.json | 2 +- packages/google-cloud-serverless/package.json | 2 +- packages/hono/package.json | 2 +- packages/nestjs/package.json | 2 +- packages/nextjs/package.json | 2 +- packages/nitro/package.json | 2 +- packages/node/package.json | 2 +- packages/nuxt/package.json | 2 +- packages/opentelemetry/package.json | 2 +- packages/react-router/package.json | 2 +- packages/react/package.json | 2 +- packages/remix/package.json | 2 +- packages/replay-canvas/package.json | 2 +- packages/replay-internal/package.json | 2 +- .../server-runtime-injection/package.json | 2 +- packages/server-utils/package.json | 2 +- packages/solid/package.json | 2 +- packages/solidstart/package.json | 2 +- packages/svelte/package.json | 2 +- packages/sveltekit/package.json | 2 +- packages/tanstackstart-react/package.json | 2 +- packages/vercel-edge/package.json | 2 +- packages/vue/package.json | 2 +- packages/wasm/package.json | 2 +- pnpm-lock.yaml | 69 ------------------- 40 files changed, 41 insertions(+), 118 deletions(-) diff --git a/docs/using-yalc.md b/docs/using-yalc.md index f95465aa45eb..abf261179c74 100644 --- a/docs/using-yalc.md +++ b/docs/using-yalc.md @@ -8,15 +8,8 @@ Here's how to set up and use yalc: ## Installing `yalc` -Either install yalc globally, - -```sh -npm install -g yalc - -pnpm add -g yalc -``` - -or add it to your desired test projects (same command without the `-g` flag) +You don't need to install yalc. The `yalc:publish` scripts run it with `pnpm dlx`, and you can do the same in your test +projects. If you prefer, install it globally with `pnpm add -g yalc` and drop the `pnpm dlx` prefix below. ## Registering/Updating packages @@ -35,7 +28,7 @@ project. Already linked test projects will be update automatically. In your test project, run ```sh -yalc add @sentry/browser #or any other SDK package +pnpm dlx yalc add @sentry/browser #or any other SDK package ``` to add the local SDK package to your project. diff --git a/package.json b/package.json index 1213b3037fcb..0a95ce38e3dc 100644 --- a/package.json +++ b/package.json @@ -161,8 +161,7 @@ "tsx": "^4.23.15", "typescript": "~7.0.2", "vitest": "^4.1.12", - "webpack": "^5.112.2", - "yalc": "^1.0.0-pre.53" + "webpack": "^5.112.2" }, "version": "0.0.0", "name": "sentry-javascript" diff --git a/packages/angular/package.json b/packages/angular/package.json index b82cf0a346db..85cf9434eb22 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -58,7 +58,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:unit:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/astro/package.json b/packages/astro/package.json index 35edcf707e9a..86c4623bdf99 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -96,7 +96,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "astro": { "external": true diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 234f7fb9671a..9ca445d6fa29 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -97,7 +97,7 @@ "lint:es-compatibility": "es-check es2022 ./build/npm/cjs/*.js && es-check es2022 ./build/npm/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index 224637a4f0d2..ebfdc40be99a 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -57,7 +57,7 @@ "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/browser/package.json b/packages/browser/package.json index 12f6ad0178a9..c63397ee82ba 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -69,7 +69,7 @@ "size:check": "cat build/bundles/bundle.min.js | gzip -9 | wc -c | awk '{$1=$1/1024; print \"ES2017: \",$1,\"kB\";}'", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/bun/package.json b/packages/bun/package.json index c67587fc5ae6..8d5aa84401c6 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -71,7 +71,7 @@ "test": "run-s install:bun test:bun", "test:bun": "bun test", "test:watch": "bun test --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 6e3c9a6f6c17..00523b4e4a39 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -100,7 +100,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/core/package.json b/packages/core/package.json index b7a04e89fb46..92c4ebc10bd8 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -83,7 +83,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "devDependencies": { diff --git a/packages/deno/package.json b/packages/deno/package.json index d679b603ed89..1e5bfb5c84ef 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -55,7 +55,7 @@ "test:types": "deno check --unstable-sloppy-imports test", "test:unit": "deno test --allow-net --allow-read --allow-run --allow-env --no-check", "test:unit:update": "deno test --allow-net --allow-read --allow-run --allow-env --no-check --allow-write -- --update", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": [ "./build/import.mjs" diff --git a/packages/effect/package.json b/packages/effect/package.json index 027f62b528fa..58ecc48eb5ac 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -77,7 +77,7 @@ "lint:types": "oxlint src --type-aware --type-check", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/elysia/package.json b/packages/elysia/package.json index b1155faaa1ba..f647f32bb9dc 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -65,7 +65,7 @@ "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/ember/package.json b/packages/ember/package.json index 72b6c4588e57..b124efedc9c5 100644 --- a/packages/ember/package.json +++ b/packages/ember/package.json @@ -38,7 +38,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:unit:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "dependencies": { "@embroider/addon-shim": "^1.11.0", diff --git a/packages/feedback/package.json b/packages/feedback/package.json index e5371a24a520..fffb9e6b72b2 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -57,7 +57,7 @@ "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index 4688670fc83c..bd76356eecef 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -70,7 +70,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index 952241680656..c14d67945949 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -74,7 +74,7 @@ "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/hono/package.json b/packages/hono/package.json index fa00cbab3b52..9a1cb3e0c245 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -130,7 +130,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index 3911d46931f6..746c48f365e6 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -88,7 +88,7 @@ "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 79e75e7e5601..143daed53d6e 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -128,7 +128,7 @@ "test:watch": "vitest --watch", "vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh", "vercel:project": "source vercel/make-project-use-current-branch.sh", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 00c81795b0b2..873f0893d713 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -66,7 +66,7 @@ "lint:es-compatibility": "es-check es2022 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/node/package.json b/packages/node/package.json index b50fb2612159..16a511f2f9e6 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -106,7 +106,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index aabf71a69814..1d7750057282 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -97,7 +97,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index eccd9ad480ab..380fe0d71354 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -54,7 +54,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 28a24409af05..341ee22d26d8 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -100,6 +100,6 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" } } diff --git a/packages/react/package.json b/packages/react/package.json index ef2fed1e5c57..1400559fbc1c 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -104,7 +104,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/remix/package.json b/packages/remix/package.json index 0414783c9d71..9ee8d87c357c 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -124,7 +124,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run --config vitest.config.unit.ts", "test:watch": "vitest --watch --config vitest.config.unit.ts", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index e707c2faa794..7abc0cc76ce6 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -41,7 +41,7 @@ "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "publishConfig": { "access": "public" diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 6aa218c5bc17..0dec99748bb4 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -57,7 +57,7 @@ "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "repository": { "type": "git", diff --git a/packages/server-runtime-injection/package.json b/packages/server-runtime-injection/package.json index 7fa9b0c76d15..ef8b0b9e2cf8 100644 --- a/packages/server-runtime-injection/package.json +++ b/packages/server-runtime-injection/package.json @@ -74,7 +74,7 @@ "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": [ "**/import-hook.mjs" diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 0b8481af2e02..182ba3b08e5f 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -131,7 +131,7 @@ "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/solid/package.json b/packages/solid/package.json index beffefcbe1fa..1b1cb8bd1f22 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -101,7 +101,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 2a3c3a23fc78..d6a88ef69c46 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -128,7 +128,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "nx": { "targets": { diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 6ab1859aef63..e8cdcf514716 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -63,7 +63,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 55eb2ebf5a1d..0b91191f427b 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -110,7 +110,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 24051e4f3a3d..5fd1b50fbbb2 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -83,7 +83,7 @@ "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index ae8ec12e0f75..7b1eb06ae1db 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -57,7 +57,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/packages/vue/package.json b/packages/vue/package.json index 240764978ed5..76b557061200 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -84,7 +84,7 @@ "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "vitest run", "test:watch": "vitest --watch", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false, "nx": { diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 2d6060a44850..cd18e858109d 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -56,7 +56,7 @@ "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", - "yalc:publish": "yalc publish --push --sig" + "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8899373abc39..d0e92cbee61e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -258,9 +258,6 @@ importers: webpack: specifier: ^5.112.2 version: 5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3) - yalc: - specifier: ^1.0.0-pre.53 - version: 1.0.0-pre.53 dev-packages/browser-integration-tests: devDependencies: @@ -11101,10 +11098,6 @@ packages: resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} - detect-indent@6.0.0: - resolution: {integrity: sha512-oSyFlqaTHCItVRGK5RmrmjB+CmaMOW7IaNA/kdxqhoa6d17j/5ce9O9eWXmV/KEdRwqpQA+Vqe8a8Bsybu4YnA==} - engines: {node: '>=8'} - detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -12819,9 +12812,6 @@ packages: ignore-by-default@1.0.1: resolution: {integrity: sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==} - ignore-walk@3.0.3: - resolution: {integrity: sha512-m7o6xuOaT1aqheYHKf8W6J5pYH85ZI9w077erOzLje3JsB1gkafkAhHHY19dqjulgIZHFm32Cp5uNZgcQqdJKw==} - ignore-walk@5.0.1: resolution: {integrity: sha512-yemi4pMf51WKT7khInJqAvsIGzoqYXblnsz0ql8tM+yi1EKYTY1evX4NAbJrLL/Aanr2HyZeluqU+Oi7MGHokw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -12885,10 +12875,6 @@ packages: inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - ini@2.0.0: - resolution: {integrity: sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==} - engines: {node: '>=10'} - ini@3.0.0: resolution: {integrity: sha512-TxYQaeNW/N8ymDvwAxPyRbhMBtnEwuvaTYpOQkFx1nSeusgezHniEc/l35Vo4iCq/mMiTJbpD7oYxN98hFlfmw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -14772,11 +14758,6 @@ packages: resolution: {integrity: sha512-4J0GL+u2Nh6OnhvUKXRr2ZMG4lR8qtLp+kv7UiV00Y+nGiSxtttCyIRHCt5L5BNkXQld/RceYItau3MDOoGiBw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} - npm-packlist@2.2.2: - resolution: {integrity: sha512-Jt01acDvJRhJGthnUJVF/w6gumWOZxO7IkpY/lsX9//zqQgnF7OJaxgQXcerd4uQOLu7W5bkb4mChL9mdfm+Zg==} - engines: {node: '>=10'} - hasBin: true - npm-packlist@5.1.3: resolution: {integrity: sha512-263/0NGrn32YFYi4J533qzrQ/krmmrWwhKkzwTuM4f/07ug51odoaNjUexxO4vxlzURHcmYMH1QjvHjsNDKLVg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -18961,10 +18942,6 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - yalc@1.0.0-pre.53: - resolution: {integrity: sha512-tpNqBCpTXplnduzw5XC+FF8zNJ9L/UXmvQyyQj7NKrDNavbJtHvzmZplL5ES/RCnjX7JR7W9wz5GVDXVP3dHUQ==} - hasBin: true - yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -18984,10 +18961,6 @@ packages: engines: {node: '>= 14.6'} hasBin: true - yargs-parser@20.2.9: - resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} - engines: {node: '>=10'} - yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -18996,10 +18969,6 @@ packages: resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} engines: {node: ^20.19.0 || ^22.12.0 || >=23} - yargs@16.2.0: - resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==} - engines: {node: '>=10'} - yargs@17.5.1: resolution: {integrity: sha512-t6YAJcxDkNX7NFYiVtKvWUz8l+PaKTLiL63mJYWR2GnHq2gjEWISzsLp9wg3aY36dY1j+gfIEL3pIF+XlJJfbA==} engines: {node: '>=12'} @@ -30282,8 +30251,6 @@ snapshots: destroy@1.2.0: {} - detect-indent@6.0.0: {} - detect-libc@2.1.2: {} detect-node@2.1.0: {} @@ -32531,10 +32498,6 @@ snapshots: ignore-by-default@1.0.1: {} - ignore-walk@3.0.3: - dependencies: - minimatch: 3.1.5 - ignore-walk@5.0.1: dependencies: minimatch: 5.1.9 @@ -32594,8 +32557,6 @@ snapshots: inherits@2.0.4: {} - ini@2.0.0: {} - ini@3.0.0: {} ini@4.1.1: {} @@ -35130,13 +35091,6 @@ snapshots: semver: 7.8.5 validate-npm-package-name: 4.0.0 - npm-packlist@2.2.2: - dependencies: - glob: 7.2.3 - ignore-walk: 3.0.3 - npm-bundled: 1.1.2 - npm-normalize-package-bin: 1.0.1 - npm-packlist@5.1.3: dependencies: glob: 8.1.0 @@ -40409,17 +40363,6 @@ snapshots: y18n@5.0.8: {} - yalc@1.0.0-pre.53: - dependencies: - chalk: 4.1.2 - detect-indent: 6.0.0 - fs-extra: 8.1.0 - glob: 7.2.3 - ignore: 5.3.2 - ini: 2.0.0 - npm-packlist: 2.2.2 - yargs: 16.2.0 - yallist@3.1.1: {} yallist@4.0.0: {} @@ -40430,22 +40373,10 @@ snapshots: yaml@2.9.0: {} - yargs-parser@20.2.9: {} - yargs-parser@21.1.1: {} yargs-parser@22.0.0: {} - yargs@16.2.0: - dependencies: - cliui: 7.0.4 - escalade: 3.2.0 - get-caller-file: 2.0.5 - require-directory: 2.1.1 - string-width: 4.2.3 - y18n: 5.0.8 - yargs-parser: 20.2.9 - yargs@17.5.1: dependencies: cliui: 7.0.4 From f49009b49e56b38f90c650da42d8a48bfcd138b8 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Thu, 12 Nov 2026 13:47:26 +0000 Subject: [PATCH 052/136] fix(server-runtime-injection): Register the CJS loader hook from the CJS build (#26278) On Node < 24.13, the CJS build of `register.ts` passed `build/esm/hook.js` to `Module.register()`. Turbopack ships that file in the Next.js server trace but does not follow its imports, so the loader thread could not find `build/esm/vendored/**` or the ESM build of `@sentry/core`. Registration then warned on every cold start. The CJS build now registers `build/cjs/hook.js`, which the package already built but did not use. That file only requires chunks that `register.js` requires too, so a tracer that ships a working `register.js` always ships them. Node accepts a CJS module as a `Module.register()` target. This is an alternative to #26271: the package does not grow and no Next.js config is needed. The `data:` URL loader that forced the ESM format for `build/esm` is removed. It only helped the CJS build load the ESM hook when a deployment dropped `build/esm/package.json`, and the CJS build no longer loads anything from `build/esm`. The ESM build still registers the ESM hook. The new `test/hook.test.ts` registers the hook from a copy that ships only `build/cjs`. The `nextjs-16-standalone` build-output test (taken from #26271) forces the `Module.register()` path against the real Turbopack standalone output. Both fail on `develop` with the error from the issue. Closes #26121 --------- Co-authored-by: isaacs --- .../tests/build-output.test.ts | 37 ++++++--- .../rollup.npm.config.mjs | 6 +- .../server-runtime-injection/src/hook.mjs | 14 ++-- .../server-runtime-injection/src/register.ts | 28 ++----- .../test/esmMarker.test.ts | 42 ---------- .../test/hook.test.ts | 80 +++++++++++++++++++ .../test/nftTrace.test.ts | 13 ++- 7 files changed, 129 insertions(+), 91 deletions(-) delete mode 100644 packages/server-runtime-injection/test/esmMarker.test.ts create mode 100644 packages/server-runtime-injection/test/hook.test.ts diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/build-output.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/build-output.test.ts index 936ff77b6494..fa21afb7e171 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/build-output.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/build-output.test.ts @@ -1,5 +1,6 @@ import { expect, test } from '@playwright/test'; import { findAbsolutePathImports } from '@sentry-internal/test-utils'; +import { spawnSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; @@ -14,19 +15,29 @@ test('emits no absolute-path imports into the relocated standalone output', () = expect(leaks).toEqual([]); }); -// Regression test for the bug this app surfaced (JS-3451): `register.ts` reaches the ESM loader -// hook through `Module.register(...)`, a runtime call `@vercel/nft` cannot trace. The hook was -// therefore never copied into the standalone output, and channel-based instrumentation failed to -// register, silently, behind `debug: true`. Asserting on the traced output rather than on emitted -// telemetry, because Next.js records its server spans through its own wrapping either way, so the -// tests in `standalone.test.ts` stay green even when channel injection is dead. -test('traces the orchestrion ESM loader hook into the standalone output', () => { - const standaloneDir = path.join(process.cwd(), '.next', 'standalone'); - const hookSuffix = path.join('@sentry', 'server-runtime-injection', 'build', 'esm', 'hook.js'); +// Regression test for JS-3451 and JS-4067. `register.ts` hands the loader hook to +// `Module.register()` by runtime path, so the standalone output must ship the hook and everything it +// loads: first `@vercel/nft` didn't trace the hook at all, then Turbopack shipped it without its +// imports. Either way channel injection failed to register, silently, behind `debug: true`. This +// checks the registration marker rather than emitted telemetry, because Next.js records its server +// spans through its own wrapping either way. The runner's Node takes the `Module.registerHooks` path, +// which never loads the hook, so force the `Module.register()` path that Node < 24.13 takes. +test('registers the orchestrion loader hook from the standalone output', () => { + const registerSuffix = path.join('@sentry', 'server-runtime-injection', 'build', 'cjs', 'register.js'); + const registerPath = fs + .readdirSync(path.join(process.cwd(), '.next', 'standalone'), { recursive: true, withFileTypes: true }) + .map(entry => path.join(entry.parentPath, entry.name)) + .find(file => file.endsWith(registerSuffix)); + expect(registerPath).toBeDefined(); - const found = fs - .readdirSync(standaloneDir, { recursive: true, withFileTypes: true }) - .some(entry => entry.isFile() && path.join(entry.parentPath, entry.name).endsWith(hookSuffix)); + const script = ` + require('node:module').registerHooks = undefined; + require(${JSON.stringify(registerPath)}).registerDiagnosticsChannelInjection(); + const marker = globalThis.__SENTRY__?.__SENTRY_ORCHESTRION__ ?? globalThis.__SENTRY_ORCHESTRION__; + process.stdout.write(JSON.stringify(marker)); + `; + const { stdout, stderr } = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8' }); - expect(found).toBe(true); + expect(stderr).not.toContain('Failed to register diagnostics-channel injection hooks'); + expect(JSON.parse(stdout)).toEqual({ runtime: [] }); }); diff --git a/packages/server-runtime-injection/rollup.npm.config.mjs b/packages/server-runtime-injection/rollup.npm.config.mjs index 8257a4ca165a..c30a7692fa5c 100644 --- a/packages/server-runtime-injection/rollup.npm.config.mjs +++ b/packages/server-runtime-injection/rollup.npm.config.mjs @@ -109,10 +109,8 @@ export default [ ...makeNPMConfigVariants( makeBaseNPMConfig({ // `register.ts` backs `./register` (the Node SDK `require`s it synchronously from - // `Sentry.init()`); `hook.mjs` backs `./hook` (the async `Module.register()` target, loaded on - // Node's ESM loader thread, which cannot resolve bare specifiers into the vendored chunks — but - // relative imports work, so it shares the ESM build's vendored chunks). `./hook` only maps its - // `import` condition, so the `build/cjs` copy is unused. + // `Sentry.init()`); `hook.mjs` is the async `Module.register()` target, loaded on Node's + // loader thread. Each build registers its own copy, which shares that build's vendored chunks. entrypoints: ['src/register.ts', 'src/hook.mjs'], packageSpecificConfig: { plugins: [ diff --git a/packages/server-runtime-injection/src/hook.mjs b/packages/server-runtime-injection/src/hook.mjs index e0f187804615..ce8cd3cd64ae 100644 --- a/packages/server-runtime-injection/src/hook.mjs +++ b/packages/server-runtime-injection/src/hook.mjs @@ -1,10 +1,10 @@ // The async module hooks handed to `Module.register()` by -// `registerDiagnosticsChannelInjection()` (Node 18.19–24.12, where the stable sync +// `registerDiagnosticsChannelInjection()` (Node 20.19–24.12 and 25.0, where the stable sync // `Module.registerHooks` API isn't available). // -// `Module.register()` loads its target on Node's ESM loader thread, so the target must be a real, -// on-disk ES module graph — the loader thread cannot resolve bare specifiers into the dependency -// graph this package bundles away, but it can follow relative imports. This shim is therefore an -// entrypoint of the regular ESM build (sharing the vendored dependency chunks) and exposed via the -// `@sentry/server-runtime-injection/hook` subpath. -export * from '@apm-js-collab/tracing-hooks/hook.mjs'; +// `Module.register()` loads its target on Node's loader thread, which +// cannot resolve bare specifiers into the dependencies this package +// bundles. This shim is therefore an entrypoint of both builds and shares +// their vendored chunks. The CJS build registers the CJS copy by path. The +// ESM copy is also exposed as `@sentry/server-runtime-injection/hook`. +export { initialize, load, resolve } from '@apm-js-collab/tracing-hooks/hook.mjs'; diff --git a/packages/server-runtime-injection/src/register.ts b/packages/server-runtime-injection/src/register.ts index b5e73dcfbc05..0f759e631659 100644 --- a/packages/server-runtime-injection/src/register.ts +++ b/packages/server-runtime-injection/src/register.ts @@ -301,9 +301,10 @@ export function registerDiagnosticsChannelInjection(): void { // own imports are missing. let hookPath: string; /*! rollup-include-cjs-only */ - // This file is `build/cjs/register.js`; the loader thread needs the ESM build, which shares - // the vendored dependency chunks. - hookPath = join(__dirname, '../esm/hook.js'); + // The CJS build registers the CJS hook. Some tracers (Turbopack) copy + // the hook but do not follow its imports. The CJS hook only requires + // files that this file requires too, so they are always shipped. + hookPath = join(__dirname, 'hook.js'); /*! rollup-include-cjs-only-end */ /*! rollup-include-esm-only */ hookPath = join(dirname(fileURLToPath(import.meta.url)), 'hook.js'); @@ -316,30 +317,11 @@ export function registerDiagnosticsChannelInjection(): void { // hook again, and this line is the only thing that says so. const hookFound = existsSync(hookPath); if (!hookFound) { - debug.warn(`No orchestrion ESM hook at ${hookPath}; falling back to the package specifier.`); + debug.warn(`No orchestrion loader hook at ${hookPath}; falling back to the package specifier.`); } const hookSpecifier = hookFound ? pathToFileURL(hookPath).href : '@sentry/server-runtime-injection/hook'; - if (hookFound) { - // Only `build/esm/package.json` marks the hook and its chunks as ESM. Deployments can drop - // that file, and Vercel disables syntax detection, so Node then parses the hook as CommonJS - // and fails on its `export`s. - // - // This registers a small loader hook before the real one. Its `load` sets - // `format: 'module'` for every URL inside our ESM build directory and passes all other URLs - // through unchanged. Hooks registered earlier also apply when Node loads hook modules - // registered later, so the real hook and its chunks load as ESM even without the marker. - // The loader is inlined as a `data:` URL because Node always loads those as ESM, so it - // cannot fail the same way and needs no file of its own. - const esmDirUrl = `${pathToFileURL(dirname(hookPath)).href}/`; - mod.register( - `data:text/javascript,${encodeURIComponent( - `const d=${JSON.stringify(esmDirUrl)};export async function load(u,c,n){return n(u,u.startsWith(d)?{...c,format:'module'}:c)}`, - )}`, - ); - } - mod.register(hookSpecifier, { parentURL, data: { instrumentations: SENTRY_RUNTIME_INSTRUMENTATIONS, diagnosticsPort }, diff --git a/packages/server-runtime-injection/test/esmMarker.test.ts b/packages/server-runtime-injection/test/esmMarker.test.ts deleted file mode 100644 index 0fe5445f3107..000000000000 --- a/packages/server-runtime-injection/test/esmMarker.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { spawnSync } from 'node:child_process'; -import { cpSync, mkdtempSync, rmSync } from 'node:fs'; -import { join } from 'node:path'; -import { afterAll, describe, expect, it } from 'vitest'; - -/** - * Deployments can drop `build/esm/package.json` (the only `"type": "module"` marker for the hook), - * and Vercel runs Node with syntax detection disabled, so the loader thread then parses the hook as - * CommonJS. Runs against the built files, so it needs the package built. - * - * The copy sits inside this package so `@sentry/*` still resolves from its `node_modules`. - */ -const copyDir = mkdtempSync(join(__dirname, '.esm-marker-')); -cpSync(join(__dirname, '..', 'build'), join(copyDir, 'build'), { recursive: true }); -rmSync(join(copyDir, 'build', 'esm', 'package.json')); - -afterAll(() => { - rmSync(copyDir, { recursive: true, force: true }); -}); - -describe('without the build/esm package.json marker', () => { - it('registers the ESM loader hook', { timeout: 30_000 }, () => { - // Removing `registerHooks` forces the `Module.register()` path, the one that loads the hook on - // Node < 24.13, whatever Node version runs the test. - const script = ` - require('node:module').registerHooks = undefined; - const { registerDiagnosticsChannelInjection } = require(${JSON.stringify(join(copyDir, 'build', 'cjs', 'register.js'))}); - registerDiagnosticsChannelInjection(); - import('data:text/javascript,export default 1').then(() => { - const marker = globalThis.__SENTRY__?.__SENTRY_ORCHESTRION__ ?? globalThis.__SENTRY_ORCHESTRION__; - process.stdout.write(JSON.stringify(marker)); - }); - `; - - const { stdout, stderr } = spawnSync(process.execPath, ['--no-experimental-detect-module', '-e', script], { - encoding: 'utf8', - }); - - expect(stderr).not.toContain('Failed to register diagnostics-channel injection hooks'); - expect(JSON.parse(stdout)).toEqual({ runtime: [] }); - }); -}); diff --git a/packages/server-runtime-injection/test/hook.test.ts b/packages/server-runtime-injection/test/hook.test.ts new file mode 100644 index 000000000000..860e8e82cc93 --- /dev/null +++ b/packages/server-runtime-injection/test/hook.test.ts @@ -0,0 +1,80 @@ +import { spawnSync } from 'node:child_process'; +import { cpSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, resolve } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +/** + * Build tracers can ship the loader hook without the files it imports (Turbopack does), and + * deployments can drop `build/esm/package.json`. The CJS build must therefore register a hook that + * needs nothing from `build/esm`. Runs against the built files, so it needs the package built. + */ +const packageDir = join(__dirname, '..'); + +/** Every file that `entry` reaches through relative `require()` calls. */ +function relativeRequireGraph(entry: string): Set { + const seen = new Set(); + const visit = (file: string): void => { + if (seen.has(file)) { + return; + } + seen.add(file); + for (const [, request] of readFileSync(file, 'utf8').matchAll(/require\(['"](\.[^'"]+)['"]\)/g)) { + visit(resolve(dirname(file), request!)); + } + }; + visit(entry); + return seen; +} + +describe('the CJS loader hook', () => { + // A tracer that copies the hook without following its imports still ships what `register.js` + // requires. So the hook must need nothing else. + it('requires only files that register.js requires too', () => { + const cjsDir = join(packageDir, 'build', 'cjs'); + const registerGraph = relativeRequireGraph(join(cjsDir, 'register.js')); + const hookGraph = relativeRequireGraph(join(cjsDir, 'hook.js')); + + const hookOnly = [...hookGraph].filter(file => !registerGraph.has(file)).map(file => relative(cjsDir, file)); + + expect(hookGraph.size).toBeGreaterThan(1); + expect(hookOnly).toEqual(['hook.js']); + }); +}); + +describe('when a deployment ships only the CJS build', () => { + let copyDir: string; + + // The copy has its own `package.json` so the `@sentry/server-runtime-injection/hook` fallback + // resolves to the copy and not to the real build. + beforeAll(() => { + copyDir = mkdtempSync(join(tmpdir(), 'sentry-cjs-only-')); + cpSync(join(packageDir, 'package.json'), join(copyDir, 'package.json')); + cpSync(join(packageDir, 'build', 'cjs'), join(copyDir, 'build', 'cjs'), { recursive: true }); + }); + + afterAll(() => { + rmSync(copyDir, { recursive: true, force: true }); + }); + + it('registers the loader hook', { timeout: 30_000 }, () => { + // Removing `registerHooks` forces the `Module.register()` path, the one that loads the hook on + // Node < 24.13, whatever Node version runs the test. + const script = ` + require('node:module').registerHooks = undefined; + const { registerDiagnosticsChannelInjection } = require(${JSON.stringify(join(copyDir, 'build', 'cjs', 'register.js'))}); + registerDiagnosticsChannelInjection(); + const marker = globalThis.__SENTRY__?.__SENTRY_ORCHESTRION__ ?? globalThis.__SENTRY_ORCHESTRION__; + process.stdout.write(JSON.stringify(marker)); + `; + + // `NODE_PATH` lets the copy resolve `@sentry/*` from this package's `node_modules`. + const { stdout, stderr } = spawnSync(process.execPath, ['-e', script], { + encoding: 'utf8', + env: { ...process.env, NODE_PATH: join(packageDir, 'node_modules') }, + }); + + expect(stderr).not.toContain('Failed to register diagnostics-channel injection hooks'); + expect(JSON.parse(stdout)).toEqual({ runtime: [] }); + }); +}); diff --git a/packages/server-runtime-injection/test/nftTrace.test.ts b/packages/server-runtime-injection/test/nftTrace.test.ts index 2aa8ff749dbe..659dfdb91570 100644 --- a/packages/server-runtime-injection/test/nftTrace.test.ts +++ b/packages/server-runtime-injection/test/nftTrace.test.ts @@ -20,9 +20,18 @@ async function traceFrom(entry: string): Promise> { return fileList; } -describe.each(['cjs', 'esm'])('the %s build', variant => { +describe('the cjs build', () => { + it('traces the CJS loader hook and the chunks it requires', { timeout: 60_000 }, async () => { + const traced = await traceFrom(`${buildDir}/cjs/register.js`); + + expect(traced).toContain(`${buildDir}/cjs/hook.js`); + expect(traced).toContain(`${buildDir}/cjs/vendored/@apm-js-collab/tracing-hooks/hook.js`); + }); +}); + +describe('the esm build', () => { it('traces the ESM loader hook and the chunks it imports', { timeout: 60_000 }, async () => { - const traced = await traceFrom(`${buildDir}/${variant}/register.js`); + const traced = await traceFrom(`${buildDir}/esm/register.js`); expect(traced).toContain(`${buildDir}/esm/hook.js`); // The hook is ESM. Without this marker the loader thread parses it as CommonJS and fails. From 7b18bf0e16866ebd351b256286ad857bba2ae7f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Fri, 13 Nov 2026 07:40:25 +0100 Subject: [PATCH 053/136] fix(nextjs): Inject build values into instrumentation for an external server SDK (#26292) part of #24830 part of [JS-3835](https://linear.app/getsentry/issue/JS-3835/run-the-nextjs-e2e-suite-on-bun-deno-and-cloudflare-from-one-app) On Turbopack builds, this injects the build release, the dist dir, the base path and a Turbopack flag as globals into `instrumentation.*`. Webpack builds already inject most of them. ## Why Next.js inlines `nextConfig.env` and `process.turbopack` only into code it compiles. When `@sentry/nextjs` is in `serverExternalPackages`, the server SDK had no build release, did not rewrite stack frames of the dist dir and did not set the `turbopack` tag. Co-authored-by: Claude Opus 5.5 --- .../turbopack/constructTurbopackConfig.ts | 6 ++ .../turbopack/generateValueInjectionRules.ts | 14 +++++ .../withSentryConfig/getFinalConfigObject.ts | 1 + .../getFinalConfigObjectBundlerUtils.ts | 2 + packages/nextjs/src/server/index.ts | 3 +- .../constructTurbopackConfig.test.ts | 62 +++++++++++++++++++ .../generateValueInjectionRules.test.ts | 44 ++++++++++++- packages/nextjs/test/serverSdk.test.ts | 9 +++ 8 files changed, 139 insertions(+), 2 deletions(-) diff --git a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts index bd124eec37ba..23294dfa6432 100644 --- a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts +++ b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts @@ -29,6 +29,7 @@ import { generateValueInjectionRules } from './generateValueInjectionRules'; * @param routeManifest - The route manifest object. * @param nextJsVersion - The Next.js version. * @param vercelCronsConfig - The Vercel crons configuration from vercel.json. + * @param releaseName - The release that `withSentryConfig` resolved for this build. * @returns The Turbopack config object. */ export function constructTurbopackConfig({ @@ -37,12 +38,14 @@ export function constructTurbopackConfig({ routeManifest, nextJsVersion, vercelCronsConfig, + releaseName, }: { userNextConfig: NextConfigObject; userSentryOptions?: SentryBuildOptions; routeManifest?: RouteManifest; nextJsVersion?: string; vercelCronsConfig?: VercelCronsConfig; + releaseName?: string; }): TurbopackOptions { // If sourcemaps are disabled, we don't need to enable native debug ids as this will add build time. const shouldEnableNativeDebugIds = @@ -59,6 +62,9 @@ export function constructTurbopackConfig({ nextJsVersion, tunnelRouteValues: getTunnelRouteInjectedValues(userNextConfig, userSentryOptions), vercelCronsConfig, + releaseName, + // Same value as `_sentryRewriteFramesDistDir` in `nextConfig.env` + distDirName: userNextConfig.distDir?.replace(/\\/g, '\\\\') || '.next', basePath: userNextConfig.basePath, }); diff --git a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts index b334a096b1f1..1153c654a8b0 100644 --- a/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts +++ b/packages/nextjs/src/config/turbopack/generateValueInjectionRules.ts @@ -13,12 +13,16 @@ export function generateValueInjectionRules({ nextJsVersion, tunnelRouteValues, vercelCronsConfig, + releaseName, + distDirName, basePath, }: { routeManifest?: RouteManifest; nextJsVersion?: string; tunnelRouteValues?: TunnelRouteInjectedValues; vercelCronsConfig?: VercelCronsConfig; + releaseName?: string; + distDirName?: string; basePath?: string; }): TurbopackMatcherWithRule[] { const rules: TurbopackMatcherWithRule[] = []; @@ -44,6 +48,16 @@ export function generateValueInjectionRules({ if (vercelCronsConfig) { serverValues._sentryVercelCronsConfig = JSON.stringify(vercelCronsConfig); } + // Next.js inlines the values of `nextConfig.env` and `process.turbopack` only into code it compiles. These globals are + // for a server SDK that Next.js does not compile, e.g. one in `serverExternalPackages`. + serverValues._sentryTurbopack = true; + if (releaseName) { + serverValues._sentryRelease = releaseName; + } + if (distDirName) { + serverValues._sentryRewriteFramesDistDir = distDirName; + } + // Inject server modules (matching webpack's __SENTRY_SERVER_MODULES__ behavior) // Use process.cwd() to get the project directory at build time serverValues.__SENTRY_SERVER_MODULES__ = getPackageModules(process.cwd()); diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index 6a2e4b164bb9..c2b712b21247 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -73,6 +73,7 @@ export function getFinalConfigObject( nextJsVersion, bundlerInfo, vercelCronsConfigResult, + releaseName, ); const shouldUseRunAfterProductionCompileHook = resolveUseRunAfterProductionCompileHookOption( diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index 3e266a8fccb8..e43099ed0233 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -107,6 +107,7 @@ export function maybeConstructTurbopackConfig( nextJsVersion: string | undefined, bundlerInfo: BundlerInfo, vercelCronsConfigResult: VercelCronsConfigResult, + releaseName: string | undefined, ): TurbopackOptions | undefined { if (!bundlerInfo.isTurbopack) { return undefined; @@ -121,6 +122,7 @@ export function maybeConstructTurbopackConfig( routeManifest, nextJsVersion, vercelCronsConfig, + releaseName, }); } diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index 1d21332676c3..e2bd19401ac2 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -53,6 +53,7 @@ export { startSpan, startSpanManual, startInactiveSpan } from '../common/utils/n const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewriteFramesDistDir?: string; _sentryRelease?: string; + _sentryTurbopack?: boolean; }; // Call at module level so `next build` prerender workers still register the runner without `init` @@ -236,7 +237,7 @@ export function init(options: NodeOptions): NodeClient | undefined { try { // @ts-expect-error `process.turbopack` is a magic string that will be replaced by Next.js - if (process.turbopack) { + if (process.turbopack || globalWithInjectedValues._sentryTurbopack) { getGlobalScope().setTag('turbopack', true); getGlobalScope().setAttribute('turbopack', true); } diff --git a/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts b/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts index 39aa27f8760a..41cc16398953 100644 --- a/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts +++ b/packages/nextjs/test/config/turbopack/constructTurbopackConfig.test.ts @@ -54,6 +54,38 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', + }, + }, + }, + ], + }, + }, + }); + }); + + it('injects the release and dist dir into the server instrumentation file', () => { + const userNextConfig: NextConfigObject = { distDir: 'build' }; + + const result = constructTurbopackConfig({ + userNextConfig, + userSentryOptions: mockSentryOptions, + releaseName: 'my-app@1.2.3', + }); + + expect(result).toEqual({ + rules: { + '**/instrumentation.*': { + loaders: [ + { + loader: '/mocked/path/to/valueInjectionLoader.js', + options: { + values: { + __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRelease: 'my-app@1.2.3', + _sentryRewriteFramesDistDir: 'build', }, }, }, @@ -92,6 +124,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -178,6 +212,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -229,6 +265,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -312,6 +350,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -357,6 +397,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -399,6 +441,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -439,6 +483,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: '15.0.0', }, }, @@ -495,6 +541,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: '14.0.0', }, }, @@ -538,6 +586,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -604,6 +654,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, }, }, @@ -646,6 +698,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, }, }, @@ -699,6 +753,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, }, }, @@ -746,6 +802,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -772,6 +830,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', }, }, }, @@ -869,6 +929,8 @@ describe('constructTurbopackConfig', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRewriteFramesDistDir: '.next', _sentryNextJsVersion: nextJsVersion, }, }, diff --git a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts index 7885f953ac51..34756d937204 100644 --- a/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts +++ b/packages/nextjs/test/config/turbopack/generateValueInjectionRules.test.ts @@ -35,6 +35,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, }, }, }, @@ -60,6 +61,37 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + }, + }, + }, + ], + }, + }, + ]); + }); + }); + + describe('with server build values', () => { + it('injects the release and dist dir only into the server instrumentation file', () => { + const result = generateValueInjectionRules({ + releaseName: 'my-app@1.2.3', + distDirName: 'build', + }); + + expect(result).toEqual([ + { + matcher: '**/instrumentation.*', + rule: { + loaders: [ + { + loader: '/mocked/path/to/valueInjectionLoader.js', + options: { + values: { + __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, + _sentryRelease: 'my-app@1.2.3', + _sentryRewriteFramesDistDir: 'build', }, }, }, @@ -104,6 +136,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, _sentryNextJsVersion: '14.0.0', }, }, @@ -147,6 +180,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, }, }, }, @@ -186,6 +220,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, }, }, }, @@ -234,6 +269,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, }, }, }, @@ -278,6 +314,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, _sentryNextJsVersion: '14.0.0', }, }, @@ -321,6 +358,7 @@ describe('generateValueInjectionRules', () => { '**/instrumentation.*', { _sentryTunnelRoute: '/monitoring', + _sentryTurbopack: true, __SENTRY_SERVER_MODULES__: expect.any(Object), }, ], @@ -338,7 +376,10 @@ describe('generateValueInjectionRules', () => { ]); expect(injectedValues).toEqual([ ['**/instrumentation-client.*', { _sentryBasePath: '/docs' }], - ['**/instrumentation.*', { _sentryBasePath: '/docs', __SENTRY_SERVER_MODULES__: expect.any(Object) }], + [ + '**/instrumentation.*', + { _sentryBasePath: '/docs', _sentryTurbopack: true, __SENTRY_SERVER_MODULES__: expect.any(Object) }, + ], ]); }); }); @@ -439,6 +480,7 @@ describe('generateValueInjectionRules', () => { options: { values: { __SENTRY_SERVER_MODULES__: expect.any(Object), + _sentryTurbopack: true, }, }, }, diff --git a/packages/nextjs/test/serverSdk.test.ts b/packages/nextjs/test/serverSdk.test.ts index 559cc23e3ca6..45460aa09f70 100644 --- a/packages/nextjs/test/serverSdk.test.ts +++ b/packages/nextjs/test/serverSdk.test.ts @@ -47,6 +47,7 @@ describe('Server init()', () => { delete process.env.VERCEL; delete (process as { turbopack?: boolean }).turbopack; delete (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRelease?: string })._sentryRelease; + delete (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryTurbopack?: boolean })._sentryTurbopack; }); it('inits the Node SDK', () => { @@ -223,6 +224,14 @@ describe('Server init()', () => { expect(second).toBe(first); }); + it('sets the `turbopack` tag when the Turbopack build injected `_sentryTurbopack`', () => { + (GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryTurbopack?: boolean })._sentryTurbopack = true; + + init({}); + + expect(getGlobalScope().getScopeData().tags.turbopack).toBe(true); + }); + it('skips init on Cloudflare Workers in a request of `withSentry` from `@sentry/cloudflare`', () => { vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }); setAsyncLocalStorageAsyncContextStrategy(); From c76d196a38197c548646f9cb034498c57374cd56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Fri, 13 Nov 2026 07:40:26 +0100 Subject: [PATCH 054/136] fix(nextjs): Run Turbopack loaders in worker threads on Bun (#26293) part of #24830 part of [JS-3835](https://linear.app/getsentry/issue/JS-3835/run-the-nextjs-e2e-suite-on-bun-deno-and-cloudflare-from-one-app) On Bun, `withSentryConfig` now sets `experimental.turbopackPluginRuntimeStrategy: 'workerThreads'` for Turbopack builds on Next.js 16.2 and newer, unless the user set it. ## Why `bun --bun next build` fails or hangs when the config has a Turbopack loader, and `withSentryConfig` always adds one. Next.js runs loaders in `node` processes and puts `process.execArgv` into their `NODE_OPTIONS`. On Bun, that contains `--bun`, which Node.js rejects. ## Known issues - Bun 1.3 crashes in worker threads when `applicationKey` is set. Bun 1.4 works. - Next.js 16.1 and older do not have the option, so Bun builds with Turbopack still fail there. Webpack builds work. --------- Co-authored-by: Claude Opus 5.5 --- packages/nextjs/src/config/types.ts | 1 + .../withSentryConfig/getFinalConfigObject.ts | 7 ++ .../getFinalConfigObjectUtils.ts | 33 +++++++++ ...rbopackPluginRuntimeStrategyOption.test.ts | 72 +++++++++++++++++++ 4 files changed, 113 insertions(+) create mode 100644 packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts diff --git a/packages/nextjs/src/config/types.ts b/packages/nextjs/src/config/types.ts index d4a2da1c56a3..7a95a339226b 100644 --- a/packages/nextjs/src/config/types.ts +++ b/packages/nextjs/src/config/types.ts @@ -55,6 +55,7 @@ export type NextConfigObject = { clientTraceMetadata?: string[]; serverComponentsExternalPackages?: string[]; // next < v15.0.0 sri?: { algorithm?: string }; + turbopackPluginRuntimeStrategy?: 'workerThreads' | 'childProcesses'; // next >= v16.2.0 }; productionBrowserSourceMaps?: boolean; // https://nextjs.org/docs/pages/api-reference/next-config-js/env diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts index c2b712b21247..9c14edd38976 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObject.ts @@ -24,6 +24,7 @@ import { maybeGetVercelCronsConfig, maybeSetClientTraceMetadataOption, maybeSetInstrumentationHookOption, + maybeSetTurbopackPluginRuntimeStrategyOption, maybeSetUpTunnelRouteRewriteRules, resolveReleaseName, shouldReturnEarlyInExperimentalBuildMode, @@ -61,6 +62,12 @@ export function getFinalConfigObject( warnIfMissingInstrumentationFile(incomingUserNextConfigObject, userSentryOptions); const bundlerInfo = getBundlerInfo(nextJsVersion); + maybeSetTurbopackPluginRuntimeStrategyOption( + incomingUserNextConfigObject, + nextJsVersion, + bundlerInfo.isTurbopack, + userSentryOptions.silent, + ); maybeWarnAboutUnsupportedTurbopack(nextJsVersion, bundlerInfo, userSentryOptions.silent); maybeWarnAboutTurbopackModuleMetadata(userSentryOptions, bundlerInfo); maybeWarnAboutApplicationKeyExcludeDependencies(userSentryOptions, bundlerInfo); diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts index 813f24b58df7..91e33d4d85c2 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts @@ -18,6 +18,39 @@ let showedExperimentalBuildModeWarning = false; const MISSING_INSTRUMENTATION_FILE_WARNING_SHOWN = '__SENTRY_MISSING_INSTRUMENTATION_FILE_WARNING_SHOWN__'; +/** + * Sets `experimental.turbopackPluginRuntimeStrategy` to `'workerThreads'` for Turbopack builds on Bun. + * + * With the default `'childProcesses'`, Next.js runs Turbopack loaders in `node` processes and puts `process.execArgv` + * into their `NODE_OPTIONS`. On Bun, `execArgv` contains `--bun`, which Node.js does not accept, so the build fails or + * hangs. `withSentryConfig` always adds loaders. + */ +export function maybeSetTurbopackPluginRuntimeStrategyOption( + incomingUserNextConfigObject: NextConfigObject, + nextJsVersion: string | undefined, + isTurbopack: boolean, + silent?: boolean, +): void { + if (!process.versions.bun || !isTurbopack || !nextJsVersion) { + return; + } + + const { major, minor } = parseSemver(nextJsVersion); + if (major === undefined || minor === undefined || major < 16 || (major === 16 && minor < 2)) { + return; + } + + if (incomingUserNextConfigObject.experimental?.turbopackPluginRuntimeStrategy === 'childProcesses') { + getBuildLogger(silent).warn( + '[@sentry/nextjs] `experimental.turbopackPluginRuntimeStrategy` is set to `childProcesses`. Turbopack builds on Bun fail or hang with this strategy. Remove the option, or set it to `workerThreads`.', + ); + return; + } + + incomingUserNextConfigObject.experimental = incomingUserNextConfigObject.experimental || {}; + incomingUserNextConfigObject.experimental.turbopackPluginRuntimeStrategy ??= 'workerThreads'; +} + /** * Resolves the Sentry release name to use for build-time behavior. * diff --git a/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts b/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts new file mode 100644 index 000000000000..3b32d2456c28 --- /dev/null +++ b/packages/nextjs/test/config/maybeSetTurbopackPluginRuntimeStrategyOption.test.ts @@ -0,0 +1,72 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { NextConfigObject } from '../../src/config/types'; +import { maybeSetTurbopackPluginRuntimeStrategyOption } from '../../src/config/withSentryConfig/getFinalConfigObjectUtils'; + +const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!; + +describe('maybeSetTurbopackPluginRuntimeStrategyOption', () => { + afterEach(() => { + Object.defineProperty(process, 'versions', originalVersions); + vi.restoreAllMocks(); + }); + + it.each(['16.2.0', '16.3.8', '17.0.0'])( + 'runs Turbopack loaders in worker threads on Bun with Next.js %s', + version => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + const config: NextConfigObject = {}; + + maybeSetTurbopackPluginRuntimeStrategyOption(config, version, true); + + expect(config.experimental).toEqual({ turbopackPluginRuntimeStrategy: 'workerThreads' }); + }, + ); + + it('keeps `childProcesses` when the user set it, and warns', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const config: NextConfigObject = { experimental: { turbopackPluginRuntimeStrategy: 'childProcesses' } }; + + maybeSetTurbopackPluginRuntimeStrategyOption(config, '16.2.0', true); + + expect(config.experimental).toEqual({ turbopackPluginRuntimeStrategy: 'childProcesses' }); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith( + '[@sentry/nextjs] `experimental.turbopackPluginRuntimeStrategy` is set to `childProcesses`. Turbopack builds on Bun fail or hang with this strategy. Remove the option, or set it to `workerThreads`.', + ); + }); + + it('does not warn about `childProcesses` when `silent` is set', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const config: NextConfigObject = { experimental: { turbopackPluginRuntimeStrategy: 'childProcesses' } }; + + maybeSetTurbopackPluginRuntimeStrategyOption(config, '16.2.0', true, true); + + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('does not warn about `childProcesses` on Node.js', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const config: NextConfigObject = { experimental: { turbopackPluginRuntimeStrategy: 'childProcesses' } }; + + maybeSetTurbopackPluginRuntimeStrategyOption(config, '16.2.0', true); + + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it.each([ + { name: 'on Node.js', bun: undefined, version: '16.2.0', isTurbopack: true }, + { name: 'with webpack', bun: '1.4.2', version: '16.2.0', isTurbopack: false }, + { name: 'on Next.js 16.1, which does not know the option', bun: '1.4.2', version: '16.1.6', isTurbopack: true }, + { name: 'on Next.js 15', bun: '1.4.2', version: '15.5.4', isTurbopack: true }, + { name: 'without a Next.js version', bun: '1.4.2', version: undefined, isTurbopack: true }, + ])('does not set the strategy $name', ({ bun, version, isTurbopack }) => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun } }); + const config: NextConfigObject = {}; + + maybeSetTurbopackPluginRuntimeStrategyOption(config, version, isTurbopack); + + expect(config.experimental).toBeUndefined(); + }); +}); From 8fff8bf45c3d59532110635907b19b9c2d468e03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Fri, 13 Nov 2026 07:40:26 +0100 Subject: [PATCH 055/136] feat(nextjs): Use the Bun integrations when Next.js runs on Bun (#26294) part of #24830 part of [JS-3835](https://linear.app/getsentry/issue/JS-3835/run-the-nextjs-e2e-suite-on-bun-deno-and-cloudflare-from-one-app) This adds a `bun` export condition to `@sentry/nextjs`. On Bun, `init` adds the fetch integration and `bunHttpServerIntegration` of `@sentry/bun` and reports Bun as the runtime. When `next build` runs on Bun, `withSentryConfig` makes `@sentry/nextjs` external, so Bun resolves it at run time and loads this entry. `@sentry/bun` is an optional peer dependency: ```sh bun add @sentry/bun bun --bun next build bun --bun next start ``` ## Why Without these integrations, all requests on Bun shared one trace and outgoing `fetch` calls had no spans, unless users added them by hand. ## CI decisions The e2e jobs now use Bun 1.4.2, not 1.3.14. Bun 1.3 crashes in the Turbopack build when `applicationKey` is set. The alternative is a Bun version for each e2e variant. ## Known issues - An app built on Node.js and started on Bun gets the Node.js entry. - vinext bundles `@sentry/nextjs`, so vinext apps on Bun must add it to the `rsc` externals of Vite. - Without `@sentry/bun` installed, an app that loads the Bun entry fails at start. Co-authored-by: Claude Opus 5.5 --- .github/actions/prepare-e2e-test/action.yml | 2 +- .../test-applications/nextjs-16/package.json | 4 +- .../nextjs-16/sentry.server.config.ts | 4 -- .../nextjs-16/tests/route-handler.test.ts | 4 +- .../nextjs-16/vite.config.mts | 11 +++- packages/nextjs/package.json | 11 ++++ packages/nextjs/rollup.npm.config.mjs | 1 + packages/nextjs/src/config/types.ts | 2 + .../getFinalConfigObjectBundlerUtils.ts | 5 ++ packages/nextjs/src/index.bun.ts | 26 ++++++++ packages/nextjs/test/bunSdk.test.ts | 62 +++++++++++++++++++ .../diagnosticsChannelInjection.test.ts | 34 +++++++++- pnpm-lock.yaml | 3 + 13 files changed, 159 insertions(+), 10 deletions(-) create mode 100644 packages/nextjs/src/index.bun.ts create mode 100644 packages/nextjs/test/bunSdk.test.ts diff --git a/.github/actions/prepare-e2e-test/action.yml b/.github/actions/prepare-e2e-test/action.yml index d81386521507..e7576ac001fc 100644 --- a/.github/actions/prepare-e2e-test/action.yml +++ b/.github/actions/prepare-e2e-test/action.yml @@ -35,7 +35,7 @@ runs: == 'bun' uses: oven-sh/setup-bun@v2 with: - bun-version: ${{ inputs.bun-version || '1.3.14' }} + bun-version: ${{ inputs.bun-version || '1.4.2' }} - name: Set up AWS SAM if: contains(inputs.test-application, 'aws-serverless') uses: aws-actions/setup-sam@v3 diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json index aa1116924f00..4d98c3b37382 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json @@ -25,7 +25,8 @@ "test:build-latest:cloudflare": "pnpm install && pnpm add next@latest && opennextjs-cloudflare build --config wrangler.opennext.jsonc", "start:cloudflare": "opennextjs-cloudflare preview --config wrangler.opennext.jsonc --var \"E2E_TEST_DSN:$E2E_TEST_DSN\"", "test:build:vinext": "pnpm install && pnpm add react@19.3.1 react-dom@19.3.1 && npm pkg set type=module && vinext build", - "test:assert:vinext": "VINEXT=1 pnpm test:prod" + "test:assert:vinext": "VINEXT=1 pnpm test:prod", + "test:build:bun": "pnpm install && bun --bun ./node_modules/next/dist/bin/next build" }, "//": "Pin `ioredis` to 5.10.1: it's the last version before the driver publishes its own native diagnostics channels; orchestrion's config covers `ioredis <5.11.0`.", "dependencies": { @@ -111,6 +112,7 @@ }, { "runtime": "bun", + "build-command": "pnpm test:build:bun", "assert-command": "pnpm test:prod", "label": "nextjs-16 (bun)" }, diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts index f0ec19dd256d..e416e7e6a255 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts @@ -1,4 +1,3 @@ -import { bunHttpServerIntegration, fetchIntegration as bunFetchIntegration } from '@sentry/bun'; import { fetchIntegration as denoFetchIntegration } from '@sentry/deno'; import * as Sentry from '@sentry/nextjs'; import { Log } from '@sentry/nextjs'; @@ -14,9 +13,6 @@ Sentry.init({ integrations: [ Sentry.vercelAIIntegration(), Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 1_000 }), - // Bun does not emit the `node:http` diagnostics channel the Node SDK uses to isolate incoming requests, so each - // request would otherwise share one trace. Next.js emits its own server spans, hence `spans: false`. - ...(process.versions.bun ? [bunHttpServerIntegration({ spans: false }), bunFetchIntegration()] : []), // The `fetch` of Deno is not undici, so the Node SDK does not see outgoing requests. ...(process.versions.deno ? [denoFetchIntegration()] : []), ], diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts index 31936d435283..330e62f79cff 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts @@ -1,5 +1,5 @@ import test, { expect } from '@playwright/test'; -import { getSpanOp, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { getRuntime, getSpanOp, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils'; import { isTurbopackDevMode } from './isDevMode'; test('Should create a span for node route handlers', async ({ request }) => { @@ -61,6 +61,8 @@ test('Should report an error with a parameterized span name for a throwing route // Error should carry the parameterized transaction name expect(errorEvent.transaction).toBe('GET /route-handler/[xoxo]/error'); + // `@sentry/nextjs` has no Deno entry, so Deno runs the Node.js entry. + expect(errorEvent.contexts?.runtime?.name).toBe(getRuntime() === 'deno' ? 'node' : getRuntime()); // Span should have parameterized name and an error status expect(span.name).toBe('GET /route-handler/[xoxo]/error'); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/vite.config.mts b/dev-packages/e2e-tests/test-applications/nextjs-16/vite.config.mts index 06fc7d855003..d816a23bc9cf 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/vite.config.mts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/vite.config.mts @@ -7,6 +7,13 @@ import { defineConfig } from 'vite'; export default defineConfig({ plugins: [vinext()], // `app/api/d1` imports `@opennextjs/cloudflare` for the OpenNext variants. Its `import()` of a computed specifier can - // not be bundled. - environments: { rsc: { resolve: { external: ['@opennextjs/cloudflare'] } } }, + // not be bundled. On Bun, `@sentry/nextjs` is external so that Bun resolves it at run time and loads its Bun entry. + // Node.js would load its CommonJS build from ESM, which hides the re-exported names. + environments: { + rsc: { + resolve: { + external: ['@opennextjs/cloudflare', ...(process.env.RUNTIME === 'bun' ? ['@sentry/nextjs'] : [])], + }, + }, + }, }); diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 143daed53d6e..735207696da7 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -43,6 +43,10 @@ "import": "./build/esm/index.client.js", "require": "./build/cjs/index.client.js" }, + "bun": { + "import": "./build/esm/index.bun.js", + "require": "./build/cjs/index.bun.js" + }, "node": "./build/cjs/index.server.js", "import": "./build/esm/index.server.js" }, @@ -100,14 +104,21 @@ }, "devDependencies": { "@sentry-internal/rollup-utils": "11.12.0", + "@sentry/bun": "11.12.0", "cjs-module-lexer": "^2.2.0", "next": "15.5.28", "react": "^18.3.1", "react-dom": "^18.3.1" }, "peerDependencies": { + "@sentry/bun": "11.12.0", "next": "^14.0 || ^15.0.0-rc.0 || ^16.0.0-0" }, + "peerDependenciesMeta": { + "@sentry/bun": { + "optional": true + } + }, "scripts": { "build": "run-p build:transpile build:types", "build:dev": "pnpm run build", diff --git a/packages/nextjs/rollup.npm.config.mjs b/packages/nextjs/rollup.npm.config.mjs index 104dc8087894..46157f68d4d6 100644 --- a/packages/nextjs/rollup.npm.config.mjs +++ b/packages/nextjs/rollup.npm.config.mjs @@ -7,6 +7,7 @@ export default [ // doesn't automatically include it when calculating the module dependency tree. entrypoints: [ 'src/index.server.ts', + 'src/index.bun.ts', 'src/index.client.ts', 'src/client/index.ts', 'src/server/index.ts', diff --git a/packages/nextjs/src/config/types.ts b/packages/nextjs/src/config/types.ts index 7a95a339226b..b8957d083c4b 100644 --- a/packages/nextjs/src/config/types.ts +++ b/packages/nextjs/src/config/types.ts @@ -49,6 +49,8 @@ export type NextConfigObject = { } >; cacheComponents?: boolean; + // Packages that Next.js compiles, also in `node_modules` + transpilePackages?: string[]; // Next.js experimental options experimental?: { instrumentationHook?: boolean; diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index e43099ed0233..e823d575c456 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -299,6 +299,11 @@ export function getServerExternalPackagesPatch( ...(userProvided || []), ...defaults, ...(buildTimeInstrumentation ? ORCHESTRION_RUNTIME_EXTERNAL_PACKAGES : []), + // Next.js resolves bundled packages without the `bun` export condition. When it is external, Bun resolves + // `@sentry/nextjs` at run time and loads its Bun entry. + ...(process.versions.bun && !incomingUserNextConfigObject.transpilePackages?.includes('@sentry/nextjs') + ? ['@sentry/nextjs'] + : []), ]; }; diff --git a/packages/nextjs/src/index.bun.ts b/packages/nextjs/src/index.bun.ts new file mode 100644 index 000000000000..76a9688b9b8a --- /dev/null +++ b/packages/nextjs/src/index.bun.ts @@ -0,0 +1,26 @@ +import { bunHttpServerIntegration, fetchIntegration } from '@sentry/bun'; +import type { NodeClient, NodeOptions } from '@sentry/node'; +import { init as initServer } from './server'; + +export * from './server'; + +/** Inits the Sentry Next.js SDK on Bun, with the integrations of `@sentry/bun` for what Bun does differently. */ +export function init(options: NodeOptions): NodeClient | undefined { + const userIntegrations = options.integrations; + return initServer({ + runtime: { name: 'bun', version: process.versions.bun as string }, + ...options, + integrations: defaults => { + const integrations = [ + // The `fetch` of Bun is not undici. + ...defaults.filter(integration => integration.name !== 'NodeFetch'), + fetchIntegration(), + // Bun does not publish `http.server.request.start`. Next.js creates its own request spans. + bunHttpServerIntegration({ spans: false }), + ]; + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations || [])]; + }, + }); +} diff --git a/packages/nextjs/test/bunSdk.test.ts b/packages/nextjs/test/bunSdk.test.ts new file mode 100644 index 000000000000..bd760d239fe5 --- /dev/null +++ b/packages/nextjs/test/bunSdk.test.ts @@ -0,0 +1,62 @@ +import type { Integration } from '@sentry/core'; +import { GLOBAL_OBJ, getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { init } from '../src/index.bun'; + +// normally this is set as part of the build process, so mock it here +(GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewriteFramesDistDir: string })._sentryRewriteFramesDistDir = '.next'; + +const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!; + +// Without a DSN, the client does not set up its integrations, so these tests do not patch `node:http`. +describe('Bun init()', () => { + afterEach(() => { + Object.defineProperty(process, 'versions', originalVersions); + getMainCarrier().__SENTRY__ = undefined; + }); + + it('reports Bun as the runtime', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + + const client = init({}); + + expect(client?.getOptions().runtime).toEqual({ name: 'bun', version: '1.4.2' }); + }); + + it('replaces the undici fetch integration with the fetch and HTTP server integrations of Bun', () => { + const client = init({}); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer'].includes(name)), + ).toEqual(['Fetch', 'BunHttpServer']); + }); + + it('adds the integrations that the user passes as an array', () => { + const userIntegration: Integration = { name: 'UserIntegration' }; + + const client = init({ integrations: [userIntegration] }); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer', 'UserIntegration'].includes(name)), + ).toEqual(['Fetch', 'BunHttpServer', 'UserIntegration']); + }); + + it('passes the Bun integrations to an integrations function of the user', () => { + const client = init({ + integrations: integrations => integrations.filter(integration => integration.name !== 'BunHttpServer'), + }); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch', 'BunHttpServer'].includes(name)), + ).toEqual(['Fetch']); + }); +}); diff --git a/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts b/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts index effe24b8bef8..144637d124d0 100644 --- a/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts +++ b/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; import { isAbsolute } from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { BUNDLE_SAFE_INSTRUMENTED_PACKAGES, externalizeOrchestrionRuntimePackages, @@ -58,6 +58,38 @@ describe('getServerExternalPackagesPatch (build-time instrumentation)', () => { }); }); +describe('getServerExternalPackagesPatch (Bun)', () => { + const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!; + + afterEach(() => { + Object.defineProperty(process, 'versions', originalVersions); + }); + + it('makes @sentry/nextjs external when the build runs on Bun', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + + const patch = getServerExternalPackagesPatch({}, 16, false); + + expect(patch.serverExternalPackages).toContain('@sentry/nextjs'); + }); + + it('keeps @sentry/nextjs bundled on Bun when it is in transpilePackages', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); + + const patch = getServerExternalPackagesPatch({ transpilePackages: ['@sentry/nextjs'] }, 16, false); + + expect(patch.serverExternalPackages).not.toContain('@sentry/nextjs'); + }); + + it('keeps @sentry/nextjs bundled when the build runs on Node.js', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: undefined } }); + + const patch = getServerExternalPackagesPatch({}, 16, false); + + expect(patch.serverExternalPackages).not.toContain('@sentry/nextjs'); + }); +}); + describe('externalizeOrchestrionRuntimePackages', () => { // An absolute path here breaks every deploy that relocates the output, so it has to stay bare. it.each([ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d0e92cbee61e..608007d77333 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1617,6 +1617,9 @@ importers: '@sentry-internal/rollup-utils': specifier: 11.12.0 version: link:../../dev-packages/rollup-utils + '@sentry/bun': + specifier: 11.12.0 + version: link:../bun cjs-module-lexer: specifier: ^2.2.0 version: 2.2.0 From c9e61e3d3d3b6686dc8560903e1c1ce4fffbeb1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Fri, 13 Nov 2026 07:40:26 +0100 Subject: [PATCH 056/136] feat(nextjs): Use the Deno fetch integration when Next.js runs on Deno (#26295) closes #24830 closes [JS-3835](https://linear.app/getsentry/issue/JS-3835/run-the-nextjs-e2e-suite-on-bun-deno-and-cloudflare-from-one-app) ## Description This adds a `deno` export condition to `@sentry/nextjs`. On Deno, `init` uses the fetch integration of `@sentry/deno` and reports Deno as the runtime. When `next build` runs on Deno, `withSentryConfig` makes `@sentry/nextjs` external. The `nextjs-16 (deno)` e2e variant is now required. `@sentry/deno` is an optional peer dependency: ```sh deno add npm:@sentry/deno deno run -A npm:next build deno run -A --conditions=deno npm:next start ``` ## Why Outgoing `fetch` calls had no spans on Deno, unless users added the integration by hand. ## Deno decisions Next.js loads the external SDK with `require`, and Deno applies the `deno` condition to `require` only with `--conditions=deno`. The alternative is a lazy `require` of `@sentry/deno` in the Node.js entry. `@sentry/deno` also gets a `default` export condition, so Deno can load it from CommonJS. ## Known issues - Without `--conditions=deno`, the app runs with the Node.js entry and has no `fetch` spans. - An app built on Node.js and started on Deno gets the Node.js entry. --------- Co-authored-by: Claude Fable 5.2 --- dev-packages/e2e-tests/README.md | 6 +- .../test-applications/nextjs-16/package.json | 16 ++--- .../nextjs-16/playwright.config.mjs | 2 +- .../nextjs-16/sentry.server.config.ts | 8 +-- .../nextjs-16/tests/route-handler.test.ts | 3 +- packages/deno/package.json | 3 +- packages/nextjs/package.json | 9 +++ packages/nextjs/rollup.npm.config.mjs | 1 + .../getFinalConfigObjectBundlerUtils.ts | 7 ++- packages/nextjs/src/index.deno.ts | 24 +++++++ .../diagnosticsChannelInjection.test.ts | 10 ++- packages/nextjs/test/denoSdk.test.ts | 62 +++++++++++++++++++ pnpm-lock.yaml | 3 + 13 files changed, 129 insertions(+), 25 deletions(-) create mode 100644 packages/nextjs/src/index.deno.ts create mode 100644 packages/nextjs/test/denoSdk.test.ts diff --git a/dev-packages/e2e-tests/README.md b/dev-packages/e2e-tests/README.md index 8c9d38ed0607..52e30cf48569 100644 --- a/dev-packages/e2e-tests/README.md +++ b/dev-packages/e2e-tests/README.md @@ -173,9 +173,9 @@ is the reference setup. (`instrument.mjs`), Bun `@sentry/bun` (`instrument.bun.mjs`), Deno `@sentry/deno` (`instrument.deno.mjs`) and Cloudflare `@sentry/cloudflare`. The framework SDK only provides the framework wrappers on the other runtimes, so values that come from its `init()` (`sdk.name`, default integrations) are Node-only. Next.js is different: it loads - `instrumentation.ts` on every runtime, so `nextjs-16` calls `init()` of `@sentry/nextjs` on Bun and Deno too, and - adds the integrations of `@sentry/bun` or `@sentry/deno` that replace the Node instrumentation those runtimes do not - trigger. + `instrumentation.ts` on every runtime, so `nextjs-16` calls `init()` of `@sentry/nextjs` on Bun and Deno too. Its + Bun and Deno variants build the app on that runtime, so `@sentry/nextjs` loads its `bun` or `deno` entry, which adds + the integrations of `@sentry/bun` or `@sentry/deno`. - **Start commands**: `playwright.config.mjs` selects the start command with `getRuntime()`. Bun and Deno use the same build as Node and only change the start command, for example `bun --bun --preload ./instrument.bun.mjs ./node_modules/@react-router/serve/bin.cjs ./build/server/index.js` and diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json index 4d98c3b37382..e9b9a7b766be 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json @@ -26,7 +26,8 @@ "start:cloudflare": "opennextjs-cloudflare preview --config wrangler.opennext.jsonc --var \"E2E_TEST_DSN:$E2E_TEST_DSN\"", "test:build:vinext": "pnpm install && pnpm add react@19.3.1 react-dom@19.3.1 && npm pkg set type=module && vinext build", "test:assert:vinext": "VINEXT=1 pnpm test:prod", - "test:build:bun": "pnpm install && bun --bun ./node_modules/next/dist/bin/next build" + "test:build:bun": "pnpm install && bun --bun ./node_modules/next/dist/bin/next build", + "test:build:deno": "pnpm install && deno run -A ./node_modules/next/dist/bin/next build" }, "//": "Pin `ioredis` to 5.10.1: it's the last version before the driver publishes its own native diagnostics channels; orchestrion's config covers `ioredis <5.11.0`.", "dependencies": { @@ -121,6 +122,13 @@ "build-command": "pnpm test:build:cloudflare", "assert-command": "pnpm test:prod", "label": "nextjs-16 (cloudflare)" + }, + { + "runtime": "deno", + "build-command": "pnpm test:build:deno", + "assert-command": "pnpm test:prod", + "deno-version": "v2.9.0", + "label": "nextjs-16 (deno)" } ], "optionalVariants": [ @@ -130,12 +138,6 @@ "assert-command": "pnpm test:prod", "label": "nextjs-16 (cloudflare, latest)" }, - { - "runtime": "deno", - "assert-command": "pnpm test:prod", - "deno-version": "v2.9.0", - "label": "nextjs-16 (deno)" - }, { "build-command": "pnpm test:build:vinext", "assert-command": "pnpm test:assert:vinext", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs index 0d18ae12efc4..7611f4a90d98 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/playwright.config.mjs @@ -8,7 +8,7 @@ if (!testEnv) { const productionStartCommands = { node: 'pnpm next start -p 3030', bun: 'bun --bun ./node_modules/next/dist/bin/next start -p 3030', - deno: 'deno run -A ./node_modules/next/dist/bin/next start -p 3030', + deno: 'deno run -A --conditions=deno ./node_modules/next/dist/bin/next start -p 3030', cloudflare: 'pnpm start:cloudflare --port 3030', }; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts index e416e7e6a255..0bf1422aa2b4 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/sentry.server.config.ts @@ -1,4 +1,3 @@ -import { fetchIntegration as denoFetchIntegration } from '@sentry/deno'; import * as Sentry from '@sentry/nextjs'; import { Log } from '@sentry/nextjs'; @@ -10,12 +9,7 @@ Sentry.init({ _flushInterval: 100, tracePropagationTargets: ['http://localhost:3030/propagation/test-outgoing-fetch/check'], // debug: true, - integrations: [ - Sentry.vercelAIIntegration(), - Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 1_000 }), - // The `fetch` of Deno is not undici, so the Node SDK does not see outgoing requests. - ...(process.versions.deno ? [denoFetchIntegration()] : []), - ], + integrations: [Sentry.vercelAIIntegration(), Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 1_000 })], // Verify Log type is available beforeSendLog(log: Log) { return log; diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts index 330e62f79cff..2cd08fbd2637 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/route-handler.test.ts @@ -61,8 +61,7 @@ test('Should report an error with a parameterized span name for a throwing route // Error should carry the parameterized transaction name expect(errorEvent.transaction).toBe('GET /route-handler/[xoxo]/error'); - // `@sentry/nextjs` has no Deno entry, so Deno runs the Node.js entry. - expect(errorEvent.contexts?.runtime?.name).toBe(getRuntime() === 'deno' ? 'node' : getRuntime()); + expect(errorEvent.contexts?.runtime?.name).toBe(getRuntime()); // Span should have parameterized name and an error status expect(span.name).toBe('GET /route-handler/[xoxo]/error'); diff --git a/packages/deno/package.json b/packages/deno/package.json index 1e5bfb5c84ef..b178b8849767 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -14,7 +14,8 @@ "import": { "types": "./build/esm/index.d.ts", "default": "./build/esm/index.js" - } + }, + "default": "./build/esm/index.js" }, "./import": { "import": "./build/import.mjs" diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 735207696da7..7dde0daa81d2 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -47,6 +47,10 @@ "import": "./build/esm/index.bun.js", "require": "./build/cjs/index.bun.js" }, + "deno": { + "import": "./build/esm/index.deno.js", + "require": "./build/cjs/index.deno.js" + }, "node": "./build/cjs/index.server.js", "import": "./build/esm/index.server.js" }, @@ -105,6 +109,7 @@ "devDependencies": { "@sentry-internal/rollup-utils": "11.12.0", "@sentry/bun": "11.12.0", + "@sentry/deno": "11.12.0", "cjs-module-lexer": "^2.2.0", "next": "15.5.28", "react": "^18.3.1", @@ -112,11 +117,15 @@ }, "peerDependencies": { "@sentry/bun": "11.12.0", + "@sentry/deno": "11.12.0", "next": "^14.0 || ^15.0.0-rc.0 || ^16.0.0-0" }, "peerDependenciesMeta": { "@sentry/bun": { "optional": true + }, + "@sentry/deno": { + "optional": true } }, "scripts": { diff --git a/packages/nextjs/rollup.npm.config.mjs b/packages/nextjs/rollup.npm.config.mjs index 46157f68d4d6..18ebb16b02ec 100644 --- a/packages/nextjs/rollup.npm.config.mjs +++ b/packages/nextjs/rollup.npm.config.mjs @@ -8,6 +8,7 @@ export default [ entrypoints: [ 'src/index.server.ts', 'src/index.bun.ts', + 'src/index.deno.ts', 'src/index.client.ts', 'src/client/index.ts', 'src/server/index.ts', diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index e823d575c456..4240231dbc13 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -299,9 +299,10 @@ export function getServerExternalPackagesPatch( ...(userProvided || []), ...defaults, ...(buildTimeInstrumentation ? ORCHESTRION_RUNTIME_EXTERNAL_PACKAGES : []), - // Next.js resolves bundled packages without the `bun` export condition. When it is external, Bun resolves - // `@sentry/nextjs` at run time and loads its Bun entry. - ...(process.versions.bun && !incomingUserNextConfigObject.transpilePackages?.includes('@sentry/nextjs') + // Next.js resolves bundled packages without the `bun` and `deno` export conditions. When it is external, Bun and + // Deno resolve `@sentry/nextjs` at run time and load their entry. + ...((process.versions.bun || process.versions.deno) && + !incomingUserNextConfigObject.transpilePackages?.includes('@sentry/nextjs') ? ['@sentry/nextjs'] : []), ]; diff --git a/packages/nextjs/src/index.deno.ts b/packages/nextjs/src/index.deno.ts new file mode 100644 index 000000000000..3c48c4da5819 --- /dev/null +++ b/packages/nextjs/src/index.deno.ts @@ -0,0 +1,24 @@ +import { fetchIntegration } from '@sentry/deno'; +import type { NodeClient, NodeOptions } from '@sentry/node'; +import { init as initServer } from './server'; + +export * from './server'; + +/** Inits the Sentry Next.js SDK on Deno, with the integrations of `@sentry/deno` for what Deno does differently. */ +export function init(options: NodeOptions): NodeClient | undefined { + const userIntegrations = options.integrations; + return initServer({ + runtime: { name: 'deno', version: process.versions.deno as string }, + ...options, + integrations: defaults => { + const integrations = [ + // The `fetch` of Deno is not undici. + ...defaults.filter(integration => integration.name !== 'NodeFetch'), + fetchIntegration(), + ]; + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations || [])]; + }, + }); +} diff --git a/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts b/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts index 144637d124d0..603dc9e89f55 100644 --- a/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts +++ b/packages/nextjs/test/config/diagnosticsChannelInjection.test.ts @@ -58,7 +58,7 @@ describe('getServerExternalPackagesPatch (build-time instrumentation)', () => { }); }); -describe('getServerExternalPackagesPatch (Bun)', () => { +describe('getServerExternalPackagesPatch (Bun and Deno)', () => { const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!; afterEach(() => { @@ -73,6 +73,14 @@ describe('getServerExternalPackagesPatch (Bun)', () => { expect(patch.serverExternalPackages).toContain('@sentry/nextjs'); }); + it('makes @sentry/nextjs external when the build runs on Deno', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, deno: '2.9.0' } }); + + const patch = getServerExternalPackagesPatch({}, 16, false); + + expect(patch.serverExternalPackages).toContain('@sentry/nextjs'); + }); + it('keeps @sentry/nextjs bundled on Bun when it is in transpilePackages', () => { Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, bun: '1.4.2' } }); diff --git a/packages/nextjs/test/denoSdk.test.ts b/packages/nextjs/test/denoSdk.test.ts new file mode 100644 index 000000000000..b320c4ab172d --- /dev/null +++ b/packages/nextjs/test/denoSdk.test.ts @@ -0,0 +1,62 @@ +import type { Integration } from '@sentry/core'; +import { GLOBAL_OBJ, getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { init } from '../src/index.deno'; + +// normally this is set as part of the build process, so mock it here +(GLOBAL_OBJ as typeof GLOBAL_OBJ & { _sentryRewriteFramesDistDir: string })._sentryRewriteFramesDistDir = '.next'; + +const originalVersions = Object.getOwnPropertyDescriptor(process, 'versions')!; + +// Without a DSN, the client does not set up its integrations, so these tests do not patch `node:http`. +describe('Deno init()', () => { + afterEach(() => { + Object.defineProperty(process, 'versions', originalVersions); + getMainCarrier().__SENTRY__ = undefined; + }); + + it('reports Deno as the runtime', () => { + Object.defineProperty(process, 'versions', { ...originalVersions, value: { ...process.versions, deno: '2.9.0' } }); + + const client = init({}); + + expect(client?.getOptions().runtime).toEqual({ name: 'deno', version: '2.9.0' }); + }); + + it('replaces the undici fetch integration with the fetch integration of Deno', () => { + const client = init({}); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch'].includes(name)), + ).toEqual(['Fetch']); + }); + + it('adds the integrations that the user passes as an array', () => { + const userIntegration: Integration = { name: 'UserIntegration' }; + + const client = init({ integrations: [userIntegration] }); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch', 'UserIntegration'].includes(name)), + ).toEqual(['Fetch', 'UserIntegration']); + }); + + it('passes the Deno integrations to an integrations function of the user', () => { + const client = init({ + integrations: integrations => integrations.filter(integration => integration.name !== 'Fetch'), + }); + + expect( + client + ?.getOptions() + .integrations.map(integration => integration.name) + .filter(name => ['NodeFetch', 'Fetch'].includes(name)), + ).toEqual([]); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 608007d77333..a6c6b91adc28 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1620,6 +1620,9 @@ importers: '@sentry/bun': specifier: 11.12.0 version: link:../bun + '@sentry/deno': + specifier: 11.12.0 + version: link:../deno cjs-module-lexer: specifier: ^2.2.0 version: 2.2.0 From 82c7b4ab26f33b67d018da31ea89aaa33326c321 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Fri, 13 Nov 2026 07:13:57 +0000 Subject: [PATCH 057/136] chore(deps): Record the postcss-selector-parser 7.2.0 deprecation in the lockfile (#26339) npm now marks `postcss-selector-parser@7.2.0` as deprecated, so `pnpm install --no-frozen-lockfile` adds a `deprecated` line to `pnpm-lock.yaml`. "Check lockfile" fails on develop and on every PR that triggers it because of that line. This commit adds the line, and the lockfile has no other change. --- pnpm-lock.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a6c6b91adc28..b082a7fcc251 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15850,6 +15850,7 @@ packages: postcss-selector-parser@7.2.0: resolution: {integrity: sha512-Khh/tERVBn0I1499dvBSHY0pWJloMJWUxDsOBM0CCDPAcVZ10Jl2L1qy1f19uEX22spa8Mv7DCdEQJc0cGwBhQ==} engines: {node: '>=4'} + deprecated: Double-escapes CSS Modules class names (#362). Use 7.2.1. postcss-svgo@7.1.3: resolution: {integrity: sha512-2QfoFOYMcj8lwcVEf9WeTlkVIAm7u2QvOEhMzkQU3KUhhGX/l8hVV9EtjMv4iq3E9iI3OeeMN0YoMLbGusuigw==} From 7a37943e996e4840f39431495e37c8de5fc93d66 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:29:26 +0000 Subject: [PATCH 058/136] chore(dev-deps): Replace nodemon with tsx watch (#26322) **Why:** nodemon was only used by two `build:transpile:watch` scripts, and both were broken: - In `nextjs`, nodemon ran `scripts/buildRollup.ts` through `ts-node`, which isn't installed (`"ts-node" exec not found`). - In `tanstackstart-react`, the script points at a `scripts/buildRollup.ts` that doesn't exist, so nodemon ran the package's `main` and never built anything. `nextjs` now uses `tsx watch` with the same tsconfig its `build:transpile` already uses. `--include src` replaces `--watch src`, because tsx only watches files the script imports, and buildRollup shells out to rolldown. `--clear-screen=false` keeps nx's interleaved watch output readable. `tanstackstart-react`'s `build:transpile` is a plain rolldown call, so its watch is now `rolldown --watch`, like the other 36 packages. The "Debug playwright tests" VS Code launch config, the last nodemon reference, is removed rather than ported. It pointed at a playwright binary path that no longer exists, and no package under `packages/` has playwright tests anymore. **How to review:** Two script lines, the launch config, and the lockfile. Verified locally: the nextjs watch builds once, rebuilds once after touching a `src` file, and doesn't loop on its own `build/` output. The tanstackstart-react watch builds without errors. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .vscode/launch.json | 27 ---------- package.json | 1 - packages/nextjs/package.json | 2 +- packages/tanstackstart-react/package.json | 2 +- pnpm-lock.yaml | 66 ----------------------- 5 files changed, 2 insertions(+), 96 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 5c59e098d55e..750acd5f866f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -52,33 +52,6 @@ "internalConsoleOptions": "openOnSessionStart", "outputCapture": "std" }, - // Run a specific test file in watch mode (must have file in currently active tab when hitting the play button). - // NOTE: If you try to run this and VSCode complains that the command `shellCommand.execute` can't be found, go - // install the recommended extension Tasks Shell Input. - { - "name": "Debug playwright tests (just open file)", - "type": "pwa-node", - "cwd": "${workspaceFolder}/packages/${input:getPackageName}", - "request": "launch", - "runtimeExecutable": "pnpm", - "runtimeArgs": [ - // `nodemon` is basically `node --watch` - "nodemon", - // be default it only watches JS files, so have it watch TS files instead - "--ext", - "ts", - "${workspaceFolder}/node_modules/playwright/node_modules/.bin/playwright", - "test", - "${file}" - ], - "skipFiles": ["/**"], - "outFiles": ["${workspaceFolder}/**/*.js", "!**/node_modules/**"], - "sourceMaps": true, - "smartStep": true, - "internalConsoleOptions": "openOnSessionStart", - // show stdout and stderr output in the debug console - "outputCapture": "std" - }, // @sentry/nextjs - Run a specific integration test file // Must have test file in currently active tab when hitting the play button, and must already have run `pnpm install` in test app directory diff --git a/package.json b/package.json index 0a95ce38e3dc..7ea21a7e2067 100644 --- a/package.json +++ b/package.json @@ -147,7 +147,6 @@ "es-check": "^9.8.1", "esbuild": "^0.28.1", "jsdom": "^21.1.2", - "nodemon": "^3.1.10", "npm-run-all2": "^6.2.0", "nx": "24.0.3", "oxfmt": "^0.74.0", diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 7dde0daa81d2..69bfefa7fd92 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -135,7 +135,7 @@ "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "nodemon --ext ts --watch src scripts/buildRollup.ts", + "build:transpile:watch": "tsx watch --tsconfig tsconfig.tsnode.json --include src --clear-screen=false scripts/buildRollup.ts", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nextjs-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 5fd1b50fbbb2..1c71cefb9a39 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -73,7 +73,7 @@ "build:types": "tsc -p tsconfig.types.json", "build:watch": "run-p build:transpile:watch", "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "nodemon --ext ts --watch src scripts/buildRollup.ts", + "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-tanstackstart-react-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b082a7fcc251..a3f4846f21cd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -213,9 +213,6 @@ importers: jsdom: specifier: ^21.1.2 version: 21.1.2(supports-color@10.0.0) - nodemon: - specifier: ^3.1.10 - version: 3.1.10 npm-run-all2: specifier: ^6.2.0 version: 6.2.0 @@ -12815,9 +12812,6 @@ packages: ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} - ignore-by-default@1.0.1: - resolution: {integrity: sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==} - ignore-walk@5.0.1: resolution: {integrity: sha512-yemi4pMf51WKT7khInJqAvsIGzoqYXblnsz0ql8tM+yi1EKYTY1evX4NAbJrLL/Aanr2HyZeluqU+Oi7MGHokw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -14708,15 +14702,6 @@ packages: resolution: {integrity: sha512-JuKopr93W+WP+TaK5yoHJGpzPF9fpkH8Vcc9CXGE993BNeRKsb3L4Wy6FzL0VxkEa6U+8M4Ni0HEm9rMMnwurg==} engines: {node: '>=6'} - nodemon@3.1.10: - resolution: {integrity: sha512-WDjw3pJ0/0jMFmyNDp3gvY2YizjLmmOUQo6DEBY+JgdvW/yQ9mEeSw6H5ythl5Ny2ytb7f9C2nIbjSxMNzbJXw==} - engines: {node: '>=10'} - hasBin: true - - nopt@1.0.10: - resolution: {integrity: sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==} - hasBin: true - nopt@6.0.0: resolution: {integrity: sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -16057,9 +16042,6 @@ packages: psl@1.8.0: resolution: {integrity: sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==} - pstree.remy@1.1.8: - resolution: {integrity: sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==} - punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -16873,10 +16855,6 @@ packages: simple-swizzle@0.2.2: resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==} - simple-update-notifier@2.0.0: - resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==} - engines: {node: '>=10'} - simple-wcswidth@1.1.2: resolution: {integrity: sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==} @@ -17538,10 +17516,6 @@ packages: resolution: {integrity: sha512-eM+pCBxXO/njtF7vdFsHuqb+ElbxqtI4r5EAvk6grfAFyJ6IvWlSkfZ5T9ozC6xWw3Fj1fGoSmrl0gUs46JVIw==} engines: {node: '>=6'} - touch@3.1.0: - resolution: {integrity: sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==} - hasBin: true - tough-cookie@4.1.4: resolution: {integrity: sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==} engines: {node: '>=6'} @@ -17787,9 +17761,6 @@ packages: unplugin: optional: true - undefsafe@2.0.5: - resolution: {integrity: sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==} - underscore.string@3.3.6: resolution: {integrity: sha512-VoC83HWXmCrF6rgkyxS9GHv8W9Q5nhMKho+OadDJGzL2oDYbYEppBaCMH6pFlwLeqj2QS+hhkw2kpXkSdD1JxQ==} @@ -30141,12 +30112,6 @@ snapshots: optionalDependencies: supports-color: 10.0.0 - debug@4.4.3(supports-color@5.5.0): - dependencies: - ms: 2.1.3 - optionalDependencies: - supports-color: 5.5.0 - debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 @@ -32503,8 +32468,6 @@ snapshots: ieee754@1.2.1: {} - ignore-by-default@1.0.1: {} - ignore-walk@5.0.1: dependencies: minimatch: 5.1.9 @@ -35037,23 +35000,6 @@ snapshots: long-timeout: 0.1.1 sorted-array-functions: 1.3.0 - nodemon@3.1.10: - dependencies: - chokidar: 3.6.0 - debug: 4.4.3(supports-color@5.5.0) - ignore-by-default: 1.0.1 - minimatch: 3.1.5 - pstree.remy: 1.1.8 - semver: 7.8.5 - simple-update-notifier: 2.0.0 - supports-color: 5.5.0 - touch: 3.1.0 - undefsafe: 2.0.5 - - nopt@1.0.10: - dependencies: - abbrev: 1.1.1 - nopt@6.0.0: dependencies: abbrev: 1.1.1 @@ -36877,8 +36823,6 @@ snapshots: psl@1.8.0: {} - pstree.remy@1.1.8: {} - punycode@2.3.1: {} pure-rand@6.1.0: {} @@ -38041,10 +37985,6 @@ snapshots: is-arrayish: 0.3.2 optional: true - simple-update-notifier@2.0.0: - dependencies: - semver: 7.8.5 - simple-wcswidth@1.1.2: {} sirv@3.0.2: @@ -38711,10 +38651,6 @@ snapshots: totalist@3.0.0: {} - touch@3.1.0: - dependencies: - nopt: 1.0.10 - tough-cookie@4.1.4: dependencies: psl: 1.8.0 @@ -38967,8 +38903,6 @@ snapshots: rolldown: 1.3.2 unplugin: 3.3.0(esbuild@0.28.1)(rolldown@1.3.2)(rollup@4.62.3)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(webpack@5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3)) - undefsafe@2.0.5: {} - underscore.string@3.3.6: dependencies: sprintf-js: 1.1.3 From 60f2958b052194bf82fe863c374345dda35c055a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:45:47 +0000 Subject: [PATCH 059/136] ref(server-runtime-injection): Say when hook registration fails because the deployment is missing a file (#26272) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Follow-up to #26271. When `Module.register()` fails with `ERR_MODULE_NOT_FOUND`, the always-on warning used to just repeat Node's "Cannot find module …". That reads like an SDK bug, when the real cause is that a build tracer didn't ship all of `@sentry/server-runtime-injection`. The warning now says so. I checked on Node 22 that `error.code` survives the trip back from the loader thread. The warning still fires once per process: issue #26121 asks for it to be quiet, but staying silent would hide that channel integrations aren't recording anything (see #25677). **How to review:** It's a single branch in the `catch` block of `registerDiagnosticsChannelInjection()`, plus one unit test. Refs #26121 via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794383205.954799) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794383205.954799/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .../server-runtime-injection/src/register.ts | 9 ++++++++- .../test/register.test.ts | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/server-runtime-injection/src/register.ts b/packages/server-runtime-injection/src/register.ts index 0f759e631659..38f32ff05ebd 100644 --- a/packages/server-runtime-injection/src/register.ts +++ b/packages/server-runtime-injection/src/register.ts @@ -343,8 +343,15 @@ export function registerDiagnosticsChannelInjection(): void { } catch (error) { marker.runtimeUnavailable = true; const reason = error instanceof Error ? error.message : String(error); + // Build tracers decide which of this package's files a deployment ships, and they miss the ones + // only reached through `Module.register()`. Say so, because the bare message reads like an SDK bug. + const missingFile = (error as { code?: unknown } | null)?.code === 'ERR_MODULE_NOT_FOUND'; warnRuntimeUnavailable( - `Failed to register diagnostics-channel injection hooks (${reason}), so channel-based integrations will not record spans.`, + missingFile + ? 'Channel-based integrations will not record spans: your deployment is missing a file from ' + + `\`@sentry/server-runtime-injection\` (${reason}). Your build's file tracing left it out. Deploy the ` + + 'whole `@sentry/server-runtime-injection` package directory with your server.' + : `Failed to register diagnostics-channel injection hooks (${reason}), so channel-based integrations will not record spans.`, ); debug.warn('Diagnostics-channel injection registration error:', error); return; diff --git a/packages/server-runtime-injection/test/register.test.ts b/packages/server-runtime-injection/test/register.test.ts index 3dfa3bdb4b15..159c570c3a80 100644 --- a/packages/server-runtime-injection/test/register.test.ts +++ b/packages/server-runtime-injection/test/register.test.ts @@ -128,6 +128,26 @@ describe('registerDiagnosticsChannelInjection - bundled/tree-shaken detection', expect(GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.runtimeUnavailable).toBe(true); }); + it('says the deployment is missing a file when registering fails with ERR_MODULE_NOT_FOUND', () => { + (globalThis as { Deno?: unknown }).Deno = { version: { deno: '2.8.3' } }; + registerHooksMock.mockImplementationOnce(() => { + throw Object.assign(new Error("Cannot find module '/var/task/hook.js'"), { code: 'ERR_MODULE_NOT_FOUND' }); + }); + + try { + registerDiagnosticsChannelInjection(); + } finally { + delete (globalThis as { Deno?: unknown }).Deno; + } + + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining( + "your deployment is missing a file from `@sentry/server-runtime-injection` (Cannot find module '/var/task/hook.js')", + ), + ); + expect(GLOBAL_OBJ.__SENTRY_ORCHESTRION__?.runtimeUnavailable).toBe(true); + }); + it('warns once when a module fails to transform because the transformer was tree-shaken', () => { registerDiagnosticsChannelInjection(); const onDiagnostics = diagnosticsCallback(); From c781d69edd8589445cfd9ad9f0c167c2e71346ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:02:53 -0500 Subject: [PATCH 060/136] feat(deps): Bump @hono/node-server from 2.1.5 to 2.1.7 (#26331) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [@hono/node-server](https://github.com/honojs/node-server) from 2.1.5 to 2.1.7.
Release notes

Sourced from @​hono/node-server's releases.

v2.1.7

Security fixes

This release includes a fix for the following security issue:

serveStatic with allowPercentInPath still allows the double-decode middleware bypass

Affects: serveStatic with allowPercentInPath: true. The fix for GHSA-rmxm-3fg6-px4f rejects a path containing %, but the allowPercentInPath option skipped that check entirely. A malformed percent sequence such as /static/%%36%31dmin/secret.txt was routed as /static/%61dmin/secret.txt, so middleware on /static/admin/* did not run, and serveStatic then decoded %61 to a and served static/admin/secret.txt. The default configuration was already fixed in 2.1.3. GHSA-fj57-4f93-cfw6

serveStatic now accepts the second decode only when its result equals the routed path with %25 replaced by %. File names containing a literal %, requested as %25, are served as before.


The same fix ships in hono v4.13.18 (GHSA-74fm-fwc7-3fwp).

Full Changelog: https://github.com/honojs/node-server/compare/v2.1.6...v2.1.7

v2.1.6

Security fixes

This release includes fixes for the following security issues:

Backslash in the request path is parsed as a path separator, bypassing path-based access control at a reverse proxy

Affects: all requests. The raw request-target was passed to the WHATWG URL parser, which treats a backslash in the path as / and resolves .. segments, so /admin\secret reached the application as /admin/secret. A reverse proxy that forwards the backslash unchanged applied its path-based rules to the original path. GHSA-jpvv-r467-5p4w

A request whose path contains a raw backslash is now rejected with 400 Bad Request, for HTTP/1.1, HTTP/2 and WebSocket upgrades. A percent-encoded backslash (%5C) and a backslash in the query string are still accepted.

WebSocket upgrade request-target starting with // replaces the host in c.req.url, bypassing Origin checks

Affects: upgradeWebSocket. The URL of an upgrade request was built by resolving the request-target against the Host header, so a request-target such as //attacker.example/ws set the host of c.req.url to a client-chosen value while routing still saw /ws. An application that compared Origin with the origin of c.req.url could be bypassed by a page on another site. GHSA-7v5p-43qr-wch5

The host of upgrade requests now comes from the Host header, as for ordinary requests.

Unhandled ECONNRESET on the socket during an asynchronous WebSocket upgrade crashes the process

Affects: upgradeWebSocket. While the application handled an upgrade request, the socket had no error listener. A client that reset the connection during asynchronous middleware caused an unhandled 'error' event and terminated the process. GHSA-qv5m-9pm6-hqp3

Error and close events on the socket are now handled while the application runs, and a pending upgrade is released when the socket closes.


The backslash fix also ships in @hono/node-server v1.19.18. Users of upgradeWebSocket are encouraged to upgrade to this version.

Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@hono/node-server&package-manager=npm_and_yarn&previous-version=2.1.5&new-version=2.1.7)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/getsentry/sentry-javascript/network/alerts).
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pnpm-lock.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a3f4846f21cd..23ab8d7639d4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -610,7 +610,7 @@ importers: version: 21.3.10 '@hono/node-server': specifier: ^2.1.5 - version: 2.1.5(hono@4.13.11) + version: 2.1.7(hono@4.13.11) '@koa/router': specifier: ^12.0.1 version: 12.0.2(supports-color@10.0.0) @@ -5340,8 +5340,8 @@ packages: '@hapi/wreck@18.1.2': resolution: {integrity: sha512-3dMnV2pfhQiyEqu8DL3VBmxkdLiRDiiUDuG79Dp+UK1gL9ZxAfDOUhB6k3D5MLqcgJJ1IARyGFhwoc1NITr/pg==} - '@hono/node-server@2.1.5': - resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==} + '@hono/node-server@2.1.7': + resolution: {integrity: sha512-Wr0E6S+v2Bw9FkpGNP5BQ5QbJvclUa06UVehd65WFZe6XeJwbrKQQ5wPDevc0IC+QyzbO7v3Llh5uo45IZcSnA==} engines: {node: '>=20'} peerDependencies: hono: ^4 || ^5.0.0-0 @@ -23513,7 +23513,7 @@ snapshots: dependencies: '@earendil-works/pi-agent-core': 1.4.0(@aws-sdk/credential-provider-node@3.972.92)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7))(@smithy/signature-v4@5.7.5)(supports-color@10.0.0)(undici@7.24.8)(ws@8.22.2)(zod@4.6.7) '@earendil-works/pi-ai': 1.4.0(@aws-sdk/credential-provider-node@3.972.92)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7))(@smithy/signature-v4@5.7.5)(supports-color@10.0.0)(undici@7.24.8)(ws@8.22.2)(zod@4.6.7) - '@hono/node-server': 2.1.5(hono@4.13.11) + '@hono/node-server': 2.1.7(hono@4.13.11) '@modelcontextprotocol/client': 2.0.0 '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) hono: 4.13.11 @@ -23846,7 +23846,7 @@ snapshots: '@hapi/bourne': 3.0.0 '@hapi/hoek': 11.0.4 - '@hono/node-server@2.1.5(hono@4.13.11)': + '@hono/node-server@2.1.7(hono@4.13.11)': dependencies: hono: 4.13.11 @@ -24441,7 +24441,7 @@ snapshots: '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7)': dependencies: - '@hono/node-server': 2.1.5(hono@4.13.11) + '@hono/node-server': 2.1.7(hono@4.13.11) ajv: 8.20.0 ajv-formats: 3.0.1 content-type: 1.0.5 From 73e928ab5e0b1bb7dba9c97cc1d39c1f4f8999b7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:22:32 +0000 Subject: [PATCH 061/136] chore(deps-dev): Bump hono from 4.13.11 to 4.13.16 (#26340) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [hono](https://github.com/honojs/hono) from 4.13.11 to 4.13.16.
Release notes

Sourced from hono's releases.

v4.13.16

Security fixes

This release includes fixes for the following security issues:

mount() and app.mount() can forward a path that bypasses middleware scoped inside the mount prefix

Affects: mount() in hono/mount and app.mount(). A dynamic prefix such as /api/:tenant/* was removed by the length of the route pattern. The forwarded path was also re-normalized by the URL parser, so a decoded \ became / and .. collapsed. Both let a crafted request skip middleware scoped inside the mount prefix. Routes such as /assets* and duplicate parameter names now throw. GHSA-4m76-xfj5-7975

RegExpRouter skips wildcard middleware for certain route patterns and for paths with an encoded line terminator

Affects: RegExpRouter, including the default SmartRouter. Wildcard middleware was not applied in three cases: a parameter written as {[^/]+} in the middleware path only, a /prefix* route next to /prefix/* middleware, and a path with an encoded line terminator. RegExpRouter now covers the same routes as the other routers. Custom patterns that can match the empty string, such as {[0-9]*}, throw UnsupportedPathError. Regenerate PreparedRegExpRouter data. GHSA-h7mg-cq63-vhpq

validator('form') skips validation for multipart/form-data requests with extra parameters

Affects: validator('form') in hono/validator. A multipart/form-data request with an extra parameter such as charset was not recognized as a form. The validator then saw an empty object while the handler could read all fields. GHSA-4h7h-rv7c-7m2v

css helper does not escape a closing tag assembled from template parts and values, allowing HTML injection

Affects: css in hono/css. A </style> split between the template and a value, or between two values, was not escaped. Closing tags are now escaped after minification. GHSA-3gg2-335m-rxc6

csrf() does not check requests sent by hyperlink auditing (text/ping)

Affects: csrf() in hono/csrf. A POST sent by Chromium's <a ping> has the content type text/ping and was not checked against Origin and Sec-Fetch-Site. GHSA-46wx-v44x-9hh2


Users who rely on path-scoped middleware with mount(), wildcard middleware with the default router, validator('form'), the css helper with untrusted values, or csrf() are strongly encouraged to upgrade to this version.

What's Changed

  • fix(jwt): reject a signature segment outside the base64url alphabet and a header with crit in honojs/hono#5597

Full Changelog: https://github.com/honojs/hono/compare/v4.13.15...v4.13.16

v4.13.15

What's Changed

Full Changelog: https://github.com/honojs/hono/compare/v4.13.14...v4.13.15

v4.13.14

What's Changed

... (truncated)

Commits
  • c91b60a 4.13.16
  • e1dd588 fix(jwt): reject a signature segment outside the base64url alphabet and a hea...
  • bf16471 Merge commit from fork
  • d88fab3 Merge commit from fork
  • 34f9043 Merge commit from fork
  • 8a103aa Merge commit from fork
  • 15bbd96 Merge commit from fork
  • 3cb29de 4.13.15
  • 17ad0e2 fix(context): allow c.header() after the response body is consumed (#5587)
  • ee88684 docs(contributing): drop the note about linking a fork branch (#5593)
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=hono&package-manager=npm_and_yarn&previous-version=4.13.11&new-version=4.13.16)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/getsentry/sentry-javascript/network/alerts).
--------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- packages/hono/package.json | 2 +- pnpm-lock.yaml | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/hono/package.json b/packages/hono/package.json index 9a1cb3e0c245..74c4d28cc09f 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -110,7 +110,7 @@ "@sentry/deno": "11.12.0", "@sentry/node": "11.12.0", "@types/node": "^20.19.0", - "hono": "4.13.11", + "hono": "4.13.16", "hono-5": "npm:hono@5.0.0-rc.1" }, "scripts": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 23ab8d7639d4..00c3f822b91c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -344,7 +344,7 @@ importers: version: 1.2.9 hono: specifier: ^4.13.7 - version: 4.13.11 + version: 4.13.16 mysql: specifier: ^2.18.1 version: 2.18.1 @@ -500,7 +500,7 @@ importers: version: 6.0.218(zod@4.6.7) hono: specifier: ^4.13.7 - version: 4.13.11 + version: 4.13.16 openai: specifier: 5.18.1 version: 5.18.1(ws@8.22.2)(zod@4.6.7) @@ -610,7 +610,7 @@ importers: version: 21.3.10 '@hono/node-server': specifier: ^2.1.5 - version: 2.1.7(hono@4.13.11) + version: 2.1.7(hono@4.13.16) '@koa/router': specifier: ^12.0.1 version: 12.0.2(supports-color@10.0.0) @@ -745,7 +745,7 @@ importers: version: 2.0.1-rc.22(crossws@0.4.10(srvx@0.11.22)) hono: specifier: ^4.13.7 - version: 4.13.11 + version: 4.13.16 ioredis: specifier: 5.10.1 version: 5.10.1(supports-color@10.0.0) @@ -1516,8 +1516,8 @@ importers: specifier: ^20.19.0 version: 20.19.43 hono: - specifier: 4.13.11 - version: 4.13.11 + specifier: 4.13.16 + version: 4.13.16 hono-5: specifier: npm:hono@5.0.0-rc.1 version: hono@5.0.0-rc.1 @@ -12636,8 +12636,8 @@ packages: hoist-non-react-statics@3.3.2: resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==} - hono@4.13.11: - resolution: {integrity: sha512-/SMX/RQNJn7oNmFwH6DtwDqcrzZU2otm1FD6OJe2cWF6cfy/F8hq0XVBv7xW3FTJshRQwuBnXHDq2kNsdZnshg==} + hono@4.13.16: + resolution: {integrity: sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A==} engines: {node: '>=16.9.0'} hono@5.0.0-rc.1: @@ -23513,10 +23513,10 @@ snapshots: dependencies: '@earendil-works/pi-agent-core': 1.4.0(@aws-sdk/credential-provider-node@3.972.92)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7))(@smithy/signature-v4@5.7.5)(supports-color@10.0.0)(undici@7.24.8)(ws@8.22.2)(zod@4.6.7) '@earendil-works/pi-ai': 1.4.0(@aws-sdk/credential-provider-node@3.972.92)(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7))(@smithy/signature-v4@5.7.5)(supports-color@10.0.0)(undici@7.24.8)(ws@8.22.2)(zod@4.6.7) - '@hono/node-server': 2.1.7(hono@4.13.11) + '@hono/node-server': 2.1.7(hono@4.13.16) '@modelcontextprotocol/client': 2.0.0 '@valibot/to-json-schema': 1.8.0(valibot@1.5.0(typescript@7.0.2)) - hono: 4.13.11 + hono: 4.13.16 js-yaml: 5.5.0 ulidx: 2.4.1 valibot: 1.5.0(typescript@7.0.2) @@ -23846,9 +23846,9 @@ snapshots: '@hapi/bourne': 3.0.0 '@hapi/hoek': 11.0.4 - '@hono/node-server@2.1.7(hono@4.13.11)': + '@hono/node-server@2.1.7(hono@4.13.16)': dependencies: - hono: 4.13.11 + hono: 4.13.16 '@humanwhocodes/config-array@0.11.14(supports-color@10.0.0)': dependencies: @@ -24441,7 +24441,7 @@ snapshots: '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.1)(supports-color@10.0.0)(zod@4.6.7)': dependencies: - '@hono/node-server': 2.1.7(hono@4.13.11) + '@hono/node-server': 2.1.7(hono@4.13.16) ajv: 8.20.0 ajv-formats: 3.0.1 content-type: 1.0.5 @@ -24451,7 +24451,7 @@ snapshots: eventsource-parser: 3.1.1 express: 5.3.0(supports-color@10.0.0) express-rate-limit: 8.7.1(express@5.3.0(supports-color@10.0.0))(supports-color@10.0.0) - hono: 4.13.11 + hono: 4.13.16 jose: 6.2.10 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 @@ -32226,7 +32226,7 @@ snapshots: dependencies: react-is: 16.13.1 - hono@4.13.11: {} + hono@4.13.16: {} hono@5.0.0-rc.1: {} From a72b2d878ee7eaf91b11348abcdd66f90c4ea8a2 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:27 +0100 Subject: [PATCH 062/136] feat(nuxt): Instrument Nitro v3 cache storage (#25951) **Why:** Starting with the RC, Nitro v3 runs `defineCachedFunction` / `defineCachedHandler` (and `cache` route rules) on an `ocache` storage. That storage only goes through KV storage when the `kv` cache driver is set, so with the default `memory` driver (and with `fs`) our KV driver instrumentation never sees cache reads or writes, and no `cache.*` spans are produced. Nitro doesn't offer a tracing channel for its cache, and the storage instance is private to Nitro's runtime. It is created in the build-time `#nitro/virtual/cache` module, though, so a bundler transform wraps that module's `createCacheStorage` export and the storage gets patched in place. It has to be patched in place because `ocache` also reads `binary` and `maxEntryBytes` from the storage object. The `kv` driver is skipped because the existing KV instrumentation already covers it. `cache.hit` comes from the stored entry: it must have a value, be unexpired, and not be marked `stale`. This PR also undoes the `kv` workaround in the nuxt-5 E2E app, so the default driver is what gets tested. **How to review:** Start with `cacheStorageInstrumentationPlugin` in `vite/storageConfig.ts`, then `instrumentCacheStorage` in `runtime/utils/instrumentStorage.ts`. The span wrapper is now shared with the KV driver instrumentation, and KV behavior is unchanged. **Unsure about:** The transform matches the exact `export const createCacheStorage =` line that Nitro generates. If Nitro changes that template, the transform does nothing (no crash), but cache spans would disappear again. Is that acceptable, or should we push upstream for a tracing channel or hook in Nitro/ocache? Note this is stacked on #25949. via **Francesco Gringl-Novy**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1793366214.663899) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1793366214.663899/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy --- .../test-applications/nuxt-5/nuxt.config.ts | 4 +- .../test-applications/nuxt-5/package.json | 9 +- .../nuxt-5/tests/cache.test.ts | 29 ++-- .../src/runtime/utils/instrumentStorage.ts | 152 ++++++++++++++---- packages/nuxt/src/vite/nitroServer.ts | 6 +- packages/nuxt/src/vite/storageConfig.ts | 49 ++++++ .../runtime/utils/instrumentStorage.test.ts | 126 +++++++++++++++ packages/nuxt/test/vite/storageConfig.test.ts | 77 +++++++++ 8 files changed, 404 insertions(+), 48 deletions(-) create mode 100644 packages/nuxt/test/runtime/utils/instrumentStorage.test.ts create mode 100644 packages/nuxt/test/vite/storageConfig.test.ts diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts index 78c559af3621..2a87330f1b18 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/nuxt.config.ts @@ -28,9 +28,7 @@ export default defineNuxtConfig({ }, }, nitro: { - // Nitro v3 only routes `defineCachedFunction`/`defineCachedHandler` through KV storage (which the SDK - // instruments) with the `kv` cache driver. The default `memory` driver bypasses KV storage entirely. - cache: { driver: 'kv' }, + ...(process.env.E2E_TEST_CACHE_DRIVER && { cache: { driver: process.env.E2E_TEST_CACHE_DRIVER } }), experimental: { database: true, }, diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json index 081e3a523b31..07c9f3bf9f91 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -18,7 +18,9 @@ "test:assert": "pnpm test:prod && pnpm test:dev", "test:build:tunnel-basepath": "pnpm install && E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app pnpm build", "test:assert:tunnel-basepath": "E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app TEST_ENV=production playwright test tunnel", - "test:assert:tunnel-dev": "E2E_TEST_TUNNEL=1 TEST_ENV=development playwright test tunnel" + "test:assert:tunnel-dev": "E2E_TEST_TUNNEL=1 TEST_ENV=development playwright test tunnel", + "test:build:kv-cache": "pnpm install && E2E_TEST_CACHE_DRIVER=kv pnpm build", + "test:assert:kv-cache": "E2E_TEST_CACHE_DRIVER=kv TEST_ENV=production playwright test cache" }, "//": [ "Currently, we need to install the Nuxt nightlies as those contain Nuxt v5", @@ -54,6 +56,11 @@ "build-command": "pnpm install", "assert-command": "pnpm test:assert:tunnel-dev", "label": "nuxt-5 (tunnel-dev)" + }, + { + "build-command": "pnpm test:build:kv-cache", + "assert-command": "pnpm test:assert:kv-cache", + "label": "nuxt-5 (kv-cache)" } ] } diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts index 676ecc4ab91f..1cd62dbae4da 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/cache.test.ts @@ -1,6 +1,15 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +// Nitro v3 only routes cached functions and handlers through KV storage with the `kv` cache driver, +// so the default (`memory`) driver is traced through ocache's storage instead. +const isKvCacheDriver = process.env.E2E_TEST_CACHE_DRIVER === 'kv'; +const GET_METHOD = isKvCacheDriver ? 'getItem' : 'get'; +const SET_METHOD = isKvCacheDriver ? 'setItem' : 'set'; +const STORAGE_ATTRIBUTES = isKvCacheDriver + ? { 'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) } } + : { 'db.system.name': { type: 'string', value: 'memory' } }; + test.describe('Cache Instrumentation', () => { const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key'; const SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit'; @@ -34,8 +43,8 @@ test.describe('Cache Instrumentation', () => { const getCacheKey = (span: (typeof allCacheSpans)[number]) => span.attributes[SEMANTIC_ATTRIBUTE_CACHE_KEY]?.value; - // Test getItem spans for cachedFunction - should have both cache miss and cache hit - const getItemSpans = findSpansByMethod('getItem'); + // Test read spans for cachedFunction - should have both cache miss and cache hit + const getItemSpans = findSpansByMethod(GET_METHOD); expect(getItemSpans.length).toBeGreaterThan(0); // Find cache miss (first call to getCachedUser('123')) @@ -51,8 +60,8 @@ test.describe('Cache Instrumentation', () => { 'cache.operation': { type: 'string', value: 'get' }, 'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' }, [SEMANTIC_ATTRIBUTE_CACHE_HIT]: { type: 'boolean', value: false }, - 'db.operation.name': { type: 'string', value: 'getItem' }, - 'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) }, + 'db.operation.name': { type: 'string', value: GET_METHOD }, + ...STORAGE_ATTRIBUTES, }); } @@ -69,13 +78,13 @@ test.describe('Cache Instrumentation', () => { 'cache.operation': { type: 'string', value: 'get' }, 'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' }, [SEMANTIC_ATTRIBUTE_CACHE_HIT]: { type: 'boolean', value: true }, - 'db.operation.name': { type: 'string', value: 'getItem' }, - 'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) }, + 'db.operation.name': { type: 'string', value: GET_METHOD }, + ...STORAGE_ATTRIBUTES, }); } - // Test setItem spans for cachedFunction - when cache miss occurs, value is set - const setItemSpans = findSpansByMethod('setItem'); + // Test write spans for cachedFunction - when cache miss occurs, value is set + const setItemSpans = findSpansByMethod(SET_METHOD); expect(setItemSpans.length).toBeGreaterThan(0); const cacheSetSpan = setItemSpans.find( @@ -86,8 +95,8 @@ test.describe('Cache Instrumentation', () => { 'sentry.op': { type: 'string', value: 'cache.put' }, 'cache.operation': { type: 'string', value: 'put' }, 'sentry.origin': { type: 'string', value: 'auto.cache.nuxt' }, - 'db.operation.name': { type: 'string', value: 'setItem' }, - 'db.collection.name': { type: 'string', value: expect.stringMatching(/^(cache)?$/) }, + 'db.operation.name': { type: 'string', value: SET_METHOD }, + ...STORAGE_ATTRIBUTES, }); } diff --git a/packages/nuxt/src/runtime/utils/instrumentStorage.ts b/packages/nuxt/src/runtime/utils/instrumentStorage.ts index 1055b4ca5876..da3318807296 100644 --- a/packages/nuxt/src/runtime/utils/instrumentStorage.ts +++ b/packages/nuxt/src/runtime/utils/instrumentStorage.ts @@ -14,10 +14,9 @@ import { captureException, debug, getClient, + handleCallbackErrors, hasSpanStreamingEnabled, isObjectLike, - SPAN_STATUS_ERROR, - SPAN_STATUS_OK, type SpanAttributes, startSpan, type StartSpanOptions, @@ -32,6 +31,7 @@ import type { Driver, Storage } from 'unstorage'; interface CacheEntry { value?: T; expires?: number; + stale?: boolean; } /** @@ -180,33 +180,119 @@ function createMethodWrapper( debug.log(`[storage] Running method: "${methodName}" on driver: "${driver.name ?? 'unknown'}"`); - return startSpan(options, async span => { - try { - const result = await target.apply(thisArg, args); - span.setStatus({ code: SPAN_STATUS_OK }); - - if (CACHE_HIT_METHODS.has(methodName)) { - span.setAttribute(CACHE_HIT, resolveCacheHit(methodName, args[0], result)); - } - - return result; - } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - captureException(error, { - mechanism: { - handled: false, - type: options.attributes?.[SENTRY_ORIGIN], - }, - }); - - // Re-throw the error to be handled by the caller - throw error; - } finally { - await flushIfServerless(); + return traceCacheOperation( + options, + () => target.apply(thisArg, args), + CACHE_HIT_METHODS.has(methodName) ? result => resolveCacheHit(methodName, args[0], result) : undefined, + ); + }, + }); +} + +/** + * Runs a cache operation in a span, optionally recording whether the result was a cache hit. + */ +function traceCacheOperation( + options: StartSpanOptions, + operation: () => unknown, + getCacheHit?: (result: unknown) => boolean, +): Promise { + return handleCallbackErrors( + () => + startSpan(options, async span => { + const result = await operation(); + + if (getCacheHit) { + span.setAttribute(CACHE_HIT, getCacheHit(result)); } + + return result; + }), + error => { + captureException(error, { + mechanism: { + handled: false, + type: 'auto.cache.nuxt', + }, }); }, - }); + () => { + void flushIfServerless(); + }, + ); +} + +/** + * The storage behind Nitro v3's `defineCachedFunction` and `defineCachedHandler` (an `ocache` storage). + */ +interface NitroCacheStorage { + get(key: string): unknown; + set(key: string, value: unknown, opts?: { ttl?: number }): unknown; +} + +/** + * Instruments the storage that Nitro v3 caches functions and handlers in. + * + * Unlike Nitro v2, Nitro v3 only writes its cache to KV storage with the `kv` cache driver, so the KV + * driver instrumentation doesn't see the default `memory` or the `fs` cache driver. + * The storage is patched in place because `ocache` reads other properties, like `binary`, from it. + */ +export function instrumentCacheStorage( + storage: MaybeInstrumented, + driverName: string, +): T { + if (storage.__sentry_instrumented__) { + return storage; + } + + const originalGet = storage.get.bind(storage); + const originalSet = storage.set.bind(storage); + + storage.get = (key: string) => + traceCacheOperation( + createCacheStorageSpanStartOptions('get', CACHE_GET, key, driverName), + () => originalGet(key), + isCacheEntryHit, + ); + + storage.set = (key: string, value: unknown, opts?: { ttl?: number }) => + // `ocache` deletes an entry by setting it to `null` + traceCacheOperation( + createCacheStorageSpanStartOptions('set', value == null ? CACHE_REMOVE : CACHE_PUT, key, driverName), + () => originalSet(key, value, opts), + ); + + storage.__sentry_instrumented__ = true; + + return storage; +} + +function createCacheStorageSpanStartOptions( + methodName: keyof NitroCacheStorage, + cacheOperation: typeof CACHE_GET | typeof CACHE_PUT | typeof CACHE_REMOVE, + key: string, + driverName: string, +): StartSpanOptions { + const client = getClient(); + return { + // With span streaming, span names have to be low cardinality, so we can't fall back to the cache key. + name: client && hasSpanStreamingEnabled(client) ? cacheOperation : key, + attributes: { + [SENTRY_OP]: cacheOperation, + [CACHE_OPERATION]: CACHE_OPERATION_NAMES[cacheOperation], + [SENTRY_ORIGIN]: 'auto.cache.nuxt', + [CACHE_KEY]: key, + [DB_OPERATION_NAME]: methodName, + [DB_SYSTEM_NAME]: driverName, + }, + }; +} + +/** + * `ocache` storage holds full cache entries, so a stored but expired or stale entry is a miss. + */ +function isCacheEntryHit(entry: unknown): boolean { + return isObjectLike(entry) && !(entry as CacheEntry).stale && isFreshCacheEntry(entry); } /** @@ -338,13 +424,7 @@ function validateCacheEntry( key: string, entry: CacheEntry | CacheEntry, ): boolean { - if (entry.value == null) { - return false; - } - - // Date.now is used by Nitro internally, so safe to use here. - // https://github.com/nitrojs/nitro/blob/5508f71b77730e967fb131de817725f5aa7c4862/src/runtime/internal/cache.ts#L78 - if (Date.now() > (entry.expires || 0)) { + if (!isFreshCacheEntry(entry)) { return false; } @@ -369,6 +449,12 @@ function validateCacheEntry( return true; } +function isFreshCacheEntry(entry: CacheEntry): entry is CacheEntry & { value: NonNullable } { + // Date.now is used by Nitro internally, so safe to use here. + // https://github.com/nitrojs/nitro/blob/5508f71b77730e967fb131de817725f5aa7c4862/src/runtime/internal/cache.ts#L78 + return entry.value != null && Date.now() <= (entry.expires || 0); +} + /** * Checks if the cache entry is a response cache entry. */ diff --git a/packages/nuxt/src/vite/nitroServer.ts b/packages/nuxt/src/vite/nitroServer.ts index 7401a6c1596d..91c164ad75f9 100644 --- a/packages/nuxt/src/vite/nitroServer.ts +++ b/packages/nuxt/src/vite/nitroServer.ts @@ -12,7 +12,7 @@ import { } from './addServerConfig'; import { addDatabaseInstrumentation } from './databaseConfig'; import { addMiddlewareImports, addMiddlewareInstrumentation } from './middlewareConfig'; -import { addStorageInstrumentation } from './storageConfig'; +import { addCacheStorageInstrumentation, addStorageInstrumentation } from './storageConfig'; import { addRuntimeInjectionTraceDep, type ServerApi } from './utils'; type NitroModuleOptions = Omit & @@ -65,6 +65,10 @@ export function setupNitroServer( addMiddlewareInstrumentation(nitro, isNitroV3); + if (isNitroV3) { + addCacheStorageInstrumentation(nitro); + } + if (deprecatedInjectMode) { setupDeprecatedInjectMode(nitro, deprecatedInjectMode, isNitroV3, serverConfigFile, moduleOptions); return; diff --git a/packages/nuxt/src/vite/storageConfig.ts b/packages/nuxt/src/vite/storageConfig.ts index 517c7884e36c..da94ea4ad1ab 100644 --- a/packages/nuxt/src/vite/storageConfig.ts +++ b/packages/nuxt/src/vite/storageConfig.ts @@ -1,7 +1,12 @@ import { addNitroPlugin, createResolver } from '@nuxt/kit'; import type { Nuxt } from '@nuxt/schema'; +import type { Nitro } from 'nitropack/types'; +import type { InputPluginOption } from 'rollup'; import { addServerTemplate } from '../vendor/server-template'; +const NITRO_CACHE_VIRTUAL_MODULE_ID = '#nitro/virtual/cache'; +const CREATE_CACHE_STORAGE_EXPORT = 'export const createCacheStorage ='; + /** * Prepares the storage config export to be used in the runtime storage instrumentation. */ @@ -23,3 +28,47 @@ export function addStorageInstrumentation(nuxt: Nuxt, isLegacyNitro: boolean): v addNitroPlugin(moduleDirResolver.resolve('./runtime/plugins/storage.server')); } } + +/** + * Instruments the storage behind Nitro v3's cached functions and handlers. + * + * Nitro v3 creates that storage in the `#nitro/virtual/cache` module, which is generated at build time and + * can't be reached at runtime, so the module's `createCacheStorage` export is wrapped while bundling. + */ +export function addCacheStorageInstrumentation(nitro: Nitro): void { + nitro.hooks.hook('rollup:before', (nitro, rollupConfig) => { + if (!rollupConfig.plugins) { + rollupConfig.plugins = []; + } + + if (!Array.isArray(rollupConfig.plugins)) { + rollupConfig.plugins = [rollupConfig.plugins]; + } + + rollupConfig.plugins.push(cacheStorageInstrumentationPlugin(nitro)); + }); +} + +function cacheStorageInstrumentationPlugin(nitro: Nitro): InputPluginOption { + const instrumentStoragePath = createResolver(import.meta.url).resolve('./runtime/utils/instrumentStorage'); + + return { + name: 'sentry-nuxt-cache-storage-instrumentation', + transform(code: string, id: string) { + // The `kv` driver re-exports a KV-backed storage, which the storage plugin already instruments + if (id !== NITRO_CACHE_VIRTUAL_MODULE_ID || !code.includes(CREATE_CACHE_STORAGE_EXPORT)) { + return null; + } + + const driverName = (nitro.options as { cache?: { driver?: string } }).cache?.driver ?? 'memory'; + + return { + code: `import { instrumentCacheStorage } from ${JSON.stringify(instrumentStoragePath)}; +${code.replace(CREATE_CACHE_STORAGE_EXPORT, 'const createUninstrumentedCacheStorage =')} +export const createCacheStorage = () => instrumentCacheStorage(createUninstrumentedCacheStorage(), ${JSON.stringify(driverName)}); +`, + map: null, + }; + }, + }; +} diff --git a/packages/nuxt/test/runtime/utils/instrumentStorage.test.ts b/packages/nuxt/test/runtime/utils/instrumentStorage.test.ts new file mode 100644 index 000000000000..11a534f783c4 --- /dev/null +++ b/packages/nuxt/test/runtime/utils/instrumentStorage.test.ts @@ -0,0 +1,126 @@ +import { + CACHE_HIT, + CACHE_KEY, + CACHE_OPERATION, + DB_OPERATION_NAME, + DB_SYSTEM_NAME, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op'; +import type * as SentryCore from '@sentry/core'; +import { describe, expect, it, vi } from 'vitest'; +import { instrumentCacheStorage } from '../../../src/runtime/utils/instrumentStorage'; + +const { captureExceptionMock, setAttributeMock, startSpanMock } = vi.hoisted(() => { + const setAttributeMock = vi.fn(); + return { + captureExceptionMock: vi.fn(), + setAttributeMock, + startSpanMock: vi.fn((_options: unknown, callback: (span: unknown) => unknown) => + callback({ setAttribute: setAttributeMock, setStatus: vi.fn() }), + ), + }; +}); + +vi.mock('@sentry/core', async importOriginal => ({ + ...(await importOriginal()), + captureException: captureExceptionMock, + startSpan: startSpanMock, +})); + +function createStorage(entries: Record = {}) { + const map = new Map(Object.entries(entries)); + return { + binary: true, + get: vi.fn((key: string) => map.get(key) ?? null), + set: vi.fn((key: string, value: unknown, _opts?: { ttl?: number }) => void map.set(key, value)), + }; +} + +const KEY = '/cache:nitrofunctions.abc:getUser:user:1.json'; + +describe('instrumentCacheStorage', () => { + it('traces reads and records a fresh entry as a cache hit', async () => { + const entry = { value: { id: 1 }, expires: Date.now() + 60_000 }; + const storage = instrumentCacheStorage(createStorage({ [KEY]: entry }), 'memory'); + + await expect(storage.get(KEY)).resolves.toBe(entry); + + expect(startSpanMock).toHaveBeenLastCalledWith( + { + name: KEY, + attributes: { + [SENTRY_OP]: CACHE_GET, + [CACHE_OPERATION]: 'get', + [SENTRY_ORIGIN]: 'auto.cache.nuxt', + [CACHE_KEY]: KEY, + [DB_OPERATION_NAME]: 'get', + [DB_SYSTEM_NAME]: 'memory', + }, + }, + expect.any(Function), + ); + expect(setAttributeMock).toHaveBeenLastCalledWith(CACHE_HIT, true); + }); + + it.each([ + ['a missing entry', undefined], + ['an expired entry', { value: { id: 1 }, expires: Date.now() - 1 }], + ['a stale entry', { value: { id: 1 }, expires: Date.now() + 60_000, stale: true }], + ])('records %s as a cache miss', async (_, entry) => { + const storage = instrumentCacheStorage(createStorage(entry ? { [KEY]: entry } : {}), 'memory'); + + await storage.get(KEY); + + expect(setAttributeMock).toHaveBeenLastCalledWith(CACHE_HIT, false); + }); + + it('traces writes, and writes of `null` as removals', async () => { + const original = createStorage(); + const originalSet = original.set; + const storage = instrumentCacheStorage(original, 'fs'); + + await storage.set(KEY, { value: 1 }, { ttl: 60 }); + expect(originalSet).toHaveBeenLastCalledWith(KEY, { value: 1 }, { ttl: 60 }); + expect(startSpanMock).toHaveBeenLastCalledWith( + expect.objectContaining({ + attributes: expect.objectContaining({ [SENTRY_OP]: CACHE_PUT, [DB_OPERATION_NAME]: 'set' }), + }), + expect.any(Function), + ); + + await storage.set(KEY, null); + expect(startSpanMock).toHaveBeenLastCalledWith( + expect.objectContaining({ attributes: expect.objectContaining({ [SENTRY_OP]: CACHE_REMOVE }) }), + expect.any(Function), + ); + }); + + it('captures and rethrows a failed operation', async () => { + const error = new Error('storage unavailable'); + const original = createStorage(); + original.get.mockRejectedValueOnce(error); + const storage = instrumentCacheStorage(original, 'memory'); + setAttributeMock.mockClear(); + + await expect(storage.get(KEY)).rejects.toBe(error); + + expect(captureExceptionMock).toHaveBeenCalledWith(error, { + mechanism: { handled: false, type: 'auto.cache.nuxt' }, + }); + expect(setAttributeMock).not.toHaveBeenCalledWith(CACHE_HIT, expect.anything()); + }); + + it('patches the storage in place and only once', async () => { + const original = createStorage(); + + const storage = instrumentCacheStorage(instrumentCacheStorage(original, 'memory'), 'memory'); + startSpanMock.mockClear(); + await storage.get(KEY); + + expect(storage).toBe(original); + expect(storage.binary).toBe(true); + expect(startSpanMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/nuxt/test/vite/storageConfig.test.ts b/packages/nuxt/test/vite/storageConfig.test.ts new file mode 100644 index 000000000000..fbc91701c09b --- /dev/null +++ b/packages/nuxt/test/vite/storageConfig.test.ts @@ -0,0 +1,77 @@ +import type { Nitro } from 'nitropack/types'; +import { describe, expect, it, vi } from 'vitest'; +import { addCacheStorageInstrumentation } from '../../src/vite/storageConfig'; + +vi.mock('@nuxt/kit', () => ({ + addNitroPlugin: vi.fn(), + createResolver: () => ({ resolve: (path: string) => `/module/${path.replace('./', '')}` }), +})); + +vi.mock('../../src/vendor/server-template', () => ({ + addServerTemplate: vi.fn(), +})); + +type TransformHook = (code: string, id: string) => { code: string } | null; + +function getCacheStorageTransform(cacheDriver?: string): TransformHook { + let rollupBeforeHook: ((nitro: Nitro, config: { plugins?: unknown }) => void) | undefined; + const nitro = { + options: { cache: cacheDriver ? { driver: cacheDriver } : undefined }, + hooks: { hook: (_name: string, callback: typeof rollupBeforeHook) => (rollupBeforeHook = callback) }, + } as unknown as Nitro; + + addCacheStorageInstrumentation(nitro); + + const rollupConfig: { plugins?: unknown } = {}; + rollupBeforeHook?.(nitro, rollupConfig); + + return (rollupConfig.plugins as Array<{ transform: TransformHook }>)[0]!.transform; +} + +const MEMORY_CACHE_MODULE = `import { createMemoryStorage } from "ocache"; +export const createCacheStorage = () => createMemoryStorage({}); + +export const cacheFunctionDefaults = {}; +`; + +describe('addCacheStorageInstrumentation', () => { + it('wraps the storage created by the cache virtual module', () => { + const transform = getCacheStorageTransform('fs'); + + expect(transform(MEMORY_CACHE_MODULE, '#nitro/virtual/cache')?.code).toBe( + `import { instrumentCacheStorage } from "/module/runtime/utils/instrumentStorage"; +import { createMemoryStorage } from "ocache"; +const createUninstrumentedCacheStorage = () => createMemoryStorage({}); + +export const cacheFunctionDefaults = {}; + +export const createCacheStorage = () => instrumentCacheStorage(createUninstrumentedCacheStorage(), "fs"); +`, + ); + }); + + it('defaults the driver name to the default memory driver', () => { + const transform = getCacheStorageTransform(); + + expect(transform(MEMORY_CACHE_MODULE, '#nitro/virtual/cache')?.code).toContain( + 'instrumentCacheStorage(createUninstrumentedCacheStorage(), "memory")', + ); + }); + + it('leaves the kv driver to the storage driver instrumentation', () => { + const transform = getCacheStorageTransform('kv'); + + expect( + transform( + 'export { createKVCacheStorage as createCacheStorage } from "#nitro/runtime/cache-kv";', + '#nitro/virtual/cache', + ), + ).toBeNull(); + }); + + it('ignores other modules', () => { + const transform = getCacheStorageTransform(); + + expect(transform(MEMORY_CACHE_MODULE, '/app/server/api/cache.ts')).toBeNull(); + }); +}); From 90c9bf087964f76c6a8f094caa9de291f58f1981 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:13:38 +0100 Subject: [PATCH 063/136] chore(build): Remove build:watch scripts (#26350) **Why:** The `build:watch` / `build:dev:watch` scripts get very little use. The top-level `nx run-many -t build:watch` doesn't even work: watch tasks never finish, so Nx's parallel slots fill up and the remaining packages never start. This removes every `build*:watch` script (root and all packages, including the `build:transpile:watch` / `build:bundle:watch` / `build:types:watch` helpers) and the `build:dev:watch` entry in `CONTRIBUTING.md`. **How to review:** It only deletes `package.json` scripts. Nothing else (CI, nx.json, other scripts) referenced them. E2E test applications keep their own scripts. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794563303.955889) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794563303.955889/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- CONTRIBUTING.md | 3 +-- package.json | 2 -- packages/angular/package.json | 3 --- packages/astro/package.json | 3 --- packages/aws-serverless/package.json | 3 --- packages/browser-utils/package.json | 3 --- packages/browser/package.json | 4 ---- packages/bun/package.json | 3 --- packages/bundler-plugins/package.json | 3 --- packages/cloudflare/package.json | 3 --- packages/core/package.json | 3 --- packages/effect/package.json | 3 --- packages/elysia/package.json | 3 --- packages/ember/package.json | 1 - packages/esbuild-plugin/package.json | 3 --- packages/feedback/package.json | 4 ---- packages/gatsby/package.json | 3 --- packages/google-cloud-serverless/package.json | 3 --- packages/hono/package.json | 3 --- packages/integration-shims/package.json | 3 --- packages/nestjs/package.json | 3 --- packages/nextjs/package.json | 3 --- packages/nitro/package.json | 4 ---- packages/node-native/package.json | 2 -- packages/node/package.json | 3 --- packages/nuxt/package.json | 3 --- packages/opentelemetry/package.json | 3 --- packages/profiling-node/package.json | 2 -- packages/react-router/package.json | 3 --- packages/react/package.json | 3 --- packages/remix/package.json | 3 --- packages/replay-canvas/package.json | 4 ---- packages/replay-internal/package.json | 4 ---- packages/replay-worker/package.json | 3 --- packages/rollup-plugin/package.json | 3 --- packages/server-runtime-injection/package.json | 3 --- packages/server-utils/package.json | 3 --- packages/solid/package.json | 3 --- packages/solidstart/package.json | 3 --- packages/svelte/package.json | 3 --- packages/sveltekit/package.json | 3 --- packages/tanstackstart-react/package.json | 3 --- packages/vercel-edge/package.json | 3 --- packages/vite-plugin/package.json | 3 --- packages/vue/package.json | 3 --- packages/wasm/package.json | 4 ---- packages/webpack-plugin/package.json | 3 --- 47 files changed, 1 insertion(+), 141 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 79a1beab5799..dfad37a4c049 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,13 +46,12 @@ doesn't match the repo, see [Node.js and pnpm Versions](#nodejs-and-pnpm-version ## Building Packages Since we are using [`TypeScript`](https://www.typescriptlang.org/), you need to transpile the code to JavaScript to be -able to use it. From the top level of the repo, there are three commands available: +able to use it. From the top level of the repo, there are two commands available: - `pnpm run build:dev`, which runs a one-time build of every package - `pnpm run build:dev:filter `, which runs `pnpm run build:dev` only in projects relevant to the given package (so, for example, running `pnpm run build:dev:filter @sentry/react` will build the `react` package, all of its dependencies (`utils`, `core`, `browser`, etc), and all packages which depend on it (currently `gatsby` and `nextjs`)) -- `pnpm run build:dev:watch`, which runs `pnpm run build:dev` in watch mode (recommended) Note: Due to package incompatibilities between Python versions, building native binaries currently requires a Python version <3.12. diff --git a/package.json b/package.json index 7ea21a7e2067..b4d705ce6f7a 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,6 @@ "build:dev:filter": "nx run-many -t build:dev -p", "build:transpile": "nx run-many -t build:transpile", "build:types": "nx run-many -t build:types", - "build:watch": "nx run-many -t build:watch", - "build:dev:watch": "nx run-many -t build:dev:watch", "build:tarball": "run-s clean:tarballs build:tarballs", "build:tarballs": "nx run-many -t build:tarball", "ci:print-build-artifact-paths": "node ./scripts/ci-print-build-artifact-paths.mjs", diff --git a/packages/angular/package.json b/packages/angular/package.json index 85cf9434eb22..b8942e05027f 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -46,9 +46,6 @@ "build": "pnpm run build:transpile", "build:transpile": "ng build --configuration production", "build:dev": "pnpm run build", - "build:watch": "pnpm run build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "ng build --configuration production --watch", "build:tarball": "pnpm --dir build pack --pack-destination ..", "clean": "node ../../scripts/rm.mjs build coverage sentry-angular-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/astro/package.json b/packages/astro/package.json index 86c4623bdf99..ee1c7032d8f1 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -84,9 +84,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-astro-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 9ca445d6fa29..651d43594316 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -86,9 +86,6 @@ "build:transpile": "run-s build:transpile:npm build:extension", "build:transpile:npm": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build dist-awslambda-layer coverage sentry-serverless-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index ebfdc40be99a..f82f2fe0f811 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -45,9 +45,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-browser-utils-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/browser/package.json b/packages/browser/package.json index c63397ee82ba..c8f530efe3c8 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -56,10 +56,6 @@ "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:bundle:watch": "rolldown -c rollup.bundle.config.mjs --watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage .rpt2_cache sentry-browser-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/bun/package.json b/packages/bun/package.json index 8d5aa84401c6..c7fd4850b447 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -58,9 +58,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-bun-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index a4abe848d02c..a39ef349e968 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -77,9 +77,6 @@ "build:version": "node -p \"'export const LIB_VERSION = ' + JSON.stringify(require('./package.json').version) + ';'\" > src/core/version.ts", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "prebuild": "pnpm run build:version", "precheck:types": "pnpm run build:version", diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 00523b4e4a39..95fed1b2d387 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -88,9 +88,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-cloudflare-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/core/package.json b/packages/core/package.json index 92c4ebc10bd8..1c955b71f20e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -72,9 +72,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-core-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/effect/package.json b/packages/effect/package.json index 58ecc48eb5ac..d578087bdb24 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -67,9 +67,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-effect-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/elysia/package.json b/packages/elysia/package.json index f647f32bb9dc..30f03c0fbb69 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -54,9 +54,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-elysia-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/ember/package.json b/packages/ember/package.json index b124efedc9c5..ba1c97d5cb27 100644 --- a/packages/ember/package.json +++ b/packages/ember/package.json @@ -29,7 +29,6 @@ "build": "rollup --config", "build:dev": "pnpm run build", "build:tarball": "pnpm pack", - "build:watch": "rollup --config --watch", "clean": "node ../../scripts/rm.mjs dist declarations *.tgz .turbo", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/esbuild-plugin/package.json b/packages/esbuild-plugin/package.json index 5c2075d58fe9..ecc777455800 100644 --- a/packages/esbuild-plugin/package.json +++ b/packages/esbuild-plugin/package.json @@ -37,9 +37,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-esbuild-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/feedback/package.json b/packages/feedback/package.json index fffb9e6b72b2..2dad2dd77ea7 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -45,10 +45,6 @@ "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "pnpm run build:transpile --watch", - "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-feedback-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index bd76356eecef..4b38bf93f1f0 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -59,9 +59,6 @@ "build:transpile": "run-p build:rollup build:plugin", "build:rollup": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage *.d.ts sentry-gatsby-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index c14d67945949..41314b5eb33c 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -63,9 +63,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-google-cloud-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/hono/package.json b/packages/hono/package.json index 74c4d28cc09f..1540e4e5ae07 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -118,9 +118,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-hono-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/integration-shims/package.json b/packages/integration-shims/package.json index fc36769f0de3..99d183a80ba0 100644 --- a/packages/integration-shims/package.json +++ b/packages/integration-shims/package.json @@ -28,9 +28,6 @@ "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm run build", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "run-p build:watch", - "build:transpile:watch": "pnpm run build:transpile --watch", "clean": "node ../../scripts/rm.mjs build", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index 746c48f365e6..4f839a87959e 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -77,9 +77,6 @@ "build:types": "run-s build:types:core build:types:setup", "build:types:core": "tsc -p tsconfig.types.json", "build:types:setup": "tsc -p tsconfig.setup-types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nestjs-*.tgz ./*.d.ts ./*.d.ts.map", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 69bfefa7fd92..460c4aec584f 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -133,9 +133,6 @@ "build:dev": "pnpm run build", "build:transpile": "tsx --tsconfig tsconfig.tsnode.json scripts/buildRollup.ts", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "tsx watch --tsconfig tsconfig.tsnode.json --include src --clear-screen=false scripts/buildRollup.ts", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nextjs-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 873f0893d713..12b88bece70a 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -54,10 +54,6 @@ "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core", "build:types:core": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:types:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", - "build:types:watch": "tsc -p tsconfig.types.json --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nitro-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/node-native/package.json b/packages/node-native/package.json index 880063f1ea53..f5337eb4b677 100644 --- a/packages/node-native/package.json +++ b/packages/node-native/package.json @@ -50,8 +50,6 @@ "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm clean && pnpm run build", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", - "build:watch": "run-p build:transpile:watch", "build:tarball": "pnpm pack" }, "dependencies": { diff --git a/packages/node/package.json b/packages/node/package.json index 16a511f2f9e6..81e61c1f1cab 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -94,9 +94,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-node-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 1d7750057282..90911a154f6d 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -85,9 +85,6 @@ "build:nuxt-module": "rolldown -c rollup.module.config.mjs && tsc -p tsconfig.module.json && node scripts/build-module-meta.mjs", "build:transpile": "rolldown -c rollup.npm.config.mjs && pnpm run build:nuxt-module", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nuxt-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 380fe0d71354..8e7c1070da83 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -42,9 +42,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-opentelemetry-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/profiling-node/package.json b/packages/profiling-node/package.json index 02a916ccbf0a..088e8557136d 100644 --- a/packages/profiling-node/package.json +++ b/packages/profiling-node/package.json @@ -42,8 +42,6 @@ "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm clean && pnpm run build", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", - "build:watch": "run-p build:transpile:watch", "build:tarball": "pnpm pack", "test:bundle": "node test-binaries.esbuild.js", "test": "vitest run", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 341ee22d26d8..56fac5778445 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -88,9 +88,6 @@ "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "run-s build:types:core", "build:types:core": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-router-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/react/package.json b/packages/react/package.json index 1400559fbc1c..755b92b2c023 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -93,9 +93,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/remix/package.json b/packages/remix/package.json index 9ee8d87c357c..0d6807ee7c15 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -112,9 +112,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-remix-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index 7abc0cc76ce6..ee4e3c30ee5c 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -29,10 +29,6 @@ "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "pnpm run build:transpile --watch", - "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 0dec99748bb4..131723e9cdd5 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -43,10 +43,6 @@ "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:dev": "run-p build:transpile build:types", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "pnpm run build:transpile --watch", - "build:bundle:watch": "pnpm run build:bundle --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", "format": "oxfmt \"src/**/*.ts\" \"test/**/*.ts\" --write", diff --git a/packages/replay-worker/package.json b/packages/replay-worker/package.json index db0dd63e05c6..b4a4e758b088 100644 --- a/packages/replay-worker/package.json +++ b/packages/replay-worker/package.json @@ -33,9 +33,6 @@ "build:examples": "rolldown -c rollup.examples.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm run build", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "pnpm run build:transpile --watch", "clean": "node ../../scripts/rm.mjs build", "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", diff --git a/packages/rollup-plugin/package.json b/packages/rollup-plugin/package.json index 2b2f0b2241f1..2d2234f1f2f5 100644 --- a/packages/rollup-plugin/package.json +++ b/packages/rollup-plugin/package.json @@ -38,9 +38,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-rollup-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/server-runtime-injection/package.json b/packages/server-runtime-injection/package.json index ef8b0b9e2cf8..ca4ffbd9beb5 100644 --- a/packages/server-runtime-injection/package.json +++ b/packages/server-runtime-injection/package.json @@ -62,9 +62,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-server-runtime-injection-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 182ba3b08e5f..4f831eaf6242 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -119,9 +119,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-server-utils-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/solid/package.json b/packages/solid/package.json index 1b1cb8bd1f22..03abfd2b5242 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -90,9 +90,6 @@ "build:types": "run-s build:types:core build:types:routers", "build:types:core": "tsc -p tsconfig.types.json", "build:types:routers": "tsc -p tsconfig.routers-types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-solid-*.tgz ./*.d.ts ./*.d.ts.map", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index d6a88ef69c46..d9586fdf3541 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -116,9 +116,6 @@ "build:types": "run-s build:types:core build:types:subexports", "build:types:core": "tsc -p tsconfig.types.json", "build:types:subexports": "tsc -p tsconfig.subexports-types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-solidstart-*.tgz ./*.d.ts ./*.d.ts.map ./client ./server", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index e8cdcf514716..6e63941b559e 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -52,9 +52,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-svelte-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 0b91191f427b..551b30fbd69d 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -98,9 +98,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-sveltekit-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 1c71cefb9a39..2a1375d1c24d 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -71,9 +71,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-tanstackstart-react-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index 7b1eb06ae1db..f0a9b86473da 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -46,9 +46,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-vercel-edge-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.json index 0a4a7f8ad4f8..643cb47bfd71 100644 --- a/packages/vite-plugin/package.json +++ b/packages/vite-plugin/package.json @@ -37,9 +37,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-vite-plugin-*.tgz", "lint": "oxlint . --type-aware", diff --git a/packages/vue/package.json b/packages/vue/package.json index 76b557061200..f33cdfab4920 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -73,9 +73,6 @@ "build:types": "run-s build:types:core build:types:router", "build:types:core": "tsc -p tsconfig.types.json", "build:types:router": "tsc -p tsconfig.router-types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-vue-*.tgz", "lint:fix": "oxlint . --fix --type-aware", diff --git a/packages/wasm/package.json b/packages/wasm/package.json index cd18e858109d..8054f94f5c73 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -44,10 +44,6 @@ "build:dev": "run-p build:transpile build:types", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch build:bundle:watch", - "build:bundle:watch": "rolldown --config rollup.bundle.config.mjs --watch", - "build:dev:watch": "run-p build:transpile:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index 207a41039015..b3a8d58f789f 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -42,9 +42,6 @@ "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", - "build:watch": "run-p build:transpile:watch", - "build:dev:watch": "pnpm run build:watch", - "build:transpile:watch": "rolldown -c rollup.npm.config.mjs --watch", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-webpack-plugin-*.tgz", "lint": "oxlint . --type-aware", From cb9e84cdfa190c047acac65477f2d9004c21b945 Mon Sep 17 00:00:00 2001 From: bardrop Date: Fri, 13 Nov 2026 15:46:15 +0530 Subject: [PATCH 064/136] fix(core): Always return a string from `_enhanceErrorWithSentryInfo` (#26349) **Why:** `Error.message` is typed as a string, but code can assign anything to it. A number, object or function then ended up as `exception.value`, and an event processor that calls a string method on it (here `DropReactControlFlowErrors` in `@sentry/nextjs`) threw, so the event was dropped before `beforeSend`. As suggested in the issue, this makes `_enhanceErrorWithSentryInfo` always return a string instead of guarding each processor. Primitives go through `String()`, objects through the existing `stringify` (JSON), with `stringifyValue` as the fallback for functions and circular objects (`[Function: name]`, `[object Object]`). `null`/`undefined` become `''`, which keeps them falsy, so the browser `'No error message'` path is unchanged. **How to review:** `packages/core/src/utils/eventbuilder.ts`, then the new `exceptionFromError` cases in the test file (all fail on `develop`). **Unsure about:** JSON for object messages. `{"code":42}` reads better than `[object Object]`, but tell me if you'd rather keep it shorter. Closes #26329 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Martin Sonnberger --- packages/core/src/utils/eventbuilder.ts | 36 ++++++++++++++-- .../core/test/lib/utils/eventbuilder.test.ts | 41 +++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/packages/core/src/utils/eventbuilder.ts b/packages/core/src/utils/eventbuilder.ts index 9b300c59c593..2e8445ed5878 100644 --- a/packages/core/src/utils/eventbuilder.ts +++ b/packages/core/src/utils/eventbuilder.ts @@ -7,10 +7,11 @@ import type { ParameterizedString } from '../types/parameterize'; import type { SeverityLevel } from '../types/severity'; import type { StackFrame } from '../types/stackframe'; import type { StackParser } from '../types/stacktrace'; -import { isError, isErrorEvent, isParameterizedString, isPlainObject } from './is'; +import { isError, isErrorEvent, isParameterizedString, isPlainObject, isPrimitive } from './is'; import { addExceptionMechanism, addExceptionTypeValue } from './misc'; -import { normalizeToSize } from './normalize'; +import { normalizeToSize, stringifyValue } from './normalize'; import { extractExceptionKeysForMessage } from './object'; +import { stringify } from './string'; /** * Extracts stack frames from the error.stack string @@ -32,13 +33,40 @@ function hasSentryFetchUrlHost(error: unknown): error is Error & { __sentry_fetc * @hidden */ export function _enhanceErrorWithSentryInfo(error: T): string { + const message = errorMessageToString(error.message); + // If the error has a __sentry_fetch_url_host__ property (added by fetch instrumentation), // enhance the error message with the hostname. if (hasSentryFetchUrlHost(error)) { - return `${error.message} (${error.__sentry_fetch_url_host__})`; + return `${message} (${error.__sentry_fetch_url_host__})`; + } + + return message; +} + +// `message` is typed as a string, but user code can assign anything to it, and event processors +// call string methods on `exception.value`. +function errorMessageToString(message: unknown): string { + if (typeof message === 'string') { + return message; + } + + if (message == null) { + return ''; + } + + if (isPrimitive(message)) { + return String(message); + } + + if (isPlainObject(message) || Array.isArray(message)) { + const json = stringify(message, ''); + if (json) { + return json; + } } - return error.message; + return stringifyValue(undefined, message); } /** diff --git a/packages/core/test/lib/utils/eventbuilder.test.ts b/packages/core/test/lib/utils/eventbuilder.test.ts index 2a08f073117e..5a2fcc003419 100644 --- a/packages/core/test/lib/utils/eventbuilder.test.ts +++ b/packages/core/test/lib/utils/eventbuilder.test.ts @@ -308,5 +308,46 @@ describe('eventFromMessage', () => { const exception = exceptionFromError(stackParser, error); expect(exception.value).toBe('Failed to fetch (localhost:8080)'); }); + + it('should enhance a non-string message', () => { + const error = new TypeError('placeholder'); + (error as { message: unknown }).message = { code: 42 }; + addNonEnumerableProperty(error, '__sentry_fetch_url_host__', 'example.com'); + + const exception = exceptionFromError(stackParser, error); + expect(exception.value).toBe('{"code":42} (example.com)'); + }); + }); +}); + +describe('exceptionFromError', () => { + const circular: Record = { code: 42 }; + circular.self = circular; + + it.each([ + ['a number', 42, '42'], + ['a bigint', BigInt(42), '42'], + ['a boolean', false, 'false'], + ['undefined', undefined, ''], + ['null', null, ''], + ['an object', { code: 42 }, '{"code":42}'], + ['an array', [1, 'two'], '[1,"two"]'], + ['a circular object', circular, '[object Object]'], + ['a function', function namedFn() {}, '[Function: namedFn]'], + ['an error', new Error('inner'), '[object Error]'], + ['a map', new Map([['code', 42]]), '[object Map]'], + [ + 'a class instance', + new (class CustomMessage { + code = 42; + })(), + '{"code":42}', + ], + ])('turns %s into a string', (_, message, expected) => { + const error = new Error('placeholder'); + (error as { message: unknown }).message = message; + + const exception = exceptionFromError(stackParser, error); + expect(exception.value).toBe(expected); }); }); From 4ab39ab190156ad2f5746e2aedc711a10e5f6261 Mon Sep 17 00:00:00 2001 From: "javascript-sdk-gitflow[bot]" <255134079+javascript-sdk-gitflow[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:18:26 +0000 Subject: [PATCH 065/136] chore: Add external contributor to CHANGELOG.md (#26351) This PR adds the external contributor to the CHANGELOG.md file, so that they are credited for their contribution. See #26349 Co-authored-by: msonnb <26038247+msonnb@users.noreply.github.com> --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6f2a8fecca0..3dd358e57fb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott -Work in this release was contributed by @kunal649. Thank you for your contribution! +Work in this release was contributed by @kunal649 and @bardrop. Thank you for your contributions! ### Important Changes From f5a71526dd90b77aa0978cb3479fba95b1f3b1ac Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:22:40 +0100 Subject: [PATCH 066/136] chore(ci): Move reviewer routing out of CODEOWNERS (#26346) **Why:** The sub-teams' "Only notify requested team members" setting (managed in security-as-code) only stops the team-wide notification if a team member is *already* requested when the team request lands. GitHub requests the CODEOWNERS teams the moment a PR is opened or marked ready. `assign-reviewers` requests individuals about 10s later. That's too late, so the whole sub-team still gets pinged. In #26343, for example, `team-javascript-sdks-framework` was requested at 07:03:05 and the workflow's picks at 07:03:15. No ruleset requires code owner review (`require_code_owner_review: false` on develop, master, v7 and v8/9/10). CODEOWNERS only routes reviewers, and the workflow does that now. So the same rules move to `.github/REVIEWERS`, which GitHub ignores and only the workflow reads. The sub-teams stop getting team requests, and the workflow keeps picking 3 people from them. The develop ruleset still requests `team-javascript-sdks` on every PR. getsentry/security-as-code#3923 turns on auto-assignment of 1 member for that team, so GitHub requests a person together with the team and the whole team isn't notified. GitHub can pick a manager there, and Terraform can't exclude members from auto-assignment. So pending review requests from `NEVER_REQUEST` users don't count towards the 3, and the workflow still requests 3 other people. A PR can end up with 4 requested reviewers. **How to review:** The rename plus the two path changes (the rules didn't change), then the `NEVER_REQUEST` filter in `scripts/assign-reviewers.mjs`. **Unsure about:** - We lose GitHub's "owned by" badge in the file view and the code owner shortcut in the reviewer picker. - Reviews that managers have already submitted still count towards the 3. Only pending requests are skipped. - GitHub's pick isn't filtered for the requester of a Junior PR the way the workflow's picks are. - `pull_request_target` runs the base branch's workflow, so this PR still routes reviewers from the old path until it merges. - Merge together with getsentry/security-as-code#3923. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794557278.893269) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794557278.893269/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .github/{CODEOWNERS => REVIEWERS} | 5 +++++ .github/workflows/assign-reviewers.yml | 2 +- scripts/assign-reviewers.mjs | 12 ++++++++---- scripts/assign-reviewers.test.mjs | 20 ++++++++++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) rename .github/{CODEOWNERS => REVIEWERS} (92%) diff --git a/.github/CODEOWNERS b/.github/REVIEWERS similarity index 92% rename from .github/CODEOWNERS rename to .github/REVIEWERS index a6dc12f405db..e534da992d3d 100644 --- a/.github/CODEOWNERS +++ b/.github/REVIEWERS @@ -1,3 +1,8 @@ +# Reviewer routing for scripts/assign-reviewers.mjs, in CODEOWNERS syntax. +# This is deliberately not a CODEOWNERS file: GitHub requests every matching +# code owner team as soon as a PR opens, before the workflow requests anyone, +# so the whole team gets notified. + # Browser, replay, feedback, and related packages /packages/browser/ @getsentry/team-javascript-sdks-browser /packages/browser-utils/ @getsentry/team-javascript-sdks-browser diff --git a/.github/workflows/assign-reviewers.yml b/.github/workflows/assign-reviewers.yml index e8d11ae70c20..60e541dcb775 100644 --- a/.github/workflows/assign-reviewers.yml +++ b/.github/workflows/assign-reviewers.yml @@ -34,7 +34,7 @@ jobs: uses: actions/checkout@v7 with: sparse-checkout: | - .github/CODEOWNERS + .github/REVIEWERS scripts/assign-reviewers.mjs scripts/junior-requesters.mjs sparse-checkout-cone-mode: false diff --git a/scripts/assign-reviewers.mjs b/scripts/assign-reviewers.mjs index ee6122f71d39..2120f7bdd5cd 100644 --- a/scripts/assign-reviewers.mjs +++ b/scripts/assign-reviewers.mjs @@ -3,9 +3,10 @@ import * as fs from 'fs'; import { getJuniorRequesters, TEAM_SLUG } from './junior-requesters.mjs'; const REQUIRED_REVIEWERS = 3; -// Managers who are members (and code owners) of the SDK teams, but should never be auto-requested for review. +// Managers who are members of the SDK teams, but should never be auto-requested for review. +// GitHub's team auto-assignment can still pick them, so their pending requests don't count towards the required reviewers. const NEVER_REQUEST = ['mydea', 'stephanie-anderson']; -const CODEOWNERS_PATH = '.github/CODEOWNERS'; +const REVIEWERS_PATH = '.github/REVIEWERS'; function patternToRegExp(pattern) { let p = pattern; @@ -100,12 +101,15 @@ export async function assignReviewers({ github, context, core }) { // Whoever asked Junior for the PR is its de facto author. const requesters = await getJuniorRequesters({ github, core, pr: currentPr }); + const neverRequest = new Set(NEVER_REQUEST.map(login => login.toLowerCase())); + const requestedReviewers = currentPr.requested_reviewers.filter(user => !neverRequest.has(user.login.toLowerCase())); + const reviews = await github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number }); // Requested reviewers drop off `requested_reviewers` once they submit a review, so count both. // Bots (AI reviewers) don't count towards the required reviewers. const existing = [ ...new Set( - [...currentPr.requested_reviewers, ...reviews.map(r => r.user)] + [...requestedReviewers, ...reviews.map(r => r.user)] .filter(user => user && user.type !== 'Bot' && user.login.toLowerCase() !== author.toLowerCase()) .map(user => user.login), ), @@ -120,7 +124,7 @@ export async function assignReviewers({ github, context, core }) { (await github.paginate(github.rest.teams.listMembersInOrg, { org: owner, team_slug })).map(m => m.login); const files = (await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number })).map(f => f.filename); - const codeowners = getOwnersForFiles(parseCodeowners(fs.readFileSync(CODEOWNERS_PATH, 'utf8')), files); + const codeowners = getOwnersForFiles(parseCodeowners(fs.readFileSync(REVIEWERS_PATH, 'utf8')), files); const codeownerPool = []; for (const codeowner of codeowners) { diff --git a/scripts/assign-reviewers.test.mjs b/scripts/assign-reviewers.test.mjs index 5ff6877615e6..0628ad394373 100644 --- a/scripts/assign-reviewers.test.mjs +++ b/scripts/assign-reviewers.test.mjs @@ -88,4 +88,24 @@ describe('assignReviewers', () => { expect.objectContaining({ reviewers: expect.arrayContaining(['b', 'c', 'd']) }), ); }); + + it('does not count pending review requests from managers towards the required reviewers', async () => { + const { github, run } = setup(assignReviewers, { + user: { login: 'author', type: 'User' }, + requested_reviewers: [ + { login: 'Mydea', type: 'User' }, + { login: 'a', type: 'User' }, + ], + }); + await run(); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: [expect.any(String), expect.any(String)] }), + ); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: expect.not.arrayContaining(['a']) }), + ); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: expect.not.arrayContaining(['Mydea']) }), + ); + }); }); From 7dcc4b1a4728e1c4168d212c15706a34edad6b28 Mon Sep 17 00:00:00 2001 From: Sigrid <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:27:57 +0100 Subject: [PATCH 067/136] feat(nuxt): Mark pageloads of cached pages (#26305) **Why:** Visitors of a Nuxt page cached by a route rule (`cache`, `swr`, `isr` on Vercel/Netlify) continued the server trace of the request that rendered it. Like Next.js (#25318) and SvelteKit (#26301), these pages now get a `sentry-cache-origin` meta tag in place of the trace tags. The pageload is `static` and links the render if it was sampled. `isr` only counts as cached on presets with a platform cache: on `node-server`, Nitro renders `isr` pages per request. Tested on a Vercel deploy. **How to review:** Start with `runtime/utils/pageMetaTags.ts` (server decision) and `runtime/utils/cacheOriginPageload.ts` (pageload). **Unsure about:** `withCacheOrigin` now exists in Next.js, SvelteKit and Nuxt. I plan to share it from `@sentry/browser` in a follow-up. Example with the UI changes from https://github.com/getsentry/sentry/pull/130771 image https://sentry-4x3dkn58u.sentry.dev/explore/traces/trace/e7492219ab72481989d6a2cd670fe8d9/ Linear: [JSSDK-36 ](https://linear.app/getsentry/issue/JSSDK-36/nuxt-rendering-modes) --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 + .../test-applications/nuxt-4/package.json | 1 + .../nuxt-4/tests/tracing.cached-html.test.ts | 132 +++++++++------ .../test-applications/nuxt-5/package.json | 1 + .../nuxt-5/tests/tracing.cached-html.test.ts | 133 +++++++++------ .../plugins/sentry-cloudflare.server.ts | 6 +- .../nuxt/src/runtime/plugins/sentry.client.ts | 7 +- .../nuxt/src/runtime/plugins/sentry.server.ts | 27 +-- .../src/runtime/utils/cacheOriginMetaTag.ts | 5 + .../src/runtime/utils/cacheOriginPageload.ts | 46 ++++++ .../nuxt/src/runtime/utils/pageMetaTags.ts | 74 +++++++++ packages/nuxt/src/vite/utils.ts | 6 +- .../nuxt/test/runtime/plugins/client.test.ts | 33 +++- .../runtime/utils/cacheOriginPageload.test.ts | 100 +++++++++++ .../test/runtime/utils/pageMetaTags.test.ts | 155 ++++++++++++++++++ .../nuxt/test/vite/addServerConfig.test.ts | 1 + 16 files changed, 604 insertions(+), 127 deletions(-) create mode 100644 packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts create mode 100644 packages/nuxt/src/runtime/utils/cacheOriginPageload.ts create mode 100644 packages/nuxt/src/runtime/utils/pageMetaTags.ts create mode 100644 packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts create mode 100644 packages/nuxt/test/runtime/utils/pageMetaTags.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dd358e57fb1..c18ccce7fe07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ Work in this release was contributed by @kunal649 and @bardrop. Thank you for yo ### Important Changes +- **feat(nuxt): Mark pageloads of cached pages ([#26305](https://github.com/getsentry/sentry-javascript/pull/26305))** + + When Nuxt serves a cached or prerendered page, for example with a `swr` or `isr` route rule, the pageload now has the `page.server_rendering.type: static` attribute and starts its own trace. If the request that rendered the cached page was sampled, the pageload also links to it. So visitors of a cached page no longer continue the trace of the request that rendered it. + - **feat(bundler-plugins): Enable hidden source maps and remove them after upload ([#25637](https://github.com/getsentry/sentry-javascript/pull/25637), [#25645](https://github.com/getsentry/sentry-javascript/pull/25645), [#25646](https://github.com/getsentry/sentry-javascript/pull/25646), [#25647](https://github.com/getsentry/sentry-javascript/pull/25647), [#25648](https://github.com/getsentry/sentry-javascript/pull/25648))** The Sentry Rollup, Vite, webpack and esbuild plugins now turn on hidden source maps when your bundler has no source maps enabled and the plugin can upload them. They upload the maps to Sentry and remove them from the build output. You no longer need to set `sourcemap: 'hidden'` or `filesToDeleteAfterUpload` globs: diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json index 35f5a25b7a42..a1cd9f3a8596 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json @@ -32,6 +32,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", + "@sentry/conventions": "0.32.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts index 42ed5115020c..f990f2bd3c3e 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts @@ -1,4 +1,5 @@ import { expect, test, type Page } from '@playwright/test'; +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; import { isViteServer, NO_META_TAGS } from './isViteServer'; @@ -18,16 +19,19 @@ test.describe('Rendering Modes with Cached HTML', () => { await testChangingTracingMetaTagsOnISRPage(page, '/rendering-modes/isr-1h-cached-page', 'ISR 1h Cached Page'); }); - test('exclude tracing meta tags on SWR-cached page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-cached-page', 'SWR Cached Page'); + test('links the render as cache origin on SWR-cached page', async ({ page }) => { + test.fail(isViteServer, NO_META_TAGS); + await testCacheOriginOnRuntimeCachedPage(page, '/rendering-modes/swr-cached-page', 'SWR Cached Page'); }); - test('exclude tracing meta tags on SWR 1h cached page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-1h-cached-page', 'SWR 1h Cached Page'); + test('links the render as cache origin on SWR 1h cached page', async ({ page }) => { + test.fail(isViteServer, NO_META_TAGS); + await testCacheOriginOnRuntimeCachedPage(page, '/rendering-modes/swr-1h-cached-page', 'SWR 1h Cached Page'); }); - test('exclude tracing meta tags on pre-rendered page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/pre-rendered-page', 'Pre-Rendered Page'); + test('marks pageloads of pre-rendered page as static without a cache origin link', async ({ page }) => { + test.fail(isViteServer, NO_META_TAGS); + await testEmptyCacheOriginOnPrerenderedPage(page, '/rendering-modes/pre-rendered-page', 'Pre-Rendered Page'); }); }); @@ -122,26 +126,25 @@ export async function testChangingTracingMetaTagsOnISRPage( }); } +async function getCacheOriginMetaTag(page: Page): Promise { + await expect(page.locator('meta[name="sentry-cache-origin"]')).toHaveCount(1); + expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); + expect(await page.locator('meta[name="baggage"]').count()).toBe(0); + return page.locator('meta[name="sentry-cache-origin"]').getAttribute('content'); +} + /** - * Tests that tracing meta-tags are excluded on cached pages (SWR, pre-rendered, etc.) - * This utility handles the common pattern of: - * 1. Making two requests to a cached page - * 2. Verifying no tracing meta-tags are present - * 3. Verifying traces are not distributed (each pageload starts its own trace) - * - * @param page - Playwright page object - * @param routePath - The route path to test (e.g., '/rendering-modes/swr-cached-page') - * @param expectedPageText - The text to verify is visible on the page (e.g., 'SWR Cached Page') + * Tests a page that a route rule caches at runtime. The cached HTML holds the `sentry-trace` value of + * the render in a `sentry-cache-origin` tag. Every pageload starts its own trace, is static, and links + * the render. */ -export async function testExcludeTracingMetaTagsOnCachedPage( +export async function testCacheOriginOnRuntimeCachedPage( page: Page, routePath: string, expectedPageText: string, ): Promise { - // === 1. Request === + // === 1. Request (renders and fills the cache) === const clientSpanPromise1 = waitForPageloadSegment(routePath); - - // Only the 1. request creates a server root span const serverSpanPromise1 = waitForServerSegment(routePath); const [_1, clientSpan1, serverSpan1] = await Promise.all([ @@ -150,13 +153,9 @@ export async function testExcludeTracingMetaTagsOnCachedPage( serverSpanPromise1, expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); + const cacheOrigin1 = await getCacheOriginMetaTag(page); - // Verify no baggage and sentry-trace meta-tags are present on first request - expect(await page.locator('meta[name="baggage"]').count()).toBe(0); - expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); - - // === 2. Request === - + // === 2. Request (served from the cache) === const clientSpanPromise2 = waitForPageloadSegment(routePath); const [_2, clientSpan2] = await Promise.all([ @@ -164,30 +163,71 @@ export async function testExcludeTracingMetaTagsOnCachedPage( clientSpanPromise2, expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); - - const clientSpan1TraceId = clientSpan1.trace_id; - const clientSpan2TraceId = clientSpan2.trace_id; - - const serverSpan1TraceId = serverSpan1.trace_id; - - await test.step('No baggage and sentry-trace meta-tags are present on second request', async () => { - expect(await page.locator('meta[name="baggage"]').count()).toBe(0); - expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); - }); - - await test.step('1. server root span and all client root spans are defined', () => { - expect(serverSpan1TraceId).toBeDefined(); - expect(clientSpan1TraceId).toBeDefined(); - expect(clientSpan2TraceId).toBeDefined(); + const cacheOrigin2 = await getCacheOriginMetaTag(page); + + const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? []; + const cacheOriginLink = { + trace_id: serverSpan1.trace_id, + span_id: originSpanId, + sampled: true, + attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'cache_origin' } }, + }; + + await test.step('The cache origin tag holds the sampled render of the 1. request', () => { + expect(originTraceId).toBe(serverSpan1.trace_id); + expect(originSpanId).toMatch(/^[a-f0-9]{16}$/); + expect(originSampled).toBe('1'); + expect(cacheOrigin2).toBe(cacheOrigin1); }); - await test.step('Trace is not distributed', () => { - // Cannot create distributed trace as HTML Meta Tags are not added (caching leads to multiple usages of the same server trace id) - expect(clientSpan1TraceId).not.toBe(clientSpan2TraceId); - expect(clientSpan1TraceId).not.toBe(serverSpan1TraceId); - expect(clientSpan2TraceId).not.toBe(serverSpan1TraceId); - // Without meta tags the pageloads have no parent and start their own traces + await test.step('Every pageload starts its own trace', () => { expect(clientSpan1.parent_span_id).toBeUndefined(); expect(clientSpan2.parent_span_id).toBeUndefined(); + expect(clientSpan1.trace_id).not.toBe(serverSpan1.trace_id); + expect(clientSpan2.trace_id).not.toBe(serverSpan1.trace_id); + expect(clientSpan1.trace_id).not.toBe(clientSpan2.trace_id); + }); + + await test.step('Every pageload is static and links the render', () => { + expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan1.links).toEqual([cacheOriginLink]); + expect(clientSpan2.links).toEqual([cacheOriginLink]); }); } + +/** + * Tests a page that Nitro prerendered during the build. The SDK does not run in the build, so the + * `sentry-cache-origin` tag is empty: every pageload starts its own trace and is static, without a link. + */ +export async function testEmptyCacheOriginOnPrerenderedPage( + page: Page, + routePath: string, + expectedPageText: string, +): Promise { + const clientSpanPromise1 = waitForPageloadSegment(routePath); + const [_1, clientSpan1] = await Promise.all([ + page.goto(routePath), + clientSpanPromise1, + expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), + ]); + const cacheOrigin1 = await getCacheOriginMetaTag(page); + + const clientSpanPromise2 = waitForPageloadSegment(routePath); + const [_2, clientSpan2] = await Promise.all([ + page.goto(routePath), + clientSpanPromise2, + expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), + ]); + const cacheOrigin2 = await getCacheOriginMetaTag(page); + + expect(cacheOrigin1).toBe(''); + expect(cacheOrigin2).toBe(''); + expect(clientSpan1.parent_span_id).toBeUndefined(); + expect(clientSpan2.parent_span_id).toBeUndefined(); + expect(clientSpan1.trace_id).not.toBe(clientSpan2.trace_id); + expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan1.links).toBeUndefined(); + expect(clientSpan2.links).toBeUndefined(); +} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json index 07c9f3bf9f91..6192f3911a06 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -40,6 +40,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", + "@sentry/conventions": "0.32.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts index 90f197cd8641..e7e209b35468 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts @@ -1,4 +1,5 @@ import { expect, test, type Page } from '@playwright/test'; +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; test.describe('Rendering Modes with Cached HTML', () => { @@ -14,18 +15,16 @@ test.describe('Rendering Modes with Cached HTML', () => { await testChangingTracingMetaTagsOnISRPage(page, '/rendering-modes/isr-1h-cached-page', 'ISR 1h Cached Page'); }); - // fixme - test.skip('exclude tracing meta tags on SWR-cached page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-cached-page', 'SWR Cached Page'); + test('links the render as cache origin on SWR-cached page', async ({ page }) => { + await testCacheOriginOnRuntimeCachedPage(page, '/rendering-modes/swr-cached-page', 'SWR Cached Page'); }); - // fixme - test.skip('exclude tracing meta tags on SWR 1h cached page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/swr-1h-cached-page', 'SWR 1h Cached Page'); + test('links the render as cache origin on SWR 1h cached page', async ({ page }) => { + await testCacheOriginOnRuntimeCachedPage(page, '/rendering-modes/swr-1h-cached-page', 'SWR 1h Cached Page'); }); - test('exclude tracing meta tags on pre-rendered page', async ({ page }) => { - await testExcludeTracingMetaTagsOnCachedPage(page, '/rendering-modes/pre-rendered-page', 'Pre-Rendered Page'); + test('marks pageloads of pre-rendered page as static without a cache origin link', async ({ page }) => { + await testEmptyCacheOriginOnPrerenderedPage(page, '/rendering-modes/pre-rendered-page', 'Pre-Rendered Page'); }); }); @@ -71,6 +70,7 @@ export async function testChangingTracingMetaTagsOnISRPage( expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); + await expect(page.locator('meta[name="baggage"]')).toHaveCount(1); const baggageMetaTagContent1 = await page.locator('meta[name="baggage"]').getAttribute('content'); const sentryTraceMetaTagContent1 = await page.locator('meta[name="sentry-trace"]').getAttribute('content'); const [htmlMetaTraceId1] = sentryTraceMetaTagContent1?.split('-') || []; @@ -87,6 +87,7 @@ export async function testChangingTracingMetaTagsOnISRPage( expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); + await expect(page.locator('meta[name="baggage"]')).toHaveCount(1); const baggageMetaTagContent2 = await page.locator('meta[name="baggage"]').getAttribute('content'); const sentryTraceMetaTagContent2 = await page.locator('meta[name="sentry-trace"]').getAttribute('content'); const [htmlMetaTraceId2] = sentryTraceMetaTagContent2?.split('-') || []; @@ -118,26 +119,25 @@ export async function testChangingTracingMetaTagsOnISRPage( }); } +async function getCacheOriginMetaTag(page: Page): Promise { + await expect(page.locator('meta[name="sentry-cache-origin"]')).toHaveCount(1); + expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); + expect(await page.locator('meta[name="baggage"]').count()).toBe(0); + return page.locator('meta[name="sentry-cache-origin"]').getAttribute('content'); +} + /** - * Tests that tracing meta-tags are excluded on cached pages (SWR, pre-rendered, etc.) - * This utility handles the common pattern of: - * 1. Making two requests to a cached page - * 2. Verifying no tracing meta-tags are present - * 3. Verifying traces are not distributed (each pageload starts its own trace) - * - * @param page - Playwright page object - * @param routePath - The route path to test (e.g., '/rendering-modes/swr-cached-page') - * @param expectedPageText - The text to verify is visible on the page (e.g., 'SWR Cached Page') + * Tests a page that a route rule caches at runtime. The cached HTML holds the `sentry-trace` value of + * the render in a `sentry-cache-origin` tag. Every pageload starts its own trace, is static, and links + * the render. */ -export async function testExcludeTracingMetaTagsOnCachedPage( +export async function testCacheOriginOnRuntimeCachedPage( page: Page, routePath: string, expectedPageText: string, ): Promise { - // === 1. Request === + // === 1. Request (renders and fills the cache) === const clientSpanPromise1 = waitForPageloadSegment(routePath); - - // Only the 1. request creates a server root span const serverSpanPromise1 = waitForServerSegment(routePath); const [_1, clientSpan1, serverSpan1] = await Promise.all([ @@ -146,13 +146,9 @@ export async function testExcludeTracingMetaTagsOnCachedPage( serverSpanPromise1, expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); + const cacheOrigin1 = await getCacheOriginMetaTag(page); - // Verify no baggage and sentry-trace meta-tags are present on first request - expect(await page.locator('meta[name="baggage"]').count()).toBe(0); - expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); - - // === 2. Request === - + // === 2. Request (served from the cache) === const clientSpanPromise2 = waitForPageloadSegment(routePath); const [_2, clientSpan2] = await Promise.all([ @@ -160,30 +156,71 @@ export async function testExcludeTracingMetaTagsOnCachedPage( clientSpanPromise2, expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), ]); - - const clientSpan1TraceId = clientSpan1.trace_id; - const clientSpan2TraceId = clientSpan2.trace_id; - - const serverSpan1TraceId = serverSpan1.trace_id; - - await test.step('No baggage and sentry-trace meta-tags are present on second request', async () => { - expect(await page.locator('meta[name="baggage"]').count()).toBe(0); - expect(await page.locator('meta[name="sentry-trace"]').count()).toBe(0); + const cacheOrigin2 = await getCacheOriginMetaTag(page); + + const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? []; + const cacheOriginLink = { + trace_id: serverSpan1.trace_id, + span_id: originSpanId, + sampled: true, + attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'cache_origin' } }, + }; + + await test.step('The cache origin tag holds the sampled render of the 1. request', () => { + expect(originTraceId).toBe(serverSpan1.trace_id); + expect(originSpanId).toMatch(/^[a-f0-9]{16}$/); + expect(originSampled).toBe('1'); + expect(cacheOrigin2).toBe(cacheOrigin1); }); - await test.step('1. server root span and all client root spans are defined', () => { - expect(serverSpan1TraceId).toBeDefined(); - expect(clientSpan1TraceId).toBeDefined(); - expect(clientSpan2TraceId).toBeDefined(); - }); - - await test.step('Trace is not distributed', () => { - // Cannot create distributed trace as HTML Meta Tags are not added (caching leads to multiple usages of the same server trace id) - expect(clientSpan1TraceId).not.toBe(clientSpan2TraceId); - expect(clientSpan1TraceId).not.toBe(serverSpan1TraceId); - expect(clientSpan2TraceId).not.toBe(serverSpan1TraceId); - // Without meta tags the pageloads have no parent and start their own traces + await test.step('Every pageload starts its own trace', () => { expect(clientSpan1.parent_span_id).toBeUndefined(); expect(clientSpan2.parent_span_id).toBeUndefined(); + expect(clientSpan1.trace_id).not.toBe(serverSpan1.trace_id); + expect(clientSpan2.trace_id).not.toBe(serverSpan1.trace_id); + expect(clientSpan1.trace_id).not.toBe(clientSpan2.trace_id); }); + + await test.step('Every pageload is static and links the render', () => { + expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan1.links).toEqual([cacheOriginLink]); + expect(clientSpan2.links).toEqual([cacheOriginLink]); + }); +} + +/** + * Tests a page that Nitro prerendered during the build. The SDK does not run in the build, so the + * `sentry-cache-origin` tag is empty: every pageload starts its own trace and is static, without a link. + */ +export async function testEmptyCacheOriginOnPrerenderedPage( + page: Page, + routePath: string, + expectedPageText: string, +): Promise { + const clientSpanPromise1 = waitForPageloadSegment(routePath); + const [_1, clientSpan1] = await Promise.all([ + page.goto(routePath), + clientSpanPromise1, + expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), + ]); + const cacheOrigin1 = await getCacheOriginMetaTag(page); + + const clientSpanPromise2 = waitForPageloadSegment(routePath); + const [_2, clientSpan2] = await Promise.all([ + page.goto(routePath), + clientSpanPromise2, + expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(), + ]); + const cacheOrigin2 = await getCacheOriginMetaTag(page); + + expect(cacheOrigin1).toBe(''); + expect(cacheOrigin2).toBe(''); + expect(clientSpan1.parent_span_id).toBeUndefined(); + expect(clientSpan2.parent_span_id).toBeUndefined(); + expect(clientSpan1.trace_id).not.toBe(clientSpan2.trace_id); + expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(clientSpan1.links).toBeUndefined(); + expect(clientSpan2.links).toBeUndefined(); } diff --git a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts index 45dfa9a87a55..ae8e8c68ed2d 100644 --- a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts @@ -9,8 +9,8 @@ import type { NitroApp, NitroAppPlugin } from 'nitropack'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; import { sentryCaptureErrorHook } from '../hooks/captureErrorHook'; import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse'; -import { addSentryTracingMetaTags } from '../utils'; import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check'; +import { addSentryPageMetaTags } from '../utils/pageMetaTags'; /** * Sentry Cloudflare Nitro plugin for when using the "cloudflare-pages" preset in Nuxt. @@ -162,9 +162,9 @@ export const sentryCloudflareNitroPlugin = if (storedTraceData && Object.keys(storedTraceData).length > 0) { debug.log('Using stored trace data for HTML meta-tags: ', storedTraceData); - addSentryTracingMetaTags(html.head, storedTraceData); + addSentryPageMetaTags(html.head, event, storedTraceData); } else { - addSentryTracingMetaTags(html.head); + addSentryPageMetaTags(html.head, event); } }); diff --git a/packages/nuxt/src/runtime/plugins/sentry.client.ts b/packages/nuxt/src/runtime/plugins/sentry.client.ts index 423e8c457492..2df161d56a01 100644 --- a/packages/nuxt/src/runtime/plugins/sentry.client.ts +++ b/packages/nuxt/src/runtime/plugins/sentry.client.ts @@ -9,6 +9,7 @@ import { import { defineNuxtPlugin, isNuxtError } from 'nuxt/app'; import type { GlobalObjWithIntegrationOptions } from '../../client/vueIntegration'; import { reportNuxtError } from '../utils'; +import { withCacheOrigin } from '../utils/cacheOriginPageload'; // --- Types are copied from @sentry/vue (so it does not need to be exported) --- // The following type is an intersection of the Route type from VueRouter v2, v3, and v4. @@ -73,7 +74,11 @@ export default defineNuxtPlugin({ if (sentryClient && '$router' in nuxtApp) { sentryClient.addIntegration( - browserTracingIntegration({ router: nuxtApp.$router as VueRouter, routeLabel: 'path' }), + browserTracingIntegration({ + router: nuxtApp.$router as VueRouter, + routeLabel: 'path', + beforeStartSpan: options => withCacheOrigin(options, nuxtApp.payload.serverRendered === true), + }), ); } } diff --git a/packages/nuxt/src/runtime/plugins/sentry.server.ts b/packages/nuxt/src/runtime/plugins/sentry.server.ts index fd35d035c077..d9045578c341 100644 --- a/packages/nuxt/src/runtime/plugins/sentry.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry.server.ts @@ -1,36 +1,13 @@ -import { debug } from '@sentry/core'; import type { H3Event } from 'h3'; import type { NitroAppPlugin } from 'nitropack'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; import { sentryCaptureErrorHook } from '../hooks/captureErrorHook'; -import { addSentryTracingMetaTags } from '../utils'; +import { addSentryPageMetaTags } from '../utils/pageMetaTags'; export default (nitroApp => { nitroApp.hooks.hook('error', sentryCaptureErrorHook); nitroApp.hooks.hook('render:html', (html: NuxtRenderHTMLContext, { event }: { event: H3Event }) => { - // h3 v1 (Nuxt 4): event.node.res.getHeaders(); h3 v2 (Nuxt 5): event.node is undefined - const nodeResHeadersH3v1 = event.node?.res?.getHeaders() || {}; - - // h3 v2 (Nuxt 5): response headers are on event.res.headers - const isPreRenderedPage = - Object.keys(nodeResHeadersH3v1).includes('x-nitro-prerender') || - // fix × typescript-eslint(no-unsafe-member-access): Unsafe member access .res on an `any` value. - // oxlint-disable-next-line typescript/no-explicit-any,typescript-oxlint/no-unsafe-member-access - !!(event as any).res?.headers?.has?.('x-nitro-prerender'); - - // oxlint-disable-next-line typescript-oxlint/no-unsafe-member-access - const isSWRCachedPage = /* Nitro v2 */ (event?.context?.cache?.options?.swr || - // oxlint-disable-next-line typescript-oxlint/no-unsafe-member-access - /* Nitro v3 */ event?.context?.routeRules?.swr) as boolean; - - if (!isPreRenderedPage && !isSWRCachedPage) { - addSentryTracingMetaTags(html.head); - } else { - const reason = isPreRenderedPage ? 'the page was pre-rendered' : 'SWR caching is enabled for the route'; - debug.log( - `Not adding Sentry tracing meta tags to HTML for ${event.path} because ${reason}. This will disable distributed tracing and prevent connecting multiple client page loads to the same server request.`, - ); - } + addSentryPageMetaTags(html.head, event); }); }) satisfies NitroAppPlugin; diff --git a/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts b/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts new file mode 100644 index 000000000000..860a747209d9 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts @@ -0,0 +1,5 @@ +/** + * Replaces `sentry-trace` and `baggage` in a page that other visitors get too. Holds the `sentry-trace` + * value of the render, or nothing for a build prerender. The client links it and never continues it. + */ +export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts b/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts new file mode 100644 index 000000000000..3ef0ddb3a28a --- /dev/null +++ b/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts @@ -0,0 +1,46 @@ +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; +import type { SpanLink, StartSpanOptions } from '@sentry/core'; +import { extractTraceparentData } from '@sentry/core'; +import { WINDOW } from '@sentry/vue'; +import { CACHE_ORIGIN_META_TAG_NAME } from './cacheOriginMetaTag'; + +// `@opentelemetry/api` `TraceFlags`, inlined because core does not export its copies. +const TRACE_FLAG_SAMPLED = 0x1; + +/** The `cache_origin` link to the sampled render that a `sentry-trace` value describes. */ +function getCacheOriginLink(sentryTrace: string): SpanLink | undefined { + const traceparent = extractTraceparentData(sentryTrace); + if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) { + return undefined; + } + return { + context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: TRACE_FLAG_SAMPLED }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }; +} + +/** + * Marks the pageload of a reused page as `static` and links the render if it was sampled (as in Next.js). + * Runs at span start, so `tracesSampler` and `ignoreSpans` see the attribute. A client-side shell + * (`ssr: false`) stays unmarked, because the server rendered none of its content. + */ +export function withCacheOrigin(spanOptions: StartSpanOptions, isServerRendered: boolean): StartSpanOptions { + if (spanOptions.op !== PAGELOAD || !isServerRendered) { + return spanOptions; + } + + const cacheOrigin = WINDOW.document + ?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`) + ?.getAttribute('content'); + if (typeof cacheOrigin !== 'string') { + return spanOptions; + } + + const link = getCacheOriginLink(cacheOrigin); + return { + ...spanOptions, + attributes: { ...spanOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + links: link ? [...(spanOptions.links ?? []), link] : spanOptions.links, + }; +} diff --git a/packages/nuxt/src/runtime/utils/pageMetaTags.ts b/packages/nuxt/src/runtime/utils/pageMetaTags.ts new file mode 100644 index 000000000000..7c9cb5d019e9 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/pageMetaTags.ts @@ -0,0 +1,74 @@ +import type { SerializedTraceData } from '@sentry/core'; +import { debug, getTraceData, GLOBAL_OBJ } from '@sentry/core'; +import type { H3Event } from 'h3'; +import type { NuxtRenderHTMLContext } from 'nuxt/app'; +import { addSentryTracingMetaTags, getEventRequestInfo } from '../utils'; +import { CACHE_ORIGIN_META_TAG_NAME } from './cacheOriginMetaTag'; + +/** Global flag set by the generated runtime-flags module to the Nitro preset of the server build. */ +export const NUXT_NITRO_PRESET_FLAG = '__SENTRY_NUXT_NITRO_PRESET__'; + +// Presets on which a platform cache serves `isr` pages. On all other presets (also `vercel-edge` and +// `netlify-edge`), Nitro ignores `isr` and renders the page for each request. +const PLATFORM_ISR_PRESETS = new Set(['vercel', 'netlify', 'netlify-legacy', 'netlify-builder']); + +interface RouteRulesContext { + // Nitro v2: the Nuxt renderer writes the merged rules here before `render:html`. + _nitro?: { routeRules?: RouteRules }; + // Nitro v3: the rules by name, without the rules set to `false`. + routeRules?: RouteRules; +} + +interface RouteRules { + cache?: unknown; + isr?: unknown; +} + +/** + * Adds the Sentry meta tags to a rendered page. A page that other visitors get too has a + * `sentry-cache-origin` tag instead of `sentry-trace` and `baggage`, so that no visitor continues the + * trace of the render. The tag is empty for build prerenders, because the SDK does not run in the build. + */ +export function addSentryPageMetaTags( + head: NuxtRenderHTMLContext['head'], + event: H3Event, + traceData?: SerializedTraceData, +): void { + const cacheOrigin = getCacheOrigin(event, traceData); + if (cacheOrigin === undefined) { + addSentryTracingMetaTags(head, traceData); + return; + } + + debug.log(`Adding the Sentry cache origin meta tag to the reused page ${getEventRequestInfo(event).path}.`); + head.push(``); +} + +/** The `sentry-trace` value of the render of a reused page, or `undefined` for a page rendered per request. */ +function getCacheOrigin(event: H3Event, traceData: SerializedTraceData | undefined): string | undefined { + if (isPrerenderRequest(event)) { + return ''; + } + if (!isCachedRoute(event)) { + return undefined; + } + return (traceData ?? getTraceData())['sentry-trace'] ?? ''; +} + +// The Nitro prerenderer sends this header with each route it renders (Nitro v2 and v3). h3 v2 deprecates +// `event.headers`, so a later h3 can remove it. Then the page gets the live tags and does not fail. +function isPrerenderRequest(event: H3Event): boolean { + return !!event.headers?.has?.('x-nitro-prerender'); +} + +// Nitro changes `swr` rules into `cache` rules, so `cache` covers both. +function isCachedRoute(event: H3Event): boolean { + const context = event.context as RouteRulesContext | undefined; + const routeRules = context?._nitro?.routeRules ?? context?.routeRules; + return !!routeRules?.cache || (!!routeRules?.isr && hasPlatformIsr()); +} + +function hasPlatformIsr(): boolean { + const preset = (GLOBAL_OBJ as typeof GLOBAL_OBJ & { [NUXT_NITRO_PRESET_FLAG]?: unknown })[NUXT_NITRO_PRESET_FLAG]; + return typeof preset === 'string' && PLATFORM_ISR_PRESETS.has(preset); +} diff --git a/packages/nuxt/src/vite/utils.ts b/packages/nuxt/src/vite/utils.ts index e5b81e2802ac..ee00b95a95c1 100644 --- a/packages/nuxt/src/vite/utils.ts +++ b/packages/nuxt/src/vite/utils.ts @@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url'; import type { SentryNuxtModuleOptions } from '../common/types'; import { addTemplate, resolvePath, resolveServerVariant } from '@nuxt/kit'; import { NUXT_DEV_MODE_FLAG, NUXT_PRERENDER_FLAG } from '../common/devMode'; +import { NUXT_NITRO_PRESET_FLAG } from '../runtime/utils/pageMetaTags'; const SERVER_API_VARIANTS = { nitro2: 'nitro2', nitro3: 'nitro3', nuxt: 'nuxt' } as const; @@ -243,8 +244,8 @@ export function addRuntimeInjectionTraceDep(nuxt: Nuxt, isNitroV3: boolean): voi } /** - * Generates the module that sets the runtime flags `Sentry.init` reads. Import it before the - * Sentry server config: a statement above the config import would not survive import hoisting. + * Generates the module that sets the runtime flags `Sentry.init` and the server plugins read. Import it + * before the Sentry server config: a statement above the config import would not survive import hoisting. */ export function addRuntimeFlagsTemplate(): ResolvedNuxtTemplate { return addTemplate({ @@ -255,6 +256,7 @@ export function addRuntimeFlagsTemplate(): ResolvedNuxtTemplate { '// Generated by @sentry/nuxt. Sets runtime flags before the Sentry server config evaluates.', `globalThis.${NUXT_DEV_MODE_FLAG} = import.meta.dev === true;`, `globalThis.${NUXT_PRERENDER_FLAG} = import.meta.prerender === true;`, + `globalThis.${NUXT_NITRO_PRESET_FLAG} = import.meta.preset;`, '', ].join('\n'), }); diff --git a/packages/nuxt/test/runtime/plugins/client.test.ts b/packages/nuxt/test/runtime/plugins/client.test.ts index 16890e7be620..cbc8b35aa117 100644 --- a/packages/nuxt/test/runtime/plugins/client.test.ts +++ b/packages/nuxt/test/runtime/plugins/client.test.ts @@ -1,8 +1,9 @@ -import type { Client } from '@sentry/core'; +import type { Client, StartSpanOptions } from '@sentry/core'; import type { isNuxtError as nuxtIsNuxtError, NuxtApp } from 'nuxt/app'; import { afterEach, describe, expect, it, vi } from 'vitest'; import clientPlugin from '../../../src/runtime/plugins/sentry.client'; import * as utils from '../../../src/runtime/utils'; +import { withCacheOrigin } from '../../../src/runtime/utils/cacheOriginPageload'; const getClient = vi.hoisted(() => vi.fn<() => Client | undefined>()); const browserTracingIntegration = vi.hoisted(() => vi.fn()); @@ -40,6 +41,10 @@ vi.mock(import('@sentry/vue'), async importOriginal => { }; }); +vi.mock(import('../../../src/runtime/utils/cacheOriginPageload'), () => ({ + withCacheOrigin: vi.fn(), +})); + vi.mock(import('nuxt/app'), () => ({ defineNuxtPlugin: vi.fn(plugin => plugin), isNuxtError: vi.fn(() => false) as unknown as typeof nuxtIsNuxtError, @@ -126,10 +131,34 @@ describe('Sentry Nuxt client plugin', () => { await (clientPlugin as NuxtPluginShape).setup(makeNuxtApp(router)); - expect(browserTracingIntegration).toHaveBeenCalledWith({ router, routeLabel: 'path' }); + expect(browserTracingIntegration).toHaveBeenCalledWith({ + router, + routeLabel: 'path', + beforeStartSpan: expect.any(Function), + }); expect(client.addIntegration).toHaveBeenCalledWith(integration); }); + it.each([true, false])( + 'passes `serverRendered: %s` from the Nuxt payload to the cache origin check of the pageload', + async serverRendered => { + let beforeStartSpan: ((options: StartSpanOptions) => StartSpanOptions) | undefined; + browserTracingIntegration.mockImplementation(options => { + beforeStartSpan = options.beforeStartSpan; + return { name: 'BrowserTracing' }; + }); + getClient.mockReturnValue(makeClient()); + const nuxtApp = makeNuxtApp({ beforeEach: vi.fn(), onError: vi.fn() }); + nuxtApp.payload = { serverRendered } as NuxtApp['payload']; + const pageloadOptions = { name: '/rendering-modes/swr-cached-page', op: 'pageload' }; + + await (clientPlugin as NuxtPluginShape).setup(nuxtApp); + beforeStartSpan?.(pageloadOptions); + + expect(withCacheOrigin).toHaveBeenCalledWith(pageloadOptions, serverRendered); + }, + ); + it('does not add browserTracingIntegration without an initialized client', async () => { getClient.mockReturnValue(undefined); diff --git a/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts b/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts new file mode 100644 index 000000000000..f90c87afac01 --- /dev/null +++ b/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts @@ -0,0 +1,100 @@ +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op'; +import type { StartSpanOptions } from '@sentry/core'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { withCacheOrigin } from '../../../src/runtime/utils/cacheOriginPageload'; + +const TRACE_ID = '4c79f60c11214eb38604f4ae0781bfb2'; +const SPAN_ID = 'fa90fdead5f74052'; + +const pageloadOptions: StartSpanOptions = { + name: '/rendering-modes/swr-cached-page', + op: PAGELOAD, + attributes: { [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.vue' }, +}; + +function addCacheOriginTag(content: string): void { + const tag = document.createElement('meta'); + tag.name = 'sentry-cache-origin'; + tag.content = content; + document.head.appendChild(tag); +} + +describe('withCacheOrigin', () => { + beforeEach(() => { + document.head.innerHTML = ''; + }); + + it('marks the pageload as static and links the sampled render', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + + const options = withCacheOrigin(pageloadOptions, true); + + expect(options).toEqual({ + ...pageloadOptions, + attributes: { ...pageloadOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + links: [ + { + context: { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }, + ], + }); + }); + + it.each([ + { origin: 'an unsampled render', content: `${TRACE_ID}-${SPAN_ID}-0` }, + { origin: 'a render without a sampling decision', content: `${TRACE_ID}-${SPAN_ID}` }, + { origin: 'a build prerender', content: '' }, + ])('marks the pageload as static without a link for $origin', ({ content }) => { + addCacheOriginTag(content); + + const options = withCacheOrigin(pageloadOptions, true); + + expect(options).toEqual({ + ...pageloadOptions, + attributes: { ...pageloadOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + }); + }); + + it('keeps the links that the pageload already has', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + const previousTraceLink = { + context: { traceId: '0d5c7c7a6f0b4a57a3f1e9c2b8d4e6f1', spanId: 'b1a2c3d4e5f60718', traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'previous_trace' }, + }; + + const options = withCacheOrigin({ ...pageloadOptions, links: [previousTraceLink] }, true); + + expect(options.links).toEqual([ + previousTraceLink, + { + context: { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }, + ]); + }); + + it('does not change a pageload without a cache origin tag', () => { + const options = withCacheOrigin(pageloadOptions, true); + + expect(options).toBe(pageloadOptions); + }); + + it('does not change the pageload of a client-side shell', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + + const options = withCacheOrigin(pageloadOptions, false); + + expect(options).toBe(pageloadOptions); + }); + + it('does not change a navigation', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + const navigationOptions: StartSpanOptions = { name: '/checkout', op: NAVIGATION }; + + const options = withCacheOrigin(navigationOptions, true); + + expect(options).toBe(navigationOptions); + }); +}); diff --git a/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts b/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts new file mode 100644 index 000000000000..cfe1fe0a5f4b --- /dev/null +++ b/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts @@ -0,0 +1,155 @@ +import { getTraceData, getTraceMetaTags } from '@sentry/core'; +import type { H3Event } from 'h3'; +import { afterEach, describe, expect, it, type Mock, vi } from 'vitest'; +import { addSentryPageMetaTags, NUXT_NITRO_PRESET_FLAG } from '../../../src/runtime/utils/pageMetaTags'; + +vi.mock(import('@sentry/core'), async importOriginal => { + const mod = await importOriginal(); + return { + ...mod, + getTraceData: vi.fn(), + getTraceMetaTags: vi.fn(), + }; +}); + +const SENTRY_TRACE = '4c79f60c11214eb38604f4ae0781bfb2-fa90fdead5f74052-1'; +const LIVE_TRACE_META_TAGS = [ + ``, + '', +].join('\n'); +const CACHE_ORIGIN_META_TAG = ``; +const EMPTY_CACHE_ORIGIN_META_TAG = ''; + +const PATH = '/rendering-modes/swr-cached-page'; + +// h3 v1 (Nitro v2): Node request, with web `Headers` built from it. The Nuxt renderer resolves the +// route rules. +function h3v1Event(routeRules: Record = {}, headers: Record = {}): H3Event { + const nodeReq = { url: PATH, headers }; + return { + path: PATH, + node: { req: nodeReq }, + get headers() { + return new Headers(nodeReq.headers); + }, + context: { _nitro: { routeRules } }, + } as unknown as H3Event; +} + +// h3 v2 (Nitro v3): web `Request`, route rules stored by name. +function h3v2Event(routeRules: Record = {}, headers: Record = {}): H3Event { + const url = `https://shop.example.com${PATH}`; + const req = new Request(url, { headers }); + return { + req, + url: new URL(url), + get headers() { + return req.headers; + }, + context: { routeRules }, + } as unknown as H3Event; +} + +function nitroV3Rule(name: string, options: unknown): Record { + return { [name]: { name, route: PATH, options, params: {} } }; +} + +describe('addSentryPageMetaTags', () => { + afterEach(() => { + vi.resetAllMocks(); + vi.unstubAllGlobals(); + }); + + it('adds the tracing meta tags to a page rendered for one request', () => { + (getTraceMetaTags as Mock).mockReturnValue(LIVE_TRACE_META_TAGS); + const head: string[] = []; + + addSentryPageMetaTags(head, h3v1Event()); + + expect(head).toEqual([LIVE_TRACE_META_TAGS]); + }); + + it.each([ + { nitro: 'Nitro v2', event: h3v1Event({ cache: { swr: true, maxAge: 3600 } }) }, + { nitro: 'Nitro v3', event: h3v2Event(nitroV3Rule('cache', { swr: true, maxAge: 3600 })) }, + ])('replaces the tracing meta tags with the render as cache origin on a cached route ($nitro)', ({ event }) => { + (getTraceData as Mock).mockReturnValue({ 'sentry-trace': SENTRY_TRACE, baggage: 'sentry-environment=production' }); + const head: string[] = []; + + addSentryPageMetaTags(head, event); + + expect(head).toEqual([CACHE_ORIGIN_META_TAG]); + }); + + it('adds the tracing meta tags when the route opts out of caching with `cache: false`', () => { + (getTraceMetaTags as Mock).mockReturnValue(LIVE_TRACE_META_TAGS); + const head: string[] = []; + + addSentryPageMetaTags(head, h3v1Event({ cache: false })); + + expect(head).toEqual([LIVE_TRACE_META_TAGS]); + }); + + it('uses the given trace data of the request for the cache origin', () => { + const storedSentryTrace = '0d5c7c7a6f0b4a57a3f1e9c2b8d4e6f1-b1a2c3d4e5f60718-1'; + const head: string[] = []; + + addSentryPageMetaTags(head, h3v1Event({ cache: {} }), { 'sentry-trace': storedSentryTrace }); + + expect(head).toEqual([``]); + expect(getTraceData).not.toHaveBeenCalled(); + }); + + it('adds an empty cache origin tag to a cached route when the server has no trace data', () => { + (getTraceData as Mock).mockReturnValue({}); + const head: string[] = []; + + addSentryPageMetaTags(head, h3v1Event({ cache: {} })); + + expect(head).toEqual([EMPTY_CACHE_ORIGIN_META_TAG]); + }); + + it.each([ + { nitro: 'Nitro v2', event: h3v1Event({}, { 'x-nitro-prerender': PATH }) }, + { nitro: 'Nitro v3', event: h3v2Event({}, { 'x-nitro-prerender': PATH }) }, + ])('adds an empty cache origin tag to a page prerendered during the build ($nitro)', ({ event }) => { + const head: string[] = []; + + addSentryPageMetaTags(head, event, { 'sentry-trace': SENTRY_TRACE }); + + expect(head).toEqual([EMPTY_CACHE_ORIGIN_META_TAG]); + }); + + it('adds the tracing meta tags when the event has no `headers` getter', () => { + (getTraceMetaTags as Mock).mockReturnValue(LIVE_TRACE_META_TAGS); + const head: string[] = []; + + addSentryPageMetaTags(head, { context: { routeRules: {} } } as unknown as H3Event); + + expect(head).toEqual([LIVE_TRACE_META_TAGS]); + }); + + it.each(['vercel', 'netlify'])('replaces the tracing meta tags on an `isr` route on the %s preset', preset => { + vi.stubGlobal(NUXT_NITRO_PRESET_FLAG, preset); + (getTraceData as Mock).mockReturnValue({ 'sentry-trace': SENTRY_TRACE }); + const head: string[] = []; + + addSentryPageMetaTags(head, h3v1Event({ isr: 3600 })); + + expect(head).toEqual([CACHE_ORIGIN_META_TAG]); + }); + + it.each([ + { preset: 'node-server', description: 'a preset without a platform cache' }, + { preset: 'vercel-edge', description: 'the Vercel edge preset, which has no ISR functions' }, + { preset: undefined, description: 'an unknown preset' }, + ])('adds the tracing meta tags to an `isr` route on $description', ({ preset }) => { + vi.stubGlobal(NUXT_NITRO_PRESET_FLAG, preset); + (getTraceMetaTags as Mock).mockReturnValue(LIVE_TRACE_META_TAGS); + const head: string[] = []; + + addSentryPageMetaTags(head, h3v2Event(nitroV3Rule('isr', true))); + + expect(head).toEqual([LIVE_TRACE_META_TAGS]); + }); +}); diff --git a/packages/nuxt/test/vite/addServerConfig.test.ts b/packages/nuxt/test/vite/addServerConfig.test.ts index d73e66af2530..5ac940f88463 100644 --- a/packages/nuxt/test/vite/addServerConfig.test.ts +++ b/packages/nuxt/test/vite/addServerConfig.test.ts @@ -178,6 +178,7 @@ describe('addServerConfigPlugin', () => { const contents = templateContents('sentry-runtime-flags.mjs'); expect(contents).toContain('globalThis.__SENTRY_NUXT_DEV_MODE__ = import.meta.dev === true;'); expect(contents).toContain('globalThis.__SENTRY_NUXT_PRERENDER__ = import.meta.prerender === true;'); + expect(contents).toContain('globalThis.__SENTRY_NUXT_NITRO_PRESET__ = import.meta.preset;'); }); it('marks the config and the flags as side-effectful so tree shaking cannot drop them', () => { From 58082816af67c2d69991ecbf62634cc98d1310ba Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:34:03 +0100 Subject: [PATCH 068/136] fix(browser): Skip CLS on browsers without Array.prototype.at (#26347) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** `web-vitals` 6 calls `Array.prototype.at(-1)` in its CLS code (`LayoutShiftManager`). Chromium only has `.at()` from 92, but we support Chrome 80+ / Edge 80+ / Opera 67+ / Samsung Internet 13+, and Chromium has emitted `layout-shift` entries since 77. So on Chromium 80–91, every layout shift throws an uncaught `TypeError: this.o.at is not a function` from web-vitals' observer callback, and the SDK reports it as an error event to the customer's project. CLS doesn't get recorded either. This PR skips the CLS observer when `.at()` is missing, instead of polyfilling `Array.prototype` in customer apps. Those browsers just report no CLS, the same as Firefox and Safari already do. The other `.at()` call (INP's `InteractionManager`) can't be reached there, because `onINP` bails unless `PerformanceEventTiming` has `interactionId` (Chrome 96+). `es-check es2020` doesn't catch any of this: `web-vitals` is external in our npm build, and es-check's feature check doesn't flag `.at()` calls in the CDN bundles either. It also adds a CI job, `Minimum Chromium Version Tests`, that runs real web vitals in Chromium 80, our minimum. Playwright only drives the Chromium it ships with, so `dev-packages/browser-min-version-tests/run.mjs` downloads the Chromium 80 snapshot (SHA-256 pinned) and drives it over the DevTools protocol with `CDPClient`, while `createBasicSentryServer` receives the envelopes. Both come from `@sentry-internal/test-utils`. For the tracing CDN bundle and the full debug bundle, it: - loads the page, causes layout shifts and clicks a button - checks that FCP, FP, TTFB and LCP are sent, and that CLS and INP are not (it first confirms the page shifted and was clicked, so those checks aren't trivially true) - checks that there are no uncaught errors, no `console.error` or browser error logs, and no error events sent to the DSN Envelopes go cross-origin to a local DSN, like they do to sentry.io. The test takes ~2.5 s, or ~6 s including the download. Against `develop`'s bundles it fails with the `.at` TypeError, an error event, and a CLS span. On this branch it passes. Two small `test-utils` changes made this possible. `CDPClient` now clears its request timeouts, so finished requests no longer keep the process alive for 30 s. `createBasicSentryServer` sends `Access-Control-Allow-Origin: *`, so browsers can read its responses. **How to review:** The fix is the guard in `instrumentCls()`. The Playwright test in `web-vitals-cls-without-array-at` deletes `Array.prototype.at` to cover the npm/ESM builds too. `run.mjs` is the Chromium 80 harness. **Unsure about:** - The new job only runs on PRs when `changed_browser_integration` is true, same as the Playwright jobs. - It downloads Chromium on every run instead of caching it. The 127 MB zip downloads about as fast as a cache restore would be, and it keeps 350 MB out of the Actions cache. - The harness found another Chromium 80 problem, not fixed here. With a same-origin or managed `tunnel`, the SDK sends `Content-Type: application/x-sentry-envelope` with `keepalive: true`. Chromium < 81 rejects that with "Preflight request for request with keepalive specified is currently not supported", so every envelope fails. That's why the harness uses a cross-origin DSN instead of a tunnel. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794556575.714379) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794556575.714379/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .github/workflows/build.yml | 34 +++ .../subject.js | 3 + .../template.html | 10 + .../web-vitals-cls-without-array-at/test.ts | 34 +++ .../browser-min-version-tests/.gitignore | 1 + .../browser-min-version-tests/install-deps.sh | 9 + .../browser-min-version-tests/package.json | 13 + .../browser-min-version-tests/page.html | 29 ++ .../browser-min-version-tests/run.mjs | 275 ++++++++++++++++++ dev-packages/test-utils/src/cdp-client.ts | 20 +- dev-packages/test-utils/src/server.ts | 2 + package.json | 1 + .../instrumentation/performanceObserver.ts | 7 + pnpm-lock.yaml | 6 + pnpm-workspace.yaml | 1 + 15 files changed, 438 insertions(+), 7 deletions(-) create mode 100644 dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js create mode 100644 dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html create mode 100644 dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts create mode 100644 dev-packages/browser-min-version-tests/.gitignore create mode 100755 dev-packages/browser-min-version-tests/install-deps.sh create mode 100644 dev-packages/browser-min-version-tests/package.json create mode 100644 dev-packages/browser-min-version-tests/page.html create mode 100644 dev-packages/browser-min-version-tests/run.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 66d006e800c7..a5bfa4b3a1ad 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -745,6 +745,39 @@ jobs: overwrite: true retention-days: 7 + # Runs the CDN bundles in the oldest Chromium we support. Chromium snapshots only exist for x64. + job_browser_min_version_tests: + name: Minimum Chromium Version Tests + needs: [job_get_metadata, job_build, job_build_bundles] + if: needs.job_build.outputs.changed_browser_integration == 'true' || github.event_name != 'pull_request' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) + uses: actions/checkout@v7 + with: + ref: ${{ env.HEAD_COMMIT }} + - name: Set up Node + uses: ./.github/actions/setup-node + - name: Restore caches + uses: ./.github/actions/restore-cache + with: + dependency_cache_key: ${{ needs.job_build.outputs.dependency_cache_key }} + + - name: Restore build bundle artifacts + uses: actions/download-artifact@v8 + with: + name: build-bundle-output + path: ${{ env.BUNDLE_ARTIFACT_DOWNLOAD_PATH }} + + # Chromium itself isn't cached: `run.mjs` downloads the 127 MB zip on each run, which is about as quick as a + # cache restore. + - name: Install Chromium dependencies + run: dev-packages/browser-min-version-tests/install-deps.sh + + - name: Run tests + run: node dev-packages/browser-min-version-tests/run.mjs + job_node_integration_tests: name: Node (${{ matrix.node }}) Integration Tests (${{ matrix.shard }}/${{ matrix.shards }}) needs: [job_get_metadata, job_build] @@ -1207,6 +1240,7 @@ jobs: job_deno_integration_tests, job_browser_playwright_tests, job_browser_loader_tests, + job_browser_min_version_tests, job_e2e_tests_1, job_e2e_tests_2, job_e2e_aws_layer_tests, diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js new file mode 100644 index 000000000000..24397a4f6f66 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/subject.js @@ -0,0 +1,3 @@ +import { simulateCLS } from '../../../../utils/web-vitals/cls.ts'; + +simulateCLS(0.15).then(() => window.dispatchEvent(new Event('cls-done'))); diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html new file mode 100644 index 000000000000..10e2e22f7d6a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/template.html @@ -0,0 +1,10 @@ + + + + + + +
+

Some content

+ + diff --git a/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts new file mode 100644 index 000000000000..68be3f8f7063 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/metrics/web-vitals-cls-without-array-at/test.ts @@ -0,0 +1,34 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { hidePage, shouldSkipTracingTest } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest.beforeEach(async ({ browserName, page }) => { + if (shouldSkipTracingTest() || browserName !== 'chromium') { + sentryTest.skip(); + } + + await page.setViewportSize({ width: 800, height: 1200 }); +}); + +// Chromium 80-91 is within our supported range and reports layout shifts, but has no `Array.prototype.at`, +// which web-vitals' CLS code relies on. +sentryTest('does not throw on layout shifts without Array.prototype.at', async ({ getLocalTestUrl, page }) => { + const pageErrors: string[] = []; + page.on('pageerror', error => pageErrors.push(error.message)); + + await page.addInitScript(() => { + // @ts-expect-error - emulating Chromium < 92 + delete Array.prototype.at; + }); + + const url = await getLocalTestUrl({ testDir: __dirname }); + const pageloadSpanPromise = waitForStreamedSpan(page, span => getSpanOp(span) === 'pageload'); + + await page.goto(url); + await page.evaluate(() => new Promise(resolve => window.addEventListener('cls-done', resolve))); + await hidePage(page); + await pageloadSpanPromise; + + expect(pageErrors).toEqual([]); +}); diff --git a/dev-packages/browser-min-version-tests/.gitignore b/dev-packages/browser-min-version-tests/.gitignore new file mode 100644 index 000000000000..36e1248d6bd9 --- /dev/null +++ b/dev-packages/browser-min-version-tests/.gitignore @@ -0,0 +1 @@ +.chromium/ diff --git a/dev-packages/browser-min-version-tests/install-deps.sh b/dev-packages/browser-min-version-tests/install-deps.sh new file mode 100755 index 000000000000..8316317a7d05 --- /dev/null +++ b/dev-packages/browser-min-version-tests/install-deps.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Old Chromium links against libXss, which current runner images don't ship. Installing from the image's +# package lists is fast; only refresh them when they are too stale to resolve the package. +set -eu + +if ! sudo apt-get install -y --no-install-recommends libxss1; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends libxss1 +fi diff --git a/dev-packages/browser-min-version-tests/package.json b/dev-packages/browser-min-version-tests/package.json new file mode 100644 index 000000000000..172040f165b6 --- /dev/null +++ b/dev-packages/browser-min-version-tests/package.json @@ -0,0 +1,13 @@ +{ + "name": "@sentry-internal/browser-min-version-tests", + "version": "11.12.0", + "license": "MIT", + "private": true, + "type": "module", + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + }, + "devDependencies": { + "@sentry-internal/test-utils": "11.12.0" + } +} diff --git a/dev-packages/browser-min-version-tests/page.html b/dev-packages/browser-min-version-tests/page.html new file mode 100644 index 000000000000..c918731ca689 --- /dev/null +++ b/dev-packages/browser-min-version-tests/page.html @@ -0,0 +1,29 @@ + + + + + + + + +

Largest contentful paint

+

Shifting

+ + + + diff --git a/dev-packages/browser-min-version-tests/run.mjs b/dev-packages/browser-min-version-tests/run.mjs new file mode 100644 index 000000000000..64d3b686010c --- /dev/null +++ b/dev-packages/browser-min-version-tests/run.mjs @@ -0,0 +1,275 @@ +// Loads the CDN bundles in the oldest Chromium we support and checks that the web vitals it can +// measure are sent, and that nothing throws. Playwright only drives the Chromium it ships with, so +// this talks to the browser over the DevTools protocol directly. Run it after `pnpm build:bundle` in +// `packages/browser`. +import { execFileSync, spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { CDPClient, createBasicSentryServer, getSpanOp } from '@sentry-internal/test-utils'; + +// Chromium 80.0.3987.0, the minimum Chrome version in our supported browsers docs. +const CHROMIUM_REVISION = '722234'; +const CHROMIUM_ZIP_SHA256 = '2a7f1d1cf4fd933f4090739667f86b52187431a5a22e5f33a4a2be158d4574dc'; +const DIR = path.dirname(fileURLToPath(import.meta.url)); +const CHROMIUM_DIR = path.join(DIR, '.chromium', CHROMIUM_REVISION); +const CHROME = path.join(CHROMIUM_DIR, 'chrome-linux', 'chrome'); +const BUNDLES_DIR = path.join(DIR, '../../packages/browser/build/bundles'); +const BUNDLES = [ + 'bundle.tracing.min.js', + // The debug build logs errors the SDK catches internally, which would otherwise go unnoticed. + 'bundle.tracing.replay.feedback.logs.metrics.debug.min.js', +]; +const PAGE = readFileSync(path.join(DIR, 'page.html'), 'utf8'); + +// What Chromium 80 can report. CLS is skipped there because web-vitals' CLS code needs +// `Array.prototype.at` (Chromium 92), and INP needs `PerformanceEventTiming.interactionId` (Chromium 96). +const EXPECTED_PAGELOAD_VITALS = ['fcp', 'fp', 'ttfb']; +const UNEXPECTED_SPAN_OPS = ['ui.webvital.cls', 'ui.interaction.click']; + +async function ensureChromium() { + if (existsSync(CHROME)) { + return; + } + const url = `https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/${CHROMIUM_REVISION}/chrome-linux.zip`; + const response = await fetch(url, { signal: AbortSignal.timeout(120_000) }); + if (!response.ok) { + throw new Error(`Downloading Chromium failed: ${response.status} ${url}`); + } + const data = Buffer.from(await response.arrayBuffer()); + const sha256 = createHash('sha256').update(data).digest('hex'); + if (sha256 !== CHROMIUM_ZIP_SHA256) { + throw new Error(`Chromium download has SHA-256 ${sha256}, expected ${CHROMIUM_ZIP_SHA256}`); + } + mkdirSync(CHROMIUM_DIR, { recursive: true }); + const zip = `${CHROMIUM_DIR}.zip`; + writeFileSync(zip, data); + execFileSync('unzip', ['-q', zip, '-d', CHROMIUM_DIR]); + rmSync(zip); +} + +// The page and the DSN are on different ports, so envelopes are sent cross-origin like they are to sentry.io. +function startPageServer(bundlePath, sentryPort) { + const page = PAGE.replace('__DSN__', `http://public@localhost:${sentryPort}/1337`); + const server = createServer((req, res) => { + if (req.url === '/bundle.js') { + res.setHeader('content-type', 'text/javascript'); + res.end(readFileSync(bundlePath)); + return; + } + res.setHeader('content-type', 'text/html'); + res.end(page); + }); + return new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve(server))); +} + +function launchChrome(userDataDir) { + const chrome = spawn(CHROME, [ + '--headless', + '--no-sandbox', + '--disable-gpu', + '--remote-debugging-port=0', + '--window-size=800,1200', + `--user-data-dir=${userDataDir}`, + 'about:blank', + ]); + const port = new Promise((resolve, reject) => { + let stderr = ''; + chrome.stderr.on('data', chunk => { + stderr += chunk; + const match = stderr.match(/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//); + if (match) { + resolve(match[1]); + } + }); + chrome.on('exit', code => reject(new Error(`Chromium exited with ${code}:\n${stderr}`))); + }); + return { chrome, port }; +} + +async function connect(port) { + // The DevTools server can come up before the initial page target exists. + let page; + for (let attempt = 0; !page && attempt < 50; attempt++) { + const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + page = targets.find(target => target.type === 'page'); + if (!page) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + } + if (!page) { + throw new Error('Chromium has no page target'); + } + const cdp = new CDPClient({ url: page.webSocketDebuggerUrl, retries: 1 }); + await cdp.connect(); + return cdp; +} + +function waitForEvent(cdp, method) { + return new Promise(resolve => { + const off = cdp.on(method, () => { + off(); + resolve(); + }); + }); +} + +async function evaluate(cdp, expression) { + const { result, exceptionDetails } = await cdp.send('Runtime.evaluate', { + expression, + awaitPromise: true, + returnByValue: true, + }); + if (exceptionDetails) { + throw new Error(`Evaluating failed: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`); + } + return result.value; +} + +function collectItems(spans, events) { + return ([, items]) => { + for (const [header, payload] of items) { + if (header.type === 'span') { + spans.push(...payload.items); + } else if (header.type === 'event') { + events.push(payload); + } + } + }; +} + +const isPageload = span => span.is_segment && getSpanOp(span) === 'pageload'; + +async function runBundle(bundle) { + const spans = []; + const events = []; + const errors = []; + const [sentryPort, closeSentryServer] = await createBasicSentryServer(collectItems(spans, events)); + const server = await startPageServer(path.join(BUNDLES_DIR, bundle), sentryPort); + const userDataDir = mkdtempSync(path.join(tmpdir(), 'chromium-profile-')); + const { chrome, port } = launchChrome(userDataDir); + let cdp; + + try { + cdp = await connect(await port); + cdp.on('Runtime.exceptionThrown', ({ exceptionDetails }) => { + errors.push(exceptionDetails.exception?.description ?? exceptionDetails.text); + }); + cdp.on('Runtime.consoleAPICalled', ({ type, args }) => { + if (type === 'error') { + errors.push(args.map(arg => arg.value ?? arg.description).join(' ')); + } + }); + cdp.on('Log.entryAdded', ({ entry }) => { + if (entry.level === 'error') { + errors.push(entry.text); + } + }); + await Promise.all([cdp.send('Runtime.enable'), cdp.send('Log.enable'), cdp.send('Page.enable')]); + + const loaded = waitForEvent(cdp, 'Page.loadEventFired'); + await cdp.send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}/` }); + await loaded; + + // Layout shifts, then a click: shifts within 500ms after an input don't count towards CLS. + await evaluate( + cdp, + `(async () => { + const element = document.getElementById('shift'); + for (let i = 1; i <= 10; i++) { + element.style.top = 200 + i * 40 + 'px'; + await new Promise(resolve => setTimeout(resolve, 50)); + } + })()`, + ); + const { x, y } = await evaluate( + cdp, + `(() => { + const rect = document.getElementById('button').getBoundingClientRect(); + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; + })()`, + ); + for (const type of ['mousePressed', 'mouseReleased']) { + await cdp.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 }); + } + await new Promise(resolve => setTimeout(resolve, 300)); + + // Without these, the checks that CLS and INP are not sent would pass without testing anything. + const { layoutShifts, clicked } = await evaluate( + cdp, + `new Promise(resolve => { + const done = layoutShifts => resolve({ layoutShifts, clicked: document.getElementById('button').dataset.clicked === 'true' }); + new PerformanceObserver(list => done(list.getEntries().length)).observe({ type: 'layout-shift', buffered: true }); + setTimeout(() => done(0), 500); + })`, + ); + if (!layoutShifts || !clicked) { + throw new Error(`Page did not shift (${layoutShifts} layout shifts) or was not clicked (${clicked})`); + } + + // Hiding the page is what makes the SDK finalize LCP and CLS. + await evaluate( + cdp, + `(() => { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }); + document.dispatchEvent(new Event('visibilitychange')); + })()`, + ); + // The pageload span, which carries FCP, FP and TTFB, ends once the page has been idle for a second. + const deadline = Date.now() + 10_000; + while (!spans.some(isPageload) && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + } finally { + await cdp?.close(); + chrome.kill(); + server.close(); + closeSentryServer(); + rmSync(userDataDir, { recursive: true, force: true }); + } + + const pageload = spans.find(isPageload); + const ops = new Set(spans.map(getSpanOp)); + const failures = [...new Set(errors)].map(error => `page error: ${error}`); + + for (const event of events) { + failures.push(`error event sent: ${event.exception?.values?.[0]?.value ?? event.message}`); + } + if (!pageload) { + failures.push('no pageload span sent'); + } else { + if (!pageload.attributes['user_agent.original']?.value.includes('Chrome/80.')) { + failures.push(`not running in Chrome 80: ${pageload.attributes['user_agent.original']?.value}`); + } + for (const vital of EXPECTED_PAGELOAD_VITALS) { + if (typeof pageload.attributes[`browser.web_vital.${vital}.value`]?.value !== 'number') { + failures.push(`pageload span has no ${vital.toUpperCase()}`); + } + } + } + const lcp = spans.find(span => getSpanOp(span) === 'ui.webvital.lcp'); + if (typeof lcp?.attributes['browser.web_vital.lcp.value']?.value !== 'number') { + failures.push('no LCP span sent'); + } + for (const unexpected of UNEXPECTED_SPAN_OPS) { + if (ops.has(unexpected)) { + failures.push(`unexpected ${unexpected} span sent`); + } + } + + return failures; +} + +await ensureChromium(); + +const results = await Promise.all(BUNDLES.map(runBundle)); +results.forEach((failures, index) => { + // eslint-disable-next-line no-console + console.log( + `${failures.length ? '✘' : '✓'} ${BUNDLES[index]}${failures.map(failure => `\n ${failure}`).join('')}`, + ); +}); +process.exitCode = results.some(failures => failures.length) ? 1 : 0; diff --git a/dev-packages/test-utils/src/cdp-client.ts b/dev-packages/test-utils/src/cdp-client.ts index 491d7bfa77d9..7d0aaead7474 100644 --- a/dev-packages/test-utils/src/cdp-client.ts +++ b/dev-packages/test-utils/src/cdp-client.ts @@ -135,18 +135,24 @@ export class CDPClient { this.#log('Sending:', method, params || ''); return new Promise((resolve, reject) => { - this.#pendingRequests.set(id, { - resolve: value => resolve(value as T), - reject, - }); - this.#ws!.send(message); - - setTimeout(() => { + // Cleared on response, so a finished request doesn't keep the process alive until the timeout. + const timeoutId = setTimeout(() => { if (this.#pendingRequests.has(id)) { this.#pendingRequests.delete(id); reject(new Error(`CDP request ${method} timed out after ${timeout}ms`)); } }, timeout); + this.#pendingRequests.set(id, { + resolve: value => { + clearTimeout(timeoutId); + resolve(value as T); + }, + reject: error => { + clearTimeout(timeoutId); + reject(error); + }, + }); + this.#ws!.send(message); }); } diff --git a/dev-packages/test-utils/src/server.ts b/dev-packages/test-utils/src/server.ts index 3fef94be89a0..3e9da4320a81 100644 --- a/dev-packages/test-utils/src/server.ts +++ b/dev-packages/test-utils/src/server.ts @@ -22,6 +22,8 @@ export function createBasicSentryServer(onEnvelope: (env: Envelope) => void): Pr console.error(e); } + // Browsers send envelopes cross-origin, as they do to sentry.io, and reject the response without this. + res.set('Access-Control-Allow-Origin', '*'); res.status(200).send(); }); diff --git a/package.json b/package.json index b4d705ce6f7a..478c7c7a1a32 100644 --- a/package.json +++ b/package.json @@ -112,6 +112,7 @@ "packages/wasm", "packages/webpack-plugin", "dev-packages/browser-integration-tests", + "dev-packages/browser-min-version-tests", "dev-packages/bundler-plugin-integration-tests", "dev-packages/e2e-tests", "dev-packages/node-integration-tests", diff --git a/packages/browser-utils/src/instrumentation/performanceObserver.ts b/packages/browser-utils/src/instrumentation/performanceObserver.ts index 4424a5f3ef87..c8a312e40af8 100644 --- a/packages/browser-utils/src/instrumentation/performanceObserver.ts +++ b/packages/browser-utils/src/instrumentation/performanceObserver.ts @@ -322,6 +322,13 @@ function unlessBfcacheDisabled(callback: (metric: Metric) => void): (metric: Met } function instrumentCls(): StopListening { + // web-vitals' CLS code calls `Array.prototype.at`, which Chromium only ships from 92. Chromium 80-91 + // still emits layout shifts, so web-vitals would throw an uncaught TypeError on every one of them. + // TODO(v12): Remove this check if the minimum supported Chromium version is raised to 92 or higher. + if (!('at' in Array.prototype)) { + return; + } + return onCLS( unlessBfcacheDisabled(metric => { triggerHandlers('cls', { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 00c3f822b91c..6894f3a6c554 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -319,6 +319,12 @@ importers: specifier: ^5.112.2 version: 5.112.2(clean-css@5.2.2)(cssnano@7.1.9(postcss@8.5.32))(csso@5.0.5)(esbuild@0.28.1)(html-minifier-terser@6.1.0)(lightningcss@1.33.0)(postcss@8.5.32)(sharp@0.35.5(@types/node@20.19.43))(svgo@4.1.0)(uglify-js@3.13.3) + dev-packages/browser-min-version-tests: + devDependencies: + '@sentry-internal/test-utils': + specifier: 11.12.0 + version: link:../test-utils + dev-packages/bun-integration-tests: devDependencies: '@sentry-internal/node-integration-tests': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index cb3f595a481f..902a3950f327 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -49,6 +49,7 @@ packages: - 'packages/wasm' - 'packages/webpack-plugin' - 'dev-packages/browser-integration-tests' + - 'dev-packages/browser-min-version-tests' - 'dev-packages/bundler-plugin-integration-tests' - 'dev-packages/e2e-tests' - 'dev-packages/node-integration-tests' From ccb0acc874c933d7b90befc3fd06547cd884237a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:50:46 +0100 Subject: [PATCH 069/136] chore(ci): Never auto-request HazAT as reviewer (#26353) **Why:** Adds @HazAT to `NEVER_REQUEST` in the assign-reviewers script, so like the other managers on the SDK teams he is never auto-picked, and a pending team-assigned request for him doesn't count towards the 3 required reviewers. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794566646.039169) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794566646.039169/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- scripts/assign-reviewers.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/assign-reviewers.mjs b/scripts/assign-reviewers.mjs index 2120f7bdd5cd..60586290e710 100644 --- a/scripts/assign-reviewers.mjs +++ b/scripts/assign-reviewers.mjs @@ -5,7 +5,7 @@ import { getJuniorRequesters, TEAM_SLUG } from './junior-requesters.mjs'; const REQUIRED_REVIEWERS = 3; // Managers who are members of the SDK teams, but should never be auto-requested for review. // GitHub's team auto-assignment can still pick them, so their pending requests don't count towards the required reviewers. -const NEVER_REQUEST = ['mydea', 'stephanie-anderson']; +const NEVER_REQUEST = ['mydea', 'stephanie-anderson', 'HazAT']; const REVIEWERS_PATH = '.github/REVIEWERS'; function patternToRegExp(pattern) { From 4f5b3fd7be83783063004886f092a55876af3ec7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:56:15 +0100 Subject: [PATCH 070/136] chore(dev-deps): Replace npm-run-all2 with pnpm script selectors (#26319) **Why:** pnpm can already do what `npm-run-all2` does, so it's one less dev dependency (~17 packages in its tree). `run-s a b` becomes `pnpm run a && pnpm run b`. `run-p a b` becomes a regex selector (`pnpm run "/^build:(transpile|types)$/"`), which runs the matching scripts of the current package concurrently and exits non-zero (killing the rest) when one fails. The 4 `run-p`/`run-s` calls that wrapped a single script are now plain `pnpm run x`. This also covers the four e2e test apps that depended on it (`vue-3`, `vue-3-static`, `react-router-6`, `react-router-6-descendant-routes`). Non-obvious choices: - No `--parallel`. It makes `pnpm run` recursive, and in a package dir it ran the matching scripts of all 63 workspace projects. - Regex selectors run at most as many scripts at once as there are CPUs (capped at 4), while `run-p` had no cap. That's fine for builds, which use the CPU anyway. The react-router-6 apps' `start` runs two servers that never exit, so it passes `--workspace-concurrency=Infinity`; otherwise on one core the second server would never start. - The Vue apps' `build` dropped the create-vue `{@}` argument forwarding. Nothing passes arguments to it: every caller runs a plain `pnpm build`. **Performance:** same or slightly faster. `run-p` starts its own Node process plus a `pnpm run` per script, while the regex selector runs everything from one pnpm process. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794299077.223779/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../package.json | 4 +- dev-packages/e2e-tests/package.json | 2 +- .../package.json | 5 +- .../react-router-6/package.json | 5 +- .../vue-3-static/package.json | 3 +- .../test-applications/vue-3/package.json | 3 +- dev-packages/test-utils/package.json | 2 +- package.json | 11 ++-- packages/astro/package.json | 2 +- packages/aws-serverless/package.json | 6 +-- packages/browser-utils/package.json | 2 +- packages/browser/package.json | 4 +- packages/bun/package.json | 4 +- packages/bundler-plugins/package.json | 6 +-- packages/cloudflare/package.json | 2 +- packages/core/package.json | 2 +- packages/deno/package.json | 4 +- packages/effect/package.json | 2 +- packages/elysia/package.json | 2 +- packages/esbuild-plugin/package.json | 2 +- packages/feedback/package.json | 4 +- packages/gatsby/package.json | 4 +- packages/google-cloud-serverless/package.json | 2 +- packages/hono/package.json | 2 +- packages/integration-shims/package.json | 2 +- packages/nestjs/package.json | 4 +- packages/nextjs/package.json | 4 +- packages/nitro/package.json | 4 +- packages/node/package.json | 2 +- packages/nuxt/package.json | 2 +- packages/opentelemetry/package.json | 2 +- packages/react-router/package.json | 4 +- packages/react/package.json | 2 +- packages/remix/package.json | 2 +- packages/replay-canvas/package.json | 4 +- packages/replay-internal/package.json | 4 +- packages/replay-worker/package.json | 2 +- packages/rollup-plugin/package.json | 2 +- .../server-runtime-injection/package.json | 2 +- packages/server-utils/package.json | 2 +- packages/solid/package.json | 4 +- packages/solidstart/package.json | 4 +- packages/svelte/package.json | 2 +- packages/sveltekit/package.json | 2 +- packages/tanstackstart-react/package.json | 2 +- packages/vercel-edge/package.json | 2 +- packages/vite-plugin/package.json | 2 +- packages/vue/package.json | 6 +-- packages/wasm/package.json | 4 +- packages/webpack-plugin/package.json | 2 +- pnpm-lock.yaml | 52 ------------------- 51 files changed, 77 insertions(+), 134 deletions(-) diff --git a/dev-packages/bundler-plugin-integration-tests/package.json b/dev-packages/bundler-plugin-integration-tests/package.json index 9c61edd0b2f5..9f42dcc5fd21 100644 --- a/dev-packages/bundler-plugin-integration-tests/package.json +++ b/dev-packages/bundler-plugin-integration-tests/package.json @@ -6,8 +6,8 @@ "scripts": { "test": "node setup.mjs && vitest run --pool threads --test-timeout=10000", "check:types": "tsc --project ./tsconfig.json --noEmit", - "clean": "run-s clean:build", - "clean:all": "run-p clean clean:deps", + "clean": "pnpm run clean:build", + "clean:all": "pnpm run \"/^(clean|clean:deps)$/\"", "clean:build": "node ../../scripts/rm.mjs ./fixtures/*/out", "clean:deps": "node ../../scripts/rm.mjs node_modules" }, diff --git a/dev-packages/e2e-tests/package.json b/dev-packages/e2e-tests/package.json index 9aa61ffb27c2..33d2e9497f32 100644 --- a/dev-packages/e2e-tests/package.json +++ b/dev-packages/e2e-tests/package.json @@ -6,7 +6,7 @@ "scripts": { "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", - "test:e2e": "run-s test:prepare test:validate test:run", + "test:e2e": "pnpm run test:prepare && pnpm run test:validate && pnpm run test:run", "test:run": "node run.mjs", "test:prepare": "node prepare.mjs", "test:validate": "node validate-packed-tarball-setup.mjs", diff --git a/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json index 16af3288c98c..0500b51516b1 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-6-descendant-routes/package.json @@ -15,7 +15,7 @@ }, "scripts": { "build": "react-scripts build", - "start": "run-p start:client start:server", + "start": "pnpm run --workspace-concurrency=Infinity \"/^start:(client|server)$/\"", "start:client": "node server/app.js", "start:server": "serve -s build", "test": "playwright test", @@ -45,7 +45,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1", - "npm-run-all2": "^6.2.0" + "serve": "14.0.1" } } diff --git a/dev-packages/e2e-tests/test-applications/react-router-6/package.json b/dev-packages/e2e-tests/test-applications/react-router-6/package.json index d61d433093d3..2101a3aa1a62 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-6/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-6/package.json @@ -15,7 +15,7 @@ }, "scripts": { "build": "react-scripts build", - "start": "run-p start:client start:server", + "start": "pnpm run --workspace-concurrency=Infinity \"/^start:(client|server)$/\"", "start:client": "node server/app.js", "start:server": "serve -s build", "test": "playwright test", @@ -45,8 +45,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1", - "npm-run-all2": "^6.2.0" + "serve": "14.0.1" }, "sentryTest": { "canaryVariants": [ diff --git a/dev-packages/e2e-tests/test-applications/vue-3-static/package.json b/dev-packages/e2e-tests/test-applications/vue-3-static/package.json index a16086c0109a..a1ffd0d90899 100644 --- a/dev-packages/e2e-tests/test-applications/vue-3-static/package.json +++ b/dev-packages/e2e-tests/test-applications/vue-3-static/package.json @@ -6,7 +6,7 @@ "scripts": { "clean": "npx rimraf node_modules pnpm-lock.yaml dist", "dev": "vite", - "build": "run-p type-check \"build-only {@}\" --", + "build": "pnpm run \"/^(type-check|build-only)$/\"", "preview": "vite preview", "build-only": "vite build", "type-check": "vue-tsc --build --force", @@ -34,7 +34,6 @@ "@vitejs/plugin-vue": "^5.0.3", "@vitejs/plugin-vue-jsx": "^3.1.0", "@vue/tsconfig": "^0.5.1", - "npm-run-all2": "^6.2.0", "typescript": "~5.3.0", "vite": "^5.4.11", "vue-tsc": "^1.8.27" diff --git a/dev-packages/e2e-tests/test-applications/vue-3/package.json b/dev-packages/e2e-tests/test-applications/vue-3/package.json index abbc7e01d4eb..f9d59c4d384a 100644 --- a/dev-packages/e2e-tests/test-applications/vue-3/package.json +++ b/dev-packages/e2e-tests/test-applications/vue-3/package.json @@ -6,7 +6,7 @@ "scripts": { "clean": "npx rimraf node_modules pnpm-lock.yaml dist", "dev": "vite", - "build": "run-p type-check \"build-only {@}\" --", + "build": "pnpm run \"/^(type-check|build-only)$/\"", "preview": "vite preview", "build-only": "vite build", "type-check": "vue-tsc --build --force", @@ -37,7 +37,6 @@ "@vitejs/plugin-vue": "^5.0.3", "@vitejs/plugin-vue-jsx": "^3.1.0", "@vue/tsconfig": "^0.5.1", - "npm-run-all2": "^6.2.0", "typescript": "~5.3.0", "vite": "^5.4.11", "vue-tsc": "^1.8.27" diff --git a/dev-packages/test-utils/package.json b/dev-packages/test-utils/package.json index 3d59752b2318..b8d356b01237 100644 --- a/dev-packages/test-utils/package.json +++ b/dev-packages/test-utils/package.json @@ -50,7 +50,7 @@ "scripts": { "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", - "build": "run-s build:transpile build:types", + "build": "pnpm run build:transpile && pnpm run build:types", "build:tarball": "pnpm pack", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", diff --git a/package.json b/package.json index 478c7c7a1a32..c86491712e4f 100644 --- a/package.json +++ b/package.json @@ -9,22 +9,22 @@ "build:dev:filter": "nx run-many -t build:dev -p", "build:transpile": "nx run-many -t build:transpile", "build:types": "nx run-many -t build:types", - "build:tarball": "run-s clean:tarballs build:tarballs", + "build:tarball": "pnpm run clean:tarballs && pnpm run build:tarballs", "build:tarballs": "nx run-many -t build:tarball", "ci:print-build-artifact-paths": "node ./scripts/ci-print-build-artifact-paths.mjs", "changelog": "tsx ./scripts/get-commit-list.ts", "generate-changelog": "tsx ./scripts/generate-changelog.ts", - "clean": "run-s clean:build clean:caches", + "clean": "pnpm run clean:build && pnpm run clean:caches", "clean:build": "nx run-many -t clean", "clean:caches": "node scripts/rm.mjs eslintcache .nxcache .nx", "clean:deps": "node scripts/rm.mjs packages/*/node_modules dev-packages/*/node_modules node_modules && pnpm install", "clean:tarballs": "node scripts/rm.mjs packages/*/*.tgz dev-packages/*/*.tgz", "clean:watchman": "watchman watch-del \".\"", - "clean:all": "run-s clean:build clean:tarballs clean:caches clean:deps clean:watchman", + "clean:all": "pnpm run clean:build && pnpm run clean:tarballs && pnpm run clean:caches && pnpm run clean:deps && pnpm run clean:watchman", "format": "oxfmt . --write", "format:check": "oxfmt . --check", - "verify": "run-s format:check lint", - "fix": "run-s format lint:fix", + "verify": "pnpm run format:check && pnpm run lint", + "fix": "pnpm run format && pnpm run lint:fix", "lint": "oxlint .", "lint:fix": "oxlint . --fix", "lint:es-compatibility": "nx run-many -t lint:es-compatibility", @@ -146,7 +146,6 @@ "es-check": "^9.8.1", "esbuild": "^0.28.1", "jsdom": "^21.1.2", - "npm-run-all2": "^6.2.0", "nx": "24.0.3", "oxfmt": "^0.74.0", "oxlint": "^1.89.0", diff --git a/packages/astro/package.json b/packages/astro/package.json index ee1c7032d8f1..0343217a3c52 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -80,7 +80,7 @@ "vite": "^8.3.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 651d43594316..0040ca03ea31 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -79,11 +79,11 @@ "@vercel/nft": "^1.11.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:extension": "rolldown -c rollup.lambda-extension.config.mjs && pnpm exec tsx scripts/buildLambdaExtension.ts", "build:layer": "node ../../scripts/rm.mjs build/aws && pnpm exec tsx scripts/buildLambdaLayer.ts", - "build:dev": "run-p build:transpile build:types", - "build:transpile": "run-s build:transpile:npm build:extension", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", + "build:transpile": "pnpm run build:transpile:npm && pnpm run build:extension", "build:transpile:npm": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index f82f2fe0f811..b0c4280b0cad 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -41,7 +41,7 @@ "@sentry-internal/rollup-utils": "11.12.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/browser/package.json b/packages/browser/package.json index c8f530efe3c8..3cd49ea617e1 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -51,8 +51,8 @@ "fake-indexeddb": "^6.2.7" }, "scripts": { - "build": "run-p build:transpile build:bundle build:types", - "build:dev": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|bundle|types)$/\"", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:bundle": "rolldown -c rollup.bundle.config.mjs", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/bun/package.json b/packages/bun/package.json index c7fd4850b447..8daab94a6c1e 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -54,7 +54,7 @@ "bun-types": "^1.2.9" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", @@ -65,7 +65,7 @@ "lint:types": "oxlint src --type-aware --type-check", "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", "install:bun": "node ./scripts/install-bun.js", - "test": "run-s install:bun test:bun", + "test": "pnpm run install:bun && pnpm run test:bun", "test:bun": "bun test", "test:watch": "bun test --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index a39ef349e968..69ac934fb8cf 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -72,7 +72,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:version": "node -p \"'export const LIB_VERSION = ' + JSON.stringify(require('./package.json').version) + ';'\" > src/core/version.ts", "build:transpile": "rolldown -c rollup.npm.config.mjs", @@ -83,11 +83,11 @@ "prelint:types": "pnpm run build:version", "pretest": "pnpm run build:version", "pretest:unit": "pnpm run build:version", - "check:types": "run-p check:types:src check:types:test", + "check:types": "pnpm run \"/^check:types:(src|test)$/\"", "check:types:src": "tsc --project ./tsconfig.json --noEmit", "check:types:test": "tsc --project ./test/tsconfig.json --noEmit", "clean": "node ../../scripts/rm.mjs build dist coverage sentry-bundler-plugins-*.tgz", - "clean:all": "run-p clean clean:deps", + "clean:all": "pnpm run \"/^(clean|clean:deps)$/\"", "clean:deps": "node ../../scripts/rm.mjs node_modules", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 95fed1b2d387..2d4b43d99e25 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -84,7 +84,7 @@ "wrangler": "4.156.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/core/package.json b/packages/core/package.json index 1c955b71f20e..09cb5d56064f 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -68,7 +68,7 @@ "access": "public" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/deno/package.json b/packages/deno/package.json index b178b8849767..832bde8e61c3 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -39,7 +39,7 @@ }, "scripts": { "deno-types": "node ./scripts/download-deno-types.mjs", - "build": "run-s build:transpile build:types", + "build": "pnpm run build:transpile && pnpm run build:types", "build:dev": "pnpm run build", "build:transpile": "pnpm run deno-types && rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", @@ -52,7 +52,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint:es-compatibility": "es-check es2022 ./build/esm/*.js --module", "install:deno": "node ./scripts/install-deno.mjs", - "test": "run-s install:deno deno-types test:types test:unit", + "test": "pnpm run install:deno && pnpm run deno-types && pnpm run test:types && pnpm run test:unit", "test:types": "deno check --unstable-sloppy-imports test", "test:unit": "deno test --allow-net --allow-read --allow-run --allow-env --no-check", "test:unit:update": "deno test --allow-net --allow-read --allow-run --allow-env --no-check --allow-write -- --update", diff --git a/packages/effect/package.json b/packages/effect/package.json index d578087bdb24..2fe0fa60ceac 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -63,7 +63,7 @@ "effect": "^4.0.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 30f03c0fbb69..316d91f7fcb8 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -50,7 +50,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/esbuild-plugin/package.json b/packages/esbuild-plugin/package.json index ecc777455800..f6aa67d378ca 100644 --- a/packages/esbuild-plugin/package.json +++ b/packages/esbuild-plugin/package.json @@ -33,7 +33,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/feedback/package.json b/packages/feedback/package.json index 2dad2dd77ea7..8958603e2100 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -40,10 +40,10 @@ "preact": "^10.29.8" }, "scripts": { - "build": "run-p build:transpile build:types build:bundle", + "build": "pnpm run \"/^build:(transpile|types|bundle)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:bundle": "rolldown -c rollup.bundle.config.mjs", - "build:dev": "run-p build:transpile build:types", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-feedback-*.tgz", diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index 4b38bf93f1f0..a4c9a8793d3c 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -53,10 +53,10 @@ "webpack": "^5.112.2" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:plugin": "tsc -p tsconfig.plugin.json", - "build:transpile": "run-p build:rollup build:plugin", + "build:transpile": "pnpm run \"/^build:(rollup|plugin)$/\"", "build:rollup": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index 41314b5eb33c..7d26f2410cc9 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -59,7 +59,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/hono/package.json b/packages/hono/package.json index 1540e4e5ae07..21b4b18d6827 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -114,7 +114,7 @@ "hono-5": "npm:hono@5.0.0-rc.1" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/integration-shims/package.json b/packages/integration-shims/package.json index 99d183a80ba0..133713d9aad0 100644 --- a/packages/integration-shims/package.json +++ b/packages/integration-shims/package.json @@ -24,7 +24,7 @@ "sideEffects": false, "private": true, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:dev": "pnpm run build", diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index 4f839a87959e..218616f8c264 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -71,10 +71,10 @@ "@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core build:types:setup", + "build:types": "pnpm run build:types:core && pnpm run build:types:setup", "build:types:core": "tsc -p tsconfig.types.json", "build:types:setup": "tsc -p tsconfig.setup-types.json", "build:tarball": "pnpm pack", diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 460c4aec584f..d357a6910ebe 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -129,7 +129,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "tsx --tsconfig tsconfig.tsnode.json scripts/buildRollup.ts", "build:types": "tsc -p tsconfig.types.json", @@ -140,7 +140,7 @@ "lint:types": "oxlint src --type-aware --type-check", "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", "test": "pnpm run test:unit", - "test:all": "run-s test:unit", + "test:all": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", "vercel:branch": "source vercel/set-up-branch-for-test-app-use.sh", diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 12b88bece70a..eba30b9b5dd7 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -49,10 +49,10 @@ "srvx": "^0.11.22" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core", + "build:types": "pnpm run build:types:core", "build:types:core": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-nitro-*.tgz", diff --git a/packages/node/package.json b/packages/node/package.json index 81e61c1f1cab..cf779475cf29 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -90,7 +90,7 @@ "@types/node": "^20.19.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 90911a154f6d..cdc69a691472 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -80,7 +80,7 @@ "vue": "^3.5.41" }, "scripts": { - "build": "run-s build:types build:transpile", + "build": "pnpm run build:types && pnpm run build:transpile", "build:dev": "pnpm run build", "build:nuxt-module": "rolldown -c rollup.module.config.mjs && tsc -p tsconfig.module.json && node scripts/build-module-meta.mjs", "build:transpile": "rolldown -c rollup.npm.config.mjs && pnpm run build:nuxt-module", diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 8e7c1070da83..5c65f22d0f45 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -38,7 +38,7 @@ "@sentry-internal/rollup-utils": "11.12.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 56fac5778445..ee925d2b6c0f 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -83,10 +83,10 @@ "react-router": ">=7.15.0 || ^8.x" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core", + "build:types": "pnpm run build:types:core", "build:types:core": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build coverage sentry-react-router-*.tgz", diff --git a/packages/react/package.json b/packages/react/package.json index 755b92b2c023..84f8238313dc 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -89,7 +89,7 @@ "redux": "^5.0.1" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/remix/package.json b/packages/remix/package.json index 0d6807ee7c15..6d64b6adf223 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -108,7 +108,7 @@ "remix": "3.x" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index ee4e3c30ee5c..31cf5a1e1006 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -24,10 +24,10 @@ ], "sideEffects": false, "scripts": { - "build": "run-p build:transpile build:types build:bundle", + "build": "pnpm run \"/^build:(transpile|types|bundle)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:bundle": "rolldown -c rollup.bundle.config.mjs", - "build:dev": "run-p build:transpile build:types", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 131723e9cdd5..fc35d882121f 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -38,10 +38,10 @@ "access": "public" }, "scripts": { - "build": "run-p build:transpile build:types build:bundle", + "build": "pnpm run \"/^build:(transpile|types|bundle)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:bundle": "rolldown -c rollup.bundle.config.mjs", - "build:dev": "run-p build:transpile build:types", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "clean": "node ../../scripts/rm.mjs build sentry-replay-*.tgz", diff --git a/packages/replay-worker/package.json b/packages/replay-worker/package.json index b4a4e758b088..a41c2420c06f 100644 --- a/packages/replay-worker/package.json +++ b/packages/replay-worker/package.json @@ -28,7 +28,7 @@ "sideEffects": false, "private": true, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:transpile": "rolldown -c rollup.worker.config.mjs", "build:examples": "rolldown -c rollup.examples.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/rollup-plugin/package.json b/packages/rollup-plugin/package.json index 2d2234f1f2f5..43d277877557 100644 --- a/packages/rollup-plugin/package.json +++ b/packages/rollup-plugin/package.json @@ -34,7 +34,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/server-runtime-injection/package.json b/packages/server-runtime-injection/package.json index ca4ffbd9beb5..0ec861152b51 100644 --- a/packages/server-runtime-injection/package.json +++ b/packages/server-runtime-injection/package.json @@ -58,7 +58,7 @@ "supports-color": "7.2.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 4f831eaf6242..2ff3dae8ecfe 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -115,7 +115,7 @@ "webpack": "^5.112.2" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/solid/package.json b/packages/solid/package.json index 03abfd2b5242..316e50646334 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -84,10 +84,10 @@ "vite-plugin-solid": "^2.11.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core build:types:routers", + "build:types": "pnpm run build:types:core && pnpm run build:types:routers", "build:types:core": "tsc -p tsconfig.types.json", "build:types:routers": "tsc -p tsconfig.routers-types.json", "build:tarball": "pnpm pack", diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index d9586fdf3541..91f7be5f6f04 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -110,10 +110,10 @@ "vite-plugin-solid": "^2.11.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core build:types:subexports", + "build:types": "pnpm run build:types:core && pnpm run build:types:subexports", "build:types:core": "tsc -p tsconfig.types.json", "build:types:subexports": "tsc -p tsconfig.subexports-types.json", "build:tarball": "pnpm pack", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 6e63941b559e..e36a8a710ef5 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -48,7 +48,7 @@ "vite": "^8.3.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 551b30fbd69d..c6792b282cb8 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -94,7 +94,7 @@ "vite": "^8.3.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 2a1375d1c24d..841d16a0c308 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -67,7 +67,7 @@ "vite": "^8.3.6" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index f0a9b86473da..4a0274d0c3f8 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -42,7 +42,7 @@ "@sentry/opentelemetry": "11.12.0" }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/vite-plugin/package.json b/packages/vite-plugin/package.json index 643cb47bfd71..5a3a6240b6d0 100644 --- a/packages/vite-plugin/package.json +++ b/packages/vite-plugin/package.json @@ -33,7 +33,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/packages/vue/package.json b/packages/vue/package.json index f33cdfab4920..79f6557c95a6 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -67,10 +67,10 @@ "vue": "~3.5.44" }, "scripts": { - "build": "run-p build:transpile build:types", - "build:dev": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", - "build:types": "run-s build:types:core build:types:router", + "build:types": "pnpm run build:types:core && pnpm run build:types:router", "build:types:core": "tsc -p tsconfig.types.json", "build:types:router": "tsc -p tsconfig.router-types.json", "build:tarball": "pnpm pack", diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 8054f94f5c73..58a6096c0819 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -39,9 +39,9 @@ "@sentry-internal/rollup-utils": "11.12.0" }, "scripts": { - "build": "run-p build:transpile build:bundle build:types", + "build": "pnpm run \"/^build:(transpile|bundle|types)$/\"", "build:bundle": "rolldown --config rollup.bundle.config.mjs", - "build:dev": "run-p build:transpile build:types", + "build:dev": "pnpm run \"/^build:(transpile|types)$/\"", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", diff --git a/packages/webpack-plugin/package.json b/packages/webpack-plugin/package.json index b3a8d58f789f..1f7d86525bc0 100644 --- a/packages/webpack-plugin/package.json +++ b/packages/webpack-plugin/package.json @@ -38,7 +38,7 @@ } }, "scripts": { - "build": "run-p build:transpile build:types", + "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", "build:transpile": "rolldown -c rollup.npm.config.mjs", "build:types": "tsc -p tsconfig.types.json", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6894f3a6c554..1d703ea31656 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -213,9 +213,6 @@ importers: jsdom: specifier: ^21.1.2 version: 21.1.2(supports-color@10.0.0) - npm-run-all2: - specifier: ^6.2.0 - version: 6.2.0 nx: specifier: 24.0.3 version: 24.0.3 @@ -13340,10 +13337,6 @@ packages: json-parse-even-better-errors@2.3.1: resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} - json-parse-even-better-errors@3.0.2: - resolution: {integrity: sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==} - engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} - json-schema-ref-resolver@3.0.0: resolution: {integrity: sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==} @@ -13971,10 +13964,6 @@ packages: memory-streams@0.1.3: resolution: {integrity: sha512-qVQ/CjkMyMInPaaRMrwWNDvf6boRZXaT/DbQeMYcCWuXPEBf1v8qChOc9OlEVQp2uOvRXa1Qu30fLmKhY6NipA==} - memorystream@0.3.1: - resolution: {integrity: sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==} - engines: {node: '>= 0.10.0'} - meow@13.2.0: resolution: {integrity: sha512-pxQJQzB6djGPXh08dacEloMFopsOqGVRKFPYvPOt9XDZ1HasbgDZA74CJGreSU4G3Ak7EFJGoiH2auq+yXISgA==} engines: {node: '>=18'} @@ -14747,10 +14736,6 @@ packages: resolution: {integrity: sha512-awzfKUO7v0FscrSpRoogyNm0sajikhBWpU0QMrW09AMi9n1PoKU6WaIqUzuJSQnpciZZmJ/jMZ2Egfmb/9LiWQ==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} - npm-normalize-package-bin@3.0.1: - resolution: {integrity: sha512-dMxCf+zZ+3zeQZXKxmyuCKlIDPGuv8EF940xbkC4kQVDTtqoh6rJFO+JTKSA6/Rwi0getWmtuy4Itup0AMcaDQ==} - engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} - npm-package-arg@9.1.0: resolution: {integrity: sha512-4J0GL+u2Nh6OnhvUKXRr2ZMG4lR8qtLp+kv7UiV00Y+nGiSxtttCyIRHCt5L5BNkXQld/RceYItau3MDOoGiBw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -14768,11 +14753,6 @@ packages: resolution: {integrity: sha512-eukJPi++DKRTjSBRcDZSDDsGqRK3ehbxfFUcgaRd0Yp6kRwOwh2WVn0r+8rMB4nnuzvAk6rQVzl6K5CkYOmnvw==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} - npm-run-all2@6.2.0: - resolution: {integrity: sha512-wA7yVIkthe6qJBfiJ2g6aweaaRlw72itsFGF6HuwCHKwtwAx/4BY1vVpk6bw6lS8RLMsexoasOkd0aYOmsFG7Q==} - engines: {node: ^14.18.0 || >=16.0.0, npm: '>= 8'} - hasBin: true - npm-run-path@4.0.1: resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} engines: {node: '>=8'} @@ -15398,11 +15378,6 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} - pidtree@0.6.0: - resolution: {integrity: sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==} - engines: {node: '>=0.10'} - hasBin: true - pify@2.3.0: resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==} engines: {node: '>=0.10.0'} @@ -16179,10 +16154,6 @@ packages: resolution: {integrity: sha512-W/BKtbL+dUjTuRL2vziuYhp76s5HZ9qQhd/dKfWIZveD0O40453QNyZhC0e63lqZrAQ4jiOapVoeJ7JrszenQQ==} engines: {node: '>=10'} - read-package-json-fast@3.0.2: - resolution: {integrity: sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw==} - engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} - read-package-json@5.0.2: resolution: {integrity: sha512-BSzugrt4kQ/Z0krro8zhTwV1Kd79ue25IhNN/VtHFy1mG/6Tluyi+msc0UpwaoQzxSHa28mntAjIZY6kEgfR9Q==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -33044,8 +33015,6 @@ snapshots: json-parse-even-better-errors@2.3.1: {} - json-parse-even-better-errors@3.0.2: {} - json-schema-ref-resolver@3.0.0: dependencies: dequal: 2.0.3 @@ -33785,8 +33754,6 @@ snapshots: dependencies: readable-stream: 1.0.34 - memorystream@0.3.1: {} - meow@13.2.0: {} merge-anything@5.1.7: @@ -35041,8 +35008,6 @@ snapshots: npm-normalize-package-bin@2.0.0: {} - npm-normalize-package-bin@3.0.1: {} - npm-package-arg@9.1.0: dependencies: hosted-git-info: 5.1.0 @@ -35077,16 +35042,6 @@ snapshots: - bluebird - supports-color - npm-run-all2@6.2.0: - dependencies: - ansi-styles: 6.2.3 - cross-spawn: 7.0.6 - memorystream: 0.3.1 - minimatch: 9.0.9 - pidtree: 0.6.0 - read-package-json-fast: 3.0.2 - shell-quote: 1.12.0 - npm-run-path@4.0.1: dependencies: path-key: 3.1.1 @@ -36006,8 +35961,6 @@ snapshots: picomatch@4.0.7: {} - pidtree@0.6.0: {} - pify@2.3.0: {} pify@4.0.1: {} @@ -36981,11 +36934,6 @@ snapshots: json-parse-even-better-errors: 2.3.1 npm-normalize-package-bin: 1.0.1 - read-package-json-fast@3.0.2: - dependencies: - json-parse-even-better-errors: 3.0.2 - npm-normalize-package-bin: 3.0.1 - read-package-json@5.0.2: dependencies: glob: 8.1.0 From d1ece2679a1de5a7aae3b106f09d8cd6dbecefb4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:58:27 +0100 Subject: [PATCH 071/136] docs(aws-serverless): Use Lambda Event Functions naming in README (#26354) **Why:** AWS renamed Lambda functions to [Lambda Event Functions](https://docs.aws.amazon.com/lambda/latest/dg/lambda-functions-chapter.html) so they're distinct from the new [Lambda Web Functions](https://docs.aws.amazon.com/lambda/latest/dg/web-functions.html). `@sentry/aws-serverless` targets Event Functions only. Web Functions run a plain HTTP server and should use `@sentry/node`, which already ships `awsLambdaWebIntegration` by default. This matches the docs wording from getsentry/sentry-docs#20722. **How to review:** It's a README-only change. I left code comments and test names alone, since "Lambda function" is still correct there and matches the AWS API. refs https://github.com/getsentry/sentry-javascript/issues/25812 via @msonnb. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0C5DRTAU2X%3A1794314659.768059) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0C5DRTAU2X%3A1794314659.768059/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Martin Sonnberger <26038247+msonnb@users.noreply.github.com> --- README.md | 2 +- packages/aws-serverless/README.md | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0d82b7f93172..dc97eaf54018 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ package. Please refer to the README and instructions of those SDKs for more deta - [`@sentry/remix`](https://github.com/getsentry/sentry-javascript/tree/master/packages/remix): SDK for Remix - [`@sentry/tanstackstart-react`](https://github.com/getsentry/sentry-javascript/tree/master/packages/tanstackstart-react): SDK for TanStack Start React - [`@sentry/aws-serverless`](https://github.com/getsentry/sentry-javascript/tree/master/packages/aws-serverless): SDK - for AWS Lambda Functions + for AWS Lambda Event Functions - [`@sentry/google-cloud-serverless`](https://github.com/getsentry/sentry-javascript/tree/master/packages/google-cloud-serverless): SDK for Google Cloud Functions - [`@sentry/electron`](https://github.com/getsentry/sentry-electron): SDK for Electron with support for native crashes diff --git a/packages/aws-serverless/README.md b/packages/aws-serverless/README.md index fc183f7dd7e2..d12f93087893 100644 --- a/packages/aws-serverless/README.md +++ b/packages/aws-serverless/README.md @@ -10,7 +10,11 @@ # Official Sentry SDK for AWS Lambda -The official Sentry SDK for monitoring AWS Lambda functions. +The official Sentry SDK for monitoring AWS Lambda Event Functions (formerly called Lambda functions). + +For Lambda Web Functions, which run a standard HTTP server, use [`@sentry/node`](https://github.com/getsentry/sentry-javascript/tree/master/packages/node) instead. Its default +[`awsLambdaWebIntegration`](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/awslambdaweb/) +adds Lambda metadata to your errors and spans. ## Documentation From d36fbf9c55826643ba44bbb915d04d8b542d86de Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:08:10 +0100 Subject: [PATCH 072/136] chore(build): Replace es-check with an acorn-based script (#26321) **Why:** The way we use `es-check` (no `--checkFeatures`, no browserslist), all it does is run `acorn.parse(code, { ecmaVersion })` on files from a glob. `scripts/es-check.mjs` does that in ~40 lines with `acorn` and `fs.globSync`, and it drops one package (`acorn`, `browserslist` and `fast-glob` are all still used elsewhere). The bigger fix is coverage. The old globs, like `./build/esm/*.js`, weren't recursive. They checked about 560 of the roughly 3,100 built files (core: 58/436, node: 8/158, nextjs: 4/224). The script now checks every `.js/.mjs/.cjs` file under `build/` (skipping `node_modules`). Every file is parsed as a module, so we no longer need `--module` or separate cjs/esm calls. Hashbangs are allowed for `aws-serverless`'s lambda extension. **Remix exceptions:** `build/esm/v3/client-bundle.js` (the `./v3/client` browser entry) inlines `web-vitals@6` untranspiled, so it is checked against es2022 instead. Its `Array.prototype.at` use is guarded since #26347, and its only ES2022 syntax is public instance class fields (Chrome 72 / Firefox 69 / Safari 14). `build/v3-node.mjs` is Node-only and uses top-level await, so it's also checked against es2022. To exclude the bundle from the es2020 pass, the script now accepts `!` globs. **Why not `--checkFeatures`:** I ran it over all of the current build output. It matches on method names, so it gets both kinds of result wrong. Every OTel `context.with()` is reported as `Array.prototype.with`. Meanwhile `arr.at(-1)` isn't reported at all (I reproduced that with a two-line file). via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794484218.498979) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794484218.498979/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- package.json | 2 +- packages/angular/package.json | 2 +- packages/astro/package.json | 2 +- packages/aws-serverless/package.json | 2 +- packages/browser-utils/package.json | 2 +- packages/browser/package.json | 2 +- packages/bun/package.json | 2 +- packages/cloudflare/package.json | 2 +- packages/core/package.json | 2 +- packages/deno/package.json | 2 +- packages/elysia/package.json | 2 +- packages/feedback/package.json | 2 +- packages/gatsby/package.json | 2 +- packages/google-cloud-serverless/package.json | 2 +- packages/hono/package.json | 2 +- packages/integration-shims/package.json | 2 +- packages/nestjs/package.json | 2 +- packages/nextjs/package.json | 2 +- packages/nitro/package.json | 2 +- packages/node-native/package.json | 2 +- packages/node/package.json | 2 +- packages/nuxt/package.json | 2 +- packages/opentelemetry/package.json | 2 +- packages/profiling-node/package.json | 2 +- packages/react-router/package.json | 2 +- packages/react/package.json | 2 +- packages/remix/package.json | 5 +- packages/replay-canvas/package.json | 2 +- packages/replay-internal/package.json | 2 +- packages/replay-worker/package.json | 2 +- .../server-runtime-injection/package.json | 2 +- packages/server-utils/package.json | 2 +- packages/solid/package.json | 2 +- packages/solidstart/package.json | 2 +- packages/svelte/package.json | 2 +- packages/sveltekit/package.json | 2 +- packages/tanstackstart-react/package.json | 2 +- packages/vercel-edge/package.json | 2 +- packages/vue/package.json | 2 +- packages/wasm/package.json | 2 +- pnpm-lock.yaml | 17 ++----- scripts/es-check.mjs | 46 +++++++++++++++++++ 42 files changed, 92 insertions(+), 54 deletions(-) create mode 100644 scripts/es-check.mjs diff --git a/package.json b/package.json index c86491712e4f..d4f8cbf9a2d7 100644 --- a/package.json +++ b/package.json @@ -142,8 +142,8 @@ "@types/jsdom": "^21.1.6", "@types/node": "^20.19.0", "@vitest/coverage-v8": "^4.1.11", + "acorn": "^8.14.0", "deepmerge": "^4.2.2", - "es-check": "^9.8.1", "esbuild": "^0.28.1", "jsdom": "^21.1.2", "nx": "24.0.3", diff --git a/packages/angular/package.json b/packages/angular/package.json index b8942e05027f..19ed4fc1cc91 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -51,7 +51,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/{esm2020,fesm2015,fesm2020}/*.mjs --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:unit:watch": "vitest --watch", diff --git a/packages/astro/package.json b/packages/astro/package.json index 0343217a3c52..2af95c285918 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -89,7 +89,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 0040ca03ea31..14991a4f7463 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -91,7 +91,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/npm/cjs/*.js && es-check es2022 ./build/npm/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index b0c4280b0cad..ab3c75015436 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -50,7 +50,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/browser/package.json b/packages/browser/package.json index 3cd49ea617e1..de9e2b2071ca 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -61,7 +61,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs/prod}/*.js && es-check es2020 ./build/npm/esm/prod/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "size:check": "cat build/bundles/bundle.min.js | gzip -9 | wc -c | awk '{$1=$1/1024; print \"ES2017: \",$1,\"kB\";}'", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/bun/package.json b/packages/bun/package.json index 8daab94a6c1e..cc6b79ccd2d3 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -63,7 +63,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "install:bun": "node ./scripts/install-bun.js", "test": "pnpm run install:bun && pnpm run test:bun", "test:bun": "bun test", diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 2d4b43d99e25..ffedba65f2de 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -93,7 +93,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/prod/*.js && es-check es2022 ./build/esm/prod/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/core/package.json b/packages/core/package.json index 09cb5d56064f..c36050eee3e1 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -77,7 +77,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/deno/package.json b/packages/deno/package.json index 832bde8e61c3..e001238bd8b7 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -50,7 +50,7 @@ "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", "lint:fix": "oxlint . --fix --type-aware", - "lint:es-compatibility": "es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "install:deno": "node ./scripts/install-deno.mjs", "test": "pnpm run install:deno && pnpm run deno-types && pnpm run test:types && pnpm run test:unit", "test:types": "deno check --unstable-sloppy-imports test", diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 316d91f7fcb8..00224d09879e 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -59,7 +59,7 @@ "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", "lint:fix": "oxlint . --fix --type-aware", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/feedback/package.json b/packages/feedback/package.json index 8958603e2100..5560bc98b492 100644 --- a/packages/feedback/package.json +++ b/packages/feedback/package.json @@ -50,7 +50,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/gatsby/package.json b/packages/gatsby/package.json index a4c9a8793d3c..7645783b6581 100644 --- a/packages/gatsby/package.json +++ b/packages/gatsby/package.json @@ -64,7 +64,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index 7d26f2410cc9..b53f3cda23f1 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -68,7 +68,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/hono/package.json b/packages/hono/package.json index 21b4b18d6827..128f29ff1d55 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -123,7 +123,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/integration-shims/package.json b/packages/integration-shims/package.json index 133713d9aad0..9f822ce2b6d1 100644 --- a/packages/integration-shims/package.json +++ b/packages/integration-shims/package.json @@ -32,7 +32,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run" }, "repository": { diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index 218616f8c264..c0dfc2e52f4d 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -82,7 +82,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index d357a6910ebe..8fb77f081e90 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -138,7 +138,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:all": "pnpm run test:unit", "test:unit": "vitest run", diff --git a/packages/nitro/package.json b/packages/nitro/package.json index eba30b9b5dd7..73e43de432bd 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -59,7 +59,7 @@ "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", "lint:fix": "oxlint . --fix --type-aware", - "lint:es-compatibility": "es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/node-native/package.json b/packages/node-native/package.json index f5337eb4b677..71eb7109ea15 100644 --- a/packages/node-native/package.json +++ b/packages/node-native/package.json @@ -44,7 +44,7 @@ "clean": "rm -rf build", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "lint:fix": "oxlint . --fix --type-aware", "build": "pnpm run build:types && pnpm run build:transpile", "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", diff --git a/packages/node/package.json b/packages/node/package.json index cf779475cf29..d9e5ecefe06d 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -99,7 +99,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index cdc69a691472..fb25583544ea 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -90,7 +90,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module && es-check es2020 ./build/module/*.mjs --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 5c65f22d0f45..1ef7ce1941c7 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -47,7 +47,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/profiling-node/package.json b/packages/profiling-node/package.json index 088e8557136d..bac8a820efc4 100644 --- a/packages/profiling-node/package.json +++ b/packages/profiling-node/package.json @@ -36,7 +36,7 @@ "clean": "rm -rf build", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2022 ./build/cjs/*.js && es-check es2022 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2022", "lint:fix": "oxlint . --fix --type-aware", "build": "pnpm run build:types && pnpm run build:transpile", "build:transpile": "pnpm exec rolldown -c rollup.npm.config.mjs", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index ee925d2b6c0f..4cc1ab5c0ff8 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -93,7 +93,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/react/package.json b/packages/react/package.json index 84f8238313dc..39930478c6cd 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -98,7 +98,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/remix/package.json b/packages/remix/package.json index 6d64b6adf223..0c537ec5d930 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -107,6 +107,9 @@ "react": "18.x", "remix": "3.x" }, + "//_scripts_comment": [ + "`lint:es-compatibility`: `build/v3-node.mjs` is Node-only and uses top-level await. `build/esm/v3/client-bundle.js` inlines web-vitals 6 untranspiled, whose only ES2022 syntax is public instance class fields (Chrome 72, Firefox 69, Safari 14, so supported by all our minimum browsers). Its `Array.prototype.at` use is guarded since #26347." + ], "scripts": { "build": "pnpm run \"/^build:(transpile|types)$/\"", "build:dev": "pnpm run build", @@ -117,7 +120,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020 'build/{cjs,esm}/**/*.js' '!build/esm/v3/client-bundle.js' build/import-hook.mjs && node ../../scripts/es-check.mjs es2022 build/esm/v3/client-bundle.js build/v3-node.mjs", "test": "pnpm run test:unit", "test:unit": "vitest run --config vitest.config.unit.ts", "test:watch": "vitest --watch --config vitest.config.unit.ts", diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index 31cf5a1e1006..594e98bf79e6 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -34,7 +34,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index fc35d882121f..24705d7c7e4d 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -50,7 +50,7 @@ "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", "lint:fix": "oxlint . --fix --type-aware", - "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/replay-worker/package.json b/packages/replay-worker/package.json index a41c2420c06f..0d013e7ab542 100644 --- a/packages/replay-worker/package.json +++ b/packages/replay-worker/package.json @@ -37,7 +37,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch" }, diff --git a/packages/server-runtime-injection/package.json b/packages/server-runtime-injection/package.json index 0ec861152b51..ae8dd5c4d00c 100644 --- a/packages/server-runtime-injection/package.json +++ b/packages/server-runtime-injection/package.json @@ -67,7 +67,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 2ff3dae8ecfe..5635003d8d11 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -124,7 +124,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test:unit": "vitest run", "test": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/solid/package.json b/packages/solid/package.json index 316e50646334..410ab7036ebd 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -95,7 +95,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 91f7be5f6f04..66a607fe19c4 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -121,7 +121,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index e36a8a710ef5..bf0ec462b2e7 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -57,7 +57,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index c6792b282cb8..9242cfa7d70e 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -103,7 +103,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 841d16a0c308..a9889fd4bb42 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -76,7 +76,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "pnpm run test:unit", "test:unit": "vitest run", "test:watch": "vitest --watch", diff --git a/packages/vercel-edge/package.json b/packages/vercel-edge/package.json index 4a0274d0c3f8..f0c9cbf3a054 100644 --- a/packages/vercel-edge/package.json +++ b/packages/vercel-edge/package.json @@ -51,7 +51,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/vue/package.json b/packages/vue/package.json index 79f6557c95a6..33808bdb0941 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -78,7 +78,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/cjs/*.js && es-check es2020 ./build/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "test": "vitest run", "test:watch": "vitest --watch", "yalc:publish": "pnpm dlx yalc publish --push --sig" diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 58a6096c0819..279ea337d84e 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -51,7 +51,7 @@ "lint:fix": "oxlint . --fix --type-aware", "lint": "oxlint . --type-aware", "lint:types": "oxlint src --type-aware --type-check", - "lint:es-compatibility": "es-check es2020 ./build/{bundles,npm/cjs}/*.js && es-check es2020 ./build/npm/esm/*.js --module", + "lint:es-compatibility": "node ../../scripts/es-check.mjs es2020", "yalc:publish": "pnpm dlx yalc publish --push --sig" }, "sideEffects": false diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1d703ea31656..e44a43d32aaf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -201,12 +201,12 @@ importers: '@vitest/coverage-v8': specifier: ^4.1.11 version: 4.1.11(vitest@4.1.12) + acorn: + specifier: ^8.14.0 + version: 8.18.0 deepmerge: specifier: ^4.2.2 version: 4.3.1 - es-check: - specifier: ^9.8.1 - version: 9.8.1 esbuild: specifier: ^0.28.1 version: 0.28.1 @@ -11438,11 +11438,6 @@ packages: resolution: {integrity: sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==} engines: {node: '>= 0.4'} - es-check@9.8.1: - resolution: {integrity: sha512-F6bumjRmN+OWpEUh3ewhE/S1ey6cHKGMNXPn0iE2tBnict3O855Uij6UYbuHnLS1E3eILvg61KdH6kHbGi9www==} - engines: {node: '>=18.0.0'} - hasBin: true - es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -30638,12 +30633,6 @@ snapshots: unbox-primitive: 1.1.0 which-typed-array: 1.1.19 - es-check@9.8.1: - dependencies: - acorn: 8.18.0 - browserslist: 4.29.0 - fast-glob: 3.3.3 - es-define-property@1.0.1: {} es-errors@1.3.0: {} diff --git a/scripts/es-check.mjs b/scripts/es-check.mjs new file mode 100644 index 000000000000..eff596cc0137 --- /dev/null +++ b/scripts/es-check.mjs @@ -0,0 +1,46 @@ +// Fails if any built file (default: everything in `build/`) uses syntax newer than the given ES version. +// Globs starting with `!` exclude files from the other globs. +/* eslint-disable no-console */ +import { globSync, readFileSync } from 'node:fs'; +import { parse } from 'acorn'; + +const [target, ...args] = process.argv.slice(2); +const ecmaVersion = Number(target?.replace(/^es/, '')); +const excludes = ['**/node_modules/**', ...args.filter(arg => arg.startsWith('!')).map(arg => arg.slice(1))]; +const includes = args.filter(arg => !arg.startsWith('!')); +const patterns = includes.length ? includes : ['build/**/*.{js,mjs,cjs}']; + +if (!ecmaVersion) { + console.error('Usage: node es-check.mjs [glob...]'); + process.exit(1); +} + +let fileCount = 0; +let failed = false; + +for (const pattern of patterns) { + const files = globSync(pattern, { exclude: excludes }); + + if (!files.length) { + console.error(`es-check: no files match ${pattern}`); + failed = true; + } + + for (const file of files) { + fileCount++; + try { + // Module grammar is stricter than script grammar and also accepts CJS and IIFE output, so + // one mode covers every file. Hashbangs are allowed for CLI entry points. + parse(readFileSync(file, 'utf8'), { ecmaVersion, sourceType: 'module', allowHashBang: true }); + } catch (error) { + console.error(`es-check: ${file} is not valid ${target}: ${error.message}`); + failed = true; + } + } +} + +if (failed) { + process.exit(1); +} + +console.log(`es-check: ${fileCount} files are valid ${target}`); From e77c78ac994a0a0d6907da0ccd32152a9a23c9b9 Mon Sep 17 00:00:00 2001 From: isaacs Date: Fri, 13 Nov 2026 12:55:21 +0100 Subject: [PATCH 073/136] feat(node): Publish flat CJS builds to cut `@sentry/node` startup time (#25968) `require('@sentry/node')` loaded 606 CommonJS files and took about 95 ms. Most of that time went to resolving, reading and evaluating many small files, because each source file was a published file. The CJS builds of `@sentry/core`, `@sentry/node`, `@sentry/server-utils` and `@sentry/server-runtime-injection` now publish one file per entry, plus shared chunks with fixed names. `require('@sentry/node')` now loads 70 files in about 52 ms. The ESM builds keep one file per module. Bundlers use them, and drop unused files by the package's `sideEffects` setting. Flat ESM files made the Next.js edge build fail on `node:` imports in code it never used, and grew the server bundles in the size check by up to 140%. Each package keeps its `@sentry/*` dependencies external, so no package carries a second copy of another. Rolldown puts a module in a chunk by the set of entries that reach it, so build-time code stays out of the runtime entries, and runtime injection stays out of the build-time ones. In the flat CJS build of `@sentry/server-runtime-injection`, the vendored loader hook chain is in `chunks/hook.js`. Both `register.js` and `hook.js` require it, so a tracer that ships `register.js` still ships everything the hook needs. The nft trace test now checks for that chunk instead of the old `vendored/` path. The Lambda layer build now finds the `getSDKSource` marker by searching the core build, because the flat CJS build has no `utils/env.js`. Two cloudflare tests lose their mocks of that old CJS path. A new test caps the files each Sentry package loads when Node requires `@sentry/node`. The runtime-entries test now also checks that build-time entries do not reach runtime injection. Three config entries already do, through the `@sentry/node` and `@sentry/nitro` roots, and are known violations. Closes #25680 Co-authored-by: Claude Opus 5.5 --- .../tests/runtime-entries.test.ts | 87 +++++++++++++++---- .../bundler-tests/tests/startup.test.ts | 69 +++++++++++++++ .../nextjs-16/tests/worker-bundle.test.ts | 2 +- dev-packages/rollup-utils/npmHelpers.mjs | 23 +++++ .../scripts/buildLambdaLayer.ts | 27 ++++-- .../instrumentDurableObjectNamespace.test.ts | 3 - .../test/utils/instrumentFetcher.test.ts | 3 - packages/core/rollup.npm.config.mjs | 14 +-- packages/node/rollup.npm.config.mjs | 65 +++++++------- .../rollup.npm.config.mjs | 52 +++++------ .../test/nftTrace.test.ts | 2 +- packages/server-utils/rollup.npm.config.mjs | 84 +++++++++--------- .../src/orchestrion/bundler/webpack.ts | 2 +- 13 files changed, 297 insertions(+), 136 deletions(-) create mode 100644 dev-packages/bundler-tests/tests/startup.test.ts diff --git a/dev-packages/bundler-tests/tests/runtime-entries.test.ts b/dev-packages/bundler-tests/tests/runtime-entries.test.ts index 09cd3694c53f..90dcb2833f8c 100644 --- a/dev-packages/bundler-tests/tests/runtime-entries.test.ts +++ b/dev-packages/bundler-tests/tests/runtime-entries.test.ts @@ -17,15 +17,35 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '../../..'); const FIXTURE_DIR = path.join(__dirname, '..', 'dist', 'runtime-entries'); +/** Third-party build tools. No Sentry code is reachable through them. */ +const BUILD_TOOL_PATTERNS: RegExp[] = [ + /(^|\/)node_modules\/(vite|webpack|rollup|esbuild|oxc-parser)\//, + /(^|\/)node_modules\/@(babel|rollup|oxc-parser)\//, + /\.wasm$/, +]; + const BUILD_TIME_PATTERNS: RegExp[] = [ /(^|\/)packages\/bundler-plugins\//, /(^|\/)node_modules\/@sentry\/bundler-plugins(\/|$)/, /(^|\/)packages\/server-utils\/build\/[^/]+\/orchestrion\/bundler\//, - /(^|\/)node_modules\/(vite|webpack|rollup|esbuild|oxc-parser)\//, - /(^|\/)node_modules\/@(babel|rollup|oxc-parser)\//, - /\.wasm$/, + ...BUILD_TOOL_PATTERNS, +]; + +const RUNTIME_INJECTION_PATTERNS: RegExp[] = [ + /(^|\/)packages\/server-runtime-injection\//, + /(^|\/)node_modules\/@sentry\/server-runtime-injection(\/|$)/, ]; +// These config entries import the `@sentry/node` root, which installs +// runtime injection when a client is made. +const KNOWN_RUNTIME_INJECTION_VIOLATIONS = new Set([ + // `getSentryRelease` + '@sentry/nextjs/config', + '@sentry/sveltekit/vite', + // `setupSentryNitroModule`, through the `@sentry/nitro` root + '@sentry/solidstart/vite', +]); + type Format = 'esm' | 'cjs'; interface Case { @@ -137,8 +157,8 @@ function writeFixture(specifier: string, conditions: string[], format: Format): return file; } -function isBuildTime(file: string): boolean { - return BUILD_TIME_PATTERNS.some(pattern => pattern.test(file)); +function matches(file: string, patterns: RegExp[]): boolean { + return patterns.some(pattern => pattern.test(file)); } type Reasons = Awaited>['reasons']; @@ -172,10 +192,10 @@ function importChain(reasons: Reasons, entry: string, file: string): string[] { } /** - * Each place where a runtime module imports a build-time module, as the - * import chain from the entry. + * Each place where a module imports a module that matches `targets`, as + * the import chain from the entry. */ -async function findBuildTimeImports(fixture: string, conditions: string[]): Promise { +async function findImports(fixture: string, conditions: string[], targets: RegExp[]): Promise { const imports: [importer: string, file: string][] = []; const { fileList, reasons } = await nodeFileTrace([fixture], { @@ -185,14 +205,14 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom // A dynamic `fs` path in config code makes nft glob the whole repo. // That is slow and finds user files, not package code. analysis: { emitGlobs: false }, - // Stop at the first build-time module, instead of tracing all of Vite - // or Babel. `.wasm` files are assets, so they stay in the trace with - // their importer. - ignore: file => isBuildTime(file) && !file.endsWith('.wasm'), + // Stop at the first target, and do not trace all of Vite or Babel. + // `.wasm` files are assets, so they stay in the trace with their + // importer. + ignore: file => matches(file, [...targets, ...BUILD_TOOL_PATTERNS]) && !file.endsWith('.wasm'), async resolve(id, parent, job, cjsResolve) { const resolved = await resolve(id, parent, job, cjsResolve); for (const file of [resolved].flat()) { - if (isBuildTime(file)) { + if (matches(file, targets)) { imports.push([path.relative(ROOT_DIR, parent), path.relative(ROOT_DIR, file)]); } } @@ -201,7 +221,7 @@ async function findBuildTimeImports(fixture: string, conditions: string[]): Prom }); for (const file of fileList) { - if (file.endsWith('.wasm')) { + if (file.endsWith('.wasm') && matches(file, targets)) { for (const parent of reasons.get(file)?.parents ?? []) { imports.push([parent, file]); } @@ -222,12 +242,20 @@ describe('server runtime entries do not reach build-time tooling', () => { if (knownViolation) { test(`${name} is a known violation`, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).not.toEqual([]); }); } else { test(name, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).toEqual([]); }); } @@ -239,13 +267,38 @@ describe('build-time entries reach build-time tooling', () => { for (const { specifier, conditions, formats } of BUILD_TIME_CASES) { for (const format of formats) { test(`${specifier} (${format}, conditions: ${conditions.join(', ')})`, async () => { - const violations = await findBuildTimeImports(writeFixture(specifier, conditions, format), conditions); + const violations = await findImports( + writeFixture(specifier, conditions, format), + conditions, + BUILD_TIME_PATTERNS, + ); expect(violations).not.toEqual([]); }); } } }); +describe('build-time entries do not reach runtime injection', () => { + for (const { specifier, conditions, formats } of BUILD_TIME_CASES) { + for (const format of formats) { + const name = `${specifier} (${format}, conditions: ${conditions.join(', ')})`; + const find = (): Promise => + findImports(writeFixture(specifier, conditions, format), conditions, RUNTIME_INJECTION_PATTERNS); + + if (KNOWN_RUNTIME_INJECTION_VIOLATIONS.has(specifier)) { + test(`${name} is a known violation`, async () => { + // Remove the entry from KNOWN_RUNTIME_INJECTION_VIOLATIONS when this fails. + expect(await find()).not.toEqual([]); + }); + } else { + test(name, async () => { + expect(await find()).toEqual([]); + }); + } + } + } +}); + test('every export of a tested package is classified', () => { const classified = new Set([...CASES, ...BUILD_TIME_CASES].map(({ specifier }) => specifier)); for (const specifier of CLIENT_ENTRIES) { diff --git a/dev-packages/bundler-tests/tests/startup.test.ts b/dev-packages/bundler-tests/tests/startup.test.ts new file mode 100644 index 000000000000..2a94028e2663 --- /dev/null +++ b/dev-packages/bundler-tests/tests/startup.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * Node resolves, reads and evaluates each published file on its own, so + * the number of files that `@sentry/node` loads sets most of its startup + * cost. Our CJS builds publish flat entry files with a few shared chunks. + * The ESM builds keep one file per module, because bundlers use them and + * drop unused files. A count is stable in CI, where a timing is not. + */ + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE_DIR = path.join(__dirname, '..', 'dist', 'startup'); + +// One entry file and its shared chunks. +const MAX_FILES_PER_PACKAGE = 10; + +const COUNTER = `import { writeSync } from 'node:fs'; +import { registerHooks } from 'node:module'; +const files = new Set(); +registerHooks({ + load(url, context, nextLoad) { + if (url.startsWith('file:')) files.add(url); + return nextLoad(url, context); + }, +}); +// A pipe write from an exit handler must be sync, or Node cuts it off. +process.on('exit', () => writeSync(1, JSON.stringify([...files]))); +`; + +function loadedFiles(specifier: string): string[] { + fs.mkdirSync(FIXTURE_DIR, { recursive: true }); + const counter = path.join(FIXTURE_DIR, 'counter.mjs'); + fs.writeFileSync(counter, COUNTER); + const fixture = path.join(FIXTURE_DIR, `${specifier.replace(/[@/]/g, '_')}.cjs`); + fs.writeFileSync(fixture, `require('${specifier}');\n`); + + const output = execFileSync(process.execPath, ['--import', counter, fixture], { encoding: 'utf8' }); + return (JSON.parse(output) as string[]).map(url => fileURLToPath(url)).filter(file => file !== fixture); +} + +/** The package that `file` belongs to, for workspace and installed packages. */ +function packageOf(file: string): string { + const installed = file.split('/node_modules/').at(-1) as string; + if (installed !== file) { + const [scope, name] = installed.split('/'); + return scope?.startsWith('@') ? `${scope}/${name}` : (scope as string); + } + const workspace = file.match(/\/packages\/([^/]+)\//); + return workspace ? `@sentry/${workspace[1]}` : file; +} + +describe('@sentry/node startup', () => { + test(`each Sentry package loads at most ${MAX_FILES_PER_PACKAGE} files`, () => { + const counts: Record = {}; + for (const file of loadedFiles('@sentry/node')) { + const pkg = packageOf(file); + if (pkg.startsWith('@sentry/')) { + counts[pkg] = (counts[pkg] ?? 0) + 1; + } + } + + const tooMany = Object.fromEntries(Object.entries(counts).filter(([, count]) => count > MAX_FILES_PER_PACKAGE)); + expect(tooMany).toEqual({}); + }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts index cb2039d442f4..75354eae915b 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/worker-bundle.test.ts @@ -25,7 +25,7 @@ test('worker bundle does not contain the orchestrion bundler plugins', () => { ); expect(serverFiles.length).toBeGreaterThan(0); - const markers = ['code-transformer-bundler-plugins', '__codeTransformerWebpackDiagnostics']; + const markers = ['__codeTransformerWebpackDiagnostics']; // The markers must still exist in the installed plugin build. // If upstream renames them, this fails instead of letting the leak check below pass. diff --git a/dev-packages/rollup-utils/npmHelpers.mjs b/dev-packages/rollup-utils/npmHelpers.mjs index 5eed20ae5aae..c17229b805aa 100644 --- a/dev-packages/rollup-utils/npmHelpers.mjs +++ b/dev-packages/rollup-utils/npmHelpers.mjs @@ -223,6 +223,29 @@ export function makeBaseNPMConfig(options = {}) { }); } +/** + * Make the CJS variants flat: one file per entry, plus chunks for the code that entries share. + * Node resolves, reads and evaluates each file on its own, so `require()` starts much faster than + * with `preserveModules`. The ESM variants keep one file per module, because bundlers use them and + * drop unused files by the package's `sideEffects` setting. Name the entries with an object `input` + * to keep their paths. Chunk names have no hash, so file tracers see the same paths in each build. + */ +export function makeCjsVariantsFlat(configs) { + return configs.map(config => + config.output.format === 'cjs' + ? { + ...config, + output: { + ...config.output, + preserveModules: false, + entryFileNames: '[name].js', + chunkFileNames: 'chunks/[name].js', + }, + } + : config, + ); +} + export function makeNPMConfigVariants(baseConfig, options = {}) { const { emitEsm = true, emitCjs = true, splitDevProd = false } = options; diff --git a/packages/aws-serverless/scripts/buildLambdaLayer.ts b/packages/aws-serverless/scripts/buildLambdaLayer.ts index 11e2b630d5cb..5df19b677d82 100644 --- a/packages/aws-serverless/scripts/buildLambdaLayer.ts +++ b/packages/aws-serverless/scripts/buildLambdaLayer.ts @@ -223,9 +223,9 @@ function buildPackageJson(): void { function replaceSDKSource(): void { console.log('Replacing SDK source.'); - const envFiles = [ - './build/aws/dist-serverless/nodejs/node_modules/@sentry/core/build/cjs/utils/env.js', - './build/aws/dist-serverless/nodejs/node_modules/@sentry/core/build/esm/utils/env.js', + const buildDirs = [ + './build/aws/dist-serverless/nodejs/node_modules/@sentry/core/build/cjs', + './build/aws/dist-serverless/nodejs/node_modules/@sentry/core/build/esm', ]; // Tolerant of whitespace/quote variations: esbuild emits the marker and `return` on @@ -234,19 +234,28 @@ function replaceSDKSource(): void { const pattern = /\/\*! __SENTRY_SDK_SOURCE__ \*\/\s*return ["']npm["'];/; const replacement = `/*! __SENTRY_SDK_SOURCE__ */ return 'aws-lambda-layer';`; - for (const envFile of envFiles) { - let content: string; + for (const buildDir of buildDirs) { + // The CJS build is flat, so the file that holds `getSDKSource` has no fixed name. + let jsFiles: string[]; try { - content = fs.readFileSync(envFile, 'utf-8'); + jsFiles = fs + .readdirSync(buildDir, { recursive: true, encoding: 'utf-8' }) + .filter(file => file.endsWith('.js')) + .map(file => path.join(buildDir, file)); } catch { - throw new Error(`Could not read ${envFile} while updating the SDK source for the Lambda layer.`); + throw new Error(`Could not read ${buildDir} while updating the SDK source for the Lambda layer.`); } - if (!pattern.test(content)) { + const matches = jsFiles + .map(file => ({ file, content: fs.readFileSync(file, 'utf-8') })) + .filter(({ content }) => pattern.test(content)); + + if (matches.length !== 1) { throw new Error( - `Could not find the __SENTRY_SDK_SOURCE__ marker in ${envFile}. The Lambda layer would silently report its SDK source as 'npm'. Has the marker or the transpile output changed?`, + `Expected the __SENTRY_SDK_SOURCE__ marker in exactly one file in ${buildDir}, found ${matches.length}. The Lambda layer would silently report its SDK source as 'npm'. Has the marker or the transpile output changed?`, ); } + const { file: envFile, content } = matches[0] as { file: string; content: string }; // pnpm hard-links the files of `file:` dependencies to the monorepo packages. Removing the file first makes // sure that the write does not also change `packages/core/build`. diff --git a/packages/cloudflare/test/instrumentations/instrumentDurableObjectNamespace.test.ts b/packages/cloudflare/test/instrumentations/instrumentDurableObjectNamespace.test.ts index a92d2a582d10..09baa95d65e6 100644 --- a/packages/cloudflare/test/instrumentations/instrumentDurableObjectNamespace.test.ts +++ b/packages/cloudflare/test/instrumentations/instrumentDurableObjectNamespace.test.ts @@ -13,9 +13,6 @@ const { getTraceDataMock } = vi.hoisted(() => ({ vi.mock('../../../core/build/esm/utils/traceData.js', () => ({ getTraceData: getTraceDataMock, })); -vi.mock('../../../core/build/cjs/utils/traceData.js', () => ({ - getTraceData: getTraceDataMock, -})); describe('instrumentDurableObjectNamespace', () => { beforeEach(() => { diff --git a/packages/cloudflare/test/utils/instrumentFetcher.test.ts b/packages/cloudflare/test/utils/instrumentFetcher.test.ts index 6edb66bc8e2c..8db5674faaad 100644 --- a/packages/cloudflare/test/utils/instrumentFetcher.test.ts +++ b/packages/cloudflare/test/utils/instrumentFetcher.test.ts @@ -13,9 +13,6 @@ const { getTraceDataMock } = vi.hoisted(() => ({ vi.mock('../../../core/build/esm/utils/traceData.js', () => ({ getTraceData: getTraceDataMock, })); -vi.mock('../../../core/build/cjs/utils/traceData.js', () => ({ - getTraceData: getTraceDataMock, -})); /** Vitest's `Request` is not typed identically to Workers `RequestInfo`. */ function workerRequest(r: Request): RequestInfo { diff --git a/packages/core/rollup.npm.config.mjs b/packages/core/rollup.npm.config.mjs index 1b079d3deb74..8695383ef3ad 100644 --- a/packages/core/rollup.npm.config.mjs +++ b/packages/core/rollup.npm.config.mjs @@ -4,7 +4,7 @@ import { readFileSync } from 'fs'; import { dirname, join } from 'path'; import { replacePlugin } from 'rolldown/plugins'; import { fileURLToPath } from 'url'; -import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; +import { makeBaseNPMConfig, makeCjsVariantsFlat, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf-8')); @@ -35,9 +35,11 @@ const settings = { }, }; -export default makeNPMConfigVariants( - makeBaseNPMConfig({ - ...settings, - entrypoints: ['src/index.ts', 'src/server.ts', 'src/browser.ts'], - }), +export default makeCjsVariantsFlat( + makeNPMConfigVariants( + makeBaseNPMConfig({ + ...settings, + entrypoints: ['src/index.ts', 'src/server.ts', 'src/browser.ts'], + }), + ), ); diff --git a/packages/node/rollup.npm.config.mjs b/packages/node/rollup.npm.config.mjs index b1262c0c1f50..e2a5ab1290fc 100644 --- a/packages/node/rollup.npm.config.mjs +++ b/packages/node/rollup.npm.config.mjs @@ -1,4 +1,9 @@ -import { makeBaseNPMConfig, makeNPMConfigVariants, makeOrchestrionLoader } from '@sentry-internal/rollup-utils'; +import { + makeBaseNPMConfig, + makeCjsVariantsFlat, + makeNPMConfigVariants, + makeOrchestrionLoader, +} from '@sentry-internal/rollup-utils'; import { createWorkerCodeBuilder } from './rollup.anr-worker.config.mjs'; const [anrWorkerConfig, getAnrBase64Code] = createWorkerCodeBuilder( @@ -35,34 +40,36 @@ export default [ // The workers need to be built first since their output is copied into the main bundle. anrWorkerConfig, localVariablesWorkerConfig, - ...makeNPMConfigVariants( - makeBaseNPMConfig({ - entrypoints: [ - 'src/index.ts', - // Combined Sentry bundler plugins + orchestrion code transform, exposed - // via the `@sentry/node/{vite,rollup,webpack,esbuild}` subpath exports. - 'src/bundler-plugin/vite.ts', - 'src/bundler-plugin/rollup.ts', - 'src/bundler-plugin/webpack.ts', - 'src/bundler-plugin/esbuild.ts', - ], - packageSpecificConfig: { - external: [/^@sentry\/opentelemetry/], - output: { - // set exports to 'named' or 'auto' so that rollup doesn't warn - exports: 'named', - preserveModules: true, + ...makeCjsVariantsFlat( + makeNPMConfigVariants( + makeBaseNPMConfig({ + entrypoints: { + index: 'src/index.ts', + // Combined Sentry bundler plugins + orchestrion code transform, exposed + // via the `@sentry/node/{vite,rollup,webpack,esbuild}` subpath exports. + 'bundler-plugin/vite': 'src/bundler-plugin/vite.ts', + 'bundler-plugin/rollup': 'src/bundler-plugin/rollup.ts', + 'bundler-plugin/webpack': 'src/bundler-plugin/webpack.ts', + 'bundler-plugin/esbuild': 'src/bundler-plugin/esbuild.ts', }, - plugins: [ - makeLazyReplacePlugin( - { - AnrWorkerScript: getAnrBase64Code, - LocalVariablesWorkerScript: getLocalVariablesBase64Code, - }, - { delimiters: ['###', '###'] }, - ), - ], - }, - }), + packageSpecificConfig: { + external: [/^@sentry\/opentelemetry/], + output: { + // set exports to 'named' or 'auto' so that rollup doesn't warn + exports: 'named', + preserveModules: true, + }, + plugins: [ + makeLazyReplacePlugin( + { + AnrWorkerScript: getAnrBase64Code, + LocalVariablesWorkerScript: getLocalVariablesBase64Code, + }, + { delimiters: ['###', '###'] }, + ), + ], + }, + }), + ), ), ]; diff --git a/packages/server-runtime-injection/rollup.npm.config.mjs b/packages/server-runtime-injection/rollup.npm.config.mjs index c30a7692fa5c..f71e5bdc75fd 100644 --- a/packages/server-runtime-injection/rollup.npm.config.mjs +++ b/packages/server-runtime-injection/rollup.npm.config.mjs @@ -2,7 +2,7 @@ import { builtinModules } from 'node:module'; import * as path from 'node:path'; import license from 'rollup-plugin-license'; import { defineConfig } from 'rolldown'; -import { makeBaseNPMConfig, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; +import { makeBaseNPMConfig, makeCjsVariantsFlat, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; // The orchestrion runtime dependency chain (`@apm-js-collab/tracing-hooks` → // `@apm-js-collab/code-transformer` → meriyah/esquery/astring/…) is bundled into this package's @@ -106,30 +106,32 @@ const orchestrionRuntimeHooks = [ export default [ ...orchestrionRuntimeHooks, - ...makeNPMConfigVariants( - makeBaseNPMConfig({ - // `register.ts` backs `./register` (the Node SDK `require`s it synchronously from - // `Sentry.init()`); `hook.mjs` is the async `Module.register()` target, loaded on Node's - // loader thread. Each build registers its own copy, which shares that build's vendored chunks. - entrypoints: ['src/register.ts', 'src/hook.mjs'], - packageSpecificConfig: { - plugins: [ - debugShim, - guardTracingDump, - plugins.makeEsqueryCjsAliasPlugin(), - thirdPartyLicensePlugin, - plugins.makeBuiltinRequireShimPlugin(), - plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), - ], - output: { - exports: 'named', - preserveModules: true, - entryFileNames: sanitizedFileNames, - // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which Deno - // rejects and vite-node (Node 26) misresolves as a relative path. Emit them `node:`-prefixed. - paths: Object.fromEntries(builtinModules.map(m => [m, `node:${m}`])), + ...makeCjsVariantsFlat( + makeNPMConfigVariants( + makeBaseNPMConfig({ + // `register.ts` backs `./register` (the Node SDK `require`s it synchronously from + // `Sentry.init()`); `hook.mjs` is the async `Module.register()` target, loaded on Node's + // loader thread. Each build registers its own copy, which shares that build's vendored chunks. + entrypoints: ['src/register.ts', 'src/hook.mjs'], + packageSpecificConfig: { + plugins: [ + debugShim, + guardTracingDump, + plugins.makeEsqueryCjsAliasPlugin(), + thirdPartyLicensePlugin, + plugins.makeBuiltinRequireShimPlugin(), + plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), + ], + output: { + exports: 'named', + preserveModules: true, + entryFileNames: sanitizedFileNames, + // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which Deno + // rejects and vite-node (Node 26) misresolves as a relative path. Emit them `node:`-prefixed. + paths: Object.fromEntries(builtinModules.map(m => [m, `node:${m}`])), + }, }, - }, - }), + }), + ), ), ]; diff --git a/packages/server-runtime-injection/test/nftTrace.test.ts b/packages/server-runtime-injection/test/nftTrace.test.ts index 659dfdb91570..e32959ac1186 100644 --- a/packages/server-runtime-injection/test/nftTrace.test.ts +++ b/packages/server-runtime-injection/test/nftTrace.test.ts @@ -25,7 +25,7 @@ describe('the cjs build', () => { const traced = await traceFrom(`${buildDir}/cjs/register.js`); expect(traced).toContain(`${buildDir}/cjs/hook.js`); - expect(traced).toContain(`${buildDir}/cjs/vendored/@apm-js-collab/tracing-hooks/hook.js`); + expect(traced).toContain(`${buildDir}/cjs/chunks/hook.js`); }); }); diff --git a/packages/server-utils/rollup.npm.config.mjs b/packages/server-utils/rollup.npm.config.mjs index cd81297a9da3..a77ea453a35f 100644 --- a/packages/server-utils/rollup.npm.config.mjs +++ b/packages/server-utils/rollup.npm.config.mjs @@ -1,6 +1,6 @@ import { builtinModules } from 'node:module'; import license from 'rollup-plugin-license'; -import { makeBaseNPMConfig, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; +import { makeBaseNPMConfig, makeCjsVariantsFlat, makeNPMConfigVariants, plugins } from '@sentry-internal/rollup-utils'; // The orchestrion build-time bundler-plugin chain (`@apm-js-collab/code-transformer-bundler-plugins` // → `@apm-js-collab/code-transformer` → meriyah/esquery/astring/…) is bundled into this package's @@ -55,46 +55,48 @@ const thirdPartyLicensePlugin = license({ const SPLITTABLE_VENDORED = /vendored\/(meriyah|astring|source-map|esquery)\//; export default [ - ...makeNPMConfigVariants( - makeBaseNPMConfig({ - // `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts` - // plugins are loaded via dedicated subpath exports (`.../orchestrion/config`, - // `.../orchestrion/vite`, etc.) — none are reachable from `src/index.ts`, so - // we list them as separate entrypoints to guarantee they end up in build/esm - // and build/cjs. - entrypoints: [ - 'src/index.ts', - 'src/index.no-diagnostic-channels.ts', - 'src/index.request-handler.ts', - 'src/orchestrion/config/index.ts', - 'src/orchestrion/bundler/vite.ts', - 'src/orchestrion/bundler/rollup.ts', - 'src/orchestrion/bundler/webpack.ts', - 'src/orchestrion/bundler/webpack-loader.ts', - 'src/orchestrion/bundler/load-hook.ts', - 'src/orchestrion/bundler/esbuild.ts', - 'src/orchestrion/bundler/bun.ts', - ], - packageSpecificConfig: { - plugins: [ - plugins.makeDebugNodeAliasPlugin(), - plugins.makeEsqueryCjsAliasPlugin(), - thirdPartyLicensePlugin, - plugins.makeBuiltinRequireShimPlugin(), - plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), - ], - output: { - // set exports to 'named' or 'auto' so that rollup doesn't warn - exports: 'named', - // set preserveModules to true because we don't want to bundle everything into one file. - preserveModules: true, - entryFileNames: sanitizedFileNames, - // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which - // Deno rejects outright and vite-node (Node 26) misresolves as a relative path. Emit them - // `node:`-prefixed. - paths: Object.fromEntries(builtinModules.map(m => [m, `node:${m}`])), + ...makeCjsVariantsFlat( + makeNPMConfigVariants( + makeBaseNPMConfig({ + // `src/orchestrion/config/index.ts` and the `src/orchestrion/bundler/*.ts` + // plugins are loaded via dedicated subpath exports (`.../orchestrion/config`, + // `.../orchestrion/vite`, etc.) — none are reachable from `src/index.ts`, so + // we list them as separate entrypoints to guarantee they end up in build/esm + // and build/cjs. + entrypoints: { + index: 'src/index.ts', + 'index.no-diagnostic-channels': 'src/index.no-diagnostic-channels.ts', + 'index.request-handler': 'src/index.request-handler.ts', + 'orchestrion/config/index': 'src/orchestrion/config/index.ts', + 'orchestrion/bundler/vite': 'src/orchestrion/bundler/vite.ts', + 'orchestrion/bundler/rollup': 'src/orchestrion/bundler/rollup.ts', + 'orchestrion/bundler/webpack': 'src/orchestrion/bundler/webpack.ts', + 'orchestrion/bundler/webpack-loader': 'src/orchestrion/bundler/webpack-loader.ts', + 'orchestrion/bundler/load-hook': 'src/orchestrion/bundler/load-hook.ts', + 'orchestrion/bundler/esbuild': 'src/orchestrion/bundler/esbuild.ts', + 'orchestrion/bundler/bun': 'src/orchestrion/bundler/bun.ts', }, - }, - }), + packageSpecificConfig: { + plugins: [ + plugins.makeDebugNodeAliasPlugin(), + plugins.makeEsqueryCjsAliasPlugin(), + thirdPartyLicensePlugin, + plugins.makeBuiltinRequireShimPlugin(), + plugins.makeCjsExportsSplitPlugin(SPLITTABLE_VENDORED), + ], + output: { + // set exports to 'named' or 'auto' so that rollup doesn't warn + exports: 'named', + // set preserveModules to true because we don't want to bundle everything into one file. + preserveModules: true, + entryFileNames: sanitizedFileNames, + // The vendored dependencies import builtins unprefixed (`import … from 'tty'`), which + // Deno rejects outright and vite-node (Node 26) misresolves as a relative path. Emit them + // `node:`-prefixed. + paths: Object.fromEntries(builtinModules.map(m => [m, `node:${m}`])), + }, + }, + }), + ), ), ]; diff --git a/packages/server-utils/src/orchestrion/bundler/webpack.ts b/packages/server-utils/src/orchestrion/bundler/webpack.ts index dec13a661026..71840bfa58b4 100644 --- a/packages/server-utils/src/orchestrion/bundler/webpack.ts +++ b/packages/server-utils/src/orchestrion/bundler/webpack.ts @@ -95,7 +95,7 @@ export function sentryOrchestrionWebpackPlugin(options: PluginOptions = {}): { a const plugin = codeTransformerWebpack({ ...orchestrionTransformOptions(options), - // The upstream plugin's own loader path points into our `vendored/` tree at + // The upstream plugin's own loader path points next to its bundled code, at // a file rollup never emitted; use our bundled loader entrypoint instead // (which also bakes in the module-injected transform for Turbopack). loaderPath: getOrchestrionLoaderPath(), From 86c084b2fa0f77e98017f0a070b362659207b68e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 06:57:21 -0500 Subject: [PATCH 074/136] feat(node): Capture the original job error for failed BullMQ jobs (#26352) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** Follow-up to #21777. Until now BullMQ only gave the telemetry adapter the error message, so we captured a synthetic `Error` with no stack, and every failed job grouped by message alone. Since bullmq 6.7.5 the worker calls `recordException(err)` with the job error right before the `job failed` event (taskforcesh/bullmq#4902, taskforcesh/bullmq#4915). We now keep that error and capture it, so failed jobs get their real type and processor stack trace. Older BullMQ versions fall back to the message-only error as before. Only `Error` instances are kept: BullMQ passes the Redis/lock errors it retries as strings, and those reset the recorded error so they can't be captured as the job failure. **How to review:** `span.ts` is the whole change. The integration test diff is mostly re-indentation: the failed-job scenario now runs against bullmq v5 (no stack) and `^6.7.5` (stack with frames from the scenario file). via **Jan Peer Stöcklmair**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CA6TD3QRK%3A1794566080.532069) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CA6TD3QRK%3A1794566080.532069/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Jan Peer Stöcklmair --- .../suites/tracing/bullmq/test.ts | 199 ++++++++++-------- .../src/integrations/tracing/bullmq/span.ts | 26 ++- .../test/integrations/tracing/bullmq.test.ts | 26 +++ 3 files changed, 155 insertions(+), 96 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/tracing/bullmq/test.ts b/dev-packages/node-integration-tests/suites/tracing/bullmq/test.ts index 49871dcc9786..bf2e343e39d7 100644 --- a/dev-packages/node-integration-tests/suites/tracing/bullmq/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/bullmq/test.ts @@ -1,6 +1,6 @@ import type { Event, SerializedMetric } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; -import { afterAll, expect } from 'vitest'; +import { afterAll, describe, expect } from 'vitest'; import { EXPECTED_SDK_NAME } from '../../../utils'; import { cleanupChildProcesses, createEsmAndCjsTests, describeWithDockerCompose } from '../../../utils/runner'; @@ -210,96 +210,121 @@ describeWithDockerCompose('bullmq', { workingDirectory: [__dirname] }, () => { }); }); - createEsmAndCjsTests(__dirname, 'scenario-failed-job.mjs', 'instrument.mjs', (createRunner, test) => { - test( - 'captures an error for a failed job and sets the error status on its process span', - { timeout: 90_000 }, - async () => { - let errorEvent: Event | undefined; - const runner = createRunner().ignore('trace_metric'); - const consumerSpansPromise = runner.collectStreamedSpansUntilSegment('process test-failed-queue'); + // BullMQ passes the job error to the telemetry adapter since 6.7.5, so only then does the error have a stack. + describe.each([ + ['bullmq v5', {}, undefined], + [ + 'bullmq v6', + { bullmq: '^6.7.5' }, + { + frames: expect.arrayContaining([ + expect.objectContaining({ filename: expect.stringContaining('scenario-failed-job') }), + ]), + }, + ], + ])('%s', (_version, additionalDependencies, expectedStacktrace) => { + createEsmAndCjsTests( + __dirname, + 'scenario-failed-job.mjs', + 'instrument.mjs', + (createRunner, test) => { + test( + 'captures an error for a failed job and sets the error status on its process span', + { timeout: 90_000 }, + async () => { + let errorEvent: Event | undefined; + const runner = createRunner().ignore('trace_metric'); + const consumerSpansPromise = runner.collectStreamedSpansUntilSegment('process test-failed-queue'); - await runner - .expect({ - event: event => { - errorEvent = event; - }, - }) - .start() - .completed(); + await runner + .expect({ + event: event => { + errorEvent = event; + }, + }) + .start() + .completed(); - const consumerSpans = await consumerSpansPromise; - const processSpan = consumerSpans.find(span => span.is_segment && span.name === 'process test-failed-queue')!; + const consumerSpans = await consumerSpansPromise; + const processSpan = consumerSpans.find( + span => span.is_segment && span.name === 'process test-failed-queue', + )!; - expect( - consumerSpans - .filter(span => span.attributes['messaging.system']?.value === 'bullmq') - .sort((a, b) => a.start_timestamp - b.start_timestamp) - .map(span => ({ - name: span.name, - status: span.status, - attributes: span.attributes, - })), - ).toEqual([ - { - name: 'process test-failed-queue', - status: 'error', - attributes: { - 'sentry.op': { type: 'string', value: 'queue.process' }, - 'sentry.origin': { type: 'string', value: 'auto.queue.bullmq.consumer' }, - 'messaging.system': { type: 'string', value: 'bullmq' }, - 'messaging.destination.name': { type: 'string', value: 'test-failed-queue' }, - 'messaging.operation.name': { type: 'string', value: 'process' }, - 'messaging.message.id': { type: 'string', value: expect.any(String) }, - 'messaging.message.retry.count': { type: 'integer', value: 0 }, - 'messaging.client.id': { type: 'string', value: expect.any(String) }, - 'messaging.bullmq.job.name': { type: 'string', value: 'failing-job' }, - 'messaging.bullmq.job.processed_timestamp': { type: 'integer', value: expect.any(Number) }, - 'messaging.bullmq.job.attempt_finished_timestamp': { type: 'integer', value: expect.any(Number) }, - 'sentry.environment': { type: 'string', value: 'production' }, - 'sentry.is_localhost': { type: 'boolean', value: false }, - 'sentry.release': { type: 'string', value: '1.0' }, - 'sentry.sdk.name': { type: 'string', value: EXPECTED_SDK_NAME }, - 'sentry.sdk.version': { type: 'string', value: SDK_VERSION }, - 'sentry.segment.id': { type: 'string', value: processSpan.span_id }, - 'sentry.segment.name': { type: 'string', value: 'process test-failed-queue' }, - 'sentry.trace_lifecycle': { type: 'string', value: 'stream' }, - 'sentry.sample_rate': { type: 'integer', value: 1 }, - 'sentry.sdk.integrations': { type: 'array', value: expect.any(Array) }, - 'sentry.segment.name.source': { type: 'string', value: 'custom' }, - 'sentry.status.message': { type: 'string', value: 'internal_error' }, - }, - }, - { - name: 'fail test-failed-queue', - status: 'ok', - attributes: { - 'sentry.op': { type: 'string', value: 'queue' }, - 'sentry.origin': { type: 'string', value: 'auto.queue.bullmq' }, - 'messaging.system': { type: 'string', value: 'bullmq' }, - 'messaging.destination.name': { type: 'string', value: 'test-failed-queue' }, - 'messaging.operation.name': { type: 'string', value: 'fail' }, - 'messaging.message.id': { type: 'string', value: expect.any(String) }, - 'messaging.bullmq.job.name': { type: 'string', value: 'failing-job' }, - 'sentry.environment': { type: 'string', value: 'production' }, - 'sentry.is_localhost': { type: 'boolean', value: false }, - 'sentry.release': { type: 'string', value: '1.0' }, - 'sentry.sdk.name': { type: 'string', value: EXPECTED_SDK_NAME }, - 'sentry.sdk.version': { type: 'string', value: SDK_VERSION }, - 'sentry.segment.id': { type: 'string', value: processSpan.span_id }, - 'sentry.segment.name': { type: 'string', value: 'process test-failed-queue' }, - 'sentry.trace_lifecycle': { type: 'string', value: 'stream' }, - }, - }, - ]); - expect(errorEvent?.exception?.values).toHaveLength(1); - expect(errorEvent?.exception?.values?.[0]?.type).toBe('Error'); - expect(errorEvent?.exception?.values?.[0]?.value).toBe('Job failed on purpose'); - expect(errorEvent?.exception?.values?.[0]?.mechanism).toEqual({ type: 'auto.queue.bullmq', handled: false }); - expect(errorEvent?.exception?.values?.[0]?.stacktrace).toBeUndefined(); - expect(errorEvent?.contexts?.trace?.trace_id).toBe(processSpan.trace_id); - expect(errorEvent?.contexts?.trace?.span_id).toBe(processSpan.span_id); + expect( + consumerSpans + .filter(span => span.attributes['messaging.system']?.value === 'bullmq') + .sort((a, b) => a.start_timestamp - b.start_timestamp) + .map(span => ({ + name: span.name, + status: span.status, + attributes: span.attributes, + })), + ).toEqual([ + { + name: 'process test-failed-queue', + status: 'error', + attributes: { + 'sentry.op': { type: 'string', value: 'queue.process' }, + 'sentry.origin': { type: 'string', value: 'auto.queue.bullmq.consumer' }, + 'messaging.system': { type: 'string', value: 'bullmq' }, + 'messaging.destination.name': { type: 'string', value: 'test-failed-queue' }, + 'messaging.operation.name': { type: 'string', value: 'process' }, + 'messaging.message.id': { type: 'string', value: expect.any(String) }, + 'messaging.message.retry.count': { type: 'integer', value: 0 }, + 'messaging.client.id': { type: 'string', value: expect.any(String) }, + 'messaging.bullmq.job.name': { type: 'string', value: 'failing-job' }, + 'messaging.bullmq.job.processed_timestamp': { type: 'integer', value: expect.any(Number) }, + 'messaging.bullmq.job.attempt_finished_timestamp': { type: 'integer', value: expect.any(Number) }, + 'sentry.environment': { type: 'string', value: 'production' }, + 'sentry.is_localhost': { type: 'boolean', value: false }, + 'sentry.release': { type: 'string', value: '1.0' }, + 'sentry.sdk.name': { type: 'string', value: EXPECTED_SDK_NAME }, + 'sentry.sdk.version': { type: 'string', value: SDK_VERSION }, + 'sentry.segment.id': { type: 'string', value: processSpan.span_id }, + 'sentry.segment.name': { type: 'string', value: 'process test-failed-queue' }, + 'sentry.trace_lifecycle': { type: 'string', value: 'stream' }, + 'sentry.sample_rate': { type: 'integer', value: 1 }, + 'sentry.sdk.integrations': { type: 'array', value: expect.any(Array) }, + 'sentry.segment.name.source': { type: 'string', value: 'custom' }, + 'sentry.status.message': { type: 'string', value: 'internal_error' }, + }, + }, + { + name: 'fail test-failed-queue', + status: 'ok', + attributes: { + 'sentry.op': { type: 'string', value: 'queue' }, + 'sentry.origin': { type: 'string', value: 'auto.queue.bullmq' }, + 'messaging.system': { type: 'string', value: 'bullmq' }, + 'messaging.destination.name': { type: 'string', value: 'test-failed-queue' }, + 'messaging.operation.name': { type: 'string', value: 'fail' }, + 'messaging.message.id': { type: 'string', value: expect.any(String) }, + 'messaging.bullmq.job.name': { type: 'string', value: 'failing-job' }, + 'sentry.environment': { type: 'string', value: 'production' }, + 'sentry.is_localhost': { type: 'boolean', value: false }, + 'sentry.release': { type: 'string', value: '1.0' }, + 'sentry.sdk.name': { type: 'string', value: EXPECTED_SDK_NAME }, + 'sentry.sdk.version': { type: 'string', value: SDK_VERSION }, + 'sentry.segment.id': { type: 'string', value: processSpan.span_id }, + 'sentry.segment.name': { type: 'string', value: 'process test-failed-queue' }, + 'sentry.trace_lifecycle': { type: 'string', value: 'stream' }, + }, + }, + ]); + expect(errorEvent?.exception?.values).toHaveLength(1); + expect(errorEvent?.exception?.values?.[0]?.type).toBe('Error'); + expect(errorEvent?.exception?.values?.[0]?.value).toBe('Job failed on purpose'); + expect(errorEvent?.exception?.values?.[0]?.mechanism).toEqual({ + type: 'auto.queue.bullmq', + handled: false, + }); + expect(errorEvent?.exception?.values?.[0]?.stacktrace).toEqual(expectedStacktrace); + expect(errorEvent?.contexts?.trace?.trace_id).toBe(processSpan.trace_id); + expect(errorEvent?.contexts?.trace?.span_id).toBe(processSpan.span_id); + }, + ); }, + { additionalDependencies }, ); }); diff --git a/packages/node/src/integrations/tracing/bullmq/span.ts b/packages/node/src/integrations/tracing/bullmq/span.ts index 10ec13bee4c2..6de52055b99e 100644 --- a/packages/node/src/integrations/tracing/bullmq/span.ts +++ b/packages/node/src/integrations/tracing/bullmq/span.ts @@ -142,6 +142,7 @@ export function toSentryAttributes(attributes: Record): export class SentryBullMQSpan implements TelemetrySpan { private _span: Span; private _scope: Scope; + private _recordedError: Error | undefined; public constructor(span: Span, scope: Scope) { this._span = span; @@ -164,11 +165,16 @@ export class SentryBullMQSpan implements TelemetrySpan { if (name === 'job failed') { this._span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - const reason = attributes?.['bullmq.job.failed.reason']; - const error = new Error(String(reason || 'Unknown error')); - // BullMQ passes only the error message (https://github.com/taskforcesh/bullmq/issues/4902), so this stack has only - // BullMQ and SDK frames, the same for every job. Without it, Sentry groups the errors by their message. - error.stack = undefined; + // Since 6.7.5, BullMQ passes the job error to `recordException` right before this event + // (https://github.com/taskforcesh/bullmq/pull/4915). Older versions pass only the error message. + let error = this._recordedError; + this._recordedError = undefined; + if (!error) { + error = new Error(String(attributes?.['bullmq.job.failed.reason'] || 'Unknown error')); + // This stack has only BullMQ and SDK frames, the same for every job. Without it, Sentry groups the errors by + // their message. + error.stack = undefined; + } captureException(error, { mechanism: { handled: false, @@ -180,13 +186,15 @@ export class SentryBullMQSpan implements TelemetrySpan { /** * Does not capture to Sentry. BullMQ calls this for Redis, lock and serialization errors that it - * retries itself, often several times for one fault. Job failures are captured in `addEvent`. + * retries itself, often several times for one fault, and for the job error right before the `job failed` event. + * Job failures are captured in `addEvent`. */ public recordException(exception: Error | string | { code?: number; message?: string; name?: string }): void { + // BullMQ passes the retried errors as strings, so only the job error is kept. + this._recordedError = exception instanceof Error ? exception : undefined; const error = - exception instanceof Error - ? exception - : new Error(typeof exception === 'string' ? exception : exception.message || 'Unknown error'); + this._recordedError ?? + new Error(typeof exception === 'string' ? exception : exception.message || 'Unknown error'); this._span.recordException(error); } diff --git a/packages/node/test/integrations/tracing/bullmq.test.ts b/packages/node/test/integrations/tracing/bullmq.test.ts index fc0e62d6ae5b..98cfd0097422 100644 --- a/packages/node/test/integrations/tracing/bullmq.test.ts +++ b/packages/node/test/integrations/tracing/bullmq.test.ts @@ -397,6 +397,32 @@ describe('SentryBullMQSpan', () => { }); }); + it('captures the job error that BullMQ recorded before the "job failed" event', () => { + const { span } = createSpan(); + const error = new TypeError('Cannot read properties of undefined'); + + span.recordException(error); + span.addEvent('job failed', { 'bullmq.job.failed.reason': error.message }); + + expect(SentryCore.captureException).toHaveBeenCalledTimes(1); + expect(SentryCore.captureException).toHaveBeenCalledWith( + expect.objectContaining({ name: 'TypeError', stack: error.stack }), + { mechanism: { handled: false, type: 'auto.queue.bullmq' } }, + ); + }); + + it('captures an error without a stack from the reason when BullMQ recorded only a string', () => { + const { span } = createSpan(); + + (span as any).recordException('Connection timed out'); + span.addEvent('job failed', { 'bullmq.job.failed.reason': 'Connection refused' }); + + expect(SentryCore.captureException).toHaveBeenCalledWith( + expect.objectContaining({ message: 'Connection refused', stack: undefined }), + { mechanism: { handled: false, type: 'auto.queue.bullmq' } }, + ); + }); + it('sets the error status on the span when the event name is "job failed"', () => { const { span, otelSpan } = createSpan(); From ddbfdacff590056623d1da096f9755b6e0611e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Fri, 13 Nov 2026 12:59:52 +0100 Subject: [PATCH 075/136] test(nextjs): Run the source map upload e2e test on Bun (#26344) closes #19179 closes [JS-1644](https://linear.app/getsentry/issue/JS-1644/is-it-possible-to-use-sentry-in-nextjs-using-bun-runtime) ## Description This adds Bun variants of the `nextjs-sourcemaps` e2e test, for Turbopack and webpack. They build with `bun --bun run build`, so Bun runs `next build` and the source map upload. The assert script also checks the runtime in the `User-Agent` of the upload requests, so a variant fails when another runtime does the upload. Co-authored-by: Claude Opus 5.5 --- .../nextjs-sourcemaps/assert-build.ts | 7 +++++++ .../nextjs-sourcemaps/package.json | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts index 5a89846b0a92..1f02a4bc61a2 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/assert-build.ts @@ -9,6 +9,7 @@ import { getAssembleRequests, findSourceMapFiles, findSourceMappingUrlComments, + getRuntime, } from '@sentry-internal/test-utils'; const requests = loadMockServerResults(); @@ -31,6 +32,12 @@ assert.ok( 'Expected at least one chunk upload with a non-empty body', ); +// The `sentry` CLI adds the runtime that runs it to its User-Agent, for example `bun/1.4.2`. +const runtime = getRuntime(); +for (const req of chunkPosts) { + assert.match(req.requestHeaders['user-agent'] ?? '', new RegExp(` ${runtime}/`), `Expected ${runtime} to upload`); +} + // Release endpoint was called assert.ok( requests.some(r => r.url?.includes('/releases/')), diff --git a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json index 5cfb7891c838..6eb21bda4d45 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-sourcemaps/package.json @@ -9,6 +9,8 @@ "test:assert": "pnpm ts-node --script-mode assert-build.ts", "test:build:delete": "pnpm install && E2E_DELETE_SOURCEMAPS=1 pnpm build", "test:build:delete-webpack": "pnpm install && E2E_DELETE_SOURCEMAPS=1 E2E_NEXT_WEBPACK=1 pnpm build", + "test:build:delete-bun": "pnpm install && E2E_DELETE_SOURCEMAPS=1 bun --bun run build", + "test:build:delete-webpack-bun": "pnpm install && E2E_DELETE_SOURCEMAPS=1 E2E_NEXT_WEBPACK=1 bun --bun run build", "test:assert:delete": "E2E_DELETE_SOURCEMAPS=1 pnpm test:assert" }, "dependencies": { @@ -37,6 +39,18 @@ "build-command": "pnpm test:build:delete-webpack", "assert-command": "pnpm test:assert:delete", "label": "nextjs-sourcemaps (delete, webpack)" + }, + { + "runtime": "bun", + "build-command": "pnpm test:build:delete-bun", + "assert-command": "pnpm test:assert:delete", + "label": "nextjs-sourcemaps (delete, turbopack, bun)" + }, + { + "runtime": "bun", + "build-command": "pnpm test:build:delete-webpack-bun", + "assert-command": "pnpm test:assert:delete", + "label": "nextjs-sourcemaps (delete, webpack, bun)" } ] } From 88cc64882596593bc7c18d9cde37fabd3ce3887e Mon Sep 17 00:00:00 2001 From: Francesco Gringl-Novy Date: Fri, 13 Nov 2026 13:16:50 +0100 Subject: [PATCH 076/136] chore(bundler-plugins): Type-check tests via lint:types (#26345) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** `check:types` in `bundler-plugins` wasn't run anywhere in CI, and the only type step that was (`lint:types`) covered `src` only. So the tests had picked up three type errors that nobody noticed. This extends `lint:types` to `test` (oxlint's `--type-check` uses `test/tsconfig.json` and reports the same errors as `tsc`), removes the now-redundant `check:types` scripts, and fixes the errors. **How to review:** In `component-annotation-oxc.test.ts`, the helper now parses with `@babel/core`'s `parseSync` instead of `@babel/parser`. `@babel/parser` v8 produces `@babel/types` v8 nodes, which don't type-match the v7 `traverse` they're passed to. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- packages/bundler-plugins/package.json | 6 +----- packages/bundler-plugins/test/core/cli-contract.test.ts | 1 + .../test/core/component-annotation-oxc.test.ts | 8 +++++--- packages/bundler-plugins/test/webpack/injection.test.ts | 6 +++++- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/packages/bundler-plugins/package.json b/packages/bundler-plugins/package.json index 69ac934fb8cf..f5f84428eabd 100644 --- a/packages/bundler-plugins/package.json +++ b/packages/bundler-plugins/package.json @@ -79,18 +79,14 @@ "build:types": "tsc -p tsconfig.types.json", "build:tarball": "pnpm pack", "prebuild": "pnpm run build:version", - "precheck:types": "pnpm run build:version", "prelint:types": "pnpm run build:version", "pretest": "pnpm run build:version", "pretest:unit": "pnpm run build:version", - "check:types": "pnpm run \"/^check:types:(src|test)$/\"", - "check:types:src": "tsc --project ./tsconfig.json --noEmit", - "check:types:test": "tsc --project ./test/tsconfig.json --noEmit", "clean": "node ../../scripts/rm.mjs build dist coverage sentry-bundler-plugins-*.tgz", "clean:all": "pnpm run \"/^(clean|clean:deps)$/\"", "clean:deps": "node ../../scripts/rm.mjs node_modules", "lint": "oxlint . --type-aware", - "lint:types": "oxlint src --type-aware --type-check", + "lint:types": "oxlint src test --type-aware --type-check", "lint:fix": "oxlint . --fix --type-aware", "test": "vitest run", "test:unit": "vitest run" diff --git a/packages/bundler-plugins/test/core/cli-contract.test.ts b/packages/bundler-plugins/test/core/cli-contract.test.ts index dc53bf4427bd..afd7ffaa2383 100644 --- a/packages/bundler-plugins/test/core/cli-contract.test.ts +++ b/packages/bundler-plugins/test/core/cli-contract.test.ts @@ -35,6 +35,7 @@ interface RecordedRequest { method: string; url: string; jsonBody?: unknown; + requestHeaders: Record; } function recordedRequestRecords(): RecordedRequest[] { diff --git a/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts b/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts index c2c57bd07799..bc64b293c4af 100644 --- a/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts +++ b/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts @@ -1,4 +1,4 @@ -import { transformAsync, traverse, types as t } from '@babel/core'; +import { parseSync, transformAsync, traverse, types as t } from '@babel/core'; import { parse } from '@babel/parser'; import MagicString from 'magic-string'; import { describe, expect, it, vi } from 'vitest'; @@ -26,9 +26,11 @@ async function parseAstAsync(code: string, options: { lang: 'jsx' | 'tsx' }): Pr } function collectAnnotations(code: string, id: string): Annotation[] { - const ast = parse(code, { + const ast = parseSync(code, { + babelrc: false, + configFile: false, sourceType: 'module', - plugins: id.endsWith('.tsx') ? ['jsx', 'typescript'] : ['jsx'], + parserOpts: { plugins: id.endsWith('.tsx') ? ['jsx', 'typescript'] : ['jsx'] }, }); const annotations: Annotation[] = []; diff --git a/packages/bundler-plugins/test/webpack/injection.test.ts b/packages/bundler-plugins/test/webpack/injection.test.ts index baf74dc6b7db..b5f2c6783040 100644 --- a/packages/bundler-plugins/test/webpack/injection.test.ts +++ b/packages/bundler-plugins/test/webpack/injection.test.ts @@ -56,7 +56,11 @@ function runWebpackSourceInjection( compilationCallback(compilation); processAssets(assets); - return assets[assetName]; + const result = assets[assetName]; + if (!result) { + throw new Error(`Asset ${assetName} was removed during injection`); + } + return result; } function runWebpackInjection(assetName: string, code: string, chunks?: TestChunk[]): string { From 239efedeed25fb7fb65d5e28bd69a09318f93a4a Mon Sep 17 00:00:00 2001 From: Sigrid <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:01:08 +0100 Subject: [PATCH 077/136] feat(sveltekit): Mark pageloads of prerendered pages (#26307) Stacked on #26301. **Why:** Vercel ISR (`config.isr`) caches the HTML of one request and serves it to every visitor until it expires. That HTML holds the live `sentry-trace` and `baggage` tags of the render, so every visitor continued the same old server trace. Next.js had the same bug, fixed in #25141. Now a page that Vercel renders for its ISR cache gets a `sentry-cache-origin` tag with the render's `sentry-trace` in place of the trace tags. The pageload starts its own trace, gets `page.server_rendering.type: static`, and links the render with a `cache_origin` link, as in Next.js (#25318). To detect an ISR render, `sentryHandle` reads the `x-vercel-isr` request header. Vercel sends it to every invocation of an ISR function, also for background revalidations and for routes that get `config.isr` from a layout. The adapter's own `__pathname` marker is gone before Kit sees the request, and `handle` cannot see the route config (tested both on a Vercel deployment). Like a `use cache` hit, the pageload links only a sampled render. An unsampled render still marks the pageload as `static`. A page with `ssr = false` gets no tags, as in the build. **How to review:** Start with `getCacheOrigin` in `handle.ts`. It returns the render's trace (ISR), `''` (build) or `undefined` (rendered for this request only). Then `withCacheOrigin` in `client/traceMetaTags.ts`. The two browser-tracing variants only wrap their existing span options. **Unsure about:** A client can send `x-vercel-isr` to a normal SSR route, and the function sees it. That only changes the pageload of the request that sends it: it links its own server request instead of continuing it. I think that is acceptable. I did not check draft mode (`bypassToken`), where Vercel does not cache the render. Example with the UI changes from https://github.com/getsentry/sentry/pull/130771 (a visitor that got an already happened ISR render): image https://sentry-4x3dkn58u.sentry.dev/explore/traces/trace/63b1dbe5fe3849f2b13df81530857c03/ Linear: [JSSDK-37](https://linear.app/getsentry/issue/JSSDK-37/sveltekit-page-options) --- CHANGELOG.md | 6 ++ .../sveltekit-2-static/package.json | 1 + .../sveltekit-2-static/tests/sdk.test.ts | 10 ++- .../sveltekit-3/package.json | 1 + .../sveltekit-3/tests/prerender.test.ts | 59 +++++++++++++-- .../src/client/svelte4BrowserTracing.ts | 26 ++++--- .../src/client/svelte5BrowserTracing.ts | 26 ++++--- .../sveltekit/src/client/traceMetaTags.ts | 41 ++++++++-- .../sveltekit/src/common/traceMetaTags.ts | 4 +- .../sveltekit/src/server-common/handle.ts | 39 ++++++++-- .../client/browserTracingIntegration.test.ts | 3 +- .../test/client/svelte5BrowserTracing.test.ts | 3 +- .../test/client/traceMetaTags.test.ts | 56 ++++++++++++++ .../test/server-common/handle.test.ts | 74 +++++++++++++++++++ 14 files changed, 297 insertions(+), 52 deletions(-) create mode 100644 packages/sveltekit/test/client/traceMetaTags.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c18ccce7fe07..193f6a328043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ Work in this release was contributed by @kunal649 and @bardrop. Thank you for yo ### Important Changes +- **feat(sveltekit): Mark pageloads of prerendered and Vercel ISR pages ([#26301](https://github.com/getsentry/sentry-javascript/pull/26301), [#26307](https://github.com/getsentry/sentry-javascript/pull/26307))** + + When SvelteKit serves a page that it rendered earlier, the pageload now has the `page.server_rendering.type: static` attribute. This covers pages prerendered during `vite build` and pages that Vercel caches with ISR (`config.isr`). For an ISR page, the pageload also links to the request that rendered the page, if that request was sampled. + + Before, every visitor of a cached ISR page continued the trace of that one request. Now each pageload starts its own trace. Pages with `ssr = false` get no attribute, because the server rendered none of their content. + - **fix(core): Set `url.scheme` without colon and `url.port` as a number ([#26284](https://github.com/getsentry/sentry-javascript/pull/26284))** HTTP spans that the SDK builds from a `URL` now send `url.scheme` without the trailing colon (`https` instead of `https:`) and `url.port` as a number instead of a string, as the Sentry conventions define them and as Node `http.server` spans already do. This changes `http.server` spans from `@sentry/cloudflare`, `Bun.serve`, Deno and Nitro, and outgoing `node:http` client spans. Update saved queries, alerts and dashboards that filter on `url.scheme:"https:"` or on `url.port` as a string. diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json index c4686c849dd6..4f66f0712160 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json @@ -27,6 +27,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "@sentry/conventions": "0.32.0", "@sveltejs/adapter-node": "^2.0.0", "@sveltejs/kit": "2.70.2", "@sveltejs/vite-plugin-svelte": "^3.0.0", diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts index a8d4a59d790c..431b64457609 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/tests/sdk.test.ts @@ -1,5 +1,7 @@ import { expect, test } from '@playwright/test'; import { waitForTransaction } from '@sentry-internal/test-utils'; +import { PAGE_SERVER_RENDERING_TYPE } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; import { waitForInitialPageload } from './utils'; function sentryMetaTagNames(html: string): string[] { @@ -33,26 +35,26 @@ test.describe('SDK-internal behavior', () => { test('Marks the pageload of a prerendered page as statically rendered, without a link', async ({ page }) => { const pageloadTxnPromise = waitForTransaction('sveltekit-2-static', txnEvent => { - return txnEvent?.transaction === '/prerendered' && txnEvent.contexts?.trace?.op === 'pageload'; + return txnEvent?.transaction === '/prerendered' && txnEvent.contexts?.trace?.op === PAGELOAD; }); await page.goto('/prerendered'); const pageloadTxn = await pageloadTxnPromise; - expect(pageloadTxn.contexts?.trace?.data?.['page.server_rendering.type']).toBe('static'); + expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_TYPE]).toBe('static'); expect(pageloadTxn.contexts?.trace?.links).toBeUndefined(); expect(pageloadTxn.contexts?.trace?.parent_span_id).toBeUndefined(); }); test("Doesn't mark the pageload of a prerendered client-side shell", async ({ page }) => { const pageloadTxnPromise = waitForTransaction('sveltekit-2-static', txnEvent => { - return txnEvent?.transaction === '/prerendered-shell' && txnEvent.contexts?.trace?.op === 'pageload'; + return txnEvent?.transaction === '/prerendered-shell' && txnEvent.contexts?.trace?.op === PAGELOAD; }); await page.goto('/prerendered-shell'); const pageloadTxn = await pageloadTxnPromise; - expect(pageloadTxn.contexts?.trace?.data?.['page.server_rendering.type']).toBeUndefined(); + expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_TYPE]).toBeUndefined(); expect(pageloadTxn.contexts?.trace?.parent_span_id).toBeUndefined(); }); }); diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json index 6d6dd79531a7..2bdb4261a836 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json @@ -24,6 +24,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "@sentry/conventions": "0.32.0", "@sveltejs/adapter-node": "^6.0.0", "@sveltejs/kit": "^3.0.0", "@sveltejs/vite-plugin-svelte": "^7.3.1", diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts b/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts index d030334c2188..504190ed9465 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/tests/prerender.test.ts @@ -1,17 +1,22 @@ import { expect, test } from '@playwright/test'; import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op'; function sentryMetaTagNames(html: string): string[] { return [...html.matchAll(/ match[1] ?? ''); } +const VERCEL_ISR_HEADERS = { 'x-vercel-isr': '1' }; + [ { path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin'] }, { path: '/prerendered-shell', kind: 'a prerendered client-side shell', expected: [] }, { path: '/', kind: 'a server-rendered page', expected: ['sentry-trace', 'baggage'] }, -].forEach(({ path, kind, expected }) => { + { path: '/', headers: VERCEL_ISR_HEADERS, kind: 'a Vercel ISR render', expected: ['sentry-cache-origin'] }, +].forEach(({ path, headers, kind, expected }) => { test(`writes the expected Sentry meta tags into ${kind} (${path})`, async ({ request }) => { - const html = await (await request.get(path)).text(); + const html = await (await request.get(path, { headers })).text(); expect(sentryMetaTagNames(html)).toEqual(expected); }); @@ -19,37 +24,75 @@ function sentryMetaTagNames(html: string): string[] { test('marks the pageload of a prerendered page as statically rendered, without a link', async ({ page }) => { const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { - return span.name === '/prerendered' && getSpanOp(span) === 'pageload' && span.is_segment; + return span.name === '/prerendered' && getSpanOp(span) === PAGELOAD && span.is_segment; }); await page.goto('/prerendered'); const pageloadSpan = await pageloadSpanPromise; - expect(pageloadSpan.attributes?.['page.server_rendering.type']).toEqual({ type: 'string', value: 'static' }); + expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); expect(pageloadSpan.links).toBeUndefined(); expect(pageloadSpan.parent_span_id).toBeUndefined(); }); test("doesn't mark the pageload of a prerendered client-side shell", async ({ page }) => { const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { - return span.name === '/prerendered-shell' && getSpanOp(span) === 'pageload' && span.is_segment; + return span.name === '/prerendered-shell' && getSpanOp(span) === PAGELOAD && span.is_segment; }); await page.goto('/prerendered-shell'); const pageloadSpan = await pageloadSpanPromise; - expect(pageloadSpan.attributes?.['page.server_rendering.type']).toBeUndefined(); + expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toBeUndefined(); expect(pageloadSpan.parent_span_id).toBeUndefined(); }); test("doesn't mark the pageload of a server-rendered page, which continues the server trace", async ({ page }) => { const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { - return span.name === '/' && getSpanOp(span) === 'pageload' && span.is_segment; + return span.name === '/' && getSpanOp(span) === PAGELOAD && span.is_segment; }); await page.goto('/'); const pageloadSpan = await pageloadSpanPromise; - expect(pageloadSpan.attributes?.['page.server_rendering.type']).toBeUndefined(); + expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toBeUndefined(); expect(pageloadSpan.parent_span_id).toMatch(/^[a-f0-9]{16}$/); }); + +test('marks the pageload of a Vercel ISR page as statically rendered and links the render', async ({ page }) => { + // The event proxy replays spans from this time on, so the server span of the render can be awaited + // after its trace id is known from the HTML. Same clock as the proxy (`process.hrtime`). + const [seconds, nanoseconds] = process.hrtime(); + const requestStart = seconds * 1e9 + nanoseconds; + const pageloadSpanPromise = waitForStreamedSpan('sveltekit-3', span => { + return span.name === '/' && getSpanOp(span) === PAGELOAD && span.is_segment; + }); + + // Only on the document: on the SDK's cross-origin envelope requests, the header would need a preflight. + await page.route( + url => url.pathname === '/', + route => route.continue({ headers: { ...route.request().headers(), ...VERCEL_ISR_HEADERS } }), + ); + await page.goto('/'); + const cacheOrigin = await page.locator('meta[name="sentry-cache-origin"]').getAttribute('content'); + const [originTraceId, originSpanId] = cacheOrigin?.split('-') ?? []; + const [originSpan, pageloadSpan] = await Promise.all([ + waitForStreamedSpan('sveltekit-3', span => span.span_id === originSpanId, requestStart), + pageloadSpanPromise, + ]); + + expect(originSpan.trace_id).toBe(originTraceId); + expect(getSpanOp(originSpan)).toBe(HTTP_SERVER); + expect(originSpan.is_segment).toBe(true); + expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' }); + expect(pageloadSpan.parent_span_id).toBeUndefined(); + expect(pageloadSpan.trace_id).not.toBe(originTraceId); + expect(pageloadSpan.links).toEqual([ + { + trace_id: originTraceId, + span_id: originSpanId, + sampled: true, + attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'cache_origin' } }, + }, + ]); +}); diff --git a/packages/sveltekit/src/client/svelte4BrowserTracing.ts b/packages/sveltekit/src/client/svelte4BrowserTracing.ts index 6ecafdc5cb1f..06a1c24b03b2 100644 --- a/packages/sveltekit/src/client/svelte4BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte4BrowserTracing.ts @@ -26,7 +26,7 @@ import type { Navigation, Page } from '@sveltejs/kit'; // eslint-disable-next-line typescript/no-deprecated import { navigating, page } from '$app/stores'; import type { Readable } from 'svelte/store'; -import { getServerRenderingAttributes } from './traceMetaTags'; +import { withCacheOrigin } from './traceMetaTags'; /** * SvelteKit 2 / Svelte 4 browser tracing (`$app/stores`). Selected at build time, so it's only @@ -51,17 +51,19 @@ export function instrumentSvelteKitTracing( function _instrumentPageload(client: Client, pageStore: Readable): void { const initialPath = WINDOW.location?.pathname; - const pageloadSpan = startBrowserTracingPageLoadSpan(client, { - // With span streaming, span names have to be low cardinality. The route id is only available - // asynchronously, which updates the span name then. - name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, - attributes: { - [SENTRY_OP]: PAGELOAD, - [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', - [SENTRY_SEGMENT_NAME_SOURCE]: 'url', - ...getServerRenderingAttributes(), - }, - }); + const pageloadSpan = startBrowserTracingPageLoadSpan( + client, + withCacheOrigin({ + // With span streaming, span names have to be low cardinality. The route id is only available + // asynchronously, which updates the span name then. + name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, + attributes: { + [SENTRY_OP]: PAGELOAD, + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + }, + }), + ); if (!pageloadSpan) { return; } diff --git a/packages/sveltekit/src/client/svelte5BrowserTracing.ts b/packages/sveltekit/src/client/svelte5BrowserTracing.ts index 8930775c56b4..135928af8c7e 100644 --- a/packages/sveltekit/src/client/svelte5BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte5BrowserTracing.ts @@ -24,7 +24,7 @@ import { import { NAVIGATION, PAGELOAD, ROUTER } from '@sentry/conventions/op'; import type { Navigation } from '@sveltejs/kit'; import { getCurrentNavigation, onNavigationChange, onPageRouteChange } from './navigationState.svelte'; -import { getServerRenderingAttributes } from './traceMetaTags'; +import { withCacheOrigin } from './traceMetaTags'; /** * SvelteKit 3 / Svelte 5 browser tracing (`$app/state` runes). Selected at build time, so it's only @@ -47,17 +47,19 @@ export function instrumentSvelteKitTracing( function _instrumentPageLoad(client: Client): void { const initialPath = WINDOW.location?.pathname; - const pageLoadSpan = startBrowserTracingPageLoadSpan(client, { - // With span streaming, span names have to be low cardinality. The route id is only available - // asynchronously, which updates the span name then. - name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, - attributes: { - [SENTRY_OP]: PAGELOAD, - [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', - [SENTRY_SEGMENT_NAME_SOURCE]: 'url', - ...getServerRenderingAttributes(), - }, - }); + const pageLoadSpan = startBrowserTracingPageLoadSpan( + client, + withCacheOrigin({ + // With span streaming, span names have to be low cardinality. The route id is only available + // asynchronously, which updates the span name then. + name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, + attributes: { + [SENTRY_OP]: PAGELOAD, + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + }, + }), + ); if (!pageLoadSpan) { return; diff --git a/packages/sveltekit/src/client/traceMetaTags.ts b/packages/sveltekit/src/client/traceMetaTags.ts index b8e09933acce..c21dbdc73077 100644 --- a/packages/sveltekit/src/client/traceMetaTags.ts +++ b/packages/sveltekit/src/client/traceMetaTags.ts @@ -1,10 +1,39 @@ -import { PAGE_SERVER_RENDERING_TYPE } from '@sentry/conventions/attributes'; -import type { SpanAttributes } from '@sentry/core'; +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import type { SpanLink, StartSpanOptions } from '@sentry/core'; +import { extractTraceparentData } from '@sentry/core'; import { WINDOW } from '@sentry/svelte'; import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; -/** Set at span start, so `tracesSampler` sees it. */ -export function getServerRenderingAttributes(): SpanAttributes { - const isPrerendered = !!WINDOW.document?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`); - return isPrerendered ? { [PAGE_SERVER_RENDERING_TYPE]: 'static' } : {}; +// `@opentelemetry/api` `TraceFlags.SAMPLED`, inlined because core does not export its copy. +const TRACE_FLAG_SAMPLED = 0x1; + +/** + * Marks the pageload of a reused page as `static` at span start, so `tracesSampler` sees it. Links the + * render only if it was sampled, like every `cache_origin` link. + */ +export function withCacheOrigin(spanOptions: StartSpanOptions): StartSpanOptions { + const cacheOrigin = WINDOW.document + ?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`) + ?.getAttribute('content'); + if (cacheOrigin == null) { + return spanOptions; + } + + const link = getSampledCacheOriginLink(cacheOrigin); + return { + ...spanOptions, + attributes: { ...spanOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + ...(link && { links: [link] }), + }; +} + +function getSampledCacheOriginLink(sentryTrace: string): SpanLink | undefined { + const traceparent = extractTraceparentData(sentryTrace); + if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) { + return undefined; + } + return { + context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: TRACE_FLAG_SAMPLED }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }; } diff --git a/packages/sveltekit/src/common/traceMetaTags.ts b/packages/sveltekit/src/common/traceMetaTags.ts index d6618a156999..16292b31274c 100644 --- a/packages/sveltekit/src/common/traceMetaTags.ts +++ b/packages/sveltekit/src/common/traceMetaTags.ts @@ -1,5 +1,5 @@ /** - * Replaces the trace meta tags of pages prerendered during the build. Empty, unlike in Next.js: spans - * from the build are not reliably sent, so there is no origin to link. + * Replaces `sentry-trace` and `baggage` in a page that many visitors get. Holds the `sentry-trace` of the + * render to link, or is empty. The client links it but never continues it. */ export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/sveltekit/src/server-common/handle.ts b/packages/sveltekit/src/server-common/handle.ts index bb996f16f7ca..e70cf289c09f 100644 --- a/packages/sveltekit/src/server-common/handle.ts +++ b/packages/sveltekit/src/server-common/handle.ts @@ -2,10 +2,13 @@ import type { Span } from '@sentry/core'; import { continueTrace, debug, + getActiveSpan, getClient, getCurrentScope, getDefaultIsolationScope, getIsolationScope, + getRootSpan, + getTraceData, getTraceMetaTags, hasSpanStreamingEnabled, httpHeadersToSpanAttributes, @@ -82,9 +85,10 @@ export const FETCH_PROXY_SCRIPT = ` */ export function addSentryCodeToPage(options: { injectFetchProxyScript: boolean; + isVercelIsrRender?: boolean; }): NonNullable { return ({ html }) => { - const metaTags = getPageMetaTags(html); + const metaTags = getPageMetaTags(html, !!options.isVercelIsrRender); const headWithMetaTags = metaTags ? `\n${metaTags}` : ''; const headWithFetchScript = options.injectFetchProxyScript ? `\n` : ''; @@ -95,15 +99,35 @@ export function addSentryCodeToPage(options: { }; } -/** Trace meta tags written during the build would put one trace into the HTML of every visitor. */ -function getPageMetaTags(html: string): string { - if (!isSvelteKitBuilding()) { +/** + * Returns the meta tags for the pageload. A page rendered for this request gets the trace meta tags. A page + * that many visitors get, such as a prerendered or ISR page, gets `sentry-cache-origin` instead, so each + * pageload starts its own trace. + */ +function getPageMetaTags(html: string, isVercelIsrRender: boolean): string { + if (!isVercelIsrRender && !isSvelteKitBuilding()) { return getTraceMetaTags(); } - return isServerRenderedPage(html) ? `` : ''; + + // An `ssr = false` page has no server-rendered content, so `page.server_rendering.type` does not apply. + // Many visitors get the same HTML, so it gets no trace tags either. + if (!isServerRenderedPage(html)) { + return ''; + } + + // The build does not reliably send spans, so a prerendered page has no trace to link. + // The empty tag still marks the pageload as static. + const originTrace = isVercelIsrRender ? getRootSpanTrace() : undefined; + return ``; +} + +/** With Kit tracing, the active span while the page renders is Kit's `sveltekit.resolve`, not the root span. */ +function getRootSpanTrace(): string | undefined { + const activeSpan = getActiveSpan(); + return getTraceData({ span: activeSpan && getRootSpan(activeSpan) })['sentry-trace']; } -/** Kit writes `node_ids` only for server-rendered pages, not for shells (`ssr = false`, SPA fallback). */ +/** Kit writes `node_ids` only if the server rendered content, not for `ssr = false` or the SPA fallback. */ function isServerRenderedPage(html: string): boolean { return html.includes('node_ids:'); } @@ -240,6 +264,9 @@ async function instrumentHandle( const res = await resolve(event, { transformPageChunk: addSentryCodeToPage({ injectFetchProxyScript: options.injectFetchProxyScript ?? true, + // Vercel sets this on every ISR invocation, also on revalidation. + // A client that sends it changes only its own response. + isVercelIsrRender: event.request.headers.has('x-vercel-isr'), }), }); diff --git a/packages/sveltekit/test/client/browserTracingIntegration.test.ts b/packages/sveltekit/test/client/browserTracingIntegration.test.ts index 89210d628788..a2b17a736c70 100644 --- a/packages/sveltekit/test/client/browserTracingIntegration.test.ts +++ b/packages/sveltekit/test/client/browserTracingIntegration.test.ts @@ -17,6 +17,7 @@ import { URL_TEMPLATE, SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; // we have to overwrite the global mock from `vitest.setup.ts` here to reset the // `navigating` store for each test. @@ -193,7 +194,7 @@ describe('browserTracingIntegration', () => { expect(startBrowserTracingPageLoadSpanSpy).toHaveBeenCalledWith(fakeClient, { name: '/', attributes: { - [SENTRY_OP]: 'pageload', + [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', [SENTRY_SEGMENT_NAME_SOURCE]: 'url', [PAGE_SERVER_RENDERING_TYPE]: 'static', diff --git a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts index a2975a0bafa5..176f7bf5c50a 100644 --- a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts +++ b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts @@ -12,6 +12,7 @@ import { URL_TEMPLATE, SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { instrumentSvelteKitTracing } from '../../src/client/svelte5BrowserTracing'; import { CACHE_ORIGIN_META_TAG_NAME } from '../../src/common/traceMetaTags'; @@ -116,7 +117,7 @@ describe('svelte5 browser tracing', () => { expect(startPageLoadSpanSpy).toHaveBeenCalledWith(client, { name: '/', attributes: { - [SENTRY_OP]: 'pageload', + [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', [SENTRY_SEGMENT_NAME_SOURCE]: 'url', [PAGE_SERVER_RENDERING_TYPE]: 'static', diff --git a/packages/sveltekit/test/client/traceMetaTags.test.ts b/packages/sveltekit/test/client/traceMetaTags.test.ts new file mode 100644 index 000000000000..b491fff60f62 --- /dev/null +++ b/packages/sveltekit/test/client/traceMetaTags.test.ts @@ -0,0 +1,56 @@ +/** + * @vitest-environment jsdom + */ + +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { withCacheOrigin } from '../../src/client/traceMetaTags'; + +const spanOptions = { name: '/pricing', attributes: { [SENTRY_OP]: PAGELOAD } }; + +function addCacheOriginTag(content: string): void { + const tag = document.createElement('meta'); + tag.name = 'sentry-cache-origin'; + tag.content = content; + document.head.appendChild(tag); +} + +describe('withCacheOrigin', () => { + beforeEach(() => { + document.head.innerHTML = ''; + }); + + it('returns the span options unchanged for a page without a cache origin tag', () => { + expect(withCacheOrigin(spanOptions)).toBe(spanOptions); + }); + + it('marks the pageload as static and links a sampled render', () => { + addCacheOriginTag('0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3-1'); + + expect(withCacheOrigin(spanOptions)).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + links: [ + { + context: { traceId: '0b37aaf4f0d74c0e80875099e7d7ca68', spanId: 'bc3a52360214dcf3', traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }, + ], + }); + }); + + it.each([ + { kind: 'an empty tag (prerendered during the build)', content: '' }, + { kind: 'an unsampled render', content: '0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3-0' }, + { kind: 'a render without a sampling decision', content: '0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3' }, + { kind: 'a malformed value', content: 'not-a-trace' }, + ])('marks the pageload as static without a link for $kind', ({ content }) => { + addCacheOriginTag(content); + + expect(withCacheOrigin(spanOptions)).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + }); + }); +}); diff --git a/packages/sveltekit/test/server-common/handle.test.ts b/packages/sveltekit/test/server-common/handle.test.ts index e7b703f08c44..c40ef465919e 100644 --- a/packages/sveltekit/test/server-common/handle.test.ts +++ b/packages/sveltekit/test/server-common/handle.test.ts @@ -540,6 +540,36 @@ describe('sentryHandle', () => { }); }); +describe('sentryHandle on Vercel ISR', () => { + it('writes the trace of the request span as the cache origin of a request that Vercel marks as an ISR render', async () => { + const event = mockEvent({ + request: new Request('https://shop.example.com/pricing', { headers: { 'x-vercel-isr': '1' } }), + url: new URL('https://shop.example.com/pricing'), + route: { id: '/pricing' }, + }); + let html: string | undefined; + let requestSpan: Span | undefined; + + await sentryHandle({ injectFetchProxyScript: false })({ + event, + resolve: async (_event, opts) => { + requestSpan = SentryCore.getActiveSpan(); + html = + (await opts?.transformPageChunk?.({ + html: '', + done: true, + })) ?? undefined; + return mockResponse; + }, + }); + + const { traceId, spanId } = requestSpan!.spanContext(); + expect(html).toBe( + `\n`, + ); + }); +}); + describe('addSentryCodeToPage', () => { const html = ` @@ -650,6 +680,50 @@ describe('addSentryCodeToPage', () => { expect(transformed).toContain(``); }); }); + + describe('while Vercel renders a page for its ISR cache', () => { + it('replaces the trace meta tags of a server-rendered page with the cache origin of this render', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false, isVercelIsrRender: true }); + + const transformed = SentryCore.startSpan({ name: 'GET /pricing' }, span => { + const { traceId, spanId } = span.spanContext(); + return { html: transformPageChunk({ html: serverRenderedHtml, done: true }), traceId, spanId }; + }); + + expect(transformed.html).toBe( + serverRenderedHtml.replace( + '', + `\n`, + ), + ); + }); + + it('uses the root span of the request as the cache origin while a child span is active', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false, isVercelIsrRender: true }); + + const transformed = SentryCore.startSpan({ name: 'GET /pricing' }, rootSpan => + SentryCore.startSpan({ name: 'sveltekit.resolve' }, () => { + const { traceId, spanId } = rootSpan.spanContext(); + return { html: transformPageChunk({ html: serverRenderedHtml, done: true }), traceId, spanId }; + }), + ); + + expect(transformed.html).toBe( + serverRenderedHtml.replace( + '', + `\n`, + ), + ); + }); + + it('adds no meta tags to a client-side shell', () => { + const transformPageChunk = addSentryCodeToPage({ injectFetchProxyScript: false, isVercelIsrRender: true }); + + const transformed = transformPageChunk({ html: clientShellHtml, done: true }); + + expect(transformed).toBe(clientShellHtml); + }); + }); }); describe('isFetchProxyRequired', () => { From ed74679f40666ea18b56a71c5b3071cf304c78c7 Mon Sep 17 00:00:00 2001 From: Andrei <168741329+andreiborza@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:02:21 +0100 Subject: [PATCH 078/136] chore: Use What/Why structure in PR template (#26348) chore: Use What/Why structure in PR template --- .github/PULL_REQUEST_TEMPLATE.md | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d12cda804156..32fab6f55b39 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,23 +1,19 @@ -**Why:** +## What -**How to review:** + -**Unsure about:** +## Why -Closes # + - +Closes: # From 9279303f77e96a047246da9a52bf3e1fd3e51240 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Fri, 13 Nov 2026 13:49:51 +0000 Subject: [PATCH 079/136] feat(bundler-plugins): Delete source maps with `deleteSourcemapsAfterUpload: true` when no upload runs (#26281) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `deleteSourcemapsAfterUpload: true` now removes source maps even when no upload runs, for example without an auth token, org or project. The framework SDKs turn on hidden source maps and delete them with globs that run whether or not an upload happened. Once they move to `deleteSourcemapsAfterUpload: true`, a build without an auth token would otherwise keep those maps in its output. The plugin still does not turn source maps on when it cannot upload them, and in development mode (`NODE_ENV=development`) it changes nothing, as before. With `sourcemaps.disable` set, maps the user enabled stay for a manual upload and the plugin warns, as before. The option is not released yet. The SDKs also need two internal options, on internal option types only; the public options do not change. First, `deleteSourcemapsAfterUpload` can be a function that the plugin calls when it decides, because the SDK Vite plugins only know that they turned maps on in their own `config` hook, after they created this plugin. On Vite it receives the environment name when an environment sets its own `build.sourcemap`. Second, `sdkEnabledSourceMaps` tells the plugin that the SDK turned the maps on. The plugin then removes every map of that build, as the SDK globs did: CSS maps, maps of chunks that `assets` or `ignore` leave out, maps of outputs with their own `sourcemap` setting, and maps other plugins emit as assets, such as Vite worker bundles. It also removes them with `sourcemaps.disable`, after it stamps the debug IDs. Without the flag, the plugin removes all maps only when it turned them on itself. --------- Co-authored-by: Jan Peer Stöcklmair --- .../src/core/build-plugin-manager.ts | 13 +- packages/bundler-plugins/src/core/index.ts | 4 +- .../src/core/options-mapping.ts | 12 +- .../src/core/sentry/telemetry.ts | 6 +- .../src/core/sourcemap-settings.ts | 54 ++++++- packages/bundler-plugins/src/core/types.ts | 28 ++++ packages/bundler-plugins/src/esbuild/index.ts | 74 +++++---- packages/bundler-plugins/src/rollup/index.ts | 4 +- .../src/rollup/source-map-handling.ts | 48 +++++- packages/bundler-plugins/src/vite/index.ts | 6 +- .../src/vite/source-map-hooks.ts | 25 ++- packages/bundler-plugins/src/webpack/index.ts | 73 +++++++-- .../test/core/option-mappings.test.ts | 25 +-- .../test/core/sourcemap-settings.test.ts | 149 ++++++++++++++++-- .../delete-sourcemaps-after-upload.test.ts | 42 ++++- .../test/esbuild/disable-upload.test.ts | 47 ++++++ .../delete-sourcemaps-after-upload.test.ts | 147 ++++++++++++++++- .../delete-sourcemaps-after-upload.test.ts | 117 +++++++++++++- .../delete-sourcemaps-after-upload.test.ts | 67 +++++++- .../buildTimeOptionsBase.ts | 7 + 20 files changed, 824 insertions(+), 124 deletions(-) diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index b70b32664d01..a05321740aa5 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -11,7 +11,7 @@ import { normalizeUserOptions, validateOptions } from './options-mapping'; import type { Logger } from './logger'; import { createLogger } from './logger'; import { allowedToSendTelemetry, createSentryInstance, safeFlushTelemetry } from './sentry/telemetry'; -import type { Options, SentrySDKBuildFlags } from './types'; +import type { InternalOptions, SentrySDKBuildFlags } from './types'; import { arrayify, getProjects, getTurborepoEnvPassthroughWarning, stripQueryAndHashFromPath } from './utils'; import { defaultRewriteSourcesHook, @@ -153,7 +153,7 @@ export type SentryBuildPluginManager = { * Decides how the plugin treats the user's source map setting (see `decideSourceMapHandling`). * Logs the decision's message once per message, unless `log` is `false`. */ - decide(kind: SourceMapKind, options?: { log?: boolean }): SourceMapDecision; + decide(kind: SourceMapKind, options?: { log?: boolean; environment?: string }): SourceMapDecision; /** Logs the decision's message, once per message. */ logDecision(decision: SourceMapDecision): void; /** @@ -183,7 +183,7 @@ export type SentryBuildPluginManager = { * The build plugin manager's behavior strongly depends on the options that are passed in. */ export function createSentryBuildPluginManager( - userOptions: Options, + userOptions: InternalOptions, bundlerPluginMetaContext: { /** * E.g. `webpack` or `nextjs` or `turbopack` @@ -970,8 +970,11 @@ export function createSentryBuildPluginManager( sourceMaps: { uploadPossible: sourceMapUploadPossible, - decide(kind, { log = true } = {}) { - const decision = decideSourceMapHandling(kind, options, sourceMapUploadPossible); + decide(kind, { log = true, environment } = {}) { + // Watch builds in development keep their source maps. + const decision = isDevMode + ? { enableHidden: false, deleteAfterUpload: false } + : decideSourceMapHandling(kind, options, sourceMapUploadPossible, environment); if (log) { logDecision(decision); } diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts index b721b2ec47e7..a784e7ded36a 100644 --- a/packages/bundler-plugins/src/core/index.ts +++ b/packages/bundler-plugins/src/core/index.ts @@ -101,7 +101,7 @@ export function getDebugIdSnippet(debugId: string): CodeInjection { } export type { Logger } from './logger'; -export type { Options, SentrySDKBuildFlags } from './types'; +export type { InternalOptions, Options, SentrySDKBuildFlags } from './types'; export { CodeInjection, replaceBooleanFlagsInCode, @@ -112,6 +112,6 @@ export { export { createSentryBuildPluginManager } from './build-plugin-manager'; export type { SentryBuildPluginManager, UploadResult, UploadStaging } from './build-plugin-manager'; export { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload'; -export { decideSourceMapHandling } from './sourcemap-settings'; +export { decideSourceMapHandling, getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps } from './sourcemap-settings'; export type { SourceMapDecision, SourceMapKind } from './sourcemap-settings'; export type { UploadFilter } from './upload-filter'; diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index f775ce0c5ad3..a811edf748db 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -1,7 +1,7 @@ import { getVercelEnv } from '@sentry/core'; import type { Logger } from './logger'; import type { - Options as UserOptions, + InternalOptions as UserOptions, SetCommitsOptions, RewriteSourcesHook, ResolveSourceMapHook, @@ -30,7 +30,8 @@ export type NormalizedOptions = { rewriteSources?: RewriteSourcesHook; resolveSourceMap?: ResolveSourceMapHook; filesToDeleteAfterUpload?: string | string[] | Promise; - deleteSourcemapsAfterUpload?: boolean; + deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); + sdkEnabledSourceMaps?: boolean | ((environment?: string) => boolean | undefined); } | undefined; release: { @@ -217,13 +218,6 @@ export function validateOptions(options: NormalizedOptions, logger: Logger): boo return false; } - if (options.sourcemaps?.deleteSourcemapsAfterUpload && options.sourcemaps.disable) { - logger.warn( - 'The `sourcemaps.deleteSourcemapsAfterUpload` option is set but source map upload is disabled via `sourcemaps.disable`.', - 'Source maps will not be deleted.', - ); - } - if (options.project && Array.isArray(options.project)) { if (options.project.length === 0) { logger.error( diff --git a/packages/bundler-plugins/src/core/sentry/telemetry.ts b/packages/bundler-plugins/src/core/sentry/telemetry.ts index 66953eb3cb1f..31b4394698c5 100644 --- a/packages/bundler-plugins/src/core/sentry/telemetry.ts +++ b/packages/bundler-plugins/src/core/sentry/telemetry.ts @@ -108,7 +108,11 @@ export function setTelemetryDataOnScope( scope.setTag('delete-after-upload', !!sourcemaps?.filesToDeleteAfterUpload); scope.setTag( 'delete-sourcemaps-after-upload', - sourcemaps?.deleteSourcemapsAfterUpload === undefined ? 'auto' : String(sourcemaps.deleteSourcemapsAfterUpload), + typeof sourcemaps?.deleteSourcemapsAfterUpload === 'function' + ? 'function' + : sourcemaps?.deleteSourcemapsAfterUpload === undefined + ? 'auto' + : String(sourcemaps.deleteSourcemapsAfterUpload), ); scope.setTag('sourcemaps-disabled', !!sourcemaps?.disable); diff --git a/packages/bundler-plugins/src/core/sourcemap-settings.ts b/packages/bundler-plugins/src/core/sourcemap-settings.ts index 0f5a3b3d12fc..2998c8759386 100644 --- a/packages/bundler-plugins/src/core/sourcemap-settings.ts +++ b/packages/bundler-plugins/src/core/sourcemap-settings.ts @@ -16,11 +16,28 @@ export type SourceMapDecision = { enableHidden: boolean; /** Remove the source maps from the build output once they are uploaded. */ deleteAfterUpload: boolean; + /** + * With `deleteAfterUpload`, remove every source map of the build, also those of CSS and of chunks + * the upload leaves out. Set when the plugin or the SDK turned the source maps on. + */ + removeAllSourceMaps?: boolean; log?: { level: 'info' | 'warn'; message: string }; }; const NO_CHANGE: SourceMapDecision = { enableHidden: false, deleteAfterUpload: false }; +/** Reads `sourcemaps.deleteSourcemapsAfterUpload`, calling the internal function form if given. */ +export function getDeleteSourcemapsAfterUpload(options: NormalizedOptions, environment?: string): boolean | undefined { + const value = options.sourcemaps?.deleteSourcemapsAfterUpload; + return typeof value === 'function' ? value(environment) : value; +} + +/** Reads the internal `sourcemaps.sdkEnabledSourceMaps` option, calling its function form if given. */ +export function getSdkEnabledSourceMaps(options: NormalizedOptions, environment?: string): boolean { + const value = options.sourcemaps?.sdkEnabledSourceMaps; + return (typeof value === 'function' ? value(environment) : value) === true; +} + /** * Decides whether the plugin turns hidden source maps on and whether it removes the maps from the * build output after the upload. The plugin only turns maps on when an upload can run, and only @@ -30,11 +47,37 @@ export function decideSourceMapHandling( kind: SourceMapKind, options: NormalizedOptions, uploadPossible: boolean, + environment?: string, ): SourceMapDecision { - const deleteOption = options.sourcemaps?.deleteSourcemapsAfterUpload; + const deleteOption = getDeleteSourcemapsAfterUpload(options, environment); + const sdkEnabledSourceMaps = getSdkEnabledSourceMaps(options, environment); if (!uploadPossible || options.sourcemaps?.disable) { - return NO_CHANGE; + if (deleteOption !== true || (kind !== 'hidden' && kind !== 'visible')) { + return NO_CHANGE; + } + // Users set `sourcemaps.disable` to upload the maps themselves. Maps the + // SDK turned on are still removed, as the SDKs' own globs did. + if (options.sourcemaps?.disable && !sdkEnabledSourceMaps) { + return { + ...NO_CHANGE, + log: { + level: 'warn', + message: + '`sourcemaps.deleteSourcemapsAfterUpload` is set, but source map upload is disabled with `sourcemaps.disable`, so the source maps are not removed.', + }, + }; + } + return { + enableHidden: kind === 'visible', + deleteAfterUpload: true, + removeAllSourceMaps: sdkEnabledSourceMaps, + log: { + level: 'warn', + message: + 'Source maps are not uploaded, but they are removed from the build output because `sourcemaps.deleteSourcemapsAfterUpload` is set.', + }, + }; } switch (kind) { @@ -74,6 +117,7 @@ export function decideSourceMapHandling( return { enableHidden: true, deleteAfterUpload: true, + removeAllSourceMaps: true, log: { level: 'info', message: @@ -83,7 +127,10 @@ export function decideSourceMapHandling( }; case 'hidden': - return { enableHidden: false, deleteAfterUpload: deleteOption === true }; + if (deleteOption !== true) { + return NO_CHANGE; + } + return { enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: sdkEnabledSourceMaps }; case 'visible': if (deleteOption !== true) { @@ -92,6 +139,7 @@ export function decideSourceMapHandling( return { enableHidden: true, deleteAfterUpload: true, + removeAllSourceMaps: sdkEnabledSourceMaps, log: { level: 'info', message: diff --git a/packages/bundler-plugins/src/core/types.ts b/packages/bundler-plugins/src/core/types.ts index 7cf821a63937..033ff005d36b 100644 --- a/packages/bundler-plugins/src/core/types.ts +++ b/packages/bundler-plugins/src/core/types.ts @@ -111,6 +111,9 @@ export interface Options { * Options related to source maps upload and processing. */ sourcemaps?: { + // TODO(v12): Replace `disable` with separate options, for example + // `upload`, `debugIds` and `deleteSourcemapsAfterUpload`, so that one + // option no longer controls several features. /** * Disables all functionality related to sourcemaps if set to `true`. * @@ -204,6 +207,10 @@ export interface Options { * `sourcemaps.assets` or `sourcemaps.ignore` keep out of the upload. Source maps you enabled yourself are only * removed for the JavaScript chunks that were uploaded; excluded chunks keep theirs. * + * `true` removes source maps you enabled yourself even when no upload runs, for example without an auth token. + * With `sourcemaps.disable` set, the plugin keeps them for a manual upload and warns. The plugin does not turn + * source maps on when it cannot upload them. + * * With webpack's array form of `devtool`, `true` replaces the array with one hidden source map setting for * all asset types, because webpack hides the array from plugins. * @@ -668,3 +675,24 @@ type DeployOptions = { }; export type HandleRecoverableErrorFn = (error: unknown, throwByDefault: boolean) => void; + +/** + * @internal For Sentry SDK packages only. It can change in any release. + * + * Like `Options`, but `sourcemaps.deleteSourcemapsAfterUpload` can also be a function, and + * `sourcemaps.sdkEnabledSourceMaps` is added. The plugin calls the functions when it decides how + * to treat the bundler's source map setting, so an SDK can give a value that it only knows after it + * created the plugin. Vite passes the name of an environment with its own `build.sourcemap`, and + * `undefined` for the top-level `build.sourcemap`. + */ +export type InternalOptions = Omit & { + sourcemaps?: Omit, 'deleteSourcemapsAfterUpload'> & { + deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); + /** + * The SDK turned on the bundler's source maps. With `deleteSourcemapsAfterUpload: true` the + * plugin then removes them like source maps it turned on itself: all of them, also those of CSS + * and of chunks that the upload leaves out. + */ + sdkEnabledSourceMaps?: boolean | ((environment?: string) => boolean | undefined); + }; +}; diff --git a/packages/bundler-plugins/src/esbuild/index.ts b/packages/bundler-plugins/src/esbuild/index.ts index 51e5f126db8f..75e9f01213df 100644 --- a/packages/bundler-plugins/src/esbuild/index.ts +++ b/packages/bundler-plugins/src/esbuild/index.ts @@ -1,4 +1,4 @@ -import type { Options, SourceMapDecision, SourceMapKind } from '../core'; +import type { InternalOptions, SourceMapDecision, SourceMapKind } from '../core'; import { createSentryBuildPluginManager, generateReleaseInjectorCode, @@ -110,7 +110,7 @@ function getEsbuildMajorVersion(): string | undefined { const pluginName = 'sentry-esbuild-plugin'; // eslint-disable-next-line @typescript-eslint/no-explicit-any -export function sentryEsbuildPlugin(userOptions: Options = {}): any { +export function sentryEsbuildPlugin(userOptions: InternalOptions = {}): any { const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, { loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`, buildTool: 'esbuild', @@ -326,36 +326,17 @@ export function sentryEsbuildPlugin(userOptions: Options = {}): any { try { await sentryBuildPluginManager.createRelease(); - if (sourcemapsEnabled) { - // The metafile lists outputs relative to `absWorkingDir`, not to the process. - const outputDir = initialOptions.absWorkingDir ?? process.cwd(); - const buildArtifacts = result.metafile - ? Object.keys(result.metafile.outputs).map(output => path.resolve(outputDir, output)) - : []; - - if (options.sourcemaps?.disable !== 'disable-upload') { - // The upload globs the paths, and glob reads backslashes as escapes. - const { uploaded, uploadedSourceMapPaths } = await upload( - buildArtifacts.map(artifact => artifact.split(path.sep).join('/')), - ); - - // esbuild writes before `onEnd` runs, so the maps are deleted from disk - // afterwards instead of being dropped from the output like in other bundlers. - // A map the plugin turned on never stays in the output. A map the user - // enabled is only deleted once it was uploaded. - if (sourceMapDecision.deleteAfterUpload) { - const sourceMaps = - sourceMapKind === 'unset' - ? buildArtifacts.filter(artifact => artifact.endsWith('.map')) - : uploadedSourceMapPaths; - - if (uploaded) { - await sentryBuildPluginManager.sourceMaps.deleteFromOutput(sourceMaps); - } else if (sourceMaps.length > 0) { - logger.error('The source maps were not uploaded, so they stay in the build output.'); - } - } - } else if (initialOptions.write === false) { + // The metafile lists outputs relative to `absWorkingDir`, not to the process. + const outputDir = initialOptions.absWorkingDir ?? process.cwd(); + const buildArtifacts = result.metafile + ? Object.keys(result.metafile.outputs).map(output => path.resolve(outputDir, output)) + : []; + + const { sourceMaps } = sentryBuildPluginManager; + const allMaps = buildArtifacts.filter(artifact => artifact.endsWith('.map')); + const deleteWithoutUpload = sourceMapDecision.deleteAfterUpload && !sourceMaps.uploadPossible; + if (sourcemapsEnabled && options.sourcemaps?.disable === 'disable-upload') { + if (initialOptions.write === false) { logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.'); } else { // The upload routine (which stamps debug IDs into temp copies of the artifacts) is @@ -367,6 +348,35 @@ export function sentryEsbuildPlugin(userOptions: Options = {}): any { .map(bundle => addDebugIdToEmittedArtifacts(bundle, logger, options.sourcemaps?.resolveSourceMap)), ); } + } else if (sourcemapsEnabled) { + // The upload globs the paths, and glob reads backslashes as escapes. + // When no upload can run, this logs why. + const { uploaded, uploadedSourceMapPaths } = await upload( + buildArtifacts.map(artifact => artifact.split(path.sep).join('/')), + ); + + // esbuild writes before `onEnd` runs, so the maps are deleted from disk + // afterwards instead of being dropped from the output like in other bundlers. + // A map the plugin turned on never stays in the output. A map the user + // enabled is only deleted once it was uploaded. + if (sourceMapDecision.deleteAfterUpload && !deleteWithoutUpload) { + const mapsToDelete = sourceMapDecision.removeAllSourceMaps ? allMaps : uploadedSourceMapPaths; + + if (uploaded) { + await sourceMaps.deleteFromOutput(mapsToDelete); + } else if (mapsToDelete.length > 0) { + logger.error('The source maps were not uploaded, so they stay in the build output.'); + } + } + } + + if (deleteWithoutUpload) { + const bundleOf = (map: string): string => map.slice(0, -'.map'.length); + const isUploaded = (map: string): boolean => + isJsFile(bundleOf(map)) && sourceMaps.shouldUpload(bundleOf(map)); + await sourceMaps.deleteFromOutput( + sourceMapDecision.removeAllSourceMaps ? allMaps : allMaps.filter(isUploaded), + ); } } finally { freeGlobalDependencyOnBuildArtifacts(); diff --git a/packages/bundler-plugins/src/rollup/index.ts b/packages/bundler-plugins/src/rollup/index.ts index 7017577c6919..c36e3b73f249 100644 --- a/packages/bundler-plugins/src/rollup/index.ts +++ b/packages/bundler-plugins/src/rollup/index.ts @@ -1,4 +1,4 @@ -import type { ChunkGraphNode, Options } from '../core'; +import type { ChunkGraphNode, InternalOptions, Options } from '../core'; import { createSentryBuildPluginManager, generateReleaseInjectorCode, @@ -91,7 +91,7 @@ function getViteParseAstAsync(): Promise { */ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type export function _createRollupPluginInternals( - userOptions: Options = {}, + userOptions: InternalOptions = {}, buildTool: 'rollup' | 'vite', buildToolMajorVersion?: string, ) { diff --git a/packages/bundler-plugins/src/rollup/source-map-handling.ts b/packages/bundler-plugins/src/rollup/source-map-handling.ts index b907b217afed..552b01950ee9 100644 --- a/packages/bundler-plugins/src/rollup/source-map-handling.ts +++ b/packages/bundler-plugins/src/rollup/source-map-handling.ts @@ -165,15 +165,32 @@ export function createSourceMapHandling(sentryBuildPluginManager: SentryBuildPlu return candidates.sort((a, b) => countMatchFields(b.match) - countMatchFields(a.match))[0]; } - function dropSourceMaps(bundle: OutputBundle): void { + function dropSourceMaps(bundle: OutputBundle, shouldDrop: (fileName: string) => boolean = () => true): void { for (const output of Object.values(bundle)) { - if (output.type === 'chunk' && isJsFile(output.fileName)) { + if (output.type === 'chunk' && isJsFile(output.fileName) && shouldDrop(output.fileName)) { // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle delete bundle[getSourceMapFileName(output)]; } } } + // Other plugins emit maps as assets, e.g. for CSS or for Vite worker + // bundles. Chunk maps stay here, because staging still needs them. + function dropAssetSourceMaps(bundle: OutputBundle): void { + const chunkMaps = new Set(); + for (const output of Object.values(bundle)) { + if (output.type === 'chunk') { + chunkMaps.add(getSourceMapFileName(output)); + } + } + for (const [fileName, output] of Object.entries(bundle)) { + if (output.type === 'asset' && fileName.endsWith('.map') && !chunkMaps.has(fileName)) { + // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle + delete bundle[fileName]; + } + } + } + return { outputOptions: rawOutputOptions => { const kind = sourceMapKindFromRollupSetting(rawOutputOptions.sourcemap); @@ -210,6 +227,23 @@ export function createSourceMapHandling(sentryBuildPluginManager: SentryBuildPlu return; } + const removeAll = record.decision.removeAllSourceMaps === true; + // With `unset` the plugin only turned on the chunk maps. Asset maps + // come from other plugins' own settings. + if (removeAll && record.kind !== 'unset') { + dropAssetSourceMaps(bundle); + } + + if (!sentryBuildPluginManager.sourceMaps.uploadPossible) { + dropSourceMaps( + bundle, + removeAll + ? undefined + : fileName => sentryBuildPluginManager.sourceMaps.shouldUpload(path.join(destination, fileName)), + ); + return; + } + const staging = await sentryBuildPluginManager.createUploadStaging(); try { @@ -231,16 +265,16 @@ export function createSourceMapHandling(sentryBuildPluginManager: SentryBuildPlu chunkPath: path.join(destination, output.fileName), }); - // A map the plugin turned on never reaches the output, whether or - // not the chunk is uploaded. A map the user enabled stays unless - // it was staged. - if (result === 'staged' || record.kind === 'unset') { + // A map the plugin or the SDK turned on never reaches the output, + // whether or not the chunk is uploaded. A map the user enabled + // stays unless it was staged. + if (result === 'staged' || removeAll) { // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle delete bundle[mapFileName]; } if (result === 'skipped' || result === 'failed') { sentryBuildPluginManager.logger.warn( - record.kind === 'unset' + removeAll ? `Could not prepare ${output.fileName} for upload, so it is not uploaded and its source map ${mapFileName} was removed from the build output.` : `Could not prepare ${output.fileName} for upload, so its source map ${mapFileName} stays in the build output.`, ); diff --git a/packages/bundler-plugins/src/vite/index.ts b/packages/bundler-plugins/src/vite/index.ts index 9c8d5437fe03..414b0b0d538e 100644 --- a/packages/bundler-plugins/src/vite/index.ts +++ b/packages/bundler-plugins/src/vite/index.ts @@ -1,4 +1,4 @@ -import type { SentryRollupPluginOptions } from '../rollup'; +import type { InternalOptions } from '../core'; import { _createRollupPluginInternals } from '../rollup'; import { createRequire } from 'node:module'; @@ -22,7 +22,7 @@ function getViteMajorVersion(): string | undefined { return undefined; } -export const sentryVitePlugin = (options?: SentryRollupPluginOptions): SentryVitePlugin[] => { +export const sentryVitePlugin = (options?: InternalOptions): SentryVitePlugin[] => { const { main, post } = _createRollupPluginInternals(options, 'vite', getViteMajorVersion()); const plugins: SentryVitePlugin[] = [{ enforce: 'pre', ...main }]; @@ -34,4 +34,4 @@ export const sentryVitePlugin = (options?: SentryRollupPluginOptions): SentryVit return plugins; }; -export type { Options as SentryVitePluginOptions } from '../core'; +export type { Options as SentryVitePluginOptions, InternalOptions as SentryVitePluginInternalOptions } from '../core'; diff --git a/packages/bundler-plugins/src/vite/source-map-hooks.ts b/packages/bundler-plugins/src/vite/source-map-hooks.ts index 04e3eedc179a..0295dae0079b 100644 --- a/packages/bundler-plugins/src/vite/source-map-hooks.ts +++ b/packages/bundler-plugins/src/vite/source-map-hooks.ts @@ -1,5 +1,6 @@ import * as path from 'node:path'; import type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind } from '../core'; +import { getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps } from '../core'; import type { OutputMatch, RollupSourceMapSetting, SourceMapHandling } from '../rollup/source-map-handling'; import { getOutputMatch, sourceMapKindFromRollupSetting } from '../rollup/source-map-handling'; @@ -96,7 +97,10 @@ export function createViteSourceMapHooks( } const environmentKind = sourceMapKindFromRollupSetting(setting); - const environmentDecision = sentryBuildPluginManager.sourceMaps.decide(environmentKind, { log: false }); + const environmentDecision = sentryBuildPluginManager.sourceMaps.decide(environmentKind, { + log: false, + environment: name, + }); decisions.set(name, { kind: environmentKind, decision: environmentDecision }); if (environmentDecision.enableHidden) { @@ -110,22 +114,27 @@ export function createViteSourceMapHooks( configResolved: config => { const environments = config.environments ?? { client: { build: config.build } }; - const { uploadPossible } = sentryBuildPluginManager.sourceMaps; - const deleteOption = sentryBuildPluginManager.normalizedOptions.sourcemaps?.deleteSourcemapsAfterUpload; - for (const [name, environment] of Object.entries(environments)) { const { kind, decision } = decisions.get(name) ?? decisions.get('*') ?? { kind: 'unset', decision: NO_CHANGE }; + const environmentName = decisions.has(name) ? name : undefined; + const { normalizedOptions } = sentryBuildPluginManager; + const deleteOption = getDeleteSourcemapsAfterUpload(normalizedOptions, environmentName); + const sdkEnabledSourceMaps = getSdkEnabledSourceMaps(normalizedOptions, environmentName); for (const output of getOutputs(config.root, environment.build)) { - // The plugin never changes an output's own setting, so the user enabled - // these maps: only hidden ones the user asked to delete are removed. + // The plugin never changes an output's own setting. Hidden maps are + // removed when the user asks for it, visible ones only when the SDK + // turned source maps on. if (output.ownSetting) { + const outputKind = sourceMapKindFromRollupSetting(output.sourcemap); + const removeAllSourceMaps = sdkEnabledSourceMaps && (outputKind === 'hidden' || outputKind === 'visible'); sourceMapHandling.setDecision(output.destination, { match: output.match, - kind: sourceMapKindFromRollupSetting(output.sourcemap), + kind: outputKind, decision: { enableHidden: false, - deleteAfterUpload: uploadPossible && deleteOption === true && output.sourcemap === 'hidden', + deleteAfterUpload: deleteOption === true && (outputKind === 'hidden' || removeAllSourceMaps), + removeAllSourceMaps, }, }); continue; diff --git a/packages/bundler-plugins/src/webpack/index.ts b/packages/bundler-plugins/src/webpack/index.ts index 85795477405d..4b60bfcfe64f 100644 --- a/packages/bundler-plugins/src/webpack/index.ts +++ b/packages/bundler-plugins/src/webpack/index.ts @@ -1,6 +1,13 @@ /* oxlint-disable max-lines */ -import type { Options, SourceMapDecision, SourceMapKind, UploadStaging } from '../core/index'; +import type { + InternalOptions, + Options, + SourceMapDecision, + SourceMapKind, + UploadFilter, + UploadStaging, +} from '../core/index'; import { createSentryBuildPluginManager, generateReleaseInjectorCode, @@ -220,13 +227,32 @@ function deleteSourceMapAssets(compilation: WebpackCompilation, sourceMapName: s } } +/** + * Drops the source maps of the JS assets that an upload would include. With `removeAll` it drops + * the source maps of all assets, CSS included. + */ +function dropSourceMaps(compilation: WebpackCompilation, shouldUpload: UploadFilter, removeAll: boolean): void { + const outputPath = compilation.outputOptions.path ?? path.resolve(); + + for (const asset of compilation.getAssets()) { + if (!removeAll && (!isJsFile(asset.name) || !shouldUpload(path.join(outputPath, asset.name)))) { + continue; + } + const relatedSourceMap = asset.info.related?.sourceMap; + const sourceMapName = typeof relatedSourceMap === 'string' ? relatedSourceMap : `${asset.name}.map`; + if (compilation.getAsset(sourceMapName)) { + deleteSourceMapAssets(compilation, sourceMapName); + } + } +} + /** * Copies each JS asset and its source map into the upload staging folder and drops the source map * assets (and their compressed variants) from the compilation, so webpack never emits them. * - * A map the plugin turned on (`pluginEnabledMaps`) never reaches the output, whether or not its - * asset is uploaded. That covers CSS maps, which `devtool` turns on along with the JS ones. A map - * the user enabled stays unless it was staged. + * A map the plugin or the SDK turned on (`pluginEnabledMaps`) never reaches the output, whether or + * not its asset is uploaded. That covers CSS maps, which `devtool` turns on along with the JS ones. + * A map the user enabled stays unless it was staged. */ async function stageSourceMaps( compilation: WebpackCompilation, @@ -271,7 +297,7 @@ async function stageSourceMaps( } } -function createSentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) { +function createSentryWebpackPlugin(userOptions: SentryWebpackPluginInternalOptions = {}) { const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, { loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? '[sentry-webpack-plugin]', buildTool: 'webpack', @@ -416,21 +442,31 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) // One plugin instance can serve several compilers (`MultiCompiler`) and // a compiler several compilations (watch mode), so nothing is shared. - const { kind: sourceMapKind, decision: sourceMapDecision } = decideSourceMaps(compiler); + const { decision: sourceMapDecision } = decideSourceMaps(compiler); + const removeAllSourceMaps = sourceMapDecision.removeAllSourceMaps === true; const pendingStagings = new Map(); - if (sourceMapDecision.deleteAfterUpload) { - // After `RealContentHashPlugin` rewrote the hash placeholders, so the staged - // JS equals the emitted file and `[contenthash]` names are final. - const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5000) + 1; + // After `RealContentHashPlugin` rewrote the hash placeholders, so the staged + // JS equals the emitted file and `[contenthash]` names are final. + const deleteStage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5000) + 1; + if (sourceMapDecision.deleteAfterUpload && !sentryBuildPluginManager.sourceMaps.uploadPossible) { compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => { - compilation.hooks.processAssets.tapPromise({ name: 'sentry-webpack-plugin', stage }, async () => { - const staging = await sentryBuildPluginManager.createUploadStaging(); - pendingStagings.set(compilation, staging); - await stageSourceMaps(compilation, staging, logger, sourceMapKind === 'unset'); + compilation.hooks.processAssets.tap({ name: 'sentry-webpack-plugin', stage: deleteStage }, () => { + dropSourceMaps(compilation, sentryBuildPluginManager.sourceMaps.shouldUpload, removeAllSourceMaps); }); }); + } else if (sourceMapDecision.deleteAfterUpload) { + compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => { + compilation.hooks.processAssets.tapPromise( + { name: 'sentry-webpack-plugin', stage: deleteStage }, + async () => { + const staging = await sentryBuildPluginManager.createUploadStaging(); + pendingStagings.set(compilation, staging); + await stageSourceMaps(compilation, staging, logger, removeAllSourceMaps); + }, + ); + }); // A staging that `afterEmit` never took belongs to a compilation that // failed before emitting, or to one whose assets were emitted without @@ -557,9 +593,14 @@ function createSentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) } // eslint-disable-next-line @typescript-eslint/no-explicit-any -export const sentryWebpackPlugin: (options?: SentryWebpackPluginOptions) => any = createSentryWebpackPlugin; +export const sentryWebpackPlugin: (options?: SentryWebpackPluginInternalOptions) => any = createSentryWebpackPlugin; + +/** @internal For Sentry SDK packages only. See `InternalOptions`. */ +export type SentryWebpackPluginInternalOptions = InternalOptions & WebpackExperiments; + +export type SentryWebpackPluginOptions = Options & WebpackExperiments; -export type SentryWebpackPluginOptions = Options & { +type WebpackExperiments = { _experiments?: Options['_experiments'] & { /** * If enabled, the webpack plugin will exit the build process after the build completes. diff --git a/packages/bundler-plugins/test/core/option-mappings.test.ts b/packages/bundler-plugins/test/core/option-mappings.test.ts index 754facc27e1e..1b853cf89b5e 100644 --- a/packages/bundler-plugins/test/core/option-mappings.test.ts +++ b/packages/bundler-plugins/test/core/option-mappings.test.ts @@ -351,24 +351,15 @@ describe('validateOptions', () => { expect(mockedLogger.error).not.toHaveBeenCalled(); }); - it('warns when `deleteSourcemapsAfterUpload` is set together with `sourcemaps.disable`', () => { - const options = normalizeUserOptions({ - sourcemaps: { disable: 'disable-upload', deleteSourcemapsAfterUpload: true }, - }); - - expect(validateOptions(options, mockedLogger)).toBe(true); - expect(mockedLogger.warn).toHaveBeenCalledWith( - expect.stringContaining('deleteSourcemapsAfterUpload'), - expect.any(String), - ); - }); + it.each([undefined, 'disable-upload'] as const)( + 'does not warn when `deleteSourcemapsAfterUpload` is set and `sourcemaps.disable` is `%s`', + disable => { + const options = normalizeUserOptions({ sourcemaps: { disable, deleteSourcemapsAfterUpload: true } }); - it('does not warn when `deleteSourcemapsAfterUpload` is set and uploads are enabled', () => { - const options = normalizeUserOptions({ sourcemaps: { deleteSourcemapsAfterUpload: true } }); - - expect(validateOptions(options, mockedLogger)).toBe(true); - expect(mockedLogger.warn).not.toHaveBeenCalled(); - }); + expect(validateOptions(options, mockedLogger)).toBe(true); + expect(mockedLogger.warn).not.toHaveBeenCalled(); + }, + ); it('should return `true` for options without special cases', () => { const options = { diff --git a/packages/bundler-plugins/test/core/sourcemap-settings.test.ts b/packages/bundler-plugins/test/core/sourcemap-settings.test.ts index 4435fb98662e..29fa32a86f3f 100644 --- a/packages/bundler-plugins/test/core/sourcemap-settings.test.ts +++ b/packages/bundler-plugins/test/core/sourcemap-settings.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect } from 'vitest'; import { normalizeUserOptions } from '../../src/core/options-mapping'; -import type { Options } from '../../src/core'; +import type { InternalOptions } from '../../src/core'; import { decideSourceMapHandling } from '../../src/core/sourcemap-settings'; import type { SourceMapKind } from '../../src/core/sourcemap-settings'; -function options(sourcemaps?: Options['sourcemaps']) { +function options(sourcemaps?: InternalOptions['sourcemaps']) { return normalizeUserOptions({ org: 'o', project: 'p', authToken: 't', release: { name: 'r' }, sourcemaps }); } @@ -52,6 +52,7 @@ describe('decideSourceMapHandling', () => { expect(decideSourceMapHandling('hidden', options({ deleteSourcemapsAfterUpload: true }), true)).toEqual({ enableHidden: false, deleteAfterUpload: true, + removeAllSourceMaps: false, }); }); @@ -91,16 +92,142 @@ describe('decideSourceMapHandling', () => { }); }); - it.each(['unset', 'off', 'visible', 'hidden', 'inline'])( - 'does nothing for a `%s` setting when no upload can run', - kind => { - expect(decideSourceMapHandling(kind, options({ deleteSourcemapsAfterUpload: true }), false)).toEqual(NO_CHANGE); - }, - ); + describe('when no upload can run', () => { + it.each(['unset', 'off', 'visible', 'hidden', 'inline'])( + 'does nothing for a `%s` setting with the option unset', + kind => { + expect(decideSourceMapHandling(kind, options(), false)).toEqual(NO_CHANGE); + }, + ); + + it.each(['unset', 'off', 'inline'])( + 'does not turn source maps on for a `%s` setting with the option set to true', + kind => { + expect(decideSourceMapHandling(kind, options({ deleteSourcemapsAfterUpload: true }), false)).toEqual(NO_CHANGE); + }, + ); + + it('deletes hidden source maps with the option set to true', () => { + const decision = decideSourceMapHandling('hidden', options({ deleteSourcemapsAfterUpload: true }), false); + + expect(decision).toMatchObject({ enableHidden: false, deleteAfterUpload: true }); + expect(decision.log?.message).toMatch(/not uploaded/); + }); + + it('switches visible source maps to hidden and deletes them with the option set to true', () => { + expect(decideSourceMapHandling('visible', options({ deleteSourcemapsAfterUpload: true }), false)).toMatchObject({ + enableHidden: true, + deleteAfterUpload: true, + }); + }); + + it.each([true, 'disable-upload'] as const)( + 'keeps source maps and warns when `sourcemaps.disable` is `%s` and the option is true', + disable => { + for (const kind of ['hidden', 'visible'] as const) { + const decision = decideSourceMapHandling(kind, options({ disable, deleteSourcemapsAfterUpload: true }), true); + + expect(decision).toMatchObject(NO_CHANGE); + expect(decision.log?.level).toBe('warn'); + expect(decision.log?.message).toMatch(/sourcemaps\.disable/); + } + }, + ); + + it.each([true, 'disable-upload'] as const)( + 'removes source maps the SDK turned on when `sourcemaps.disable` is `%s`', + disable => { + expect( + decideSourceMapHandling( + 'hidden', + options({ disable, deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }), + true, + ), + ).toMatchObject({ enableHidden: false, deleteAfterUpload: true, removeAllSourceMaps: true }); + }, + ); - it.each([true, 'disable-upload'] as const)('does nothing when `sourcemaps.disable` is `%s`', disable => { - expect(decideSourceMapHandling('unset', options({ disable, deleteSourcemapsAfterUpload: true }), true)).toEqual( - NO_CHANGE, + it.each([true, 'disable-upload'] as const)( + 'does not turn source maps on when `sourcemaps.disable` is `%s`', + disable => { + expect(decideSourceMapHandling('unset', options({ disable, deleteSourcemapsAfterUpload: true }), true)).toEqual( + NO_CHANGE, + ); + }, ); }); + + describe('with source maps the SDK turned on', () => { + const sdkOptions = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }; + + it.each(['hidden', 'visible'])('removes all `%s` source maps', kind => { + expect(decideSourceMapHandling(kind, options(sdkOptions), true)).toMatchObject({ + enableHidden: kind === 'visible', + deleteAfterUpload: true, + removeAllSourceMaps: true, + }); + }); + + it.each(['hidden', 'visible'])('removes all `%s` source maps when no upload can run', kind => { + expect(decideSourceMapHandling(kind, options(sdkOptions), false)).toMatchObject({ + enableHidden: kind === 'visible', + deleteAfterUpload: true, + removeAllSourceMaps: true, + }); + }); + + it.each(['unset', 'off', 'inline'])('does not turn `%s` source maps on without an upload', kind => { + expect(decideSourceMapHandling(kind, options(sdkOptions), false)).toEqual(NO_CHANGE); + }); + + it.each([undefined, false])('keeps them when `deleteSourcemapsAfterUpload` is %s', deleteSourcemapsAfterUpload => { + expect( + decideSourceMapHandling('hidden', options({ deleteSourcemapsAfterUpload, sdkEnabledSourceMaps: true }), true), + ).toEqual(NO_CHANGE); + }); + + it('calls the function form when it decides', () => { + let value: boolean | undefined; + const normalized = options({ deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: () => value }); + + expect(decideSourceMapHandling('hidden', normalized, true)).toMatchObject({ removeAllSourceMaps: false }); + value = true; + expect(decideSourceMapHandling('hidden', normalized, true)).toMatchObject({ removeAllSourceMaps: true }); + }); + }); + + describe('with the internal function form', () => { + it('calls the function when it decides', () => { + let value: boolean | undefined; + const normalized = options({ deleteSourcemapsAfterUpload: () => value }); + + expect(decideSourceMapHandling('hidden', normalized, true)).toEqual(NO_CHANGE); + value = true; + expect(decideSourceMapHandling('hidden', normalized, true)).toEqual({ + enableHidden: false, + deleteAfterUpload: true, + removeAllSourceMaps: false, + }); + }); + + it('passes the environment to both functions', () => { + const normalized = options({ + deleteSourcemapsAfterUpload: environment => environment === 'client', + sdkEnabledSourceMaps: environment => environment === 'client', + }); + + expect(decideSourceMapHandling('hidden', normalized, true, 'client')).toMatchObject({ + deleteAfterUpload: true, + removeAllSourceMaps: true, + }); + expect(decideSourceMapHandling('hidden', normalized, true, 'nitro')).toEqual(NO_CHANGE); + expect(decideSourceMapHandling('hidden', normalized, true)).toEqual(NO_CHANGE); + }); + + it('treats `undefined` from the function like an unset option', () => { + expect(decideSourceMapHandling('unset', options({ deleteSourcemapsAfterUpload: () => undefined }), true)).toEqual( + decideSourceMapHandling('unset', options(), true), + ); + }); + }); }); diff --git a/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts index 75578262a922..c82bd9a91bd0 100644 --- a/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/esbuild/delete-sourcemaps-after-upload.test.ts @@ -5,7 +5,7 @@ import * as esbuild from 'esbuild'; import type { BuildOptions } from 'esbuild'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { sentryEsbuildPlugin } from '../../src/esbuild'; -import type { Options } from '../../src/core'; +import type { InternalOptions, Options } from '../../src/core'; const { mockSourcemapUpload } = vi.hoisted(() => ({ mockSourcemapUpload: vi.fn() })); @@ -58,7 +58,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (esbuild)', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); - function build(pluginOptions: Options = {}, overrides: BuildOptions = {}) { + function build(pluginOptions: InternalOptions = {}, overrides: BuildOptions = {}) { return esbuild.build({ entryPoints: [entry], bundle: true, @@ -174,6 +174,23 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (esbuild)', () => { expect(uploads).toHaveLength(1); }); + it.each<[string, InternalOptions]>([ + ['after the upload', {}], + ['when no upload runs', { authToken: undefined }], + ])( + 'deletes every map the SDK turned on, also those of chunks and CSS that were not uploaded (%s)', + async (_, options) => { + await build( + { ...options, sourcemaps: { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true } }, + { ...writeSplitBuild(), sourcemap: 'external' }, + ); + + const files = fs.readdirSync(outDir); + expect(files.filter(file => file.endsWith('.map'))).toEqual([]); + expect(files).toContain('entry.css'); + }, + ); + it('warns when source maps are turned off', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); await build({ silent: false }, { sourcemap: false }); @@ -197,6 +214,27 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (esbuild)', () => { expect(uploads).toHaveLength(0); }); + it('deletes external source maps when the option is true and no upload runs', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + await build( + { silent: false, authToken: undefined, sourcemaps: { deleteSourcemapsAfterUpload: true } }, + { sourcemap: 'external' }, + ); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + expect(uploads).toHaveLength(0); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('No auth token provided')); + }); + + it('keeps the source maps in development mode when the option is true', async () => { + vi.stubEnv('NODE_ENV', 'development'); + await build({ sourcemaps: { deleteSourcemapsAfterUpload: true } }, { sourcemap: 'external' }); + vi.unstubAllEnvs(); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(uploads).toHaveLength(0); + }); + it('leaves the source map setting alone and does not log when the build does not write', async () => { const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined); const result = await build({ silent: false }, { write: false }); diff --git a/packages/bundler-plugins/test/esbuild/disable-upload.test.ts b/packages/bundler-plugins/test/esbuild/disable-upload.test.ts index ca077832169e..fb8801c69d65 100644 --- a/packages/bundler-plugins/test/esbuild/disable-upload.test.ts +++ b/packages/bundler-plugins/test/esbuild/disable-upload.test.ts @@ -43,6 +43,53 @@ describe('sourcemaps.disable: "disable-upload"', () => { expect(bundle).toContain(`//# debugId=${debugId}`); }); + it('keeps the stamped source map with `deleteSourcemapsAfterUpload: true`', async () => { + const outDir = path.join(tmpDir, 'dist'); + + await esbuild.build({ + entryPoints: [entry], + bundle: true, + sourcemap: 'external', + outdir: outDir, + absWorkingDir: tmpDir, + plugins: [ + sentryEsbuildPlugin({ + telemetry: false, + sourcemaps: { disable: 'disable-upload', deleteSourcemapsAfterUpload: true }, + }), + ], + }); + + const bundle = fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8'); + const map = JSON.parse(fs.readFileSync(path.join(outDir, 'entry.js.map'), 'utf8')); + expect(map.debug_id).toBe(bundle.match(DEBUG_ID_MARKER)?.[1]); + }); + + it('stamps the bundle before it deletes a source map the SDK turned on', async () => { + const outDir = path.join(tmpDir, 'dist'); + + await esbuild.build({ + entryPoints: [entry], + bundle: true, + sourcemap: 'external', + outdir: outDir, + absWorkingDir: tmpDir, + plugins: [ + sentryEsbuildPlugin({ + telemetry: false, + sourcemaps: { disable: 'disable-upload', deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }, + }), + ], + }); + + const bundle = fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8'); + const debugId = bundle.match(DEBUG_ID_MARKER)?.[1]; + + expect(debugId).toBeDefined(); + expect(bundle).toContain(`//# debugId=${debugId}`); + expect(fs.existsSync(path.join(outDir, 'entry.js.map'))).toBe(false); + }); + it('does not stamp emitted source maps when uploading is enabled', async () => { const outDir = path.join(tmpDir, 'dist'); diff --git a/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts index 0c28e0b13076..29a7531ff95f 100644 --- a/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/rollup/delete-sourcemaps-after-upload.test.ts @@ -2,10 +2,11 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { rollup } from 'rollup'; +import type { Plugin } from 'rollup'; import { rolldown } from 'rolldown'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { sentryRollupPlugin } from '../../src/rollup'; -import type { Options } from '../../src/core'; +import { _createRollupPluginInternals, sentryRollupPlugin } from '../../src/rollup'; +import type { InternalOptions, Options } from '../../src/core'; const { mockSourcemapUpload, mockReleaseCreate } = vi.hoisted(() => ({ mockSourcemapUpload: vi.fn(), @@ -250,6 +251,148 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (rollup / rolldown)', () => { expect(mkdtempSpy).not.toHaveBeenCalled(); }); + it('removes hidden source maps when the option is true and no upload runs', async () => { + const mkdtempSpy = vi.spyOn(fs.promises, 'mkdtemp'); + const build = await rollup({ + input: entry, + plugins: [ + sentryRollupPlugin({ ...credentials, authToken: undefined, sourcemaps: { deleteSourcemapsAfterUpload: true } }), + ], + }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + + expect(fs.readdirSync(outDir)).toEqual(['entry.js']); + expect(uploads).toHaveLength(0); + expect(mkdtempSpy).not.toHaveBeenCalled(); + }); + + it.each<[string, Options['sourcemaps']]>([ + ['"disable-upload"', { disable: 'disable-upload' }], + ['`true`', { disable: true }], + ])('keeps hidden source maps when the option is true and `sourcemaps.disable` is %s', async (_label, sourcemaps) => { + const build = await rollup({ + input: entry, + plugins: [ + sentryRollupPlugin({ ...credentials, sourcemaps: { ...sourcemaps, deleteSourcemapsAfterUpload: true } }), + ], + }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + expect(uploads).toHaveLength(0); + }); + + it('keeps hidden source maps without an upload when the option is unset', async () => { + const build = await rollup({ + input: entry, + plugins: [sentryRollupPlugin({ ...credentials, authToken: undefined })], + }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + }); + + it('keeps the maps of chunks matched by `sourcemaps.ignore` when no upload runs', async () => { + const build = await rollup({ + input: entry, + plugins: [ + sentryRollupPlugin({ + ...credentials, + authToken: undefined, + sourcemaps: { ignore: ['**/entry.js'], deleteSourcemapsAfterUpload: true }, + }), + ], + }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'entry.js.map']); + }); + + it('keeps the maps other plugins emit as assets when the setting is unset', async () => { + const build = await rollup({ + input: entry, + plugins: [ + sentryRollupPlugin(credentials), + { + name: 'css', + generateBundle() { + this.emitFile({ type: 'asset', fileName: 'style.css', source: 'body { color: red; }\n' }); + this.emitFile({ type: 'asset', fileName: 'style.css.map', source: '{"version":3,"mappings":""}' }); + }, + }, + ], + }); + await build.write({ dir: outDir }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'style.css', 'style.css.map']); + }); + + describe('with source maps the SDK turned on', () => { + // `sentryRollupPlugin` only takes the public options. + function sdkRollupPlugin(options: InternalOptions): Plugin[] { + const { main, post } = _createRollupPluginInternals({ ...credentials, ...options }, 'rollup'); + return (post ? [main, post] : [main]) as Plugin[]; + } + + // Vite emits worker bundles and their maps as assets. + const assetMapsPlugin: Plugin = { + name: 'asset-maps', + generateBundle() { + this.emitFile({ type: 'asset', fileName: 'style.css', source: 'body { color: red; }\n' }); + this.emitFile({ type: 'asset', fileName: 'style.css.map', source: '{"version":3,"mappings":""}' }); + this.emitFile({ type: 'asset', fileName: 'worker.js', source: 'self.onmessage = () => {};\n' }); + this.emitFile({ type: 'asset', fileName: 'worker.js.map', source: '{"version":3,"mappings":""}' }); + }, + }; + + const sdkSourcemaps = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true, ignore: ['**/vendor.js'] }; + + async function writeSdkBuild(options: InternalOptions): Promise { + const vendor = path.join(tmpDir, 'vendor.js'); + fs.writeFileSync(vendor, 'console.log("vendor");\n'); + const build = await rollup({ input: [entry, vendor], plugins: [...sdkRollupPlugin(options), assetMapsPlugin] }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + } + + it('removes the maps of ignored chunks and of assets after the upload', async () => { + await writeSdkBuild({ sourcemaps: sdkSourcemaps }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'style.css', 'vendor.js', 'worker.js']); + expect(uploads).toHaveLength(1); + expectUploadedPair(uploads[0]!, fs.readFileSync(path.join(outDir, 'entry.js'), 'utf8')); + }); + + it('removes all maps when no upload runs', async () => { + await writeSdkBuild({ authToken: undefined, sourcemaps: sdkSourcemaps }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'style.css', 'vendor.js', 'worker.js']); + expect(uploads).toHaveLength(0); + }); + + it('reads the function form when it decides', async () => { + let sdkEnabled: boolean | undefined; + const plugins = sdkRollupPlugin({ sourcemaps: { ...sdkSourcemaps, sdkEnabledSourceMaps: () => sdkEnabled } }); + sdkEnabled = true; + const vendor = path.join(tmpDir, 'vendor.js'); + fs.writeFileSync(vendor, 'console.log("vendor");\n'); + const build = await rollup({ input: [entry, vendor], plugins: [...plugins, assetMapsPlugin] }); + await build.write({ dir: outDir, sourcemap: 'hidden' }); + + expect(fs.readdirSync(outDir).sort()).toEqual(['entry.js', 'style.css', 'vendor.js', 'worker.js']); + }); + + it('keeps the maps when `deleteSourcemapsAfterUpload` is not true', async () => { + await writeSdkBuild({ sourcemaps: { sdkEnabledSourceMaps: true } }); + + expect( + fs + .readdirSync(outDir) + .filter(file => file.endsWith('.map')) + .sort(), + ).toEqual(['entry.js.map', 'style.css.map', 'vendor.js.map', 'worker.js.map']); + }); + }); + it('returns no source maps from generate() and does not log or stage', async () => { const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined); const mkdtempSpy = vi.spyOn(fs.promises, 'mkdtemp'); diff --git a/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts index 8ab267e0d785..5a154ca8231a 100644 --- a/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/vite/delete-sourcemaps-after-upload.test.ts @@ -5,7 +5,7 @@ import { build, createBuilder } from 'vite'; import type { Plugin, ResolvedConfig } from 'vite'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { sentryVitePlugin } from '../../src/vite'; -import type { Options } from '../../src/core'; +import type { InternalOptions, Options } from '../../src/core'; const { mockSourcemapUpload } = vi.hoisted(() => ({ mockSourcemapUpload: vi.fn() })); @@ -70,7 +70,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { fs.rmSync(root, { recursive: true, force: true }); }); - function viteConfig(pluginOptions: Options, plugins: Plugin[] = []) { + function viteConfig(pluginOptions: InternalOptions, plugins: Plugin[] = []) { return { configFile: false as const, logLevel: 'silent' as const, @@ -203,6 +203,91 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { expectUploadedPairs(uploads[0]!, readChunks(outDir)); }); + it('keeps visible source maps an output enables when the option is true', async () => { + const config = viteConfig({ sourcemaps: { deleteSourcemapsAfterUpload: true } }); + await build({ + ...config, + build: { ...config.build, rollupOptions: { input: entry, output: { sourcemap: true } } }, + }); + + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toHaveLength(2); + }); + + it.each([true, 'hidden'] as const)( + 'removes `%s` source maps an output enables when the SDK turned source maps on', + async sourcemap => { + const config = viteConfig({ sourcemaps: { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true } }); + await build({ + ...config, + build: { ...config.build, rollupOptions: { input: entry, output: { sourcemap } } }, + }); + + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toEqual([]); + expect(uploads).toHaveLength(1); + expectUploadedPairs(uploads[0]!, readChunks(outDir)); + }, + ); + + it('removes hidden source maps when the option is true and no upload runs', async () => { + const config = viteConfig({ authToken: undefined, sourcemaps: { deleteSourcemapsAfterUpload: true } }); + await build({ ...config, build: { ...config.build, sourcemap: 'hidden' } }); + + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toEqual([]); + expect(uploads).toHaveLength(0); + }); + + it('reads the option from the internal function form when it decides', async () => { + let deleteMaps: boolean | undefined; + const sdkPlugin: Plugin = { + name: 'sdk', + config() { + deleteMaps = true; + return { build: { sourcemap: 'hidden' } }; + }, + }; + const config = viteConfig({}); + await build({ + ...config, + plugins: [ + sdkPlugin, + ...sentryVitePlugin({ ...credentials, sourcemaps: { deleteSourcemapsAfterUpload: () => deleteMaps } }), + ], + }); + + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toEqual([]); + expect(uploads).toHaveLength(1); + expectUploadedPairs(uploads[0]!, readChunks(outDir)); + }); + + it('removes the maps of ignored chunks and of CSS when the SDK turned the maps on', async () => { + let sdkEnabled: boolean | undefined; + const sdkPlugin: Plugin = { + name: 'sdk', + config() { + sdkEnabled = true; + return { build: { sourcemap: 'hidden' } }; + }, + generateBundle() { + this.emitFile({ type: 'asset', fileName: 'assets/style.css.map', source: '{"version":3,"mappings":""}' }); + }, + }; + const config = viteConfig( + { + sourcemaps: { + deleteSourcemapsAfterUpload: true, + sdkEnabledSourceMaps: () => sdkEnabled, + ignore: ['**/lazy-*'], + }, + }, + [sdkPlugin], + ); + await build(config); + + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toEqual([]); + expect(uploads).toHaveLength(1); + expect(Object.keys(uploads[0]!.files).filter(file => file.endsWith('.js'))).toHaveLength(1); + }); + it('keeps hidden source maps the user enabled and uploads them from disk', async () => { const config = viteConfig({}); await build({ ...config, build: { ...config.build, sourcemap: 'hidden' } }); @@ -328,6 +413,34 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (vite)', () => { expect(uploads).toHaveLength(2); }); + it('asks the function form per environment with its own setting', async () => { + const serverOutDir = path.join(root, 'dist-server'); + const askedFor: Array = []; + const builder = await createBuilder({ + ...viteConfig({ + sourcemaps: { + deleteSourcemapsAfterUpload: environment => { + askedFor.push(environment); + return environment === undefined ? true : undefined; + }, + }, + }), + build: { outDir, minify: false, sourcemap: 'hidden', rollupOptions: { input: entry } }, + environments: { + ssr: { + build: { outDir: serverOutDir, minify: false, sourcemap: 'hidden', rollupOptions: { input: entry } }, + }, + }, + builder: {}, + }); + await builder.buildApp(); + + expect(askedFor).toContain(undefined); + expect(askedFor).toContain('ssr'); + expect(listFiles(outDir).filter(file => file.endsWith('.map'))).toEqual([]); + expect(listFiles(serverOutDir).filter(file => file.endsWith('.map'))).toHaveLength(2); + }); + it('still restores debug IDs for "disable-upload" builds', async () => { const config = viteConfig({ sourcemaps: { disable: 'disable-upload' } }); await build({ ...config, build: { ...config.build, sourcemap: true } }); diff --git a/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts b/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts index 789f6d97d9d4..1982b1a34d9f 100644 --- a/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts +++ b/packages/bundler-plugins/test/webpack/delete-sourcemaps-after-upload.test.ts @@ -5,7 +5,7 @@ import { EntryPlugin, SourceMapDevToolPlugin, webpack } from 'webpack'; import type { Compiler, Configuration, Stats } from 'webpack'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { sentryWebpackPlugin } from '../../src/webpack/index'; -import type { Options } from '../../src/core'; +import type { InternalOptions, Options } from '../../src/core'; const { mockSourcemapUpload, mockReleaseCreate } = vi.hoisted(() => ({ mockSourcemapUpload: vi.fn(), @@ -98,7 +98,7 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (webpack)', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); - function config(pluginOptions: Options = {}, overrides: Configuration = {}): Configuration { + function config(pluginOptions: InternalOptions = {}, overrides: Configuration = {}): Configuration { return { mode: 'production', context: tmpDir, @@ -248,6 +248,20 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (webpack)', () => { expect(mkdtempSpy).not.toHaveBeenCalled(); }); + it('removes hidden source maps when the option is true and no upload runs', async () => { + const mkdtempSpy = vi.spyOn(fs.promises, 'mkdtemp'); + await build( + config( + { authToken: undefined, sourcemaps: { deleteSourcemapsAfterUpload: true } }, + { devtool: 'hidden-source-map' }, + ), + ); + + expect(fs.readdirSync(outDir)).toEqual(['bundle.js']); + expect(uploads).toHaveLength(0); + expect(mkdtempSpy).not.toHaveBeenCalled(); + }); + it('stages the final content of content-hashed bundles', async () => { const output = { path: outDir, filename: '[name].[contenthash].js' }; await build(config({}, { output })); @@ -444,6 +458,55 @@ describe('sourcemaps.deleteSourcemapsAfterUpload (webpack)', () => { expect(uploads).toHaveLength(1); }); + describe('with source maps the SDK turned on', () => { + const sdkSourcemaps = { deleteSourcemapsAfterUpload: true, sdkEnabledSourceMaps: true }; + + function sdkConfig(pluginOptions: InternalOptions): Configuration { + fs.writeFileSync(path.join(tmpDir, 'style.css'), 'body { color: red; }\n'); + fs.writeFileSync(path.join(tmpDir, 'entry.js'), "import './style.css';\nconsole.log(42);\n"); + fs.writeFileSync(path.join(tmpDir, 'vendor.js'), 'console.log("vendor");\n'); + return config(pluginOptions, { + devtool: 'hidden-source-map', + experiments: { css: true }, + entry: { bundle: './entry.js', vendor: './vendor.js' }, + output: { path: outDir, filename: '[name].js' }, + }); + } + + it('removes the maps of ignored chunks and of CSS after the upload', async () => { + await build(sdkConfig({ sourcemaps: { ...sdkSourcemaps, ignore: ['**/vendor.js'] } })); + + const files = fs.readdirSync(outDir); + expect(files.filter(file => file.endsWith('.map'))).toEqual([]); + expect(files.filter(file => file.endsWith('.css'))).toHaveLength(1); + expect(uploads).toHaveLength(1); + expectUploadedPair(uploads[0]!, fs.readFileSync(path.join(outDir, 'bundle.js'), 'utf8')); + expect(Object.keys(uploads[0]!.files)).toHaveLength(2); + }); + + it('removes all maps when no upload runs', async () => { + const mkdtempSpy = vi.spyOn(fs.promises, 'mkdtemp'); + await build(sdkConfig({ authToken: undefined, sourcemaps: { ...sdkSourcemaps, ignore: ['**/vendor.js'] } })); + + const files = fs.readdirSync(outDir); + expect(files.filter(file => file.endsWith('.map'))).toEqual([]); + expect(files.filter(file => file.endsWith('.css'))).toHaveLength(1); + expect(uploads).toHaveLength(0); + expect(mkdtempSpy).not.toHaveBeenCalled(); + }); + + it('keeps the maps when `deleteSourcemapsAfterUpload` is not true', async () => { + await build(sdkConfig({ sourcemaps: { sdkEnabledSourceMaps: true } })); + + expect( + fs + .readdirSync(outDir) + .filter(file => file.endsWith('.map')) + .sort(), + ).toEqual(['bundle.css.map', 'bundle.js.map', 'vendor.js.map']); + }); + }); + it('treats eval without source maps as turned off', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); await build(config({ silent: false }, { devtool: 'eval' })); diff --git a/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts b/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts index 130e38c086bc..ae924dec5edd 100644 --- a/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts +++ b/packages/core/src/build-time-plugins/buildTimeOptionsBase.ts @@ -208,6 +208,9 @@ export interface ReactComponentAnnotationOptions { } interface SourceMapsOptions { + // TODO(v12): Replace `disable` with separate options, for example + // `upload`, `debugIds` and `deleteSourcemapsAfterUpload`, so that one + // option no longer controls several features. /** * If this flag is `true`, any functionality related to source maps will be disabled. This includes the automatic upload of source maps. * @@ -261,6 +264,10 @@ interface SourceMapsOptions { * `sourcemaps.assets` or `sourcemaps.ignore` keep out of the upload. Source maps you enabled yourself are only * removed for the JavaScript chunks that were uploaded; excluded chunks keep theirs. * + * `true` removes source maps you enabled yourself even when no upload runs, for example without an auth token. + * With `sourcemaps.disable` set, the plugin keeps them for a manual upload and warns. The plugin does not turn + * source maps on when it cannot upload them. + * * With webpack's array form of `devtool`, `true` replaces the array with one hidden source map setting for * all asset types, because webpack hides the array from plugins. */ From c7d73e48cdc48c617f40137f2da8e20cda567a44 Mon Sep 17 00:00:00 2001 From: Andrei <168741329+andreiborza@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:11:00 +0100 Subject: [PATCH 080/136] feat(server-utils): Record Bedrock prompts, system instructions, and tool definitions (#26249) ## What Bedrock `Converse`, `ConverseStream`, `InvokeModel`, and `InvokeModelWithResponseStream` spans now record the input messages, system instructions, and tool definitions. Claude request bodies are recorded like the Anthropic integration records them, and `dataCollection.genAI.inputs` turns this off. Extracted from #26118. ## Why Other AI integrations already record their inputs, so Bedrock spans showed less in the AI views. --------- Co-authored-by: Claude Opus 5.5 --- .../bedrock/instrument-gen-ai.mjs | 9 + .../aws-serverless/bedrock/scenario.mjs | 5 + .../suites/aws-serverless/bedrock/test.ts | 28 ++++ .../server-utils/src/ai/anthropic-ai/index.ts | 4 +- .../server-utils/src/ai/anthropic-ai/utils.ts | 17 +- .../services/bedrock-runtime-content.ts | 158 ++++++++++++++++++ .../aws-sdk/services/bedrock-runtime.ts | 22 ++- .../test/ai/lib/utils/anthropic-utils.test.ts | 28 +--- .../test/integrations/aws-sdk-bedrock.test.ts | 154 ++++++++++++++++- 9 files changed, 387 insertions(+), 38 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/aws-serverless/bedrock/instrument-gen-ai.mjs create mode 100644 packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts diff --git a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/instrument-gen-ai.mjs b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/instrument-gen-ai.mjs new file mode 100644 index 000000000000..fe1c5c47983f --- /dev/null +++ b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/instrument-gen-ai.mjs @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/aws-serverless'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + transport: loggingTransport, +}); diff --git a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/scenario.mjs b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/scenario.mjs index c1705ff0d403..14f377347a47 100644 --- a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/scenario.mjs +++ b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/scenario.mjs @@ -33,7 +33,11 @@ async function converse() { await client.send( new ConverseCommand({ modelId: 'anthropic.claude-3-5-sonnet-20240620-v1:0', + system: [{ text: 'You are a weather bot.' }], messages: [{ role: 'user', content: [{ text: 'Hello' }] }], + toolConfig: { + tools: [{ toolSpec: { name: 'get_weather', inputSchema: { json: { type: 'object' } } } }], + }, inferenceConfig: { maxTokens: 100, temperature: 0.5, topP: 0.9 }, }), ); @@ -68,6 +72,7 @@ async function invokeModel() { max_tokens: 100, temperature: 0.5, top_p: 0.9, + system: 'You are a weather bot.', messages: [{ role: 'user', content: 'Hello' }], }), }), diff --git a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts index c028dbc686d7..dd9867391034 100644 --- a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts +++ b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts @@ -1,4 +1,5 @@ import { + GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MAX_TOKENS, @@ -7,6 +8,8 @@ import { GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_STREAMING, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, SENTRY_OP, @@ -54,6 +57,25 @@ function assertBedrockSpans(container: SerializedStreamedSpanContainer): void { expect(invokeModelSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["end_turn"]'); } +const SYSTEM_INSTRUCTIONS = JSON.stringify([{ type: 'text', content: 'You are a weather bot.' }]); + +function assertBedrockInputs(container: SerializedStreamedSpanContainer): void { + const converseSpan = container.items.find(span => span.name === `chat ${MODEL_ID}`); + expect(converseSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(SYSTEM_INSTRUCTIONS); + expect(converseSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( + JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]), + ); + expect(converseSpan!.attributes[GEN_AI_TOOL_DEFINITIONS].value).toBe( + JSON.stringify([{ name: 'get_weather', inputSchema: { json: { type: 'object' } } }]), + ); + + const invokeModelSpan = container.items.find(span => span.name === `generate_content ${MODEL_ID}`); + expect(invokeModelSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe(SYSTEM_INSTRUCTIONS); + expect(invokeModelSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( + JSON.stringify([{ role: 'user', content: 'Hello' }]), + ); +} + function assertStreamSpans(container: SerializedStreamedSpanContainer): void { const converseStreamSpan = container.items.find(span => span.name === `chat ${MODEL_ID}`); expect(converseStreamSpan!.status).toBe('ok'); @@ -90,6 +112,12 @@ describe('awsIntegration - Bedrock', () => { }); }); + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-gen-ai.mjs', (createTestRunner, test) => { + test('records Bedrock inputs by default', { timeout: 90_000 }, async () => { + await createTestRunner().ignore('event').expect({ span: assertBedrockInputs }).start().completed(); + }); + }); + createEsmAndCjsTests(__dirname, 'scenario-stream.mjs', 'instrument.mjs', (createTestRunner, test) => { test('ends Bedrock stream spans when the streams finish, fail, or are aborted', { timeout: 90_000 }, async () => { await createTestRunner().ignore('event').expect({ span: assertStreamSpans }).start().completed(); diff --git a/packages/server-utils/src/ai/anthropic-ai/index.ts b/packages/server-utils/src/ai/anthropic-ai/index.ts index 5723adf1fde3..6b4f7d357ce6 100644 --- a/packages/server-utils/src/ai/anthropic-ai/index.ts +++ b/packages/server-utils/src/ai/anthropic-ai/index.ts @@ -29,7 +29,7 @@ import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants'; import { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming'; import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner'; import type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types'; -import { handleResponseError, messagesFromParams, setMessagesAttribute } from './utils'; +import { getMessagesAttributes, handleResponseError, messagesFromParams } from './utils'; // Set only while a streaming helper (e.g. `messages.stream()`) synchronously delegates to the // underlying `create`. The SDK invokes that internal `create` synchronously, so a plain flag @@ -80,7 +80,7 @@ export function extractRequestAttributes( */ export function addPrivateRequestAttributes(span: Span, params: Record): void { const messages = messagesFromParams(params); - setMessagesAttribute(span, messages); + span.setAttributes(getMessagesAttributes(messages)); } /** diff --git a/packages/server-utils/src/ai/anthropic-ai/utils.ts b/packages/server-utils/src/ai/anthropic-ai/utils.ts index 65001dba746c..491b357d79a7 100644 --- a/packages/server-utils/src/ai/anthropic-ai/utils.ts +++ b/packages/server-utils/src/ai/anthropic-ai/utils.ts @@ -5,24 +5,21 @@ import { extractSystemInstructions } from '../core/utils'; import type { AnthropicAiResponse } from './types'; /** - * Set the input messages attribute, extracting system instructions into their own attribute. + * Get the input messages attribute, with system instructions extracted into their own attribute. */ -export function setMessagesAttribute(span: Span, messages: unknown): void { +export function getMessagesAttributes(messages: unknown): Record { if (Array.isArray(messages) && messages.length === 0) { - return; + return {}; } const { systemInstructions, filteredMessages } = extractSystemInstructions(messages); + const attributes: Record = {}; if (systemInstructions) { - span.setAttributes({ - [GEN_AI_SYSTEM_INSTRUCTIONS]: systemInstructions, - }); + attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = systemInstructions; } - - span.setAttributes({ - [GEN_AI_INPUT_MESSAGES]: stringify(filteredMessages), - }); + attributes[GEN_AI_INPUT_MESSAGES] = stringify(filteredMessages); + return attributes; } const ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record = { diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts new file mode 100644 index 000000000000..b38068553f21 --- /dev/null +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts @@ -0,0 +1,158 @@ +import { isObjectLike, stringify } from '@sentry/core'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, +} from '@sentry/conventions/attributes'; +import { getMessagesAttributes, messagesFromParams } from '../../../ai/anthropic-ai/utils'; +import type { GenAiMessagePart } from '../../../ai/types'; + +/** + * Translate Converse `ContentBlock`s (also used by Amazon Nova `InvokeModel` bodies) into message parts. + * The conventions require a `type` on each part, and Bedrock's blocks (`{ text }`, `{ toolUse }`, ...) have none. + * + * Media is reported by modality only: inline media is raw bytes, which the conventions require to be + * dropped rather than recorded. Blocks without content worth recording (`cachePoint`, redacted + * reasoning, unknown members) are left out rather than serialized, so no binary payload slips through. + */ +function contentBlocksToParts(content: unknown): GenAiMessagePart[] { + return Array.isArray(content) ? content.flatMap(contentBlockToParts) : []; +} + +function contentBlockToParts(block: unknown): GenAiMessagePart[] { + if (!isObjectLike(block)) { + return []; + } + + if (typeof block.text === 'string') { + return [{ type: 'text', content: block.text }]; + } + + const { toolUse, toolResult, reasoningContent, guardContent, citationsContent } = block; + + if (isObjectLike(toolUse)) { + return [ + { + type: 'tool_call', + id: toolUse.toolUseId, + name: toolUse.name, + arguments: stringify(toolUse.input ?? {}, String), + }, + ]; + } + + if (isObjectLike(toolResult)) { + return [{ type: 'tool_call_response', id: toolResult.toolUseId, result: toolResultToString(toolResult.content) }]; + } + + if (isObjectLike(reasoningContent)) { + const reasoningText = reasoningContent.reasoningText; + return isObjectLike(reasoningText) && typeof reasoningText.text === 'string' + ? [{ type: 'reasoning', content: reasoningText.text }] + : []; + } + + if (isObjectLike(guardContent)) { + // `guardContent.text` is a `{ text }` block, `guardContent.image` an image block. + return contentBlockToParts(isObjectLike(guardContent.text) ? guardContent.text : guardContent); + } + + if (isObjectLike(citationsContent)) { + return contentBlocksToParts(citationsContent.content); + } + + for (const modality of ['image', 'video', 'audio', 'document']) { + const media = block[modality]; + if (isObjectLike(media)) { + // Only image formats (`png`, ...) map to a MIME type by prefix; `undefined` is left out of the JSON. + const format = modality === 'image' && typeof media.format === 'string' ? `image/${media.format}` : undefined; + return [{ type: 'blob', modality, mime_type: format }]; + } + } + + return []; +} + +function toolResultToString(content: unknown): string { + if (!Array.isArray(content)) { + return ''; + } + + return content + .map(block => { + if (!isObjectLike(block)) { + return undefined; + } + if (typeof block.text === 'string') { + return block.text; + } + return block.json !== undefined ? stringify(block.json, String) : undefined; + }) + .filter((text): text is string => text !== undefined) + .join('\n'); +} + +function converseMessagesToMessages(messages: unknown): Array<{ role: string; parts: GenAiMessagePart[] }> { + if (!Array.isArray(messages)) { + return []; + } + + return messages + .filter(isObjectLike) + .map(message => ({ + role: typeof message.role === 'string' ? message.role : 'user', + parts: contentBlocksToParts(message.content), + })) + .filter(message => message.parts.length > 0); +} + +/** + * Input attributes of a Converse-shaped request (`Converse`, `ConverseStream`, and Amazon Nova + * `InvokeModel` bodies, which use the same `messages`/`system`/`toolConfig` shape). + */ +export function getConverseInputAttributes(input: Record): Record { + const attributes: Record = {}; + + const systemInstructions = contentBlocksToParts(input.system); + if (systemInstructions.length) { + attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = JSON.stringify(systemInstructions); + } + + const messages = converseMessagesToMessages(input.messages); + if (messages.length) { + attributes[GEN_AI_INPUT_MESSAGES] = JSON.stringify(messages); + } + + const toolConfig = input.toolConfig; + if (isObjectLike(toolConfig) && Array.isArray(toolConfig.tools)) { + // `cachePoint` entries share the list with the `toolSpec`s; they are not tools. + const toolSpecs = toolConfig.tools + .map(tool => (isObjectLike(tool) ? tool.toolSpec : undefined)) + .filter(isObjectLike); + if (toolSpecs.length) { + attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(toolSpecs); + } + } + + return attributes; +} + +/** + * Claude `InvokeModel` bodies are Anthropic Messages API requests, so they are recorded like the Anthropic + * integration records them. + */ +export function getClaudeInputAttributes(body: Record): Record { + const attributes = getMessagesAttributes(messagesFromParams(body)); + if (Array.isArray(body.tools)) { + attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(body.tools); + } + return attributes; +} + +/** Input attributes of the single-prompt `InvokeModel` bodies (Titan, Llama, Cohere, Mistral, ...). */ +export function getPromptInputAttributes(prompt: unknown): Record { + if (typeof prompt !== 'string') { + return {}; + } + return { [GEN_AI_INPUT_MESSAGES]: JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: prompt }] }]) }; +} diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts index d834dc09c2e9..f77e04f6f5ed 100644 --- a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts @@ -14,7 +14,7 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op'; import type { StreamResponseState } from '../../../ai/core/utils'; -import { endStreamSpan, getTokenUsageAttributes } from '../../../ai/core/utils'; +import { endStreamSpan, getTokenUsageAttributes, resolveAIRecordingOptions } from '../../../ai/core/utils'; import { isInsidePiAiSpan } from '../../../ai/pi-ai/providers'; import { DEBUG_BUILD } from '../../../debug-build'; import { @@ -23,6 +23,11 @@ import { GEN_AI_SYSTEM_VALUE_AWS_BEDROCK, } from '../constants'; import type { NormalizedRequest, NormalizedResponse } from '../types'; +import { + getClaudeInputAttributes, + getConverseInputAttributes, + getPromptInputAttributes, +} from './bedrock-runtime-content'; import type { RequestMetadata, ServiceExtension } from './ServiceExtension'; // Simplified types inlined from @aws-sdk/client-bedrock-runtime @@ -134,6 +139,10 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { } } + if (resolveAIRecordingOptions().recordInputs) { + Object.assign(spanAttributes, getConverseInputAttributes(request.commandInput)); + } + return { spanName, spanOp: GEN_AI_CHAT, @@ -258,6 +267,10 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { spanAttributes[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = requestBody.stop; } } + + if (resolveAIRecordingOptions().recordInputs) { + Object.assign(spanAttributes, getInvokeModelInputAttributes(modelId, requestBody)); + } } return { @@ -412,6 +425,13 @@ export class BedrockRuntimeServiceExtension implements ServiceExtension { } } +function getInvokeModelInputAttributes(modelId: string, requestBody: ParsedChunk): Record { + if (modelId.includes('amazon.nova')) return getConverseInputAttributes(requestBody); + if (modelId.includes('anthropic.claude')) return getClaudeInputAttributes(requestBody); + // The other families send one prompt string: Titan as `inputText`, Cohere Command R as `message`. + return getPromptInputAttributes(requestBody.inputText ?? requestBody.message ?? requestBody.prompt); +} + type StreamProcessor = (parsedChunk: ParsedChunk, state: StreamResponseState) => void; function resolveStreamProcessor(modelId: string): StreamProcessor | undefined { diff --git a/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts b/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts index 591c5ae004a0..e6eae3860949 100644 --- a/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts +++ b/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts @@ -1,10 +1,9 @@ import { describe, expect, it } from 'vitest'; import { + getMessagesAttributes, mapAnthropicErrorToStatusMessage, messagesFromParams, - setMessagesAttribute, } from '../../../../src/ai/anthropic-ai/utils'; -import type { Span } from '@sentry/core'; describe('anthropic-ai-utils', () => { describe('mapAnthropicErrorToStatusMessage', () => { @@ -98,32 +97,15 @@ describe('anthropic-ai-utils', () => { }); }); - describe('setMessagesAtribute', () => { - const mock = { - attributes: {} as Record, - setAttributes(kv: Record) { - for (const [key, val] of Object.entries(kv)) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - if (val === undefined) delete this.attributes[key]; - else this.attributes[key] = val; - } - }, - }; - const span = mock as unknown as Span; - - it('sets the input messages attribute', () => { - setMessagesAttribute(span, [{ role: 'user', content: 'hello, world' }]); - expect(mock.attributes).toStrictEqual({ + describe('getMessagesAttributes', () => { + it('returns the input messages attribute', () => { + expect(getMessagesAttributes([{ role: 'user', content: 'hello, world' }])).toStrictEqual({ 'gen_ai.input.messages': '[{"role":"user","content":"hello, world"}]', }); }); it('ignores empty array', () => { - setMessagesAttribute(span, [{ role: 'user', content: 'hello, world' }]); - const before = { ...mock.attributes }; - - setMessagesAttribute(span, []); - expect(mock.attributes).toStrictEqual(before); + expect(getMessagesAttributes([])).toStrictEqual({}); }); }); }); diff --git a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts index e7fbf41d50d0..3367410fc0f0 100644 --- a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts +++ b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts @@ -1,10 +1,13 @@ import { + GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, @@ -28,14 +31,18 @@ const CLAUDE_REQUEST_BODY = { messages: [{ role: 'user', content: 'What is the capital of France?' }], }; -function invokeModelPreSpanHook(commandInput: Record): RequestMetadata { +function preSpanHook(commandName: string, commandInput: Record): RequestMetadata { return new BedrockRuntimeServiceExtension().requestPreSpanHook({ serviceName: 'BedrockRuntime', - commandName: 'InvokeModel', + commandName, commandInput, }); } +function invokeModelPreSpanHook(commandInput: Record): RequestMetadata { + return preSpanHook('InvokeModel', commandInput); +} + describe('BedrockRuntimeServiceExtension InvokeModel request', () => { it('reads a request body passed as bytes', () => { const body = new TextEncoder().encode(JSON.stringify(CLAUDE_REQUEST_BODY)); @@ -48,6 +55,7 @@ describe('BedrockRuntimeServiceExtension InvokeModel request', () => { [GEN_AI_REQUEST_MODEL]: CLAUDE_MODEL_ID, [GEN_AI_REQUEST_MAX_TOKENS]: 1024, [GEN_AI_REQUEST_TEMPERATURE]: 0.5, + [GEN_AI_INPUT_MESSAGES]: JSON.stringify(CLAUDE_REQUEST_BODY.messages), }); }); @@ -81,6 +89,148 @@ describe('BedrockRuntimeServiceExtension InvokeModel request', () => { }); }); +const WEATHER_TOOL_SPEC = { + name: 'get_weather', + description: 'Get the weather for a city', + inputSchema: { json: { type: 'object', properties: { city: { type: 'string' } } } }, +}; + +describe('BedrockRuntimeServiceExtension input recording', () => { + afterEach(() => { + setCurrentClient(undefined as never); + }); + + it('records Converse system instructions, messages, and tool definitions as message parts', () => { + const { spanAttributes } = preSpanHook('Converse', { + modelId: 'amazon.nova-pro-v1:0', + system: [{ text: 'You are a weather bot.' }, { cachePoint: { type: 'default' } }], + messages: [ + { + role: 'user', + content: [ + { text: 'What is the weather in Kawasaki?' }, + { image: { format: 'png', source: { bytes: new Uint8Array([1, 2, 3]) } } }, + { image: { source: { bytes: new Uint8Array([1]) } } }, + { document: { name: 'forecast', source: { bytes: new Uint8Array([1]) } } }, + { guardContent: { text: { text: 'Guarded text' } } }, + { guardContent: { image: { format: 'jpeg', source: { bytes: new Uint8Array([1]) } } } }, + { cachePoint: { type: 'default' } }, + ], + }, + { + role: 'assistant', + content: [ + { reasoningContent: { reasoningText: { text: 'I need the weather tool.' } } }, + { reasoningContent: { redactedContent: new Uint8Array([1]) } }, + { toolUse: { toolUseId: 'tooluse_1', name: 'get_weather', input: { city: 'Kawasaki' } } }, + ], + }, + { + role: 'user', + content: [ + { + toolResult: { + toolUseId: 'tooluse_1', + content: [{ text: 'Sunny' }, { json: { celsius: 21 } }, { image: { format: 'png' } }], + }, + }, + { citationsContent: { content: [{ text: 'Cited text' }] } }, + ], + }, + { role: 'user', content: [{ cachePoint: { type: 'default' } }] }, + ], + toolConfig: { tools: [{ toolSpec: WEATHER_TOOL_SPEC }, { cachePoint: { type: 'default' } }] }, + }); + + expect(spanAttributes).toEqual({ + [GEN_AI_PROVIDER_NAME]: 'aws.bedrock', + [GEN_AI_OPERATION_NAME]: 'chat', + [GEN_AI_REQUEST_MODEL]: 'amazon.nova-pro-v1:0', + [GEN_AI_SYSTEM_INSTRUCTIONS]: JSON.stringify([{ type: 'text', content: 'You are a weather bot.' }]), + [GEN_AI_INPUT_MESSAGES]: JSON.stringify([ + { + role: 'user', + parts: [ + { type: 'text', content: 'What is the weather in Kawasaki?' }, + { type: 'blob', modality: 'image', mime_type: 'image/png' }, + { type: 'blob', modality: 'image' }, + { type: 'blob', modality: 'document' }, + { type: 'text', content: 'Guarded text' }, + { type: 'blob', modality: 'image', mime_type: 'image/jpeg' }, + ], + }, + { + role: 'assistant', + parts: [ + { type: 'reasoning', content: 'I need the weather tool.' }, + { type: 'tool_call', id: 'tooluse_1', name: 'get_weather', arguments: '{"city":"Kawasaki"}' }, + ], + }, + { + role: 'user', + parts: [ + { type: 'tool_call_response', id: 'tooluse_1', result: 'Sunny\n{"celsius":21}' }, + { type: 'text', content: 'Cited text' }, + ], + }, + ]), + [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify([WEATHER_TOOL_SPEC]), + }); + }); + + it('records Claude InvokeModel system instructions, messages, and tool definitions like the Anthropic integration', () => { + const tools = [{ name: 'get_weather', input_schema: { type: 'object' } }]; + const messages = [{ role: 'user', content: [{ type: 'text', text: 'What is the weather in Kawasaki?' }] }]; + const body = { system: [{ type: 'text', text: 'You are a weather bot.' }], messages, tools }; + + const { spanAttributes } = invokeModelPreSpanHook({ modelId: CLAUDE_MODEL_ID, body: JSON.stringify(body) }); + + expect(spanAttributes).toEqual({ + [GEN_AI_PROVIDER_NAME]: 'aws.bedrock', + [GEN_AI_OPERATION_NAME]: 'generate_content', + [GEN_AI_REQUEST_MODEL]: CLAUDE_MODEL_ID, + [GEN_AI_SYSTEM_INSTRUCTIONS]: JSON.stringify([{ type: 'text', content: 'You are a weather bot.' }]), + [GEN_AI_INPUT_MESSAGES]: JSON.stringify(messages), + [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify(tools), + }); + }); + + it.each([ + { family: 'Titan', modelId: 'amazon.titan-text-express-v1', body: { inputText: 'Kawasaki' } }, + { family: 'Llama', modelId: 'meta.llama3-8b-instruct-v1:0', body: { prompt: 'Kawasaki' } }, + { family: 'Cohere Command R', modelId: 'cohere.command-r-v1:0', body: { message: 'Kawasaki' } }, + { family: 'Cohere Command', modelId: 'cohere.command-text-v14', body: { prompt: 'Kawasaki' } }, + { family: 'Mistral', modelId: 'mistral.mistral-7b-instruct-v0:2', body: { prompt: 'Kawasaki' } }, + { + family: 'Nova', + modelId: 'amazon.nova-lite-v1:0', + body: { messages: [{ role: 'user', content: [{ text: 'Kawasaki' }] }] }, + }, + ])('records the $family InvokeModel prompt as a user message', ({ modelId, body }) => { + const { spanAttributes } = invokeModelPreSpanHook({ modelId, body: JSON.stringify(body) }); + + expect(spanAttributes?.[GEN_AI_INPUT_MESSAGES]).toBe( + JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Kawasaki' }] }]), + ); + }); + + it.each([ + { commandName: 'Converse', commandInput: { messages: [{ role: 'user', content: [{ text: 'Kawasaki' }] }] } }, + { + commandName: 'InvokeModel', + commandInput: { modelId: CLAUDE_MODEL_ID, body: JSON.stringify(CLAUDE_REQUEST_BODY) }, + }, + ])('records no $commandName input when dataCollection.genAI.inputs is off', ({ commandName, commandInput }) => { + const client = new TestClient(getDefaultTestClientOptions({ dataCollection: { genAI: { inputs: false } } })); + setCurrentClient(client); + client.init(); + + const { spanAttributes } = preSpanHook(commandName, commandInput); + + expect(spanAttributes).not.toHaveProperty(GEN_AI_INPUT_MESSAGES); + }); +}); + const STREAM_COMMANDS = [ { commandName: 'ConverseStream', streamField: 'stream' }, { commandName: 'InvokeModelWithResponseStream', streamField: 'body' }, From 97b275d72b3731f3832b0204aaaf1d37046014b3 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:37:21 +0100 Subject: [PATCH 081/136] fix(server-utils): Use the client's provider name for Anthropic platform clients (#26119) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** `AnthropicBedrock` (`@anthropic-ai/bedrock-sdk`) extends `BaseAnthropic` and builds its `messages` from `@anthropic-ai/sdk`'s own `Messages` class. Our orchestrion hooks on that file already trace it, with prompts, responses, and usage, and with no duplicate native OTel span. I checked this against the real `@anthropic-ai/bedrock-sdk@1.1.1`. The one gap was that the spans said `gen_ai.provider.name: anthropic`. The SDK stores the platform on the client as `_genAIProviderName` (`aws.bedrock` on Bedrock). This reads that value from the resource's client and falls back to `anthropic`. **How to review:** The change is in `getProviderName` and its two call sites. The integration scenario subclasses `Anthropic` and sets `_genAIProviderName` the same way `AnthropicBedrock` does, so no new dev dependency is needed. **Unsure about:** `_genAIProviderName` is marked `@internal` in the SDK. bedrock-sdk sets it from 0.35.0 on; 0.34.4 and earlier keep reporting `anthropic`. Only the Bedrock clients (`AnthropicBedrock`, `AnthropicBedrockMantle` → `aws.bedrock`) and Vertex (`gcp.vertex_ai`) set it. `AnthropicFoundry` and `AnthropicAws` don't, so they still report `anthropic`. Closes #19154 via @sergical. -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A66186d788a1c1871f4c4c595b090855b) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A66186d788a1c1871f4c4c595b090855b/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: David Cramer <23610+dcramer@users.noreply.github.com> --- .../anthropic/v1/scenario-platform-client.mjs | 55 +++++++++++++++++++ .../suites/tracing/anthropic/v1/test.ts | 16 ++++++ .../server-utils/src/ai/anthropic-ai/index.ts | 12 +++- .../server-utils/src/ai/anthropic-ai/utils.ts | 10 ++++ .../src/integrations/anthropic.ts | 3 +- .../test/ai/lib/tracing/anthropic-ai.test.ts | 36 ++++++++++++ .../test/ai/lib/utils/anthropic-utils.test.ts | 18 ++++++ 7 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-platform-client.mjs diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-platform-client.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-platform-client.mjs new file mode 100644 index 000000000000..44d6ab87f579 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-platform-client.mjs @@ -0,0 +1,55 @@ +import Anthropic from '@anthropic-ai/sdk'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +// `AnthropicBedrock` (`@anthropic-ai/bedrock-sdk`) is a `BaseAnthropic` subclass that names its platform this way +// and reuses the SDK's `Messages` resource. +class BedrockClient extends Anthropic { + constructor(options) { + super(options); + this._genAIProviderName = 'aws.bedrock'; + } +} + +function startMockServer() { + const app = express(); + app.use(express.json()); + + app.post('/v1/messages', (req, res) => { + res.json({ + id: 'msg_bedrock', + type: 'message', + role: 'assistant', + model: req.body.model, + content: [{ type: 'text', text: 'Hello!' }], + stop_reason: 'end_turn', + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 15 }, + }); + }); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +async function run() { + const server = await startMockServer(); + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + const client = new BedrockClient({ apiKey: 'mock-api-key', baseURL: `http://localhost:${server.address().port}` }); + await client.messages.create({ + model: 'anthropic.claude-3-5-sonnet-20240620-v1:0', + max_tokens: 100, + messages: [{ role: 'user', content: 'Hello' }], + }); + }); + + await Sentry.flush(2000); + + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts index afda0052828f..14ae36fa4292 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts @@ -1,6 +1,7 @@ import type { Event, SerializedStreamedSpanContainer } from '@sentry/core'; import { GEN_AI_CONVERSATION_ID, + GEN_AI_PROVIDER_NAME, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, @@ -289,4 +290,19 @@ describe('Anthropic integration (1.x)', () => { }); } }); + + createEsmAndCjsTests(__dirname, 'scenario-platform-client.mjs', 'instrument.mjs', (createRunner, test) => { + test('uses the provider name of a platform client such as AnthropicBedrock', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const chatSpan = spanForCall(container.items, 'msg_bedrock'); + expect(chatSpan.attributes[GEN_AI_PROVIDER_NAME]?.value).toBe('aws.bedrock'); + }, + }) + .start() + .completed(); + }); + }); }); diff --git a/packages/server-utils/src/ai/anthropic-ai/index.ts b/packages/server-utils/src/ai/anthropic-ai/index.ts index 6b4f7d357ce6..eea9820cd329 100644 --- a/packages/server-utils/src/ai/anthropic-ai/index.ts +++ b/packages/server-utils/src/ai/anthropic-ai/index.ts @@ -29,7 +29,7 @@ import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants'; import { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming'; import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner'; import type { AnthropicAiOptions, AnthropicAiResponse, AnthropicAiStreamingEvent, ContentBlock } from './types'; -import { getMessagesAttributes, handleResponseError, messagesFromParams } from './utils'; +import { getMessagesAttributes, getProviderName, handleResponseError, messagesFromParams } from './utils'; // Set only while a streaming helper (e.g. `messages.stream()`) synchronously delegates to the // underlying `create`. The SDK invokes that internal `create` synchronously, so a plain flag @@ -47,9 +47,10 @@ export function extractRequestAttributes( args: unknown[], operationName: string, recordInputs: boolean, + providerName = 'anthropic', ): Record { const attributes: Record = { - [GEN_AI_PROVIDER_NAME]: 'anthropic', + [GEN_AI_PROVIDER_NAME]: providerName, [GEN_AI_OPERATION_NAME]: operationName, [SENTRY_ORIGIN]: ANTHROPIC_AI_ORIGIN, }; @@ -261,7 +262,12 @@ function instrumentMethod( } const operationName = instrumentedMethod.operation || 'unknown'; - const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs); + const requestAttributes = extractRequestAttributes( + args, + operationName, + !!options.recordInputs, + getProviderName(invocationThis), + ); const model = requestAttributes[GEN_AI_REQUEST_MODEL] || 'unknown'; const client = getClient(); // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality. diff --git a/packages/server-utils/src/ai/anthropic-ai/utils.ts b/packages/server-utils/src/ai/anthropic-ai/utils.ts index 491b357d79a7..4aa0a35972e6 100644 --- a/packages/server-utils/src/ai/anthropic-ai/utils.ts +++ b/packages/server-utils/src/ai/anthropic-ai/utils.ts @@ -4,6 +4,16 @@ import { GEN_AI_INPUT_MESSAGES, GEN_AI_SYSTEM_INSTRUCTIONS } from '@sentry/conve import { extractSystemInstructions } from '../core/utils'; import type { AnthropicAiResponse } from './types'; +/** + * The `gen_ai.provider.name` of the client that owns an SDK resource such as `messages`. The SDK's clients + * for other platforms set their own, e.g. `aws.bedrock` for `AnthropicBedrock`. + */ +export function getProviderName(resource: unknown): string { + const name = (resource as { _client?: { _genAIProviderName?: unknown } } | null | undefined)?._client + ?._genAIProviderName; + return typeof name === 'string' && name ? name : 'anthropic'; +} + /** * Get the input messages attribute, with system instructions extracted into their own attribute. */ diff --git a/packages/server-utils/src/integrations/anthropic.ts b/packages/server-utils/src/integrations/anthropic.ts index 4dfbff811c52..7b9251342c5c 100644 --- a/packages/server-utils/src/integrations/anthropic.ts +++ b/packages/server-utils/src/integrations/anthropic.ts @@ -6,6 +6,7 @@ import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai'; import { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants'; +import { getProviderName } from '../ai/anthropic-ai/utils'; import { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming'; import { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner'; import type { AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types'; @@ -134,7 +135,7 @@ function createGenAiSpan( const { recordInputs } = resolveAIRecordingOptions(options); - const attributes = extractRequestAttributes(args, operation, recordInputs); + const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self)); const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown'; attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN; const client = getClient(); diff --git a/packages/server-utils/test/ai/lib/tracing/anthropic-ai.test.ts b/packages/server-utils/test/ai/lib/tracing/anthropic-ai.test.ts index 1a08d660ab7d..18799c8e871d 100644 --- a/packages/server-utils/test/ai/lib/tracing/anthropic-ai.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/anthropic-ai.test.ts @@ -89,3 +89,39 @@ describe('instrumentAnthropicAiClient span names', () => { expect(spanToStaticSpanJSON(endedSpans[0]!).description).toBe('chat'); }); }); + +describe('instrumentAnthropicAiClient provider name', () => { + beforeEach(() => { + getMainCarrier().__SENTRY__ = undefined; + }); + + afterEach(() => { + getMainCarrier().__SENTRY__ = undefined; + }); + + it.each([ + { name: 'uses the provider name of a platform client', providerName: 'aws.bedrock', expected: 'aws.bedrock' }, + { name: 'falls back to anthropic', providerName: undefined, expected: 'anthropic' }, + ])('$name', async ({ providerName, expected }) => { + const client = new TestClient( + getDefaultTestClientOptions({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }), + ); + setCurrentClient(client); + client.init(); + const endedSpans: Span[] = []; + client.on('spanEnd', span => endedSpans.push(span)); + + const anthropic = { + _genAIProviderName: providerName, + messages: { create: vi.fn().mockResolvedValue({ id: 'msg', content: [] }) } as Record, + }; + anthropic.messages._client = anthropic; + + await instrumentAnthropicAiClient(anthropic).messages.create({ + model: 'anthropic.claude-3-5-sonnet-20240620-v1:0', + messages: [{ role: 'user', content: 'Hello' }], + }); + + expect(spanToStaticSpanJSON(endedSpans[0]!).data['gen_ai.provider.name']).toBe(expected); + }); +}); diff --git a/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts b/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts index e6eae3860949..f60992f7e78d 100644 --- a/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts +++ b/packages/server-utils/test/ai/lib/utils/anthropic-utils.test.ts @@ -1,11 +1,29 @@ import { describe, expect, it } from 'vitest'; import { getMessagesAttributes, + getProviderName, mapAnthropicErrorToStatusMessage, messagesFromParams, } from '../../../../src/ai/anthropic-ai/utils'; describe('anthropic-ai-utils', () => { + describe('getProviderName', () => { + it('reads the provider name of the client that owns the resource', () => { + expect(getProviderName({ _client: { _genAIProviderName: 'aws.bedrock' } })).toBe('aws.bedrock'); + }); + + it.each([ + undefined, + null, + {}, + { _client: {} }, + { _client: { _genAIProviderName: '' } }, + { _client: { _genAIProviderName: 1 } }, + ])('falls back to anthropic for %j', resource => { + expect(getProviderName(resource)).toBe('anthropic'); + }); + }); + describe('mapAnthropicErrorToStatusMessage', () => { it('maps known Anthropic error types to SpanStatusType values', () => { expect(mapAnthropicErrorToStatusMessage('invalid_request_error')).toBe('invalid_argument'); From f94f11e4c92376574232462dbf577ace1882c772 Mon Sep 17 00:00:00 2001 From: Sigrid <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:50:53 +0100 Subject: [PATCH 082/136] test(nextjs): Cover the server request link of a late trace meta tag (#26357) ## What Adds an E2E test to both Cache Components apps for a trace meta tag that streams in after the pageload stopped waiting for it. The test checks that the pageload keeps its own trace and links the server request with a `server_request` link. ## Why Until now, only unit tests with fake timers and a hand-written meta tag covered this case. This test runs it against a real streamed response from a production build. The page waits 10.5 seconds: longer than the pageload's 10-second wait, but short enough that the tag arrives before the pageload ends. --- .../app/slow-stream/page.tsx | 20 +++++++++++++ .../cacheOrigin-pageloadConnection.spec.ts | 30 +++++++++++++++++++ .../app/slow-stream/page.tsx | 20 +++++++++++++ .../cacheOrigin-pageloadConnection.spec.ts | 30 +++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/app/slow-stream/page.tsx create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/app/slow-stream/page.tsx diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/app/slow-stream/page.tsx b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/app/slow-stream/page.tsx new file mode 100644 index 000000000000..478ac04626a6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/app/slow-stream/page.tsx @@ -0,0 +1,20 @@ +import { headers } from 'next/headers'; +import { Suspense } from 'react'; + +// Above the pageload's 10 second wait for the trace meta tag, but short enough that the tag still +// arrives before the pageload ends. +const DELAY_MS = 10_500; + +async function SlowContent() { + await headers(); + await new Promise(resolve => setTimeout(resolve, DELAY_MS)); + return

Slow content

; +} + +export default function Page() { + return ( + Loading...

}> + +
+ ); +} diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts index f06c4da961cd..36efdae23642 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts @@ -212,3 +212,33 @@ test('keeps a navigation that starts while the pageload waits for the trace meta expect(pageloadTx.contexts?.trace?.data?.['sentry.idle_span_finish_reason']).toBe('cancelled'); expect(navigationTx.contexts?.trace?.data?.['sentry.idle_span_finish_reason']).toBe('idleTimeout'); }); + +test('links the server request when its trace meta tag arrives after the pageload stopped waiting', async ({ + page, +}) => { + test.skip(process.env.TEST_ENV !== 'production', 'Only a prerendered shell makes the trace meta tag arrive late'); + test.setTimeout(60_000); + + const pageloadTxPromise = waitForTransaction(APP, transactionEvent => { + return transactionEvent.transaction === '/slow-stream' && transactionEvent.contexts?.trace?.op === 'pageload'; + }); + + await page.goto('/slow-stream', { waitUntil: 'commit' }); + await expect(page.locator('#slow-content')).toBeVisible({ timeout: 20_000 }); + const [requestTraceId, requestSpanId] = (await page + .locator('meta[name="sentry-trace"]') + .getAttribute('content'))!.split('-'); + + const pageloadTx = await pageloadTxPromise; + + // The tag arrived after the pageload had started its own trace, so the pageload only links it. + expect(pageloadTx.contexts?.trace?.trace_id).not.toBe(requestTraceId); + expect(pageloadTx.contexts?.trace?.links).toEqual([ + { + trace_id: requestTraceId, + span_id: requestSpanId, + sampled: true, + attributes: { [SENTRY_LINK_TYPE]: 'server_request' }, + }, + ]); +}); diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/app/slow-stream/page.tsx b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/app/slow-stream/page.tsx new file mode 100644 index 000000000000..478ac04626a6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/app/slow-stream/page.tsx @@ -0,0 +1,20 @@ +import { headers } from 'next/headers'; +import { Suspense } from 'react'; + +// Above the pageload's 10 second wait for the trace meta tag, but short enough that the tag still +// arrives before the pageload ends. +const DELAY_MS = 10_500; + +async function SlowContent() { + await headers(); + await new Promise(resolve => setTimeout(resolve, DELAY_MS)); + return

Slow content

; +} + +export default function Page() { + return ( + Loading...

}> + +
+ ); +} diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts index 3d1512789f82..b5eadf749de5 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/tests/cacheOrigin-pageloadConnection.spec.ts @@ -211,3 +211,33 @@ test('keeps a navigation that starts while the pageload waits for the trace meta value: 'idleTimeout', }); }); + +test('links the server request when its trace meta tag arrives after the pageload stopped waiting', async ({ + page, +}) => { + test.skip(process.env.TEST_ENV !== 'production', 'Only a prerendered shell makes the trace meta tag arrive late'); + test.setTimeout(60_000); + + const pageloadSpanPromise = waitForStreamedSpan(APP, span => { + return span.name === '/slow-stream' && getSpanOp(span) === 'pageload' && span.is_segment; + }); + + await page.goto('/slow-stream', { waitUntil: 'commit' }); + await expect(page.locator('#slow-content')).toBeVisible({ timeout: 20_000 }); + const [requestTraceId, requestSpanId] = (await page + .locator('meta[name="sentry-trace"]') + .getAttribute('content'))!.split('-'); + + const pageloadSpan = await pageloadSpanPromise; + + // The tag arrived after the pageload had started its own trace, so the pageload only links it. + expect(pageloadSpan.trace_id).not.toBe(requestTraceId); + expect(pageloadSpan.links).toEqual([ + { + trace_id: requestTraceId, + span_id: requestSpanId, + sampled: true, + attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'server_request' } }, + }, + ]); +}); From 52bd8e815474cc0c703c739adaa35911cfd73679 Mon Sep 17 00:00:00 2001 From: Martin Sonnberger Date: Fri, 13 Nov 2026 16:08:25 +0100 Subject: [PATCH 083/136] fix(replay): Minify the compression worker to ES2020 (#26355) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Why:** The replay compression worker gets minified with `minifySync`, which doesn't pick up `transform.target` and defaults to esnext. The worker code in our bundles currently contains ES2021 syntax (`t||={}`, `this.v&&=…`), so it fails to start on ES2020-only browsers (e.g. Safari 13–14, Chrome 80–84). `lint:es-compatibility` never caught it because the worker is embedded as a string. The build now parses the minified worker as ES2020 and fails if it isn't. The size change is negligible (+9 B raw, −2 B gzip). **How to review:** Single file, `packages/replay-worker/rollup.worker.config.mjs`. I confirmed the new check fails the build without the `target` fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- packages/replay-worker/rollup.worker.config.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/replay-worker/rollup.worker.config.mjs b/packages/replay-worker/rollup.worker.config.mjs index 323772986beb..e282d9c4b1bc 100644 --- a/packages/replay-worker/rollup.worker.config.mjs +++ b/packages/replay-worker/rollup.worker.config.mjs @@ -1,6 +1,7 @@ // inspired by https://justinribeiro.com/chronicle/2020/07/17/building-module-web-workers-for-cross-browser-compatibility-with-rollup/ import { treeShakePreset } from '@sentry-internal/rollup-utils'; +import { parse } from 'acorn'; import { defineConfig } from 'rolldown'; import { minifySync } from 'rolldown/utils'; @@ -42,7 +43,11 @@ const config = defineConfig([ // emits string literals as backticks, which would terminate the literal early and silently // produce an empty chunk. renderChunk(code) { - const { code: minified } = minifySync('worker.js', code, { module: true }); + // Unlike `output.minify`, `minifySync` doesn't pick up `transform.target` and defaults to esnext. + const { code: minified } = minifySync('worker.js', code, { module: true, compress: { target: 'es2020' } }); + + // `lint:es-compatibility` can't see into the string we embed below, so check the syntax here. + parse(minified, { ecmaVersion: 2020, sourceType: 'module' }); return `export default ${JSON.stringify(minified)};`; }, From 075093d507c241543ac7fe34c90e15c86a317e71 Mon Sep 17 00:00:00 2001 From: Sigrid <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:11:06 +0100 Subject: [PATCH 084/136] ref: Share the cache origin helpers of Next.js, Nuxt and SvelteKit (#26363) ## What Next.js, Nuxt and SvelteKit now use one shared implementation of the `sentry-cache-origin` tag from #25318, #26305 and #26307. There is no change for users. - `@sentry/core` holds the tag name, the server code that writes the tag, and the client code that marks and links the pageload. All of these are `_INTERNAL_` exports. The client part is in `@sentry/core/browser`, and the server part is in `@sentry/core/server`. - Nuxt now links the request's root span explicitly, like SvelteKit. The Nuxt E2E tests check that the tag holds the `http.server` root span. ## Why Each SDK had its own copy of the tag name, the tag writer and the pageload logic. With one module, the server writer and the client reader cannot drift apart. A round-trip test now checks that the client reads the tag the server writes. Each framework keeps its own decision about which page is reused (build, `x-vercel-isr`, Nitro route rules, Next.js prerender context). Those rules differ per framework, so a shared helper would only pass them through. The Nuxt change already behaves the same today: no child span is active while Nuxt renders the page. The explicit root span protects the link from a future child span. That is the bug SvelteKit had with `sveltekit.resolve`. Two edge cases are now handled the same way in all three SDKs, and the SDKs never write either one: - An empty tag marks the pageload without a link. Before this change, only Next.js ignored an empty tag, and Next.js never writes one. - Core reads the first tag. Before this change, Next.js read the last one, but a Next.js document never has more than one tag. --- .../nuxt-4/tests/tracing.cached-html.test.ts | 6 +- .../nuxt-5/tests/tracing.cached-html.test.ts | 6 +- packages/core/src/browser.ts | 1 + packages/core/src/index.ts | 1 + packages/core/src/server.ts | 1 + packages/core/src/utils/cacheOrigin.ts | 72 +++++++++ .../core/test/lib/utils/cacheOrigin.test.ts | 153 ++++++++++++++++++ .../appRouterPageloadInstrumentation.ts | 9 +- .../src/client/routing/traceMetaTags.ts | 63 ++------ packages/nextjs/src/common/traceMetaTags.ts | 6 - .../getFinalConfigObjectUtils.ts | 5 +- .../nextjs/src/server/nextSentryPropagator.ts | 4 +- .../nextjs/test/client/traceMetaTags.test.ts | 63 ++------ .../nuxt/src/runtime/plugins/sentry.client.ts | 9 +- .../src/runtime/utils/cacheOriginMetaTag.ts | 5 - .../src/runtime/utils/cacheOriginPageload.ts | 46 ------ .../nuxt/src/runtime/utils/pageMetaTags.ts | 25 +-- .../nuxt/test/runtime/plugins/client.test.ts | 46 ++++-- .../runtime/utils/cacheOriginPageload.test.ts | 100 ------------ .../test/runtime/utils/pageMetaTags.test.ts | 17 +- .../src/client/svelte4BrowserTracing.ts | 23 +-- .../src/client/svelte5BrowserTracing.ts | 23 +-- .../sveltekit/src/client/traceMetaTags.ts | 39 ----- .../sveltekit/src/common/traceMetaTags.ts | 5 - .../sveltekit/src/server-common/handle.ts | 15 +- .../client/browserTracingIntegration.test.ts | 4 +- .../test/client/svelte5BrowserTracing.test.ts | 4 +- .../test/client/traceMetaTags.test.ts | 56 ------- 28 files changed, 361 insertions(+), 446 deletions(-) create mode 100644 packages/core/src/utils/cacheOrigin.ts create mode 100644 packages/core/test/lib/utils/cacheOrigin.test.ts delete mode 100644 packages/nextjs/src/common/traceMetaTags.ts delete mode 100644 packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts delete mode 100644 packages/nuxt/src/runtime/utils/cacheOriginPageload.ts delete mode 100644 packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts delete mode 100644 packages/sveltekit/src/client/traceMetaTags.ts delete mode 100644 packages/sveltekit/src/common/traceMetaTags.ts delete mode 100644 packages/sveltekit/test/client/traceMetaTags.test.ts diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts index f990f2bd3c3e..b6fae84d4a54 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.cached-html.test.ts @@ -168,14 +168,14 @@ export async function testCacheOriginOnRuntimeCachedPage( const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? []; const cacheOriginLink = { trace_id: serverSpan1.trace_id, - span_id: originSpanId, + span_id: serverSpan1.span_id, sampled: true, attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'cache_origin' } }, }; - await test.step('The cache origin tag holds the sampled render of the 1. request', () => { + await test.step('The cache origin tag holds the `http.server` root span of the 1. request', () => { expect(originTraceId).toBe(serverSpan1.trace_id); - expect(originSpanId).toMatch(/^[a-f0-9]{16}$/); + expect(originSpanId).toBe(serverSpan1.span_id); expect(originSampled).toBe('1'); expect(cacheOrigin2).toBe(cacheOrigin1); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts index e7e209b35468..14e714ba8f13 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.cached-html.test.ts @@ -161,14 +161,14 @@ export async function testCacheOriginOnRuntimeCachedPage( const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? []; const cacheOriginLink = { trace_id: serverSpan1.trace_id, - span_id: originSpanId, + span_id: serverSpan1.span_id, sampled: true, attributes: { [SENTRY_LINK_TYPE]: { type: 'string', value: 'cache_origin' } }, }; - await test.step('The cache origin tag holds the sampled render of the 1. request', () => { + await test.step('The cache origin tag holds the `http.server` root span of the 1. request', () => { expect(originTraceId).toBe(serverSpan1.trace_id); - expect(originSpanId).toMatch(/^[a-f0-9]{16}$/); + expect(originSpanId).toBe(serverSpan1.span_id); expect(originSampled).toBe('1'); expect(cacheOrigin2).toBe(cacheOrigin1); }); diff --git a/packages/core/src/browser.ts b/packages/core/src/browser.ts index 450a20d1b38c..1a16c1165894 100644 --- a/packages/core/src/browser.ts +++ b/packages/core/src/browser.ts @@ -12,6 +12,7 @@ export { } from './tracing/browserSpanApi'; export { startIdleSpan } from './tracing/idleSpan'; +export { _INTERNAL_withCacheOrigin } from './utils/cacheOrigin'; export type { XhrBreadcrumbData, XhrBreadcrumbHint } from './types/breadcrumb'; export type { BrowserClientReplayOptions } from './types/browseroptions'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5e01bde701e6..11fd3f6cad1f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -134,6 +134,7 @@ export { applySdkMetadata } from './utils/sdkMetadata'; export { getTraceData } from './utils/traceData'; export { matchesTracePropagationTargets, shouldPropagateTraceForUrl } from './utils/tracePropagationTargets'; export { getTraceMetaTags } from './utils/meta'; +export { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from './utils/cacheOrigin'; export { debounce } from './utils/debounce'; export { uniq } from './utils/array'; export { makeWeakRef, derefWeakRef } from './utils/weakRef'; diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index f7f74af63dee..50dfb6639b05 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -35,6 +35,7 @@ export { wrapMcpServerWithSentry } from './integrations/mcp-server'; export { isNodeEnv, loadModule } from './utils/node'; export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace'; export { vercelWaitUntil } from './utils/vercelWaitUntil'; +export { _INTERNAL_getCacheOriginMetaTag, _INTERNAL_getRootSpanSentryTrace } from './utils/cacheOrigin'; export { getReleaseFromCommitEnv as _INTERNAL_getReleaseFromCommitEnv, readCommitEnvVar as _INTERNAL_readCommitEnvVar, diff --git a/packages/core/src/utils/cacheOrigin.ts b/packages/core/src/utils/cacheOrigin.ts new file mode 100644 index 000000000000..d0e08f9dad26 --- /dev/null +++ b/packages/core/src/utils/cacheOrigin.ts @@ -0,0 +1,72 @@ +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import type { SpanLink } from '../types/link'; +import type { StartSpanOptions } from '../types/startSpanOptions'; +import { getActiveSpan, getRootSpan, TRACE_FLAG_SAMPLED } from './spanUtils'; +import { getTraceData } from './traceData'; +import { extractTraceparentData } from './tracing'; +import { GLOBAL_OBJ } from './worldwide'; + +/** + * Replaces `sentry-trace` and `baggage` in a cached or prerendered page, so that no visitor continues the + * trace of the render. + * + * - No tag: the server rendered the page for this request, or rendered no content (a client-side shell) + * - Empty `content`: there is no trace of the render to link, for example for a page prerendered in the build + * - A `sentry-trace` value: the client links the render + */ +export const _INTERNAL_CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; + +/** Returns the `sentry-cache-origin` meta tag. Without `renderTrace`, the tag is empty. */ +export function _INTERNAL_getCacheOriginMetaTag(renderTrace: string | undefined): string { + return ``; +} + +/** + * Returns the `sentry-trace` of the request's root span, which a cached page links as its render. Unlike + * `getTraceData()`, it ignores an active child span, such as SvelteKit's `sveltekit.resolve`. + */ +export function _INTERNAL_getRootSpanSentryTrace(): string | undefined { + const activeSpan = getActiveSpan(); + return getTraceData({ span: activeSpan && getRootSpan(activeSpan) })['sentry-trace']; +} + +/** + * Sets `page.server_rendering.type` on a pageload whose document has a `sentry-cache-origin` tag, even an + * empty one. Links the render if the tag holds the `sentry-trace` of a sampled render. Pass `undefined` as + * `serverRenderingType` while the type is not known. + * + * Call it before the span starts, so `tracesSampler` and `ignoreSpans` see the attribute. + */ +export function _INTERNAL_withCacheOrigin( + spanOptions: StartSpanOptions, + serverRenderingType: 'static' | 'partially_static' | undefined, +): StartSpanOptions { + const renderTrace = (GLOBAL_OBJ as { document?: Document }).document + ?.querySelector(`meta[name="${_INTERNAL_CACHE_ORIGIN_META_TAG_NAME}"]`) + ?.getAttribute('content'); + if (renderTrace == null) { + return spanOptions; + } + + const link = getSampledRenderLink(renderTrace); + return { + ...spanOptions, + attributes: { + ...spanOptions.attributes, + ...(serverRenderingType && { [PAGE_SERVER_RENDERING_TYPE]: serverRenderingType }), + }, + ...(link && { links: [...(spanOptions.links ?? []), link] }), + }; +} + +// Only a sampled render sent spans, so a link to any other render would point at nothing. +function getSampledRenderLink(renderTrace: string): SpanLink | undefined { + const traceparent = extractTraceparentData(renderTrace); + if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) { + return undefined; + } + return { + context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: TRACE_FLAG_SAMPLED }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, + }; +} diff --git a/packages/core/test/lib/utils/cacheOrigin.test.ts b/packages/core/test/lib/utils/cacheOrigin.test.ts new file mode 100644 index 000000000000..e4cd8572ccbb --- /dev/null +++ b/packages/core/test/lib/utils/cacheOrigin.test.ts @@ -0,0 +1,153 @@ +/** + * @vitest-environment jsdom + */ + +import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes'; +import { PAGELOAD } from '@sentry/conventions/op'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { setCurrentClient, startSpan } from '../../../src'; +import type { StartSpanOptions } from '../../../src/types/startSpanOptions'; +import { + _INTERNAL_getCacheOriginMetaTag, + _INTERNAL_getRootSpanSentryTrace, + _INTERNAL_withCacheOrigin, +} from '../../../src/utils/cacheOrigin'; +import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; +import { resetGlobals } from '../../testutils'; + +const TRACE_ID = '0b37aaf4f0d74c0e80875099e7d7ca68'; +const SPAN_ID = 'bc3a52360214dcf3'; + +const spanOptions: StartSpanOptions = { name: '/pricing', attributes: { [SENTRY_OP]: PAGELOAD } }; + +const cacheOriginLink = { + context: { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, +}; + +function addCacheOriginTag(content: string): void { + const tag = document.createElement('meta'); + tag.name = 'sentry-cache-origin'; + tag.content = content; + document.head.appendChild(tag); +} + +describe('_INTERNAL_getCacheOriginMetaTag', () => { + it('holds the sentry-trace value of the render', () => { + expect(_INTERNAL_getCacheOriginMetaTag(`${TRACE_ID}-${SPAN_ID}-1`)).toBe( + ``, + ); + }); + + it('is empty without a sentry-trace value', () => { + expect(_INTERNAL_getCacheOriginMetaTag(undefined)).toBe(''); + }); +}); + +describe('_INTERNAL_getRootSpanSentryTrace', () => { + beforeEach(() => { + resetGlobals(); + const client = new TestClient( + getDefaultTestClientOptions({ dsn: 'https://123@sentry.io/42', tracesSampleRate: 1 }), + ); + setCurrentClient(client); + client.init(); + }); + + it('returns the sentry-trace of the root span while a child span is active', () => { + startSpan({ name: 'GET /pricing' }, rootSpan => + startSpan({ name: 'sveltekit.resolve' }, () => { + const { traceId, spanId } = rootSpan.spanContext(); + expect(_INTERNAL_getRootSpanSentryTrace()).toBe(`${traceId}-${spanId}-1`); + }), + ); + }); +}); + +describe('_INTERNAL_withCacheOrigin', () => { + beforeEach(() => { + document.head.innerHTML = ''; + }); + + it('returns the span options unchanged for a page without a cache origin tag', () => { + expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toBe(spanOptions); + }); + + // HTML requires `content` on a named meta tag, so the SDK cannot have written this one. + it('returns the span options unchanged for a cache origin tag without `content`', () => { + const tag = document.createElement('meta'); + tag.name = 'sentry-cache-origin'; + document.head.appendChild(tag); + + expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toBe(spanOptions); + }); + + it('sets the rendering type and links a sampled render', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + + expect(_INTERNAL_withCacheOrigin(spanOptions, 'partially_static')).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'partially_static' }, + links: [cacheOriginLink], + }); + }); + + it.each([ + { kind: 'an empty tag (prerendered during the build)', content: '' }, + { kind: 'an unsampled render', content: `${TRACE_ID}-${SPAN_ID}-0` }, + { kind: 'a render without a sampling decision', content: `${TRACE_ID}-${SPAN_ID}` }, + { kind: 'a malformed value', content: 'not-a-trace' }, + ])('sets the rendering type without a link for $kind', ({ content }) => { + addCacheOriginTag(content); + + expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + }); + }); + + it('links the render but leaves the rendering type unset without one', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + + expect(_INTERNAL_withCacheOrigin(spanOptions, undefined)).toEqual({ ...spanOptions, links: [cacheOriginLink] }); + }); + + it('keeps the links that the span options already have', () => { + addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); + const previousTraceLink = { + context: { traceId: '0d5c7c7a6f0b4a57a3f1e9c2b8d4e6f1', spanId: 'b1a2c3d4e5f60718', traceFlags: 1 }, + attributes: { [SENTRY_LINK_TYPE]: 'previous_trace' }, + }; + + expect(_INTERNAL_withCacheOrigin({ ...spanOptions, links: [previousTraceLink] }, 'static').links).toEqual([ + previousTraceLink, + cacheOriginLink, + ]); + }); +}); + +// The server writes the tag and the client reads it, so the HTML format must stay readable by the client. +describe('the tag that _INTERNAL_getCacheOriginMetaTag writes', () => { + beforeEach(() => { + document.head.innerHTML = ''; + }); + + it('makes _INTERNAL_withCacheOrigin link the render', () => { + document.head.innerHTML = _INTERNAL_getCacheOriginMetaTag(`${TRACE_ID}-${SPAN_ID}-1`); + + expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + links: [cacheOriginLink], + }); + }); + + it('makes _INTERNAL_withCacheOrigin set the rendering type without a link when it is empty', () => { + document.head.innerHTML = _INTERNAL_getCacheOriginMetaTag(undefined); + + expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toEqual({ + name: '/pricing', + attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, + }); + }); +}); diff --git a/packages/nextjs/src/client/routing/appRouterPageloadInstrumentation.ts b/packages/nextjs/src/client/routing/appRouterPageloadInstrumentation.ts index 20e7a0e727e0..da1d0f1a92ab 100644 --- a/packages/nextjs/src/client/routing/appRouterPageloadInstrumentation.ts +++ b/packages/nextjs/src/client/routing/appRouterPageloadInstrumentation.ts @@ -14,15 +14,16 @@ import { hasSpanStreamingEnabled, PAGELOAD_SPAN_NAME_FALLBACK, } from '@sentry/core'; +import { _INTERNAL_withCacheOrigin } from '@sentry/core/browser'; import { resolveCurrentRoute, startBrowserTracingPageLoadSpan, WINDOW } from '@sentry/react'; import { stripTrailingSlash } from './parameterization'; import type { TraceMetaTagValues, TraceMetaTagWait } from './traceMetaTags'; import { addTraceMetaTagLink, canWaitForTraceMetaTag, + getServerRenderingType, readTraceMetaTags, waitForTraceMetaTag, - withCacheOrigin, } from './traceMetaTags'; /** @@ -52,7 +53,11 @@ function startPageloadSpan( documentUrl: string, traceMetaTags?: TraceMetaTagValues, ): Span | undefined { - const span = startBrowserTracingPageLoadSpan(client, withCacheOrigin(spanOptions, traceMetaTags), traceMetaTags); + const span = startBrowserTracingPageLoadSpan( + client, + _INTERNAL_withCacheOrigin(spanOptions, getServerRenderingType(traceMetaTags)), + traceMetaTags, + ); const scope = getCurrentScope(); const { normalizedRequest } = scope.getScopeData().sdkProcessingMetadata; if (normalizedRequest) { diff --git a/packages/nextjs/src/client/routing/traceMetaTags.ts b/packages/nextjs/src/client/routing/traceMetaTags.ts index c276a8cef03e..8980d781862a 100644 --- a/packages/nextjs/src/client/routing/traceMetaTags.ts +++ b/packages/nextjs/src/client/routing/traceMetaTags.ts @@ -1,16 +1,12 @@ -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; -import type { Span, SpanLink, StartSpanOptions } from '@sentry/core'; +import { SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import type { Span } from '@sentry/core'; import { extractTraceparentData, GLOBAL_OBJ } from '@sentry/core'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../../common/traceMetaTags'; import { WINDOW } from '@sentry/react'; // `@opentelemetry/api` `TraceFlags`, inlined because core does not export its copies. const TRACE_FLAG_SAMPLED = 0x1; const TRACE_FLAG_NONE = 0x0; -const SERVER_REQUEST_LINK_TYPE = 'server_request'; -const CACHE_ORIGIN_LINK_TYPE = 'cache_origin'; - export interface TraceMetaTagValues { sentryTrace: string; baggage: string | undefined; @@ -132,65 +128,34 @@ export function waitForTraceMetaTag( return { giveUp: () => settle(onGiveUp) }; } -/** The span link to the span a `sentry-trace` value describes, if the value is one. */ -function traceMetaTagLink(sentryTrace: string, linkType: string): SpanLink | undefined { +/** + * Adds a span link to the span described by a `sentry-trace` value. Used when the tag arrives after + * the pageload span exists, which can only link the server request, not continue it. + */ +export function addTraceMetaTagLink(span: Span, { sentryTrace }: TraceMetaTagValues): void { const traceparent = extractTraceparentData(sentryTrace); if (!traceparent?.traceId || !traceparent.parentSpanId) { - return undefined; + return; } - return { + span.addLink({ context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: traceparent.parentSampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE, }, - attributes: { [SENTRY_LINK_TYPE]: linkType }, - }; -} - -/** - * Adds a span link to the span described by a `sentry-trace` value. Used when the tag arrives after - * the pageload span exists, which can only link the server request, not continue it. - */ -export function addTraceMetaTagLink(span: Span, { sentryTrace }: TraceMetaTagValues): void { - const link = traceMetaTagLink(sentryTrace, SERVER_REQUEST_LINK_TYPE); - if (link) { - span.addLink(link); - } + attributes: { [SENTRY_LINK_TYPE]: 'server_request' }, + }); } /** * How the server rendered a document with a `sentry-cache-origin` tag. With trace meta tags of this * request, only the shell was reused. Unset while a resumed part can still bring those tags. */ -function getServerRenderingType(traceMetaTags: TraceMetaTagValues | undefined): string | undefined { +export function getServerRenderingType( + traceMetaTags: TraceMetaTagValues | undefined, +): 'static' | 'partially_static' | undefined { if (traceMetaTags) { return 'partially_static'; } return canWaitForTraceMetaTag() ? undefined : 'static'; } - -/** - * Marks a pageload whose document carries a `sentry-cache-origin` tag with how the server rendered - * it, and links the render that the page reuses. Applied at span start, so `tracesSampler` and - * `ignoreSpans` see both. Like a `use cache` hit, the pageload links only a sampled render. - */ -export function withCacheOrigin(spanOptions: StartSpanOptions, traceMetaTags?: TraceMetaTagValues): StartSpanOptions { - const document = getDocument(); - const cacheOrigin = document && lastMetaContent(document, CACHE_ORIGIN_META_TAG_NAME); - if (!cacheOrigin) { - return spanOptions; - } - - const link = traceMetaTagLink(cacheOrigin, CACHE_ORIGIN_LINK_TYPE); - const isSampled = link?.context.traceFlags === TRACE_FLAG_SAMPLED; - const serverRenderingType = getServerRenderingType(traceMetaTags); - return { - ...spanOptions, - attributes: { - ...spanOptions.attributes, - ...(serverRenderingType && { [PAGE_SERVER_RENDERING_TYPE]: serverRenderingType }), - }, - links: link && isSampled ? [...(spanOptions.links ?? []), link] : spanOptions.links, - }; -} diff --git a/packages/nextjs/src/common/traceMetaTags.ts b/packages/nextjs/src/common/traceMetaTags.ts deleted file mode 100644 index 90ae909bf962..000000000000 --- a/packages/nextjs/src/common/traceMetaTags.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Name of the meta tag the server writes in place of `sentry-trace` while Next.js prerenders a document. - * Its content is the `sentry-trace` value of the prerender. The client turns it into a `cache_origin` - * link and never continues it, because the document is served to every later visitor. - */ -export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts index 91e33d4d85c2..b9b9062e95a6 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectUtils.ts @@ -1,5 +1,4 @@ -import { CACHE_ORIGIN_META_TAG_NAME } from '../../common/traceMetaTags'; -import { debug, isMatchingPattern, parseSemver } from '@sentry/core'; +import { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME, debug, isMatchingPattern, parseSemver } from '@sentry/core'; import { getSentryRelease } from '@sentry/node'; import * as fs from 'fs'; import * as path from 'path'; @@ -188,7 +187,7 @@ export function maybeSetClientTraceMetadataOption( incomingUserNextConfigObject.experimental.clientTraceMetadata = [ 'baggage', 'sentry-trace', - CACHE_ORIGIN_META_TAG_NAME, + _INTERNAL_CACHE_ORIGIN_META_TAG_NAME, ...(incomingUserNextConfigObject.experimental?.clientTraceMetadata || []), ]; } diff --git a/packages/nextjs/src/server/nextSentryPropagator.ts b/packages/nextjs/src/server/nextSentryPropagator.ts index b583beff3465..6df02637197e 100644 --- a/packages/nextjs/src/server/nextSentryPropagator.ts +++ b/packages/nextjs/src/server/nextSentryPropagator.ts @@ -1,7 +1,7 @@ import type { Context, TextMapSetter, TracerProvider } from '@opentelemetry/api'; import { defaultTextMapSetter, propagation } from '@opentelemetry/api'; +import { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from '@sentry/core'; import { SentryPropagator } from '@sentry/opentelemetry'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; import { isPrerenderContext, markPrerendersOnTracerProvider } from './prerenderContext'; /** @@ -28,7 +28,7 @@ export class NextSentryPropagator extends SentryPropagator { super.inject(ctx, values, defaultTextMapSetter); const sentryTrace = values['sentry-trace']; if (sentryTrace) { - setter.set(carrier, CACHE_ORIGIN_META_TAG_NAME, sentryTrace); + setter.set(carrier, _INTERNAL_CACHE_ORIGIN_META_TAG_NAME, sentryTrace); } } } diff --git a/packages/nextjs/test/client/traceMetaTags.test.ts b/packages/nextjs/test/client/traceMetaTags.test.ts index ec821cc2312f..6710468e0fbf 100644 --- a/packages/nextjs/test/client/traceMetaTags.test.ts +++ b/packages/nextjs/test/client/traceMetaTags.test.ts @@ -1,14 +1,13 @@ // @vitest-environment jsdom -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes'; -import { PAGELOAD } from '@sentry/conventions/op'; -import type { Span, StartSpanOptions } from '@sentry/core'; +import { SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; +import type { Span } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { addTraceMetaTagLink, canWaitForTraceMetaTag, + getServerRenderingType, readTraceMetaTags, waitForTraceMetaTag, - withCacheOrigin, } from '../../src/client/routing/traceMetaTags'; const HEAD_TRACE = '11111111111111111111111111111111-1111111111111111-1'; @@ -222,62 +221,20 @@ describe('addTraceMetaTagLink', () => { }); }); -describe('withCacheOrigin', () => { - const PAGELOAD_OPTIONS: StartSpanOptions = { name: '/products/:id', attributes: { [SENTRY_OP]: PAGELOAD } }; - const PRERENDER_LINK = { - context: { traceId: '11111111111111111111111111111111', spanId: '1111111111111111', traceFlags: 1 }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }; - - it('returns the options unchanged for a document without a sentry-cache-origin tag', () => { - appendMeta(document.head, 'sentry-trace', HEAD_TRACE); - - expect(withCacheOrigin(PAGELOAD_OPTIONS, { sentryTrace: HEAD_TRACE, baggage: undefined })).toBe(PAGELOAD_OPTIONS); - }); - - it('marks a fully reused page as static and links a sampled render as cache origin', () => { - appendMeta(document.head, 'sentry-cache-origin', HEAD_TRACE); - - expect(withCacheOrigin(PAGELOAD_OPTIONS)).toEqual({ - name: '/products/:id', - attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - links: [PRERENDER_LINK], - }); +describe('getServerRenderingType', () => { + it('is static for a fully reused page', () => { + expect(getServerRenderingType(undefined)).toBe('static'); }); - it('marks a page as partially static when the pageload continues the trace of this request', () => { - appendMeta(document.head, 'sentry-cache-origin', HEAD_TRACE); - - expect(withCacheOrigin(PAGELOAD_OPTIONS, { sentryTrace: BODY_TRACE, baggage: undefined })).toEqual({ - name: '/products/:id', - attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'partially_static' }, - links: [PRERENDER_LINK], - }); + it('is partially static when the pageload continues the trace of this request', () => { + expect(getServerRenderingType({ sentryTrace: BODY_TRACE, baggage: undefined })).toBe('partially_static'); }); // A navigation or the wait cap can start the pageload before the resumed part arrives. - it('leaves the type unset while a resumed part can still bring the trace of this request', () => { - appendMeta(document.head, 'sentry-cache-origin', HEAD_TRACE); + it('is unset while a resumed part can still bring the trace of this request', () => { setReadyState('loading'); vi.spyOn(performance, 'getEntriesByType').mockReturnValue([]); - expect(withCacheOrigin(PAGELOAD_OPTIONS)).toEqual({ - name: '/products/:id', - attributes: { [SENTRY_OP]: PAGELOAD }, - links: [PRERENDER_LINK], - }); - }); - - it.each([ - { tag: 'holds an unsampled trace', content: '11111111111111111111111111111111-1111111111111111-0' }, - { tag: 'holds a trace without a sampling decision', content: '11111111111111111111111111111111-1111111111111111' }, - { tag: 'holds no sentry-trace value', content: 'prerendered' }, - ])('marks the page without a link when the tag $tag', ({ content }) => { - appendMeta(document.head, 'sentry-cache-origin', content); - - expect(withCacheOrigin(PAGELOAD_OPTIONS)).toEqual({ - name: '/products/:id', - attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - }); + expect(getServerRenderingType(undefined)).toBeUndefined(); }); }); diff --git a/packages/nuxt/src/runtime/plugins/sentry.client.ts b/packages/nuxt/src/runtime/plugins/sentry.client.ts index 2df161d56a01..16fae57beb68 100644 --- a/packages/nuxt/src/runtime/plugins/sentry.client.ts +++ b/packages/nuxt/src/runtime/plugins/sentry.client.ts @@ -1,4 +1,6 @@ +import { PAGELOAD } from '@sentry/conventions/op'; import { getClient, GLOBAL_OBJ } from '@sentry/core'; +import { _INTERNAL_withCacheOrigin } from '@sentry/core/browser'; import { browserTracingIntegration, _INTERNAL_createVueRouteProvider, @@ -9,7 +11,6 @@ import { import { defineNuxtPlugin, isNuxtError } from 'nuxt/app'; import type { GlobalObjWithIntegrationOptions } from '../../client/vueIntegration'; import { reportNuxtError } from '../utils'; -import { withCacheOrigin } from '../utils/cacheOriginPageload'; // --- Types are copied from @sentry/vue (so it does not need to be exported) --- // The following type is an intersection of the Route type from VueRouter v2, v3, and v4. @@ -77,7 +78,11 @@ export default defineNuxtPlugin({ browserTracingIntegration({ router: nuxtApp.$router as VueRouter, routeLabel: 'path', - beforeStartSpan: options => withCacheOrigin(options, nuxtApp.payload.serverRendered === true), + // A client-side shell (`ssr: false`) has no server-rendered content to mark. + beforeStartSpan: options => + options.op === PAGELOAD && nuxtApp.payload.serverRendered === true + ? _INTERNAL_withCacheOrigin(options, 'static') + : options, }), ); } diff --git a/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts b/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts deleted file mode 100644 index 860a747209d9..000000000000 --- a/packages/nuxt/src/runtime/utils/cacheOriginMetaTag.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Replaces `sentry-trace` and `baggage` in a page that other visitors get too. Holds the `sentry-trace` - * value of the render, or nothing for a build prerender. The client links it and never continues it. - */ -export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts b/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts deleted file mode 100644 index 3ef0ddb3a28a..000000000000 --- a/packages/nuxt/src/runtime/utils/cacheOriginPageload.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; -import { PAGELOAD } from '@sentry/conventions/op'; -import type { SpanLink, StartSpanOptions } from '@sentry/core'; -import { extractTraceparentData } from '@sentry/core'; -import { WINDOW } from '@sentry/vue'; -import { CACHE_ORIGIN_META_TAG_NAME } from './cacheOriginMetaTag'; - -// `@opentelemetry/api` `TraceFlags`, inlined because core does not export its copies. -const TRACE_FLAG_SAMPLED = 0x1; - -/** The `cache_origin` link to the sampled render that a `sentry-trace` value describes. */ -function getCacheOriginLink(sentryTrace: string): SpanLink | undefined { - const traceparent = extractTraceparentData(sentryTrace); - if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) { - return undefined; - } - return { - context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: TRACE_FLAG_SAMPLED }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }; -} - -/** - * Marks the pageload of a reused page as `static` and links the render if it was sampled (as in Next.js). - * Runs at span start, so `tracesSampler` and `ignoreSpans` see the attribute. A client-side shell - * (`ssr: false`) stays unmarked, because the server rendered none of its content. - */ -export function withCacheOrigin(spanOptions: StartSpanOptions, isServerRendered: boolean): StartSpanOptions { - if (spanOptions.op !== PAGELOAD || !isServerRendered) { - return spanOptions; - } - - const cacheOrigin = WINDOW.document - ?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`) - ?.getAttribute('content'); - if (typeof cacheOrigin !== 'string') { - return spanOptions; - } - - const link = getCacheOriginLink(cacheOrigin); - return { - ...spanOptions, - attributes: { ...spanOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - links: link ? [...(spanOptions.links ?? []), link] : spanOptions.links, - }; -} diff --git a/packages/nuxt/src/runtime/utils/pageMetaTags.ts b/packages/nuxt/src/runtime/utils/pageMetaTags.ts index 7c9cb5d019e9..6b88ed637701 100644 --- a/packages/nuxt/src/runtime/utils/pageMetaTags.ts +++ b/packages/nuxt/src/runtime/utils/pageMetaTags.ts @@ -1,9 +1,9 @@ import type { SerializedTraceData } from '@sentry/core'; -import { debug, getTraceData, GLOBAL_OBJ } from '@sentry/core'; +import { debug, GLOBAL_OBJ } from '@sentry/core'; +import { _INTERNAL_getCacheOriginMetaTag, _INTERNAL_getRootSpanSentryTrace } from '@sentry/core/server'; import type { H3Event } from 'h3'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; import { addSentryTracingMetaTags, getEventRequestInfo } from '../utils'; -import { CACHE_ORIGIN_META_TAG_NAME } from './cacheOriginMetaTag'; /** Global flag set by the generated runtime-flags module to the Nitro preset of the server build. */ export const NUXT_NITRO_PRESET_FLAG = '__SENTRY_NUXT_NITRO_PRESET__'; @@ -27,32 +27,23 @@ interface RouteRules { /** * Adds the Sentry meta tags to a rendered page. A page that other visitors get too has a * `sentry-cache-origin` tag instead of `sentry-trace` and `baggage`, so that no visitor continues the - * trace of the render. The tag is empty for build prerenders, because the SDK does not run in the build. + * trace of the render. */ export function addSentryPageMetaTags( head: NuxtRenderHTMLContext['head'], event: H3Event, traceData?: SerializedTraceData, ): void { - const cacheOrigin = getCacheOrigin(event, traceData); - if (cacheOrigin === undefined) { + const isPrerender = isPrerenderRequest(event); + if (!isPrerender && !isCachedRoute(event)) { addSentryTracingMetaTags(head, traceData); return; } debug.log(`Adding the Sentry cache origin meta tag to the reused page ${getEventRequestInfo(event).path}.`); - head.push(``); -} - -/** The `sentry-trace` value of the render of a reused page, or `undefined` for a page rendered per request. */ -function getCacheOrigin(event: H3Event, traceData: SerializedTraceData | undefined): string | undefined { - if (isPrerenderRequest(event)) { - return ''; - } - if (!isCachedRoute(event)) { - return undefined; - } - return (traceData ?? getTraceData())['sentry-trace'] ?? ''; + // Sentry skips its server init in the prerender build, so a prerendered page has no trace to link. + const renderTrace = isPrerender ? undefined : (traceData?.['sentry-trace'] ?? _INTERNAL_getRootSpanSentryTrace()); + head.push(_INTERNAL_getCacheOriginMetaTag(renderTrace)); } // The Nitro prerenderer sends this header with each route it renders (Nitro v2 and v3). h3 v2 deprecates diff --git a/packages/nuxt/test/runtime/plugins/client.test.ts b/packages/nuxt/test/runtime/plugins/client.test.ts index cbc8b35aa117..e0eef316a7ff 100644 --- a/packages/nuxt/test/runtime/plugins/client.test.ts +++ b/packages/nuxt/test/runtime/plugins/client.test.ts @@ -1,11 +1,12 @@ +import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op'; import type { Client, StartSpanOptions } from '@sentry/core'; import type { isNuxtError as nuxtIsNuxtError, NuxtApp } from 'nuxt/app'; import { afterEach, describe, expect, it, vi } from 'vitest'; import clientPlugin from '../../../src/runtime/plugins/sentry.client'; import * as utils from '../../../src/runtime/utils'; -import { withCacheOrigin } from '../../../src/runtime/utils/cacheOriginPageload'; const getClient = vi.hoisted(() => vi.fn<() => Client | undefined>()); +const withCacheOriginMock = vi.hoisted(() => vi.fn()); const browserTracingIntegration = vi.hoisted(() => vi.fn()); const vueIntegration = vi.hoisted(() => vi.fn()); const createVueRouteProvider = vi.hoisted(() => vi.fn()); @@ -29,6 +30,11 @@ vi.mock(import('@sentry/core'), async importOriginal => { }; }); +vi.mock(import('@sentry/core/browser'), async importOriginal => ({ + ...(await importOriginal()), + _INTERNAL_withCacheOrigin: withCacheOriginMock, +})); + vi.mock(import('@sentry/vue'), async importOriginal => { const mod = await importOriginal(); return { @@ -41,10 +47,6 @@ vi.mock(import('@sentry/vue'), async importOriginal => { }; }); -vi.mock(import('../../../src/runtime/utils/cacheOriginPageload'), () => ({ - withCacheOrigin: vi.fn(), -})); - vi.mock(import('nuxt/app'), () => ({ defineNuxtPlugin: vi.fn(plugin => plugin), isNuxtError: vi.fn(() => false) as unknown as typeof nuxtIsNuxtError, @@ -139,9 +141,10 @@ describe('Sentry Nuxt client plugin', () => { expect(client.addIntegration).toHaveBeenCalledWith(integration); }); - it.each([true, false])( - 'passes `serverRendered: %s` from the Nuxt payload to the cache origin check of the pageload', - async serverRendered => { + describe('beforeStartSpan', () => { + async function setupBeforeStartSpan( + serverRendered: boolean, + ): Promise<(options: StartSpanOptions) => StartSpanOptions> { let beforeStartSpan: ((options: StartSpanOptions) => StartSpanOptions) | undefined; browserTracingIntegration.mockImplementation(options => { beforeStartSpan = options.beforeStartSpan; @@ -150,14 +153,31 @@ describe('Sentry Nuxt client plugin', () => { getClient.mockReturnValue(makeClient()); const nuxtApp = makeNuxtApp({ beforeEach: vi.fn(), onError: vi.fn() }); nuxtApp.payload = { serverRendered } as NuxtApp['payload']; - const pageloadOptions = { name: '/rendering-modes/swr-cached-page', op: 'pageload' }; await (clientPlugin as NuxtPluginShape).setup(nuxtApp); - beforeStartSpan?.(pageloadOptions); + return beforeStartSpan!; + } - expect(withCacheOrigin).toHaveBeenCalledWith(pageloadOptions, serverRendered); - }, - ); + it('passes the pageload of a server-rendered page to the cache origin helper as static', async () => { + const beforeStartSpan = await setupBeforeStartSpan(true); + const pageloadOptions = { name: '/rendering-modes/swr-cached-page', op: PAGELOAD }; + + beforeStartSpan(pageloadOptions); + + expect(withCacheOriginMock).toHaveBeenCalledWith(pageloadOptions, 'static'); + }); + + it.each([ + { kind: 'the pageload of a client-side shell', serverRendered: false, op: PAGELOAD }, + { kind: 'a navigation', serverRendered: true, op: NAVIGATION }, + ])('does not change $kind', async ({ serverRendered, op }) => { + const beforeStartSpan = await setupBeforeStartSpan(serverRendered); + const options = { name: '/rendering-modes/swr-cached-page', op }; + + expect(beforeStartSpan(options)).toBe(options); + expect(withCacheOriginMock).not.toHaveBeenCalled(); + }); + }); it('does not add browserTracingIntegration without an initialized client', async () => { getClient.mockReturnValue(undefined); diff --git a/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts b/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts deleted file mode 100644 index f90c87afac01..000000000000 --- a/packages/nuxt/test/runtime/utils/cacheOriginPageload.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; -import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op'; -import type { StartSpanOptions } from '@sentry/core'; -import { beforeEach, describe, expect, it } from 'vitest'; -import { withCacheOrigin } from '../../../src/runtime/utils/cacheOriginPageload'; - -const TRACE_ID = '4c79f60c11214eb38604f4ae0781bfb2'; -const SPAN_ID = 'fa90fdead5f74052'; - -const pageloadOptions: StartSpanOptions = { - name: '/rendering-modes/swr-cached-page', - op: PAGELOAD, - attributes: { [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.vue' }, -}; - -function addCacheOriginTag(content: string): void { - const tag = document.createElement('meta'); - tag.name = 'sentry-cache-origin'; - tag.content = content; - document.head.appendChild(tag); -} - -describe('withCacheOrigin', () => { - beforeEach(() => { - document.head.innerHTML = ''; - }); - - it('marks the pageload as static and links the sampled render', () => { - addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); - - const options = withCacheOrigin(pageloadOptions, true); - - expect(options).toEqual({ - ...pageloadOptions, - attributes: { ...pageloadOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - links: [ - { - context: { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 1 }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }, - ], - }); - }); - - it.each([ - { origin: 'an unsampled render', content: `${TRACE_ID}-${SPAN_ID}-0` }, - { origin: 'a render without a sampling decision', content: `${TRACE_ID}-${SPAN_ID}` }, - { origin: 'a build prerender', content: '' }, - ])('marks the pageload as static without a link for $origin', ({ content }) => { - addCacheOriginTag(content); - - const options = withCacheOrigin(pageloadOptions, true); - - expect(options).toEqual({ - ...pageloadOptions, - attributes: { ...pageloadOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - }); - }); - - it('keeps the links that the pageload already has', () => { - addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); - const previousTraceLink = { - context: { traceId: '0d5c7c7a6f0b4a57a3f1e9c2b8d4e6f1', spanId: 'b1a2c3d4e5f60718', traceFlags: 1 }, - attributes: { [SENTRY_LINK_TYPE]: 'previous_trace' }, - }; - - const options = withCacheOrigin({ ...pageloadOptions, links: [previousTraceLink] }, true); - - expect(options.links).toEqual([ - previousTraceLink, - { - context: { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 1 }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }, - ]); - }); - - it('does not change a pageload without a cache origin tag', () => { - const options = withCacheOrigin(pageloadOptions, true); - - expect(options).toBe(pageloadOptions); - }); - - it('does not change the pageload of a client-side shell', () => { - addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); - - const options = withCacheOrigin(pageloadOptions, false); - - expect(options).toBe(pageloadOptions); - }); - - it('does not change a navigation', () => { - addCacheOriginTag(`${TRACE_ID}-${SPAN_ID}-1`); - const navigationOptions: StartSpanOptions = { name: '/checkout', op: NAVIGATION }; - - const options = withCacheOrigin(navigationOptions, true); - - expect(options).toBe(navigationOptions); - }); -}); diff --git a/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts b/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts index cfe1fe0a5f4b..2aca9037af9d 100644 --- a/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts +++ b/packages/nuxt/test/runtime/utils/pageMetaTags.test.ts @@ -1,4 +1,5 @@ -import { getTraceData, getTraceMetaTags } from '@sentry/core'; +import { getTraceMetaTags } from '@sentry/core'; +import { _INTERNAL_getRootSpanSentryTrace } from '@sentry/core/server'; import type { H3Event } from 'h3'; import { afterEach, describe, expect, it, type Mock, vi } from 'vitest'; import { addSentryPageMetaTags, NUXT_NITRO_PRESET_FLAG } from '../../../src/runtime/utils/pageMetaTags'; @@ -7,11 +8,15 @@ vi.mock(import('@sentry/core'), async importOriginal => { const mod = await importOriginal(); return { ...mod, - getTraceData: vi.fn(), getTraceMetaTags: vi.fn(), }; }); +vi.mock(import('@sentry/core/server'), async importOriginal => ({ + ...(await importOriginal()), + _INTERNAL_getRootSpanSentryTrace: vi.fn(), +})); + const SENTRY_TRACE = '4c79f60c11214eb38604f4ae0781bfb2-fa90fdead5f74052-1'; const LIVE_TRACE_META_TAGS = [ ``, @@ -73,7 +78,7 @@ describe('addSentryPageMetaTags', () => { { nitro: 'Nitro v2', event: h3v1Event({ cache: { swr: true, maxAge: 3600 } }) }, { nitro: 'Nitro v3', event: h3v2Event(nitroV3Rule('cache', { swr: true, maxAge: 3600 })) }, ])('replaces the tracing meta tags with the render as cache origin on a cached route ($nitro)', ({ event }) => { - (getTraceData as Mock).mockReturnValue({ 'sentry-trace': SENTRY_TRACE, baggage: 'sentry-environment=production' }); + (_INTERNAL_getRootSpanSentryTrace as Mock).mockReturnValue(SENTRY_TRACE); const head: string[] = []; addSentryPageMetaTags(head, event); @@ -97,11 +102,11 @@ describe('addSentryPageMetaTags', () => { addSentryPageMetaTags(head, h3v1Event({ cache: {} }), { 'sentry-trace': storedSentryTrace }); expect(head).toEqual([``]); - expect(getTraceData).not.toHaveBeenCalled(); + expect(_INTERNAL_getRootSpanSentryTrace).not.toHaveBeenCalled(); }); it('adds an empty cache origin tag to a cached route when the server has no trace data', () => { - (getTraceData as Mock).mockReturnValue({}); + (_INTERNAL_getRootSpanSentryTrace as Mock).mockReturnValue(undefined); const head: string[] = []; addSentryPageMetaTags(head, h3v1Event({ cache: {} })); @@ -131,7 +136,7 @@ describe('addSentryPageMetaTags', () => { it.each(['vercel', 'netlify'])('replaces the tracing meta tags on an `isr` route on the %s preset', preset => { vi.stubGlobal(NUXT_NITRO_PRESET_FLAG, preset); - (getTraceData as Mock).mockReturnValue({ 'sentry-trace': SENTRY_TRACE }); + (_INTERNAL_getRootSpanSentryTrace as Mock).mockReturnValue(SENTRY_TRACE); const head: string[] = []; addSentryPageMetaTags(head, h3v1Event({ isr: 3600 })); diff --git a/packages/sveltekit/src/client/svelte4BrowserTracing.ts b/packages/sveltekit/src/client/svelte4BrowserTracing.ts index 06a1c24b03b2..f92a42468742 100644 --- a/packages/sveltekit/src/client/svelte4BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte4BrowserTracing.ts @@ -5,6 +5,7 @@ import { PAGELOAD_SPAN_NAME_FALLBACK, ROUTER_SPAN_NAME_FALLBACK, } from '@sentry/core'; +import { _INTERNAL_withCacheOrigin } from '@sentry/core/browser'; import { getCurrentScope, startBrowserTracingNavigationSpan, @@ -26,7 +27,6 @@ import type { Navigation, Page } from '@sveltejs/kit'; // eslint-disable-next-line typescript/no-deprecated import { navigating, page } from '$app/stores'; import type { Readable } from 'svelte/store'; -import { withCacheOrigin } from './traceMetaTags'; /** * SvelteKit 2 / Svelte 4 browser tracing (`$app/stores`). Selected at build time, so it's only @@ -53,16 +53,19 @@ function _instrumentPageload(client: Client, pageStore: Readable): void { const pageloadSpan = startBrowserTracingPageLoadSpan( client, - withCacheOrigin({ - // With span streaming, span names have to be low cardinality. The route id is only available - // asynchronously, which updates the span name then. - name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, - attributes: { - [SENTRY_OP]: PAGELOAD, - [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', - [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + _INTERNAL_withCacheOrigin( + { + // With span streaming, span names have to be low cardinality. The route id is only available + // asynchronously, which updates the span name then. + name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, + attributes: { + [SENTRY_OP]: PAGELOAD, + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + }, }, - }), + 'static', + ), ); if (!pageloadSpan) { return; diff --git a/packages/sveltekit/src/client/svelte5BrowserTracing.ts b/packages/sveltekit/src/client/svelte5BrowserTracing.ts index 135928af8c7e..1cfcf792c883 100644 --- a/packages/sveltekit/src/client/svelte5BrowserTracing.ts +++ b/packages/sveltekit/src/client/svelte5BrowserTracing.ts @@ -5,6 +5,7 @@ import { PAGELOAD_SPAN_NAME_FALLBACK, ROUTER_SPAN_NAME_FALLBACK, } from '@sentry/core'; +import { _INTERNAL_withCacheOrigin } from '@sentry/core/browser'; import { getCurrentScope, startBrowserTracingNavigationSpan, @@ -24,7 +25,6 @@ import { import { NAVIGATION, PAGELOAD, ROUTER } from '@sentry/conventions/op'; import type { Navigation } from '@sveltejs/kit'; import { getCurrentNavigation, onNavigationChange, onPageRouteChange } from './navigationState.svelte'; -import { withCacheOrigin } from './traceMetaTags'; /** * SvelteKit 3 / Svelte 5 browser tracing (`$app/state` runes). Selected at build time, so it's only @@ -49,16 +49,19 @@ function _instrumentPageLoad(client: Client): void { const pageLoadSpan = startBrowserTracingPageLoadSpan( client, - withCacheOrigin({ - // With span streaming, span names have to be low cardinality. The route id is only available - // asynchronously, which updates the span name then. - name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, - attributes: { - [SENTRY_OP]: PAGELOAD, - [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', - [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + _INTERNAL_withCacheOrigin( + { + // With span streaming, span names have to be low cardinality. The route id is only available + // asynchronously, which updates the span name then. + name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : initialPath, + attributes: { + [SENTRY_OP]: PAGELOAD, + [SENTRY_ORIGIN]: 'auto.pageload.sveltekit', + [SENTRY_SEGMENT_NAME_SOURCE]: 'url', + }, }, - }), + 'static', + ), ); if (!pageLoadSpan) { diff --git a/packages/sveltekit/src/client/traceMetaTags.ts b/packages/sveltekit/src/client/traceMetaTags.ts deleted file mode 100644 index c21dbdc73077..000000000000 --- a/packages/sveltekit/src/client/traceMetaTags.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes'; -import type { SpanLink, StartSpanOptions } from '@sentry/core'; -import { extractTraceparentData } from '@sentry/core'; -import { WINDOW } from '@sentry/svelte'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; - -// `@opentelemetry/api` `TraceFlags.SAMPLED`, inlined because core does not export its copy. -const TRACE_FLAG_SAMPLED = 0x1; - -/** - * Marks the pageload of a reused page as `static` at span start, so `tracesSampler` sees it. Links the - * render only if it was sampled, like every `cache_origin` link. - */ -export function withCacheOrigin(spanOptions: StartSpanOptions): StartSpanOptions { - const cacheOrigin = WINDOW.document - ?.querySelector(`meta[name="${CACHE_ORIGIN_META_TAG_NAME}"]`) - ?.getAttribute('content'); - if (cacheOrigin == null) { - return spanOptions; - } - - const link = getSampledCacheOriginLink(cacheOrigin); - return { - ...spanOptions, - attributes: { ...spanOptions.attributes, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - ...(link && { links: [link] }), - }; -} - -function getSampledCacheOriginLink(sentryTrace: string): SpanLink | undefined { - const traceparent = extractTraceparentData(sentryTrace); - if (!traceparent?.traceId || !traceparent.parentSpanId || !traceparent.parentSampled) { - return undefined; - } - return { - context: { traceId: traceparent.traceId, spanId: traceparent.parentSpanId, traceFlags: TRACE_FLAG_SAMPLED }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }; -} diff --git a/packages/sveltekit/src/common/traceMetaTags.ts b/packages/sveltekit/src/common/traceMetaTags.ts deleted file mode 100644 index 16292b31274c..000000000000 --- a/packages/sveltekit/src/common/traceMetaTags.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Replaces `sentry-trace` and `baggage` in a page that many visitors get. Holds the `sentry-trace` of the - * render to link, or is empty. The client links it but never continues it. - */ -export const CACHE_ORIGIN_META_TAG_NAME = 'sentry-cache-origin'; diff --git a/packages/sveltekit/src/server-common/handle.ts b/packages/sveltekit/src/server-common/handle.ts index e70cf289c09f..404e41b45cbb 100644 --- a/packages/sveltekit/src/server-common/handle.ts +++ b/packages/sveltekit/src/server-common/handle.ts @@ -2,13 +2,10 @@ import type { Span } from '@sentry/core'; import { continueTrace, debug, - getActiveSpan, getClient, getCurrentScope, getDefaultIsolationScope, getIsolationScope, - getRootSpan, - getTraceData, getTraceMetaTags, hasSpanStreamingEnabled, httpHeadersToSpanAttributes, @@ -24,11 +21,12 @@ import { } from '@sentry/core'; import { flushIfServerless, + _INTERNAL_getCacheOriginMetaTag, + _INTERNAL_getRootSpanSentryTrace, _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, _INTERNAL_setTunnelDefaults as setTunnelDefaults, } from '@sentry/core/server'; import { getTunnelBasePath } from '../common/tunnel'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../common/traceMetaTags'; import type { Handle, ResolveOptions } from './handleTypes'; import { DEBUG_BUILD } from '../common/debug-build'; import { getTracePropagationData, sendErrorToSentry } from './utils'; @@ -117,14 +115,7 @@ function getPageMetaTags(html: string, isVercelIsrRender: boolean): string { // The build does not reliably send spans, so a prerendered page has no trace to link. // The empty tag still marks the pageload as static. - const originTrace = isVercelIsrRender ? getRootSpanTrace() : undefined; - return ``; -} - -/** With Kit tracing, the active span while the page renders is Kit's `sveltekit.resolve`, not the root span. */ -function getRootSpanTrace(): string | undefined { - const activeSpan = getActiveSpan(); - return getTraceData({ span: activeSpan && getRootSpan(activeSpan) })['sentry-trace']; + return _INTERNAL_getCacheOriginMetaTag(isVercelIsrRender ? _INTERNAL_getRootSpanSentryTrace() : undefined); } /** Kit writes `node_ids` only if the server rendered content, not for `ssr = false` or the SPA fallback. */ diff --git a/packages/sveltekit/test/client/browserTracingIntegration.test.ts b/packages/sveltekit/test/client/browserTracingIntegration.test.ts index a2b17a736c70..c055649573bb 100644 --- a/packages/sveltekit/test/client/browserTracingIntegration.test.ts +++ b/packages/sveltekit/test/client/browserTracingIntegration.test.ts @@ -9,7 +9,7 @@ import { writable } from 'svelte/store'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { navigating, page } from '$app/stores'; import { browserTracingIntegration } from '../../src/client'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../../src/common/traceMetaTags'; +import { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from '@sentry/core'; import { PAGE_SERVER_RENDERING_TYPE, SENTRY_SEGMENT_NAME_SOURCE, @@ -182,7 +182,7 @@ describe('browserTracingIntegration', () => { it('marks the pageload of a prerendered page as statically rendered, without a link', async () => { const marker = document.createElement('meta'); - marker.name = CACHE_ORIGIN_META_TAG_NAME; + marker.name = _INTERNAL_CACHE_ORIGIN_META_TAG_NAME; marker.content = ''; document.head.appendChild(marker); diff --git a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts index 176f7bf5c50a..bdd14979d190 100644 --- a/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts +++ b/packages/sveltekit/test/client/svelte5BrowserTracing.test.ts @@ -15,7 +15,7 @@ import { import { PAGELOAD } from '@sentry/conventions/op'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { instrumentSvelteKitTracing } from '../../src/client/svelte5BrowserTracing'; -import { CACHE_ORIGIN_META_TAG_NAME } from '../../src/common/traceMetaTags'; +import { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from '@sentry/core'; // The Svelte 5 variant reads navigation state from rune-backed helpers (`navigationState.svelte.ts`), // which need the Svelte compiler. We mock them here so the variant's orchestration logic (fetch @@ -108,7 +108,7 @@ describe('svelte5 browser tracing', () => { it('marks the pageload of a prerendered page as statically rendered, without a link', () => { const marker = document.createElement('meta'); - marker.name = CACHE_ORIGIN_META_TAG_NAME; + marker.name = _INTERNAL_CACHE_ORIGIN_META_TAG_NAME; marker.content = ''; document.head.appendChild(marker); diff --git a/packages/sveltekit/test/client/traceMetaTags.test.ts b/packages/sveltekit/test/client/traceMetaTags.test.ts deleted file mode 100644 index b491fff60f62..000000000000 --- a/packages/sveltekit/test/client/traceMetaTags.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @vitest-environment jsdom - */ - -import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes'; -import { PAGELOAD } from '@sentry/conventions/op'; -import { beforeEach, describe, expect, it } from 'vitest'; -import { withCacheOrigin } from '../../src/client/traceMetaTags'; - -const spanOptions = { name: '/pricing', attributes: { [SENTRY_OP]: PAGELOAD } }; - -function addCacheOriginTag(content: string): void { - const tag = document.createElement('meta'); - tag.name = 'sentry-cache-origin'; - tag.content = content; - document.head.appendChild(tag); -} - -describe('withCacheOrigin', () => { - beforeEach(() => { - document.head.innerHTML = ''; - }); - - it('returns the span options unchanged for a page without a cache origin tag', () => { - expect(withCacheOrigin(spanOptions)).toBe(spanOptions); - }); - - it('marks the pageload as static and links a sampled render', () => { - addCacheOriginTag('0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3-1'); - - expect(withCacheOrigin(spanOptions)).toEqual({ - name: '/pricing', - attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - links: [ - { - context: { traceId: '0b37aaf4f0d74c0e80875099e7d7ca68', spanId: 'bc3a52360214dcf3', traceFlags: 1 }, - attributes: { [SENTRY_LINK_TYPE]: 'cache_origin' }, - }, - ], - }); - }); - - it.each([ - { kind: 'an empty tag (prerendered during the build)', content: '' }, - { kind: 'an unsampled render', content: '0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3-0' }, - { kind: 'a render without a sampling decision', content: '0b37aaf4f0d74c0e80875099e7d7ca68-bc3a52360214dcf3' }, - { kind: 'a malformed value', content: 'not-a-trace' }, - ])('marks the pageload as static without a link for $kind', ({ content }) => { - addCacheOriginTag(content); - - expect(withCacheOrigin(spanOptions)).toEqual({ - name: '/pricing', - attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' }, - }); - }); -}); From 6a4315bcce775e8954e2cf21709a1bbae4168c89 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:18:05 +0100 Subject: [PATCH 085/136] fix(server-utils): Mark AI spans as cancelled when the caller aborts (#26297) **Why:** If the caller aborts an OpenAI, Anthropic or Google GenAI call before the response arrives, or aborts a non-streaming call, the span is recorded as `internal_error`. The same abort mid-stream is already `cancelled` on Google GenAI and Bedrock. These calls now record `cancelled` on both the client-wrapper path and the Orchestrion path. We check the signal, not the error name, because SDK timeouts also throw an `AbortError`. A caller's own `AbortSignal.timeout()` also stays an error: it's a timeout, and under span streaming `cancelled` is sent as `ok`. Anthropic's `messages.stream()` follows the same rule. `stream.aborted` is set for any abort of the caller's signal and doesn't say why, so its `'end'` listener now also reads the caller's signal. An abort with no signal (`stream.abort()`, or breaking out of the loop) stays `cancelled`. This also removes a duplicate `'end'` listener on Anthropic's `MessageStream`, left over from two PRs merging into the same function. **How to review:** Start with `getErrorStatus` / `markCancelledIfAborted` in `ai/core/utils.ts`. The provider changes are call sites. The new OpenAI and Anthropic `scenario-abort` integration tests fail on `develop` and pass here. Refs #26130. This covers the pre-stream item. Checking the signal after the loop for OpenAI/Anthropic mid-stream, and `cancel()` on Mistral and Workers AI, are still open there. via **Rola Abuhasna**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0C848BQ509%3A1794404980.248379) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0C848BQ509%3A1794404980.248379/?project=4510944073809921) --------- Co-authored-by: RulaKhaled Co-authored-by: Claude Opus 5.5 Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- .../tracing/anthropic/scenario-abort.mjs | 69 ++++++++++++++ .../suites/tracing/anthropic/test.ts | 27 ++++++ .../tracing/anthropic/v1/scenario-threads.mjs | 20 ++++ .../suites/tracing/anthropic/v1/test.ts | 2 + .../scenario-stream-midway-error.mjs | 27 ++++++ .../suites/tracing/google-genai/test.ts | 6 +- .../suites/tracing/openai/scenario-abort.mjs | 57 ++++++++++++ .../suites/tracing/openai/test.ts | 25 +++++ .../server-utils/src/ai/anthropic-ai/index.ts | 30 ++++-- .../src/ai/anthropic-ai/streaming.ts | 19 ++-- .../src/ai/anthropic-ai/tool-runner.ts | 7 +- packages/server-utils/src/ai/core/utils.ts | 35 ++++++- .../server-utils/src/ai/google-genai/index.ts | 31 ++++--- .../src/ai/google-genai/streaming.ts | 4 +- packages/server-utils/src/ai/openai/index.ts | 29 +++--- .../src/integrations/anthropic.ts | 27 ++++-- .../aws-sdk/services/bedrock-runtime.ts | 11 ++- .../src/integrations/google-genai.ts | 13 ++- .../src/integrations/openai-compatible.ts | 5 +- .../server-utils/src/integrations/openai.ts | 5 +- .../tracing/anthropic-ai-tool-runner.test.ts | 20 +++- .../ai/lib/tracing/anthropic-ai-usage.test.ts | 19 ++++ .../test/ai/lib/tracing/caller-abort.test.ts | 92 +++++++++++++++++++ .../test/ai/lib/tracing/stream-errors.test.ts | 12 +++ 24 files changed, 515 insertions(+), 77 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs create mode 100644 packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs new file mode 100644 index 000000000000..8a15d662c231 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs @@ -0,0 +1,69 @@ +import Anthropic from '@anthropic-ai/sdk'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +function startMockAnthropicServer() { + const app = express(); + app.use(express.json()); + + // Never responds, so each request only ends when the client gives up on it. + app.post('/anthropic/v1/messages', () => {}); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +function abortAfter(ms) { + const controller = new AbortController(); + setTimeout(() => controller.abort(), ms); + return controller.signal; +} + +async function run() { + const server = await startMockAnthropicServer(); + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + const client = new Anthropic({ + apiKey: 'mock-api-key', + baseURL: `http://localhost:${server.address().port}/anthropic`, + maxRetries: 0, + }); + const messages = [{ role: 'user', content: 'Aborted by the caller' }]; + + const requests = [ + [{ model: 'abort-before-stream', stream: true }, { signal: abortAfter(50) }], + [{ model: 'abort-non-streaming' }, { signal: abortAfter(50) }], + [{ model: 'timeout-before-stream', stream: true }, { timeout: 50 }], + [{ model: 'timeout-non-streaming' }, { timeout: 50 }], + ]; + for (const [params, requestOptions] of requests) { + try { + await client.messages.create({ ...params, max_tokens: 100, messages }, requestOptions); + } catch { + // Error expected + } + } + + const streamRequests = [ + [{ model: 'stream-helper-abort' }, { signal: abortAfter(50) }], + [{ model: 'stream-helper-signal-timeout' }, { signal: AbortSignal.timeout(50) }], + ]; + for (const [params, requestOptions] of streamRequests) { + try { + await client.messages.stream({ ...params, max_tokens: 100, messages }, requestOptions).finalMessage(); + } catch { + // Error expected + } + } + }); + + await Sentry.flush(2000); + + server.closeAllConnections(); + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts index 87d1cd735458..54dd27321cd1 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts @@ -586,4 +586,31 @@ describe('Anthropic integration', () => { }); }); }); + + createEsmAndCjsTests(__dirname, 'scenario-abort.mjs', 'instrument.mjs', (createRunner, test) => { + test('ends a call the caller aborts as cancelled, but a timeout as an error', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.anthropic'); + expect(spans).toHaveLength(6); + const statusByModel = Object.fromEntries( + spans.map(span => [span.attributes[GEN_AI_REQUEST_MODEL]?.value, span.status]), + ); + // Span streaming sends `cancelled` as `ok`. + expect(statusByModel).toEqual({ + 'abort-before-stream': 'ok', + 'abort-non-streaming': 'ok', + 'timeout-before-stream': 'error', + 'timeout-non-streaming': 'error', + 'stream-helper-abort': 'ok', + 'stream-helper-signal-timeout': 'error', + }); + }, + }) + .start() + .completed(); + }); + }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs index c2286913e5ff..b6419eebca33 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/scenario-threads.mjs @@ -73,6 +73,10 @@ function startMockAnthropicServer() { app.post('/anthropic/v1/messages', (req, res) => { const mode = req.headers['x-mode']; + // Never responds, so the request only ends when the caller's signal fires. + if (mode === 'thread_stream_signal_abort' || mode === 'thread_stream_signal_timeout') { + return; + } if (mode === 'thread_stream_error') { res.status(400).json({ type: 'error', error: { type: 'invalid_request_error', message: 'Bad thread' } }); return; @@ -197,6 +201,22 @@ const MODES = { stream.abort(); await stream.finalMessage().catch(() => {}); }, + async thread_stream_signal_abort(client) { + const controller = new AbortController(); + setTimeout(() => controller.abort(), 50); + await client.beta.messages + .thread({ model: MODEL, max_tokens: 100 }) + .stream(params.messages, {}, { signal: controller.signal }) + .finalMessage() + .catch(() => {}); + }, + async thread_stream_signal_timeout(client) { + await client.beta.messages + .thread({ model: MODEL, max_tokens: 100 }) + .stream(params.messages, {}, { signal: AbortSignal.timeout(50) }) + .finalMessage() + .catch(() => {}); + }, async thread_stream_truncated(client) { await client.beta.messages .thread({ model: MODEL, max_tokens: 100 }) diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts index 14ae36fa4292..a8b24e150714 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/v1/test.ts @@ -138,6 +138,8 @@ describe('Anthropic integration (1.x)', () => { const STATUS_ONLY_MODES = [ { mode: 'thread_stream_abort', status: 'ok' }, { mode: 'thread_stream_abort_early', status: 'ok' }, + { mode: 'thread_stream_signal_abort', status: 'ok' }, + { mode: 'thread_stream_signal_timeout', status: 'error' }, { mode: 'thread_stream_truncated', status: 'ok' }, { mode: 'thread_stream_error', status: 'error' }, ]; diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/scenario-stream-midway-error.mjs b/dev-packages/node-integration-tests/suites/tracing/google-genai/scenario-stream-midway-error.mjs index 321928dc78bf..27cd1c9f25c7 100644 --- a/dev-packages/node-integration-tests/suites/tracing/google-genai/scenario-stream-midway-error.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/scenario-stream-midway-error.mjs @@ -7,6 +7,11 @@ function startMockGoogleGenAIServer() { app.use(express.json()); app.post('/v1beta/models/:model\\:streamGenerateContent', (req, res) => { + // Never responds, so the request only ends when the client gives up on it. + if (req.params.model.endsWith('before-stream')) { + return; + } + res.setHeader('Content-Type', 'application/json'); res.setHeader('Transfer-Encoding', 'chunked'); @@ -81,6 +86,28 @@ async function run() { // Error expected } + const beforeStream = new AbortController(); + setTimeout(() => beforeStream.abort(), 50); + try { + await client.models.generateContentStream({ + model: 'caller-abort-before-stream', + contents: [{ role: 'user', parts: [{ text: 'The caller aborts before the first chunk' }] }], + config: { abortSignal: beforeStream.signal }, + }); + } catch { + // Error expected + } + + try { + await client.models.generateContentStream({ + model: 'timeout-before-stream', + contents: [{ role: 'user', parts: [{ text: 'The SDK timeout fires before the first chunk' }] }], + config: { httpOptions: { timeout: 50 } }, + }); + } catch { + // Error expected + } + try { const timedOutStream = await client.models.generateContentStream({ model: 'timeout', diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts index c9a1944151d0..afc273ab86c5 100644 --- a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts @@ -597,7 +597,7 @@ describe('Google GenAI integration', () => { .expect({ span: container => { const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); - expect(spans).toHaveLength(4); + expect(spans).toHaveLength(6); const midwaySpan = spans.find(span => span.name === 'generate_content midway-error'); expect(midwaySpan!.status).toBe('error'); @@ -613,6 +613,10 @@ describe('Google GenAI integration', () => { // `cancelled` is sent as `ok` under span streaming, so a timeout must not be recorded as one. expect(spans.find(span => span.name === 'generate_content caller-abort')!.status).toBe('ok'); expect(spans.find(span => span.name === 'generate_content timeout')!.status).toBe('error'); + expect(spans.find(span => span.name === 'generate_content caller-abort-before-stream')!.status).toBe( + 'ok', + ); + expect(spans.find(span => span.name === 'generate_content timeout-before-stream')!.status).toBe('error'); }, }) .start() diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs new file mode 100644 index 000000000000..5f225f4b7908 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs @@ -0,0 +1,57 @@ +import * as Sentry from '@sentry/node'; +import express from 'express'; +import OpenAI from 'openai'; + +function startMockServer() { + const app = express(); + app.use(express.json()); + + // Never responds, so each request only ends when the client gives up on it. + app.post('/openai/chat/completions', () => {}); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +function abortAfter(ms) { + const controller = new AbortController(); + setTimeout(() => controller.abort(), ms); + return controller.signal; +} + +async function run() { + const server = await startMockServer(); + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + const client = new OpenAI({ + baseURL: `http://localhost:${server.address().port}/openai`, + apiKey: 'mock-api-key', + maxRetries: 0, + }); + const messages = [{ role: 'user', content: 'Aborted by the caller' }]; + + const requests = [ + [{ model: 'abort-before-stream', stream: true }, { signal: abortAfter(50) }], + [{ model: 'abort-non-streaming' }, { signal: abortAfter(50) }], + [{ model: 'timeout-before-stream', stream: true }, { timeout: 50 }], + [{ model: 'timeout-non-streaming' }, { timeout: 50 }], + ]; + for (const [params, requestOptions] of requests) { + try { + await client.chat.completions.create({ ...params, messages }, requestOptions); + } catch { + // Error expected + } + } + }); + + await Sentry.flush(2000); + + server.closeAllConnections(); + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/test.ts index a6be1844dbab..98b9f8755573 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/test.ts @@ -1722,4 +1722,29 @@ describe('OpenAI integration', () => { }); }, ); + + createEsmAndCjsTests(__dirname, 'scenario-abort.mjs', 'instrument.mjs', (createRunner, test) => { + test('ends a call the caller aborts as cancelled, but an SDK timeout as an error', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.openai'); + expect(spans).toHaveLength(4); + const statusByModel = Object.fromEntries( + spans.map(span => [span.attributes[GEN_AI_REQUEST_MODEL]?.value, span.status]), + ); + // Span streaming sends `cancelled` as `ok`. + expect(statusByModel).toEqual({ + 'abort-before-stream': 'ok', + 'abort-non-streaming': 'ok', + 'timeout-before-stream': 'error', + 'timeout-non-streaming': 'error', + }); + }, + }) + .start() + .completed(); + }); + }); }); diff --git a/packages/server-utils/src/ai/anthropic-ai/index.ts b/packages/server-utils/src/ai/anthropic-ai/index.ts index eea9820cd329..4d987af2a474 100644 --- a/packages/server-utils/src/ai/anthropic-ai/index.ts +++ b/packages/server-utils/src/ai/anthropic-ai/index.ts @@ -1,5 +1,5 @@ /* eslint-disable typescript-eslint/no-deprecated */ -import { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, startSpanManual } from '@sentry/core'; +import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core'; import type { Span, SpanAttributeValue } from '@sentry/core'; import { GEN_AI_OPERATION_NAME, @@ -20,7 +20,9 @@ import { import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes'; import type { InstrumentedMethodEntry } from '../core/utils'; import { + getErrorStatus, getGenAiSpanOp, + getRequestSignal, getTokenUsageAttributes, resolveAIRecordingOptions, wrapPromiseWithMethods, @@ -165,9 +167,9 @@ export function addResponseAttributes(span: Span, response: AnthropicAiResponse, /** * Handle common error catching and reporting for streaming requests */ -function handleStreamingError(error: unknown, span: Span): never { +function handleStreamingError(error: unknown, span: Span, abortSignal: AbortSignal | undefined): never { if (span.isRecording()) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); span.end(); } throw error; @@ -186,6 +188,7 @@ function handleStreamingRequest( isStreamRequested: boolean, isStreamingMethod: boolean, ): R | Promise { + const abortSignal = getRequestSignal(args[1]); // messages.stream() always returns a sync MessageStream, even with stream: true param if (isStreamRequested && !isStreamingMethod) { let originalResult!: Promise; @@ -206,7 +209,7 @@ function handleStreamingRequest( options.recordOutputs ?? false, ) as unknown as R; } catch (error) { - return handleStreamingError(error, span); + return handleStreamingError(error, span, abortSignal); } })(); }); @@ -223,10 +226,10 @@ function handleStreamingRequest( suppressDelegatedCreate = true; const messageStream = target.apply(invocationThis, args); suppressDelegatedCreate = false; - return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false); + return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false, abortSignal); } catch (error) { suppressDelegatedCreate = false; - return handleStreamingError(error, span); + return handleStreamingError(error, span, abortSignal); } }); } @@ -296,6 +299,7 @@ function instrumentMethod( ); } + const abortSignal = getRequestSignal(args[1]); let originalResult!: Promise; const instrumentedPromise = startSpan(spanConfig, span => { @@ -305,10 +309,16 @@ function instrumentMethod( addPrivateRequestAttributes(span, params); } - return originalResult.then(result => { - addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs); - return result; - }); + return originalResult.then( + result => { + addResponseAttributes(span, result as AnthropicAiResponse, options.recordOutputs); + return result; + }, + error => { + span.setStatus(getErrorStatus(abortSignal)); + throw error; + }, + ); }); return wrapPromiseWithMethods(originalResult, instrumentedPromise); diff --git a/packages/server-utils/src/ai/anthropic-ai/streaming.ts b/packages/server-utils/src/ai/anthropic-ai/streaming.ts index 253ff094f829..8931d6098b8d 100644 --- a/packages/server-utils/src/ai/anthropic-ai/streaming.ts +++ b/packages/server-utils/src/ai/anthropic-ai/streaming.ts @@ -1,6 +1,6 @@ import { captureException, SPAN_STATUS_ERROR } from '@sentry/core'; import type { Span } from '@sentry/core'; -import { endStreamSpan } from '../core/utils'; +import { endStreamSpan, getErrorStatus } from '../core/utils'; import type { AnthropicAiStreamingEvent } from './types'; import { mapAnthropicErrorToStatusMessage } from './utils'; @@ -262,6 +262,7 @@ export function instrumentMessageStream stream: R, span: Span, recordOutputs: boolean, + abortSignal?: AbortSignal, ): R { const state: StreamingState = { responseTexts: [], @@ -290,8 +291,11 @@ export function instrumentMessageStream // Fires last on every stream, so a stream that stops without 'message' (aborted, or the body closed early) still // ends its span. An 'abort' listener would also stop the SDK from raising an unobserved abort as a rejection. stream.on('end', () => { - if (span.isRecording() && (stream as { aborted?: boolean }).aborted) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + if (span.isRecording() && stream.aborted) { + // `aborted` is also set when the caller's `AbortSignal.timeout()` fires, which is a timeout, not a cancellation. + span.setStatus( + abortSignal?.aborted ? getErrorStatus(abortSignal) : { code: SPAN_STATUS_ERROR, message: 'cancelled' }, + ); } endStreamSpan(span, state, recordOutputs); }); @@ -312,14 +316,5 @@ export function instrumentMessageStream } }); - // An aborted stream emits only `abort` and `end`. We don't listen for `abort`: doing so would stop the SDK from - // raising an unhandled rejection when the caller never awaits the aborted stream. - stream.on('end', () => { - if (stream.aborted && span.isRecording()) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); - } - endStreamSpan(span, state, recordOutputs); - }); - return stream; } diff --git a/packages/server-utils/src/ai/anthropic-ai/tool-runner.ts b/packages/server-utils/src/ai/anthropic-ai/tool-runner.ts index ebf033a462a3..f373f79c2468 100644 --- a/packages/server-utils/src/ai/anthropic-ai/tool-runner.ts +++ b/packages/server-utils/src/ai/anthropic-ai/tool-runner.ts @@ -29,7 +29,7 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes'; -import { resolveAIRecordingOptions } from '../core/utils'; +import { getErrorStatus, resolveAIRecordingOptions } from '../core/utils'; import { withCleanScopes } from '../../utils/withCleanScopes'; import { ANTHROPIC_AI_ORIGIN } from './constants'; import type { AnthropicAiOptions } from './types'; @@ -217,13 +217,12 @@ function runWithSpan( } function handleToolError(span: Span, error: unknown, context: RunContext): void { + span.setStatus(getErrorStatus(context?.signal)); + // An aborted tool, caller abort or timeout, throws because the run stopped, not because the tool failed. if (context?.signal?.aborted) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); return; } - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); - // Only a runner passes `toolUse`/`toolUseBlock` (SDK 0.85+), and it hands the throw to the model as a result. // A direct call rethrows to its caller, and a `ToolError` is sent on purpose, so neither is captured. const fromRunner = !!(context?.toolUse ?? context?.toolUseBlock); diff --git a/packages/server-utils/src/ai/core/utils.ts b/packages/server-utils/src/ai/core/utils.ts index 93949ec40eca..816c023ab08e 100644 --- a/packages/server-utils/src/ai/core/utils.ts +++ b/packages/server-utils/src/ai/core/utils.ts @@ -2,8 +2,8 @@ /** * Shared utils for AI integrations (OpenAI, Anthropic, Verce.AI, etc.) */ -import { getClient, isObjectLike, isThenable, stringify } from '@sentry/core'; -import type { Span } from '@sentry/core'; +import { getClient, isObjectLike, isThenable, SPAN_STATUS_ERROR, stringify } from '@sentry/core'; +import type { Span, SpanStatus } from '@sentry/core'; import { GEN_AI_OUTPUT_MESSAGES, GEN_AI_RESPONSE_FINISH_REASONS, @@ -233,6 +233,37 @@ export interface StreamResponseState { reasoningOutputTokens?: number; } +/** + * Reads `signal` from the request options OpenAI and Anthropic take as their second argument. + */ +export function getRequestSignal(requestOptions: unknown): AbortSignal | undefined { + return isObjectLike(requestOptions) ? (requestOptions.signal as AbortSignal | undefined) : undefined; +} + +/** + * Checks the signal rather than the error name, because SDK timeouts also throw an `AbortError`. A caller's + * own `AbortSignal.timeout()` is a timeout too, not a cancellation. + */ +export function isCallerAbort(abortSignal: AbortSignal | undefined): boolean { + return !!abortSignal?.aborted && (abortSignal.reason as { name?: unknown } | undefined)?.name !== 'TimeoutError'; +} + +/** + * A caller's abort is `cancelled`, anything else `internal_error`. + */ +export function getErrorStatus(abortSignal: AbortSignal | undefined): SpanStatus { + return { code: SPAN_STATUS_ERROR, message: isCallerAbort(abortSignal) ? 'cancelled' : 'internal_error' }; +} + +/** + * Overrides the status of a span whose call the caller aborted. + */ +export function markCancelledIfAborted(span: Span, abortSignal: AbortSignal | undefined): void { + if (isCallerAbort(abortSignal)) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + } +} + /** * Ends a streaming span by setting all accumulated response attributes and ending the span. * Shared across OpenAI, Anthropic, and Google GenAI streaming implementations. diff --git a/packages/server-utils/src/ai/google-genai/index.ts b/packages/server-utils/src/ai/google-genai/index.ts index 8b0477ae40d4..cdc1fe022b62 100644 --- a/packages/server-utils/src/ai/google-genai/index.ts +++ b/packages/server-utils/src/ai/google-genai/index.ts @@ -4,7 +4,6 @@ import { getClient, handleCallbackErrors, hasSpanStreamingEnabled, - SPAN_STATUS_ERROR, startSpan, startSpanManual, stringify, @@ -31,7 +30,13 @@ import { SENTRY_ORIGIN, } from '@sentry/conventions/attributes'; import type { InstrumentedMethodEntry } from '../core/utils'; -import { buildMethodPath, getGenAiSpanOp, getTokenUsageAttributes, resolveAIRecordingOptions } from '../core/utils'; +import { + buildMethodPath, + getErrorStatus, + getGenAiSpanOp, + getTokenUsageAttributes, + resolveAIRecordingOptions, +} from '../core/utils'; import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants'; import { instrumentStream } from './streaming'; import type { Candidate, ContentPart, GoogleGenAIOptions, GoogleGenAIResponse } from './types'; @@ -285,6 +290,13 @@ export function resolveChatParams( return { ...params, config: chatConfig }; } +/** + * Reads the caller's `config.abortSignal` from params resolved by `resolveChatParams`. + */ +export function getAbortSignal(params: Record | undefined): AbortSignal | undefined { + return (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal; +} + /** * Instrument any async or synchronous genai method with Sentry spans * Handles operations like models.generateContent and chat.sendMessage and chats.create @@ -304,6 +316,7 @@ function instrumentMethod( const operationName = instrumentedMethod.operation || 'unknown'; const params = args[0] as Record | undefined; const attributeParams = resolveChatParams(operationName, params, context); + const abortSignal = getAbortSignal(attributeParams); const requestAttributes = extractRequestAttributes( operationName, attributeParams, @@ -333,14 +346,9 @@ function instrumentMethod( addPrivateRequestAttributes(span, attributeParams, operationName); } const stream = await target.apply(context, args); - return instrumentStream( - stream, - span, - Boolean(options.recordOutputs), - (attributeParams?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal, - ) as R; + return instrumentStream(stream, span, Boolean(options.recordOutputs), abortSignal) as R; } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); span.end(); throw error; } @@ -359,11 +367,10 @@ function instrumentMethod( addPrivateRequestAttributes(span, attributeParams, operationName); } - // `onError` is a no-op because the rejection is rethrown to the caller and `startSpan` already - // marks the span errored; both leading callbacks are positional and only exist to reach `onSuccess`. + // The rejection is rethrown to the caller. `startSpan` keeps the status set here. return handleCallbackErrors( () => target.apply(context, args), - () => {}, + () => span.setStatus(getErrorStatus(abortSignal)), () => {}, result => { // Only add response attributes for content-producing methods, not for embeddings diff --git a/packages/server-utils/src/ai/google-genai/streaming.ts b/packages/server-utils/src/ai/google-genai/streaming.ts index 3b19a991e0d0..9aa416d650ad 100644 --- a/packages/server-utils/src/ai/google-genai/streaming.ts +++ b/packages/server-utils/src/ai/google-genai/streaming.ts @@ -1,6 +1,6 @@ import { captureException, SPAN_STATUS_ERROR } from '@sentry/core'; import type { Span } from '@sentry/core'; -import { endStreamSpan } from '../core/utils'; +import { endStreamSpan, getErrorStatus } from '../core/utils'; import type { GoogleGenAIResponse } from './types'; import type { MessagePart } from './utils'; import { candidatesToMessageParts, setOutputMessagesAttribute } from './utils'; @@ -137,7 +137,7 @@ export async function* instrumentStream( yield chunk; } } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: abortSignal?.aborted ? 'cancelled' : 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); throw error; } finally { if (recordOutputs) { diff --git a/packages/server-utils/src/ai/openai/index.ts b/packages/server-utils/src/ai/openai/index.ts index ada47a5710c7..06d34be7b412 100644 --- a/packages/server-utils/src/ai/openai/index.ts +++ b/packages/server-utils/src/ai/openai/index.ts @@ -1,14 +1,6 @@ /* eslint-disable typescript-eslint/no-deprecated */ import { DEBUG_BUILD } from '../../debug-build'; -import { - getClient, - hasSpanStreamingEnabled, - SPAN_STATUS_ERROR, - startSpan, - startSpanManual, - debug, - stringify, -} from '@sentry/core'; +import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core'; import type { Span, SpanAttributeValue } from '@sentry/core'; import { GEN_AI_EMBEDDINGS_INPUT, @@ -24,7 +16,9 @@ import type { InstrumentedMethodEntry } from '../core/utils'; import { buildMethodPath, extractSystemInstructions, + getErrorStatus, getGenAiSpanOp, + getRequestSignal, resolveAIRecordingOptions, wrapPromiseWithMethods, } from '../core/utils'; @@ -158,6 +152,7 @@ function instrumentMethod( const params = args[0] as Record | undefined; const isStreamRequested = params && typeof params === 'object' && params.stream === true; + const abortSignal = getRequestSignal(args[1]); const client = getClient(); const spanConfig = { @@ -190,7 +185,7 @@ function instrumentMethod( options.recordOutputs ?? false, ) as unknown as R; } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); span.end(); throw error; } @@ -211,10 +206,16 @@ function instrumentMethod( addRequestAttributes(span, params, operationName); } - return originalResult.then(result => { - addResponseAttributes(span, result, options.recordOutputs, operationName); - return result; - }); + return originalResult.then( + result => { + addResponseAttributes(span, result, options.recordOutputs, operationName); + return result; + }, + error => { + span.setStatus(getErrorStatus(abortSignal)); + throw error; + }, + ); }); return wrapPromiseWithMethods(originalResult, instrumentedPromise); diff --git a/packages/server-utils/src/integrations/anthropic.ts b/packages/server-utils/src/integrations/anthropic.ts index 7b9251342c5c..2a9e51d17d22 100644 --- a/packages/server-utils/src/integrations/anthropic.ts +++ b/packages/server-utils/src/integrations/anthropic.ts @@ -2,7 +2,7 @@ import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attribu import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; import { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core'; -import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; +import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes } from '../ai/anthropic-ai'; import { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants'; @@ -61,6 +61,9 @@ function instrumentAnthropic(options: AnthropicAiOptions): void { data => createGenAiSpan(data, operation, options, stream), { beforeSpanEnd: (span, data) => { + if ('error' in data) { + markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1])); + } addResponseAttributes( span, data.result as AnthropicAiResponse, @@ -98,9 +101,12 @@ function instrumentAnthropic(options: AnthropicAiOptions): void { diagnosticsChannel .tracingChannel(CHANNELS.ANTHROPIC_THREAD_STREAM) .start.subscribe(message => { - const stream = (message as OrchestrionChannelContext).self as ThreadStream | undefined; + const data = message as OrchestrionChannelContext; + const stream = data.self as ThreadStream | undefined; if (isMessageStream(stream) && stream.controller?.signal) { - threadStreams.set(stream.controller.signal, stream); + // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry + // the reason a caller's signal fired with. + threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) }); } }); } @@ -210,7 +216,7 @@ type ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { sig * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a * stream parses the response itself, so the `create()` result is never parsed and never ends its span. */ -const threadStreams = new WeakMap(); +const threadStreams = new WeakMap(); /** * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may @@ -223,12 +229,13 @@ function wrapThreadStreamRequest( options: AnthropicAiOptions, ): boolean { const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal; - const stream = signal && threadStreams.get(signal); + const threadStream = signal && threadStreams.get(signal); const request = data.result as { _responseProps?: () => Promise } | undefined; // A finished stream sends no more requests, so a later call with its signal is the caller's own. - if (!stream || stream.ended || typeof request?._responseProps !== 'function') { + if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') { return false; } + const { stream, callerSignal } = threadStream; const { recordOutputs } = resolveAIRecordingOptions(options); // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on. @@ -236,12 +243,12 @@ function wrapThreadStreamRequest( () => { // Only a rejected attempt is retried, so nothing else may claim this stream. threadStreams.delete(signal); - instrumentMessageStream(stream, span, recordOutputs); + instrumentMessageStream(stream, span, recordOutputs, callerSignal); }, error => { - // A caller abort is not a failed request. The stream still emits 'end', which ends the span as cancelled. + // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal. if (signal.aborted) { - instrumentMessageStream(stream, span, recordOutputs); + instrumentMessageStream(stream, span, recordOutputs, callerSignal); } else { end(error); } @@ -275,7 +282,7 @@ function wrapStreamResult( } if (stream === 'message-stream' && isMessageStream(result)) { - instrumentMessageStream(result, span, recordOutputs); + instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1])); return true; } diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts index f77e04f6f5ed..aab0bf1383c0 100644 --- a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime.ts @@ -1,5 +1,5 @@ import type { Span } from '@sentry/core'; -import { debug, SPAN_STATUS_ERROR } from '@sentry/core'; +import { debug } from '@sentry/core'; import { GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, @@ -14,7 +14,12 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op'; import type { StreamResponseState } from '../../../ai/core/utils'; -import { endStreamSpan, getTokenUsageAttributes, resolveAIRecordingOptions } from '../../../ai/core/utils'; +import { + endStreamSpan, + getErrorStatus, + getTokenUsageAttributes, + resolveAIRecordingOptions, +} from '../../../ai/core/utils'; import { isInsidePiAiSpan } from '../../../ai/pi-ai/providers'; import { DEBUG_BUILD } from '../../../debug-build'; import { @@ -459,7 +464,7 @@ async function* instrumentStream( yield item; } } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: abortSignal?.aborted ? 'cancelled' : 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); throw error; } finally { endStreamSpan(span, state, false); diff --git a/packages/server-utils/src/integrations/google-genai.ts b/packages/server-utils/src/integrations/google-genai.ts index 2170f040a4e5..6ffae5f8df56 100644 --- a/packages/server-utils/src/integrations/google-genai.ts +++ b/packages/server-utils/src/integrations/google-genai.ts @@ -9,11 +9,12 @@ import { spanToJSON, startInactiveSpan, } from '@sentry/core'; -import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; +import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils'; import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes, + getAbortSignal, resolveChatParams, } from '../ai/google-genai'; import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; @@ -54,6 +55,14 @@ function instrumentGoogleGenai(options: GoogleGenAIOptions): void { data => createGenAiSpan(data, operation, options), { beforeSpanEnd: (span, data) => { + if ('error' in data) { + const params = resolveChatParams( + operation, + data.arguments?.[0] as Record | undefined, + data.self, + ); + markCancelledIfAborted(span, getAbortSignal(params)); + } // Embeddings responses carry no content attributes. if (operation !== 'embeddings') { addResponseAttributes( @@ -152,7 +161,7 @@ function wrapStreamResult( { [Symbol.asyncIterator]: iterate }, span, recordOutputs ?? false, - (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal, + getAbortSignal(params), ); result[Symbol.asyncIterator] = () => instrumented; diff --git a/packages/server-utils/src/integrations/openai-compatible.ts b/packages/server-utils/src/integrations/openai-compatible.ts index 48bacae5bcf8..4e4a0301a8b8 100644 --- a/packages/server-utils/src/integrations/openai-compatible.ts +++ b/packages/server-utils/src/integrations/openai-compatible.ts @@ -7,7 +7,7 @@ import { startInactiveSpan, } from '@sentry/core'; import { GEN_AI_PROVIDER_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; -import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; +import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { addRequestAttributes, extractRequestAttributes } from '../ai/openai'; import { instrumentStream } from '../ai/openai/streaming'; @@ -56,6 +56,9 @@ export function createOpenAiCompatibleIntegration createGenAiSpan(data, operation, provider, options), { beforeSpanEnd: (span, data) => { + if ('error' in data) { + markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1])); + } addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs); }, deferSpanEnd: ({ span, data, end }) => diff --git a/packages/server-utils/src/integrations/openai.ts b/packages/server-utils/src/integrations/openai.ts index 88e58a172b0c..3dda9492956e 100644 --- a/packages/server-utils/src/integrations/openai.ts +++ b/packages/server-utils/src/integrations/openai.ts @@ -2,7 +2,7 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; import { defineIntegration, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core'; -import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; +import { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils'; import { addRequestAttributes, extractRequestAttributes } from '../ai/openai'; import { wrapApiPromiseResponse } from '../ai/core/apiPromise'; import { instrumentStream } from '../ai/openai/streaming'; @@ -44,6 +44,9 @@ function instrumentOpenai(options: OpenAiOptions): void { data => createGenAiSpan(data, operation, options), { beforeSpanEnd: (span, data) => { + if ('error' in data) { + markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1])); + } addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs, operation); }, deferSpanEnd: ({ span, data, end }) => diff --git a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-tool-runner.test.ts b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-tool-runner.test.ts index 5736a661188c..ff685f561b2e 100644 --- a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-tool-runner.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-tool-runner.test.ts @@ -256,7 +256,7 @@ describe('instrumentAnthropicAiClient tool runner', () => { expect(events).toHaveLength(0); }); - it('does not capture a ToolError or a call aborted by the runner', async () => { + it('does not capture a ToolError or a call aborted by the runner, but marks a timed-out one as an error', async () => { const toolError = Object.assign(new Error('bad input'), { name: 'ToolError' }); const refuses = tool('refuses', async () => { throw toolError; @@ -265,13 +265,27 @@ describe('instrumentAnthropicAiClient tool runner', () => { throw new Error('aborted'); }); - instrumentAnthropicAiClient(fakeClient()).beta.messages.toolRunner({ tools: [refuses, aborted] }); + const timedOut = tool('timedOut', async () => { + throw new Error('timed out'); + }); + + instrumentAnthropicAiClient(fakeClient()).beta.messages.toolRunner({ tools: [refuses, aborted, timedOut] }); await expect(refuses.run({}, { toolUse: { id: 'toolu_1' } })).rejects.toBe(toolError); await expect(aborted.run({}, { toolUse: { id: 'toolu_2' }, signal: AbortSignal.abort() })).rejects.toThrow( 'aborted', ); - expect(toolSpans().map(span => span.status)).toEqual(['internal_error', 'cancelled']); + await expect( + timedOut.run( + {}, + { + toolUse: { id: 'toolu_3' }, + signal: AbortSignal.abort(new DOMException('The operation timed out', 'TimeoutError')), + }, + ), + ).rejects.toThrow('timed out'); + + expect(toolSpans().map(span => span.status)).toEqual(['internal_error', 'cancelled', 'internal_error']); expect(events).toHaveLength(0); }); diff --git a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts index 78569bc446ec..5d06a19c1e80 100644 --- a/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/anthropic-ai-usage.test.ts @@ -312,6 +312,25 @@ describe('instrumentMessageStream', () => { }); }); + it.each([ + { reason: 'the caller aborts its signal', signal: AbortSignal.abort(), status: 'cancelled' }, + { + reason: "the caller's AbortSignal.timeout() fired", + signal: AbortSignal.abort(new DOMException('The operation timed out', 'TimeoutError')), + status: 'internal_error', + }, + ])('ends an aborted stream as $status when $reason', ({ signal, status }) => { + const { span } = createMockSpan(); + const setStatus = vi.fn(); + Object.assign(span, { setStatus }); + const stream = instrumentMessageStream(Object.assign(new EventEmitter(), { aborted: true }), span, false, signal); + + stream.emit('end'); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: status }); + }); + it('leaves the status alone when the body closes early without an abort', () => { const { span } = createMockSpan(); const setStatus = vi.fn(); diff --git a/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts b/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts new file mode 100644 index 000000000000..e9e999e1b2fe --- /dev/null +++ b/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts @@ -0,0 +1,92 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getMainCarrier, setCurrentClient, spanToStaticSpanJSON } from '@sentry/core'; +import type { Span } from '@sentry/core'; +import { instrumentAnthropicAiClient } from '../../../../src/ai/anthropic-ai'; +import { instrumentGoogleGenAIClient } from '../../../../src/ai/google-genai'; +import { instrumentOpenAiClient } from '../../../../src/ai/openai'; +import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; + +type Call = (signal: AbortSignal, stream: boolean) => Promise; + +// Each provider's SDK rejects with an `AbortError` for both a caller abort and its own timeout. +function rejectingMethod(): ReturnType { + return vi.fn().mockRejectedValue(new DOMException('This operation was aborted', 'AbortError')); +} + +const providers: Array<{ name: string; call: () => Call }> = [ + { + name: 'openai', + call: () => { + const client = instrumentOpenAiClient({ chat: { completions: { create: rejectingMethod() } } }); + return (signal, stream) => client.chat.completions.create({ model: 'gpt-4o', messages: [], stream }, { signal }); + }, + }, + { + name: 'anthropic', + call: () => { + const client = instrumentAnthropicAiClient({ messages: { create: rejectingMethod() } }); + return (signal, stream) => + client.messages.create({ model: 'claude-sonnet-4-5', max_tokens: 10, messages: [], stream }, { signal }); + }, + }, + { + name: 'google-genai', + call: () => { + const client = instrumentGoogleGenAIClient({ + models: { generateContent: rejectingMethod(), generateContentStream: rejectingMethod() }, + }); + return (signal, stream) => { + const params = { model: 'gemini-2.5-flash', contents: 'Hello', config: { abortSignal: signal } }; + return stream ? client.models.generateContentStream(params) : client.models.generateContent(params); + }; + }, + }, +]; + +describe.each(providers)('$name caller aborts', ({ call }) => { + let endedSpans: Span[]; + + beforeEach(() => { + getMainCarrier().__SENTRY__ = undefined; + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + traceLifecycle: 'static', + }), + ); + setCurrentClient(client); + client.init(); + endedSpans = []; + client.on('spanEnd', span => endedSpans.push(span)); + }); + + afterEach(() => { + getMainCarrier().__SENTRY__ = undefined; + }); + + async function statusAfterRejection(signal: AbortSignal, stream: boolean): Promise { + await expect(call()(signal, stream)).rejects.toThrow('This operation was aborted'); + expect(endedSpans).toHaveLength(1); + return spanToStaticSpanJSON(endedSpans[0]!).status; + } + + describe.each([ + { kind: 'streaming', stream: true }, + { kind: 'non-streaming', stream: false }, + ])('$kind request', ({ stream }) => { + it('marks the span as cancelled when the caller aborts before the response', async () => { + expect(await statusAfterRejection(AbortSignal.abort(), stream)).toBe('cancelled'); + }); + + it("marks the span as errored when the caller's own timeout fired", async () => { + const timeoutSignal = AbortSignal.abort(new DOMException('The operation timed out', 'TimeoutError')); + + expect(await statusAfterRejection(timeoutSignal, stream)).toBe('internal_error'); + }); + + it("marks the span as errored when the request fails without the caller's signal firing", async () => { + expect(await statusAfterRejection(new AbortController().signal, stream)).toBe('internal_error'); + }); + }); +}); diff --git a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts index 30c37aec9ba5..8e7d1f490169 100644 --- a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts @@ -176,6 +176,18 @@ describe('google-genai stream aborts', () => { expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); }); + it("marks the span as errored when the caller's own timeout fired", async () => { + const { span, setStatus } = createMockSpan(); + const timeoutSignal = AbortSignal.abort(new DOMException('The operation timed out', 'TimeoutError')); + + await expect(drain(instrumentGoogleGenAIStream(abortedStream(), span, false, timeoutSignal))).rejects.toBe( + abortError, + ); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + }); + it("marks the span as errored when an abort didn't come from the caller's signal", async () => { const { span, setStatus } = createMockSpan(); From 14e0d5683730ffd62f123e70e59e9210ed31172d Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Fri, 13 Nov 2026 17:44:39 +0000 Subject: [PATCH 086/136] feat(node): Instrument HTTP/2 servers that use the compat API (#25992) Node only publishes `http.server.request.start` for `node:http` servers, so `node:http2` requests (Fastify `http2: true`, Hono, srvx with TLS) got no isolation, trace continuation, spans or sessions. On `http2.server.stream.start` we now wrap `stream.session.server`'s emit like for HTTP/1, and the compat API's `'request'` event runs through the existing pipeline. Raw `'stream'` API servers (gRPC) are out of scope. Unlike `http.server.request.start`, the HTTP/2 channel message has no `server`, so we read it from `stream.session.server`. That getter exists on `ServerHttp2Session` in Node 22 and 24 but is not in the Node docs. If Node removes it, the listener does nothing and HTTP/2 requests are untraced again, as today. --- .../tracing/http2-server/instrument.mjs | 9 ++ .../tracing/http2-server/scenario-fastify.mjs | 26 +++++ .../suites/tracing/http2-server/scenario.mjs | 41 +++++++ .../suites/tracing/http2-server/test.ts | 103 ++++++++++++++++++ packages/core/src/index.ts | 1 + .../core/src/integrations/http/constants.ts | 3 +- .../integrations/http/server-subscription.ts | 21 +++- packages/core/src/server.ts | 2 +- packages/core/src/utils/request.ts | 14 ++- .../lib/integrations/http/constants.test.ts | 5 + .../http/server-subscription.test.ts | 43 +++++++- packages/core/test/lib/utils/request.test.ts | 34 ++++++ .../http/httpServerIntegration.ts | 13 ++- .../http/httpServerSpansIntegration.ts | 8 +- 14 files changed, 309 insertions(+), 14 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/http2-server/instrument.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/http2-server/scenario-fastify.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/http2-server/scenario.mjs create mode 100644 dev-packages/node-integration-tests/suites/tracing/http2-server/test.ts diff --git a/dev-packages/node-integration-tests/suites/tracing/http2-server/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/http2-server/instrument.mjs new file mode 100644 index 000000000000..46a27dd03b74 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/http2-server/instrument.mjs @@ -0,0 +1,9 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + tracesSampleRate: 1.0, + transport: loggingTransport, +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario-fastify.mjs b/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario-fastify.mjs new file mode 100644 index 000000000000..d26b38fba250 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario-fastify.mjs @@ -0,0 +1,26 @@ +import Fastify from 'fastify'; +import http2 from 'node:http2'; + +async function run() { + const app = Fastify({ http2: true }); + + app.get('/users/:id', async () => { + return { ok: true }; + }); + + await app.listen({ port: 0 }); + + const client = http2.connect(`http://localhost:${app.server.address().port}`); + await new Promise((resolve, reject) => { + const stream = client.request({ ':path': '/users/42' }); + stream.on('error', reject); + stream.on('data', () => {}); + stream.on('end', resolve); + stream.end(); + }); + + client.close(); + await app.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario.mjs b/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario.mjs new file mode 100644 index 000000000000..db90c22c2e5c --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/http2-server/scenario.mjs @@ -0,0 +1,41 @@ +import * as Sentry from '@sentry/node'; +import http2 from 'node:http2'; + +const server = http2.createServer((request, response) => { + if (request.url === '/error') { + Sentry.captureException(new Error('error in http2 handler')); + response.statusCode = 500; + response.end(); + return; + } + + Sentry.startSpan({ name: 'handler-work' }, () => {}); + response.end('ok'); +}); + +function request(client, headers) { + return new Promise((resolve, reject) => { + const stream = client.request(headers); + stream.on('error', reject); + stream.on('data', () => {}); + stream.on('end', resolve); + stream.end(); + }); +} + +server.listen(0, async () => { + const client = http2.connect(`http://localhost:${server.address().port}`); + + await request(client, { + ':path': '/users/42?q=1', + 'sentry-trace': '12312012123120121231201212312012-1121201211212012-1', + baggage: 'sentry-release=2.1.0,sentry-environment=myEnv', + }); + await request(client, { + ':path': '/error', + 'sentry-trace': '45645645645645645645645645645645-4564564564564564-1', + }); + + client.close(); + server.close(); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/http2-server/test.ts b/dev-packages/node-integration-tests/suites/tracing/http2-server/test.ts new file mode 100644 index 000000000000..3559b8378261 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/http2-server/test.ts @@ -0,0 +1,103 @@ +import { + HTTP_RESPONSE_STATUS_CODE, + NETWORK_PROTOCOL_VERSION, + SENTRY_OP, + SENTRY_ORIGIN, + SERVER_ADDRESS, + URL_PATH, + URL_QUERY, +} from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import { afterAll, describe, expect } from 'vitest'; +import { supports } from '../../../utils'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +describe.runIf(supports({ min: 22, runtimes: ['node'] }))('http2 server', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('isolates compat API requests and continues their traces', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const segment = container.items.find(item => item.is_segment); + expect(segment?.attributes[URL_PATH]?.value).toBe('/users/42'); + + expect(segment).toMatchObject({ + name: 'GET', + trace_id: '12312012123120121231201212312012', + parent_span_id: '1121201211212012', + status: 'ok', + }); + expect(segment?.attributes).toMatchObject({ + [SENTRY_OP]: { value: HTTP_SERVER }, + [SENTRY_ORIGIN]: { value: 'auto.http.http_server' }, + [URL_QUERY]: { value: 'q=1' }, + [SERVER_ADDRESS]: { value: 'localhost' }, + [NETWORK_PROTOCOL_VERSION]: { value: '2.0' }, + [HTTP_RESPONSE_STATUS_CODE]: { value: 200 }, + }); + expect(Object.keys(segment?.attributes ?? {}).filter(key => key.includes(':'))).toEqual([]); + + const child = container.items.find(item => item.name === 'handler-work'); + expect(child?.parent_span_id).toBe(segment?.span_id); + }, + }) + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('error in http2 handler'); + expect(event.request?.url).toMatch(/^http:\/\/localhost:\d+\/error$/); + expect(event.request?.method).toBe('GET'); + expect(Object.keys(event.request?.headers ?? {}).filter(key => key.startsWith(':'))).toEqual([]); + expect(event.transaction).toBe('GET /error'); + expect(event.contexts?.trace?.trace_id).toBe('45645645645645645645645645645645'); + }, + }) + .expect({ + span: container => { + const segment = container.items.find(item => item.is_segment); + expect(segment?.attributes[URL_PATH]?.value).toBe('/error'); + expect(segment?.status).toBe('error'); + expect(segment?.attributes[HTTP_RESPONSE_STATUS_CODE]?.value).toBe(500); + expect(segment?.trace_id).toBe('45645645645645645645645645645645'); + }, + }) + .start() + .completed(); + }); + + test('does not trigger HTTP/2 compat API warnings', async () => { + await createRunner().ensureNoErrorOutput().start().completed(); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario-fastify.mjs', 'instrument.mjs', (createRunner, test) => { + test('nests fastify spans under the HTTP/2 server span', async () => { + await createRunner() + .expect({ + span: container => { + const segment = container.items.find(item => item.is_segment); + expect(segment?.name).toBe('GET /users/:id'); + expect(segment?.attributes).toMatchObject({ + [SENTRY_OP]: { value: HTTP_SERVER }, + [NETWORK_PROTOCOL_VERSION]: { value: '2.0' }, + [HTTP_RESPONSE_STATUS_CODE]: { value: 200 }, + }); + + const fastifySpans = container.items.filter( + item => item.attributes[SENTRY_ORIGIN]?.value === 'auto.http.fastify', + ); + expect(fastifySpans.length).toBeGreaterThan(0); + for (const span of fastifySpans) { + expect(span.trace_id).toBe(segment?.trace_id); + } + }, + }) + .start() + .completed(); + }); + }); +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 11fd3f6cad1f..1af72cd73655 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -147,6 +147,7 @@ export { httpRequestToRequestData, extractQueryParamsFromUrl, headersToDict, + getHostFromHeaders, httpHeadersToSpanAttributes, getContentLengthFromHeaders, getMaxBodyByteLength, diff --git a/packages/core/src/integrations/http/constants.ts b/packages/core/src/integrations/http/constants.ts index f2af12b00b62..0fad2962451e 100644 --- a/packages/core/src/integrations/http/constants.ts +++ b/packages/core/src/integrations/http/constants.ts @@ -1,5 +1,6 @@ export const LOG_PREFIX = '@sentry/instrumentation-http'; export const HTTP_ON_CLIENT_REQUEST = 'http.client.request.created'; export const HTTP_ON_SERVER_REQUEST = 'http.server.request.start'; +export const HTTP2_ON_SERVER_STREAM = 'http2.server.stream.start'; export type ClientSubscriptionName = typeof HTTP_ON_CLIENT_REQUEST; -export type ServerSubscriptionName = typeof HTTP_ON_SERVER_REQUEST; +export type ServerSubscriptionName = typeof HTTP_ON_SERVER_REQUEST | typeof HTTP2_ON_SERVER_STREAM; diff --git a/packages/core/src/integrations/http/server-subscription.ts b/packages/core/src/integrations/http/server-subscription.ts index 40298235066b..7acf305b6a5c 100644 --- a/packages/core/src/integrations/http/server-subscription.ts +++ b/packages/core/src/integrations/http/server-subscription.ts @@ -19,7 +19,7 @@ import type { ServerSubscriptionName } from './constants'; type ChannelListener = (message: unknown, name: string | symbol) => void; -import { HTTP_ON_SERVER_REQUEST } from './constants'; +import { HTTP2_ON_SERVER_STREAM, HTTP_ON_SERVER_REQUEST } from './constants'; import type { HttpIncomingMessage, HttpInstrumentationOptions, HttpServer, HttpServerResponse } from './types'; import { DEBUG_BUILD } from '../../debug-build'; import { debug } from '../../utils/debug-logger'; @@ -30,6 +30,7 @@ import { getClient, getCurrentScope, getIsolationScope, withIsolationScope } fro import { hasSpansEnabled } from '../../utils/hasSpansEnabled'; import { getContentLengthFromHeaders, + getHostFromHeaders, headersToDict, httpHeadersToSpanAttributes, httpRequestToRequestData, @@ -280,7 +281,17 @@ export function getHttpServerSubscriptions(options: HttpInstrumentationOptions): instrumentServer(effectiveOptions, server); }; - return { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequest }; + // HTTP/2 servers emit the compat API's `'request'` event from inside their + // `'stream'` listener, so the same emit wrapper covers them. Servers that + // use only the raw `'stream'` API (e.g. gRPC) are not instrumented. + const onHttp2ServerStream: ChannelListener = (data: unknown): void => { + const server = (data as { stream?: { session?: { server?: HttpServer } } }).stream?.session?.server; + if (server) { + instrumentServer(effectiveOptions, server); + } + }; + + return { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequest, [HTTP2_ON_SERVER_STREAM]: onHttp2ServerStream }; } function buildServerSpanWrap( @@ -335,7 +346,7 @@ function buildServerSpanWrap( const headers = request.headers; const userAgent = headers['user-agent']; const httpVersion = request.httpVersion; - const host = headers.host as undefined | string; + const host = getHostFromHeaders(headers); const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') || 'localhost'; const scheme = fullUrl.startsWith('https') ? 'https' : 'http'; const { socket } = request; @@ -398,7 +409,9 @@ function buildServerSpanWrap( isEnded = true; // set attributes that come from the response span.setAttributes({ - [HTTP_RESPONSE_STATUS_TEXT]: response.statusMessage?.toUpperCase(), + // HTTP/2 has no status text, and reading it emits a process warning. + [HTTP_RESPONSE_STATUS_TEXT]: + request.httpVersion === '2.0' ? undefined : response.statusMessage?.toUpperCase(), [HTTP_RESPONSE_STATUS_CODE]: response.statusCode, ...httpHeadersToSpanAttributes(headersToDict(response.headers), dataCollectionOptions, 'response'), }); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 50dfb6639b05..ad4d521f39bc 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -62,7 +62,7 @@ export { getRequestUrlFromClientRequest, getRequestOptions, } from './integrations/http/get-request-url'; -export { HTTP_ON_CLIENT_REQUEST, HTTP_ON_SERVER_REQUEST } from './integrations/http/constants'; +export { HTTP_ON_CLIENT_REQUEST, HTTP_ON_SERVER_REQUEST, HTTP2_ON_SERVER_STREAM } from './integrations/http/constants'; export type { HttpInstrumentationOptions, HttpClientRequest, diff --git a/packages/core/src/utils/request.ts b/packages/core/src/utils/request.ts index 82c7135fb2ac..9527b97d534e 100644 --- a/packages/core/src/utils/request.ts +++ b/packages/core/src/utils/request.ts @@ -74,6 +74,10 @@ export function headersToDict( try { Object.entries(reqHeaders).forEach(([key, value]) => { + // HTTP/2 pseudo-headers (`:method`, `:path`, ...) are not headers. + if (key.startsWith(':')) { + return; + } if (typeof value === 'string') { headers[key] = value; } else if (typeof value === 'number') { @@ -87,6 +91,14 @@ export function headersToDict( return headers; } +/** + * The `host` header, or the HTTP/2 `:authority` pseudo-header that replaces it. + */ +export function getHostFromHeaders(headers: Record): string | undefined { + const host = headers.host ?? headers[':authority']; + return typeof host === 'string' ? host : undefined; +} + /** * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands. */ @@ -213,7 +225,7 @@ export function httpRequestToRequestData(request: { // Check for x-forwarded-host first, then fall back to host header const forwardedHost = typeof headers['x-forwarded-host'] === 'string' ? headers['x-forwarded-host'] : undefined; - const host = forwardedHost || (typeof headers.host === 'string' ? headers.host : undefined); + const host = forwardedHost || getHostFromHeaders(headers); // Check for x-forwarded-proto first, then fall back to existing protocol detection const forwardedProto = typeof headers['x-forwarded-proto'] === 'string' ? headers['x-forwarded-proto'] : undefined; diff --git a/packages/core/test/lib/integrations/http/constants.test.ts b/packages/core/test/lib/integrations/http/constants.test.ts index 6a63e74ba5c6..d666c6167456 100644 --- a/packages/core/test/lib/integrations/http/constants.test.ts +++ b/packages/core/test/lib/integrations/http/constants.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; import { + HTTP2_ON_SERVER_STREAM, HTTP_ON_CLIENT_REQUEST, HTTP_ON_SERVER_REQUEST, LOG_PREFIX, @@ -17,4 +18,8 @@ describe('http constants', () => { it('HTTP_ON_SERVER_REQUEST is the diagnostics-channel name', () => { expect(HTTP_ON_SERVER_REQUEST).toBe('http.server.request.start'); }); + + it('HTTP2_ON_SERVER_STREAM is the diagnostics-channel name', () => { + expect(HTTP2_ON_SERVER_STREAM).toBe('http2.server.stream.start'); + }); }); diff --git a/packages/core/test/lib/integrations/http/server-subscription.test.ts b/packages/core/test/lib/integrations/http/server-subscription.test.ts index 04c50f221632..68bd2327e304 100644 --- a/packages/core/test/lib/integrations/http/server-subscription.test.ts +++ b/packages/core/test/lib/integrations/http/server-subscription.test.ts @@ -1,6 +1,8 @@ import { CLIENT_ADDRESS, CLIENT_PORT, + HTTP_RESPONSE_STATUS_CODE, + HTTP_RESPONSE_STATUS_TEXT, NETWORK_LOCAL_ADDRESS, NETWORK_LOCAL_PORT, NETWORK_PEER_ADDRESS, @@ -8,13 +10,16 @@ import { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION, NETWORK_TRANSPORT, + SENTRY_OP, SERVER_ADDRESS, SERVER_PORT, URL_FULL, URL_PATH, URL_QUERY, } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; import * as http from 'node:http'; +import * as http2 from 'node:http2'; import type { AddressInfo } from 'node:net'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -22,7 +27,7 @@ import { getIsolationScope } from '../../../../src/currentScopes'; import { Scope } from '../../../../src/scope'; import { spanToJSON } from '../../../../src/utils/spanUtils'; import { setCurrentClient } from '../../../../src/sdk'; -import { HTTP_ON_SERVER_REQUEST } from '../../../../src/integrations/http/constants'; +import { HTTP2_ON_SERVER_STREAM, HTTP_ON_SERVER_REQUEST } from '../../../../src/integrations/http/constants'; import { getHttpServerSubscriptions } from '../../../../src/integrations/http/server-subscription'; import type { HttpInstrumentationOptions } from '../../../../src/integrations/http/types'; import type { Event } from '../../../../src/types/event'; @@ -147,6 +152,42 @@ describe('getHttpServerSubscriptions', () => { ); }); + it('creates a root http.server span for an HTTP/2 compat API request', async () => { + const http2Server = http2.createServer((_req, res) => res.end('ok')); + server = http2Server as unknown as http.Server; + await new Promise(resolve => http2Server.listen(0, '127.0.0.1', () => resolve())); + + const { [HTTP2_ON_SERVER_STREAM]: onServerStream } = getHttpServerSubscriptions({ spans: true }); + // The listener must run before the compat API's own 'stream' listener, like the channel does. + http2Server.prependListener('stream', stream => onServerStream({ stream }, HTTP2_ON_SERVER_STREAM)); + + const { port } = http2Server.address() as AddressInfo; + const session = http2.connect(`http://127.0.0.1:${port}`); + await new Promise((resolve, reject) => { + const stream = session.request({ ':path': '/users/42?foo=bar' }); + stream.on('error', reject); + stream.resume(); + stream.on('end', resolve); + stream.end(); + }); + session.close(); + + const transaction = await waitForTransaction(); + const data = transaction.contexts?.trace?.data; + expect(transaction.transaction).toBe('GET /users/42'); + expect(data).toEqual( + expect.objectContaining({ + [SENTRY_OP]: HTTP_SERVER, + [HTTP_RESPONSE_STATUS_CODE]: 200, + [URL_FULL]: `http://127.0.0.1:${port}/users/42?foo=bar`, + [SERVER_ADDRESS]: '127.0.0.1', + [NETWORK_PROTOCOL_VERSION]: '2.0', + }), + ); + expect(data).not.toHaveProperty(HTTP_RESPONSE_STATUS_TEXT); + expect(Object.keys(data ?? {}).filter(key => key.includes(':'))).toEqual([]); + }); + it('prefers the forwarded client over the socket for `client.address`', async () => { server = http.createServer((_req, res) => res.end('ok')); await new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve())); diff --git a/packages/core/test/lib/utils/request.test.ts b/packages/core/test/lib/utils/request.test.ts index 640e7c118f66..30af4105ea51 100644 --- a/packages/core/test/lib/utils/request.test.ts +++ b/packages/core/test/lib/utils/request.test.ts @@ -64,6 +64,19 @@ describe('request utils', () => { 'x-string': 'hello', }); }); + + it('drops HTTP/2 pseudo-headers', () => { + expect( + headersToDict({ + ':method': 'GET', + ':path': '/users', + ':authority': 'example.com', + 'user-agent': 'test', + }), + ).toEqual({ + 'user-agent': 'test', + }); + }); }); describe('winterCGRequestToRequestData', () => { @@ -143,6 +156,27 @@ describe('request utils', () => { }); }); + it('uses the HTTP/2 :authority pseudo-header as the host', () => { + const actual = httpRequestToRequestData({ + method: 'GET', + url: '/blabla?xx=a', + headers: { + ':method': 'GET', + ':path': '/blabla?xx=a', + ':authority': 'example.com:8443', + ':scheme': 'https', + }, + socket: { encrypted: true }, + }); + + expect(actual).toEqual({ + method: 'GET', + url: 'https://example.com:8443/blabla?xx=a', + query_string: 'xx=a', + headers: {}, + }); + }); + it('works with relative URL request with host', () => { const actual = httpRequestToRequestData({ url: '/blabla', diff --git a/packages/node/src/integrations/http/httpServerIntegration.ts b/packages/node/src/integrations/http/httpServerIntegration.ts index b3c0c939d971..0000e54bc683 100644 --- a/packages/node/src/integrations/http/httpServerIntegration.ts +++ b/packages/node/src/integrations/http/httpServerIntegration.ts @@ -3,7 +3,12 @@ import { context, createContextKey, propagation } from '@opentelemetry/api'; import type { Integration, IntegrationFn } from '@sentry/core'; import { addNonEnumerableProperty, debug, getClient } from '@sentry/core'; import type { HttpIncomingMessage, HttpServerResponse } from '@sentry/core/server'; -import { getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST, recordRequestSession } from '@sentry/core/server'; +import { + getHttpServerSubscriptions, + HTTP2_ON_SERVER_STREAM, + HTTP_ON_SERVER_REQUEST, + recordRequestSession, +} from '@sentry/core/server'; import { subscribeDiagnosticsChannel } from '@sentry/server-utils'; import type { RequestEventData } from '@sentry/core'; import { DEBUG_BUILD } from '../../debug-build'; @@ -138,8 +143,10 @@ const _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => return { name: INTEGRATION_NAME, setupOnce() { - const { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart } = getHttpServerSubscriptions(_options); + const { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart, [HTTP2_ON_SERVER_STREAM]: onHttp2ServerStreamStart } = + getHttpServerSubscriptions(_options); subscribeDiagnosticsChannel(HTTP_ON_SERVER_REQUEST, onHttpServerRequestStart); + subscribeDiagnosticsChannel(HTTP2_ON_SERVER_STREAM, onHttp2ServerStreamStart); }, afterAllSetup(client) { if (DEBUG_BUILD && client.getIntegrationByName('Http')) { @@ -153,7 +160,7 @@ const _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => /** * This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests - * handled via the node `http` module. + * handled via the node `http` module, or via the compat API of the `http2` module. * * This version uses OpenTelemetry for context propagation and span management. * diff --git a/packages/node/src/integrations/http/httpServerSpansIntegration.ts b/packages/node/src/integrations/http/httpServerSpansIntegration.ts index 4d896a62485d..e83205354efb 100644 --- a/packages/node/src/integrations/http/httpServerSpansIntegration.ts +++ b/packages/node/src/integrations/http/httpServerSpansIntegration.ts @@ -42,6 +42,7 @@ import { getSpanStatusFromHttpCode, httpHeadersToSpanAttributes, getContentLengthFromHeaders, + getHostFromHeaders, parseStringToURLObject, SPAN_STATUS_ERROR, stripUrlQueryAndFragment, @@ -153,7 +154,7 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions const headers = request.headers; const userAgent = headers['user-agent']; const httpVersion = request.httpVersion; - const host = headers.host as string | undefined; + const host = getHostFromHeaders(headers); const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') || 'localhost'; const scheme = fullUrl.startsWith('https') ? 'https' : 'http'; @@ -360,11 +361,12 @@ function getIncomingRequestAttributesOnResponse( // take socket from the request, // since it may be detached from the response object in keep-alive mode const { socket } = request; - const { statusCode, statusMessage } = response; + const { statusCode } = response; const newAttributes: SpanAttributes = { [HTTP_RESPONSE_STATUS_CODE]: statusCode, - [HTTP_RESPONSE_STATUS_TEXT]: statusMessage?.toUpperCase(), + // HTTP/2 has no status text, and reading it emits a process warning. + [HTTP_RESPONSE_STATUS_TEXT]: request.httpVersion === '2.0' ? undefined : response.statusMessage?.toUpperCase(), }; // `client.address` is the originating client, so a forwarding header wins over the socket, which From a36dd15d6873b3fcd81e65b368b95e10173095af Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:02:39 +0100 Subject: [PATCH 087/136] fix(bundler-plugins): Skip default commit association on Vercel builds that --auto can't resolve (#26320) **Why:** With no `setCommits` set, non-production Vercel builds fall back to `{ auto: true }`. Vercel's own builders have no `origin` remote and no other CI variables, and the CLI only reads `VERCEL_GIT_*` on production builds, so that `set-commits --auto` call always fails there. The plugin swallows the error, but the new CLI reports each failure to its own telemetry, where Vercel builds make up about 40% of the "no repository for `--auto`" errors. Those builds now skip commit association. The skip only happens when `--auto` has nothing to read: no `origin` remote and none of the CI repository variables the CLI falls back to (`GITHUB_REPOSITORY`, `CI_PROJECT_PATH`, ...). Builds that have either, such as `vercel build` / `vercel deploy --prebuilt` in GitHub Actions, keep `--auto` exactly as before, so a build that associated commits today still does. The `VERCEL_GIT_*` branch stays production-only, as the existing comment says, and production detection now uses `getVercelEnv()` (`VERCEL_TARGET_ENV`, falling back to `VERCEL_ENV`), the same check deploy detection below it uses. An explicit user `setCommits` still wins. **Before / after:** No user has to change anything. The only builds that behave differently are ones where `--auto` was already failing quietly. | Setup | Before (CLI 0.49) | After | Action needed | |---|---|---|---| | Vercel production (`VERCEL_TARGET_ENV=production`) | Commits from `VERCEL_GIT_*` | Same | None | | Vercel production with only `VERCEL_ENV=production` | `--auto` fails on Vercel's builders, so no commits | Commits from `VERCEL_GIT_*` | None (this gets better) | | Vercel preview / custom env on Vercel's builders | `--auto` fails quietly, no commits | Skipped, no commits (no failing call) | None, unless you want preview commits (see below) | | Vercel preview with a git remote or CI variables (`vercel build` / `--prebuilt` in GitHub Actions) | `--auto` works | Same | None | | Not on Vercel, with a git checkout | `--auto` works | Same | None | | Not on Vercel, no `.git` (Docker), CI variables set | `--auto` uses CI variables | Same | None | | Not on Vercel, no `.git`, no CI variables | `--auto` fails quietly | Same (this PR only touches Vercel) | Pass the commit in | | `release.setCommits` set explicitly | User config wins | Same | None | Preview commits stay opt-in, because a preview's previous commit is the PR's stem commit and Sentry would notify the authors of unrelated PRs. Users who want them anyway can set: ```js release: { setCommits: { repo: `${process.env.VERCEL_GIT_REPO_OWNER}/${process.env.VERCEL_GIT_REPO_SLUG}`, commit: process.env.VERCEL_GIT_COMMIT_SHA, }, } ``` **Unsure about:** The CI variable list copies the CLI's `--auto` fallback (`packages/cli/src/lib/ci.ts` in getsentry/toolkit), so it has to stay in sync when that list grows. This adds at most one `git` call per build, and only on non-production Vercel builds. via @betegon. -- [View Session](https://junior-prod.sentry.dev/conversations/local%3Aweb%3A88cbe6ba657193037915c052) [[Sentry]](https://sentry.sentry.io/explore/conversations/local%3Aweb%3A88cbe6ba657193037915c052/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: bete <28983162+betegon@users.noreply.github.com> --- .../src/core/options-mapping.ts | 11 ++- packages/bundler-plugins/src/core/utils.ts | 31 ++++++++ .../test/core/option-mappings.test.ts | 73 +++++++++++++++++++ 3 files changed, 112 insertions(+), 3 deletions(-) diff --git a/packages/bundler-plugins/src/core/options-mapping.ts b/packages/bundler-plugins/src/core/options-mapping.ts index a811edf748db..0fc5e20cd44a 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -9,7 +9,7 @@ import type { ModuleMetadata, ModuleMetadataCallback, } from './types'; -import { determineReleaseName, readCommitEnvVar } from './utils'; +import { determineReleaseName, canAutoDetectRepository, readCommitEnvVar } from './utils'; export type NormalizedOptions = { org: string | undefined; @@ -138,6 +138,8 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption _experiments: userOptions._experiments ?? {}, }; + const vercelEnv = getVercelEnv(); + if (options.release.setCommits === undefined) { const vercelCommitSha = readCommitEnvVar('VERCEL_GIT_COMMIT_SHA'); if ( @@ -148,7 +150,7 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption // We only want to set commits for the production env because Sentry becomes extremely noisy (eg on slack) for // preview environments because the previous commit is always the "stem" commit of the preview/PR causing Sentry // to notify you for other people creating PRs. - process.env['VERCEL_TARGET_ENV'] === 'production' + vercelEnv === 'production' ) { options.release.setCommits = { shouldNotThrowOnFailure: true, @@ -158,6 +160,10 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption ignoreEmpty: true, ignoreMissing: true, }; + } else if (process.env['VERCEL'] && vercelEnv !== 'production' && !canAutoDetectRepository()) { + // Vercel's own builders have no git remote and no other CI variables, so `--auto` can only fail there. + // Builds that have either, such as `vercel build` in GitHub Actions, keep `--auto` below. + options.release.setCommits = false; } else { options.release.setCommits = { shouldNotThrowOnFailure: true, @@ -168,7 +174,6 @@ export function normalizeUserOptions(userOptions: UserOptions): NormalizedOption } } - const vercelEnv = getVercelEnv(); if (options.release.deploy === undefined && process.env['VERCEL'] && vercelEnv) { options.release.deploy = { env: vercelEnv, diff --git a/packages/bundler-plugins/src/core/utils.ts b/packages/bundler-plugins/src/core/utils.ts index 60a4068c2fcf..358fb9c224d1 100644 --- a/packages/bundler-plugins/src/core/utils.ts +++ b/packages/bundler-plugins/src/core/utils.ts @@ -216,6 +216,37 @@ function gitRevision(): string | undefined { return gitRevision; } +// Mirrors the CLI's `set-commits --auto` fallback for builds without an `origin` remote. Vercel is left out +// because the CLI only reads `VERCEL_GIT_*` on production builds. +const CI_REPOSITORY_ENV_VARS = [ + 'GITHUB_REPOSITORY', + 'CI_PROJECT_PATH', + 'BITBUCKET_REPO_FULL_NAME', + 'RENDER_GIT_REPO_SLUG', + 'RAILWAY_GIT_REPO_NAME', + 'CIRCLE_PROJECT_REPONAME', + 'BUILDKITE_REPO', + 'BUILD_REPOSITORY_URI', +] as const; + +/** + * Whether `set-commits --auto` can find the repository: from the `origin` git remote, or from CI variables. + */ +export function canAutoDetectRepository(): boolean { + if ( + CI_REPOSITORY_ENV_VARS.some(name => process.env[name]) || + (process.env['NETLIFY'] && process.env['REPOSITORY_URL']) + ) { + return true; + } + try { + childProcess.execSync('git remote get-url origin', { stdio: 'ignore', windowsHide: true }); + return true; + } catch { + return false; + } +} + /** * Tries to guess a release name based on environmental data. */ diff --git a/packages/bundler-plugins/test/core/option-mappings.test.ts b/packages/bundler-plugins/test/core/option-mappings.test.ts index 1b853cf89b5e..488ac801622a 100644 --- a/packages/bundler-plugins/test/core/option-mappings.test.ts +++ b/packages/bundler-plugins/test/core/option-mappings.test.ts @@ -1,3 +1,4 @@ +import childProcess from 'child_process'; import type { Options } from '../../src/core'; import type { NormalizedOptions } from '../../src/core/options-mapping'; import { normalizeUserOptions, validateOptions } from '../../src/core/options-mapping'; @@ -209,6 +210,78 @@ describe('normalizeUserOptions()', () => { vi.restoreAllMocks(); }); + test.each(['preview', 'development', 'staging'])( + 'should skip commit association on %s Vercel builds without a git remote', + targetEnv => { + vi.spyOn(childProcess, 'execSync').mockImplementation(() => { + throw new Error('fatal: not a git repository'); + }); + // Only Vercel's variables, so CI variables from the machine running the tests don't leak in. + process.env = { + VERCEL: '1', + VERCEL_TARGET_ENV: targetEnv, + VERCEL_GIT_COMMIT_SHA: 'abc123', + VERCEL_GIT_REPO_OWNER: 'my-owner', + VERCEL_GIT_REPO_SLUG: 'my-repo', + }; + + const normalizedOptions = normalizeUserOptions({ release: { name: 'my-release' } }); + + expect(normalizedOptions.release.setCommits).toBe(false); + vi.restoreAllMocks(); + }, + ); + + test('should keep automatic commit association on preview Vercel builds that have a git remote', () => { + const execSyncSpy = vi + .spyOn(childProcess, 'execSync') + .mockReturnValue(Buffer.from('https://github.com/my-owner/my-repo.git')); + // Only Vercel's variables, so the git remote is what keeps `--auto`, not CI variables from the test machine. + process.env = { + VERCEL: '1', + VERCEL_TARGET_ENV: 'preview', + VERCEL_GIT_COMMIT_SHA: 'abc123', + VERCEL_GIT_REPO_OWNER: 'my-owner', + VERCEL_GIT_REPO_SLUG: 'my-repo', + }; + + const normalizedOptions = normalizeUserOptions({ release: { name: 'my-release' } }); + + expect(execSyncSpy).toHaveBeenCalledWith('git remote get-url origin', expect.anything()); + expect(normalizedOptions.release.setCommits).toEqual(expect.objectContaining({ auto: true })); + expect(normalizedOptions.release.setCommits).not.toHaveProperty('commit'); + vi.restoreAllMocks(); + }); + + test('should keep automatic commit association on preview Vercel builds in another CI without a git remote', () => { + vi.spyOn(childProcess, 'execSync').mockImplementation(() => { + throw new Error('fatal: not a git repository'); + }); + process.env['VERCEL'] = '1'; + process.env['VERCEL_TARGET_ENV'] = 'preview'; + process.env['GITHUB_REPOSITORY'] = 'my-owner/my-repo'; + + const normalizedOptions = normalizeUserOptions({ release: { name: 'my-release' } }); + + expect(normalizedOptions.release.setCommits).toEqual(expect.objectContaining({ auto: true })); + vi.restoreAllMocks(); + }); + + test('should associate commits from Vercel env vars when only VERCEL_ENV is production', () => { + process.env['VERCEL'] = '1'; + delete process.env['VERCEL_TARGET_ENV']; + process.env['VERCEL_ENV'] = 'production'; + process.env['VERCEL_GIT_COMMIT_SHA'] = 'abc123'; + process.env['VERCEL_GIT_REPO_OWNER'] = 'my-owner'; + process.env['VERCEL_GIT_REPO_SLUG'] = 'my-repo'; + + const normalizedOptions = normalizeUserOptions({ release: { name: 'my-release' } }); + + expect(normalizedOptions.release.setCommits).toEqual( + expect.objectContaining({ commit: 'abc123', repo: 'my-owner/my-repo' }), + ); + }); + test('should not create deploy config when Vercel env vars are missing', () => { const userOptions: Options = { org: 'my-org', From f843dc67d988b630d30a773ca27d6fcd704a3d90 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:07:31 +0100 Subject: [PATCH 088/136] chore(ci): Skip busy users when assigning PR reviewers (#26358) ## What The assign-reviewers workflow no longer requests reviews from people who set their GitHub status to busy. It picks someone else from the codeowner pool or the team instead. ## Why GitHub's own team review assignment already skips busy members, and the workflow should do the same so people who are out or heads-down don't get pinged. User status is only available through GraphQL, so the script reads it in one batched query. If that query fails, the workflow logs a warning and skips nobody, so a lookup problem never blocks review assignment. Open question: org-scoped statuses should be visible to the GitFlow App token, but that's only confirmed once the workflow runs. The `Busy, skipped:` log line shows whether it works. via @msonnb. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0C5DRTAU2X%3A1794578604.624729) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0C5DRTAU2X%3A1794578604.624729/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Martin Sonnberger <26038247+msonnb@users.noreply.github.com> --- scripts/assign-reviewers.mjs | 34 ++++++++++++++++++-- scripts/assign-reviewers.test.mjs | 52 +++++++++++++++++++++++++++++-- scripts/github-test-utils.mjs | 3 +- 3 files changed, 83 insertions(+), 6 deletions(-) diff --git a/scripts/assign-reviewers.mjs b/scripts/assign-reviewers.mjs index 60586290e710..fe43374e1b25 100644 --- a/scripts/assign-reviewers.mjs +++ b/scripts/assign-reviewers.mjs @@ -87,6 +87,32 @@ export function pickReviewers({ existing, codeownerPool, teamPool, exclude }) { return picked; } +/** + * Returns the logins that set their GitHub status to busy ("limited availability"). GitHub's own team review + * assignment skips these users too. User status is only exposed via GraphQL. + */ +export async function getBusyLogins({ github, core, logins }) { + const unique = [...new Map(logins.map(login => [login.toLowerCase(), login])).values()]; + if (!unique.length) { + return []; + } + + const query = `query(${unique.map((_, i) => `$l${i}: String!`).join(', ')}) { + ${unique.map((_, i) => `u${i}: user(login: $l${i}) { login status { indicatesLimitedAvailability } }`).join('\n ')} + }`; + const variables = Object.fromEntries(unique.map((login, i) => [`l${i}`, login])); + + try { + const data = await github.graphql(query, variables); + return Object.values(data) + .filter(user => user?.status?.indicatesLimitedAvailability) + .map(user => user.login); + } catch (error) { + core.warning(`Could not read reviewer availability, not skipping busy users: ${error.message}`); + return []; + } +} + export async function assignReviewers({ github, context, core }) { const { owner, repo } = context.repo; const pull_number = context.payload.pull_request.number; @@ -137,15 +163,19 @@ export async function assignReviewers({ github, context, core }) { } } + const teamPool = await listTeamMembers(TEAM_SLUG); + const busy = await getBusyLogins({ github, core, logins: [...codeownerPool, ...teamPool] }); + const reviewers = pickReviewers({ existing, codeownerPool, - teamPool: await listTeamMembers(TEAM_SLUG), - exclude: [author, ...requesters, ...NEVER_REQUEST], + teamPool, + exclude: [author, ...requesters, ...NEVER_REQUEST, ...busy], }); core.info(`Codeowners: ${codeowners.join(', ') || '(none)'}`); core.info(`Existing reviewers: ${existing.join(', ') || '(none)'}`); + core.info(`Busy, skipped: ${busy.join(', ') || '(none)'}`); if (!reviewers.length) { core.info('No eligible reviewers left to request.'); diff --git a/scripts/assign-reviewers.test.mjs b/scripts/assign-reviewers.test.mjs index 0628ad394373..896ffc38f236 100644 --- a/scripts/assign-reviewers.test.mjs +++ b/scripts/assign-reviewers.test.mjs @@ -1,6 +1,12 @@ -import { describe, expect, it } from 'vitest'; - -import { assignReviewers, getOwnersForFiles, parseCodeowners, pickReviewers } from './assign-reviewers.mjs'; +import { describe, expect, it, vi } from 'vitest'; + +import { + assignReviewers, + getBusyLogins, + getOwnersForFiles, + parseCodeowners, + pickReviewers, +} from './assign-reviewers.mjs'; import { attribution, junior, setup } from './github-test-utils.mjs'; const CODEOWNERS = ` @@ -80,7 +86,47 @@ describe('pickReviewers', () => { }); }); +describe('getBusyLogins', () => { + const core = { warning: vi.fn() }; + + it('returns users whose status indicates limited availability', async () => { + const github = { + graphql: vi.fn(async () => ({ + u0: { login: 'a', status: { indicatesLimitedAvailability: true } }, + u1: { login: 'b', status: { indicatesLimitedAvailability: false } }, + u2: { login: 'c', status: null }, + })), + }; + expect(await getBusyLogins({ github, core, logins: ['a', 'b', 'c', 'A'] })).toEqual(['a']); + expect(github.graphql).toHaveBeenCalledWith(expect.any(String), { l0: 'A', l1: 'b', l2: 'c' }); + }); + + it('skips the query when there are no logins', async () => { + const github = { graphql: vi.fn() }; + expect(await getBusyLogins({ github, core, logins: [] })).toEqual([]); + expect(github.graphql).not.toHaveBeenCalled(); + }); + + it('treats nobody as busy when the query fails', async () => { + const github = { graphql: vi.fn(async () => Promise.reject(new Error('boom'))) }; + expect(await getBusyLogins({ github, core, logins: ['a'] })).toEqual([]); + expect(core.warning).toHaveBeenCalledWith(expect.stringContaining('boom')); + }); +}); + describe('assignReviewers', () => { + it('does not request a review from busy users', async () => { + const { github, run } = setup(assignReviewers, { user: { login: 'author', type: 'User' } }); + github.graphql.mockResolvedValue({ u0: { login: 'a', status: { indicatesLimitedAvailability: true } } }); + await run(); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: expect.arrayContaining(['b', 'c', 'd']) }), + ); + expect(github.rest.pulls.requestReviewers).toHaveBeenCalledWith( + expect.objectContaining({ reviewers: expect.not.arrayContaining(['a']) }), + ); + }); + it('does not request a review from the requester of a Junior PR', async () => { const { github, run } = setup(assignReviewers, { user: junior, body: attribution('**Alice Example**') }); await run(); diff --git a/scripts/github-test-utils.mjs b/scripts/github-test-utils.mjs index 37857c50ea65..3ad406f7aa0c 100644 --- a/scripts/github-test-utils.mjs +++ b/scripts/github-test-utils.mjs @@ -10,6 +10,7 @@ const profiles = { export function setup(run, pr) { const github = { paginate: vi.fn(async method => (method === github.rest.teams.listMembersInOrg ? Object.values(profiles) : [])), + graphql: vi.fn(async () => ({})), rest: { pulls: { get: vi.fn(async () => ({ @@ -35,7 +36,7 @@ export function setup(run, pr) { repo: { owner: 'getsentry', repo: 'sentry-javascript' }, payload: { pull_request: { number: 1 } }, }; - const core = { info: vi.fn() }; + const core = { info: vi.fn(), warning: vi.fn() }; return { github, run: () => run({ github, context, core }) }; } From 9cc4d871fe302d334a2c024cb92656582b1c293a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:35:55 +0100 Subject: [PATCH 089/136] chore(deps): Bump `@sentry/conventions` to 0.33.0 (#26374) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What Bumps `@sentry/conventions` from 0.32.0 to 0.33.0 in every package and test app. No SDK code changes. ## Why Keeps us on the latest conventions. 0.33.0 only fixes attribute docs and examples (mostly `gen_ai.*`). No constants were added, removed, renamed, or deprecated, so there is nothing to adopt or migrate, and emitted values stay the same. The `astro-5-cf-pages` and `tanstackstart-react` e2e apps still pinned 0.31.0. Both pins came in with feature PRs that merged after the 0.32.0 bump, so I aligned them with the other exact pins. Revert those two lines if the older pin was on purpose. via [automation `sched_ae2548aa50f44ee9e080350e80e0d775`](https://junior-prod.sentry.dev/automations/sched_ae2548aa50f44ee9e080350e80e0d775) · Run ID `sched_ae2548aa50f44ee9e080350e80e0d775:1794643200000`. -- [View Session](https://junior-prod.sentry.dev/conversations/agent-dispatch%3Adispatch_d51d80ac1d57765017e7e84dce7fb414) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent-dispatch%3Adispatch_d51d80ac1d57765017e7e84dce7fb414/?project=4510944073809921) Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- .../browser-integration-tests/package.json | 2 +- .../cloudflare-integration-tests/package.json | 2 +- .../deno-integration-tests/package.json | 2 +- .../test-applications/angular-19/package.json | 2 +- .../astro-5-cf-pages/package.json | 2 +- .../cloudflare-pi-durable/package.json | 2 +- .../package.json | 2 +- .../gen-ai-libraries/package.json | 2 +- .../nextjs-16-adapter/package.json | 2 +- .../nextjs-16-cacheComponents/package.json | 2 +- .../package.json | 2 +- .../nextjs-16-tunnel/package.json | 2 +- .../test-applications/nitro-3/package.json | 2 +- .../test-applications/node-eve/package.json | 2 +- .../test-applications/node-hapi/package.json | 2 +- .../node-mastra/package.json | 2 +- .../node-openai-decisions/package.json | 2 +- .../node-pi-durable/package.json | 2 +- .../nuxt-4-static/package.json | 2 +- .../test-applications/nuxt-4/package.json | 2 +- .../test-applications/nuxt-5/package.json | 2 +- .../solidstart-static/package.json | 2 +- .../sveltekit-2-static/package.json | 2 +- .../sveltekit-3/package.json | 2 +- .../tanstackstart-react/package.json | 2 +- .../node-integration-tests/package.json | 2 +- packages/angular/package.json | 2 +- packages/astro/package.json | 2 +- packages/aws-serverless/package.json | 2 +- packages/browser-utils/package.json | 2 +- packages/browser/package.json | 2 +- packages/bun/package.json | 2 +- packages/cloudflare/package.json | 2 +- packages/core/package.json | 2 +- packages/deno/package.json | 2 +- packages/effect/package.json | 2 +- packages/elysia/package.json | 2 +- packages/ember/package.json | 2 +- packages/google-cloud-serverless/package.json | 2 +- packages/hono/package.json | 2 +- packages/nestjs/package.json | 2 +- packages/nextjs/package.json | 2 +- packages/nitro/package.json | 2 +- packages/node/package.json | 2 +- packages/nuxt/package.json | 2 +- packages/opentelemetry/package.json | 2 +- packages/profiling-node/package.json | 2 +- packages/react-router/package.json | 2 +- packages/react/package.json | 2 +- packages/remix/package.json | 2 +- packages/replay-internal/package.json | 2 +- packages/server-utils/package.json | 2 +- packages/solid/package.json | 2 +- packages/solidstart/package.json | 2 +- packages/svelte/package.json | 2 +- packages/sveltekit/package.json | 2 +- packages/tanstackstart-react/package.json | 2 +- packages/vue/package.json | 2 +- pnpm-lock.yaml | 150 +++++++++--------- 59 files changed, 133 insertions(+), 133 deletions(-) diff --git a/dev-packages/browser-integration-tests/package.json b/dev-packages/browser-integration-tests/package.json index 2eeff5ed3129..6809d901a3e2 100644 --- a/dev-packages/browser-integration-tests/package.json +++ b/dev-packages/browser-integration-tests/package.json @@ -61,7 +61,7 @@ "@playwright/test": "1.64.1", "@sentry/browser": "11.12.0", "@sentry/browser-utils": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "11.12.0", "@sentry/replay": "11.12.0", "@sentry/replay-canvas": "11.12.0", diff --git a/dev-packages/cloudflare-integration-tests/package.json b/dev-packages/cloudflare-integration-tests/package.json index 869263da78bb..a1ddbfeaaac4 100644 --- a/dev-packages/cloudflare-integration-tests/package.json +++ b/dev-packages/cloudflare-integration-tests/package.json @@ -28,7 +28,7 @@ "@prisma/client": "6.15.0", "@sentry-internal/test-utils": "11.12.0", "@sentry/cloudflare": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "11.12.0", "@sentry/hono": "11.12.0", "ai": "^6.0.0", diff --git a/dev-packages/deno-integration-tests/package.json b/dev-packages/deno-integration-tests/package.json index f91826f278bc..36221d8d7d38 100644 --- a/dev-packages/deno-integration-tests/package.json +++ b/dev-packages/deno-integration-tests/package.json @@ -17,7 +17,7 @@ }, "devDependencies": { "@sentry-internal/node-integration-tests": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/deno": "11.12.0", "mysql": "^2.18.1", diff --git a/dev-packages/e2e-tests/test-applications/angular-19/package.json b/dev-packages/e2e-tests/test-applications/angular-19/package.json index 8fdc1cd3f236..482669183709 100644 --- a/dev-packages/e2e-tests/test-applications/angular-19/package.json +++ b/dev-packages/e2e-tests/test-applications/angular-19/package.json @@ -33,7 +33,7 @@ "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "http-server": "^14.1.1", "typescript": "~5.6.2" diff --git a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json index b679df6add37..19f034c34e4f 100644 --- a/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json +++ b/dev-packages/e2e-tests/test-applications/astro-5-cf-pages/package.json @@ -20,7 +20,7 @@ "astro": "^5.17.1" }, "devDependencies": { - "@sentry/conventions": "0.31.0", + "@sentry/conventions": "0.33.0", "wrangler": "^4.63.0" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/package.json index b3d9c70eb8a9..0a077b8f57bb 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/package.json +++ b/dev-packages/e2e-tests/test-applications/cloudflare-pi-durable/package.json @@ -24,7 +24,7 @@ "@cloudflare/workers-types": "^4.20260426.0", "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "typescript": "^5.5.2", "vite": "7.3.5", "wrangler": "^4.136.2" diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-send-to-sentry/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-workers-send-to-sentry/package.json index 0e01d1cec1c9..86e4c538b506 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-workers-send-to-sentry/package.json +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-send-to-sentry/package.json @@ -19,7 +19,7 @@ "@cloudflare/workers-types": "^5.20260727.1", "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "^26.1.2", "sentry": "~0.44.1", "typescript": "~6.0.3", diff --git a/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json b/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json index a8c03f02a9ab..bac7a3ea9c8f 100644 --- a/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json +++ b/dev-packages/e2e-tests/test-applications/gen-ai-libraries/package.json @@ -33,7 +33,7 @@ "@cloudflare/workers-types": "^4.20260426.0", "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/express": "^4.17.21", "@types/node": "^18.19.1", "tsx": "4.21.0", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/package.json index 85ca40e4ef3d..239e4cbd0e61 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-adapter/package.json @@ -20,7 +20,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/package.json index 4292a42c3843..0f36bae7bf66 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-cacheComponents/package.json @@ -35,7 +35,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/package.json index 6da961d2bf6c..3b6a13f4c579 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-streaming-cacheComponents/package.json @@ -32,7 +32,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json index 7949f9a2312d..afc5bd63ab7d 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-16-tunnel/package.json @@ -36,7 +36,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/package.json b/dev-packages/e2e-tests/test-applications/nitro-3/package.json index 220276c63139..1d716de7438f 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/package.json +++ b/dev-packages/e2e-tests/test-applications/nitro-3/package.json @@ -21,7 +21,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "latest || *", "nitro": "^3.0.260522-beta", "rolldown": "latest", diff --git a/dev-packages/e2e-tests/test-applications/node-eve/package.json b/dev-packages/e2e-tests/test-applications/node-eve/package.json index 978dc8a2dbd8..3962f8690196 100644 --- a/dev-packages/e2e-tests/test-applications/node-eve/package.json +++ b/dev-packages/e2e-tests/test-applications/node-eve/package.json @@ -32,7 +32,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "24.x", "typescript": "~5.9.0" }, diff --git a/dev-packages/e2e-tests/test-applications/node-hapi/package.json b/dev-packages/e2e-tests/test-applications/node-hapi/package.json index 70e17ef2e6f1..8026ca581200 100644 --- a/dev-packages/e2e-tests/test-applications/node-hapi/package.json +++ b/dev-packages/e2e-tests/test-applications/node-hapi/package.json @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" } } diff --git a/dev-packages/e2e-tests/test-applications/node-mastra/package.json b/dev-packages/e2e-tests/test-applications/node-mastra/package.json index d2cf7f675fc3..a2627e5d681a 100644 --- a/dev-packages/e2e-tests/test-applications/node-mastra/package.json +++ b/dev-packages/e2e-tests/test-applications/node-mastra/package.json @@ -29,7 +29,7 @@ "@mastra/deployer": "~1.74.0", "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "24.x", "mastra": "~1.28.0", "typescript": "~5.9.0" diff --git a/dev-packages/e2e-tests/test-applications/node-openai-decisions/package.json b/dev-packages/e2e-tests/test-applications/node-openai-decisions/package.json index 94125ec7a332..12793f352adc 100644 --- a/dev-packages/e2e-tests/test-applications/node-openai-decisions/package.json +++ b/dev-packages/e2e-tests/test-applications/node-openai-decisions/package.json @@ -24,7 +24,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/express": "^4.17.21", "@types/node": "^24.0.0", "typescript": "~5.9.0" diff --git a/dev-packages/e2e-tests/test-applications/node-pi-durable/package.json b/dev-packages/e2e-tests/test-applications/node-pi-durable/package.json index 2f2fdcc528ae..0462d710b941 100644 --- a/dev-packages/e2e-tests/test-applications/node-pi-durable/package.json +++ b/dev-packages/e2e-tests/test-applications/node-pi-durable/package.json @@ -20,7 +20,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@types/node": "24.x" }, "engines": { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json index 2f318a648dd3..6f9f8523b77b 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json @@ -26,7 +26,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json index a1cd9f3a8596..32dff24aae06 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json @@ -32,7 +32,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json index 6192f3911a06..0a3f1584ff03 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -40,7 +40,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/solidstart-static/package.json b/dev-packages/e2e-tests/test-applications/solidstart-static/package.json index 5a73c4c69571..59e4669806dc 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart-static/package.json +++ b/dev-packages/e2e-tests/test-applications/solidstart-static/package.json @@ -18,7 +18,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "@solidjs/meta": "^0.29.4", "@solidjs/router": "^1.0.0", diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json index 4f66f0712160..fce7e6c98ba3 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-static/package.json @@ -27,7 +27,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sveltejs/adapter-node": "^2.0.0", "@sveltejs/kit": "2.70.2", "@sveltejs/vite-plugin-svelte": "^3.0.0", diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json index 2bdb4261a836..c6eaf15e8da5 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json @@ -24,7 +24,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sveltejs/adapter-node": "^6.0.0", "@sveltejs/kit": "^3.0.0", "@sveltejs/vite-plugin-svelte": "^7.3.1", diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json index 0eef79524818..520246fdfe60 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json @@ -36,7 +36,7 @@ "mysql": "^2.18.1" }, "devDependencies": { - "@sentry/conventions": "0.31.0", + "@sentry/conventions": "0.33.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@types/node": "^24.10.0", diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json index ed97e01a4bb1..d333114a48fb 100644 --- a/dev-packages/node-integration-tests/package.json +++ b/dev-packages/node-integration-tests/package.json @@ -60,7 +60,7 @@ "@sentry-internal/rollup-utils": "11.12.0", "@sentry-internal/test-utils": "11.12.0", "@sentry/aws-serverless": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "@sentry/core": "11.12.0", "@sentry/hono": "11.12.0", "@sentry/node": "11.12.0", diff --git a/packages/angular/package.json b/packages/angular/package.json index 19ed4fc1cc91..4f9c2eebc7b6 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -23,7 +23,7 @@ "dependencies": { "@sentry/browser": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "tslib": "^2.4.1" }, "devDependencies": { diff --git a/packages/astro/package.json b/packages/astro/package.json index 2af95c285918..e848972df3c6 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -68,7 +68,7 @@ "@sentry/browser": "11.12.0", "@sentry/cloudflare": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/node": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", "@sentry/server-utils": "11.12.0", diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 14991a4f7463..6e2f23a29559 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -66,7 +66,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index ab3c75015436..c6fef1a3958a 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -34,7 +34,7 @@ }, "dependencies": { "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "web-vitals": "^6.2.3" }, "devDependencies": { diff --git a/packages/browser/package.json b/packages/browser/package.json index de9e2b2071ca..675a182cfd8a 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -39,7 +39,7 @@ }, "dependencies": { "@sentry/browser-utils": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/feedback": "11.12.0", "@sentry/replay": "11.12.0", "@sentry/replay-canvas": "11.12.0", diff --git a/packages/bun/package.json b/packages/bun/package.json index cc6b79ccd2d3..f45a91a705b0 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -45,7 +45,7 @@ "dependencies": { "@sentry/bundler-plugins": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/node": "11.12.0", "@sentry/server-utils": "11.12.0" }, diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index ffedba65f2de..939b9bac894d 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -53,7 +53,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/opentelemetry": "11.12.0", "@sentry/server-utils": "11.12.0", diff --git a/packages/core/package.json b/packages/core/package.json index c36050eee3e1..585b8136ce4e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -88,6 +88,6 @@ "zod": "^4.6.7" }, "dependencies": { - "@sentry/conventions": "^0.32.0" + "@sentry/conventions": "^0.33.0" } } diff --git a/packages/deno/package.json b/packages/deno/package.json index e001238bd8b7..896c8342688f 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -29,7 +29,7 @@ ], "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", "@sentry/server-utils": "11.12.0" diff --git a/packages/effect/package.json b/packages/effect/package.json index 2fe0fa60ceac..6269c7133ae6 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -45,7 +45,7 @@ }, "dependencies": { "@sentry/browser": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0" }, diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 00224d09879e..2b1d2e005ec1 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -34,7 +34,7 @@ "dependencies": { "@sentry/bun": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0" + "@sentry/conventions": "^0.33.0" }, "peerDependencies": { "elysia": "^1.4.0" diff --git a/packages/ember/package.json b/packages/ember/package.json index ba1c97d5cb27..0a813d1fdc04 100644 --- a/packages/ember/package.json +++ b/packages/ember/package.json @@ -43,7 +43,7 @@ "@embroider/addon-shim": "^1.11.0", "@embroider/macros": "^1.20.2", "@sentry/browser": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "decorator-transforms": "^2.3.2" }, diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index b53f3cda23f1..aa0b86a69862 100644 --- a/packages/google-cloud-serverless/package.json +++ b/packages/google-cloud-serverless/package.json @@ -36,7 +36,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", diff --git a/packages/hono/package.json b/packages/hono/package.json index 128f29ff1d55..172f5f4b646e 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -74,7 +74,7 @@ "dependencies": { "@opentelemetry/api": "^1.9.1", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/server-utils": "11.12.0" }, "peerDependencies": { diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index c0dfc2e52f4d..9a7b642be58d 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -54,7 +54,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/server-utils": "11.12.0" diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index 8fb77f081e90..5114337813d1 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -95,7 +95,7 @@ "@sentry/browser-utils": "11.12.0", "@sentry/bundler-plugins": "11.12.0", "@sentry/cloudflare": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/opentelemetry": "11.12.0", diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 73e43de432bd..dd80a5e678c4 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -36,7 +36,7 @@ }, "dependencies": { "@sentry/bundler-plugins": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", diff --git a/packages/node/package.json b/packages/node/package.json index d9e5ecefe06d..2682815e78c4 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -78,7 +78,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/opentelemetry": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index fb25583544ea..6d6fff06e0fd 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -56,7 +56,7 @@ "@nuxt/kit": "^4.6.0", "@sentry/browser": "11.12.0", "@sentry/cloudflare": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/bundler-plugins": "11.12.0", diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 1ef7ce1941c7..878276151244 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -27,7 +27,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0" }, "peerDependencies": { diff --git a/packages/profiling-node/package.json b/packages/profiling-node/package.json index bac8a820efc4..714e88b91d9f 100644 --- a/packages/profiling-node/package.json +++ b/packages/profiling-node/package.json @@ -48,7 +48,7 @@ "test:watch": "vitest --watch" }, "dependencies": { - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/node-cpu-profiler": "^2.4.4", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0" diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 4cc1ab5c0ff8..297ab2a9f684 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -57,7 +57,7 @@ "dependencies": { "@opentelemetry/api": "^1.9.1", "@sentry/browser": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/react": "11.12.0", diff --git a/packages/react/package.json b/packages/react/package.json index 39930478c6cd..2415560ae3a0 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -59,7 +59,7 @@ "dependencies": { "@sentry/browser": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0" + "@sentry/conventions": "^0.33.0" }, "peerDependencies": { "react": "17.x || 18.x || 19.x", diff --git a/packages/remix/package.json b/packages/remix/package.json index 0c537ec5d930..4025b4cb76d6 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -78,7 +78,7 @@ "@remix-run/router": "^1.23.4", "@sentry/browser": "11.12.0", "@sentry/bundler-plugins": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/react": "11.12.0", diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 24705d7c7e4d..0d96bcd7d532 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -68,7 +68,7 @@ "devDependencies": { "@sentry-internal/replay-worker": "11.12.0", "@sentry-internal/rollup-utils": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/rrweb": "2.46.0", "@sentry/rrweb-snapshot": "2.46.0", "fflate": "0.8.3", diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 5635003d8d11..f0f5b56d6361 100644 --- a/packages/server-utils/package.json +++ b/packages/server-utils/package.json @@ -102,7 +102,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0" }, "devDependencies": { diff --git a/packages/solid/package.json b/packages/solid/package.json index 410ab7036ebd..77b09e41c5ed 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -56,7 +56,7 @@ "dependencies": { "@sentry/browser": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0" + "@sentry/conventions": "^0.33.0" }, "peerDependencies": { "@solidjs/router": ">=0.13.4 <2.0.0-0", diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 66a607fe19c4..9bcd74768773 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -91,7 +91,7 @@ "@sentry/server-utils": "11.12.0", "@sentry/solid": "11.12.0", "@sentry/bundler-plugins": "11.12.0", - "@sentry/conventions": "0.32.0", + "@sentry/conventions": "0.33.0", "h3": "^1.15.10" }, "devDependencies": { diff --git a/packages/svelte/package.json b/packages/svelte/package.json index bf0ec462b2e7..1df54b8c7a23 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -33,7 +33,7 @@ }, "dependencies": { "@sentry/browser": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "magic-string": "~0.30.0" }, diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 9242cfa7d70e..30ae0140f876 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -73,7 +73,7 @@ "@opentelemetry/api": "^1.9.1", "@sentry/cloudflare": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/node": "11.12.0", "@sentry/server-runtime-injection": "11.12.0", "@sentry/server-utils": "11.12.0", diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index a9889fd4bb42..13dd8b1c63b0 100644 --- a/packages/tanstackstart-react/package.json +++ b/packages/tanstackstart-react/package.json @@ -53,7 +53,7 @@ "dependencies": { "@opentelemetry/api": "^1.9.1", "@sentry/browser-utils": "11.12.0", - "@sentry/conventions": "^0.32.0", + "@sentry/conventions": "^0.33.0", "@sentry/core": "11.12.0", "@sentry/node": "11.12.0", "@sentry/react": "11.12.0", diff --git a/packages/vue/package.json b/packages/vue/package.json index 33808bdb0941..0f8b8d4826e7 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -46,7 +46,7 @@ "dependencies": { "@sentry/browser": "11.12.0", "@sentry/core": "11.12.0", - "@sentry/conventions": "^0.32.0" + "@sentry/conventions": "^0.33.0" }, "peerDependencies": { "@tanstack/vue-router": "^1.64.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e44a43d32aaf..ada98a8757a1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -271,8 +271,8 @@ importers: specifier: 11.12.0 version: link:../../packages/browser-utils '@sentry/conventions': - specifier: 0.32.0 - version: 0.32.0 + specifier: 0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../../packages/core @@ -490,8 +490,8 @@ importers: specifier: 11.12.0 version: link:../../packages/cloudflare '@sentry/conventions': - specifier: 0.32.0 - version: 0.32.0 + specifier: 0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../../packages/core @@ -526,8 +526,8 @@ importers: specifier: 11.12.0 version: link:../node-integration-tests '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../../packages/core @@ -663,8 +663,8 @@ importers: specifier: 11.12.0 version: link:../../packages/aws-serverless '@sentry/conventions': - specifier: 0.32.0 - version: 0.32.0 + specifier: 0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../../packages/core @@ -924,8 +924,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -988,8 +988,8 @@ importers: specifier: 11.12.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1016,8 +1016,8 @@ importers: packages/aws-serverless: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1050,8 +1050,8 @@ importers: specifier: 11.12.0 version: link:../browser-utils '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1078,8 +1078,8 @@ importers: packages/browser-utils: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1097,8 +1097,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1177,8 +1177,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1214,8 +1214,8 @@ importers: packages/core: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 devDependencies: '@sentry-internal/rollup-utils': specifier: 11.12.0 @@ -1230,8 +1230,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1252,8 +1252,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1277,8 +1277,8 @@ importers: specifier: 11.12.0 version: link:../bun '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1305,8 +1305,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1448,8 +1448,8 @@ importers: packages/google-cloud-serverless: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1488,8 +1488,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1538,8 +1538,8 @@ importers: packages/nestjs: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1584,8 +1584,8 @@ importers: specifier: 11.12.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1642,8 +1642,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1679,8 +1679,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1735,8 +1735,8 @@ importers: specifier: 11.12.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1796,8 +1796,8 @@ importers: packages/opentelemetry: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1812,8 +1812,8 @@ importers: packages/profiling-node: dependencies: '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1837,8 +1837,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1904,8 +1904,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -1965,8 +1965,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2055,8 +2055,8 @@ importers: specifier: 11.12.0 version: link:../../dev-packages/rollup-utils '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/rrweb': specifier: 2.46.0 version: 2.46.0 @@ -2127,8 +2127,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2161,8 +2161,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2204,8 +2204,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: 0.32.0 - version: 0.32.0 + specifier: 0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2274,8 +2274,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2311,8 +2311,8 @@ importers: specifier: 11.12.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2375,8 +2375,8 @@ importers: specifier: 11.12.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -2443,8 +2443,8 @@ importers: specifier: 11.12.0 version: link:../browser '@sentry/conventions': - specifier: ^0.32.0 - version: 0.32.0 + specifier: ^0.33.0 + version: 0.33.0 '@sentry/core': specifier: 11.12.0 version: link:../core @@ -8166,8 +8166,8 @@ packages: resolution: {integrity: sha512-MLxTpTU3E8QACQ/5c0sENMR2gRiMXpGaKeD5IHY+3wyU2fUSJVB0QPU/l1WhoyZbX8N9ospBgf5UEG7taVF9rg==} engines: {node: ^14.15.0 || >=16.10.0, npm: ^6.11.0 || ^7.5.6 || >=8.0.0, yarn: '>= 1.13.0'} - '@sentry/conventions@0.32.0': - resolution: {integrity: sha512-WkSQcDhUUsz1SwxR23LpmyPKba+dgxxiH0DWV4VSM9yaAvhhl87ppW2Ts3g4piIKCVflc31aJeWy+biUbYfsMQ==} + '@sentry/conventions@0.33.0': + resolution: {integrity: sha512-5aa3g/VOnMoL8yHbfkYIWBYC3BLgMudgRNBTKNMrcMEj1mE9aKIt/CYCG7sasijhiSU4nTcSEzyM2voIVzLCng==} engines: {node: '>=14'} '@sentry/node-cpu-profiler@2.4.4': @@ -26373,7 +26373,7 @@ snapshots: transitivePeerDependencies: - chokidar - '@sentry/conventions@0.32.0': {} + '@sentry/conventions@0.33.0': {} '@sentry/node-cpu-profiler@2.4.4': dependencies: From d1d5d80a7c003518e22f9a55cc784475920edbbc Mon Sep 17 00:00:00 2001 From: Andrei <168741329+andreiborza@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:51:03 +0100 Subject: [PATCH 090/136] test(e2e): Run OTel SDK E2E apps on SDK v3 with an SDK v2 variant (#25703) ## What The OpenTelemetry SDK E2E apps now run on OTel SDK v3 by default, and each has an OTel SDK v2 variant. - `node-otel-sdk-node`, `node-express-otlp`, `nextjs-otlp` and `sveltekit-2-otlp` use SDK v3, with a v2 variant on `@opentelemetry/api` 1.9.1 - Removes `node-otel-sdk-node-v3`, which the default run now covers ## Why Users run both SDK major versions, and they need different `@opentelemetry/api` minors. The tests are the same, so only the setup changes per variant. --------- Co-authored-by: Claude Opus 5.5 --- .../nextjs-otlp/otel-tracer-provider.ts | 22 ++++++ .../otel-v2/otel-tracer-provider.ts | 11 +++ .../nextjs-otlp/otel.server.config.ts | 14 +--- .../nextjs-otlp/package.json | 17 +++-- .../nextjs-otlp/tsconfig.json | 2 +- .../otel-v2/tracer-provider.ts | 9 +++ .../node-express-otlp/package.json | 19 ++++- .../node-express-otlp/src/app.ts | 22 ++---- .../node-express-otlp/src/tracer-provider.ts | 20 +++++ .../node-otel-sdk-node-v3/package.json | 25 ------- .../playwright.config.mjs | 34 --------- .../node-otel-sdk-node-v3/pnpm-workspace.yaml | 3 - .../node-otel-sdk-node-v3/src/app.mjs | 47 ------------ .../start-event-proxy.mjs | 6 -- .../start-otel-proxy.mjs | 6 -- .../tests/errors.test.ts | 31 -------- .../tests/opentelemetry.test.ts | 73 ------------------- .../node-otel-sdk-node/package.json | 27 +++++-- .../src/instrument-otel-v2.mjs} | 7 +- .../node-otel-sdk-node/src/instrument.mjs | 7 +- .../otel-v2/otel-tracer-provider.ts | 11 +++ .../sveltekit-2-otlp/package.json | 23 ++++-- .../src/instrumentation.server.ts | 14 +--- .../src/otel-tracer-provider.ts | 22 ++++++ 24 files changed, 181 insertions(+), 291 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-tracer-provider.ts create mode 100644 dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-v2/otel-tracer-provider.ts create mode 100644 dev-packages/e2e-tests/test-applications/node-express-otlp/otel-v2/tracer-provider.ts create mode 100644 dev-packages/e2e-tests/test-applications/node-express-otlp/src/tracer-provider.ts delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/package.json delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/playwright.config.mjs delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/pnpm-workspace.yaml delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/app.mjs delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-event-proxy.mjs delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-otel-proxy.mjs delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/errors.test.ts delete mode 100644 dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/opentelemetry.test.ts rename dev-packages/e2e-tests/test-applications/{node-otel-sdk-node-v3/src/instrument.mjs => node-otel-sdk-node/src/instrument-otel-v2.mjs} (86%) create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/otel-v2/otel-tracer-provider.ts create mode 100644 dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/otel-tracer-provider.ts diff --git a/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-tracer-provider.ts b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-tracer-provider.ts new file mode 100644 index 000000000000..dd56ed7a742a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-tracer-provider.ts @@ -0,0 +1,22 @@ +import { context, propagation, trace } from '@opentelemetry/api'; +import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; +import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core'; +import type { Resource } from '@opentelemetry/resources'; +import type { SpanExporter } from '@opentelemetry/sdk-trace'; +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'; + +// OpenTelemetry SDK v3 has no `NodeTracerProvider.register()`, so the app registers the tracer +// provider, context manager and propagator itself. The OTel SDK v2 variant replaces this file with +// `otel-v2/otel-tracer-provider.ts`. +export function registerTracerProvider(exporter: SpanExporter, resource: Resource): void { + trace.setGlobalTracerProvider( + new TracerProvider({ + resource, + spanProcessors: [new BatchSpanProcessor({ exporter, scheduledDelayMillis: 100 })], + }), + ); + context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable()); + propagation.setGlobalPropagator( + new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }), + ); +} diff --git a/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-v2/otel-tracer-provider.ts b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-v2/otel-tracer-provider.ts new file mode 100644 index 000000000000..3af449a59158 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel-v2/otel-tracer-provider.ts @@ -0,0 +1,11 @@ +import type { Resource } from '@opentelemetry/resources'; +import type { SpanExporter } from '@opentelemetry/sdk-trace-base'; +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; + +export function registerTracerProvider(exporter: SpanExporter, resource: Resource): void { + new NodeTracerProvider({ + resource, + spanProcessors: [new BatchSpanProcessor(exporter, { scheduledDelayMillis: 100 })], + }).register(); +} diff --git a/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel.server.config.ts b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel.server.config.ts index 0ee1bc170f31..33d2bef4f832 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nextjs-otlp/otel.server.config.ts @@ -1,9 +1,8 @@ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { resourceFromAttributes } from '@opentelemetry/resources'; -import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; -import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { getOtlpTracesEndpoint } from '@sentry/nextjs'; import { OTLP_RECEIVER_PORT, startOtlpReceiver } from './otel-receiver'; +import { registerTracerProvider } from './otel-tracer-provider'; // Next.js can run `register()` more than once in dev, which would leave a second receiver fighting // for the port and a second set of providers losing the race to register globally. @@ -27,13 +26,8 @@ if (!globalWithOtelFlag.__otelRegistered) { // The app owns tracing: this registers the global tracer provider, context manager and // propagator. Sentry is initialized afterwards with `enableOpenTelemetrySetup: false` so it does // not contend for any of them. - new NodeTracerProvider({ + registerTracerProvider( + new OTLPTraceExporter({ url: `${otlpBaseUrl}/v1/traces`, headers: otlpTracesEndpoint.headers }), resource, - spanProcessors: [ - new BatchSpanProcessor( - new OTLPTraceExporter({ url: `${otlpBaseUrl}/v1/traces`, headers: otlpTracesEndpoint.headers }), - { scheduledDelayMillis: 100 }, - ), - ], - }).register(); + ); } diff --git a/dev-packages/e2e-tests/test-applications/nextjs-otlp/package.json b/dev-packages/e2e-tests/test-applications/nextjs-otlp/package.json index 64c289e9439a..11a1be9b3bdd 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-otlp/package.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-otlp/package.json @@ -14,16 +14,18 @@ "test:dev": "TEST_ENV=development playwright test", "test:dev-webpack": "TEST_ENV=development-webpack playwright test", "test:build": "pnpm install && pnpm build", + "test:build:otel-v2": "pnpm remove @opentelemetry/context-async-hooks @opentelemetry/core @opentelemetry/sdk-trace && pnpm add @opentelemetry/api@1.9.1 @opentelemetry/exporter-trace-otlp-http@^0.220.0 @opentelemetry/resources@^2.9.0 @opentelemetry/sdk-trace-base@^2.9.0 @opentelemetry/sdk-trace-node@^2.9.0 && pnpm dedupe && cp otel-v2/otel-tracer-provider.ts otel-tracer-provider.ts && pnpm build", "test:build-webpack": "pnpm install && pnpm build-webpack", "test:assert": "pnpm test:prod && pnpm test:dev", "test:assert-webpack": "pnpm test:prod && pnpm test:dev-webpack" }, "dependencies": { - "@opentelemetry/api": "^1.9.1", - "@opentelemetry/exporter-trace-otlp-http": "^0.220.0", - "@opentelemetry/resources": "^2.9.0", - "@opentelemetry/sdk-trace-base": "^2.9.0", - "@opentelemetry/sdk-trace-node": "^2.9.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/context-async-hooks": "^3.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", + "@opentelemetry/resources": "^3.0.0", + "@opentelemetry/sdk-trace": "^3.0.0", "@sentry/core": "file:../../packed/sentry-core-packed.tgz", "@sentry/nextjs": "file:../../packed/sentry-nextjs-packed.tgz", "next": "16.3.0", @@ -46,6 +48,11 @@ "build-command": "pnpm test:build-webpack", "label": "nextjs-otlp (webpack)", "assert-command": "pnpm test:assert-webpack" + }, + { + "build-command": "pnpm test:build:otel-v2", + "assert-command": "pnpm test:assert", + "label": "nextjs-otlp (OTel SDK v2)" } ] } diff --git a/dev-packages/e2e-tests/test-applications/nextjs-otlp/tsconfig.json b/dev-packages/e2e-tests/test-applications/nextjs-otlp/tsconfig.json index cc9ed39b5aa2..f1fb9c3599e1 100644 --- a/dev-packages/e2e-tests/test-applications/nextjs-otlp/tsconfig.json +++ b/dev-packages/e2e-tests/test-applications/nextjs-otlp/tsconfig.json @@ -23,5 +23,5 @@ } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts", "**/*.mts"], - "exclude": ["node_modules"] + "exclude": ["node_modules", "otel-v2"] } diff --git a/dev-packages/e2e-tests/test-applications/node-express-otlp/otel-v2/tracer-provider.ts b/dev-packages/e2e-tests/test-applications/node-express-otlp/otel-v2/tracer-provider.ts new file mode 100644 index 000000000000..d87aab506191 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-otlp/otel-v2/tracer-provider.ts @@ -0,0 +1,9 @@ +import type { SpanExporter } from '@opentelemetry/sdk-trace-base'; +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; + +export function registerTracerProvider(exporter: SpanExporter): void { + new NodeTracerProvider({ + spanProcessors: [new BatchSpanProcessor(exporter, { scheduledDelayMillis: 100 })], + }).register(); +} diff --git a/dev-packages/e2e-tests/test-applications/node-express-otlp/package.json b/dev-packages/e2e-tests/test-applications/node-express-otlp/package.json index 70d0b7343d22..ac311b7023b1 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-otlp/package.json +++ b/dev-packages/e2e-tests/test-applications/node-express-otlp/package.json @@ -8,13 +8,15 @@ "test": "playwright test", "clean": "npx rimraf node_modules pnpm-lock.yaml", "test:build": "pnpm install && pnpm build", + "test:build:otel-v2": "pnpm remove @opentelemetry/context-async-hooks @opentelemetry/core @opentelemetry/sdk-trace && pnpm add @opentelemetry/api@1.9.1 @opentelemetry/exporter-trace-otlp-http@^0.220.0 @opentelemetry/sdk-trace-base@^2.9.0 @opentelemetry/sdk-trace-node@^2.9.0 && pnpm dedupe && cp otel-v2/tracer-provider.ts src/tracer-provider.ts && pnpm build", "test:assert": "pnpm test" }, "dependencies": { - "@opentelemetry/api": "^1.9.1", - "@opentelemetry/exporter-trace-otlp-http": "^0.220.0", - "@opentelemetry/sdk-trace-base": "^2.9.0", - "@opentelemetry/sdk-trace-node": "^2.9.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/context-async-hooks": "^3.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", + "@opentelemetry/sdk-trace": "^3.0.0", "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "@types/express": "^4.17.21", "@types/node": "^18.19.1", @@ -24,5 +26,14 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" + }, + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:otel-v2", + "assert-command": "pnpm test:assert", + "label": "node-express-otlp (OTel SDK v2)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/node-express-otlp/src/app.ts b/dev-packages/e2e-tests/test-applications/node-express-otlp/src/app.ts index c6246a18f3a9..e6cb40ad2639 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-otlp/src/app.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-otlp/src/app.ts @@ -1,9 +1,8 @@ import { trace } from '@opentelemetry/api'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; -import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; -import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import * as Sentry from '@sentry/node'; import express from 'express'; +import { registerTracerProvider } from './tracer-provider'; const dsn = process.env.E2E_TEST_DSN as string; const appPort = 3030; @@ -17,19 +16,12 @@ if (!otlpTracesEndpoint) { // The user brings their own OpenTelemetry setup. In production `url` would be // `otlpTracesEndpoint.url`; here it points at the local receiver below so the test can assert what // was actually exported. The auth headers are the real DSN-derived ones either way. -const provider = new NodeTracerProvider({ - spanProcessors: [ - new BatchSpanProcessor( - new OTLPTraceExporter({ - url: `http://localhost:${otlpReceiverPort}/v1/traces`, - headers: otlpTracesEndpoint.headers, - }), - { scheduledDelayMillis: 100 }, - ), - ], -}); - -provider.register(); +registerTracerProvider( + new OTLPTraceExporter({ + url: `http://localhost:${otlpReceiverPort}/v1/traces`, + headers: otlpTracesEndpoint.headers, + }), +); Sentry.init({ dsn, diff --git a/dev-packages/e2e-tests/test-applications/node-express-otlp/src/tracer-provider.ts b/dev-packages/e2e-tests/test-applications/node-express-otlp/src/tracer-provider.ts new file mode 100644 index 000000000000..ec591e7e4c14 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express-otlp/src/tracer-provider.ts @@ -0,0 +1,20 @@ +import { context, propagation, trace } from '@opentelemetry/api'; +import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; +import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core'; +import type { SpanExporter } from '@opentelemetry/sdk-trace'; +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'; + +// OpenTelemetry SDK v3 has no `NodeTracerProvider.register()`, so the app registers the tracer +// provider, context manager and propagator itself. The OTel SDK v2 variant replaces this file with +// `otel-v2/tracer-provider.ts`. +export function registerTracerProvider(exporter: SpanExporter): void { + trace.setGlobalTracerProvider( + new TracerProvider({ + spanProcessors: [new BatchSpanProcessor({ exporter, scheduledDelayMillis: 100 })], + }), + ); + context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable()); + propagation.setGlobalPropagator( + new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }), + ); +} diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/package.json b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/package.json deleted file mode 100644 index 906c97985e07..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "node-otel-sdk-node-v3", - "version": "1.0.0", - "private": true, - "scripts": { - "start": "node --import ./src/instrument.mjs src/app.mjs", - "clean": "npx rimraf node_modules pnpm-lock.yaml", - "test:build": "pnpm install", - "test:assert": "playwright test" - }, - "dependencies": { - "@opentelemetry/api": "^1.10.0", - "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", - "@opentelemetry/instrumentation": "^0.300.0", - "@opentelemetry/instrumentation-http": "^0.300.0", - "@opentelemetry/sdk-node": "^0.300.0", - "@opentelemetry/sdk-trace": "^3.0.0", - "@sentry/node": "file:../../packed/sentry-node-packed.tgz", - "express": "^4.21.2" - }, - "devDependencies": { - "@playwright/test": "1.64.1", - "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" - } -} diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/playwright.config.mjs deleted file mode 100644 index 888e61cfb2dc..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/playwright.config.mjs +++ /dev/null @@ -1,34 +0,0 @@ -import { getPlaywrightConfig } from '@sentry-internal/test-utils'; - -const config = getPlaywrightConfig( - { - startCommand: `pnpm start`, - }, - { - webServer: [ - { - command: `node ./start-event-proxy.mjs`, - port: 3031, - stdout: 'pipe', - stderr: 'pipe', - }, - { - command: `node ./start-otel-proxy.mjs`, - port: 3032, - stdout: 'pipe', - stderr: 'pipe', - }, - { - command: 'pnpm start', - port: 3030, - stdout: 'pipe', - stderr: 'pipe', - env: { - PORT: 3030, - }, - }, - ], - }, -); - -export default config; diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/pnpm-workspace.yaml deleted file mode 100644 index 428f42f5ee7b..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/pnpm-workspace.yaml +++ /dev/null @@ -1,3 +0,0 @@ -allowBuilds: - protobufjs: false -minimumReleaseAge: 0 diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/app.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/app.mjs deleted file mode 100644 index ee441975d47c..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/app.mjs +++ /dev/null @@ -1,47 +0,0 @@ -import { trace } from '@opentelemetry/api'; -import * as Sentry from '@sentry/node'; -import express from 'express'; -import http from 'node:http'; - -const app = express(); -const port = 3030; -const tracer = trace.getTracer('node-otel-sdk-node-v3'); - -app.get('/test-telemetry/:id', function (req, res) { - tracer.startActiveSpan('telemetry-handler', span => { - const { traceId, spanId } = span.spanContext(); - - Sentry.captureException(new Error(`This is an exception with id ${req.params.id}`)); - - span.end(); - - res.json({ traceId, spanId }); - }); -}); - -app.get('/test-exception/:id', function (req, _res) { - throw new Error(`This is an exception with id ${req.params.id}`); -}); - -app.get('/test-outgoing', function (_req, res) { - http.get(`http://localhost:${port}/echo-headers`, response => { - let body = ''; - response.on('data', chunk => (body += chunk)); - response.on('end', () => res.type('json').send(body)); - }); -}); - -app.get('/echo-headers', function (req, res) { - res.send(req.headers); -}); - -// Answers with the OpenTelemetry span the request ran under, so the test can check what the error -// captured by Sentry was linked to. -app.use(function onError(_err, _req, res, _next) { - const spanContext = trace.getActiveSpan()?.spanContext(); - res.status(500).json({ traceId: spanContext?.traceId, spanId: spanContext?.spanId }); -}); - -app.listen(port, () => { - console.log(`Example app listening on port ${port}`); -}); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-event-proxy.mjs deleted file mode 100644 index 52bbf5464e17..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-event-proxy.mjs +++ /dev/null @@ -1,6 +0,0 @@ -import { startEventProxyServer } from '@sentry-internal/test-utils'; - -startEventProxyServer({ - port: 3031, - proxyServerName: 'node-otel-sdk-node-v3', -}); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-otel-proxy.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-otel-proxy.mjs deleted file mode 100644 index 0a3a31f582b2..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/start-otel-proxy.mjs +++ /dev/null @@ -1,6 +0,0 @@ -import { startProxyServer } from '@sentry-internal/test-utils'; - -startProxyServer({ - port: 3032, - proxyServerName: 'node-otel-sdk-node-v3-otel', -}); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/errors.test.ts b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/errors.test.ts deleted file mode 100644 index 603e9c053aaa..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/errors.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { expect, test } from '@playwright/test'; -import { waitForError } from '@sentry-internal/test-utils'; - -test('links errors to the active OpenTelemetry span', async ({ baseURL }) => { - const errorEventPromise = waitForError('node-otel-sdk-node-v3', errorEvent => { - return errorEvent.exception?.values?.[0]?.value === 'This is an exception with id 123'; - }); - - const response = await fetch(`${baseURL}/test-telemetry/123`); - const { traceId, spanId } = (await response.json()) as { traceId: string; spanId: string }; - - const errorEvent = await errorEventPromise; - - expect(errorEvent.contexts?.trace).toEqual({ trace_id: traceId, span_id: spanId }); -}); - -test('links errors from the Sentry instrumentation to the active OpenTelemetry span', async ({ baseURL }) => { - const errorEventPromise = waitForError('node-otel-sdk-node-v3', errorEvent => { - return errorEvent.exception?.values?.[0]?.value === 'This is an exception with id 456'; - }); - - const response = await fetch(`${baseURL}/test-exception/456`); - const { traceId, spanId } = (await response.json()) as { traceId: string; spanId: string }; - - const errorEvent = await errorEventPromise; - - // With tracing off, Sentry's channel instrumentation still runs and reports the errors express - // never handles. - expect(errorEvent.exception?.values?.[0]?.mechanism).toEqual({ type: 'auto.http.express', handled: false }); - expect(errorEvent.contexts?.trace).toEqual({ trace_id: traceId, span_id: spanId }); -}); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/opentelemetry.test.ts b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/opentelemetry.test.ts deleted file mode 100644 index cbeffac8b286..000000000000 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/tests/opentelemetry.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { expect, test } from '@playwright/test'; -import { waitForError, waitForPlainRequest, waitForTransaction } from '@sentry-internal/test-utils'; - -interface OtlpSpan { - name: string; - traceId: string; -} - -/** - * The proxy hands back the payloads it received as newline separated JSON, so a single read can - * hold more than one OTLP export. - */ -function getExportedSpans(data: string): OtlpSpan[] { - return data - .split('\n') - .filter(Boolean) - .flatMap( - line => (JSON.parse(line) as { resourceSpans?: { scopeSpans?: { spans?: OtlpSpan[] }[] }[] }).resourceSpans ?? [], - ) - .flatMap(resourceSpan => resourceSpan.scopeSpans ?? []) - .flatMap(scopeSpan => scopeSpan.spans ?? []); -} - -test('exports the spans of the user OpenTelemetry setup to their own collector', async ({ baseURL }) => { - let traceId: string | undefined; - - // Every test in this app exports into the same proxy, and the http span only ends once the - // response is out, so wait for this request's own trace to be complete. Waiting on the span names - // alone matches a batch that another test filled, whose spans are on a different trace. - const otelExportPromise = waitForPlainRequest('node-otel-sdk-node-v3-otel', data => { - const names = getExportedSpans(data) - .filter(span => span.traceId === traceId) - .map(span => span.name); - return names.includes('telemetry-handler') && names.includes('GET'); - }); - - const response = await fetch(`${baseURL}/test-telemetry/234`); - ({ traceId } = (await response.json()) as { traceId: string }); - - const exportedSpans = getExportedSpans(await otelExportPromise).filter(span => span.traceId === traceId); - - // The user's own http instrumentation keeps working and stays on the same trace as their spans. - expect(exportedSpans.map(span => span.name)).toEqual(expect.arrayContaining(['telemetry-handler', 'GET'])); -}); - -test('sends no spans to Sentry', async ({ baseURL }) => { - const transactionPromise = waitForTransaction('node-otel-sdk-node-v3', () => true); - const errorPromise = waitForError('node-otel-sdk-node-v3', errorEvent => { - return errorEvent.exception?.values?.[0]?.value === 'This is an exception with id 345'; - }); - - await fetch(`${baseURL}/test-telemetry/345`); - // Proves the request's telemetry reached the proxy, so the absence check below is not vacuous. - await errorPromise; - - // Absence can only be time bounded. This guards against Sentry's own instrumentation emitting - // spans again, which would produce a transaction for every request, well inside this window. - const transaction = await Promise.race([ - transactionPromise, - new Promise(resolve => setTimeout(() => resolve(undefined), 3000)), - ]); - - expect(transaction).toBeUndefined(); -}); - -test('leaves outgoing trace propagation to the user propagator', async ({ baseURL }) => { - const response = await fetch(`${baseURL}/test-outgoing`); - const headers = (await response.json()) as Record; - - expect(headers['traceparent']).toMatch(/^00-[a-f0-9]{32}-[a-f0-9]{16}-\d{2}$/); - expect(headers['sentry-trace']).toBeUndefined(); - expect(headers['baggage']).toBeUndefined(); -}); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/package.json b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/package.json index 809cb1a510fc..c9a16056ae37 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/package.json +++ b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/package.json @@ -3,23 +3,34 @@ "version": "1.0.0", "private": true, "scripts": { - "start": "node --import ./src/instrument.mjs src/app.mjs", + "start": "node --import ./src/${INSTRUMENT_FILE:-instrument.mjs} src/app.mjs", "clean": "npx rimraf node_modules pnpm-lock.yaml", "test:build": "pnpm install", - "test:assert": "playwright test" + "test:build:otel-v2": "pnpm remove @opentelemetry/sdk-trace && pnpm add @opentelemetry/api@1.9.1 @opentelemetry/exporter-trace-otlp-http@^0.220.0 @opentelemetry/instrumentation@^0.220.0 @opentelemetry/instrumentation-http@^0.220.0 @opentelemetry/sdk-node@^0.220.0 @opentelemetry/sdk-trace-base@^2.9.0 && pnpm dedupe", + "test:assert": "playwright test", + "test:assert:otel-v2": "INSTRUMENT_FILE=instrument-otel-v2.mjs playwright test" }, "dependencies": { - "@opentelemetry/api": "1.9.1", - "@opentelemetry/exporter-trace-otlp-http": "^0.220.0", - "@opentelemetry/instrumentation": "^0.220.0", - "@opentelemetry/instrumentation-http": "^0.220.0", - "@opentelemetry/sdk-node": "^0.220.0", - "@opentelemetry/sdk-trace-base": "^2.9.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/instrumentation-http": "^0.300.0", + "@opentelemetry/sdk-node": "^0.300.0", + "@opentelemetry/sdk-trace": "^3.0.0", "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "express": "^4.21.2" }, "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" + }, + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:otel-v2", + "assert-command": "pnpm test:assert:otel-v2", + "label": "node-otel-sdk-node (OTel SDK v2)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/instrument.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument-otel-v2.mjs similarity index 86% rename from dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/instrument.mjs rename to dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument-otel-v2.mjs index c9b910fd3122..25749a79ff21 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node-v3/src/instrument.mjs +++ b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument-otel-v2.mjs @@ -1,7 +1,7 @@ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { NodeSDK } from '@opentelemetry/sdk-node'; -import { BatchSpanProcessor } from '@opentelemetry/sdk-trace'; +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; import * as Sentry from '@sentry/node'; import { register } from 'node:module'; @@ -16,10 +16,7 @@ register('@opentelemetry/instrumentation/hook.mjs', import.meta.url); const sdk = new NodeSDK({ instrumentations: [new HttpInstrumentation()], spanProcessors: [ - new BatchSpanProcessor({ - exporter: new OTLPTraceExporter({ url: 'http://localhost:3032/' }), - scheduledDelayMillis: 100, - }), + new BatchSpanProcessor(new OTLPTraceExporter({ url: 'http://localhost:3032/' }), { scheduledDelayMillis: 100 }), ], }); diff --git a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument.mjs b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument.mjs index 25749a79ff21..c9b910fd3122 100644 --- a/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument.mjs +++ b/dev-packages/e2e-tests/test-applications/node-otel-sdk-node/src/instrument.mjs @@ -1,7 +1,7 @@ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { NodeSDK } from '@opentelemetry/sdk-node'; -import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace'; import * as Sentry from '@sentry/node'; import { register } from 'node:module'; @@ -16,7 +16,10 @@ register('@opentelemetry/instrumentation/hook.mjs', import.meta.url); const sdk = new NodeSDK({ instrumentations: [new HttpInstrumentation()], spanProcessors: [ - new BatchSpanProcessor(new OTLPTraceExporter({ url: 'http://localhost:3032/' }), { scheduledDelayMillis: 100 }), + new BatchSpanProcessor({ + exporter: new OTLPTraceExporter({ url: 'http://localhost:3032/' }), + scheduledDelayMillis: 100, + }), ], }); diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/otel-v2/otel-tracer-provider.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/otel-v2/otel-tracer-provider.ts new file mode 100644 index 000000000000..3af449a59158 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/otel-v2/otel-tracer-provider.ts @@ -0,0 +1,11 @@ +import type { Resource } from '@opentelemetry/resources'; +import type { SpanExporter } from '@opentelemetry/sdk-trace-base'; +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; + +export function registerTracerProvider(exporter: SpanExporter, resource: Resource): void { + new NodeTracerProvider({ + resource, + spanProcessors: [new BatchSpanProcessor(exporter, { scheduledDelayMillis: 100 })], + }).register(); +} diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/package.json index 8812b0dd9400..c6650b8d4dc7 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/package.json @@ -12,14 +12,16 @@ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "test:prod": "TEST_ENV=production playwright test", "test:build": "pnpm install && pnpm build", + "test:build:otel-v2": "pnpm remove @opentelemetry/context-async-hooks @opentelemetry/core @opentelemetry/sdk-trace && pnpm add @opentelemetry/api@1.9.1 @opentelemetry/exporter-trace-otlp-http@^0.220.0 @opentelemetry/resources@^2.9.0 @opentelemetry/sdk-trace-base@^2.9.0 @opentelemetry/sdk-trace-node@^2.9.0 && pnpm dedupe && cp otel-v2/otel-tracer-provider.ts src/otel-tracer-provider.ts && pnpm build", "test:assert": "pnpm test:prod" }, "dependencies": { - "@opentelemetry/api": "^1.9.1", - "@opentelemetry/exporter-trace-otlp-http": "^0.220.0", - "@opentelemetry/resources": "^2.9.0", - "@opentelemetry/sdk-trace-base": "^2.9.0", - "@opentelemetry/sdk-trace-node": "^2.9.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/context-async-hooks": "^3.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.300.0", + "@opentelemetry/resources": "^3.0.0", + "@opentelemetry/sdk-trace": "^3.0.0", "@sentry/core": "file:../../packed/sentry-core-packed.tgz", "@sentry/sveltekit": "file:../../packed/sentry-sveltekit-packed.tgz" }, @@ -34,5 +36,14 @@ "typescript": "^5.0.0", "vite": "^7.3.2" }, - "type": "module" + "type": "module", + "sentryTest": { + "variants": [ + { + "build-command": "pnpm test:build:otel-v2", + "assert-command": "pnpm test:assert", + "label": "sveltekit-2-otlp (OTel SDK v2)" + } + ] + } } diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/instrumentation.server.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/instrumentation.server.ts index 91406fc9ba24..4e81313c7714 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/instrumentation.server.ts +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/instrumentation.server.ts @@ -1,10 +1,9 @@ import { E2E_TEST_DSN } from '$env/static/private'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { resourceFromAttributes } from '@opentelemetry/resources'; -import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; -import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import * as Sentry from '@sentry/sveltekit'; import { OTLP_RECEIVER_PORT, startOtlpReceiver } from './otel-receiver'; +import { registerTracerProvider } from './otel-tracer-provider'; startOtlpReceiver(); @@ -21,15 +20,10 @@ if (!otlpTracesEndpoint) { // The app owns tracing: this registers the global tracer provider, context manager and // propagator. Sentry is initialized afterwards with `enableOpenTelemetrySetup: false` so it does // not contend for any of them. -new NodeTracerProvider({ +registerTracerProvider( + new OTLPTraceExporter({ url: `${otlpBaseUrl}/v1/traces`, headers: otlpTracesEndpoint.headers }), resource, - spanProcessors: [ - new BatchSpanProcessor( - new OTLPTraceExporter({ url: `${otlpBaseUrl}/v1/traces`, headers: otlpTracesEndpoint.headers }), - { scheduledDelayMillis: 100 }, - ), - ], -}).register(); +); Sentry.init({ environment: 'qa', diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/otel-tracer-provider.ts b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/otel-tracer-provider.ts new file mode 100644 index 000000000000..dd56ed7a742a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2-otlp/src/otel-tracer-provider.ts @@ -0,0 +1,22 @@ +import { context, propagation, trace } from '@opentelemetry/api'; +import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; +import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from '@opentelemetry/core'; +import type { Resource } from '@opentelemetry/resources'; +import type { SpanExporter } from '@opentelemetry/sdk-trace'; +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'; + +// OpenTelemetry SDK v3 has no `NodeTracerProvider.register()`, so the app registers the tracer +// provider, context manager and propagator itself. The OTel SDK v2 variant replaces this file with +// `otel-v2/otel-tracer-provider.ts`. +export function registerTracerProvider(exporter: SpanExporter, resource: Resource): void { + trace.setGlobalTracerProvider( + new TracerProvider({ + resource, + spanProcessors: [new BatchSpanProcessor({ exporter, scheduledDelayMillis: 100 })], + }), + ); + context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable()); + propagation.setGlobalPropagator( + new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }), + ); +} From b1e12e367c46dad9fb9ecab7d64a7e44669543a9 Mon Sep 17 00:00:00 2001 From: Andrei <168741329+andreiborza@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:51:59 +0100 Subject: [PATCH 091/136] fix(server-utils): Record output of Workers AI chat-completion responses (#26175) ## What Workers AI spans for responses in the OpenAI chat-completion format now record the output, finish reason, response id and model. Streamed responses also get the response id, model and finish reason. ## Why Newer models such as gemma-4 return `choices`, so non-streaming spans had token usage but no output. Closes: #26120 --------- Co-authored-by: Claude Opus 5.5 --- .../tests/ai-streaming.test.ts | 8 ++- .../src/ai/workers-ai/streaming.ts | 10 +++ .../server-utils/src/ai/workers-ai/types.ts | 11 ++++ .../server-utils/src/ai/workers-ai/utils.ts | 36 ++++++++++- .../lib/tracing/workers-ai-streaming.test.ts | 17 ++++- .../ai/lib/utils/workers-ai-utils.test.ts | 62 +++++++++++++++++++ 6 files changed, 140 insertions(+), 4 deletions(-) diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-agent/tests/ai-streaming.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-agent/tests/ai-streaming.test.ts index a2d3c37b66dc..559542c30c9c 100644 --- a/dev-packages/e2e-tests/test-applications/cloudflare-agent/tests/ai-streaming.test.ts +++ b/dev-packages/e2e-tests/test-applications/cloudflare-agent/tests/ai-streaming.test.ts @@ -16,7 +16,13 @@ function assertGenAiStreamingSpan(span: SerializedStreamedSpan): void { expect(span.attributes['gen_ai.response.streaming']?.value).toBe(true); expect(span.attributes['gen_ai.response.text']?.value).toBe('The capital of France is Paris.'); expect(span.attributes['gen_ai.output.messages']?.value).toBe( - JSON.stringify([{ role: 'assistant', parts: [{ type: 'text', content: 'The capital of France is Paris.' }] }]), + JSON.stringify([ + { + role: 'assistant', + parts: [{ type: 'text', content: 'The capital of France is Paris.' }], + finish_reason: 'stop', + }, + ]), ); expect(span.attributes['gen_ai.usage.input_tokens']?.value).toBe(15); expect(span.attributes['gen_ai.usage.output_tokens']?.value).toBe(8); diff --git a/packages/server-utils/src/ai/workers-ai/streaming.ts b/packages/server-utils/src/ai/workers-ai/streaming.ts index 37aefd9a6046..2b44b37841d6 100644 --- a/packages/server-utils/src/ai/workers-ai/streaming.ts +++ b/packages/server-utils/src/ai/workers-ai/streaming.ts @@ -21,6 +21,8 @@ interface WorkersAiStreamChunk { tool_calls?: unknown[]; // OpenAI-compatible streaming shape emitted for models routed through the // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`). + id?: unknown; + model?: unknown; choices?: Array<{ delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] }; finish_reason?: unknown; @@ -121,6 +123,13 @@ function processLine( } if (Array.isArray(parsed.choices)) { + if (typeof parsed.id === 'string') { + state.responseId = parsed.id; + } + if (typeof parsed.model === 'string') { + state.responseModel = parsed.model; + } + for (const choice of parsed.choices) { if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) { state.responseTexts.push(choice.delta.content); @@ -184,6 +193,7 @@ export function instrumentWorkersAiStream( setOutputMessagesAttribute(span, { responseText: state.responseTexts.join(''), toolCalls: state.toolCalls, + finishReason: state.finishReasons[0], }); } diff --git a/packages/server-utils/src/ai/workers-ai/types.ts b/packages/server-utils/src/ai/workers-ai/types.ts index c96169c86f25..a9209990981c 100644 --- a/packages/server-utils/src/ai/workers-ai/types.ts +++ b/packages/server-utils/src/ai/workers-ai/types.ts @@ -37,7 +37,18 @@ export interface WorkersAiInput { * The (subset of) outputs returned by Workers AI text generation models that we read from. */ export interface WorkersAiOutput { + id?: unknown; + model?: unknown; response?: unknown; tool_calls?: unknown[]; + choices?: WorkersAiChoice[]; usage?: WorkersAiUsage; } + +/** + * The (subset of) a choice in the OpenAI chat-completion format that we read from. + */ +export interface WorkersAiChoice { + message?: { content?: unknown; tool_calls?: unknown[] }; + finish_reason?: unknown; +} diff --git a/packages/server-utils/src/ai/workers-ai/utils.ts b/packages/server-utils/src/ai/workers-ai/utils.ts index 422da29faaaf..2c8cdad9bc60 100644 --- a/packages/server-utils/src/ai/workers-ai/utils.ts +++ b/packages/server-utils/src/ai/workers-ai/utils.ts @@ -12,6 +12,8 @@ import { GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, @@ -32,7 +34,7 @@ import { addResponseAttributes as addDecideResponseAttributes } from '../typesaf // Re-exported so `workers-ai/streaming.ts` keeps importing it from this module. export { setOutputMessagesAttribute }; import { WORKERS_AI_ORIGIN, WORKERS_AI_PROVIDER_NAME } from './constants'; -import type { WorkersAiInput, WorkersAiOutput } from './types'; +import type { WorkersAiChoice, WorkersAiInput, WorkersAiOutput } from './types'; export type WorkersAiOperationName = 'chat' | 'embeddings' | 'decide' | 'extract'; @@ -209,6 +211,17 @@ export function addResponseAttributes( span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens)); } + if (Array.isArray(response.choices)) { + if (typeof response.id === 'string') { + span.setAttribute(GEN_AI_RESPONSE_ID, response.id); + } + if (typeof response.model === 'string') { + span.setAttribute(GEN_AI_RESPONSE_MODEL, response.model); + } + addChoicesResponseAttributes(span, response.choices, recordOutputs); + return; + } + if (recordOutputs) { let responseText: string | undefined; if (typeof response.response === 'string') { @@ -229,6 +242,27 @@ export function addResponseAttributes( } } +function addChoicesResponseAttributes(span: Span, choices: WorkersAiChoice[], recordOutputs: boolean): void { + const finishReasons = choices + .map(choice => choice.finish_reason) + .filter((reason): reason is string => typeof reason === 'string'); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify(finishReasons)); + } + + if (!recordOutputs) { + return; + } + + const messages = choices.map(({ message, finish_reason }) => ({ + responseText: typeof message?.content === 'string' ? message.content : undefined, + toolCalls: message?.tool_calls, + finishReason: typeof finish_reason === 'string' ? finish_reason : undefined, + })); + + setOutputMessagesAttribute(span, messages); +} + function addExtractResponseAttributes(span: Span, body: unknown, recordOutputs: boolean): void { if (!isObjectLike(body)) { return; diff --git a/packages/server-utils/test/ai/lib/tracing/workers-ai-streaming.test.ts b/packages/server-utils/test/ai/lib/tracing/workers-ai-streaming.test.ts index 433a0774cd20..44bd0a06df57 100644 --- a/packages/server-utils/test/ai/lib/tracing/workers-ai-streaming.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/workers-ai-streaming.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest'; import type { Span } from '@sentry/core'; import { GEN_AI_OUTPUT_MESSAGES, + GEN_AI_RESPONSE_ID, + GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, @@ -105,10 +107,10 @@ describe('instrumentWorkersAiStream', () => { // which the Cloudflare Agents SDK uses) stream `choices[].delta.content` instead of the // native top-level `response` field. Usage still arrives top-level, which is why the // pre-fix parser captured tokens but dropped the response text entirely. - it('accumulates response text from OpenAI-compatible choices[].delta.content chunks', async () => { + it('records output, id and model from OpenAI-compatible choices[].delta.content chunks', async () => { const { span, attributes, ended } = createMockSpan(); const chunks = [ - 'data: {"choices":[{"delta":{"content":"The capital "},"finish_reason":null}]}\n\n', + 'data: {"id":"chatcmpl-1","model":"@cf/google/gemma-4-26b-a4b-it","choices":[{"delta":{"content":"The capital "},"finish_reason":null}]}\n\n', 'data: {"choices":[{"delta":{"content":"of France "},"finish_reason":null}]}\n\n', 'data: {"choices":[{"delta":{"content":"is Paris."},"finish_reason":"stop"}]}\n\n', 'data: {"usage":{"prompt_tokens":12,"completion_tokens":7,"total_tokens":19}}\n\ndata: [DONE]\n\n', @@ -118,7 +120,16 @@ describe('instrumentWorkersAiStream', () => { await new Response(instrumented).text(); expect(attributes[GEN_AI_RESPONSE_STREAMING]).toBe(true); + expect(attributes[GEN_AI_RESPONSE_ID]).toBe('chatcmpl-1'); + expect(attributes[GEN_AI_RESPONSE_MODEL]).toBe('@cf/google/gemma-4-26b-a4b-it'); expect(attributes[GEN_AI_RESPONSE_TEXT]).toBe('The capital of France is Paris.'); + expect(JSON.parse(attributes[GEN_AI_OUTPUT_MESSAGES] as string)).toEqual([ + { + role: 'assistant', + parts: [{ type: 'text', content: 'The capital of France is Paris.' }], + finish_reason: 'stop', + }, + ]); expect(attributes[GEN_AI_USAGE_INPUT_TOKENS]).toBe(12); expect(attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toBe(7); expect(attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toBe(19); @@ -158,6 +169,7 @@ describe('instrumentWorkersAiStream', () => { arguments: '{"owner":"cloudflare","name":"agents"}', }, ], + finish_reason: 'tool_calls', }, ]); }); @@ -189,6 +201,7 @@ describe('instrumentWorkersAiStream', () => { { role: 'assistant', parts: [{ type: 'tool_call', id: 'call_1', name: 'getRepoInfo', arguments: '{"owner":"cloudflare"}' }], + finish_reason: 'tool_calls', }, ]); }); diff --git a/packages/server-utils/test/ai/lib/utils/workers-ai-utils.test.ts b/packages/server-utils/test/ai/lib/utils/workers-ai-utils.test.ts index fab753399663..bab865db0dcd 100644 --- a/packages/server-utils/test/ai/lib/utils/workers-ai-utils.test.ts +++ b/packages/server-utils/test/ai/lib/utils/workers-ai-utils.test.ts @@ -13,6 +13,8 @@ import { GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_OUTPUT_MESSAGES, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, @@ -371,6 +373,66 @@ describe('workers-ai utils', () => { ); }); + it('records id, model, text and finish reason from OpenAI chat-completion responses', () => { + const { span, attributes } = createMockSpan(); + + addResponseAttributes( + span, + { + id: 'chatcmpl-1', + object: 'chat.completion', + model: '@cf/google/gemma-4-26b-a4b-it', + choices: [{ index: 0, message: { role: 'assistant', content: 'Hello there!' }, finish_reason: 'stop' }], + usage: { prompt_tokens: 19, completion_tokens: 4, total_tokens: 23 }, + }, + true, + ); + + expect(attributes).toEqual({ + [GEN_AI_RESPONSE_ID]: 'chatcmpl-1', + [GEN_AI_RESPONSE_MODEL]: '@cf/google/gemma-4-26b-a4b-it', + [GEN_AI_RESPONSE_FINISH_REASONS]: JSON.stringify(['stop']), + [GEN_AI_OUTPUT_MESSAGES]: JSON.stringify([ + { role: 'assistant', parts: [{ type: 'text', content: 'Hello there!' }], finish_reason: 'stop' }, + ]), + [GEN_AI_USAGE_INPUT_TOKENS]: 19, + [GEN_AI_USAGE_OUTPUT_TOKENS]: 4, + [GEN_AI_USAGE_TOTAL_TOKENS]: 23, + }); + }); + + it('records tool calls from OpenAI chat-completion responses with null content', () => { + const { span, attributes } = createMockSpan(); + const toolCalls = [ + { id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '{"city":"Paris"}' } }, + ]; + + addResponseAttributes( + span, + { choices: [{ message: { content: null, tool_calls: toolCalls }, finish_reason: 'tool_calls' }] }, + true, + ); + + expect(attributes).toEqual({ + [GEN_AI_RESPONSE_FINISH_REASONS]: JSON.stringify(['tool_calls']), + [GEN_AI_OUTPUT_MESSAGES]: JSON.stringify([ + { + role: 'assistant', + parts: [{ type: 'tool_call', id: 'call_1', name: 'lookup', arguments: '{"city":"Paris"}' }], + finish_reason: 'tool_calls', + }, + ]), + }); + }); + + it('records only the finish reason from OpenAI chat-completion responses when recordOutputs is false', () => { + const { span, attributes } = createMockSpan(); + + addResponseAttributes(span, { choices: [{ message: { content: 'Hi' }, finish_reason: 'stop' }] }, false); + + expect(attributes).toEqual({ [GEN_AI_RESPONSE_FINISH_REASONS]: JSON.stringify(['stop']) }); + }); + it('does not set output messages when recordOutputs is false', () => { const { span, attributes } = createMockSpan(); From c0501fcd9c636e12f1c07e1793c8af3e36f70344 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:53:06 +0100 Subject: [PATCH 092/136] test(e2e): Trim tracer provider variants down to node-express (#26385) ## What Removes the `(tracer provider)` e2e variant (`E2E_TEST_OTEL_SETUP=true`) from every app except `node-express`. In `node-express`, the variant now gets a route that creates spans through `@opentelemetry/api`. ## Why The variants came in with getsentry/sentry-javascript#22957 when node stopped registering a tracer provider by default. They reran each suite unchanged and never touched OTel API spans, which is what `enableOpenTelemetrySetup: true` exists for. Keeping one targeted variant is cheaper. It also removes a duplicate job name (`node-express-static` reused the `node-express (tracer provider)` label). Open question: Nuxt may need its own variant again later, since Nitro bundles `@opentelemetry/api`. We're leaving it out for now. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794818405.731789) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794818405.731789/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../nestjs-basic/package.json | 9 ----- .../nestjs-basic/src/instrument.ts | 3 -- .../node-express-static/package.json | 9 ----- .../node-express-static/src/app.ts | 3 -- .../node-express/package.json | 2 ++ .../test-applications/node-express/src/app.ts | 11 ++++++ .../node-express/tests/otel-api.test.ts | 36 +++++++++++++++++++ .../node-fastify-5/package.json | 9 ----- .../node-fastify-5/src/app.ts | 3 -- .../node-fastify-6/package.json | 9 +---- .../node-fastify-6/src/app.ts | 2 -- .../nuxt-4-static/package.json | 7 ---- .../nuxt-4-static/sentry.server.config.ts | 3 -- .../test-applications/nuxt-4/package.json | 5 --- .../nuxt-4/sentry.server.config.ts | 3 -- 15 files changed, 50 insertions(+), 64 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/node-express/tests/otel-api.test.ts diff --git a/dev-packages/e2e-tests/test-applications/nestjs-basic/package.json b/dev-packages/e2e-tests/test-applications/nestjs-basic/package.json index 3f3f1256e788..4e569e57a1de 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-basic/package.json +++ b/dev-packages/e2e-tests/test-applications/nestjs-basic/package.json @@ -32,14 +32,5 @@ "@types/express": "^4.17.17", "@types/node": "^18.19.1", "typescript": "~5.0.0" - }, - "sentryTest": { - "variants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "nestjs-basic (tracer provider)" - } - ] } } diff --git a/dev-packages/e2e-tests/test-applications/nestjs-basic/src/instrument.ts b/dev-packages/e2e-tests/test-applications/nestjs-basic/src/instrument.ts index 7b07f60a3252..475d395af1f0 100644 --- a/dev-packages/e2e-tests/test-applications/nestjs-basic/src/instrument.ts +++ b/dev-packages/e2e-tests/test-applications/nestjs-basic/src/instrument.ts @@ -10,7 +10,4 @@ Sentry.init({ // We expect the app to send a lot of events in a short time bufferSize: 1000, }, - // Opt into the Sentry OpenTelemetry tracer provider in the "(tracer provider)" e2e variant. - // Leaving it `undefined` otherwise keeps the SDK's default (no provider). - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, }); diff --git a/dev-packages/e2e-tests/test-applications/node-express-static/package.json b/dev-packages/e2e-tests/test-applications/node-express-static/package.json index 4e05d8429c08..71339a610d87 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-static/package.json +++ b/dev-packages/e2e-tests/test-applications/node-express-static/package.json @@ -25,14 +25,5 @@ "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "@sentry/core": "file:../../packed/sentry-core-packed.tgz" - }, - "sentryTest": { - "variants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "node-express (tracer provider)" - } - ] } } diff --git a/dev-packages/e2e-tests/test-applications/node-express-static/src/app.ts b/dev-packages/e2e-tests/test-applications/node-express-static/src/app.ts index 4fe40c8da5df..dd5ace65f9a2 100644 --- a/dev-packages/e2e-tests/test-applications/node-express-static/src/app.ts +++ b/dev-packages/e2e-tests/test-applications/node-express-static/src/app.ts @@ -24,9 +24,6 @@ Sentry.init({ outputs: false, }, }, - // Opt into the Sentry OpenTelemetry tracer provider in the "(tracer provider)" e2e variant. - // Leaving it `undefined` otherwise keeps the SDK's default (no provider). - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, integrations: [ Sentry.nativeNodeFetchIntegration({ headersToSpanAttributes: { diff --git a/dev-packages/e2e-tests/test-applications/node-express/package.json b/dev-packages/e2e-tests/test-applications/node-express/package.json index adc4b406f5d4..281f5211a5ea 100644 --- a/dev-packages/e2e-tests/test-applications/node-express/package.json +++ b/dev-packages/e2e-tests/test-applications/node-express/package.json @@ -12,6 +12,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.26.0", + "@opentelemetry/api": "^1.9.1", "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "@trpc/server": "10.45.4", "@trpc/client": "10.45.4", @@ -24,6 +25,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "@sentry/conventions": "0.33.0", "@sentry/core": "file:../../packed/sentry-core-packed.tgz" }, "sentryTest": { diff --git a/dev-packages/e2e-tests/test-applications/node-express/src/app.ts b/dev-packages/e2e-tests/test-applications/node-express/src/app.ts index 1f196b138dd8..b202ee049ee1 100644 --- a/dev-packages/e2e-tests/test-applications/node-express/src/app.ts +++ b/dev-packages/e2e-tests/test-applications/node-express/src/app.ts @@ -33,6 +33,7 @@ Sentry.init({ ], }); +import { trace } from '@opentelemetry/api'; import { TRPCError, initTRPC } from '@trpc/server'; import * as trpcExpress from '@trpc/server/adapters/express'; import express from 'express'; @@ -77,6 +78,16 @@ app.get('/test-transaction', function (_req, res) { res.send({ status: 'ok' }); }); +app.get('/test-otel-api-span', function (_req, res) { + const tracer = trace.getTracer('node-express'); + tracer.startActiveSpan('otel-api-span', span => { + tracer.startActiveSpan('otel-api-child-span', childSpan => childSpan.end()); + span.end(); + }); + + res.send({ status: 'ok' }); +}); + app.get('/test-outgoing-fetch', async function (_req, res) { const response = await fetch('http://localhost:3030/test-success'); const data = await response.json(); diff --git a/dev-packages/e2e-tests/test-applications/node-express/tests/otel-api.test.ts b/dev-packages/e2e-tests/test-applications/node-express/tests/otel-api.test.ts new file mode 100644 index 000000000000..fe2b3ed82150 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/node-express/tests/otel-api.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from '@playwright/test'; +import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; +import { HTTP_SERVER } from '@sentry/conventions/op'; + +test.skip(process.env.E2E_TEST_OTEL_SETUP !== 'true', 'Only runs in the tracer provider variant'); + +test('Captures spans started via @opentelemetry/api as children of the request span', async ({ baseURL }) => { + const spansPromise = collectStreamedSpansUntilSegment( + 'node-express', + segment => getSpanOp(segment) === HTTP_SERVER && segment.name === 'GET /test-otel-api-span', + ); + + await fetch(`${baseURL}/test-otel-api-span`); + + const spans = await spansPromise; + const segmentSpan = spans.find(span => span.is_segment && span.name === 'GET /test-otel-api-span')!; + const otelSpan = spans.find(span => span.name === 'otel-api-span'); + const otelChildSpan = spans.find(span => span.name === 'otel-api-child-span'); + + expect(otelSpan).toEqual( + expect.objectContaining({ + trace_id: segmentSpan.trace_id, + is_segment: false, + attributes: expect.objectContaining({ + 'sentry.segment.id': { value: segmentSpan.span_id, type: 'string' }, + }), + }), + ); + expect(otelChildSpan).toEqual( + expect.objectContaining({ + trace_id: segmentSpan.trace_id, + parent_span_id: otelSpan!.span_id, + is_segment: false, + }), + ); +}); diff --git a/dev-packages/e2e-tests/test-applications/node-fastify-5/package.json b/dev-packages/e2e-tests/test-applications/node-fastify-5/package.json index fc96a360b6ec..205729484a3d 100644 --- a/dev-packages/e2e-tests/test-applications/node-fastify-5/package.json +++ b/dev-packages/e2e-tests/test-applications/node-fastify-5/package.json @@ -20,14 +20,5 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" - }, - "sentryTest": { - "variants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "node-fastify-5 (tracer provider)" - } - ] } } diff --git a/dev-packages/e2e-tests/test-applications/node-fastify-5/src/app.ts b/dev-packages/e2e-tests/test-applications/node-fastify-5/src/app.ts index 93c942bd16ef..d17c8cf6abb9 100644 --- a/dev-packages/e2e-tests/test-applications/node-fastify-5/src/app.ts +++ b/dev-packages/e2e-tests/test-applications/node-fastify-5/src/app.ts @@ -36,9 +36,6 @@ Sentry.init({ tracesSampleRate: 1, tunnel: 'http://localhost:3031/', // proxy server tracePropagationTargets: ['http://localhost:3030', '/external-allowed'], - // Opt into the Sentry OpenTelemetry tracer provider in the "(tracer provider)" e2e variant. - // Leaving it `undefined` otherwise keeps the SDK's default (no provider). - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, }); import type * as H from 'http'; diff --git a/dev-packages/e2e-tests/test-applications/node-fastify-6/package.json b/dev-packages/e2e-tests/test-applications/node-fastify-6/package.json index fc948455cba7..ce07fd7af7e3 100644 --- a/dev-packages/e2e-tests/test-applications/node-fastify-6/package.json +++ b/dev-packages/e2e-tests/test-applications/node-fastify-6/package.json @@ -22,13 +22,6 @@ "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { - "optional": true, - "optionalVariants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "node-fastify-6 (tracer provider)" - } - ] + "optional": true } } diff --git a/dev-packages/e2e-tests/test-applications/node-fastify-6/src/app.ts b/dev-packages/e2e-tests/test-applications/node-fastify-6/src/app.ts index d2135c2e8c69..2892ef342e9c 100644 --- a/dev-packages/e2e-tests/test-applications/node-fastify-6/src/app.ts +++ b/dev-packages/e2e-tests/test-applications/node-fastify-6/src/app.ts @@ -35,8 +35,6 @@ Sentry.init({ tracesSampleRate: 1, tunnel: 'http://localhost:3031/', // proxy server tracePropagationTargets: ['http://localhost:3030', '/external-allowed'], - // Only the "(tracer provider)" variant opts in; `undefined` keeps the SDK default - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, }); import type * as H from 'http'; diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json index 6f9f8523b77b..6ca156f76ff1 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4-static/package.json @@ -30,13 +30,6 @@ "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" }, "sentryTest": { - "variants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "nuxt-4-static (tracer provider)" - } - ], "canaryVariants": [ { "build-command": "pnpm test:build-canary", diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4-static/sentry.server.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4-static/sentry.server.config.ts index d954cf92b242..af2cc3c0eaf2 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4-static/sentry.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4-static/sentry.server.config.ts @@ -5,9 +5,6 @@ Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1.0, // Capture 100% of the transactions tunnel: 'http://localhost:3031/', // proxy server - // Opt into the Sentry OpenTelemetry tracer provider in the "(tracer provider)" e2e variant. - // Leaving it `undefined` otherwise keeps the SDK's default (no provider). - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, // Several tests trigger the same server error one after another, which Dedupe would drop. integrations: integrations => integrations.filter(integration => integration.name !== 'Dedupe'), }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json index 32dff24aae06..4ddb02c0b118 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json @@ -37,11 +37,6 @@ }, "sentryTest": { "variants": [ - { - "build-command": "E2E_TEST_OTEL_SETUP=true pnpm test:build", - "assert-command": "E2E_TEST_OTEL_SETUP=true pnpm test:assert", - "label": "nuxt-4 (tracer provider)" - }, { "build-command": "pnpm test:build", "assert-command": "pnpm test:prod:import", diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.server.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.server.config.ts index c956224de1fc..ab66d40e13c7 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.server.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.server.config.ts @@ -4,9 +4,6 @@ Sentry.init({ dsn: process.env.E2E_TEST_TUNNEL ? 'http://public@localhost:3031/1337' : 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1.0, // Capture 100% of the transactions tunnel: 'http://localhost:3031/', // proxy server - // Opt into the Sentry OpenTelemetry tracer provider in the "(tracer provider)" e2e variant. - // Leaving it `undefined` otherwise keeps the SDK's default (no provider). - enableOpenTelemetrySetup: process.env.E2E_TEST_OTEL_SETUP === 'true' ? true : undefined, // Several tests trigger the same server error one after another, which Dedupe would drop. integrations: integrations => [ ...integrations.filter(integration => integration.name !== 'Dedupe'), From aba93bc9049396f154980b8830fbcf79ddc1ad6a Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Mon, 16 Nov 2026 11:19:42 +0100 Subject: [PATCH 093/136] chore(ci): Align Node 27 integration test sharding (#26375) ## What Run Node 27 integration tests on four shards, matching the other Node versions. ## Why Shorten the slow Node 27 shards. One benchmark run per setup on GitHub ARM runners, with unchanged tests and worker settings: | Metric | [3 shards](https://github.com/getsentry/sentry-javascript/actions/runs/43595340020) | [4 shards](https://github.com/getsentry/sentry-javascript/actions/runs/43595890213) | Saved | |---|---:|---:|---:| | Slowest shard, including setup | 4m26s | 3m39s | 47s | | All Node 27 integration jobs finished, from workflow start | 6m02s | 5m25s | 37s | --------- Co-authored-by: OpenAI Codex --- .github/workflows/build.yml | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a5bfa4b3a1ad..93faffc0ee3f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -789,19 +789,9 @@ jobs: strategy: fail-fast: false matrix: - node: [20.19, 22, 24, 26] + node: [20.19, 22, 24, 26, '^27.0.0-0'] shard: [1, 2, 3, 4] shards: [4] - include: - - node: '^27.0.0-0' - shard: 1 - shards: 3 - - node: '^27.0.0-0' - shard: 2 - shards: 3 - - node: '^27.0.0-0' - shard: 3 - shards: 3 steps: - name: Check out current commit (${{ needs.job_get_metadata.outputs.commit_label }}) uses: actions/checkout@v7 From 005db14f4c8d925f4422228d23d54784ea690e36 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:23:07 +0100 Subject: [PATCH 094/136] test(nitro): Move tunnel e2e tests into a dedicated nitro-3-tunnel app (#26384) ## What Replaces the `nitro-3 (tunnel-basepath)` and `nitro-3 (tunnel-basepath-dev)` variants with a minimal `nitro-3-tunnel` app that always serves the managed tunnel under `/app`, prod and dev in one job. The tunnel checks move into a shared `runManagedTunnelSuite` (`@sentry-internal/test-utils/tunnel-suite`), and `nitro-3` drops its tunnel toggles. ## Why The variants rebuilt the whole `nitro-3` app twice just to run one spec, and the env-gated config leaked into the default app. A tiny app is cheaper to build, and the shared suite gives every framework the same checks instead of slightly different hand-written ones. This is the first PR of a stack. Each follow-up moves one framework (Nuxt, SolidStart, React Router, SvelteKit, Astro, TanStack Start, Remix) onto its own `-tunnel` app and extends the suite where that framework needs it. The suite is its own entry point so the event proxy and Playwright configs, which import the main entry, don't load `@playwright/test`. via @mydea. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AD0CA8FXFXAS%3A1794818346.521559) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0CA8FXFXAS%3A1794818346.521559/?project=4510944073809921) --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Francesco Gringl-Novy <2411343+mydea@users.noreply.github.com> --- .../nitro-3-tunnel/index.html | 20 +++ .../nitro-3-tunnel/instrument.mjs | 7 + .../nitro-3-tunnel/package.json | 23 ++++ .../nitro-3-tunnel/playwright.config.mjs | 8 ++ .../nitro-3-tunnel/pnpm-workspace.yaml | 3 + .../nitro-3-tunnel/server/api/anchor.ts | 3 + .../nitro-3-tunnel/server/api/error.ts | 5 + .../nitro-3-tunnel/server/middleware/auth.ts | 7 + .../nitro-3-tunnel/start-event-proxy.mjs | 6 + .../nitro-3-tunnel/tests/tunnel.test.ts | 3 + .../nitro-3-tunnel/vite.config.ts | 8 ++ .../test-applications/nitro-3/instrument.mjs | 3 +- .../test-applications/nitro-3/package.json | 19 +-- .../nitro-3/server/middleware/test.ts | 7 +- .../test-applications/nitro-3/src/main.ts | 12 +- .../nitro-3/tests/tunnel.test.ts | 70 ---------- .../test-applications/nitro-3/vite.config.ts | 5 - dev-packages/test-utils/package.json | 11 ++ dev-packages/test-utils/rollup.npm.config.mjs | 2 +- dev-packages/test-utils/src/tunnel-suite.ts | 120 ++++++++++++++++++ pnpm-lock.yaml | 3 + 21 files changed, 233 insertions(+), 112 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/index.html create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/instrument.mjs create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/package.json create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/playwright.config.mjs create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/pnpm-workspace.yaml create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/anchor.ts create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/error.ts create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/middleware/auth.ts create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/start-event-proxy.mjs create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/tests/tunnel.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/nitro-3-tunnel/vite.config.ts delete mode 100644 dev-packages/e2e-tests/test-applications/nitro-3/tests/tunnel.test.ts create mode 100644 dev-packages/test-utils/src/tunnel-suite.ts diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/index.html b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/index.html new file mode 100644 index 000000000000..61742e1966a5 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/index.html @@ -0,0 +1,20 @@ + + + + + Nitro Tunnel E2E Test + + + + + diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/instrument.mjs b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/instrument.mjs new file mode 100644 index 000000000000..5bc7c75f8cd1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/instrument.mjs @@ -0,0 +1,7 @@ +import * as Sentry from '@sentry/nitro'; + +Sentry.init({ + dsn: 'http://public@localhost:3031/1337', + integrations: [Sentry.serveTunnelIntegration()], + tracesSampleRate: 1, +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/package.json b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/package.json new file mode 100644 index 000000000000..162068d34d3e --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/package.json @@ -0,0 +1,23 @@ +{ + "name": "nitro-3-tunnel", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "vite build", + "start": "PORT=3030 NODE_OPTIONS='--import ./instrument.mjs' node .output/server/index.mjs", + "clean": "npx rimraf node_modules pnpm-lock.yaml .output", + "test:build": "pnpm install && pnpm build", + "test:assert": "TEST_ENV=production playwright test && TEST_ENV=development playwright test" + }, + "dependencies": { + "@sentry/browser": "latest || *", + "@sentry/nitro": "latest || *" + }, + "devDependencies": { + "@playwright/test": "1.64.1", + "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "nitro": "^3.0.260522-beta", + "vite": "latest" + } +} diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/playwright.config.mjs new file mode 100644 index 000000000000..24dd4d9ac31d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/playwright.config.mjs @@ -0,0 +1,8 @@ +import { getPlaywrightConfig } from '@sentry-internal/test-utils'; + +export default getPlaywrightConfig({ + startCommand: + process.env.TEST_ENV === 'development' + ? `PORT=3030 NODE_OPTIONS='--import ./instrument.mjs' pnpm exec vite dev --port 3030` + : `pnpm start`, +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/pnpm-workspace.yaml new file mode 100644 index 000000000000..c6eea3e5ab0a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +minimumReleaseAge: 0 +overrides: + 'unstorage': '2.0.0-alpha.7' diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/anchor.ts b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/anchor.ts new file mode 100644 index 000000000000..7f820ccd5ef3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/anchor.ts @@ -0,0 +1,3 @@ +import { defineHandler } from 'nitro/h3'; + +export default defineHandler(() => ({ ok: true })); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/error.ts b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/error.ts new file mode 100644 index 000000000000..8630745dc6f1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/api/error.ts @@ -0,0 +1,5 @@ +import { defineHandler } from 'nitro/h3'; + +export default defineHandler(() => { + throw new Error('Tunnel test error'); +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/middleware/auth.ts b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/middleware/auth.ts new file mode 100644 index 000000000000..5052cc94842f --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/server/middleware/auth.ts @@ -0,0 +1,7 @@ +import { defineHandler, HTTPError } from 'nitro/h3'; + +export default defineHandler(event => { + if (event.req.method === 'POST') { + throw new HTTPError({ status: 401, statusText: 'blocked by user auth' }); + } +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/start-event-proxy.mjs b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/start-event-proxy.mjs new file mode 100644 index 000000000000..fc9c49b19b09 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/start-event-proxy.mjs @@ -0,0 +1,6 @@ +import { startEventProxyServer } from '@sentry-internal/test-utils'; + +startEventProxyServer({ + port: 3031, + proxyServerName: 'nitro-3-tunnel', +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/tests/tunnel.test.ts b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/tests/tunnel.test.ts new file mode 100644 index 000000000000..713764759c82 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/tests/tunnel.test.ts @@ -0,0 +1,3 @@ +import { runManagedTunnelSuite } from '@sentry-internal/test-utils/tunnel-suite'; + +runManagedTunnelSuite({ appName: 'nitro-3-tunnel', basePath: '/app' }); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/vite.config.ts b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/vite.config.ts new file mode 100644 index 000000000000..06e9ca9776f7 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nitro-3-tunnel/vite.config.ts @@ -0,0 +1,8 @@ +import { withSentryConfig } from '@sentry/nitro'; +import { nitro } from 'nitro/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + // @ts-expect-error The Nitro plugin's types don't accept the config `withSentryConfig` returns + plugins: [nitro(withSentryConfig({ serverDir: './server', baseURL: '/app/' }))], +}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/instrument.mjs b/dev-packages/e2e-tests/test-applications/nitro-3/instrument.mjs index c5c0fbd3d966..53b80d309a5b 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/instrument.mjs +++ b/dev-packages/e2e-tests/test-applications/nitro-3/instrument.mjs @@ -2,8 +2,7 @@ import * as Sentry from '@sentry/nitro'; Sentry.init({ environment: 'qa', // dynamic sampling bias to keep transactions - dsn: process.env.E2E_TEST_TUNNEL ? 'http://public@localhost:3031/1337' : process.env.E2E_TEST_DSN, + dsn: process.env.E2E_TEST_DSN, tunnel: `http://localhost:3031/`, // proxy server - integrations: process.env.E2E_TEST_TUNNEL ? [Sentry.serveTunnelIntegration()] : [], tracesSampleRate: 1, }); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/package.json b/dev-packages/e2e-tests/test-applications/nitro-3/package.json index 1d716de7438f..c8103a134e82 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/package.json +++ b/dev-packages/e2e-tests/test-applications/nitro-3/package.json @@ -9,10 +9,7 @@ "clean": "npx rimraf node_modules pnpm-lock.yaml .output", "test": "playwright test", "test:build": "pnpm install && pnpm build", - "test:assert": "pnpm test", - "test:build:tunnel-basepath": "pnpm install && E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app pnpm build", - "test:assert:tunnel-basepath": "E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app playwright test tunnel", - "test:assert:tunnel-basepath-dev": "TEST_ENV=development E2E_TEST_TUNNEL=1 E2E_TEST_BASE_PATH=/app playwright test tunnel" + "test:assert": "pnpm test" }, "dependencies": { "@sentry/browser": "latest || *", @@ -26,19 +23,5 @@ "nitro": "^3.0.260522-beta", "rolldown": "latest", "vite": "latest" - }, - "sentryTest": { - "variants": [ - { - "build-command": "pnpm test:build:tunnel-basepath", - "assert-command": "pnpm test:assert:tunnel-basepath", - "label": "nitro-3 (tunnel-basepath)" - }, - { - "build-command": "pnpm install", - "assert-command": "pnpm test:assert:tunnel-basepath-dev", - "label": "nitro-3 (tunnel-basepath-dev)" - } - ] } } diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/server/middleware/test.ts b/dev-packages/e2e-tests/test-applications/nitro-3/server/middleware/test.ts index 0120ae6ce24e..92d8f80c3756 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/server/middleware/test.ts +++ b/dev-packages/e2e-tests/test-applications/nitro-3/server/middleware/test.ts @@ -1,11 +1,6 @@ -import { defineHandler, getQuery, HTTPError, setResponseHeader } from 'nitro/h3'; +import { defineHandler, getQuery, setResponseHeader } from 'nitro/h3'; export default defineHandler(event => { - // The tunnel variant checks that the managed tunnel answers before an auth middleware like this one. - if (process.env.E2E_TEST_TUNNEL && event.req.method === 'POST' && event.req.headers.get('x-auth') !== 'ok') { - throw new HTTPError({ status: 401, statusText: 'blocked by user auth' }); - } - setResponseHeader(event, 'x-sentry-test-middleware', 'executed'); const query = getQuery(event); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/src/main.ts b/dev-packages/e2e-tests/test-applications/nitro-3/src/main.ts index d09a43e411ed..d27d0ba1763a 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/src/main.ts +++ b/dev-packages/e2e-tests/test-applications/nitro-3/src/main.ts @@ -1,18 +1,10 @@ import * as Sentry from '@sentry/browser'; -declare const __E2E_TEST_TUNNEL__: boolean; -declare const __E2E_TEST_BASE_PATH__: string; - // Let's us test trace propagation Sentry.init({ environment: 'qa', - dsn: __E2E_TEST_TUNNEL__ ? 'http://public@localhost:3031/1337' : 'https://public@dsn.ingest.sentry.io/1337', - // Plain Nitro has no client SDK to pass `baseURL` on, so the browser names it. The server picks it up itself. - tunnel: __E2E_TEST_TUNNEL__ - ? __E2E_TEST_BASE_PATH__ - ? { basePath: __E2E_TEST_BASE_PATH__ } - : true - : 'http://localhost:3031/', // proxy server + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tunnel: 'http://localhost:3031/', // proxy server integrations: [Sentry.browserTracingIntegration()], tracesSampleRate: 1.0, }); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/tests/tunnel.test.ts b/dev-packages/e2e-tests/test-applications/nitro-3/tests/tunnel.test.ts deleted file mode 100644 index 9d7cfadaeeb6..000000000000 --- a/dev-packages/e2e-tests/test-applications/nitro-3/tests/tunnel.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { expect, test } from '@playwright/test'; -import { - isServerSpanAt, - makeClientReportEnvelope, - waitForError, - watchForTunnelSpan, -} from '@sentry-internal/test-utils'; -import { getTunnelPath } from '@sentry/core'; -import { connect } from 'node:net'; - -test.skip(!process.env.E2E_TEST_TUNNEL, 'Only runs in the tunnel variant'); - -const BASE_PATH = process.env.E2E_TEST_BASE_PATH ?? ''; -const TUNNEL_PATH = new RegExp(`^${BASE_PATH}/[a-z0-9]{1,7}$`); - -test('answers the managed tunnel before the app auth middleware', async ({ page }) => { - // The variant's auth middleware rejects every other POST. - expect((await page.request.post(`${BASE_PATH}/api/anything`, { data: 'x' })).status()).toBe(401); - - const raceTunnelSpan = watchForTunnelSpan('nitro-3', isServerSpanAt(TUNNEL_PATH)); - const tunnelResponsePromise = page.waitForResponse( - response => response.request().method() === 'POST' && TUNNEL_PATH.test(new URL(response.url()).pathname), - ); - - await page.goto(`${BASE_PATH}/`); - - expect((await tunnelResponsePromise).status()).toBe(200); - expect( - await raceTunnelSpan(isServerSpanAt(`${BASE_PATH}/api/test-transaction`), () => - page.request.get(`${BASE_PATH}/api/test-transaction`), - ), - ).toBe('anchor'); -}); - -test('answers a request to the managed tunnel itself', async ({ request }) => { - const dsn = 'http://public@localhost:3031/1337'; - const response = await request.post(`${BASE_PATH}${getTunnelPath(dsn)}`, { - data: makeClientReportEnvelope(dsn), - headers: { 'Content-Type': 'application/x-sentry-envelope' }, - }); - - expect(response.status()).toBe(200); -}); - -test('does not report a client that drops the connection before the envelope header as an error', async ({ - request, -}) => { - const dsn = 'http://public@localhost:3031/1337'; - const firstErrorPromise = waitForError('nitro-3', () => true); - - // Part of the envelope header line, without its newline, then the connection drops. - await new Promise(resolve => { - const socket = connect(3030, 'localhost', () => { - socket.write( - `POST ${BASE_PATH}${getTunnelPath(dsn)} HTTP/1.1\r\nHost: localhost:3030\r\nContent-Type: application/x-sentry-envelope\r\nContent-Length: 1000000\r\n\r\n`, - ); - socket.write(JSON.stringify({ dsn, padding: 'x'.repeat(1000) }).slice(0, 500)); - setTimeout(() => { - socket.destroy(); - resolve(); - }, 300); - }); - }); - - // Errors are sent in order, so one from the dropped request would arrive before this one. - await request.get(`${BASE_PATH}/api/test-error`); - - const firstError = await firstErrorPromise; - expect(firstError.exception?.values?.[0]?.value).toBe('This is a test error'); -}); diff --git a/dev-packages/e2e-tests/test-applications/nitro-3/vite.config.ts b/dev-packages/e2e-tests/test-applications/nitro-3/vite.config.ts index b79a665ba851..bb1593e1dcf3 100644 --- a/dev-packages/e2e-tests/test-applications/nitro-3/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/nitro-3/vite.config.ts @@ -3,10 +3,6 @@ import { nitro } from 'nitro/vite'; import { defineConfig } from 'vite'; export default defineConfig({ - define: { - __E2E_TEST_TUNNEL__: JSON.stringify(!!process.env.E2E_TEST_TUNNEL), - __E2E_TEST_BASE_PATH__: JSON.stringify(process.env.E2E_TEST_BASE_PATH ?? ''), - }, plugins: [ nitro( // FIXME: Nitro plugin has a type issue @@ -14,7 +10,6 @@ export default defineConfig({ withSentryConfig({ serverDir: './server', experimental: { tasks: true }, - ...(process.env.E2E_TEST_BASE_PATH && { baseURL: `${process.env.E2E_TEST_BASE_PATH}/` }), }), ), ], diff --git a/dev-packages/test-utils/package.json b/dev-packages/test-utils/package.json index b8d356b01237..8f4c2f8eedc7 100644 --- a/dev-packages/test-utils/package.json +++ b/dev-packages/test-utils/package.json @@ -41,6 +41,16 @@ "types": "./build/types/cloudflare.d.ts", "default": "./build/cjs/cloudflare.js" } + }, + "./tunnel-suite": { + "import": { + "types": "./build/types/tunnel-suite.d.ts", + "default": "./build/esm/tunnel-suite.js" + }, + "require": { + "types": "./build/types/tunnel-suite.d.ts", + "default": "./build/cjs/tunnel-suite.js" + } } }, "sideEffects": false, @@ -61,6 +71,7 @@ "@playwright/test": "1.64.1" }, "dependencies": { + "@sentry/conventions": "^0.33.0", "express": "^4.22.3", "ws": "^8.20.1" }, diff --git a/dev-packages/test-utils/rollup.npm.config.mjs b/dev-packages/test-utils/rollup.npm.config.mjs index 600fca5e73e6..c48d3da692ab 100644 --- a/dev-packages/test-utils/rollup.npm.config.mjs +++ b/dev-packages/test-utils/rollup.npm.config.mjs @@ -2,7 +2,7 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollu export default makeNPMConfigVariants( makeBaseNPMConfig({ - entrypoints: ['src/index.ts', 'src/cli.ts', 'src/cloudflare.ts'], + entrypoints: ['src/index.ts', 'src/cli.ts', 'src/cloudflare.ts', 'src/tunnel-suite.ts'], packageSpecificConfig: { output: { // set exports to 'named' or 'auto' so that rollup doesn't warn diff --git a/dev-packages/test-utils/src/tunnel-suite.ts b/dev-packages/test-utils/src/tunnel-suite.ts new file mode 100644 index 000000000000..d572b4dbb450 --- /dev/null +++ b/dev-packages/test-utils/src/tunnel-suite.ts @@ -0,0 +1,120 @@ +import { expect, test } from '@playwright/test'; +import { HTTP_CLIENT } from '@sentry/conventions/op'; +import type { Event, SerializedStreamedSpan } from '@sentry/core'; +import { connect } from 'node:net'; +import { getSpanOp, waitForError, waitForRequest } from './event-proxy-server'; +import { isServerSpanAt, makeClientReportEnvelope, watchForTunnelSpan } from './tunnel'; + +/** The port `getPlaywrightConfig` serves the app on by default. */ +const APP_PORT = 3030; + +/** The DSN a tunnel test app sends to, which forwards to its event proxy. */ +const TUNNEL_TEST_DSN = 'http://public@localhost:3031/1337'; + +/** The path the SDK derives from `TUNNEL_TEST_DSN`. */ +const DSN_TUNNEL_PATH = '/qpo967'; + +/** The message of the error that `{basePath}/api/error` throws. */ +const TUNNEL_TEST_ERROR_MESSAGE = 'Tunnel test error'; + +export interface ManagedTunnelSuiteOptions { + /** The `proxyServerName` of the app's event proxy. */ + appName: string; + /** The base path the app and its managed tunnel are served under, like `/app`. */ + basePath: string; +} + +/** + * Tests the managed tunnel of an app that serves it under a base path. The app has: + * - `serveTunnelIntegration()` on the server and `tunnel: true` (or the base path) in the browser, both with + * `TUNNEL_TEST_DSN` + * - a page at `{basePath}/` that loads the browser SDK + * - `GET {basePath}/api/anchor`, answered with a 200 + * - `GET {basePath}/api/error`, which throws `TUNNEL_TEST_ERROR_MESSAGE` + * - a middleware that answers every POST with a 401 + */ +export function runManagedTunnelSuite({ appName, basePath }: ManagedTunnelSuiteOptions): void { + const tunnelPath = `${basePath}${DSN_TUNNEL_PATH}`; + const isTunnelRequest = (method: string, url: string): boolean => + method === 'POST' && new URL(url).pathname === tunnelPath; + + test('answers the browser under the base path before the app middleware, without spans of it', async ({ page }) => { + expect((await page.request.post(`${basePath}/api/anchor`, { data: 'x' })).status()).toBe(401); + + const raceTunnelSpan = watchForTunnelSpan( + appName, + span => isServerSpanAt(tunnelPath)(span) || isIngestRequestSpan(span), + ); + const tunnelResponsePromise = page.waitForResponse(response => + isTunnelRequest(response.request().method(), response.url()), + ); + + await page.goto(`${basePath}/`); + + expect((await tunnelResponsePromise).status()).toBe(200); + expect( + await raceTunnelSpan(isServerSpanAt(`${basePath}/api/anchor`), () => page.request.get(`${basePath}/api/anchor`)), + ).toBe('anchor'); + }); + + test('forwards browser events without the cookies of the browser', async ({ page, context, baseURL }) => { + const message = 'Tunnel cookie test'; + await context.addCookies([{ name: 'session', value: '8f2c1d', url: baseURL }]); + const proxyRequestPromise = waitForRequest(appName, ({ envelope }) => + envelope[1].some( + ([itemHeader, item]) => + itemHeader.type === 'event' && (item as Event).exception?.values?.[0]?.value === message, + ), + ); + + await page.goto(`${basePath}/`); + await page.waitForFunction(() => typeof (globalThis as { __SENTRY__?: unknown }).__SENTRY__ === 'object'); + const tunnelRequestPromise = page.waitForRequest( + request => isTunnelRequest(request.method(), request.url()) && !!request.postData()?.includes(message), + ); + await page.evaluate(message => { + setTimeout(() => { + throw new Error(message); + }); + }, message); + + expect((await (await tunnelRequestPromise).allHeaders()).cookie).toBe('session=8f2c1d'); + const { rawProxyRequestHeaders } = await proxyRequestPromise; + expect(rawProxyRequestHeaders.cookie).toBeUndefined(); + expect(rawProxyRequestHeaders['content-type']).toBe('application/x-sentry-envelope'); + }); + + test('answers tunnel requests without errors, also when the client drops the connection', async ({ request }) => { + const firstErrorPromise = waitForError(appName, () => true); + + const response = await request.post(tunnelPath, { + data: makeClientReportEnvelope(TUNNEL_TEST_DSN), + headers: { 'Content-Type': 'application/x-sentry-envelope' }, + }); + expect(response.status()).toBe(200); + + // Part of the envelope header line, without its newline, then the connection drops. + await new Promise(resolve => { + const socket = connect(APP_PORT, 'localhost', () => { + socket.write( + `POST ${tunnelPath} HTTP/1.1\r\nHost: localhost:${APP_PORT}\r\nContent-Type: application/x-sentry-envelope\r\nContent-Length: 1000000\r\n\r\n`, + ); + socket.write(JSON.stringify({ dsn: TUNNEL_TEST_DSN, padding: 'x'.repeat(1000) }).slice(0, 500)); + setTimeout(() => { + socket.destroy(); + resolve(); + }, 300); + }); + }); + + // Errors are sent in order, so one from a tunnel request would arrive before this one. + await request.get(`${basePath}/api/error`); + + expect((await firstErrorPromise).exception?.values?.[0]?.value).toBe(TUNNEL_TEST_ERROR_MESSAGE); + }); +} + +function isIngestRequestSpan(span: SerializedStreamedSpan): boolean { + const url = span.attributes['url.full']?.value; + return getSpanOp(span) === HTTP_CLIENT && typeof url === 'string' && url.startsWith('http://localhost:3031/'); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ada98a8757a1..44f267f09936 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -895,6 +895,9 @@ importers: dev-packages/test-utils: dependencies: + '@sentry/conventions': + specifier: ^0.33.0 + version: 0.33.0 express: specifier: ^4.22.3 version: 4.22.3(supports-color@10.0.0) From 426af091f5feee99ef8a4a6b5e4547a7214bb0e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Mon, 16 Nov 2026 11:29:01 +0100 Subject: [PATCH 095/136] feat(cloudflare): Continue the Cloudflare trace of the invocation (#25613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes #22214 closes [JS-3018](https://linear.app/getsentry/issue/JS-3018) ## Description When Sentry tracing is not set up (no `tracesSampleRate` or `tracesSampler`), this continues the trace that Cloudflare starts for each invocation (fetch, scheduled, queue and email handlers, and `WorkerEntrypoint` RPC methods). Errors and logs then have the same trace id as the Cloudflare spans in Workers Observability. An incoming Sentry trace (`sentry-trace` header or RPC trace data) still has precedence. When tracing is set up, the SDK keeps starting its own traces as before. This keeps a single tracing source per trace, so Cloudflare and SDK spans never mix in one trace and Sentry does not get the same request spans twice. We can still add an opt-in to continue the Cloudflare trace with tracing enabled later if there is demand. `tracesSampleRate: 0` counts as tracing set up (same check as `hasSpansEnabled`). ## Known issues - The SDK reads `Span.spanContext()`, which ships in workerd 1.20261009.1. Older runtimes keep the current behavior, so only the optional CI job with the latest wrangler runs the new code path. - Durable Object handlers do not continue the Cloudflare trace, because `DurableObjectState` has no `tracing`. A follow-up can read `tracing` from `cloudflare:workers` instead. - Without a Cloudflare traces destination, the parent of the Sentry error is not in Sentry. ## Sentry traces Error without tracing, in the Cloudflare trace: https://sentry-sdks.sentry.io/explore/traces/trace/666e09b1979b18724b8fd77faed99e1b/?project=4510555608449024&statsPeriod=14d (captured with `tracesSampleRate: 0` before tracing gated the behavior) Same error without this PR, in its own trace: https://sentry-sdks.sentry.io/explore/traces/trace/bc56b593dcf941c7b21af6216f215dff/?project=4510555608449024&statsPeriod=14d via **Jan Peer Stöcklmair**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CA6TD3QRK%3A1794409643.554379) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CA6TD3QRK%3A1794409643.554379/?project=4510944073809921) --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> --- CHANGELOG.md | 6 + .../cloudflare-integration-tests/expect.ts | 2 + .../cloudflare-integration-tests/runtime.ts | 31 ++++ .../suites/hono-sdk/test.ts | 8 +- .../suites/tracing/cloudflare-trace/index.ts | 18 +++ .../cloudflare-trace/instrument.server.ts | 6 + .../suites/tracing/cloudflare-trace/test.ts | 104 ++++++++++++ .../tracing/cloudflare-trace/vite.config.mts | 7 + .../tracing/cloudflare-trace/wrangler.jsonc | 9 ++ .../suites/tracing/dsc-url-source/test.ts | 8 +- .../worker/instrumentEmail.ts | 2 + .../worker/instrumentQueue.ts | 2 + .../worker/instrumentScheduled.ts | 2 + .../cloudflare/src/utils/cloudflareTrace.ts | 58 +++++++ .../cloudflare/src/wrapMethodWithSentry.ts | 11 +- .../src/wrapRequestHandlerWithInit.ts | 2 + .../instrumentWorkerEntrypoint.test.ts | 95 +++++++++++ .../worker/instrumentEmail.test.ts | 46 ++++++ .../worker/instrumentQueue.test.ts | 46 ++++++ .../worker/instrumentScheduled.test.ts | 46 ++++++ packages/cloudflare/test/request.test.ts | 153 ++++++++++++++++++ .../test/utils/cloudflareTrace.test.ts | 153 ++++++++++++++++++ .../src/utils/wrapServerRequestHandler.ts | 7 + 23 files changed, 816 insertions(+), 6 deletions(-) create mode 100644 dev-packages/cloudflare-integration-tests/runtime.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts create mode 100644 dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc create mode 100644 packages/cloudflare/src/utils/cloudflareTrace.ts create mode 100644 packages/cloudflare/test/utils/cloudflareTrace.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 193f6a328043..16b687a4b908 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,12 @@ Work in this release was contributed by @kunal649 and @bardrop. Thank you for yo HTTP spans that the SDK builds from a `URL` now send `url.scheme` without the trailing colon (`https` instead of `https:`) and `url.port` as a number instead of a string, as the Sentry conventions define them and as Node `http.server` spans already do. This changes `http.server` spans from `@sentry/cloudflare`, `Bun.serve`, Deno and Nitro, and outgoing `node:http` client spans. Update saved queries, alerts and dashboards that filter on `url.scheme:"https:"` or on `url.port` as a string. +- **feat(cloudflare): Continue the Cloudflare trace of the invocation ([#25613](https://github.com/getsentry/sentry-javascript/pull/25613))** + + When tracing is not set up (no `tracesSampleRate` or `tracesSampler`), errors and logs from fetch, scheduled, queue and email handlers and from `WorkerEntrypoint` RPC methods now get the trace id that Cloudflare gives the invocation. With this trace id, you can find the Cloudflare spans and logs of an error in Workers Observability. This needs workerd 1.20261009.1 or newer and Workers Observability turned on. An incoming Sentry trace still has precedence. + + The `parent_span_id` of these events is the id of a Cloudflare span. This span is in Sentry only when you export your Workers traces to Sentry. + ## 11.12.0 ### Important Changes diff --git a/dev-packages/cloudflare-integration-tests/expect.ts b/dev-packages/cloudflare-integration-tests/expect.ts index 71eb5c9963c4..5d7699e70367 100644 --- a/dev-packages/cloudflare-integration-tests/expect.ts +++ b/dev-packages/cloudflare-integration-tests/expect.ts @@ -1,6 +1,7 @@ import type { Contexts, Envelope, Event, SdkInfo } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; import { expect } from 'vitest'; +import { supports } from './runtime'; export const UUID_MATCHER = expect.stringMatching(/^[\da-f]{32}$/); export const UUID_V4_MATCHER = expect.stringMatching( @@ -39,6 +40,7 @@ function defaultContexts(eventContexts: Contexts = {}): Contexts { trace: { trace_id: UUID_MATCHER, span_id: SHORT_UUID_MATCHER, + parent_span_id: supports({ minWorkerd: '1.20261009.1' }) ? SHORT_UUID_MATCHER : undefined, }, cloud_resource: { 'cloud.provider': 'cloudflare' }, culture: { timezone: expect.any(String) }, diff --git a/dev-packages/cloudflare-integration-tests/runtime.ts b/dev-packages/cloudflare-integration-tests/runtime.ts new file mode 100644 index 000000000000..9f175f0c94be --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/runtime.ts @@ -0,0 +1,31 @@ +import { parseSemver } from '@sentry/core'; +import { createRequire } from 'module'; + +// `wrangler dev` runs the workerd that its own miniflare depends on. +const wranglerRequire = createRequire(createRequire(__filename).resolve('wrangler/package.json')); +const miniflareRequire = createRequire(wranglerRequire.resolve('miniflare/package.json')); +const WORKERD_VERSION = parseSemver((miniflareRequire('workerd/package.json') as { version: string }).version); + +export type Requirements = { + /** Lowest workerd version that runs the tests, for example `1.20261009.1`. */ + minWorkerd?: string; +}; + +/** + * Whether the workerd that runs the Workers meets the requirements of the tests, for use in `it.runIf` and + * `it.skipIf`. The pinned wrangler of the required CI job runs an older workerd than the latest wrangler of the + * optional CI job. + */ +export function supports({ minWorkerd }: Requirements): boolean { + if (!minWorkerd) { + return true; + } + + const required = parseSemver(minWorkerd); + const difference = + (WORKERD_VERSION.major || 0) - (required.major || 0) || + (WORKERD_VERSION.minor || 0) - (required.minor || 0) || + (WORKERD_VERSION.patch || 0) - (required.patch || 0); + + return difference >= 0; +} diff --git a/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts b/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts index 33ba266ed7cc..ebf929489edd 100644 --- a/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/hono-sdk/test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { eventEnvelope } from '../../expect'; +import { eventEnvelope, SHORT_UUID_MATCHER, UUID_MATCHER } from '../../expect'; import { createRunner } from '../../runner'; import { getSpanOp, getSpansFromEnvelope } from '../../spanUtils'; @@ -28,6 +28,12 @@ it('Hono app captures parametrized errors (Hono SDK)', async ({ signal }) => { method: 'GET', url: expect.stringContaining('/error/param-123'), }, + contexts: { + trace: { + trace_id: UUID_MATCHER, + span_id: SHORT_UUID_MATCHER, + }, + }, breadcrumbs: [ { timestamp: expect.any(Number), diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts new file mode 100644 index 000000000000..4da39ebf2b88 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/index.ts @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/cloudflare'; + +// `getActiveSpan` and `Span.spanContext` are newer than the installed workers types, and older runtimes do not have +// them. +interface CloudflareTracing { + getActiveSpan?(): { isTraced?: boolean; spanContext?(): { traceId: string; spanId: string } } | undefined; +} + +export default { + async fetch(_request, _env, ctx) { + const span = (ctx.tracing as unknown as CloudflareTracing | undefined)?.getActiveSpan?.(); + const spanContext = span?.isTraced ? span.spanContext?.() : undefined; + + Sentry.captureException(new Error('Error in a Cloudflare trace')); + + return Response.json(spanContext ? { traceId: spanContext.traceId, spanId: spanContext.spanId } : null); + }, +} satisfies ExportedHandler; diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts new file mode 100644 index 000000000000..0d33b7bb23d0 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/instrument.server.ts @@ -0,0 +1,6 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: { SENTRY_DSN: string; TRACES_SAMPLE_RATE: string }) => ({ + dsn: env.SENTRY_DSN, + tracesSampleRate: env.TRACES_SAMPLE_RATE ? Number(env.TRACES_SAMPLE_RATE) : undefined, +})); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts new file mode 100644 index 000000000000..2f6323969634 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/test.ts @@ -0,0 +1,104 @@ +import type { Event, SerializedStreamedSpanContainer } from '@sentry/core'; +import { expect, it } from 'vitest'; +import { SHORT_UUID_MATCHER, UUID_MATCHER } from '../../../expect'; +import { createRunner } from '../../../runner'; +import { supports } from '../../../runtime'; + +// `Span.spanContext()` ships in workerd 1.20261009.1. Without it, the Worker responds with `null`. +it.runIf(supports({ minWorkerd: '1.20261009.1' }))( + 'uses the Cloudflare trace for the error event when tracing is not set up', + async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + expect(cloudflareSpan).toEqual({ traceId: UUID_MATCHER, spanId: SHORT_UUID_MATCHER }); + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace).toEqual({ + trace_id: cloudflareSpan?.traceId, + span_id: SHORT_UUID_MATCHER, + parent_span_id: cloudflareSpan?.spanId, + }); + }, +); + +it.runIf(supports({ minWorkerd: '1.20261009.1' }))( + 'starts its own trace when tracing is set up', + async ({ signal }) => { + const errorEvents: Event[] = []; + const spanContainers: SerializedStreamedSpanContainer[] = []; + + const runner = createRunner(__dirname) + .withWranglerArgs('--var', 'TRACES_SAMPLE_RATE:1') + .unordered() + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('span'); + spanContainers.push(envelope[1][0][1] as SerializedStreamedSpanContainer); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + const segmentSpans = spanContainers.flatMap(container => container.items).filter(span => span.is_segment); + expect(cloudflareSpan).toEqual({ traceId: UUID_MATCHER, spanId: SHORT_UUID_MATCHER }); + expect(errorEvents).toHaveLength(1); + expect(segmentSpans).toHaveLength(1); + expect(segmentSpans[0]?.trace_id).not.toBe(cloudflareSpan?.traceId); + expect(segmentSpans[0]?.parent_span_id).toBeUndefined(); + expect(errorEvents[0]?.contexts?.trace?.trace_id).toBe(segmentSpans[0]?.trace_id); + }, +); + +it.skipIf(supports({ minWorkerd: '1.20261009.1' }))( + 'starts its own trace on runtimes without `Span.spanContext()`', + async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + const cloudflareSpan = await runner.makeRequest<{ traceId: string; spanId: string } | null>('get', '/'); + await runner.completed(); + + expect(cloudflareSpan).toBeNull(); + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace).toEqual({ trace_id: UUID_MATCHER, span_id: SHORT_UUID_MATCHER }); + }, +); + +it('continues an incoming Sentry trace instead of the Cloudflare trace', async ({ signal }) => { + const errorEvents: Event[] = []; + + const runner = createRunner(__dirname) + .expect(envelope => { + expect(envelope[1][0][0].type).toBe('event'); + errorEvents.push(envelope[1][0][1] as Event); + }) + .start(signal); + + await runner.makeRequest('get', '/', { + headers: { 'sentry-trace': '12345678901234567890123456789012-1234567890123456-1' }, + }); + await runner.completed(); + + expect(errorEvents).toHaveLength(1); + expect(errorEvents[0]?.contexts?.trace?.trace_id).toBe('12345678901234567890123456789012'); + expect(errorEvents[0]?.contexts?.trace?.parent_span_id).toBe('1234567890123456'); +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/vite.config.mts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc new file mode 100644 index 000000000000..37b1010b07a7 --- /dev/null +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/cloudflare-trace/wrangler.jsonc @@ -0,0 +1,9 @@ +{ + "name": "cloudflare-trace-worker", + "compatibility_date": "2025-06-17", + "main": "index.ts", + "compatibility_flags": ["nodejs_compat"], + "vars": { + "TRACES_SAMPLE_RATE": "", + }, +} diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts index f9916e5c03c7..fb98b6ed2bc5 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/dsc-url-source/test.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest'; -import { eventEnvelope } from '../../../expect'; +import { eventEnvelope, SHORT_UUID_MATCHER, UUID_MATCHER } from '../../../expect'; import { createRunner } from '../../../runner'; import { getSpanOp, getSpansFromEnvelope } from '../../../spanUtils'; @@ -29,6 +29,12 @@ it('omits the span name from the DSC for url-source spans when tracing is enable method: 'GET', url: expect.any(String), }, + contexts: { + trace: { + trace_id: UUID_MATCHER, + span_id: SHORT_UUID_MATCHER, + }, + }, }, { includeSamplingFields: true, includeSampleRand: true, includeTransaction: false }, ), diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts b/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts index 11a8fb9b419d..cafb160e896b 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentEmail.ts @@ -16,6 +16,7 @@ import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; +import { continueCloudflareTrace } from '../../utils/cloudflareTrace'; import { instrumentContext } from '../../utils/instrumentContext'; import { setInvocationState } from '../../utils/invocationContext'; import { instrumentEnv } from './instrumentEnv'; @@ -38,6 +39,7 @@ function wrapEmailHandler( isolationScope.setClient(client); addCloudResourceContext(isolationScope); + continueCloudflareTrace(context); return startSpan( { diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts b/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts index f6339248726f..045cf261ca9f 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentQueue.ts @@ -24,6 +24,7 @@ import { ensureInstrumented } from '../../instrument'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; +import { continueCloudflareTrace } from '../../utils/cloudflareTrace'; import { instrumentContext } from '../../utils/instrumentContext'; import { setInvocationState } from '../../utils/invocationContext'; import { extractQueueTraceContext } from '../../utils/queueTraceMeta'; @@ -79,6 +80,7 @@ function wrapQueueHandler( isolationScope.setClient(client); addCloudResourceContext(isolationScope); + continueCloudflareTrace(context); return startSpan( { diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts b/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts index 8285830b73c1..2cbe32129368 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentScheduled.ts @@ -21,6 +21,7 @@ import type { CronTriggersIntegration } from '../../integrations/cronTriggers'; import { getFinalOptions } from '../../options'; import { addCloudResourceContext } from '../../scope-utils'; import { init } from '../../sdk'; +import { continueCloudflareTrace } from '../../utils/cloudflareTrace'; import { instrumentContext } from '../../utils/instrumentContext'; import { setInvocationState } from '../../utils/invocationContext'; import { instrumentEnv } from './instrumentEnv'; @@ -40,6 +41,7 @@ function wrapScheduledHandler( isolationScope.setClient(client); addCloudResourceContext(isolationScope); + continueCloudflareTrace(context); const description = `Scheduled Cron ${controller.cron}`; diff --git a/packages/cloudflare/src/utils/cloudflareTrace.ts b/packages/cloudflare/src/utils/cloudflareTrace.ts new file mode 100644 index 000000000000..6b9fa51e93d2 --- /dev/null +++ b/packages/cloudflare/src/utils/cloudflareTrace.ts @@ -0,0 +1,58 @@ +import { _INTERNAL_safeMathRandom, getCurrentScope, hasSpansEnabled, isContinuingTrace } from '@sentry/core'; + +interface CloudflareSpanContext { + traceId: string; + spanId: string; +} + +// The part of `ctx.tracing` the SDK reads. `getActiveSpan` and `Span.spanContext` exist only in +// newer runtimes, so every member is optional. +interface CloudflareTracing { + getActiveSpan?: () => + | { + readonly isTraced?: boolean; + spanContext?: () => CloudflareSpanContext; + } + | undefined; +} + +const TRACE_ID_REGEXP = /^(?!0{32})[0-9a-f]{32}$/; +const SPAN_ID_REGEXP = /^(?!0{16})[0-9a-f]{16}$/; + +/** + * Sets the propagation context of the current scope to the Cloudflare trace of the invocation, so + * errors, logs and spans get the trace id of the spans that Cloudflare exports. + * + * Only runs when Sentry tracing is not set up (no `tracesSampleRate` or `tracesSampler`), so a trace + * has one source: either the SDK or Cloudflare, never a mix of both. + * + * Does nothing when the current scope already continues a trace, for example an incoming Sentry + * trace, when Cloudflare does not trace the invocation, or when the runtime does not expose + * `Span.spanContext()`. + */ +export function continueCloudflareTrace(context: unknown): void { + if (hasSpansEnabled() || isContinuingTrace(getCurrentScope().getPropagationContext())) { + return; + } + + let spanContext: CloudflareSpanContext | undefined; + try { + const span = (context as { tracing?: CloudflareTracing } | undefined)?.tracing?.getActiveSpan?.(); + spanContext = span?.isTraced ? span.spanContext?.() : undefined; + } catch { + // Runtime getters on the execution context can throw on foreign or already-torn-down contexts. + return; + } + + if (!spanContext || !TRACE_ID_REGEXP.test(spanContext.traceId) || !SPAN_ID_REGEXP.test(spanContext.spanId)) { + return; + } + + // No `dsc` and no `sampled`: the SDK is the head of the Sentry trace, so it builds the dynamic + // sampling context itself. + getCurrentScope().setPropagationContext({ + traceId: spanContext.traceId, + parentSpanId: spanContext.spanId, + sampleRand: _INTERNAL_safeMathRandom(), + }); +} diff --git a/packages/cloudflare/src/wrapMethodWithSentry.ts b/packages/cloudflare/src/wrapMethodWithSentry.ts index fe1927833e7e..bb701c1530d8 100644 --- a/packages/cloudflare/src/wrapMethodWithSentry.ts +++ b/packages/cloudflare/src/wrapMethodWithSentry.ts @@ -16,6 +16,7 @@ import type { ExecutionContextCompat } from './executionContext'; import { flushAndDispose, getOriginalWaitUntil } from './flush'; import { ensureInstrumented } from './instrument'; import { init } from './sdk'; +import { continueCloudflareTrace } from './utils/cloudflareTrace'; import { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext'; import { withInvocationIsolationScope } from './utils/invocationScope'; import { extractRpcMeta } from './utils/rpcMeta'; @@ -183,6 +184,8 @@ export function wrapMethodWithSentry( } }; + continueCloudflareTrace(context); + if (!spanName) { try { if (callback) { @@ -272,10 +275,10 @@ export function wrapMethodWithSentry( if (rpcMeta) { return runWithTeardown(() => - continueTrace( - { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' }, - executeSpan, - ), + continueTrace({ sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' }, () => { + continueCloudflareTrace(context); + return executeSpan(); + }), ); } diff --git a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts index 76470db655f4..837cf36c5d99 100644 --- a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts +++ b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts @@ -14,6 +14,7 @@ import type { CloudflareClient, CloudflareOptions } from './client'; import type { ExecutionContextCompat } from './executionContext'; import { flushAndDispose, getOriginalWaitUntil } from './flush'; import { addCloudResourceContext, addCultureContext } from './scope-utils'; +import { continueCloudflareTrace } from './utils/cloudflareTrace'; import { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext'; import { withInvocationIsolationScope } from './utils/invocationScope'; @@ -128,6 +129,7 @@ export function wrapRequestHandlerWithInit( origin: 'auto.http.cloudflare', mechanism: captureErrors ? { handled: false, type: getRequestErrorMechanismType(context) } : undefined, attributes, + onTraceContinued: () => continueCloudflareTrace(context), isStreamingResponse: response => { const classification = safeCallback( DEBUG_BUILD ? 'Error in `isStreamingResponse`, using the default classification:' : '', diff --git a/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts index 875e03aab0db..dcef18a8800a 100644 --- a/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts +++ b/packages/cloudflare/test/instrumentations/instrumentWorkerEntrypoint.test.ts @@ -574,6 +574,101 @@ describe('instrumentWorkerEntrypoint', () => { expect(initAndBind).toHaveBeenCalledTimes(5); }); + + describe('with a Cloudflare trace', () => { + const CLOUDFLARE_TRACE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; + const CLOUDFLARE_SPAN_ID = 'b1c2d3e4f5a60718'; + const INCOMING_TRACE_ID = '12312012123120121231201212312012'; + const INCOMING_SPAN_ID = '1121201211212012'; + const CLOUDFLARE_TRACING = { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }; + + it('attaches errors of RPC calls without RPC metadata to the Cloudflare trace', async () => { + const events: Event[] = []; + const waits: Promise[] = []; + const context = { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext; + context.waitUntil = vi.fn(promise => { + waits.push(promise); + }); + const TestClass = class extends WorkerEntrypoint { + async fail(): Promise { + throw new Error('rpc failure'); + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint( + () => ({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + beforeSend(event) { + events.push(event); + return null; + }, + }), + TestClass as unknown as WorkerEntrypointConstructor, + ), + [context, {}], + ); + + await expect(obj.fail()).rejects.toThrow('rpc failure'); + await Promise.all(waits); + + expect(events).toHaveLength(1); + expect(events[0]?.contexts?.trace?.trace_id).toBe(CLOUDFLARE_TRACE_ID); + expect(events[0]?.contexts?.trace?.parent_span_id).toBe(CLOUDFLARE_SPAN_ID); + }); + + it('does not make the RPC span a child of the Cloudflare span when tracing is set up', () => { + let rpcSpan: ReturnType | undefined; + const TestClass = class extends WorkerEntrypoint { + read() { + rpcSpan = SentryCore.spanToJSON(SentryCore.getActiveSpan()!); + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint( + () => ({ dsn: 'https://public@o1.ingest.sentry.io/1337', tracesSampleRate: 1 }), + TestClass as unknown as WorkerEntrypointConstructor, + ), + [{ ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING }, {}], + ); + + obj.read({ + __sentry_rpc_meta__: { + 'sentry-trace': `${INCOMING_TRACE_ID}-${INCOMING_SPAN_ID}-1`, + baggage: `sentry-trace_id=${INCOMING_TRACE_ID},sentry-org_id=2`, + }, + }); + + expect(rpcSpan?.trace_id).not.toBe(CLOUDFLARE_TRACE_ID); + expect(rpcSpan?.trace_id).not.toBe(INCOMING_TRACE_ID); + expect(rpcSpan?.parent_span_id).toBeUndefined(); + }); + + it('prefers the Sentry trace of the RPC metadata', () => { + let rpcSpan: ReturnType | undefined; + const TestClass = class extends WorkerEntrypoint { + read() { + rpcSpan = SentryCore.spanToJSON(SentryCore.getActiveSpan()!); + } + }; + const obj = Reflect.construct( + instrumentWorkerEntrypoint( + () => ({ dsn: 'https://public@o1.ingest.sentry.io/1337', tracesSampleRate: 1 }), + TestClass as unknown as WorkerEntrypointConstructor, + ), + [{ ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING }, {}], + ); + + obj.read({ __sentry_rpc_meta__: { 'sentry-trace': `${INCOMING_TRACE_ID}-${INCOMING_SPAN_ID}-1` } }); + + expect(rpcSpan?.trace_id).toBe(INCOMING_TRACE_ID); + expect(rpcSpan?.parent_span_id).toBe(INCOMING_SPAN_ID); + }); + }); }); describe('env instrumentation', () => { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts index 2c15f5a39966..50fadfa56e8f 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentEmail.test.ts @@ -279,6 +279,52 @@ describe('instrumentEmail', () => { trace_id: expect.stringMatching(/[a-f0-9]{32}/), }); }); + + describe('with a Cloudflare trace', () => { + const context = { + ...createMockExecutionContext(), + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ + traceId: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', + spanId: 'b1c2d3e4f5a60718', + traceFlags: 1, + }), + }), + }, + } as unknown as ExecutionContext; + + test('continues the Cloudflare trace when tracing is not set up', async () => { + let propagationContext: ReturnType | undefined; + const handler = { + email(_arg, _env, _context) { + propagationContext = SentryCore.getCurrentScope().getPropagationContext(); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + await wrappedHandler.email?.(createMockEmailMessage(), MOCK_ENV, context); + + expect(propagationContext?.traceId).toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(propagationContext?.parentSpanId).toBe('b1c2d3e4f5a60718'); + }); + + test('does not make the email span a child of the Cloudflare span when tracing is set up', async () => { + let rootSpan: ReturnType | undefined; + const handler = { + email(_arg, _env, _context) { + rootSpan = SentryCore.spanToJSON(SentryCore.getRootSpan(SentryCore.getActiveSpan()!)); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN, tracesSampleRate: 1 }), handler); + await wrappedHandler.email?.(createMockEmailMessage(), MOCK_ENV, context); + + expect(rootSpan?.trace_id).not.toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(rootSpan?.parent_span_id).toBeUndefined(); + }); + }); }); test('flush must be called when all waitUntil are done', async () => { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts index d58d1e5ff4fa..dbfe1ae0e031 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentQueue.test.ts @@ -398,6 +398,52 @@ describe('instrumentQueue', () => { }, ]); }); + + describe('with a Cloudflare trace', () => { + const context = { + ...createMockExecutionContext(), + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ + traceId: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', + spanId: 'b1c2d3e4f5a60718', + traceFlags: 1, + }), + }), + }, + } as unknown as ExecutionContext; + + test('continues the Cloudflare trace when tracing is not set up', async () => { + let propagationContext: ReturnType | undefined; + const handler = { + queue(_arg, _env, _context) { + propagationContext = SentryCore.getCurrentScope().getPropagationContext(); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + await wrappedHandler.queue?.(createMockQueueBatch(), MOCK_ENV, context); + + expect(propagationContext?.traceId).toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(propagationContext?.parentSpanId).toBe('b1c2d3e4f5a60718'); + }); + + test('does not make the queue span a child of the Cloudflare span when tracing is set up', async () => { + let rootSpan: ReturnType | undefined; + const handler = { + queue(_arg, _env, _context) { + rootSpan = SentryCore.spanToJSON(SentryCore.getRootSpan(SentryCore.getActiveSpan()!)); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN, tracesSampleRate: 1 }), handler); + await wrappedHandler.queue?.(createMockQueueBatch(), MOCK_ENV, context); + + expect(rootSpan?.trace_id).not.toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(rootSpan?.parent_span_id).toBeUndefined(); + }); + }); }); test('flush must be called when all waitUntil are done', async () => { diff --git a/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts b/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts index 843683be8925..851d2fe11ac9 100644 --- a/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts +++ b/packages/cloudflare/test/instrumentations/worker/instrumentScheduled.test.ts @@ -305,6 +305,52 @@ describe('instrumentScheduled', () => { test('keeps the descriptive span name when span streaming is disabled', async () => { expect(await spanNameFor('static')).toBe('Scheduled Cron 0 0 0 * * *'); }); + + describe('with a Cloudflare trace', () => { + const context = { + ...createMockExecutionContext(), + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ + traceId: 'a1b2c3d4e5f60718293a4b5c6d7e8f90', + spanId: 'b1c2d3e4f5a60718', + traceFlags: 1, + }), + }), + }, + } as unknown as ExecutionContext; + + test('continues the Cloudflare trace when tracing is not set up', async () => { + let propagationContext: ReturnType | undefined; + const handler = { + scheduled(_arg, _env, _context) { + propagationContext = SentryCore.getCurrentScope().getPropagationContext(); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN }), handler); + await wrappedHandler.scheduled?.(createMockScheduledController(), MOCK_ENV, context); + + expect(propagationContext?.traceId).toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(propagationContext?.parentSpanId).toBe('b1c2d3e4f5a60718'); + }); + + test('does not make the scheduled span a child of the Cloudflare span when tracing is set up', async () => { + let rootSpan: ReturnType | undefined; + const handler = { + scheduled(_arg, _env, _context) { + rootSpan = SentryCore.spanToJSON(SentryCore.getRootSpan(SentryCore.getActiveSpan()!)); + }, + } satisfies ExportedHandler; + + const wrappedHandler = withSentry(env => ({ dsn: env.SENTRY_DSN, tracesSampleRate: 1 }), handler); + await wrappedHandler.scheduled?.(createMockScheduledController(), MOCK_ENV, context); + + expect(rootSpan?.trace_id).not.toBe('a1b2c3d4e5f60718293a4b5c6d7e8f90'); + expect(rootSpan?.parent_span_id).toBeUndefined(); + }); + }); }); describe('cron monitoring', () => { diff --git a/packages/cloudflare/test/request.test.ts b/packages/cloudflare/test/request.test.ts index f1ff999fe1ce..b20f2cab2f76 100644 --- a/packages/cloudflare/test/request.test.ts +++ b/packages/cloudflare/test/request.test.ts @@ -703,6 +703,159 @@ describe('withSentry', () => { links: undefined, }); }); + + describe('with a Cloudflare trace', () => { + const CLOUDFLARE_TRACE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; + const CLOUDFLARE_SPAN_ID = 'b1c2d3e4f5a60718'; + const CLOUDFLARE_TRACING = { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }; + + test('attaches errors to the Cloudflare trace when tracing is not set up', async () => { + let sentryEvent: Event = {}; + await wrapRequestHandler( + { + options: { + dsn: MOCK_OPTIONS.dsn, + cacheClient: false, + beforeSend(event) { + sentryEvent = event; + return null; + }, + }, + request: new Request('https://example.com'), + context: { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext, + }, + () => { + SentryCore.captureException(new Error('test')); + return new Response('test'); + }, + ); + + expect(sentryEvent.contexts?.trace?.trace_id).toBe(CLOUDFLARE_TRACE_ID); + expect(sentryEvent.contexts?.trace?.parent_span_id).toBe(CLOUDFLARE_SPAN_ID); + }); + + test.each([0, 1])('starts its own trace with tracesSampleRate %s', async rate => { + let sentryEvent: Event = {}; + await wrapRequestHandler( + { + options: { + dsn: MOCK_OPTIONS.dsn, + cacheClient: false, + tracesSampleRate: rate, + beforeSend(event) { + sentryEvent = event; + return null; + }, + }, + request: new Request('https://example.com'), + context: { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext, + }, + () => { + SentryCore.captureException(new Error('test')); + return new Response('test'); + }, + ); + + expect(sentryEvent.contexts?.trace?.trace_id).toMatch(/^[a-f0-9]{32}$/); + expect(sentryEvent.contexts?.trace?.trace_id).not.toBe(CLOUDFLARE_TRACE_ID); + expect(sentryEvent.contexts?.trace?.parent_span_id).toBeUndefined(); + }); + + test('does not make the request span a child of the Cloudflare span', async () => { + let rootSpan: ReturnType | undefined; + await wrapRequestHandler( + { + options: { dsn: MOCK_OPTIONS.dsn, cacheClient: false, tracesSampleRate: 1 }, + request: new Request('https://example.com'), + context: { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext, + }, + () => { + rootSpan = SentryCore.spanToJSON(SentryCore.getRootSpan(SentryCore.getActiveSpan()!)); + return new Response('test'); + }, + ); + + expect(rootSpan?.trace_id).not.toBe(CLOUDFLARE_TRACE_ID); + expect(rootSpan?.parent_span_id).toBeUndefined(); + }); + + test('prefers an incoming sentry-trace header', async () => { + const request = new Request('https://example.com'); + request.headers.set('sentry-trace', '12312012123120121231201212312012-1121201211212012'); + + let sentryEvent: Event = {}; + await wrapRequestHandler( + { + options: { + dsn: MOCK_OPTIONS.dsn, + cacheClient: false, + beforeSend(event) { + sentryEvent = event; + return null; + }, + }, + request, + context: { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext, + }, + () => { + SentryCore.captureException(new Error('test')); + return new Response('test'); + }, + ); + + expect(sentryEvent.contexts?.trace?.trace_id).toBe('12312012123120121231201212312012'); + }); + + test.each([ + { + reason: 'the org ids do not match', + headers: { + 'sentry-trace': '12312012123120121231201212312012-1121201211212012-1', + baggage: 'sentry-trace_id=12312012123120121231201212312012,sentry-org_id=2', + }, + options: {}, + }, + { + reason: 'strictTraceContinuation is set and the baggage has no org id', + headers: { 'sentry-trace': '12312012123120121231201212312012-1121201211212012-1' }, + options: { strictTraceContinuation: true }, + }, + { + reason: 'the sentry-trace header is malformed', + headers: { 'sentry-trace': 'not-a-sentry-trace' }, + options: {}, + }, + ])('uses the Cloudflare trace when $reason', async ({ headers, options }) => { + let sentryEvent: Event = {}; + await wrapRequestHandler( + { + options: { + dsn: 'https://public@o1.ingest.sentry.io/1337', + cacheClient: false, + ...options, + beforeSend(event) { + sentryEvent = event; + return null; + }, + }, + request: new Request('https://example.com', { headers }), + context: { ...createMockExecutionContext(), tracing: CLOUDFLARE_TRACING } as unknown as ExecutionContext, + }, + () => { + SentryCore.captureException(new Error('test')); + return new Response('test'); + }, + ); + + expect(sentryEvent.contexts?.trace?.trace_id).toBe(CLOUDFLARE_TRACE_ID); + expect(sentryEvent.contexts?.trace?.parent_span_id).toBe(CLOUDFLARE_SPAN_ID); + }); + }); }); describe('httpServerIntegration span options', () => { diff --git a/packages/cloudflare/test/utils/cloudflareTrace.test.ts b/packages/cloudflare/test/utils/cloudflareTrace.test.ts new file mode 100644 index 000000000000..21b1f38cc667 --- /dev/null +++ b/packages/cloudflare/test/utils/cloudflareTrace.test.ts @@ -0,0 +1,153 @@ +import type { Client } from '@sentry/core'; +import { getCurrentScope, withScope } from '@sentry/core'; +import { describe, expect, it } from 'vitest'; +import { continueCloudflareTrace } from '../../src/utils/cloudflareTrace'; + +const CLOUDFLARE_TRACE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; +const CLOUDFLARE_SPAN_ID = 'b1c2d3e4f5a60718'; + +describe('continueCloudflareTrace()', () => { + it('continues the trace of a traced Cloudflare span', () => { + const context = { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }, + }; + + withScope(() => { + continueCloudflareTrace(context); + + expect(getCurrentScope().getPropagationContext()).toEqual({ + traceId: CLOUDFLARE_TRACE_ID, + parentSpanId: CLOUDFLARE_SPAN_ID, + sampleRand: expect.any(Number), + }); + }); + }); + + it.each([ + ['tracesSampleRate', { tracesSampleRate: 1 }], + ['tracesSampleRate 0', { tracesSampleRate: 0 }], + ['tracesSampler', { tracesSampler: () => 1 }], + ])('keeps the propagation context when tracing is set up with %s', (_, options) => { + const context = { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }, + }; + + withScope(scope => { + scope.setClient({ getOptions: () => options } as unknown as Client); + const propagationContext = scope.getPropagationContext(); + + continueCloudflareTrace(context); + + expect(scope.getPropagationContext()).toBe(propagationContext); + }); + }); + + it('keeps the propagation context when the scope continues a trace', () => { + const context = { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }, + }; + + withScope(scope => { + scope.setPropagationContext({ + traceId: '12345678901234567890123456789012', + parentSpanId: '1234567890123456', + sampleRand: 0.5, + }); + const propagationContext = scope.getPropagationContext(); + + continueCloudflareTrace(context); + + expect(scope.getPropagationContext()).toBe(propagationContext); + }); + }); + + it.each([ + ['there is no execution context', undefined], + ['the runtime has no tracing API', {}], + ['the runtime has no getActiveSpan', { tracing: {} }], + ['there is no active span', { tracing: { getActiveSpan: () => undefined } }], + [ + 'the runtime has no spanContext', + { + tracing: { getActiveSpan: () => ({ isTraced: true }) }, + }, + ], + [ + 'Cloudflare does not trace the invocation', + { + tracing: { + getActiveSpan: () => ({ + isTraced: false, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: CLOUDFLARE_SPAN_ID, traceFlags: 0 }), + }), + }, + }, + ], + [ + 'the span context has null ids', + { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: '0'.repeat(32), spanId: '0'.repeat(16), traceFlags: 0 }), + }), + }, + }, + ], + [ + 'the span context has a malformed trace id', + { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: 'not-a-trace-id', spanId: CLOUDFLARE_SPAN_ID, traceFlags: 1 }), + }), + }, + }, + ], + [ + 'the span context has a malformed span id', + { + tracing: { + getActiveSpan: () => ({ + isTraced: true, + spanContext: () => ({ traceId: CLOUDFLARE_TRACE_ID, spanId: 'B1C2D3E4F5A60718', traceFlags: 1 }), + }), + }, + }, + ], + [ + 'reading the active span throws', + { + tracing: { + getActiveSpan: () => { + throw new Error('torn down'); + }, + }, + }, + ], + ])('keeps the propagation context when %s', (_, context) => { + withScope(scope => { + const propagationContext = scope.getPropagationContext(); + + continueCloudflareTrace(context); + + expect(scope.getPropagationContext()).toBe(propagationContext); + }); + }); +}); diff --git a/packages/server-utils/src/utils/wrapServerRequestHandler.ts b/packages/server-utils/src/utils/wrapServerRequestHandler.ts index fec8f40b7f78..4daac8988428 100644 --- a/packages/server-utils/src/utils/wrapServerRequestHandler.ts +++ b/packages/server-utils/src/utils/wrapServerRequestHandler.ts @@ -57,6 +57,11 @@ export interface ServerRequestHandlerConfig { routeName?: string; /** Span attributes that only the runtime knows, e.g. the route parameters. */ attributes?: SpanAttributes; + /** + * Called in the scope of the continued trace, before the span starts. Lets the runtime continue + * its own trace, e.g. the trace that Cloudflare exports for the invocation. + */ + onTraceContinued?: () => void; /** Whether the response streams. Return `undefined` to use the default classification. */ isStreamingResponse?: (response: Response) => boolean | undefined; /** @@ -174,6 +179,8 @@ export async function wrapServerRequestHandler { + config.onTraceContinued?.(); + if (!createSpan) { let response: R; try { From 2a0c6f33cb290d6539463a8b78a86c9d07d4acc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Peer=20St=C3=B6cklmair?= Date: Mon, 16 Nov 2026 11:29:01 +0100 Subject: [PATCH 096/136] test(cloudflare): Add e2e test for the Cloudflare trace id without tracing (#25643) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This adds the e2e app `cloudflare-workers-without-tracing-send-to-sentry`. It deploys a real Worker without Sentry tracing (no `tracesSampleRate`) and with Cloudflare traces on, and checks that an error in Sentry has the Cloudflare trace id and the Cloudflare request span as its parent. More tests without tracing can go into this app. ## Why The integration tests of #25613 run on a local workerd. This test checks the fix on Cloudflare, against the span that Workers Observability stores for the request. ## Sentry traces With #25613, the error is in the Cloudflare trace: https://sentry-sdks.sentry.io/explore/traces/trace/666e09b1979b18724b8fd77faed99e1b/?project=4510555608449024&statsPeriod=14d (captured with `tracesSampleRate: 0`, before #25613 limited the behavior to setups without tracing) Without #25613, the error has its own trace: https://sentry-sdks.sentry.io/explore/traces/trace/bc56b593dcf941c7b21af6216f215dff/?project=4510555608449024&statsPeriod=14d via **Jan Peer Stöcklmair**. -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CA6TD3QRK%3A1794409643.554379) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CA6TD3QRK%3A1794409643.554379/?project=4510944073809921) Co-authored-by: Claude Opus 5.5 --- .github/workflows/cleanup-e2e-workers.yml | 1 + dev-packages/e2e-tests/.env.example | 2 + dev-packages/e2e-tests/README.md | 3 + .../.gitignore | 5 ++ .../global-setup.ts | 3 + .../global-teardown.ts | 1 + .../package.json | 34 +++++++++++ .../playwright.config.ts | 13 +++++ .../pnpm-workspace.yaml | 4 ++ .../src/env.d.ts | 3 + .../src/index.ts | 16 ++++++ .../src/instrument.server.ts | 5 ++ .../tests/send-to-sentry.test.ts | 36 ++++++++++++ .../tsconfig.json | 16 ++++++ .../tsconfig.node.json | 7 +++ .../vite.config.ts | 7 +++ .../wrangler.jsonc | 11 ++++ dev-packages/test-utils/src/cli.ts | 1 + dev-packages/test-utils/src/cloudflare.ts | 56 +++++++++++++++++++ 19 files changed, 224 insertions(+) create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/.gitignore create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-setup.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-teardown.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/package.json create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/playwright.config.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/pnpm-workspace.yaml create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/env.d.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/index.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/instrument.server.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tests/send-to-sentry.test.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.json create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.node.json create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/vite.config.ts create mode 100644 dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/wrangler.jsonc diff --git a/.github/workflows/cleanup-e2e-workers.yml b/.github/workflows/cleanup-e2e-workers.yml index 69aae225e408..4b986b32805e 100644 --- a/.github/workflows/cleanup-e2e-workers.yml +++ b/.github/workflows/cleanup-e2e-workers.yml @@ -20,6 +20,7 @@ jobs: worker-prefix: - e2e-send-to-sentry - e2e-flue-send-to-sentry + - e2e-without-tracing-send-to-sentry steps: - name: Set up Node uses: actions/setup-node@v7 diff --git a/dev-packages/e2e-tests/.env.example b/dev-packages/e2e-tests/.env.example index 17326f227680..4417292a006c 100644 --- a/dev-packages/e2e-tests/.env.example +++ b/dev-packages/e2e-tests/.env.example @@ -23,5 +23,7 @@ E2E_OPENAI_DECISIONS_API_KEY= # Cloudflare credentials for E2E tests that deploy a real Worker (e.g. cloudflare-workers-send-to-sentry). # The API token needs "Workers Scripts: Edit" on the account; "Workers KV Storage: Read" additionally silences a # warning when a worker is deleted. Leave it empty to use a `wrangler login` session instead. +# Apps that read Workers Logs (e.g. cloudflare-workers-without-tracing-send-to-sentry) need an API token with +# "Workers Observability: Edit". CLOUDFLARE_API_TOKEN= CLOUDFLARE_ACCOUNT_ID= diff --git a/dev-packages/e2e-tests/README.md b/dev-packages/e2e-tests/README.md index 52e30cf48569..1f0e2b27180f 100644 --- a/dev-packages/e2e-tests/README.md +++ b/dev-packages/e2e-tests/README.md @@ -152,6 +152,9 @@ Apps like `cloudflare-workers-send-to-sentry` deploy the built app as a real Wor `cloudflare-flue-send-to-sentry/src/auth.ts`. - Add the `workerPrefix` to `.github/workflows/cleanup-e2e-workers.yml`, which deletes the Worker of a PR when the PR closes. +- To check what Cloudflare stored for a request (for example its Cloudflare trace id), read Workers Logs with + `fetchWorkersLogsEvents`. `CLOUDFLARE_API_TOKEN` then also needs "Workers Observability: Edit". See + `cloudflare-workers-without-tracing-send-to-sentry`. - Set `"sentryTest": { "optional": true }` in `package.json`, because only the optional CI job has the Cloudflare secrets. diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/.gitignore b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/.gitignore new file mode 100644 index 000000000000..b6c344e957e1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/.gitignore @@ -0,0 +1,5 @@ +dist +.wrangler +node_modules +test-results +pnpm-lock.yaml diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-setup.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-setup.ts new file mode 100644 index 000000000000..5a3e6215ca04 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-setup.ts @@ -0,0 +1,3 @@ +import { createWorkerGlobalSetup } from '@sentry-internal/test-utils/cloudflare'; + +export default createWorkerGlobalSetup({ workerPrefix: 'e2e-without-tracing-send-to-sentry' }); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-teardown.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-teardown.ts new file mode 100644 index 000000000000..c7bcfe696e66 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/global-teardown.ts @@ -0,0 +1 @@ +export { workerGlobalTeardown as default } from '@sentry-internal/test-utils/cloudflare'; diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/package.json b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/package.json new file mode 100644 index 000000000000..9dfe01fc5709 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/package.json @@ -0,0 +1,34 @@ +{ + "name": "cloudflare-workers-without-tracing-send-to-sentry", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "vite build", + "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.node.json", + "test": "playwright test", + "clean": "npx rimraf node_modules pnpm-lock.yaml dist .wrangler", + "test:build": "pnpm install && pnpm build", + "test:assert": "pnpm typecheck && pnpm test" + }, + "dependencies": { + "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz" + }, + "devDependencies": { + "@cloudflare/vite-plugin": "^1.47.0", + "@cloudflare/workers-types": "^5.20260727.1", + "@playwright/test": "1.64.1", + "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "@types/node": "^26.1.2", + "sentry": "~0.44.1", + "typescript": "~6.0.3", + "vite": "^8.1.5", + "wrangler": "^4.114.0" + }, + "volta": { + "extends": "../../package.json" + }, + "sentryTest": { + "optional": true + } +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/playwright.config.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/playwright.config.ts new file mode 100644 index 000000000000..9452ae9ac890 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/playwright.config.ts @@ -0,0 +1,13 @@ +import { getPlaywrightConfig } from '@sentry-internal/test-utils'; + +const config = getPlaywrightConfig(undefined, { + // The tests read what arrived in Sentry through the sentry CLI, so there is no event proxy to start. + webServer: undefined, + // The worker is deployed once for the whole run and deleted again afterwards. + globalSetup: './global-setup.ts', + globalTeardown: './global-teardown.ts', + // A test polls Workers Logs and then Sentry, each for up to 180s. + timeout: 400_000, +}); + +export default config; diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/pnpm-workspace.yaml new file mode 100644 index 000000000000..fd29a82085e0 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/pnpm-workspace.yaml @@ -0,0 +1,4 @@ +allowBuilds: + esbuild: true + workerd: true +minimumReleaseAge: 0 diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/env.d.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/env.d.ts new file mode 100644 index 000000000000..eb80bafb4834 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/env.d.ts @@ -0,0 +1,3 @@ +interface Env { + E2E_TEST_DSN: string; +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/index.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/index.ts new file mode 100644 index 000000000000..2f403c3d780f --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/index.ts @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/cloudflare'; + +export default { + async fetch(request) { + switch (new URL(request.url).pathname) { + case '/test-error': { + const eventId = Sentry.captureException(new Error('E2E test error in a Cloudflare trace')); + // Workers Logs store the `cf-ray` of the request with the invocation, so the test finds the Cloudflare trace + // with it. + return Response.json({ eventId, rayId: request.headers.get('cf-ray') }); + } + default: + return new Response('Hello World!'); + } + }, +} satisfies ExportedHandler; diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/instrument.server.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/instrument.server.ts new file mode 100644 index 000000000000..74b036c1283d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/src/instrument.server.ts @@ -0,0 +1,5 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +export default defineCloudflareOptions((env: Env) => ({ + dsn: env.E2E_TEST_DSN, +})); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tests/send-to-sentry.test.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tests/send-to-sentry.test.ts new file mode 100644 index 000000000000..ec0da7fc8ce3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tests/send-to-sentry.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from '@playwright/test'; +import { EVENT_POLLING_OPTIONS, fetchEvent, traceTarget } from '@sentry-internal/test-utils/cli'; +import type { ApiEvent } from '@sentry-internal/test-utils/cli'; +import { fetchFromWorker, fetchWorkersLogsEvents } from '@sentry-internal/test-utils/cloudflare'; +import type { WorkersLogsEvent } from '@sentry-internal/test-utils/cloudflare'; + +// Set by global-setup.ts once the worker for this run is deployed. +const workerUrl = process.env.E2E_TEST_WORKER_URL; + +test('Sends an error in the Cloudflare trace to Sentry', async () => { + const { eventId, rayId }: { eventId: string; rayId: string } = JSON.parse( + await fetchFromWorker(`${workerUrl}/test-error`, 200), + ); + + // The span of the request is the root span of the Cloudflare trace, and the only span with the `cf-ray` of the + // request. + let cloudflareSpans: WorkersLogsEvent[] = []; + await expect + .poll( + async () => + (cloudflareSpans = await fetchWorkersLogsEvents({ '$metadata.rayId': rayId, '$metadata.type': 'span' })), + EVENT_POLLING_OPTIONS, + ) + .toHaveLength(1); + const { traceId, spanId } = cloudflareSpans[0]!.$metadata; + expect(traceId).toEqual(expect.stringMatching(/^[\da-f]{32}$/)); + expect(spanId).toEqual(expect.stringMatching(/^[\da-f]{16}$/)); + + console.log(`Polling for error eventId ${eventId}: sentry trace view ${traceTarget(traceId!)}`); + + let event: ApiEvent | undefined; + await expect.poll(() => (event = fetchEvent(eventId)), EVENT_POLLING_OPTIONS).toBeDefined(); + + expect(event?.contexts?.trace?.trace_id).toBe(traceId); + expect(event?.contexts?.trace?.parent_span_id).toBe(spanId); +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.json b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.json new file mode 100644 index 000000000000..94b03468f288 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "es2022", + "moduleResolution": "bundler", + "types": ["@cloudflare/workers-types", "node"], + "skipLibCheck": true, + "noEmit": true, + "isolatedModules": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "strict": true + }, + "include": ["src/**/*", "vite.config.ts"] +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.node.json b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.node.json new file mode 100644 index 000000000000..c49bedb6b3e3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/tsconfig.node.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["tests/**/*", "global-setup.ts", "global-teardown.ts", "playwright.config.ts"] +} diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/vite.config.ts b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/vite.config.ts new file mode 100644 index 000000000000..005f4448f6cb --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/vite.config.ts @@ -0,0 +1,7 @@ +import { cloudflare } from '@cloudflare/vite-plugin'; +import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [cloudflare(), sentryCloudflareVitePlugin()], +}); diff --git a/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/wrangler.jsonc new file mode 100644 index 000000000000..ea985e5a54b7 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/cloudflare-workers-without-tracing-send-to-sentry/wrangler.jsonc @@ -0,0 +1,11 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + // Placeholder only: every test run deploys under a unique name, see global-setup.ts. + "name": "cloudflare-workers-without-tracing-send-to-sentry", + "main": "src/index.ts", + "compatibility_date": "2026-05-20", + "compatibility_flags": ["nodejs_compat"], + "workers_dev": true, + // The tests read the Cloudflare trace of each request from Workers Logs. + "observability": { "enabled": true, "traces": { "enabled": true } }, +} diff --git a/dev-packages/test-utils/src/cli.ts b/dev-packages/test-utils/src/cli.ts index 7e0d92dded70..212b83dba125 100644 --- a/dev-packages/test-utils/src/cli.ts +++ b/dev-packages/test-utils/src/cli.ts @@ -135,6 +135,7 @@ export interface ApiEvent { type: string; data: { values?: { type?: string; value?: string; mechanism?: { type?: string; handled?: boolean } }[] }; }[]; + contexts?: { trace?: { trace_id?: string; span_id?: string; parent_span_id?: string } }; } /** Fetch an error event of the E2E test project. Returns `undefined` while the event is not stored yet. */ diff --git a/dev-packages/test-utils/src/cloudflare.ts b/dev-packages/test-utils/src/cloudflare.ts index f50908f03dc4..7dfd0a3445ce 100644 --- a/dev-packages/test-utils/src/cloudflare.ts +++ b/dev-packages/test-utils/src/cloudflare.ts @@ -224,6 +224,62 @@ export function workerGlobalTeardown(config: FullConfig): void { } } +/** An event of Workers Logs: an invocation, a `console` call, or a span of the Cloudflare trace. */ +export interface WorkersLogsEvent { + $metadata: { + /** The `cf-ray` header of the request that the event belongs to. */ + rayId?: string; + /** `span` for a span of the Cloudflare trace, `cf-worker-event` for an invocation. */ + type?: string; + traceId?: string; + spanId?: string; + }; +} + +/** + * Returns the Workers Logs events of the last hour with the given values, for example + * `{ '$metadata.rayId': rayId }`. Returns an empty list while the events are not queryable yet. + * + * `CLOUDFLARE_API_TOKEN` needs the "Workers Observability: Edit" permission, which the query endpoint + * requires also for reads. A `wrangler login` session does not have it. + */ +export async function fetchWorkersLogsEvents(values: Record): Promise { + const now = Date.now(); + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/workers/observability/telemetry/query`, + { + method: 'POST', + headers: { Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + queryId: 'sentry-e2e-tests', + // Runs the query without saving it to the account. + dry: true, + view: 'events', + limit: 100, + timeframe: { from: now - 60 * 60 * 1000, to: now }, + parameters: { + filters: Object.entries(values).map(([key, value]) => ({ key, operation: 'eq', type: 'string', value })), + }, + }), + }, + ); + + if (response.status === 429) { + return []; + } + + const body = await response.text(); + + if (!response.ok) { + throw new Error( + `The Workers Logs query failed with status ${response.status}: ${body}. ` + + 'CLOUDFLARE_API_TOKEN needs the "Workers Observability: Edit" permission.', + ); + } + + return (JSON.parse(body) as { result: { events?: { events?: WorkersLogsEvent[] } } }).result.events?.events ?? []; +} + /** * Sends a request until the Worker itself answers it, and returns the body of that answer. * From de1f8e3da46d649a87cd23d01188273f80544821 Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Mon, 16 Nov 2026 11:37:52 +0100 Subject: [PATCH 097/136] perf(ci): Shard slow Nuxt and Next.js E2E variants (#26376) ## What Run Nuxt default/tracer-provider and Next.js webpack-development E2E variants on two shards (current bottleneck for full ci runs), with unchanged test coverage and one worker per job. ## Why Shorten slow E2E jobs. One run per setup; timings include setup and show the slowest shard: | Variant | [Unsharded](https://github.com/getsentry/sentry-javascript/actions/runs/43597234206) | [Two shards](https://github.com/getsentry/sentry-javascript/actions/runs/43604329193) | Saved | |---|---:|---:|---:| | Nuxt default | 4m03s | 3m40s | 23s | | Nuxt tracer provider | 3m58s | 3m35s | 23s | | Next.js webpack development | 3m31s | 2m25s | 66s | | Next.js latest webpack development | 3m39s | 2m22s | 77s | --------- Co-authored-by: OpenAI Codex --- .github/workflows/build.yml | 1 + .github/workflows/canary.yml | 1 + .github/workflows/optional-e2e.yml | 1 + dev-packages/e2e-tests/README.md | 4 +++ dev-packages/e2e-tests/lib/getTestMatrix.mjs | 31 ++++++++++++++----- .../test-applications/nextjs-16/package.json | 6 ++-- .../test-applications/nuxt-4/package.json | 5 ++- .../test-utils/src/playwright-config.ts | 4 +++ 8 files changed, 42 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 93faffc0ee3f..7c07cc019758 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1090,6 +1090,7 @@ jobs: E2E_TEST_SENTRY_PROJECT: 'sentry-javascript-e2e-tests' # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 8e29e056370e..f8ef50f4da66 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -85,6 +85,7 @@ jobs: E2E_TEST_SENTRY_PROJECT: 'sentry-javascript-e2e-tests' # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: diff --git a/.github/workflows/optional-e2e.yml b/.github/workflows/optional-e2e.yml index eea799a5a5f9..48c469acacb1 100644 --- a/.github/workflows/optional-e2e.yml +++ b/.github/workflows/optional-e2e.yml @@ -63,6 +63,7 @@ jobs: E2E_PR_NUMBER: ${{ inputs.pr_number }} # The `runtime` of a runtime variant, see dev-packages/e2e-tests/README.md RUNTIME: ${{ matrix.runtime }} + SENTRY_E2E_TEST_SHARD: ${{ matrix.test-shard }} # Without the root node_modules, `pnpm run` would first install the whole workspace. pnpm_config_verify_deps_before_run: 'false' strategy: diff --git a/dev-packages/e2e-tests/README.md b/dev-packages/e2e-tests/README.md index 1f0e2b27180f..49f3db499220 100644 --- a/dev-packages/e2e-tests/README.md +++ b/dev-packages/e2e-tests/README.md @@ -302,6 +302,10 @@ of a test application. set its `assert-command` to run production tests and add a development variant to run both environments in parallel. The local `test:assert` script can still run both; select the base variant locally with `--variant