diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.md index 4f0a55cbe326..29f9a82844ea 100644 --- a/.cursor/BUGBOT.md +++ b/.cursor/BUGBOT.md @@ -14,7 +14,6 @@ Keep reviews high-signal. Prefer actionable, high-confidence findings over specu ### Security Vulnerabilities - Exposed **real** secrets, API keys, tokens, or credentials in production code, comments, logs, or committed configs. Do **not** flag test fixtures, unit/integration/E2E helpers, or docs/examples that use obviously fake / placeholder DSNs and credentials (bogus DSNs in tests are expected). -- Unsafe use of `eval()`, `Function()`, or `innerHTML` - Unsafe regular expressions that could cause ReDoS attacks - `JSON.stringify` output that goes into generated code (bundler plugins, loaders, virtual modules, `define` values). Use `stringifyForCodeInjection` from `@sentry/core` instead. It escapes `<`, `>`, U+2028 and U+2029, so the code stays safe when inlined in a ` diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts deleted file mode 100644 index 35f7567b28cf..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/cloudflare/sentry.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineNitroPlugin } from '#imports'; -import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins'; - -export default defineNitroPlugin( - sentryCloudflareNitroPlugin({ - dsn: 'https://public@dsn.ingest.sentry.io/1337', - tracesSampleRate: 1.0, - enableLogs: true, - tunnel: 'http://localhost:3031/', // proxy server - // 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/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts index 267dbff7e478..e819ea167be6 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/nuxt.config.ts @@ -36,10 +36,10 @@ export default defineNuxtConfig({ }, nitro: { ...(cloudflare && { - preset: 'cloudflare_module', + // Like `cloudflare_module`, and also exports the `$DurableObject` class from the Worker. The Sentry module sets + // up the SDK from `sentry.cloudflare.config.ts`, because the Nitro preset does not use `sentry.server.config.ts`. + preset: 'cloudflare_durable', cloudflare: { nodeCompat: true, deployConfig: false }, - // Sets up the SDK on Cloudflare, where the Nitro preset does not use `sentry.server.config.ts`. - plugins: ['~~/cloudflare/sentry.ts'], // The bundled `mysql` driver pulls in `readable-stream`, whose base `require('stream')` has no // usable prototype under Nitro's unenv polyfill (throws `superCtor.prototype ... undefined`). // Alias it to workerd's native `node:stream`, which has a real `Readable`. 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 aa77c0425098..dd4d1000d40d 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/package.json @@ -36,7 +36,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "wrangler": "^4.72.0" }, diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt b/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt new file mode 100644 index 000000000000..445ab6da73d9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/public/humans.txt @@ -0,0 +1 @@ +Team: Sentry diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts new file mode 100644 index 000000000000..df5881da2623 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/sentry.cloudflare.config.ts @@ -0,0 +1,12 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +// On Cloudflare, the Sentry Nuxt module wraps the Worker with `withSentry` and these options. Node, Bun and Deno use +// `sentry.server.config.ts`. +export default defineCloudflareOptions({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, + enableLogs: true, + tunnel: 'http://localhost:3031/', // proxy server + // 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/server/api/durable-object/index.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/index.ts new file mode 100644 index 000000000000..9a1e123d07a1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/index.ts @@ -0,0 +1,10 @@ +import { defineEventHandler, getRequestURL } from '#imports'; + +// With the `cloudflare_durable` preset, `durableFetch` sends a request to the Durable Object of Nitro, which handles it +// with the same Nitro app. +export default defineEventHandler(async event => { + const { durableFetch } = event.context.cloudflare as { durableFetch: (request: Request) => Promise }; + const response = await durableFetch(new Request(new URL('/api/durable-object/target', getRequestURL(event)))); + + return response.json(); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts new file mode 100644 index 000000000000..f454c84cba34 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/server/api/durable-object/target.ts @@ -0,0 +1,5 @@ +import { defineEventHandler } from '#imports'; + +export default defineEventHandler(event => { + return { durable: !!(event.context.cloudflare as { durable?: unknown } | undefined)?.durable }; +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts index 6aeef1e31e88..698206fea06d 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/build-injection.test.ts @@ -57,7 +57,7 @@ test.describe('Orchestrion build-time injection', () => { }); }); -const NO_SERVER_CONFIG = 'Cloudflare: `sentryCloudflareNitroPlugin` sets up the SDK, not `sentry.server.config.ts`'; +const NO_SERVER_CONFIG = 'Cloudflare: `sentry.cloudflare.config.ts` sets up the SDK, not `sentry.server.config.ts`'; test.describe('Sentry server config injection', () => { test('evaluates Sentry.init before nitro runs its plugins', () => { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts index 644a371447c0..a1e9672587d7 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/cache.streaming-lifecycle.test.ts @@ -1,10 +1,8 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); test.describe('Cache Instrumentation', () => { const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key'; @@ -14,6 +12,7 @@ test.describe('Cache Instrumentation', () => { const spans = await collectStreamedSpansUntilSegment( 'nuxt-4', span => span.attributes['url.path']?.value === '/api/cache-test', + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', ); return spans.filter(span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt'); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts index 70fe76fb4c5c..2a59b09a22dc 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database-multi.streaming-lifecycle.test.ts @@ -1,15 +1,15 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; +import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); async function collectDbSpans() { const spans = await collectStreamedSpansUntilSegment( 'nuxt-4', span => span.attributes['url.path']?.value === '/api/db-multi-test', + span => getSpanOp(span) === 'db.query', ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-multi-test'); @@ -30,9 +30,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT default_table' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM default_table WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -49,9 +49,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT user_profiles' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM user_profiles WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -68,9 +68,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT events' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM events WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -90,23 +90,23 @@ test.describe('multiple database instances', () => { expect(sessionSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT sessions' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM sessions WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(accountSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT accounts' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM accounts WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(metricSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT metrics' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM metrics WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); // All spans belong to the same trace as the request's root span @@ -129,18 +129,18 @@ test.describe('multiple database instances', () => { expect(logsInsertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT logs' }, 'db.query.text': { type: 'string', value: 'INSERT INTO logs (message) VALUES (?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(auditLogsInsertSpan).toBeDefined(); expect(auditLogsInsertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT audit_logs' }, 'db.query.text': { type: 'string', value: 'INSERT INTO audit_logs (action) VALUES (?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts index 74ca13e02b93..7729f0e5251c 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/database.streaming-lifecycle.test.ts @@ -1,15 +1,22 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; +import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); + +// `@sentry/cloudflare` does not capture D1 errors, so the error hook of Nitro captures them on Cloudflare. The D1 +// error has a `cause`, so the event links the errors with an `exception_id`. +const DB_ERROR_MECHANISM = + RUNTIME === 'cloudflare' + ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 } + : { handled: false, type: 'auto.db.nuxt' }; async function collectDbSpans() { const spans = await collectStreamedSpansUntilSegment( 'nuxt-4', span => span.attributes['url.path']?.value === '/api/db-test', + span => getSpanOp(span) === 'db.query', ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test'); @@ -22,17 +29,20 @@ test.describe('database integration', () => { await request.get('/api/db-test?method=prepare-get'); - const dbSpan = (await dbSpansPromise).find(span => span.name === 'SELECT users'); + const dbSpans = await dbSpansPromise; + const dbSpan = dbSpans.find(span => span.name === 'SELECT users'); - expect(dbSpan).toBeDefined(); + // On Cloudflare, `@sentry/cloudflare` and the database instrumentation of `@sentry/nuxt` must not both create a + // span for the same D1 query. + expect(dbSpans.filter(span => span.name === 'SELECT users')).toHaveLength(1); expect(dbSpan?.status).toBe('ok'); expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT users' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), 'sentry.op': { type: 'string', value: 'db.query' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -47,8 +57,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT products' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM products WHERE price > ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -63,8 +73,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT orders' }, 'db.query.text': { type: 'string', value: 'INSERT INTO orders (customer, amount) VALUES (?, ?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -79,8 +89,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT items' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM items WHERE category = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -98,8 +108,8 @@ test.describe('database integration', () => { type: 'string', value: 'INSERT INTO messages (content, created_at) VALUES (?, ?)', }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -115,8 +125,8 @@ test.describe('database integration', () => { expect(insertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT logs' }, 'db.query.text': { type: 'string', value: `INSERT INTO logs (message, level) VALUES (?, ?)` }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); // DDL statements are summarized as `{operation} {table}` as well, with the statement on the attribute @@ -134,7 +144,7 @@ test.describe('database integration', () => { test('captures database error and marks span as failed', async ({ request }) => { const errorPromise = waitForError('nuxt-4', errorEvent => { return !!errorEvent?.exception?.values?.some( - value => value.mechanism?.type === 'auto.db.nuxt' && value.value?.includes('no such table'), + value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'), ); }); @@ -146,14 +156,11 @@ test.describe('database integration', () => { const [error, dbSpans] = await Promise.all([errorPromise, dbSpansPromise]); - const dbException = error.exception?.values?.find(value => value.mechanism?.type === 'auto.db.nuxt'); + const dbException = error.exception?.values?.find(value => value.mechanism?.type === DB_ERROR_MECHANISM.type); expect(dbException).toBeDefined(); expect(dbException?.value).toContain('no such table'); - expect(dbException?.mechanism).toEqual({ - handled: false, - type: 'auto.db.nuxt', - }); + expect(dbException?.mechanism).toEqual(DB_ERROR_MECHANISM); const dbSpan = dbSpans.find(span => span.name === 'SELECT nonexistent_table'); @@ -162,14 +169,16 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT nonexistent_table' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM nonexistent_table WHERE invalid_column = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); test('captures breadcrumb for db.exec() queries', async ({ request }) => { const errorPromise = waitForError('nuxt-4', errorEvent => { - return !!errorEvent?.exception?.values?.some(value => value.mechanism?.type === 'auto.db.nuxt'); + return !!errorEvent?.exception?.values?.some( + value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'), + ); }); await request.get('/api/db-test?method=error').catch(() => { @@ -184,7 +193,11 @@ test.describe('database integration', () => { expect(dbBreadcrumb).toBeDefined(); expect(dbBreadcrumb?.message).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`); - expect(dbBreadcrumb?.data?.['db.query.text']).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`); + expect(dbBreadcrumb?.data).toMatchObject( + RUNTIME === 'cloudflare' + ? { 'db.operation.name': 'exec' } + : { 'db.query.text': `INSERT INTO logs (message, level) VALUES (?, ?)` }, + ); }); test('multiple database operations in single request create multiple spans', async ({ request }) => { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts new file mode 100644 index 000000000000..72449a714ea9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/durable-object.streaming-lifecycle.test.ts @@ -0,0 +1,24 @@ +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { RUNTIME } from './runtime'; + +test.skip(RUNTIME !== 'cloudflare', 'Only the Cloudflare build has the Durable Object of Nitro'); + +test('traces the request that the Worker sends to the Durable Object of Nitro', async ({ request }) => { + const workerSpanPromise = waitForStreamedSpan( + 'nuxt-4', + span => span.is_segment === true && span.attributes['url.path']?.value === '/api/durable-object', + ); + const durableObjectSpanPromise = waitForStreamedSpan( + 'nuxt-4', + span => span.is_segment === true && span.attributes['url.path']?.value === '/api/durable-object/target', + ); + + const response = await request.get('/api/durable-object'); + expect(await response.json()).toEqual({ durable: true }); + + const [workerSpan, durableObjectSpan] = await Promise.all([workerSpanPromise, durableObjectSpanPromise]); + + expect(getSpanOp(durableObjectSpan)).toBe('http.server'); + expect(durableObjectSpan.trace_id).toBe(workerSpan.trace_id); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts index 195cc9b10567..d74f31e64e13 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/middleware.streaming-lifecycle.test.ts @@ -2,10 +2,8 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); // Nitro runs every file in `server/middleware/` on every request, so each surface tells its spans apart by // middleware name. `nuxt/server` has no object syntax (`onRequest`, `onBeforeResponse`) and no `eventHandler` @@ -31,7 +29,11 @@ const MIDDLEWARE = { } as const; async function collectRequestSpans(path = '/api/middleware-test') { - const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === path); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-4', + span => span.attributes['url.path']?.value === path, + span => getSpanOp(span) === 'middleware', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === path); return spans.filter(span => span.trace_id === rootSpan?.trace_id); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts index f3640262c4db..ceb8bafa41b7 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/runtime.ts @@ -10,10 +10,10 @@ export const MONGOOSE_UNSUPPORTED = 'Cloudflare: Nitro cannot bundle the `mongod export const SERVER_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.http.cloudflare' : 'auto.http.http_server'; -// The Cloudflare variant builds without `sentry.server.config.ts`, as the Cloudflare setup of `@sentry/nuxt` documents. -// The module adds the db0, storage, cache and middleware instrumentation only with that file. -export const NO_SERVER_CONFIG_INSTRUMENTATION = - 'Cloudflare: `@sentry/nuxt` instruments db0, storage, cache and middleware only with a `sentry.server.config.ts`'; +// On Cloudflare, the databases are D1 databases. `@sentry/cloudflare` creates the spans of their queries, and +// `@sentry/nuxt` leaves them out of its database instrumentation. +export const DB_SYSTEM_NAME = RUNTIME === 'cloudflare' ? 'cloudflare-d1' : 'sqlite'; +export const DB_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.db.cloudflare.d1' : 'auto.db.nuxt'; /** The command and arguments that start the built server on the runtime of the variant. */ export function getServerCommand(preload?: string): [string, string[]] { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts index b9eb33fc8f1d..94ff4270e4e4 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage-aliases.streaming-lifecycle.test.ts @@ -1,13 +1,15 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); async function collectStorageSpans(route: string) { - const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === route); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-4', + span => span.attributes['url.path']?.value === route, + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route); return spans.filter( diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts index a602f881c3cc..5f8ef9ccd540 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/storage.streaming-lifecycle.test.ts @@ -1,13 +1,15 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { NO_SERVER_CONFIG_INSTRUMENTATION, RUNTIME } from './runtime'; test.skip(isViteServer, NITRO_ONLY); -test.skip(RUNTIME === 'cloudflare', NO_SERVER_CONFIG_INSTRUMENTATION); async function collectStorageSpans(route: string) { - const spans = await collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes['url.path']?.value === route); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-4', + span => span.attributes['url.path']?.value === route, + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route); return spans.filter( diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts index 2563dd037d2c..cc0161fab24d 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.client.streaming-lifecycle.test.ts @@ -1,5 +1,12 @@ +import { URL_FULL } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpansUntilSegment, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { + collectStreamedSpansUntilSegment, + getSpanOp, + waitForStreamedSpan, + waitForStreamedSpans, +} from '@sentry-internal/test-utils'; +import { isViteServer } from './isViteServer'; test('sends a pageload root span with a parameterized URL', async ({ page }) => { const pageloadSpanPromise = waitForStreamedSpan('nuxt-4', span => { @@ -126,3 +133,27 @@ test('sends component tracking spans when `trackComponents` is enabled', async ( }), }); }); + +// Nuxt fetches its build manifest in the browser, for example to find prerendered pages. A span for it can prolong the pageload. +test('does not send a span for the build manifest request', async ({ page }) => { + test.skip(isViteServer, 'The Vite server builds no app manifest when it prerenders no routes'); + + const httpClientUrls: string[] = []; + const dataRequestSpanPromise = waitForStreamedSpans('nuxt-4', spans => { + httpClientUrls.push( + ...spans.filter(span => getSpanOp(span) === 'http.client').map(span => `${span.attributes[URL_FULL]?.value}`), + ); + return httpClientUrls.some(url => url.includes('/api/test-param/build-manifest')); + }); + const manifestResponsePromise = page.waitForResponse(response => response.url().includes('/_nuxt/builds/meta/')); + + await page.goto('/test-param/build-manifest'); + // Only fetches the manifest if Nuxt has not fetched it already. + await page.getByText('Fetch App Manifest').click(); + await manifestResponsePromise; + // A manifest span would arrive before the span of this later request. + await page.getByText('Fetch Server Data').click(); + await dataRequestSpanPromise; + + expect(httpClientUrls).not.toContainEqual(expect.stringContaining('/_nuxt/builds/')); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts index 96fedb422257..451ab2f1a4d9 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.static-lifecycle.test.ts @@ -1,4 +1,4 @@ -import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; import { waitForError, waitForTransaction } from '@sentry-internal/test-utils'; @@ -21,27 +21,30 @@ test('sends a server action transaction on pageload', async ({ page }) => { ); }); -test('does not send transactions for build asset folder "_nuxt"', async ({ page }) => { - let buildAssetFolderOccurred = false; - - waitForTransaction('nuxt-4', transactionEvent => { - if (transactionEvent.transaction?.match(/^GET \/_nuxt\//)) { - buildAssetFolderOccurred = true; - } - return false; // expects to return a boolean (but not relevant here) - }); - - const transactionEventPromise = waitForTransaction('nuxt-4', transactionEvent => { - return transactionEvent.transaction.includes('GET /test-param/'); +[ + // Nuxt build output that the HTTP integration does not ignore. + '/_nuxt/builds/latest.json', + '/_nuxt/entry.js.map', + // File from `public/` that the HTTP integration does not ignore. + '/humans.txt', + // Common static file that the HTTP integration ignores. + '/favicon.ico', +].forEach(path => { + test(`does not send a server transaction for the file ${path}`, async ({ baseURL }) => { + const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path); + + expect(transactionPaths).not.toContain(path); }); +}); - await page.goto('/test-param/1234'); - - const transactionEvent = await transactionEventPromise; - - expect(buildAssetFolderOccurred).toBe(false); +// Routes that look like build output. They also show that the helper sees sent transactions, so the tests above cannot +// pass by accident. +['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => { + test(`sends a server transaction for the route ${path}`, async ({ baseURL }) => { + const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path); - expect(transactionEvent.transaction).toBe('GET /test-param/:param()'); + expect(transactionPaths).toContain(path); + }); }); test('captures server API calls made with Nitro $fetch', async ({ page }) => { @@ -61,3 +64,22 @@ test('captures server API calls made with Nitro $fetch', async ({ page }) => { expect(httpClientSpan.parent_span_id).toEqual(httpServerFetchSpan.contexts.trace.span_id); expect(httpClientSpan.op).toEqual('http.client'); }); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server transaction up to the page's transaction, + * which arrives after any transaction for `path`. + */ +async function getServerTransactionPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`; + const transactionPaths: string[] = []; + const pageTransactionPromise = waitForTransaction('nuxt-4', transactionEvent => { + transactionPaths.push(`${transactionEvent.contexts?.trace?.data?.[URL_PATH]}`); + return transactionPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageTransactionPromise; + + return transactionPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts index 25d54633ebf7..5523bced86b5 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.server.streaming-lifecycle.test.ts @@ -1,5 +1,11 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { + collectStreamedSpans, + getSpanOp, + waitForStreamedSpan, + waitForStreamedSpans, +} from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; import { isViteServer, NITRO_ONLY } from './isViteServer'; import { SERVER_ORIGIN } from './runtime'; @@ -17,28 +23,30 @@ test('sends a server root span on pageload', async ({ page }) => { expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN); }); -test('does not send spans for build asset folder "_nuxt"', async ({ page }) => { - let buildAssetFolderOccurred = false; - - waitForStreamedSpan('nuxt-4', span => { - if (span.is_segment && /^GET \/_nuxt\//.test(span.name)) { - buildAssetFolderOccurred = true; - } - return false; // expects to return a boolean (but not relevant here) - }); - - const serverSpanPromise = waitForStreamedSpan('nuxt-4', span => { - return span.is_segment && span.name.includes('GET /test-param/'); +[ + // Nuxt build output that the HTTP integration does not ignore. + '/_nuxt/builds/latest.json', + '/_nuxt/entry.js.map', + // File from `public/` that the HTTP integration does not ignore. + '/humans.txt', + // Common static file that the HTTP integration ignores. + '/favicon.ico', +].forEach(path => { + test(`does not send a server span for the file ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).not.toContain(path); }); +}); - await page.goto('/test-param/1234'); - - const serverSpan = await serverSpanPromise; - - expect(buildAssetFolderOccurred).toBe(false); +// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot +// pass by accident. +['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => { + test(`sends a server span for the route ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); - expect(serverSpan.name).toBe('GET /test-param/:param()'); - expect(serverSpan.attributes['sentry.segment.name.source']?.value).toBe('route'); + expect(segmentPaths).toContain(path); + }); }); IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { @@ -76,3 +84,22 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { expect(httpClientSpan?.parent_span_id).toBe(serverSegmentSpan?.span_id); }); }); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives + * after any segment for `path`. + */ +async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`; + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('nuxt-4', spans => { + segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`)); + return segmentPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageSegmentPromise; + + return segmentPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts index 696f7752d3c9..ab4781e5950e 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/tests/tracing.streaming-lifecycle.test.ts @@ -3,11 +3,7 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; import { isViteServer, NITRO_ONLY } from './isViteServer'; -import { RUNTIME, SERVER_ORIGIN } from './runtime'; - -// `sentryCloudflareNitroPlugin` takes the trace data of the meta tags when the request starts, before the route -// names the segment. -const CLOUDFLARE_META_TAGS_BEFORE_ROUTE = 'Cloudflare meta tags are created before the route is known'; +import { SERVER_ORIGIN } from './runtime'; async function getBaggageMetaTagAndServerSpan(request: APIRequestContext, path: string) { const serverSpanPromise = waitForStreamedSpan('nuxt-4', span => { @@ -25,22 +21,12 @@ test.describe('distributed tracing', () => { const PARAM = 's0me-param'; test('puts the parametrized route in the baggage meta tag', async ({ request }) => { - test.skip(RUNTIME === 'cloudflare', CLOUDFLARE_META_TAGS_BEFORE_ROUTE); - const { baggageMetaTagContent, serverSpan } = await getBaggageMetaTagAndServerSpan(request, `/test-param/${PARAM}`); expect(baggageMetaTagContent).toContain(`sentry-trace_id=${serverSpan.trace_id}`); // URL-encoded for parametrized 'GET /test-param/s0me-param' -> `GET /test-param/:param` expect(baggageMetaTagContent).toContain(`sentry-transaction=GET%20%2Ftest-param%2F%3Aparam`); }); - test('leaves the transaction out of the baggage meta tag on Cloudflare', async ({ request }) => { - test.skip(RUNTIME !== 'cloudflare', CLOUDFLARE_META_TAGS_BEFORE_ROUTE); - - const { baggageMetaTagContent, serverSpan } = await getBaggageMetaTagAndServerSpan(request, `/test-param/${PARAM}`); - expect(baggageMetaTagContent).toContain(`sentry-trace_id=${serverSpan.trace_id}`); - expect(baggageMetaTagContent).not.toContain('sentry-transaction='); - }); - test('capture a distributed pageload trace', async ({ page }) => { const clientSpanPromise = waitForStreamedSpan('nuxt-4', span => { return ( diff --git a/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc index 35ba0deb951f..39972b0ef6ad 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc +++ b/dev-packages/e2e-tests/test-applications/nuxt-4/wrangler.jsonc @@ -20,4 +20,9 @@ "database_id": "00000000-0000-0000-0000-000000000003", }, ], + // The binding name and the class that the `cloudflare_durable` preset of Nitro use. + "durable_objects": { + "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }], + }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["$DurableObject"] }], } diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue deleted file mode 100644 index edd3b5d91e9a..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/app/app.vue +++ /dev/null @@ -1,13 +0,0 @@ - - - diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts deleted file mode 100644 index 107f439a3c53..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/nuxt.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -// https://nuxt.com/docs/api/configuration/nuxt-config -export default defineNuxtConfig({ - compatibilityDate: '2025-06-06', - modules: ['@sentry/nuxt/module'], - nitro: { - preset: 'cloudflare_module', - cloudflare: { - nodeCompat: true, - deployConfig: false, - }, - }, -}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json deleted file mode 100644 index b681f9ed4b51..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "nuxt-5-cloudflare", - "type": "module", - "private": true, - "scripts": { - "build": "nuxt build", - "dev": "nuxt dev", - "preview": "wrangler dev --var \"E2E_TEST_DSN:$E2E_TEST_DSN\" --port 3030 --log-level=$(test $CI && echo 'none' || echo 'log')", - "test": "playwright test", - "test:build": "pnpm install && pnpm build", - "test:assert": "pnpm test" - }, - "//": [ - "Nuxt v5 is only on the Nuxt nightlies, like the `nuxt-5` app.", - "`ofetch` is a dependency of `nuxt`, which Nuxt's virtual `fetch.server.mjs` can't resolve from the app, see `nuxt-5`." - ], - "dependencies": { - "@sentry/nuxt": "file:../../packed/sentry-nuxt-packed.tgz", - "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", - "nuxt": "npm:nuxt-nightly@5x", - "ofetch": "^2.0.0-alpha.3", - "vue": "^3.5.41" - }, - "devDependencies": { - "@playwright/test": "1.64.1", - "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "wrangler": "^4.72.0" - }, - "sentryTest": { - "optional": true - } -} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs deleted file mode 100644 index 4a688103e068..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/playwright.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -import { getPlaywrightConfig } from '@sentry-internal/test-utils'; - -const config = getPlaywrightConfig({ startCommand: 'pnpm preview', port: 3030 }); - -export default config; diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts deleted file mode 100644 index dbaf5fea80d5..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/anchor.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { defineHandler } from 'nitro'; - -// A plain route for tests to request. -export default defineHandler(() => 'ok'); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts deleted file mode 100644 index fd0ec635de08..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/api/internal.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { defineHandler } from 'nitro'; - -// Fetched internally while the page renders on the server. -export default defineHandler(() => 'internal'); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts deleted file mode 100644 index 36ce35d46765..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/server/plugins/sentry.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { definePlugin } from 'nitro'; -import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins'; - -export default definePlugin( - sentryCloudflareNitroPlugin({ - dsn: 'https://public@dsn.ingest.sentry.io/1337', - tracesSampleRate: 1.0, - tunnel: 'http://localhost:3031/', // proxy server - }), -); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts deleted file mode 100644 index f3eed2d6e10e..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tests/internal-fetch.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, test } from '@playwright/test'; -import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; -import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; - -function getUrlPath(span: SerializedStreamedSpan): string | undefined { - const attribute = span.attributes['url.path']; - - return attribute?.type === 'string' ? attribute.value : undefined; -} - -test('does not instrument the internal `$fetch` of a server-rendered page as its own request', async ({ request }) => { - // One listener, so it gets every span that the proxy received before the barrier span. - const spans: SerializedStreamedSpan[] = []; - const barrierPromise = waitForStreamedSpans('nuxt-5-cloudflare', batch => { - spans.push(...batch); - return batch.some(span => span.is_segment && getUrlPath(span) === '/api/anchor'); - }); - - await request.get('/'); - await request.get('/api/anchor'); - await barrierPromise; - - const serverSpanPaths = spans.filter(span => getSpanOp(span) === 'http.server').map(getUrlPath); - expect(serverSpanPaths).toContain('/'); - expect(serverSpanPaths).not.toContain('/api/internal'); - - const rootSpan = spans.find(span => span.is_segment && getUrlPath(span) === '/'); - expect(rootSpan?.attributes['sentry.sdk.name']).toEqual({ type: 'string', value: 'sentry.javascript.nuxt' }); -}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json deleted file mode 100644 index a746f2a70c28..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // https://nuxt.com/docs/guide/concepts/typescript - "extends": "./.nuxt/tsconfig.json" -} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc deleted file mode 100644 index da71d4978e33..000000000000 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-cloudflare/wrangler.jsonc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "nuxt-5-cloudflare", - "main": "./.output/server/index.mjs", - "compatibility_date": "2026-06-29", - "compatibility_flags": ["nodejs_compat"], - "assets": { - "directory": "./.output/public", - "binding": "ASSETS", - }, -} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts index 4dc1e34c400a..06aff0008baa 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/assert-build.ts @@ -16,6 +16,9 @@ import { /** This variant omits `sourcemaps.filesToDeleteAfterUpload`, so Sentry must upload but not delete. */ const keepClientSourceMaps = process.env.E2E_KEEP_CLIENT_SOURCEMAPS === 'true'; +/** This variant has no auth token, so Sentry uploads nothing but still removes the client maps it enabled. */ +const noUpload = process.env.E2E_NO_UPLOAD === 'true'; + /** `nuxt generate` emits no `.output/server`. Keyed on the command so a missing one under `nuxt build` still fails. */ const isStaticBuild = process.env.NUXT_COMMAND === 'generate'; @@ -59,121 +62,123 @@ function debugIdsOfChunksWithoutSourceMap(dir: string): Set { console.log( `Variant: ${isStaticBuild ? 'nuxt generate' : 'nuxt build'}, ` + - `client source maps ${keepClientSourceMaps ? 'kept' : 'deleted'}\n`, -); - -// Nuxt 5 writes the client build to `CLIENT_OUTPUT` directly. After Sentry deletes the client maps there, a chunk -// that never had a map looks the same as one whose map was deleted. So the client upload is checked only when the -// maps are kept. The upload is the same in all variants. -const outputDirsWithSourceMaps = [ - ...(keepClientSourceMaps ? [CLIENT_OUTPUT] : []), - ...(isStaticBuild ? [] : [SERVER_OUTPUT]), -]; -const debugIdsWithoutSourceMap = new Set( - outputDirsWithSourceMaps.flatMap(dir => [...debugIdsOfChunksWithoutSourceMap(dir)]), + `client source maps ${keepClientSourceMaps ? 'kept' : 'deleted'}${noUpload ? ', no upload' : ''}\n`, ); -const { requests, bundles, sourcemaps, uploadedDebugIds } = assertSourceMapUpload({ - outputDirs: outputDirsWithSourceMaps, - // The client output is checked below, because the "kept" variant expects its maps to stay. - strippedDirs: [], - // Vite builds the client and Nitro builds the server. Counting bundles would still pass with either - // plugin dropped, so each side is pinned to a marker only that side's source supplies. - // Nitro 3 deletes `sourcesContent` from the server maps unless `experimental.sourcemapMinify` is `false`. The module - // sets it to `false`, which is the only reason the server marker survives into `sourcesContent`. - markers: { 'client source (Vite plugin)': CLIENT_MARKER, 'server source (Rollup plugin)': SERVER_MARKER }, - debugIdsWithoutSourceMap: [...debugIdsWithoutSourceMap], -}); -console.log(`Found ${bundles.length} artifact bundle(s)\n`); - -// --- Nuxt-specific checks on the upload --- - -// Sentry rejects a release that names no project with a 400, and the mock server accepts anything, -// so assert on the body rather than on the call alone. -const releaseCreates = requests.filter(r => r.url?.includes('/releases') && r.method === 'POST'); -assert.ok(releaseCreates.length > 0, 'Expected a POST to create the release'); -for (const request of releaseCreates) { - const body = request.jsonBody as { version?: string; projects?: string[] } | undefined; - assert.equal( - body?.version, - 'test-release', - `Expected the release create body to carry the version, got ${JSON.stringify(body)}`, - ); - assert.deepEqual( - body?.projects, - ['test-project'], - `Expected the release create body to name the project, got ${JSON.stringify(body)}`, +if (!noUpload) { + // Nuxt 5 writes the client build to `CLIENT_OUTPUT` directly. After Sentry deletes the client maps there, a chunk + // that never had a map looks the same as one whose map was deleted. So the client upload is checked only when the + // maps are kept. The upload is the same in all variants. + const outputDirsWithSourceMaps = [ + ...(keepClientSourceMaps ? [CLIENT_OUTPUT] : []), + ...(isStaticBuild ? [] : [SERVER_OUTPUT]), + ]; + const debugIdsWithoutSourceMap = new Set( + outputDirsWithSourceMaps.flatMap(dir => [...debugIdsOfChunksWithoutSourceMap(dir)]), ); -} -assert.ok( - requests.some(r => r.url?.includes('/releases/') && r.method === 'PUT'), - 'Expected a PUT to finalize the release', -); + const { requests, bundles, sourcemaps, uploadedDebugIds } = assertSourceMapUpload({ + outputDirs: outputDirsWithSourceMaps, + // The client output is checked below, because the "kept" variant expects its maps to stay. + strippedDirs: [], + // Vite builds the client and Nitro builds the server. Counting bundles would still pass with either + // plugin dropped, so each side is pinned to a marker only that side's source supplies. + // Nitro 3 deletes `sourcesContent` from the server maps unless `experimental.sourcemapMinify` is `false`. The module + // sets it to `false`, which is the only reason the server marker survives into `sourcesContent`. + markers: { 'client source (Vite plugin)': CLIENT_MARKER, 'server source (Rollup plugin)': SERVER_MARKER }, + debugIdsWithoutSourceMap: [...debugIdsWithoutSourceMap], + }); + console.log(`Found ${bundles.length} artifact bundle(s)\n`); + + // --- Nuxt-specific checks on the upload --- + + // Sentry rejects a release that names no project with a 400, and the mock server accepts anything, + // so assert on the body rather than on the call alone. + const releaseCreates = requests.filter(r => r.url?.includes('/releases') && r.method === 'POST'); + assert.ok(releaseCreates.length > 0, 'Expected a POST to create the release'); + for (const request of releaseCreates) { + const body = request.jsonBody as { version?: string; projects?: string[] } | undefined; + assert.equal( + body?.version, + 'test-release', + `Expected the release create body to carry the version, got ${JSON.stringify(body)}`, + ); + assert.deepEqual( + body?.projects, + ['test-project'], + `Expected the release create body to name the project, got ${JSON.stringify(body)}`, + ); + } -assert.ok( - requests.some(r => r.url?.includes('/chunk-upload/') && r.method === 'GET'), - 'Expected a GET for the chunk-upload options', -); + assert.ok( + requests.some(r => r.url?.includes('/releases/') && r.method === 'PUT'), + 'Expected a PUT to finalize the release', + ); + + assert.ok( + requests.some(r => r.url?.includes('/chunk-upload/') && r.method === 'GET'), + 'Expected a GET for the chunk-upload options', + ); -for (const request of getAssembleRequests(requests)) { - assert.ok((request.assembleBody?.chunks?.length ?? 0) > 0, 'Expected assemble request to have chunk checksums'); - for (const chunk of request.assembleBody?.chunks ?? []) { - assert.match(chunk, /^[\da-f]{40}$/i, `Expected a SHA-1 chunk checksum, got: ${chunk}`); + for (const request of getAssembleRequests(requests)) { + assert.ok((request.assembleBody?.chunks?.length ?? 0) > 0, 'Expected assemble request to have chunk checksums'); + for (const chunk of request.assembleBody?.chunks ?? []) { + assert.match(chunk, /^[\da-f]{40}$/i, `Expected a SHA-1 chunk checksum, got: ${chunk}`); + } } -} -// `rewriteSources` normalizes `../../../foo` to `./foo` so paths stay resolvable in Sentry. -const unnormalizedSources = [...new Set(sourcemaps.flatMap(map => map.sourcemap.sources ?? []))].filter( - source => source.startsWith('../') || path.isAbsolute(source), -); -assert.deepEqual(unnormalizedSources, [], `Expected every uploaded source to be normalized to './…'`); + // `rewriteSources` normalizes `../../../foo` to `./foo` so paths stay resolvable in Sentry. + const unnormalizedSources = [...new Set(sourcemaps.flatMap(map => map.sourcemap.sources ?? []))].filter( + source => source.startsWith('../') || path.isAbsolute(source), + ); + assert.deepEqual(unnormalizedSources, [], `Expected every uploaded source to be normalized to './…'`); -const malformedDebugIds = [...uploadedDebugIds].filter(debugId => !UUID_REGEX.test(debugId)); -assert.deepEqual(malformedDebugIds, [], 'Expected every uploaded debug ID to be a UUID'); + const malformedDebugIds = [...uploadedDebugIds].filter(debugId => !UUID_REGEX.test(debugId)); + assert.deepEqual(malformedDebugIds, [], 'Expected every uploaded debug ID to be a UUID'); -// --- Every output directory ships at least one uploaded debug ID --- + // --- Every output directory ships at least one uploaded debug ID --- -// The shared assertions cover the directories that keep their maps. A directory whose maps are deleted -// must still ship a debug ID with an uploaded map, or a build that uploads nothing would pass. -for (const outputDir of isStaticBuild ? [CLIENT_OUTPUT] : [CLIENT_OUTPUT, SERVER_OUTPUT]) { - const injectedDebugIds = findInjectedDebugIds({ outputDir }); - assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); - assert.ok( - injectedDebugIds.some(debugId => uploadedDebugIds.has(debugId)), - `Expected at least one debug ID in ${outputDir} to have an uploaded sourcemap`, - ); + // The shared assertions cover the directories that keep their maps. A directory whose maps are deleted + // must still ship a debug ID with an uploaded map, or a build that uploads nothing would pass. + for (const outputDir of isStaticBuild ? [CLIENT_OUTPUT] : [CLIENT_OUTPUT, SERVER_OUTPUT]) { + const injectedDebugIds = findInjectedDebugIds({ outputDir }); + assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); + assert.ok( + injectedDebugIds.some(debugId => uploadedDebugIds.has(debugId)), + `Expected at least one debug ID in ${outputDir} to have an uploaded sourcemap`, + ); - console.log(` ${outputDir}: ${injectedDebugIds.length} injected debug ID(s)`); + console.log(` ${outputDir}: ${injectedDebugIds.length} injected debug ID(s)`); - // Nitro bundles the SSR build again, so its debug IDs can end up next to Nitro's own. - // Reference issue: https://github.com/getsentry/sentry-javascript/issues/18519 - const filesWithMultipleDebugIds = findFilesWithMultipleDebugIds({ outputDir }); - assert.deepEqual(filesWithMultipleDebugIds, [], `Expected at most one debug ID per file in ${outputDir}`); + // Nitro bundles the SSR build again, so its debug IDs can end up next to Nitro's own. + // Reference issue: https://github.com/getsentry/sentry-javascript/issues/18519 + const filesWithMultipleDebugIds = findFilesWithMultipleDebugIds({ outputDir }); + assert.deepEqual(filesWithMultipleDebugIds, [], `Expected at most one debug ID per file in ${outputDir}`); - // A server file can borrow the debug ID of its SSR build chunk. Then the upload check above passes on - // Vite's map even if Nitro uploaded nothing. - const filesWithForeignSourcemaps = findFilesWithForeignSourcemaps({ outputDir }, sourcemaps); - assert.deepEqual( - filesWithForeignSourcemaps, - [], - `Expected the source map uploaded for each file in ${outputDir} to be generated for that file`, - ); -} + // A server file can borrow the debug ID of its SSR build chunk. Then the upload check above passes on + // Vite's map even if Nitro uploaded nothing. + const filesWithForeignSourcemaps = findFilesWithForeignSourcemaps({ outputDir }, sourcemaps); + assert.deepEqual( + filesWithForeignSourcemaps, + [], + `Expected the source map uploaded for each file in ${outputDir} to be generated for that file`, + ); + } -// If both builds upload a map under a borrowed debug ID, Sentry can resolve with the wrong one. -const conflictingDebugIds = findDebugIdsWithConflictingSourcemaps(sourcemaps); -assert.deepEqual(conflictingDebugIds, [], 'Expected every uploaded debug ID to resolve to exactly one source map'); - -// TODO: Nitro 3 bundles the SSR build's output again, but its maps stop at that output -// (`.nuxt/vite/services/ssr/...`) and do not chain to the SSR build's own maps. So server frames do not reach -// `.vue` files. Assert this when the server maps reach the original sources: -// const serverDebugIds = new Set(findInjectedDebugIds({ outputDir: SERVER_OUTPUT })); -// const serverSources = sourcemaps -// .filter(map => map.debugId && serverDebugIds.has(map.debugId)) -// .flatMap(map => getSourcemapSources(map.sourcemap)); -// assert.ok(serverSources.some(source => source.endsWith('app/pages/index.vue'))); -console.log(''); + // If both builds upload a map under a borrowed debug ID, Sentry can resolve with the wrong one. + const conflictingDebugIds = findDebugIdsWithConflictingSourcemaps(sourcemaps); + assert.deepEqual(conflictingDebugIds, [], 'Expected every uploaded debug ID to resolve to exactly one source map'); + + // TODO: Nitro 3 bundles the SSR build's output again, but its maps stop at that output + // (`.nuxt/vite/services/ssr/...`) and do not chain to the SSR build's own maps. So server frames do not reach + // `.vue` files. Assert this when the server maps reach the original sources: + // const serverDebugIds = new Set(findInjectedDebugIds({ outputDir: SERVER_OUTPUT })); + // const serverSources = sourcemaps + // .filter(map => map.debugId && serverDebugIds.has(map.debugId)) + // .flatMap(map => getSourcemapSources(map.sourcemap)); + // assert.ok(serverSources.some(source => source.endsWith('app/pages/index.vue'))); + console.log(''); +} // --- What the build leaves behind in the client output --- diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts index f2f14911dde3..550dd0526694 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5-sourcemaps/nuxt.config.ts @@ -3,11 +3,17 @@ // own warning tells users to set, which makes it the setup worth regression-testing. const keepClientSourceMaps = process.env.E2E_KEEP_CLIENT_SOURCEMAPS === 'true'; +// Without an auth token nothing is uploaded, but Sentry still removes the client maps it enabled. +const noUpload = process.env.E2E_NO_UPLOAD === 'true'; + +// With `sourcemap.client` unset, Sentry enables the client maps, uploads them and removes them itself. +const sdkClientSourceMaps = process.env.E2E_SDK_CLIENT_SOURCEMAPS === 'true'; + export default defineNuxtConfig({ compatibilityDate: '2025-06-06', imports: { autoImport: false }, - sourcemap: { client: 'hidden' }, + sourcemap: { client: noUpload || sdkClientSourceMaps ? undefined : 'hidden' }, modules: ['@sentry/nuxt/module'], @@ -21,13 +27,16 @@ export default defineNuxtConfig({ sentry: { sentryUrl: 'http://localhost:3032', - authToken: 'fake-auth-token', + authToken: noUpload ? undefined : 'fake-auth-token', org: 'test-org', project: 'test-project', release: { name: 'test-release' }, // Dropping `filesToDeleteAfterUpload` is the whole point of the "kept" variant: Sentry should // upload the maps and leave the emitted files alone. - sourcemaps: keepClientSourceMaps ? {} : { filesToDeleteAfterUpload: ['.output/public/**/*.map'] }, + sourcemaps: + keepClientSourceMaps || noUpload || sdkClientSourceMaps + ? {} + : { filesToDeleteAfterUpload: ['.output/public/**/*.map'] }, debug: true, }, }); 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 af833ac3a1bf..0f49c72b9be1 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 @@ -10,6 +10,10 @@ "test:assert": "pnpm ts-node --script-mode assert-build.ts", "test:build:keep-client-sourcemaps": "E2E_KEEP_CLIENT_SOURCEMAPS=true pnpm test:build", "test:assert:keep-client-sourcemaps": "E2E_KEEP_CLIENT_SOURCEMAPS=true pnpm test:assert", + "test:build:no-upload": "E2E_NO_UPLOAD=true pnpm test:build", + "test:assert:no-upload": "E2E_NO_UPLOAD=true pnpm test:assert", + "test:build:sdk-client-sourcemaps": "E2E_SDK_CLIENT_SOURCEMAPS=true pnpm test:build", + "test:assert:sdk-client-sourcemaps": "pnpm test:assert", "test:build:static": "NUXT_COMMAND=generate pnpm test:build", "test:assert:static": "NUXT_COMMAND=generate pnpm test:assert" }, @@ -23,7 +27,7 @@ "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "@types/node": "^22.20.0", - "ts-node": "10.9.1", + "ts-node": "10.9.2", "typescript": "~5.0.0" }, "sentryTest": { @@ -34,6 +38,16 @@ "assert-command": "pnpm test:assert:keep-client-sourcemaps", "label": "nuxt-5-sourcemaps (client source maps kept)" }, + { + "build-command": "pnpm test:build:no-upload", + "assert-command": "pnpm test:assert:no-upload", + "label": "nuxt-5-sourcemaps (no upload)" + }, + { + "build-command": "pnpm test:build:sdk-client-sourcemaps", + "assert-command": "pnpm test:assert:sdk-client-sourcemaps", + "label": "nuxt-5-sourcemaps (client source maps enabled by Sentry)" + }, { "build-command": "pnpm test:build:static", "assert-command": "pnpm test:assert:static", diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue new file mode 100644 index 000000000000..23d21e84878d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/components/SSRErrorComponent.vue @@ -0,0 +1,9 @@ + + + diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/internal-fetch.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/internal-fetch.vue new file mode 100644 index 000000000000..b7ea529037a8 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/internal-fetch.vue @@ -0,0 +1,11 @@ + + + diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error-boundary.vue b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error-boundary.vue new file mode 100644 index 000000000000..4134ac65c0d9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/app/pages/ssr-error-boundary.vue @@ -0,0 +1,14 @@ + + + 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 f81873ea0b21..37c91d4425e5 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 @@ -1,4 +1,15 @@ // https://nuxt.com/docs/api/configuration/nuxt-config +// The runtime variants set `RUNTIME` for the build, see dev-packages/e2e-tests/README.md. +const runtime = process.env.RUNTIME || 'node'; +const cloudflare = runtime === 'cloudflare'; + +// `node:sqlite` is not available on Bun, which has its own SQLite module, and on Cloudflare, which has D1. +function database(name: string, binding: string) { + if (cloudflare) { + return { connector: 'cloudflare-d1', options: { bindingName: binding } } as const; + } + return { connector: runtime === 'bun' ? 'bun-sqlite' : 'sqlite', options: { name } } as const; +} export default defineNuxtConfig({ compatibilityDate: '2025-07-15', @@ -22,23 +33,23 @@ export default defineNuxtConfig({ }, }, nitro: { + ...(cloudflare && { + // The Sentry module sets up the SDK from `sentry.cloudflare.config.ts`, because the Nitro preset does not use + // `sentry.server.config.ts`. + preset: 'cloudflare_module', + cloudflare: { nodeCompat: true, deployConfig: false }, + }), + // Files for one runtime replace their counterpart in the copy of the app for that runtime, see + // dev-packages/e2e-tests/README.md, and are no routes of their own. + ignore: ['**/*.cloudflare.ts'], ...(process.env.E2E_TEST_CACHE_DRIVER && { cache: { driver: process.env.E2E_TEST_CACHE_DRIVER } }), experimental: { database: true, }, database: { - default: { - connector: 'sqlite', - options: { name: 'db' }, - }, - users: { - connector: 'sqlite', - options: { name: 'users_db' }, - }, - analytics: { - connector: 'sqlite', - options: { name: 'analytics_db' }, - }, + default: database('db', 'DB'), + users: database('users_db', 'USERS_DB'), + analytics: database('analytics_db', 'ANALYTICS_DB'), }, storage: { 'test-storage': { 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 aa4f306f2cf8..f6a43458c82f 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/package.json +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/package.json @@ -8,6 +8,9 @@ "generate": "nuxt generate", "preview": "nuxt preview", "start": "node .output/server/index.mjs", + "start:bun": "bun .output/server/index.mjs", + "start:deno": "deno run -A .output/server/index.mjs", + "start:cloudflare": "wrangler dev --port 3030", "start:import": "node --import ./.output/server/sentry.server.config.mjs .output/server/index.mjs", "clean": "npx nuxi cleanup", "test": "playwright test", @@ -17,7 +20,9 @@ "test:build-canary": "pnpm add nuxt@npm:nuxt-nightly@latest && pnpm add nitro@npm:nitro-nightly@latest && pnpm install --force && pnpm build", "test:assert": "pnpm test:prod && pnpm test:dev", "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" + "test:assert:kv-cache": "E2E_TEST_CACHE_DRIVER=kv TEST_ENV=production playwright test cache", + "test:build:bun": "pnpm install && bun --bun nuxt build", + "test:build:cloudflare": "rm sentry.server.config.ts && pnpm test:build" }, "//": [ "Currently, we need to install the Nuxt nightlies as those contain Nuxt v5", @@ -27,6 +32,9 @@ ], "dependencies": { "@pinia/nuxt": "^0.11.3", + "@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/nuxt": "file:../../packed/sentry-nuxt-packed.tgz", "db0": "^0.4.2", "mongoose": "^9.10.2", @@ -37,8 +45,9 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.35.0", - "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz" + "@sentry/conventions": "0.36.0", + "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", + "wrangler": "^4.72.0" }, "sentryTest": { "optional": true, @@ -55,6 +64,24 @@ "build-command": "pnpm test:build:kv-cache", "assert-command": "pnpm test:assert:kv-cache", "label": "nuxt-5 (kv-cache)" + }, + { + "runtime": "bun", + "build-command": "pnpm test:build:bun", + "assert-command": "pnpm test:prod", + "label": "nuxt-5 (bun)" + }, + { + "runtime": "deno", + "deno-version": "v2.9.0", + "assert-command": "pnpm test:prod", + "label": "nuxt-5 (deno)" + }, + { + "runtime": "cloudflare", + "build-command": "pnpm test:build:cloudflare", + "assert-command": "pnpm test:prod", + "label": "nuxt-5 (cloudflare)" } ] } diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts index e539cfa89cd3..c02b05ea3fc1 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/playwright.config.ts @@ -1,4 +1,4 @@ -import { getPlaywrightConfig } from '@sentry-internal/test-utils'; +import { getPlaywrightConfig, getRuntime } from '@sentry-internal/test-utils'; const testEnv = process.env.TEST_ENV; @@ -6,6 +6,14 @@ if (!testEnv) { throw new Error('No test env defined'); } +// The server config is bundled into the Nitro output, so every runtime starts the server entry without a preload. +const productionStartCommands = { + node: 'pnpm start', + bun: 'pnpm start:bun', + deno: 'pnpm start:deno', + cloudflare: 'pnpm start:cloudflare', +}; + const getStartCommand = () => { if (testEnv === 'development') { // The Sentry server config is bundled into the dev server via a nitro plugin, so no preload is needed. @@ -13,7 +21,7 @@ const getStartCommand = () => { } if (testEnv === 'production') { - return 'pnpm start'; + return productionStartCommands[getRuntime()]; } throw new Error(`Unknown test env: ${testEnv}`); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml b/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml index 4210a62a804d..2e21551db362 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/pnpm-workspace.yaml @@ -1,3 +1,5 @@ allowBuilds: '@sentry/cli': true + esbuild: true + workerd: true minimumReleaseAge: 0 diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt b/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt new file mode 100644 index 000000000000..445ab6da73d9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/public/humans.txt @@ -0,0 +1 @@ +Team: Sentry diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts new file mode 100644 index 000000000000..c77b6dc33a99 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.cloudflare.config.ts @@ -0,0 +1,11 @@ +import { defineCloudflareOptions } from '@sentry/cloudflare'; + +// On Cloudflare, the Sentry Nuxt module wraps the Worker with `withSentry` and these options. Node, Bun and Deno use +// `sentry.server.config.ts`. +export default defineCloudflareOptions({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, + tunnel: 'http://localhost:3031/', // proxy server + // 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-5/sentry.server.config.bun.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.bun.ts new file mode 100644 index 000000000000..eadb5d6e4647 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.bun.ts @@ -0,0 +1,16 @@ +import { bunServerIntegration, fetchIntegration } from '@sentry/bun'; +import * as Sentry from '@sentry/nuxt'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, // Capture 100% of the transactions + tunnel: 'http://localhost:3031/', // proxy server + // Several tests trigger the same server error one after another, which Dedupe would drop. + integrations: integrations => [ + ...integrations.filter(integration => integration.name !== 'Dedupe'), + // On Bun, Nitro 3 builds with its `bun` preset, which serves with `Bun.serve`. Bun emits none of the undici channels + // the Node SDK listens to, so these add the incoming request and outgoing `fetch` instrumentation. + bunServerIntegration(), + fetchIntegration(), + ], +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts new file mode 100644 index 000000000000..a0647a774c99 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/sentry.server.config.deno.ts @@ -0,0 +1,14 @@ +import { fetchIntegration } from '@sentry/deno'; +import * as Sentry from '@sentry/nuxt'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1.0, // Capture 100% of the transactions + tunnel: 'http://localhost:3031/', // proxy server + // Several tests trigger the same server error one after another, which Dedupe would drop. + integrations: integrations => [ + ...integrations.filter(integration => integration.name !== 'Dedupe'), + // The `fetch` of Deno is not undici, so the Node SDK does not see outgoing requests. + fetchIntegration(), + ], +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts new file mode 100644 index 000000000000..bba737796b18 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-mongoose.cloudflare.ts @@ -0,0 +1,7 @@ +import { defineHandler } from 'nitro'; +import { HTTPError } from 'nitro/h3'; + +// Replaces `db-mongoose.ts` on Cloudflare, see `MONGOOSE_UNSUPPORTED` in `tests/runtime.ts`. +export default defineHandler(() => { + throw new HTTPError({ status: 501 }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts index e814c930311b..9bd704b2349f 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/server/api/db-test.ts @@ -18,10 +18,10 @@ export default defineHandler(async event => { case 'prepare-all': { await db.exec('CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL)'); - await db.exec(`INSERT OR REPLACE INTO products (id, name, price) VALUES - (1, 'Product A', 10.99), - (2, 'Product B', 20.50), - (3, 'Product C', 15.25)`); + // One line, because D1 runs every line of `exec` as a statement of its own. + await db.exec( + `INSERT OR REPLACE INTO products (id, name, price) VALUES (1, 'Product A', 10.99), (2, 'Product B', 20.50), (3, 'Product C', 15.25)`, + ); const stmt = db.prepare('SELECT * FROM products WHERE price > ?'); const results = await stmt.all(10); return { success: true, count: results.length, results }; @@ -36,10 +36,9 @@ export default defineHandler(async event => { case 'prepare-bind': { await db.exec('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, category TEXT, value INTEGER)'); - await db.exec(`INSERT OR REPLACE INTO items (id, category, value) VALUES - (1, 'electronics', 100), - (2, 'books', 50), - (3, 'electronics', 200)`); + await db.exec( + `INSERT OR REPLACE INTO items (id, category, value) VALUES (1, 'electronics', 100), (2, 'books', 50), (3, 'electronics', 200)`, + ); const stmt = db.prepare('SELECT * FROM items WHERE category = ?'); const boundStmt = stmt.bind('electronics'); const results = await boundStmt.all(); 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 1cd62dbae4da..e5163a76f359 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 @@ -18,6 +18,7 @@ test.describe('Cache Instrumentation', () => { const spans = await collectStreamedSpansUntilSegment( 'nuxt-5', span => span.attributes['url.path']?.value === '/api/cache-test', + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/cache-test'); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts index 62e233af87d6..98d9a8ccde2a 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database-multi.test.ts @@ -1,10 +1,12 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils'; +import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime'; async function collectDbSpans() { const spans = await collectStreamedSpansUntilSegment( 'nuxt-5', span => span.attributes['url.path']?.value === '/api/db-multi-test', + span => getSpanOp(span) === 'db.query', ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-multi-test'); @@ -25,9 +27,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT default_table' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM default_table WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -44,9 +46,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT user_profiles' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM user_profiles WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -63,9 +65,9 @@ test.describe('multiple database instances', () => { expect(selectSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT events' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM events WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -85,23 +87,23 @@ test.describe('multiple database instances', () => { expect(sessionSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT sessions' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM sessions WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(accountSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT accounts' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM accounts WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(metricSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT metrics' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM metrics WHERE id = ?' }, - 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'analytics_db.sqlite' } }), + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); // All spans belong to the same trace as the request's root span @@ -124,18 +126,18 @@ test.describe('multiple database instances', () => { expect(logsInsertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT logs' }, 'db.query.text': { type: 'string', value: 'INSERT INTO logs (message) VALUES (?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); expect(auditLogsInsertSpan).toBeDefined(); expect(auditLogsInsertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT audit_logs' }, 'db.query.text': { type: 'string', value: 'INSERT INTO audit_logs (action) VALUES (?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'users_db.sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'users_db.sqlite' } }), + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts index de55b7ce8df4..184eac58bb50 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/database.test.ts @@ -1,10 +1,19 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; +import { DB_ORIGIN, DB_SYSTEM_NAME, RUNTIME } from './runtime'; + +// `@sentry/cloudflare` does not capture D1 errors, so the error hook of Nitro captures them on Cloudflare. The D1 +// error has a `cause`, so the event links the errors with an `exception_id`. +const DB_ERROR_MECHANISM = + RUNTIME === 'cloudflare' + ? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 } + : { handled: false, type: 'auto.db.nuxt' }; async function collectDbSpans() { const spans = await collectStreamedSpansUntilSegment( 'nuxt-5', span => span.attributes['url.path']?.value === '/api/db-test', + span => getSpanOp(span) === 'db.query', ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test'); @@ -17,17 +26,20 @@ test.describe('database integration', () => { await request.get('/api/db-test?method=prepare-get'); - const dbSpan = (await dbSpansPromise).find(span => span.name === 'SELECT users'); + const dbSpans = await dbSpansPromise; + const dbSpan = dbSpans.find(span => span.name === 'SELECT users'); - expect(dbSpan).toBeDefined(); + // On Cloudflare, `@sentry/cloudflare` and the database instrumentation of `@sentry/nuxt` must not both create a + // span for the same D1 query. + expect(dbSpans.filter(span => span.name === 'SELECT users')).toHaveLength(1); expect(dbSpan?.status).toBe('ok'); expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT users' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM users WHERE id = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'db.namespace': { type: 'string', value: 'db.sqlite' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + ...(RUNTIME !== 'cloudflare' && { 'db.namespace': { type: 'string', value: 'db.sqlite' } }), 'sentry.op': { type: 'string', value: 'db.query' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -42,8 +54,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT products' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM products WHERE price > ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -58,8 +70,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT orders' }, 'db.query.text': { type: 'string', value: 'INSERT INTO orders (customer, amount) VALUES (?, ?)' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -74,8 +86,8 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT items' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM items WHERE category = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -93,8 +105,8 @@ test.describe('database integration', () => { type: 'string', value: 'INSERT INTO messages (content, created_at) VALUES (?, ?)', }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); @@ -110,8 +122,8 @@ test.describe('database integration', () => { expect(insertSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'INSERT logs' }, 'db.query.text': { type: 'string', value: `INSERT INTO logs (message, level) VALUES (?, ?)` }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); // DDL statements are summarized as `{operation} {table}` as well, with the statement on the attribute @@ -129,7 +141,7 @@ test.describe('database integration', () => { test('captures database error and marks span as failed', async ({ request }) => { const errorPromise = waitForError('nuxt-5', errorEvent => { return !!errorEvent?.exception?.values?.some( - value => value.mechanism?.type === 'auto.db.nuxt' && value.value?.includes('no such table'), + value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'), ); }); @@ -141,14 +153,11 @@ test.describe('database integration', () => { const [error, dbSpans] = await Promise.all([errorPromise, dbSpansPromise]); - const dbException = error.exception?.values?.find(value => value.mechanism?.type === 'auto.db.nuxt'); + const dbException = error.exception?.values?.find(value => value.mechanism?.type === DB_ERROR_MECHANISM.type); expect(dbException).toBeDefined(); expect(dbException?.value).toContain('no such table'); - expect(dbException?.mechanism).toEqual({ - handled: false, - type: 'auto.db.nuxt', - }); + expect(dbException?.mechanism).toEqual(DB_ERROR_MECHANISM); const dbSpan = dbSpans.find(span => span.name === 'SELECT nonexistent_table'); @@ -157,14 +166,16 @@ test.describe('database integration', () => { expect(dbSpan?.attributes).toMatchObject({ 'db.query.summary': { type: 'string', value: 'SELECT nonexistent_table' }, 'db.query.text': { type: 'string', value: 'SELECT * FROM nonexistent_table WHERE invalid_column = ?' }, - 'db.system.name': { type: 'string', value: 'sqlite' }, - 'sentry.origin': { type: 'string', value: 'auto.db.nuxt' }, + 'db.system.name': { type: 'string', value: DB_SYSTEM_NAME }, + 'sentry.origin': { type: 'string', value: DB_ORIGIN }, }); }); test('captures breadcrumb for db.exec() queries', async ({ request }) => { const errorPromise = waitForError('nuxt-5', errorEvent => { - return !!errorEvent?.exception?.values?.some(value => value.mechanism?.type === 'auto.db.nuxt'); + return !!errorEvent?.exception?.values?.some( + value => value.mechanism?.type === DB_ERROR_MECHANISM.type && value.value?.includes('no such table'), + ); }); await request.get('/api/db-test?method=error').catch(() => { @@ -179,7 +190,11 @@ test.describe('database integration', () => { expect(dbBreadcrumb).toBeDefined(); expect(dbBreadcrumb?.message).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`); - expect(dbBreadcrumb?.data?.['db.query.text']).toBe(`INSERT INTO logs (message, level) VALUES (?, ?)`); + expect(dbBreadcrumb?.data).toMatchObject( + RUNTIME === 'cloudflare' + ? { 'db.operation.name': 'exec' } + : { 'db.query.text': `INSERT INTO logs (message, level) VALUES (?, ?)` }, + ); }); test('multiple database operations in single request create multiple spans', async ({ request }) => { diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts index 5d3ba010670f..856be6be6c0f 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/db-mongoose.test.ts @@ -1,5 +1,8 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; +import { MONGOOSE_UNSUPPORTED, RUNTIME } from './runtime'; + +test.skip(RUNTIME === 'cloudflare', MONGOOSE_UNSUPPORTED); // The Nitro bundle force-inlines the instrumented drivers while their CommonJS dependencies and // Node builtins stay external, and every `require()` across that boundary needs working interop diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts index 2dcc253a98d1..e24e004a1ad9 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/errors.server.test.ts @@ -1,6 +1,7 @@ import { expect, test } from '@playwright/test'; import { waitForError } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; +import { RUNTIME } from './runtime'; import { waitForHydration } from './waitForHydration'; IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { @@ -114,3 +115,30 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { }); }); }); + +test.describe('SSR error boundary', () => { + test('captures error thrown in NuxtErrorBoundary during SSR with 200 response', async ({ page }) => { + const errorPromise = waitForError('nuxt-5', async errorEvent => { + return errorEvent?.exception?.values?.[0]?.value === 'SSR Error inside NuxtErrorBoundary'; + }); + + const response = await page.goto('/ssr-error-boundary'); + expect(response?.status()).toBe(200); + + const error = await errorPromise; + + if (RUNTIME !== 'bun') { + expect(error.transaction).toEqual('GET /ssr-error-boundary'); + } + expect(error.exception.values[0]).toMatchObject({ + type: 'Error', + value: 'SSR Error inside NuxtErrorBoundary', + mechanism: { + handled: false, + type: 'auto.function.nuxt.vue-error', + }, + }); + + await expect(page.locator('#error-fallback')).toBeVisible(); + }); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts new file mode 100644 index 000000000000..e69775e11489 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/internal-fetch.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from '@playwright/test'; +import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; +import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; + +test('does not instrument the internal `$fetch` of a server-rendered page as its own request', async ({ request }) => { + // One listener, so it gets every span that the proxy received before the barrier span. + const spans: SerializedStreamedSpan[] = []; + const barrierPromise = waitForStreamedSpans('nuxt-5', batch => { + spans.push(...batch); + return batch.some(span => span.is_segment && span.attributes['url.path']?.value === '/api/test-param/barrier'); + }); + + const response = await request.get('/internal-fetch'); + expect(await response.text()).toContain('Param: internal!'); + await request.get('/api/test-param/barrier'); + await barrierPromise; + + const pageServerSpans = spans.filter( + span => getSpanOp(span) === 'http.server' && span.attributes['url.path']?.value === '/internal-fetch', + ); + const internalFetchServerSpans = spans.filter( + span => getSpanOp(span) === 'http.server' && span.attributes['url.path']?.value === '/api/test-param/internal', + ); + + expect(pageServerSpans).toHaveLength(1); + expect(pageServerSpans[0]?.attributes['sentry.sdk.name']).toEqual({ + type: 'string', + value: 'sentry.javascript.nuxt', + }); + expect(internalFetchServerSpans).toHaveLength(0); +}); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts index 8add88c82f06..3d1c14c1cb64 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/middleware.test.ts @@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils'; import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; +import { RUNTIME } from './runtime'; // Nitro runs every file in `server/middleware/` on every request, so each surface tells its spans apart by // middleware name. `nuxt/server` has no object syntax (`middleware`) and no `eventHandler` alias, so only the @@ -27,7 +28,11 @@ const MIDDLEWARE = { } as const; async function collectRequestSpans(path = '/api/middleware-test') { - const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === path); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-5', + span => span.attributes['url.path']?.value === path, + span => getSpanOp(span) === 'middleware', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === path); return spans.filter(span => span.trace_id === rootSpan?.trace_id); @@ -98,6 +103,11 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { }); test('captures a middleware error and marks its span as errored', async ({ request }) => { + test.fail( + RUNTIME === 'bun', + 'Bun: the `Bun.serve` instrumentation sets no transaction name on the isolation scope, so the error has none', + ); + const spansPromise = collectRequestSpans(path); const errorEventPromise = waitForError('nuxt-5', errorEvent => { return errorEvent?.exception?.values?.[0]?.value === middleware.authErrorMessage; diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts index c16c103126d6..fbda046aeb09 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime-injection.test.ts @@ -1,6 +1,7 @@ import { execFileSync } from 'node:child_process'; import { expect, test } from '@playwright/test'; import { isDevMode } from './isDevMode'; +import { RUNTIME } from './runtime'; // Nitro v3 bundles every dependency, including the SDK's copy of `@sentry/server-runtime-injection`. // On Node versions without `Module.registerHooks` (< 24.13), that bundled copy registers its ESM @@ -9,6 +10,7 @@ import { isDevMode } from './isDevMode'; // resolution directly instead of the missing warning. test('keeps the runtime injection loader hook resolvable from the server output', () => { test.skip(isDevMode, 'nuxt dev has no server output'); + test.skip(RUNTIME === 'cloudflare', 'Cloudflare: the Worker bundle has no `node_modules` and no loader hook'); const resolved = execFileSync( 'node', diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts new file mode 100644 index 000000000000..631286dde6d2 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/runtime.ts @@ -0,0 +1,38 @@ +import { getRuntime } from '@sentry-internal/test-utils'; + +export const RUNTIME = getRuntime(); + +export const NO_PROCESS = 'Cloudflare: the Worker is no process the tests can start or watch exit'; + +// Without Sentry too, the Cloudflare preset of Nitro cannot bundle the `mongodb` driver for Workers. +export const MONGOOSE_UNSUPPORTED = 'Cloudflare: Nitro cannot bundle the `mongodb` driver for Workers'; + +// Nitro 3 serves with `Bun.serve` on Bun and with `node:http` on Node and Deno. +const SERVER_ORIGINS = { + node: 'auto.http.http_server', + bun: 'auto.http.bun.serve', + deno: 'auto.http.http_server', + cloudflare: 'auto.http.cloudflare', +}; + +export const SERVER_ORIGIN = SERVER_ORIGINS[RUNTIME]; + +// On Cloudflare, the databases are D1 databases. `@sentry/cloudflare` creates the spans of their queries, and +// `@sentry/nuxt` leaves them out of its database instrumentation. +export const DB_SYSTEM_NAME = RUNTIME === 'cloudflare' ? 'cloudflare-d1' : 'sqlite'; +export const DB_ORIGIN = RUNTIME === 'cloudflare' ? 'auto.db.cloudflare.d1' : 'auto.db.nuxt'; + +/** The command and arguments that start the built server on the runtime of the variant. */ +export function getServerCommand(): [string, string[]] { + const entry = '.output/server/index.mjs'; + + if (RUNTIME === 'bun') { + return ['bun', [entry]]; + } + + if (RUNTIME === 'deno') { + return ['deno', ['run', '-A', entry]]; + } + + return ['node', [entry]]; +} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts index 3ea755529149..239fd2651f0b 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/startup-error.test.ts @@ -1,15 +1,24 @@ import { spawn } from 'node:child_process'; import { expect, test } from '@playwright/test'; import { waitForError, waitForSession } from '@sentry-internal/test-utils'; +import { getServerCommand, NO_PROCESS, RUNTIME } from './runtime'; + +test.skip(RUNTIME === 'cloudflare', NO_PROCESS); // Errors thrown between server start and `listen` (module evaluation, nitro plugin runs) must be // captured and flushed before the process exits. Each test spawns its own server process because // the crash kills it; events still reach the shared event proxy via the tunnel. +// Deno hands an error thrown while the modules evaluate to the `unhandledRejection` listeners, where Node and Bun +// treat it as an uncaught exception. The listener of the SDK (mode `warn`) keeps the process alive, so on Deno it +// exits with 0 once it has nothing left to do. +const CRASH_EXIT_CODE = RUNTIME === 'deno' ? 0 : 1; + /** Starts the built server and resolves with its exit code. */ function spawnCrashingServer(env: Record): Promise { return new Promise((resolve, reject) => { - const child = spawn('node', ['.output/server/index.mjs'], { + const [command, args] = getServerCommand(); + const child = spawn(command, args, { // Session tracking needs a release; builds without git (e.g. the E2E runner's temp copy) // have none injected, so pin one for the crashed-session assertion. env: { ...process.env, SENTRY_RELEASE: 'startup-error-test', ...env }, @@ -27,7 +36,7 @@ test('captures error and crashed session when a nitro plugin throws during start const [errorEvent, session] = await Promise.all([errorPromise, sessionPromise]); - expect(exitCode).toBe(1); + expect(exitCode).toBe(CRASH_EXIT_CODE); expect(errorEvent.exception?.values?.[0]?.value).toBe('startup-crash-test'); expect(errorEvent.exception?.values?.[0]?.mechanism?.handled).toBe(false); expect(session.status).toBe('crashed'); @@ -41,7 +50,7 @@ test('captures error when a server module throws during bundle evaluation', asyn const errorEvent = await errorPromise; - expect(exitCode).toBe(1); + expect(exitCode).toBe(CRASH_EXIT_CODE); expect(errorEvent.exception?.values?.[0]?.value).toBe('eval-crash-test'); expect(errorEvent.exception?.values?.[0]?.mechanism?.handled).toBe(false); }); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts index 0dc4353a927f..76c8b4bbf464 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage-aliases.test.ts @@ -2,7 +2,11 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; async function collectStorageSpans(route: string) { - const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === route); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-5', + span => span.attributes['url.path']?.value === route, + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route); return spans.filter( diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts index e8c10e66901d..ab3b3f63456c 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/storage.test.ts @@ -2,7 +2,11 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils'; async function collectStorageSpans(route: string) { - const spans = await collectStreamedSpansUntilSegment('nuxt-5', span => span.attributes['url.path']?.value === route); + const spans = await collectStreamedSpansUntilSegment( + 'nuxt-5', + span => span.attributes['url.path']?.value === route, + span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt', + ); const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === route); return spans.filter( diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts index 2a0dcebe48c4..100ca864b4ff 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.server.test.ts @@ -1,6 +1,13 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { + collectStreamedSpans, + getSpanOp, + waitForStreamedSpan, + waitForStreamedSpans, +} from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; +import { SERVER_ORIGIN } from './runtime'; test('sends a server root span on pageload', async ({ page }) => { const serverSpanPromise = waitForStreamedSpan('nuxt-5', span => { @@ -12,31 +19,33 @@ test('sends a server root span on pageload', async ({ page }) => { const serverSpan = await serverSpanPromise; expect(getSpanOp(serverSpan)).toBe('http.server'); - expect(serverSpan.attributes['sentry.origin']?.value).toBe('auto.http.http_server'); + expect(serverSpan.attributes['sentry.origin']?.value).toBe(SERVER_ORIGIN); }); -test('does not send spans for build asset folder "_nuxt"', async ({ page }) => { - let buildAssetFolderOccurred = false; - - waitForStreamedSpan('nuxt-5', span => { - if (span.is_segment && /^GET \/_nuxt\//.test(span.name)) { - buildAssetFolderOccurred = true; - } - return false; // expects to return a boolean (but not relevant here) - }); - - const serverSpanPromise = waitForStreamedSpan('nuxt-5', span => { - return span.is_segment && span.name.includes('GET /test-param/'); +[ + // Nuxt build output that the HTTP integration does not ignore. + '/_nuxt/builds/latest.json', + '/_nuxt/entry.js.map', + // File from `public/` that the HTTP integration does not ignore. + '/humans.txt', + // Common static file that the HTTP integration ignores. + '/favicon.ico', +].forEach(path => { + test(`does not send a server span for the file ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).not.toContain(path); }); +}); - await page.goto('/test-param/1234'); - - const serverSpan = await serverSpanPromise; - - expect(buildAssetFolderOccurred).toBe(false); +// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot +// pass by accident. +['/test-param/jane.doe', '/api/test-param/data.json', '/test-param/_nuxt/'].forEach(path => { + test(`sends a server span for the route ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); - expect(serverSpan.name).toBe('GET /test-param/:param()'); - expect(serverSpan.attributes['sentry.segment.name.source']?.value).toBe('route'); + expect(segmentPaths).toContain(path); + }); }); IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { @@ -72,3 +81,22 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => { expect(httpClientSpan?.parent_span_id).toBe(serverSegmentSpan?.span_id); }); }); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives + * after any segment for `path`. + */ +async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/test-param/after${path.replace(/\W+/g, '-')}`; + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('nuxt-5', spans => { + segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`)); + return segmentPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageSegmentPromise; + + return segmentPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts index 5580819bec1f..c704cd39b2e0 100644 --- a/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/tests/tracing.test.ts @@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test'; import { collectStreamedSpans, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; import { IMPORT_SURFACES } from './importSurfaces'; +import { SERVER_ORIGIN } from './runtime'; function expectSegmentSpan( span: SerializedStreamedSpan | undefined, @@ -53,7 +54,7 @@ test.describe('distributed tracing', () => { expectSegmentSpan(serverSpan, { name: 'GET /test-param/:param()', op: 'http.server', - origin: 'auto.http.http_server', + origin: SERVER_ORIGIN, }); expect(serverSpan.trace_id).toBe(metaTraceId); expect(clientSpan.parent_span_id).toBe(serverSpan.span_id); @@ -117,13 +118,13 @@ test.describe('distributed tracing', () => { expectSegmentSpan(ssrSpan, { name: 'GET /test-param/user/:userId()', op: 'http.server', - origin: 'auto.http.http_server', + origin: SERVER_ORIGIN, }); expectSegmentSpan(serverReqSpan, { name: `GET ${apiPrefix}/user/:userId`, op: 'http.server', - origin: 'auto.http.http_server', + origin: SERVER_ORIGIN, }); expect(serverReqSpan.parent_span_id).toBe(httpClientSpan?.span_id); diff --git a/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc b/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc new file mode 100644 index 000000000000..f2af1eb45c25 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/nuxt-5/wrangler.jsonc @@ -0,0 +1,23 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "nuxt-5", + "main": "./.output/server/index.mjs", + "compatibility_date": "2026-06-29", + "compatibility_flags": ["nodejs_compat"], + "assets": { + "directory": "./.output/public", + "binding": "ASSETS", + // Like Nitro on Node, serve pre-rendered pages at their path instead of redirecting to a trailing slash. + "html_handling": "drop-trailing-slash", + }, + // `wrangler dev` keeps these in a local SQLite file, so they need no real database. + "d1_databases": [ + { "binding": "DB", "database_name": "db", "database_id": "00000000-0000-0000-0000-000000000001" }, + { "binding": "USERS_DB", "database_name": "users_db", "database_id": "00000000-0000-0000-0000-000000000002" }, + { + "binding": "ANALYTICS_DB", + "database_name": "analytics_db", + "database_id": "00000000-0000-0000-0000-000000000003", + }, + ], +} diff --git a/dev-packages/e2e-tests/test-applications/react-17/package.json b/dev-packages/e2e-tests/test-applications/react-17/package.json index 99e9368fef2f..e3b6133cf145 100644 --- a/dev-packages/e2e-tests/test-applications/react-17/package.json +++ b/dev-packages/e2e-tests/test-applications/react-17/package.json @@ -43,7 +43,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" }, "sentryTest": { "variants": [ diff --git a/dev-packages/e2e-tests/test-applications/react-19/package.json b/dev-packages/e2e-tests/test-applications/react-19/package.json index 592f1dab46e1..f61ab8c0194b 100644 --- a/dev-packages/e2e-tests/test-applications/react-19/package.json +++ b/dev-packages/e2e-tests/test-applications/react-19/package.json @@ -42,6 +42,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } diff --git a/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json index 4405ba83c8c8..c2341146f6bb 100644 --- a/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json +++ b/dev-packages/e2e-tests/test-applications/react-create-browser-router/package.json @@ -43,6 +43,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } diff --git a/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json index 80481c626bd4..68d9a04800ea 100644 --- a/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json +++ b/dev-packages/e2e-tests/test-applications/react-create-hash-router/package.json @@ -44,7 +44,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" }, "sentryTest": { "canaryVariants": [ diff --git a/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json b/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json index 419a9e289d61..c9c7b04d522c 100644 --- a/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json +++ b/dev-packages/e2e-tests/test-applications/react-create-memory-router/package.json @@ -43,6 +43,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } diff --git a/dev-packages/e2e-tests/test-applications/react-router-5/package.json b/dev-packages/e2e-tests/test-applications/react-router-5/package.json index 1ceea6c66961..13627f545a57 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-5/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-5/package.json @@ -45,6 +45,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } 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 0500b51516b1..7a557f62ed7b 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 @@ -45,6 +45,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } diff --git a/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json index 87ddbf4ab3f8..96ca48541b92 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-6-use-routes/package.json @@ -42,6 +42,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } 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 2101a3aa1a62..cfcdafba1382 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 @@ -45,7 +45,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" }, "sentryTest": { "canaryVariants": [ diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts index 5a9fa9c841aa..315b794cb70a 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes.ts @@ -5,6 +5,7 @@ export default [ ...prefix('performance', [ index('routes/performance/index.tsx'), route('ssr', 'routes/performance/ssr.tsx'), + route('single-segment', 'routes/performance/single-segment.tsx'), route('with/:param', 'routes/performance/dynamic-param.tsx'), route('static', 'routes/performance/static.tsx'), route('server-loader', 'routes/performance/server-loader.tsx'), diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx new file mode 100644 index 000000000000..0fb1943c6723 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/app/routes/performance/single-segment.tsx @@ -0,0 +1,7 @@ +export default function SingleSegmentPage() { + return ( +
+

Single Segment Page

+
+ ); +} diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts index bf3cb1682ca2..98db532433db 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/react-router-7-framework-instrumentation/tests/performance/performance.server.test.ts @@ -137,38 +137,35 @@ test.describe('server - instrumentation API performance', () => { 'Dev server emits extra http.server segments for module requests', ); - // Navigate to `/performance/` with the trailing slash: `/performance` is answered with a 301 to - // it, and that redirect is a second request with a second `http.server` segment. It should not - // be sent at all — `ignoreStatusCodes` covers 301 — but that option is only applied to - // transactions, so span streaming emits it. Going straight to the final URL keeps this test - // about double-instrumentation instead of failing on the redirect. + // The route is only requested by this test, and segments are filtered by its path: the event + // proxy receives the segments of every test running in parallel, so without the filter + // requests from other tests would show up as duplicates. // // A streamed server segment is named after the method alone until a route is matched, so a - // duplicate shows up as a bare `GET`. Collect the origin and path alongside the name — they are - // what says which instrumentation emitted the extra segment, and for which request. + // duplicate shows up as a bare `GET`. Collect the origin alongside the name — it is what says + // which instrumentation emitted the extra segment. + const urlPath = '/performance/single-segment'; const httpServerSegments: Array> = []; void waitForStreamedSpans(APP_NAME, spans => { for (const span of spans) { - if (getSpanOp(span) === 'http.server' && span.is_segment) { + if (getSpanOp(span) === 'http.server' && span.is_segment && span.attributes['url.path']?.value === urlPath) { httpServerSegments.push({ name: span.name, origin: span.attributes['sentry.origin']?.value, - urlPath: span.attributes['url.path']?.value, }); } } return false; }); - await page.goto(`/performance/`); + await page.goto(urlPath); // Give any (erroneous) duplicate span time to arrive before asserting. await page.waitForTimeout(3000); expect(httpServerSegments).toEqual([ { - name: 'GET /performance', + name: 'GET /performance/single-segment', origin: 'auto.http.react_router.instrumentation_api', - urlPath: '/performance/', }, ]); }); diff --git a/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json b/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json index 4c0333dac6bf..cf4f7afdd31a 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-7-lazy-routes/package.json @@ -42,6 +42,6 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" } } diff --git a/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json b/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json index 9069a62bfe86..0eb7e8d48267 100644 --- a/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json +++ b/dev-packages/e2e-tests/test-applications/react-router-cross-usage/package.json @@ -43,7 +43,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "serve": "14.0.1" + "serve": "14.2.8" }, "sentryTest": { "baseVariant": { diff --git a/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json b/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json index 78309062e685..79df7bc26d6c 100644 --- a/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json +++ b/dev-packages/e2e-tests/test-applications/react-send-to-sentry/package.json @@ -42,9 +42,10 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "serve": "14.0.1" + "serve": "14.2.8" }, "sentryTest": { - "optional": true + "optional": true, + "needsSecrets": true } } diff --git a/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts b/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts index bac48fb868dd..607a789fc0e9 100644 --- a/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/remix-sourcemaps/assert-build.ts @@ -46,8 +46,7 @@ for (const chunk of chunks) { } console.log(`no client chunk carries more than one debug ID (${chunks.length} chunks)\n`); -// The SDK turns on hidden source maps when the app sets none, and asks the bundler plugin to -// remove them from both the client and the SSR output, also when no upload runs. +// Without an auth token the SDK turns no source maps on, so the build writes none. if (process.env.E2E_NO_UPLOAD) { // The mock server only writes its results file when a request reaches it. const requests = fs.existsSync('.tmp_mock_uploads.json') ? loadMockServerResults() : []; diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json index 7e4b61b95afa..76a006213b41 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/package.json @@ -17,6 +17,7 @@ "@sentry/solid": "file:../../packed/sentry-solid-packed.tgz", "@solidjs/router": "^2.0.0", "@solidjs/web": "^2.0.0", + "graphql": "16.9.0", "solid-js": "^2.0.0" }, "devDependencies": { @@ -24,7 +25,8 @@ "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "@sentry/cloudflare": "file:../../packed/sentry-cloudflare-packed.tgz", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", + "@sentry/node": "file:../../packed/sentry-node-packed.tgz", "@solidjs/vite-plugin": "^3.0.0", "typescript": "^5.4.5", "vite": "^8.1.5", diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx index 65ef2fc1eced..4a4e2e891f2c 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/Home.tsx @@ -1,5 +1,5 @@ import { createSignal } from 'solid-js'; -import { failingServerFunction } from './server-functions'; +import { failingServerFunction, graphqlServerFunction } from './server-functions'; export default function Home() { const [result, setResult] = createSignal(''); @@ -17,6 +17,14 @@ export default function Home() { > Call failing server function +

{result()}

); diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts index cab935d77837..3544aa2a6e9e 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/src/server-functions.ts @@ -1,4 +1,13 @@ +import { buildSchema, graphql } from 'graphql'; + export async function failingServerFunction(): Promise { 'use server'; throw new Error('Error thrown from a server function in Solid 2 SSR E2E test app'); } + +export async function graphqlServerFunction(): Promise { + 'use server'; + const schema = buildSchema('type Query { hello: String }'); + const result = await graphql({ schema, source: 'query Hello { hello }', rootValue: { hello: () => 'world' } }); + return String(result.data?.hello); +} diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts new file mode 100644 index 000000000000..67b01772bd8d --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/bundled-dependency.server.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from '@playwright/test'; +import { GRAPHQL_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { GRAPHQL, HTTP_SERVER } from '@sentry/conventions/op'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; + +test('instruments a dependency the server build bundles', async ({ page }) => { + const graphqlSpanPromise = waitForStreamedSpan('solid-2-ssr', span => { + return getSpanOp(span) === GRAPHQL && span.attributes?.[GRAPHQL_OPERATION_NAME]?.value === 'Hello'; + }); + // The server function's request span. It continues the pageload's trace, as the page request does, so it is + // found by its method within the trace of the graphql span. + const serverSpanPromise = graphqlSpanPromise.then(graphqlSpan => + waitForStreamedSpan( + 'solid-2-ssr', + span => + getSpanOp(span) === HTTP_SERVER && + span.is_segment && + span.trace_id === graphqlSpan.trace_id && + span.name.startsWith('POST'), + 0, + ), + ); + + await page.goto('/'); + await page.locator('#graphqlBtn').click(); + await expect(page.locator('#result')).toHaveText('world'); + + const [graphqlSpan, serverSpan] = await Promise.all([graphqlSpanPromise, serverSpanPromise]); + + expect(graphqlSpan.attributes?.[SENTRY_ORIGIN]?.value).toMatch(/^auto\.graphql\./); + expect(graphqlSpan.parent_span_id).toBeDefined(); + expect(serverSpan.status).not.toBe('error'); +}); diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts index a5719de334fd..a1ccc3007f28 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/tests/trace-propagation.test.ts @@ -1,12 +1,9 @@ import { expect, test } from '@playwright/test'; import { URL_PATH } from '@sentry/conventions/attributes'; import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op'; -import { getRuntime, getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; +import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils'; test('continues the server trace in the pageload', async ({ page }) => { - // On Cloudflare, nothing sends the trace to the browser yet: `addServerTimingTraceHeader` only covers Node. - test.skip(getRuntime() === 'cloudflare', 'No trace propagation to the browser on Cloudflare yet'); - // Other tests request `/user/:id` too, so both spans are matched on a path no other test uses. const path = `/user/trace-${Date.now()}`; diff --git a/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts b/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts index 77919094f2f5..5aee3f41c812 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/solid-2-ssr/vite.config.ts @@ -1,3 +1,4 @@ +import { sentryVitePlugin } from '@sentry/node/vite'; import solid from '@solidjs/vite-plugin'; import { defineConfig } from 'vite'; @@ -13,6 +14,12 @@ export default defineConfig({ serverFunctions: true, observe: process.env.SOLID_OBSERVE === '1', }), + // Instruments the dependencies the server build bundles, such as `graphql`. No auth token, so nothing is uploaded. + sentryVitePlugin({ + telemetry: false, + sourcemaps: { disable: true }, + release: { create: false, finalize: false, inject: false }, + }), ], build: { target: 'esnext', diff --git a/dev-packages/e2e-tests/test-applications/solid-2/package.json b/dev-packages/e2e-tests/test-applications/solid-2/package.json index b316900a2e21..c9433e77f520 100644 --- a/dev-packages/e2e-tests/test-applications/solid-2/package.json +++ b/dev-packages/e2e-tests/test-applications/solid-2/package.json @@ -23,7 +23,7 @@ }, "devDependencies": { "@playwright/test": "1.64.1", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", "@solidjs/vite-plugin": "^3.0.0", "typescript": "^5.4.5", diff --git a/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts new file mode 100644 index 000000000000..8c08e841fa29 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/solidstart-1-tunnel/tests/build-assets.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; + +// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path. +const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map'; +const PAGE_PATH = '/app/after-build-file'; + +// In development, the server SDK does not know the base path when it initializes. +test.skip(process.env.TEST_ENV === 'development', 'Production only'); + +test('does not send a server span for a build file under the base path', async ({ baseURL }) => { + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('solidstart-1-tunnel', spans => { + segmentPaths.push( + ...spans + .filter(span => span.is_segment && getSpanOp(span) === 'http.server') + .map(span => `${span.attributes['url.path']?.value}`), + ); + return segmentPaths.includes(PAGE_PATH); + }); + + await fetch(`${baseURL}${BUILD_FILE_PATH}`); + // A span for the build file would arrive before the span of this later request. + await fetch(`${baseURL}${PAGE_PATH}`); + await pageSegmentPromise; + + expect(segmentPaths).not.toContain(BUILD_FILE_PATH); +}); diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts new file mode 100644 index 000000000000..b651f5a1adae --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/solidstart-2-tunnel/tests/build-assets.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from '@playwright/test'; +import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; + +// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path. +const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map'; +const PAGE_PATH = '/app/after-build-file'; + +// In development, the server SDK does not know the base path when it initializes. +test.skip(process.env.TEST_ENV === 'development', 'Production only'); + +test('does not send a server span for a build file under the base path', async ({ baseURL }) => { + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('solidstart-2-tunnel', spans => { + segmentPaths.push( + ...spans + .filter(span => span.is_segment && getSpanOp(span) === 'http.server') + .map(span => `${span.attributes['url.path']?.value}`), + ); + return segmentPaths.includes(PAGE_PATH); + }); + + await fetch(`${baseURL}${BUILD_FILE_PATH}`); + // A span for the build file would arrive before the span of this later request. + await fetch(`${baseURL}${PAGE_PATH}`); + await pageSegmentPromise; + + expect(segmentPaths).not.toContain(BUILD_FILE_PATH); +}); diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts index a36e573063dc..f65997d009a2 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart-2/assert-build.ts @@ -1,25 +1,77 @@ +import * as assert from 'node:assert/strict'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { assertSourceMapUpload, findDebugIdsInFilesWithGlobCharacters } from '@sentry-internal/test-utils'; +import { + assertSourceMapUpload, + findDebugIdsInFilesWithGlobCharacters, + findInjectedDebugIds, + findSourceMapFiles, + findSourceMappingUrlComments, + getChunkUploadPosts, + loadMockServerResults, +} from '@sentry-internal/test-utils'; const CLIENT_OUTPUT = path.join('.output', 'public'); const SERVER_OUTPUT = path.join('.output', 'server'); -// The app does not set `build.sourcemap`, so the SDK enables hidden maps and must delete them after upload. -// TODO: The client maps stay in `.output/public`, because the SDK's deletion glob `./**/*.map` skips dot -// folders. Add `CLIENT_OUTPUT` to `strippedDirs` once the SDK deletes them. -assertSourceMapUpload({ - outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT], - strippedDirs: [SERVER_OUTPUT], - markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' }, - debugIdsWithoutSourceMap: [ - // Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. - ...(fs.existsSync('.tmp_debug_ids_without_source_map') - ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean) - : []), - ...findDebugIdsInFilesWithGlobCharacters({ outputDir: SERVER_OUTPUT }), - ], -}); +/** Debug IDs of chunks for which no source map can be uploaded. */ +const debugIdsWithoutSourceMap = [ + // Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. + ...(fs.existsSync('.tmp_debug_ids_without_source_map') + ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean) + : []), + ...findDebugIdsInFilesWithGlobCharacters({ outputDir: SERVER_OUTPUT }), +]; + +// The app does not set `build.sourcemap`, so the SDK enables hidden maps and asks the bundler plugin to +// remove them from the client output, also when no upload runs. `@sentry/nitro` handles the server output. +if (process.env.E2E_NO_UPLOAD) { + assert.deepEqual(findSourceMapFiles({ outputDir: CLIENT_OUTPUT }), [], `Expected no source maps in ${CLIENT_OUTPUT}`); + assert.deepEqual( + findSourceMappingUrlComments({ outputDir: CLIENT_OUTPUT }), + [], + `Expected no sourceMappingURL comments in ${CLIENT_OUTPUT}`, + ); +} else if (process.env.E2E_VARIANT === 'manual-upload') { + // `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on + // stay with the debug IDs of their chunks, ready for an upload with the CLI. + assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload'); + + for (const outputDir of [CLIENT_OUTPUT, SERVER_OUTPUT]) { + assert.deepEqual( + findSourceMappingUrlComments({ outputDir }), + [], + `Expected no sourceMappingURL comments in ${outputDir}`, + ); + + const mapDebugIds = new Set( + findSourceMapFiles({ outputDir }).map(file => { + const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string }; + return (map.debug_id ?? map.debugId)?.toLowerCase(); + }), + ); + const injectedDebugIds = findInjectedDebugIds({ outputDir }); + + assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); + assert.deepEqual( + injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId) && !debugIdsWithoutSourceMap.includes(debugId)), + [], + `Expected a source map with the same debug ID for every chunk in ${outputDir}`, + ); + assert.ok( + injectedDebugIds.some(debugId => mapDebugIds.has(debugId)), + `Expected at least one chunk in ${outputDir} to have a kept source map`, + ); + console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`); + } +} else { + // Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed. + assertSourceMapUpload({ + outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT], + markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' }, + debugIdsWithoutSourceMap, + }); +} // The server adds the release to the page, so no content-hashed client file may contain it. const clientFilesWithRelease = fs diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/package.json b/dev-packages/e2e-tests/test-applications/solidstart-2/package.json index bcb170291a94..9dbce23d24d2 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart-2/package.json +++ b/dev-packages/e2e-tests/test-applications/solidstart-2/package.json @@ -9,7 +9,13 @@ "start": "HOST=localhost PORT=3030 node .output/server/index.mjs", "test:prod": "TEST_ENV=production playwright test", "test:build": "pnpm install && pnpm build", - "test:assert": "node assert-build.ts && pnpm test:prod" + "test:assert": "node assert-build.ts && pnpm test:prod", + "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build", + "test:assert:no-upload": "E2E_NO_UPLOAD=1 node assert-build.ts", + "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build", + "test:assert:manual-upload": "E2E_VARIANT=manual-upload node assert-build.ts", + "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build", + "test:assert:delete-all": "E2E_VARIANT=delete-all node assert-build.ts" }, "type": "module", "dependencies": { @@ -31,6 +37,23 @@ "node": ">=24" }, "sentryTest": { - "optional": true + "optional": true, + "optionalVariants": [ + { + "build-command": "pnpm test:build:no-upload", + "assert-command": "pnpm test:assert:no-upload", + "label": "solidstart-2 (no upload)" + }, + { + "build-command": "pnpm test:build:manual-upload", + "assert-command": "pnpm test:assert:manual-upload", + "label": "solidstart-2 (manual upload)" + }, + { + "build-command": "pnpm test:build:delete-all", + "assert-command": "pnpm test:assert:delete-all", + "label": "solidstart-2 (delete all)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts index e2e668c9ec90..d175ad0b25fd 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart-2/tests/performance.server.test.ts @@ -1,5 +1,5 @@ import { expect, test } from '@playwright/test'; -import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils'; +import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; test('sends a server action span on pageload', async ({ page }) => { const spansPromise = collectStreamedSpans( @@ -46,3 +46,40 @@ test('sends a server action span on client navigation', async ({ page }) => { 'code.function.name': { value: 'getPrefecture', type: 'string' }, }); }); + +['/_build/assets/entry.js.map', '/_build/.vite/manifest.json'].forEach(path => { + test(`does not send a server span for the file ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).not.toContain(path); + }); +}); + +// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot +// pass by accident. +['/users/jane.doe', '/users/_build/'].forEach(path => { + test(`sends a server span for the route ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).toContain(path); + }); +}); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives + * after any segment for `path`. + */ +async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/users/after${path.replace(/\W+/g, '-')}`; + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('solidstart-2', spans => { + segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes['url.path']?.value}`)); + return segmentPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageSegmentPromise; + + return segmentPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts b/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts index 74811201d2cf..8135f882102d 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart-2/vite.config.ts @@ -5,26 +5,34 @@ import { defineConfig } from 'vite'; import * as fs from 'node:fs'; // Rolldown emits no map for chunks without mappable source (e.g. Vite's preload helper), so their debug -// IDs can't be uploaded. Recorded here because the SDK deletes all maps after the upload. +// IDs can't be uploaded. Recorded before the bundler plugin removes the maps from the bundle. function recordChunksWithoutSourceMap() { return { name: 'record-chunks-without-source-map', apply: 'build' as const, enforce: 'post' as const, - writeBundle(_options: unknown, bundle: Record) { - for (const output of Object.values(bundle)) { - if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) { - continue; + generateBundle: { + order: 'pre' as const, + handler(_options: unknown, bundle: Record) { + for (const output of Object.values(bundle)) { + if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) { + continue; + } + for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) { + fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`); + } } - for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) { - fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`); - } - } + }, }, }; } +// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI. +// `delete-all`: the app turns source maps on itself, and Sentry removes them. +const variant = process.env.E2E_VARIANT; + export default defineConfig({ + build: variant === 'delete-all' ? { sourcemap: true } : undefined, plugins: [ solidStart({ appRoot: './src', @@ -32,11 +40,17 @@ export default defineConfig({ }), sentrySolidStart({ sentryUrl: 'http://localhost:3032', - authToken: 'fake-auth-token', + authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token', org: 'test-org', project: 'test-project', release: { name: 'test-release' }, debug: true, + sourcemaps: + variant === 'manual-upload' + ? { upload: false, delete: false } + : variant === 'delete-all' + ? { delete: true } + : undefined, }), // `serverDir` defaults to `false`, which skips plugin scanning entirely. nitro({ serverDir: './server' }), diff --git a/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts b/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts index 176403391980..21b532bdf292 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart/app.config.ts @@ -4,19 +4,30 @@ import { defineConfig } from '@solidjs/start/config'; // The inject mode variants set `E2E_TEST_INJECT_MODE` for the build and the test run. const injectMode = process.env.E2E_TEST_INJECT_MODE as 'top-level-import' | 'experimental_dynamic-import' | undefined; +// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI. +// `delete-all`: the app turns source maps on itself, and Sentry removes them. +const variant = process.env.E2E_VARIANT; + export default defineConfig( withSentry( { middleware: './src/middleware.ts', + ...(variant === 'delete-all' && { vite: { build: { sourcemap: true } } }), }, { sentryUrl: 'http://localhost:3032', - authToken: 'fake-auth-token', + authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token', org: 'test-org', project: 'test-project', release: { name: 'test-release' }, debug: true, autoInjectServerSentry: injectMode, + sourcemaps: + variant === 'manual-upload' + ? { upload: false, delete: false } + : variant === 'delete-all' + ? { delete: true } + : undefined, }, ), ); diff --git a/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts b/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts index 243960c51ac5..c6f189e4b6c4 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart/assert-build.ts @@ -1,18 +1,69 @@ +import * as assert from 'node:assert/strict'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { assertSourceMapUpload } from '@sentry-internal/test-utils'; +import { + assertSourceMapUpload, + findInjectedDebugIds, + findSourceMapFiles, + findSourceMappingUrlComments, + getChunkUploadPosts, + loadMockServerResults, +} from '@sentry-internal/test-utils'; const CLIENT_OUTPUT = path.join('.output', 'public'); const SERVER_OUTPUT = path.join('.output', 'server'); -// The app does not set `build.sourcemap`, so the SDK enables hidden maps and must delete them after upload. -// Vinxi writes the server output after the SDK deleted the maps, so `.output/server` keeps Nitro's own maps, -// which carry no mappings. They are not served, so only the client output must be free of maps. -assertSourceMapUpload({ - outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT], - strippedDirs: [CLIENT_OUTPUT], - markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' }, -}); +// The app does not set `build.sourcemap`, so the SDK enables hidden maps and asks the bundler plugin to +// remove them, also when no upload runs. Vinxi writes the server output after that, so `.output/server` +// keeps Nitro's own maps, which carry no mappings. They are not served, so only the client output must +// be free of maps. +if (process.env.E2E_NO_UPLOAD) { + assert.deepEqual(findSourceMapFiles({ outputDir: CLIENT_OUTPUT }), [], `Expected no source maps in ${CLIENT_OUTPUT}`); + assert.deepEqual( + findSourceMappingUrlComments({ outputDir: CLIENT_OUTPUT }), + [], + `Expected no sourceMappingURL comments in ${CLIENT_OUTPUT}`, + ); +} else if (process.env.E2E_VARIANT === 'manual-upload') { + // `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on + // stay with the debug IDs of their chunks, ready for an upload with the CLI. + assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload'); + + for (const outputDir of [CLIENT_OUTPUT]) { + assert.deepEqual( + findSourceMappingUrlComments({ outputDir }), + [], + `Expected no sourceMappingURL comments in ${outputDir}`, + ); + + const mapDebugIds = new Set( + findSourceMapFiles({ outputDir }).map(file => { + const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string }; + return (map.debug_id ?? map.debugId)?.toLowerCase(); + }), + ); + const injectedDebugIds = findInjectedDebugIds({ outputDir }); + + assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); + assert.deepEqual( + injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId)), + [], + `Expected a source map with the same debug ID for every chunk in ${outputDir}`, + ); + assert.ok( + injectedDebugIds.some(debugId => mapDebugIds.has(debugId)), + `Expected at least one chunk in ${outputDir} to have a kept source map`, + ); + console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`); + } +} else { + // Also covers the `delete-all` variant: the maps the app turned on are uploaded and removed. + assertSourceMapUpload({ + outputDirs: [CLIENT_OUTPUT, SERVER_OUTPUT], + strippedDirs: [CLIENT_OUTPUT], + markers: { 'client source': 'SOURCEMAP_MARKER_CLIENT', 'server source': 'SOURCEMAP_MARKER_SERVER' }, + }); +} // The server adds the release to the page, so no content-hashed client file may contain it. const clientFilesWithRelease = fs diff --git a/dev-packages/e2e-tests/test-applications/solidstart/package.json b/dev-packages/e2e-tests/test-applications/solidstart/package.json index c703e71a8568..a7293add49ee 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart/package.json +++ b/dev-packages/e2e-tests/test-applications/solidstart/package.json @@ -10,7 +10,13 @@ "test:prod": "TEST_ENV=production playwright test", "test:build": "pnpm install && pnpm build", "test:assert": "node assert-build.ts && pnpm test:prod && pnpm test:dev", - "test:dev": "TEST_ENV=development playwright test db" + "test:dev": "TEST_ENV=development playwright test db", + "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build", + "test:assert:no-upload": "E2E_NO_UPLOAD=1 node assert-build.ts", + "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build", + "test:assert:manual-upload": "E2E_VARIANT=manual-upload node assert-build.ts", + "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build", + "test:assert:delete-all": "E2E_VARIANT=delete-all node assert-build.ts" }, "type": "module", "dependencies": { @@ -21,7 +27,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@solidjs/meta": "^0.29.4", "@solidjs/router": "^1.0.0", "@solidjs/start": "^1.0.2", @@ -47,6 +53,21 @@ "build-command": "VITE_E2E_TEST_TRACE_LIFECYCLE=static pnpm test:build", "assert-command": "E2E_TEST_TRACE_LIFECYCLE=static pnpm test:prod", "label": "solidstart (static trace lifecycle)" + }, + { + "build-command": "pnpm test:build:no-upload", + "assert-command": "pnpm test:assert:no-upload", + "label": "solidstart (no upload)" + }, + { + "build-command": "pnpm test:build:manual-upload", + "assert-command": "pnpm test:assert:manual-upload", + "label": "solidstart (manual upload)" + }, + { + "build-command": "pnpm test:build:delete-all", + "assert-command": "pnpm test:assert:delete-all", + "label": "solidstart (delete all)" } ] } diff --git a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts index bbac70d1abcb..c6adae79775e 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.static-lifecycle.test.ts @@ -1,4 +1,4 @@ -import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; import { waitForTransaction } from '@sentry-internal/test-utils'; @@ -49,3 +49,46 @@ test('sends a server action transaction on client navigation', async ({ page }) ]), ); }); + +[ + // SolidStart build output that the HTTP integration does not ignore. + '/_build/assets/entry.js.map', + '/_build/.vite/manifest.json', + // Common static file that the HTTP integration ignores. + '/favicon.ico', +].forEach(path => { + test(`does not send a server transaction for the file ${path}`, async ({ baseURL }) => { + const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path); + + expect(transactionPaths).not.toContain(path); + }); +}); + +// Routes that look like build output. They also show that the helper sees sent transactions, so the tests above cannot +// pass by accident. +['/users/jane.doe', '/users/_build/'].forEach(path => { + test(`sends a server transaction for the route ${path}`, async ({ baseURL }) => { + const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path); + + expect(transactionPaths).toContain(path); + }); +}); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server transaction up to the page's transaction, + * which arrives after any transaction for `path`. + */ +async function getServerTransactionPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/users/after${path.replace(/\W+/g, '-')}`; + const transactionPaths: string[] = []; + const pageTransactionPromise = waitForTransaction('solidstart', transactionEvent => { + transactionPaths.push(`${transactionEvent.contexts?.trace?.data?.[URL_PATH]}`); + return transactionPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageTransactionPromise; + + return transactionPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts index 251a1601ae53..fb2886396856 100644 --- a/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts +++ b/dev-packages/e2e-tests/test-applications/solidstart/tests/performance.server.streaming-lifecycle.test.ts @@ -1,5 +1,6 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; import { expect, test } from '@playwright/test'; -import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils'; +import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils'; test('sends a server action span on pageload', async ({ page }) => { const spansPromise = collectStreamedSpans( @@ -46,3 +47,46 @@ test('sends a server action span on client navigation', async ({ page }) => { 'code.function.name': { value: 'getPrefecture', type: 'string' }, }); }); + +[ + // SolidStart build output that the HTTP integration does not ignore. + '/_build/assets/entry.js.map', + '/_build/.vite/manifest.json', + // Common static file that the HTTP integration ignores. + '/favicon.ico', +].forEach(path => { + test(`does not send a server span for the file ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).not.toContain(path); + }); +}); + +// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot +// pass by accident. +['/users/jane.doe', '/users/_build/'].forEach(path => { + test(`sends a server span for the route ${path}`, async ({ baseURL }) => { + const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path); + + expect(segmentPaths).toContain(path); + }); +}); + +/** + * Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives + * after any segment for `path`. + */ +async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise { + const pagePath = `/users/after${path.replace(/\W+/g, '-')}`; + const segmentPaths: string[] = []; + const pageSegmentPromise = waitForStreamedSpans('solidstart', spans => { + segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`)); + return segmentPaths.includes(pagePath); + }); + + await fetch(`${baseURL}${path}`); + await fetch(`${baseURL}${pagePath}`); + await pageSegmentPromise; + + return segmentPaths; +} diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json index 765d71dccb12..2889ad2612c6 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2.5.0-twp/package.json @@ -24,7 +24,7 @@ "@sveltejs/kit": "2.8.3", "@sveltejs/vite-plugin-svelte": "^3.0.0", "svelte": "^5.0.0-next.115", - "svelte-check": "^3.6.0", + "svelte-check": "^4.7.8", "typescript": "^5.0.0", "vite": "^5.4.11" }, diff --git a/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json index 6b7444a17ed4..6cd9feebb3c7 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-2/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@playwright/test": "1.64.1", "@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@sveltejs/adapter-node": "^2.0.0", "@sveltejs/kit": "2.70.4", "@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 6d0d3f376fce..f147de3fd87b 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-3/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-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.35.0", + "@sentry/conventions": "0.36.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-cloudflare-pages/package.json b/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json index 7e983db34293..b8de6e77638c 100644 --- a/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/package.json +++ b/dev-packages/e2e-tests/test-applications/sveltekit-cloudflare-pages/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.35.0", + "@sentry/conventions": "0.36.0", "@sveltejs/adapter-cloudflare": "^5.0.3", "@sveltejs/kit": "2.70.4", "@sveltejs/vite-plugin-svelte": "^5.0.3", diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore index 4187ae735082..634fe9c9c6d9 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/.gitignore @@ -9,3 +9,4 @@ src/routeTree.gen.ts .tmp_chunks .tmp_build_stdout .tmp_build_stderr +.tmp_debug_ids_without_source_map 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 d420d797a699..bf6de88af70b 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 @@ -24,12 +24,6 @@ const SERVER_OUTPUT = path.join('.output', 'server'); const CLIENT_MARKER = 'SOURCEMAP_MARKER_CLIENT'; const SERVER_MARKER = 'SOURCEMAP_MARKER_SERVER'; -const DEBUG_ID_PATTERN = /sentry-dbid-([\da-f-]{36})/gi; - -function readDebugIds(file: string): string[] { - return [...fs.readFileSync(file, 'utf8').matchAll(DEBUG_ID_PATTERN)].map(match => (match[1] as string).toLowerCase()); -} - function emittedJsFiles(dir: string): string[] { return fs .readdirSync(dir, { recursive: true, withFileTypes: true }) @@ -37,22 +31,13 @@ function emittedJsFiles(dir: string): string[] { .map(entry => path.join(entry.parentPath, entry.name)); } -/** In debug mode, the Sentry plugin logs each file it deletes after the upload. */ -const deletedFiles = new Set( - [...fs.readFileSync('.tmp_build_stdout', 'utf8').matchAll(/Deleting asset after upload: (.+)$/gm)].map(match => - path.relative(fs.realpathSync('.'), match[1] as string), - ), +/** Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. */ +const debugIdsWithoutSourceMap = new Set( + fs.existsSync('.tmp_debug_ids_without_source_map') + ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean) + : [], ); -/** A chunk without mappable source, such as Nitro's runtime, gets a debug ID but no source map to upload. */ -function debugIdsOfChunksWithoutSourceMap(dir: string): Set { - return new Set( - emittedJsFiles(dir) - .filter(file => !fs.existsSync(`${file}.map`) && !deletedFiles.has(`${file}.map`)) - .flatMap(readDebugIds), - ); -} - function sourceMapsIn(dir: string): string[] { return fs .readdirSync(dir, { recursive: true, withFileTypes: true }) @@ -116,8 +101,9 @@ for (const outputDir of [CLIENT_OUTPUT, SERVER_OUTPUT]) { const injectedDebugIds = findInjectedDebugIds({ outputDir }); assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); - const exemptDebugIds = debugIdsOfChunksWithoutSourceMap(outputDir); - const unuploaded = injectedDebugIds.filter(debugId => !uploadedDebugIds.has(debugId) && !exemptDebugIds.has(debugId)); + const unuploaded = injectedDebugIds.filter( + debugId => !uploadedDebugIds.has(debugId) && !debugIdsWithoutSourceMap.has(debugId), + ); assert.deepEqual(unuploaded, [], `Expected every debug ID in ${outputDir} to have an uploaded source map`); // A file of Nitro's output can carry the debug ID of the SSR chunk it was built from. diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts new file mode 100644 index 000000000000..5e53903c5fcf --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-manual-upload.ts @@ -0,0 +1,51 @@ +import * as assert from 'assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import { + findInjectedDebugIds, + findSourceMapFiles, + findSourceMappingUrlComments, + getChunkUploadPosts, + loadMockServerResults, +} from '@sentry-internal/test-utils'; + +/** Written by the build, see `recordChunksWithoutSourceMap` in `vite.config.ts`. */ +const debugIdsWithoutSourceMap = new Set( + fs.existsSync('.tmp_debug_ids_without_source_map') + ? fs.readFileSync('.tmp_debug_ids_without_source_map', 'utf8').split('\n').filter(Boolean) + : [], +); + +// `upload: false` with `delete: false`: nothing reaches Sentry, and the hidden maps Sentry turned on for +// the client and the Nitro server stay with the debug IDs of their chunks, ready for an upload with the CLI. +assert.deepEqual(getChunkUploadPosts(loadMockServerResults()), [], 'Expected no source map upload'); + +for (const outputDir of [path.join('.output', 'public'), path.join('.output', 'server')]) { + assert.deepEqual( + findSourceMappingUrlComments({ outputDir }), + [], + `Expected no sourceMappingURL comments in ${outputDir}`, + ); + + const mapDebugIds = new Set( + findSourceMapFiles({ outputDir }).map(file => { + const map = JSON.parse(fs.readFileSync(file, 'utf8')) as { debug_id?: string; debugId?: string }; + return (map.debug_id ?? map.debugId)?.toLowerCase(); + }), + ); + const injectedDebugIds = findInjectedDebugIds({ outputDir }); + + assert.ok(injectedDebugIds.length > 0, `Expected debug IDs to be injected into ${outputDir}`); + assert.deepEqual( + injectedDebugIds.filter(debugId => !mapDebugIds.has(debugId) && !debugIdsWithoutSourceMap.has(debugId)), + [], + `Expected a source map with the same debug ID for every chunk in ${outputDir}`, + ); + assert.ok( + injectedDebugIds.some(debugId => mapDebugIds.has(debugId)), + `Expected at least one chunk in ${outputDir} to have a kept source map`, + ); + console.log(` ${outputDir}: ${injectedDebugIds.length} debug ID(s), ${mapDebugIds.size} kept source map(s)`); +} + +console.log('All source map assertions passed!'); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts new file mode 100644 index 000000000000..81ee63f2151a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/assert-no-upload.ts @@ -0,0 +1,23 @@ +import * as assert from 'assert/strict'; +import * as fs from 'fs'; +import * as path from 'path'; +import { findSourceMapFiles, findSourceMappingUrlComments } from '@sentry-internal/test-utils'; + +// Without an auth token no upload can run, so the SDK turns on no source maps for the client and the +// Nitro server. +for (const outputDir of [path.join('.output', 'public'), path.join('.output', 'server')]) { + assert.deepEqual(findSourceMapFiles({ outputDir }), [], `Expected no source maps in ${outputDir}`); + assert.deepEqual( + findSourceMappingUrlComments({ outputDir }), + [], + `Expected no sourceMappingURL comments in ${outputDir}`, + ); +} + +const buildLog = fs.readFileSync('.tmp_build_stdout', 'utf8') + fs.readFileSync('.tmp_build_stderr', 'utf8'); +assert.ok( + !buildLog.includes('deleteSourcemapsAfterUpload'), + 'Expected no message about `sourcemaps.deleteSourcemapsAfterUpload`, which the app does not set', +); + +console.log('All source map assertions passed!'); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json index 1dd5050c0372..aa109970330d 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/package.json @@ -7,7 +7,13 @@ "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", "clean": "npx rimraf node_modules pnpm-lock.yaml .output", "test:build": "pnpm install && pnpm build", - "test:assert": "pnpm ts-node --script-mode assert-build.ts" + "test:build:no-upload": "pnpm install && E2E_NO_UPLOAD=1 pnpm build", + "test:assert": "pnpm ts-node --script-mode assert-build.ts", + "test:assert:no-upload": "pnpm ts-node --script-mode assert-no-upload.ts", + "test:build:manual-upload": "pnpm install && E2E_VARIANT=manual-upload pnpm build", + "test:assert:manual-upload": "pnpm ts-node --script-mode assert-manual-upload.ts", + "test:build:delete-all": "pnpm install && E2E_VARIANT=delete-all pnpm build", + "test:assert:delete-all": "pnpm test:assert" }, "dependencies": { "@sentry/tanstackstart-react": "file:../../packed/sentry-tanstackstart-react-packed.tgz", @@ -24,11 +30,28 @@ "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react-swc": "^4.2.0", - "ts-node": "10.9.1", + "ts-node": "10.9.2", "typescript": "^5.9.0", "vite": "^8.3.0" }, "sentryTest": { - "optional": true + "optional": true, + "optionalVariants": [ + { + "build-command": "pnpm test:build:no-upload", + "assert-command": "pnpm test:assert:no-upload", + "label": "tanstackstart-react-sourcemaps (no upload)" + }, + { + "build-command": "pnpm test:build:manual-upload", + "assert-command": "pnpm test:assert:manual-upload", + "label": "tanstackstart-react-sourcemaps (manual upload)" + }, + { + "build-command": "pnpm test:build:delete-all", + "assert-command": "pnpm test:assert:delete-all", + "label": "tanstackstart-react-sourcemaps (delete all)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts index 34e4c52c56d4..898124522baf 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-sourcemaps/vite.config.ts @@ -2,21 +2,56 @@ import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite'; import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import viteReact from '@vitejs/plugin-react-swc'; import { nitro } from 'nitro/vite'; +import * as fs from 'node:fs'; import { defineConfig } from 'vite'; +// A chunk without mappable source, such as Nitro's runtime, gets a debug ID but no source map to +// upload. Recorded before the Sentry plugin removes the maps in its own `generateBundle` hook. +function recordChunksWithoutSourceMap() { + return { + name: 'record-chunks-without-source-map', + apply: 'build' as const, + generateBundle: { + order: 'pre' as const, + handler(_options: unknown, bundle: Record) { + for (const output of Object.values(bundle)) { + if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) { + continue; + } + for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) { + fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`); + } + } + }, + }, + }; +} + +// `manual-upload`: Sentry uploads nothing and keeps the maps it turned on, for an upload with the CLI. +// `delete-all`: the app turns source maps on itself, and Sentry removes them. +const variant = process.env.E2E_VARIANT; + export default defineConfig({ + build: variant === 'delete-all' ? { sourcemap: true } : undefined, plugins: [ // Prerendering and the SPA shell render pages at build time, which must carry the release as well. tanstackStart({ prerender: { enabled: true }, pages: [{ path: '/prerendered' }], spa: { enabled: true } }), nitro(), viteReact(), + recordChunksWithoutSourceMap(), sentryTanstackStart({ sentryUrl: 'http://localhost:3032', - authToken: 'fake-auth-token', + authToken: process.env.E2E_NO_UPLOAD ? undefined : 'fake-auth-token', org: 'test-org', project: 'test-project', release: { name: 'test-release' }, debug: true, + sourcemaps: + variant === 'manual-upload' + ? { upload: false, delete: false } + : variant === 'delete-all' + ? { delete: true } + : undefined, }), ], }); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json index 878ce6975449..0b9e2a2f6f28 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react-static/package.json @@ -32,7 +32,7 @@ "@vitejs/plugin-react-swc": "^4.3.3", "typescript": "^5.9.0", "vite": "8.3.4", - "vite-tsconfig-paths": "^5.1.4", + "vite-tsconfig-paths": "^6.1.1", "@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/tanstackstart-react/package.json b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json index b6af9d9e98f7..4d127b218501 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/package.json @@ -27,14 +27,14 @@ "mysql": "^2.18.1" }, "devDependencies": { - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@types/node": "^24.10.0", "@vitejs/plugin-react-swc": "^4.3.3", "typescript": "^5.9.0", "vite": "8.3.4", - "vite-tsconfig-paths": "^5.1.4", + "vite-tsconfig-paths": "^6.1.1", "@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/tanstackstart-react/vite.config.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts index 4c290a5899db..6de962e77b3e 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/vite.config.ts @@ -7,21 +7,25 @@ import { nitro } from 'nitro/vite'; import { sentryTanstackStart } from '@sentry/tanstackstart-react/vite'; // Rolldown emits no map for chunks without mappable source (e.g. Vite's preload helper), so their debug -// IDs can't be uploaded. Recorded here because the SDK deletes all maps after the upload. +// IDs can't be uploaded. Recorded here because the Sentry plugin removes the maps from the bundle in its +// own `generateBundle` hook. function recordChunksWithoutSourceMap() { return { name: 'record-chunks-without-source-map', apply: 'build' as const, enforce: 'post' as const, - writeBundle(_options: unknown, bundle: Record) { - for (const output of Object.values(bundle)) { - if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) { - continue; + generateBundle: { + order: 'pre' as const, + handler(_options: unknown, bundle: Record) { + for (const output of Object.values(bundle)) { + if (output.type !== 'chunk' || !output.code || bundle[`${output.fileName}.map`]) { + continue; + } + for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) { + fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`); + } } - for (const match of output.code.matchAll(/sentry-dbid-([\da-f-]{36})/gi)) { - fs.appendFileSync('.tmp_debug_ids_without_source_map', `${match[1]!.toLowerCase()}\n`); - } - } + }, }, }; } diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json index 054fbc9b378d..b15bd7ffb49a 100644 --- a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json +++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/package.json @@ -24,6 +24,7 @@ "@types/node": "^26.1.2", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", + "@vinext/cloudflare": "^1.4.0", "@vitejs/plugin-react": "^6.1.1", "@vitejs/plugin-rsc": "^0.5.35", "react-server-dom-webpack": "^19.3.0", @@ -31,5 +32,14 @@ "vinext": "^1.0.1", "vite": "^8.3.0", "wrangler": "^4.135.0" + }, + "sentryTest": { + "optionalVariants": [ + { + "build-command": "E2E_VINEXT_WORKERS_CACHE=1 pnpm test:build", + "assert-command": "pnpm test tests/page-errors.test.ts", + "label": "vinext-cf-workers (workers cache)" + } + ] } } diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx new file mode 100644 index 000000000000..e1ac01c3a6c3 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/src/app/page-error/page.tsx @@ -0,0 +1,6 @@ +import { connection } from 'next/server'; + +export default async function PageError() { + await connection(); + throw new Error('Page render error from vinext'); +} diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts new file mode 100644 index 000000000000..a476a3059cd9 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from '@playwright/test'; +import { collectStreamedSpans, waitForError } from '@sentry-internal/test-utils'; + +test('Captures an error thrown while a page renders', async ({ request }) => { + const errorPromise = waitForError('vinext-cf-workers', event => { + return event.exception?.values?.[0]?.value === 'Page render error from vinext'; + }); + // vinext's Workers Cache adapter renders the page in a second invocation, whose request URL has a + // `__vinext_cache_key` query parameter. The error must be in the trace of the incoming request. + const requestSpansPromise = collectStreamedSpans('vinext-cf-workers', spans => + spans.some(span => span.is_segment && span.name === 'GET /page-error' && !span.attributes['url.query']), + ); + + const response = await request.get('/page-error'); + expect(response.status()).toBe(500); + + const errorEvent = await errorPromise; + const requestSpans = await requestSpansPromise; + + expect(errorEvent.sdk?.name).toBe('sentry.javascript.nextjs'); + expect(errorEvent.environment).toBe('qa'); + expect(errorEvent.transaction).toBe('GET /page-error'); + expect(errorEvent.exception?.values?.[0]?.mechanism).toEqual({ + handled: false, + type: 'auto.function.nextjs.on_request_error', + }); + expect(errorEvent.contexts?.trace?.trace_id).toBe(requestSpans[0]?.trace_id); +}); diff --git a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts index 6bab8f3b5d74..2659b6c30ad6 100644 --- a/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts +++ b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/vite.config.ts @@ -1,5 +1,6 @@ import { cloudflare } from '@cloudflare/vite-plugin'; import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite'; +import { workersCacheCdnAdapter } from '@vinext/cloudflare/cache/workers-cache-cdn-adapter'; import vinext from 'vinext'; import { defineConfig } from 'vite'; @@ -7,7 +8,9 @@ import { defineConfig } from 'vite'; // `@sentry/nextjs/cloudflare`. export default defineConfig({ plugins: [ - vinext(), + // The `vinext-cf-workers (workers cache)` variant renders cacheable pages in the `VinextCachedResponse` + // entrypoint, which the default export calls through `ctx.exports`. + vinext(process.env.E2E_VINEXT_WORKERS_CACHE ? { cache: { cdn: workersCacheCdnAdapter() } } : {}), cloudflare({ viteEnvironment: { name: 'rsc', childEnvironments: ['ssr'] } }), sentryCloudflareVitePlugin(), ], diff --git a/dev-packages/node-integration-tests/.oxlintrc.json b/dev-packages/node-integration-tests/.oxlintrc.json index 56d441ab0c82..30c28284ed4d 100644 --- a/dev-packages/node-integration-tests/.oxlintrc.json +++ b/dev-packages/node-integration-tests/.oxlintrc.json @@ -20,6 +20,34 @@ ], "import/first": "off" } + }, + { + "files": ["suites/**/test.ts", "suites/**/*.test.ts"], + "rules": { + "no-restricted-properties": [ + "error", + { + "object": "process", + "property": "version", + "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead." + }, + { + "object": "process", + "property": "versions", + "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead." + }, + { + "object": "ctx", + "property": "skip", + "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead." + }, + { + "object": "context", + "property": "skip", + "message": "Gate the test with `test.runIf(supports({ ... }))` from `utils/index.ts` instead." + } + ] + } } ] } diff --git a/dev-packages/node-integration-tests/README.md b/dev-packages/node-integration-tests/README.md index 26b2eab24a81..7442e5c19d67 100644 --- a/dev-packages/node-integration-tests/README.md +++ b/dev-packages/node-integration-tests/README.md @@ -9,7 +9,8 @@ suites/ |---- test.ts [assertions] |---- scenario.ts [Sentry initialization and test subject] |---- customTest/ - |---- test.ts [assertions] + |---- tracing.test.ts [tracing assertions] + |---- errors.test.ts [error assertions] |---- scenario_1.ts [optional extra test scenario] |---- scenario_2.ts [optional extra test scenario] |---- server_with_mongo.ts [optional custom server] @@ -22,12 +23,13 @@ folders containing test scenarios and assertions. `scenario.ts` contains the initialization logic and the test subject. By default, `{TEST_DIR}/scenario.ts` is used, but `runServer` also accepts an optional `scenarioPath` argument for non-standard usage. -`test.ts` is required for each test case, and contains the server runner logic, request interceptors for Sentry -requests, and assertions. Test server, interceptors and assertions are all run on the same Vitest thread. +`test.ts` and descriptive `*.test.ts` files contain the server runner logic, request interceptors for Sentry requests, +and assertions. A suite can use several named test files so Vitest can schedule them independently while sharing +scenario files. Each test's server, interceptors and assertions run on the same Vitest thread. ### Utilities -`utils/` contains helpers and Sentry-specific assertions that can be used in (`test.ts`). +`utils/` contains helpers and Sentry-specific assertions for the test files. Nock interceptors are internally used to capture envelope requests by `getEnvelopeRequest` and `getMultipleEnvelopeRequest` helpers. After capturing required requests, the interceptors are removed. Nock can manually diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json index 0351f33c48fc..0b1488d21a78 100644 --- a/dev-packages/node-integration-tests/package.json +++ b/dev-packages/node-integration-tests/package.json @@ -61,7 +61,7 @@ "@sentry-internal/rollup-utils": "11.17.0", "@sentry-internal/test-utils": "11.17.0", "@sentry/aws-serverless": "11.17.0", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "@sentry/core": "11.17.0", "@sentry/hono": "11.17.0", "@sentry/node": "11.17.0", @@ -124,6 +124,7 @@ "winston": "^3.17.0", "winston-transport": "^4.9.0", "ws": "^8.20.1", + "yaml": "^2.9.0", "yargs": "^18.2.0", "zod": "^4.6.7" }, diff --git a/dev-packages/node-integration-tests/scripts/clean.js b/dev-packages/node-integration-tests/scripts/clean.js index 1c0f4f27c095..f871d809b34f 100644 --- a/dev-packages/node-integration-tests/scripts/clean.js +++ b/dev-packages/node-integration-tests/scripts/clean.js @@ -1,6 +1,7 @@ const { execSync } = require('child_process'); const { globSync, rmSync } = require('fs'); +// `fs.globSync` needs Node 22. This is a local helper, and the repo pins Node 24 in `devEngines`. for (const path of globSync(['suites/**/node_modules', 'suites/**/tmp_*'])) { rmSync(path, { recursive: true, force: true }); } diff --git a/dev-packages/node-integration-tests/src/index.ts b/dev-packages/node-integration-tests/src/index.ts index 57369ec52d92..311805ae4bbb 100644 --- a/dev-packages/node-integration-tests/src/index.ts +++ b/dev-packages/node-integration-tests/src/index.ts @@ -7,6 +7,12 @@ export * from './mocks/anthropic'; export * from './mocks/google'; export * from './mocks/openai'; +/** + * Mirror the feature flag limits in `@sentry/core`. + */ +export const FLAG_BUFFER_SIZE = 100; +export const MAX_FLAGS_PER_SPAN = 10; + /** * Debug logging transport */ diff --git a/dev-packages/node-integration-tests/suites/docker-compose.test.ts b/dev-packages/node-integration-tests/suites/docker-compose.test.ts new file mode 100644 index 000000000000..aed23bd28785 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/docker-compose.test.ts @@ -0,0 +1,39 @@ +import { readdirSync, readFileSync } from 'fs'; +import { join, relative } from 'path'; +import { expect, test } from 'vitest'; +import { parse } from 'yaml'; + +function findComposeFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + if (entry.isDirectory()) { + return entry.name === 'node_modules' || entry.name.startsWith('tmp_') + ? [] + : findComposeFiles(join(dir, entry.name)); + } + return entry.name === 'docker-compose.yml' ? [join(dir, entry.name)] : []; + }); +} + +const composeFiles = findComposeFiles(__dirname); + +// `up --wait` returns as soon as a service without a healthcheck has started, so the test would race +// the service's startup. +test.each(composeFiles.map(file => relative(__dirname, file)))('every service in %s has a healthcheck', file => { + const config = parse(readFileSync(join(__dirname, file), 'utf8')) as { + services?: Record; + }; + + const missing = Object.entries(config.services ?? {}) + .filter(([, service]) => { + const healthcheck = service?.healthcheck; + const command = [healthcheck?.test ?? []].flat(); + return healthcheck?.disable === true || !command[0] || command[0] === 'NONE'; + }) + .map(([name]) => name); + + expect(missing).toEqual([]); +}); + +test('finds the docker-compose files', () => { + expect(composeFiles.length).toBeGreaterThan(0); +}); diff --git a/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts b/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts index 5f52af14aaed..39d605af1c91 100644 --- a/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts +++ b/dev-packages/node-integration-tests/suites/esm/warn-esm/test.ts @@ -5,6 +5,7 @@ afterAll(() => { cleanupChildProcesses(); }); +// eslint-disable-next-line no-restricted-properties -- builds the expected warning text, does not gate the test const esmWarning = `[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`; test('does not warn if using ESM on Node.js versions that support `register()`', async () => { diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts index db7eb3a8815a..da7f756096e8 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/scenario.ts @@ -1,6 +1,5 @@ -import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core'; import * as Sentry from '@sentry/node'; -import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { loggingTransport, FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests'; Sentry.init({ traceLifecycle: 'static', diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts index 74ff1c125b45..edf859217675 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onError/basic/test.ts @@ -1,5 +1,5 @@ -import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core'; import { afterAll, test } from 'vitest'; +import { FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests'; import { cleanupChildProcesses, createRunner } from '../../../../../utils/runner'; afterAll(() => { diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts index 2c07e46b40ed..44e632bf327f 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/scenario.ts @@ -1,6 +1,5 @@ -import { _INTERNAL_MAX_FLAGS_PER_SPAN as MAX_FLAGS_PER_SPAN } from '@sentry/core'; import * as Sentry from '@sentry/node'; -import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { loggingTransport, MAX_FLAGS_PER_SPAN } from '@sentry-internal/node-integration-tests'; Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', diff --git a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts index e2caf9ed4fc1..ade1ea5f9134 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/featureFlagsIntegration/onSpan/test.ts @@ -1,5 +1,5 @@ -import { _INTERNAL_MAX_FLAGS_PER_SPAN as MAX_FLAGS_PER_SPAN } from '@sentry/core'; import { afterAll, expect, test } from 'vitest'; +import { MAX_FLAGS_PER_SPAN } from '@sentry-internal/node-integration-tests'; import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; afterAll(() => { diff --git a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts index 77aa7d912540..ba4f7cdcb5c6 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/scenario.ts @@ -1,8 +1,7 @@ import type { ClientOptions, UserContext } from '@growthbook/growthbook'; import { GrowthBookClient } from '@growthbook/growthbook'; -import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core'; import * as Sentry from '@sentry/node'; -import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import { loggingTransport, FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests'; // Wrapper class to instantiate GrowthBookClient class GrowthBookWrapper { diff --git a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts index 82e39eb62364..4fb9efb6d0d4 100644 --- a/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts +++ b/dev-packages/node-integration-tests/suites/featureFlags/growthbook/onError/basic/test.ts @@ -1,5 +1,5 @@ -import { _INTERNAL_FLAG_BUFFER_SIZE as FLAG_BUFFER_SIZE } from '@sentry/core'; import { afterAll, test } from 'vitest'; +import { FLAG_BUFFER_SIZE } from '@sentry-internal/node-integration-tests'; import { cleanupChildProcesses, createRunner } from '../../../../../utils/runner'; afterAll(() => { diff --git a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts index e4293aa20ea9..fa14a71416dc 100644 --- a/dev-packages/node-integration-tests/suites/hono-sdk/test.ts +++ b/dev-packages/node-integration-tests/suites/hono-sdk/test.ts @@ -1,5 +1,7 @@ import { afterAll, describe, expect } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../utils/runner'; +import { supports } from '../../utils'; +import { HONO_MAJORS } from '../hono/hono-majors'; const ROUTE_NAME_CASES: Array<{ method: 'get' | 'post'; path: string; name: string; route: string }> = [ { method: 'get', path: '/users/me', name: 'GET /users/me', route: '/users/me' }, @@ -15,163 +17,173 @@ const ROUTE_NAME_CASES: Array<{ method: 'get' | 'post'; path: string; name: stri { method: 'get', path: '/outer/self-watering-plant', name: 'GET /outer/:itemId', route: '/outer/:itemId' }, ]; -describe('hono-sdk (Node)', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - let scenario: ReturnType | undefined; - async function runScenario() { - const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ - ...ROUTE_NAME_CASES, - { method: 'get', path: '/does-not-exist', expectError: true }, - { method: 'get', path: '/' }, - { method: 'get', path: '/hello/world' }, - ]; - const runner = createRunner().expect({ - event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' }, - }); - const collectors = requests.map(({ path }) => { - const key = path; - return [ - key, - runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key), - ] as const; - }); +for (const { major, minNode, options } of HONO_MAJORS) { + describe.runIf(supports({ min: minNode }))(`hono-sdk (Node) on Hono ${major}`, () => { + afterAll(() => { + cleanupChildProcesses(); + }); - const started = runner.start(); - for (const { method, path, expectError } of requests) { - await started.makeRequest(method, path, { expectError }); - } - await started.completed(); - return new Map(await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const))); - } - async function getScenario(key: string) { - scenario ??= runScenario(); - return (await scenario).get(key)!; - } + createEsmAndCjsTests( + __dirname, + 'scenario.mjs', + 'instrument.mjs', + (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post' | 'put'; path: string; expectError?: boolean }> = [ + ...ROUTE_NAME_CASES, + { method: 'get', path: '/does-not-exist', expectError: true }, + { method: 'get', path: '/' }, + { method: 'get', path: '/hello/world' }, + ]; + const runner = createRunner().expect({ + event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' }, + }); + const collectors = requests.map(({ path }) => { + const key = path; + return [ + key, + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === key), + ] as const; + }); - test('names each request after the route of the handler that responded', async () => { - for (const { path, name, route } of ROUTE_NAME_CASES) { - const container = await getScenario(path); - const segment = container.items.find(item => item.is_segment && item.name === name); - if (!segment) { - throw new Error(`segment for \`${name}\` not in this container`); + const started = runner.start(); + for (const { method, path, expectError } of requests) { + await started.makeRequest(method, path, { expectError }); + } + await started.completed(); + return new Map( + await Promise.all(collectors.map(async ([key, spans]) => [key, { items: await spans }] as const)), + ); + } + async function getScenario(key: string) { + scenario ??= runScenario(); + return (await scenario).get(key)!; } - expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route }); - expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); - } - }); - test('names an event captured in a route handler after that route', async () => { - const runner = createRunner() - .ignore('span') - .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } }) - .start(); - runner.makeRequest('get', '/users/42/capture'); - await runner.completed(); - }); + test('names each request after the route of the handler that responded', async () => { + for (const { path, name, route } of ROUTE_NAME_CASES) { + const container = await getScenario(path); + const segment = container.items.find(item => item.is_segment && item.name === name); + if (!segment) { + throw new Error(`segment for \`${name}\` not in this container`); + } + expect(segment.attributes?.['http.route']).toEqual({ type: 'string', value: route }); + expect(segment.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); + } + }); - test('keeps the runtime name for a request without a route', async () => { - const container = await getScenario('/does-not-exist'); - const segment = container.items.find(item => item.is_segment); - expect(segment?.name).toBe('GET'); - expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' }); - expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' }); - expect(segment?.attributes?.['http.route']).toBeUndefined(); - }); + test('names an event captured in a route handler after that route', async () => { + const runner = createRunner() + .ignore('span') + .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } }) + .start(); + runner.makeRequest('get', '/users/42/capture'); + await runner.completed(); + }); - test('names an event from the route handler that runs after next() after that route', async () => { - const runner = createRunner() - .ignore('span') - .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } }) - .start(); - runner.makeRequest('get', '/posts/draft'); - await runner.completed(); - }); + test('keeps the runtime name for a request without a route', async () => { + const container = await getScenario('/does-not-exist'); + const segment = container.items.find(item => item.is_segment); + expect(segment?.name).toBe('GET'); + expect(segment?.attributes?.['sentry.segment.name.source']).toEqual({ type: 'string', value: 'url' }); + expect(segment?.attributes?.['url.path']).toEqual({ type: 'string', value: '/does-not-exist' }); + expect(segment?.attributes?.['http.route']).toBeUndefined(); + }); - test('names a HEAD request after the GET route', async () => { - const runner = createRunner() - .ignore('span') - .expect({ - event: { - exception: { values: [{ value: 'Test error from a HEAD request' }] }, - transaction: 'HEAD /head-error/:id', - }, - }) - .start(); - runner.makeRequest('head', '/head-error/1', { expectError: true }); - await runner.completed(); - }); + test('names an event from the route handler that runs after next() after that route', async () => { + const runner = createRunner() + .ignore('span') + .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } }) + .start(); + runner.makeRequest('get', '/posts/draft'); + await runner.completed(); + }); - test('creates a segment span for a basic GET request', async () => { - const container = await getScenario('/'); - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'GET /', - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - }), - }); - }); + test('names a HEAD request after the GET route', async () => { + const runner = createRunner() + .ignore('span') + .expect({ + event: { + exception: { values: [{ value: 'Test error from a HEAD request' }] }, + transaction: 'HEAD /head-error/:id', + }, + }) + .start(); + runner.makeRequest('head', '/head-error/1', { expectError: true }); + await runner.completed(); + }); - test('creates a segment span with a parametrized route name', async () => { - const container = await getScenario('/hello/world'); - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'GET /hello/:name', - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - }), - }); - }); + test('creates a segment span for a basic GET request', async () => { + const container = await getScenario('/'); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'GET /', + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + }), + }); + }); - test('captures an error with the correct mechanism', async () => { - const runner = createRunner() - .ignore('span') - .expect({ - event: { - exception: { - values: [ - { - type: 'Error', - value: 'Test error from Hono app', - mechanism: { - type: 'auto.http.hono.context_error', - handled: false, - }, + test('creates a segment span with a parametrized route name', async () => { + const container = await getScenario('/hello/world'); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'GET /hello/:name', + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + }), + }); + }); + + test('captures an error with the correct mechanism', async () => { + const runner = createRunner() + .ignore('span') + .expect({ + event: { + exception: { + values: [ + { + type: 'Error', + value: 'Test error from Hono app', + mechanism: { + type: 'auto.http.hono.context_error', + handled: false, + }, + }, + ], }, - ], - }, - transaction: 'GET /error/:param', - }, - }) - .start(); - runner.makeRequest('get', '/error/param-123', { expectError: true }); - await runner.completed(); - }); + transaction: 'GET /error/:param', + }, + }) + .start(); + runner.makeRequest('get', '/error/param-123', { expectError: true }); + await runner.completed(); + }); - test('creates a segment span with error status when an error occurs', async () => { - const runner = createRunner() - .ignore('event') - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'GET /error/:param', - status: 'error', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.status.message': { type: 'string', value: 'internal_error' }, - 'http.response.status_code': { type: 'integer', value: 500 }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/error/param-456', { expectError: true }); - await runner.completed(); - }); + test('creates a segment span with error status when an error occurs', async () => { + const runner = createRunner() + .ignore('event') + .expect({ + span: container => { + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'GET /error/:param', + status: 'error', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.status.message': { type: 'string', value: 'internal_error' }, + 'http.response.status_code': { type: 'integer', value: 500 }, + }), + }); + }, + }) + .start(); + runner.makeRequest('get', '/error/param-456', { expectError: true }); + await runner.completed(); + }); + }, + options, + ); }); -}); +} diff --git a/dev-packages/node-integration-tests/suites/hono/hono-majors.ts b/dev-packages/node-integration-tests/suites/hono/hono-majors.ts new file mode 100644 index 000000000000..0e19ca53bad9 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/hono/hono-majors.ts @@ -0,0 +1,26 @@ +import { SUPPORTS_REQUIRE_OF_ESM } from '../../utils'; + +type HonoMajor = { + major: 4 | 5; + minNode?: number; + options: { + /** Installed in the tmp dir of the suite. Without them, the scenario uses the root dependencies. */ + additionalDependencies?: Record; + failsOnCjs?: boolean; + }; +}; + +// Exact versions: these are required CI jobs, so a new Hono release must not break them. +// The Hono E2E apps use version ranges and show new releases. +export const HONO_MAJORS: HonoMajor[] = [ + { major: 4, options: {} }, + { + major: 5, + minNode: 22, + options: { + additionalDependencies: { hono: '5.0.0-rc.1', '@hono/node-server': '2.1.7' }, + // Hono 5 ships only ES modules, and not every runtime can `require()` them. + failsOnCjs: !SUPPORTS_REQUIRE_OF_ESM, + }, + }, +]; diff --git a/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs b/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs new file mode 100644 index 000000000000..25bf91c46f6c --- /dev/null +++ b/dev-packages/node-integration-tests/suites/hono/scenario-error-middleware.mjs @@ -0,0 +1,43 @@ +import { serve } from '@hono/node-server'; +import * as Sentry from '@sentry/node'; +import { sendPortToRunner } from '@sentry-internal/node-integration-tests'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +// Hono 5 only: `onError()` and `notFound()` register `(c, next)` middleware that reads the error from +// `c.error`. `honoMiddleware(app)` installs the route hook, so the sub-app below is instrumented at mount. +const app = new Hono(); +app.use(Sentry.honoMiddleware(app)); + +app.notFound('/not-found-error/*', () => { + throw new Error('Error from a not-found handler'); +}); +app.notFound('/not-found-http-exception/*', () => { + throw new HTTPException(404, { message: 'Not found from a not-found handler' }); +}); + +app.get('/replace-error', () => { + throw new Error('Original error from a route handler'); +}); +app.onError('/replace-error', c => { + throw new Error('Replacement error from an error handler', { cause: c.error }); +}); + +const subApp = new Hono(); +subApp.use(async function subAppMiddleware(_c, next) { + await next(); +}); +subApp.onError( + async function errorMiddleware(_c, next) { + await next(); + }, + c => c.text('Handled by the sub-app error handler', 500), +); +subApp.get('/fail', () => { + throw new Error('Error from a sub-app route'); +}); +app.route('/sub', subApp); + +serve({ fetch: app.fetch, port: 0 }, info => { + sendPortToRunner(info.port); +}); diff --git a/dev-packages/node-integration-tests/suites/hono/test.ts b/dev-packages/node-integration-tests/suites/hono/test.ts index 2ccb6a2f24f8..61efd29b8246 100644 --- a/dev-packages/node-integration-tests/suites/hono/test.ts +++ b/dev-packages/node-integration-tests/suites/hono/test.ts @@ -1,5 +1,9 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { MIDDLEWARE } from '@sentry/conventions/op'; import { afterAll, describe, expect } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../utils/runner'; +import { supports } from '../../utils'; +import { HONO_MAJORS } from './hono-majors'; // Verifies that Hono is auto-instrumented out of the box by `@sentry/node` (the `honoIntegration` // default), without importing `@sentry/hono` or registering the `sentry()` middleware manually. @@ -50,344 +54,445 @@ function segmentNamed(name: string, route: string): { span: (container: { items: }; } -describe('hono auto-instrumentation', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - let scenario: ReturnType | undefined; - async function runScenario() { - const requests: Array<{ method: 'get' | 'post'; path: string; expectError?: boolean }> = [ - ...ROUTE_NAME_CASES, - { method: 'get', path: '/traced/1' }, - { method: 'get', path: '/does-not-exist', expectError: true }, - { method: 'get', path: '/' }, - { method: 'get', path: '/hello/world' }, - { method: 'get', path: '/arity-two-handler' }, - { method: 'get', path: '/test-basepath-mw/hello' }, - { method: 'get', path: '/sub/hello' }, - { method: 'get', path: '/outer/self-watering-plant' }, - ]; - const uniqueRequests = new Map(requests.map(request => [request.path, request])); - const runner = createRunner().unordered(); - const collectors = [...uniqueRequests.keys()].map( - path => [path, runner.collectStreamedSpansUntilSegment(span => attr(span, 'url.path') === path)] as const, - ); - const started = runner.start(); - for (const { method, path, expectError } of uniqueRequests.values()) { - await started.makeRequest(method, path, { expectError }); - } - await started.completed(); - return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); - } - async function getSpans(path: string) { - scenario ??= runScenario(); - return (await scenario).get(path)!; - } - - test('names each request after the route of the handler that responded', async () => { - for (const { path, name, route } of ROUTE_NAME_CASES) { - segmentNamed(name, route).span({ items: await getSpans(path) }); - } - }); - - test('names an event captured in a route handler after that route', async () => { - const runner = createRunner() - .ignore('span') - .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } }) - .start(); - runner.makeRequest('get', '/users/42/capture'); - await runner.completed(); - }); - - test('does not rename a span that a middleware starts around the route handler', async () => { - const container = { items: await getSpans('/traced/1') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id'); - if (!segment) { - throw new Error('segment for `GET /traced/:id` not in this container'); - } - expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1); - }); - - test('keeps the runtime name for a request without a route', async () => { - const container = { items: await getSpans('/does-not-exist') }; - - const segment = container.items.find(item => item.is_segment && attr(item, 'url.path') === '/does-not-exist'); - if (!segment) { - throw new Error('segment for `/does-not-exist` not in this container'); - } - expect(segment.name).toBe('GET'); - expect(attr(segment, 'sentry.segment.name.source')).toBe('url'); - expect(attr(segment, 'http.route')).toBeUndefined(); +for (const { major, minNode, options } of HONO_MAJORS) { + describe.runIf(supports({ min: minNode }))(`hono auto-instrumentation on Hono ${major}`, () => { + afterAll(() => { + cleanupChildProcesses(); }); - test('names an event from the route handler that runs after next() after that route', async () => { - const runner = createRunner() - .ignore('span') - .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } }) - .start(); - runner.makeRequest('get', '/posts/draft'); - await runner.completed(); - }); - - test('names a HEAD request after the GET route', async () => { - const runner = createRunner() - .unordered() - .expect({ - event: { - exception: { values: [{ value: 'Test error from a HEAD request' }] }, - transaction: 'HEAD /head-error/:id', - }, - }) - .start(); - runner.makeRequest('head', '/head-error/1', { expectError: true }); - await runner.completed(); - }); - - test('creates a transaction for a basic GET request', async () => { - const container = { items: await getSpans('/') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /'); - if (!segment) { - throw new Error('segment for `GET /` not in this container'); - } - expect(op(segment)).toBe('http.server'); - expect(segment.status).toBe('ok'); - }); - - test('creates a transaction with a parametrized route name', async () => { - const container = { items: await getSpans('/hello/world') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name'); - if (!segment) { - throw new Error('segment for `GET /hello/:name` not in this container'); - } - expect(op(segment)).toBe('http.server'); - expect(attr(segment, 'sentry.segment.name.source')).toBe('route'); - }); - - test('captures an error with the correct mechanism', async () => { - const runner = createRunner() - .unordered() - .expect({ - event: { - exception: { - values: [ - { - type: 'Error', - value: 'Test error from Hono app', - mechanism: { - type: 'auto.http.hono.context_error', - handled: false, - }, + createEsmAndCjsTests( + __dirname, + 'scenario.mjs', + 'instrument.mjs', + (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const requests: Array<{ method: 'get' | 'post'; path: string; expectError?: boolean }> = [ + ...ROUTE_NAME_CASES, + { method: 'get', path: '/traced/1' }, + { method: 'get', path: '/does-not-exist', expectError: true }, + { method: 'get', path: '/' }, + { method: 'get', path: '/hello/world' }, + { method: 'get', path: '/arity-two-handler' }, + { method: 'get', path: '/test-basepath-mw/hello' }, + { method: 'get', path: '/sub/hello' }, + { method: 'get', path: '/outer/self-watering-plant' }, + ]; + const uniqueRequests = new Map(requests.map(request => [request.path, request])); + const runner = createRunner().unordered(); + const collectors = [...uniqueRequests.keys()].map( + path => [path, runner.collectStreamedSpansUntilSegment(span => attr(span, 'url.path') === path)] as const, + ); + const started = runner.start(); + for (const { method, path, expectError } of uniqueRequests.values()) { + await started.makeRequest(method, path, { expectError }); + } + await started.completed(); + return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); + } + async function getSpans(path: string) { + scenario ??= runScenario(); + return (await scenario).get(path)!; + } + + test('names each request after the route of the handler that responded', async () => { + for (const { path, name, route } of ROUTE_NAME_CASES) { + segmentNamed(name, route).span({ items: await getSpans(path) }); + } + }); + + test('names an event captured in a route handler after that route', async () => { + const runner = createRunner() + .ignore('span') + .expect({ event: { message: 'Message from a route handler', transaction: 'GET /users/:id/capture' } }) + .start(); + runner.makeRequest('get', '/users/42/capture'); + await runner.completed(); + }); + + test('does not rename a span that a middleware starts around the route handler', async () => { + const container = { items: await getSpans('/traced/1') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /traced/:id'); + if (!segment) { + throw new Error('segment for `GET /traced/:id` not in this container'); + } + expect(container.items.filter(item => item.name === 'user span')).toHaveLength(1); + }); + + test('keeps the runtime name for a request without a route', async () => { + const container = { items: await getSpans('/does-not-exist') }; + + const segment = container.items.find(item => item.is_segment && attr(item, 'url.path') === '/does-not-exist'); + if (!segment) { + throw new Error('segment for `/does-not-exist` not in this container'); + } + expect(segment.name).toBe('GET'); + expect(attr(segment, 'sentry.segment.name.source')).toBe('url'); + expect(attr(segment, 'http.route')).toBeUndefined(); + }); + + test('names an event from the route handler that runs after next() after that route', async () => { + const runner = createRunner() + .ignore('span') + .expect({ event: { message: 'Message from a route handler after next()', transaction: 'GET /posts/*' } }) + .start(); + runner.makeRequest('get', '/posts/draft'); + await runner.completed(); + }); + + test('names a HEAD request after the GET route', async () => { + const runner = createRunner() + .unordered() + .expect({ + event: { + exception: { values: [{ value: 'Test error from a HEAD request' }] }, + transaction: 'HEAD /head-error/:id', + }, + }) + .start(); + runner.makeRequest('head', '/head-error/1', { expectError: true }); + await runner.completed(); + }); + + test('creates a transaction for a basic GET request', async () => { + const container = { items: await getSpans('/') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /'); + if (!segment) { + throw new Error('segment for `GET /` not in this container'); + } + expect(op(segment)).toBe('http.server'); + expect(segment.status).toBe('ok'); + }); + + test('creates a transaction with a parametrized route name', async () => { + const container = { items: await getSpans('/hello/world') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /hello/:name'); + if (!segment) { + throw new Error('segment for `GET /hello/:name` not in this container'); + } + expect(op(segment)).toBe('http.server'); + expect(attr(segment, 'sentry.segment.name.source')).toBe('route'); + }); + + test('captures an error with the correct mechanism', async () => { + const runner = createRunner() + .unordered() + .expect({ + event: { + exception: { + values: [ + { + type: 'Error', + value: 'Test error from Hono app', + mechanism: { + type: 'auto.http.hono.context_error', + handled: false, + }, + }, + ], }, - ], - }, - transaction: 'GET /error/:param', - }, - }) - .start(); - runner.makeRequest('get', '/error/param-123', { expectError: true }); - await runner.completed(); - }); - - test('creates a transaction with internal_error status when an error occurs', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const segment = container.items.find(item => item.is_segment && item.name === 'GET /error/:param'); - if (!segment) { - throw new Error('segment for `GET /error/:param` not in this container'); - } - expect(op(segment)).toBe('http.server'); - expect(segment.status).toBe('error'); - expect(attr(segment, 'http.response.status_code')).toBe(500); - }, - }) - .start(); - runner.makeRequest('get', '/error/param-456', { expectError: true }); - await runner.completed(); - }); - - test('does not wrap a route handler declared with an unused next param as middleware', async () => { - const container = { items: await getSpans('/arity-two-handler') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler'); - if (!segment) { - throw new Error('segment for `GET /arity-two-handler` not in this container'); - } - // The arity-2 handler is the route handler (last in its method+path group), so it must not - // produce a middleware span. - const middlewareSpans = container.items.filter(item => op(item) === 'middleware'); - expect(middlewareSpans).toHaveLength(0); - }); - - test('creates a middleware span for .use() on a .basePath() clone', async () => { - const container = { items: await getSpans('/test-basepath-mw/hello') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /test-basepath-mw/hello'); - if (!segment) { - throw new Error('segment for `GET /test-basepath-mw/hello` not in this container'); - } - const middlewareSpan = container.items.find( - item => op(item) === 'middleware' && item.name === 'basepathMiddleware', - ); - expect(middlewareSpan).toBeDefined(); - expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono'); - }); - - test('does not create a middleware span for the Sentry middleware in a mounted sub-app', async () => { - const container = { items: await getSpans('/sub/hello') }; - - const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello'); - if (!segment) { - throw new Error('segment for `GET /sub/hello` not in this container'); - } - const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); - // The sub-app's user middleware is traced … - expect(middlewareNames).toContain('subMiddleware'); - // … but the sub-app's own auto-registered Sentry middleware must not appear as a span - // (it is copied into the parent at mount time and must stay unwrapped). - expect(middlewareNames).not.toContain(''); - }); - - test('traces an internal .request() call without the inner app re-instrumenting the request', async () => { - const container = { items: await getSpans('/outer/self-watering-plant') }; - - // Transaction is named after the outer route, not the internal one. - const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId'); - if (!segment) { - throw new Error('segment for `GET /outer/:itemId` not in this container'); - } + transaction: 'GET /error/:param', + }, + }) + .start(); + runner.makeRequest('get', '/error/param-123', { expectError: true }); + await runner.completed(); + }); + + test('creates a transaction with internal_error status when an error occurs', async () => { + const runner = createRunner() + .unordered() + .expect({ + span: container => { + const segment = container.items.find(item => item.is_segment && item.name === 'GET /error/:param'); + if (!segment) { + throw new Error('segment for `GET /error/:param` not in this container'); + } + expect(op(segment)).toBe('http.server'); + expect(segment.status).toBe('error'); + expect(attr(segment, 'http.response.status_code')).toBe(500); + }, + }) + .start(); + runner.makeRequest('get', '/error/param-456', { expectError: true }); + await runner.completed(); + }); + + test('does not wrap a route handler declared with an unused next param as middleware', async () => { + const container = { items: await getSpans('/arity-two-handler') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /arity-two-handler'); + if (!segment) { + throw new Error('segment for `GET /arity-two-handler` not in this container'); + } + // The arity-2 handler is the route handler (last in its method+path group), so it must not + // produce a middleware span. + const middlewareSpans = container.items.filter(item => op(item) === 'middleware'); + expect(middlewareSpans).toHaveLength(0); + }); + + test('creates a middleware span for .use() on a .basePath() clone', async () => { + const container = { items: await getSpans('/test-basepath-mw/hello') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /test-basepath-mw/hello'); + if (!segment) { + throw new Error('segment for `GET /test-basepath-mw/hello` not in this container'); + } + const middlewareSpan = container.items.find( + item => op(item) === 'middleware' && item.name === 'basepathMiddleware', + ); + expect(middlewareSpan).toBeDefined(); + expect(attr(middlewareSpan!, 'sentry.origin')).toBe('auto.middleware.hono'); + }); + + test('does not create a middleware span for the Sentry middleware in a mounted sub-app', async () => { + const container = { items: await getSpans('/sub/hello') }; + + const segment = container.items.find(item => item.is_segment && item.name === 'GET /sub/hello'); + if (!segment) { + throw new Error('segment for `GET /sub/hello` not in this container'); + } + const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); + // The sub-app's user middleware is traced … + expect(middlewareNames).toContain('subMiddleware'); + // … but the sub-app's own auto-registered Sentry middleware must not appear as a span + // (it is copied into the parent at mount time and must stay unwrapped). + expect(middlewareNames).not.toContain(''); + }); + + test('traces an internal .request() call without the inner app re-instrumenting the request', async () => { + const container = { items: await getSpans('/outer/self-watering-plant') }; + + // Transaction is named after the outer route, not the internal one. + const segment = container.items.find(item => item.is_segment && item.name === 'GET /outer/:itemId'); + if (!segment) { + throw new Error('segment for `GET /outer/:itemId` not in this container'); + } + + // The internal dispatch is traced with the raw inner path — the inner app's Sentry + // middleware must not re-name it to the parametrized route. + const internalRequestSpans = container.items.filter( + item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request', + ); + expect(internalRequestSpans).toHaveLength(1); + expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant'); + + // The inner app's Sentry middleware must not add a middleware span. + const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); + expect(middlewareNames).not.toContain(''); + }); + + test('captures an error thrown inside an internal .request() even when the outer handler degrades to 200', async () => { + const runner = createRunner() + .unordered() + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('inventory db is down'); + expect(event.exception?.values?.[0]?.mechanism).toEqual( + expect.objectContaining({ type: 'auto.http.hono.context_error', handled: false }), + ); + }, + }) + .start(); + runner.makeRequest('get', '/degraded/self-watering-plant'); + await runner.completed(); + }); + + test('captures an error thrown after an internal .request() with the outer request data', async () => { + const runner = createRunner() + .unordered() + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe( + 'Test error from outer Hono app after internal request', + ); + // The internal `.request()` dispatch must not overwrite the request data with its own URL. + expect(event.request?.url).toContain('/outer-error/self-watering-plant'); + expect(event.request?.url).not.toContain('/item/'); + }, + }) + .start(); + runner.makeRequest('get', '/outer-error/self-watering-plant', { expectError: true }); + await runner.completed(); + }); + + test('does not set the middleware span to error for a 3xx middleware error', async () => { + const runner = createRunner() + .unordered() + .expect({ + span: container => { + const middlewareSpan = container.items.find( + item => op(item) === 'middleware' && item.name === 'throwingMiddleware', + ); + if (!middlewareSpan) { + throw new Error('middleware span `throwingMiddleware` not in this container'); + } + expect(middlewareSpan.status).not.toBe('error'); + }, + }) + .start(); + runner.makeRequest('get', '/mw-throw/301', { expectError: true }); + await runner.completed(); + }); + + test('does not set the middleware span to error for a 4xx middleware error', async () => { + const runner = createRunner() + .unordered() + .expect({ + span: container => { + const middlewareSpan = container.items.find( + item => op(item) === 'middleware' && item.name === 'throwingMiddleware', + ); + if (!middlewareSpan) { + throw new Error('middleware span `throwingMiddleware` not in this container'); + } + expect(middlewareSpan.status).not.toBe('error'); + }, + }) + .start(); + runner.makeRequest('get', '/mw-throw/404', { expectError: true }); + await runner.completed(); + }); + + test('sets the middleware span to error for a 5xx middleware error', async () => { + const runner = createRunner() + .unordered() + .expect({ + span: container => { + const middlewareSpan = container.items.find( + item => op(item) === 'middleware' && item.name === 'throwingMiddleware', + ); + if (!middlewareSpan) { + throw new Error('middleware span `throwingMiddleware` not in this container'); + } + expect(middlewareSpan.status).toBe('error'); + }, + }) + .start(); + runner.makeRequest('get', '/mw-throw/503', { expectError: true }); + await runner.completed(); + }); + }, + options, + ); + }); +} - // The internal dispatch is traced with the raw inner path — the inner app's Sentry - // middleware must not re-name it to the parametrized route. - const internalRequestSpans = container.items.filter( - item => attr(item, 'sentry.origin') === 'auto.http.hono.internal_request', +for (const { major, minNode, options } of HONO_MAJORS) { + describe.runIf(supports({ min: minNode }))( + `hono auto-instrumentation with honoMiddleware(app) on Hono ${major}`, + () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests( + __dirname, + 'scenario-honoMiddleware.mjs', + 'instrument.mjs', + (createRunner, test) => { + test('wraps route handlers only when more than one matches, and only once', async () => { + const runner = createRunner() + .unordered() + .expect(segmentNamed('GET /users/me', '/users/me')) + .expect(segmentNamed('GET /posts/:id', '/posts/:id')) + .expect(segmentNamed('GET /posts/:id', '/posts/:id')) + .expect(segmentNamed('GET /posts/*', '/posts/*')) + .start(); + + expect(await runner.makeRequest('get', '/users/me')).toEqual({ wrappers: 0 }); + // The second request gets the same cached handler list. + expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 }); + expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 }); + expect(await runner.makeRequest('get', '/posts/draft')).toEqual({ wrappers: 1 }); + await runner.completed(); + }); + }, + options, ); - expect(internalRequestSpans).toHaveLength(1); - expect(internalRequestSpans[0]?.name).toBe('GET /item/self-watering-plant'); - - // The inner app's Sentry middleware must not add a middleware span. - const middlewareNames = container.items.filter(item => op(item) === 'middleware').map(item => item.name); - expect(middlewareNames).not.toContain(''); - }); - - test('captures an error thrown inside an internal .request() even when the outer handler degrades to 200', async () => { - const runner = createRunner() - .unordered() - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('inventory db is down'); - expect(event.exception?.values?.[0]?.mechanism).toEqual( - expect.objectContaining({ type: 'auto.http.hono.context_error', handled: false }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/degraded/self-watering-plant'); - await runner.completed(); - }); - - test('captures an error thrown after an internal .request() with the outer request data', async () => { - const runner = createRunner() - .unordered() - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('Test error from outer Hono app after internal request'); - // The internal `.request()` dispatch must not overwrite the request data with its own URL. - expect(event.request?.url).toContain('/outer-error/self-watering-plant'); - expect(event.request?.url).not.toContain('/item/'); - }, - }) - .start(); - runner.makeRequest('get', '/outer-error/self-watering-plant', { expectError: true }); - await runner.completed(); - }); - - test('does not set the middleware span to error for a 3xx middleware error', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const middlewareSpan = container.items.find( - item => op(item) === 'middleware' && item.name === 'throwingMiddleware', - ); - if (!middlewareSpan) { - throw new Error('middleware span `throwingMiddleware` not in this container'); - } - expect(middlewareSpan.status).not.toBe('error'); - }, - }) - .start(); - runner.makeRequest('get', '/mw-throw/301', { expectError: true }); - await runner.completed(); - }); - - test('does not set the middleware span to error for a 4xx middleware error', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const middlewareSpan = container.items.find( - item => op(item) === 'middleware' && item.name === 'throwingMiddleware', - ); - if (!middlewareSpan) { - throw new Error('middleware span `throwingMiddleware` not in this container'); - } - expect(middlewareSpan.status).not.toBe('error'); - }, - }) - .start(); - runner.makeRequest('get', '/mw-throw/404', { expectError: true }); - await runner.completed(); - }); + }, + ); +} - test('sets the middleware span to error for a 5xx middleware error', async () => { - const runner = createRunner() - .unordered() - .expect({ - span: container => { - const middlewareSpan = container.items.find( - item => op(item) === 'middleware' && item.name === 'throwingMiddleware', - ); - if (!middlewareSpan) { - throw new Error('middleware span `throwingMiddleware` not in this container'); - } - expect(middlewareSpan.status).toBe('error'); - }, - }) - .start(); - runner.makeRequest('get', '/mw-throw/503', { expectError: true }); - await runner.completed(); +// Hono 5 runs `onError()` and `notFound()` handlers as `(c, next)` middleware. Hono 4 has no such +// middleware, so these cases run only on Hono 5. +for (const { minNode, options } of HONO_MAJORS.filter(({ major }) => major === 5)) { + describe.runIf(supports({ min: minNode }))('hono error and not-found middleware on Hono 5', () => { + afterAll(() => { + cleanupChildProcesses(); }); - }); -}); - -describe('hono auto-instrumentation with honoMiddleware(app)', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - createEsmAndCjsTests(__dirname, 'scenario-honoMiddleware.mjs', 'instrument.mjs', (createRunner, test) => { - test('wraps route handlers only when more than one matches, and only once', async () => { - const runner = createRunner() - .unordered() - .expect(segmentNamed('GET /users/me', '/users/me')) - .expect(segmentNamed('GET /posts/:id', '/posts/:id')) - .expect(segmentNamed('GET /posts/:id', '/posts/:id')) - .expect(segmentNamed('GET /posts/*', '/posts/*')) - .start(); - - expect(await runner.makeRequest('get', '/users/me')).toEqual({ wrappers: 0 }); - // The second request gets the same cached handler list. - expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 }); - expect(await runner.makeRequest('get', '/posts/1')).toEqual({ wrappers: 1 }); - expect(await runner.makeRequest('get', '/posts/draft')).toEqual({ wrappers: 1 }); - await runner.completed(); - }); + createEsmAndCjsTests( + __dirname, + 'scenario-error-middleware.mjs', + 'instrument.mjs', + (createRunner, test) => { + test('captures an error from a not-found handler, but not a 404 HTTPException', async () => { + // In this order, an event for the 404 would arrive first and fail the expectation. + const runner = createRunner() + .ignore('span') + .expect({ + event: { + exception: { + values: [ + { + type: 'Error', + value: 'Error from a not-found handler', + mechanism: { type: 'auto.http.hono.context_error', handled: false }, + }, + ], + }, + }, + }) + .start(); + await runner.makeRequest('get', '/not-found-http-exception/1', { expectError: true }); + await runner.makeRequest('get', '/not-found-error/1', { expectError: true }); + await runner.completed(); + }); + + test('captures the error that an error handler throws, with the original error as its cause', async () => { + const runner = createRunner() + .ignore('span') + .expect({ + event: { + exception: { + values: [ + { + value: 'Original error from a route handler', + mechanism: { exception_id: 1, handled: true, parent_id: 0, source: 'cause', type: 'chained' }, + }, + { + value: 'Replacement error from an error handler', + mechanism: { exception_id: 0, handled: false, type: 'auto.http.hono.context_error' }, + }, + ], + }, + transaction: 'GET /replace-error', + }, + }) + .start(); + await runner.makeRequest('get', '/replace-error', { expectError: true }); + await runner.completed(); + }); + + test('does not create a middleware span for error middleware in a sub-app', async () => { + const runner = createRunner().unordered(); + const spans = runner.collectStreamedSpansUntilSegment(span => attr(span, URL_PATH) === '/sub/fail'); + const started = runner.start(); + await started.makeRequest('get', '/sub/fail', { expectError: true }); + await started.completed(); + + const items = await spans; + expect(items.find(item => item.is_segment)?.name).toBe('GET /sub/fail'); + const middlewareNames = items.filter(item => op(item) === MIDDLEWARE).map(item => item.name); + expect(middlewareNames).toContain('subAppMiddleware'); + expect(middlewareNames).not.toContain('errorMiddleware'); + }); + }, + options, + ); }); -}); +} diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json new file mode 100644 index 000000000000..3dbc1ca591c0 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/dev-packages/node-integration-tests/suites/modules/instrument.mjs b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js similarity index 53% rename from dev-packages/node-integration-tests/suites/modules/instrument.mjs rename to dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js index c8cdc9cac0a2..115249cf6d38 100644 --- a/dev-packages/node-integration-tests/suites/modules/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/lib/scenario.js @@ -1,11 +1,11 @@ import * as Sentry from '@sentry/node'; import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import 'esm-app-transitive'; Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', transport: loggingTransport, - // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to - // capture the thrown route error this test inspects. - integrations: [Sentry.expressIntegration()], }); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/esm-app/package.json b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json new file mode 100644 index 000000000000..7c4e56ac3728 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/esm-app/package.json @@ -0,0 +1,10 @@ +{ + "name": "esm-app", + "private": true, + "dependencies": { + "esm-app-dependency": "^1.0.0" + }, + "devDependencies": { + "esm-app-missing-dependency": "^2.0.0" + } +} diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.js b/dev-packages/node-integration-tests/suites/modules/scenario.js new file mode 100644 index 000000000000..fc966f0457fb --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/scenario.js @@ -0,0 +1,12 @@ +const { loggingTransport } = require('@sentry-internal/node-integration-tests'); +const Sentry = require('@sentry/node'); + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, +}); + +require('express'); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/scenario.mjs b/dev-packages/node-integration-tests/suites/modules/scenario.mjs new file mode 100644 index 000000000000..874679d5b877 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/modules/scenario.mjs @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; +import 'express'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, +}); + +Sentry.captureException(new Error('error_1')); diff --git a/dev-packages/node-integration-tests/suites/modules/server.js b/dev-packages/node-integration-tests/suites/modules/server.js deleted file mode 100644 index bf5ec659e060..000000000000 --- a/dev-packages/node-integration-tests/suites/modules/server.js +++ /dev/null @@ -1,23 +0,0 @@ -const { loggingTransport } = require('@sentry-internal/node-integration-tests'); -const Sentry = require('@sentry/node'); - -Sentry.init({ - dsn: 'https://public@dsn.ingest.sentry.io/1337', - release: '1.0', - transport: loggingTransport, - // Tracing is off, so `expressIntegration()` is not a default integration; opt in explicitly to - // capture the thrown route error this test inspects. - integrations: [Sentry.expressIntegration()], -}); - -// express must be required after Sentry is initialized -const express = require('express'); -const { startExpressServerAndSendPortToRunner } = require('@sentry-internal/node-integration-tests'); - -const app = express(); - -app.get('/test1', () => { - throw new Error('error_1'); -}); - -startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/modules/server.mjs b/dev-packages/node-integration-tests/suites/modules/server.mjs deleted file mode 100644 index d34710e81dad..000000000000 --- a/dev-packages/node-integration-tests/suites/modules/server.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests'; -import express from 'express'; - -const app = express(); - -app.get('/test1', () => { - throw new Error('error_1'); -}); - -startExpressServerAndSendPortToRunner(app); diff --git a/dev-packages/node-integration-tests/suites/modules/test.ts b/dev-packages/node-integration-tests/suites/modules/test.ts index 5e6b65cc8672..cee120ea4f03 100644 --- a/dev-packages/node-integration-tests/suites/modules/test.ts +++ b/dev-packages/node-integration-tests/suites/modules/test.ts @@ -1,35 +1,42 @@ import { SDK_VERSION } from '@sentry/core'; -import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'fs'; +import { copyFileSync, cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs'; import { dirname, join } from 'path'; import { afterAll, describe, expect, test } from 'vitest'; import { cleanupChildProcesses, createRunner } from '../../utils/runner'; +// Each test writes its packages into a folder of its own, because the Bun integration tests run this suite in +// several projects at the same time. +function makeTempDir(): string { + return mkdtempSync(join(__dirname, 'tmp-')); +} + describe('modulesIntegration', () => { afterAll(() => { cleanupChildProcesses(); }); test('CJS', async () => { - const runner = createRunner(__dirname, 'server.js') - .withMockSentryServer() + await createRunner(__dirname, 'scenario.js') .expect({ event: { modules: { - // exact version comes from require.caches express: expect.stringMatching(/^4\.\d+\.\d+$/), - // this comes from package.json '@sentry/node': SDK_VERSION, - yargs: '^18.2.0', + // Declared in package.json and installed, but never loaded + yargs: expect.stringMatching(/^18\.\d+\.\d+$/), + // Not declared, but loaded by express, so it is in require.cache + finalhandler: expect.stringMatching(/^\d+\.\d+\.\d+$/), }, }, }) - .start(); - runner.makeRequest('get', '/test1', { expectError: true }); - await runner.completed(); + .start() + .completed(); }); test('CJS with the isolated layouts of pnpm and Bun', async () => { - const nodeModulesDir = join(__dirname, 'node_modules'); + const tempDir = makeTempDir(); + copyFileSync(join(__dirname, 'scenario-isolated.js'), join(tempDir, 'scenario-isolated.js')); + const nodeModulesDir = join(tempDir, 'node_modules'); for (const [storeDir, name, version, linked] of [ ['.pnpm', 'pnpm-isolated-package', '1.2.3', true], // Only a dependency of the app uses this version, so it is not linked into `node_modules` @@ -50,7 +57,7 @@ describe('modulesIntegration', () => { } try { - await createRunner(__dirname, 'scenario-isolated.js') + await createRunner(tempDir, 'scenario-isolated.js') .expect({ event: { modules: { @@ -64,26 +71,58 @@ describe('modulesIntegration', () => { .start() .completed(); } finally { - rmSync(nodeModulesDir, { recursive: true, force: true }); + rmSync(tempDir, { recursive: true, force: true }); } }); test('ESM', async () => { - const runner = createRunner(__dirname, 'server.mjs') - .withInstrument(join(__dirname, 'instrument.mjs')) - .withMockSentryServer() + await createRunner(__dirname, 'scenario.mjs') .expect({ event: { modules: { - // this comes from package.json - express: expect.stringMatching(/^\^4\.\d+\.\d+$/), + express: expect.stringMatching(/^4\.\d+\.\d+$/), '@sentry/node': SDK_VERSION, - yargs: '^18.2.0', + yargs: expect.stringMatching(/^18\.\d+\.\d+$/), }, }, }) - .start(); - runner.makeRequest('get', '/test1', { expectError: true }); - await runner.completed(); + .start() + .completed(); + }); + + test('ESM app in a subfolder with its own package.json', async () => { + const tempDir = makeTempDir(); + const appDir = join(tempDir, 'esm-app'); + cpSync(join(__dirname, 'esm-app'), appDir, { recursive: true }); + const packageDir = join(appDir, 'node_modules', 'esm-app-dependency'); + mkdirSync(packageDir, { recursive: true }); + writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name: 'esm-app-dependency', version: '1.4.0' })); + // A CommonJS package that the app imports but does not declare, like a transitive dependency + const transitiveDir = join(appDir, 'node_modules', 'esm-app-transitive'); + mkdirSync(transitiveDir, { recursive: true }); + writeFileSync( + join(transitiveDir, 'package.json'), + JSON.stringify({ name: 'esm-app-transitive', version: '3.1.0' }), + ); + writeFileSync(join(transitiveDir, 'index.js'), 'module.exports = {};'); + + try { + await createRunner(appDir, 'lib', 'scenario.js') + .expect({ + event: event => { + // Packages the SDK itself loads from the repo's node_modules can show up too + expect(event.modules).toMatchObject({ + 'esm-app-dependency': '1.4.0', + 'esm-app-transitive': '3.1.0', + // Not installed, so the range from package.json is all there is + 'esm-app-missing-dependency': '^2.0.0', + }); + }, + }) + .start() + .completed(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts new file mode 100644 index 000000000000..4fa31cfa130e --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/embeddings.test.ts @@ -0,0 +1,102 @@ +import { afterAll, describe, expect } from 'vitest'; +import { + GEN_AI_EMBEDDINGS_INPUT, + GEN_AI_OPERATION_NAME, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MODEL, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +const EXPECTED_ORIGIN = 'auto.ai.google_genai'; + +describe('Google GenAI integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => { + test('creates google genai embeddings spans with genAI recording disabled', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + expect(spans.map(span => span.name).sort()).toEqual([ + 'embeddings error-model', + 'embeddings text-embedding-004', + 'embeddings text-embedding-004', + ]); + + const successfulSpans = spans.filter( + span => span.name === 'embeddings text-embedding-004' && span.status === 'ok', + ); + expect(successfulSpans).toHaveLength(2); + for (const span of successfulSpans) { + expect(span.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings'); + expect(span.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); + expect(span.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN); + expect(span.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(span.attributes[GEN_AI_REQUEST_MODEL].value).toBe('text-embedding-004'); + expect(span.attributes[GEN_AI_EMBEDDINGS_INPUT]).toBeUndefined(); + } + + const errorSpan = spans.find(span => span.name === 'embeddings error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); + }, + }) + .start() + .completed(); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('creates google genai embeddings spans with genAI recording enabled', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + expect(spans.map(span => span.name).sort()).toEqual([ + 'embeddings error-model', + 'embeddings text-embedding-004', + 'embeddings text-embedding-004', + ]); + + const stringInputSpan = spans.find( + span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'What is the capital of France?', + ); + expect(stringInputSpan!.name).toBe('embeddings text-embedding-004'); + expect(stringInputSpan!.status).toBe('ok'); + expect(stringInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); + expect(stringInputSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + + const errorSpan = spans.find(span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'This will fail'); + expect(errorSpan!.name).toBe('embeddings error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); + + const arrayInputSpan = spans.find( + span => + span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === + '[{"role":"user","parts":[{"text":"First input text"}]},{"role":"user","parts":[{"text":"Second input text"}]}]', + ); + expect(arrayInputSpan!.name).toBe('embeddings text-embedding-004'); + expect(arrayInputSpan!.status).toBe('ok'); + expect(arrayInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); + }, + }) + .start() + .completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts new file mode 100644 index 000000000000..04f9a49a8157 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/generation.test.ts @@ -0,0 +1,194 @@ +import { afterAll, describe, expect } from 'vitest'; +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_REQUEST_TOP_P, + GEN_AI_RESPONSE_TEXT, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +const EXPECTED_ORIGIN = 'auto.ai.google_genai'; + +describe('Google GenAI integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('creates google genai related spans with genAI recording disabled', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + expect(spans.map(span => span.name).sort()).toEqual([ + 'chat gemini-1.5-pro', + 'generate_content error-model', + 'generate_content gemini-1.5-flash', + ]); + + const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); + expect(chatSpan!.status).toBe('ok'); + expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat'); + expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); + expect(chatSpan!.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN); + expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro'); + // Given once to `chats.create()` and reused for every message the chat sends. + expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); + expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); + expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]).toBeUndefined(); + expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); + expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); + expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); + + const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); + expect(generateContentSpan!.status).toBe('ok'); + expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash'); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); + + const errorSpan = spans.find(span => span.name === 'generate_content error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(errorSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(errorSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('error-model'); + }, + }) + .start() + .completed(); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('creates google genai related spans with genAI recording enabled', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + expect(spans.map(span => span.name).sort()).toEqual([ + 'chat gemini-1.5-pro', + 'generate_content error-model', + 'generate_content gemini-1.5-flash', + ]); + + const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); + expect(chatSpan!.status).toBe('ok'); + expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat'); + expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); + expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro'); + expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + // Given once to `chats.create()` and reused for every message the chat sends. + expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); + expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); + expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( + '[{"type":"text","content":"You are a friendly robot who likes to be funny."}]', + ); + expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); + expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); + expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); + + const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); + expect(generateContentSpan!.status).toBe('ok'); + expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash'); + expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); + + const errorSpan = spans.find(span => span.name === 'generate_content error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + }, + }) + .start() + .completed(); + }); + }); + + createEsmAndCjsTests( + __dirname, + 'scenario-system-instructions.mjs', + 'instrument-with-pii.mjs', + (createRunner, test) => { + test('extracts system instructions and normalizes messages', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(2); + const [firstSpan, secondSpan] = spans; + + // [0] generate_content with a string system instruction + expect(firstSpan!.name).toBe('generate_content gemini-1.5-flash'); + expect(firstSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(firstSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( + JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]), + ); + expect(firstSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( + JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]), + ); + + // [1] generate_content with a `Content` system instruction and a tool-call turn + expect(secondSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( + JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]), + ); + expect(secondSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( + JSON.stringify([ + { role: 'user', parts: [{ type: 'text', content: 'What time is it in Tokyo?' }] }, + { + role: 'assistant', + parts: [{ type: 'tool_call', name: 'get_time', arguments: '{"timezone":"Asia/Tokyo"}' }], + }, + { + role: 'user', + parts: [{ type: 'tool_call_response', name: 'get_time', result: '{"output":"10:00"}' }], + }, + ]), + ); + }, + }) + .start() + .completed(); + }); + }, + ); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts new file mode 100644 index 000000000000..63274847115f --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/options.test.ts @@ -0,0 +1,112 @@ +import { afterAll, describe, expect } from 'vitest'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + GEN_AI_REQUEST_MODEL, + GEN_AI_RESPONSE_TEXT, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +const EXPECTED_ORIGIN = 'auto.ai.google_genai'; + +describe('Google GenAI integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-options.mjs', (createRunner, test) => { + test('creates google genai related spans with custom options', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + expect(spans.map(span => span.name).sort()).toEqual([ + 'chat gemini-1.5-pro', + 'generate_content error-model', + 'generate_content gemini-1.5-flash', + ]); + + const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); + expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); + expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + + const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); + expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + + const errorSpan = spans.find(span => span.name === 'generate_content error-model'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + }, + }) + .start() + .completed(); + }); + }); + + createEsmAndCjsTests( + __dirname, + 'scenario-recording-functions.mjs', + 'instrument-with-recording-functions.mjs', + (createRunner, test) => { + test('decides content recording per call when the options are functions', async () => { + await createRunner() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); + const recordedByModel = Object.fromEntries( + spans.map(span => [ + span.attributes[GEN_AI_REQUEST_MODEL]?.value, + { + inputs: GEN_AI_INPUT_MESSAGES in span.attributes, + outputs: GEN_AI_RESPONSE_TEXT in span.attributes, + }, + ]), + ); + expect(recordedByModel).toEqual({ + 'gemini-public': { inputs: true, outputs: true }, + 'gemini-private': { inputs: false, outputs: false }, + 'gemini-public-stream': { inputs: true, outputs: false }, + }); + }, + }) + .start() + .completed(); + }); + }, + ); + + createEsmAndCjsTests( + __dirname, + 'scenario-recording-functions.mjs', + 'instrument-with-span-hooks.mjs', + (createRunner, test) => { + test('runs the span hooks at start in the caller context and at end with the response', async () => { + await createRunner() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); + const hooksByKey = Object.fromEntries( + spans.map(span => [ + span.attributes[GEN_AI_REQUEST_MODEL]?.value, + [span.attributes['test.start']?.value, span.attributes['test.end']?.value], + ]), + ); + expect(hooksByKey).toEqual({ + 'gemini-public': ['gemini-public:public', 'Paris.'], + 'gemini-private': ['gemini-private:private', 'Paris.'], + // A stream has no single response object, and its tag changes only after the call started. + 'gemini-public-stream': ['gemini-public-stream:private', 'no response'], + }); + }, + }) + .start() + .completed(); + }); + }, + ); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts new file mode 100644 index 000000000000..978ef2041656 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/streaming.test.ts @@ -0,0 +1,230 @@ +import type { Event, SerializedStreamedSpanContainer } from '@sentry/core'; +import { afterAll, describe, expect } from 'vitest'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + GEN_AI_REQUEST_MAX_TOKENS, + GEN_AI_REQUEST_TEMPERATURE, + GEN_AI_REQUEST_TOP_P, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, + GEN_AI_RESPONSE_MODEL, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, + GEN_AI_RESPONSE_TEXT, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +const EXPECTED_ORIGIN = 'auto.ai.google_genai'; + +describe('Google GenAI integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument.mjs', (createRunner, test) => { + test('creates google genai streaming spans with genAI recording disabled', async () => { + let receivedEvent: Event | undefined; + let receivedSpans: SerializedStreamedSpanContainer['items'] = []; + + await createRunner() + // The provider surfaces blocked content within the stream and never returns it to the caller as + // a thrown error, so the instrumentation intentionally captures it as an event. + .unordered() + .expect({ + event: event => { + receivedEvent = event; + }, + }) + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + receivedSpans = container.items; + }, + }) + .start() + .completed(); + + expect(receivedEvent).toMatchObject({ + event_id: expect.any(String), + exception: { + values: [ + { + value: 'Content blocked: The prompt was blocked due to safety concerns', + mechanism: { type: 'auto.ai.google_genai', handled: false }, + }, + ], + }, + }); + + const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai'); + expect(spans).toHaveLength(4); + expect(spans.map(span => span.name).sort()).toEqual([ + 'chat gemini-1.5-pro', + 'generate_content blocked-model', + 'generate_content error-model', + 'generate_content gemini-1.5-flash', + ]); + + const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); + expect(generateContentSpan!.status).toBe('ok'); + expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]?.value).toEqual(expect.any(Number)); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id'); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro'); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(10); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); + expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22); + + const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); + expect(chatSpan!.status).toBe('ok'); + expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + // Given once to `chats.create()` and reused for every message the chat sends. + expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); + expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id'); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro'); + + const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model'); + expect(blockedSpan!.status).toBe('error'); + expect(blockedSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + + const errorSpan = spans.find(span => span.name === 'generate_content error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + }); + }); + + createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { + test('creates google genai streaming spans with genAI recording enabled', async () => { + let receivedEvent: Event | undefined; + let receivedSpans: SerializedStreamedSpanContainer['items'] = []; + + await createRunner() + // The provider surfaces blocked content within the stream and never returns it to the caller as + // a thrown error, so the instrumentation intentionally captures it as an event. + .unordered() + .expect({ + event: event => { + receivedEvent = event; + }, + }) + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + receivedSpans = container.items; + }, + }) + .start() + .completed(); + + expect(receivedEvent).toMatchObject({ + event_id: expect.any(String), + exception: { + values: [ + { + value: 'Content blocked: The prompt was blocked due to safety concerns', + mechanism: { type: 'auto.ai.google_genai', handled: false }, + }, + ], + }, + }); + + const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai'); + expect(spans).toHaveLength(4); + expect(spans.map(span => span.name).sort()).toEqual([ + 'chat gemini-1.5-pro', + 'generate_content blocked-model', + 'generate_content error-model', + 'generate_content gemini-1.5-flash', + ]); + + const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); + expect(generateContentSpan!.status).toBe('ok'); + expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); + expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); + + const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); + expect(chatSpan!.status).toBe('ok'); + expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + // Given once to `chats.create()` and reused for every message the chat sends. + expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); + expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); + expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); + expect(chatSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); + + const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model'); + expect(blockedSpan!.status).toBe('error'); + expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(blockedSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); + expect(blockedSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(blockedSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + + const errorSpan = spans.find(span => span.name === 'generate_content error-model'); + expect(errorSpan!.status).toBe('error'); + expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(errorSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); + expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + }); + }); + + createEsmAndCjsTests( + __dirname, + 'scenario-stream-midway-error.mjs', + 'instrument-with-pii.mjs', + (createRunner, test) => { + test('marks the span as errored when the stream fails midway, but not when the caller breaks early', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); + expect(spans).toHaveLength(6); + + const midwaySpan = spans.find(span => span.name === 'generate_content midway-error'); + expect(midwaySpan!.status).toBe('error'); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID]?.value).toBe('mock-midway-response-id'); + expect(midwaySpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(8); + expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will be cut off'); + + const earlyBreakSpan = spans.find(span => span.name === 'generate_content early-break'); + expect(earlyBreakSpan!.status).toBe('ok'); + expect(earlyBreakSpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will '); + + // `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() + .completed(); + }); + }, + ); +}); 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 deleted file mode 100644 index dfbf4d8eb345..000000000000 --- a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts +++ /dev/null @@ -1,691 +0,0 @@ -import type { Event, SerializedStreamedSpanContainer } from '@sentry/core'; -import { afterAll, describe, expect } from 'vitest'; -import { - GEN_AI_EMBEDDINGS_INPUT, - 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_TEMPERATURE, - GEN_AI_REQUEST_TOP_P, - GEN_AI_RESPONSE_FINISH_REASONS, - GEN_AI_RESPONSE_ID, - GEN_AI_RESPONSE_MODEL, - GEN_AI_RESPONSE_STREAMING, - GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, - GEN_AI_RESPONSE_TEXT, - GEN_AI_RESPONSE_TOOL_CALLS, - 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, -} from '@sentry/conventions/attributes'; -import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; - -const EXPECTED_ORIGIN = 'auto.ai.google_genai'; - -describe('Google GenAI integration', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - test('creates google genai related spans with genAI recording disabled', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - expect(spans.map(span => span.name).sort()).toEqual([ - 'chat gemini-1.5-pro', - 'generate_content error-model', - 'generate_content gemini-1.5-flash', - ]); - - const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); - expect(chatSpan!.status).toBe('ok'); - expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat'); - expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); - expect(chatSpan!.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN); - expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro'); - // Given once to `chats.create()` and reused for every message the chat sends. - expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); - expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); - expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]).toBeUndefined(); - expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); - expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); - expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); - - const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); - expect(generateContentSpan!.status).toBe('ok'); - expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash'); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); - - const errorSpan = spans.find(span => span.name === 'generate_content error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(errorSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(errorSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('error-model'); - }, - }) - .start() - .completed(); - }); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { - test('creates google genai related spans with genAI recording enabled', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - expect(spans.map(span => span.name).sort()).toEqual([ - 'chat gemini-1.5-pro', - 'generate_content error-model', - 'generate_content gemini-1.5-flash', - ]); - - const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); - expect(chatSpan!.status).toBe('ok'); - expect(chatSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.chat'); - expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); - expect(chatSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-pro'); - expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - // Given once to `chats.create()` and reused for every message the chat sends. - expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); - expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); - expect(chatSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( - '[{"type":"text","content":"You are a friendly robot who likes to be funny."}]', - ); - expect(chatSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); - expect(chatSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); - expect(chatSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); - - const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); - expect(generateContentSpan!.status).toBe('ok'); - expect(generateContentSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MODEL].value).toBe('gemini-1.5-flash'); - expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); - - const errorSpan = spans.find(span => span.name === 'generate_content error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - }, - }) - .start() - .completed(); - }); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-options.mjs', (createRunner, test) => { - test('creates google genai related spans with custom options', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - expect(spans.map(span => span.name).sort()).toEqual([ - 'chat gemini-1.5-pro', - 'generate_content error-model', - 'generate_content gemini-1.5-flash', - ]); - - const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); - expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); - expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - - const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); - expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - - const errorSpan = spans.find(span => span.name === 'generate_content error-model'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - }, - }) - .start() - .completed(); - }); - }); - - const EXPECTED_AVAILABLE_TOOLS_JSON = - '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]'; - - createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-options.mjs', (createRunner, test) => { - test('creates google genai related spans with tool calls', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - const nonStreamingToolsSpan = spans.find( - span => - span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON && - span.attributes[GEN_AI_RESPONSE_STREAMING] === undefined, - ); - expect(nonStreamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); - expect(nonStreamingToolsSpan!.status).toBe('ok'); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - expect(JSON.parse(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([ - { - id: 'call_light_control_1', - name: 'controlLight', - args: { brightness: 0.3, colorTemperature: 'warm' }, - }, - ]); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe( - JSON.stringify([ - { - role: 'assistant', - parts: [ - { type: 'text', content: 'I need to check the light status first.' }, - { - type: 'tool_call', - id: 'call_light_control_1', - name: 'controlLight', - arguments: '{"brightness":0.3,"colorTemperature":"warm"}', - }, - ], - }, - ]), - ); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8); - expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(23); - - const streamingToolsSpan = spans.find( - span => - span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON && - span.attributes[GEN_AI_RESPONSE_STREAMING]?.value === true, - ); - expect(streamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); - expect(streamingToolsSpan!.status).toBe('ok'); - expect(streamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(streamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - expect(JSON.parse(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([ - { - id: 'call_light_stream_1', - name: 'controlLight', - args: { brightness: 0.5, colorTemperature: 'cool' }, - }, - ]); - // The text arrives either side of the tool call, so it stays two parts. - expect(streamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe( - JSON.stringify([ - { - role: 'assistant', - parts: [ - { type: 'text', content: 'Let me control the lights for you.' }, - { - type: 'tool_call', - id: 'call_light_stream_1', - name: 'controlLight', - arguments: '{"brightness":0.5,"colorTemperature":"cool"}', - }, - { type: 'text', content: ' Done!' }, - ], - }, - ]), - ); - expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-tools-id'); - expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-2.0-flash-001'); - expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12); - expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(10); - expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22); - - const noToolsSpan = spans.find(span => span.attributes[GEN_AI_TOOL_DEFINITIONS] === undefined); - expect(noToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); - expect(noToolsSpan!.status).toBe('ok'); - expect(noToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(noToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(noToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); - expect(noToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); - expect(noToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); - expect(noToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); - }, - }) - .start() - .completed(); - }); - }); - - createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument.mjs', (createRunner, test) => { - test('creates google genai streaming spans with genAI recording disabled', async () => { - let receivedEvent: Event | undefined; - let receivedSpans: SerializedStreamedSpanContainer['items'] = []; - - await createRunner() - // The provider surfaces blocked content within the stream and never returns it to the caller as - // a thrown error, so the instrumentation intentionally captures it as an event. - .unordered() - .expect({ - event: event => { - receivedEvent = event; - }, - }) - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - receivedSpans = container.items; - }, - }) - .start() - .completed(); - - expect(receivedEvent).toMatchObject({ - event_id: expect.any(String), - exception: { - values: [ - { - value: 'Content blocked: The prompt was blocked due to safety concerns', - mechanism: { type: 'auto.ai.google_genai', handled: false }, - }, - ], - }, - }); - - const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai'); - expect(spans).toHaveLength(4); - expect(spans.map(span => span.name).sort()).toEqual([ - 'chat gemini-1.5-pro', - 'generate_content blocked-model', - 'generate_content error-model', - 'generate_content gemini-1.5-flash', - ]); - - const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); - expect(generateContentSpan!.status).toBe('ok'); - expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]?.value).toEqual(expect.any(Number)); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id'); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro'); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(10); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); - expect(generateContentSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22); - - const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); - expect(chatSpan!.status).toBe('ok'); - expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); - // Given once to `chats.create()` and reused for every message the chat sends. - expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); - expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-streaming-id'); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-1.5-pro'); - - const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model'); - expect(blockedSpan!.status).toBe('error'); - expect(blockedSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - - const errorSpan = spans.find(span => span.name === 'generate_content error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.generate_content'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - }); - }); - - createEsmAndCjsTests(__dirname, 'scenario-streaming.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { - test('creates google genai streaming spans with genAI recording enabled', async () => { - let receivedEvent: Event | undefined; - let receivedSpans: SerializedStreamedSpanContainer['items'] = []; - - await createRunner() - // The provider surfaces blocked content within the stream and never returns it to the caller as - // a thrown error, so the instrumentation intentionally captures it as an event. - .unordered() - .expect({ - event: event => { - receivedEvent = event; - }, - }) - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - receivedSpans = container.items; - }, - }) - .start() - .completed(); - - expect(receivedEvent).toMatchObject({ - event_id: expect.any(String), - exception: { - values: [ - { - value: 'Content blocked: The prompt was blocked due to safety concerns', - mechanism: { type: 'auto.ai.google_genai', handled: false }, - }, - ], - }, - }); - - const spans = receivedSpans.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai'); - expect(spans).toHaveLength(4); - expect(spans.map(span => span.name).sort()).toEqual([ - 'chat gemini-1.5-pro', - 'generate_content blocked-model', - 'generate_content error-model', - 'generate_content gemini-1.5-flash', - ]); - - const generateContentSpan = spans.find(span => span.name === 'generate_content gemini-1.5-flash'); - expect(generateContentSpan!.status).toBe('ok'); - expect(generateContentSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); - expect(generateContentSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(generateContentSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(100); - expect(generateContentSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); - - const chatSpan = spans.find(span => span.name === 'chat gemini-1.5-pro'); - expect(chatSpan!.status).toBe('ok'); - expect(chatSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('chat'); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); - expect(chatSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - // Given once to `chats.create()` and reused for every message the chat sends. - expect(chatSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.8); - expect(chatSpan!.attributes[GEN_AI_REQUEST_TOP_P].value).toBe(0.9); - expect(chatSpan!.attributes[GEN_AI_REQUEST_MAX_TOKENS].value).toBe(150); - expect(chatSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["STOP"]'); - - const blockedSpan = spans.find(span => span.name === 'generate_content blocked-model'); - expect(blockedSpan!.status).toBe('error'); - expect(blockedSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(blockedSpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true); - expect(blockedSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - expect(blockedSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - - const errorSpan = spans.find(span => span.name === 'generate_content error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(errorSpan!.attributes[GEN_AI_REQUEST_TEMPERATURE].value).toBe(0.7); - expect(errorSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); - }); - }); - - createEsmAndCjsTests( - __dirname, - 'scenario-system-instructions.mjs', - 'instrument-with-pii.mjs', - (createRunner, test) => { - test('extracts system instructions and normalizes messages', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(2); - const [firstSpan, secondSpan] = spans; - - // [0] generate_content with a string system instruction - expect(firstSpan!.name).toBe('generate_content gemini-1.5-flash'); - expect(firstSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); - expect(firstSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( - JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]), - ); - expect(firstSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( - JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]), - ); - - // [1] generate_content with a `Content` system instruction and a tool-call turn - expect(secondSpan!.attributes[GEN_AI_SYSTEM_INSTRUCTIONS].value).toBe( - JSON.stringify([{ type: 'text', content: 'You are a helpful assistant' }]), - ); - expect(secondSpan!.attributes[GEN_AI_INPUT_MESSAGES].value).toBe( - JSON.stringify([ - { role: 'user', parts: [{ type: 'text', content: 'What time is it in Tokyo?' }] }, - { - role: 'assistant', - parts: [{ type: 'tool_call', name: 'get_time', arguments: '{"timezone":"Asia/Tokyo"}' }], - }, - { - role: 'user', - parts: [{ type: 'tool_call_response', name: 'get_time', result: '{"output":"10:00"}' }], - }, - ]), - ); - }, - }) - .start() - .completed(); - }); - }, - ); - - createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument.mjs', (createRunner, test) => { - test('creates google genai embeddings spans with genAI recording disabled', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - expect(spans.map(span => span.name).sort()).toEqual([ - 'embeddings error-model', - 'embeddings text-embedding-004', - 'embeddings text-embedding-004', - ]); - - const successfulSpans = spans.filter( - span => span.name === 'embeddings text-embedding-004' && span.status === 'ok', - ); - expect(successfulSpans).toHaveLength(2); - for (const span of successfulSpans) { - expect(span.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings'); - expect(span.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); - expect(span.attributes[SENTRY_ORIGIN].value).toBe(EXPECTED_ORIGIN); - expect(span.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - expect(span.attributes[GEN_AI_REQUEST_MODEL].value).toBe('text-embedding-004'); - expect(span.attributes[GEN_AI_EMBEDDINGS_INPUT]).toBeUndefined(); - } - - const errorSpan = spans.find(span => span.name === 'embeddings error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[SENTRY_OP].value).toBe('gen_ai.embeddings'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); - }, - }) - .start() - .completed(); - }); - }); - - createEsmAndCjsTests(__dirname, 'scenario-embeddings.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { - test('creates google genai embeddings spans with genAI recording enabled', async () => { - await createRunner() - .expect({ - span: container => { - expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); - const spans = container.items.filter( - span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', - ); - expect(spans).toHaveLength(3); - expect(spans.map(span => span.name).sort()).toEqual([ - 'embeddings error-model', - 'embeddings text-embedding-004', - 'embeddings text-embedding-004', - ]); - - const stringInputSpan = spans.find( - span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'What is the capital of France?', - ); - expect(stringInputSpan!.name).toBe('embeddings text-embedding-004'); - expect(stringInputSpan!.status).toBe('ok'); - expect(stringInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); - expect(stringInputSpan!.attributes[GEN_AI_PROVIDER_NAME].value).toBe('google_genai'); - - const errorSpan = spans.find(span => span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === 'This will fail'); - expect(errorSpan!.name).toBe('embeddings error-model'); - expect(errorSpan!.status).toBe('error'); - expect(errorSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); - - const arrayInputSpan = spans.find( - span => - span.attributes[GEN_AI_EMBEDDINGS_INPUT]?.value === - '[{"role":"user","parts":[{"text":"First input text"}]},{"role":"user","parts":[{"text":"Second input text"}]}]', - ); - expect(arrayInputSpan!.name).toBe('embeddings text-embedding-004'); - expect(arrayInputSpan!.status).toBe('ok'); - expect(arrayInputSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('embeddings'); - }, - }) - .start() - .completed(); - }); - }); - - createEsmAndCjsTests( - __dirname, - 'scenario-stream-midway-error.mjs', - 'instrument-with-pii.mjs', - (createRunner, test) => { - test('marks the span as errored when the stream fails midway, but not when the caller breaks early', async () => { - await createRunner() - .unordered() - .expect({ - span: container => { - const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); - expect(spans).toHaveLength(6); - - const midwaySpan = spans.find(span => span.name === 'generate_content midway-error'); - expect(midwaySpan!.status).toBe('error'); - expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); - expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID]?.value).toBe('mock-midway-response-id'); - expect(midwaySpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(8); - expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will be cut off'); - - const earlyBreakSpan = spans.find(span => span.name === 'generate_content early-break'); - expect(earlyBreakSpan!.status).toBe('ok'); - expect(earlyBreakSpan!.attributes[GEN_AI_RESPONSE_TEXT]?.value).toBe('This stream will '); - - // `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() - .completed(); - }); - }, - ); - - createEsmAndCjsTests( - __dirname, - 'scenario-recording-functions.mjs', - 'instrument-with-recording-functions.mjs', - (createRunner, test) => { - test('decides content recording per call when the options are functions', async () => { - await createRunner() - .expect({ - span: container => { - const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); - const recordedByModel = Object.fromEntries( - spans.map(span => [ - span.attributes[GEN_AI_REQUEST_MODEL]?.value, - { - inputs: GEN_AI_INPUT_MESSAGES in span.attributes, - outputs: GEN_AI_RESPONSE_TEXT in span.attributes, - }, - ]), - ); - expect(recordedByModel).toEqual({ - 'gemini-public': { inputs: true, outputs: true }, - 'gemini-private': { inputs: false, outputs: false }, - 'gemini-public-stream': { inputs: true, outputs: false }, - }); - }, - }) - .start() - .completed(); - }); - }, - ); - - createEsmAndCjsTests( - __dirname, - 'scenario-recording-functions.mjs', - 'instrument-with-span-hooks.mjs', - (createRunner, test) => { - test('runs the span hooks at start in the caller context and at end with the response', async () => { - await createRunner() - .expect({ - span: container => { - const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === EXPECTED_ORIGIN); - const hooksByKey = Object.fromEntries( - spans.map(span => [ - span.attributes[GEN_AI_REQUEST_MODEL]?.value, - [span.attributes['test.start']?.value, span.attributes['test.end']?.value], - ]), - ); - expect(hooksByKey).toEqual({ - 'gemini-public': ['gemini-public:public', 'Paris.'], - 'gemini-private': ['gemini-private:private', 'Paris.'], - // A stream has no single response object, and its tag changes only after the call started. - 'gemini-public-stream': ['gemini-public-stream:private', 'no response'], - }); - }, - }) - .start() - .completed(); - }); - }, - ); -}); diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts new file mode 100644 index 000000000000..188e1a07695d --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/tools.test.ts @@ -0,0 +1,130 @@ +import { afterAll, describe, expect } from 'vitest'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + 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, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; + +describe('Google GenAI integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + const EXPECTED_AVAILABLE_TOOLS_JSON = + '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]'; + + createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-options.mjs', (createRunner, test) => { + test('creates google genai related spans with tool calls', async () => { + await createRunner() + .expect({ + span: container => { + expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined(); + const spans = container.items.filter( + span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.google_genai', + ); + expect(spans).toHaveLength(3); + const nonStreamingToolsSpan = spans.find( + span => + span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON && + span.attributes[GEN_AI_RESPONSE_STREAMING] === undefined, + ); + expect(nonStreamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); + expect(nonStreamingToolsSpan!.status).toBe('ok'); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + expect(JSON.parse(nonStreamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([ + { + id: 'call_light_control_1', + name: 'controlLight', + args: { brightness: 0.3, colorTemperature: 'warm' }, + }, + ]); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe( + JSON.stringify([ + { + role: 'assistant', + parts: [ + { type: 'text', content: 'I need to check the light status first.' }, + { + type: 'tool_call', + id: 'call_light_control_1', + name: 'controlLight', + arguments: '{"brightness":0.3,"colorTemperature":"warm"}', + }, + ], + }, + ]), + ); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8); + expect(nonStreamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(23); + + const streamingToolsSpan = spans.find( + span => + span.attributes[GEN_AI_TOOL_DEFINITIONS]?.value === EXPECTED_AVAILABLE_TOOLS_JSON && + span.attributes[GEN_AI_RESPONSE_STREAMING]?.value === true, + ); + expect(streamingToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); + expect(streamingToolsSpan!.status).toBe('ok'); + expect(streamingToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(streamingToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + expect(JSON.parse(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS].value as string)).toEqual([ + { + id: 'call_light_stream_1', + name: 'controlLight', + args: { brightness: 0.5, colorTemperature: 'cool' }, + }, + ]); + // The text arrives either side of the tool call, so it stays two parts. + expect(streamingToolsSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe( + JSON.stringify([ + { + role: 'assistant', + parts: [ + { type: 'text', content: 'Let me control the lights for you.' }, + { + type: 'tool_call', + id: 'call_light_stream_1', + name: 'controlLight', + arguments: '{"brightness":0.5,"colorTemperature":"cool"}', + }, + { type: 'text', content: ' Done!' }, + ], + }, + ]), + ); + expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('mock-response-tools-id'); + expect(streamingToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL].value).toBe('gemini-2.0-flash-001'); + expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12); + expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(10); + expect(streamingToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(22); + + const noToolsSpan = spans.find(span => span.attributes[GEN_AI_TOOL_DEFINITIONS] === undefined); + expect(noToolsSpan!.name).toBe('generate_content gemini-2.0-flash-001'); + expect(noToolsSpan!.status).toBe('ok'); + expect(noToolsSpan!.attributes[GEN_AI_OPERATION_NAME].value).toBe('generate_content'); + expect(noToolsSpan!.attributes[GEN_AI_INPUT_MESSAGES]).toBeDefined(); + expect(noToolsSpan!.attributes[GEN_AI_RESPONSE_TEXT]).toBeDefined(); + expect(noToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(8); + expect(noToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(12); + expect(noToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(20); + }, + }) + .start() + .completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts new file mode 100644 index 000000000000..1eaeabac76d6 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/expected.ts @@ -0,0 +1,69 @@ +export const WEATHER_TOOL_DEFINITION = JSON.stringify([ + { + type: 'function', + function: { + name: 'get_weather', + description: 'Get the current weather in a given location', + parameters: { + type: 'object', + properties: { + latitude: { type: 'number', description: 'The latitude of the location' }, + longitude: { type: 'number', description: 'The longitude of the location' }, + }, + required: ['latitude', 'longitude'], + }, + }, + }, +]); + +export const CHAT_TOOL_CALLS = JSON.stringify([ + { + id: 'call_12345xyz', + type: 'function', + function: { + name: 'get_weather', + arguments: '{"latitude":48.8566,"longitude":2.3522}', + }, + }, +]); + +export const CHAT_STREAM_TOOL_CALLS = JSON.stringify([ + { + index: 0, + id: 'call_12345xyz', + type: 'function', + function: { + name: 'get_weather', + arguments: '{"latitude":48.8566,"longitude":2.3522}', + }, + }, +]); + +export const CHAT_GEMINI_STREAM_TOOL_CALLS = JSON.stringify([ + { + id: 'call_paris', + type: 'function', + function: { + name: 'get_weather', + arguments: '{"latitude":48.8566,"longitude":2.3522}', + }, + }, + { + id: 'call_london', + type: 'function', + function: { + name: 'get_weather', + arguments: '{"latitude":51.5072,"longitude":-0.1276}', + }, + }, +]); + +export const RESPONSES_TOOL_CALLS = JSON.stringify([ + { + type: 'function_call', + id: 'fc_12345xyz', + call_id: 'call_12345xyz', + name: 'get_weather', + arguments: '{"latitude":48.8566,"longitude":2.3522}', + }, +]); diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts new file mode 100644 index 000000000000..896f7eaf9e5e --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-disabled.test.ts @@ -0,0 +1,265 @@ +import { afterAll, describe, expect } from 'vitest'; +import { + GEN_AI_OPERATION_NAME, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MODEL, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_ID, + GEN_AI_RESPONSE_MODEL, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_RESPONSE_TOOL_CALLS, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../../../../../../packages/server-utils/src/ai/core/gen-ai-attributes'; +import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; + +describe('OpenAI Tool Calls integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('creates openai tool calls related spans with genAI recording disabled', async () => { + await createRunner() + .expect({ + span: container => { + const segment = container.items.find(span => span.is_segment && span.name === 'main'); + expect(segment).toBeDefined(); + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.openai'); + expect(spans).toHaveLength(5); + const chatToolsSpan = spans.find( + span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-tools-123', + ); + expect(chatToolsSpan!.name).toBe('chat gpt-4'); + expect(chatToolsSpan!.status).toBe('ok'); + expect(chatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ + type: 'string', + value: 'chat', + }); + expect(chatToolsSpan!.attributes[SENTRY_OP]).toEqual({ + type: 'string', + value: 'gen_ai.chat', + }); + expect(chatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ + type: 'string', + value: 'auto.ai.openai', + }); + expect(chatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ type: 'string', value: 'openai' }); + expect(chatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + // Tool definitions are gen AI input data, so `genAI.inputs: false` drops them. + expect(chatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); + expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ + type: 'string', + value: 'chatcmpl-tools-123', + }); + expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ + type: 'string', + value: '["tool_calls"]', + }); + expect(chatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ + type: 'integer', + value: 15, + }); + expect(chatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ + type: 'integer', + value: 25, + }); + expect(chatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ + type: 'integer', + value: 40, + }); + + const streamingChatToolsSpan = spans.find( + span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-tools-123', + ); + expect(streamingChatToolsSpan!.name).toBe('chat gpt-4'); + expect(streamingChatToolsSpan!.status).toBe('ok'); + expect(streamingChatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ + type: 'string', + value: 'chat', + }); + expect(streamingChatToolsSpan!.attributes[SENTRY_OP]).toEqual({ + type: 'string', + value: 'gen_ai.chat', + }); + expect(streamingChatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ + type: 'string', + value: 'auto.ai.openai', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ + type: 'string', + value: 'openai', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({ + type: 'boolean', + value: true, + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); + expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ + type: 'string', + value: 'chatcmpl-stream-tools-123', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ + type: 'string', + value: '["tool_calls"]', + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({ + type: 'boolean', + value: true, + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ + type: 'integer', + value: 15, + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ + type: 'integer', + value: 25, + }); + expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ + type: 'integer', + value: 40, + }); + + const geminiStreamSpan = spans.find( + span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-gemini-tools-123', + ); + expect(geminiStreamSpan).toBeDefined(); + expect(geminiStreamSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS]).toBeUndefined(); + + const responsesToolsSpan = spans.find( + span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_tools_789', + ); + expect(responsesToolsSpan!.name).toBe('chat gpt-4'); + expect(responsesToolsSpan!.status).toBe('ok'); + expect(responsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ + type: 'string', + value: 'chat', + }); + expect(responsesToolsSpan!.attributes[SENTRY_OP]).toEqual({ + type: 'string', + value: 'gen_ai.chat', + }); + expect(responsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ + type: 'string', + value: 'auto.ai.openai', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ + type: 'string', + value: 'openai', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toBeUndefined(); + expect(responsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); + expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ + type: 'string', + value: 'resp_tools_789', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ + type: 'string', + value: '["completed"]', + }); + expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ + type: 'integer', + value: 8, + }); + expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ + type: 'integer', + value: 12, + }); + expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ + type: 'integer', + value: 20, + }); + + const streamingResponsesToolsSpan = spans.find( + span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_stream_tools_789', + ); + expect(streamingResponsesToolsSpan!.name).toBe('chat gpt-4'); + expect(streamingResponsesToolsSpan!.status).toBe('ok'); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ + type: 'string', + value: 'chat', + }); + expect(streamingResponsesToolsSpan!.attributes[SENTRY_OP]).toEqual({ + type: 'string', + value: 'gen_ai.chat', + }); + expect(streamingResponsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ + type: 'string', + value: 'auto.ai.openai', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ + type: 'string', + value: 'openai', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({ + type: 'boolean', + value: true, + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ + type: 'string', + value: 'gpt-4', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ + type: 'string', + value: 'resp_stream_tools_789', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ + type: 'string', + value: '["in_progress","completed"]', + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({ + type: 'boolean', + value: true, + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ + type: 'integer', + value: 8, + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ + type: 'integer', + value: 12, + }); + expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ + type: 'integer', + value: 20, + }); + }, + }) + .start() + .completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts similarity index 52% rename from dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts rename to dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts index cf5e050605da..45fc61b48419 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/recording-enabled.test.ts @@ -1,3 +1,10 @@ +import { + WEATHER_TOOL_DEFINITION, + CHAT_TOOL_CALLS, + CHAT_STREAM_TOOL_CALLS, + CHAT_GEMINI_STREAM_TOOL_CALLS, + RESPONSES_TOOL_CALLS, +} from './expected'; import { afterAll, describe, expect } from 'vitest'; import { GEN_AI_INPUT_MESSAGES, @@ -25,316 +32,6 @@ describe('OpenAI Tool Calls integration', () => { cleanupChildProcesses(); }); - const WEATHER_TOOL_DEFINITION = JSON.stringify([ - { - type: 'function', - function: { - name: 'get_weather', - description: 'Get the current weather in a given location', - parameters: { - type: 'object', - properties: { - latitude: { type: 'number', description: 'The latitude of the location' }, - longitude: { type: 'number', description: 'The longitude of the location' }, - }, - required: ['latitude', 'longitude'], - }, - }, - }, - ]); - - const CHAT_TOOL_CALLS = JSON.stringify([ - { - id: 'call_12345xyz', - type: 'function', - function: { - name: 'get_weather', - arguments: '{"latitude":48.8566,"longitude":2.3522}', - }, - }, - ]); - - const CHAT_STREAM_TOOL_CALLS = JSON.stringify([ - { - index: 0, - id: 'call_12345xyz', - type: 'function', - function: { - name: 'get_weather', - arguments: '{"latitude":48.8566,"longitude":2.3522}', - }, - }, - ]); - - const CHAT_GEMINI_STREAM_TOOL_CALLS = JSON.stringify([ - { - id: 'call_paris', - type: 'function', - function: { - name: 'get_weather', - arguments: '{"latitude":48.8566,"longitude":2.3522}', - }, - }, - { - id: 'call_london', - type: 'function', - function: { - name: 'get_weather', - arguments: '{"latitude":51.5072,"longitude":-0.1276}', - }, - }, - ]); - - const RESPONSES_TOOL_CALLS = JSON.stringify([ - { - type: 'function_call', - id: 'fc_12345xyz', - call_id: 'call_12345xyz', - name: 'get_weather', - arguments: '{"latitude":48.8566,"longitude":2.3522}', - }, - ]); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - test('creates openai tool calls related spans with genAI recording disabled', async () => { - await createRunner() - .expect({ - span: container => { - const segment = container.items.find(span => span.is_segment && span.name === 'main'); - expect(segment).toBeDefined(); - const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.openai'); - expect(spans).toHaveLength(5); - const chatToolsSpan = spans.find( - span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-tools-123', - ); - expect(chatToolsSpan!.name).toBe('chat gpt-4'); - expect(chatToolsSpan!.status).toBe('ok'); - expect(chatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ - type: 'string', - value: 'chat', - }); - expect(chatToolsSpan!.attributes[SENTRY_OP]).toEqual({ - type: 'string', - value: 'gen_ai.chat', - }); - expect(chatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ - type: 'string', - value: 'auto.ai.openai', - }); - expect(chatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ type: 'string', value: 'openai' }); - expect(chatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - // Tool definitions are gen AI input data, so `genAI.inputs: false` drops them. - expect(chatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); - expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ - type: 'string', - value: 'chatcmpl-tools-123', - }); - expect(chatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ - type: 'string', - value: '["tool_calls"]', - }); - expect(chatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ - type: 'integer', - value: 15, - }); - expect(chatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ - type: 'integer', - value: 25, - }); - expect(chatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ - type: 'integer', - value: 40, - }); - - const streamingChatToolsSpan = spans.find( - span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-tools-123', - ); - expect(streamingChatToolsSpan!.name).toBe('chat gpt-4'); - expect(streamingChatToolsSpan!.status).toBe('ok'); - expect(streamingChatToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ - type: 'string', - value: 'chat', - }); - expect(streamingChatToolsSpan!.attributes[SENTRY_OP]).toEqual({ - type: 'string', - value: 'gen_ai.chat', - }); - expect(streamingChatToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ - type: 'string', - value: 'auto.ai.openai', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ - type: 'string', - value: 'openai', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({ - type: 'boolean', - value: true, - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); - expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ - type: 'string', - value: 'chatcmpl-stream-tools-123', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ - type: 'string', - value: '["tool_calls"]', - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({ - type: 'boolean', - value: true, - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ - type: 'integer', - value: 15, - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ - type: 'integer', - value: 25, - }); - expect(streamingChatToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ - type: 'integer', - value: 40, - }); - - const geminiStreamSpan = spans.find( - span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'chatcmpl-stream-gemini-tools-123', - ); - expect(geminiStreamSpan).toBeDefined(); - expect(geminiStreamSpan!.attributes[GEN_AI_RESPONSE_TOOL_CALLS]).toBeUndefined(); - - const responsesToolsSpan = spans.find( - span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_tools_789', - ); - expect(responsesToolsSpan!.name).toBe('chat gpt-4'); - expect(responsesToolsSpan!.status).toBe('ok'); - expect(responsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ - type: 'string', - value: 'chat', - }); - expect(responsesToolsSpan!.attributes[SENTRY_OP]).toEqual({ - type: 'string', - value: 'gen_ai.chat', - }); - expect(responsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ - type: 'string', - value: 'auto.ai.openai', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ - type: 'string', - value: 'openai', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toBeUndefined(); - expect(responsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); - expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ - type: 'string', - value: 'resp_tools_789', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ - type: 'string', - value: '["completed"]', - }); - expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ - type: 'integer', - value: 8, - }); - expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ - type: 'integer', - value: 12, - }); - expect(responsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ - type: 'integer', - value: 20, - }); - - const streamingResponsesToolsSpan = spans.find( - span => span.attributes[GEN_AI_RESPONSE_ID]?.value === 'resp_stream_tools_789', - ); - expect(streamingResponsesToolsSpan!.name).toBe('chat gpt-4'); - expect(streamingResponsesToolsSpan!.status).toBe('ok'); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_OPERATION_NAME]).toEqual({ - type: 'string', - value: 'chat', - }); - expect(streamingResponsesToolsSpan!.attributes[SENTRY_OP]).toEqual({ - type: 'string', - value: 'gen_ai.chat', - }); - expect(streamingResponsesToolsSpan!.attributes[SENTRY_ORIGIN]).toEqual({ - type: 'string', - value: 'auto.ai.openai', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_PROVIDER_NAME]).toEqual({ - type: 'string', - value: 'openai', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE]).toEqual({ - type: 'boolean', - value: true, - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_TOOL_DEFINITIONS]).toBeUndefined(); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_MODEL]).toEqual({ - type: 'string', - value: 'gpt-4', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_ID]).toEqual({ - type: 'string', - value: 'resp_stream_tools_789', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS]).toEqual({ - type: 'string', - value: '["in_progress","completed"]', - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_RESPONSE_STREAMING]).toEqual({ - type: 'boolean', - value: true, - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS]).toEqual({ - type: 'integer', - value: 8, - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]).toEqual({ - type: 'integer', - value: 12, - }); - expect(streamingResponsesToolsSpan!.attributes[GEN_AI_USAGE_TOTAL_TOKENS]).toEqual({ - type: 'integer', - value: 20, - }); - }, - }) - .start() - .completed(); - }); - }); - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { test('creates openai tool calls related spans with genAI recording enabled', async () => { await createRunner() diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts new file mode 100644 index 000000000000..c50d0a59733d --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/lifecycle.test.ts @@ -0,0 +1,221 @@ +import { + GEN_AI_CONVERSATION_ID, + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_RESPONSE_FINISH_REASONS, + GEN_AI_RESPONSE_STREAMING, + GEN_AI_TOOL_CALL_ARGUMENTS, + SENTRY_OP, + SENTRY_STATUS_MESSAGE, +} 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 provider session id that pi-durable stores with each conversation, a UUIDv7. +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +// The pi packages declare `engines.node >= 22.19`. +describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmTests(__dirname, 'scenario-reports.mjs', 'instrument.mjs', (createRunner, test) => { + test('captures failures pi-durable does not propagate, and tags idle compaction with its conversation', async () => { + let runConversationId: unknown; + let compactionConversationId: unknown; + + await createRunner() + .unordered() + .expect({ + event: event => { + const exception = event.exception?.values?.[0]; + expect(exception?.value).toBe('afterResponse hook failed'); + expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); + }, + }) + .expect({ + event: event => { + const exception = event.exception?.values?.[0]; + expect(exception?.value).toBe('card declined'); + expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); + }, + }) + .expect({ + span: container => { + const agent = container.items.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + runConversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; + }, + }) + .expect({ + span: container => { + // A compaction started while idle belongs to no run, so its request is a trace of its own. + expect(container.items).toHaveLength(1); + const summary = container.items[0]!; + expect(summary.is_segment).toBe(true); + expect(summary.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT); + compactionConversationId = summary.attributes[GEN_AI_CONVERSATION_ID]?.value; + }, + }) + .start() + .completed(); + + expect(runConversationId).toMatch(UUID); + expect(compactionConversationId).toBe(runConversationId); + }); + }); + + createEsmTests(__dirname, 'scenario-retention.mjs', 'instrument.mjs', (createRunner, test) => { + // Bun does not implement `v8.setFlagsFromString`, which the scenario needs to force GC. + test.runIf(supports({ runtimes: ['node', 'deno'] }))( + 'does not keep the traces of tool calls alive for subagent conversations that never run', + async () => { + await createRunner() + .ignore('span') + .expect({ event: { message: 'pi-durable retention', extra: { toolCalls: 3, alive: 0 } } }) + .start() + .completed(); + }, + ); + }); + + createEsmTests(__dirname, 'scenario-restart-abort.mjs', 'instrument.mjs', (createRunner, test) => { + test('starts no run for an abort handler in a Harness that never saw the run', async () => { + await createRunner() + .ignore('span') + .expect({ + event: { + message: 'pi-durable restart abort', + extra: { status: 'unanswered', reason: 'aborted', runsStarted: 0 }, + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario-interrupted.mjs', 'instrument.mjs', (createRunner, test) => { + test('reports a provider that throws as a fault, and nothing for failed, aborted or closed runs', async () => { + await createRunner() + .ignore('span') + .expect({ + event: event => { + const exception = event.exception?.values?.[0]; + expect(exception?.value).toBe('provider broke'); + expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); + }, + }) + .expect({ + event: event => { + expect(event.message).toBe('pi-durable interrupted done'); + }, + }) + .start() + .completed(); + }); + + test('ends every run that does not end with an answer', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + // 1. The model request failed: the run and the request are errors. + const chat = container.items.find(span => span.name === 'chat faux-model')!; + expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail please.'); + expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["error"]'); + expect(chat.status).toBe('error'); + expect(chat.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error'); + const agent = container.items.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + expect(agent.status).toBe('error'); + expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error'); + }, + }) + .expect({ + span: container => { + // 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'); + }, + }) + .expect({ + span: container => { + // 3. Aborted while the tool ran: cancelled, which streamed spans report as ok. + const slow = container.items.find(span => span.name === 'execute_tool slow')!; + expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"abort"}'); + expect(slow.status).toBe('ok'); + expect(container.items.find(span => span.is_segment)!.status).toBe('ok'); + }, + }) + .expect({ + span: container => { + // 4. Aborted while the model request ran. + const chat = container.items.find(span => span.name === 'chat faux-model')!; + expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["aborted"]'); + expect(container.items).toHaveLength(2); + }, + }) + .expect({ + span: container => { + // 5. The Harness closed while the tool ran: the run still ends, so the trace has a segment. + const slow = container.items.find(span => span.name === 'execute_tool slow')!; + expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"close"}'); + const agent = container.items.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + expect(slow.parent_span_id).toBe(agent.span_id); + }, + }) + .expect({ + span: container => { + // 6. The run failed, and the Harness closed right after `wait()`, before the commit that + // ended the run resolved: the run keeps its own status. + const chat = container.items.find(span => span.name === 'chat faux-model')!; + expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail, then close.'); + const agent = container.items.find(span => span.is_segment)!; + expect(agent.status).toBe('error'); + expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error'); + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario-compaction.mjs', 'instrument.mjs', (createRunner, test) => { + test('keeps a compaction that pi-durable starts for a run inside that run', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items; + const summary = spans.find(span => + String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Summary'), + )!; + const agent = spans.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + expect(summary.parent_span_id).toBe(agent.span_id); + // pi-durable completes the summary without streaming; the run's own request streams. + expect(summary.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined(); + const answer = spans.find(span => + String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Third answer'), + )!; + expect(answer.parent_span_id).toBe(agent.span_id); + expect(answer.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); + }, + }) + .expect({ + span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'), + }) + .expect({ + span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'), + }) + .start() + .completed(); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts new file mode 100644 index 000000000000..ab5091b9fbcd --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/options.test.ts @@ -0,0 +1,139 @@ +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_CALL_ARGUMENTS, + GEN_AI_TOOL_CALL_RESULT, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_TOOL_DESCRIPTION, + GEN_AI_USAGE_INPUT_TOKENS, +} from '@sentry/conventions/attributes'; + +import { afterAll, describe, expect } from 'vitest'; + +import { supports } from '../../../utils'; +import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner'; + +const CONTENT_ATTRIBUTES = [ + GEN_AI_INPUT_MESSAGES, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_SYSTEM_INSTRUCTIONS, + GEN_AI_TOOL_DEFINITIONS, + GEN_AI_TOOL_CALL_ARGUMENTS, + GEN_AI_TOOL_CALL_RESULT, +]; + +// The pi packages declare `engines.node >= 22.19`. +describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + 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(); + } + } + }, + }) + .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-recording-functions.mjs', + 'instrument-with-recording-functions.mjs', + (createRunner, test) => { + test('decides content recording per call when the options are functions', async () => { + await createRunner() + .expect({ + span: container => { + const recorded = container.items + .filter(span => /^(chat|execute_tool) /.test(span.name)) + .sort((a, b) => a.start_timestamp - b.start_timestamp) + .map(({ name, attributes }) => [ + name, + GEN_AI_INPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_ARGUMENTS in attributes, + GEN_AI_OUTPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_RESULT in attributes, + ]); + expect(recorded).toEqual([ + ['chat faux-model', true, true], + ['execute_tool get_weather', false, false], + ['chat faux-model', true, false], + ]); + }, + }) + .start() + .completed(); + }); + }, + ); + + createEsmTests( + __dirname, + 'scenario-recording-functions.mjs', + 'instrument-with-span-hooks.mjs', + (createRunner, test) => { + test('runs the span hooks of the model and tool calls', async () => { + await createRunner() + .expect({ + span: container => { + const hooks = container.items + .filter(span => /^(chat|execute_tool) /.test(span.name)) + .sort((a, b) => a.start_timestamp - b.start_timestamp) + .map(({ attributes }) => [attributes['test.start']?.value, attributes['test.end']?.value]); + expect(hooks).toEqual([ + ['chat', 'toolUse'], + ['Berlin', 'It is sunny in Berlin.'], + ['chat', 'stop'], + ]); + }, + }) + .start() + .completed(); + }); + }, + ); +}); 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 deleted file mode 100644 index d646b7a59975..000000000000 --- a/dev-packages/node-integration-tests/suites/tracing/pi-durable/test.ts +++ /dev/null @@ -1,722 +0,0 @@ -import { - GEN_AI_CONVERSATION_ID, - 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_CALL_ARGUMENTS, - GEN_AI_TOOL_CALL_RESULT, - GEN_AI_TOOL_DEFINITIONS, - GEN_AI_TOOL_DESCRIPTION, - GEN_AI_TOOL_NAME, - GEN_AI_USAGE_INPUT_TOKENS, - GEN_AI_USAGE_OUTPUT_TOKENS, - SENTRY_OP, - SENTRY_ORIGIN, - SENTRY_STATUS_MESSAGE, -} from '@sentry/conventions/attributes'; -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 { supports } from '../../../utils'; -import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner'; - -// The provider session id that pi-durable stores with each conversation, a UUIDv7. -const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; - -const CONTENT_ATTRIBUTES = [ - GEN_AI_INPUT_MESSAGES, - GEN_AI_OUTPUT_MESSAGES, - GEN_AI_SYSTEM_INSTRUCTIONS, - GEN_AI_TOOL_DEFINITIONS, - GEN_AI_TOOL_CALL_ARGUMENTS, - GEN_AI_TOOL_CALL_RESULT, -]; - -// The pi packages declare `engines.node >= 22.19`. -describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - // The pi packages are ESM-only: their `exports` maps have no `require` condition. - createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - test('traces each run as its own invoke_agent trace with chat and execute_tool children', async () => { - let toolRunTraceId: string | undefined; - let brokenToolSpanId: string | undefined; - let errorTraceId: string | undefined; - let errorSpanId: string | undefined; - const conversationIds: unknown[] = []; - - await createRunner() - .unordered() - .expect({ - span: container => { - const spans = container.items; - 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 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( - 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'); - expect(agent.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('invoke_agent'); - const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; - expect(conversationId).toMatch(UUID); - - const chats = spans - .filter(span => span.name === 'chat faux-model') - .sort((a, b) => a.start_timestamp - b.start_timestamp); - 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_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); - expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0); - expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0); - // pi-durable sends the prompt and the tools as positional system messages. - expect(chat.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]?.value).toBe('You are a weather assistant.'); - expect( - JSON.parse(String(chat.attributes[GEN_AI_TOOL_DEFINITIONS]?.value)).map( - (tool: { name: string }) => tool.name, - ), - ).toEqual(['get_weather', 'broken']); - } - - // Mapped from pi-ai's shape to the conventions: the tool calls and tool results the - // second request carries are what Sentry's conversation view renders. - expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))).toEqual([ - { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Berlin?' }] }, - ]); - const answerInput = JSON.parse(String(chats[1]!.attributes[GEN_AI_INPUT_MESSAGES]?.value)); - expect(answerInput.map((message: { role: string }) => message.role)).toEqual([ - 'user', - 'assistant', - 'tool', - 'tool', - ]); - expect(answerInput[1].parts).toEqual([ - { type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Berlin"}' }, - { type: 'tool_call', id: 'call_2', name: 'broken', arguments: '{}' }, - ]); - expect(answerInput[2].parts).toEqual([ - { - type: 'tool_call_response', - id: 'call_1', - name: 'get_weather', - result: 'It is 21 degrees and sunny in Berlin.', - }, - ]); - expect(chats.map(chat => chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).sort()).toEqual([ - '["stop"]', - '["tool_call"]', - ]); - expect(chats.map(chat => chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).join()).toContain( - 'It is 21 degrees and sunny in Berlin.', - ); - - const weather = spans.find(span => span.name === 'execute_tool get_weather')!; - expect(weather.parent_span_id).toBe(agent.span_id); - expect(weather.status).toBe('ok'); - expect(weather.attributes[SENTRY_OP]?.value).toBe(GEN_AI_EXECUTE_TOOL); - expect(weather.attributes[GEN_AI_TOOL_NAME]?.value).toBe('get_weather'); - expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.'); - expect(weather.attributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]?.value).toBe('call_1'); - expect(weather.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"city":"Berlin"}'); - expect(weather.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('sunny in Berlin'); - expect(weather.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); - - const broken = spans.find(span => span.name === 'execute_tool broken')!; - expect(broken.parent_span_id).toBe(agent.span_id); - expect(broken.status).toBe('error'); - // The error result pi-durable gives the model, not the thrown error. - expect(broken.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('[error] broken tool'); - - toolRunTraceId = agent.trace_id; - brokenToolSpanId = broken.span_id; - conversationIds.push(conversationId); - }, - }) - .expect({ - span: container => { - const spans = container.items; - const agent = spans.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - expect(spans).toHaveLength(2); - - const chat = spans.find(span => span.name === 'chat faux-model')!; - expect(chat.parent_span_id).toBe(agent.span_id); - expect(chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toContain('Goodbye.'); - - conversationIds.push(agent.attributes[GEN_AI_CONVERSATION_ID]?.value); - }, - }) - .expect({ - span: container => { - // The request that opened the Harness and submitted both inputs holds no agent work. - expect(container.items).toHaveLength(1); - expect(container.items[0]!.name).toBe('pi-durable-request'); - }, - }) - .expect({ - event: event => { - const exception = event.exception?.values?.[0]; - expect(exception?.value).toBe('broken tool'); - expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); - - errorTraceId = event.contexts?.trace?.trace_id; - errorSpanId = event.contexts?.trace?.span_id; - }, - }) - .start() - .completed(); - - // Both runs belong to the root conversation, so they share one conversation id. - expect(conversationIds).toHaveLength(2); - expect(conversationIds[0]).toBe(conversationIds[1]); - // The tool error is reported on the failing call's span, in the run's trace. - expect(errorTraceId).toBe(toolRunTraceId); - expect(errorSpanId).toBe(brokenToolSpanId); - }); - - 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(); - } - } - }, - }) - .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) => { - test('reports app tool failures but not failures of the built-in coding tools', async () => { - const appErrors: unknown[] = []; - - // Ordered, with spans ignored: a captured failure of the built-in `bash` tool would be an - // extra event before the sentinel, which the scenario sends once everything else is sent. - // The two app failures are processed concurrently, so they may arrive in either order. - await createRunner() - .ignore('span') - .expect({ - event: event => { - expect(['app read failed', 'Intentional pi-durable tool failure']).toContain( - event.exception?.values?.[0]?.value, - ); - appErrors.push(event.exception?.values?.[0]?.value); - }, - }) - .expect({ - event: event => { - expect(['app read failed', 'Intentional pi-durable tool failure']).toContain( - event.exception?.values?.[0]?.value, - ); - appErrors.push(event.exception?.values?.[0]?.value); - }, - }) - .expect({ - event: event => { - expect(event.message).toBe('pi-durable tools done'); - }, - }) - .start() - .completed(); - - expect(appErrors.sort()).toEqual(['Intentional pi-durable tool failure', 'app read failed']); - }); - - test('records the tool result the model receives', async () => { - let errorSpanId: string | undefined; - let failingToolSpanId: string | undefined; - - await createRunner() - .unordered() - .expect({ - event: event => { - const exception = event.exception?.values?.[0]; - expect(exception?.value).toBe('Intentional pi-durable tool failure'); - expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); - errorSpanId = event.contexts?.trace?.span_id; - }, - }) - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('app read failed'); - }, - }) - .expect({ - span: container => { - const spans = container.items; - - const bash = spans.find(span => span.name === 'execute_tool bash')!; - expect(bash.status).toBe('error'); - expect(bash.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toMatch(/Command exited with code \d+/); - - const read = spans.find(span => span.name === 'execute_tool read')!; - expect(read.status).toBe('error'); - expect(read.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('app read failed'); - - // The streamed output becomes the result, since the tool returns no content. - const streamer = spans.find(span => span.name === 'execute_tool streamer')!; - expect(streamer.status).toBe('ok'); - expect(streamer.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('line 1\nline 2\n'); - - const secret = spans.find(span => span.name === 'execute_tool secret')!; - expect(secret.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('redacted by afterTool'); - - const failNow = spans.find(span => span.name === 'execute_tool fail_now')!; - expect(failNow.status).toBe('error'); - failingToolSpanId = failNow.span_id; - }, - }) - .start() - .completed(); - - expect(errorSpanId).toBe(failingToolSpanId); - }); - }); - - createEsmTests(__dirname, 'scenario-reports.mjs', 'instrument.mjs', (createRunner, test) => { - test('captures failures pi-durable does not propagate, and tags idle compaction with its conversation', async () => { - let runConversationId: unknown; - let compactionConversationId: unknown; - - await createRunner() - .unordered() - .expect({ - event: event => { - const exception = event.exception?.values?.[0]; - expect(exception?.value).toBe('afterResponse hook failed'); - expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); - }, - }) - .expect({ - event: event => { - const exception = event.exception?.values?.[0]; - expect(exception?.value).toBe('card declined'); - expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); - }, - }) - .expect({ - span: container => { - const agent = container.items.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - runConversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; - }, - }) - .expect({ - span: container => { - // A compaction started while idle belongs to no run, so its request is a trace of its own. - expect(container.items).toHaveLength(1); - const summary = container.items[0]!; - expect(summary.is_segment).toBe(true); - expect(summary.attributes[SENTRY_OP]?.value).toBe(GEN_AI_CHAT); - compactionConversationId = summary.attributes[GEN_AI_CONVERSATION_ID]?.value; - }, - }) - .start() - .completed(); - - expect(runConversationId).toMatch(UUID); - expect(compactionConversationId).toBe(runConversationId); - }); - }); - - createEsmTests(__dirname, 'scenario-subagent.mjs', 'instrument.mjs', (createRunner, test) => { - test('nests subagent runs under the tool call that started them', async () => { - await createRunner() - .unordered() - .expect({ - span: container => { - const spans = container.items; - const parent = spans.find(span => span.is_segment)!; - const delegate = spans.find(span => span.name === 'execute_tool delegate')!; - expect(parent.name).toBe('invoke_agent'); - expect(delegate.parent_span_id).toBe(parent.span_id); - - // The subagent's run is a child of the delegating call, in the same trace, on its own - // conversation. - const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!; - expect(child.parent_span_id).toBe(delegate.span_id); - const parentConversation = String(parent.attributes[GEN_AI_CONVERSATION_ID]?.value); - const childConversation = String(child.attributes[GEN_AI_CONVERSATION_ID]?.value); - expect(parentConversation).toMatch(UUID); - expect(childConversation).toMatch(UUID); - expect(childConversation).not.toBe(parentConversation); - - const childChat = spans.find(span => span.parent_span_id === child.span_id)!; - expect(childChat.name).toBe('chat faux-model'); - expect(childChat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(childConversation); - expect(delegate.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Weather in Vienna?'); - }, - }) - .expect({ - span: container => { - const spans = container.items; - const parent = spans.find(span => span.is_segment)!; - const fork = spans.find(span => span.name === 'execute_tool fork_delegate')!; - const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!; - expect(fork.parent_span_id).toBe(parent.span_id); - expect(child.parent_span_id).toBe(fork.span_id); - expect(fork.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Forked task.'); - }, - }) - .expect({ - span: container => { - const spans = container.items; - const batch = spans.find(span => span.name === 'execute_tool batch')!; - const inner = spans.find(span => span.name === 'execute_tool inner')!; - expect(batch.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id); - // A tool that runs another tool itself: the inner call ends with its own result. - expect(inner.parent_span_id).toBe(batch.span_id); - expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT'); - expect(batch.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('OUTER RESULT'); - }, - }) - .expect({ - span: container => { - const spans = container.items; - const relay = spans.find(span => span.name === 'execute_tool relay')!; - const inner = spans.find(span => span.name === 'execute_tool inner')!; - expect(relay.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id); - // A nested call is a task of its own: its span is a child of the calling tool's span. - expect(inner.parent_span_id).toBe(relay.span_id); - expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT'); - expect(relay.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('RELAY RESULT'); - }, - }) - .start() - .completed(); - }); - }); - - createEsmTests(__dirname, 'scenario-retention.mjs', 'instrument.mjs', (createRunner, test) => { - // Bun does not implement `v8.setFlagsFromString`, which the scenario needs to force GC. - test.runIf(supports({ runtimes: ['node', 'deno'] }))( - 'does not keep the traces of tool calls alive for subagent conversations that never run', - async () => { - await createRunner() - .ignore('span') - .expect({ event: { message: 'pi-durable retention', extra: { toolCalls: 3, alive: 0 } } }) - .start() - .completed(); - }, - ); - }); - - createEsmTests(__dirname, 'scenario-restart-abort.mjs', 'instrument.mjs', (createRunner, test) => { - test('starts no run for an abort handler in a Harness that never saw the run', async () => { - await createRunner() - .ignore('span') - .expect({ - event: { - message: 'pi-durable restart abort', - extra: { status: 'unanswered', reason: 'aborted', runsStarted: 0 }, - }, - }) - .start() - .completed(); - }); - }); - - createEsmTests(__dirname, 'scenario-interrupted.mjs', 'instrument.mjs', (createRunner, test) => { - test('reports a provider that throws as a fault, and nothing for failed, aborted or closed runs', async () => { - await createRunner() - .ignore('span') - .expect({ - event: event => { - const exception = event.exception?.values?.[0]; - expect(exception?.value).toBe('provider broke'); - expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); - }, - }) - .expect({ - event: event => { - expect(event.message).toBe('pi-durable interrupted done'); - }, - }) - .start() - .completed(); - }); - - test('ends every run that does not end with an answer', async () => { - await createRunner() - .unordered() - .expect({ - span: container => { - // 1. The model request failed: the run and the request are errors. - const chat = container.items.find(span => span.name === 'chat faux-model')!; - expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail please.'); - expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["error"]'); - expect(chat.status).toBe('error'); - expect(chat.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('internal_error'); - const agent = container.items.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - expect(agent.status).toBe('error'); - expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error'); - }, - }) - .expect({ - span: container => { - // 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'); - }, - }) - .expect({ - span: container => { - // 3. Aborted while the tool ran: cancelled, which streamed spans report as ok. - const slow = container.items.find(span => span.name === 'execute_tool slow')!; - expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"abort"}'); - expect(slow.status).toBe('ok'); - expect(container.items.find(span => span.is_segment)!.status).toBe('ok'); - }, - }) - .expect({ - span: container => { - // 4. Aborted while the model request ran. - const chat = container.items.find(span => span.name === 'chat faux-model')!; - expect(chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).toBe('["aborted"]'); - expect(container.items).toHaveLength(2); - }, - }) - .expect({ - span: container => { - // 5. The Harness closed while the tool ran: the run still ends, so the trace has a segment. - const slow = container.items.find(span => span.name === 'execute_tool slow')!; - expect(slow.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"job":"close"}'); - const agent = container.items.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - expect(slow.parent_span_id).toBe(agent.span_id); - }, - }) - .expect({ - span: container => { - // 6. The run failed, and the Harness closed right after `wait()`, before the commit that - // ended the run resolved: the run keeps its own status. - const chat = container.items.find(span => span.name === 'chat faux-model')!; - expect(chat.attributes[GEN_AI_INPUT_MESSAGES]?.value).toContain('Fail, then close.'); - const agent = container.items.find(span => span.is_segment)!; - expect(agent.status).toBe('error'); - expect(agent.attributes[SENTRY_STATUS_MESSAGE]?.value).toBe('model_error'); - }, - }) - .start() - .completed(); - }); - }); - - createEsmTests(__dirname, 'scenario-concurrent.mjs', 'instrument.mjs', (createRunner, test) => { - test('keeps concurrent runs apart and out of the scopes of the requests that submitted them', async () => { - const runTraceIds = new Set(); - const errorTraceIds = new Set(); - - await createRunner() - .unordered() - .expect({ - span: container => { - const spans = container.items; - const agent = spans.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - const chats = spans.filter(span => span.name === 'chat faux-model'); - expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe( - 'request A', - ); - // The run's own conversation id, not the one the request set on its scope. - const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; - expect(conversationId).toMatch(UUID); - for (const span of spans) { - expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); - expect(span.attributes['request']).toBeUndefined(); - } - expect( - spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value, - ).toBe('{"tag":"request A"}'); - runTraceIds.add(agent.trace_id); - }, - }) - .expect({ - span: container => { - const spans = container.items; - const agent = spans.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - const chats = spans.filter(span => span.name === 'chat faux-model'); - expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe( - 'request B', - ); - const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; - expect(conversationId).toMatch(UUID); - for (const span of spans) { - expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); - expect(span.attributes['request']).toBeUndefined(); - } - expect( - spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value, - ).toBe('{"tag":"request B"}'); - runTraceIds.add(agent.trace_id); - }, - }) - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('work failed for request A'); - expect(event.tags?.request).toBeUndefined(); - errorTraceIds.add(String(event.contexts?.trace?.trace_id)); - }, - }) - .expect({ - event: event => { - expect(event.exception?.values?.[0]?.value).toBe('work failed for request B'); - expect(event.tags?.request).toBeUndefined(); - errorTraceIds.add(String(event.contexts?.trace?.trace_id)); - }, - }) - .start() - .completed(); - - // Each tool error belongs to its run's trace. - expect(errorTraceIds).toEqual(runTraceIds); - }); - }); - - createEsmTests(__dirname, 'scenario-compaction.mjs', 'instrument.mjs', (createRunner, test) => { - test('keeps a compaction that pi-durable starts for a run inside that run', async () => { - await createRunner() - .unordered() - .expect({ - span: container => { - const spans = container.items; - const summary = spans.find(span => - String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Summary'), - )!; - const agent = spans.find(span => span.is_segment)!; - expect(agent.name).toBe('invoke_agent'); - expect(summary.parent_span_id).toBe(agent.span_id); - // pi-durable completes the summary without streaming; the run's own request streams. - expect(summary.attributes[GEN_AI_RESPONSE_STREAMING]).toBeUndefined(); - const answer = spans.find(span => - String(span.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).includes('Third answer'), - )!; - expect(answer.parent_span_id).toBe(agent.span_id); - expect(answer.attributes[GEN_AI_RESPONSE_STREAMING]?.value).toBe(true); - }, - }) - .expect({ - span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'), - }) - .expect({ - span: container => expect(container.items.find(span => span.is_segment)!.name).toBe('invoke_agent'), - }) - .start() - .completed(); - }); - }); - - createEsmTests( - __dirname, - 'scenario-recording-functions.mjs', - 'instrument-with-recording-functions.mjs', - (createRunner, test) => { - test('decides content recording per call when the options are functions', async () => { - await createRunner() - .expect({ - span: container => { - const recorded = container.items - .filter(span => /^(chat|execute_tool) /.test(span.name)) - .sort((a, b) => a.start_timestamp - b.start_timestamp) - .map(({ name, attributes }) => [ - name, - GEN_AI_INPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_ARGUMENTS in attributes, - GEN_AI_OUTPUT_MESSAGES in attributes || GEN_AI_TOOL_CALL_RESULT in attributes, - ]); - expect(recorded).toEqual([ - ['chat faux-model', true, true], - ['execute_tool get_weather', false, false], - ['chat faux-model', true, false], - ]); - }, - }) - .start() - .completed(); - }); - }, - ); - - createEsmTests( - __dirname, - 'scenario-recording-functions.mjs', - 'instrument-with-span-hooks.mjs', - (createRunner, test) => { - test('runs the span hooks of the model and tool calls', async () => { - await createRunner() - .expect({ - span: container => { - const hooks = container.items - .filter(span => /^(chat|execute_tool) /.test(span.name)) - .sort((a, b) => a.start_timestamp - b.start_timestamp) - .map(({ attributes }) => [attributes['test.start']?.value, attributes['test.end']?.value]); - expect(hooks).toEqual([ - ['chat', 'toolUse'], - ['Berlin', 'It is sunny in Berlin.'], - ['chat', 'stop'], - ]); - }, - }) - .start() - .completed(); - }); - }, - ); -}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts new file mode 100644 index 000000000000..fb4db7dcd553 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tools.test.ts @@ -0,0 +1,100 @@ +import { GEN_AI_TOOL_CALL_RESULT } from '@sentry/conventions/attributes'; + +import { afterAll, describe, expect } from 'vitest'; + +import { supports } from '../../../utils'; +import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner'; + +// The pi packages declare `engines.node >= 22.19`. +describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmTests(__dirname, 'scenario-tools.mjs', 'instrument.mjs', (createRunner, test) => { + test('reports app tool failures but not failures of the built-in coding tools', async () => { + const appErrors: unknown[] = []; + + // Ordered, with spans ignored: a captured failure of the built-in `bash` tool would be an + // extra event before the sentinel, which the scenario sends once everything else is sent. + // The two app failures are processed concurrently, so they may arrive in either order. + await createRunner() + .ignore('span') + .expect({ + event: event => { + expect(['app read failed', 'Intentional pi-durable tool failure']).toContain( + event.exception?.values?.[0]?.value, + ); + appErrors.push(event.exception?.values?.[0]?.value); + }, + }) + .expect({ + event: event => { + expect(['app read failed', 'Intentional pi-durable tool failure']).toContain( + event.exception?.values?.[0]?.value, + ); + appErrors.push(event.exception?.values?.[0]?.value); + }, + }) + .expect({ + event: event => { + expect(event.message).toBe('pi-durable tools done'); + }, + }) + .start() + .completed(); + + expect(appErrors.sort()).toEqual(['Intentional pi-durable tool failure', 'app read failed']); + }); + + test('records the tool result the model receives', async () => { + let errorSpanId: string | undefined; + let failingToolSpanId: string | undefined; + + await createRunner() + .unordered() + .expect({ + event: event => { + const exception = event.exception?.values?.[0]; + expect(exception?.value).toBe('Intentional pi-durable tool failure'); + expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); + errorSpanId = event.contexts?.trace?.span_id; + }, + }) + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('app read failed'); + }, + }) + .expect({ + span: container => { + const spans = container.items; + + const bash = spans.find(span => span.name === 'execute_tool bash')!; + expect(bash.status).toBe('error'); + expect(bash.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toMatch(/Command exited with code \d+/); + + const read = spans.find(span => span.name === 'execute_tool read')!; + expect(read.status).toBe('error'); + expect(read.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('app read failed'); + + // The streamed output becomes the result, since the tool returns no content. + const streamer = spans.find(span => span.name === 'execute_tool streamer')!; + expect(streamer.status).toBe('ok'); + expect(streamer.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('line 1\nline 2\n'); + + const secret = spans.find(span => span.name === 'execute_tool secret')!; + expect(secret.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('redacted by afterTool'); + + const failNow = spans.find(span => span.name === 'execute_tool fail_now')!; + expect(failNow.status).toBe('error'); + failingToolSpanId = failNow.span_id; + }, + }) + .start() + .completed(); + + expect(errorSpanId).toBe(failingToolSpanId); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts new file mode 100644 index 000000000000..d431e01fa6cb --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/pi-durable/tracing.test.ts @@ -0,0 +1,321 @@ +import { + GEN_AI_CONVERSATION_ID, + 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_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_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, +} from '@sentry/conventions/attributes'; +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 { supports } from '../../../utils'; +import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner'; + +// The provider session id that pi-durable stores with each conversation, a UUIDv7. +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +// The pi packages declare `engines.node >= 22.19`. +describe.runIf(supports({ min: 22 }))('pi-durable integration', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + test('traces each run as its own invoke_agent trace with chat and execute_tool children', async () => { + let toolRunTraceId: string | undefined; + let brokenToolSpanId: string | undefined; + let errorTraceId: string | undefined; + let errorSpanId: string | undefined; + const conversationIds: unknown[] = []; + + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items; + 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 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( + 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'); + expect(agent.attributes[GEN_AI_OPERATION_NAME]?.value).toBe('invoke_agent'); + const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; + expect(conversationId).toMatch(UUID); + + const chats = spans + .filter(span => span.name === 'chat faux-model') + .sort((a, b) => a.start_timestamp - b.start_timestamp); + 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_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); + expect(chat.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBeGreaterThan(0); + expect(chat.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBeGreaterThan(0); + // pi-durable sends the prompt and the tools as positional system messages. + expect(chat.attributes[GEN_AI_SYSTEM_INSTRUCTIONS]?.value).toBe('You are a weather assistant.'); + expect( + JSON.parse(String(chat.attributes[GEN_AI_TOOL_DEFINITIONS]?.value)).map( + (tool: { name: string }) => tool.name, + ), + ).toEqual(['get_weather', 'broken']); + } + + // Mapped from pi-ai's shape to the conventions: the tool calls and tool results the + // second request carries are what Sentry's conversation view renders. + expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))).toEqual([ + { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Berlin?' }] }, + ]); + const answerInput = JSON.parse(String(chats[1]!.attributes[GEN_AI_INPUT_MESSAGES]?.value)); + expect(answerInput.map((message: { role: string }) => message.role)).toEqual([ + 'user', + 'assistant', + 'tool', + 'tool', + ]); + expect(answerInput[1].parts).toEqual([ + { type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Berlin"}' }, + { type: 'tool_call', id: 'call_2', name: 'broken', arguments: '{}' }, + ]); + expect(answerInput[2].parts).toEqual([ + { + type: 'tool_call_response', + id: 'call_1', + name: 'get_weather', + result: 'It is 21 degrees and sunny in Berlin.', + }, + ]); + expect(chats.map(chat => chat.attributes[GEN_AI_RESPONSE_FINISH_REASONS]?.value).sort()).toEqual([ + '["stop"]', + '["tool_call"]', + ]); + expect(chats.map(chat => chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).join()).toContain( + 'It is 21 degrees and sunny in Berlin.', + ); + + const weather = spans.find(span => span.name === 'execute_tool get_weather')!; + expect(weather.parent_span_id).toBe(agent.span_id); + expect(weather.status).toBe('ok'); + expect(weather.attributes[SENTRY_OP]?.value).toBe(GEN_AI_EXECUTE_TOOL); + expect(weather.attributes[GEN_AI_TOOL_NAME]?.value).toBe('get_weather'); + expect(weather.attributes[GEN_AI_TOOL_DESCRIPTION]?.value).toBe('Get the current weather for a city.'); + expect(weather.attributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE]?.value).toBe('call_1'); + expect(weather.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value).toBe('{"city":"Berlin"}'); + expect(weather.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('sunny in Berlin'); + expect(weather.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); + + const broken = spans.find(span => span.name === 'execute_tool broken')!; + expect(broken.parent_span_id).toBe(agent.span_id); + expect(broken.status).toBe('error'); + // The error result pi-durable gives the model, not the thrown error. + expect(broken.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toContain('[error] broken tool'); + + toolRunTraceId = agent.trace_id; + brokenToolSpanId = broken.span_id; + conversationIds.push(conversationId); + }, + }) + .expect({ + span: container => { + const spans = container.items; + const agent = spans.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + expect(spans).toHaveLength(2); + + const chat = spans.find(span => span.name === 'chat faux-model')!; + expect(chat.parent_span_id).toBe(agent.span_id); + expect(chat.attributes[GEN_AI_OUTPUT_MESSAGES]?.value).toContain('Goodbye.'); + + conversationIds.push(agent.attributes[GEN_AI_CONVERSATION_ID]?.value); + }, + }) + .expect({ + span: container => { + // The request that opened the Harness and submitted both inputs holds no agent work. + expect(container.items).toHaveLength(1); + expect(container.items[0]!.name).toBe('pi-durable-request'); + }, + }) + .expect({ + event: event => { + const exception = event.exception?.values?.[0]; + expect(exception?.value).toBe('broken tool'); + expect(exception?.mechanism).toEqual({ type: 'auto.ai.pi_durable', handled: false }); + + errorTraceId = event.contexts?.trace?.trace_id; + errorSpanId = event.contexts?.trace?.span_id; + }, + }) + .start() + .completed(); + + // Both runs belong to the root conversation, so they share one conversation id. + expect(conversationIds).toHaveLength(2); + expect(conversationIds[0]).toBe(conversationIds[1]); + // The tool error is reported on the failing call's span, in the run's trace. + expect(errorTraceId).toBe(toolRunTraceId); + expect(errorSpanId).toBe(brokenToolSpanId); + }); + }); + + createEsmTests(__dirname, 'scenario-subagent.mjs', 'instrument.mjs', (createRunner, test) => { + test('nests subagent runs under the tool call that started them', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items; + const parent = spans.find(span => span.is_segment)!; + const delegate = spans.find(span => span.name === 'execute_tool delegate')!; + expect(parent.name).toBe('invoke_agent'); + expect(delegate.parent_span_id).toBe(parent.span_id); + + // The subagent's run is a child of the delegating call, in the same trace, on its own + // conversation. + const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!; + expect(child.parent_span_id).toBe(delegate.span_id); + const parentConversation = String(parent.attributes[GEN_AI_CONVERSATION_ID]?.value); + const childConversation = String(child.attributes[GEN_AI_CONVERSATION_ID]?.value); + expect(parentConversation).toMatch(UUID); + expect(childConversation).toMatch(UUID); + expect(childConversation).not.toBe(parentConversation); + + const childChat = spans.find(span => span.parent_span_id === child.span_id)!; + expect(childChat.name).toBe('chat faux-model'); + expect(childChat.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(childConversation); + expect(delegate.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Weather in Vienna?'); + }, + }) + .expect({ + span: container => { + const spans = container.items; + const parent = spans.find(span => span.is_segment)!; + const fork = spans.find(span => span.name === 'execute_tool fork_delegate')!; + const child = spans.find(span => span.name === 'invoke_agent' && !span.is_segment)!; + expect(fork.parent_span_id).toBe(parent.span_id); + expect(child.parent_span_id).toBe(fork.span_id); + expect(fork.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('Answer: Forked task.'); + }, + }) + .expect({ + span: container => { + const spans = container.items; + const batch = spans.find(span => span.name === 'execute_tool batch')!; + const inner = spans.find(span => span.name === 'execute_tool inner')!; + expect(batch.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id); + // A tool that runs another tool itself: the inner call ends with its own result. + expect(inner.parent_span_id).toBe(batch.span_id); + expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT'); + expect(batch.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('OUTER RESULT'); + }, + }) + .expect({ + span: container => { + const spans = container.items; + const relay = spans.find(span => span.name === 'execute_tool relay')!; + const inner = spans.find(span => span.name === 'execute_tool inner')!; + expect(relay.parent_span_id).toBe(spans.find(span => span.is_segment)!.span_id); + // A nested call is a task of its own: its span is a child of the calling tool's span. + expect(inner.parent_span_id).toBe(relay.span_id); + expect(inner.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('INNER RESULT'); + expect(relay.attributes[GEN_AI_TOOL_CALL_RESULT]?.value).toBe('RELAY RESULT'); + }, + }) + .start() + .completed(); + }); + }); + + createEsmTests(__dirname, 'scenario-concurrent.mjs', 'instrument.mjs', (createRunner, test) => { + test('keeps concurrent runs apart and out of the scopes of the requests that submitted them', async () => { + const runTraceIds = new Set(); + const errorTraceIds = new Set(); + + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items; + const agent = spans.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + const chats = spans.filter(span => span.name === 'chat faux-model'); + expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe( + 'request A', + ); + // The run's own conversation id, not the one the request set on its scope. + const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; + expect(conversationId).toMatch(UUID); + for (const span of spans) { + expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); + expect(span.attributes['request']).toBeUndefined(); + } + expect( + spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value, + ).toBe('{"tag":"request A"}'); + runTraceIds.add(agent.trace_id); + }, + }) + .expect({ + span: container => { + const spans = container.items; + const agent = spans.find(span => span.is_segment)!; + expect(agent.name).toBe('invoke_agent'); + const chats = spans.filter(span => span.name === 'chat faux-model'); + expect(JSON.parse(String(chats[0]!.attributes[GEN_AI_INPUT_MESSAGES]?.value))[0].parts[0].content).toBe( + 'request B', + ); + const conversationId = agent.attributes[GEN_AI_CONVERSATION_ID]?.value; + expect(conversationId).toMatch(UUID); + for (const span of spans) { + expect(span.attributes[GEN_AI_CONVERSATION_ID]?.value).toBe(conversationId); + expect(span.attributes['request']).toBeUndefined(); + } + expect( + spans.find(span => span.name === 'execute_tool work')!.attributes[GEN_AI_TOOL_CALL_ARGUMENTS]?.value, + ).toBe('{"tag":"request B"}'); + runTraceIds.add(agent.trace_id); + }, + }) + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('work failed for request A'); + expect(event.tags?.request).toBeUndefined(); + errorTraceIds.add(String(event.contexts?.trace?.trace_id)); + }, + }) + .expect({ + event: event => { + expect(event.exception?.values?.[0]?.value).toBe('work failed for request B'); + expect(event.tags?.request).toBeUndefined(); + errorTraceIds.add(String(event.contexts?.trace?.trace_id)); + }, + }) + .start() + .completed(); + + // Each tool error belongs to its run's trace. + expect(errorTraceIds).toEqual(runTraceIds); + }); + }); +}); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs new file mode 100644 index 000000000000..726f9e18f2c1 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/scenario-extract.mjs @@ -0,0 +1,29 @@ +import * as Sentry from '@sentry/node'; +import { experimental_extract } from 'ai'; +import { Experimental_ExtractionMockModelV4 } from 'ai/test'; + +async function run() { + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + await experimental_extract({ + model: new Experimental_ExtractionMockModelV4({ + provider: 'gateway', + modelId: 'cloudflare/clairic', + doExtract: async () => ({ + answers: { + invoiceNumber: { type: 'text', value: 'INV-2291', confidence: 0.98 }, + total: { type: 'number', value: 1080, confidence: 0.95 }, + }, + usage: { inputTokens: 50, outputTokens: 4 }, + warnings: [], + }), + }), + state: 'Invoice INV-2291 from Northwind Supply. Total due: $1,080.', + fields: { + invoiceNumber: { type: 'text', instructions: 'The invoice number' }, + total: { type: 'number', instructions: 'The total amount due' }, + }, + }); + }); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts index f6059b7ad0e0..4ee62ba8d1e7 100644 --- a/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/vercelai/v6_v7/v7/generation/test.ts @@ -11,16 +11,27 @@ import { GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_ENVIRONMENT, + SENTRY_IS_LOCALHOST, SENTRY_OP, SENTRY_ORIGIN, + SENTRY_RELEASE, + SENTRY_SDK_NAME, + SENTRY_SDK_VERSION, + SENTRY_SEGMENT_ID, + SENTRY_SEGMENT_NAME, + SENTRY_TRACE_LIFECYCLE, } from '@sentry/conventions/attributes'; import { GEN_AI_DECIDE, GEN_AI_EXECUTE_TOOL, + GEN_AI_EXTRACT, GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT, } from '@sentry/conventions/op'; -import { SUPPORTS_REQUIRE_OF_ESM } from '../../../../../../utils'; +import type { SerializedStreamedSpan } from '@sentry/core'; +import { SDK_VERSION } from '@sentry/core'; +import { EXPECTED_SDK_NAME, SUPPORTS_REQUIRE_OF_ESM } from '../../../../../../utils'; import { cleanupChildProcesses, createEsmAndCjsTests, createEsmTests } from '../../../../../../utils/runner'; import { registerVercelAiGenerationTests } from '../../suite'; import { join } from 'node:path'; @@ -134,6 +145,120 @@ describe('Vercel AI integration experimental_decide', () => { ); }); +describe('Vercel AI integration experimental_extract', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + function getExtractSpans(container: { items: SerializedStreamedSpan[] }): { + extractSpan: SerializedStreamedSpan; + segmentSpan: SerializedStreamedSpan; + } { + const extractSpans = container.items.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_EXTRACT); + expect(extractSpans).toHaveLength(1); + return { extractSpan: extractSpans[0]!, segmentSpan: container.items.find(span => span.is_segment)! }; + } + + function expectedBaseAttributes(segmentSpan: SerializedStreamedSpan): Record { + return { + [SENTRY_ORIGIN]: { type: 'string', value: 'auto.ai.vercelai' }, + [SENTRY_OP]: { type: 'string', value: GEN_AI_EXTRACT }, + [GEN_AI_OPERATION_NAME]: { type: 'string', value: 'extract' }, + [GEN_AI_PROVIDER_NAME]: { type: 'string', value: 'gateway' }, + 'vercel.ai.model.provider': { type: 'string', value: 'gateway' }, + [GEN_AI_REQUEST_MODEL]: { type: 'string', value: 'cloudflare/clairic' }, + 'vercel.ai.settings.maxRetries': { type: 'integer', value: 2 }, + [GEN_AI_USAGE_INPUT_TOKENS]: { type: 'integer', value: 50 }, + [GEN_AI_USAGE_OUTPUT_TOKENS]: { type: 'integer', value: 4 }, + [GEN_AI_USAGE_TOTAL_TOKENS]: { type: 'integer', value: 54 }, + [GEN_AI_RESPONSE_MODEL]: { type: 'string', value: 'cloudflare/clairic' }, + [SENTRY_TRACE_LIFECYCLE]: { type: 'string', value: 'stream' }, + [SENTRY_SEGMENT_NAME]: { type: 'string', value: segmentSpan.name }, + [SENTRY_SEGMENT_ID]: { type: 'string', value: segmentSpan.span_id }, + [SENTRY_SDK_NAME]: { type: 'string', value: EXPECTED_SDK_NAME }, + [SENTRY_SDK_VERSION]: { type: 'string', value: SDK_VERSION }, + [SENTRY_RELEASE]: { type: 'string', value: '1.0' }, + [SENTRY_ENVIRONMENT]: { type: 'string', value: 'production' }, + [SENTRY_IS_LOCALHOST]: { type: 'boolean', value: false }, + }; + } + + createEsmTests( + join(__dirname, '../..'), + 'scenario-extract.mjs', + 'instrument-decide.mjs', + (createRunner, test) => { + test('creates an extract span', async () => { + await createRunner() + .expect({ + span: container => { + const { extractSpan, segmentSpan } = getExtractSpans(container); + expect(extractSpan.name).toBe('extract cloudflare/clairic'); + expect(extractSpan.status).toBe('ok'); + expect(extractSpan.attributes).toEqual({ + ...expectedBaseAttributes(segmentSpan), + [GEN_AI_INPUT_MESSAGES]: { + type: 'string', + value: JSON.stringify([ + { + state: 'Invoice INV-2291 from Northwind Supply. Total due: $1,080.', + fields: { + invoiceNumber: { type: 'text', instructions: 'The invoice number' }, + total: { type: 'number', instructions: 'The total amount due' }, + }, + }, + ]), + }, + [GEN_AI_OUTPUT_MESSAGES]: { + type: 'string', + value: JSON.stringify([ + { + answers: { + invoiceNumber: { type: 'text', value: 'INV-2291', confidence: 0.98 }, + total: { type: 'number', value: 1080, confidence: 0.95 }, + }, + }, + ]), + }, + }); + }, + }) + .start() + .completed(); + }); + }, + { + additionalDependencies: { + ai: '^7.0.178', + }, + }, + ); + + createEsmTests( + join(__dirname, '../..'), + 'scenario-extract.mjs', + 'instrument-decide-no-recording.mjs', + (createRunner, test) => { + test('does not record inputs or outputs when recording is off', async () => { + await createRunner() + .expect({ + span: container => { + const { extractSpan, segmentSpan } = getExtractSpans(container); + expect(extractSpan.attributes).toEqual(expectedBaseAttributes(segmentSpan)); + }, + }) + .start() + .completed(); + }); + }, + { + additionalDependencies: { + ai: '^7.0.178', + }, + }, + ); +}); + describe('Vercel AI runtime and tool context (v7)', () => { afterAll(() => { cleanupChildProcesses(); diff --git a/dev-packages/node-integration-tests/utils/runner/createRunner.ts b/dev-packages/node-integration-tests/utils/runner/createRunner.ts index e555f1d483df..f9a2258bd590 100644 --- a/dev-packages/node-integration-tests/utils/runner/createRunner.ts +++ b/dev-packages/node-integration-tests/utils/runner/createRunner.ts @@ -801,7 +801,16 @@ export function createRunner(...paths: string[]) { } = {}, ): Promise { try { - await waitForEvent(portReady.promise, PORT_TIMEOUT, 'Timed out waiting for server port'); + await waitForEvent( + Promise.race([ + portReady.promise, + Promise.race([completedDeferred.promise, exitedDeferred.promise]).then(() => { + throw completeError ?? new Error('Scenario stopped before reporting its server port'); + }), + ]), + PORT_TIMEOUT, + 'Timed out waiting for server port', + ); } catch (e) { complete(e as Error); return; diff --git a/dev-packages/node-integration-tests/vite.config.ts b/dev-packages/node-integration-tests/vite.config.ts index cb56054fadcd..ad01a4483376 100644 --- a/dev-packages/node-integration-tests/vite.config.ts +++ b/dev-packages/node-integration-tests/vite.config.ts @@ -6,7 +6,7 @@ export default defineConfig({ test: { ...baseConfig.test, isolate: false, - include: ['./**/test.ts'], + include: ['./**/test.ts', './suites/**/*.test.ts'], testTimeout: 15000, // Ensure we can see debug output when DEBUG=true ...(process.env.DEBUG diff --git a/dev-packages/size-limit-gh-action/index.mjs b/dev-packages/size-limit-gh-action/index.mjs index b23a752b1e94..8331e61e6b15 100644 --- a/dev-packages/size-limit-gh-action/index.mjs +++ b/dev-packages/size-limit-gh-action/index.mjs @@ -7,8 +7,8 @@ import { getExecOutput } from '@actions/exec'; import { context, getOctokit } from '@actions/github'; import { markdownTable } from 'markdown-table'; import sizeConfig from '../../.size-limit.js'; -import { getArtifactsForBranchAndWorkflow } from './utils/getArtifactsForBranchAndWorkflow.mjs'; -import { MAX_INCREASE_BYTES, SizeLimitFormatter } from './utils/SizeLimitFormatter.mjs'; +import { getArtifactForBranch } from './utils/artifacts.mjs'; +import { formatResults, getSizeIncreases, MAX_INCREASE_BYTES, parseResults } from './utils/results.mjs'; const OVERRIDE_LABEL = 'Accept Bundlesize Increase'; const RELEASE_BRANCH_PREFIX = 'prepare-release/'; @@ -16,196 +16,210 @@ const SIZE_LIMIT_HEADING = '## size-limit report 📦 '; const ARTIFACT_NAME = 'size-limit-action'; const ACTION_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)); const RESULTS_FILE_PATH = path.join(ACTION_DIRECTORY, 'size-limit-results.json'); +const WORKFLOW_FILE = path.basename(process.env.GITHUB_WORKFLOW_REF.split('@')[0]); +const REPO_URL = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`; -const { getInput, setFailed } = core; +const NO_BASELINE_FAILURE = 'No baseline size measurements found. Re-run after the base build completes.'; +const INCREASE_FAILURE = + `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` + + `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`; + +const artifactClient = new DefaultArtifactClient(); async function run() { - try { - const { payload, repo } = context; - const pr = payload.pull_request; + // Only set on PRs, where it is the PR's base branch + const comparisonBranch = core.getInput('comparison_branch'); + const githubToken = core.getInput('github_token'); + const octokit = getOctokit(githubToken); + const pr = context.payload.pull_request; + + if (comparisonBranch && !pr) { + throw new Error('No PR found. Only pull_request workflows are supported.'); + } - // The comparison branch is the base branch we are comparing against (in our case usually develop) - const comparisonBranch = getInput('comparison_branch'); - const githubToken = getInput('github_token'); + const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']); + const current = parseResults(stdout); - if (comparisonBranch && !pr) { - throw new Error('No PR found. Only pull_request workflows are supported.'); - } + if (!comparisonBranch) { + await uploadResults(current); + return; + } - const octokit = getOctokit(githubToken); - let increaseAccepted = false; + const mergedBaseSha = await getMergedBaseSha(octokit); + const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch }); - if (comparisonBranch) { - const { data: currentPr } = await octokit.rest.pulls.get({ - ...repo, - pull_number: pr.number, - }); - increaseAccepted = currentPr.labels.some(label => label.name === OVERRIDE_LABEL); - } + const hasIncrease = baseline ? getSizeIncreases(baseline.results, current, sizeConfig).length > 0 : false; + const bodyParts = [SIZE_LIMIT_HEADING]; + let failure; - const limit = new SizeLimitFormatter(); - const artifactClient = new DefaultArtifactClient(); + if (baseline) { + bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }))); + } - // Build and measure each bundle defined in .size-limit.js for the current branch - const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']); - const current = limit.parseResults(stdout); + if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) { + // Release PRs target master, which has no baseline and would include every change since the last release anyway + core.info('Release PR detected. Reporting bundle sizes without enforcing limits.'); + } else if (!baseline) { + failure = NO_BASELINE_FAILURE; + bodyParts.push(failure); + } else if (hasIncrease && !(await hasLabel(octokit, pr, OVERRIDE_LABEL))) { + failure = INCREASE_FAILURE; + } - // If we have no comparison branch, we only store the results as artifacts (likely running on develop) - if (!comparisonBranch) { - await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(current), 'utf8'); - await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); - return; - } + bodyParts.push(markdownTable(formatResults(baseline?.results, current))); + if (baseline) { + bodyParts.push(`[View base workflow run](${baseline.workflowRun.html_url})`); + } - // Else, we fetch the results for the comparison branch and compare them with the current branch (likely running on a PR) - let base; - let baseWorkflowRun; - - try { - const workflowName = process.env.GITHUB_WORKFLOW; - core.startGroup(`getArtifactsForBranchAndWorkflow - workflow:"${workflowName}", branch:"${comparisonBranch}"`); - const artifacts = await getArtifactsForBranchAndWorkflow(octokit, { - ...repo, - artifactName: ARTIFACT_NAME, - branch: comparisonBranch, - workflowName, - }); - core.endGroup(); - - if (!artifacts) { - throw new Error('No artifacts found'); - } - - baseWorkflowRun = artifacts.workflowRun; - - await artifactClient.downloadArtifact(artifacts.artifact.id, { - path: ACTION_DIRECTORY, - findBy: { - token: githubToken, - workflowRunId: artifacts.workflowRun.id, - repositoryOwner: repo.owner, - repositoryName: repo.repo, - }, - }); - - base = JSON.parse(await fs.readFile(RESULTS_FILE_PATH, { encoding: 'utf8' })); - } catch (error) { - core.startGroup('Warning, unable to find base results'); - core.error(error); - core.endGroup(); - } + const body = bodyParts.join('\n\n'); + await core.summary.addRaw(body).write(); + await updatePrComments(octokit, pr, { body, failure }); - const increases = base ? limit.getSizeIncreases(base, current, sizeConfig) : []; - const bodyParts = [SIZE_LIMIT_HEADING]; - - // Check if our baseline build is up to date with the target branch (likely develop) and report any mismatches - if (base) { - const baselineSha = baseWorkflowRun.head_sha; // The commit SHA of the baseline build (where we pull the size-limit results from) - const repoUrl = `${context.serverUrl}/${repo.owner}/${repo.repo}`; - const commitLink = sha => `[${sha.slice(0, 7)}](${repoUrl}/commit/${sha})`; - - try { - const { data: mergeCommit } = await octokit.rest.repos.getCommit({ ...repo, ref: context.sha }); - const mergedBaseSha = mergeCommit.parents[0].sha; // The SHA of the target branch (likely develop) base commit that was used to test this PR - - bodyParts.push( - `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`, - `Against: ${commitLink(baselineSha)} (${comparisonBranch}) · [base run #${baseWorkflowRun.run_number}](${baseWorkflowRun.html_url})`, - ); - - if (baselineSha === mergedBaseSha) { - bodyParts.push("✅ Baseline matches: this diff contains only this PR's changes."); - } else { - const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({ - ...repo, - basehead: `${baselineSha}...${mergedBaseSha}`, - }); - const differences = []; - if (comparison.ahead_by > 0) { - differences.push( - `${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`, - ); - } - if (comparison.behind_by > 0) { - differences.push( - `${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`, - ); - } - const guidance = - comparison.behind_by > 0 - ? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.` - : `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`; - bodyParts.push( - `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` + - `[Compare commits](${comparison.html_url}). ${guidance}`, - ); - } - } catch (error) { - core.warning(`Unable to check baseline alignment: ${error.message}`); - bodyParts.push('⚠️ Unable to verify whether the baseline matches the PR build.'); - } - } + if (failure) { + core.setFailed(failure); + } +} - let failure; - if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) { - // Release PRs target master, which has no baseline and would include every change since the last release anyway - core.info('Release PR detected. Reporting bundle sizes without enforcing limits.'); - } else if (!base) { - failure = 'No baseline size measurements found. Re-run after the base build completes.'; - bodyParts.push(failure); - } else if (increases.length > 0 && !increaseAccepted) { - failure = - `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` + - `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`; +async function uploadResults(results) { + await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(results), 'utf8'); + await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); +} + +/** + * On PRs, GitHub checks out a merge of the PR into its base branch (`refs/pull//merge`). Its first parent is the + * base branch commit this PR is compared against. + */ +async function getMergedBaseSha(octokit) { + try { + const { data } = await octokit.rest.repos.getCommit({ ...context.repo, ref: context.sha }); + return data.parents[0].sha; + } catch (error) { + core.warning(`Unable to resolve the base commit of the PR test merge: ${error.message}`); + return undefined; + } +} + +async function downloadBaseline(octokit, githubToken, { comparisonBranch }) { + try { + const found = await getArtifactForBranch(octokit, { + workflow: WORKFLOW_FILE, + branch: comparisonBranch, + artifactName: ARTIFACT_NAME, + }); + + if (!found) { + throw new Error('No artifacts found'); } - bodyParts.push(markdownTable(limit.formatResults(base, current))); - if (baseWorkflowRun) { - bodyParts.push(`[View base workflow run](${baseWorkflowRun.html_url})`); + await artifactClient.downloadArtifact(found.artifact.id, { + path: ACTION_DIRECTORY, + findBy: { + token: githubToken, + workflowRunId: found.workflowRun.id, + repositoryOwner: context.repo.owner, + repositoryName: context.repo.repo, + }, + }); + + return { + results: JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')), + sha: found.workflowRun.head_sha, + workflowRun: found.workflowRun, + }; + } catch (error) { + core.warning(`Unable to find base results: ${error.message}`); + return undefined; + } +} + +/** + * Report which commits were compared, and whether the baseline contains exactly what this PR was tested against. + */ +async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }) { + const unverified = '⚠️ Unable to verify whether the baseline matches the PR build.'; + if (!mergedBaseSha) { + return [unverified]; + } + + const { sha, workflowRun } = baseline; + const parts = [ + `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`, + `Against: ${commitLink(sha)} (${comparisonBranch}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`, + ]; + + if (sha === mergedBaseSha) { + parts.push("✅ Baseline matches: this diff contains only this PR's changes."); + return parts; + } + + try { + const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({ + ...context.repo, + basehead: `${sha}...${mergedBaseSha}`, + }); + const differences = []; + if (comparison.ahead_by > 0) { + differences.push( + `${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`, + ); + } + if (comparison.behind_by > 0) { + differences.push( + `${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`, + ); } + const guidance = + comparison.behind_by > 0 + ? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.` + : `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`; + parts.push( + `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` + + `[Compare commits](${comparison.html_url}). ${guidance}`, + ); + } catch (error) { + core.warning(`Unable to check baseline alignment: ${error.message}`); + parts.push(unverified); + } + + return parts; +} + +async function hasLabel(octokit, pr, label) { + const { data } = await octokit.rest.pulls.get({ ...context.repo, pull_number: pr.number }); + return data.labels.some(({ name }) => name === label); +} - const body = bodyParts.join('\n\n'); - await core.summary.addRaw(body).write(); - - try { - const comments = await octokit.paginate(octokit.rest.issues.listComments, { - ...repo, - issue_number: pr.number, - per_page: 100, - }); - const sizeLimitComment = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING)); - if (sizeLimitComment) { - await octokit.rest.issues.updateComment({ - ...repo, - comment_id: sizeLimitComment.id, - body, - }); - } else { - await octokit.rest.issues.createComment({ - ...repo, - issue_number: pr.number, - body, - }); - } - - if (failure && increases.length > 0 && !comments.some(comment => comment.body === failure)) { - await octokit.rest.issues.createComment({ - ...repo, - issue_number: pr.number, - body: failure, - }); - } - } catch { - core.warning('Unable to update PR comments. The size report is available in the job summary.'); +/** + * Keep one size report comment up to date. A size increase also gets its own comment, which notifies the author. + */ +async function updatePrComments(octokit, pr, { body, failure }) { + try { + const comments = await octokit.paginate(octokit.rest.issues.listComments, { + ...context.repo, + issue_number: pr.number, + per_page: 100, + }); + + const report = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING)); + if (report) { + await octokit.rest.issues.updateComment({ ...context.repo, comment_id: report.id, body }); + } else { + await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body }); } - if (failure) { - setFailed(failure); + if (failure === INCREASE_FAILURE && !comments.some(comment => comment.body === failure)) { + await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body: failure }); } - } catch (error) { - core.error(error); - setFailed(error.message); + } catch { + core.warning('Unable to update PR comments. The size report is available in the job summary.'); } } -await run(); +function commitLink(sha) { + return `[${sha.slice(0, 7)}](${REPO_URL}/commit/${sha})`; +} + +await run().catch(error => { + core.error(error); + core.setFailed(error.message); +}); diff --git a/dev-packages/size-limit-gh-action/package.json b/dev-packages/size-limit-gh-action/package.json index 828f16819b39..ed6d2eaa289c 100644 --- a/dev-packages/size-limit-gh-action/package.json +++ b/dev-packages/size-limit-gh-action/package.json @@ -1,6 +1,6 @@ { "name": "@sentry-internal/size-limit-gh-action", - "description": "An internal Github Action to compare the current size of a PR against the one on develop.", + "description": "An internal Github Action to compare the bundle sizes of a PR against its base.", "version": "11.17.0", "license": "MIT", "engines": { diff --git a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs b/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs deleted file mode 100644 index 8e1449f2df7a..000000000000 --- a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs +++ /dev/null @@ -1,106 +0,0 @@ -import bytes from 'bytes-iec'; - -export const MAX_INCREASE_BYTES = 500; - -const SIZE_RESULTS_HEADER = ['Path', 'Size', '% Change', 'Change']; - -const EmptyResult = { - name: '-', - size: 0, -}; - -export class SizeLimitFormatter { - formatBytes(size) { - return bytes.format(size, { unitSeparator: ' ' }); - } - - formatPercentageChange(base = 0, current = 0) { - if (base === 0) { - return 'added'; - } - - if (current === 0) { - return 'removed'; - } - - const value = ((current - base) / base) * 100; - const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100; - - if (value > 0) { - return `+${formatted}%`; - } - - if (value === 0) { - return '-'; - } - - return `${formatted}%`; - } - - formatChange(base = 0, current = 0) { - if (base === 0) { - return 'added'; - } - - if (current === 0) { - return 'removed'; - } - - const value = current - base; - const formatted = this.formatBytes(value); - - if (value > 0) { - return `+${formatted} 🔺`; - } - - if (value === 0) { - return '-'; - } - - return `${formatted} 🔽`; - } - - formatSizeResult(name, base, current) { - return [ - name, - this.formatBytes(current.size), - this.formatPercentageChange(base.size, current.size), - this.formatChange(base.size, current.size), - ]; - } - - parseResults(output) { - const results = JSON.parse(output); - - return results.reduce( - (current, result) => ({ - ...current, - [result.name]: { - name: result.name, - size: result.size, - }, - }), - {}, - ); - } - - getSizeIncreases(base, current, config) { - return config - .filter(({ name, gzip }) => gzip === true && base[name]) - .map(({ name }) => ({ name, increase: current[name].size - base[name].size })) - .filter(({ increase }) => increase > MAX_INCREASE_BYTES); - } - - formatResults(base, current) { - const names = [...new Set([...(base ? Object.keys(base) : []), ...Object.keys(current)])]; - const header = SIZE_RESULTS_HEADER; - const fields = names.map(name => { - const baseResult = base?.[name] || EmptyResult; - const currentResult = current[name] || EmptyResult; - - return this.formatSizeResult(name, baseResult, currentResult); - }); - - return [header, ...fields]; - } -} diff --git a/dev-packages/size-limit-gh-action/utils/artifacts.mjs b/dev-packages/size-limit-gh-action/utils/artifacts.mjs new file mode 100644 index 000000000000..0dbe1ee48178 --- /dev/null +++ b/dev-packages/size-limit-gh-action/utils/artifacts.mjs @@ -0,0 +1,58 @@ +import * as core from '@actions/core'; +import { context } from '@actions/github'; + +const MAX_COMMITS = 50; + +/** + * Find the newest `artifactName` artifact on `branch`. This walks the branch's commits, because listing workflow runs by + * branch is eventually consistent and can silently skip the most recent runs. + */ +export async function getArtifactForBranch(octokit, { workflow, branch, artifactName }) { + const { data: commits } = await octokit.rest.repos.listCommits({ + ...context.repo, + sha: branch, + per_page: MAX_COMMITS, + }); + + for (const [index, { sha }] of commits.entries()) { + const found = await getArtifactForCommit(octokit, { workflow, sha, artifactName }); + if (found) { + if (index > 0) { + core.info(`Using results from ${sha}, which is ${index} commit(s) behind the tip of "${branch}".`); + } + return found; + } + } + + core.warning(`No "${artifactName}" artifact found in the last ${commits.length} commits of "${branch}".`); + return null; +} + +async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) { + for (const workflowRun of await listRunsForCommit(octokit, { workflow, sha })) { + const { data } = await octokit.rest.actions.listWorkflowRunArtifacts({ ...context.repo, run_id: workflowRun.id }); + const artifact = data.artifacts.find(({ name }) => name === artifactName); + if (artifact) { + core.info(`Found "${artifactName}" for commit ${sha} in ${workflowRun.html_url}`); + return { artifact, workflowRun }; + } + } + + return null; +} + +/** + * Newest first. Runs from forks are never trusted. + */ +async function listRunsForCommit(octokit, { workflow, sha }) { + const { data } = await octokit.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: workflow, + head_sha: sha, + per_page: 100, + }); + + return data.workflow_runs + .filter(run => run.head_repository?.full_name === `${context.repo.owner}/${context.repo.repo}`) + .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); +} diff --git a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs b/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs deleted file mode 100644 index 7e0b28d4c278..000000000000 --- a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import * as core from '@actions/core'; - -// How many commits to walk back on the branch before giving up on finding a build with a size-limit artifact. -const DEFAULT_MAX_COMMITS = 50; -const COMMITS_PER_PAGE = 100; -const RUNS_PER_PAGE = 100; - -/** - * Find the most recent build artifact for a branch by walking its git history. - * - * We deliberately drive this from `repos.listCommits` (authoritative, strictly ordered git history) rather than from - * `listWorkflowRuns` filtered by branch + event. That listing is backed by an eventually-consistent index that can omit - * or reorder very recent runs, which previously made us silently compare against a days-old baseline while still - * reporting it as the latest one. Walking commits newest-first and pinning each run by `head_sha` sidesteps that: the - * order is exact, and if the tip commit has no artifact yet we fall back to its parent and correctly report the baseline - * as not-latest. - */ -export async function getArtifactsForBranchAndWorkflow(octokit, { owner, repo, workflowName, branch, artifactName }) { - const workflowId = await findWorkflowId(octokit, { owner, repo, workflowName }); - - if (!workflowId) { - return null; - } - - let commitsChecked = 0; - - for await (const response of octokit.paginate.iterator(octokit.rest.repos.listCommits, { - owner, - repo, - sha: branch, - per_page: COMMITS_PER_PAGE, - })) { - for (const { sha } of response.data) { - const isLatest = commitsChecked === 0; - commitsChecked++; - - const found = await findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName }); - - if (found) { - if (!isLatest) { - core.info( - `Base artifact comes from commit ${sha}, which is ${commitsChecked - 1} commit(s) behind the tip of "${branch}".`, - ); - } - return { ...found, isLatest }; - } - - if (commitsChecked >= DEFAULT_MAX_COMMITS) { - core.warning( - `No "${artifactName}" artifact found within the last ${DEFAULT_MAX_COMMITS} commits of "${branch}".`, - ); - return null; - } - } - } - - core.warning(`No "${artifactName}" artifact found on branch "${branch}".`); - return null; -} - -/** - * Resolve a workflow's numeric id from its display name. - */ -async function findWorkflowId(octokit, { owner, repo, workflowName }) { - const allWorkflows = []; - - for await (const response of octokit.paginate.iterator(octokit.rest.actions.listRepoWorkflows, { owner, repo })) { - const targetWorkflow = response.data.find(({ name }) => name === workflowName); - allWorkflows.push(...response.data.map(({ name }) => name)); - - if (targetWorkflow) { - return targetWorkflow.id; - } - } - - core.info( - `Unable to find workflow with name "${workflowName}" in the repository. Found workflows: ${allWorkflows.join(', ')}`, - ); - return null; -} - -/** - * Return the first `artifactName` artifact produced by any run of `workflowId` for the exact `sha`, preferring the most - * recent run (in case of re-runs). Runs originating from a fork are never trusted. - */ -async function findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName }) { - const { - data: { workflow_runs: workflowRuns }, - } = await octokit.rest.actions.listWorkflowRuns({ - owner, - repo, - workflow_id: workflowId, - head_sha: sha, - per_page: RUNS_PER_PAGE, - }); - - const runs = workflowRuns - .filter(workflowRun => workflowRun.head_repository?.full_name === `${owner}/${repo}`) - .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); - - for (const workflowRun of runs) { - const { - data: { artifacts }, - } = await octokit.rest.actions.listWorkflowRunArtifacts({ - owner, - repo, - run_id: workflowRun.id, - }); - - const artifact = artifacts?.find(({ name }) => name === artifactName); - if (artifact) { - core.info(`Found suitable artifact for commit ${sha}: ${artifact.url} (run ${workflowRun.html_url})`); - return { artifact, workflowRun }; - } - } - - return null; -} diff --git a/dev-packages/size-limit-gh-action/utils/results.mjs b/dev-packages/size-limit-gh-action/utils/results.mjs new file mode 100644 index 000000000000..9cbdfc145bb6 --- /dev/null +++ b/dev-packages/size-limit-gh-action/utils/results.mjs @@ -0,0 +1,69 @@ +import bytes from 'bytes-iec'; + +export const MAX_INCREASE_BYTES = 500; + +export function parseResults(output) { + return Object.fromEntries(JSON.parse(output).map(({ name, size }) => [name, { name, size }])); +} + +export function getSizeIncreases(base, current, config) { + return config + .filter(({ name, gzip }) => gzip === true && base[name]) + .map(({ name }) => ({ name, increase: current[name].size - base[name].size })) + .filter(({ increase }) => increase > MAX_INCREASE_BYTES); +} + +export function formatResults(base, current) { + const names = [...new Set([...Object.keys(base ?? {}), ...Object.keys(current)])]; + + return [ + ['Path', 'Size', '% Change', 'Change'], + ...names.map(name => { + const baseSize = base?.[name]?.size ?? 0; + const currentSize = current[name]?.size ?? 0; + return [ + name, + formatBytes(currentSize), + formatPercentageChange(baseSize, currentSize), + formatChange(baseSize, currentSize), + ]; + }), + ]; +} + +function formatBytes(size) { + return bytes.format(size, { unitSeparator: ' ' }); +} + +function formatPercentageChange(base, current) { + if (base === 0) { + return 'added'; + } + if (current === 0) { + return 'removed'; + } + + const value = ((current - base) / base) * 100; + const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100; + + if (value > 0) { + return `+${formatted}%`; + } + return value === 0 ? '-' : `${formatted}%`; +} + +function formatChange(base, current) { + if (base === 0) { + return 'added'; + } + if (current === 0) { + return 'removed'; + } + + const value = current - base; + + if (value > 0) { + return `+${formatBytes(value)} 🔺`; + } + return value === 0 ? '-' : `${formatBytes(value)} 🔽`; +} diff --git a/dev-packages/test-utils/package.json b/dev-packages/test-utils/package.json index 7ae64d616150..a5322ab61c31 100644 --- a/dev-packages/test-utils/package.json +++ b/dev-packages/test-utils/package.json @@ -71,7 +71,7 @@ "@playwright/test": "1.64.1" }, "dependencies": { - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "express": "^4.22.3", "ws": "^8.20.1" }, diff --git a/packages/angular/.oxlintrc.json b/packages/angular/.oxlintrc.json index 915515b69e92..9a229b793d98 100644 --- a/packages/angular/.oxlintrc.json +++ b/packages/angular/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "jsPlugins": [ { "name": "sdk", diff --git a/packages/angular/package.json b/packages/angular/package.json index e2b36fbbc096..dacc9be2b282 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -23,7 +23,7 @@ "dependencies": { "@sentry/browser": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "tslib": "^2.4.1" }, "devDependencies": { diff --git a/packages/astro/package.json b/packages/astro/package.json index 56abcf9800b7..710d13c854a1 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -35,6 +35,14 @@ "import": "./build/esm/index.worker.js", "require": "./build/cjs/index.worker.js" }, + "bun": { + "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/esm/index.server.js", "browser": "./build/esm/index.client.js", "import": "./build/esm/index.client.js", @@ -62,13 +70,23 @@ "access": "public" }, "peerDependencies": { + "@sentry/bun": "11.17.0", + "@sentry/deno": "11.17.0", "astro": ">=4.0.0-beta || >=7.0.0-beta" }, + "peerDependenciesMeta": { + "@sentry/bun": { + "optional": true + }, + "@sentry/deno": { + "optional": true + } + }, "dependencies": { "@sentry/browser": "11.17.0", "@sentry/cloudflare": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", "@sentry/server-utils": "11.17.0", @@ -76,6 +94,8 @@ }, "devDependencies": { "@sentry-internal/rollup-utils": "11.17.0", + "@sentry/bun": "11.17.0", + "@sentry/deno": "11.17.0", "astro": "^4.16.19", "vite": "^8.3.6" }, diff --git a/packages/astro/rollup.npm.config.mjs b/packages/astro/rollup.npm.config.mjs index 65e59feac11a..1736189e9008 100644 --- a/packages/astro/rollup.npm.config.mjs +++ b/packages/astro/rollup.npm.config.mjs @@ -4,6 +4,8 @@ const variants = makeNPMConfigVariants( makeBaseNPMConfig({ entrypoints: [ 'src/index.server.ts', + 'src/index.bun.ts', + 'src/index.deno.ts', 'src/index.client.ts', 'src/index.worker.ts', 'src/index.workerd.ts', diff --git a/packages/astro/src/index.bun.ts b/packages/astro/src/index.bun.ts new file mode 100644 index 000000000000..ecde81973b74 --- /dev/null +++ b/packages/astro/src/index.bun.ts @@ -0,0 +1,30 @@ +import { bunHttpServerIntegration, fetchIntegration } from '@sentry/bun'; +import { _INTERNAL_captureOptionsSetByUser } from '@sentry/core'; +import type { NodeClient, NodeOptions } from '@sentry/node'; +import { init as initServer } from './server/sdk'; + +// oxlint-disable-next-line typescript/no-deprecated +export { default } from './index.server'; +export * from './index.server'; + +/** Inits the Sentry Astro SDK on Bun, with the integrations of `@sentry/bun` for what Bun does differently. */ +export function init(options: NodeOptions): NodeClient | undefined { + const userOptions = _INTERNAL_captureOptionsSetByUser(options); + const userIntegrations = userOptions.integrations; + return initServer({ + runtime: { name: 'bun', version: process.versions.bun as string }, + ...userOptions, + 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`, which `httpIntegration` needs for request isolation and spans. + bunHttpServerIntegration(), + ]; + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations || [])]; + }, + }); +} diff --git a/packages/astro/src/index.deno.ts b/packages/astro/src/index.deno.ts new file mode 100644 index 000000000000..42862026951f --- /dev/null +++ b/packages/astro/src/index.deno.ts @@ -0,0 +1,28 @@ +import { _INTERNAL_captureOptionsSetByUser } from '@sentry/core'; +import { fetchIntegration } from '@sentry/deno'; +import type { NodeClient, NodeOptions } from '@sentry/node'; +import { init as initServer } from './server/sdk'; + +// oxlint-disable-next-line typescript/no-deprecated +export { default } from './index.server'; +export * from './index.server'; + +/** Inits the Sentry Astro SDK on Deno, with the integrations of `@sentry/deno` for what Deno does differently. */ +export function init(options: NodeOptions): NodeClient | undefined { + const userOptions = _INTERNAL_captureOptionsSetByUser(options); + const userIntegrations = userOptions.integrations; + return initServer({ + runtime: { name: 'deno', version: process.versions.deno as string }, + ...userOptions, + 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/astro/src/integration/index.ts b/packages/astro/src/integration/index.ts index 50f57a481cf8..19c38019cb68 100644 --- a/packages/astro/src/integration/index.ts +++ b/packages/astro/src/integration/index.ts @@ -1,7 +1,7 @@ import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; -import { warnOnRemovedBuildOptions } from '@sentry/core'; +import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; -import type { AstroConfig, AstroIntegration, AstroIntegrationLogger } from 'astro'; +import type { AstroConfig, AstroIntegration } from 'astro'; import * as fs from 'fs'; import { createRequire } from 'module'; import * as path from 'path'; @@ -10,9 +10,13 @@ import { sentryCloudflareNodeWarningPlugin, sentryCloudflareVitePlugin } from '. import { buildReleaseSnippet, getRuntimeRelease, makeServerReleaseVitePlugin } from './release'; import { makeServerInitVitePlugin, SENTRY_MIDDLEWARE_MODULE, SERVER_INIT_IMPORT } from './serverInit'; import { buildClientSnippet, buildSdkInitFileImportSnippet, buildServerSnippet } from './snippets'; +import { _getUpdatedSourceMapSettings, hasEnvironmentSourceMapSetting } from './sourceMaps'; import { getAstroTunnelOptions, makeTunnelOptionsVitePlugin, TUNNEL_OPTIONS_IMPORT } from './tunnel'; import type { SentryOptions } from './types'; +export { _getUpdatedSourceMapSettings } from './sourceMaps'; +export type { UserSourceMapSetting } from './sourceMaps'; + const PKG_NAME = '@sentry/astro'; export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { @@ -62,74 +66,73 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { }; const sourceMapsNeeded = sdkEnabled.client || sdkEnabled.server; - const shouldUploadSourcemaps = sourceMapsNeeded && sourcemaps?.disable !== true; + // TODO(v12): Add the Sentry plugin with `sourcemaps.disable: true` too, like with the options that replace it. + const shouldUploadSourcemaps = sourceMapsNeeded && resolveSourceMapsFeatures(sourcemaps).legacyDisable !== true; // The plugin would inject the release into the client's startup chunks, which changes their hashes on every // release and invalidates cached chunks. The page HTML carries it to the browser instead. const runtimeRelease = shouldUploadSourcemaps && command !== 'dev' ? getRuntimeRelease(release) : undefined; - // We don't need to check for AUTH_TOKEN here, because the plugin will pick it up from the env if (shouldUploadSourcemaps && command !== 'dev') { - const computedSourceMapSettings = _getUpdatedSourceMapSettings(config, options, logger); + const buildState: ViteBuildState = { writesCloudflareWorker: false }; + const sourceMapState = { sdkEnabled: false }; + const sdkEnabledSourceMaps = (environment?: string): boolean => + sourceMapState.sdkEnabled && !hasEnvironmentSourceMapSetting(config, environment); + // A user's own glob replaces the SDK's deletion. Maps in a Cloudflare `_worker.js` folder + // stay, so that wrangler can read them for `upload_source_maps`. + // With `sourcemaps.delete` the bundler plugin ignores this option and warns if the user set it. + const deleteSourcemapsAfterUpload = + sourcemaps?.delete !== undefined + ? sourcemaps.deleteSourcemapsAfterUpload + : (sourcemaps?.deleteSourcemapsAfterUpload ?? + (sourcemaps?.filesToDeleteAfterUpload === undefined + ? (environment?: string) => + sdkEnabledSourceMaps(environment) && !buildState.writesCloudflareWorker ? true : undefined + : undefined)); + + const sentryPlugins = sentryVitePlugin({ + applicationKey, + moduleMetadata, + // Priority: top-level options > env vars + org: org ?? env.SENTRY_ORG, + project: project ?? env.SENTRY_PROJECT, + authToken: authToken ?? env.SENTRY_AUTH_TOKEN, + url: sentryUrl ?? env.SENTRY_URL, + headers, + telemetry: telemetry ?? true, + silent: silent ?? false, + errorHandler, + _metaOptions: { + telemetry: { + metaFramework: 'astro', + }, + }, + debug: debug ?? false, + release: runtimeRelease ? { ...release, name: runtimeRelease, inject: false } : release, + sourcemaps: { + ...sourcemaps, + assets: sourcemaps?.assets ?? getSourcemapsAssetsGlobs(config), + deleteSourcemapsAfterUpload, + sdkEnabledSourceMaps, + }, + bundleSizeOptimizations: { + ...bundleSizeOptimizations, + }, + }); - let updatedFilesToDeleteAfterUpload: string[] | undefined = undefined; - - if ( - typeof sourcemaps?.filesToDeleteAfterUpload === 'undefined' && - computedSourceMapSettings.previousUserSourceMapSetting === 'unset' - ) { - // This also works for adapters, as the source maps are also copied to e.g. the .vercel folder. - // Static output has no client folder and writes client assets to `/` instead. - // Astro removes the hidden `.prerender` folder itself, but we don't want to rely on that. - updatedFilesToDeleteAfterUpload = [ - './dist/**/client/**/*.map', - './dist/**/server/**/*.map', - `./dist/**/${config.build?.assets ?? '_astro'}/**/*.map`, - './dist/**/.prerender/**/*.map', - ]; - - debug && - logger.info( - `Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify( - updatedFilesToDeleteAfterUpload, - )}\` to delete generated source maps after they were uploaded to Sentry.`, - ); - } + const computedSourceMapSettings = _getUpdatedSourceMapSettings(config, options, logger); + sourceMapState.sdkEnabled = + computedSourceMapSettings.previousUserSourceMapSetting === 'unset' && + computedSourceMapSettings.updatedSourceMapSetting === 'hidden'; updateConfig({ vite: { - build: { - sourcemap: computedSourceMapSettings.updatedSourceMapSetting, - }, + ...(computedSourceMapSettings.updatedSourceMapSetting === undefined + ? {} + : { build: { sourcemap: computedSourceMapSettings.updatedSourceMapSetting } }), plugins: [ - sentryVitePlugin({ - applicationKey, - moduleMetadata, - // Priority: top-level options > env vars - org: org ?? env.SENTRY_ORG, - project: project ?? env.SENTRY_PROJECT, - authToken: authToken ?? env.SENTRY_AUTH_TOKEN, - url: sentryUrl ?? env.SENTRY_URL, - headers, - telemetry: telemetry ?? true, - silent: silent ?? false, - errorHandler, - _metaOptions: { - telemetry: { - metaFramework: 'astro', - }, - }, - debug: debug ?? false, - release: runtimeRelease ? { ...release, name: runtimeRelease, inject: false } : release, - sourcemaps: { - ...sourcemaps, - assets: sourcemaps?.assets ?? getSourcemapsAssetsGlobs(config), - filesToDeleteAfterUpload: sourcemaps?.filesToDeleteAfterUpload ?? updatedFilesToDeleteAfterUpload, - }, - bundleSizeOptimizations: { - ...bundleSizeOptimizations, - }, - }), + makeViteBuildStatePlugin(buildState), + sentryPlugins, ...(runtimeRelease ? [makeServerReleaseVitePlugin(runtimeRelease)] : []), ], }, @@ -282,6 +285,26 @@ export const sentryAstro = (options: SentryOptions = {}): AstroIntegration => { }; }; +type ViteBuildState = { + /** The current Vite build writes the Worker of an older Cloudflare adapter to `_worker.js`. */ + writesCloudflareWorker: boolean; +}; + +/** + * Records what the SDK needs to know about each Vite build. Its `config` hook runs before the one + * of the Sentry plugin, which reads `buildState` there. + */ +function makeViteBuildStatePlugin(buildState: ViteBuildState): VitePlugin { + return { + name: 'sentry-astro-vite-build-state', + apply: 'build', + enforce: 'post', + config(viteConfig) { + buildState.writesCloudflareWorker = /(?:^|[\\/])_worker\.js[\\/]*$/.test(viteConfig.build?.outDir ?? ''); + }, + }; +} + // Every sub-plugin of `sentryCloudflareVitePlugin()` but its orchestrion transform has this prefix, // and some are added whatever its options are. const CLOUDFLARE_VITE_PLUGIN_NAME_PREFIX = 'sentry-cloudflare-'; @@ -381,71 +404,3 @@ function getOutDirGlob(config: AstroConfig): string { // fallback to default output dir return 'dist'; } - -/** - * Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps - */ -export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined; - -/** There are 3 ways to set up source map generation (https://github.com/getsentry/sentry-javascript/issues/13993) - * - * 1. User explicitly disabled source maps - * - keep this setting (emit a warning that errors won't be unminified in Sentry) - * - We won't upload anything - * - * 2. Users enabled source map generation (true, 'hidden', 'inline'). - * - keep this setting (don't do anything - like deletion - besides uploading) - * - * 3. Users didn't set source maps generation - * - we enable 'hidden' source maps generation - * - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this) - * - * --> only exported for testing - */ -export function _getUpdatedSourceMapSettings( - astroConfig: AstroConfig, - sentryOptions: SentryOptions | undefined, - logger: AstroIntegrationLogger, -): { previousUserSourceMapSetting: UserSourceMapSetting; updatedSourceMapSetting: boolean | 'inline' | 'hidden' } { - let previousUserSourceMapSetting: UserSourceMapSetting = undefined; - - astroConfig.build = astroConfig.build || {}; - - const viteSourceMap = astroConfig?.vite?.build?.sourcemap; - let updatedSourceMapSetting = viteSourceMap; - - const settingKey = 'vite.build.sourcemap'; - const debug = sentryOptions?.debug; - - if (viteSourceMap === false) { - previousUserSourceMapSetting = 'disabled'; - updatedSourceMapSetting = viteSourceMap; - - if (debug) { - // Longer debug message with more details - logger.warn( - `Source map generation is currently disabled in your Astro configuration (\`${settingKey}: false\`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`, - ); - } else { - logger.warn('Source map generation is disabled in your Astro configuration.'); - } - } else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) { - previousUserSourceMapSetting = 'enabled'; - updatedSourceMapSetting = viteSourceMap; - - debug && - logger.info( - `We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`, - ); - } else { - previousUserSourceMapSetting = 'unset'; - updatedSourceMapSetting = 'hidden'; - - debug && - logger.info( - `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`, - ); - } - - return { previousUserSourceMapSetting, updatedSourceMapSetting }; -} diff --git a/packages/astro/src/integration/middleware/index.ts b/packages/astro/src/integration/middleware/index.ts index 76f977fa0966..238682e10434 100644 --- a/packages/astro/src/integration/middleware/index.ts +++ b/packages/astro/src/integration/middleware/index.ts @@ -2,7 +2,7 @@ import { handleRequest } from '../../server/middleware'; // The one `@sentry/astro` entry that resolves to server code on every runtime, so the integration's virtual module // imports it from here. -export { _INTERNAL_setTunnelDefaults } from '@sentry/core/server'; +export { setTunnelDefaults } from '@sentry/core/server'; type MiddlewareNext = () => Promise; type MiddlewareHandler = (ctx: unknown, next: MiddlewareNext) => Promise | Response | Promise | void; diff --git a/packages/astro/src/integration/sourceMaps.ts b/packages/astro/src/integration/sourceMaps.ts new file mode 100644 index 000000000000..ff622bf5a338 --- /dev/null +++ b/packages/astro/src/integration/sourceMaps.ts @@ -0,0 +1,133 @@ +import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; +import type { AstroConfig, AstroIntegrationLogger } from 'astro'; +import type { SentryOptions } from './types'; + +/** + * Whether the user enabled (true, 'hidden', 'inline') or disabled (false) source maps + */ +export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined; + +/** There are 3 ways to set up source map generation (https://github.com/getsentry/sentry-javascript/issues/13993) + * + * 1. User explicitly disabled source maps + * - keep this setting (emit a warning that errors won't be unminified in Sentry) + * - We won't upload anything + * + * 2. Users enabled source map generation (true, 'hidden', 'inline') or set `sourcemap` in the output options. + * - keep this setting (don't do anything - like deletion - besides uploading) + * + * 3. Users didn't set source maps generation + * - we enable 'hidden' source maps generation when Sentry can upload the maps, or when + * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset + * - we remove the maps from the build output, except in a Cloudflare `_worker.js` folder and + * with `sourcemaps.delete: false` + * + * --> only exported for testing + */ +export function _getUpdatedSourceMapSettings( + astroConfig: AstroConfig, + sentryOptions: SentryOptions | undefined, + logger: AstroIntegrationLogger, +): { + previousUserSourceMapSetting: UserSourceMapSetting; + updatedSourceMapSetting: boolean | 'inline' | 'hidden' | undefined; +} { + let previousUserSourceMapSetting: UserSourceMapSetting = undefined; + + astroConfig.build = astroConfig.build || {}; + + const viteSourceMap = astroConfig?.vite?.build?.sourcemap; + const outputSourceMapSettings = getOutputSourceMapSettings(astroConfig?.vite?.build); + let updatedSourceMapSetting = viteSourceMap; + + const settingKey = 'vite.build.sourcemap'; + const debug = sentryOptions?.debug; + + if (viteSourceMap === false) { + previousUserSourceMapSetting = 'disabled'; + updatedSourceMapSetting = viteSourceMap; + + if (debug) { + // Longer debug message with more details + logger.warn( + `Source map generation is currently disabled in your Astro configuration (\`${settingKey}: false\`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`, + ); + } else { + logger.warn('Source map generation is disabled in your Astro configuration.'); + } + } else if (viteSourceMap && ['hidden', 'inline', true].includes(viteSourceMap)) { + previousUserSourceMapSetting = 'enabled'; + updatedSourceMapSetting = viteSourceMap; + + debug && + logger.info( + `We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`, + ); + } else if (outputSourceMapSettings.length > 0) { + previousUserSourceMapSetting = outputSourceMapSettings.every(setting => setting === false) ? 'disabled' : 'enabled'; + updatedSourceMapSetting = undefined; + + debug && + logger.info( + `We discovered \`sourcemap\` in the output options of \`vite.build\`, which overrides \`${settingKey}\`. Sentry will keep this source map setting.`, + ); + } else { + previousUserSourceMapSetting = 'unset'; + updatedSourceMapSetting = undefined; + + const sourcemaps = sentryOptions?.sourcemaps; + const { injectDebugIds, upload, legacyDisable } = resolveSourceMapsFeatures(sourcemaps); + + // Astro fixes the setting of the client build before the bundler plugin can turn source maps on. + // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. + if ( + (upload && hasSourceMapUploadCredentials(sentryOptions)) || + legacyDisable === 'disable-upload' || + (sourcemaps?.delete === false && injectDebugIds) + ) { + updatedSourceMapSetting = 'hidden'; + + debug && + logger.info( + sourcemaps?.delete === false + ? `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps stay in the build output.` + : `Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`, + ); + } + } + + return { previousUserSourceMapSetting, updatedSourceMapSetting }; +} + +/** + * Whether the user set `build.sourcemap` for the given Vite environment. + * Astro copies the top-level setting into the `client` environment, so + * the bundler plugin also passes that name when the user set nothing there. + */ +export function hasEnvironmentSourceMapSetting(astroConfig: AstroConfig, environment: string | undefined): boolean { + if (environment === undefined) { + return false; + } + // Astro 4 types `vite` with Vite 5, which has no environments. + const vite = astroConfig.vite as + | { environments?: Record } + | undefined; + return vite?.environments?.[environment]?.build?.sourcemap !== undefined; +} + +type OutputOptions = { sourcemap?: unknown }; +type BundlerOptions = { output?: OutputOptions | OutputOptions[] }; + +/** + * The `sourcemap` settings of the bundler outputs, which override + * `vite.build.sourcemap`. Vite 8 reads both options. + */ +function getOutputSourceMapSettings( + build: { rollupOptions?: BundlerOptions; rolldownOptions?: BundlerOptions } | undefined, +): unknown[] { + return [build?.rolldownOptions?.output ?? [], build?.rollupOptions?.output ?? []] + .flat() + .map(output => output.sourcemap) + .filter(setting => setting !== undefined); +} diff --git a/packages/astro/src/integration/tunnel.ts b/packages/astro/src/integration/tunnel.ts index 33faad943393..9ec1ba864fd8 100644 --- a/packages/astro/src/integration/tunnel.ts +++ b/packages/astro/src/integration/tunnel.ts @@ -37,7 +37,7 @@ export function makeTunnelOptionsVitePlugin(tunnelOptions: BrowserTunnelOptions) } return options?.ssr - ? `import { _INTERNAL_setTunnelDefaults } from '@sentry/astro/middleware';\n_INTERNAL_setTunnelDefaults(${stringifyForCodeInjection({ basePath: tunnelOptions.basePath })});` + ? `import { setTunnelDefaults } from '@sentry/astro/middleware';\nsetTunnelDefaults(${stringifyForCodeInjection({ basePath: tunnelOptions.basePath })});` : `globalThis[${stringifyForCodeInjection(TUNNEL_OPTIONS_GLOBAL)}] = ${stringifyForCodeInjection(tunnelOptions)};`; }, transform: (code, id) => diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index 625ce1919e4a..4ed4c644b00b 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -28,6 +28,7 @@ import { HTTP_SPAN_NAME_FALLBACK, httpHeadersToSpanAttributes, objectify, + SDK_VERSION, setHttpStatus, spanToJSON, startSpan, @@ -39,11 +40,7 @@ import { filterCollectedUrlFragment, filterCollectedUrlQuery, } from '@sentry/core'; -import { - flushIfServerless, - _INTERNAL_getCacheOriginMetaTags, - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, -} from '@sentry/core/server'; +import { flushIfServerless, _INTERNAL_getCacheOriginMetaTags, handleServedTunnelRequest } from '@sentry/core/server'; import { setHttpServerSpanRouteAttribute } from '@sentry/server-utils'; import type { APIContext, MiddlewareHandler, MiddlewareNext, RoutePart } from 'astro'; @@ -77,6 +74,8 @@ function sendErrorToSentry(e: unknown): unknown { return objectifiedErr; } +const SDK_NAME = 'sentry.javascript.astro'; + type AstroLocalsWithSentry = Record & { __sentry_wrapped__?: boolean; }; @@ -87,7 +86,8 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler = return async (ctx, next) => { // The middleware the integration adds runs the server init first, so this only bails without a server init, or when // this middleware was added by hand and the request comes before any SSR page, which still runs the init. - if (!getClient()) { + const client = getClient(); + if (!client) { return next(); } @@ -96,6 +96,13 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler = return tunnelResponse; } + // With `sentryCloudflareVitePlugin()` of `@sentry/cloudflare/vite`, `@sentry/cloudflare` inits the client. + const sdk = client.getOptions()._metadata?.sdk; + if (sdk && sdk.name !== SDK_NAME) { + sdk.name = SDK_NAME; + sdk.packages = [{ name: 'npm:@sentry/astro', version: SDK_VERSION }, ...(sdk.packages || [])]; + } + // For static (prerendered) routes, we only want to inject the parametrized route meta tags if (isPrerenderedRequest(ctx)) { return handleStaticRoute(ctx, next); diff --git a/packages/astro/src/tunnel.ts b/packages/astro/src/tunnel.ts index 8658c09365e8..cdf3d872b04e 100644 --- a/packages/astro/src/tunnel.ts +++ b/packages/astro/src/tunnel.ts @@ -1,5 +1,5 @@ import type { BrowserTunnelOptions, Options } from '@sentry/core'; -import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; +import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; /** Set by the Sentry Astro integration from the `base` and `trailingSlash` config. */ export const TUNNEL_OPTIONS_GLOBAL = '__sentry_astro_tunnel_options'; diff --git a/packages/astro/test/integration/index.files.test.ts b/packages/astro/test/integration/index.files.test.ts index 39ca0ef66ed9..1a397f558a7b 100644 --- a/packages/astro/test/integration/index.files.test.ts +++ b/packages/astro/test/integration/index.files.test.ts @@ -9,7 +9,8 @@ vi.mock('fs', async requireActual => { }); // Without a configured name, the real resolver falls back to the git revision of this checkout. -vi.mock('@sentry/bundler-plugins/core', () => ({ +vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({ + ...(await importOriginal>()), resolveReleaseName: (name?: string) => name, })); diff --git a/packages/astro/test/integration/index.test.ts b/packages/astro/test/integration/index.test.ts index e841abd43a97..c918b3905ade 100644 --- a/packages/astro/test/integration/index.test.ts +++ b/packages/astro/test/integration/index.test.ts @@ -4,16 +4,26 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { _getUpdatedSourceMapSettings, sentryAstro } from '../../src/integration'; import type { SentryOptions } from '../../src/integration/types'; -const sentryVitePluginSpy = vi.fn(() => 'sentryVitePlugin'); +type CapturedSourcemapsOptions = { + deleteSourcemapsAfterUpload?: boolean | ((environment?: string) => boolean | undefined); + sdkEnabledSourceMaps?: (environment?: string) => boolean; +}; + +let capturedSourcemapsOptions: CapturedSourcemapsOptions | undefined; + +const sentryVitePluginSpy = vi.fn((options: { sourcemaps?: CapturedSourcemapsOptions }) => { + capturedSourcemapsOptions = options.sourcemaps; + return 'sentryVitePlugin'; +}); vi.mock('@sentry/bundler-plugins/vite', () => ({ - // @ts-expect-error - just mocking around - sentryVitePlugin: vi.fn(args => sentryVitePluginSpy(args)), + sentryVitePlugin: vi.fn((args: { sourcemaps?: CapturedSourcemapsOptions }) => sentryVitePluginSpy(args)), })); // Without a configured name, the real resolver falls back to the git revision of this checkout. const resolveReleaseName = vi.fn((name?: string) => name); -vi.mock('@sentry/bundler-plugins/core', () => ({ +vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({ + ...(await importOriginal>()), resolveReleaseName: (name?: string) => resolveReleaseName(name), })); @@ -89,7 +99,7 @@ describe('sentryAstro integration', () => { expect(integration.name).toBe('@sentry/astro'); }); - it('enables "hidden" source maps, adds filesToDeleteAfterUpload and adds the sentry vite plugin if an auth token is detected', async () => { + it('enables "hidden" source maps, asks for their deletion and adds the sentry vite plugin if an auth token is detected', async () => { const integration = sentryAstro({ org: 'my-org', project: 'my-project', @@ -107,7 +117,7 @@ describe('sentryAstro integration', () => { build: { sourcemap: 'hidden', }, - plugins: ['sentryVitePlugin'], + plugins: [expect.objectContaining({ name: 'sentry-astro-vite-build-state' }), 'sentryVitePlugin'], }, }); expect(updateConfig).toHaveBeenCalledWith({ @@ -127,12 +137,8 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['out/**/*', 'out/**/.prerender/**/*'], - filesToDeleteAfterUpload: [ - './dist/**/client/**/*.map', - './dist/**/server/**/*.map', - './dist/**/_astro/**/*.map', - './dist/**/.prerender/**/*.map', - ], + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -163,12 +169,8 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['dist/**/*', 'dist/**/.prerender/**/*'], - filesToDeleteAfterUpload: [ - './dist/**/client/**/*.map', - './dist/**/server/**/*.map', - './dist/**/_astro/**/*.map', - './dist/**/.prerender/**/*.map', - ], + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -207,12 +209,8 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['{.vercel,dist}/**/*', '{.vercel,dist}/**/.prerender/**/*'], - filesToDeleteAfterUpload: [ - './dist/**/client/**/*.map', - './dist/**/server/**/*.map', - './dist/**/_astro/**/*.map', - './dist/**/.prerender/**/*.map', - ], + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -251,12 +249,8 @@ describe('sentryAstro integration', () => { bundleSizeOptimizations: {}, sourcemaps: { assets: ['dist/server/**/*, dist/client/**/*'], - filesToDeleteAfterUpload: [ - './dist/**/client/**/*.map', - './dist/**/server/**/*.map', - './dist/**/_astro/**/*.map', - './dist/**/.prerender/**/*.map', - ], + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), }, _metaOptions: { telemetry: { @@ -267,7 +261,7 @@ describe('sentryAstro integration', () => { ); }); - it('prefers user-specified filesToDeleteAfterUpload over the default values', async () => { + it('lets user-specified filesToDeleteAfterUpload replace the SDK deletion', async () => { const integration = sentryAstro({ org: 'my-org', project: 'my-project', @@ -289,11 +283,202 @@ describe('sentryAstro integration', () => { expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: ['./custom/path/**/*'], + deleteSourcemapsAfterUpload: undefined, }), }), ); }); + describe('deleteSourcemapsAfterUpload', () => { + async function runSetup(options: SentryOptions, astroConfig: Partial = {}): Promise { + const integration = sentryAstro({ org: 'my-org', project: 'my-project', ...options }); + // @ts-expect-error - the hook exists, and we only need to pass what we actually use + await integration.hooks['astro:config:setup']({ + ...baseConfigHookObject, + updateConfig, + injectScript, + config: astroConfig as AstroConfig, + }); + } + + function expectSourcemapsOptions({ sdkEnabledSourceMaps, ...sourcemaps }: Record): void { + expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); + expect(sentryVitePluginSpy).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }), + ); + expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.()).toBe(sdkEnabledSourceMaps); + } + + // The bundler plugin calls the function form in its `config` hook, after the build state + // plugin ran. + function runBuildStatePlugin(viteConfig: { build?: { outDir?: string } }): void { + const plugin = updateConfig.mock.calls + .flatMap(([astroConfigUpdate]) => astroConfigUpdate.vite?.plugins ?? []) + .find(plugin => plugin?.name === 'sentry-astro-vite-build-state'); + plugin.config(viteConfig); + } + + function expectDeleteOption(value: boolean | undefined): void { + expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); + const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; + expect(typeof option === 'function' ? option() : option).toBe(value); + } + + it('is `true` when the SDK enabled the source maps', async () => { + await runSetup({}); + runBuildStatePlugin({ build: { outDir: 'dist/' } }); + expectDeleteOption(true); + }); + + // Older Cloudflare adapters write the Worker there, and wrangler reads its maps. + it.each(['dist/_worker.js/', '/path/to/project/dist/_worker.js', 'C:\\project\\dist\\_worker.js\\'])( + 'is not set for a build into `%s`', + async outDir => { + await runSetup({}); + runBuildStatePlugin({ build: { outDir } }); + expectDeleteOption(undefined); + + runBuildStatePlugin({ build: { outDir: 'dist/' } }); + expectDeleteOption(true); + }, + ); + + it('lets a user-set `true` remove the maps of a Cloudflare `_worker.js` build', async () => { + await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: true } }); + runBuildStatePlugin({ build: { outDir: 'dist/_worker.js/' } }); + expectDeleteOption(true); + }); + + it.each(['hidden', true] as const)('is not set when the user set `vite.build.sourcemap: %s`', async sourcemap => { + await runSetup({}, { vite: { build: { sourcemap } } }); + expectDeleteOption(undefined); + }); + + it.each([ + [true, undefined], + [false, undefined], + [true, 'hidden'], + [false, 'hidden'], + ] as const)('passes a user-set `%s` through when `vite.build.sourcemap` is `%s`', async (value, sourcemap) => { + await runSetup({ sourcemaps: { deleteSourcemapsAfterUpload: value } }, { vite: { build: { sourcemap } } }); + expectDeleteOption(value); + }); + + it('is not set when the user set `filesToDeleteAfterUpload`', async () => { + await runSetup({ sourcemaps: { filesToDeleteAfterUpload: ['./dist/**/*.map'] } }); + expectDeleteOption(undefined); + }); + + it('lets a user-set `true` win over the user glob', async () => { + await runSetup({ + sourcemaps: { deleteSourcemapsAfterUpload: true, filesToDeleteAfterUpload: ['./dist/**/*.map'] }, + }); + expectDeleteOption(true); + }); + + // Then the plugin removes all of these maps, also those of chunks outside the user's + // `assets` or `ignore`. + it('marks the source maps as SDK-enabled when the user narrowed the upload', async () => { + await runSetup({ sourcemaps: { assets: ['./dist/client/**/*'], ignore: ['**/vendor/**'] } }); + expectSourcemapsOptions({ + assets: ['./dist/client/**/*'], + ignore: ['**/vendor/**'], + sdkEnabledSourceMaps: true, + }); + expectDeleteOption(true); + }); + + // The output setting overrides `vite.build.sourcemap`, so these maps are the user's. + it.each([ + { rollupOptions: { output: { sourcemap: true } } }, + { rollupOptions: { output: [{}, { sourcemap: 'hidden' }] } }, + { rolldownOptions: { output: { sourcemap: false } } }, + ] as const)('leaves the source maps to the user with the output options %j', async build => { + await runSetup({}, { vite: { build } } as Partial); + expectViteSourceMapSetting(undefined); + expectSourcemapsOptions({ sdkEnabledSourceMaps: false }); + expectDeleteOption(undefined); + }); + + // Astro copies the top-level setting into the `client` environment. + it('marks the source maps of the `client` environment as SDK-enabled', async () => { + await runSetup({}); + runBuildStatePlugin({ build: { outDir: 'dist/' } }); + expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(true); + const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; + expect(typeof option === 'function' ? option('client') : option).toBe(true); + }); + + it('does not mark the source maps of an environment the user set as SDK-enabled', async () => { + await runSetup({}, { + vite: { environments: { client: { build: { sourcemap: true } } } }, + } as Partial); + runBuildStatePlugin({ build: { outDir: 'dist/' } }); + expect(capturedSourcemapsOptions?.sdkEnabledSourceMaps?.('client')).toBe(false); + const option = capturedSourcemapsOptions?.deleteSourcemapsAfterUpload; + expect(typeof option === 'function' ? option('client') : option).toBeUndefined(); + expectSourcemapsOptions({ sdkEnabledSourceMaps: true }); + expectDeleteOption(true); + }); + + it.each(['hidden', true, false] as const)( + 'does not mark source maps as SDK-enabled when the user set `vite.build.sourcemap: %s`', + async sourcemap => { + await runSetup({}, { vite: { build: { sourcemap } } }); + expectSourcemapsOptions({ sdkEnabledSourceMaps: false }); + }, + ); + + // The maps are removed in this mode too, after the plugin stamps the debug IDs. + it("is `true` with `disable: 'disable-upload'`", async () => { + await runSetup({ sourcemaps: { disable: 'disable-upload' } }); + expectSourcemapsOptions({ disable: 'disable-upload', sdkEnabledSourceMaps: true }); + expectDeleteOption(true); + }); + + function expectViteSourceMapSetting(sourcemap: 'hidden' | undefined): void { + const viteConfigUpdate = updateConfig.mock.calls + .map(([astroConfigUpdate]) => astroConfigUpdate.vite) + .find(vite => + vite?.plugins?.some((plugin: { name?: string }) => plugin?.name === 'sentry-astro-vite-build-state'), + ); + expect(viteConfigUpdate?.build?.sourcemap).toBe(sourcemap); + } + + it.each([{ upload: false }, { injectDebugIds: false }])( + 'adds the plugin, turns no source maps on and asks for no deletion with %j', + async sourcemaps => { + await runSetup({ sourcemaps }); + expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: false }); + expectDeleteOption(undefined); + expectViteSourceMapSetting(undefined); + }, + ); + + // The bundler plugin must only see the `deleteSourcemapsAfterUpload` the user set, because it + // warns when both options are set. + it.each([ + [{ delete: true }, 'hidden', undefined], + [{ delete: false }, 'hidden', undefined], + [{ upload: false, delete: false }, 'hidden', undefined], + [{ upload: false, delete: true }, undefined, undefined], + [{ injectDebugIds: false, delete: false }, undefined, undefined], + [{ delete: false, deleteSourcemapsAfterUpload: true }, 'hidden', true], + ] as const)('with %j it sets the source map setting to %s', async (sourcemaps, setting, deleteAfterUpload) => { + await runSetup({ sourcemaps }); + expectSourcemapsOptions({ ...sourcemaps, sdkEnabledSourceMaps: setting === 'hidden' }); + expect(capturedSourcemapsOptions?.deleteSourcemapsAfterUpload).toBe(deleteAfterUpload); + expectViteSourceMapSetting(setting); + }); + + it('enables hidden source maps when `upload: true` replaces `disable: true`', async () => { + await runSetup({ sourcemaps: { disable: true, upload: true } }); + expectSourcemapsOptions({ sdkEnabledSourceMaps: true }); + expectDeleteOption(true); + expectViteSourceMapSetting('hidden'); + }); + }); + it('ignores the removed `sourceMapsUploadOptions` when computing the vite plugin options', async () => { const integration = sentryAstro({ org: 'my-org', @@ -872,7 +1057,7 @@ describe('_getUpdatedSourceMapSettings', () => { beforeEach(() => { astroConfig = { vite: { build: {} } } as Omit & { vite: { build: { sourcemap?: any } } }; - sentryOptions = {}; + sentryOptions = { org: 'my-org', project: 'my-project' }; logger = { info: vi.fn(), warn: vi.fn(), @@ -901,6 +1086,17 @@ describe('_getUpdatedSourceMapSettings', () => { }); }); + it.each([ + [{ rollupOptions: { output: { sourcemap: true } } }, 'enabled'], + [{ rolldownOptions: { output: [{ sourcemap: 'hidden' }, { sourcemap: false }] } }, 'enabled'], + [{ rollupOptions: { output: { sourcemap: false } } }, 'disabled'], + ] as const)('keeps the output options %j as a user setting', (build, expected) => { + astroConfig = { vite: { build } } as unknown as typeof astroConfig; + const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger); + expect(result.previousUserSourceMapSetting).toBe(expected); + expect(result.updatedSourceMapSetting).toBeUndefined(); + }); + it('should enable "hidden" source maps when unset', () => { astroConfig.vite.build.sourcemap = undefined; const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger); @@ -908,6 +1104,41 @@ describe('_getUpdatedSourceMapSettings', () => { expect(result.updatedSourceMapSetting).toBe('hidden'); }); + it.each([ + [{ upload: false }, undefined], + [{ injectDebugIds: false }, undefined], + [{ delete: true }, 'hidden'], + [{ delete: false }, 'hidden'], + [{ upload: false, delete: false }, 'hidden'], + [{ upload: false, delete: true }, undefined], + [{ injectDebugIds: false, delete: false }, undefined], + [{ upload: true }, 'hidden'], + [{ disable: 'disable-upload' }, 'hidden'], + ] as const)('with unset source maps and %j it returns %s', (sourcemaps, expected) => { + const result = _getUpdatedSourceMapSettings(astroConfig, { ...sentryOptions, sourcemaps }, logger); + expect(result.previousUserSourceMapSetting).toBe('unset'); + expect(result.updatedSourceMapSetting).toBe(expected); + }); + + it.each<[SentryOptions, 'hidden' | undefined]>([ + [{ project: 'my-project' }, undefined], + [{ org: 'my-org' }, undefined], + [{ project: 'my-project', authToken: 'sntrys_token' }, 'hidden'], + [{ org: 'my-org', project: ['my-project'] }, 'hidden'], + [{ project: 'my-project', sourcemaps: { delete: false } }, 'hidden'], + [{ project: 'my-project', sourcemaps: { disable: 'disable-upload' } }, 'hidden'], + ])('with unset source maps and the options %j it returns %s', (options, expected) => { + const result = _getUpdatedSourceMapSettings(astroConfig, options, logger); + expect(result.updatedSourceMapSetting).toBe(expected); + }); + + it('returns undefined for unset source maps without an auth token', () => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + const result = _getUpdatedSourceMapSettings(astroConfig, sentryOptions, logger); + vi.unstubAllEnvs(); + expect(result.updatedSourceMapSetting).toBeUndefined(); + }); + it('should log warnings and messages when debug is enabled', () => { sentryOptions = { debug: true }; diff --git a/packages/astro/test/server/bunSdk.test.ts b/packages/astro/test/server/bunSdk.test.ts new file mode 100644 index 000000000000..003fd9f0d93c --- /dev/null +++ b/packages/astro/test/server/bunSdk.test.ts @@ -0,0 +1,72 @@ +import type { Integration } from '@sentry/core'; +import { getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { init } from '../../src/index.bun'; + +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.5' } }); + + const client = init({}); + + expect(client?.getOptions().runtime).toEqual({ name: 'bun', version: '1.4.5' }); + }); + + it('inits the Astro SDK', () => { + const client = init({}); + + expect(client?.getOptions()._metadata?.sdk?.name).toBe('sentry.javascript.astro'); + }); + + 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']); + }); + + it('does not report the Bun runtime and integrations as set by the user', () => { + const client = init({ integrations: integrations => integrations }); + + expect(client?.getSdkMetadata()?.optionsSetByUser).toEqual(['integrations']); + expect(client?.getSdkMetadata()?.integrationsSetByUser).toEqual([]); + }); +}); diff --git a/packages/astro/test/server/denoSdk.test.ts b/packages/astro/test/server/denoSdk.test.ts new file mode 100644 index 000000000000..45ebcb307075 --- /dev/null +++ b/packages/astro/test/server/denoSdk.test.ts @@ -0,0 +1,72 @@ +import type { Integration } from '@sentry/core'; +import { getMainCarrier } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { init } from '../../src/index.deno'; + +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('inits the Astro SDK', () => { + const client = init({}); + + expect(client?.getOptions()._metadata?.sdk?.name).toBe('sentry.javascript.astro'); + }); + + 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([]); + }); + + it('does not report the Deno runtime and integrations as set by the user', () => { + const client = init({ integrations: integrations => integrations }); + + expect(client?.getSdkMetadata()?.optionsSetByUser).toEqual(['integrations']); + expect(client?.getSdkMetadata()?.integrationsSetByUser).toEqual([]); + }); +}); diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts index 082c9af75ef7..b9d50b76e7e4 100644 --- a/packages/astro/test/server/middleware.test.ts +++ b/packages/astro/test/server/middleware.test.ts @@ -38,7 +38,7 @@ describe('sentryMiddleware with the managed tunnel', () => { const getClientSpy = vi.spyOn(SentryCore, 'getClient').mockReturnValue({} as Client); const tunnelResponse = new Response('forwarded'); const matcherSpy = vi - .spyOn(SentryCoreServer, '_INTERNAL_handleServedTunnelRequest') + .spyOn(SentryCoreServer, 'handleServedTunnelRequest') .mockReturnValue(Promise.resolve(tunnelResponse)); const next = vi.fn(); const request = new Request('https://myDomain.io/abc123', { method: 'POST' }); @@ -227,6 +227,37 @@ describe('sentryMiddleware', () => { }); }); + it('sets the Astro SDK name on a client that another SDK inited', async () => { + const sdk = { + name: 'sentry.javascript.cloudflare', + packages: [{ name: 'npm:@sentry/cloudflare', version: SentryCore.SDK_VERSION }], + version: SentryCore.SDK_VERSION, + }; + vi.spyOn(SentryCore, 'getClient').mockImplementation( + () => + ({ + getOptions: () => ({ _metadata: { sdk } }), + getDataCollectionOptions: () => DATA_COLLECTION_DEFAULTS, + }) as unknown as Client, + ); + const middleware = handleRequest(); + const ctx = { ...DYNAMIC_REQUEST_CONTEXT, routePattern: '/users' }; + + // @ts-expect-error, a partial ctx object is fine here + await middleware(ctx, () => Promise.resolve(new Response('ok'))); + // @ts-expect-error, a partial ctx object is fine here + await middleware(ctx, () => Promise.resolve(new Response('ok'))); + + expect(sdk).toEqual({ + name: 'sentry.javascript.astro', + packages: [ + { name: 'npm:@sentry/astro', version: SentryCore.SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SentryCore.SDK_VERSION }, + ], + version: SentryCore.SDK_VERSION, + }); + }); + it("sets source route if the url couldn't be decoded correctly", async () => { const middleware = handleRequest(); const ctx = { diff --git a/packages/aws-serverless/package.json b/packages/aws-serverless/package.json index 52eab180ffe1..6d2b58237e7e 100644 --- a/packages/aws-serverless/package.json +++ b/packages/aws-serverless/package.json @@ -66,7 +66,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", diff --git a/packages/aws-serverless/src/tunnel.ts b/packages/aws-serverless/src/tunnel.ts index 927cc927de82..bfe4c94e2c5c 100644 --- a/packages/aws-serverless/src/tunnel.ts +++ b/packages/aws-serverless/src/tunnel.ts @@ -1,9 +1,5 @@ import { debug } from '@sentry/core'; -import { - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, - _INTERNAL_isServedTunnelRequest as isServedTunnelRequest, - _INTERNAL_pickForwardedHeaders as pickForwardedHeaders, -} from '@sentry/core/server'; +import { handleServedTunnelRequest, isServedTunnelRequest, pickForwardedHeaders } from '@sentry/core/server'; import { DEBUG_BUILD } from './debug-build'; /** diff --git a/packages/browser-utils/.oxlintrc.json b/packages/browser-utils/.oxlintrc.json index a0967ad5a718..a5c0bddd3943 100644 --- a/packages/browser-utils/.oxlintrc.json +++ b/packages/browser-utils/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true }, @@ -8,8 +8,7 @@ { "files": ["src/metrics/**"], "rules": { - "typescript/explicit-function-return-type": "off", - "typescript/no-non-null-assertion": "off" + "typescript/explicit-function-return-type": "off" } } ] diff --git a/packages/browser-utils/package.json b/packages/browser-utils/package.json index e10b60b891e8..717c06838333 100644 --- a/packages/browser-utils/package.json +++ b/packages/browser-utils/package.json @@ -34,7 +34,7 @@ }, "dependencies": { "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "web-vitals": "^6.2.3" }, "devDependencies": { diff --git a/packages/browser-utils/src/htmlTreeAsString.ts b/packages/browser-utils/src/htmlTreeAsString.ts index 46dcc493a431..d8652ef7f5cf 100644 --- a/packages/browser-utils/src/htmlTreeAsString.ts +++ b/packages/browser-utils/src/htmlTreeAsString.ts @@ -15,7 +15,7 @@ type SimpleNode = { type AccessorKey = 'parentNode' | 'tagName' | 'id' | 'className' | 'getAttribute' | 'dataset'; const accessors: Partial> = {}; -// oxlint-disable typescript/unbound-method +// oxlint-disable typescript/unbound-method, typescript/no-non-null-assertion -- a missing descriptor throws into the catch below try { if (typeof Node !== 'undefined') { accessors.parentNode = Object.getOwnPropertyDescriptor(Node.prototype, 'parentNode')!.get!; @@ -33,7 +33,7 @@ try { // Polyfilled or stubbed prototypes may not have the expected descriptors. // _safeRead falls back to direct property access. } -// oxlint-enable typescript/unbound-method +// oxlint-enable typescript/unbound-method, typescript/no-non-null-assertion function _safeRead(el: unknown, prop: AccessorKey, arg?: string): T { const fn = accessors[prop]; diff --git a/packages/browser-utils/src/web-vitals/emitSpan.ts b/packages/browser-utils/src/web-vitals/emitSpan.ts index 90b11673e1b6..289858dca1aa 100644 --- a/packages/browser-utils/src/web-vitals/emitSpan.ts +++ b/packages/browser-utils/src/web-vitals/emitSpan.ts @@ -153,6 +153,6 @@ function getReplayAttributes(): SpanAttributes { [SENTRY_REPLAY_ID]: replayId, // Not the `SENTRY_REPLAY_IS_BUFFERING` convention: that one has no `sentry._internal.` prefix, and // the rest of the SDK sets the prefixed key (see `logs/internal.ts`, `metrics/internal.ts`). - 'sentry._internal.replay_is_buffering': replay!.getRecordingMode() === 'buffer' ? true : undefined, + 'sentry._internal.replay_is_buffering': replay?.getRecordingMode() === 'buffer' ? true : undefined, }; } diff --git a/packages/browser-utils/src/web-vitals/interactionCache.ts b/packages/browser-utils/src/web-vitals/interactionCache.ts index 5a007f699c0a..bfe1bf2b026a 100644 --- a/packages/browser-utils/src/web-vitals/interactionCache.ts +++ b/packages/browser-utils/src/web-vitals/interactionCache.ts @@ -37,6 +37,7 @@ export function createInteractionCache({ const get = (entry: E): T | undefined => { // The most likely match is the latest item. for (let i = items.length - 1; i >= 0; i--) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop if (match(items[i]!, entry)) { return items[i]; } diff --git a/packages/browser/.oxlintrc.json b/packages/browser/.oxlintrc.json index 28df8e880028..62e4d719c5d8 100644 --- a/packages/browser/.oxlintrc.json +++ b/packages/browser/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true }, diff --git a/packages/browser/package.json b/packages/browser/package.json index b9ceef988167..69fbfc17f31f 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -39,7 +39,7 @@ }, "dependencies": { "@sentry/browser-utils": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/feedback": "11.17.0", "@sentry/replay": "11.17.0", "@sentry/replay-canvas": "11.17.0", diff --git a/packages/browser/src/integrations/spotlight.ts b/packages/browser/src/integrations/spotlight.ts index d4714ce1afbc..718803b53c6a 100644 --- a/packages/browser/src/integrations/spotlight.ts +++ b/packages/browser/src/integrations/spotlight.ts @@ -45,7 +45,8 @@ function setupSidecarForwarding(client: Client, sidecarUrl: string): void { client.on('beforeEnvelope', (envelope: Envelope) => { if (failCount > 3) { - debug.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:', failCount); + DEBUG_BUILD && + debug.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:', failCount); return; } @@ -65,10 +66,11 @@ function setupSidecarForwarding(client: Client, sidecarUrl: string): void { }, err => { failCount++; - debug.error( - "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/", - err, - ); + DEBUG_BUILD && + debug.error( + "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/", + err, + ); }, ); }); diff --git a/packages/browser/src/utils/managedTunnel.ts b/packages/browser/src/utils/managedTunnel.ts index 35b0ef9f959c..89f5f585e5f2 100644 --- a/packages/browser/src/utils/managedTunnel.ts +++ b/packages/browser/src/utils/managedTunnel.ts @@ -4,7 +4,7 @@ import { getTunnelPath, isURLObjectRelative, makeDsn, - _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, + normalizeTunnelBasePath, parseStringToURLObject, } from '@sentry/core'; import { DEBUG_BUILD } from '../debug-build'; diff --git a/packages/bun/package.json b/packages/bun/package.json index 1ed97e3049cf..4f7dcb8b403c 100644 --- a/packages/bun/package.json +++ b/packages/bun/package.json @@ -48,7 +48,7 @@ "dependencies": { "@sentry/bundler-plugins": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", "@sentry/server-utils": "11.17.0" diff --git a/packages/bun/src/tunnelServer.ts b/packages/bun/src/tunnelServer.ts index 3df1bc78740a..12adfb4b5e06 100644 --- a/packages/bun/src/tunnelServer.ts +++ b/packages/bun/src/tunnelServer.ts @@ -1,11 +1,8 @@ import * as http from 'node:http'; import * as https from 'node:https'; -import { _INTERNAL_normalizeTunnelBasePath, debug } from '@sentry/core'; -import { - _INTERNAL_getServedTunnel as getServedTunnel, - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, -} from '@sentry/core/server'; -import { _INTERNAL_instrumentTunnelServer as instrumentTunnelServer } from '@sentry/server-utils'; +import { normalizeTunnelBasePath, debug } from '@sentry/core'; +import { getServedTunnel, handleServedTunnelRequest } from '@sentry/core/server'; +import { instrumentTunnelServer } from '@sentry/server-utils'; import type { Server } from 'bun'; type BunServeOptions = Parameters[0] & { routes?: Record }; @@ -113,7 +110,7 @@ function getTunnelRoutePaths(): string[] { return []; } - const basePath = _INTERNAL_normalizeTunnelBasePath(servedTunnel.basePath); + const basePath = normalizeTunnelBasePath(servedTunnel.basePath); return servedTunnel.paths.flatMap(path => [`${basePath}${path}`, `${basePath}${path}/`]); } diff --git a/packages/bundler-plugins/src/core/build-plugin-manager.ts b/packages/bundler-plugins/src/core/build-plugin-manager.ts index 838a9cc8e3d4..804f5398fa14 100644 --- a/packages/bundler-plugins/src/core/build-plugin-manager.ts +++ b/packages/bundler-plugins/src/core/build-plugin-manager.ts @@ -1,6 +1,5 @@ /* oxlint-disable max-lines */ import { closeSession, DEFAULT_ENVIRONMENT, makeSession, setMeasurement, startSpan } from '@sentry/core'; -import * as dotenv from 'dotenv'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -24,6 +23,7 @@ import type { SourceMapDecision, SourceMapKind } from './sourcemap-settings'; import { decideSourceMapHandling, getSourceMapFeatures } from './sourcemap-settings'; import type { UploadFilter } from './upload-filter'; import { createUploadFilter } from './upload-filter'; +import { getMissingUploadCredential, readSentryBuildPluginEnvFile } from './upload-credentials'; import { LIB_VERSION } from './version'; // Module-level guard to prevent duplicate deploy records when multiple bundler plugin @@ -205,21 +205,13 @@ export function createSentryBuildPluginManager( debug: userOptions.debug ?? false, }); - try { - const dotenvFile = fs.readFileSync(path.join(process.cwd(), '.env.sentry-build-plugin'), 'utf-8'); - // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want. - const dotenvResult = dotenv.parse(dotenvFile); - + const dotenvResult = readSentryBuildPluginEnvFile(); + if (dotenvResult) { // Vite has a bug/behaviour where spreading into process.env will cause it to crash // https://github.com/vitest-dev/vitest/issues/1870#issuecomment-1501140251 Object.assign(process.env, dotenvResult); logger.info('Using environment variables configured in ".env.sentry-build-plugin".'); - } catch (e: unknown) { - // Ignore "file not found" errors but throw all others - if (typeof e === 'object' && e && 'code' in e && e.code !== 'ENOENT') { - throw e; - } } const options = normalizeUserOptions(userOptions); @@ -1065,16 +1057,7 @@ function getSourceMapUploadBlocker(options: NormalizedOptions, isDevMode: boolea if (isDevMode) { return 'dev-mode'; } - if (!options.authToken) { - return 'no-auth-token'; - } - if (!options.org && !options.authToken.startsWith('sntrys_')) { - return 'no-org'; - } - if (!getProjects(options.project)?.[0]) { - return 'no-project'; - } - return undefined; + return getMissingUploadCredential(options); } function canUploadSourceMaps(options: NormalizedOptions, logger: Logger, isDevMode: boolean): boolean { diff --git a/packages/bundler-plugins/src/core/debug-id-upload.ts b/packages/bundler-plugins/src/core/debug-id-upload.ts index 718b6c5973db..d927e292eaa2 100644 --- a/packages/bundler-plugins/src/core/debug-id-upload.ts +++ b/packages/bundler-plugins/src/core/debug-id-upload.ts @@ -404,6 +404,7 @@ export function defaultRewriteSourcesHook(source: string): string { if (source.match(PROTOCOL_REGEX)) { return source.replace(PROTOCOL_REGEX, ''); } else { - return path.relative(process.cwd(), path.normalize(source)); + // Source map `sources` are URLs, so Windows separators must not leak into the uploaded map. + return path.relative(process.cwd(), path.normalize(source)).split(path.sep).join('/'); } } diff --git a/packages/bundler-plugins/src/core/index.ts b/packages/bundler-plugins/src/core/index.ts index abad714a3706..5aec05052595 100644 --- a/packages/bundler-plugins/src/core/index.ts +++ b/packages/bundler-plugins/src/core/index.ts @@ -121,4 +121,5 @@ export { getSourceMapFeatures, } from './sourcemap-settings'; export type { SourceMapDecision, SourceMapKind } from './sourcemap-settings'; +export { hasSourceMapUploadCredentials } from './upload-credentials'; 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 aaba124acd8d..29bf9bec22a6 100644 --- a/packages/bundler-plugins/src/core/options-mapping.ts +++ b/packages/bundler-plugins/src/core/options-mapping.ts @@ -1,4 +1,4 @@ -import { getVercelEnv } from '@sentry/core'; +import { getVercelEnv, warnOnConflictingSourceMapOptions } from '@sentry/core'; import type { Logger } from './logger'; import type { InternalOptions as UserOptions, @@ -9,6 +9,7 @@ import type { ModuleMetadata, ModuleMetadataCallback, } from './types'; +import { parseProjectEnvVar } from './upload-credentials'; import { canAutoDetectRepository, readCommitEnvVar, resolveReleaseName } from './utils'; export type NormalizedOptions = { @@ -99,11 +100,7 @@ export const SENTRY_SAAS_URL = 'https://sentry.io'; export function normalizeUserOptions(userOptions: UserOptions): NormalizedOptions { const options = { org: userOptions.org ?? process.env['SENTRY_ORG'], - project: - userOptions.project ?? - (process.env['SENTRY_PROJECT']?.includes(',') - ? process.env['SENTRY_PROJECT'].split(',').map(p => p.trim()) - : process.env['SENTRY_PROJECT']), + project: userOptions.project ?? parseProjectEnvVar(process.env['SENTRY_PROJECT']), authToken: userOptions.authToken ?? process.env['SENTRY_AUTH_TOKEN'], // 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. @@ -222,32 +219,7 @@ export function validateOptions(options: NormalizedOptions, logger: Logger): boo } } - const sourcemaps = options.sourcemaps; - const usesFeatureOptions = sourcemaps?.upload !== undefined || sourcemaps?.injectDebugIds !== undefined; - if (usesFeatureOptions && sourcemaps?.disable !== undefined) { - logger.warn( - '`sourcemaps.disable` is ignored because `sourcemaps.upload` or `sourcemaps.injectDebugIds` is set.', - 'Please remove `sourcemaps.disable`.', - ); - } - if (sourcemaps?.injectDebugIds === false && sourcemaps.upload === true) { - logger.warn( - '`sourcemaps.upload` is set, but `sourcemaps.injectDebugIds` is `false`.', - 'Source maps are not uploaded, because the upload matches files by debug ID.', - ); - } - if (sourcemaps?.delete !== undefined && sourcemaps.deleteSourcemapsAfterUpload !== undefined) { - logger.warn( - '`sourcemaps.deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set.', - 'Please remove `sourcemaps.deleteSourcemapsAfterUpload`.', - ); - } - if (sourcemaps?.delete === false && sourcemaps.filesToDeleteAfterUpload !== undefined) { - logger.warn( - '`sourcemaps.filesToDeleteAfterUpload` still deletes the files it matches, although `sourcemaps.delete` is `false`.', - 'Remove `sourcemaps.filesToDeleteAfterUpload` to keep the source maps.', - ); - } + warnOnConflictingSourceMapOptions(options.sourcemaps, message => logger.warn(message)); if (options.release?.deploy && typeof options.release.deploy === 'object' && !options.release.deploy.env) { logger.error( diff --git a/packages/bundler-plugins/src/core/upload-credentials.ts b/packages/bundler-plugins/src/core/upload-credentials.ts new file mode 100644 index 000000000000..e89fc7c2f53d --- /dev/null +++ b/packages/bundler-plugins/src/core/upload-credentials.ts @@ -0,0 +1,66 @@ +import * as dotenv from 'dotenv'; +import * as fs from 'fs'; +import * as path from 'path'; +import { getProjects } from './utils'; + +export type UploadCredentials = { + authToken?: string; + org?: string; + project?: string | string[]; +}; + +/** The variables in `.env.sentry-build-plugin`, or `undefined` when the file does not exist. */ +export function readSentryBuildPluginEnvFile(): Record | undefined { + try { + const dotenvFile = fs.readFileSync(path.join(process.cwd(), '.env.sentry-build-plugin'), 'utf-8'); + // NOTE: Do not use the dotenv.config API directly to read the dotenv file! For some ungodly reason, it falls back to reading `${process.cwd()}/.env` which is absolutely not what we want. + return dotenv.parse(dotenvFile); + } catch (e: unknown) { + // Ignore "file not found" errors but throw all others + if (typeof e === 'object' && e && 'code' in e && e.code !== 'ENOENT') { + throw e; + } + return undefined; + } +} + +/** Reads `SENTRY_PROJECT`, which holds one project or a comma-separated list. */ +export function parseProjectEnvVar(value: string | undefined): string | string[] | undefined { + return value?.includes(',') ? value.split(',').map(p => p.trim()) : value; +} + +/** The first credential the upload needs that is missing. */ +export function getMissingUploadCredential({ + authToken, + org, + project, +}: UploadCredentials): 'no-auth-token' | 'no-org' | 'no-project' | undefined { + if (!authToken) { + return 'no-auth-token'; + } + if (!org && !authToken.startsWith('sntrys_')) { + return 'no-org'; + } + if (!getProjects(project)?.[0]) { + return 'no-project'; + } + return undefined; +} + +/** + * Whether the plugin has the credentials to upload source maps. It reads the same environment + * variables and `.env.sentry-build-plugin` file as the plugin, so SDKs can call it before they + * create the plugin. + */ +export function hasSourceMapUploadCredentials(options: UploadCredentials | undefined): boolean { + const envFile = readSentryBuildPluginEnvFile(); + const env = (name: string): string | undefined => envFile?.[name] ?? process.env[name]; + + return ( + getMissingUploadCredential({ + authToken: options?.authToken ?? env('SENTRY_AUTH_TOKEN'), + org: options?.org ?? env('SENTRY_ORG'), + project: options?.project ?? parseProjectEnvVar(env('SENTRY_PROJECT')), + }) === undefined + ); +} diff --git a/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts b/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts new file mode 100644 index 000000000000..d10b40448715 --- /dev/null +++ b/packages/bundler-plugins/test/core/default-rewrite-sources-hook.test.ts @@ -0,0 +1,34 @@ +import type * as Path from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('path', async () => { + const actual = await vi.importActual('path'); + return { ...actual.win32, default: actual.win32 }; +}); + +import { defaultRewriteSourcesHook } from '../../src/core/debug-id-upload'; + +describe('defaultRewriteSourcesHook on Windows', () => { + beforeEach(() => { + vi.spyOn(process, 'cwd').mockReturnValue('C:\\project\\dist\\assets'); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('returns forward-slash sources for relative inputs', () => { + expect(defaultRewriteSourcesHook('../../node_modules/nanoid/index.browser.js')).toBe( + '../../node_modules/nanoid/index.browser.js', + ); + expect(defaultRewriteSourcesHook('../../src/main.js')).toBe('../../src/main.js'); + }); + + it('returns forward-slash sources for absolute inputs', () => { + expect(defaultRewriteSourcesHook('C:\\project\\src\\main.js')).toBe('../../src/main.js'); + }); + + it('strips the protocol from URL sources', () => { + expect(defaultRewriteSourcesHook('webpack://my-app/src/main.js')).toBe('my-app/src/main.js'); + }); +}); diff --git a/packages/bundler-plugins/test/core/option-mappings.test.ts b/packages/bundler-plugins/test/core/option-mappings.test.ts index 42df3d9a3317..ef56d9117d9d 100644 --- a/packages/bundler-plugins/test/core/option-mappings.test.ts +++ b/packages/bundler-plugins/test/core/option-mappings.test.ts @@ -448,34 +448,12 @@ describe('validateOptions', () => { }); describe('source map options', () => { - it.each([ - [{ upload: false, disable: true }, /`sourcemaps\.disable` is ignored/], - [{ injectDebugIds: false, disable: 'disable-upload' }, /`sourcemaps\.disable` is ignored/], - [{ upload: true, injectDebugIds: false }, /`sourcemaps\.injectDebugIds` is `false`/], - [{ delete: true, deleteSourcemapsAfterUpload: false }, /`sourcemaps\.deleteSourcemapsAfterUpload` is ignored/], - [{ delete: false, filesToDeleteAfterUpload: ['dist/**/*.map'] }, /`sourcemaps\.filesToDeleteAfterUpload` still/], - ] as const)('warns about %j', (sourcemaps, message) => { - const options = { sourcemaps } as Partial; + it('warns about conflicting options through the plugin logger', () => { + const options = { sourcemaps: { upload: true, injectDebugIds: false } } as Partial; expect(validateOptions(options as unknown as NormalizedOptions, mockedLogger)).toBe(true); expect(mockedLogger.warn).toHaveBeenCalledTimes(1); - expect(mockedLogger.warn).toHaveBeenCalledWith(expect.stringMatching(message), expect.any(String)); - }); - - it.each([ - { upload: false }, - { injectDebugIds: false }, - { upload: false, injectDebugIds: false }, - { delete: false }, - { disable: true, deleteSourcemapsAfterUpload: true }, - { disable: true, delete: true }, - { delete: true, filesToDeleteAfterUpload: ['extra/**'] }, - { filesToDeleteAfterUpload: ['dist/**/*.map'] }, - ] as const)('does not warn about %j', sourcemaps => { - const options = { sourcemaps } as Partial; - - expect(validateOptions(options as unknown as NormalizedOptions, mockedLogger)).toBe(true); - expect(mockedLogger.warn).not.toHaveBeenCalled(); + expect(mockedLogger.warn).toHaveBeenCalledWith(expect.stringMatching(/`sourcemaps\.injectDebugIds` is `false`/)); }); }); diff --git a/packages/bundler-plugins/test/core/upload-credentials.test.ts b/packages/bundler-plugins/test/core/upload-credentials.test.ts new file mode 100644 index 000000000000..71ef8723f733 --- /dev/null +++ b/packages/bundler-plugins/test/core/upload-credentials.test.ts @@ -0,0 +1,70 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasSourceMapUploadCredentials } from '../../src/core/upload-credentials'; + +describe('hasSourceMapUploadCredentials', () => { + let cwd: string; + + beforeEach(() => { + cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-upload-credentials-')); + vi.spyOn(process, 'cwd').mockReturnValue(cwd); + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + vi.stubEnv('SENTRY_ORG', ''); + vi.stubEnv('SENTRY_PROJECT', ''); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + fs.rmSync(cwd, { recursive: true, force: true }); + }); + + it('returns true with an auth token, org and project in the options', () => { + expect(hasSourceMapUploadCredentials({ authToken: 'token', org: 'org', project: 'project' })).toBe(true); + }); + + it.each([ + ['auth token', { org: 'org', project: 'project' }], + ['org', { authToken: 'token', project: 'project' }], + ['project', { authToken: 'token', org: 'org' }], + ['project in the list', { authToken: 'token', org: 'org', project: [] }], + ])('returns false without an %s', (_, options) => { + expect(hasSourceMapUploadCredentials(options)).toBe(false); + }); + + it('returns false without options', () => { + expect(hasSourceMapUploadCredentials(undefined)).toBe(false); + }); + + it('accepts an org token without an org', () => { + expect(hasSourceMapUploadCredentials({ authToken: 'sntrys_token', project: 'project' })).toBe(true); + }); + + it('reads the environment variables', () => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project1,project2'); + + expect(hasSourceMapUploadCredentials({})).toBe(true); + }); + + it('reads `.env.sentry-build-plugin` before the plugin loads it', () => { + fs.writeFileSync( + path.join(cwd, '.env.sentry-build-plugin'), + 'SENTRY_AUTH_TOKEN=token\nSENTRY_ORG=org\nSENTRY_PROJECT=project\n', + ); + + expect(hasSourceMapUploadCredentials({})).toBe(true); + expect(process.env.SENTRY_AUTH_TOKEN).toBe(''); + }); + + it('prefers the options over the environment', () => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); + + expect(hasSourceMapUploadCredentials({ project: [] })).toBe(false); + }); +}); diff --git a/packages/cloudflare/package.json b/packages/cloudflare/package.json index 84403d7a9cb8..612cffbe5a4d 100644 --- a/packages/cloudflare/package.json +++ b/packages/cloudflare/package.json @@ -53,7 +53,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/opentelemetry": "11.17.0", "@sentry/server-utils": "11.17.0", diff --git a/packages/cloudflare/src/client.ts b/packages/cloudflare/src/client.ts index e6935595d153..25f3e6063210 100644 --- a/packages/cloudflare/src/client.ts +++ b/packages/cloudflare/src/client.ts @@ -1,8 +1,8 @@ import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core'; import { _INTERNAL_clearAiProviderSkips, - _INTERNAL_flushLogsBuffer, - _INTERNAL_flushMetricsBuffer, + flushLogsBuffer, + flushMetricsBuffer, applySdkMetadata, debug, GLOBAL_OBJ, @@ -338,8 +338,8 @@ export class CloudflareClient extends ServerRuntimeClient { const traceId = span.spanContext().traceId; this._eagerDrain(() => this.emit('flushTraceSpans', traceId)); }); - this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this))); - this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this))); + this.on('afterCaptureLog', () => this._eagerDrain(() => flushLogsBuffer(this))); + this.on('afterCaptureMetric', () => this._eagerDrain(() => flushMetricsBuffer(this))); } /** diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts index b86371145050..7d36839a6857 100644 --- a/packages/cloudflare/src/index.ts +++ b/packages/cloudflare/src/index.ts @@ -134,6 +134,7 @@ export { _INTERNAL_wrapRequestHandler, getDefaultIntegrations, init as _INTERNAL export { getFinalOptions as _INTERNAL_getFinalOptions } from './options'; export { httpServerIntegration } from './integrations/httpServer'; +export { addServerTimingTraceHeader } from '@sentry/server-utils/request-handler'; export { fetchIntegration } from './integrations/fetch'; export type { FetchIntegrationOptions } from '@sentry/core'; export { spotlightIntegration } from './integrations/spotlight'; diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts b/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts index a3de0f67b24b..9351c03a6e05 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts @@ -37,6 +37,8 @@ const instrumentedBindings = new WeakMap(); * - R2 Buckets (via `head` + `put` + `createMultipartUpload` duck-typing) * - Workers AI (via `run` + `gateway` + `toMarkdown` duck-typing) * + * `ctx.exports` is wrapped the same way, as its entries are bindings to this Worker's own exports. + * * @param env - The Cloudflare env object to instrument * @param options - Optional CloudflareOptions to control RPC and Queue trace propagation */ @@ -104,31 +106,7 @@ export function instrumentEnv>(env: Env, opt } if (isJSRPC(item)) { - const instrumented = new Proxy(item, { - get(target, p) { - const value = Reflect.get(target, p); - - if (p === 'fetch' && typeof value === 'function') { - return instrumentFetcher((...args) => Reflect.apply(value, target, args)); - } - - if (p === 'connect' && typeof value === 'function') { - return (...args: unknown[]) => Reflect.apply(value, target, args); - } - - if ( - propagateRpcTrace && - typeof value === 'function' && - typeof p === 'string' && - !STUB_NON_RPC_METHODS.has(p) - ) { - return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args)); - } - - return value; - }, - }); - + const instrumented = instrumentServiceStub(item, propagateRpcTrace); instrumentedBindings.set(item, instrumented); return instrumented; } @@ -137,3 +115,30 @@ export function instrumentEnv>(env: Env, opt }, }); } + +function instrumentServiceStub(stub: T, propagateRpcTrace: boolean): T { + return new Proxy(stub, { + get(target, p) { + const value = Reflect.get(target, p); + + if (p === 'fetch' && typeof value === 'function') { + return instrumentFetcher((...args) => Reflect.apply(value, target, args)); + } + + if (p === 'connect' && typeof value === 'function') { + return (...args: unknown[]) => Reflect.apply(value, target, args); + } + + if (propagateRpcTrace && typeof value === 'function' && typeof p === 'string' && !STUB_NON_RPC_METHODS.has(p)) { + return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args)); + } + + return value; + }, + // An entrypoint in `ctx.exports` is callable: `ctx.exports.Name({ props })` returns a stub with these props. + apply(target, thisArg, args) { + const result: unknown = Reflect.apply(target as (...args: unknown[]) => unknown, thisArg, args); + return isProxyable(result) ? instrumentServiceStub(result, propagateRpcTrace) : result; + }, + }); +} diff --git a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts index a303d417f169..1352cf99795a 100644 --- a/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts +++ b/packages/cloudflare/src/instrumentations/worker/instrumentTail.ts @@ -14,6 +14,7 @@ import { instrumentEnv } from './instrumentEnv'; type TailMethod = 'tail' | 'trace' | 'tailStream'; +// workerd calls `trace` only when the worker has no `tail`. It is not documented, but it is still in use. const TAIL_METHODS: TailMethod[] = ['tail', 'trace', 'tailStream']; const MECHANISM_TYPES: Record = { diff --git a/packages/cloudflare/src/utils/instrumentContext.ts b/packages/cloudflare/src/utils/instrumentContext.ts index af28f07d3ced..9f834d215262 100644 --- a/packages/cloudflare/src/utils/instrumentContext.ts +++ b/packages/cloudflare/src/utils/instrumentContext.ts @@ -1,5 +1,6 @@ import { type DurableObjectState, type DurableObjectStorage, type ExecutionContext } from '@cloudflare/workers-types'; import { instrumentDurableObjectStorage } from '../instrumentations/instrumentDurableObjectStorage'; +import { instrumentEnv } from '../instrumentations/worker/instrumentEnv'; type ContextType = ExecutionContext | DurableObjectState; type OverridesStore = Map unknown>; @@ -11,6 +12,8 @@ type OverridesStore = Map(ctx: T): T { }; } + if ('exports' in ctx) { + let instrumentedExports: unknown; + descriptors.exports = { + configurable: true, + enumerable: true, + get: () => (instrumentedExports ??= instrumentEnv(ctx.exports as Record)), + }; + } + return Object.create(ctx, descriptors); } diff --git a/packages/cloudflare/src/vite/autoInstrument.ts b/packages/cloudflare/src/vite/autoInstrument.ts index aa1c6d48bca4..bef38c6dc05e 100644 --- a/packages/cloudflare/src/vite/autoInstrument.ts +++ b/packages/cloudflare/src/vite/autoInstrument.ts @@ -19,6 +19,9 @@ const JS_EXTENSION_REGEX = /\.[cm]?[jt]sx?$/; // Re-exports everything the generated code uses, and adds the Next.js span handling and OpenTelemetry context. const NEXTJS_CLOUDFLARE_MODULE = '@sentry/nextjs/cloudflare'; +// `@cloudflare/vite-plugin` loads the Worker from this module. `resolveId` prefixes it with `\0`. +const CLOUDFLARE_WORKER_ENTRY_ID = 'virtual:cloudflare/worker-entry'; + /** * Whether `@sentry/nextjs/cloudflare` resolves from `importer`. Vite throws instead of returning `null` when * `@sentry/nextjs` is installed in a version without that entry. @@ -31,6 +34,33 @@ async function resolvesNextjsCloudflare(resolver: ModuleResolver, importer: stri } } +function isCloudflareWorkerEntry(id: string): boolean { + const bare = (id.charCodeAt(0) === 0 ? id.slice(1) : id).replace(/[?#].*$/, ''); + return bare === CLOUDFLARE_WORKER_ENTRY_ID; +} + +/** + * Exported names of the `export { A, B } from "..."` statements other plugins append to the + * worker-entry facade, such as vinext's Workers Cache response stages. `default` is the user entry, + * which the entry transform wraps. + */ +function appendedNamedReexports(ast: ProgramBody): string[] { + const names: string[] = []; + for (const node of ast.body) { + if (node.type !== 'ExportNamedDeclaration') continue; + const { source, specifiers } = node as BaseNode & { + source?: { value?: unknown } | null; + specifiers?: Array<{ exported?: { name?: string } }>; + }; + if (typeof source?.value !== 'string') continue; + for (const specifier of specifiers ?? []) { + const exported = specifier.exported?.name; + if (exported && exported !== 'default') names.push(exported); + } + } + return names; +} + /** * 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"`). @@ -81,8 +111,50 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa return entry; } + async function instrumentFacadeEntrypoints( + ctx: TransformContext, + code: string, + ): Promise<{ code: string; map: unknown } | undefined> { + let ast: ProgramBody; + try { + ast = ctx.parse(code); + } catch { + return undefined; + } + + const names = appendedNamedReexports(ast); + if (names.length === 0) return undefined; + + // A virtual module has no directory. Resolve options and `@sentry/nextjs/cloudflare` from a real file. + const importer = entryFilePath ?? wranglerConfigPath; + if (!importer) return undefined; + + const sentryModule = + isVinext && (await resolvesNextjsCloudflare(ctx, importer)) ? NEXTJS_CLOUDFLARE_MODULE : undefined; + const { optionsFn, importStmt: optionsImport } = instrumentFilePath + ? buildOptionsImport(importer, instrumentFilePath, { absolute: true }) + : { optionsFn: ENV_FALLBACK_OPTIONS_FN, importStmt: undefined }; + + // Adapters build some entrypoints with a factory, which no static check can see. `withSentry` + // checks at run time whether the value extends `WorkerEntrypoint`, and returns any other value, + // such as a Durable Object, unchanged. + const classWrappers = new Map(names.map(name => [name, 'workerEntrypoint'])); + return ( + applyAutoInstrumentTransforms(code, ast, { + classWrappers, + optionsFn, + optionsImport, + sentryModule, + wrapDefault: false, + }) ?? undefined + ); + } + return { name: 'sentry-cloudflare-auto-instrument', + // vinext appends its Workers Cache entrypoints to the worker-entry module in a normal transform. + // Running after all normal plugins makes them visible here in any plugin order. + enforce: 'post' as const, // Without it, `vite dev` calls `buildStart` only for the client environment, which this plugin skips. perEnvironmentStartEndDuringDev: true, @@ -157,6 +229,12 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa // client entry next to a `src/index.ts` worker) out of the browser bundle. if (this.environment?.name === 'client') return undefined; + // Named entrypoints appended to this facade are invoked through `ctx.exports` and never run + // the wrapped default export, so `Sentry.init` does not run in that invocation. + if (isCloudflareWorkerEntry(id)) { + return instrumentFacadeEntrypoints(this, code); + } + const virtualEntry = this.environment && virtualEntries.get(this.environment.name); const entryPath = virtualEntry ?? (entrySpecifier ? await resolveEntrySpecifier(this, entrySpecifier) : entryFilePath); @@ -208,7 +286,7 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa agentCandidates.size > 0 ? await detectAgentClasses(ast, normalizedId, agentCandidates, { parse: code => this.parse(code), - resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined, + resolve: this.resolve?.bind(this), }) : undefined; diff --git a/packages/cloudflare/src/vite/index.ts b/packages/cloudflare/src/vite/index.ts index 921c036ae327..515691c574bd 100644 --- a/packages/cloudflare/src/vite/index.ts +++ b/packages/cloudflare/src/vite/index.ts @@ -71,7 +71,9 @@ export interface SentryCloudflareVitePluginOptions { * - wraps your Worker entry (and any Durable Object, Workflow or * WorkerEntrypoint class in your wrangler config) with the matching Sentry * helper — opt out with `autoInstrumentation: false` and call - * `Sentry.withSentry()` yourself. + * `Sentry.withSentry()` yourself. WorkerEntrypoint classes that another Vite + * plugin adds to the Worker's exports, such as the Workers Cache entrypoints + * of vinext, are wrapped as well. * * @example * ```ts diff --git a/packages/cloudflare/src/vite/moduleShape.ts b/packages/cloudflare/src/vite/moduleShape.ts index 8125428599b1..edb1a81c0dfb 100644 --- a/packages/cloudflare/src/vite/moduleShape.ts +++ b/packages/cloudflare/src/vite/moduleShape.ts @@ -212,6 +212,7 @@ export function shapeFromSource(rawCode: string): ModuleShape { // `class X extends Y {` / `class X extends Y {`, optionally exported and/or abstract. const CLASS_RE = /\b(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)([^{]*)\{/g; for (const match of code.matchAll(CLASS_RE)) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group const className = match[1]!; const isDefault = /\bexport\s+default\b/.test(match[0]); const superRef = superRefFromHeader(match[2] ?? ''); @@ -249,6 +250,7 @@ export function shapeFromSource(rawCode: string): ModuleShape { // `import Default, { a as b }, * as ns from '...'` in its various shapes. for (const match of code.matchAll(/\bimport\s+([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g)) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group addSourceImports(shape, match[1] ?? '', match[2]!); } @@ -265,6 +267,7 @@ function superRefFromHeader(header: string): SuperRef | undefined { const match = /\bextends\s+([A-Za-z_$][\w$]*)\s*(?:\.\s*([A-Za-z_$][\w$]*))?/.exec(withoutParams); if (!match) return undefined; + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group return match[2] ? { kind: 'member', object: match[1]!, property: match[2] } : { kind: 'identifier', name: match[1]! }; } @@ -302,6 +305,7 @@ function parseSpecifierList(clause: string): Array<{ imported: string; local: st const aliased = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(part); if (aliased) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture groups specifiers.push({ imported: aliased[1]!, local: aliased[2]! }); } else if (/^[A-Za-z_$][\w$]*$/.test(part)) { specifiers.push({ imported: part, local: part }); @@ -317,6 +321,7 @@ function addSourceImports(shape: ModuleShape, clause: string, source: string): v const namespaceMatch = /\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(clause); if (namespaceMatch) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group shape.namespaces.set(namespaceMatch[1]!, source); } @@ -330,6 +335,7 @@ function addSourceImports(shape: ModuleShape, clause: string, source: string): v // A leading bare identifier (before any brace/star) is the default import. const defaultMatch = /^\s*([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(clause); if (defaultMatch) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- mandatory capture group shape.imports.set(defaultMatch[1]!, { source, imported: DEFAULT_EXPORT }); } } @@ -340,7 +346,7 @@ function stripComments(code: string): string { let index = 0; while (index < code.length) { - const char = code[index]!; + const char = code.charAt(index); const next = code[index + 1]; if (char === '/' && next === '/') { @@ -362,12 +368,12 @@ function stripComments(code: string): string { result += char; index++; while (index < code.length) { - const inner = code[index]!; + const inner = code.charAt(index); result += inner; index++; if (inner === '\\') { if (index < code.length) { - result += code[index]!; + result += code.charAt(index); index++; } continue; diff --git a/packages/cloudflare/src/vite/transform.ts b/packages/cloudflare/src/vite/transform.ts index 16de8fc6386d..50df26a4b5a9 100644 --- a/packages/cloudflare/src/vite/transform.ts +++ b/packages/cloudflare/src/vite/transform.ts @@ -132,6 +132,12 @@ export interface TransformContext { * handlers get them too. */ workerInfo?: { name?: string; compatibilityDate?: string }; + /** + * Whether `export default ` is wrapped with `withSentry`. False for the worker-entry + * module of `@cloudflare/vite-plugin`, whose default export is the user entry's default export, + * which the entry transform wraps. + */ + wrapDefault?: boolean; } export interface TransformResult { @@ -197,9 +203,11 @@ export function applyAutoInstrumentTransforms( handleNamedExport(node, ctx, state); } } - for (const node of ast.body) { - if (node.type === 'ExportDefaultDeclaration') { - wrapDefaultExport(node as ExportDefaultNode, ctx, state); + if (ctx.wrapDefault !== false) { + for (const node of ast.body) { + if (node.type === 'ExportDefaultDeclaration') { + wrapDefaultExport(node as ExportDefaultNode, ctx, state); + } } } diff --git a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts index 837cf36c5d99..37150a1a28bc 100644 --- a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts +++ b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts @@ -3,7 +3,7 @@ import { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/convent import type { SpanAttributes } from '@sentry/core'; import { getIsolationScope, safeCallback } from '@sentry/core'; import { - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, + handleServedTunnelRequest, _INTERNAL_setScopeFlushedByRuntime as setScopeFlushedByRuntime, } from '@sentry/core/server'; import { wrapServerRequestHandler } from '@sentry/server-utils/request-handler'; diff --git a/packages/cloudflare/test/instrumentContext.test.ts b/packages/cloudflare/test/instrumentContext.test.ts index 4304a303a155..9c601c01680b 100644 --- a/packages/cloudflare/test/instrumentContext.test.ts +++ b/packages/cloudflare/test/instrumentContext.test.ts @@ -1,3 +1,4 @@ +import * as SentryCore from '@sentry/core'; import { describe, expect, it, type Mocked, vi } from 'vitest'; import { instrumentContext } from '../src/utils/instrumentContext'; @@ -97,8 +98,33 @@ describe('instrumentContext', () => { expect(instrumented.originalStorage).toBeUndefined(); }); }); + + it('adds trace headers to fetch calls on an entrypoint called with props through exports', async () => { + vi.spyOn(SentryCore, '_INTERNAL_getTracingHeadersForFetchRequest').mockReturnValue({ + 'sentry-trace': '12345678901234567890123456789012-1234567890123456-1', + }); + const fetch = vi.fn().mockResolvedValue(new Response('ok')); + const entrypoint = createRpcStub(vi.fn((_options: { props: { id: number } }) => createRpcStub({ fetch }))); + const context = { ...makeExecutionContextMock(), exports: { Entrypoint: entrypoint } }; + const instrumented = instrumentContext(context); + + await instrumented.exports.Entrypoint({ props: { id: 1 } }).fetch('https://loopback/'); + + expect(entrypoint).toHaveBeenCalledWith({ props: { id: 1 } }); + expect(fetch).toHaveBeenCalledWith('https://loopback/', { + headers: { 'sentry-trace': '12345678901234567890123456789012-1234567890123456-1' }, + }); + expect(context.exports.Entrypoint).toBe(entrypoint); + }); }); +/** An RPC stub returns a value for every property name, as workerd's RPC stubs do. */ +function createRpcStub(target: T): T { + return new Proxy(target, { + get: (stub, prop) => (prop in stub ? Reflect.get(stub, prop) : () => {}), + }); +} + function makeExecutionContextMock() { return { waitUntil: vi.fn(), diff --git a/packages/cloudflare/test/vite/autoInstrument.test.ts b/packages/cloudflare/test/vite/autoInstrument.test.ts index fedb63e63d78..9603e9a33f9d 100644 --- a/packages/cloudflare/test/vite/autoInstrument.test.ts +++ b/packages/cloudflare/test/vite/autoInstrument.test.ts @@ -542,6 +542,67 @@ describe('sentryCloudflareAutoInstrumentPlugin', () => { expect(warnings[0]).toContain('MyDO'); }); + it('wraps named entrypoints a host adapter appends to the Cloudflare worker-entry facade', async () => { + const dir = writeTempDir({ + 'wrangler.toml': 'main = "index.ts"', + 'instrument.server.ts': 'export default () => ({ dsn: "x" });', + }); + const plugin = sentryCloudflareAutoInstrumentPlugin(); + plugin.configResolved({ root: dir, plugins: [{ name: 'vinext:config' }] }); + const resolve = vi.fn().mockResolvedValue({ id: join(dir, 'node_modules/@sentry/nextjs/cloudflare.js') }); + + // The statement `workersCacheCdnAdapter()` of `@vinext/cloudflare` appends. + const adapter = JSON.stringify(join(dir, 'node_modules/@vinext/cloudflare/dist/cache/cdn-adapter.worker.js')); + const code = [ + 'import * as mod from "virtual:cloudflare/user-entry";', + 'export * from "virtual:cloudflare/user-entry";', + 'export default mod.default ?? {};', + `export { VinextCachedResponse, VinextUncachedResponse } from ${adapter};`, + ].join('\n'); + + const result = await plugin.transform.call( + { parse: (c: string) => parseJS(c), resolve }, + code, + '\0virtual:cloudflare/worker-entry', + ); + + const instrumentImport = join(dir, 'instrument.server.ts').replace(/\\/g, '/'); + expect(result.code).toBe( + [ + "import * as __SENTRY__ from '@sentry/nextjs/cloudflare';", + `import __SENTRY_OPTIONS_CALLBACK__ from '${instrumentImport}';`, + 'import * as mod from "virtual:cloudflare/user-entry";', + 'export * from "virtual:cloudflare/user-entry";', + 'export default mod.default ?? {};', + `import { VinextCachedResponse as __SENTRY_REEXPORT_VinextCachedResponse__ } from ${adapter};`, + 'const __SENTRY_WRAPPED_VinextCachedResponse__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, __SENTRY_OPTIONS_CALLBACK__, __SENTRY_REEXPORT_VinextCachedResponse__);', + `import { VinextUncachedResponse as __SENTRY_REEXPORT_VinextUncachedResponse__ } from ${adapter};`, + 'const __SENTRY_WRAPPED_VinextUncachedResponse__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, __SENTRY_OPTIONS_CALLBACK__, __SENTRY_REEXPORT_VinextUncachedResponse__);', + 'export { __SENTRY_WRAPPED_VinextCachedResponse__ as VinextCachedResponse, __SENTRY_WRAPPED_VinextUncachedResponse__ as VinextUncachedResponse };', + ].join('\n'), + ); + expect(resolve).toHaveBeenCalledWith('@sentry/nextjs/cloudflare', join(dir, 'index.ts')); + }); + + it('leaves the Cloudflare worker-entry facade alone when no named entrypoint was appended', async () => { + const dir = writeTempDir({ 'wrangler.toml': 'main = "index.ts"' }); + const plugin = sentryCloudflareAutoInstrumentPlugin(); + plugin.configResolved({ root: dir }); + + const code = [ + 'import * as mod from "virtual:cloudflare/user-entry";', + 'export * from "virtual:cloudflare/user-entry";', + 'export default mod.default ?? {};', + ].join('\n'); + const result = await plugin.transform.call( + { parse: (c: string) => parseJS(c) }, + code, + '\0virtual:cloudflare/worker-entry', + ); + + expect(result).toBeUndefined(); + }); + it('does not warn for a shim that re-exports everything from a query variant of the entry', async () => { const dir = writeTempDir({ 'wrangler.toml': [ diff --git a/packages/core/.oxlintrc.json b/packages/core/.oxlintrc.json index 227cf5b770b9..e45dfa197576 100644 --- a/packages/core/.oxlintrc.json +++ b/packages/core/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "jsPlugins": [ { "name": "sdk", diff --git a/packages/core/package.json b/packages/core/package.json index 20e2a669cb22..abf063b38070 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -88,6 +88,6 @@ "zod": "^4.6.7" }, "dependencies": { - "@sentry/conventions": "^0.35.0" + "@sentry/conventions": "^0.36.0" } } diff --git a/packages/core/src/build-time-plugins/warnOnConflictingSourceMapOptions.ts b/packages/core/src/build-time-plugins/warnOnConflictingSourceMapOptions.ts new file mode 100644 index 000000000000..c49e841583dd --- /dev/null +++ b/packages/core/src/build-time-plugins/warnOnConflictingSourceMapOptions.ts @@ -0,0 +1,71 @@ +import { consoleSandbox } from '../utils/debug-logger'; + +/** The source map options that can conflict with each other. */ +export interface ConflictingSourceMapOptions { + disable?: boolean | 'disable-upload'; + upload?: boolean; + injectDebugIds?: boolean; + delete?: boolean; + deleteSourcemapsAfterUpload?: unknown; + filesToDeleteAfterUpload?: unknown; +} + +// An SDK and each of its plugin instances call this for the same options. +const loggedWarnings = new Set(); + +/** + * Warns about `sourcemaps` options that conflict with each other. It logs + * each warning once per process. + * + * The bundler plugin calls this for the options it gets. SDKs that apply some of the options + * themselves call it with the user's options, because the plugin does not see them all. + * + * @param sourcemaps The user's `sourcemaps` options, if any. + * @param logWarning Called with each warning message. Defaults to `console.warn` with a + * `[Sentry]` prefix. Pass a logger that adds its own prefix to route the warnings through it. + * + * @internal Only meant for Sentry-internal SDK usage. + * @hidden + */ +export function warnOnConflictingSourceMapOptions( + sourcemaps: ConflictingSourceMapOptions | undefined, + logWarning: (message: string) => void = message => + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn(`[Sentry] ${message}`); + }), +): void { + if (!sourcemaps) { + return; + } + + const warn = (message: string): void => { + if (!loggedWarnings.has(message)) { + loggedWarnings.add(message); + logWarning(message); + } + }; + + const usesFeatureOptions = sourcemaps.upload !== undefined || sourcemaps.injectDebugIds !== undefined; + // TODO(v12): Remove along with `sourcemaps.disable`. + if (usesFeatureOptions && sourcemaps.disable !== undefined) { + warn( + '`sourcemaps.disable` is ignored because `sourcemaps.upload` or `sourcemaps.injectDebugIds` is set. Please remove `sourcemaps.disable`.', + ); + } + if (sourcemaps.injectDebugIds === false && sourcemaps.upload === true) { + warn( + '`sourcemaps.upload` is set, but `sourcemaps.injectDebugIds` is `false`. Source maps are not uploaded, because the upload matches files by debug ID.', + ); + } + if (sourcemaps.delete !== undefined && sourcemaps.deleteSourcemapsAfterUpload !== undefined) { + warn( + '`sourcemaps.deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set. Please remove `sourcemaps.deleteSourcemapsAfterUpload`.', + ); + } + if (sourcemaps.delete === false && sourcemaps.filesToDeleteAfterUpload !== undefined) { + warn( + '`sourcemaps.filesToDeleteAfterUpload` still deletes the files it matches, although `sourcemaps.delete` is `false`. Remove `sourcemaps.filesToDeleteAfterUpload` to keep the source maps.', + ); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e2161bfd57ea..73f7a53c45a0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -102,11 +102,7 @@ export { safeCallback } from './utils/safeCallback'; export { parameterize, fmt } from './utils/parameterize'; export type { HandleTunnelRequestOptions } from './utils/tunnelForward'; export { handleTunnelRequest } from './utils/tunnelForward'; -export { - applyBrowserTunnelDefaults as _INTERNAL_applyBrowserTunnelDefaults, - getTunnelPath, - normalizeTunnelBasePath as _INTERNAL_normalizeTunnelBasePath, -} from './utils/tunnel'; +export { applyBrowserTunnelDefaults, getTunnelPath, normalizeTunnelBasePath } from './utils/tunnel'; export { addAutoIpAddressToSession } from './utils/ipAddress'; export { convertSpanLinksForEnvelope, @@ -119,7 +115,6 @@ export { getSpanDescendants, getStatusMessage, getRootSpan, - INTERNAL_getSegmentSpan, getActiveSpan, addChildSpanToSpan, spanTimeInputToSeconds, @@ -186,12 +181,28 @@ export { profiler } from './profiling'; export { instrumentFetchRequest, _INTERNAL_getTracingHeadersForFetchRequest } from './fetch'; export { captureFeedback } from './feedback'; export type { ReportDialogOptions } from './report-dialog'; -export { _INTERNAL_captureLog, _INTERNAL_flushLogsBuffer, _INTERNAL_captureSerializedLog } from './logs/internal'; +export { + captureLogEvent, + flushLogsBuffer, + bufferSerializedLog, + // oxlint-disable-next-line typescript/no-deprecated + _INTERNAL_captureLog, + // oxlint-disable-next-line typescript/no-deprecated + _INTERNAL_flushLogsBuffer, + // oxlint-disable-next-line typescript/no-deprecated + _INTERNAL_captureSerializedLog, +} from './logs/internal'; export { logger } from './logs/public-api'; export { consoleLoggingIntegration } from './logs/console-integration'; export { - _INTERNAL_captureMetric, + flushMetricsBuffer, + captureMetricEvent, + bufferSerializedMetric, + // oxlint-disable-next-line typescript/no-deprecated _INTERNAL_flushMetricsBuffer, + // oxlint-disable-next-line typescript/no-deprecated + _INTERNAL_captureMetric, + // oxlint-disable-next-line typescript/no-deprecated _INTERNAL_captureSerializedMetric, } from './metrics/internal'; export { metrics } from './metrics/public-api'; @@ -204,8 +215,6 @@ export { _INTERNAL_copyFlagsFromScopeToEvent, _INTERNAL_insertFlagToScope, _INTERNAL_addFeatureFlagToActiveSpan, - _INTERNAL_FLAG_BUFFER_SIZE, - _INTERNAL_MAX_FLAGS_PER_SPAN, } from './utils/featureFlags'; export { applyAggregateErrorsToEvent } from './utils/aggregate-errors'; export { getBreadcrumbLogLevelFromHttpStatusCode } from './utils/breadcrumb-log-level'; @@ -569,5 +578,7 @@ export { export { warnOnRemovedBuildOptions } from './build-time-plugins/warnOnRemovedBuildOptions'; export { resolveSourceMapsFeatures } from './build-time-plugins/resolveSourceMapsFeatures'; export type { SourceMapsFeatures } from './build-time-plugins/resolveSourceMapsFeatures'; +export { warnOnConflictingSourceMapOptions } from './build-time-plugins/warnOnConflictingSourceMapOptions'; +export type { ConflictingSourceMapOptions } from './build-time-plugins/warnOnConflictingSourceMapOptions'; export { stringifyForCodeInjection } from './build-time-plugins/stringifyForCodeInjection'; export { startSpan, startInactiveSpan, startSpanManual } from './tracing/trace'; diff --git a/packages/core/src/integrations/consola.ts b/packages/core/src/integrations/consola.ts index 2c57c9e44360..015f6c4a7d8a 100644 --- a/packages/core/src/integrations/consola.ts +++ b/packages/core/src/integrations/consola.ts @@ -1,7 +1,7 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import type { Client } from '../client'; import { getClient } from '../currentScopes'; -import { _INTERNAL_captureLog } from '../logs/internal'; +import { captureLogEvent } from '../logs/internal'; import { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from '../logs/utils'; import type { LogSeverityLevel } from '../types/log'; import { isPlainObject } from '../utils/is'; @@ -279,7 +279,7 @@ export function createConsolaReporter(options: ConsolaReporterOptions = {}): Con Object.assign(attributes, extractionResult.attributes); } - _INTERNAL_captureLog({ + captureLogEvent({ level: logSeverityLevel, message: extractionResult?.message || diff --git a/packages/core/src/integrations/reportSdkConfig.ts b/packages/core/src/integrations/reportSdkConfig.ts index f30bda46f007..2efdcfabb2c7 100644 --- a/packages/core/src/integrations/reportSdkConfig.ts +++ b/packages/core/src/integrations/reportSdkConfig.ts @@ -1,13 +1,14 @@ import type { Client } from '../client'; import { DEBUG_BUILD } from '../debug-build'; import { defineIntegration } from '../integration'; -import { _INTERNAL_flushMetricsBuffer } from '../metrics/internal'; +import { flushMetricsBuffer } from '../metrics/internal'; import { count } from '../metrics/public-api'; import { Scope } from '../scope'; import type { Integration, IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; import { fnv1a32 } from '../utils/hash'; import { isPlainObject } from '../utils/is'; +import { isBrowser } from '../utils/isBrowser'; import { safeUnref } from '../utils/timer'; const _experimentalReportSdkConfigIntegration = (() => ({ @@ -38,7 +39,7 @@ const _experimentalReportSdkConfigIntegration = (() => ({ client.on('flush', () => { report(); // Capturing can register the metrics flusher too late for this flush, or after an existing flusher. - _INTERNAL_flushMetricsBuffer(client); + flushMetricsBuffer(client); }); }, })) satisfies IntegrationFn; @@ -57,11 +58,16 @@ function serialize(value: unknown, ancestors = new Set()): unknown { return `[Function:${fnv1a32(Function.prototype.toString.call(value))}]`; } - // initialScope extras can contain bigints or symbols; JSON throws on bigints and omits symbols. + // JSON throws on bigints and omits symbols. if (typeof value === 'bigint' || typeof value === 'symbol') { return `[${typeof value}:${fnv1a32(String(value))}]`; } + // JSON turns these into null, which would make them look like an explicit null. + if (typeof value === 'number' && !Number.isFinite(value)) { + return `[${value}]`; + } + // Pass through primitives and null unchanged. if (value === null || typeof value !== 'object') { return value; @@ -95,7 +101,7 @@ function serialize(value: unknown, ancestors = new Set()): unknown { } // Integrations hold the SDK defaults by the time the client has them; serverName would split configurations by host. -const EXCLUDED_OPTIONS = new Set(['dist', 'dsn', 'integrations', 'release', 'serverName']); +const EXCLUDED_OPTIONS = new Set(['dist', 'dsn', 'environment', 'integrations', 'release', 'serverName']); function buildConfigAttributes(client: Client): Record { const { @@ -105,8 +111,8 @@ function buildConfigAttributes(client: Client): Record { removedDefaultIntegrations, } = client.getSdkMetadata() || {}; const clientOptions = client.getOptions(); - const { environment } = clientOptions; - const runtime = 'runtime' in clientOptions ? clientOptions.runtime : undefined; + // Server clients set their runtime as an option; browser clients have none. + const runtime = 'runtime' in clientOptions ? clientOptions.runtime : isBrowser() ? { name: 'browser' } : undefined; // Only what the user passed, so SDK defaults never show up as config. const options: Record = Object.fromEntries( @@ -121,6 +127,10 @@ function buildConfigAttributes(client: Client): Record { }); } + if (isPlainObject(options.initialScope)) { + options.initialScope = describeShape(options.initialScope); + } + if (Array.isArray(options.defaultIntegrations)) { // `getIntegrationsToSetup` flags these as default instances, but the user passed them. options.defaultIntegrations = options.defaultIntegrations.map((integration: Integration) => @@ -130,10 +140,9 @@ function buildConfigAttributes(client: Client): Record { // The hash covers the whole payload, so a payload cached by its hash is never stale. const payload = JSON.stringify({ - version: 3, + version: 4, sdk: serialize(sdk), runtime: serialize(runtime), - environment, // Not an init() option, so it stays out of `options`. ...(removedDefaultIntegrations && { removed_default_integrations: removedDefaultIntegrations }), options: serialize(options), @@ -145,6 +154,25 @@ function buildConfigAttributes(client: Client): Record { }; } +/** + * Keeps the keys of nested plain objects and replaces every value with a placeholder. + * `initialScope` holds data such as the user's ID, which would make the hash unique per user. + */ +function describeShape(value: unknown, ancestors = new Set()): unknown { + if (!isPlainObject(value) || ancestors.has(value)) { + return '[value]'; + } + + const nextAncestors = new Set(ancestors).add(value); + + const shape: Record = {}; + for (const key of Object.keys(value)) { + shape[key] = describeShape(value[key], nextAncestors); + } + + return shape; +} + function describeIntegration(name: string, options: unknown): { name: string; options?: unknown } { if (options === undefined) { return { name }; diff --git a/packages/core/src/logs/console-integration.ts b/packages/core/src/logs/console-integration.ts index 2385da4fce34..22fad7433fb6 100644 --- a/packages/core/src/logs/console-integration.ts +++ b/packages/core/src/logs/console-integration.ts @@ -7,7 +7,7 @@ import type { IntegrationFn } from '../types/integration'; import { CONSOLE_LEVELS } from '../utils/debug-logger'; import { isPlainObject } from '../utils/is'; import { normalize } from '../utils/normalize'; -import { _INTERNAL_captureLog } from './internal'; +import { captureLogEvent } from './internal'; import { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions } from './utils'; interface CaptureConsoleOptions { @@ -42,7 +42,7 @@ const _consoleLoggingIntegration = ((options: Partial = { followingArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(followingArgs, normalizeDepth, normalizeMaxBreadth)}` : 'Assertion failed'; - _INTERNAL_captureLog({ level: 'error', message: assertionMessage, attributes: DEFAULT_ATTRIBUTES }); + captureLogEvent({ level: 'error', message: assertionMessage, attributes: DEFAULT_ATTRIBUTES }); } return; } @@ -76,7 +76,7 @@ const _consoleLoggingIntegration = ((options: Partial = { } } - _INTERNAL_captureLog({ + captureLogEvent({ level: isLevelLog ? 'info' : level, message: formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth), severityNumber: isLevelLog ? 10 : undefined, diff --git a/packages/core/src/logs/internal.ts b/packages/core/src/logs/internal.ts index dd5cc98ee5fc..da3639b2ea6d 100644 --- a/packages/core/src/logs/internal.ts +++ b/packages/core/src/logs/internal.ts @@ -52,7 +52,8 @@ function setLogAttribute( } /** - * Captures a serialized log event and adds it to the log buffer for the given client. + * Adds an already serialized log to the log buffer for the given client. + * It skips enrichment and `beforeSendLog`, so the log must be fully processed. * * @param client - A client. Uses the current client if not provided. * @param serializedLog - The serialized log event to capture. @@ -60,17 +61,17 @@ function setLogAttribute( * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_captureSerializedLog(client: Client, serializedLog: SerializedLog): void { +export function bufferSerializedLog(client: Client, serializedLog: SerializedLog): void { const bufferMap = _getBufferMap(); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); if (logBuffer === undefined) { // Set up flushing on the first log, so apps that never capture logs don't bundle the flush code. - setupWeightBasedFlushing(client, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer); + setupWeightBasedFlushing(client, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, flushLogsBuffer); bufferMap.set(client, [serializedLog]); } else { if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) { - _INTERNAL_flushLogsBuffer(client, logBuffer); + flushLogsBuffer(client, logBuffer); bufferMap.set(client, [serializedLog]); } else { bufferMap.set(client, [...logBuffer, serializedLog]); @@ -78,6 +79,12 @@ export function _INTERNAL_captureSerializedLog(client: Client, serializedLog: Se } } +/** + * @deprecated Use `bufferSerializedLog` instead. + */ +// TODO(v12): Remove once the Electron SDK no longer uses it. +export const _INTERNAL_captureSerializedLog = bufferSerializedLog; + /** * Captures a log event and sends it to Sentry. * @@ -89,10 +96,10 @@ export function _INTERNAL_captureSerializedLog(client: Client, serializedLog: Se * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_captureLog( +export function captureLogEvent( beforeLog: Log, currentScope = getCurrentScope(), - captureSerializedLog: (client: Client, log: SerializedLog) => void = _INTERNAL_captureSerializedLog, + captureSerializedLog: (client: Client, log: SerializedLog) => void = bufferSerializedLog, ): void { const client = currentScope?.getClient() ?? getClient(); if (!client) { @@ -200,6 +207,12 @@ export function _INTERNAL_captureLog( client.emit('afterCaptureLog', log); } +/** + * @deprecated Use `captureLogEvent` instead. + */ +// TODO(v12): Remove once the Electron SDK no longer uses it. +export const _INTERNAL_captureLog = captureLogEvent; + /** * Flushes the logs buffer to Sentry. * @@ -209,8 +222,8 @@ export function _INTERNAL_captureLog( * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_flushLogsBuffer(client: Client, maybeLogBuffer?: Array): void { - const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? []; +export function flushLogsBuffer(client: Client, maybeLogBuffer?: Array): void { + const logBuffer = maybeLogBuffer ?? getLogBuffer(client) ?? []; if (logBuffer.length === 0) { return; } @@ -234,6 +247,12 @@ export function _INTERNAL_flushLogsBuffer(client: Client, maybeLogBuffer?: Array client.sendEnvelope(envelope); } +/** + * @deprecated Use `flushLogsBuffer` instead. + */ +// TODO(v12): Remove once the React Native SDK no longer uses it. +export const _INTERNAL_flushLogsBuffer = flushLogsBuffer; + /** * Returns the log buffer for a given client. * @@ -242,7 +261,7 @@ export function _INTERNAL_flushLogsBuffer(client: Client, maybeLogBuffer?: Array * @param client - The client to get the log buffer for. * @returns The log buffer for the given client. */ -export function _INTERNAL_getLogBuffer(client: Client): Array | undefined { +export function getLogBuffer(client: Client): Array | undefined { return _getBufferMap().get(client); } diff --git a/packages/core/src/logs/public-api.ts b/packages/core/src/logs/public-api.ts index c37ce60fc88e..c11395b94e3d 100644 --- a/packages/core/src/logs/public-api.ts +++ b/packages/core/src/logs/public-api.ts @@ -1,7 +1,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 { captureLogEvent } from './internal'; import { fmt } from '../utils/parameterize'; /** @@ -20,7 +20,7 @@ function captureLog( scope?: Scope, severityNumber?: Log['severityNumber'], ): void { - _INTERNAL_captureLog({ level, message, attributes, severityNumber }, scope); + captureLogEvent({ level, message, attributes, severityNumber }, scope); } /** diff --git a/packages/core/src/metrics/internal.ts b/packages/core/src/metrics/internal.ts index 6e4dd5881009..3925ba87f899 100644 --- a/packages/core/src/metrics/internal.ts +++ b/packages/core/src/metrics/internal.ts @@ -49,7 +49,8 @@ function setMetricAttribute( } /** - * Captures a serialized metric event and adds it to the metric buffer for the given client. + * Adds an already serialized metric to the metric buffer for the given client. + * It skips enrichment and `beforeSendMetric`, so the metric must be fully processed. * * @param client - A client. Uses the current client if not provided. * @param serializedMetric - The serialized metric event to capture. @@ -57,9 +58,9 @@ function setMetricAttribute( * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void { +export function bufferSerializedMetric(client: Client, serializedMetric: SerializedMetric): void { const bufferMap = _getBufferMap(); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); if (metricBuffer === undefined) { // Set up flushing on the first metric, so apps that never capture metrics don't bundle the flush code. @@ -68,12 +69,12 @@ export function _INTERNAL_captureSerializedMetric(client: Client, serializedMetr 'afterCaptureMetric', 'flushMetrics', estimateMetricSizeInBytes, - _INTERNAL_flushMetricsBuffer, + flushMetricsBuffer, ); bufferMap.set(client, [serializedMetric]); } else { if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) { - _INTERNAL_flushMetricsBuffer(client, metricBuffer); + flushMetricsBuffer(client, metricBuffer); bufferMap.set(client, [serializedMetric]); } else { bufferMap.set(client, [...metricBuffer, serializedMetric]); @@ -81,6 +82,12 @@ export function _INTERNAL_captureSerializedMetric(client: Client, serializedMetr } } +/** + * @deprecated Use `bufferSerializedMetric` instead. + */ +// TODO(v12): Remove once the Electron SDK no longer uses it. +export const _INTERNAL_captureSerializedMetric = bufferSerializedMetric; + /** * Options for capturing a metric internally. */ @@ -184,9 +191,9 @@ function _buildSerializedMetric( * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void { +export function captureMetricEvent(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void { const currentScope = options?.scope ?? getCurrentScope(); - const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric; + const captureSerializedMetric = options?.captureSerializedMetric ?? bufferSerializedMetric; const client = currentScope?.getClient() ?? getClient(); if (!client) { DEBUG_BUILD && debug.warn('No client available to capture metric.'); @@ -229,6 +236,12 @@ export function _INTERNAL_captureMetric(beforeMetric: Metric, options?: Internal client.emit('afterCaptureMetric', processedMetric); } +/** + * @deprecated Use `captureMetricEvent` instead. + */ +// TODO(v12): Remove once the Electron SDK no longer uses it. +export const _INTERNAL_captureMetric = captureMetricEvent; + /** * Flushes the metrics buffer to Sentry. * @@ -238,8 +251,8 @@ export function _INTERNAL_captureMetric(beforeMetric: Metric, options?: Internal * @experimental This method will experience breaking changes. This is not yet part of * the stable Sentry SDK API and can be changed or removed without warning. */ -export function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array): void { - const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? []; +export function flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array): void { + const metricBuffer = maybeMetricBuffer ?? getMetricBuffer(client) ?? []; if (metricBuffer.length === 0) { return; } @@ -263,6 +276,12 @@ export function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: client.sendEnvelope(envelope); } +/** + * @deprecated Use `flushMetricsBuffer` instead. + */ +// TODO(v12): Remove. +export const _INTERNAL_flushMetricsBuffer = flushMetricsBuffer; + /** * Returns the metric buffer for a given client. * @@ -271,7 +290,7 @@ export function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: * @param client - The client to get the metric buffer for. * @returns The metric buffer for the given client. */ -export function _INTERNAL_getMetricBuffer(client: Client): Array | undefined { +export function getMetricBuffer(client: Client): Array | undefined { return _getBufferMap().get(client); } diff --git a/packages/core/src/metrics/public-api.ts b/packages/core/src/metrics/public-api.ts index ca0b4fab83a0..547098dd0b43 100644 --- a/packages/core/src/metrics/public-api.ts +++ b/packages/core/src/metrics/public-api.ts @@ -1,7 +1,7 @@ import type { Scope } from '../scope'; import type { MetricUnit } from '../types/measurement'; import type { Metric, MetricType } from '../types/metric'; -import { _INTERNAL_captureMetric } from './internal'; +import { captureMetricEvent } from './internal'; /** * Options for capturing a metric. @@ -32,7 +32,7 @@ export interface MetricOptions { * @param options - Options for capturing the metric. */ function captureMetric(type: MetricType, name: string, value: number, options?: MetricOptions): void { - _INTERNAL_captureMetric( + captureMetricEvent( { type, name, value, unit: options?.unit, attributes: options?.attributes }, { scope: options?.scope }, ); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index e3636550b77c..046106d68909 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -7,28 +7,16 @@ export type { ServerRuntimeClientOptions } from './server-runtime-client'; export { ServerRuntimeClient } from './server-runtime-client'; export type { TunnelRequestLike } from './utils/tunnel'; +export { getServedTunnel, handleServedTunnelRequest, isServedTunnelRequest, isTunnelRequest } from './utils/tunnel'; +export { httpServerHandlesTunnel, setNodeTunnelHandler } from './utils/tunnelStore'; export { - getServedTunnel as _INTERNAL_getServedTunnel, - getTunnelPaths as _INTERNAL_getTunnelPaths, - handleServedTunnelRequest as _INTERNAL_handleServedTunnelRequest, - isServedTunnelRequest as _INTERNAL_isServedTunnelRequest, - isTunnelRequest, -} from './utils/tunnel'; -export { - httpServerHandlesTunnel as _INTERNAL_httpServerHandlesTunnel, - setNodeTunnelHandler as _INTERNAL_setNodeTunnelHandler, -} from './utils/tunnelStore'; -export { - forwardTunnelRequest as _INTERNAL_forwardTunnelRequest, - handleServedNodeTunnelRequest as _INTERNAL_handleServedNodeTunnelRequest, - pickForwardedHeaders as _INTERNAL_pickForwardedHeaders, + forwardTunnelRequest, + handleServedNodeTunnelRequest, + pickForwardedHeaders, handleTunnelRequestIfMatched, } from './utils/tunnelForward'; export { serveTunnelIntegration } from './integrations/serveTunnel'; -export { - _INTERNAL_resetTunnelDefaults, - setTunnelDefaults as _INTERNAL_setTunnelDefaults, -} from './utils/tunnelDefaults'; +export { resetTunnelDefaults, setTunnelDefaults } from './utils/tunnelDefaults'; export type { ServerRuntimeOptions } from './types/options'; export { trpcMiddleware } from './trpc'; export { wrapMcpServerWithSentry } from './integrations/mcp-server'; diff --git a/packages/core/src/tracing/idleSpan.ts b/packages/core/src/tracing/idleSpan.ts index f9d163a1de02..334e191e69a7 100644 --- a/packages/core/src/tracing/idleSpan.ts +++ b/packages/core/src/tracing/idleSpan.ts @@ -313,7 +313,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti span.setStatus({ code: SPAN_STATUS_OK }); } - debug.log(`[Tracing] Idle span "${spanJSON.op}" finished`); + DEBUG_BUILD && debug.log(`[Tracing] Idle span "${spanJSON.op}" finished`); const childSpans = getSpanDescendants(span).filter(child => child !== span); diff --git a/packages/core/src/tracing/spans/spanBuffer.ts b/packages/core/src/tracing/spans/spanBuffer.ts index b726032a3707..0552b679e9f4 100644 --- a/packages/core/src/tracing/spans/spanBuffer.ts +++ b/packages/core/src/tracing/spans/spanBuffer.ts @@ -213,6 +213,9 @@ export class SpanBuffer { * Spans are captured when they end, but the segment span can still be renamed afterwards * (e.g. once the route is known). Only replace the value we set at capture time, so that * values set by users or `beforeSendSpan` are kept. + * + * Renames that Next.js applies only when it serializes the segment span (`processSegmentSpan`) come after + * this and are not refreshed. */ function refreshSegmentName( spanJSON: SerializedStreamedSpan, diff --git a/packages/core/src/utils/cookie.ts b/packages/core/src/utils/cookie.ts index 787cf4b862e5..f5dfe3ef733e 100644 --- a/packages/core/src/utils/cookie.ts +++ b/packages/core/src/utils/cookie.ts @@ -47,7 +47,7 @@ export function parseCookieHeader(value: string | string[], headerName: 'cookie' return []; } return headerName === 'set-cookie' - ? splitJoinedSetCookieHeader(headerValue).map(cookie => cookie.split(';')[0]!) + ? splitJoinedSetCookieHeader(headerValue).flatMap(cookie => cookie.split(';', 1)) : headerValue.split(';'); }); diff --git a/packages/core/src/utils/data-collection/filterKeyValueData.ts b/packages/core/src/utils/data-collection/filterKeyValueData.ts index ff8012327ab5..6f29fef766ef 100644 --- a/packages/core/src/utils/data-collection/filterKeyValueData.ts +++ b/packages/core/src/utils/data-collection/filterKeyValueData.ts @@ -45,8 +45,8 @@ export function filterKeyValueData( } const result: Record = {}; - for (const key of Object.keys(data)) { - result[key] = shouldFilterDataKey(key, behavior, additionalDenyTerms) ? FILTERED : data[key]!; + for (const [key, value] of Object.entries(data)) { + result[key] = shouldFilterDataKey(key, behavior, additionalDenyTerms) ? FILTERED : value; } return result; } diff --git a/packages/core/src/utils/flushIfServerless.ts b/packages/core/src/utils/flushIfServerless.ts index d5a63749eb34..cb537ec7dc4d 100644 --- a/packages/core/src/utils/flushIfServerless.ts +++ b/packages/core/src/utils/flushIfServerless.ts @@ -1,3 +1,4 @@ +// oxlint-disable sdk/no-unguarded-debug-logs -- server-only, never part of a browser bundle import { getIsolationScope } from '../currentScopes'; import { getDefaultIsolationScope } from '../defaultScopes'; import { flush } from '../exports'; diff --git a/packages/core/src/utils/should-ignore-span.ts b/packages/core/src/utils/should-ignore-span.ts index 7b791b4b9801..f2bb0a1655a2 100644 --- a/packages/core/src/utils/should-ignore-span.ts +++ b/packages/core/src/utils/should-ignore-span.ts @@ -5,6 +5,7 @@ import { debug } from './debug-logger'; import { isMatchingPattern } from './string'; function logIgnoredSpan(droppedSpan: Pick): void { + // oxlint-disable-next-line sdk/no-unguarded-debug-logs -- every caller already gates this with `DEBUG_BUILD &&` debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \`ignoreSpans\`.`); } diff --git a/packages/core/src/utils/traceData.ts b/packages/core/src/utils/traceData.ts index 62c98a8fc7f8..d7c3a6aedad6 100644 --- a/packages/core/src/utils/traceData.ts +++ b/packages/core/src/utils/traceData.ts @@ -9,6 +9,7 @@ import { spanIsNonRecordingSpan } from '../tracing/sentryNonRecordingSpan'; import type { Span } from '../types/span'; import type { SerializedTraceData } from '../types/tracing'; import { dynamicSamplingContextToSentryBaggageHeader } from './baggage'; +import { DEBUG_BUILD } from '../debug-build'; import { debug } from './debug-logger'; import { hasSpansEnabled } from './hasSpansEnabled'; import { getActiveSpan, spanToTraceHeader, spanToTraceparentHeader } from './spanUtils'; @@ -68,7 +69,7 @@ export function getTraceData( const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace); if (!isValidSentryTraceHeader) { - debug.warn('Invalid sentry-trace data. Cannot generate trace data'); + DEBUG_BUILD && debug.warn('Invalid sentry-trace data. Cannot generate trace data'); return {}; } diff --git a/packages/core/src/utils/tracing.ts b/packages/core/src/utils/tracing.ts index e7eb7c5443f1..cea3e19773b4 100644 --- a/packages/core/src/utils/tracing.ts +++ b/packages/core/src/utils/tracing.ts @@ -2,6 +2,7 @@ import type { Client } from '../client'; import type { DynamicSamplingContext } from '../types/envelope'; import type { PropagationContext } from '../types/tracing'; import type { TraceparentData } from '../types/transaction'; +import { DEBUG_BUILD } from '../debug-build'; import { debug } from '../utils/debug-logger'; import { baggageHeaderToDynamicSamplingContext } from './baggage'; import { extractOrgIdFromClient } from './dsn'; @@ -181,9 +182,10 @@ export function shouldContinueTrace(client: Client, baggageOrgId?: string): bool // Case: baggage orgID and Client orgID don't match - always start new trace if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) { - debug.log( - `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`, - ); + DEBUG_BUILD && + debug.log( + `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`, + ); return false; } @@ -194,9 +196,10 @@ export function shouldContinueTrace(client: Client, baggageOrgId?: string): bool // - Baggage has orgID, but Client doesn't have one // - Client has orgID, but baggage doesn't have one if ((baggageOrgId && !clientOrgId) || (!baggageOrgId && clientOrgId)) { - debug.log( - `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`, - ); + DEBUG_BUILD && + debug.log( + `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`, + ); return false; } } diff --git a/packages/core/src/utils/tunnelDefaults.ts b/packages/core/src/utils/tunnelDefaults.ts index 7583749cd8a2..21b4aa45433c 100644 --- a/packages/core/src/utils/tunnelDefaults.ts +++ b/packages/core/src/utils/tunnelDefaults.ts @@ -85,6 +85,6 @@ export function applyServerTunnelDefaults(client: Client | undefined): void { * * @internal */ -export function _INTERNAL_resetTunnelDefaults(): void { +export function resetTunnelDefaults(): void { setStoredTunnelDefaults(undefined); } diff --git a/packages/core/src/utils/tunnelForward.ts b/packages/core/src/utils/tunnelForward.ts index bb5ca0102c72..77a896d26a7d 100644 --- a/packages/core/src/utils/tunnelForward.ts +++ b/packages/core/src/utils/tunnelForward.ts @@ -1,4 +1,5 @@ /* oxlint-disable max-lines */ +// oxlint-disable sdk/no-unguarded-debug-logs -- server-only, never part of a browser bundle import { getEnvelopeEndpointWithUrlEncodedAuth } from '../api'; import { getClient } from '../currentScopes'; import { suppressTracing } from '../tracing/trace'; diff --git a/packages/core/test/lib/build-time-plugins/warnOnConflictingSourceMapOptions.test.ts b/packages/core/test/lib/build-time-plugins/warnOnConflictingSourceMapOptions.test.ts new file mode 100644 index 000000000000..ab51787fd492 --- /dev/null +++ b/packages/core/test/lib/build-time-plugins/warnOnConflictingSourceMapOptions.test.ts @@ -0,0 +1,81 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { warnOnConflictingSourceMapOptions as WarnOnConflictingSourceMapOptions } from '../../../src/build-time-plugins/warnOnConflictingSourceMapOptions'; + +describe('warnOnConflictingSourceMapOptions', () => { + let warnOnConflictingSourceMapOptions: typeof WarnOnConflictingSourceMapOptions; + + // The module remembers the warnings it logged. + beforeEach(async () => { + vi.resetModules(); + ({ warnOnConflictingSourceMapOptions } = + await import('../../../src/build-time-plugins/warnOnConflictingSourceMapOptions')); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it.each([ + [{ upload: false, disable: true }, /`sourcemaps\.disable` is ignored/], + [{ injectDebugIds: false, disable: 'disable-upload' }, /`sourcemaps\.disable` is ignored/], + [{ upload: true, injectDebugIds: false }, /`sourcemaps\.injectDebugIds` is `false`/], + [{ delete: true, deleteSourcemapsAfterUpload: false }, /`sourcemaps\.deleteSourcemapsAfterUpload` is ignored/], + [{ delete: false, filesToDeleteAfterUpload: ['dist/**/*.map'] }, /`sourcemaps\.filesToDeleteAfterUpload` still/], + ] as const)('warns once about %j', (sourcemaps, message) => { + const logWarning = vi.fn(); + + warnOnConflictingSourceMapOptions(sourcemaps, logWarning); + + expect(logWarning).toHaveBeenCalledTimes(1); + expect(logWarning).toHaveBeenCalledWith(expect.stringMatching(message)); + }); + + it.each([ + undefined, + {}, + { upload: false }, + { injectDebugIds: false }, + { upload: false, injectDebugIds: false }, + { delete: false }, + { disable: true, deleteSourcemapsAfterUpload: true }, + { disable: true, delete: true }, + { delete: true, filesToDeleteAfterUpload: ['extra/**'] }, + { filesToDeleteAfterUpload: ['dist/**/*.map'] }, + ] as const)('does not warn about %j', sourcemaps => { + const logWarning = vi.fn(); + + warnOnConflictingSourceMapOptions(sourcemaps, logWarning); + + expect(logWarning).not.toHaveBeenCalled(); + }); + + it('warns about each conflict', () => { + const logWarning = vi.fn(); + + warnOnConflictingSourceMapOptions( + { disable: true, upload: true, injectDebugIds: false, delete: false, filesToDeleteAfterUpload: 'x' }, + logWarning, + ); + + expect(logWarning).toHaveBeenCalledTimes(3); + }); + + it('logs each warning once, also for later calls', () => { + const logWarning = vi.fn(); + + warnOnConflictingSourceMapOptions({ upload: true, injectDebugIds: false }, logWarning); + warnOnConflictingSourceMapOptions({ upload: true, injectDebugIds: false, disable: true }, logWarning); + + expect(logWarning).toHaveBeenCalledTimes(2); + expect(logWarning).toHaveBeenNthCalledWith(1, expect.stringMatching(/`sourcemaps\.injectDebugIds` is `false`/)); + expect(logWarning).toHaveBeenNthCalledWith(2, expect.stringMatching(/`sourcemaps\.disable` is ignored/)); + }); + + it('logs with a `[Sentry]` prefix by default', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + warnOnConflictingSourceMapOptions({ upload: true, injectDebugIds: false }); + + expect(warnSpy).toHaveBeenCalledWith(expect.stringMatching(/^\[Sentry\] `sourcemaps\.upload` is set/)); + }); +}); diff --git a/packages/core/test/lib/client.test.ts b/packages/core/test/lib/client.test.ts index 8d05b74cf9d8..488cf66ec90f 100644 --- a/packages/core/test/lib/client.test.ts +++ b/packages/core/test/lib/client.test.ts @@ -18,8 +18,8 @@ import { } from '../../src'; import * as integrationModule from '../../src/integration'; import * as logsInternalModule from '../../src/logs/internal'; -import { _INTERNAL_captureLog } from '../../src/logs/internal'; -import { _INTERNAL_captureMetric } from '../../src/metrics/internal'; +import { captureLogEvent } from '../../src/logs/internal'; +import { captureMetricEvent } from '../../src/metrics/internal'; import * as traceModule from '../../src/tracing/trace'; import { DEFAULT_TRANSPORT_BUFFER_SIZE } from '../../src/transports/base'; import type { Envelope } from '../../src/types/envelope'; @@ -3152,12 +3152,12 @@ describe('Client', () => { const flushLogsHandler = vi.fn(); client.on('flushLogs', flushLogsHandler); - _INTERNAL_captureLog({ message: 'test log', level: 'info' }, scope); + captureLogEvent({ message: 'test log', level: 'info' }, scope); await client.close(); expect(flushLogsHandler).toHaveBeenCalledTimes(1); - expect(logsInternalModule._INTERNAL_getLogBuffer(client)).toEqual([]); + expect(logsInternalModule.getLogBuffer(client)).toEqual([]); }); test('multiple concurrent flush calls should just work', async () => { @@ -4224,11 +4224,11 @@ describe('Client', () => { expect(onSpy).not.toHaveBeenCalledWith('afterCaptureLog', expect.any(Function)); - _INTERNAL_captureLog({ message: 'test log 1', level: 'info' }, scope); + captureLogEvent({ message: 'test log 1', level: 'info' }, scope); expect(onSpy).toHaveBeenCalledWith('afterCaptureLog', expect.any(Function)); onSpy.mockClear(); - _INTERNAL_captureLog({ message: 'test log 2', level: 'info' }, scope); + captureLogEvent({ message: 'test log 2', level: 'info' }, scope); expect(onSpy).not.toHaveBeenCalledWith('afterCaptureLog', expect.any(Function)); onSpy.mockRestore(); @@ -4246,7 +4246,7 @@ describe('Client', () => { // Create a large log message that will exceed the 800KB threshold const largeMessage = 'x'.repeat(400_000); // 400KB string - _INTERNAL_captureLog({ message: largeMessage, level: 'info' }, scope); + captureLogEvent({ message: largeMessage, level: 'info' }, scope); expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); }); @@ -4263,7 +4263,7 @@ describe('Client', () => { // Create a log message that won't exceed the threshold const message = 'x'.repeat(100_000); // 100KB string - _INTERNAL_captureLog({ message, level: 'info' }, scope); + captureLogEvent({ message, level: 'info' }, scope); expect(sendEnvelopeSpy).not.toHaveBeenCalled(); }); @@ -4279,7 +4279,7 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // Add a log which will trigger afterCaptureLog event - _INTERNAL_captureLog({ message: 'test log', level: 'info' }, scope); + captureLogEvent({ message: 'test log', level: 'info' }, scope); expect(sendEnvelopeSpy).not.toHaveBeenCalled(); @@ -4300,13 +4300,13 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // Add initial log (starts the timer) - _INTERNAL_captureLog({ message: 'test log 1', level: 'info' }, scope); + captureLogEvent({ message: 'test log 1', level: 'info' }, scope); // Fast forward part of the idle timeout vi.advanceTimersByTime(2500); // Add another log which should NOT reset the timeout - _INTERNAL_captureLog({ message: 'test log 2', level: 'info' }, scope); + captureLogEvent({ message: 'test log 2', level: 'info' }, scope); // Fast forward the remaining time to reach the full timeout from the first log vi.advanceTimersByTime(2500); @@ -4326,7 +4326,7 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // First batch: Add a log and let it flush - _INTERNAL_captureLog({ message: 'test log 1', level: 'info' }, scope); + captureLogEvent({ message: 'test log 1', level: 'info' }, scope); // Fast forward to trigger the first flush vi.advanceTimersByTime(5000); @@ -4334,7 +4334,7 @@ describe('Client', () => { expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); // Second batch: Add another log after the first flush completed - _INTERNAL_captureLog({ message: 'test log 2', level: 'info' }, scope); + captureLogEvent({ message: 'test log 2', level: 'info' }, scope); // Should not have flushed yet expect(sendEnvelopeSpy).toHaveBeenCalledTimes(1); @@ -4357,8 +4357,8 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // Add some logs - _INTERNAL_captureLog({ message: 'test1', level: 'info' }, scope); - _INTERNAL_captureLog({ message: 'test2', level: 'info' }, scope); + captureLogEvent({ message: 'test1', level: 'info' }, scope); + captureLogEvent({ message: 'test2', level: 'info' }, scope); // Trigger flush event client.emit('flush'); @@ -4377,7 +4377,7 @@ describe('Client', () => { scope.setClient(client); // Capture a log which will start the flush timer - _INTERNAL_captureLog({ message: 'test log', level: 'info' }, scope); + captureLogEvent({ message: 'test log', level: 'info' }, scope); // Verify safeUnref was called on the timer expect(safeUnrefSpy).toHaveBeenCalledTimes(1); @@ -4397,7 +4397,7 @@ describe('Client', () => { client.on('flushLogs', flushLogsHandler); // Capture a log which starts the weight-based flush timer - _INTERNAL_captureLog({ message: 'test log', level: 'info' }, scope); + captureLogEvent({ message: 'test log', level: 'info' }, scope); expect(flushLogsHandler).not.toHaveBeenCalled(); @@ -4425,11 +4425,11 @@ describe('Client', () => { expect(onSpy).not.toHaveBeenCalledWith('afterCaptureMetric', expect.any(Function)); - _INTERNAL_captureMetric({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); expect(onSpy).toHaveBeenCalledWith('afterCaptureMetric', expect.any(Function)); onSpy.mockClear(); - _INTERNAL_captureMetric({ name: 'metric2', value: 2, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'metric2', value: 2, type: 'counter', attributes: {} }, { scope }); expect(onSpy).not.toHaveBeenCalledWith('afterCaptureMetric', expect.any(Function)); onSpy.mockRestore(); @@ -4447,7 +4447,7 @@ describe('Client', () => { // Create large metrics that will exceed the 800KB threshold const largeValue = 'x'.repeat(400_000); // 400KB string - _INTERNAL_captureMetric( + captureMetricEvent( { name: 'large_metric', value: 1, type: 'counter', attributes: { large_value: largeValue } }, { scope }, ); @@ -4466,7 +4466,7 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // Create metrics that won't exceed the threshold - _INTERNAL_captureMetric({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); expect(sendEnvelopeSpy).not.toHaveBeenCalled(); }); @@ -4482,8 +4482,8 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); // Add some metrics - _INTERNAL_captureMetric({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); - _INTERNAL_captureMetric({ name: 'metric2', value: 2, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'metric2', value: 2, type: 'counter', attributes: {} }, { scope }); // Trigger flush event client.emit('flush'); @@ -4502,7 +4502,7 @@ describe('Client', () => { scope.setClient(client); // Capture a metric which will start the flush timer - _INTERNAL_captureMetric({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); // Verify safeUnref was called on the timer expect(safeUnrefSpy).toHaveBeenCalledTimes(1); @@ -4522,7 +4522,7 @@ describe('Client', () => { client.on('flushMetrics', flushMetricsHandler); // Capture a metric which starts the weight-based flush timer - _INTERNAL_captureMetric({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); expect(flushMetricsHandler).not.toHaveBeenCalled(); @@ -4543,7 +4543,7 @@ describe('Client', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'test_metric', value: 42, type: 'counter', attributes: {} }, { scope }); expect(safeUnrefSpy).not.toHaveBeenCalled(); @@ -4561,7 +4561,7 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); - _INTERNAL_captureMetric({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); + captureMetricEvent({ name: 'metric1', value: 1, type: 'counter', attributes: {} }, { scope }); expect(sendEnvelopeSpy).not.toHaveBeenCalled(); @@ -4582,7 +4582,7 @@ describe('Client', () => { const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); const largeValue = 'x'.repeat(400_000); - _INTERNAL_captureMetric( + captureMetricEvent( { name: 'large_metric', value: 1, type: 'counter', attributes: { large_value: largeValue } }, { scope }, ); diff --git a/packages/core/test/lib/integrations/consola.test.ts b/packages/core/test/lib/integrations/consola.test.ts index 6cdaedc64cba..386df56ec84f 100644 --- a/packages/core/test/lib/integrations/consola.test.ts +++ b/packages/core/test/lib/integrations/consola.test.ts @@ -1,14 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getClient, getCurrentScope } from '../../../src/currentScopes'; import { createConsolaReporter } from '../../../src/integrations/consola'; -import { _INTERNAL_captureLog } from '../../../src/logs/internal'; +import { captureLogEvent } from '../../../src/logs/internal'; import { formatConsoleArgs } from '../../../src/logs/utils'; import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; // Mock dependencies vi.mock('../../../src/logs/internal', () => ({ - _INTERNAL_captureLog: vi.fn(), - _INTERNAL_flushLogsBuffer: vi.fn(), + captureLogEvent: vi.fn(), + flushLogsBuffer: vi.fn(), })); vi.mock('../../../src/logs/utils', async importOriginal => { @@ -72,7 +72,7 @@ describe('createConsolaReporter', () => { userId: 123, smallObj: { word: 'hi' }, }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe( 'Calling: consola.log({ message: "", time: new Date(), userId: 123, smallObj: { word: "hi" } })', ); @@ -95,7 +95,7 @@ describe('createConsolaReporter', () => { }, ], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe( '{"noMessage":"Calling: consola.log({ noMessage: \\"\\", time: new Date() })","time":"2026-02-24T10:24:04.477Z"}', ); @@ -118,7 +118,7 @@ describe('createConsolaReporter', () => { }, ], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe( '{"message":"Calling: consola.raw({ message: \\"\\", userId: 123, smallObj: { word: \\"hi\\" } })","userId":123,"smallObj":{"word":"hi"}}', ); @@ -137,7 +137,7 @@ describe('createConsolaReporter', () => { }); expect(formatConsoleArgs).toHaveBeenCalledWith(['Hello', 'world', 123, { key: 'value' }], 3, 1000); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith({ + expect(captureLogEvent).toHaveBeenCalledWith({ level: 'info', message: 'Hello world 123 {"key":"value"}', attributes: { @@ -158,7 +158,7 @@ describe('createConsolaReporter', () => { args: [], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('From consola message key'); }); @@ -169,7 +169,7 @@ describe('createConsolaReporter', () => { }); expect(formatConsoleArgs).toHaveBeenCalledWith([], 3, 1000); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe(''); }); @@ -181,7 +181,7 @@ describe('createConsolaReporter', () => { args: [{ 'sentry.origin': 'object-args', 'consola.tag': 'object-args-tag' }, 'Test'], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.attributes?.['sentry.origin']).toBe('object-args'); expect(call.attributes?.['consola.tag']).toBe('object-args-tag'); }); @@ -198,7 +198,7 @@ describe('createConsolaReporter', () => { ], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.attributes?.['sentry.message.parameter.0']).toEqual({ level1: { level2: { level3: '[Object]' } }, simpleKey: 'simple value', @@ -219,7 +219,7 @@ describe('createConsolaReporter', () => { ], }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe( '{"level1":{"level2":{"level3":"[Object]"}},"simpleKey":"simple value"} Deep object 12345 {"another":"object","level1":{"level2":{"level3":"[Object]"}}}', ); @@ -237,14 +237,14 @@ describe('createConsolaReporter', () => { it('stores Date and Error in message params (fallback)', () => { const date = new Date('2023-01-01T00:00:00.000Z'); sentryReporter.log({ type: 'info', args: ['Time:', date] }); - expect(vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]!.attributes?.['sentry.message.parameter.0']).toBe( + expect(vi.mocked(captureLogEvent).mock.calls[0]![0]!.attributes?.['sentry.message.parameter.0']).toBe( '2023-01-01T00:00:00.000Z', ); vi.clearAllMocks(); const err = new Error('Test error'); sentryReporter.log({ type: 'error', args: ['Error occurred:', err] }); - const errCall = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const errCall = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(errCall.attributes?.['sentry.message.parameter.0']).toMatchObject({ message: 'Test error', name: 'Error', @@ -253,7 +253,7 @@ describe('createConsolaReporter', () => { it('handles console substitution patterns in first arg', () => { sentryReporter.log({ type: 'info', args: ['Value: %d, another: %s', 42, 'hello'] }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; // We don't substitute as it gets too complicated on the client-side: https://github.com/getsentry/sentry-javascript/pull/17703 expect(call.message).toBe('Value: %d, another: %s 42 hello'); @@ -270,7 +270,7 @@ describe('createConsolaReporter', () => { // @ts-expect-error Testing legacy fallback sentryReporter.log({ type: level ?? 'info', args }); expect(formatConsoleArgs).toHaveBeenCalled(); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; if (template !== undefined) expect(call.attributes?.['sentry.message.template']).toBe(template); if (template === 'Normal log {} {}') expect(call.attributes?.data).toBeUndefined(); if (level) expect(call.level).toBe(level); @@ -278,7 +278,7 @@ describe('createConsolaReporter', () => { it('object-first: empty object as first arg', () => { sentryReporter.log({ type: 'info', args: [{}, 'Empty object log'] }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{} Empty object log'); expect(call.attributes?.['sentry.origin']).toBe('auto.log.consola'); }); @@ -292,7 +292,7 @@ describe('createConsolaReporter', () => { args: ['Message', circular], }); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith({ + expect(captureLogEvent).toHaveBeenCalledWith({ level: 'info', message: 'Message {"self":"[Circular ~]"}', attributes: { @@ -311,7 +311,7 @@ describe('createConsolaReporter', () => { }); expect(formatConsoleArgs).toHaveBeenCalledWith(['Hello', 'world', 123, { key: 'value' }], 3, 1000); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.level).toBe('info'); expect(call.message).toContain('Hello'); expect(call.attributes?.['sentry.message.template']).toBe('Hello {} {} {}'); @@ -328,7 +328,7 @@ describe('createConsolaReporter', () => { sessionId: 'abc-123', }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('User action'); expect(call.attributes).toMatchObject({ 'consola.type': 'info', @@ -349,7 +349,7 @@ describe('createConsolaReporter', () => { ] as const)('maps type "%s" to Sentry level "%s"', (type, expectedLevel) => { sentryReporter.log({ type, args: [`${type} message`] }); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: expectedLevel, message: `${type} message`, @@ -369,7 +369,7 @@ describe('createConsolaReporter', () => { ] as const)('maps consola type "%s" to Sentry level "%s"', (type, expectedLevel) => { sentryReporter.log({ type, args: [`Test ${type}`] }); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: expectedLevel, message: `Test ${type}`, @@ -387,7 +387,7 @@ describe('createConsolaReporter', () => { args: ['Fatal message'], }); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: 'fatal', message: 'Fatal message', @@ -411,21 +411,21 @@ describe('createConsolaReporter', () => { type: 'error', args: ['Error message'], }); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(1); + expect(captureLogEvent).toHaveBeenCalledTimes(1); // Should capture warn filteredReporter.log({ type: 'warn', args: ['Warn message'], }); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(2); + expect(captureLogEvent).toHaveBeenCalledTimes(2); // Should not capture info filteredReporter.log({ type: 'info', args: ['Info message'], }); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(2); + expect(captureLogEvent).toHaveBeenCalledTimes(2); }); it('should use default levels when none specified', () => { @@ -439,7 +439,7 @@ describe('createConsolaReporter', () => { }); }); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(6); + expect(captureLogEvent).toHaveBeenCalledTimes(6); }); }); }); diff --git a/packages/core/test/lib/integrations/reportSdkConfig.test.ts b/packages/core/test/lib/integrations/reportSdkConfig.test.ts index 028e0d0a92b9..5e0114362da4 100644 --- a/packages/core/test/lib/integrations/reportSdkConfig.test.ts +++ b/packages/core/test/lib/integrations/reportSdkConfig.test.ts @@ -5,6 +5,7 @@ import type { Integration } from '../../../src/types/integration'; import { experimentalReportSdkConfigIntegration } from '../../../src/integrations/reportSdkConfig'; import type * as metricsApi from '../../../src/metrics/public-api'; import { count } from '../../../src/metrics/public-api'; +import { isBrowser } from '../../../src/utils/isBrowser'; import { captureOptionsSetByUser } from '../../../src/utils/sdkMetadata'; import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; @@ -13,12 +14,18 @@ vi.mock('../../../src/metrics/public-api', async importOriginal => ({ count: vi.fn(), })); +vi.mock('../../../src/utils/isBrowser', () => ({ isBrowser: vi.fn(() => false) })); + const tagIntegration = defineIntegration((_options: { tag?: string; filter?: RegExp } = {}) => ({ name: 'Tag' })); function reportConfig(options: ReturnType): Record { - let payload: Record = {}; + return JSON.parse(reportAttributes(options)['sentry.sdk_config.payload'] as string); +} + +function reportAttributes(options: ReturnType): Record { + let attributes: Record = {}; vi.mocked(count).mockImplementation((_name, _value, metricOptions) => { - payload = JSON.parse(String(metricOptions?.attributes?.['sentry.sdk_config.payload'])); + attributes = metricOptions?.attributes ?? {}; }); const client = new TestClient(options); @@ -26,7 +33,7 @@ function reportConfig(options: ReturnType): client.init(); vi.advanceTimersByTime(0); - return payload; + return attributes; } describe('experimentalReportSdkConfigIntegration', () => { @@ -65,13 +72,11 @@ describe('experimentalReportSdkConfigIntegration', () => { ); expect(payload).toEqual({ - version: 3, + version: 4, sdk: { name: 'sentry.javascript.node', version: '11.14.0' }, runtime: { name: 'node', version: 'v24.22.1' }, - environment: 'staging', options: { runtime: { name: 'node', version: 'v24.22.1' }, - environment: 'staging', defaultIntegrations: false, integrations: [ { name: 'ExperimentalReportSdkConfig' }, @@ -102,12 +107,125 @@ describe('experimentalReportSdkConfigIntegration', () => { ); expect(payload).toEqual({ - version: 3, - ...resolvedOptions, + version: 4, + runtime: resolvedOptions.runtime, options: { integrations: [{ name: 'ExperimentalReportSdkConfig' }] }, }); }); + it('reports the same payload for every environment, so environments share a hash', () => { + const payloads = ['staging', 'production'].map(environment => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ environment, integrations: [experimentalReportSdkConfigIntegration()] }), + }), + ), + ); + + expect(payloads[1]).toEqual(payloads[0]); + expect(payloads[0]).toEqual({ version: 4, options: { integrations: [{ name: 'ExperimentalReportSdkConfig' }] } }); + }); + + it('reports a browser runtime when the client sets none', () => { + vi.mocked(isBrowser).mockReturnValueOnce(true); + + const payload = reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + integrations: [experimentalReportSdkConfigIntegration()], + }), + ); + + expect(payload.runtime).toEqual({ name: 'browser' }); + }); + + it('reports no runtime outside the browser when the client sets none', () => { + const payload = reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + integrations: [experimentalReportSdkConfigIntegration()], + }), + ); + + expect(payload).not.toHaveProperty('runtime'); + }); + + it('reports a different hash for a different runtime', () => { + const options = { dsn: 'https://username@domain/123', integrations: [experimentalReportSdkConfigIntegration()] }; + // Server clients set the runtime; the test client's options type doesn't declare it. + const nodeRuntime = { runtime: { name: 'node', version: 'v24.22.1' } }; + const otherNodeRuntime = { runtime: { name: 'node', version: 'v26.0.0' } }; + + const node = reportAttributes(getDefaultTestClientOptions({ ...options, ...nodeRuntime })); + const otherNode = reportAttributes(getDefaultTestClientOptions({ ...options, ...otherNodeRuntime })); + vi.mocked(isBrowser).mockReturnValueOnce(true); + const browser = reportAttributes(getDefaultTestClientOptions(options)); + + expect(new Set([node, otherNode, browser].map(attributes => attributes['sentry.sdk_config.hash'])).size).toBe(3); + }); + + it('reports non-finite numbers as markers, so they differ from null', () => { + const userOptions = captureOptionsSetByUser({ + tracesSampleRate: NaN, + sampleRate: Infinity, + profileSessionSampleRate: -Infinity, + maxBreadcrumbs: null as unknown as number, + integrations: [experimentalReportSdkConfigIntegration()], + }); + + const payload = reportConfig(getDefaultTestClientOptions({ dsn: 'https://username@domain/123', ...userOptions })); + + expect(payload.options).toEqual({ + integrations: [{ name: 'ExperimentalReportSdkConfig' }], + maxBreadcrumbs: null, + profileSessionSampleRate: '[-Infinity]', + sampleRate: '[Infinity]', + tracesSampleRate: '[NaN]', + }); + }); + + it('reports only the shape of initialScope, so per-user values neither leave the app nor split the hash', () => { + const payloads = ['42', '43'].map(id => + reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ + initialScope: { + user: { id, email: `${id}@example.com` }, + tags: { plan: 'pro' }, + level: 'warning' as const, + fingerprint: [id], + }, + integrations: [experimentalReportSdkConfigIntegration()], + }), + }), + ), + ); + + expect(payloads[1]).toEqual(payloads[0]); + expect((payloads[0]?.options as Record).initialScope).toEqual({ + fingerprint: '[value]', + level: '[value]', + tags: { plan: '[value]' }, + user: { email: '[value]', id: '[value]' }, + }); + }); + + it('reports an initialScope callback as a function', () => { + const payload = reportConfig( + getDefaultTestClientOptions({ + dsn: 'https://username@domain/123', + ...captureOptionsSetByUser({ + initialScope: scope => scope, + integrations: [experimentalReportSdkConfigIntegration()], + }), + }), + ); + + expect((payload.options as Record).initialScope).toMatch(/^\[Function:\w+\]$/); + }); + it('reports the names of the default integrations the user passed', () => { const userOptions = captureOptionsSetByUser({ defaultIntegrations: [experimentalReportSdkConfigIntegration()], @@ -172,11 +290,11 @@ describe('experimentalReportSdkConfigIntegration', () => { ); expect(addedPayload).toEqual({ - version: 3, + version: 4, options: { integrations: [{ name: 'Tag', options: { tag: 'user' } }] }, }); expect(removedPayload).toEqual({ - version: 3, + version: 4, removed_default_integrations: ['Dropped'], options: { integrations: [] }, }); @@ -203,7 +321,7 @@ describe('experimentalReportSdkConfigIntegration', () => { ); expect(payload).toEqual({ - version: 3, + version: 4, removed_default_integrations: ['Dropped', 'Zeta'], options: { integrations: [{ name: 'Tag', options: { tag: 'user' } }, { name: 'ExperimentalReportSdkConfig' }], @@ -228,7 +346,7 @@ describe('experimentalReportSdkConfigIntegration', () => { ), ); - expect(payloads[0]).toEqual({ version: 3, options: { integrations: [{ name: 'Tag', options: { tag: 'user' } }] } }); + expect(payloads[0]).toEqual({ version: 4, options: { integrations: [{ name: 'Tag', options: { tag: 'user' } }] } }); expect(payloads[1]).toEqual(payloads[0]); }); @@ -252,7 +370,7 @@ describe('experimentalReportSdkConfigIntegration', () => { ); expect(payload).toEqual({ - version: 3, + version: 4, removed_default_integrations: ['Dropped'], options: { integrations: [{ name: 'Tag', options: { tag: 'only' } }] }, }); @@ -344,6 +462,6 @@ describe('experimentalReportSdkConfigIntegration', () => { }), ); - expect(payload).toEqual({ version: 3, options: {} }); + expect(payload).toEqual({ version: 4, options: {} }); }); }); diff --git a/packages/core/test/lib/logs/console-integration.test.ts b/packages/core/test/lib/logs/console-integration.test.ts index a2a878365064..3041ab94a7a4 100644 --- a/packages/core/test/lib/logs/console-integration.test.ts +++ b/packages/core/test/lib/logs/console-integration.test.ts @@ -1,13 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getClient } from '../../../src/currentScopes'; import { consoleLoggingIntegration } from '../../../src/logs/console-integration'; -import { _INTERNAL_captureLog } from '../../../src/logs/internal'; +import { captureLogEvent } from '../../../src/logs/internal'; import { formatConsoleArgs } from '../../../src/logs/utils'; import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; vi.mock('../../../src/logs/internal', () => ({ - _INTERNAL_captureLog: vi.fn(), - _INTERNAL_flushLogsBuffer: vi.fn(), + captureLogEvent: vi.fn(), + flushLogsBuffer: vi.fn(), })); vi.mock('../../../src/logs/utils', async importOriginal => { @@ -62,7 +62,7 @@ describe('consoleLoggingIntegration', () => { it('extracts object keys as attributes and uses second string arg as message', () => { triggerConsole('log', { userId: 100, action: 'login' }, 'User logged in'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.level).toBe('info'); expect(call.message).toBe('{"userId":100,"action":"login"} User logged in'); @@ -78,7 +78,7 @@ describe('consoleLoggingIntegration', () => { it('extracts object keys as attributes with no second arg', () => { triggerConsole('info', { event: 'click', count: 2 }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"event":"click","count":2}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -92,7 +92,7 @@ describe('consoleLoggingIntegration', () => { it('adds remaining args after second string as sentry.message.parameter.*', () => { triggerConsole('info', { userId: 123 }, 'User action', 'req-abc', 1234567890); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"userId":123} User action req-abc 1234567890'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -108,7 +108,7 @@ describe('consoleLoggingIntegration', () => { it('treats all args after the object as parameters when second arg is not a string', () => { triggerConsole('info', { userId: 123 }, 42, { extra: 'data' }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"userId":123} 42 {"extra":"data"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -123,7 +123,7 @@ describe('consoleLoggingIntegration', () => { it('handles empty object as first arg', () => { triggerConsole('info', {}, 'Empty object log'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{} Empty object log'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -139,7 +139,7 @@ describe('consoleLoggingIntegration', () => { simpleKey: 'simple value', }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"level1":{"level2":{"level3":"[Object]"}},"simpleKey":"simple value"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -155,7 +155,7 @@ describe('consoleLoggingIntegration', () => { level1: { level2: { level3: { level4: 'deep' } } }, }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe( '{"simpleKey":"value"} Deep object 12345 {"another":"object","level1":{"level2":{"level3":"[Object]"}}}', ); @@ -174,7 +174,7 @@ describe('consoleLoggingIntegration', () => { it('does not add sentry.message.template in object-first mode', () => { triggerConsole('info', { key: 'val' }, 'message string', 'extra'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"key":"val"} message string extra'); expect(call.attributes).not.toHaveProperty('sentry.message.template'); }); @@ -182,7 +182,7 @@ describe('consoleLoggingIntegration', () => { it('extracts object with a "message" key as attributes', () => { triggerConsole('info', { message: 'user login', userId: 123, sessionId: 'sess-abc' }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"message":"user login","userId":123,"sessionId":"sess-abc"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -198,7 +198,7 @@ describe('consoleLoggingIntegration', () => { it('formats all args as message and adds template + parameters', () => { triggerConsole('info', 'Hello', 'world', 123, { key: 'value' }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Hello world 123 {"key":"value"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -214,7 +214,7 @@ describe('consoleLoggingIntegration', () => { it('does not extract object keys as attributes when first arg is a string', () => { triggerConsole('info', 'Normal log', { data: 1 }, 123); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Normal log {"data":1} 123'); expect(call.attributes).not.toHaveProperty('data'); }); @@ -222,7 +222,7 @@ describe('consoleLoggingIntegration', () => { it('does not add template when first arg is the only arg', () => { triggerConsole('info', 'Solo message'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Solo message'); expect(call.attributes).not.toHaveProperty('sentry.message.template'); expect(call.attributes).not.toHaveProperty('sentry.message.parameter.0'); @@ -231,7 +231,7 @@ describe('consoleLoggingIntegration', () => { it('does not add template when first arg contains console substitution patterns', () => { triggerConsole('info', 'Value: %d, another: %s', 42, 'hello'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Value: %d, another: %s 42 hello'); expect(call.attributes).not.toHaveProperty('sentry.message.template'); expect(call.attributes).not.toHaveProperty('sentry.message.parameter.0'); @@ -241,7 +241,7 @@ describe('consoleLoggingIntegration', () => { triggerConsole('info', [1, 2, 3], 'Array data'); expect(formatConsoleArgs).toHaveBeenCalled(); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('[1,2,3] Array data'); // If arrays were treated as objects, their indices would leak as attribute keys ('0', '1', '2') expect(call.attributes).not.toHaveProperty('0'); @@ -250,7 +250,7 @@ describe('consoleLoggingIntegration', () => { it('does not generate template when first arg is a number', () => { triggerConsole('info', 42, 'is the answer'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('42 is the answer'); expect(call.attributes).toEqual({ 'sentry.origin': 'auto.log.console', @@ -264,7 +264,7 @@ describe('consoleLoggingIntegration', () => { const err = new Error('Test error'); triggerConsole('error', err, 'context info'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toContain('Error: Test error'); expect(call.message).toContain('context info'); expect(call.attributes).not.toHaveProperty('message'); @@ -275,7 +275,7 @@ describe('consoleLoggingIntegration', () => { const err = new Error('connection refused'); triggerConsole('error', 'Error occurred:', err); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.attributes?.['sentry.message.parameter.0']).toMatchObject({ message: 'connection refused', name: 'Error', @@ -288,7 +288,7 @@ describe('consoleLoggingIntegration', () => { simpleKey: 'simple value', }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Deep {"level1":{"level2":{"level3":"[Object]"}},"simpleKey":"simple value"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -306,7 +306,7 @@ describe('consoleLoggingIntegration', () => { const jsonStr = JSON.stringify({ some: 'structure', object: { foo: 2 } }); triggerConsole('log', jsonStr); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"some":"structure","object":{"foo":2}}'); expect(call.attributes).not.toHaveProperty('some'); expect(call.attributes).not.toHaveProperty('object'); @@ -315,7 +315,7 @@ describe('consoleLoggingIntegration', () => { it('treats a plain object as object-first', () => { triggerConsole('log', { some: 'structure', object: { foo: 1 } }); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"some":"structure","object":{"foo":1}}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -331,7 +331,7 @@ describe('consoleLoggingIntegration', () => { } triggerConsole('info', new MyClass(), 'extra'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toContain('extra'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -343,7 +343,7 @@ describe('consoleLoggingIntegration', () => { it('does not treat null as object-first', () => { triggerConsole('info', null, 'after null'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.attributes).not.toHaveProperty('sentry.message.parameter.0'); expect(call.message).toContain('null'); }); @@ -351,7 +351,7 @@ describe('consoleLoggingIntegration', () => { it('does not treat undefined as object-first', () => { triggerConsole('info', undefined, 'after undefined'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toContain('undefined'); }); }); @@ -360,7 +360,7 @@ describe('consoleLoggingIntegration', () => { it('maps console.log to info with severityNumber 10', () => { triggerConsole('log', 'test message'); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: 'info', severityNumber: 10, @@ -377,7 +377,7 @@ describe('consoleLoggingIntegration', () => { ] as const)('maps console.%s to %s', (consoleLevel, sentryLevel) => { triggerConsole(consoleLevel, `${consoleLevel} message`); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: sentryLevel, message: `${consoleLevel} message`, @@ -390,7 +390,7 @@ describe('consoleLoggingIntegration', () => { it('captures error log when assertion fails with no message', () => { triggerConsole('assert', false); - expect(_INTERNAL_captureLog).toHaveBeenCalledWith( + expect(captureLogEvent).toHaveBeenCalledWith( expect.objectContaining({ level: 'error', message: 'Assertion failed', @@ -401,7 +401,7 @@ describe('consoleLoggingIntegration', () => { it('captures error log with message when assertion fails', () => { triggerConsole('assert', false, 'expected true'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.level).toBe('error'); expect(call.message).toBe('Assertion failed: expected true'); }); @@ -409,7 +409,7 @@ describe('consoleLoggingIntegration', () => { it('does not capture when assertion passes', () => { triggerConsole('assert', true, 'should not appear'); - expect(_INTERNAL_captureLog).not.toHaveBeenCalled(); + expect(captureLogEvent).not.toHaveBeenCalled(); }); }); @@ -424,10 +424,10 @@ describe('consoleLoggingIntegration', () => { integration.setup!(filteredClient, true); triggerConsole('error', 'captured'); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(1); + expect(captureLogEvent).toHaveBeenCalledTimes(1); triggerConsole('info', 'not captured'); - expect(_INTERNAL_captureLog).toHaveBeenCalledTimes(1); + expect(captureLogEvent).toHaveBeenCalledTimes(1); }); }); @@ -438,7 +438,7 @@ describe('consoleLoggingIntegration', () => { triggerConsole('info', circular); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"key":"value","self":"[Circular ~]"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -454,7 +454,7 @@ describe('consoleLoggingIntegration', () => { triggerConsole('info', 'Message', circular); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('Message {"self":"[Circular ~]"}'); expect(call.attributes).toEqual( expect.objectContaining({ @@ -468,14 +468,14 @@ describe('consoleLoggingIntegration', () => { const date = new Date('2023-01-01T00:00:00.000Z'); triggerConsole('info', 'Time:', date); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.attributes?.['sentry.message.parameter.0']).toBe('2023-01-01T00:00:00.000Z'); }); it('preserves sentry.origin from object attributes when object is first arg', () => { triggerConsole('info', { 'sentry.origin': 'custom.origin', key: 'val' }, 'msg'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe('{"sentry.origin":"custom.origin","key":"val"} msg'); expect(call.attributes?.['sentry.origin']).toBe('custom.origin'); }); @@ -483,7 +483,7 @@ describe('consoleLoggingIntegration', () => { it('captures empty message when called with no arguments', () => { triggerConsole('log'); - const call = vi.mocked(_INTERNAL_captureLog).mock.calls[0]![0]; + const call = vi.mocked(captureLogEvent).mock.calls[0]![0]; expect(call.message).toBe(''); }); diff --git a/packages/core/test/lib/logs/internal.test.ts b/packages/core/test/lib/logs/internal.test.ts index fa3797d7dfac..c952a6120962 100644 --- a/packages/core/test/lib/logs/internal.test.ts +++ b/packages/core/test/lib/logs/internal.test.ts @@ -1,11 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { fmt, Scope } from '../../../src'; -import { - _INTERNAL_captureLog, - _INTERNAL_flushLogsBuffer, - _INTERNAL_getLogBuffer, - _removeLoneSurrogates, -} from '../../../src/logs/internal'; +import { captureLogEvent, flushLogsBuffer, getLogBuffer, _removeLoneSurrogates } from '../../../src/logs/internal'; import type { Log } from '../../../src/types/log'; import * as loggerModule from '../../../src/utils/debug-logger'; import * as timeModule from '../../../src/utils/time'; @@ -17,7 +12,7 @@ const PUBLIC_DSN = 'https://username@domain/123'; // toWellFormed() is only available in Node 20+, Chrome 111+, Safari 15.4+, Firefox 119+, Hermes const hasToWellFormed = typeof ''.isWellFormed === 'function'; -describe('_INTERNAL_captureLog', () => { +describe('captureLogEvent', () => { beforeEach(() => { _INTERNAL_resetSequenceNumber(); }); @@ -27,9 +22,9 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'info', message: 'test log message' }, scope); - expect(_INTERNAL_getLogBuffer(client)).toHaveLength(1); - expect(_INTERNAL_getLogBuffer(client)?.[0]).toEqual( + captureLogEvent({ level: 'info', message: 'test log message' }, scope); + expect(getLogBuffer(client)).toHaveLength(1); + expect(getLogBuffer(client)?.[0]).toEqual( expect.objectContaining({ level: 'info', body: 'test log message', @@ -53,9 +48,9 @@ describe('_INTERNAL_captureLog', () => { sampleRand: 1, }); - _INTERNAL_captureLog({ level: 'error', message: 'test log with trace' }, scope); + captureLogEvent({ level: 'error', message: 'test log with trace' }, scope); - expect(_INTERNAL_getLogBuffer(client)?.[0]).toEqual( + expect(getLogBuffer(client)?.[0]).toEqual( expect.objectContaining({ trace_id: '3d9355f71e9c444b81161599adac6e29', severity_number: 17, // error level maps to 17 @@ -73,9 +68,9 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'info', message: 'test log with metadata' }, scope); + captureLogEvent({ level: 'info', message: 'test log with metadata' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.release': { value: '1.0.0', @@ -104,9 +99,9 @@ describe('_INTERNAL_captureLog', () => { }, }); - _INTERNAL_captureLog({ level: 'info', message: 'test log with SDK metadata' }, scope); + captureLogEvent({ level: 'info', message: 'test log with SDK metadata' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.sdk.name': { value: 'sentry.javascript.node', @@ -130,9 +125,9 @@ describe('_INTERNAL_captureLog', () => { // Mock getSdkMetadata to return no SDK info vi.spyOn(client, 'getSdkMetadata').mockReturnValue({}); - _INTERNAL_captureLog({ level: 'info', message: 'test log without SDK metadata' }, scope); + captureLogEvent({ level: 'info', message: 'test log without SDK metadata' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).not.toEqual( expect.arrayContaining([ expect.objectContaining({ key: 'sentry.sdk.name' }), @@ -148,7 +143,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with custom attributes', @@ -157,7 +152,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ userId: { value: '123', @@ -185,7 +180,7 @@ describe('_INTERNAL_captureLog', () => { scope_5: { value: [true, false, true], unit: 'second' }, }); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with custom attributes', @@ -194,7 +189,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toStrictEqual({ userId: { @@ -240,16 +235,16 @@ describe('_INTERNAL_captureLog', () => { // Fill the buffer to max size (100 is the MAX_LOG_BUFFER_SIZE constant in client.ts) for (let i = 0; i < 100; i++) { - _INTERNAL_captureLog({ level: 'info', message: `log message ${i}` }, scope); + captureLogEvent({ level: 'info', message: `log message ${i}` }, scope); } - expect(_INTERNAL_getLogBuffer(client)).toHaveLength(100); + expect(getLogBuffer(client)).toHaveLength(100); // Add one more to trigger flush - _INTERNAL_captureLog({ level: 'info', message: 'trigger flush' }, scope); + captureLogEvent({ level: 'info', message: 'trigger flush' }, scope); // After flushing the 100 logs, the new log starts a fresh buffer with 1 item - const buffer = _INTERNAL_getLogBuffer(client); + const buffer = getLogBuffer(client); expect(buffer).toHaveLength(1); expect(buffer?.[0]?.body).toBe('trigger flush'); }); @@ -259,7 +254,7 @@ describe('_INTERNAL_captureLog', () => { const client = new TestClient(options); const mockSendEnvelope = vi.spyOn(client as any, 'sendEnvelope').mockImplementation(() => {}); - _INTERNAL_flushLogsBuffer(client); + flushLogsBuffer(client); expect(mockSendEnvelope).not.toHaveBeenCalled(); }); @@ -271,9 +266,9 @@ describe('_INTERNAL_captureLog', () => { const parameterizedMessage = fmt`Hello ${'John'}, welcome to ${'Sentry'}`; - _INTERNAL_captureLog({ level: 'info', message: parameterizedMessage }, scope); + captureLogEvent({ level: 'info', message: parameterizedMessage }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.message.template': { value: 'Hello %s, welcome to %s', @@ -297,9 +292,9 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'debug', message: fmt`User logged in` }, scope); + captureLogEvent({ level: 'debug', message: fmt`User logged in` }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -323,7 +318,7 @@ describe('_INTERNAL_captureLog', () => { scope.setAttribute('scope_1', 'attribute_value'); scope.setAttribute('scope_2', { value: 38, unit: 'gigabytes' }); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'original message', @@ -341,7 +336,7 @@ describe('_INTERNAL_captureLog', () => { }, }); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer).toBeDefined(); expect(logBuffer?.[0]).toEqual( expect.objectContaining({ @@ -386,7 +381,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - expect(() => _INTERNAL_captureLog({ level: 'info', message: 'test message' }, scope)).not.toThrow(); + expect(() => captureLogEvent({ level: 'info', message: 'test message' }, scope)).not.toThrow(); expect(beforeSendLog).toHaveBeenCalled(); expect(recordDroppedEventSpy).toHaveBeenCalledWith('callback_error', 'log_item', 1); @@ -394,7 +389,7 @@ describe('_INTERNAL_captureLog', () => { 'The `beforeSendLog` callback threw an error, dropping the log:', exception, ); - expect(_INTERNAL_getLogBuffer(client)).toBeUndefined(); + expect(getLogBuffer(client)).toBeUndefined(); recordDroppedEventSpy.mockRestore(); }); @@ -412,7 +407,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test message', @@ -423,7 +418,7 @@ describe('_INTERNAL_captureLog', () => { expect(beforeSendLog).toHaveBeenCalled(); expect(recordDroppedEventSpy).toHaveBeenCalledWith('before_send', 'log_item', 1); expect(loggerWarnSpy).toHaveBeenCalledWith('beforeSendLog returned null, log will not be captured.'); - expect(_INTERNAL_getLogBuffer(client)).toBeUndefined(); + expect(getLogBuffer(client)).toBeUndefined(); recordDroppedEventSpy.mockRestore(); loggerWarnSpy.mockRestore(); @@ -442,7 +437,7 @@ describe('_INTERNAL_captureLog', () => { attributes: {}, }; - _INTERNAL_captureLog(log, scope); + captureLogEvent(log, scope); expect(beforeCaptureLogSpy).toHaveBeenCalledWith('beforeCaptureLog', log); expect(beforeCaptureLogSpy).toHaveBeenCalledWith('afterCaptureLog', log); @@ -467,12 +462,12 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with sampled replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with sampled replay' }, scope); // Verify getReplayId was called with onlyIfSampled=true expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.replay_id': { value: 'sampled-replay-id', @@ -498,12 +493,12 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with unsampled replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with unsampled replay' }, scope); // Verify getReplayId was called with onlyIfSampled=true expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -526,11 +521,11 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with buffer replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with buffer replay' }, scope); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.replay_id': { value: 'buffer-replay-id', @@ -553,9 +548,9 @@ describe('_INTERNAL_captureLog', () => { // Mock no replay integration found vi.spyOn(client, 'getIntegrationByName').mockReturnValue(undefined); - _INTERNAL_captureLog({ level: 'info', message: 'test log without replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log without replay' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -579,7 +574,7 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with replay and other attributes', @@ -588,7 +583,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ component: { value: 'auth', @@ -624,7 +619,7 @@ describe('_INTERNAL_captureLog', () => { testCases.forEach(returnValue => { // Clear buffer for each test - _INTERNAL_getLogBuffer(client)?.splice(0); + getLogBuffer(client)?.splice(0); const mockReplayIntegration = { getReplayId: vi.fn(() => returnValue), @@ -632,9 +627,9 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: `test log with replay returning ${returnValue}` }, scope); + captureLogEvent({ level: 'info', message: `test log with replay returning ${returnValue}` }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -656,12 +651,12 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with buffered replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with buffered replay' }, scope); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.replay_id': { value: 'buffer-replay-id', @@ -689,12 +684,12 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with session replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with session replay' }, scope); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.replay_id': { value: 'session-replay-id', @@ -719,12 +714,12 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with stopped replay' }, scope); + captureLogEvent({ level: 'info', message: 'test log with stopped replay' }, scope); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.replay_id': { value: 'stopped-replay-id', @@ -749,13 +744,13 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog({ level: 'info', message: 'test log with buffer mode but no replay ID' }, scope); + captureLogEvent({ level: 'info', message: 'test log with buffer mode but no replay ID' }, scope); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); // getRecordingMode should not be called if there's no replay ID expect(mockReplayIntegration.getRecordingMode).not.toHaveBeenCalled(); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -772,9 +767,9 @@ describe('_INTERNAL_captureLog', () => { // Mock no replay integration found vi.spyOn(client, 'getIntegrationByName').mockReturnValue(undefined); - _INTERNAL_captureLog({ level: 'info', message: 'test log without replay integration' }, scope); + captureLogEvent({ level: 'info', message: 'test log without replay integration' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -800,7 +795,7 @@ describe('_INTERNAL_captureLog', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with buffer replay and other attributes', @@ -809,7 +804,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ component: { value: 'auth', @@ -854,9 +849,9 @@ describe('_INTERNAL_captureLog', () => { username: 'testuser', }); - _INTERNAL_captureLog({ level: 'info', message: 'test log with user' }, scope); + captureLogEvent({ level: 'info', message: 'test log with user' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.id': { value: '123', @@ -886,9 +881,9 @@ describe('_INTERNAL_captureLog', () => { // email and username are missing }); - _INTERNAL_captureLog({ level: 'info', message: 'test log with partial user' }, scope); + captureLogEvent({ level: 'info', message: 'test log with partial user' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.id': { value: '123', @@ -911,9 +906,9 @@ describe('_INTERNAL_captureLog', () => { // id is missing }); - _INTERNAL_captureLog({ level: 'info', message: 'test log with email and username' }, scope); + captureLogEvent({ level: 'info', message: 'test log with email and username' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.email': { value: 'user@example.com', @@ -936,9 +931,9 @@ describe('_INTERNAL_captureLog', () => { scope.setClient(client); scope.setUser({}); - _INTERNAL_captureLog({ level: 'info', message: 'test log with empty user' }, scope); + captureLogEvent({ level: 'info', message: 'test log with empty user' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' }, }); @@ -958,7 +953,7 @@ describe('_INTERNAL_captureLog', () => { email: 'user@example.com', }); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with user and other attributes', @@ -967,7 +962,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ component: { value: 'auth', @@ -1010,9 +1005,9 @@ describe('_INTERNAL_captureLog', () => { username: undefined, // undefined value }); - _INTERNAL_captureLog({ level: 'info', message: 'test log with non-string user values' }, scope); + captureLogEvent({ level: 'info', message: 'test log with non-string user values' }, scope); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.id': { value: 123, @@ -1038,7 +1033,7 @@ describe('_INTERNAL_captureLog', () => { email: 'user@example.com', }); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with existing user attributes', @@ -1050,7 +1045,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.custom': { value: 'custom-value', @@ -1081,7 +1076,7 @@ describe('_INTERNAL_captureLog', () => { username: 'scope-user', }); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with partial existing user attributes', @@ -1093,7 +1088,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'other.attr': { value: 'value', @@ -1134,7 +1129,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'test log with user-provided system attributes', @@ -1149,7 +1144,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logAttributes = _INTERNAL_getLogBuffer(client)?.[0]?.attributes; + const logAttributes = getLogBuffer(client)?.[0]?.attributes; expect(logAttributes).toEqual({ 'user.custom': { value: 'preserved-value', @@ -1184,11 +1179,11 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'info', message: 'first' }, scope); - _INTERNAL_captureLog({ level: 'info', message: 'second' }, scope); - _INTERNAL_captureLog({ level: 'info', message: 'third' }, scope); + captureLogEvent({ level: 'info', message: 'first' }, scope); + captureLogEvent({ level: 'info', message: 'second' }, scope); + captureLogEvent({ level: 'info', message: 'third' }, scope); - const buffer = _INTERNAL_getLogBuffer(client); + const buffer = getLogBuffer(client); expect(buffer?.[0]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 0, type: 'integer' }); expect(buffer?.[1]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 1, type: 'integer' }); expect(buffer?.[2]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 2, type: 'integer' }); @@ -1211,11 +1206,11 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'info', message: 'keep first' }, scope); - _INTERNAL_captureLog({ level: 'info', message: 'drop me' }, scope); - _INTERNAL_captureLog({ level: 'info', message: 'keep second' }, scope); + captureLogEvent({ level: 'info', message: 'keep first' }, scope); + captureLogEvent({ level: 'info', message: 'drop me' }, scope); + captureLogEvent({ level: 'info', message: 'keep second' }, scope); - const buffer = _INTERNAL_getLogBuffer(client); + const buffer = getLogBuffer(client); expect(buffer).toHaveLength(2); expect(buffer?.[0]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 0, type: 'integer' }); expect(buffer?.[1]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 1, type: 'integer' }); @@ -1233,10 +1228,10 @@ describe('_INTERNAL_captureLog', () => { const count = 50; for (let i = 0; i < count; i++) { - _INTERNAL_captureLog({ level: 'info', message: `log ${i}` }, scope); + captureLogEvent({ level: 'info', message: `log ${i}` }, scope); } - const buffer = _INTERNAL_getLogBuffer(client)!; + const buffer = getLogBuffer(client)!; expect(buffer).toHaveLength(count); for (let i = 1; i < count; i++) { @@ -1254,7 +1249,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'info', message: 'first' }, scope); + captureLogEvent({ level: 'info', message: 'first' }, scope); _INTERNAL_resetSequenceNumber(); @@ -1262,9 +1257,9 @@ describe('_INTERNAL_captureLog', () => { const scope2 = new Scope(); scope2.setClient(client2); - _INTERNAL_captureLog({ level: 'info', message: 'after reset' }, scope2); + captureLogEvent({ level: 'info', message: 'after reset' }, scope2); - const buffer2 = _INTERNAL_getLogBuffer(client2); + const buffer2 = getLogBuffer(client2); expect(buffer2?.[0]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 0, type: 'integer' }); }); }); @@ -1276,9 +1271,9 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog({ level: 'error', message: 'bad surrogate \uD800 here' }, scope); + captureLogEvent({ level: 'error', message: 'bad surrogate \uD800 here' }, scope); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer?.[0]?.body).toBe('bad surrogate \uFFFD here'); }); @@ -1289,9 +1284,9 @@ describe('_INTERNAL_captureLog', () => { scope.setClient(client); const badValue = 'bad\uD800value'; - _INTERNAL_captureLog({ level: 'error', message: fmt`parameterized ${badValue} message` }, scope); + captureLogEvent({ level: 'error', message: fmt`parameterized ${badValue} message` }, scope); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer?.[0]?.body).toBe('parameterized bad\uFFFDvalue message'); }); @@ -1301,7 +1296,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'error', message: 'test', @@ -1310,7 +1305,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer?.[0]?.attributes?.['bad']).toEqual({ value: '{"a":"\uFFFD"}', type: 'string', @@ -1323,7 +1318,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'error', message: 'test', @@ -1332,7 +1327,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer?.[0]?.attributes?.['bad\uFFFDkey']).toEqual({ value: 'value', type: 'string', @@ -1345,7 +1340,7 @@ describe('_INTERNAL_captureLog', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureLog( + captureLogEvent( { level: 'info', message: 'hello 😀 world', @@ -1354,7 +1349,7 @@ describe('_INTERNAL_captureLog', () => { scope, ); - const logBuffer = _INTERNAL_getLogBuffer(client); + const logBuffer = getLogBuffer(client); expect(logBuffer?.[0]?.body).toBe('hello 😀 world'); expect(logBuffer?.[0]?.attributes?.['emoji']).toEqual({ value: '🎉 party', diff --git a/packages/core/test/lib/metrics/internal.test.ts b/packages/core/test/lib/metrics/internal.test.ts index 869f2ee38665..c3482231d0fd 100644 --- a/packages/core/test/lib/metrics/internal.test.ts +++ b/packages/core/test/lib/metrics/internal.test.ts @@ -1,10 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Scope } from '../../../src'; -import { - _INTERNAL_captureMetric, - _INTERNAL_flushMetricsBuffer, - _INTERNAL_getMetricBuffer, -} from '../../../src/metrics/internal'; +import { captureMetricEvent, flushMetricsBuffer, getMetricBuffer } from '../../../src/metrics/internal'; import type { Metric } from '../../../src/types/metric'; import * as loggerModule from '../../../src/utils/debug-logger'; import * as isBrowserModule from '../../../src/utils/isBrowser'; @@ -16,7 +12,7 @@ const PUBLIC_DSN = 'https://username@domain/123'; const SEQUENCE_ATTR = { 'sentry.timestamp.sequence': { value: expect.any(Number), type: 'integer' } }; -describe('_INTERNAL_captureMetric', () => { +describe('captureMetricEvent', () => { beforeEach(() => { _INTERNAL_resetSequenceNumber(); }); @@ -27,9 +23,9 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - expect(_INTERNAL_getMetricBuffer(client)).toHaveLength(1); - expect(_INTERNAL_getMetricBuffer(client)?.[0]).toEqual( + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + expect(getMetricBuffer(client)).toHaveLength(1); + expect(getMetricBuffer(client)?.[0]).toEqual( expect.objectContaining({ name: 'test.metric', type: 'counter', @@ -51,9 +47,9 @@ describe('_INTERNAL_captureMetric', () => { sampleRand: 1, }); - _INTERNAL_captureMetric({ type: 'gauge', name: 'test.gauge', value: 42 }, { scope }); + captureMetricEvent({ type: 'gauge', name: 'test.gauge', value: 42 }, { scope }); - expect(_INTERNAL_getMetricBuffer(client)?.[0]).toEqual( + expect(getMetricBuffer(client)?.[0]).toEqual( expect.objectContaining({ trace_id: '3d9355f71e9c444b81161599adac6e29', }), @@ -70,9 +66,9 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.release': { @@ -101,9 +97,9 @@ describe('_INTERNAL_captureMetric', () => { }, }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.sdk.name': { @@ -127,9 +123,9 @@ describe('_INTERNAL_captureMetric', () => { // Mock getSdkMetadata to return no SDK info vi.spyOn(client, 'getSdkMetadata').mockReturnValue({}); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).not.toEqual( expect.arrayContaining([ expect.objectContaining({ key: 'sentry.sdk.name' }), @@ -144,7 +140,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -154,7 +150,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, endpoint: { @@ -176,9 +172,9 @@ describe('_INTERNAL_captureMetric', () => { scope.setAttribute('scope_attribute_1', 1); scope.setAttributes({ scope_attribute_2: { value: 'test' }, scope_attribute_3: { value: 38, unit: 'gigabyte' } }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, scope_attribute_1: { @@ -204,12 +200,12 @@ describe('_INTERNAL_captureMetric', () => { scope.setClient(client); scope.setAttribute('my-attribute', 42); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', value: 1, attributes: { 'my-attribute': 43 } }, { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'my-attribute': { value: 43, type: 'integer' }, @@ -224,16 +220,16 @@ describe('_INTERNAL_captureMetric', () => { // Fill the buffer to max size (1000 is the MAX_METRIC_BUFFER_SIZE constant) for (let i = 0; i < 1000; i++) { - _INTERNAL_captureMetric({ type: 'counter', name: `metric.${i}`, value: i }, { scope }); + captureMetricEvent({ type: 'counter', name: `metric.${i}`, value: i }, { scope }); } - expect(_INTERNAL_getMetricBuffer(client)).toHaveLength(1000); + expect(getMetricBuffer(client)).toHaveLength(1000); // Add one more to trigger flush - _INTERNAL_captureMetric({ type: 'counter', name: 'trigger.flush', value: 999 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'trigger.flush', value: 999 }, { scope }); // After flushing the 1000 metrics, the new metric starts a fresh buffer with 1 item - const buffer = _INTERNAL_getMetricBuffer(client); + const buffer = getMetricBuffer(client); expect(buffer).toHaveLength(1); expect(buffer?.[0]?.name).toBe('trigger.flush'); }); @@ -246,10 +242,10 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); const sendEnvelope = vi.spyOn(client as any, 'sendEnvelope').mockImplementation(() => {}); - _INTERNAL_flushMetricsBuffer(client); + flushMetricsBuffer(client); const envelope = sendEnvelope.mock.calls[0]![0]; const envelopeItemPayload = envelope[1][0][1]; @@ -264,10 +260,10 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); const sendEnvelope = vi.spyOn(client as any, 'sendEnvelope').mockImplementation(() => {}); - _INTERNAL_flushMetricsBuffer(client); + flushMetricsBuffer(client); const envelope = sendEnvelope.mock.calls[0]![0]; const envelopeItemPayload = envelope[1][0][1]; @@ -279,7 +275,7 @@ describe('_INTERNAL_captureMetric', () => { const client = new TestClient(options); const mockSendEnvelope = vi.spyOn(client as any, 'sendEnvelope').mockImplementation(() => {}); - _INTERNAL_flushMetricsBuffer(client); + flushMetricsBuffer(client); expect(mockSendEnvelope).not.toHaveBeenCalled(); }); @@ -298,7 +294,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'original.metric', @@ -315,7 +311,7 @@ describe('_INTERNAL_captureMetric', () => { attributes: { original: true }, }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toBeDefined(); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -348,7 +344,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -360,7 +356,7 @@ describe('_INTERNAL_captureMetric', () => { expect(beforeSendMetric).toHaveBeenCalled(); expect(recordDroppedEventSpy).toHaveBeenCalledWith('before_send', 'trace_metric', 1); expect(loggerWarnSpy).toHaveBeenCalledWith('`beforeSendMetric` returned `null`, will not send metric.'); - expect(_INTERNAL_getMetricBuffer(client)).toBeUndefined(); + expect(getMetricBuffer(client)).toBeUndefined(); recordDroppedEventSpy.mockRestore(); loggerWarnSpy.mockRestore(); @@ -382,7 +378,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - expect(() => _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope })).not.toThrow(); + expect(() => captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope })).not.toThrow(); expect(beforeSendMetric).toHaveBeenCalled(); expect(recordDroppedEventSpy).toHaveBeenCalledWith('callback_error', 'trace_metric', 1); @@ -390,7 +386,7 @@ describe('_INTERNAL_captureMetric', () => { 'The `beforeSendMetric` callback threw an error, dropping the metric:', exception, ); - expect(_INTERNAL_getMetricBuffer(client)).toBeUndefined(); + expect(getMetricBuffer(client)).toBeUndefined(); recordDroppedEventSpy.mockRestore(); }); @@ -409,7 +405,7 @@ describe('_INTERNAL_captureMetric', () => { attributes: {}, }; - _INTERNAL_captureMetric(metric, { scope }); + captureMetricEvent(metric, { scope }); expect(afterCaptureMetricSpy).toHaveBeenCalledWith('afterCaptureMetric', expect.objectContaining(metric)); afterCaptureMetricSpy.mockRestore(); @@ -432,11 +428,11 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.replay_id': { @@ -461,11 +457,11 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); }); @@ -485,11 +481,11 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.replay_id': { @@ -512,9 +508,9 @@ describe('_INTERNAL_captureMetric', () => { // Mock no replay integration found vi.spyOn(client, 'getIntegrationByName').mockReturnValue(undefined); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); }); @@ -537,7 +533,7 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -547,7 +543,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, endpoint: { @@ -583,7 +579,7 @@ describe('_INTERNAL_captureMetric', () => { testCases.forEach(returnValue => { // Clear buffer for each test - _INTERNAL_getMetricBuffer(client)?.splice(0); + getMetricBuffer(client)?.splice(0); const mockReplayIntegration = { getReplayId: vi.fn(() => returnValue), @@ -591,9 +587,9 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); expect(metricAttributes).not.toHaveProperty('sentry.replay_id'); }); @@ -613,12 +609,12 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.replay_id': { @@ -646,12 +642,12 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.replay_id': { @@ -676,12 +672,12 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); expect(mockReplayIntegration.getRecordingMode).toHaveBeenCalled(); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'sentry.replay_id': { @@ -706,13 +702,13 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); expect(mockReplayIntegration.getReplayId).toHaveBeenCalledWith(true); // getRecordingMode should not be called if there's no replay ID expect(mockReplayIntegration.getRecordingMode).not.toHaveBeenCalled(); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); expect(metricAttributes).not.toHaveProperty('sentry.replay_id'); expect(metricAttributes).not.toHaveProperty('sentry._internal.replay_is_buffering'); @@ -727,9 +723,9 @@ describe('_INTERNAL_captureMetric', () => { // Mock no replay integration found vi.spyOn(client, 'getIntegrationByName').mockReturnValue(undefined); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); expect(metricAttributes).not.toHaveProperty('sentry.replay_id'); expect(metricAttributes).not.toHaveProperty('sentry._internal.replay_is_buffering'); @@ -754,7 +750,7 @@ describe('_INTERNAL_captureMetric', () => { vi.spyOn(client, 'getIntegrationByName').mockReturnValue(mockReplayIntegration as any); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -764,7 +760,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, endpoint: { @@ -809,9 +805,9 @@ describe('_INTERNAL_captureMetric', () => { username: 'testuser', }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.id': { @@ -841,9 +837,9 @@ describe('_INTERNAL_captureMetric', () => { // email and username are missing }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.id': { @@ -866,9 +862,9 @@ describe('_INTERNAL_captureMetric', () => { // id is missing }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.email': { @@ -891,9 +887,9 @@ describe('_INTERNAL_captureMetric', () => { scope.setClient(client); scope.setUser({}); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR }); }); @@ -912,7 +908,7 @@ describe('_INTERNAL_captureMetric', () => { email: 'user@example.com', }); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -922,7 +918,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, endpoint: { @@ -965,9 +961,9 @@ describe('_INTERNAL_captureMetric', () => { username: undefined, }); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.id': { @@ -993,7 +989,7 @@ describe('_INTERNAL_captureMetric', () => { email: 'user@example.com', }); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -1006,7 +1002,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.custom': { @@ -1037,7 +1033,7 @@ describe('_INTERNAL_captureMetric', () => { username: 'scope-user', }); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -1050,7 +1046,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'other.attr': { @@ -1091,7 +1087,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -1107,7 +1103,7 @@ describe('_INTERNAL_captureMetric', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual({ ...SEQUENCE_ATTR, 'user.custom': { @@ -1144,11 +1140,11 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'first', value: 1 }, { scope }); - _INTERNAL_captureMetric({ type: 'counter', name: 'second', value: 2 }, { scope }); - _INTERNAL_captureMetric({ type: 'counter', name: 'third', value: 3 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'first', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'second', value: 2 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'third', value: 3 }, { scope }); - const buffer = _INTERNAL_getMetricBuffer(client); + const buffer = getMetricBuffer(client); expect(buffer?.[0]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 0, type: 'integer' }); expect(buffer?.[1]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 1, type: 'integer' }); expect(buffer?.[2]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 2, type: 'integer' }); @@ -1162,7 +1158,7 @@ describe('_INTERNAL_captureMetric', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'first', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'first', value: 1 }, { scope }); _INTERNAL_resetSequenceNumber(); @@ -1170,9 +1166,9 @@ describe('_INTERNAL_captureMetric', () => { const scope2 = new Scope(); scope2.setClient(client2); - _INTERNAL_captureMetric({ type: 'counter', name: 'after reset', value: 2 }, { scope: scope2 }); + captureMetricEvent({ type: 'counter', name: 'after reset', value: 2 }, { scope: scope2 }); - const buffer2 = _INTERNAL_getMetricBuffer(client2); + const buffer2 = getMetricBuffer(client2); expect(buffer2?.[0]?.attributes?.['sentry.timestamp.sequence']).toEqual({ value: 0, type: 'integer' }); }); }); diff --git a/packages/core/test/lib/metrics/public-api.test.ts b/packages/core/test/lib/metrics/public-api.test.ts index 646fdeca9879..e7c063318bc8 100644 --- a/packages/core/test/lib/metrics/public-api.test.ts +++ b/packages/core/test/lib/metrics/public-api.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { Scope } from '../../../src'; -import { _INTERNAL_getMetricBuffer } from '../../../src/metrics/internal'; +import { getMetricBuffer } from '../../../src/metrics/internal'; import { count, distribution, gauge } from '../../../src/metrics/public-api'; import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; @@ -16,7 +16,7 @@ describe('Metrics Public API', () => { count('api.requests', undefined, { scope }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -35,7 +35,7 @@ describe('Metrics Public API', () => { count('items.processed', 5, { scope }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -61,7 +61,7 @@ describe('Metrics Public API', () => { }, }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -101,7 +101,7 @@ describe('Metrics Public API', () => { unit: 'byte', }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -123,7 +123,7 @@ describe('Metrics Public API', () => { gauge('memory.usage', 1024, { scope }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -145,7 +145,7 @@ describe('Metrics Public API', () => { unit: 'megabyte', }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -171,7 +171,7 @@ describe('Metrics Public API', () => { }, }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -206,7 +206,7 @@ describe('Metrics Public API', () => { distribution('task.duration', 500, { scope }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -228,7 +228,7 @@ describe('Metrics Public API', () => { unit: 'millisecond', }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -254,7 +254,7 @@ describe('Metrics Public API', () => { }, }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(1); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ @@ -291,7 +291,7 @@ describe('Metrics Public API', () => { gauge('memory.usage', 1024, { scope }); distribution('task.duration', 500, { scope }); - const metricBuffer = _INTERNAL_getMetricBuffer(client); + const metricBuffer = getMetricBuffer(client); expect(metricBuffer).toHaveLength(3); expect(metricBuffer?.[0]).toEqual( expect.objectContaining({ diff --git a/packages/core/test/lib/server-runtime-client.test.ts b/packages/core/test/lib/server-runtime-client.test.ts index 12ae4d625503..9cd83d10eeb3 100644 --- a/packages/core/test/lib/server-runtime-client.test.ts +++ b/packages/core/test/lib/server-runtime-client.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, test, vi } from 'vitest'; import { applySdkMetadata, createTransport, Scope } from '../../src'; -import { _INTERNAL_captureMetric, _INTERNAL_getMetricBuffer } from '../../src/metrics/internal'; +import { captureMetricEvent, getMetricBuffer } from '../../src/metrics/internal'; import type { ServerRuntimeClientOptions } from '../../src/server-runtime-client'; import { ServerRuntimeClient } from '../../src/server-runtime-client'; import type { Event, EventHint } from '../../src/types/event'; @@ -245,9 +245,9 @@ describe('ServerRuntimeClient', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual( expect.objectContaining({ 'server.address': { @@ -264,9 +264,9 @@ describe('ServerRuntimeClient', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); + captureMetricEvent({ type: 'counter', name: 'test.metric', value: 1 }, { scope }); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).not.toEqual( expect.objectContaining({ 'server.address': expect.anything(), @@ -280,7 +280,7 @@ describe('ServerRuntimeClient', () => { const scope = new Scope(); scope.setClient(client); - _INTERNAL_captureMetric( + captureMetricEvent( { type: 'counter', name: 'test.metric', @@ -290,7 +290,7 @@ describe('ServerRuntimeClient', () => { { scope }, ); - const metricAttributes = _INTERNAL_getMetricBuffer(client)?.[0]?.attributes; + const metricAttributes = getMetricBuffer(client)?.[0]?.attributes; expect(metricAttributes).toEqual( expect.objectContaining({ 'server.address': { diff --git a/packages/core/test/lib/tracing/idleSpan.test.ts b/packages/core/test/lib/tracing/idleSpan.test.ts index a689b166041c..d9a37209a1d6 100644 --- a/packages/core/test/lib/tracing/idleSpan.test.ts +++ b/packages/core/test/lib/tracing/idleSpan.test.ts @@ -664,6 +664,37 @@ describe('startIdleSpan', () => { }); }); + describe('ignoreSpans', () => { + const initClient = (traceLifecycle: 'static' | 'stream'): void => { + const client = new TestClient( + getDefaultTestClientOptions({ dsn, tracesSampleRate: 1, traceLifecycle, ignoreSpans: [/\/health$/] }), + ); + setCurrentClient(client); + client.init(); + }; + + it('does not wait for an ignored span with span streaming', () => { + initClient('stream'); + const idleSpan = startIdleSpan({ name: 'pageload' }); + + startInactiveSpan({ name: 'GET https://api.example.com/health' }); + vi.advanceTimersByTime(TRACING_DEFAULTS.idleTimeout); + + expect(spanToJSON(idleSpan).end_timestamp).toBeDefined(); + }); + + it('excludes ignored spans when trimming the end timestamp', () => { + initClient('static'); + const idleSpan = startIdleSpan({ name: 'pageload', startTime: 1000 }, { finalTimeout: 99_999_999 }); + + startInactiveSpan({ name: 'ui.render', startTime: 1001 }).end(1005); + startInactiveSpan({ name: 'GET https://api.example.com/health', startTime: 1009 }).end(1010); + vi.runAllTimers(); + + expect(spanToJSON(idleSpan).end_timestamp).toBe(1005); + }); + }); + describe('child span timeout', () => { it('finishes when a child span exceed timeout', () => { const idleSpan = startIdleSpan({ name: 'idle span' }); diff --git a/packages/core/test/lib/utils/tunnel.test.ts b/packages/core/test/lib/utils/tunnel.test.ts index 5ccef88e765a..c09ca8d53a43 100644 --- a/packages/core/test/lib/utils/tunnel.test.ts +++ b/packages/core/test/lib/utils/tunnel.test.ts @@ -29,7 +29,7 @@ import { } from '../../../src/utils/tunnelForward'; import { serveTunnelIntegration } from '../../../src/integrations/serveTunnel'; import { - _INTERNAL_resetTunnelDefaults, + resetTunnelDefaults, applyServerTunnelDefaults, enableManagedTunnel, setTunnelDefaults, @@ -1041,7 +1041,7 @@ describe('a forward that throws right away', () => { describe('serveTunnelIntegration', () => { afterEach(() => { getCurrentScope().setClient(undefined); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('ignores the server spans of tunnel requests and keeps user filters', () => { @@ -1190,7 +1190,7 @@ describe('normalizeTunnelBasePath', () => { describe('setTunnelDefaults', () => { afterEach(() => { getCurrentScope().setClient(undefined); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('serves the tunnel under the base path and drops its spans there', () => { @@ -1223,13 +1223,13 @@ describe('setTunnelDefaults', () => { const client = getCurrentScope().getClient()!; setTunnelDefaults({ basePath: '/app' }); expect(client.getOptions()._managedTunnel).toEqual({ basePath: '/custom' }); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); setTestClient(TEST_DSN, {}); const rootClient = getCurrentScope().getClient()!; setTunnelDefaults({ basePath: '/' }); expect(rootClient.getOptions()._managedTunnel).toEqual({}); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); setTestClient(TEST_DSN); const offClient = getCurrentScope().getClient()!; diff --git a/packages/deno/package.json b/packages/deno/package.json index 7cd9e507d1fb..c221df08bcb8 100644 --- a/packages/deno/package.json +++ b/packages/deno/package.json @@ -29,7 +29,7 @@ ], "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", "@sentry/server-utils": "11.17.0" diff --git a/packages/deno/src/integrations/contextlines.ts b/packages/deno/src/integrations/contextlines.ts index e367003d8437..eca57a4b900f 100644 --- a/packages/deno/src/integrations/contextlines.ts +++ b/packages/deno/src/integrations/contextlines.ts @@ -111,6 +111,10 @@ async function addSourceContextToFrames(frames: StackFrame[], contextLines: numb if (sourceFile) { try { const lines = sourceFile.split('\n'); + // A trailing newline ends the last line, it does not start another one. + if (lines[lines.length - 1] === '') { + lines.pop(); + } addContextToFrame(lines, frame, contextLines); } catch { // anomaly, being defensive in case diff --git a/packages/deno/src/integrations/http.ts b/packages/deno/src/integrations/http.ts index ea6a4fbae6c0..c1db427e5270 100644 --- a/packages/deno/src/integrations/http.ts +++ b/packages/deno/src/integrations/http.ts @@ -184,13 +184,14 @@ const _denoHttpIntegration = ((options: DenoHttpIntegrationOptions = {}) => { }); subscribe(HTTP_ON_SERVER_REQUEST, onHttpServerRequest); + const { ignoreOutgoingRequests } = options; const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequest } = getHttpClientSubscriptions({ ...options, breadcrumbs, tracePropagation, applyCustomAttributesOnSpan: options.outgoingRequestApplyCustomAttributes, - ignoreOutgoingRequests: options.ignoreOutgoingRequests - ? (url, request) => options.ignoreOutgoingRequests!(url, getRequestOptions(request)) + ignoreOutgoingRequests: ignoreOutgoingRequests + ? (url, request) => ignoreOutgoingRequests(url, getRequestOptions(request)) : undefined, // Deno doesn't run OTel's http instrumentation, so there's no // double-wrap to detect; skip the warning to avoid loading the module. diff --git a/packages/deno/src/sdk.ts b/packages/deno/src/sdk.ts index 11aeec949924..6cf358c9db7c 100644 --- a/packages/deno/src/sdk.ts +++ b/packages/deno/src/sdk.ts @@ -15,7 +15,12 @@ import { requestDataIntegration, stackParserFromStackParserOptions, } from '@sentry/core'; -import { detectOrchestrionSetup, getTracingIntegrations, getErrorIntegrations } from '@sentry/server-utils'; +import { + createGetModuleFromFilename, + detectOrchestrionSetup, + getTracingIntegrations, + getErrorIntegrations, +} from '@sentry/server-utils'; import { DenoClient } from './client'; import { nodeStackLineParser } from '@sentry/core/server'; import { breadcrumbsIntegration } from './integrations/breadcrumbs'; @@ -61,7 +66,7 @@ export function getDefaultIntegrations(options: Options): Integration[] { return [...getDefaultIntegrationsWithoutPerformance(), ...(hasSpansEnabled(options) ? getTracingIntegrations() : [])]; } -const defaultStackParser: StackParser = createStackParser(nodeStackLineParser()); +const defaultStackParser: StackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename())); /** * The Sentry Deno SDK Client. diff --git a/packages/deno/src/tunnelServer.ts b/packages/deno/src/tunnelServer.ts index 9c606f38fe67..faaa232d4441 100644 --- a/packages/deno/src/tunnelServer.ts +++ b/packages/deno/src/tunnelServer.ts @@ -1,5 +1,5 @@ import { debug } from '@sentry/core'; -import { _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest } from '@sentry/core/server'; +import { handleServedTunnelRequest } from '@sentry/core/server'; type ServeHandler = (request: Request, info: Deno.ServeHandlerInfo) => Response | Promise; diff --git a/packages/deno/test/contextlines.test.ts b/packages/deno/test/contextlines.test.ts new file mode 100644 index 000000000000..db1a346efa3e --- /dev/null +++ b/packages/deno/test/contextlines.test.ts @@ -0,0 +1,27 @@ +import type { Client, Event } from '@sentry/core'; +import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts'; +import { contextLinesIntegration } from '../build/esm/index.js'; + +Deno.test('does not add an empty line after the last line of a file to the context', async () => { + const filename = new URL(import.meta.url).pathname; + const lines = (await Deno.readTextFile(filename)).split('\n'); + assertEquals(lines[lines.length - 1], ''); + const lastLine = lines.length - 1; + + const event: Event = { + exception: { + values: [{ stacktrace: { frames: [{ filename, lineno: lastLine, colno: 1, in_app: true }] } }], + }, + }; + + const processed = await contextLinesIntegration({ frameContextLines: 2 }).processEvent?.( + event, + {}, + undefined as unknown as Client, + ); + const frame = processed?.exception?.values?.[0]?.stacktrace?.frames?.[0]; + + assertEquals(frame?.pre_context, lines.slice(lastLine - 3, lastLine - 1)); + assertEquals(frame?.context_line, lines[lastLine - 1]); + assertEquals(frame?.post_context, []); +}); diff --git a/packages/deno/test/sdk.test.ts b/packages/deno/test/sdk.test.ts index 9eebad5e6482..1ff0a08d6123 100644 --- a/packages/deno/test/sdk.test.ts +++ b/packages/deno/test/sdk.test.ts @@ -120,3 +120,11 @@ Deno.test('getDefaultIntegrations is getDefaultIntegrationsWithoutPerformance pl assertEquals(full.slice(0, base.length), base); assertArrayIncludes(full.slice(base.length), ['Graphql', 'Postgres', 'OpenAI']); }); + +Deno.test('the default stack parser fills the module of frames', () => { + const client = init({}); + const frames = client + .getOptions() + .stackParser('Error\n at handle (file:///app/node_modules/postgres/src/connection.js:10:5)'); + assertEquals(frames[0]?.module, 'postgres.src:connection'); +}); diff --git a/packages/effect/package.json b/packages/effect/package.json index 3eada774a2bd..409c85fbb33d 100644 --- a/packages/effect/package.json +++ b/packages/effect/package.json @@ -45,7 +45,7 @@ }, "dependencies": { "@sentry/browser": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0" }, diff --git a/packages/effect/src/client/index.ts b/packages/effect/src/client/index.ts index f71634cb0b54..6fda780201be 100644 --- a/packages/effect/src/client/index.ts +++ b/packages/effect/src/client/index.ts @@ -17,28 +17,28 @@ export type EffectClientLayerOptions = BrowserOptions; * On Effect v4 the layer also registers a Sentry `ErrorReporter`, so failures passing through * `Effect.withErrorReporting`, `ErrorReporter.report` or the built-in HTTP and RPC boundaries are captured. * - * To enable Effect tracing, logs, or metrics, compose with the respective layers: - * - `Layer.setTracer(Sentry.SentryEffectTracer)` for tracing - * - `Logger.replace(Logger.defaultLogger, Sentry.SentryEffectLogger)` for logs - * - `Sentry.SentryEffectMetricsLayer` for metrics + * To enable Effect tracing, logs, or metrics, merge the respective layers: + * - `Sentry.layerTracer` for tracing + * - `Sentry.layerLogger` for logs + * - `Sentry.layerMetrics` for metrics * * @example * ```typescript * import * as Sentry from '@sentry/effect/client'; - * import { Layer, Logger, LogLevel } from 'effect'; + * import { Layer } from 'effect'; * - * const SentryLive = Layer.mergeAll( - * Sentry.effectLayer({ + * const SentryLayer = Layer.mergeAll( + * Sentry.layer({ * dsn: '__DSN__', * integrations: [Sentry.browserTracingIntegration()], * tracesSampleRate: 1.0, * }), - * Layer.setTracer(Sentry.SentryEffectTracer), - * Logger.replace(Logger.defaultLogger, Sentry.SentryEffectLogger), + * Sentry.layerTracer, + * Sentry.layerLogger, * ); * ``` */ -export function effectLayer(options: EffectClientLayerOptions): EffectLayer.Layer { +export function layer(options: EffectClientLayerOptions): EffectLayer.Layer { return mergeLayer( suspendLayer(() => { init(options); diff --git a/packages/effect/src/client/tracer.ts b/packages/effect/src/client/tracer.ts index e4313b7fa927..2dc181ac2383 100644 --- a/packages/effect/src/client/tracer.ts +++ b/packages/effect/src/client/tracer.ts @@ -1,5 +1,5 @@ import { startInactiveSpan } from '@sentry/core/browser'; -import { makeSentryTracer } from '../tracer'; +import { makeSentryTracer, makeTracerLayer } from '../tracer'; /** * Effect `Tracer` that records Effect spans as Sentry spans in browser clients. @@ -8,4 +8,9 @@ import { makeSentryTracer } from '../tracer'; * keeps the browser variant substitutable (mocks, bundler interop) exactly as it was when the tracer * called it directly. */ -export const SentryEffectTracer = makeSentryTracer(options => startInactiveSpan(options), false); +export const Tracer = makeSentryTracer(options => startInactiveSpan(options), false); + +/** + * Layer that records Effect spans as Sentry spans in browser clients. + */ +export const layerTracer = makeTracerLayer(Tracer); diff --git a/packages/effect/src/compat.ts b/packages/effect/src/compat.ts index 5e21bbefa360..b600e9e2cec6 100644 --- a/packages/effect/src/compat.ts +++ b/packages/effect/src/compat.ts @@ -1,6 +1,9 @@ import { isObjectLike } from '@sentry/core'; import * as Context from 'effect/Context'; import * as Exit from 'effect/Exit'; +import * as Layer from 'effect/Layer'; +import * as Logger from 'effect/Logger'; +import type * as Tracer from 'effect/Tracer'; // Check if we're running Effect v4 by checking the Exit/Cause structure // In v4, causes have a 'reasons' array @@ -20,12 +23,27 @@ export const isEffectV4 = (() => { })(); interface ContextExports { + /** Effect v3 before 3.11 does not export it. */ Reference: typeof Context.Reference; /** Only Effect v3 exports it. */ GenericTag(key: string): Context.Key; } -// Effect v4 has no `Context.GenericTag` and Effect v3 before 3.11 has no `Context.Reference`. Both are read -// through a separate binding because bundlers fail the build on a namespace member the installed version lacks. -// It is exported so our own build cannot fold a single use back into `Context.`. +interface LayerExports { + /** Only Effect v3 exports it. */ + setTracer(tracer: Tracer.Tracer): Layer.Layer; +} + +interface LoggerExports { + /** Only Effect v4 exports it. */ + layer: typeof Logger.layer; + /** Only Effect v3 exports it. */ + add(logger: Logger.Logger): Layer.Layer; +} + +// Members that only one Effect version exports are read through these bindings, because bundlers fail the +// build on a namespace member the installed version lacks. They are exported so our own build cannot fold a +// single use back into `.`. export const contextExports = Context as unknown as ContextExports; +export const layerExports = Layer as unknown as LayerExports; +export const loggerExports = Logger as unknown as LoggerExports; diff --git a/packages/effect/src/errorReporter.ts b/packages/effect/src/errorReporter.ts index 1ef26e108b02..a2961e681b8a 100644 --- a/packages/effect/src/errorReporter.ts +++ b/packages/effect/src/errorReporter.ts @@ -36,44 +36,45 @@ const SEVERITY_TO_LEVEL = new Map([ ['Trace', 'debug'], ]); -function makeSentryErrorReporter(): EffectErrorReporter.ErrorReporter { - const reported = new WeakSet(); +const reported = new WeakSet(); - return { - [TYPE_ID]: TYPE_ID, - report({ cause }: { readonly cause: Cause.Cause }): void { - if (reported.has(cause)) { - return; - } - reported.add(cause); +/** + * One instance for every Sentry layer, so the reporters set holds it once even when the layer is provided twice. + */ +const sentryErrorReporter: EffectErrorReporter.ErrorReporter = { + [TYPE_ID]: TYPE_ID, + report({ cause }: { readonly cause: Cause.Cause }): void { + if (reported.has(cause)) { + return; + } + reported.add(cause); - for (const reason of cause.reasons) { - if (reason._tag === 'Interrupt') { - continue; - } + for (const reason of cause.reasons) { + if (reason._tag === 'Interrupt') { + continue; + } - // The raw error is captured rather than Effect's pretty-printed copy so Sentry sees the original stack, - // `cause` chain and error class. - const error = reason._tag === 'Fail' ? reason.error : reason.defect; + // The raw error is captured rather than Effect's pretty-printed copy so Sentry sees the original stack, + // `cause` chain and error class. + const error = reason._tag === 'Fail' ? reason.error : reason.defect; - if (isObjectLike(error)) { - if (reported.has(error) || error[IGNORE] === true) { - continue; - } - reported.add(error); + if (isObjectLike(error)) { + if (reported.has(error) || error[IGNORE] === true) { + continue; } - - captureException(error, { - mechanism: { type: 'auto.function.effect.error_reporter', handled: false }, - captureContext: { - level: (isObjectLike(error) && SEVERITY_TO_LEVEL.get(error[SEVERITY])) || 'error', - extra: isObjectLike(error) ? { ...(error[ATTRIBUTES] as Record | undefined) } : undefined, - }, - }); + reported.add(error); } - }, - }; -} + + captureException(error, { + mechanism: { type: 'auto.function.effect.error_reporter', handled: false }, + captureContext: { + level: (isObjectLike(error) && SEVERITY_TO_LEVEL.get(error[SEVERITY])) || 'error', + extra: isObjectLike(error) ? { ...(error[ATTRIBUTES] as Record | undefined) } : undefined, + }, + }); + } + }, +}; /** * Registers a Sentry `ErrorReporter` for `Effect.withErrorReporting`, `ErrorReporter.report` and the @@ -86,8 +87,6 @@ export function makeSentryErrorReporterLayer(): Layer.Layer { return Layer.empty; } - const sentryErrorReporter = makeSentryErrorReporter(); - return Layer.effect( CurrentErrorReporters, Effect.gen(function* () { diff --git a/packages/effect/src/index.client.ts b/packages/effect/src/index.client.ts index 14ad2597abdf..f0a714900319 100644 --- a/packages/effect/src/index.client.ts +++ b/packages/effect/src/index.client.ts @@ -3,10 +3,10 @@ /* eslint-disable import/export */ export * from '@sentry/browser'; -export { effectLayer, init } from './client/index'; +export { layer, init } from './client/index'; export type { EffectClientLayerOptions } from './client/index'; -export { SentryEffectTracer } from './client/tracer'; -export { SentryEffectExternalSpanLayer } from './tracer'; -export { SentryEffectLogger } from './logger'; -export { SentryEffectMetricsLayer } from './metrics'; +export { layerTracer } from './client/tracer'; +export { layerExternalSpan } from './tracer'; +export { layerLogger } from './logger'; +export { layerMetrics } from './metrics'; diff --git a/packages/effect/src/index.server.ts b/packages/effect/src/index.server.ts index 6ceec3346390..636841579179 100644 --- a/packages/effect/src/index.server.ts +++ b/packages/effect/src/index.server.ts @@ -1,9 +1,9 @@ export * from '@sentry/node'; -export { effectLayer, init } from './server/index'; +export { layer, init } from './server/index'; export type { EffectServerLayerOptions } from './server/index'; -export { SentryEffectTracer } from './server/tracer'; -export { SentryEffectExternalSpanLayer } from './tracer'; -export { SentryEffectLogger } from './logger'; -export { SentryEffectMetricsLayer } from './metrics'; +export { layerTracer } from './server/tracer'; +export { layerExternalSpan } from './tracer'; +export { layerLogger } from './logger'; +export { layerMetrics } from './metrics'; diff --git a/packages/effect/src/index.types.ts b/packages/effect/src/index.types.ts index 5502308c1812..7aa58ccdea8d 100644 --- a/packages/effect/src/index.types.ts +++ b/packages/effect/src/index.types.ts @@ -14,7 +14,7 @@ export * from './index.server'; export type { EffectClientLayerOptions } from './index.client'; export type { EffectServerLayerOptions } from './index.server'; -export declare function effectLayer( +export declare function layer( options: clientSdk.EffectClientLayerOptions | serverSdk.EffectServerLayerOptions, ): EffectLayer.Layer; @@ -22,7 +22,7 @@ export declare function init(options: Options | clientSdk.BrowserOptions | serve export declare const linkedErrorsIntegration: typeof clientSdk.linkedErrorsIntegration; export declare const consoleIntegration: typeof serverSdk.consoleIntegration; export declare const contextLinesIntegration: typeof clientSdk.contextLinesIntegration; -export declare const SentryEffectTracer: typeof clientSdk.SentryEffectTracer; +export declare const layerTracer: typeof clientSdk.layerTracer; export declare const startSpan: typeof clientSdk.startSpan; export declare const startSpanManual: typeof clientSdk.startSpanManual; export declare const startInactiveSpan: typeof clientSdk.startInactiveSpan; diff --git a/packages/effect/src/logger.ts b/packages/effect/src/logger.ts index a5fc7fe6923d..77441d3b8818 100644 --- a/packages/effect/src/logger.ts +++ b/packages/effect/src/logger.ts @@ -1,7 +1,9 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { isObjectLike, logger as sentryLogger } from '@sentry/core'; -import * as Logger from 'effect/Logger'; +import type * as Layer from 'effect/Layer'; +import * as EffectLogger from 'effect/Logger'; import type * as LogLevel from 'effect/LogLevel'; +import { isEffectV4, loggerExports } from './compat'; const LOG_ATTRIBUTES = { [SENTRY_ORIGIN]: 'auto.log.effect', @@ -21,10 +23,7 @@ function getLogLevelTag(logLevel: LogLevel.LogLevel): LogLevel.LogLevel | 'Warni return 'Info'; } -/** - * Effect Logger that sends logs to Sentry. - */ -export const SentryEffectLogger = Logger.make(({ logLevel, message }) => { +const effectLogger = EffectLogger.make(({ logLevel, message }) => { let msg: string; if (typeof message === 'string') { msg = message; @@ -64,3 +63,19 @@ export const SentryEffectLogger = Logger.make(({ logLevel, message }) => { tag satisfies never; } }); + +/** + * Layer that sends Effect logs to Sentry. It adds the Sentry logger to the loggers in place, so Effect still logs + * to the console. + * + * Effect v4 builds all layers of a `Layer.mergeAll` from the same loggers, so next to another layer that adds a + * logger, only one of the two loggers stays. Stack such layers with `Layer.provideMerge`: + * + * @example + * ```typescript + * const LoggerLayer = Sentry.layerLogger.pipe(Layer.provideMerge(OtlpLoggerLayer)); + * ``` + */ +export const layerLogger: Layer.Layer = isEffectV4 + ? loggerExports.layer([effectLogger], { mergeWithExisting: true }) + : loggerExports.add(effectLogger); diff --git a/packages/effect/src/metrics.ts b/packages/effect/src/metrics.ts index 764149009be5..edb569bb3cd4 100644 --- a/packages/effect/src/metrics.ts +++ b/packages/effect/src/metrics.ts @@ -180,7 +180,7 @@ function createMetricsReporterEffect(previousCounterValues: Map) * The layer manages its own state for delta counter calculations, * which is automatically cleaned up when the layer is finalized. */ -export const SentryEffectMetricsLayer: Layer.Layer = Layer.effectDiscard( +export const layerMetrics: Layer.Layer = Layer.effectDiscard( Effect.gen(function* () { const previousCounterValues = new Map(); diff --git a/packages/effect/src/server/index.ts b/packages/effect/src/server/index.ts index 06a670b3f2b6..e4fd1e99df13 100644 --- a/packages/effect/src/server/index.ts +++ b/packages/effect/src/server/index.ts @@ -17,29 +17,30 @@ export type EffectServerLayerOptions = NodeOptions; * On Effect v4 the layer also registers a Sentry `ErrorReporter`, so failures passing through * `Effect.withErrorReporting`, `ErrorReporter.report` or the built-in HTTP and RPC boundaries are captured. * - * To enable Effect tracing, logs, or metrics, compose with the respective layers: - * - `Layer.setTracer(Sentry.SentryEffectTracer)` for tracing - * - `Logger.replace(Logger.defaultLogger, Sentry.SentryEffectLogger)` for logs - * - `Sentry.SentryEffectMetricsLayer` for metrics + * To enable Effect tracing, logs, or metrics, merge the respective layers: + * - `Sentry.layerTracer` for tracing + * - `Sentry.layerLogger` for logs + * - `Sentry.layerMetrics` for metrics * * @example * ```typescript * import * as Sentry from '@sentry/effect/server'; * import { NodeRuntime } from '@effect/platform-node'; - * import { Layer, Logger } from 'effect'; - * import { HttpLive } from './Http.js'; + * import { Layer } from 'effect'; + * import { HttpLayer } from './Http.js'; * - * const SentryLive = Layer.mergeAll( - * Sentry.effectLayer({ dsn: '__DSN__' }), - * Layer.setTracer(Sentry.SentryEffectTracer), - * Logger.replace(Logger.defaultLogger, Sentry.SentryEffectLogger), + * const SentryLayer = Layer.mergeAll( + * Sentry.layer({ dsn: '__DSN__', tracesSampleRate: 1.0 }), + * Sentry.layerTracer, + * Sentry.layerLogger, + * Sentry.layerMetrics, * ); * - * const MainLive = HttpLive.pipe(Layer.provide(SentryLive)); - * MainLive.pipe(Layer.launch, NodeRuntime.runMain); + * const MainLayer = HttpLayer.pipe(Layer.provide(SentryLayer)); + * MainLayer.pipe(Layer.launch, NodeRuntime.runMain); * ``` */ -export function effectLayer(options: EffectServerLayerOptions): EffectLayer.Layer { +export function layer(options: EffectServerLayerOptions): EffectLayer.Layer { return mergeLayer( suspendLayer(() => { init(options); diff --git a/packages/effect/src/server/sdk.ts b/packages/effect/src/server/sdk.ts index 9dd6eda8190c..8fd9fb183f20 100644 --- a/packages/effect/src/server/sdk.ts +++ b/packages/effect/src/server/sdk.ts @@ -5,7 +5,7 @@ import { contextLinesIntegration, init as initNode, linkedErrorsIntegration } fr /** * Only the integrations needed to enrich captured errors with source context and `cause` chains. - * Node's auto-instrumentation defaults are left out because `SentryEffectTracer` records Effect's own spans. + * Node's auto-instrumentation defaults are left out because `Tracer` records Effect's own spans. */ export function getDefaultIntegrations(): Integration[] { return [contextLinesIntegration(), linkedErrorsIntegration()]; diff --git a/packages/effect/src/server/tracer.ts b/packages/effect/src/server/tracer.ts index 0814db123343..df76a040bb84 100644 --- a/packages/effect/src/server/tracer.ts +++ b/packages/effect/src/server/tracer.ts @@ -1,5 +1,5 @@ import { startInactiveSpan } from '@sentry/core'; -import { makeSentryTracer } from '../tracer'; +import { makeSentryTracer, makeTracerLayer } from '../tracer'; /** * Effect `Tracer` that records Effect spans as Sentry spans on the server. @@ -14,4 +14,9 @@ import { makeSentryTracer } from '../tracer'; * * See `./client/tracer.ts` for why the call is wrapped in an arrow. */ -export const SentryEffectTracer = makeSentryTracer(options => startInactiveSpan(options), true); +export const Tracer = makeSentryTracer(options => startInactiveSpan(options), true); + +/** + * Layer that records Effect spans as Sentry spans in the server. + */ +export const layerTracer = makeTracerLayer(Tracer); diff --git a/packages/effect/src/tracer.ts b/packages/effect/src/tracer.ts index e53961a85207..8cf22ab33a83 100644 --- a/packages/effect/src/tracer.ts +++ b/packages/effect/src/tracer.ts @@ -20,7 +20,7 @@ import type * as EffectLayer from 'effect/Layer'; import { succeed as succeedLayer } from 'effect/Layer'; import * as Option from 'effect/Option'; import * as EffectTracer from 'effect/Tracer'; -import { contextExports, isEffectV4 } from './compat'; +import { contextExports, isEffectV4, layerExports } from './compat'; const EFFECT_SPAN_SYMBOL = Symbol.for('@sentry/effect.EffectSpan'); @@ -230,10 +230,18 @@ const ExternalSpanFlag = ( /** * Makes the tracer continue the trace of a `Tracer.externalSpan` parent instead of ignoring it. Provide it - * next to the tracer layer to continue every external span in the runtime, or provide it to a single + * next to `layerTracer` to continue every external span in the runtime, or provide it to a single * effect with `Effect.provide` to continue only that one. */ -export const SentryEffectExternalSpanLayer: EffectLayer.Layer = succeedLayer(ExternalSpanFlag, true); +export const layerExternalSpan: EffectLayer.Layer = succeedLayer(ExternalSpanFlag, true); + +/** + * Makes Effect record its spans with `tracer`. Effect v3 reads the tracer from its default services, which a + * `Tracer.Tracer` service does not change, so v3 needs `Layer.setTracer`. + */ +export function makeTracerLayer(tracer: EffectTracer.Tracer): EffectLayer.Layer { + return isEffectV4 ? succeedLayer(EffectTracer.Tracer, tracer) : layerExports.setTracer(tracer); +} interface FiberLike { /** The span the fiber runs in. Only Effect v3 fibers have it. */ @@ -287,7 +295,7 @@ function withFiberContext(fiber: FiberLike, execution: () => X): X { * - A parent this tracer created becomes the Sentry parent. * - Any other parent (`Tracer.externalSpan` bridging a trace this SDK did not start, such as an * OpenTelemetry span of another app in the same process or persisted trace state) is ignored unless - * {@link SentryEffectExternalSpanLayer} is provided, so a span joins a foreign trace only when the user + * {@link layerExternalSpan} is provided, so a span joins a foreign trace only when the user * asked for it. The span then nests where Effect would have put it without the `parent` option: under * the fiber's current span, or parentless. With the layer, the span continues that trace: it is a root * span whose `parent_span_id` is the external span. No dynamic sampling context is frozen, so the SDK @@ -434,7 +442,7 @@ const makeSentryTracerV4 = ( /** * Creates an Effect `Tracer` that records Effect spans as Sentry spans. * - * Use the `SentryEffectTracer` exported from `@sentry/effect` rather than calling this directly — the + * Use the `Tracer` exported from `@sentry/effect` rather than calling this directly — the * client and server entries each bind the right `startInactiveSpan` for their platform. * * `newTraceForRootSpans` is the one behavioural difference between the platforms: Effect gives every diff --git a/packages/effect/test/errorReporter-v3.test.ts b/packages/effect/test/errorReporter-v3.test.ts index 3d90e00be0ca..b965c4bf7f29 100644 --- a/packages/effect/test/errorReporter-v3.test.ts +++ b/packages/effect/test/errorReporter-v3.test.ts @@ -3,7 +3,7 @@ import { Effect, Layer } from 'effect'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import type * as Compat from '../src/compat'; import { makeSentryErrorReporterLayer } from '../src/errorReporter'; -import { effectLayer } from '../src/server/index'; +import * as Sentry from '../src/server/index'; // Effect v3 ships no `ErrorReporter` API. vi.mock('../src/compat', async importOriginal => ({ @@ -20,11 +20,11 @@ describe('Sentry ErrorReporter without the Effect v4 ErrorReporter API', () => { expect(makeSentryErrorReporterLayer()).toBe(Layer.empty); }); - it('still builds the effectLayer', async () => { + it('still builds the Sentry layer', async () => { const result = await Effect.runPromise( Effect.succeed('ok').pipe( Effect.provide( - effectLayer({ + Sentry.layer({ dsn: 'https://username@domain/123', transport: () => ({ send: vi.fn().mockResolvedValue({}), diff --git a/packages/effect/test/errorReporter.test.ts b/packages/effect/test/errorReporter.test.ts index 62e6cb346708..10a1030614bf 100644 --- a/packages/effect/test/errorReporter.test.ts +++ b/packages/effect/test/errorReporter.test.ts @@ -21,206 +21,215 @@ class FatalError extends Data.TaggedError('FatalError')<{ readonly message: stri readonly [ErrorReporter.severity] = 'Fatal' as const; } -describe.each([ - [{ subSdkName: 'browser', effectLayer: sentryClient.effectLayer }], - [{ subSdkName: 'node', effectLayer: sentryServer.effectLayer }], -])('Sentry ErrorReporter ($subSdkName)', ({ effectLayer }) => { - let events: Event[]; - - function makeLayer(): Layer.Layer { - return effectLayer({ - dsn: TEST_DSN, - transport: () => ({ - send: vi.fn().mockResolvedValue({}), - flush: vi.fn().mockResolvedValue(true), - }), - beforeSend: event => { - events.push(event); - return event; - }, +describe.each([[{ subSdkName: 'browser', Sentry: sentryClient }], [{ subSdkName: 'node', Sentry: sentryServer }]])( + 'Sentry ErrorReporter ($subSdkName)', + ({ Sentry }) => { + let events: Event[]; + + function makeLayer(): Layer.Layer { + return Sentry.layer({ + dsn: TEST_DSN, + transport: () => ({ + send: vi.fn().mockResolvedValue({}), + flush: vi.fn().mockResolvedValue(true), + }), + beforeSend: event => { + events.push(event); + return event; + }, + }); + } + + const flush = Effect.promise(() => getClient()!.flush(1000)); + + beforeEach(() => { + events = []; + getMainCarrier().__SENTRY__ = undefined; }); - } - - const flush = Effect.promise(() => getClient()!.flush(1000)); - - beforeEach(() => { - events = []; - getMainCarrier().__SENTRY__ = undefined; - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it.effect('captures Effect.fail errors reported through withErrorReporting', () => - Effect.gen(function* () { - yield* Effect.fail(new Error('Effect failure')).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]).toEqual( - expect.objectContaining({ - level: 'error', - exception: { - values: [ - expect.objectContaining({ - type: 'Error', - value: 'Effect failure', - mechanism: { type: 'auto.function.effect.error_reporter', handled: false }, - stacktrace: expect.objectContaining({ - frames: expect.arrayContaining([expect.objectContaining({ filename: expect.any(String) })]), + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it.effect('captures Effect.fail errors reported through withErrorReporting', () => + Effect.gen(function* () { + yield* Effect.fail(new Error('Effect failure')).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]).toEqual( + expect.objectContaining({ + level: 'error', + exception: { + values: [ + expect.objectContaining({ + type: 'Error', + value: 'Effect failure', + mechanism: { type: 'auto.function.effect.error_reporter', handled: false }, + stacktrace: expect.objectContaining({ + frames: expect.arrayContaining([expect.objectContaining({ filename: expect.any(String) })]), + }), }), - }), - ], - }, - }), - ); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('captures Effect.die defects', () => - Effect.gen(function* () { - yield* Effect.die(new TypeError('Effect defect')).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]).toEqual( - expect.objectContaining({ type: 'TypeError', value: 'Effect defect' }), - ); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('captures non-error values', () => - Effect.gen(function* () { - yield* Effect.die('plain defect').pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]?.value).toBe('plain defect'); - expect(events[0]?.level).toBe('error'); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('captures causes reported with ErrorReporter.report', () => - Effect.gen(function* () { - yield* ErrorReporter.report(Cause.fail(new Error('Manually reported'))); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]?.value).toBe('Manually reported'); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('skips errors annotated with ErrorReporter.ignore', () => - Effect.gen(function* () { - yield* Effect.fail(new IgnoredError({ reason: 'expected' })).pipe(Effect.withErrorReporting, Effect.exit); - yield* Effect.fail(new Error('Sentinel')).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]?.value).toBe('Sentinel'); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('skips interruptions', () => - Effect.gen(function* () { - yield* Effect.interrupt.pipe(Effect.withErrorReporting, Effect.exit); - yield* Effect.fail(new Error('Sentinel')).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]?.value).toBe('Sentinel'); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('maps the severity annotation to the event level', () => - Effect.gen(function* () { - yield* Effect.fail(new RateLimitError({ retryAfter: 60 })).pipe(Effect.withErrorReporting, Effect.exit); - yield* Effect.fail(new FatalError({ message: 'disk gone' })).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(2); - expect( - events.map(event => ({ - type: event.exception?.values?.[0]?.type, - level: event.level, - })), - ).toEqual( - expect.arrayContaining([ - { type: 'RateLimitError', level: 'warning' }, - { type: 'FatalError', level: 'fatal' }, - ]), - ); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('forwards the attributes annotation as extra data', () => - Effect.gen(function* () { - yield* Effect.fail(new RateLimitError({ retryAfter: 60 })).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.extra).toEqual({ retryAfter: 60 }); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('reports the same error only once', () => - Effect.gen(function* () { - const error = new Error('Reported twice'); - yield* Effect.fail(error).pipe(Effect.withErrorReporting, Effect.withErrorReporting, Effect.exit); - yield* Effect.fail(error).pipe(Effect.withErrorReporting, Effect.exit); - yield* flush; - - expect(events).toHaveLength(1); - }).pipe(Effect.provide(makeLayer())), - ); - - it.effect('keeps reporters registered before the Sentry layer', () => - Effect.gen(function* () { - const userReporter = vi.fn(); - - yield* Effect.fail(new Error('Shared failure')).pipe( - Effect.withErrorReporting, - Effect.exit, - Effect.provide(makeLayer().pipe(Layer.provide(ErrorReporter.layer([ErrorReporter.make(userReporter)])))), - ); - yield* flush; - - expect(userReporter).toHaveBeenCalledWith( - expect.objectContaining({ error: expect.objectContaining({ message: 'Shared failure' }) }), - ); - expect(events).toHaveLength(1); - expect(events[0]?.exception?.values?.[0]?.value).toBe('Shared failure'); - }), - ); - - it.effect('attaches the error to the active span', () => - Effect.gen(function* () { - yield* Effect.fail(new Error('Failure in span')).pipe( - Effect.withErrorReporting, - Effect.exit, - Effect.withSpan('failing-operation'), - ); - yield* flush; - - expect(events).toHaveLength(1); - expect(events[0]?.contexts?.trace?.trace_id).toEqual(expect.any(String)); - }).pipe( - Effect.withTracer(sentryServer.SentryEffectTracer), - Effect.provide( - effectLayer({ - dsn: TEST_DSN, - tracesSampleRate: 1, - transport: () => ({ - send: vi.fn().mockResolvedValue({}), - flush: vi.fn().mockResolvedValue(true), + ], + }, }), - beforeSend: event => { - events.push(event); - return event; - }, - }), + ); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('captures Effect.die defects', () => + Effect.gen(function* () { + yield* Effect.die(new TypeError('Effect defect')).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]).toEqual( + expect.objectContaining({ type: 'TypeError', value: 'Effect defect' }), + ); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('captures non-error values', () => + Effect.gen(function* () { + yield* Effect.die('plain defect').pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]?.value).toBe('plain defect'); + expect(events[0]?.level).toBe('error'); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('captures causes reported with ErrorReporter.report', () => + Effect.gen(function* () { + yield* ErrorReporter.report(Cause.fail(new Error('Manually reported'))); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]?.value).toBe('Manually reported'); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('skips errors annotated with ErrorReporter.ignore', () => + Effect.gen(function* () { + yield* Effect.fail(new IgnoredError({ reason: 'expected' })).pipe(Effect.withErrorReporting, Effect.exit); + yield* Effect.fail(new Error('Sentinel')).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]?.value).toBe('Sentinel'); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('skips interruptions', () => + Effect.gen(function* () { + yield* Effect.interrupt.pipe(Effect.withErrorReporting, Effect.exit); + yield* Effect.fail(new Error('Sentinel')).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]?.value).toBe('Sentinel'); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('maps the severity annotation to the event level', () => + Effect.gen(function* () { + yield* Effect.fail(new RateLimitError({ retryAfter: 60 })).pipe(Effect.withErrorReporting, Effect.exit); + yield* Effect.fail(new FatalError({ message: 'disk gone' })).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(2); + expect( + events.map(event => ({ + type: event.exception?.values?.[0]?.type, + level: event.level, + })), + ).toEqual( + expect.arrayContaining([ + { type: 'RateLimitError', level: 'warning' }, + { type: 'FatalError', level: 'fatal' }, + ]), + ); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('forwards the attributes annotation as extra data', () => + Effect.gen(function* () { + yield* Effect.fail(new RateLimitError({ retryAfter: 60 })).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.extra).toEqual({ retryAfter: 60 }); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('reports the same error only once', () => + Effect.gen(function* () { + const error = new Error('Reported twice'); + yield* Effect.fail(error).pipe(Effect.withErrorReporting, Effect.withErrorReporting, Effect.exit); + yield* Effect.fail(error).pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + }).pipe(Effect.provide(makeLayer())), + ); + + it.effect('reports a failure once when the Sentry layer is provided twice', () => + Effect.gen(function* () { + yield* Effect.fail('Provided twice').pipe(Effect.withErrorReporting, Effect.exit); + yield* flush; + + expect(events).toHaveLength(1); + }).pipe(Effect.provide(makeLayer()), Effect.provide(makeLayer())), + ); + + it.effect('keeps reporters registered before the Sentry layer', () => + Effect.gen(function* () { + const userReporter = vi.fn(); + + yield* Effect.fail(new Error('Shared failure')).pipe( + Effect.withErrorReporting, + Effect.exit, + Effect.provide(makeLayer().pipe(Layer.provide(ErrorReporter.layer([ErrorReporter.make(userReporter)])))), + ); + yield* flush; + + expect(userReporter).toHaveBeenCalledWith( + expect.objectContaining({ error: expect.objectContaining({ message: 'Shared failure' }) }), + ); + expect(events).toHaveLength(1); + expect(events[0]?.exception?.values?.[0]?.value).toBe('Shared failure'); + }), + ); + + it.effect('attaches the error to the active span', () => + Effect.gen(function* () { + yield* Effect.fail(new Error('Failure in span')).pipe( + Effect.withErrorReporting, + Effect.exit, + Effect.withSpan('failing-operation'), + ); + yield* flush; + + expect(events).toHaveLength(1); + expect(events[0]?.contexts?.trace?.trace_id).toEqual(expect.any(String)); + }).pipe( + Effect.provide(sentryServer.layerTracer), + Effect.provide( + Sentry.layer({ + dsn: TEST_DSN, + tracesSampleRate: 1, + transport: () => ({ + send: vi.fn().mockResolvedValue({}), + flush: vi.fn().mockResolvedValue(true), + }), + beforeSend: event => { + events.push(event); + return event; + }, + }), + ), ), - ), - ); -}); + ); + }, +); diff --git a/packages/effect/test/layer.test.ts b/packages/effect/test/layer.test.ts index 31493c589d88..2184d3c5775a 100644 --- a/packages/effect/test/layer.test.ts +++ b/packages/effect/test/layer.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from '@effect/vitest'; import * as sentryCore from '@sentry/core'; import * as sentryCoreBrowser from '@sentry/core/browser'; +import type { Log } from '@sentry/core'; import { getClient, getMainCarrier, SDK_VERSION } from '@sentry/core'; -import { Effect, Layer, Logger } from 'effect'; +import { Effect, Layer } from 'effect'; import * as References from 'effect/References'; import { afterEach, beforeEach, vi } from 'vitest'; import * as sentryClient from '../src/index.client'; @@ -21,163 +22,163 @@ describe.each([ [ { subSdkName: 'browser', - effectLayer: sentryClient.effectLayer, - SentryEffectTracer: sentryClient.SentryEffectTracer, - SentryEffectLogger: sentryClient.SentryEffectLogger, - SentryEffectMetricsLayer: sentryClient.SentryEffectMetricsLayer, + Sentry: sentryClient, startInactiveSpan: sentryCoreBrowser as { startInactiveSpan: typeof sentryCore.startInactiveSpan }, }, ], [ { subSdkName: 'node', - effectLayer: sentryServer.effectLayer, - SentryEffectTracer: sentryServer.SentryEffectTracer, - SentryEffectLogger: sentryServer.SentryEffectLogger, - SentryEffectMetricsLayer: sentryServer.SentryEffectMetricsLayer, + Sentry: sentryServer, startInactiveSpan: sentryCore as { startInactiveSpan: typeof sentryCore.startInactiveSpan }, }, ], -])( - 'effectLayer ($subSdkName)', - ({ subSdkName, effectLayer, SentryEffectTracer, SentryEffectLogger, startInactiveSpan }) => { - beforeEach(() => { - getMainCarrier().__SENTRY__ = undefined; - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); +])('layer ($subSdkName)', ({ subSdkName, Sentry, startInactiveSpan }) => { + beforeEach(() => { + getMainCarrier().__SENTRY__ = undefined; + }); - it('creates a valid Effect layer', () => { - const layer = effectLayer({ - dsn: TEST_DSN, - transport: getMockTransport(), - }); + afterEach(() => { + vi.restoreAllMocks(); + }); - expect(layer).toBeDefined(); - expect(Layer.isLayer(layer)).toBe(true); + it('creates a valid Effect layer', () => { + const layer = Sentry.layer({ + dsn: TEST_DSN, + transport: getMockTransport(), }); - it.effect('applies SDK metadata', () => - Effect.gen(function* () { - yield* Effect.void; - - const client = getClient(); - const metadata = client?.getOptions()._metadata?.sdk; - - expect(metadata?.name).toBe('sentry.javascript.effect'); - expect(metadata?.packages).toEqual([ - { name: 'npm:@sentry/effect', version: SDK_VERSION }, - { name: `npm:@sentry/${subSdkName}`, version: SDK_VERSION }, - ]); - }).pipe( - Effect.provide( - effectLayer({ + expect(layer).toBeDefined(); + expect(Layer.isLayer(layer)).toBe(true); + }); + + it.effect('applies SDK metadata', () => + Effect.gen(function* () { + yield* Effect.void; + + const client = getClient(); + const metadata = client?.getOptions()._metadata?.sdk; + + expect(metadata?.name).toBe('sentry.javascript.effect'); + expect(metadata?.packages).toEqual([ + { name: 'npm:@sentry/effect', version: SDK_VERSION }, + { name: `npm:@sentry/${subSdkName}`, version: SDK_VERSION }, + ]); + }).pipe( + Effect.provide( + Sentry.layer({ + dsn: TEST_DSN, + transport: getMockTransport(), + }), + ), + ), + ); + + it.effect('layer can be provided to an Effect program', () => + Effect.gen(function* () { + const result = yield* Effect.succeed('test-result'); + expect(result).toBe('test-result'); + }).pipe( + Effect.provide( + Sentry.layer({ + dsn: TEST_DSN, + transport: getMockTransport(), + }), + ), + ), + ); + + it.effect('layer enables tracing when tracer is set', () => + Effect.gen(function* () { + const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); + + const result = yield* Effect.withSpan('test-span')(Effect.succeed('traced')); + expect(result).toBe('traced'); + expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'test-span' })); + }).pipe( + Effect.provide( + Layer.mergeAll( + Sentry.layer({ dsn: TEST_DSN, transport: getMockTransport(), }), + Sentry.layerTracer, ), ), - ); - - it.effect('layer can be provided to an Effect program', () => - Effect.gen(function* () { - const result = yield* Effect.succeed('test-result'); - expect(result).toBe('test-result'); - }).pipe( - Effect.provide( - effectLayer({ + ), + ); + + it.effect('layer can be composed with tracer', () => + Effect.gen(function* () { + const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); + + const result = yield* Effect.succeed(42).pipe( + Effect.map(n => n * 2), + Effect.withSpan('computation'), + ); + expect(result).toBe(84); + expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'computation' })); + }).pipe( + Effect.provide( + Layer.mergeAll( + Sentry.layer({ dsn: TEST_DSN, transport: getMockTransport(), }), + Sentry.layerTracer, ), ), - ); - - it.effect('layer enables tracing when tracer is set', () => - Effect.gen(function* () { - const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); - - const result = yield* Effect.withSpan('test-span')(Effect.succeed('traced')); - expect(result).toBe('traced'); - expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'test-span' })); - }).pipe( - Effect.withTracer(SentryEffectTracer), - Effect.provide( - effectLayer({ + ), + ); + + it.effect('layer can be composed with logger', () => { + const logs: Log[] = []; + + return Effect.gen(function* () { + yield* Effect.logInfo('test log'); + expect(logs).toEqual([expect.objectContaining({ level: 'info', message: 'test log' })]); + }).pipe( + Effect.provide( + Layer.mergeAll( + Sentry.layer({ dsn: TEST_DSN, + enableLogs: true, + beforeSendLog: log => { + logs.push(log); + return log; + }, transport: getMockTransport(), }), + Sentry.layerLogger, ), ), ); + }); - it.effect('layer can be composed with tracer', () => - Effect.gen(function* () { - const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); - - const result = yield* Effect.succeed(42).pipe( - Effect.map(n => n * 2), - Effect.withSpan('computation'), - ); - expect(result).toBe(84); - expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'computation' })); - }).pipe( - Effect.withTracer(SentryEffectTracer), - Effect.provide( - effectLayer({ + it.effect('layer can be composed with all Effect features', () => + Effect.gen(function* () { + const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); + + yield* Effect.logInfo('starting computation'); + const result = yield* Effect.succeed(42).pipe( + Effect.map(n => n * 2), + Effect.withSpan('computation'), + ); + yield* Effect.logInfo('computation complete'); + expect(result).toBe(84); + expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'computation' })); + }).pipe( + Effect.provideService(References.MinimumLogLevel, 'All'), + Effect.provide( + Layer.mergeAll( + Sentry.layer({ dsn: TEST_DSN, transport: getMockTransport(), }), + Sentry.layerTracer, + Sentry.layerLogger, ), ), - ); - - it.effect('layer can be composed with logger', () => - Effect.gen(function* () { - yield* Effect.logInfo('test log'); - const result = yield* Effect.succeed('logged'); - expect(result).toBe('logged'); - }).pipe( - Effect.provideService(References.MinimumLogLevel, 'All'), - Effect.provide( - Layer.mergeAll( - effectLayer({ - dsn: TEST_DSN, - transport: getMockTransport(), - }), - Logger.layer([SentryEffectLogger]), - ), - ), - ), - ); - - it.effect('layer can be composed with all Effect features', () => - Effect.gen(function* () { - const startInactiveSpanMock = vi.spyOn(startInactiveSpan, 'startInactiveSpan'); - - yield* Effect.logInfo('starting computation'); - const result = yield* Effect.succeed(42).pipe( - Effect.map(n => n * 2), - Effect.withSpan('computation'), - ); - yield* Effect.logInfo('computation complete'); - expect(result).toBe(84); - expect(startInactiveSpanMock).toHaveBeenCalledWith(expect.objectContaining({ name: 'computation' })); - }).pipe( - Effect.withTracer(SentryEffectTracer), - Effect.provideService(References.MinimumLogLevel, 'All'), - Effect.provide( - Layer.mergeAll( - effectLayer({ - dsn: TEST_DSN, - transport: getMockTransport(), - }), - Logger.layer([SentryEffectLogger]), - ), - ), - ), - ); - }, -); + ), + ); +}); diff --git a/packages/effect/test/logger.test.ts b/packages/effect/test/logger.test.ts index 9b17311d195f..a37fd763bc2a 100644 --- a/packages/effect/test/logger.test.ts +++ b/packages/effect/test/logger.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from '@effect/vitest'; import * as sentryCore from '@sentry/core'; -import { Effect, Logger } from 'effect'; +import { Effect, Layer, Logger } from 'effect'; import * as References from 'effect/References'; import { afterEach, vi } from 'vitest'; -import { SentryEffectLogger } from '../src/logger'; +import * as Sentry from '../src/logger'; vi.mock('@sentry/core', async importOriginal => { const original = await importOriginal(); @@ -23,12 +23,12 @@ vi.mock('@sentry/core', async importOriginal => { const LOG_ATTRIBUTES = { 'sentry.origin': 'auto.log.effect' }; -describe('SentryEffectLogger', () => { +describe('Logger', () => { afterEach(() => { vi.clearAllMocks(); }); - const loggerLayer = Logger.layer([SentryEffectLogger]); + const loggerLayer = Sentry.layerLogger.pipe(Layer.provideMerge(Logger.layer([]))); const withAllLogLevels = (effect: Effect.Effect) => Effect.provideService(effect, References.MinimumLogLevel, 'All'); @@ -122,4 +122,23 @@ describe('SentryEffectLogger', () => { } }).pipe(withAllLogLevels, Effect.provide(loggerLayer)), ); + + it.effect('keeps the console logger', () => + Effect.gen(function* () { + const loggers = yield* Effect.service(Logger.CurrentLoggers); + expect(loggers.has(Logger.defaultLogger)).toBe(true); + expect(loggers.has(Logger.tracerLogger)).toBe(true); + }).pipe(Effect.provide(Sentry.layerLogger)), + ); + + it.effect('keeps the logger of the layer it is stacked on', () => { + const messages: unknown[] = []; + const otherLoggerLayer = Logger.layer([Logger.make(({ message }) => messages.push(message))]); + + return Effect.gen(function* () { + yield* Effect.logInfo('Stacked message'); + expect(sentryCore.logger.info).toHaveBeenCalledWith('Stacked message', LOG_ATTRIBUTES); + expect(messages).toEqual([['Stacked message']]); + }).pipe(Effect.provide(Sentry.layerLogger.pipe(Layer.provideMerge(otherLoggerLayer)))); + }); }); diff --git a/packages/effect/test/metrics.test.ts b/packages/effect/test/metrics.test.ts index a8d5a9813fa9..254b453b050d 100644 --- a/packages/effect/test/metrics.test.ts +++ b/packages/effect/test/metrics.test.ts @@ -4,9 +4,9 @@ import * as Context from 'effect/Context'; import { Duration, Effect, Layer, Metric } from 'effect'; import { TestClock } from 'effect/testing'; import { afterEach, beforeEach, vi } from 'vitest'; -import { SentryEffectMetricsLayer } from '../src/metrics'; +import { layerMetrics } from '../src/metrics'; -describe('SentryEffectMetricsLayer', () => { +describe('layerMetrics', () => { const mockCount = vi.fn(); const mockGauge = vi.fn(); const mockDistribution = vi.fn(); @@ -145,7 +145,7 @@ describe('SentryEffectMetricsLayer', () => { ); }); -describe('SentryEffectMetricsLayer flushing', () => { +describe('layerMetrics flushing', () => { const mockCount = vi.fn(); const mockGauge = vi.fn(); const mockDistribution = vi.fn(); @@ -161,7 +161,7 @@ describe('SentryEffectMetricsLayer flushing', () => { vi.restoreAllMocks(); }); - const TestLayer = SentryEffectMetricsLayer.pipe(Layer.provideMerge(TestClock.layer())); + const TestLayer = layerMetrics.pipe(Layer.provideMerge(TestClock.layer())); it.effect('sends counter metrics to Sentry', () => Effect.gen(function* () { diff --git a/packages/effect/test/tracer.test.ts b/packages/effect/test/tracer.test.ts index 7865d134edee..3fb99001276d 100644 --- a/packages/effect/test/tracer.test.ts +++ b/packages/effect/test/tracer.test.ts @@ -7,9 +7,9 @@ import { Effect, Exit } from 'effect'; import { TestClock } from 'effect/testing'; import * as Tracer from 'effect/Tracer'; import { afterEach, beforeEach, vi } from 'vitest'; -import { SentryEffectTracer as clientTracer } from '../src/client/tracer'; -import { SentryEffectTracer as serverTracer } from '../src/server/tracer'; -import { SentryEffectExternalSpanLayer } from '../src/tracer'; +import { Tracer as clientTracer } from '../src/client/tracer'; +import { Tracer as serverTracer } from '../src/server/tracer'; +import { layerExternalSpan } from '../src/tracer'; // The two variants differ only in which module they start spans through, so spying on `spanApi` also // asserts that wiring: the client tracer must go through `@sentry/core/browser` (which installs @@ -35,7 +35,7 @@ function mockSpan(overrides: Record = {}): sentryCore.Span { } as unknown as sentryCore.Span; } -describe.each(VARIANTS)('SentryEffectTracer ($variant)', ({ variant, tracer, spanApi }) => { +describe.each(VARIANTS)('Tracer ($variant)', ({ variant, tracer, spanApi }) => { const withSentryTracer = (effect: Effect.Effect) => Effect.withTracer(effect, tracer); afterEach(() => { @@ -351,7 +351,7 @@ describe.each(VARIANTS)('SentryEffectTracer ($variant)', ({ variant, tracer, spa it('continues the trace of an external parent as a new root span with the external span layer', () => { const parent = Tracer.externalSpan({ traceId, spanId, sampled: true }); const span = run( - Effect.withSpan('reactor', { parent })(currentSentrySpan).pipe(Effect.provide(SentryEffectExternalSpanLayer)), + Effect.withSpan('reactor', { parent })(currentSentrySpan).pipe(Effect.provide(layerExternalSpan)), ); expect(sentryCore.spanToJSON(span)).toMatchObject({ trace_id: traceId, parent_span_id: spanId }); @@ -366,7 +366,7 @@ describe.each(VARIANTS)('SentryEffectTracer ($variant)', ({ variant, tracer, spa it('honors the sampling decision of an external parent', () => { const parent = Tracer.externalSpan({ traceId, spanId, sampled: false }); const span = run( - Effect.withSpan('reactor', { parent })(currentSentrySpan).pipe(Effect.provide(SentryEffectExternalSpanLayer)), + Effect.withSpan('reactor', { parent })(currentSentrySpan).pipe(Effect.provide(layerExternalSpan)), ); expect(sentryCore.spanToJSON(span).trace_id).toBe(traceId); diff --git a/packages/elysia/package.json b/packages/elysia/package.json index 44aba5abacf0..68534abd8cfc 100644 --- a/packages/elysia/package.json +++ b/packages/elysia/package.json @@ -34,7 +34,7 @@ "dependencies": { "@sentry/bun": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0" + "@sentry/conventions": "^0.36.0" }, "peerDependencies": { "elysia": "^1.4.0" diff --git a/packages/ember/.oxlintrc.json b/packages/ember/.oxlintrc.json index d8795cdf8424..80a5ccc9f35a 100644 --- a/packages/ember/.oxlintrc.json +++ b/packages/ember/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true }, diff --git a/packages/ember/package.json b/packages/ember/package.json index 17e0e5c7dfdf..58fef7979537 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.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "decorator-transforms": "^2.3.2" }, diff --git a/packages/eslint-plugin-sdk/src/index.js b/packages/eslint-plugin-sdk/src/index.js index 949edb72dc55..e1f27895b734 100644 --- a/packages/eslint-plugin-sdk/src/index.js +++ b/packages/eslint-plugin-sdk/src/index.js @@ -12,11 +12,13 @@ module.exports = { rules: { 'no-eq-empty': require('./rules/no-eq-empty'), 'no-class-field-initializers': require('./rules/no-class-field-initializers'), + 'no-unguarded-debug-logs': require('./rules/no-unguarded-debug-logs'), 'no-regexp-constructor': require('./rules/no-regexp-constructor'), 'no-focused-tests': require('./rules/no-focused-tests'), 'no-skipped-tests': require('./rules/no-skipped-tests'), 'no-unsafe-random-apis': require('./rules/no-unsafe-random-apis'), 'no-unfiltered-url-attributes': require('./rules/no-unfiltered-url-attributes'), 'no-unguarded-span-apis': require('./rules/no-unguarded-span-apis'), + 'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'), }, }; diff --git a/packages/eslint-plugin-sdk/src/rules/no-unguarded-debug-logs.js b/packages/eslint-plugin-sdk/src/rules/no-unguarded-debug-logs.js new file mode 100644 index 000000000000..0dcd0ce587fb --- /dev/null +++ b/packages/eslint-plugin-sdk/src/rules/no-unguarded-debug-logs.js @@ -0,0 +1,142 @@ +'use strict'; + +/** + * @fileoverview Rule to require a `DEBUG_BUILD` gate on `debug.log` / `debug.warn` / `debug.error` + * calls in code that ships to the browser. + * + * Production bundles replace `DEBUG_BUILD` with `false`, so gated calls are dropped together with + * their message strings. Ungated calls are no-ops at runtime but their strings still ship. + * + * A call counts as gated when it is the right-hand side of `DEBUG_BUILD && ...`, inside the + * consequent of `if (DEBUG_BUILD)` or `DEBUG_BUILD ? ... : ...`, or after an + * `if (!DEBUG_BUILD) return;` in an enclosing block. All of these are removed by minifiers alike. + */ + +const { isBrowserFacing, splitPackagePath } = require('../utils/browser-facing'); + +const GATES = new Set(['DEBUG_BUILD', 'IS_DEBUG_BUILD', '__DEBUG_BUILD__']); + +const LOG_METHODS = new Set(['log', 'warn', 'error']); + +/** `core` is shared with server runtimes, but everything the browser SDK uses comes from it. */ +function isInScope(filename) { + if (isBrowserFacing(filename)) { + return true; + } + const location = splitPackagePath(filename); + return !!location && location.pkg === 'core' && location.path.startsWith('src/'); +} + +/** Whether `test` is truthy only if a gate is, i.e. a gate or a `&&` chain containing one. */ +function isGate(test) { + if (test.type === 'Identifier') { + return GATES.has(test.name); + } + if (test.type === 'LogicalExpression' && test.operator === '&&') { + return isGate(test.left) || isGate(test.right); + } + return false; +} + +/** `if (!DEBUG_BUILD) return;` (or `throw`, or a block of those). */ +function isNegatedGateExit(statement) { + if ( + statement.type !== 'IfStatement' || + statement.alternate || + statement.test.type !== 'UnaryExpression' || + statement.test.operator !== '!' || + !isGate(statement.test.argument) + ) { + return false; + } + const exit = + statement.consequent.type === 'BlockStatement' + ? statement.consequent.body[statement.consequent.body.length - 1] + : statement.consequent; + return !!exit && (exit.type === 'ReturnStatement' || exit.type === 'ThrowStatement'); +} + +function isGuardedBy(parent, child) { + switch (parent.type) { + case 'LogicalExpression': + return parent.operator === '&&' && parent.right === child && isGate(parent.left); + case 'IfStatement': + case 'ConditionalExpression': + return parent.consequent === child && isGate(parent.test); + case 'Program': + case 'BlockStatement': + case 'StaticBlock': + case 'SwitchCase': { + const statements = parent.type === 'SwitchCase' ? parent.consequent : parent.body; + const index = statements.indexOf(child); + return statements.slice(0, index).some(isNegatedGateExit); + } + default: + return false; + } +} + +function isGuarded(node) { + let child = node; + let parent = node.parent; + while (parent) { + if (isGuardedBy(parent, child)) { + return true; + } + child = parent; + parent = parent.parent; + } + return false; +} + +module.exports = { + meta: { + type: 'suggestion', + docs: { + description: 'Require a `DEBUG_BUILD` gate on `debug.*` logging calls in browser-facing code', + category: 'Best Practices', + recommended: true, + }, + fixable: null, + schema: [], + messages: { + unguardedDebugLog: + '`{{callee}}()` must be gated with `DEBUG_BUILD && {{callee}}(...)`. Without the gate its message ships in production bundles.', + }, + }, + create: function (context) { + if (!isInScope(context.getFilename())) { + return {}; + } + + const debugNames = new Set(['debug']); + + return { + ImportSpecifier(node) { + if (node.imported.type === 'Identifier' && node.imported.name === 'debug') { + debugNames.add(node.local.name); + } + }, + CallExpression(node) { + const callee = node.callee; + if ( + callee.type !== 'MemberExpression' || + callee.computed || + callee.object.type !== 'Identifier' || + !debugNames.has(callee.object.name) || + callee.property.type !== 'Identifier' || + !LOG_METHODS.has(callee.property.name) || + isGuarded(node) + ) { + return; + } + + context.report({ + node, + messageId: 'unguardedDebugLog', + data: { callee: `${callee.object.name}.${callee.property.name}` }, + }); + }, + }; + }, +}; diff --git a/packages/eslint-plugin-sdk/src/rules/no-unguarded-span-apis.js b/packages/eslint-plugin-sdk/src/rules/no-unguarded-span-apis.js index fd7c9bda3f30..7263fd01e553 100644 --- a/packages/eslint-plugin-sdk/src/rules/no-unguarded-span-apis.js +++ b/packages/eslint-plugin-sdk/src/rules/no-unguarded-span-apis.js @@ -1,11 +1,11 @@ 'use strict'; /** - * @fileoverview Rule to keep browser-facing code on the `@sentry/core` span-start APIs. + * @fileoverview Rule to keep browser-facing code on the `@sentry/core/browser` span-start APIs. * * `startSpan`, `startInactiveSpan`, `startSpanManual` and `startIdleSpan` exist in two variants * under the same name: the plain ones at `@sentry/core` / `@sentry/core/server`, and guarded ones at - * `@sentry/core` that install `spanStreamingIntegration` on the client before starting the + * `@sentry/core/browser` that install `spanStreamingIntegration` on the client before starting the * span. The browser SDK's `init()` deliberately does not reference that integration - that reference * alone would keep the whole span streaming graph in every bundle, including error-only ones. * @@ -13,72 +13,17 @@ * creates spans that are then never sent. This rule is the only thing that catches it. */ +const { isBrowserFacing } = require('../utils/browser-facing'); + const SPAN_START_APIS = ['startSpan', 'startInactiveSpan', 'startSpanManual', 'startIdleSpan']; const RESTRICTED_SOURCES = ['@sentry/core', '@sentry/core/server']; -/** - * Which parts of which package are browser-facing. - * - * `true` means the package's whole `src` (plus `addon`, for ember) ships to the browser. An array - * lists the paths that do, for packages that also contain server, edge or build-time code - those - * must keep using the plain `@sentry/core` APIs. - */ -const BROWSER_FACING = { - angular: true, - browser: true, - 'browser-utils': true, - ember: true, - feedback: true, - gatsby: true, - react: true, - 'replay-canvas': true, - 'replay-internal': true, - solid: true, - svelte: true, - vue: true, - wasm: true, - - astro: ['src/client'], - effect: ['src/client'], - nextjs: ['src/client'], - nuxt: ['src/client'], - 'react-router': ['src/client'], - remix: ['src/client'], - solidstart: ['src/client'], - sveltekit: ['src/client'], - 'tanstackstart-react': ['src/client'], -}; - -/** Resolve `` and the package-relative path out of a file path. */ -function splitPackagePath(filename) { - const match = /(?:^|\/)packages\/([^/]+)\/(.+)$/.exec(filename.replace(/\\/g, '/')); - return match ? { pkg: match[1], path: match[2] } : undefined; -} - -function isBrowserFacing(filename) { - const location = splitPackagePath(filename); - if (!location) { - return false; - } - - const scope = BROWSER_FACING[location.pkg]; - if (!scope) { - return false; - } - - if (scope === true) { - return location.path.startsWith('src/') || location.path.startsWith('addon/'); - } - - return scope.some(prefix => location.path === prefix || location.path.startsWith(`${prefix}/`)); -} - module.exports = { meta: { type: 'problem', docs: { - description: 'Enforce importing span-start APIs from `@sentry/core` in browser-facing code', + description: 'Enforce importing span-start APIs from `@sentry/core/browser` in browser-facing code', category: 'Possible Errors', recommended: true, }, @@ -86,7 +31,7 @@ module.exports = { schema: [], messages: { unguardedSpanApi: - '`{{name}}` must be imported from `@sentry/core` (or `@sentry/browser`) in browser-facing code. The `{{source}}` variant does not install `spanStreamingIntegration`, so spans it starts are created but never sent.', + '`{{name}}` must be imported from `@sentry/core/browser` (or `@sentry/browser`) in browser-facing code. The `{{source}}` variant does not install `spanStreamingIntegration`, so spans it starts are created but never sent.', }, }, create: function (context) { diff --git a/packages/eslint-plugin-sdk/src/rules/no-unsafe-html-writes.js b/packages/eslint-plugin-sdk/src/rules/no-unsafe-html-writes.js new file mode 100644 index 000000000000..420fce213c27 --- /dev/null +++ b/packages/eslint-plugin-sdk/src/rules/no-unsafe-html-writes.js @@ -0,0 +1,68 @@ +'use strict'; + +/** + * Flags writes that parse a string as HTML: assigning `innerHTML` / `outerHTML`, and calling + * `insertAdjacentHTML()` or `document.write()` / `document.writeln()`. + * The SDK runs inside customer pages, so any of these can turn data into an XSS sink. + * Reading `innerHTML` / `outerHTML` is fine. + */ + +const HTML_PROPERTIES = new Set(['innerHTML', 'outerHTML']); +const DOCUMENT_WRITE_METHODS = new Set(['write', 'writeln']); + +function getPropertyName(node) { + if (!node.computed && node.property.type === 'Identifier') { + return node.property.name; + } + if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string') { + return node.property.value; + } + return undefined; +} + +function isDocument(node) { + if (node.type === 'Identifier') { + return node.name === 'document'; + } + return node.type === 'MemberExpression' && getPropertyName(node) === 'document'; +} + +module.exports = { + meta: { + type: 'problem', + docs: { + description: + 'Disallow writing HTML strings into the DOM (`innerHTML`, `outerHTML`, `insertAdjacentHTML`, `document.write`).', + }, + schema: [], + messages: { + htmlProperty: 'Do not assign `{{name}}`. Build DOM nodes with `createElement` / `textContent` instead.', + htmlMethod: 'Do not call `{{name}}()`. Build DOM nodes with `createElement` / `textContent` instead.', + }, + }, + create(context) { + return { + AssignmentExpression(node) { + if (node.left.type !== 'MemberExpression') { + return; + } + const name = getPropertyName(node.left); + if (name && HTML_PROPERTIES.has(name)) { + context.report({ node, messageId: 'htmlProperty', data: { name } }); + } + }, + CallExpression(node) { + const callee = node.callee; + if (callee.type !== 'MemberExpression') { + return; + } + const name = getPropertyName(callee); + if (name === 'insertAdjacentHTML') { + context.report({ node, messageId: 'htmlMethod', data: { name } }); + } else if (name && DOCUMENT_WRITE_METHODS.has(name) && isDocument(callee.object)) { + context.report({ node, messageId: 'htmlMethod', data: { name: `document.${name}` } }); + } + }, + }; + }, +}; diff --git a/packages/eslint-plugin-sdk/src/utils/browser-facing.js b/packages/eslint-plugin-sdk/src/utils/browser-facing.js new file mode 100644 index 000000000000..0fff74948838 --- /dev/null +++ b/packages/eslint-plugin-sdk/src/utils/browser-facing.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * Which parts of which package are browser-facing. + * + * `true` means the package's whole `src` (plus `addon`, for ember) ships to the browser. An array + * lists the paths that do, for packages that also contain server, edge or build-time code. + * + * `core` is not listed: it is shared with server runtimes, so whether it counts depends on the rule. + */ +const BROWSER_FACING = { + angular: true, + browser: true, + 'browser-utils': true, + ember: true, + feedback: true, + gatsby: true, + react: true, + 'replay-canvas': true, + 'replay-internal': true, + solid: true, + svelte: true, + vue: true, + wasm: true, + + astro: ['src/client'], + effect: ['src/client'], + nextjs: ['src/client'], + nuxt: ['src/client'], + 'react-router': ['src/client'], + remix: ['src/client'], + solidstart: ['src/client'], + sveltekit: ['src/client'], + 'tanstackstart-react': ['src/client'], +}; + +/** Resolve `` and the package-relative path out of a file path. */ +function splitPackagePath(filename) { + const match = /(?:^|\/)packages\/([^/]+)\/(.+)$/.exec(filename.replace(/\\/g, '/')); + return match ? { pkg: match[1], path: match[2] } : undefined; +} + +function isBrowserFacing(filename) { + const location = splitPackagePath(filename); + if (!location) { + return false; + } + + const scope = BROWSER_FACING[location.pkg]; + if (!scope) { + return false; + } + + if (scope === true) { + return location.path.startsWith('src/') || location.path.startsWith('addon/'); + } + + return scope.some(prefix => location.path === prefix || location.path.startsWith(`${prefix}/`)); +} + +module.exports = { splitPackagePath, isBrowserFacing }; diff --git a/packages/eslint-plugin-sdk/test/lib/rules/no-unguarded-debug-logs.test.ts b/packages/eslint-plugin-sdk/test/lib/rules/no-unguarded-debug-logs.test.ts new file mode 100644 index 000000000000..ef50c59d986c --- /dev/null +++ b/packages/eslint-plugin-sdk/test/lib/rules/no-unguarded-debug-logs.test.ts @@ -0,0 +1,87 @@ +import { RuleTester } from 'eslint'; +import { describe, test } from 'vitest'; +// @ts-expect-error untyped module +import rule from '../../../src/rules/no-unguarded-debug-logs'; + +const CORE_FILE = '/repo/packages/core/src/utils/dsn.ts'; +const BROWSER_FILE = '/repo/packages/browser/src/integrations/spotlight.ts'; + +const error = { messageId: 'unguardedDebugLog' }; + +describe('no-unguarded-debug-logs', () => { + test('ruleTester', () => { + const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2022, + sourceType: 'module', + }, + }); + + ruleTester.run('no-unguarded-debug-logs', rule, { + valid: [ + { filename: CORE_FILE, code: "DEBUG_BUILD && debug.log('a');" }, + { filename: CORE_FILE, code: "DEBUG_BUILD && debug.warn('a');" }, + { filename: CORE_FILE, code: "DEBUG_BUILD && debug.error('a');" }, + // Extra conditions on either side of the gate. + { filename: CORE_FILE, code: "DEBUG_BUILD && enabled && debug.log('a');" }, + { filename: CORE_FILE, code: "enabled && DEBUG_BUILD && debug.log('a');" }, + { filename: CORE_FILE, code: "DEBUG_BUILD && (debug.log('a'), debug.warn('b'));" }, + // `if` and ternary gates are removed by minifiers just like `&&`. + { filename: CORE_FILE, code: "if (DEBUG_BUILD) { debug.log('a'); debug.warn('b'); }" }, + { filename: CORE_FILE, code: "if (DEBUG_BUILD && enabled) debug.log('a');" }, + { filename: CORE_FILE, code: "DEBUG_BUILD ? debug.log('a') : undefined;" }, + // A gate on an enclosing scope covers nested callbacks. + { filename: CORE_FILE, code: "if (DEBUG_BUILD) { list.forEach(item => debug.log('a', item)); }" }, + // Early exit at the top of a function. + { filename: CORE_FILE, code: "function f() { if (!DEBUG_BUILD) return; debug.log('a'); }" }, + { filename: CORE_FILE, code: "function f() { if (!DEBUG_BUILD) { return true; } debug.log('a'); }" }, + // Other packages' gate names. + { filename: '/repo/packages/angular/src/sdk.ts', code: "IS_DEBUG_BUILD && debug.warn('a');" }, + { filename: CORE_FILE, code: "__DEBUG_BUILD__ && debug.warn('a');" }, + // Only the logging methods carry message strings. + { filename: CORE_FILE, code: 'debug.enable();' }, + { filename: CORE_FILE, code: 'promise.catch(debug.error);' }, + // Server, edge and build-time code keeps its logs. + { filename: '/repo/packages/node/src/sdk/index.ts', code: "debug.log('a');" }, + { filename: '/repo/packages/nextjs/src/server/index.ts', code: "debug.log('a');" }, + // Tests don't ship. + { filename: '/repo/packages/core/test/lib/dsn.test.ts', code: "debug.log('a');" }, + { filename: '/repo/packages/browser/test/index.test.ts', code: "debug.log('a');" }, + ], + invalid: [ + { filename: CORE_FILE, code: "debug.log('a');", errors: [error] }, + { filename: CORE_FILE, code: "debug.warn('a');", errors: [error] }, + { filename: BROWSER_FILE, code: "debug.error('a');", errors: [error] }, + { filename: '/repo/packages/nextjs/src/client/index.ts', code: "debug.log('a');", errors: [error] }, + { filename: '/repo/packages/ember/addon/index.ts', code: "debug.log('a');", errors: [error] }, + // Only `&&` gates. `||` runs the call when the gate is off. + { filename: CORE_FILE, code: "DEBUG_BUILD || debug.log('a');", errors: [error] }, + { filename: CORE_FILE, code: "(DEBUG_BUILD || enabled) && debug.log('a');", errors: [error] }, + // The `else` branch and the left-hand side are not gated. + { filename: CORE_FILE, code: "if (DEBUG_BUILD) {} else { debug.log('a'); }", errors: [error] }, + { filename: CORE_FILE, code: "DEBUG_BUILD ? undefined : debug.log('a');", errors: [error] }, + { filename: CORE_FILE, code: "debug.log('a') && DEBUG_BUILD;", errors: [error] }, + { filename: CORE_FILE, code: "if (!DEBUG_BUILD) { debug.log('a'); }", errors: [error] }, + // A negated gate only covers what comes after the early exit. + { + filename: CORE_FILE, + code: "function f() { debug.log('a'); if (!DEBUG_BUILD) return; }", + errors: [error], + }, + { + filename: CORE_FILE, + code: "function f() { if (!DEBUG_BUILD) { cleanup(); } debug.log('a'); }", + errors: [error], + }, + // An unrelated gate isn't enough. + { filename: CORE_FILE, code: "enabled && debug.log('a');", errors: [error] }, + // Aliased imports of `debug`. + { + filename: BROWSER_FILE, + code: "import { debug as coreDebug } from '@sentry/core'; coreDebug.log('a');", + errors: [error], + }, + ], + }); + }); +}); diff --git a/packages/eslint-plugin-sdk/test/lib/rules/no-unsafe-html-writes.test.ts b/packages/eslint-plugin-sdk/test/lib/rules/no-unsafe-html-writes.test.ts new file mode 100644 index 000000000000..b577f8fd10d8 --- /dev/null +++ b/packages/eslint-plugin-sdk/test/lib/rules/no-unsafe-html-writes.test.ts @@ -0,0 +1,51 @@ +import { RuleTester } from 'eslint'; +import { describe, test } from 'vitest'; +// @ts-expect-error untyped module +import rule from '../../../src/rules/no-unsafe-html-writes'; + +describe('no-unsafe-html-writes', () => { + test('ruleTester', () => { + const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2020, + }, + }); + + ruleTester.run('no-unsafe-html-writes', rule, { + valid: [ + { code: 'const html = document.documentElement.innerHTML;' }, + { code: 'if (el.outerHTML) { use(el.outerHTML); }' }, + { code: 'el.textContent = value;' }, + { code: "const tag = { tagName: 'script', innerHTML: code };" }, + { code: 'stream.write(chunk);' }, + { code: 'el[key] = value;' }, + ], + invalid: [ + { + code: 'el.innerHTML = value;', + errors: [{ messageId: 'htmlProperty', data: { name: 'innerHTML' } }], + }, + { + code: 'el.innerHTML += value;', + errors: [{ messageId: 'htmlProperty', data: { name: 'innerHTML' } }], + }, + { + code: "el['outerHTML'] = value;", + errors: [{ messageId: 'htmlProperty', data: { name: 'outerHTML' } }], + }, + { + code: "el.insertAdjacentHTML('beforeend', value);", + errors: [{ messageId: 'htmlMethod', data: { name: 'insertAdjacentHTML' } }], + }, + { + code: 'document.write(value);', + errors: [{ messageId: 'htmlMethod', data: { name: 'document.write' } }], + }, + { + code: 'WINDOW.document.writeln(value);', + errors: [{ messageId: 'htmlMethod', data: { name: 'document.writeln' } }], + }, + ], + }); + }); +}); diff --git a/packages/feedback/.oxlintrc.json b/packages/feedback/.oxlintrc.json index 4cd4930fa802..c996f1bd946a 100644 --- a/packages/feedback/.oxlintrc.json +++ b/packages/feedback/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"] + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"] } diff --git a/packages/feedback/src/core/components/Actor.css.ts b/packages/feedback/src/core/components/Actor.styles.ts similarity index 100% rename from packages/feedback/src/core/components/Actor.css.ts rename to packages/feedback/src/core/components/Actor.styles.ts diff --git a/packages/feedback/src/core/components/Actor.ts b/packages/feedback/src/core/components/Actor.ts index ba90e9e116ec..225248a3c6aa 100644 --- a/packages/feedback/src/core/components/Actor.ts +++ b/packages/feedback/src/core/components/Actor.ts @@ -1,5 +1,5 @@ import { DOCUMENT, TRIGGER_LABEL } from '../../constants'; -import { createActorStyles } from './Actor.css'; +import { createActorStyles } from './Actor.styles'; import { FeedbackIcon } from './FeedbackIcon'; export interface ActorProps { diff --git a/packages/feedback/src/modal/components/Dialog.css.ts b/packages/feedback/src/modal/components/Dialog.styles.ts similarity index 100% rename from packages/feedback/src/modal/components/Dialog.css.ts rename to packages/feedback/src/modal/components/Dialog.styles.ts diff --git a/packages/feedback/src/modal/components/Dialog.tsx b/packages/feedback/src/modal/components/Dialog.tsx index 1edec67bc374..082d30825d1d 100644 --- a/packages/feedback/src/modal/components/Dialog.tsx +++ b/packages/feedback/src/modal/components/Dialog.tsx @@ -1,7 +1,7 @@ import type { FeedbackFormData, FeedbackInternalOptions } from '@sentry/core'; import type { VNode } from 'preact'; import { Fragment, h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars -import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks'; +import { useCallback, useLayoutEffect, useRef, useState } from 'preact/hooks'; import { SUCCESS_MESSAGE_TIMEOUT } from '../../constants'; import type { Props as HeaderProps } from './DialogHeader'; import { DialogHeader } from './DialogHeader'; @@ -17,7 +17,6 @@ interface Props extends HeaderProps, FormProps { export function Dialog({ open, onFormSubmitted, ...props }: Props): VNode { const options = props.options; - const successIconHtml = useMemo(() => ({ __html: SuccessIcon().outerHTML }), []); const [timeoutId, setTimeoutId] = useState(null); const dialogRef = useRef(null); @@ -78,7 +77,9 @@ export function Dialog({ open, onFormSubmitted, ...props }: Props): VNode {
{options.successMessageText} - + + +
) : ( diff --git a/packages/feedback/src/modal/components/DialogHeader.tsx b/packages/feedback/src/modal/components/DialogHeader.tsx index 8820b91d8a3a..9dfdcca83c76 100644 --- a/packages/feedback/src/modal/components/DialogHeader.tsx +++ b/packages/feedback/src/modal/components/DialogHeader.tsx @@ -1,7 +1,6 @@ import type { FeedbackInternalOptions } from '@sentry/core'; import type { VNode } from 'preact'; import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused-vars -import { useMemo } from 'preact/hooks'; import { SentryLogo } from './SentryLogo'; export interface Props { @@ -9,8 +8,6 @@ export interface Props { } export function DialogHeader({ options }: Props): VNode { - const logoHtml = useMemo(() => ({ __html: SentryLogo().outerHTML }), []); - return (

{options.formTitle} @@ -21,8 +18,9 @@ export function DialogHeader({ options }: Props): VNode { href="https://sentry.io/welcome/" title="Powered by Sentry" rel="noopener noreferrer" - dangerouslySetInnerHTML={logoHtml} - /> + > + + ) : null}

); diff --git a/packages/feedback/src/modal/components/SentryLogo.ts b/packages/feedback/src/modal/components/SentryLogo.ts deleted file mode 100644 index 8a3c338d341e..000000000000 --- a/packages/feedback/src/modal/components/SentryLogo.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { DOCUMENT } from '../../constants'; -import { setAttributesNS } from '../../util/setAttributesNS'; - -const XMLNS = 'http://www.w3.org/2000/svg'; - -/** - * Sentry Logo - */ -export function SentryLogo(): SVGElement { - const createElementNS = (tagName: K): SVGElementTagNameMap[K] => - DOCUMENT.createElementNS(XMLNS, tagName); - const svg = setAttributesNS(createElementNS('svg'), { - width: '32', - height: '30', - viewBox: '0 0 72 66', - fill: 'inherit', - }); - - const path = setAttributesNS(createElementNS('path'), { - transform: 'translate(11, 11)', - d: 'M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z', - }); - svg.appendChild(path); - - return svg; -} diff --git a/packages/feedback/src/modal/components/SentryLogo.tsx b/packages/feedback/src/modal/components/SentryLogo.tsx new file mode 100644 index 000000000000..1145429a6281 --- /dev/null +++ b/packages/feedback/src/modal/components/SentryLogo.tsx @@ -0,0 +1,16 @@ +import type { VNode } from 'preact'; +import { h } from 'preact'; + +/** + * Sentry Logo + */ +export function SentryLogo(): VNode { + return ( + + + + ); +} diff --git a/packages/feedback/src/modal/components/SuccessIcon.ts b/packages/feedback/src/modal/components/SuccessIcon.ts deleted file mode 100644 index fe76c6d0ecfa..000000000000 --- a/packages/feedback/src/modal/components/SuccessIcon.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { WINDOW } from '../../constants'; -import { setAttributesNS } from '../../util/setAttributesNS'; - -const WIDTH = 16; -const HEIGHT = 17; -const XMLNS = 'http://www.w3.org/2000/svg'; - -/** - * Success Icon (checkmark) - */ -export function SuccessIcon(): SVGElement { - const createElementNS = (tagName: K): SVGElementTagNameMap[K] => - WINDOW.document.createElementNS(XMLNS, tagName); - const svg = setAttributesNS(createElementNS('svg'), { - width: `${WIDTH}`, - height: `${HEIGHT}`, - viewBox: `0 0 ${WIDTH} ${HEIGHT}`, - fill: 'inherit', - }); - - const g = setAttributesNS(createElementNS('g'), { - clipPath: 'url(#clip0_57_156)', - }); - - const path2 = setAttributesNS(createElementNS('path'), { - ['fill-rule']: 'evenodd', - ['clip-rule']: 'evenodd', - d: 'M3.55544 15.1518C4.87103 16.0308 6.41775 16.5 8 16.5C10.1217 16.5 12.1566 15.6571 13.6569 14.1569C15.1571 12.6566 16 10.6217 16 8.5C16 6.91775 15.5308 5.37103 14.6518 4.05544C13.7727 2.73985 12.5233 1.71447 11.0615 1.10897C9.59966 0.503466 7.99113 0.34504 6.43928 0.653721C4.88743 0.962403 3.46197 1.72433 2.34315 2.84315C1.22433 3.96197 0.462403 5.38743 0.153721 6.93928C-0.15496 8.49113 0.00346625 10.0997 0.608967 11.5615C1.21447 13.0233 2.23985 14.2727 3.55544 15.1518ZM4.40546 3.1204C5.46945 2.40946 6.72036 2.03 8 2.03C9.71595 2.03 11.3616 2.71166 12.575 3.92502C13.7883 5.13838 14.47 6.78405 14.47 8.5C14.47 9.77965 14.0905 11.0306 13.3796 12.0945C12.6687 13.1585 11.6582 13.9878 10.476 14.4775C9.29373 14.9672 7.99283 15.0953 6.73777 14.8457C5.48271 14.596 4.32987 13.9798 3.42502 13.075C2.52018 12.1701 1.90397 11.0173 1.65432 9.76224C1.40468 8.50718 1.5328 7.20628 2.0225 6.02404C2.5122 4.8418 3.34148 3.83133 4.40546 3.1204Z', - }); - const path = setAttributesNS(createElementNS('path'), { - d: 'M6.68775 12.4297C6.78586 12.4745 6.89218 12.4984 7 12.5C7.11275 12.4955 7.22315 12.4664 7.32337 12.4145C7.4236 12.3627 7.51121 12.2894 7.58 12.2L12 5.63999C12.0848 5.47724 12.1071 5.28902 12.0625 5.11098C12.0178 4.93294 11.9095 4.77744 11.7579 4.67392C11.6064 4.57041 11.4221 4.52608 11.24 4.54931C11.0579 4.57254 10.8907 4.66173 10.77 4.79999L6.88 10.57L5.13 8.56999C5.06508 8.49566 4.98613 8.43488 4.89768 8.39111C4.80922 8.34735 4.713 8.32148 4.61453 8.31498C4.51605 8.30847 4.41727 8.32147 4.32382 8.35322C4.23038 8.38497 4.14413 8.43484 4.07 8.49999C3.92511 8.63217 3.83692 8.81523 3.82387 9.01092C3.81083 9.2066 3.87393 9.39976 4 9.54999L6.43 12.24C6.50187 12.3204 6.58964 12.385 6.68775 12.4297Z', - }); - - svg.appendChild(g).append(path, path2); - - const speakerDefs = createElementNS('defs'); - const speakerClipPathDef = setAttributesNS(createElementNS('clipPath'), { - id: 'clip0_57_156', - }); - - const speakerRect = setAttributesNS(createElementNS('rect'), { - width: `${WIDTH}`, - height: `${WIDTH}`, - fill: 'white', - transform: 'translate(0 0.5)', - }); - - speakerClipPathDef.appendChild(speakerRect); - speakerDefs.appendChild(speakerClipPathDef); - - svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect); - - return svg; -} diff --git a/packages/feedback/src/modal/components/SuccessIcon.tsx b/packages/feedback/src/modal/components/SuccessIcon.tsx new file mode 100644 index 000000000000..67c5b5bd3cef --- /dev/null +++ b/packages/feedback/src/modal/components/SuccessIcon.tsx @@ -0,0 +1,18 @@ +import type { VNode } from 'preact'; +import { h } from 'preact'; + +/** + * Success Icon (checkmark) + */ +export function SuccessIcon(): VNode { + return ( + + + + + ); +} diff --git a/packages/feedback/src/modal/integration.tsx b/packages/feedback/src/modal/integration.tsx index d9c00e8093b4..d424cd1de813 100644 --- a/packages/feedback/src/modal/integration.tsx +++ b/packages/feedback/src/modal/integration.tsx @@ -4,7 +4,7 @@ import { h, render } from 'preact'; import * as hooks from 'preact/hooks'; import { DOCUMENT } from '../constants'; import { Dialog } from './components/Dialog'; -import { createDialogStyles } from './components/Dialog.css'; +import { createDialogStyles } from './components/Dialog.styles'; function getUser(): User | undefined { const currentUser = getCurrentScope().getUser(); diff --git a/packages/feedback/src/screenshot/components/ScreenshotEditor.tsx b/packages/feedback/src/screenshot/components/ScreenshotEditor.tsx index 414250dbf4a0..f23402843c8d 100644 --- a/packages/feedback/src/screenshot/components/ScreenshotEditor.tsx +++ b/packages/feedback/src/screenshot/components/ScreenshotEditor.tsx @@ -4,7 +4,7 @@ import { h } from 'preact'; // eslint-disable-line @typescript-eslint/no-unused- import type * as Hooks from 'preact/hooks'; import { DOCUMENT, WINDOW } from '../../constants'; import IconCloseFactory from './IconClose'; -import { createScreenshotInputStyles } from './ScreenshotInput.css'; +import { createScreenshotInputStyles } from './ScreenshotInput.styles'; import ToolbarFactory from './Toolbar'; import { useTakeScreenshotFactory } from './useTakeScreenshot'; @@ -123,7 +123,7 @@ export function ScreenshotEditorFactory({ const useTakeScreenshot = useTakeScreenshotFactory({ hooks }); const Toolbar = ToolbarFactory({ h }); const IconClose = IconCloseFactory({ h }); - const editorStyleInnerText = { __html: createScreenshotInputStyles(options.styleNonce).innerText }; + const editorStyles = createScreenshotInputStyles(options.styleNonce).textContent; const dialogStyle = (dialog.el as HTMLElement).style; @@ -294,7 +294,7 @@ export function ScreenshotEditorFactory({ return (
-
diff --git a/packages/feedback/src/screenshot/components/ScreenshotInput.css.ts b/packages/feedback/src/screenshot/components/ScreenshotInput.styles.ts similarity index 100% rename from packages/feedback/src/screenshot/components/ScreenshotInput.css.ts rename to packages/feedback/src/screenshot/components/ScreenshotInput.styles.ts diff --git a/packages/gatsby/.oxlintrc.json b/packages/gatsby/.oxlintrc.json index 82e1187d7863..a29954e1aa0b 100644 --- a/packages/gatsby/.oxlintrc.json +++ b/packages/gatsby/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true, "node": true diff --git a/packages/gatsby/gatsby-node.js b/packages/gatsby/gatsby-node.js index f6fb559f68d8..cb09716f4960 100644 --- a/packages/gatsby/gatsby-node.js +++ b/packages/gatsby/gatsby-node.js @@ -1,28 +1,60 @@ const fs = require('fs'); +const { hasSourceMapUploadCredentials } = require('@sentry/bundler-plugins/core'); const { sentryWebpackPlugin } = require('@sentry/bundler-plugins/webpack'); +const { consoleSandbox, resolveSourceMapsFeatures } = require('@sentry/core'); const SENTRY_USER_CONFIG = ['./sentry.config.js', './sentry.config.ts']; -exports.onCreateWebpackConfig = ({ getConfig, actions }, options) => { +// Gatsby calls `onCreateWebpackConfig` once per build stage. +let warnedAboutDeleteOptions = false; + +exports.onCreateWebpackConfig = ({ getConfig, actions, stage }, options) => { const enableClientWebpackPlugin = options.enableClientWebpackPlugin !== false; if (process.env.NODE_ENV === 'production' && enableClientWebpackPlugin) { const prevSourceMapSetting = getConfig() && 'devtool' in getConfig() ? getConfig().devtool : undefined; + const { injectDebugIds, upload } = resolveSourceMapsFeatures(options.sourcemaps); + // `sourcemaps.delete` replaces the flat `deleteSourcemapsAfterUpload`. + const deleteOption = options.sourcemaps?.delete ?? options.deleteSourcemapsAfterUpload; + if ( + options.sourcemaps?.delete !== undefined && + options.deleteSourcemapsAfterUpload !== undefined && + !warnedAboutDeleteOptions + ) { + warnedAboutDeleteOptions = true; + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn( + '[Sentry] `deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set. Please remove `deleteSourcemapsAfterUpload`.', + ); + }); + } + // Sentry turns source maps on to upload them, or when `sourcemaps.delete: false` keeps them for a manual upload. + // The plugin gets no credentials from these options, only from the environment. const shouldAutomaticallyEnableSourceMaps = - prevSourceMapSetting !== 'source-map' && prevSourceMapSetting !== 'hidden-source-map'; + prevSourceMapSetting !== 'source-map' && + prevSourceMapSetting !== 'hidden-source-map' && + ((upload && hasSourceMapUploadCredentials(undefined)) || + (options.sourcemaps?.delete === false && injectDebugIds)); + + // Gatsby reads the `build-html` maps in `.cache` to map HTML render errors. The plugin does not + // get `sourcemaps.delete` itself, because it would also remove those. + const deleteSourcemapsAfterUpload = + stage === 'build-javascript' && (deleteOption || (deleteOption !== false && shouldAutomaticallyEnableSourceMaps)) + ? true + : undefined; if (shouldAutomaticallyEnableSourceMaps) { // eslint-disable-next-line no-console console.log( - '[Sentry] Automatically enabling source map generation by setting `devtool: "hidden-source-map"`. Those source maps will be deleted after they were uploaded to Sentry', + `[Sentry] Automatically enabling source map generation by setting \`devtool: "hidden-source-map"\`. ${ + deleteSourcemapsAfterUpload + ? 'Those source maps will be deleted after they were uploaded to Sentry' + : 'Those source maps stay in the build output' + }`, ); } - // Delete source maps per default or when this is explicitly set to `true` (`deleteSourceMapsAfterUpload: true` can override the default behavior) - const deleteSourcemapsAfterUpload = - options.deleteSourcemapsAfterUpload || - (options.deleteSourcemapsAfterUpload !== false && shouldAutomaticallyEnableSourceMaps); - actions.setWebpackConfig({ devtool: shouldAutomaticallyEnableSourceMaps ? 'hidden-source-map' : prevSourceMapSetting, plugins: [ @@ -30,8 +62,11 @@ exports.onCreateWebpackConfig = ({ getConfig, actions }, options) => { sourcemaps: { // Only include files from the build output directory assets: ['./public/**'], - // Delete source files after uploading - filesToDeleteAfterUpload: deleteSourcemapsAfterUpload ? ['./public/**/*.map'] : undefined, + upload: options.sourcemaps?.upload, + injectDebugIds: options.sourcemaps?.injectDebugIds, + deleteSourcemapsAfterUpload, + // Also removes CSS maps and maps of chunks that are not uploaded. + sdkEnabledSourceMaps: deleteSourcemapsAfterUpload, // Ignore files that aren't users' source code related ignore: [ 'polyfill-*', // related to polyfills diff --git a/packages/gatsby/test/gatsby-node.test.ts b/packages/gatsby/test/gatsby-node.test.ts index cb1a8f406b33..ae2e769f3fc9 100644 --- a/packages/gatsby/test/gatsby-node.test.ts +++ b/packages/gatsby/test/gatsby-node.test.ts @@ -106,122 +106,219 @@ describe('onCreateWebpackConfig', () => { }); }); - describe('delete source maps after upload', () => { + describe('source maps', () => { beforeEach(() => { - vi.clearAllMocks(); + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); }); - const actions = { - setWebpackConfig: vi.fn(), - }; - - const getConfig = vi.fn(); - - it('sets sourceMapFilesToDeleteAfterUpload when provided in options', () => { - const actions = { - setWebpackConfig: vi.fn(), - }; - - const getConfig = vi.fn().mockReturnValue({ devtool: 'source-map' }); + afterEach(() => { + vi.unstubAllEnvs(); + }); - onCreateWebpackConfig({ actions, getConfig }, { deleteSourcemapsAfterUpload: true }); + it.each([ + [{}, undefined], + [{ sourcemaps: { delete: false } }, 'hidden-source-map'], + ])('without upload credentials, with the options %j it sets devtool %s', (options, devtool) => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + const actions = { setWebpackConfig: vi.fn() }; - expect(actions.setWebpackConfig).toHaveBeenCalledTimes(1); + onCreateWebpackConfig({ actions, getConfig: () => ({}), stage: 'build-javascript' }, options); - expect(sentryWebpackPlugin).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: ['./public/**/*.map'], - }), - }), - ); + expect(actions.setWebpackConfig).toHaveBeenCalledWith(expect.objectContaining({ devtool })); }); it.each([ { - name: 'without provided options: sets hidden source maps and deletes source maps', + name: 'build-javascript, devtool unset: enables hidden source maps and passes delete options', + stage: 'build-javascript', initialConfig: undefined, options: {}, - expected: { - devtool: 'hidden-source-map', - deleteSourceMaps: true, - }, + expected: { devtool: 'hidden-source-map', deleteOptions: true }, }, { - name: "preserves enabled source-map and doesn't delete", - initialConfig: { devtool: 'source-map' }, + name: 'build-javascript, devtool false: enables hidden source maps and passes delete options', + stage: 'build-javascript', + initialConfig: { devtool: false }, options: {}, - expected: { - devtool: 'source-map', - deleteSourceMaps: false, - }, + expected: { devtool: 'hidden-source-map', deleteOptions: true }, }, { - name: "preserves enabled hidden-source-map and doesn't delete", - initialConfig: { devtool: 'hidden-source-map' }, + name: 'build-javascript, devtool eval: enables hidden source maps and passes delete options', + stage: 'build-javascript', + initialConfig: { devtool: 'eval' }, options: {}, - expected: { - devtool: 'hidden-source-map', - deleteSourceMaps: false, - }, + expected: { devtool: 'hidden-source-map', deleteOptions: true }, }, { - name: 'deletes source maps, when user explicitly sets it', - initialConfig: { devtool: 'eval' }, + name: 'build-javascript, source-map: keeps it and passes no delete options', + stage: 'build-javascript', + initialConfig: { devtool: 'source-map' }, options: {}, - expected: { - devtool: 'hidden-source-map', - deleteSourceMaps: true, - }, + expected: { devtool: 'source-map', deleteOptions: undefined }, }, { - name: 'replaces disabled source maps with hidden ones and deletes them', - initialConfig: { devtool: false }, + name: 'build-javascript, hidden-source-map: keeps it and passes no delete options', + stage: 'build-javascript', + initialConfig: { devtool: 'hidden-source-map' }, options: {}, - expected: { - devtool: 'hidden-source-map', - deleteSourceMaps: true, - }, + expected: { devtool: 'hidden-source-map', deleteOptions: undefined }, }, { - name: 'explicit deleteSourcemapsAfterUpload true', + name: 'build-javascript, devtool false, user false: enables hidden source maps and passes no delete options', + stage: 'build-javascript', + initialConfig: { devtool: false }, + options: { deleteSourcemapsAfterUpload: false }, + expected: { devtool: 'hidden-source-map', deleteOptions: undefined }, + }, + { + name: 'build-javascript, source-map, user true: passes delete options', + stage: 'build-javascript', initialConfig: { devtool: 'source-map' }, options: { deleteSourcemapsAfterUpload: true }, - expected: { - devtool: 'source-map', - deleteSourceMaps: true, - }, + expected: { devtool: 'source-map', deleteOptions: true }, }, { - name: 'explicit deleteSourcemapsAfterUpload false', + name: 'build-javascript, hidden-source-map, user true: passes delete options', + stage: 'build-javascript', + initialConfig: { devtool: 'hidden-source-map' }, + options: { deleteSourcemapsAfterUpload: true }, + expected: { devtool: 'hidden-source-map', deleteOptions: true }, + }, + { + name: 'build-javascript, source-map, user truthy value: passes delete options as true', + stage: 'build-javascript', + initialConfig: { devtool: 'source-map' }, + options: { deleteSourcemapsAfterUpload: 'true' }, + expected: { devtool: 'source-map', deleteOptions: true }, + }, + { + name: 'build-javascript, hidden-source-map, user false: passes no delete options', + stage: 'build-javascript', initialConfig: { devtool: 'hidden-source-map' }, options: { deleteSourcemapsAfterUpload: false }, - expected: { - devtool: 'hidden-source-map', - deleteSourceMaps: false, - }, + expected: { devtool: 'hidden-source-map', deleteOptions: undefined }, }, - ])('$name', ({ initialConfig, options, expected }) => { - getConfig.mockReturnValue(initialConfig); + { + name: 'build-html, devtool false: enables hidden source maps and passes no delete options', + stage: 'build-html', + initialConfig: { devtool: false }, + options: {}, + expected: { devtool: 'hidden-source-map', deleteOptions: undefined }, + }, + { + name: 'build-html, source-map, user true: passes no delete options', + stage: 'build-html', + initialConfig: { devtool: 'source-map' }, + options: { deleteSourcemapsAfterUpload: true }, + expected: { devtool: 'source-map', deleteOptions: undefined }, + }, + ])('$name', ({ stage, initialConfig, options, expected }) => { + const actions = { setWebpackConfig: vi.fn() }; + const getConfig = vi.fn().mockReturnValue(initialConfig); - onCreateWebpackConfig({ actions: actions, getConfig: getConfig }, options); + onCreateWebpackConfig({ actions, getConfig, stage }, options); expect(actions.setWebpackConfig).toHaveBeenCalledTimes(1); - - expect(actions.setWebpackConfig).toHaveBeenCalledWith( + expect(actions.setWebpackConfig).toHaveBeenCalledWith({ + devtool: expected.devtool, + plugins: [expect.any(Object)], + }); + expect(sentryWebpackPlugin).toHaveBeenCalledWith( expect.objectContaining({ - devtool: expected.devtool, - plugins: expect.arrayContaining([expect.any(Object)]), + sourcemaps: { + assets: ['./public/**'], + deleteSourcemapsAfterUpload: expected.deleteOptions, + sdkEnabledSourceMaps: expected.deleteOptions, + ignore: ['polyfill-*', 'framework-*', 'webpack-runtime-*'], + }, }), ); + }); - expect(sentryWebpackPlugin).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ - assets: ['./public/**'], - filesToDeleteAfterUpload: expected.deleteSourceMaps ? ['./public/**/*.map'] : undefined, + // Each row: the stage, the `devtool` Gatsby hands over, the `sourcemaps` options, the `devtool` + // of the final config, and whether the plugin removes every source map of the stage. + it.each([ + ['build-javascript', undefined, { upload: false }, undefined, undefined], + ['build-javascript', false, { injectDebugIds: false }, false, undefined], + ['build-javascript', 'source-map', { upload: false }, 'source-map', undefined], + ['build-javascript', undefined, { upload: false, delete: false }, 'hidden-source-map', undefined], + ['build-javascript', undefined, { injectDebugIds: false, delete: false }, undefined, undefined], + ['build-javascript', 'source-map', { upload: false, delete: true }, 'source-map', true], + ['build-javascript', undefined, { delete: false }, 'hidden-source-map', undefined], + ['build-javascript', 'source-map', { delete: true }, 'source-map', true], + ['build-javascript', undefined, { delete: true }, 'hidden-source-map', true], + ['build-html', 'source-map', { delete: true }, 'source-map', undefined], + ] as const)( + '%s, devtool %s, `sourcemaps: %j`: sets devtool %s', + (stage, devtool, sourcemaps, expectedDevtool, deletes) => { + const actions = { setWebpackConfig: vi.fn() }; + const getConfig = vi.fn().mockReturnValue(devtool === undefined ? undefined : { devtool }); + + onCreateWebpackConfig({ actions, getConfig, stage }, { sourcemaps }); + + expect(actions.setWebpackConfig).toHaveBeenCalledWith({ + devtool: expectedDevtool, + plugins: [expect.any(Object)], + }); + expect(sentryWebpackPlugin).toHaveBeenCalledWith( + expect.objectContaining({ + sourcemaps: { + assets: ['./public/**'], + upload: 'upload' in sourcemaps ? sourcemaps.upload : undefined, + injectDebugIds: 'injectDebugIds' in sourcemaps ? sourcemaps.injectDebugIds : undefined, + deleteSourcemapsAfterUpload: deletes, + sdkEnabledSourceMaps: deletes, + ignore: ['polyfill-*', 'framework-*', 'webpack-runtime-*'], + }, }), - }), + ); + }, + ); + + it.each([ + ['build-javascript', {}, 'will be deleted after they were uploaded'], + ['build-html', {}, 'stay in the build output'], + ['build-javascript', { delete: false }, 'stay in the build output'], + ] as const)('logs for stage %s and `sourcemaps: %j` that the maps %s', (stage, sourcemaps, message) => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined); + const actions = { setWebpackConfig: vi.fn() }; + + onCreateWebpackConfig({ actions, getConfig: vi.fn().mockReturnValue(undefined), stage }, { sourcemaps }); + + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining(message)); + logSpy.mockRestore(); + }); + + it('warns once when `sourcemaps.delete` and the flat option are both set', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const getConfig = vi.fn().mockReturnValue({ devtool: 'source-map' }); + const options = { deleteSourcemapsAfterUpload: true, sourcemaps: { delete: false } }; + + for (const stage of ['build-javascript', 'build-html']) { + onCreateWebpackConfig({ actions: { setWebpackConfig: vi.fn() }, getConfig, stage }, options); + } + + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('`deleteSourcemapsAfterUpload` is ignored because `sourcemaps.delete` is set'), + ); + warnSpy.mockRestore(); + }); + + it.each([ + [{ delete: false }, { deleteSourcemapsAfterUpload: true }, undefined], + [{ delete: true }, { deleteSourcemapsAfterUpload: false }, true], + ])('lets `sourcemaps: %j` win over the flat option %j', (sourcemaps, flatOptions, deletes) => { + const actions = { setWebpackConfig: vi.fn() }; + const getConfig = vi.fn().mockReturnValue({ devtool: 'source-map' }); + + onCreateWebpackConfig({ actions, getConfig, stage: 'build-javascript' }, { ...flatOptions, sourcemaps }); + + expect(sentryWebpackPlugin).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining({ deleteSourcemapsAfterUpload: deletes }) }), ); }); }); diff --git a/packages/google-cloud-serverless/package.json b/packages/google-cloud-serverless/package.json index 8255d0f0e187..2b24a0b7633c 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.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", diff --git a/packages/hono/package.json b/packages/hono/package.json index f20e2d1b9e07..f45ddc9a9ac4 100644 --- a/packages/hono/package.json +++ b/packages/hono/package.json @@ -74,7 +74,7 @@ "dependencies": { "@opentelemetry/api": "^1.9.1", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/server-utils": "11.17.0" }, "peerDependencies": { @@ -83,7 +83,7 @@ "@sentry/cloudflare": "11.17.0", "@sentry/deno": "11.17.0", "@sentry/node": "11.17.0", - "hono": "^4.x" + "hono": "^4.x || ^5.0.0-0" }, "peerDependenciesMeta": { "@cloudflare/workers-types": { diff --git a/packages/integration-shims/.oxlintrc.json b/packages/integration-shims/.oxlintrc.json index 4cd4930fa802..c996f1bd946a 100644 --- a/packages/integration-shims/.oxlintrc.json +++ b/packages/integration-shims/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"] + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"] } diff --git a/packages/nestjs/package.json b/packages/nestjs/package.json index 8f9d76a1c005..68e2bf410d05 100644 --- a/packages/nestjs/package.json +++ b/packages/nestjs/package.json @@ -54,7 +54,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/server-utils": "11.17.0" diff --git a/packages/nextjs/package.json b/packages/nextjs/package.json index f297e5c32da4..2698162d2b40 100644 --- a/packages/nextjs/package.json +++ b/packages/nextjs/package.json @@ -95,7 +95,7 @@ "@sentry/browser-utils": "11.17.0", "@sentry/bundler-plugins": "11.17.0", "@sentry/cloudflare": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/opentelemetry": "11.17.0", diff --git a/packages/nextjs/src/client/index.ts b/packages/nextjs/src/client/index.ts index ffde88fb6169..fa71a15bc7f3 100644 --- a/packages/nextjs/src/client/index.ts +++ b/packages/nextjs/src/client/index.ts @@ -3,7 +3,7 @@ /* eslint-disable import/export */ import type { BrowserTunnelOptions, Client, EventProcessor, Integration } from '@sentry/core'; import { - _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, + applyBrowserTunnelDefaults, _INTERNAL_captureOptionsSetByUser, applySdkMetadata, consoleSandbox, diff --git a/packages/nextjs/src/cloudflare/index.ts b/packages/nextjs/src/cloudflare/index.ts index 8325693f488b..ae2fa26a4e2b 100644 --- a/packages/nextjs/src/cloudflare/index.ts +++ b/packages/nextjs/src/cloudflare/index.ts @@ -13,10 +13,7 @@ import { spanToJSON, } from '@sentry/core'; import { registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy } from '@sentry/opentelemetry'; -import { - _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, - _INTERNAL_setTunnelDefaults as setTunnelDefaults, -} from '@sentry/core/server'; +import { forwardTunnelRequest, 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'; diff --git a/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts b/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts index 596ff04d7a8d..39bba67c0e70 100644 --- a/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts +++ b/packages/nextjs/src/common/utils/dropMiddlewareTunnelRequests.ts @@ -1,13 +1,7 @@ import { HTTP_TARGET, URL_FULL, URL_PATH, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; 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 { normalizeTunnelBasePath, escapeStringForRegex, getClient, isSentryRequestUrl, type Span } from '@sentry/core'; +import { getServedTunnel } from '@sentry/core/server'; import { ATTR_NEXT_ROUTE, ATTR_NEXT_SPAN_TYPE } from '../nextSpanAttributes'; import { getTunnelRouteRequestPattern, diff --git a/packages/nextjs/src/config/getBuildPluginOptions.ts b/packages/nextjs/src/config/getBuildPluginOptions.ts index fb3defba4c50..715865f50eeb 100644 --- a/packages/nextjs/src/config/getBuildPluginOptions.ts +++ b/packages/nextjs/src/config/getBuildPluginOptions.ts @@ -1,7 +1,12 @@ -import type { Options as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core'; +import type { InternalOptions as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core'; import * as fs from 'fs'; import * as path from 'path'; import { getBuildLogger } from './buildLogger'; +import { + getDeleteSourceMapsOption, + getSourceMapFeatureOptions, + mergeFilesToDeleteAfterUpload, +} from './sourceMapOptions'; import type { SentryBuildOptions } from './types'; const LOGGER_PREFIXES = { @@ -179,30 +184,39 @@ function createSourcemapUploadIgnorePattern( } /** - * Creates file patterns for deletion after source map upload + * Creates file patterns for deletion after the source map upload that runs after the production compile. + * The webpack plugin removes the maps of webpack builds itself (see `deleteSourcemapsAfterUpload`). */ function createFilesToDeleteAfterUploadPattern( normalizedDistPath: string, buildTool: BuildTool, deleteSourcemapsAfterUpload: boolean, - useRunAfterProductionCompileHook: boolean = false, ): string[] | undefined { - if (!deleteSourcemapsAfterUpload) { + if (!deleteSourcemapsAfterUpload || !buildTool.startsWith('after-production-compile')) { return undefined; } + return SOURCEMAP_EXTENSIONS.map(ext => path.posix.join(normalizedDistPath, 'static', '**', ext)); +} + +/** + * Whether the webpack plugin removes the source maps of this compiler from the build output. + */ +function shouldWebpackPluginDeleteSourcemaps( + buildTool: BuildTool, + deleteSourcemapsAfterUpload: boolean, + userFilesToDeleteAfterUpload: string | string[] | undefined, + useRunAfterProductionCompileHook: boolean = false, +): boolean { // We don't want to delete source maps for server builds as this led to errors on Vercel in the past // See: https://github.com/getsentry/sentry-javascript/issues/13099 - if (buildTool === 'webpack-nodejs' || buildTool === 'webpack-edge') { - return undefined; - } - - // Skip deletion for webpack client builds when using the experimental hook - if (buildTool === 'webpack-client' && useRunAfterProductionCompileHook) { - return undefined; - } - - return SOURCEMAP_EXTENSIONS.map(ext => path.posix.join(normalizedDistPath, 'static', '**', ext)); + // With the hook, the upload runs after the compile and must still find the maps. + return ( + buildTool === 'webpack-client' && + !useRunAfterProductionCompileHook && + userFilesToDeleteAfterUpload === undefined && + deleteSourcemapsAfterUpload + ); } /** @@ -287,7 +301,10 @@ export function getBuildPluginOptions({ const normalizedDistDirAbsPath = normalizePathForGlob(distDirAbsPath); const loggerPrefix = LOGGER_PREFIXES[buildTool]; const widenClientFileUpload = sentryBuildOptions.widenClientFileUpload ?? false; - const deleteSourcemapsAfterUpload = sentryBuildOptions.sourcemaps?.deleteSourcemapsAfterUpload ?? false; + const userSourcemaps = sentryBuildOptions.sourcemaps; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(userSourcemaps) ?? false; + // `sourcemaps.delete: true` removes the source maps next to the user's `filesToDeleteAfterUpload`. + const userFilesReplaceDeletion = userSourcemaps?.delete !== true; const sourcemapUploadAssets = createSourcemapUploadAssetPatterns( normalizedDistDirAbsPath, @@ -301,27 +318,30 @@ export function getBuildPluginOptions({ const userFilesToDeleteAfterUpload = sentryBuildOptions.sourcemaps?.filesToDeleteAfterUpload; - if (sentryBuildOptions.debug && userFilesToDeleteAfterUpload !== undefined) { + if (sentryBuildOptions.debug && userFilesToDeleteAfterUpload !== undefined && userFilesReplaceDeletion) { logger.debug( '[@sentry/nextjs] Skipping auto-deletion of source maps as user has provided filesToDeleteAfterUpload:', userFilesToDeleteAfterUpload, ); } - const filesToDeleteAfterUpload = - userFilesToDeleteAfterUpload !== undefined - ? Array.isArray(userFilesToDeleteAfterUpload) - ? userFilesToDeleteAfterUpload - : [userFilesToDeleteAfterUpload] - : createFilesToDeleteAfterUploadPattern( - normalizedDistDirAbsPath, - buildTool, - deleteSourcemapsAfterUpload, - useRunAfterProductionCompileHook, - ); + const filesToDeleteAfterUpload = mergeFilesToDeleteAfterUpload( + createFilesToDeleteAfterUploadPattern(normalizedDistDirAbsPath, buildTool, deleteSourcemapsAfterUpload), + userFilesToDeleteAfterUpload, + userFilesReplaceDeletion, + ); const skipSourcemapsUpload = shouldSkipSourcemapUpload(buildTool, useRunAfterProductionCompileHook); + const webpackPluginDeletesSourcemaps = buildTool.startsWith('webpack') + ? shouldWebpackPluginDeleteSourcemaps( + buildTool, + deleteSourcemapsAfterUpload, + userFilesReplaceDeletion ? userFilesToDeleteAfterUpload : undefined, + useRunAfterProductionCompileHook, + ) + : undefined; + return { // Only the browser reads these tags (`thirdPartyErrorFilterIntegration`), so server bundles skip the per-module cost. applicationKey: @@ -343,11 +363,16 @@ export function getBuildPluginOptions({ silent: sentryBuildOptions.silent, url: sentryBuildOptions.sentryUrl, sourcemaps: { - disable: skipSourcemapsUpload ? true : (sentryBuildOptions.sourcemaps?.disable ?? false), + ...getSourceMapFeatureOptions(userSourcemaps, skipSourcemapsUpload), + // `sourcemaps.delete` does not reach the plugin, which would also remove the server source maps. rewriteSources: sentryBuildOptions.sourcemaps?.rewriteSources ?? rewriteWebpackSources, assets: sentryBuildOptions.sourcemaps?.assets ?? sourcemapUploadAssets, ignore: finalIgnorePatterns, filesToDeleteAfterUpload, + deleteSourcemapsAfterUpload: webpackPluginDeletesSourcemaps, + // Every client map goes, also those the user turned on with `productionBrowserSourceMaps` or + // `devtool`, and those of chunks the upload leaves out. + sdkEnabledSourceMaps: webpackPluginDeletesSourcemaps, resolveSourceMap: sentryBuildOptions.sourcemaps?.resolveSourceMap, }, release: createReleaseConfig(releaseName, sentryBuildOptions), diff --git a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts index a9dafeaeac86..7d44bc311ef4 100644 --- a/packages/nextjs/src/config/handleRunAfterProductionCompile.ts +++ b/packages/nextjs/src/config/handleRunAfterProductionCompile.ts @@ -1,9 +1,11 @@ import type { createSentryBuildPluginManager as createSentryBuildPluginManagerType } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; import { loadModule } from '@sentry/core/server'; import * as fs from 'fs'; import * as path from 'path'; import { getBuildLogger } from './buildLogger'; import { getBuildPluginOptions } from './getBuildPluginOptions'; +import { getDeleteSourceMapsOption } from './sourceMapOptions'; import type { SentryBuildOptions } from './types'; /** @@ -59,7 +61,9 @@ export async function handleRunAfterProductionCompile( await sentryBuildPluginManager.createRelease(); // Skip debug ID injection if sourcemaps are disabled which are only relevant for sourcemap correlation - if (!usesNativeDebugIds && sentryBuildOptions.sourcemaps?.disable !== true) { + const { injectDebugIds } = resolveSourceMapsFeatures(sentryBuildOptions.sourcemaps); + + if (!usesNativeDebugIds && injectDebugIds) { await sentryBuildPluginManager.injectDebugIds([distDir]); } @@ -68,7 +72,7 @@ export async function handleRunAfterProductionCompile( prepareArtifacts: false, }); - const deleteSourcemapsAfterUpload = sentryBuildOptions.sourcemaps?.deleteSourcemapsAfterUpload ?? false; + const deleteSourcemapsAfterUpload = getDeleteSourceMapsOption(sentryBuildOptions.sourcemaps) ?? false; // Deletion covers all of `static/`, so if Next.js emits chunks outside the upload // patterns, their maps would be deleted without ever having been uploaded — warn instead @@ -77,7 +81,7 @@ export async function handleRunAfterProductionCompile( deleteSourcemapsAfterUpload && buildTool === 'turbopack' && !sentryBuildOptions.sourcemaps?.assets && - options.sourcemaps?.disable !== true + resolveSourceMapsFeatures(options.sourcemaps).injectDebugIds ) { await warnAboutUncoveredSourcemaps( path.join(distDir, 'static'), diff --git a/packages/nextjs/src/config/sourceMapOptions.ts b/packages/nextjs/src/config/sourceMapOptions.ts new file mode 100644 index 000000000000..341f9e8ea203 --- /dev/null +++ b/packages/nextjs/src/config/sourceMapOptions.ts @@ -0,0 +1,55 @@ +import type { InternalOptions as SentryBuildPluginOptions } from '@sentry/bundler-plugins/core'; +import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; +import type { SentryBuildOptions } from './types'; + +type SourceMapsOptions = SentryBuildOptions['sourcemaps']; + +/** + * Whether Sentry turns source maps on that the user did not set: when it can upload them, or when + * `sourcemaps.delete: false` keeps them for a manual upload. + */ +export function sentryEnablesSourceMaps(options: SentryBuildOptions): boolean { + const { sourcemaps } = options; + const { injectDebugIds, upload } = resolveSourceMapsFeatures(sourcemaps); + return (upload && hasSourceMapUploadCredentials(options)) || (sourcemaps?.delete === false && injectDebugIds); +} + +/** Reads `sourcemaps.delete`. When it is unset, `sourcemaps.deleteSourcemapsAfterUpload` decides. */ +export function getDeleteSourceMapsOption(sourcemaps: SourceMapsOptions): boolean | undefined { + return sourcemaps?.delete ?? sourcemaps?.deleteSourcemapsAfterUpload; +} + +/** + * The user's `filesToDeleteAfterUpload` replace the SDK's patterns. With `sourcemaps.delete: true` both apply. + */ +export function mergeFilesToDeleteAfterUpload( + defaultFiles: string[] | undefined, + userFiles: string | string[] | undefined, + userFilesReplaceDeletion: boolean, +): string[] | undefined { + if (userFiles === undefined) { + return defaultFiles; + } + + const userFilesArray = [userFiles].flat(); + return defaultFiles && !userFilesReplaceDeletion ? [...defaultFiles, ...userFilesArray] : userFilesArray; +} + +/** + * `disable`, `upload` and `injectDebugIds` for the bundler plugin. It warns when `disable` is set next to the + * options that replace it, so `disable` gets no default then. + */ +// TODO(v12): Remove `disable`. +export function getSourceMapFeatureOptions( + userSourcemaps: SourceMapsOptions, + skipSourcemapsUpload: boolean, +): Pick, 'disable' | 'upload' | 'injectDebugIds'> { + if (skipSourcemapsUpload) { + return { disable: true }; + } + + const { disable, upload, injectDebugIds } = userSourcemaps ?? {}; + const usesFeatureOptions = upload !== undefined || injectDebugIds !== undefined; + return { disable: disable ?? (usesFeatureOptions ? undefined : false), upload, injectDebugIds }; +} diff --git a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts index b0e41a3d20b6..9a96263f610e 100644 --- a/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts +++ b/packages/nextjs/src/config/turbopack/constructTurbopackConfig.ts @@ -1,4 +1,4 @@ -import { debug, escapeStringForRegex } from '@sentry/core'; +import { debug, escapeStringForRegex, resolveSourceMapsFeatures } from '@sentry/core'; import * as path from 'path'; import { getOrchestrionLoaderPath, @@ -49,7 +49,7 @@ export function constructTurbopackConfig({ // If sourcemaps are disabled, we don't need to enable native debug ids as this will add build time. const shouldEnableNativeDebugIds = (supportsNativeDebugIds(nextJsVersion ?? '') && userNextConfig?.turbopack?.debugIds) ?? - userSentryOptions?.sourcemaps?.disable !== true; + resolveSourceMapsFeatures(userSentryOptions?.sourcemaps).injectDebugIds; const newConfig: TurbopackOptions = { ...userNextConfig.turbopack, diff --git a/packages/nextjs/src/config/types.ts b/packages/nextjs/src/config/types.ts index ec8ac46504b1..e8d1489172ec 100644 --- a/packages/nextjs/src/config/types.ts +++ b/packages/nextjs/src/config/types.ts @@ -453,7 +453,7 @@ export type SentryBuildOptions = Omit< type SentryBuildSourceMapsOptions = Omit< NonNullable, - 'ignore' | 'filesToDeleteAfterUpload' + 'ignore' | 'filesToDeleteAfterUpload' | 'delete' > & { /** * A glob or an array of globs that specifies which build artifacts should not be uploaded to Sentry. @@ -486,17 +486,30 @@ type SentryBuildSourceMapsOptions = Omit< filesToDeleteAfterUpload?: string | string[]; /** - * Toggle whether generated source maps within your Next.js build folder should be automatically deleted after being - * uploaded to Sentry. + * Toggle whether the client source maps within your Next.js build folder should be automatically deleted after + * being uploaded to Sentry. Server source maps are kept. * - * Only applies to source maps the SDK generated itself. Setting `disable` to `true` or `"disable-upload"` leaves - * source map generation entirely to your Next.js config, so nothing is auto-deleted either. + * When `true`, all client source maps are deleted, also those you turned on yourself (for example with + * `productionBrowserSourceMaps`) and those that were not uploaded. * - * Defaults to `true`. + * Defaults to `true` for webpack builds and for Turbopack builds in which the SDK turns on the client source maps. + * With `disable` set to `true` or `"disable-upload"`, nothing is deleted unless you set this option to `true`. */ - // TODO(v12): Collapse into `filesToDeleteAfterUpload`, which already overrides this and is part of the shared - // build-time options. Two ways to express the same thing is one too many for a public API. deleteSourcemapsAfterUpload?: boolean; + + /** + * Whether the client source maps are removed from your Next.js build folder. Server source maps are kept. + * + * - `true`: Sentry removes every client source map, also the ones you turned on yourself (for example with + * `productionBrowserSourceMaps`) and the ones that were not uploaded. + * - `false`: Sentry removes no source map. When the source map setting is not set, Sentry turns source maps on + * and they stay in the build output. + * + * Defaults to `true` for webpack builds and for Turbopack builds in which the SDK turns on the client source maps. + * Without an upload (`upload: false` or `injectDebugIds: false`), nothing is removed unless you set this option + * to `true`. + */ + delete?: boolean; }; export type NextConfigFunction = ( diff --git a/packages/nextjs/src/config/util.ts b/packages/nextjs/src/config/util.ts index 1473b86bd745..49e3e3080944 100644 --- a/packages/nextjs/src/config/util.ts +++ b/packages/nextjs/src/config/util.ts @@ -1,7 +1,7 @@ import { parseSemver } from '@sentry/core'; +import { collectInstalledModules } from '@sentry/server-utils/no-diagnostic-channels'; import * as fs from 'fs'; import { createRequire } from 'module'; -import * as path from 'path'; // Default page extensions per https://github.com/vercel/next.js/blob/f1dbc9260d48c7995f6c52f8fbcc65f08e627992/packages/next/server/config-shared.ts#L161 export const DEFAULT_PAGE_EXTENSIONS = ['tsx', 'ts', 'jsx', 'js']; @@ -220,23 +220,16 @@ export function detectActiveBundler(): 'turbopack' | 'webpack' { } } -/** - * Extract modules from project directory's package.json - */ +/** The project's dependencies, with exact installed versions where they resolve and declared ranges otherwise. */ export function getPackageModules(projectDir: string): Record { - try { - const packageJson = path.join(projectDir, 'package.json'); - const packageJsonContent = fs.readFileSync(packageJson, 'utf8'); - const packageJsonObject = JSON.parse(packageJsonContent) as { - dependencies?: Record; - devDependencies?: Record; - }; - - return { - ...packageJsonObject.dependencies, - ...packageJsonObject.devDependencies, - }; - } catch { - return {}; - } + return collectInstalledModules({ + readFile: filePath => { + try { + return fs.readFileSync(filePath, 'utf8'); + } catch { + return undefined; + } + }, + cwd: projectDir, + }); } diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 4ad41bc2733d..09bffbda9765 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -10,6 +10,7 @@ import type { VercelCronsConfig } from '../common/types'; import { getBuildLogger } from './buildLogger'; import { externalizeOrchestrionRuntimePackages } from './diagnosticsChannelInjection'; import { getBuildPluginOptions, normalizePathForGlob } from './getBuildPluginOptions'; +import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from './sourceMapOptions'; import type { RouteManifest } from './manifest/types'; import type { BuildContext, @@ -361,7 +362,7 @@ export function constructWebpackConfigFunction({ loadModule<{ sentryWebpackPlugin: any }>('@sentry/bundler-plugins/webpack', module) ?? {}; if (sentryWebpackPlugin) { - if (!userSentryOptions.sourcemaps?.disable) { + if (sentryEnablesSourceMaps(userSentryOptions)) { // Source maps can be configured in 3 ways: // 1. (next config): productionBrowserSourceMaps // 2. (next config): experimental.serverSourceMaps @@ -384,7 +385,7 @@ export function constructWebpackConfigFunction({ } // enable source map deletion if not explicitly disabled - if (!isServer && userSentryOptions.sourcemaps?.deleteSourcemapsAfterUpload === undefined) { + if (!isServer && getDeleteSourceMapsOption(userSentryOptions.sourcemaps) === undefined) { debug.warn( '[@sentry/nextjs] Source maps will be automatically deleted after being uploaded to Sentry. If you want to keep the source maps, set the `sourcemaps.deleteSourcemapsAfterUpload` option to false in `withSentryConfig()`. If you do not want to generate and upload sourcemaps at all, set the `sourcemaps.disable` option to true.', ); diff --git a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts index 4240231dbc13..b6172939b069 100644 --- a/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts +++ b/packages/nextjs/src/config/withSentryConfig/getFinalConfigObjectBundlerUtils.ts @@ -6,6 +6,7 @@ import { import { getBuildLogger } from '../buildLogger'; import { handleRunAfterProductionCompile } from '../handleRunAfterProductionCompile'; import type { RouteManifest } from '../manifest/types'; +import { getDeleteSourceMapsOption, sentryEnablesSourceMaps } from '../sourceMapOptions'; import { constructTurbopackConfig } from '../turbopack'; import type { NextConfigObject, SentryBuildOptions, TurbopackOptions } from '../types'; import { detectActiveBundler, supportsProductionCompileHook, supportsTurbopackRuleCondition } from '../util'; @@ -247,7 +248,8 @@ export function maybeEnableTurbopackSourcemaps( bundlerInfo: BundlerInfo, ): void { // Enable source maps for turbopack builds - if (!bundlerInfo.isTurbopackSupported || !bundlerInfo.isTurbopack || userSentryOptions.sourcemaps?.disable) { + const { isTurbopack, isTurbopackSupported } = bundlerInfo; + if (!isTurbopackSupported || !isTurbopack || !sentryEnablesSourceMaps(userSentryOptions)) { return; } @@ -264,7 +266,7 @@ export function maybeEnableTurbopackSourcemaps( incomingUserNextConfigObject.productionBrowserSourceMaps = true; // Enable source map deletion if not explicitly disabled - if (userSentryOptions.sourcemaps?.deleteSourcemapsAfterUpload !== undefined) { + if (getDeleteSourceMapsOption(userSentryOptions.sourcemaps) !== undefined) { return; } diff --git a/packages/nextjs/src/config/withSentryConfig/index.ts b/packages/nextjs/src/config/withSentryConfig/index.ts index 5151e0400b73..ae2af09a24a3 100644 --- a/packages/nextjs/src/config/withSentryConfig/index.ts +++ b/packages/nextjs/src/config/withSentryConfig/index.ts @@ -1,4 +1,4 @@ -import { isThenable, warnOnRemovedBuildOptions } from '@sentry/core'; +import { isThenable, warnOnConflictingSourceMapOptions, warnOnRemovedBuildOptions } from '@sentry/core'; import { getBuildLogger } from '../buildLogger'; import type { ExportedNextConfig as NextConfig, NextConfigFunction, SentryBuildOptions } from '../types'; import { DEFAULT_SERVER_EXTERNAL_PACKAGES } from './constants'; @@ -19,6 +19,8 @@ export function withSentryConfig(nextConfig?: C, sentryBuildOptions: SentryBu const logWarning = (message: string): void => getBuildLogger(sentryBuildOptions.silent).warn(message); warnOnRemovedBuildOptions(sentryBuildOptions, ['unstable_sentryWebpackPluginOptions'], logWarning); warnOnRemovedBuildOptions(sentryBuildOptions.webpack, ['unstable_sentryWebpackPluginOptions'], logWarning); + // The bundler plugin does not get `sourcemaps.delete` or the user's `deleteSourcemapsAfterUpload`. + warnOnConflictingSourceMapOptions(sentryBuildOptions.sourcemaps, logWarning); const castNextConfig = (nextConfig as NextConfig) || {}; if (typeof castNextConfig === 'function') { diff --git a/packages/nextjs/src/edge/index.ts b/packages/nextjs/src/edge/index.ts index 1424eb978eff..c4474ad30726 100644 --- a/packages/nextjs/src/edge/index.ts +++ b/packages/nextjs/src/edge/index.ts @@ -16,10 +16,7 @@ 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 { forwardTunnelRequest, 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'; diff --git a/packages/nextjs/src/server/index.ts b/packages/nextjs/src/server/index.ts index 89c4be32a877..a56455e1b6cf 100644 --- a/packages/nextjs/src/server/index.ts +++ b/packages/nextjs/src/server/index.ts @@ -13,17 +13,9 @@ import { isClientClosed, } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; -import { - _INTERNAL_installTunnelHooks as installTunnelHooks, - addServerTimingTraceHeader, - getDefaultIntegrations, - httpIntegration, - init as nodeInit, -} from '@sentry/node'; -import { - _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, - _INTERNAL_setTunnelDefaults as setTunnelDefaults, -} from '@sentry/core/server'; +import { addServerTimingTraceHeader, getDefaultIntegrations, httpIntegration, init as nodeInit } from '@sentry/node'; +import { forwardTunnelRequest, setTunnelDefaults } from '@sentry/core/server'; +import { instrumentTunnelServers } from '@sentry/server-utils'; import { DEBUG_BUILD } from '../common/debug-build'; import { getInjectedBasePath } from '../common/utils/basePath'; import { devErrorSymbolicationEventProcessor } from '../common/devErrorSymbolicationEventProcessor'; @@ -183,7 +175,7 @@ export function init(userOptions: NodeOptions): NodeClient | undefined { // keeps the function invocation open until it times out. `vercel dev` gets no generated route, so it keeps the hook. const isServedByVercelTunnelRoute = !!process.env.VERCEL && process.env.VERCEL_ENV !== 'development'; if (tunnelRoute && !isServedByVercelTunnelRoute) { - installTunnelHooks(); + instrumentTunnelServers(); } if (DEBUG_BUILD && opts.debug) { diff --git a/packages/nextjs/src/server/vercelQueuesMonitoring.ts b/packages/nextjs/src/server/vercelQueuesMonitoring.ts index 977046b79045..4d2ff52d4f38 100644 --- a/packages/nextjs/src/server/vercelQueuesMonitoring.ts +++ b/packages/nextjs/src/server/vercelQueuesMonitoring.ts @@ -97,12 +97,12 @@ export function maybeEnrichQueueProducerSpan(span: Span): void { } // Extract topic from path: /api/v3/topic/[/] - const topicMatch = parsed.pathname.match(/^\/api\/v3\/topic\/([^/]+)/); - if (!topicMatch) { + const encodedTopic = parsed.pathname.match(/^\/api\/v3\/topic\/([^/]+)/)?.[1]; + if (!encodedTopic) { return; } - const topic = decodeURIComponent(topicMatch[1]!); + const topic = decodeURIComponent(encodedTopic); span.setAttribute(MESSAGING_SYSTEM, 'vercel.queue'); span.setAttribute(MESSAGING_DESTINATION_NAME, topic); diff --git a/packages/nextjs/test/config/getBuildPluginOptions.test.ts b/packages/nextjs/test/config/getBuildPluginOptions.test.ts index e04c76e5cb98..7f72a4abffd4 100644 --- a/packages/nextjs/test/config/getBuildPluginOptions.test.ts +++ b/packages/nextjs/test/config/getBuildPluginOptions.test.ts @@ -483,93 +483,121 @@ describe('getBuildPluginOptions', () => { ]); }); - it('configures file deletion when deleteSourcemapsAfterUpload is enabled for webpack-client without useRunAfterProductionCompileHook', () => { - const sentryBuildOptions: SentryBuildOptions = { - org: 'test-org', - project: 'test-project', - sourcemaps: { - deleteSourcemapsAfterUpload: true, - }, - }; - + it('has the webpack plugin delete the client source maps instead of a glob', () => { const result = getBuildPluginOptions({ - sentryBuildOptions, + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: true }, + }, releaseName: mockReleaseName, distDirAbsPath: mockDistDirAbsPath, buildTool: 'webpack-client', useRunAfterProductionCompileHook: false, }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ - '/path/to/.next/static/**/*.js.map', - '/path/to/.next/static/**/*.mjs.map', - '/path/to/.next/static/**/*.cjs.map', - '/path/to/.next/static/**/*.css.map', - ]); + expect(result.sourcemaps).toMatchObject({ + filesToDeleteAfterUpload: undefined, + deleteSourcemapsAfterUpload: true, + }); }); - it('does not configure file deletion when deleteSourcemapsAfterUpload is enabled for webpack-client with useRunAfterProductionCompileHook', () => { - const sentryBuildOptions: SentryBuildOptions = { - org: 'test-org', - project: 'test-project', - sourcemaps: { - deleteSourcemapsAfterUpload: true, + it.each([false, undefined])('has the webpack plugin keep the client source maps when the option is %s', option => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: option }, }, - }; + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool: 'webpack-client', + }); + + expect(result.sourcemaps).toMatchObject({ + filesToDeleteAfterUpload: undefined, + deleteSourcemapsAfterUpload: false, + }); + }); + it('does not delete client source maps in the webpack plugin with useRunAfterProductionCompileHook', () => { const result = getBuildPluginOptions({ - sentryBuildOptions, + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: true }, + }, releaseName: mockReleaseName, distDirAbsPath: mockDistDirAbsPath, buildTool: 'webpack-client', useRunAfterProductionCompileHook: true, }); - // File deletion should be undefined when using the hook - expect(result.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + // The upload runs after the compile, and the after-production-compile options delete the maps. + expect(result.sourcemaps).toMatchObject({ + filesToDeleteAfterUpload: undefined, + deleteSourcemapsAfterUpload: false, + }); }); - it('does not configure file deletion for server builds even when deleteSourcemapsAfterUpload is enabled', () => { - const sentryBuildOptions: SentryBuildOptions = { - org: 'test-org', - project: 'test-project', - sourcemaps: { - deleteSourcemapsAfterUpload: true, - }, - }; + it.each(['webpack-nodejs', 'webpack-edge'] as const)( + 'does not delete source maps of %s builds even when deleteSourcemapsAfterUpload is enabled', + buildTool => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: true }, + }, + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool, + }); - const serverBuildTools = ['webpack-nodejs', 'webpack-edge'] as const; + expect(result.sourcemaps).toMatchObject({ + filesToDeleteAfterUpload: undefined, + deleteSourcemapsAfterUpload: false, + sdkEnabledSourceMaps: false, + }); + }, + ); - serverBuildTools.forEach(buildTool => { + it.each(['after-production-compile-webpack', 'after-production-compile-turbopack'] as const)( + 'leaves deleteSourcemapsAfterUpload unset for %s builds', + buildTool => { const result = getBuildPluginOptions({ - sentryBuildOptions, + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: true }, + }, releaseName: mockReleaseName, distDirAbsPath: mockDistDirAbsPath, buildTool, }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); - }); - }); + expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); + expect(result.sourcemaps?.sdkEnabledSourceMaps).toBeUndefined(); + }, + ); - it('does not configure file deletion when deleteSourcemapsAfterUpload is disabled', () => { - const sentryBuildOptions: SentryBuildOptions = { - org: 'test-org', - project: 'test-project', - sourcemaps: { - deleteSourcemapsAfterUpload: false, - }, - }; - - const result = getBuildPluginOptions({ - sentryBuildOptions, - releaseName: mockReleaseName, - distDirAbsPath: mockDistDirAbsPath, - buildTool: 'webpack-client', - }); + it.each([true, false])( + 'sets sdkEnabledSourceMaps to the client delete option (deleteSourcemapsAfterUpload: %s)', + option => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { + org: 'test-org', + project: 'test-project', + sourcemaps: { deleteSourcemapsAfterUpload: option }, + }, + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool: 'webpack-client', + }); - expect(result.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); - }); + expect(result.sourcemaps).toMatchObject({ deleteSourcemapsAfterUpload: option, sdkEnabledSourceMaps: option }); + }, + ); it('uses custom filesToDeleteAfterUpload string when provided', () => { const sentryBuildOptions: SentryBuildOptions = { @@ -588,6 +616,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['.next/static/**/*.map']); + expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBe(false); }); it('uses custom filesToDeleteAfterUpload array when provided', () => { @@ -627,6 +656,7 @@ describe('getBuildPluginOptions', () => { }); expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + expect(result.sourcemaps?.deleteSourcemapsAfterUpload).toBe(false); }); it('filesToDeleteAfterUpload bypasses server build guard', () => { @@ -739,6 +769,58 @@ describe('getBuildPluginOptions', () => { ]); }); + it.each([ + ['after-production-compile-turbopack', true, ['custom/**/*.map']], + ['after-production-compile-webpack', true, ['custom/**/*.map']], + ] as const)( + 'deletes the static source maps next to the user files for %s with `delete: true`', + (buildTool, deleteOption, userFiles) => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { sourcemaps: { delete: deleteOption, filesToDeleteAfterUpload: [...userFiles] } }, + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool, + }); + + expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual([ + '/path/to/.next/static/**/*.js.map', + '/path/to/.next/static/**/*.mjs.map', + '/path/to/.next/static/**/*.cjs.map', + '/path/to/.next/static/**/*.css.map', + ...userFiles, + ]); + }, + ); + + it('deletes only the user files with `delete: false`', () => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { + sourcemaps: { delete: false, deleteSourcemapsAfterUpload: true, filesToDeleteAfterUpload: 'custom/**/*.map' }, + }, + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool: 'after-production-compile-turbopack', + }); + + expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(['custom/**/*.map']); + }); + + // The plugin would also remove the server source maps, which broke deployments on Vercel. + it.each(['webpack-nodejs', 'webpack-edge'] as const)( + 'keeps the source maps of %s with `delete: true`', + buildTool => { + const result = getBuildPluginOptions({ + sentryBuildOptions: { sourcemaps: { delete: true } }, + releaseName: mockReleaseName, + distDirAbsPath: mockDistDirAbsPath, + buildTool, + }); + + expect(result.sourcemaps).toMatchObject({ deleteSourcemapsAfterUpload: false, sdkEnabledSourceMaps: false }); + expect(result.sourcemaps).not.toHaveProperty('delete'); + }, + ); + it('disables sourcemaps when disable flag is set', () => { const sentryBuildOptions: SentryBuildOptions = { org: 'test-org', diff --git a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts index 634218b4cdaa..2cfe68e173ce 100644 --- a/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts +++ b/packages/nextjs/test/config/handleRunAfterProductionCompile.test.ts @@ -11,7 +11,8 @@ import { } from '../../src/config/handleRunAfterProductionCompile'; import type { SentryBuildOptions } from '../../src/config/types'; -vi.mock('@sentry/core/server', () => ({ +vi.mock('@sentry/core/server', async importOriginal => ({ + ...(await importOriginal>()), loadModule: vi.fn(), })); diff --git a/packages/nextjs/test/config/silent.test.ts b/packages/nextjs/test/config/silent.test.ts index 3cd414fc2867..b0236067b765 100644 --- a/packages/nextjs/test/config/silent.test.ts +++ b/packages/nextjs/test/config/silent.test.ts @@ -23,10 +23,14 @@ const NOT_A_DIRECTORY = { silent: __filename, notSilent: path.join(__dirname, 't beforeEach(() => { delete process.env.__SENTRY_UNSUPPORTED_TURBOPACK_WARNING_SHOWN__; + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); }); afterEach(() => { delete process.env.__SENTRY_UNSUPPORTED_TURBOPACK_WARNING_SHOWN__; + vi.unstubAllEnvs(); }); describe('getBuildLogger', () => { diff --git a/packages/nextjs/test/config/sourceMapOptions.test.ts b/packages/nextjs/test/config/sourceMapOptions.test.ts new file mode 100644 index 000000000000..ecf15450b13a --- /dev/null +++ b/packages/nextjs/test/config/sourceMapOptions.test.ts @@ -0,0 +1,134 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + getDeleteSourceMapsOption, + getSourceMapFeatureOptions, + mergeFilesToDeleteAfterUpload, + sentryEnablesSourceMaps, +} from '../../src/config/sourceMapOptions'; +import type { NextConfigObject, SentryBuildOptions } from '../../src/config/types'; +import type { BundlerInfo } from '../../src/config/withSentryConfig/getFinalConfigObjectBundlerUtils'; +import { maybeEnableTurbopackSourcemaps } from '../../src/config/withSentryConfig/getFinalConfigObjectBundlerUtils'; + +const TURBOPACK_SUPPORTED: BundlerInfo = { isTurbopack: true, isWebpack: false, isTurbopackSupported: true }; +const CREDENTIALS = { authToken: 'token', org: 'org', project: 'project' }; + +beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + vi.stubEnv('SENTRY_ORG', ''); + vi.stubEnv('SENTRY_PROJECT', ''); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe('sentryEnablesSourceMaps', () => { + it.each([ + [undefined, true], + [{ upload: false }, false], + [{ injectDebugIds: false }, false], + [{ upload: false, delete: false }, true], + [{ upload: false, delete: true }, false], + [{ injectDebugIds: false, delete: false }, false], + [{ disable: true }, false], + [{ disable: 'disable-upload' }, false], + [{ disable: 'disable-upload', delete: false }, true], + [{ disable: true, upload: true }, true], + ] as const)('with %j it returns %s', (sourcemaps, expected) => { + expect(sentryEnablesSourceMaps({ ...CREDENTIALS, sourcemaps })).toBe(expected); + }); + + it.each([ + [undefined, false], + [{ delete: false }, true], + ] as const)('without upload credentials, with %j it returns %s', (sourcemaps, expected) => { + expect(sentryEnablesSourceMaps({ sourcemaps })).toBe(expected); + }); +}); + +describe('getDeleteSourceMapsOption', () => { + it.each([ + [undefined, undefined], + [{ deleteSourcemapsAfterUpload: true }, true], + [{ delete: false, deleteSourcemapsAfterUpload: true }, false], + [{ delete: true, deleteSourcemapsAfterUpload: false }, true], + ] as const)('with %j it returns %s', (sourcemaps, expected) => { + expect(getDeleteSourceMapsOption(sourcemaps)).toBe(expected); + }); +}); + +describe('getSourceMapFeatureOptions', () => { + it.each([ + [undefined, { disable: false }], + [{ disable: 'disable-upload' }, { disable: 'disable-upload' }], + [{ upload: false }, { disable: undefined, upload: false }], + [{ injectDebugIds: false }, { disable: undefined, injectDebugIds: false }], + // The bundler plugin warns about this combination. + [ + { disable: true, upload: true }, + { disable: true, upload: true }, + ], + ] as const)('with %j it returns %j', (sourcemaps, expected) => { + expect(getSourceMapFeatureOptions(sourcemaps, false)).toEqual(expected); + }); + + it('switches the webpack plugin off when the upload runs after the compile', () => { + expect(getSourceMapFeatureOptions({ upload: true, injectDebugIds: true }, true)).toEqual({ disable: true }); + }); +}); + +describe('mergeFilesToDeleteAfterUpload', () => { + it.each([ + [['default'], undefined, true, ['default']], + [undefined, undefined, true, undefined], + [['default'], 'user', true, ['user']], + [['default'], ['user'], false, ['default', 'user']], + [undefined, ['user'], false, ['user']], + ] as const)('with the defaults %j and the user files %j', (defaults, userFiles, replace, expected) => { + expect( + mergeFilesToDeleteAfterUpload(defaults && [...defaults], userFiles && ([userFiles].flat() as string[]), replace), + ).toEqual(expected); + }); +}); + +describe('maybeEnableTurbopackSourcemaps with the new source map options', () => { + function run(sourcemaps: NonNullable, nextConfig: NextConfigObject = {}) { + const userSentryOptions: SentryBuildOptions = { ...CREDENTIALS, sourcemaps }; + maybeEnableTurbopackSourcemaps(nextConfig, userSentryOptions, TURBOPACK_SUPPORTED); + return { nextConfig, sourcemaps: userSentryOptions.sourcemaps }; + } + + it.each([{ upload: false }, { injectDebugIds: false }, { upload: false, delete: true }])( + 'turns no source maps on with %j', + sourcemaps => { + const result = run(sourcemaps); + + expect(result.nextConfig.productionBrowserSourceMaps).toBeUndefined(); + expect(result.sourcemaps).toEqual(sourcemaps); + }, + ); + + it.each([{ delete: false }, { upload: false, delete: false }, { delete: true }])( + 'turns source maps on and keeps the user-set `delete` with %j', + sourcemaps => { + const result = run(sourcemaps); + + expect(result.nextConfig.productionBrowserSourceMaps).toBe(true); + expect(result.sourcemaps).toEqual(sourcemaps); + }, + ); + + it('defaults to deletion when it turns source maps on for `upload: true`', () => { + const result = run({ upload: true }); + + expect(result.nextConfig.productionBrowserSourceMaps).toBe(true); + expect(result.sourcemaps).toEqual({ upload: true, deleteSourcemapsAfterUpload: true }); + }); + + it('turns no source maps on without upload credentials', () => { + const nextConfig: NextConfigObject = {}; + maybeEnableTurbopackSourcemaps(nextConfig, { sourcemaps: {} }, TURBOPACK_SUPPORTED); + + expect(nextConfig.productionBrowserSourceMaps).toBeUndefined(); + }); +}); diff --git a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts index db66e495a79b..5b9b3fb6bfed 100644 --- a/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts +++ b/packages/nextjs/test/config/webpack/constructWebpackConfig.test.ts @@ -4,7 +4,7 @@ import * as coreServer from '@sentry/core/server'; import * as fs from 'fs'; import type * as os from 'os'; import * as path from 'path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as getBuildPluginOptionsModule from '../../../src/config/getBuildPluginOptions'; import { CLIENT_SDK_CONFIG_FILE, @@ -28,6 +28,16 @@ vi.mock('@sentry/server-utils/orchestrion/webpack', async importOriginal => ({ sentryOrchestrionWebpackPlugin: () => ({ _name: 'sentry-orchestrion-webpack-plugin' }), })); +beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + describe('constructWebpackConfigFunction()', () => { it('includes expected properties', async () => { vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ @@ -99,6 +109,91 @@ describe('constructWebpackConfigFunction()', () => { getBuildPluginOptionsSpy.mockRestore(); }); + // Each row: the client `devtool` that Next.js hands over (`source-map` with + // `productionBrowserSourceMaps`), the user's `sourcemaps` options, and + // whether the plugin removes every client map. + it.each([ + ['the SDK turns the maps on', undefined, {}, true], + ['`productionBrowserSourceMaps` is set', 'source-map', {}, true], + ['the user set `deleteSourcemapsAfterUpload: false`', 'source-map', { deleteSourcemapsAfterUpload: false }, false], + ['the user set `filesToDeleteAfterUpload`', undefined, { filesToDeleteAfterUpload: ['custom/**/*.map'] }, false], + ['`disable` is true', 'source-map', { disable: true }, false], + ['`disable` is "disable-upload"', 'source-map', { disable: 'disable-upload' }, false], + [ + '`disable` is true and the user deletes', + 'source-map', + { disable: true, deleteSourcemapsAfterUpload: true }, + true, + ], + [ + '`disable` is "disable-upload" and the user deletes', + 'source-map', + { disable: 'disable-upload', deleteSourcemapsAfterUpload: true }, + true, + ], + ] as const)('client source map deletion when %s', async (_, devtool, sourcemaps, deletesAll) => { + const sentryWebpackPlugin = vi.fn(() => ({ _name: 'sentry-webpack-plugin' })); + vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ sentryWebpackPlugin })); + + await materializeFinalWebpackConfig({ + exportedNextConfig, + incomingWebpackConfig: { ...clientWebpackConfig, devtool }, + incomingWebpackBuildContext: clientBuildContext, + sentryBuildTimeOptions: { sourcemaps: { ...sourcemaps } }, + }); + + expect(sentryWebpackPlugin).toHaveBeenCalledWith( + expect.objectContaining({ + sourcemaps: expect.objectContaining({ + deleteSourcemapsAfterUpload: deletesAll, + sdkEnabledSourceMaps: deletesAll, + }), + }), + ); + }); + + // Each row: the client `devtool` that Next.js hands over, the user's `sourcemaps` options, the + // `devtool` of the final config, and whether the plugin removes every client map. + it.each([ + [undefined, { upload: false }, undefined, false], + [undefined, { injectDebugIds: false }, undefined, false], + [undefined, { upload: false, delete: false }, 'hidden-source-map', false], + ['source-map', { upload: false, delete: true }, 'source-map', true], + [undefined, { delete: false }, 'hidden-source-map', false], + ['source-map', { delete: true }, 'source-map', true], + ['source-map', { delete: false, deleteSourcemapsAfterUpload: true }, 'source-map', false], + [undefined, { delete: true, filesToDeleteAfterUpload: ['custom/**/*.map'] }, 'hidden-source-map', true], + ] as const)( + 'with the client devtool %s and `sourcemaps: %j` it sets devtool %s', + async (devtool, sourcemaps, expectedDevtool, deletesAll) => { + const sentryWebpackPlugin = vi.fn(() => ({ _name: 'sentry-webpack-plugin' })); + vi.spyOn(coreServer, 'loadModule').mockImplementation(() => ({ sentryWebpackPlugin })); + + const finalWebpackConfig = await materializeFinalWebpackConfig({ + exportedNextConfig, + incomingWebpackConfig: { ...clientWebpackConfig, devtool }, + incomingWebpackBuildContext: clientBuildContext, + sentryBuildTimeOptions: { sourcemaps: { ...sourcemaps } }, + }); + + expect(finalWebpackConfig.devtool).toBe(expectedDevtool); + expect(sentryWebpackPlugin).toHaveBeenCalledWith( + expect.objectContaining({ + sourcemaps: expect.objectContaining({ + deleteSourcemapsAfterUpload: deletesAll, + sdkEnabledSourceMaps: deletesAll, + upload: 'upload' in sourcemaps ? sourcemaps.upload : undefined, + injectDebugIds: 'injectDebugIds' in sourcemaps ? sourcemaps.injectDebugIds : undefined, + }), + }), + ); + // The plugin would also remove the server source maps. + expect(sentryWebpackPlugin).not.toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining({ delete: expect.anything() }) }), + ); + }, + ); + it('does not auto-enable source map generation when `disable` is "disable-upload"', () => { const finalNextConfig = materializeFinalNextConfig( { diff --git a/packages/nextjs/test/config/withSentryConfig.test.ts b/packages/nextjs/test/config/withSentryConfig.test.ts index 8960683f59cb..af2cc03a303b 100644 --- a/packages/nextjs/test/config/withSentryConfig.test.ts +++ b/packages/nextjs/test/config/withSentryConfig.test.ts @@ -55,6 +55,20 @@ describe('withSentryConfig', () => { }); }); + // The bundler plugin does not get `sourcemaps.delete` or the user's `deleteSourcemapsAfterUpload`. + it.each([ + [{ delete: true, deleteSourcemapsAfterUpload: false }, '`sourcemaps.deleteSourcemapsAfterUpload` is ignored'], + [{ delete: false, filesToDeleteAfterUpload: ['.next/**/*.map'] }, '`sourcemaps.filesToDeleteAfterUpload` still'], + ])('warns about the conflicting source map options %j', (sourcemaps, message) => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + materializeFinalNextConfig(exportedNextConfig, undefined, { sourcemaps }); + + expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining(message)); + + consoleWarnSpy.mockRestore(); + }); + it('includes expected properties', () => { const finalConfig = materializeFinalNextConfig(exportedNextConfig); @@ -543,8 +557,15 @@ describe('withSentryConfig', () => { describe('turbopack sourcemap configuration', () => { const originalTurbopack = process.env.TURBOPACK; + beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); + }); + afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); process.env.TURBOPACK = originalTurbopack; }); diff --git a/packages/nextjs/test/edgeSdk.test.ts b/packages/nextjs/test/edgeSdk.test.ts index e424c2ca6fa0..b3531d4e82ef 100644 --- a/packages/nextjs/test/edgeSdk.test.ts +++ b/packages/nextjs/test/edgeSdk.test.ts @@ -11,11 +11,7 @@ import { 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 { 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'; @@ -116,7 +112,7 @@ describe('Edge init()', () => { afterEach(() => { delete globalWithInjectedValues._sentryBasePath; delete globalWithInjectedValues._sentryTunnelRoute; - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('serves the fixed path of the `tunnelRoute` without `serveTunnelIntegration`', () => { diff --git a/packages/nextjs/test/serverSdk.test.ts b/packages/nextjs/test/serverSdk.test.ts index 3442c98853c6..20155c6311e4 100644 --- a/packages/nextjs/test/serverSdk.test.ts +++ b/packages/nextjs/test/serverSdk.test.ts @@ -7,15 +7,12 @@ import { shouldIgnoreSpan, withIsolationScope, } from '@sentry/core'; +import * as SentryServerUtils from '@sentry/server-utils'; 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 { 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'; @@ -126,7 +123,7 @@ describe('Server init()', () => { afterEach(() => { delete globalWithInjectedValues._sentryBasePath; delete globalWithInjectedValues._sentryTunnelRoute; - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('serves the fixed path of the `tunnelRoute` without `serveTunnelIntegration`', () => { @@ -148,12 +145,14 @@ describe('Server init()', () => { ])('installs the tunnel hooks %s only without the generated route', (_description, env, calls) => { globalWithInjectedValues._sentryTunnelRoute = '/monitoring'; Object.entries(env).forEach(([name, value]) => vi.stubEnv(name, value)); - const installTunnelHooks = vi.spyOn(SentryNode, '_INTERNAL_installTunnelHooks').mockImplementation(() => {}); + const instrumentTunnelServers = vi + .spyOn(SentryServerUtils, 'instrumentTunnelServers') + .mockImplementation(() => {}); init({ dsn: TEST_DSN }); - expect(installTunnelHooks).toHaveBeenCalledTimes(calls); - installTunnelHooks.mockRestore(); + expect(instrumentTunnelServers).toHaveBeenCalledTimes(calls); + instrumentTunnelServers.mockRestore(); vi.unstubAllEnvs(); }); diff --git a/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts b/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts index d13bdfb0a84b..7383f683e116 100644 --- a/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts +++ b/packages/nextjs/test/utils/dropMiddlewareTunnelRequests.test.ts @@ -13,7 +13,7 @@ const served = vi.hoisted(() => ({ tunnel: undefined as { paths: string[]; baseP vi.mock('@sentry/core/server', async requireActual => { return { ...(await requireActual()), - _INTERNAL_getServedTunnel: () => served.tunnel, + getServedTunnel: () => served.tunnel, }; }); diff --git a/packages/nitro/package.json b/packages/nitro/package.json index 0e790546ee64..cfdd9d1eaa01 100644 --- a/packages/nitro/package.json +++ b/packages/nitro/package.json @@ -41,7 +41,7 @@ }, "dependencies": { "@sentry/bundler-plugins": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", diff --git a/packages/nitro/src/config.ts b/packages/nitro/src/config.ts index cdc0f2b00dfb..df201afb02f0 100644 --- a/packages/nitro/src/config.ts +++ b/packages/nitro/src/config.ts @@ -1,6 +1,7 @@ import type { BuildTimeOptionsBase } from '@sentry/core'; import type { NitroConfig } from 'nitro/types'; import { createNitroModule } from './module'; +import { createOrchestrionModule } from './orchestrion'; import { configureSourcemapSettings } from './sourceMaps'; export type SentryNitroOptions = BuildTimeOptionsBase; @@ -9,7 +10,14 @@ export type SentryNitroOptions = BuildTimeOptionsBase; * Modifies the passed in Nitro configuration with automatic build-time instrumentation. */ export function withSentryConfig(config: NitroConfig, sentryOptions?: SentryNitroOptions): NitroConfig { - return setupSentryNitroModule(config, sentryOptions); + const sentryConfig = setupSentryNitroModule(config, sentryOptions); + + // Not part of `setupSentryNitroModule`, as framework SDKs that use it add the transform themselves. + if (sentryOptions?.buildTimeInstrumentation !== false) { + sentryConfig.modules?.push(createOrchestrionModule()); + } + + return sentryConfig; } /** diff --git a/packages/nitro/src/module.ts b/packages/nitro/src/module.ts index e417ebcd42a5..07c39017197e 100644 --- a/packages/nitro/src/module.ts +++ b/packages/nitro/src/module.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; import type { NitroModule } from 'nitro/types'; import type { SentryNitroOptions } from './config'; import { setIsNitroDevServer } from './devServer'; diff --git a/packages/nitro/src/orchestrion.ts b/packages/nitro/src/orchestrion.ts new file mode 100644 index 000000000000..e91fb434a276 --- /dev/null +++ b/packages/nitro/src/orchestrion.ts @@ -0,0 +1,41 @@ +import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup'; +import type { NitroModule } from 'nitro/types'; + +// The names `sentryOrchestrionPlugin` returns, with and without `buildTimeInstrumentation`. +const ORCHESTRION_PLUGIN_NAMES = ['code-transformer', 'sentry-orchestrion-disabled']; + +function hasOrchestrionPlugin(plugins: unknown): boolean { + if (Array.isArray(plugins)) { + return plugins.some(hasOrchestrionPlugin); + } + const name = (plugins as { name?: unknown } | null | undefined)?.name; + return typeof name === 'string' && ORCHESTRION_PLUGIN_NAMES.includes(name); +} + +/** + * Creates a Nitro module that adds the orchestrion code transform to the server build, so instrumented + * dependencies publish `diagnostics_channel` events from the bundle. + */ +export function createOrchestrionModule(): NitroModule { + return { + name: 'sentry-orchestrion', + setup: nitro => { + // Under Vite, the server build also runs the Vite plugins, where a Sentry Vite plugin may already add the + // transform without showing up in the config below. A module transformed twice fails the build. + if (nitro.options.builder === 'vite') { + return; + } + + // Apps that add the plugin themselves keep theirs. Registering at `build:before` runs this after the + // `rollup:before` hooks of every module, in whichever order the modules are listed. + nitro.hooks.hookOnce('build:before', () => { + nitro.hooks.hook('rollup:before', (_nitro, config) => { + if (hasOrchestrionPlugin(config.plugins)) { + return; + } + config.plugins = [config.plugins, sentryOrchestrionPlugin()]; + }); + }); + }, + }; +} diff --git a/packages/nitro/src/runtime/plugins/server.ts b/packages/nitro/src/runtime/plugins/server.ts index 5f5827812e5e..b370b959da4c 100644 --- a/packages/nitro/src/runtime/plugins/server.ts +++ b/packages/nitro/src/runtime/plugins/server.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; import { definePlugin } from 'nitro'; import { useRuntimeConfig } from 'nitro/runtime-config'; // @ts-expect-error - This is a virtual module diff --git a/packages/nitro/src/sourceMaps.ts b/packages/nitro/src/sourceMaps.ts index ea68b33f282f..a32df5f81100 100644 --- a/packages/nitro/src/sourceMaps.ts +++ b/packages/nitro/src/sourceMaps.ts @@ -1,5 +1,6 @@ import type { Options as BundlerPluginOptions } from '@sentry/bundler-plugins/core'; import { createSentryBuildPluginManager } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures, warnOnConflictingSourceMapOptions } from '@sentry/core'; import type { Nitro, NitroConfig } from 'nitro/types'; import type { SentryNitroOptions } from './config'; @@ -7,9 +8,12 @@ import type { SentryNitroOptions } from './config'; * Registers a `compiled` hook to upload source maps after the build completes. */ export function setupSourceMaps(nitro: Nitro, options?: SentryNitroOptions, sentryEnabledSourcemaps?: boolean): void { + // The plugin manager does not get `sourcemaps.delete`. + warnOnConflictingSourceMapOptions(options?.sourcemaps); + // The `compiled` hook fires on EVERY rebuild during `nitro dev` watch mode. // nitro.options.dev is reliably set by the time module setup runs. - if (shouldSkipSourcemapUpload(nitro, options)) { + if (shouldSkipBuildHook(nitro, options)) { return; } @@ -19,18 +23,24 @@ export function setupSourceMaps(nitro: Nitro, options?: SentryNitroOptions, sent } /** - * Determines if sourcemap uploads should be skipped. + * Determines if the build hook, which creates the release and uploads source maps, should be skipped. */ -function shouldSkipSourcemapUpload(nitro: Nitro, options?: SentryNitroOptions): boolean { +function shouldSkipBuildHook(nitro: Nitro, options?: SentryNitroOptions): boolean { return !!( nitro.options.dev || nitro.options.preset === 'nitro-prerender' || - nitro.options.sourcemap === false || - (nitro.options.sourcemap as unknown) === 'inline' || - options?.sourcemaps?.disable === true + // TODO(v12): Run the hook with `sourcemaps.disable: true` too, like with the options that replace it. + resolveSourceMapsFeatures(options?.sourcemaps).legacyDisable === true ); } +/** + * With `sourcemap: false` or `'inline'`, the build has no `.map` files to upload or delete. + */ +function hasSourceMapFiles(nitro: Nitro): boolean { + return nitro.options.sourcemap !== false && (nitro.options.sourcemap as unknown) !== 'inline'; +} + /** * Handles the actual source map upload after the build completes. */ @@ -50,13 +60,23 @@ async function handleSourceMapUpload( await sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal(); await sentryBuildPluginManager.createRelease(); + if (!hasSourceMapFiles(nitro)) { + return; + } + await sentryBuildPluginManager.injectDebugIds([outputDir]); - if (options?.sourcemaps?.disable !== 'disable-upload') { + const { upload } = resolveSourceMapsFeatures(options?.sourcemaps); + + if (upload) { await sentryBuildPluginManager.uploadSourcemaps([outputDir], { // We don't prepare the artifacts because we injected debug IDs manually before prepareArtifacts: false, }); + } + + // Without an upload the user uploads the source maps by hand, so they stay unless `sourcemaps.delete` is `true`. + if (upload || options?.sourcemaps?.delete === true) { await sentryBuildPluginManager.deleteArtifacts(); } } @@ -86,10 +106,18 @@ export function getPluginOptions( sentryEnabledSourcemaps?: boolean, outputDir?: string, ): BundlerPluginOptions { + const deleteOption = options?.sourcemaps?.delete; + const userFilesToDelete = options?.sourcemaps?.filesToDeleteAfterUpload; + // `sourcemaps.delete` replaces the rule that only the source maps Sentry enabled are deleted. const defaultFilesToDelete = - sentryEnabledSourcemaps && outputDir ? [`${removeTrailingSlash(outputDir)}/**/*.map`] : undefined; - - if (options?.debug && defaultFilesToDelete && options?.sourcemaps?.filesToDeleteAfterUpload === undefined) { + (deleteOption ?? sentryEnabledSourcemaps) && outputDir ? [`${removeTrailingSlash(outputDir)}/**/*.map`] : undefined; + // The user's files replace the default. With `sourcemaps.delete: true` both apply. + const filesToDeleteAfterUpload = + deleteOption === true && defaultFilesToDelete + ? [...defaultFilesToDelete, ...[userFilesToDelete ?? []].flat()] + : (userFilesToDelete ?? defaultFilesToDelete); + + if (options?.debug && defaultFilesToDelete && userFilesToDelete === undefined) { // eslint-disable-next-line no-console console.log( `[@sentry/nitro] Setting \`sourcemaps.filesToDeleteAfterUpload: ["${defaultFilesToDelete[0]}"]\` to delete generated source maps after they were uploaded to Sentry.`, @@ -108,9 +136,11 @@ export function getPluginOptions( errorHandler: options?.errorHandler, sourcemaps: { disable: options?.sourcemaps?.disable, + upload: options?.sourcemaps?.upload, + injectDebugIds: options?.sourcemaps?.injectDebugIds, assets: options?.sourcemaps?.assets, ignore: options?.sourcemaps?.ignore, - filesToDeleteAfterUpload: options?.sourcemaps?.filesToDeleteAfterUpload ?? defaultFilesToDelete, + filesToDeleteAfterUpload, rewriteSources: options?.sourcemaps?.rewriteSources ?? ((source: string) => normalizePath(source)), }, release: options?.release, @@ -130,34 +160,42 @@ export function getPluginOptions( 2. User enabled source map generation (true) - Keep their setting (don't modify besides uploading) 3. User did not set source maps (undefined) - - We enable source maps for Sentry + - We enable source maps when Sentry uploads them, or when `sourcemaps.delete: false` keeps them for a manual + upload. Otherwise we leave the setting unset - Configure `filesToDeleteAfterUpload` to clean up .map files after upload */ export function configureSourcemapSettings( config: NitroConfig, moduleOptions?: SentryNitroOptions, ): { sentryEnabledSourcemaps: boolean } { - const sourcemapUploadDisabled = moduleOptions?.sourcemaps?.disable === true; - if (sourcemapUploadDisabled) { + const { injectDebugIds, upload, legacyDisable } = resolveSourceMapsFeatures(moduleOptions?.sourcemaps); + if (legacyDisable === true) { return { sentryEnabledSourcemaps: false }; } + // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. + const usesSourceMaps = upload || legacyDisable === 'disable-upload'; + // Without an upload, Sentry only turns source maps on when `sourcemaps.delete: false` keeps them. + const sentryEnablesSourceMaps = usesSourceMaps || (moduleOptions?.sourcemaps?.delete === false && injectDebugIds); + // Nitro types `sourcemap` as `boolean`, but it forwards the value to Vite which also accepts `'hidden'` and `'inline'`. const userSourcemap = (config as { sourcemap?: boolean | 'hidden' | 'inline' }).sourcemap; if (userSourcemap === false) { - // eslint-disable-next-line no-console - console.warn( - '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or use `sourcemaps: { disable: true }` in your Sentry options to silence this warning.', - ); + usesSourceMaps && + // eslint-disable-next-line no-console + console.warn( + '[@sentry/nitro] You have explicitly disabled source maps (`sourcemap: false`). Sentry will not upload source maps, and errors will not be unminified. To let Sentry handle source maps, remove the `sourcemap` option from your Nitro config, or use `sourcemaps: { disable: true }` in your Sentry options to silence this warning.', + ); return { sentryEnabledSourcemaps: false }; } if (userSourcemap === 'inline') { - // eslint-disable-next-line no-console - console.warn( - '[@sentry/nitro] You have set `sourcemap: "inline"`. Inline source maps are embedded in the output bundle, so there are no `.map` files to upload. Sentry will not upload source maps. Set `sourcemap: "hidden"` (or leave it unset) to let Sentry upload source maps and un-minify errors.', - ); + usesSourceMaps && + // eslint-disable-next-line no-console + console.warn( + '[@sentry/nitro] You have set `sourcemap: "inline"`. Inline source maps are embedded in the output bundle, so there are no `.map` files to upload. Sentry will not upload source maps. Set `sourcemap: "hidden"` (or leave it unset) to let Sentry upload source maps and un-minify errors.', + ); return { sentryEnabledSourcemaps: false }; } @@ -169,7 +207,7 @@ export function configureSourcemapSettings( `[@sentry/nitro] Source maps are already enabled (\`sourcemap: ${JSON.stringify(userSourcemap)}\`). Sentry will upload them for error unminification.`, ); } - } else { + } else if (sentryEnablesSourceMaps) { // User did not explicitly set sourcemap, enable hidden source maps for Sentry. // `'hidden'` emits .map files without adding a `//# sourceMappingURL=` comment to the output, avoiding public exposure. (config as { sourcemap?: unknown }).sourcemap = 'hidden'; diff --git a/packages/nitro/test/module.test.ts b/packages/nitro/test/module.test.ts index e7a4f050aa7f..dad1459c311b 100644 --- a/packages/nitro/test/module.test.ts +++ b/packages/nitro/test/module.test.ts @@ -1,6 +1,6 @@ import type { Client } from '@sentry/core'; import { getCurrentScope, makeDsn } from '@sentry/core'; -import { _INTERNAL_resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; +import { resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { setIsNitroDevServer } from '../src/devServer'; import { createNitroModule } from '../src/module'; @@ -33,7 +33,7 @@ function setup(options: { describe('createNitroModule', () => { afterEach(() => { getCurrentScope().setClient(undefined); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); vi.clearAllMocks(); vi.unstubAllEnvs(); }); diff --git a/packages/nitro/test/orchestrion.test.ts b/packages/nitro/test/orchestrion.test.ts new file mode 100644 index 000000000000..e127a5ec6129 --- /dev/null +++ b/packages/nitro/test/orchestrion.test.ts @@ -0,0 +1,107 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup'; +import { createNitro } from 'nitro/builder'; +import type { Nitro, NitroModule, RollupConfig } from 'nitro/types'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { withSentryConfig } from '../src/config'; +import { createOrchestrionModule } from '../src/orchestrion'; + +function userModule(plugin: { name: string }): NitroModule { + return { + setup: nitro => { + nitro.hooks.hook('rollup:before', (_nitro, config) => { + config.plugins = [config.plugins, plugin]; + }); + }, + }; +} + +function pluginNames(config: RollupConfig): string[] { + return [config.plugins].flat(Infinity).map(plugin => (plugin as { name: string }).name); +} + +describe('createOrchestrionModule', () => { + let rootDir: string; + let nitro: Nitro | undefined; + + async function buildConfig(options: { + modules: NitroModule[]; + builder?: 'rollup' | 'rolldown' | 'vite'; + plugins?: unknown[]; + }) { + nitro = await createNitro({ + rootDir, + dev: false, + builder: options.builder ?? 'rolldown', + modules: options.modules, + }); + const config = { plugins: [{ name: 'nitro:app' }, ...(options.plugins ?? [])] } as RollupConfig; + await nitro.hooks.callHook('build:before', nitro); + await nitro.hooks.callHook('rollup:before', nitro, config); + return config; + } + + beforeEach(() => { + rootDir = mkdtempSync(join(tmpdir(), 'sentry-nitro-orchestrion-')); + }); + + afterEach(async () => { + await nitro?.close(); + nitro = undefined; + rmSync(rootDir, { recursive: true, force: true }); + }); + + it('adds the orchestrion plugin to the server build', async () => { + const config = await buildConfig({ modules: [createOrchestrionModule()] }); + + expect(pluginNames(config)).toEqual(['nitro:app', 'code-transformer']); + }); + + it.each([ + ['before', (own: NitroModule) => [own, createOrchestrionModule()]], + ['after', (own: NitroModule) => [createOrchestrionModule(), own]], + ])('keeps an orchestrion plugin that a module listed %s it adds', async (_order, modules) => { + const config = await buildConfig({ modules: modules(userModule(sentryOrchestrionPlugin())) }); + + expect(pluginNames(config)).toEqual(['nitro:app', 'code-transformer']); + }); + + it('keeps an orchestrion plugin from `rollupConfig.plugins`, nested as `@sentry/node/rollup` returns it', async () => { + const config = await buildConfig({ + modules: [createOrchestrionModule()], + plugins: [[{ name: 'sentry-rollup' }, sentryOrchestrionPlugin()]], + }); + + expect(pluginNames(config)).toEqual(['nitro:app', 'sentry-rollup', 'code-transformer']); + }); + + it('respects a disabled orchestrion plugin that the app adds', async () => { + const config = await buildConfig({ + modules: [userModule(sentryOrchestrionPlugin({ buildTimeInstrumentation: false })), createOrchestrionModule()], + }); + + expect(pluginNames(config)).toEqual(['nitro:app', 'sentry-orchestrion-disabled']); + }); + + it('does not add the plugin to Vite builds', async () => { + const config = await buildConfig({ builder: 'vite', modules: [createOrchestrionModule()] }); + + expect(pluginNames(config)).toEqual(['nitro:app']); + }); +}); + +describe('withSentryConfig', () => { + function moduleNames(config: ReturnType): unknown[] { + return (config.modules ?? []).map(module => (module as NitroModule).name); + } + + it('adds the orchestrion module', () => { + expect(moduleNames(withSentryConfig({}))).toEqual(['sentry', 'sentry-orchestrion']); + }); + + it('does not add the orchestrion module with `buildTimeInstrumentation: false`', () => { + expect(moduleNames(withSentryConfig({}, { buildTimeInstrumentation: false }))).toEqual(['sentry']); + }); +}); diff --git a/packages/nitro/test/sourceMapUpload.test.ts b/packages/nitro/test/sourceMapUpload.test.ts new file mode 100644 index 000000000000..e855978d023f --- /dev/null +++ b/packages/nitro/test/sourceMapUpload.test.ts @@ -0,0 +1,84 @@ +import type { Nitro } from 'nitro/types'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { SentryNitroOptions } from '../src/config'; +import { setupSourceMaps } from '../src/sourceMaps'; + +const manager = vi.hoisted(() => ({ + telemetry: { emitBundlerPluginExecutionSignal: vi.fn().mockResolvedValue(undefined) }, + createRelease: vi.fn().mockResolvedValue(undefined), + injectDebugIds: vi.fn().mockResolvedValue(undefined), + uploadSourcemaps: vi.fn().mockResolvedValue(undefined), + deleteArtifacts: vi.fn().mockResolvedValue(undefined), +})); + +vi.mock('@sentry/bundler-plugins/core', () => ({ + createSentryBuildPluginManager: vi.fn(() => manager), +})); + +/** Runs the `compiled` hook that `setupSourceMaps` registers, if any. */ +async function runBuild(options: SentryNitroOptions, sourcemap?: boolean | 'hidden' | 'inline'): Promise { + const hooks: ((nitro: Nitro) => Promise)[] = []; + const nitro = { + options: { dev: false, sourcemap, output: { serverDir: '/output/server' } }, + hooks: { hook: (_name: string, hook: (nitro: Nitro) => Promise) => hooks.push(hook) }, + } as unknown as Nitro; + + setupSourceMaps(nitro, options, true); + await Promise.all(hooks.map(hook => hook(nitro))); + return hooks.length > 0; +} + +describe('the `compiled` hook', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('uploads and deletes by default', async () => { + await runBuild({}); + + expect(manager.createRelease).toHaveBeenCalledTimes(1); + expect(manager.injectDebugIds).toHaveBeenCalledWith(['/output/server']); + expect(manager.uploadSourcemaps).toHaveBeenCalledTimes(1); + expect(manager.deleteArtifacts).toHaveBeenCalledTimes(1); + }); + + it.each([{ upload: false }, { injectDebugIds: false }, { disable: 'disable-upload' }] as const)( + 'creates the release but uploads and deletes nothing with %j', + async sourcemaps => { + await runBuild({ sourcemaps }); + + expect(manager.createRelease).toHaveBeenCalledTimes(1); + expect(manager.uploadSourcemaps).not.toHaveBeenCalled(); + expect(manager.deleteArtifacts).not.toHaveBeenCalled(); + }, + ); + + it('deletes without an upload with `delete: true`', async () => { + await runBuild({ sourcemaps: { upload: false, delete: true } }); + + expect(manager.uploadSourcemaps).not.toHaveBeenCalled(); + expect(manager.deleteArtifacts).toHaveBeenCalledTimes(1); + }); + + // Nitro resolves an unset `sourcemap` to `false`, so this is also `upload: false` without a source map setting. + it.each([ + [{}, false], + [{ upload: false }, false], + [{ upload: false, delete: true }, false], + [{}, 'inline'], + ] as const)( + 'creates the release but skips the source map steps with %j and `sourcemap: %s`', + async (sourcemaps, sourcemap) => { + await runBuild({ sourcemaps }, sourcemap); + + expect(manager.createRelease).toHaveBeenCalledTimes(1); + expect(manager.injectDebugIds).not.toHaveBeenCalled(); + expect(manager.uploadSourcemaps).not.toHaveBeenCalled(); + expect(manager.deleteArtifacts).not.toHaveBeenCalled(); + }, + ); + + it('does not run with `disable: true`', async () => { + await expect(runBuild({ sourcemaps: { disable: true } })).resolves.toBe(false); + }); +}); diff --git a/packages/nitro/test/sourceMaps.test.ts b/packages/nitro/test/sourceMaps.test.ts index 421994c4e2f1..47d4f78f569f 100644 --- a/packages/nitro/test/sourceMaps.test.ts +++ b/packages/nitro/test/sourceMaps.test.ts @@ -265,6 +265,65 @@ describe('configureSourcemapSettings', () => { expect(config.sourcemap).toBe('hidden'); }); + + it.each([ + [{ upload: false }, undefined, false], + [{ injectDebugIds: false }, undefined, false], + [{ upload: false, delete: true }, undefined, false], + [{ injectDebugIds: false, delete: false }, undefined, false], + [{ upload: false, delete: false }, 'hidden', true], + [{ delete: false }, 'hidden', true], + [{ delete: true }, 'hidden', true], + [{ disable: true, upload: true }, 'hidden', true], + ] as const)('with an unset setting and `sourcemaps: %j` it sets %s', (sourcemaps, expected, sentryEnabled) => { + const config: NitroConfig = {}; + const result = configureSourcemapSettings(config, { sourcemaps }); + + expect(config.sourcemap).toBe(expected); + expect(result.sentryEnabledSourcemaps).toBe(sentryEnabled); + expect(config.experimental?.sourcemapMinify).toBe(false); + }); + + it('does not warn about `sourcemap: false` when Sentry uploads nothing', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + configureSourcemapSettings({ sourcemap: false }, { sourcemaps: { upload: false } }); + + expect(warnSpy).not.toHaveBeenCalled(); + warnSpy.mockRestore(); + }); +}); + +describe('getPluginOptions with the new source map options', () => { + it('passes `upload` and `injectDebugIds` through', () => { + const result = getPluginOptions({ sourcemaps: { upload: false, injectDebugIds: true } }); + + expect(result.sourcemaps).toMatchObject({ upload: false, injectDebugIds: true }); + }); + + it.each([ + ['deletes every source map with `delete: true`', { delete: true }, false, ['/output/server/**/*.map']], + [ + 'deletes the user files next to the source maps with `delete: true`', + { delete: true, filesToDeleteAfterUpload: ['extra/**'] }, + false, + ['/output/server/**/*.map', 'extra/**'], + ], + ['keeps the source maps Sentry enabled with `delete: false`', { delete: false }, true, undefined], + [ + 'deletes only the user files with `delete: false`', + { delete: false, filesToDeleteAfterUpload: ['extra/**'] }, + true, + ['extra/**'], + ], + ] as const)('%s', (_label, sourcemaps, sentryEnabled, expected) => { + const result = getPluginOptions( + { sourcemaps: { ...sourcemaps, filesToDeleteAfterUpload: sourcemaps.filesToDeleteAfterUpload?.slice() } }, + sentryEnabled, + '/output/server', + ); + + expect(result.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); + }); }); describe('setupSentryNitroModule', () => { @@ -293,6 +352,22 @@ describe('setupSentryNitroModule', () => { }); describe('setupSourceMaps', () => { + // The plugin manager does not get `sourcemaps.delete`. + it('warns about conflicting source map options', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const nitro = { + options: { dev: true, output: { serverDir: '/output/server' } }, + hooks: { hook: vi.fn() }, + } as any; + + setupSourceMaps(nitro, { sourcemaps: { delete: false, filesToDeleteAfterUpload: ['.output/**/*.map'] } }); + + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('`sourcemaps.filesToDeleteAfterUpload` still deletes the files'), + ); + warnSpy.mockRestore(); + }); + it('does not register hook in dev mode', () => { const hookFn = vi.fn(); const nitro = { @@ -317,7 +392,7 @@ describe('setupSourceMaps', () => { expect(hookFn).not.toHaveBeenCalled(); }); - it('does not register hook when nitro sourcemap is disabled', () => { + it('registers the hook for the release when nitro sourcemap is disabled', () => { const hookFn = vi.fn(); const nitro = { options: { dev: false, sourcemap: false, output: { serverDir: '/output/server' } }, @@ -326,7 +401,7 @@ describe('setupSourceMaps', () => { setupSourceMaps(nitro); - expect(hookFn).not.toHaveBeenCalled(); + expect(hookFn).toHaveBeenCalledWith('compiled', expect.any(Function)); }); it('does not register hook in nitro-prerender preset', () => { diff --git a/packages/node/package.json b/packages/node/package.json index 02a7acb389d2..b6c8b0a1cb02 100644 --- a/packages/node/package.json +++ b/packages/node/package.json @@ -78,7 +78,7 @@ }, "dependencies": { "@opentelemetry/api": "^1.9.1", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/opentelemetry": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 77ec1c2b9f21..a536903d06dd 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -196,7 +196,7 @@ export { wrapMcpServerWithSentry, } from '@sentry/core/server'; export type { TunnelRequestLike } from '@sentry/core/server'; -export { installTunnelHooks as _INTERNAL_installTunnelHooks, serveTunnelIntegration } from './integrations/serveTunnel'; +export { serveTunnelIntegration } from './integrations/serveTunnel'; export { addServerTimingTraceHeader } from './utils/serverTimingHeader'; export { getTunnelPath, handleTunnelRequest } from '@sentry/core'; export type { HandleTunnelRequestOptions, ServerTunnelOptions } from '@sentry/core'; @@ -253,7 +253,7 @@ export { workerThreadsIntegration } from './integrations/workerThreads'; export { NODE_VERSION } from './nodeVersion'; export { defaultStackParser, getSentryRelease } from './sdk/api'; export { getHttpAgent, makeNodeTransport } from './transports'; -export { createGetModuleFromFilename } from './utils/module'; +export { createGetModuleFromFilename } from '@sentry/server-utils'; export { eveConversationHook, eveIntegration, getInstrumentedModuleNames } from '@sentry/server-utils'; export { eveInstrumentation } from './eve'; diff --git a/packages/node/src/integrations/anr/worker.ts b/packages/node/src/integrations/anr/worker.ts index e2f0836af5cd..2c666fccb51a 100644 --- a/packages/node/src/integrations/anr/worker.ts +++ b/packages/node/src/integrations/anr/worker.ts @@ -14,8 +14,8 @@ import { uuid4, } from '@sentry/core'; import { callFrameToStackFrame, watchdogTimer } from '@sentry/core/server'; +import { createGetModuleFromFilename } from '@sentry/server-utils'; import { makeNodeTransport } from '../../transports'; -import { createGetModuleFromFilename } from '../../utils/module'; import type { WorkerStartData } from './common'; type VoidFunction = () => void; diff --git a/packages/node/src/integrations/modules.ts b/packages/node/src/integrations/modules.ts index 54842d0cd5a3..5891d0c73710 100644 --- a/packages/node/src/integrations/modules.ts +++ b/packages/node/src/integrations/modules.ts @@ -1,6 +1,7 @@ -import { existsSync, readFileSync, realpathSync } from 'node:fs'; -import { basename, dirname, join } from 'node:path'; +import { existsSync, readFileSync } from 'node:fs'; +import { Module } from 'node:module'; import { GLOBAL_OBJ, type IntegrationFn } from '@sentry/core'; +import { collectInstalledModules } from '@sentry/server-utils'; type ModuleInfo = Record; @@ -46,114 +47,42 @@ const _modulesIntegration = (() => { }) satisfies IntegrationFn; /** - * Add node modules / packages to the event. - * For this, multiple sources are used: - * - They can be injected at build time into the __SENTRY_SERVER_MODULES__ variable (e.g. in Next.js) - * - They are extracted from the dependencies & devDependencies in the package.json file - * - They are extracted from the require.cache (CJS only) + * Adds the app's packages to the event. Versions injected at build time (e.g. by the Next.js SDK) are used as is. + * Otherwise, it uses exact installed versions where they resolve from the entry file, and declared ranges for the rest. */ export const modulesIntegration = _modulesIntegration; -function getRequireCachePaths(): string[] { +function readFile(path: string): string | undefined { try { - return require.cache ? Object.keys(require.cache) : []; + // Throwing on the many missing files would pause the debugger each time when localVariables captures caught + // exceptions, which trips its rate limit. + return existsSync(path) ? readFileSync(path, 'utf8') : undefined; } catch { - return []; + return undefined; } } -/** Extract information about package.json modules */ -function collectModules(): ModuleInfo { - return { - ...getServerModules(), - ...getModulesFromPackageJson(), - /*! rollup-include-cjs-only */ - ...collectRequireModules(), - /*! rollup-include-cjs-only-end */ - }; -} - -/** - * Whether `dir` is a node_modules folder of the main module, a folder - * `/<.pnpm or .bun>//node_modules`, where the isolated layouts of pnpm and Bun keep - * each package, or a scope folder (`@scope`) in one of these folders. - */ -function isMainModulesDir(dir: string, mainPaths: string[]): boolean { - if (basename(dir).startsWith('@')) { - return isMainModulesDir(dirname(dir), mainPaths); - } - - if (mainPaths.includes(dir)) { - return true; +/** Files loaded through the CommonJS loader, which includes CommonJS packages imported from ESM. */ +function getLoadedCommonJsFiles(): string[] { + try { + return Object.keys((Module as { _cache?: Record })._cache || {}); + } catch { + return []; } - - const storeDir = dirname(dirname(dir)); - return ( - basename(dir) === 'node_modules' && - ['.pnpm', '.bun'].includes(basename(storeDir)) && - mainPaths.includes(dirname(storeDir)) - ); } -/** Whether `require(name)` in the main module loads the package in `packageDir`. */ -function isResolvedFromMain(name: string, packageDir: string, mainPaths: string[]): boolean { - const resolvedDir = mainPaths.map(dir => join(dir, name)).find(dir => existsSync(dir)); - return !!resolvedDir && realpathSync(resolvedDir) === realpathSync(packageDir); -} - -/** Extract information about package.json modules from require.cache */ -function collectRequireModules(): ModuleInfo { - const mainPaths = require.main?.paths || []; - const paths = getRequireCachePaths(); - - // We start with the modules from package.json (if possible) - // These may be overwritten by more specific versions from the require.cache - const infos: ModuleInfo = {}; - const packageDirs: Record = {}; - const seen = new Set(); - - paths.forEach(path => { - let dir = path; - - /** Traverse directories upward in the search of package.json file */ - const updir = (): void | (() => void) => { - const orig = dir; - dir = dirname(orig); - - if (!dir || orig === dir || seen.has(orig)) { - return undefined; - } - if (!isMainModulesDir(dir, mainPaths)) { - return updir(); - } - - const pkgfile = join(orig, 'package.json'); - seen.add(orig); - - if (!existsSync(pkgfile)) { - return updir(); - } - - try { - const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as { - name: string; - version: string; - }; - // The isolated layouts of pnpm and Bun keep every version of a package. Keep the one that the main module loads. - const previousDir = packageDirs[info.name]; - if (!previousDir || !isResolvedFromMain(info.name, previousDir, mainPaths)) { - infos[info.name] = info.version; - packageDirs[info.name] = orig; - } - } catch { - // no-empty - } - }; - - updir(); +function collectModules(): ModuleInfo { + const serverModules = getServerModules(); + // The build already resolved exact versions, so skip the file reads at runtime. + if (Object.keys(serverModules).length) { + return serverModules; + } + return collectInstalledModules({ + readFile, + entryPath: process.argv[1], + cwd: process.cwd(), + loadedFiles: getLoadedCommonJsFiles(), }); - - return infos; } /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ @@ -163,28 +92,3 @@ function _getModules(): ModuleInfo { } return moduleCache; } - -interface PackageJson { - dependencies?: Record; - devDependencies?: Record; -} - -function getPackageJson(): PackageJson { - try { - const filePath = join(process.cwd(), 'package.json'); - const packageJson = JSON.parse(readFileSync(filePath, 'utf8')) as PackageJson; - - return packageJson; - } catch { - return {}; - } -} - -function getModulesFromPackageJson(): ModuleInfo { - const packageJson = getPackageJson(); - - return { - ...packageJson.dependencies, - ...packageJson.devDependencies, - }; -} diff --git a/packages/node/src/integrations/serveTunnel.ts b/packages/node/src/integrations/serveTunnel.ts index 9a799638563b..24feb5516ca5 100644 --- a/packages/node/src/integrations/serveTunnel.ts +++ b/packages/node/src/integrations/serveTunnel.ts @@ -1,15 +1,4 @@ -import { - _INTERNAL_instrumentTunnelServers as instrumentTunnelServers, - makeServeTunnelIntegration, -} from '@sentry/server-utils'; - -/** - * Lets every `node:http` server answer managed tunnel requests before the app sees them. Nothing is answered until the - * tunnel is on. For framework SDKs that enable the tunnel after `init`, like TanStack Start's `tunnelRoute`. - */ -export function installTunnelHooks(): void { - instrumentTunnelServers(); -} +import { makeServeTunnelIntegration } from '@sentry/server-utils'; /** * Lets your server forward the events of a browser SDK set up with `tunnel: true` to Sentry. diff --git a/packages/node/src/logs/capture.ts b/packages/node/src/logs/capture.ts index 0b6761333ae4..0e3b092a52e3 100644 --- a/packages/node/src/logs/capture.ts +++ b/packages/node/src/logs/capture.ts @@ -1,7 +1,7 @@ import { SENTRY_MESSAGE_TEMPLATE } from '@sentry/conventions/attributes'; import { format } from 'node:util'; import type { Log, LogSeverityLevel, ParameterizedString, Scope } from '@sentry/core'; -import { _INTERNAL_captureLog } from '@sentry/core'; +import { captureLogEvent } from '@sentry/core'; /** * Additional metadata to capture the log with. @@ -42,9 +42,9 @@ export function captureLog(level: LogSeverityLevel, ...args: CaptureLogArgs): vo attributes[`sentry.message.parameter.${index}`] = param; }); const message = format(messageOrMessageTemplate, ...paramsOrAttributes); - _INTERNAL_captureLog({ level, message, attributes }, maybeMetadata?.scope); + captureLogEvent({ level, message, attributes }, maybeMetadata?.scope); } else { - _INTERNAL_captureLog( + captureLogEvent( { level, message: messageOrMessageTemplate, attributes: paramsOrAttributes }, // type-casting here because from the type definitions we know that `maybeAttributesOrMetadata` is a metadata object (or undefined) (maybeAttributesOrMetadata as CaptureLogMetadata | undefined)?.scope ?? maybeMetadata?.scope, diff --git a/packages/node/src/sdk/api.ts b/packages/node/src/sdk/api.ts index 2e07f45297d8..4ec86b711ccd 100644 --- a/packages/node/src/sdk/api.ts +++ b/packages/node/src/sdk/api.ts @@ -3,7 +3,7 @@ import type { StackParser } from '@sentry/core'; import { createStackParser, GLOBAL_OBJ } from '@sentry/core'; import { _INTERNAL_getReleaseFromCommitEnv as getReleaseFromCommitEnv, nodeStackLineParser } from '@sentry/core/server'; -import { createGetModuleFromFilename } from '../utils/module'; +import { createGetModuleFromFilename } from '@sentry/server-utils'; /** * Returns a release dynamically from environment variables. diff --git a/packages/node/test/integrations/modules.test.ts b/packages/node/test/integrations/modules.test.ts index 31ee5671e40a..8fc3ed484c41 100644 --- a/packages/node/test/integrations/modules.test.ts +++ b/packages/node/test/integrations/modules.test.ts @@ -20,17 +20,15 @@ describe('modulesIntegration', () => { // The runtime injection happens only now — after the module is already evaluated. (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/turbopack-injected': '1.2.3' }; - const modules = modulesIntegration().getModules?.() ?? {}; - expect(modules['@sentry/turbopack-injected']).toBe('1.2.3'); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/turbopack-injected': '1.2.3' }); }); - it('reads modules already present before evaluation (webpack DefinePlugin / pre-set global)', async () => { + it('uses only modules already present before evaluation (webpack DefinePlugin / pre-set global)', async () => { (GLOBAL_OBJ as GlobalWithModules).__SENTRY_SERVER_MODULES__ = { '@sentry/prebuilt-injected': '4.5.6' }; vi.resetModules(); const { modulesIntegration } = await import('../../src/integrations/modules'); - const modules = modulesIntegration().getModules?.() ?? {}; - expect(modules['@sentry/prebuilt-injected']).toBe('4.5.6'); + expect(modulesIntegration().getModules?.()).toEqual({ '@sentry/prebuilt-injected': '4.5.6' }); }); }); diff --git a/packages/node/test/logs/exports.test.ts b/packages/node/test/logs/exports.test.ts index 782ba85ee2c0..a95abaa96789 100644 --- a/packages/node/test/logs/exports.test.ts +++ b/packages/node/test/logs/exports.test.ts @@ -8,13 +8,13 @@ vi.mock('@sentry/core', async () => { const actual = await vi.importActual('@sentry/core'); return { ...actual, - _INTERNAL_captureLog: vi.fn(), + captureLogEvent: vi.fn(), }; }); describe('Node Logger', () => { // Use the mocked function - const mockCaptureLog = vi.mocked(sentryCore._INTERNAL_captureLog); + const mockCaptureLog = vi.mocked(sentryCore.captureLogEvent); beforeEach(() => { // Reset mocks @@ -35,7 +35,7 @@ describe('Node Logger', () => { expect(nodeLogger.fatal).toBeTypeOf('function'); }); - it('should call _INTERNAL_captureLog with trace level', () => { + it('should call captureLogEvent with trace level', () => { nodeLogger.trace('Test trace message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -47,7 +47,7 @@ describe('Node Logger', () => { ); }); - it('should call _INTERNAL_captureLog with debug level', () => { + it('should call captureLogEvent with debug level', () => { nodeLogger.debug('Test debug message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -59,7 +59,7 @@ describe('Node Logger', () => { ); }); - it('should call _INTERNAL_captureLog with info level', () => { + it('should call captureLogEvent with info level', () => { nodeLogger.info('Test info message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -71,7 +71,7 @@ describe('Node Logger', () => { ); }); - it('should call _INTERNAL_captureLog with warn level', () => { + it('should call captureLogEvent with warn level', () => { nodeLogger.warn('Test warn message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -83,7 +83,7 @@ describe('Node Logger', () => { ); }); - it('should call _INTERNAL_captureLog with error level', () => { + it('should call captureLogEvent with error level', () => { nodeLogger.error('Test error message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -95,7 +95,7 @@ describe('Node Logger', () => { ); }); - it('should call _INTERNAL_captureLog with fatal level', () => { + it('should call captureLogEvent with fatal level', () => { nodeLogger.fatal('Test fatal message', { key: 'value' }); expect(mockCaptureLog).toHaveBeenCalledWith( { @@ -175,7 +175,7 @@ describe('Node Logger', () => { }); describe('scustom cope', () => { - it('calls _INTERNAL_captureLog with custom scope for basic log message', () => { + it('calls captureLogEvent with custom scope for basic log message', () => { const customScope = new Scope(); nodeLogger.debug('User logged in', undefined, { scope: customScope }); expect(mockCaptureLog).toHaveBeenCalledWith( @@ -187,7 +187,7 @@ describe('Node Logger', () => { ); }); - it('calls _INTERNAL_captureLog with custom scope for parametrized log message', () => { + it('calls captureLogEvent with custom scope for parametrized log message', () => { const customScope = new Scope(); nodeLogger.debug('User %s logged in from %s', ['Alice', 'mobile'], undefined, { scope: customScope }); expect(mockCaptureLog).toHaveBeenCalledWith( @@ -204,7 +204,7 @@ describe('Node Logger', () => { ); }); - it('calls _INTERNAL_captureLog with custom scope for fmt log message', () => { + it('calls captureLogEvent with custom scope for fmt log message', () => { const customScope = new Scope(); nodeLogger.debug(nodeLogger.fmt`User ${'Alice'} logged in from ${'mobile'}`, undefined, { scope: customScope }); expect(mockCaptureLog).toHaveBeenCalledWith( diff --git a/packages/nuxt/package.json b/packages/nuxt/package.json index 238acc2ec18b..963d10d6e3b2 100644 --- a/packages/nuxt/package.json +++ b/packages/nuxt/package.json @@ -56,7 +56,7 @@ "@nuxt/kit": "^4.6.0", "@sentry/browser": "11.17.0", "@sentry/cloudflare": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/bundler-plugins": "11.17.0", diff --git a/packages/nuxt/src/client/sdk.ts b/packages/nuxt/src/client/sdk.ts index 3b9c437cd274..e23a1934acc5 100644 --- a/packages/nuxt/src/client/sdk.ts +++ b/packages/nuxt/src/client/sdk.ts @@ -1,11 +1,15 @@ -import { getDefaultIntegrations as getBrowserDefaultIntegrations, init as initBrowser } from '@sentry/browser'; +import { getDefaultIntegrations as getBrowserDefaultIntegrations, init as initBrowser, WINDOW } from '@sentry/browser'; +import { URL_FULL } from '@sentry/conventions/attributes'; +import { HTTP_CLIENT } from '@sentry/conventions/op'; import type { Client } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, DEFAULT_ENVIRONMENT, DEV_ENVIRONMENT, + escapeStringForRegex, } from '@sentry/core'; +import { getNuxtPublicBuildAssetsUrl } from '../common/buildAssets'; import { applyNuxtTunnelBasePath } from '../common/tunnel'; import type { SentryNuxtClientOptions } from '../common/types'; @@ -21,6 +25,7 @@ export function init(options: SentryNuxtClientOptions): Client | undefined { defaultIntegrations: [...getBrowserDefaultIntegrations(options)], environment: options.environment ?? process.env.SENTRY_ENVIRONMENT ?? envFallback, ..._INTERNAL_captureOptionsSetByUser(options), + ignoreSpans: [...(options.ignoreSpans || []), ...getBuildManifestRequestFilters()], }; applyNuxtTunnelBasePath(sentryOptions); @@ -28,3 +33,27 @@ export function init(options: SentryNuxtClientOptions): Client | undefined { return initBrowser(sentryOptions); } + +/** + * Nuxt fetches its build manifest after hydration and polls for new builds. These requests would prolong pageloads. + * `url.full` holds the URL as the app passed it at span start, and the resolved URL later. + */ +function getBuildManifestRequestFilters(): NonNullable { + const buildAssetsUrl = getNuxtPublicBuildAssetsUrl(); + if (!buildAssetsUrl) { + return []; + } + + const manifestUrl = `${buildAssetsUrl}builds/`; + const urlPattern = [manifestUrl, resolveUrl(manifestUrl)].map(escapeStringForRegex).join('|'); + + return [{ op: HTTP_CLIENT, attributes: { [URL_FULL]: new RegExp(`^(?:${urlPattern})`) } }]; +} + +function resolveUrl(url: string): string { + try { + return new URL(url, WINDOW.location.href).href; + } catch { + return url; + } +} diff --git a/packages/nuxt/src/common/buildAssets.ts b/packages/nuxt/src/common/buildAssets.ts new file mode 100644 index 000000000000..debe9663fb94 --- /dev/null +++ b/packages/nuxt/src/common/buildAssets.ts @@ -0,0 +1,59 @@ +import { GLOBAL_OBJ } from '@sentry/core'; +import { NUXT_BASE_PATH_GLOBAL } from './tunnel'; + +/** Holds `app.buildAssetsDir`. Set by the generated client config plugin and server runtime-flags module. */ +export const NUXT_BUILD_ASSETS_DIR_GLOBAL = '__sentry_nuxt_build_assets_dir'; + +/** Holds `app.cdnURL`. Set by the generated client config plugin. */ +export const NUXT_CDN_URL_GLOBAL = '__sentry_nuxt_cdn_url'; + +/** Holds the paths of the files in `public/`, without `app.baseURL`. Set by the server runtime-flags module. */ +export const NUXT_PUBLIC_FILES_GLOBAL = '__sentry_nuxt_public_files'; + +const DEFAULT_BUILD_ASSETS_DIR = '/_nuxt/'; + +type GlobalWithNuxtPaths = { + [NUXT_BASE_PATH_GLOBAL]?: string; + [NUXT_BUILD_ASSETS_DIR_GLOBAL]?: string; + [NUXT_CDN_URL_GLOBAL]?: string; + [NUXT_PUBLIC_FILES_GLOBAL]?: string[]; +}; + +/** + * Returns `app.buildAssetsDir` with a leading and a trailing slash. + * Returns `undefined` for `/`, because there build output and routes share one path. + */ +export function getNuxtBuildAssetsDir( + buildAssetsDir = (GLOBAL_OBJ as GlobalWithNuxtPaths)[NUXT_BUILD_ASSETS_DIR_GLOBAL] ?? DEFAULT_BUILD_ASSETS_DIR, +): string | undefined { + const dir = joinPath(buildAssetsDir); + return dir === '/' ? undefined : dir; +} + +/** Returns `app.baseURL` + `app.buildAssetsDir`, the path prefix of build output requests to the server. */ +export function getNuxtBuildAssetsPath( + baseURL = (GLOBAL_OBJ as GlobalWithNuxtPaths)[NUXT_BASE_PATH_GLOBAL] ?? '', + buildAssetsDir?: string, +): string | undefined { + const dir = getNuxtBuildAssetsDir(buildAssetsDir); + return dir && joinPath(baseURL, dir); +} + +/** Returns `app.cdnURL` (or `app.baseURL`) + `app.buildAssetsDir`, the URL prefix the browser loads build output from. */ +export function getNuxtPublicBuildAssetsUrl(): string | undefined { + const cdnURL = (GLOBAL_OBJ as GlobalWithNuxtPaths)[NUXT_CDN_URL_GLOBAL]; + const dir = getNuxtBuildAssetsDir(); + return cdnURL && dir ? `${cdnURL.replace(/\/+$/, '')}${dir}` : getNuxtBuildAssetsPath(); +} + +/** Returns the request paths of the files in `public/`, with `app.baseURL`. */ +export function getNuxtPublicFilePaths(): string[] { + const basePath = joinPath((GLOBAL_OBJ as GlobalWithNuxtPaths)[NUXT_BASE_PATH_GLOBAL] ?? ''); + return ((GLOBAL_OBJ as GlobalWithNuxtPaths)[NUXT_PUBLIC_FILES_GLOBAL] ?? []).map( + file => `${basePath}${file.replace(/^\/+/, '')}`, + ); +} + +function joinPath(...segments: string[]): string { + return `/${segments.join('/')}/`.replace(/\/{2,}/g, '/'); +} diff --git a/packages/nuxt/src/common/tunnel.ts b/packages/nuxt/src/common/tunnel.ts index ba8b24c18115..24194a8d9401 100644 --- a/packages/nuxt/src/common/tunnel.ts +++ b/packages/nuxt/src/common/tunnel.ts @@ -1,8 +1,11 @@ import type { Options } from '@sentry/core'; -import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; +import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; -/** Set by the generated client config plugin to the app's runtime `app.baseURL`. */ -export const NUXT_TUNNEL_BASE_PATH_GLOBAL = '__sentry_nuxt_base_path'; +/** + * Holds `app.baseURL`. Set by the generated client config plugin (runtime value) and server runtime-flags module + * (build-time value). + */ +export const NUXT_BASE_PATH_GLOBAL = '__sentry_nuxt_base_path'; /** * Serves the managed tunnel under the app's `app.baseURL`, which a proxy in front of the app may be the only path @@ -10,6 +13,6 @@ export const NUXT_TUNNEL_BASE_PATH_GLOBAL = '__sentry_nuxt_base_path'; * A `basePath` the user set wins. */ export function applyNuxtTunnelBasePath(options: Pick): void { - const basePath = (GLOBAL_OBJ as { [NUXT_TUNNEL_BASE_PATH_GLOBAL]?: string })[NUXT_TUNNEL_BASE_PATH_GLOBAL]; + const basePath = (GLOBAL_OBJ as { [NUXT_BASE_PATH_GLOBAL]?: string })[NUXT_BASE_PATH_GLOBAL]; options.tunnel = applyBrowserTunnelDefaults(options.tunnel, { basePath }); } diff --git a/packages/nuxt/src/module.ts b/packages/nuxt/src/module.ts index 1778ab59236b..3c1c1118003c 100644 --- a/packages/nuxt/src/module.ts +++ b/packages/nuxt/src/module.ts @@ -3,14 +3,16 @@ import { addPlugin, addPluginTemplate, addTemplate, addVitePlugin, createResolve import type {} from '@nuxt/nitro-server'; import * as path from 'path'; -import { NUXT_TUNNEL_BASE_PATH_GLOBAL } from './common/tunnel'; +import { NUXT_BUILD_ASSETS_DIR_GLOBAL, NUXT_CDN_URL_GLOBAL } from './common/buildAssets'; +import { NUXT_BASE_PATH_GLOBAL } from './common/tunnel'; import type { SentryNuxtModuleOptions } from './common/types'; +import { setupCloudflareEntry } from './vite/cloudflare'; import { addTunnelPlugin, setupNitroServer } from './vite/nitroServer'; import { setupOrchestrion } from './vite/orchestrion'; import { NUXT_RELEASE_RUNTIME_CONFIG_KEY, setupSourceMaps } from './vite/sourceMaps'; -import { findDefaultSdkInitFile, resolveServerApi } from './vite/utils'; +import { findCloudflareOptionsFile, findDefaultSdkInitFile, resolveServerApi } from './vite/utils'; import { setupViteServer } from './vite/viteServer'; -import { stringifyForCodeInjection } from '@sentry/core'; +import { stringifyForCodeInjection, warnOnConflictingSourceMapOptions } from '@sentry/core'; export type ModuleOptions = SentryNuxtModuleOptions; type NuxtPageSubset = { file?: string; path: string }; @@ -64,7 +66,9 @@ export default defineNuxtModule({ name: 'sentry-client-config', async setup() { const runtimeConfig = useRuntimeConfig(); - globalThis.${NUXT_TUNNEL_BASE_PATH_GLOBAL} = runtimeConfig.app.baseURL; + globalThis.${NUXT_BASE_PATH_GLOBAL} = runtimeConfig.app.baseURL; + globalThis.${NUXT_BUILD_ASSETS_DIR_GLOBAL} = runtimeConfig.app.buildAssetsDir; + globalThis.${NUXT_CDN_URL_GLOBAL} = runtimeConfig.app.cdnURL; const sentryRelease = runtimeConfig.public.${NUXT_RELEASE_RUNTIME_CONFIG_KEY}; if (sentryRelease) { globalThis.SENTRY_RELEASE = { id: sentryRelease }; @@ -84,35 +88,46 @@ export default defineNuxtModule({ } const serverConfigFile = await findDefaultSdkInitFile('server', nuxt, moduleOptions); + const cloudflareOptionsFile = await findCloudflareOptionsFile(nuxt, moduleOptions); const nuxtMajor = parseInt((nuxt as unknown as { _version: string })._version?.split('.')[0] ?? '3', 10); const isMinNuxtV4 = nuxtMajor >= 4; // Orchestrion runs on both the Node path (gated on a server config file) and the Cloudflare path - // (which has no server config file — the SDK is set up via `sentryCloudflareNitroPlugin`). The + // (which has no server config file, the SDK is set up via `withSentry` or `sentryCloudflareNitroPlugin`). The // Cloudflare detection happens inside, keyed off the resolved Nitro preset. setupOrchestrion(nuxt, !!serverConfigFile, moduleOptions.buildTimeInstrumentation); - if (serverConfigFile) { - if (serverApi === 'nuxt') { + if (cloudflareOptionsFile) { + setupCloudflareEntry(nuxt, cloudflareOptionsFile); + } + + if (serverApi === 'nuxt') { + if (serverConfigFile) { setupViteServer(nuxt, serverConfigFile, moduleOptions); - } else { - setupNitroServer(nuxt, serverApi, serverConfigFile, moduleOptions); } + } else if (serverConfigFile || cloudflareOptionsFile) { + setupNitroServer(nuxt, serverApi, serverConfigFile, moduleOptions, !!cloudflareOptionsFile); } else { - // The Cloudflare setup initializes the SDK from `sentryCloudflareNitroPlugin`, so it needs the tunnel too. + // `sentryCloudflareNitroPlugin` initializes the SDK without a config file, so it needs the tunnel too. addTunnelPlugin(serverApi); } - // Names the server spans of pages after their route, with the SDK set up from the server config or from - // `sentryCloudflareNitroPlugin`. + // Names the server spans of pages after their route, with the SDK set up from the server config, from + // `sentry.cloudflare.config.ts` or from `sentryCloudflareNitroPlugin`. if (isMinNuxtV4) { addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector.server'), mode: 'server' }); } else { addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/route-detector-legacy.server'), mode: 'server' }); } - if (clientConfigFile || serverConfigFile) { - setupSourceMaps(moduleOptions, nuxt, addVitePlugin, !!clientConfigFile); + if ((nuxt.options.experimental as { ssrErrorBoundary?: boolean }).ssrErrorBoundary) { + addPlugin({ src: moduleDirResolver.resolve('./runtime/plugins/error-boundary.server'), mode: 'server' }); + } + + if (clientConfigFile || serverConfigFile || cloudflareOptionsFile) { + // The bundler plugins do not get `sourcemaps.delete`. + warnOnConflictingSourceMapOptions(moduleOptions.sourcemaps); + setupSourceMaps(moduleOptions, nuxt, addVitePlugin, !!clientConfigFile, serverApi === 'nuxt'); } let pagesData: NuxtPageSubset[] = []; @@ -164,6 +179,10 @@ export default defineNuxtModule({ const relativePath = path.relative(nuxt.options.buildDir, serverConfigFile); tsConfig.include.push(relativePath); } + if (cloudflareOptionsFile) { + const relativePath = path.relative(nuxt.options.buildDir, cloudflareOptionsFile); + tsConfig.include.push(relativePath); + } }); }, }); diff --git a/packages/nuxt/src/runtime/plugins/cloudflare-entry.server.ts b/packages/nuxt/src/runtime/plugins/cloudflare-entry.server.ts new file mode 100644 index 000000000000..d679ebeac1d6 --- /dev/null +++ b/packages/nuxt/src/runtime/plugins/cloudflare-entry.server.ts @@ -0,0 +1,21 @@ +import { getIsolationScope, stripUrlQueryAndFragment } from '@sentry/core'; +import type { H3Event } from 'h3'; +import type { NitroAppPlugin } from 'nitropack'; +import { markCloudflareEntryWrapped } from '../utils/cloudflare-entry'; + +type H3V2Event = { req: { method: string }; url: { pathname: string } }; + +export default (nitroApp => { + // This plugin runs before the plugins of the app, so a `sentryCloudflareNitroPlugin` there sees the flag. + markCloudflareEntryWrapped(); + + // `withSentry` sets no transaction name, so errors captured during the request would have none. + // This is the same best-effort name the Node SDK sets when a request starts. + nitroApp.hooks.hook('request', (event: H3Event) => { + // h3 v1 (Nitro 2) has the method and the path on the event, h3 v2 (Nitro 3) on `event.req` and `event.url`. + const { req, url } = event as unknown as Partial; + const method = event.method ?? req?.method; + const path = event.path ?? url?.pathname; + getIsolationScope().setTransactionName(`${method} ${stripUrlQueryAndFragment(path)}`); + }); +}) satisfies NitroAppPlugin; diff --git a/packages/nuxt/src/runtime/plugins/error-boundary.server.ts b/packages/nuxt/src/runtime/plugins/error-boundary.server.ts new file mode 100644 index 000000000000..cae1e1d16a83 --- /dev/null +++ b/packages/nuxt/src/runtime/plugins/error-boundary.server.ts @@ -0,0 +1,14 @@ +import { defineNuxtPlugin } from 'nuxt/app'; +import { reportNuxtError } from '../utils'; +import { isIgnoredNuxtError } from '../utils/isIgnoredNuxtError'; + +export default defineNuxtPlugin(nuxtApp => { + const caught: Parameters[0][] = []; + nuxtApp.hook('vue:error', (error, instance, info) => { + if (!isIgnoredNuxtError(error)) caught.push({ error, instance, info }); + }); + // The Nitro `error` hook reports errors that end on the error page. + nuxtApp.hook('app:rendered', () => { + if (!nuxtApp.payload.error) caught.forEach(reportNuxtError); + }); +}); diff --git a/packages/nuxt/src/runtime/plugins/index.ts b/packages/nuxt/src/runtime/plugins/index.ts index b7a5c217edf2..aef1496d70c7 100644 --- a/packages/nuxt/src/runtime/plugins/index.ts +++ b/packages/nuxt/src/runtime/plugins/index.ts @@ -1 +1,2 @@ +// oxlint-disable-next-line typescript/no-deprecated -- supported until removal export { sentryCloudflareNitroPlugin } from './sentry-cloudflare.server'; diff --git a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts index b8893f5ebbbe..8492bbd2c3ee 100644 --- a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts @@ -5,21 +5,20 @@ import { wrapRequestHandler } from '@sentry/cloudflare/request'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, + consoleSandbox, debug, getDefaultIsolationScope, getIsolationScope, getTraceData, stripUrlQueryAndFragment, } from '@sentry/core'; -import { - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, - _INTERNAL_isServedTunnelRequest as isServedTunnelRequest, -} from '@sentry/core/server'; +import { handleServedTunnelRequest, isServedTunnelRequest } from '@sentry/core/server'; import type { H3Event } from 'h3'; import type { NitroApp, NitroAppPlugin } from 'nitropack'; import type { NuxtRenderHTMLContext } from 'nuxt/app'; import { sentryCaptureErrorHook } from '../hooks/captureErrorHook'; import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse'; +import { isCloudflareEntryWrapped } from '../utils/cloudflare-entry'; import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check'; import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags'; @@ -66,10 +65,32 @@ function getRequestHandlerOptions(cloudflareOptions: CloudflareOptions): Cloudfl * debug: nitroApp.h3App.options.debug * }))); * ``` + * + * @deprecated Add a `sentry.cloudflare.config.ts` file with the Sentry setup to the root of the Nuxt app instead. + * + * ```ts + * // sentry.cloudflare.config.ts + * import { defineCloudflareOptions } from '@sentry/cloudflare'; + * + * export default defineCloudflareOptions(env => ({ + * dsn: env.SENTRY_DSN, + * })); + * ``` */ +// TODO(v12): Remove `sentryCloudflareNitroPlugin`. export const sentryCloudflareNitroPlugin = (optionsOrFn: CloudflareOptions | ((nitroApp: NitroApp) => CloudflareOptions)): NitroAppPlugin => (nitroApp: NitroApp): void => { + if (isCloudflareEntryWrapped()) { + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn( + '[Sentry] `sentryCloudflareNitroPlugin` does nothing, because Sentry sets up the SDK from `sentry.cloudflare.config.ts`. Remove the plugin.', + ); + }); + return; + } + const traceDataMap = new WeakMap>(); // Nitro v3 (Nuxt 5) has no `localFetch`. It hands the Worker's own request to `fetch`, with `ctx` on it. diff --git a/packages/nuxt/src/runtime/plugins/sentry.client.ts b/packages/nuxt/src/runtime/plugins/sentry.client.ts index 16fae57beb68..8837727f34f7 100644 --- a/packages/nuxt/src/runtime/plugins/sentry.client.ts +++ b/packages/nuxt/src/runtime/plugins/sentry.client.ts @@ -8,9 +8,10 @@ import { setRouteProvider, vueIntegration, } from '@sentry/vue'; -import { defineNuxtPlugin, isNuxtError } from 'nuxt/app'; +import { defineNuxtPlugin } from 'nuxt/app'; import type { GlobalObjWithIntegrationOptions } from '../../client/vueIntegration'; import { reportNuxtError } from '../utils'; +import { isIgnoredNuxtError } from '../utils/isIgnoredNuxtError'; // --- 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. @@ -38,16 +39,6 @@ interface VueRouter { type VueRouteProviderRouter = ReturnType[0]>; -// 3xx/4xx Nuxt errors are expected control flow (redirects, not-found pages), not bugs. The server skips them too. -function isIgnoredNuxtError(error: unknown): boolean { - if (!isNuxtError(error)) { - return false; - } - // oxlint-disable-next-line typescript/no-deprecated - const statusCode = error?.status || error?.statusCode; - return !!statusCode && statusCode >= 300 && statusCode < 500; -} - // Tree-shakable guard to remove all code related to tracing declare const __SENTRY_TRACING__: boolean; @@ -106,11 +97,14 @@ export default defineNuxtPlugin({ } }); + // Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time. nuxtApp.hook('app:error', error => { if (isIgnoredNuxtError(error)) { return; } - reportNuxtError({ error }); + setTimeout(() => { + reportNuxtError({ error }); + }); }); // Nuxt calls `vue:error` for every error that reaches the root component, so an error thrown during setup @@ -119,7 +113,9 @@ export default defineNuxtPlugin({ if (isIgnoredNuxtError(error)) { return; } - reportNuxtError({ error, instance, info }); + setTimeout(() => { + reportNuxtError({ error, instance, info }); + }); }); }, }); diff --git a/packages/nuxt/src/runtime/plugins/tunnel-legacy.server.ts b/packages/nuxt/src/runtime/plugins/tunnel-legacy.server.ts index 51aed67bffed..830c4d769156 100644 --- a/packages/nuxt/src/runtime/plugins/tunnel-legacy.server.ts +++ b/packages/nuxt/src/runtime/plugins/tunnel-legacy.server.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; import type { NitroAppPlugin } from 'nitropack'; import { useRuntimeConfig } from 'nitropack/runtime'; diff --git a/packages/nuxt/src/runtime/plugins/tunnel.server.ts b/packages/nuxt/src/runtime/plugins/tunnel.server.ts index 611466e662df..1a53b005df1d 100644 --- a/packages/nuxt/src/runtime/plugins/tunnel.server.ts +++ b/packages/nuxt/src/runtime/plugins/tunnel.server.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; import { useRuntimeConfig } from 'nitro/runtime-config'; import type { NitroAppPlugin } from 'nitro/types'; diff --git a/packages/nuxt/src/runtime/utils.ts b/packages/nuxt/src/runtime/utils.ts index becb6ef55d19..a5378fb430ac 100644 --- a/packages/nuxt/src/runtime/utils.ts +++ b/packages/nuxt/src/runtime/utils.ts @@ -100,11 +100,8 @@ export function reportNuxtError(options: { } } - // Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time. - setTimeout(() => { - captureException(error, { - captureContext: { contexts: { nuxt: metadata } }, - mechanism: { handled: false, type: `auto.function.nuxt.${instance ? 'vue' : 'app'}-error` }, - }); + captureException(error, { + captureContext: { contexts: { nuxt: metadata } }, + mechanism: { handled: false, type: `auto.function.nuxt.${instance ? 'vue' : 'app'}-error` }, }); } diff --git a/packages/nuxt/src/runtime/utils/buildAssetRequestFilters.ts b/packages/nuxt/src/runtime/utils/buildAssetRequestFilters.ts new file mode 100644 index 000000000000..14f02e3d6895 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/buildAssetRequestFilters.ts @@ -0,0 +1,16 @@ +import { URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import type { Options } from '@sentry/core'; +import { escapeStringForRegex } from '@sentry/core'; + +/** + * Returns the `ignoreSpans` entries for requests to `buildAssetsPath` (`app.baseURL` + `app.buildAssetsDir`), the + * build output that the static asset filters miss, such as `.map` and `.json` files. Matches `url.path`, because a + * span name has no path yet when `ignoreSpans` runs. A runtime `NUXT_APP_BASE_URL` disables this filter, because the + * path comes from build-time config. + */ +export function getBuildAssetRequestFilters(buildAssetsPath: string | undefined): NonNullable { + return buildAssetsPath + ? [{ op: HTTP_SERVER, attributes: { [URL_PATH]: new RegExp(`^${escapeStringForRegex(buildAssetsPath)}`) } }] + : []; +} diff --git a/packages/nuxt/src/runtime/utils/cloudflare-entry.ts b/packages/nuxt/src/runtime/utils/cloudflare-entry.ts new file mode 100644 index 000000000000..93130cbe916e --- /dev/null +++ b/packages/nuxt/src/runtime/utils/cloudflare-entry.ts @@ -0,0 +1,15 @@ +import { GLOBAL_OBJ } from '@sentry/core'; + +const CLOUDFLARE_ENTRY_WRAPPED_FLAG = '__SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__'; + +type GlobalWithCloudflareEntryFlag = typeof GLOBAL_OBJ & { [CLOUDFLARE_ENTRY_WRAPPED_FLAG]?: boolean }; + +/** Records that the Sentry Nuxt module wrapped the Worker entry with `withSentry`. */ +export function markCloudflareEntryWrapped(): void { + (GLOBAL_OBJ as GlobalWithCloudflareEntryFlag)[CLOUDFLARE_ENTRY_WRAPPED_FLAG] = true; +} + +/** Whether the Sentry Nuxt module wrapped the Worker entry with `withSentry`. */ +export function isCloudflareEntryWrapped(): boolean { + return (GLOBAL_OBJ as GlobalWithCloudflareEntryFlag)[CLOUDFLARE_ENTRY_WRAPPED_FLAG] === true; +} diff --git a/packages/nuxt/src/runtime/utils/cloudflareWorkers.d.ts b/packages/nuxt/src/runtime/utils/cloudflareWorkers.d.ts new file mode 100644 index 000000000000..1f268de7c258 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/cloudflareWorkers.d.ts @@ -0,0 +1,7 @@ +// `@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' { + // workerd versions from before March 2025 have no `withEnv`. + export const withEnv: ((env: unknown, callback: () => T) => T) | undefined; +} diff --git a/packages/nuxt/src/runtime/utils/isIgnoredNuxtError.ts b/packages/nuxt/src/runtime/utils/isIgnoredNuxtError.ts new file mode 100644 index 000000000000..d345f0614415 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/isIgnoredNuxtError.ts @@ -0,0 +1,11 @@ +import { isNuxtError } from 'nuxt/app'; + +// 3xx/4xx Nuxt errors are expected control flow (redirects, not-found pages), not bugs. The server skips them too. +export function isIgnoredNuxtError(error: unknown): boolean { + if (!isNuxtError(error)) { + return false; + } + // oxlint-disable-next-line typescript/no-deprecated + const statusCode = error?.status || error?.statusCode; + return !!statusCode && statusCode >= 300 && statusCode < 500; +} diff --git a/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts b/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts new file mode 100644 index 000000000000..21df1f940fd8 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts @@ -0,0 +1,87 @@ +import type { DurableObjectState, ExecutionContext, ExportedHandler } from '@cloudflare/workers-types'; +import type { CloudflareOptions } from '@sentry/cloudflare'; +import { instrumentDurableObjectWithSentry, withSentry } from '@sentry/cloudflare'; +import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata } from '@sentry/core'; +// A namespace import keeps a missing `withEnv` export a missing property instead of a module linking error. +import * as cloudflareWorkers from 'cloudflare:workers'; +import { getBuildAssetRequestFilters } from './buildAssetRequestFilters'; + +type OptionsCallback = (env: unknown) => CloudflareOptions; +type NitroDurableObjectClass = new (state: DurableObjectState, env: unknown) => object; +type Method = (this: unknown, ...args: unknown[]) => unknown; + +/** + * Wraps the default export of the Nitro Worker entry with `withSentry`. Each handler runs with the `env` that + * `withSentry` instruments as the `env` of `cloudflare:workers`, so db0 of Nitro 3 reads instrumented D1 bindings. + * `buildAssetsPath` is `app.baseURL` + `app.buildAssetsDir`, the path of the build output that the SDK ignores. + */ +export function wrapNitroCloudflareEntryWithSentry( + optionsCallback: OptionsCallback, + handler: Handler, + buildAssetsPath?: string, +): Handler { + const handlerWithEnv = Object.fromEntries( + Object.entries(handler).map(([name, value]) => [ + name, + typeof value === 'function' + ? (event: unknown, env: unknown, context: ExecutionContext): unknown => + runWithEnv(env, () => (value as Method).call(handler, event, env, context)) + : value, + ]), + ) as Handler; + + const optionsCallbackWithMetadata = withNuxtSdkMetadata(optionsCallback); + // Nitro sends a request for a build file that the Cloudflare assets do not have to `env.ASSETS` before the Nitro app + // runs, but `withSentry` sees the request. + return withSentry(env => { + const options = optionsCallbackWithMetadata(env); + return { + ...options, + ignoreSpans: [...(options.ignoreSpans || []), ...getBuildAssetRequestFilters(buildAssetsPath)], + }; + }, handlerWithEnv); +} + +/** + * Wraps the Durable Object class of the Nitro Worker entry with `instrumentDurableObjectWithSentry`. Each method runs + * with the instrumented `this.env` as the `env` of `cloudflare:workers`. + */ +export function wrapNitroDurableObjectWithSentry( + optionsCallback: OptionsCallback, + NitroDurableObject: NitroDurableObjectClass, +): NitroDurableObjectClass { + class NitroDurableObjectWithEnv extends NitroDurableObject {} + + for (const name of Object.getOwnPropertyNames(NitroDurableObject.prototype)) { + const method: unknown = Object.getOwnPropertyDescriptor(NitroDurableObject.prototype, name)?.value; + if (name === 'constructor' || typeof method !== 'function') { + continue; + } + + // Frameworks can read the name of a method, so the wrapper keeps it. + const { [name]: methodWithEnv } = { + [name](this: { env?: unknown }, ...args: unknown[]): unknown { + return runWithEnv(this.env, () => (method as Method).apply(this, args)); + }, + }; + Object.defineProperty(NitroDurableObjectWithEnv.prototype, name, { + value: methodWithEnv, + writable: true, + configurable: true, + }); + } + + return instrumentDurableObjectWithSentry(withNuxtSdkMetadata(optionsCallback), NitroDurableObjectWithEnv); +} + +function runWithEnv(env: unknown, callback: () => unknown): unknown { + return cloudflareWorkers.withEnv && env !== undefined ? cloudflareWorkers.withEnv(env, callback) : callback(); +} + +function withNuxtSdkMetadata(optionsCallback: OptionsCallback): OptionsCallback { + return env => { + const options = _INTERNAL_captureOptionsSetByUser({ ...optionsCallback(env) }); + applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']); + return options; + }; +} diff --git a/packages/nuxt/src/server/sdk.ts b/packages/nuxt/src/server/sdk.ts index 8253409daac1..36e0f1179bea 100644 --- a/packages/nuxt/src/server/sdk.ts +++ b/packages/nuxt/src/server/sdk.ts @@ -1,5 +1,6 @@ -import * as path from 'node:path'; -import type { Client, Event, EventProcessor } from '@sentry/core'; +import { HTTP_REQUEST_METHOD, URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import type { Client, EventProcessor } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, @@ -7,10 +8,12 @@ import { debug, DEFAULT_ENVIRONMENT, DEV_ENVIRONMENT, + escapeStringForRegex, getClient, isClientClosed, } from '@sentry/core'; import { init as initNode } from '@sentry/node'; +import { getNuxtBuildAssetsPath, getNuxtPublicFilePaths } from '../common/buildAssets'; import { DEBUG_BUILD } from '../common/debug-build'; import { isNuxtDevRuntime, @@ -19,6 +22,7 @@ import { markNuxtServerInitialized, } from '../common/devMode'; import type { SentryNuxtServerOptions } from '../common/types'; +import { getBuildAssetRequestFilters } from '../runtime/utils/buildAssetRequestFilters'; /** * Initializes the server-side of the Nuxt SDK @@ -59,6 +63,11 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { const sentryOptions = { environment: options.environment ?? process.env.SENTRY_ENVIRONMENT ?? envFallback, ..._INTERNAL_captureOptionsSetByUser(options), + ignoreSpans: [ + ...(options.ignoreSpans || []), + ...getBuildAssetRequestFilters(getNuxtBuildAssetsPath()), + ...getPublicFileRequestFilters(), + ], }; applySdkMetadata(sentryOptions, 'nuxt', ['nuxt', 'node']); @@ -71,44 +80,28 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { // On the client, not the global scope, so a later `init()` after // `close()` does not stack another copy. - client?.addEventProcessor(lowQualityTransactionsFilter(options)); client?.addEventProcessor(clientSourceMapErrorFilter(options)); return client; } /** - * Filter out transactions for resource requests which we don't want to send to Sentry - * for quota reasons. - * - * Only exported for testing + * Ignores files from `public/` that the HTTP integration's static asset filter misses, such as `.pdf` and `.txt` files. + * Matches exact paths, because a route can share a prefix with a public dir. */ -export function lowQualityTransactionsFilter(options: SentryNuxtServerOptions): EventProcessor { - return Object.assign( - (event => { - if (event.type !== 'transaction' || !event.transaction || isCacheEvent(event)) { - return event; - } - - // Check if this looks like a parametrized route (contains :param or :param() patterns) - const hasRouteParameters = /\/:[^(/\s]*(\([^)]*\))?[^/\s]*/.test(event.transaction); - - if (hasRouteParameters) { - return event; - } - - // We don't want to send transaction for file requests, so everything ending with a *.someExtension should be filtered out - // path.extname will return an empty string for normal page requests - if (path.extname(event.transaction)) { - options.debug && - DEBUG_BUILD && - debug.log('NuxtLowQualityTransactionsFilter filtered transaction: ', event.transaction); - return null; - } - return event; - }) satisfies EventProcessor, - { id: 'NuxtLowQualityTransactionsFilter' }, - ); +function getPublicFileRequestFilters(): NonNullable { + const paths = getNuxtPublicFilePaths(); + return paths.length + ? [ + { + op: HTTP_SERVER, + attributes: { + [HTTP_REQUEST_METHOD]: 'GET', + [URL_PATH]: new RegExp(`^(?:${paths.map(escapeStringForRegex).join('|')})$`), + }, + }, + ] + : []; } /** @@ -129,10 +122,3 @@ export function clientSourceMapErrorFilter(options: SentryNuxtServerOptions): Ev { id: 'NuxtClientSourceMapErrorFilter' }, ); } - -/** - * Checks if the event is a cache event. - */ -function isCacheEvent(e: Event): boolean { - return e.contexts?.trace?.origin === 'auto.cache.nuxt'; -} diff --git a/packages/nuxt/src/vite/addServerConfig.ts b/packages/nuxt/src/vite/addServerConfig.ts index e37b2c5f66e5..3ccaa648900c 100644 --- a/packages/nuxt/src/vite/addServerConfig.ts +++ b/packages/nuxt/src/vite/addServerConfig.ts @@ -8,6 +8,7 @@ import * as fs from 'fs'; import type { Nitro } from 'nitropack'; import type { InputPluginOption } from 'rollup'; import type { SentryNuxtModuleOptions } from '../common/types'; +import { getNitroPublicFilePaths } from './publicFiles'; import { addRuntimeFlagsTemplate, constructFunctionReExport, @@ -107,10 +108,24 @@ export function addSentryTopImport(moduleOptions: SentryNuxtModuleOptions, nitro /** * Registers a Nitro plugin that statically imports the Sentry server config, so the SDK initializes * at server startup without a `node --import` preload. + * + * On a Cloudflare preset, it removes the plugin again. It warns then only when the app has no + * `sentry.cloudflare.config` file (`hasCloudflareOptionsFile`), because an app with both files can build for Node and + * for Cloudflare. */ -export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLegacyNitro: boolean): void { +export function addServerConfigPlugin( + nuxt: Nuxt, + serverConfigFile: string, + isLegacyNitro: boolean, + hasCloudflareOptionsFile: boolean, +): void { const configPath = createResolver(nuxt.options.rootDir).resolve(serverConfigFile); - const runtimeFlagsTemplate = addRuntimeFlagsTemplate(); + let publicFilePaths: string[] = []; + // Nitro starts before Nuxt generates the templates. + nuxt.hook('nitro:init', nitro => { + publicFilePaths = getNitroPublicFilePaths(nitro, nuxt); + }); + const runtimeFlagsTemplate = addRuntimeFlagsTemplate(() => publicFilePaths); const configPluginTemplate = addTemplate({ filename: 'sentry-server-config-plugin.mjs', @@ -156,7 +171,7 @@ export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLe } }); - // On Cloudflare the SDK is set up through `sentryCloudflareNitroPlugin`; the Node SDK config + // On Cloudflare `withSentry` sets up the SDK with the options of `sentry.cloudflare.config.ts`; the Node SDK config // must not end up in the worker bundle. `nitro.options.preset` is resolved here. nuxt.hook('nitro:init', nitro => { if (nuxt.options._prepare || !isCloudflarePreset(nitro.options.preset)) { @@ -164,10 +179,13 @@ export function addServerConfigPlugin(nuxt: Nuxt, serverConfigFile: string, isLe } nitro.options.plugins = (nitro.options.plugins ?? []).filter(plugin => plugin !== configPluginTemplate.dst); + if (hasCloudflareOptionsFile) { + return; + } consoleSandbox(() => { // eslint-disable-next-line no-console console.warn( - `[Sentry] Found \`${basename(configPath)}\`, but the Nitro preset targets Cloudflare, where this file is not used. Set up the SDK with \`sentryCloudflareNitroPlugin\` instead: https://docs.sentry.io/platforms/javascript/guides/nuxt/install/cloudflare-workers/`, + `[Sentry] Found \`${basename(configPath)}\`, but the Nitro preset targets Cloudflare, where this file is not used. Set up the SDK in \`sentry.cloudflare.config.ts\` instead: https://docs.sentry.io/platforms/javascript/guides/nuxt/install/cloudflare-workers/`, ); }); }); diff --git a/packages/nuxt/src/vite/cloudflare.ts b/packages/nuxt/src/vite/cloudflare.ts new file mode 100644 index 000000000000..0ac1a9815df1 --- /dev/null +++ b/packages/nuxt/src/vite/cloudflare.ts @@ -0,0 +1,176 @@ +import { createResolver } from '@nuxt/kit'; +import type { Nuxt } from '@nuxt/schema'; +import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; +import type { Plugin } from 'rollup'; +import { getNuxtBuildAssetsPath } from '../common/buildAssets'; +import { skipDatabaseInstrumentation } from './databaseConfig'; +import { isCloudflarePreset } from './utils'; + +const WRAPPED_ENTRY_ID = '\0sentry-cloudflare-entry'; +const ORIGINAL_ENTRY_QUERY = '?sentry-cloudflare-original'; +// The Durable Object class that the Cloudflare presets of Nitro export from the Worker entry. +const NITRO_DURABLE_OBJECT = '$DurableObject'; + +function normalizePath(path: string): string { + return path.replace(/\\/g, '/'); +} + +/** + * On a Cloudflare preset, wraps the Nitro Worker entry with `withSentry` of `@sentry/cloudflare`, which gets its + * options from the default export of `optionsFile`, and names the transaction of each request. It also wraps the + * Durable Object that Nitro exports with `instrumentDurableObjectWithSentry`, and turns off a + * `sentryCloudflareNitroPlugin` of the app. It does nothing in dev and on the `cloudflare-worker` preset. + */ +export function setupCloudflareEntry(nuxt: Nuxt, optionsFile: string): void { + nuxt.hook('nitro:init', nitro => { + // The `cloudflare-dev` preset extends `nitro-dev`, so the dev server does not run the Worker entry. + if (nuxt.options._prepare || nitro.options.dev || !isCloudflarePreset(nitro.options.preset)) { + return; + } + + // The entry of this service worker preset of Nitro 2 has no default export. + if (nitro.options.preset.replace(/-/g, '_') === 'cloudflare_worker') { + consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn( + '[Sentry] The Worker of the `cloudflare-worker` preset has no default export, so Sentry cannot wrap it with `withSentry`. Use the `cloudflare-module` preset to set up the SDK from `sentry.cloudflare.config.ts`.', + ); + }); + return; + } + + nitro.options.rollupConfig ??= { output: {} }; + + if (nitro.options.rollupConfig.plugins === null || nitro.options.rollupConfig.plugins === undefined) { + nitro.options.rollupConfig.plugins = []; + } else if (!Array.isArray(nitro.options.rollupConfig.plugins)) { + nitro.options.rollupConfig.plugins = [nitro.options.rollupConfig.plugins]; + } + + const { baseURL, buildAssetsDir } = nuxt.options.app; + nitro.options.rollupConfig.plugins.push( + wrapCloudflareEntryWithSentry(nitro.options.entry, optionsFile, getNuxtBuildAssetsPath(baseURL, buildAssetsDir)), + ); + // Nitro runs its plugins in this order. This plugin must run first, because it tells a + // `sentryCloudflareNitroPlugin` of the app that `withSentry` already wraps each request. + const entryPlugin = createResolver(import.meta.url).resolve('./runtime/plugins/cloudflare-entry.server'); + nitro.options.plugins.unshift(entryPlugin); + // Nitro builds the prerenderer from the config of the app, which does not have the changes of this hook. + nitro.hooks.hook('prerender:config', prerenderConfig => { + prerenderConfig.plugins = [entryPlugin, ...(prerenderConfig.plugins ?? [])]; + }); + // db0 reads the D1 bindings from the instrumented `env`: Nitro 2 from `globalThis.__env__`, and Nitro 3 from the + // `env` of `cloudflare:workers`, which the wrapped entry sets. So the db0 instrumentation would add a second span + // for each D1 query. + skipDatabaseInstrumentation(nitro, 'cloudflare-d1'); + }); +} + +/** + * A Rollup plugin that replaces the Nitro Worker entry with a module that exports its default export and its + * `$DurableObject` export wrapped by `runtime/utils/wrapCloudflareEntry`, with the options that `optionsFile` + * returns, and all its other exports unchanged. `buildAssetsPath` is the path of the build output that the SDK ignores. + * + * Only exported for testing. + */ +export function wrapCloudflareEntryWithSentry(entry: string, optionsFile: string, buildAssetsPath?: string): Plugin { + let hasDurableObject = false; + let hasDefaultExport = true; + + const wrapperModule = createResolver(import.meta.url).resolve('./runtime/utils/wrapCloudflareEntry'); + + function getWrappedEntryCode(originalEntry: string): string { + const lines = [ + `import { wrapNitroCloudflareEntryWithSentry } from ${stringifyForCodeInjection(wrapperModule)};`, + `import userOptions from ${stringifyForCodeInjection(optionsFile)};`, + `import handler from ${stringifyForCodeInjection(originalEntry)};`, + `export * from ${stringifyForCodeInjection(originalEntry)};`, + `export default wrapNitroCloudflareEntryWithSentry(userOptions, handler, ${buildAssetsPath ? stringifyForCodeInjection(buildAssetsPath) : 'undefined'});`, + ]; + + // The local export takes precedence over the same name of `export *`. + if (hasDurableObject) { + lines.push( + `import { wrapNitroDurableObjectWithSentry } from ${stringifyForCodeInjection(wrapperModule)};`, + `import { ${NITRO_DURABLE_OBJECT} as NitroDurableObject } from ${stringifyForCodeInjection(originalEntry)};`, + `export const ${NITRO_DURABLE_OBJECT} = wrapNitroDurableObjectWithSentry(userOptions, NitroDurableObject);`, + ); + } + + return lines.join('\n'); + } + + return { + name: 'sentry-nuxt-cloudflare-entry', + async resolveId(source, importer, options) { + // Nitro passes its entry, a path without a file extension, as the Rollup input. + if (!options.isEntry || normalizePath(source) !== normalizePath(entry)) { + return null; + } + + const resolution = await this.resolve(source, importer, { ...options, skipSelf: true }); + if (!resolution || resolution.external) { + return null; + } + + // The `cloudflare` (service worker) preset registers a `fetch` listener and has no default export. + const moduleInfo = await this.load(resolution); + if (!moduleInfo.exports?.includes('default')) { + hasDefaultExport = false; + this.warn(`[Sentry] The Nitro entry has no default export, so Sentry cannot wrap it with \`withSentry\`.`); + return null; + } + + hasDurableObject = moduleInfo.exports.includes(NITRO_DURABLE_OBJECT); + return WRAPPED_ENTRY_ID; + }, + load(id) { + return id === WRAPPED_ENTRY_ID ? getWrappedEntryCode(entry) : null; + }, + // The Vite builder of Nitro 3 resolves the entry before it asks this plugin, so `resolveId` cannot replace the + // entry there. Then this hook replaces the code of the entry module. The new code imports the original code from + // the same file with a query, which Vite loads as a second module. + transform(code, id) { + if ( + !hasDefaultExport || + !this.getModuleInfo(id)?.isEntry || + normalizePath(id).replace(JS_EXTENSION_REGEX, '') !== normalizePath(entry).replace(JS_EXTENSION_REGEX, '') + ) { + return null; + } + + const exportedNames = getExportedNames(this.parse(code).body as ExportNode[]); + if (!exportedNames.has('default')) { + this.warn(`[Sentry] The Nitro entry has no default export, so Sentry cannot wrap it with \`withSentry\`.`); + return null; + } + + hasDurableObject = exportedNames.has(NITRO_DURABLE_OBJECT); + return { code: getWrappedEntryCode(`${id}${ORIGINAL_ENTRY_QUERY}`), map: { mappings: '' } }; + }, + }; +} + +const JS_EXTENSION_REGEX = /\.[cm]?[jt]s$/; + +type ExportNode = { + type: string; + declaration?: { id?: { name?: string }; declarations?: { id?: { name?: string } }[] } | null; + specifiers?: { exported?: { name?: string; value?: unknown } }[]; +}; + +function getExportedNames(programBody: ExportNode[]): Set { + const names = new Set(); + + for (const node of programBody) { + if (node.type === 'ExportDefaultDeclaration') { + names.add('default'); + } else if (node.type === 'ExportNamedDeclaration') { + names.add(node.declaration?.id?.name); + node.declaration?.declarations?.forEach(declaration => names.add(declaration.id?.name)); + node.specifiers?.forEach(specifier => names.add(specifier.exported?.name ?? specifier.exported?.value)); + } + } + + return names; +} diff --git a/packages/nuxt/src/vite/databaseConfig.ts b/packages/nuxt/src/vite/databaseConfig.ts index 159d42b093c3..571f53be517c 100644 --- a/packages/nuxt/src/vite/databaseConfig.ts +++ b/packages/nuxt/src/vite/databaseConfig.ts @@ -1,9 +1,12 @@ import { addNitroPlugin, createResolver } from '@nuxt/kit'; import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; -import type { NitroConfig } from 'nitropack/types'; +import type { ConnectorName } from 'db0'; +import type { Nitro, NitroConfig } from 'nitropack/types'; import type { SentryNuxtModuleOptions } from '../common/types'; import { addServerTemplate } from '../vendor/server-template'; +const DATABASE_CONFIG_TEMPLATE = '#sentry/database-config.mjs'; + /** * Sets up the database instrumentation. */ @@ -36,10 +39,8 @@ export function addDatabaseInstrumentation( // Create a virtual module to pass this data to runtime addServerTemplate({ - filename: '#sentry/database-config.mjs', - getContents: () => { - return `export const databaseConfig = ${stringifyForCodeInjection(databaseConfig)};`; - }, + filename: DATABASE_CONFIG_TEMPLATE, + getContents: () => getDatabaseConfigModule(databaseConfig), }); if (isLegacyNitro) { @@ -48,3 +49,21 @@ export function addDatabaseInstrumentation( addNitroPlugin(createResolver(import.meta.url).resolve('./runtime/plugins/database.server')); } } + +/** + * Leaves the databases with the given db0 connector out of the database instrumentation of this Nitro build. + */ +export function skipDatabaseInstrumentation(nitro: Nitro, connector: ConnectorName): void { + if (!nitro.options.virtual[DATABASE_CONFIG_TEMPLATE]) { + return; + } + + const databaseConfig = Object.fromEntries( + Object.entries(nitro.options.database ?? {}).filter(([, config]) => config.connector !== connector), + ); + nitro.options.virtual[DATABASE_CONFIG_TEMPLATE] = () => getDatabaseConfigModule(databaseConfig); +} + +function getDatabaseConfigModule(databaseConfig: object): string { + return `export const databaseConfig = ${stringifyForCodeInjection(databaseConfig)};`; +} diff --git a/packages/nuxt/src/vite/nitroServer.ts b/packages/nuxt/src/vite/nitroServer.ts index 91c164ad75f9..2d8a553fd6a3 100644 --- a/packages/nuxt/src/vite/nitroServer.ts +++ b/packages/nuxt/src/vite/nitroServer.ts @@ -21,12 +21,16 @@ type NitroModuleOptions = Omit, - serverConfigFile: string, + serverConfigFile: string | undefined, moduleOptions: NitroModuleOptions, + hasCloudflareOptionsFile: boolean, ): void { const isNitroV3 = serverApi === 'nitro3'; const moduleDirResolver = createResolver(import.meta.url); @@ -36,8 +40,8 @@ export function setupNitroServer( const deprecatedInjectMode = injectMode === 'top-level-import' || injectMode === 'experimental_dynamic-import' ? injectMode : undefined; - if (!deprecatedInjectMode) { - addServerConfigPlugin(nuxt, serverConfigFile, !isNitroV3); + if (serverConfigFile && !deprecatedInjectMode) { + addServerConfigPlugin(nuxt, serverConfigFile, !isNitroV3, hasCloudflareOptionsFile); } if (isNitroV3) { @@ -69,6 +73,10 @@ export function setupNitroServer( addCacheStorageInstrumentation(nitro); } + if (!serverConfigFile) { + return; + } + if (deprecatedInjectMode) { setupDeprecatedInjectMode(nitro, deprecatedInjectMode, isNitroV3, serverConfigFile, moduleOptions); return; diff --git a/packages/nuxt/src/vite/orchestrion.ts b/packages/nuxt/src/vite/orchestrion.ts index 101545f018b9..190a6ddb457a 100644 --- a/packages/nuxt/src/vite/orchestrion.ts +++ b/packages/nuxt/src/vite/orchestrion.ts @@ -12,14 +12,16 @@ import { isCloudflarePreset } from './utils'; // external makes Nitro resolve the default export as a namespace object. const IORedisDependencies = ['standard-as-callback']; +const CLOUDFLARE_DC_MODULE = '@sentry/cloudflare/orchestrion-diagnostics-channel'; + /** * Configures Nitro to bundle and transform dependencies that publish tracing * events through diagnostics channels. * * `hasServerConfig` reflects whether a `sentry.server.config` file was found. On Node the SDK is * initialized from that file, so orchestrion only makes sense when it exists. On Cloudflare the SDK - * is initialized through `sentryCloudflareNitroPlugin` instead (no server config file), so the - * transform must still run there — detected via the Nitro preset. + * is initialized through `withSentry` or `sentryCloudflareNitroPlugin` instead (no server config file), so the + * transform must still run there, detected via the Nitro preset. */ export function setupOrchestrion(nuxt: Nuxt, hasServerConfig: boolean, buildTimeInstrumentation?: boolean): void { if (buildTimeInstrumentation === false) { @@ -37,8 +39,8 @@ export function setupOrchestrion(nuxt: Nuxt, hasServerConfig: boolean, buildTime return; } - // On Cloudflare (workerd) the SDK is initialized through `sentryCloudflareNitroPlugin` (no - // server config file), so the transform must still run there — detected via the Nitro preset. + // On Cloudflare (workerd) the SDK is initialized through `withSentry` or `sentryCloudflareNitroPlugin` (no + // server config file), so the transform must still run there, detected via the Nitro preset. const isCloudflare = isCloudflarePreset(nitroConfig.preset); if (!hasServerConfig && !isCloudflare) { @@ -53,7 +55,11 @@ export function setupOrchestrion(nuxt: Nuxt, hasServerConfig: boolean, buildTime nitroConfig.rollupConfig.plugins = [nitroConfig.rollupConfig.plugins]; } - nitroConfig.rollupConfig.plugins.push(sentryOrchestrionPlugin({}), sentryCommonJSInteropPlugin()); + nitroConfig.rollupConfig.plugins.push( + // On workerd, the facade defers the channel events of module-scope calls until a request runs. + sentryOrchestrionPlugin(isCloudflare ? { dcModule: CLOUDFLARE_DC_MODULE } : {}), + sentryCommonJSInteropPlugin(), + ); const externals = (nitroConfig.externals ||= {}); const inline = externals.inline; diff --git a/packages/nuxt/src/vite/publicFiles.ts b/packages/nuxt/src/vite/publicFiles.ts new file mode 100644 index 000000000000..bbe0d8855ddd --- /dev/null +++ b/packages/nuxt/src/vite/publicFiles.ts @@ -0,0 +1,63 @@ +import { getLayerDirectories } from '@nuxt/kit'; +import type { Nuxt } from '@nuxt/schema'; +import { isStaticAssetRequest } from '@sentry/core/server'; +import type { Nitro } from 'nitropack'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +type PublicDir = { dir: string; baseURL?: string }; + +/** Returns the paths of the files Nitro serves from its public asset dirs, without the client build. */ +export function getNitroPublicFilePaths(nitro: Nitro, nuxt: Nuxt): string[] { + const clientBuildDir = path.resolve(nuxt.options.buildDir, 'dist/client'); + const publicDirs = nitro.options.publicAssets.filter( + asset => !isInDirectory(path.resolve(asset.dir), clientBuildDir), + ); + return getPublicFilePaths(publicDirs, nuxt.options.app.baseURL); +} + +/** Returns the paths of the files in the `public/` dirs of all layers, which the Vite server serves. */ +export function getLayerPublicFilePaths(nuxt: Nuxt): string[] { + const publicDirs = getLayerDirectories(nuxt).map(dirs => ({ dir: dirs.public })); + return getPublicFilePaths(publicDirs, nuxt.options.app.baseURL); +} + +/** + * Returns the URL paths of the files, without `app.baseURL`. Skips files the HTTP integration already ignores, + * so the user's `ignoreStaticAssets` option still applies to them. + */ +function getPublicFilePaths(publicDirs: PublicDir[], baseURL: string): string[] { + return publicDirs + .flatMap(({ dir, baseURL: dirURL }) => + listFiles(path.resolve(dir)).map(file => + path.posix.join('/', dirURL ?? '', toUrlPath(path.relative(path.resolve(dir), file))), + ), + ) + .filter(urlPath => !isStaticAssetRequest(path.posix.join('/', baseURL, urlPath))); +} + +/** + * Percent-encodes the file path the way a browser encodes the request path, because spans store the encoded path. + * `%`, `#` and `?` are part of the file name, so they are escaped before URL parsing. + */ +function toUrlPath(relativeFilePath: string): string { + const filePath = relativeFilePath.split(path.sep).join('/').replace(/[%#?]/g, encodeURIComponent); + return new URL(filePath, 'http://localhost/').pathname; +} + +function listFiles(dir: string): string[] { + if (!fs.existsSync(dir)) { + return []; + } + + return fs + .readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter(entry => entry.isFile()) + .map(entry => path.join(entry.parentPath, entry.name)); +} + +/** Also true for the dir itself. */ +function isInDirectory(file: string, dir: string): boolean { + const relativePath = path.relative(dir, file); + return relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath); +} diff --git a/packages/nuxt/src/vite/sourceMapDeletion.ts b/packages/nuxt/src/vite/sourceMapDeletion.ts index 874381d66b36..12e7b7ab0cc7 100644 --- a/packages/nuxt/src/vite/sourceMapDeletion.ts +++ b/packages/nuxt/src/vite/sourceMapDeletion.ts @@ -1,30 +1,56 @@ -import { createSentryBuildPluginManager, globFiles, type Options } from '@sentry/bundler-plugins/core'; +import { + createSentryBuildPluginManager, + globFiles, + type InternalOptions, + type Options, +} from '@sentry/bundler-plugins/core'; +import type { NitroConfig } from 'nitropack'; import * as fs from 'node:fs'; import * as path from 'node:path'; -/** Nitro's output directories, which depend on the Nitro preset, e.g. `dist` for the public files on Netlify. */ -type NitroOutputDirs = { publicDir: string; serverDir: string }; - -/** The sides whose source maps only exist because Sentry enabled them, and where Nitro writes them once it is set up. */ -export type DeletionFallback = { client: boolean; server: boolean; outputDirs?: NitroOutputDirs }; +/** + * The sides whose source maps only exist because Sentry enabled them, and where Nitro writes them once it is set + * up. `publicDir` is only set for a builder other than Vite, where no Vite plugin removes the client maps. + */ +export type DeletionFallback = { client: boolean; server: boolean; serverDir?: string; publicDir?: string }; /** * Globs for the source maps in Nitro's output directories of the sides whose source maps only exist because Sentry - * enabled them. Empty until Nitro is set up. + * enabled them. Empty until Nitro is set up. With the Vite builder, the Vite plugin removes the client maps itself. + * + * `sourcemaps.delete` replaces that rule: `true` covers both sides, `false` none. */ -export function getFallbackFilesToDelete(fallback: DeletionFallback | undefined): string[] { - if (!fallback?.outputDirs) { +export function getFallbackFilesToDelete(fallback: DeletionFallback | undefined, deleteOption?: boolean): string[] { + if (fallback?.serverDir === undefined || deleteOption === false) { return []; } - const { client, server, outputDirs } = fallback; - const { publicDir, serverDir } = outputDirs; + const { serverDir, publicDir } = fallback; + const client = deleteOption ?? fallback.client; + const server = deleteOption ?? fallback.server; return [ - ...(client ? getPublicSourceMapGlobs(publicDir, server ? undefined : serverDir) : []), + ...(client && publicDir !== undefined ? getPublicSourceMapGlobs(publicDir, server ? undefined : serverDir) : []), ...(server ? [`${toGlobPath(serverDir)}/**/*.map`] : []), ]; } +/** + * `rollupConfig.output.sourcemap` overrides `sourcemap.server`, so the server source maps are then the user's. + * `sourcemaps.delete: true` removes the server maps, so no `sourceMappingURL` comment may point to them. + */ +export function applyNitroSourceMapSettings( + nitroConfig: NitroConfig, + fallback: DeletionFallback, + deleteOption: boolean | undefined, +): void { + const userOutputSetting = nitroConfig.rollupConfig?.output?.sourcemap !== undefined; + fallback.server &&= !userOutputSetting; + + if (deleteOption === true && nitroConfig.sourceMap === true && !userOutputSetting) { + nitroConfig.sourceMap = 'hidden'; + } +} + /** Some presets write the server into the public dir, e.g. Cloudflare Pages into `dist/_worker.js`. */ function getPublicSourceMapGlobs(publicDir: string, keptServerDir: string | undefined): string[] { const publicGlob = toGlobPath(publicDir); @@ -37,17 +63,106 @@ function getPublicSourceMapGlobs(publicDir: string, keptServerDir: string | unde return [`${publicGlob}/*.map`, `${publicGlob}/!(${serverDirName})/**/*.map`]; } +/** Only the Vite builder runs the Vite plugin that removes the client source maps. */ +export function isViteBuilder(nuxt: { options: { builder?: unknown } }): boolean { + const { builder } = nuxt.options; + return builder === undefined || builder === 'vite' || builder === '@nuxt/vite-builder'; +} + +export function logSentryEnabledSourceMaps(fallback: DeletionFallback, deleteOption?: boolean): void { + for (const side of ['client', 'server'] as const) { + if (fallback[side] && deleteOption !== undefined) { + // eslint-disable-next-line no-console + console.log( + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. ${ + deleteOption + ? 'Sentry deletes them from the build output.' + : 'They stay in the build output, because `sourcemaps.delete` is `false`.' + }`, + ); + } else if (fallback[side]) { + // eslint-disable-next-line no-console + console.log( + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + ); + } + } +} + /** `filesToDeleteAfterUpload` is matched from the working directory and needs forward slashes, also on Windows. */ function toGlobPath(directory: string): string { return path.relative(process.cwd(), directory).split(path.sep).join('/') || '.'; } +/** + * Options for the Vite plugin of the client build. It removes the client maps Sentry enabled, unless the + * user set `filesToDeleteAfterUpload`. The user's glob runs in the Nitro build instead, because a broad + * glob would also match the SSR maps Nitro still needs. The SDK never read the user's + * `deleteSourcemapsAfterUpload`, and `delete` replaces it. + * + * `sourcemaps.delete` replaces that rule for the client environment: `true` removes every client map, `false` + * none. The plugin does not get the option itself, because it would also remove the SSR maps. + * + * The Vite server runs no Nitro, so a second plugin runs in its server environments (`viteServer`) and applies + * the same rules to the server maps there. + */ +export function withClientSourceMapDeletion( + options: Options, + userSourcemaps: Pick, 'delete' | 'filesToDeleteAfterUpload'> | undefined, + fallback: DeletionFallback, + viteServer = false, +): InternalOptions { + // The Vite server plugin is only added to server builds, so a build without an environment name is the server. + const getSide = (environment: string | undefined): 'client' | 'server' | undefined => + viteServer + ? environment === 'client' + ? 'client' + : 'server' + : isClientEnvironment(environment) + ? 'client' + : undefined; + + return { + ...options, + sourcemaps: { + ...options.sourcemaps, + filesToDeleteAfterUpload: undefined, + delete: undefined, + // The Vite plugin reads these in its `config` hook, after `modules:done` set the fallback. + deleteSourcemapsAfterUpload: environment => { + const side = getSide(environment); + if (side === undefined) { + return undefined; + } + if (userSourcemaps?.delete !== undefined) { + return userSourcemaps.delete; + } + return fallback[side] && userSourcemaps?.filesToDeleteAfterUpload === undefined ? true : undefined; + }, + // Makes the plugin remove every source map of the environment, not only those of uploaded chunks. + sdkEnabledSourceMaps: environment => { + const side = getSide(environment); + return side !== undefined && (userSourcemaps?.delete === true || fallback[side]); + }, + }, + }; +} + +/** + * With the Vite environment API, one config holds the `client` and the server environments. Without it, the + * plugin is only part of the client config, which has no named environments. + */ +function isClientEnvironment(environment: string | undefined): boolean { + return environment === undefined || environment === 'client'; +} + export function withoutSourceMapDeletion(options: Options): Options { return { ...options, sourcemaps: { ...options.sourcemaps, filesToDeleteAfterUpload: undefined, + delete: undefined, deleteSourcemapsAfterUpload: false, }, }; diff --git a/packages/nuxt/src/vite/sourceMapSettings.ts b/packages/nuxt/src/vite/sourceMapSettings.ts index a03899e4ce73..c78faed3c76e 100644 --- a/packages/nuxt/src/vite/sourceMapSettings.ts +++ b/packages/nuxt/src/vite/sourceMapSettings.ts @@ -1,3 +1,7 @@ +import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; +import type { SentryNuxtModuleOptions } from '../common/types'; + /** A valid source map setting */ export type SourceMapSetting = boolean | 'hidden' | 'inline'; @@ -37,3 +41,51 @@ export function validateDifferentSourceMapSettings({ ); } } + +/** + * Whether Sentry turns source maps on that the user did not set: when it uploads them, or when + * `sourcemaps.delete: false` keeps them for a manual upload. + */ +export function sentryEnablesSourceMaps(moduleOptions: SentryNuxtModuleOptions): boolean { + const { sourcemaps } = moduleOptions; + const { injectDebugIds, upload, legacyDisable } = resolveSourceMapsFeatures(sourcemaps); + // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. + return ( + legacyDisable === 'disable-upload' || + (upload && hasSourceMapUploadCredentials(moduleOptions)) || + (sourcemaps?.delete === false && injectDebugIds) + ); +} + +/** Logs that the user's source map setting is kept. */ +export function logKeepEnabledSourceMapSetting( + sentryNuxtModuleOptions: SentryNuxtModuleOptions, + settingKey: string, + settingValue: string, +): void { + if (sentryNuxtModuleOptions.debug) { + // eslint-disable-next-line no-console + console.log( + `[Sentry] \`${settingKey}\` is enabled with \`${settingValue}\`. This will correctly un-minify the code snippet on the Sentry Issue Details page.`, + ); + } +} + +/** Warns that the user turned source maps off. */ +export function warnExplicitlyDisabledSourceMap(settingKey: string, isDebug: boolean | undefined): void { + if (isDebug) { + // eslint-disable-next-line no-console + console.warn( + `[Sentry] Source map generation is currently disabled in your Vite configuration (\`${settingKey}: false \`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`, + ); + } else { + // eslint-disable-next-line no-console + console.warn(`[Sentry] Source map generation (\`${settingKey}\`) is disabled in your Vite configuration.`); + } +} + +/** Logs that Sentry turned source maps on. */ +export function logSentryEnablesSourceMap(settingKey: string, settingValue: string): void { + // eslint-disable-next-line no-console + console.log(`[Sentry] Enabled source map generation in the build options with \`${settingKey}: ${settingValue}\`.`); +} diff --git a/packages/nuxt/src/vite/sourceMaps.ts b/packages/nuxt/src/vite/sourceMaps.ts index 0fbcdacf8981..ded5a827068a 100644 --- a/packages/nuxt/src/vite/sourceMaps.ts +++ b/packages/nuxt/src/vite/sourceMaps.ts @@ -2,22 +2,30 @@ import type { Nuxt } from '@nuxt/schema'; import { resolveReleaseName } from '@sentry/bundler-plugins/core'; import { sentryRollupPlugin, type SentryRollupPluginOptions } from '@sentry/bundler-plugins/rollup'; import { sentryVitePlugin, type SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; -import { warnOnRemovedBuildOptions } from '@sentry/core'; +import { resolveSourceMapsFeatures, warnOnRemovedBuildOptions } from '@sentry/core'; import type { NitroConfig } from 'nitropack'; import type { Plugin } from 'vite'; import type { SentryNuxtModuleOptions } from '../common/types'; import { + applyNitroSourceMapSettings, deletePublicSourceMaps, deleteSourceMapsAfterBuild, type DeletionFallback, getFallbackFilesToDelete, + isViteBuilder, + logSentryEnabledSourceMaps, + withClientSourceMapDeletion, withoutSourceMapDeletion, } from './sourceMapDeletion'; import { validateSourceMapsOptionsPlugin } from './sentryVitePlugin'; import { extractNuxtSourceMapSetting, + logKeepEnabledSourceMapSetting, + logSentryEnablesSourceMap, + sentryEnablesSourceMaps, type SourceMapSetting, validateDifferentSourceMapSettings, + warnExplicitlyDisabledSourceMap, } from './sourceMapSettings'; /** @@ -25,6 +33,8 @@ import { */ export type UserSourceMapSetting = 'enabled' | 'disabled' | 'unset' | undefined; +type AddVitePluginOptions = { dev?: boolean; build?: boolean; server?: boolean; client?: boolean }; + /** The public runtime config key that gives the release to the client SDK. */ export const NUXT_RELEASE_RUNTIME_CONFIG_KEY = '_sentryRelease'; @@ -34,8 +44,9 @@ export const NUXT_RELEASE_RUNTIME_CONFIG_KEY = '_sentryRelease'; export function setupSourceMaps( moduleOptions: SentryNuxtModuleOptions, nuxt: Nuxt, - addVitePlugin: (plugin: Plugin[], options?: { dev?: boolean; build?: boolean; server?: boolean }) => void, + addVitePlugin: (plugin: Plugin[], options?: AddVitePluginOptions) => void, hasClientConfigFile = false, + viteServer = false, ): void { // Warn here rather than in `getPluginOptions`, which runs once per bundler (Vite and Nitro's // Rollup) and would emit the same warning twice. @@ -43,7 +54,8 @@ export function setupSourceMaps( const isDebug = moduleOptions.debug; - const sourceMapsEnabled = moduleOptions.sourcemaps?.disable !== true; + // TODO(v12): Add the Sentry plugins with `sourcemaps.disable: true` too, like with the options that replace it. + const sourceMapsEnabled = resolveSourceMapsFeatures(moduleOptions.sourcemaps).legacyDisable !== true; // In case we overwrite the source map settings, we default to deleting the files const shouldDeleteFilesFallback: DeletionFallback = { client: true, server: true }; @@ -58,29 +70,13 @@ export function setupSourceMaps( // ONLY THIS nuxt.sourcemap.(server/client) setting is the one Sentry will overwrite with 'hidden', if needed. const previousSourceMapSettings = changeNuxtSourceMapSettings(nuxt, moduleOptions); + const sentryEnabled = sentryEnablesSourceMaps(moduleOptions); // Mutate in place so the Vite plugin (which captured this object at registration time) sees the updated values - shouldDeleteFilesFallback.client = previousSourceMapSettings.client === 'unset'; - shouldDeleteFilesFallback.server = previousSourceMapSettings.server === 'unset'; - - if (isDebug && (shouldDeleteFilesFallback.client || shouldDeleteFilesFallback.server)) { - const enabledDeleteFallbacks = - shouldDeleteFilesFallback.client && shouldDeleteFilesFallback.server - ? 'client-side and server-side' - : shouldDeleteFilesFallback.server - ? 'server-side' - : 'client-side'; - - if (!moduleOptions.sourcemaps?.filesToDeleteAfterUpload) { - // eslint-disable-next-line no-console - console.log( - `[Sentry] We enabled \`'hidden'\` source maps for your ${enabledDeleteFallbacks} build. Source map files will be automatically deleted after uploading them to Sentry.`, - ); - } else { - // eslint-disable-next-line no-console - console.log( - `[Sentry] We enabled \`'hidden'\` source maps for your ${enabledDeleteFallbacks} build. Source map files will be deleted according to your \`sourcemaps.filesToDeleteAfterUpload\` configuration. To use automatic deletion instead, leave \`filesToDeleteAfterUpload\` empty.`, - ); - } + shouldDeleteFilesFallback.client = sentryEnabled && previousSourceMapSettings.client === 'unset'; + shouldDeleteFilesFallback.server = sentryEnabled && previousSourceMapSettings.server === 'unset'; + + if (isDebug) { + logSentryEnabledSourceMaps(shouldDeleteFilesFallback, moduleOptions.sourcemaps?.delete); } } }); @@ -92,19 +88,32 @@ export function setupSourceMaps( build: true, }); - const clientPluginOptions = getPluginOptions(moduleOptions, shouldDeleteFilesFallback); + const clientPluginOptions = getPluginOptions(moduleOptions); addVitePlugin( sentryVitePlugin( - withoutSourceMapDeletion( + withClientSourceMapDeletion( // Only the generated client config plugin reads the release from the runtime config. hasClientConfigFile ? moveClientReleaseToRuntimeConfig(nuxt, moduleOptions, clientPluginOptions) : clientPluginOptions, + moduleOptions.sourcemaps, + shouldDeleteFilesFallback, ), ), // Nitro bundles the SSR output again, so debug IDs from the SSR build would point to the wrong maps. { dev: false, build: true, server: false }, ); + + if (viteServer) { + // The Vite server runs no Nitro, so its SSR output is final and no Rollup plugin uploads it. A plugin of + // its own injects the release, which the client plugin leaves to the runtime config. + addVitePlugin( + sentryVitePlugin( + withClientSourceMapDeletion(clientPluginOptions, moduleOptions.sourcemaps, shouldDeleteFilesFallback, true), + ), + { dev: false, build: true, client: false }, + ); + } } nuxt.hook('nitro:config', (nitroConfig: NitroConfig) => { @@ -119,9 +128,7 @@ export function setupSourceMaps( } validateNitroSourceMapSettings(nuxt, nitroConfig, moduleOptions); - - // `rollupConfig.output.sourcemap` overrides `sourcemap.server`, so the server source maps are the user's. - shouldDeleteFilesFallback.server &&= nitroConfig.rollupConfig.output?.sourcemap === undefined; + applyNitroSourceMapSettings(nitroConfig, shouldDeleteFilesFallback, moduleOptions.sourcemaps?.delete); if (isDebug) { // eslint-disable-next-line no-console @@ -139,7 +146,10 @@ export function setupSourceMaps( nuxt.hook('nitro:init', nitro => { if (sourceMapsEnabled && !nitro.options.dev && !nuxt.options?._prepare) { const publicDir = nitro.options.output.publicDir; - shouldDeleteFilesFallback.outputDirs = { publicDir, serverDir: nitro.options.output.serverDir }; + shouldDeleteFilesFallback.serverDir = nitro.options.output.serverDir; + if (!isViteBuilder(nuxt)) { + shouldDeleteFilesFallback.publicDir = publicDir; + } const rollupConfig = (nitro.options.rollupConfig ??= { output: {} }); rollupConfig.plugins = [ @@ -230,6 +240,10 @@ export function getPluginOptions( sourcemaps: { disable: moduleOptions.sourcemaps?.disable, + upload: sourcemapsOptions.upload, + injectDebugIds: sourcemapsOptions.injectDebugIds, + // `sourcemaps.delete` does not reach the plugins: `withClientSourceMapDeletion` and + // `filesToDeleteAfterUpload` apply it, because Nitro still needs the maps of the SSR build. // The server/client files are in different places depending on the nitro preset (e.g. '.output/server' or '.netlify/functions-internal/server') // We cannot determine automatically how the build folder looks like (depends on the preset), so each plugin uploads its own build output (the vitePlugin for the Nuxt client and the rollupPlugin for Nitro). // If we could know where the server/client assets are located, we could do something like this (based on the Nitro preset): isNitro ? ['./.output/server/**/*'] : ['./.output/public/**/*'], @@ -243,23 +257,31 @@ export function getPluginOptions( } /** - * Determines which files to delete after upload. If the user set `filesToDeleteAfterUpload`, we use - * that. Otherwise we only delete the source maps Sentry generated itself — i.e. the sides - * (client/server) whose `sourcemap` setting resolved to `undefined`, where Sentry stepped in and - * enabled `'hidden'`. Given Nuxt's default of `{ server: true, client: false }`, this isn't the - * default case: it only kicks in when a side is left `undefined` (whole config or a single sub-key). - * Sentry deletes them in Nitro's output directories, which are only known once Nitro is set up. + * Determines which files to delete after the build. If the user set `filesToDeleteAfterUpload`, we use + * that. Otherwise we only delete the source maps Sentry generated itself, i.e. when the `sourcemap` setting + * of a side resolved to `undefined` and Sentry enabled `'hidden'`. This covers the server maps, and the + * client maps with a builder other than Vite. Sentry deletes them in Nitro's output directories, which are + * only known once Nitro is set up. + * + * `sourcemaps.delete: true` deletes the source maps of both sides next to the user's files, and + * `sourcemaps.delete: false` only the user's files. * @see https://nuxt.com/docs/4.x/api/nuxt-config#sourcemap */ function resolveFilesToDeleteAfterUpload( moduleOptions: SentryNuxtModuleOptions, shouldDeleteFilesFallback?: DeletionFallback, ): string | Array | undefined { - const fallbackFilesToDelete = getFallbackFilesToDelete(shouldDeleteFilesFallback); + const deleteOption = moduleOptions.sourcemaps?.delete; + const fallbackFilesToDelete = getFallbackFilesToDelete(shouldDeleteFilesFallback, deleteOption); const shouldDeleteFilesAfterUpload = fallbackFilesToDelete.length > 0; const filesToDeleteAfterUpload = moduleOptions.sourcemaps?.filesToDeleteAfterUpload; + if (deleteOption === true) { + const files = [...fallbackFilesToDelete, ...[filesToDeleteAfterUpload ?? []].flat()]; + return files.length > 0 ? files : undefined; + } + if (typeof filesToDeleteAfterUpload === 'undefined' && shouldDeleteFilesAfterUpload && moduleOptions.debug) { // eslint-disable-next-line no-console console.log( @@ -270,7 +292,7 @@ function resolveFilesToDeleteAfterUpload( ); } - return filesToDeleteAfterUpload + return filesToDeleteAfterUpload !== undefined ? filesToDeleteAfterUpload : shouldDeleteFilesAfterUpload ? fallbackFilesToDelete @@ -284,8 +306,11 @@ function resolveFilesToDeleteAfterUpload( 2. users enabled source map generation (true, hidden, inline). - keep this setting (don't do anything - like deletion - besides uploading) 3. users did not set source maps generation - - we enable 'hidden' source maps generation - - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this) + - we enable 'hidden' source maps generation when Sentry uploads the maps, or when `sourcemaps.delete: false` + keeps them for a manual upload. Otherwise we leave it unset + - client with the Vite builder: pass `deleteSourcemapsAfterUpload: true`, so the maps never reach the build output + - client with another builder: configure `filesToDeleteAfterUpload` for the .map files in Nitro's public dir + - server: configure `filesToDeleteAfterUpload` to delete the .map files after the build (we emit a log about this) Users only have to explicitly enable client source maps. Sentry only overwrites the base Nuxt source map settings as they propagate. */ @@ -304,6 +329,7 @@ export function changeNuxtSourceMapSettings( const nuxtSourceMap = nuxt.options.sourcemap; const isDebug = sentryModuleOptions.debug; + const sentryEnabled = sentryEnablesSourceMaps(sentryModuleOptions); if (typeof nuxtSourceMap === 'string' || typeof nuxtSourceMap === 'boolean' || typeof nuxtSourceMap === 'undefined') { switch (nuxtSourceMap) { @@ -318,9 +344,11 @@ export function changeNuxtSourceMapSettings( previousUserSourceMapSetting = { client: 'enabled', server: 'enabled' }; break; case undefined: - nuxt.options.sourcemap = { server: 'hidden', client: 'hidden' }; - isDebug && logSentryEnablesSourceMap('sourcemap.client', 'hidden'); - isDebug && logSentryEnablesSourceMap('sourcemap.server', 'hidden'); + if (sentryEnabled) { + nuxt.options.sourcemap = { server: 'hidden', client: 'hidden' }; + isDebug && logSentryEnablesSourceMap('sourcemap.client', 'hidden'); + isDebug && logSentryEnablesSourceMap('sourcemap.server', 'hidden'); + } previousUserSourceMapSetting = { client: 'unset', server: 'unset' }; break; } @@ -332,8 +360,10 @@ export function changeNuxtSourceMapSettings( logKeepEnabledSourceMapSetting(sentryModuleOptions, 'sourcemap.client', nuxtSourceMap.client.toString()); previousUserSourceMapSetting.client = 'enabled'; } else { - nuxt.options.sourcemap.client = 'hidden'; - isDebug && logSentryEnablesSourceMap('sourcemap.client', 'hidden'); + if (sentryEnabled) { + nuxt.options.sourcemap.client = 'hidden'; + isDebug && logSentryEnablesSourceMap('sourcemap.client', 'hidden'); + } previousUserSourceMapSetting.client = 'unset'; } @@ -344,8 +374,10 @@ export function changeNuxtSourceMapSettings( logKeepEnabledSourceMapSetting(sentryModuleOptions, 'sourcemap.server', nuxtSourceMap.server.toString()); previousUserSourceMapSetting.server = 'enabled'; } else { - nuxt.options.sourcemap.server = 'hidden'; - isDebug && logSentryEnablesSourceMap('sourcemap.server', 'hidden'); + if (sentryEnabled) { + nuxt.options.sourcemap.server = 'hidden'; + isDebug && logSentryEnablesSourceMap('sourcemap.server', 'hidden'); + } previousUserSourceMapSetting.server = 'unset'; } } @@ -404,33 +436,3 @@ export function validateNitroSourceMapSettings( ); } } - -function logKeepEnabledSourceMapSetting( - sentryNuxtModuleOptions: SentryNuxtModuleOptions, - settingKey: string, - settingValue: string, -): void { - if (sentryNuxtModuleOptions.debug) { - // eslint-disable-next-line no-console - console.log( - `[Sentry] \`${settingKey}\` is enabled with \`${settingValue}\`. This will correctly un-minify the code snippet on the Sentry Issue Details page.`, - ); - } -} - -function warnExplicitlyDisabledSourceMap(settingKey: string, isDebug: boolean | undefined): void { - if (isDebug) { - // eslint-disable-next-line no-console - console.warn( - `[Sentry] Source map generation is currently disabled in your Vite configuration (\`${settingKey}: false \`). This setting is either a default setting or was explicitly set in your configuration. Sentry won't override this setting. Without source maps, code snippets on the Sentry Issues page will remain minified. To show unminified code, enable source maps in \`${settingKey}\` (e.g. by setting them to \`hidden\`).`, - ); - } else { - // eslint-disable-next-line no-console - console.warn(`[Sentry] Source map generation (\`${settingKey}\`) is disabled in your Vite configuration.`); - } -} - -function logSentryEnablesSourceMap(settingKey: string, settingValue: string): void { - // eslint-disable-next-line no-console - console.log(`[Sentry] Enabled source map generation in the build options with \`${settingKey}: ${settingValue}\`.`); -} diff --git a/packages/nuxt/src/vite/utils.ts b/packages/nuxt/src/vite/utils.ts index 9619318907c0..898187390c10 100644 --- a/packages/nuxt/src/vite/utils.ts +++ b/packages/nuxt/src/vite/utils.ts @@ -5,7 +5,9 @@ import * as path from 'path'; import { fileURLToPath } from 'node:url'; import type { SentryNuxtModuleOptions } from '../common/types'; import { addTemplate, resolvePath, resolveServerVariant } from '@nuxt/kit'; +import { NUXT_BUILD_ASSETS_DIR_GLOBAL, NUXT_PUBLIC_FILES_GLOBAL } from '../common/buildAssets'; import { NUXT_DEV_MODE_FLAG, NUXT_PRERENDER_FLAG } from '../common/devMode'; +import { NUXT_BASE_PATH_GLOBAL } from '../common/tunnel'; import { NUXT_NITRO_PRESET_FLAG } from '../runtime/utils/pageMetaTags'; const SERVER_API_VARIANTS = { nitro2: 'nitro2', nitro3: 'nitro3', nuxt: 'nuxt' } as const; @@ -28,9 +30,27 @@ export async function findDefaultSdkInitFile( type: 'server' | 'client', nuxt?: Nuxt, options?: SentryNuxtModuleOptions, +): Promise { + return findConfigFile(`sentry.${type}.config`, nuxt, options); +} + +/** + * Find the `sentry.cloudflare.config` file, whose default export returns the options of `@sentry/cloudflare`. + */ +export async function findCloudflareOptionsFile( + nuxt?: Nuxt, + options?: SentryNuxtModuleOptions, +): Promise { + return findConfigFile('sentry.cloudflare.config', nuxt, options); +} + +async function findConfigFile( + basename: string, + nuxt?: Nuxt, + options?: SentryNuxtModuleOptions, ): Promise { const possibleFileExtensions = ['ts', 'js', 'mjs', 'cjs', 'mts', 'cts']; - const relativePaths = possibleFileExtensions.map(ext => `sentry.${type}.config.${ext}`); + const relativePaths = possibleFileExtensions.map(ext => `${basename}.${ext}`); // Get layers from highest priority to lowest const layers = [...(nuxt?.options._layers ?? [])].reverse(); @@ -247,16 +267,19 @@ export function addRuntimeInjectionTraceDep(nuxt: Nuxt, isNitroV3: boolean): voi * 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 { +export function addRuntimeFlagsTemplate(getPublicFilePaths: () => string[] = () => []): ResolvedNuxtTemplate { return addTemplate({ filename: 'sentry-runtime-flags.mjs', write: true, - getContents: () => + getContents: ({ nuxt }) => [ '// 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;`, + `globalThis.${NUXT_BASE_PATH_GLOBAL} = ${stringifyForCodeInjection(nuxt.options.app.baseURL)};`, + `globalThis.${NUXT_BUILD_ASSETS_DIR_GLOBAL} = ${stringifyForCodeInjection(nuxt.options.app.buildAssetsDir)};`, + `globalThis.${NUXT_PUBLIC_FILES_GLOBAL} = ${stringifyForCodeInjection(getPublicFilePaths())};`, '', ].join('\n'), }); diff --git a/packages/nuxt/src/vite/viteServer.ts b/packages/nuxt/src/vite/viteServer.ts index 2cc86244ae46..4f43d5876178 100644 --- a/packages/nuxt/src/vite/viteServer.ts +++ b/packages/nuxt/src/vite/viteServer.ts @@ -4,6 +4,7 @@ import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import type { Plugin } from 'vite'; import type { SentryNuxtModuleOptions } from '../common/types'; +import { getLayerPublicFilePaths } from './publicFiles'; import { addRuntimeFlagsTemplate } from './utils'; const SERVER_ENTRY_ALIAS = '#server-entry'; @@ -30,7 +31,7 @@ export function setupViteServer(nuxt: Nuxt, serverConfigFile: string, moduleOpti const configPath = createResolver(nuxt.options.rootDir).resolve(serverConfigFile); const metaTagsPath = createResolver(import.meta.url).resolve('./runtime/vite-server'); - const importPaths = [addRuntimeFlagsTemplate().dst, configPath, metaTagsPath]; + const importPaths = [addRuntimeFlagsTemplate(() => getLayerPublicFilePaths(nuxt)).dst, configPath, metaTagsPath]; let isConfigBundled = false; addVitePlugin( diff --git a/packages/nuxt/test/client/sdk.test.ts b/packages/nuxt/test/client/sdk.test.ts index f171fa15dea1..210ebc03a0b4 100644 --- a/packages/nuxt/test/client/sdk.test.ts +++ b/packages/nuxt/test/client/sdk.test.ts @@ -1,7 +1,12 @@ import * as SentryBrowser from '@sentry/browser'; +import { SENTRY_OP, URL_FULL } from '@sentry/conventions/attributes'; +import { HTTP_CLIENT } from '@sentry/conventions/op'; +import { GLOBAL_OBJ } from '@sentry/core'; import { SDK_VERSION } from '@sentry/vue'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { init } from '../../src/client'; +import { NUXT_BUILD_ASSETS_DIR_GLOBAL, NUXT_CDN_URL_GLOBAL } from '../../src/common/buildAssets'; +import { NUXT_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; const browserInit = vi.spyOn(SentryBrowser, 'init'); @@ -142,5 +147,85 @@ describe('Nuxt Client SDK', () => { expect(callArgs?.environment).toBe('options-env'); }); }); + + describe('ignoreSpans', () => { + const globalWithNuxtPaths = GLOBAL_OBJ as { + [NUXT_BASE_PATH_GLOBAL]?: string; + [NUXT_BUILD_ASSETS_DIR_GLOBAL]?: string; + [NUXT_CDN_URL_GLOBAL]?: string; + }; + + afterEach(() => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_CDN_URL_GLOBAL] = undefined; + }); + + const startFetchSpan = (url: string): SentryBrowser.Span => + SentryBrowser.startInactiveSpan({ name: 'GET', attributes: { [SENTRY_OP]: HTTP_CLIENT, [URL_FULL]: url } }); + + it.each([ + 'http://localhost:3000/_nuxt/builds/meta/b621250d-af25-415d-8df9-7e893c1af467.json', + 'http://localhost:3000/_nuxt/builds/latest.json?1794411940545', + '/_nuxt/builds/meta/b621250d-af25-415d-8df9-7e893c1af467.json', + ])('ignores build manifest requests (%s)', url => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startFetchSpan(url).isRecording()).toBe(false); + }); + + it.each([ + 'http://localhost:3000/api/builds/latest.json', + 'http://localhost:3000/_nuxt/builds-B13LvVLZ.js', + 'http://localhost:3000/_nuxt/entry.js', + 'http://localhost:3000/api/_nuxt/builds/latest.json', + 'https://example.com/_nuxt/builds/latest.json', + '/api/_nuxt/builds/latest.json', + ])('keeps other requests (%s)', url => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startFetchSpan(url).isRecording()).toBe(true); + }); + + it('merges the default with user-provided ignoreSpans', () => { + init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + ignoreSpans: [{ attributes: { [URL_FULL]: /\/health$/ } }], + }); + + expect(startFetchSpan('https://api.example.com/health').isRecording()).toBe(false); + expect(startFetchSpan('http://localhost:3000/_nuxt/builds/latest.json').isRecording()).toBe(false); + }); + + it('ignores manifest requests in the configured buildAssetsDir instead of `/_nuxt/`', () => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/assets/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startFetchSpan('http://localhost:3000/assets/builds/latest.json').isRecording()).toBe(false); + expect(startFetchSpan('http://localhost:3000/_nuxt/builds/latest.json').isRecording()).toBe(true); + expect(startFetchSpan('https://api.example.com/v1/assets/builds/123').isRecording()).toBe(true); + }); + + it('ignores manifest requests under the configured baseURL', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/shop/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startFetchSpan('http://localhost:3000/shop/_nuxt/builds/latest.json').isRecording()).toBe(false); + expect(startFetchSpan('/shop/_nuxt/builds/latest.json').isRecording()).toBe(false); + expect(startFetchSpan('http://localhost:3000/_nuxt/builds/latest.json').isRecording()).toBe(true); + }); + + it('ignores manifest requests to the configured cdnURL', () => { + globalWithNuxtPaths[NUXT_CDN_URL_GLOBAL] = 'https://cdn.example.com/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startFetchSpan('https://cdn.example.com/_nuxt/builds/latest.json').isRecording()).toBe(false); + expect(startFetchSpan('http://localhost:3000/_nuxt/builds/latest.json').isRecording()).toBe(true); + }); + }); }); }); diff --git a/packages/nuxt/test/common/buildAssets.test.ts b/packages/nuxt/test/common/buildAssets.test.ts new file mode 100644 index 000000000000..d227c8df68aa --- /dev/null +++ b/packages/nuxt/test/common/buildAssets.test.ts @@ -0,0 +1,126 @@ +import { GLOBAL_OBJ } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + getNuxtBuildAssetsDir, + getNuxtBuildAssetsPath, + getNuxtPublicBuildAssetsUrl, + getNuxtPublicFilePaths, + NUXT_BUILD_ASSETS_DIR_GLOBAL, + NUXT_CDN_URL_GLOBAL, + NUXT_PUBLIC_FILES_GLOBAL, +} from '../../src/common/buildAssets'; +import { NUXT_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; + +const globalWithNuxtPaths = GLOBAL_OBJ as { + [NUXT_BASE_PATH_GLOBAL]?: string; + [NUXT_BUILD_ASSETS_DIR_GLOBAL]?: string; + [NUXT_CDN_URL_GLOBAL]?: string; + [NUXT_PUBLIC_FILES_GLOBAL]?: string[]; +}; + +afterEach(() => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_CDN_URL_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_PUBLIC_FILES_GLOBAL] = undefined; +}); + +describe('getNuxtBuildAssetsDir', () => { + it('defaults to `/_nuxt/` when the generated code did not set the dir', () => { + expect(getNuxtBuildAssetsDir()).toBe('/_nuxt/'); + }); + + it.each([ + ['/_nuxt/', '/_nuxt/'], + ['/assets/', '/assets/'], + ['assets', '/assets/'], + ['/static/build', '/static/build/'], + ['//assets//', '/assets/'], + ])('normalizes `%s` to `%s`', (configured, expected) => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = configured; + + expect(getNuxtBuildAssetsDir()).toBe(expected); + }); + + it.each(['/', '', '//'])('returns undefined for the root dir `%s`', configured => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = configured; + + expect(getNuxtBuildAssetsDir()).toBeUndefined(); + }); +}); + +describe('getNuxtBuildAssetsPath', () => { + it('defaults to `/_nuxt/` when the generated code did not set the paths', () => { + expect(getNuxtBuildAssetsPath()).toBe('/_nuxt/'); + }); + + it.each([ + ['/', '/_nuxt/', '/_nuxt/'], + ['/app/', '/_nuxt/', '/app/_nuxt/'], + ['/app', 'assets', '/app/assets/'], + ['/shop/de/', '/static/build/', '/shop/de/static/build/'], + ])('joins the base path `%s` and the dir `%s` to `%s`', (basePath, dir, expected) => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = basePath; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = dir; + + expect(getNuxtBuildAssetsPath()).toBe(expected); + }); + + it('returns undefined for the root dir, also under a base path', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/app/'; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/'; + + expect(getNuxtBuildAssetsPath()).toBeUndefined(); + }); + + it('joins the given base path and dir instead of the values of the generated code', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/app/'; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/assets/'; + + expect(getNuxtBuildAssetsPath('/shop', 'static/build')).toBe('/shop/static/build/'); + }); +}); + +describe('getNuxtPublicBuildAssetsUrl', () => { + it('returns the build assets path without a cdnURL', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/app/'; + + expect(getNuxtPublicBuildAssetsUrl()).toBe('/app/_nuxt/'); + }); + + it.each([ + ['https://cdn.example.com', '/_nuxt/', 'https://cdn.example.com/_nuxt/'], + ['https://cdn.example.com/app/', '/assets/', 'https://cdn.example.com/app/assets/'], + ])('uses the cdnURL `%s` instead of the baseURL', (cdnURL, dir, expected) => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/ignored/'; + globalWithNuxtPaths[NUXT_CDN_URL_GLOBAL] = cdnURL; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = dir; + + expect(getNuxtPublicBuildAssetsUrl()).toBe(expected); + }); + + it('returns undefined for the root dir, also with a cdnURL', () => { + globalWithNuxtPaths[NUXT_CDN_URL_GLOBAL] = 'https://cdn.example.com/'; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/'; + + expect(getNuxtPublicBuildAssetsUrl()).toBeUndefined(); + }); +}); + +describe('getNuxtPublicFilePaths', () => { + it('returns no paths when the generated code did not set the files', () => { + expect(getNuxtPublicFilePaths()).toEqual([]); + }); + + it.each([ + [undefined, ['/humans.txt', '/docs/guide.pdf']], + ['/', ['/humans.txt', '/docs/guide.pdf']], + ['/shop/', ['/shop/humans.txt', '/shop/docs/guide.pdf']], + ['/shop', ['/shop/humans.txt', '/shop/docs/guide.pdf']], + ])('prefixes the files with the base path `%s`', (basePath, expected) => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = basePath; + globalWithNuxtPaths[NUXT_PUBLIC_FILES_GLOBAL] = ['/humans.txt', '/docs/guide.pdf']; + + expect(getNuxtPublicFilePaths()).toEqual(expected); + }); +}); diff --git a/packages/nuxt/test/common/tunnel.test.ts b/packages/nuxt/test/common/tunnel.test.ts index b5076d2cc083..f925015cb2b0 100644 --- a/packages/nuxt/test/common/tunnel.test.ts +++ b/packages/nuxt/test/common/tunnel.test.ts @@ -1,8 +1,8 @@ import { GLOBAL_OBJ } from '@sentry/core'; import { afterEach, describe, expect, it } from 'vitest'; -import { applyNuxtTunnelBasePath, NUXT_TUNNEL_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; +import { applyNuxtTunnelBasePath, NUXT_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; -const globalWithBasePath = GLOBAL_OBJ as { [NUXT_TUNNEL_BASE_PATH_GLOBAL]?: string }; +const globalWithBasePath = GLOBAL_OBJ as { [NUXT_BASE_PATH_GLOBAL]?: string }; describe('applyNuxtTunnelBasePath', () => { afterEach(() => { @@ -10,7 +10,7 @@ describe('applyNuxtTunnelBasePath', () => { }); it('serves the managed tunnel under `app.baseURL`', () => { - globalWithBasePath[NUXT_TUNNEL_BASE_PATH_GLOBAL] = '/app/'; + globalWithBasePath[NUXT_BASE_PATH_GLOBAL] = '/app/'; const options: Parameters[0] = { tunnel: true }; applyNuxtTunnelBasePath(options); @@ -19,7 +19,7 @@ describe('applyNuxtTunnelBasePath', () => { }); it('serves from the root for the default base URL', () => { - globalWithBasePath[NUXT_TUNNEL_BASE_PATH_GLOBAL] = '/'; + globalWithBasePath[NUXT_BASE_PATH_GLOBAL] = '/'; const options: Parameters[0] = { tunnel: true }; applyNuxtTunnelBasePath(options); diff --git a/packages/nuxt/test/runtime/plugins/client.test.ts b/packages/nuxt/test/runtime/plugins/client.test.ts index e0eef316a7ff..2e175d52e585 100644 --- a/packages/nuxt/test/runtime/plugins/client.test.ts +++ b/packages/nuxt/test/runtime/plugins/client.test.ts @@ -1,7 +1,7 @@ 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import clientPlugin from '../../../src/runtime/plugins/sentry.client'; import * as utils from '../../../src/runtime/utils'; @@ -245,6 +245,14 @@ describe('Sentry Nuxt client plugin', () => { }); describe.each(['app:error', 'vue:error'] as const)('%s hook — status-code filtering', hookName => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + const fireHook = (nuxtApp: { hook: ReturnType }, error: unknown) => { const cb = nuxtApp.hook.mock.calls.find(c => c[0] === hookName)?.[1] as ( e: unknown, @@ -255,6 +263,7 @@ describe('Sentry Nuxt client plugin', () => { // plugin passes the extra args through for vue:error, so include them // uniformly here and rely on expect.objectContaining({ error }) below. cb(error, undefined, 'setup'); + vi.runAllTimers(); }; // The plugin's skip guard reads `error.status || error.statusCode`, so both @@ -310,6 +319,14 @@ describe('Sentry Nuxt client plugin', () => { }); describe('vue:error hook — component instance passthrough', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + it('forwards the error, component instance and info to reportNuxtError', async () => { const reportSpy = vi.spyOn(utils, 'reportNuxtError').mockImplementation(() => {}); getClient.mockReturnValue(makeClient()); @@ -325,6 +342,7 @@ describe('Sentry Nuxt client plugin', () => { const err = new Error('vue boom'); const instance = { $props: { foo: 1 } }; vueErrorCb(err, instance, 'render'); + vi.runAllTimers(); expect(reportSpy).toHaveBeenCalledWith({ error: err, instance, info: 'render' }); }); diff --git a/packages/nuxt/test/runtime/plugins/cloudflare-entry.server.test.ts b/packages/nuxt/test/runtime/plugins/cloudflare-entry.server.test.ts new file mode 100644 index 000000000000..38f85fdf15af --- /dev/null +++ b/packages/nuxt/test/runtime/plugins/cloudflare-entry.server.test.ts @@ -0,0 +1,37 @@ +import { getIsolationScope } from '@sentry/core'; +import type { NitroApp } from 'nitropack'; +import { afterEach, describe, expect, it } from 'vitest'; +import cloudflareEntryPlugin from '../../../src/runtime/plugins/cloudflare-entry.server'; + +type HookCallback = (arg: unknown) => void; + +describe('cloudflare-entry.server', () => { + afterEach(() => { + getIsolationScope().setTransactionName(undefined); + delete (globalThis as { __SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__?: boolean }) + .__SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__; + }); + + it('names the transaction after the method and the path without the query of an h3 v1 event', () => { + const nitroHooks: Record = {}; + cloudflareEntryPlugin({ + hooks: { hook: (name: string, callback: HookCallback) => (nitroHooks[name] = callback) }, + } as unknown as NitroApp); + + nitroHooks.request?.({ method: 'GET', path: '/api/users/42?include=profile#details' }); + + expect(getIsolationScope().getScopeData().transactionName).toBe('GET /api/users/42'); + }); + + it('names the transaction after the method and the path of an h3 v2 event', () => { + const nitroHooks: Record = {}; + const url = 'https://example.com/api/users/42?include=profile'; + cloudflareEntryPlugin({ + hooks: { hook: (name: string, callback: HookCallback) => (nitroHooks[name] = callback) }, + } as unknown as NitroApp); + + nitroHooks.request?.({ req: new Request(url, { method: 'POST' }), url: new URL(url) }); + + expect(getIsolationScope().getScopeData().transactionName).toBe('POST /api/users/42'); + }); +}); diff --git a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts index d1be68efd7e6..4a4bd3c725de 100644 --- a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts +++ b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts @@ -4,8 +4,14 @@ import { wrapRequestHandler } from '@sentry/cloudflare/request'; import { getTunnelPath, SDK_VERSION } from '@sentry/core'; import type { NitroApp } from 'nitropack'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import cloudflareEntryPlugin from '../../../src/runtime/plugins/cloudflare-entry.server'; import { sentryCloudflareNitroPlugin } from '../../../src/runtime/plugins/sentry-cloudflare.server'; +vi.mock('@sentry/core', async () => ({ + ...(await vi.importActual('@sentry/core')), + consoleSandbox: (callback: () => void) => callback(), +})); + vi.mock('@sentry/cloudflare/request', () => ({ wrapRequestHandler: vi.fn((_options: unknown, callback: () => unknown) => callback()), })); @@ -52,6 +58,8 @@ describe('sentryCloudflareNitroPlugin', () => { afterEach(() => { vi.restoreAllMocks(); + delete (globalThis as { __SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__?: boolean }) + .__SENTRY_NUXT_CLOUDFLARE_ENTRY_WRAPPED__; }); it('passes a defaultIntegrations list that extends the SDK defaults', async () => { @@ -123,4 +131,34 @@ describe('sentryCloudflareNitroPlugin', () => { expect.any(Function), ); }); + + it('does not wrap an internal `$fetch` on Nitro v3, which has no Worker context', async () => { + const fetch = vi.fn(() => Promise.resolve(new Response('app'))); + const nitroApp = { fetch, hooks: { hook: vi.fn() } } as unknown as NitroApp & { + fetch: (request: Request) => Promise; + }; + sentryCloudflareNitroPlugin({ dsn: DSN })(nitroApp); + + const request = new Request('https://example.com/api/internal'); + await nitroApp.fetch(request); + + expect(fetch).toHaveBeenCalledWith(request); + expect(wrapRequestHandler).not.toHaveBeenCalled(); + }); + + it('does nothing after the Nitro plugin of the `sentry.cloudflare.config.ts` setup ran', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const localFetch = vi.fn(); + const hook = vi.fn(); + const nitroApp = { localFetch, hooks: { hook } } as unknown as NitroApp; + + cloudflareEntryPlugin({ hooks: { hook: vi.fn() } } as unknown as NitroApp); + sentryCloudflareNitroPlugin({ dsn: DSN })(nitroApp); + + expect(nitroApp.localFetch).toBe(localFetch); + expect(hook).not.toHaveBeenCalled(); + expect(consoleWarnSpy).toHaveBeenCalledWith( + '[Sentry] `sentryCloudflareNitroPlugin` does nothing, because Sentry sets up the SDK from `sentry.cloudflare.config.ts`. Remove the plugin.', + ); + }); }); diff --git a/packages/nuxt/test/runtime/plugins/tunnel-legacy.server.test.ts b/packages/nuxt/test/runtime/plugins/tunnel-legacy.server.test.ts index e5d2a42c7319..ff69e6d35796 100644 --- a/packages/nuxt/test/runtime/plugins/tunnel-legacy.server.test.ts +++ b/packages/nuxt/test/runtime/plugins/tunnel-legacy.server.test.ts @@ -9,7 +9,7 @@ const { setTunnelDefaults, useRuntimeConfig } = vi.hoisted(() => ({ })); vi.mock('@sentry/core/server', () => ({ - _INTERNAL_setTunnelDefaults: setTunnelDefaults, + setTunnelDefaults: setTunnelDefaults, })); vi.mock('nitropack/runtime', () => ({ useRuntimeConfig })); diff --git a/packages/nuxt/test/runtime/utils.test.ts b/packages/nuxt/test/runtime/utils.test.ts index e930f63afde0..f5c9dfbe2b31 100644 --- a/packages/nuxt/test/runtime/utils.test.ts +++ b/packages/nuxt/test/runtime/utils.test.ts @@ -115,8 +115,6 @@ describe('reportNuxtError', () => { }; beforeEach(() => { - // Using fake timers as setTimeout is used in `reportNuxtError` - vi.useFakeTimers(); vi.clearAllMocks(); (getClient as Mock).mockReturnValue(mockClient); }); @@ -127,7 +125,6 @@ describe('reportNuxtError', () => { test('captures exception with correct error and metadata', () => { reportNuxtError({ error: mockError }); - vi.runAllTimers(); expect(captureException).toHaveBeenCalledWith(mockError, { captureContext: { contexts: { nuxt: { info: undefined } } }, @@ -137,7 +134,6 @@ describe('reportNuxtError', () => { test('includes instance props if attachProps is not explicitly defined', () => { reportNuxtError({ error: mockError, instance: mockInstance }); - vi.runAllTimers(); expect(captureException).toHaveBeenCalledWith(mockError, { captureContext: { contexts: { nuxt: { info: undefined, propsData: { foo: 'bar' } } } }, @@ -149,7 +145,6 @@ describe('reportNuxtError', () => { mockClient.getOptions.mockReturnValue({ attachProps: false }); reportNuxtError({ error: mockError, instance: mockInstance }); - vi.runAllTimers(); expect(captureException).toHaveBeenCalledWith(mockError, { captureContext: { contexts: { nuxt: { info: undefined } } }, @@ -159,7 +154,6 @@ describe('reportNuxtError', () => { test('handles absence of instance correctly', () => { reportNuxtError({ error: mockError, info: 'Some info' }); - vi.runAllTimers(); expect(captureException).toHaveBeenCalledWith(mockError, { captureContext: { contexts: { nuxt: { info: 'Some info' } } }, diff --git a/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts b/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts new file mode 100644 index 000000000000..e1a01b993985 --- /dev/null +++ b/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts @@ -0,0 +1,183 @@ +// @vitest-environment node +import type { ExportedHandler } from '@cloudflare/workers-types'; +import { URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import { SDK_VERSION } from '@sentry/core'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + wrapNitroCloudflareEntryWithSentry, + wrapNitroDurableObjectWithSentry, +} from '../../../src/runtime/utils/wrapCloudflareEntry'; + +const cloudflareWorkers = vi.hoisted(() => { + let currentEnv: unknown; + + return { + withEnv: (env: unknown, callback: () => T): T => { + const previousEnv = currentEnv; + currentEnv = env; + try { + return callback(); + } finally { + currentEnv = previousEnv; + } + }, + getEnv: (): unknown => currentEnv, + }; +}); + +vi.mock('cloudflare:workers', () => ({ withEnv: cloudflareWorkers.withEnv })); + +vi.mock('@sentry/cloudflare', () => ({ + withSentry: (optionsCallback: unknown, handler: unknown) => ({ optionsCallback, handler }), + instrumentDurableObjectWithSentry: (optionsCallback: unknown, DurableObjectClass: unknown) => ({ + optionsCallback, + DurableObjectClass, + }), +})); + +type WrappedHandler = { + optionsCallback: (env: unknown) => unknown; + handler: Record unknown>; +}; + +type WrappedDurableObject = { + optionsCallback: (env: unknown) => unknown; + DurableObjectClass: new (state: unknown, env: unknown) => { fetch: () => unknown }; +}; + +describe('wrapNitroCloudflareEntryWithSentry', () => { + it('runs each handler with the `env` it gets as the `env` of `cloudflare:workers`', () => { + const handler = { fetch: () => cloudflareWorkers.getEnv(), queue: () => cloudflareWorkers.getEnv() }; + const env = { DB: 'instrumented D1 binding' }; + + const wrapped = wrapNitroCloudflareEntryWithSentry( + () => ({}), + handler as unknown as ExportedHandler, + ) as unknown as WrappedHandler; + + expect(wrapped.handler.fetch?.({}, env, {})).toBe(env); + expect(wrapped.handler.queue?.({ messages: [] }, env, {})).toBe(env); + expect(cloudflareWorkers.getEnv()).toBeUndefined(); + }); + + it('passes the options of the app with the Nuxt SDK metadata to `withSentry`', () => { + const wrapped = wrapNitroCloudflareEntryWithSentry( + env => ({ dsn: (env as { SENTRY_DSN: string }).SENTRY_DSN }), + {}, + ) as unknown as WrappedHandler; + + expect(wrapped.optionsCallback({ SENTRY_DSN: 'https://public@dsn.ingest.sentry.io/1337' })).toEqual({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + _metadata: { + optionsSetByUser: ['dsn'], + sdk: { + name: 'sentry.javascript.nuxt', + version: SDK_VERSION, + packages: [ + { name: 'npm:@sentry/nuxt', version: SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SDK_VERSION }, + ], + }, + }, + ignoreSpans: [], + }); + }); + + it('ignores the server spans of requests to the build output after the `ignoreSpans` of the app', () => { + const healthCheckFilter = { attributes: { [URL_PATH]: '/health' } }; + const wrapped = wrapNitroCloudflareEntryWithSentry( + () => ({ ignoreSpans: [healthCheckFilter] }), + {}, + '/shop/_nuxt/', + ) as unknown as WrappedHandler; + + const options = wrapped.optionsCallback({}) as { ignoreSpans: unknown[] }; + + expect(options.ignoreSpans).toEqual([ + healthCheckFilter, + { op: HTTP_SERVER, attributes: { [URL_PATH]: /^\/shop\/_nuxt\// } }, + ]); + }); + + it('does not report the build output filter as an option that the app set', () => { + const wrapped = wrapNitroCloudflareEntryWithSentry( + () => ({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }), + {}, + '/_nuxt/', + ) as unknown as WrappedHandler; + + const options = wrapped.optionsCallback({}) as { _metadata: { optionsSetByUser: string[] } }; + + expect(options._metadata.optionsSetByUser).toEqual(['dsn']); + }); +}); + +describe('wrapNitroDurableObjectWithSentry', () => { + class NitroDurableObject { + public constructor( + _state: unknown, + public env: unknown, + ) {} + + public fetch(): unknown { + return cloudflareWorkers.getEnv(); + } + } + + it('runs each method with `this.env` as the `env` of `cloudflare:workers` and keeps its name', () => { + const env = { DB: 'instrumented D1 binding' }; + + const { DurableObjectClass } = wrapNitroDurableObjectWithSentry( + () => ({}), + NitroDurableObject, + ) as unknown as WrappedDurableObject; + const durableObject = new DurableObjectClass({}, env); + + expect(durableObject).toBeInstanceOf(NitroDurableObject); + expect(durableObject.fetch()).toBe(env); + expect(durableObject.fetch.name).toBe('fetch'); + }); + + it('passes the options of the app with the Nuxt SDK metadata to `instrumentDurableObjectWithSentry`', () => { + const { optionsCallback } = wrapNitroDurableObjectWithSentry( + () => ({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }), + NitroDurableObject, + ) as unknown as WrappedDurableObject; + + expect(optionsCallback({})).toEqual({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + _metadata: { + optionsSetByUser: ['dsn'], + sdk: { + name: 'sentry.javascript.nuxt', + version: SDK_VERSION, + packages: [ + { name: 'npm:@sentry/nuxt', version: SDK_VERSION }, + { name: 'npm:@sentry/cloudflare', version: SDK_VERSION }, + ], + }, + }, + }); + }); +}); + +describe('without `withEnv` in `cloudflare:workers`', () => { + afterEach(() => { + vi.doUnmock('cloudflare:workers'); + }); + + it('calls the handlers directly', async () => { + vi.resetModules(); + vi.doMock('cloudflare:workers', () => ({ withEnv: undefined })); + const { wrapNitroCloudflareEntryWithSentry: wrapWithoutWithEnv } = + await import('../../../src/runtime/utils/wrapCloudflareEntry'); + const env = { DB: 'D1 binding' }; + + const wrapped = wrapWithoutWithEnv(() => ({}), { + fetch: (_request: unknown, handlerEnv: unknown) => handlerEnv, + } as unknown as ExportedHandler) as unknown as WrappedHandler; + + expect(wrapped.handler.fetch?.({}, env, {})).toBe(env); + }); +}); diff --git a/packages/nuxt/test/server/sdk.test.ts b/packages/nuxt/test/server/sdk.test.ts index a0538c115f50..11c660e1dae7 100644 --- a/packages/nuxt/test/server/sdk.test.ts +++ b/packages/nuxt/test/server/sdk.test.ts @@ -1,11 +1,14 @@ -import type { Event } from '@sentry/core'; -import { originalConsoleMethods } from '@sentry/core'; +import { HTTP_REQUEST_METHOD, SENTRY_OP, URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import { GLOBAL_OBJ, originalConsoleMethods } from '@sentry/core'; import * as SentryNode from '@sentry/node'; import { getGlobalScope, SDK_VERSION } from '@sentry/node'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { NUXT_BUILD_ASSETS_DIR_GLOBAL, NUXT_PUBLIC_FILES_GLOBAL } from '../../src/common/buildAssets'; import { NUXT_DEV_MODE_FLAG, NUXT_PRERENDER_FLAG, NUXT_SERVER_INITIALIZED_FLAG } from '../../src/common/devMode'; +import { NUXT_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; import { init } from '../../src/server'; -import { clientSourceMapErrorFilter, lowQualityTransactionsFilter } from '../../src/server/sdk'; +import { clientSourceMapErrorFilter } from '../../src/server/sdk'; const nodeInit = vi.spyOn(SentryNode, 'init'); @@ -239,42 +242,144 @@ describe('Nuxt Server SDK', () => { }); }); - describe('lowQualityTransactionsFilter', () => { - const options = { debug: false }; - const filter = lowQualityTransactionsFilter(options); - - describe('filters out low quality transactions', () => { - it.each([ - 'GET /_nuxt/some_asset.js', - 'GET _nuxt/some_asset.js', - 'GET /icons/favicon.ico', - 'GET /assets/logo.png', - 'GET /icons/zones/forest.svg', - ])('filters out low quality transaction: (%s)', transaction => { - const event = { type: 'transaction' as const, transaction }; - expect(filter(event, {})).toBeNull(); + describe('ignoreSpans', () => { + const startServerSpan = (path: string, method = 'GET'): SentryNode.Span => + SentryNode.startInactiveSpan({ + name: method, + forceTransaction: true, + attributes: { [SENTRY_OP]: HTTP_SERVER, [URL_PATH]: path, [HTTP_REQUEST_METHOD]: method }, }); + + it.each([ + '/_nuxt/entry.js', + '/_nuxt/entry.js.map', + '/_nuxt/builds/meta/b621250d-af25-415d-8df9-7e893c1af467.json', + '/_nuxt/builds/latest.json', + ])('ignores build asset requests (%s)', path => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(false); + }); + + it.each([ + '/', + '/_server', + '/user/jane.doe', + '/api/data.json', + '/blog/_payload.json', + '/blog/_nuxt-tips', + '/blog/_nuxt/', + '/api/_nuxt/entry.js.map', + ])('keeps route requests (%s)', path => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(true); + }); + + it('merges the default with user-provided ignoreSpans', () => { + init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + ignoreSpans: [{ attributes: { [URL_PATH]: '/health' } }], + }); + + expect(startServerSpan('/health').isRecording()).toBe(false); + expect(startServerSpan('/_nuxt/entry.js').isRecording()).toBe(false); }); - describe('keeps high quality transactions', () => { - // Nuxt parametrizes routes sometimes in a special way - especially catchAll o.O - it.each(['GET /', 'POST /_server', 'GET /catchAll/:id(.*)*', 'GET /article/:slug()', 'GET /user/:id'])( - 'does not filter out route transactions (%s)', - transaction => { - const event = { type: 'transaction' as const, transaction }; - expect(filter(event, {})).toEqual(event); + describe('with configured app paths', () => { + const globalWithNuxtPaths = GLOBAL_OBJ as { + [NUXT_BASE_PATH_GLOBAL]?: string; + [NUXT_BUILD_ASSETS_DIR_GLOBAL]?: string; + }; + + afterEach(() => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = undefined; + }); + + it('ignores requests for the configured `buildAssetsDir` instead of `/_nuxt/`', () => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/assets/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/assets/entry.js.map').isRecording()).toBe(false); + expect(startServerSpan('/_nuxt/entry.js.map').isRecording()).toBe(true); + }); + + it.each(['/blog/assets/', '/api/assets/123', '/user/assets/avatar.json'])( + 'keeps routes that contain the configured `buildAssetsDir` after the start (%s)', + path => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/assets/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(true); }, ); - }); - it('does not filter non-transaction events', () => { - const event = { type: 'error' as const, transaction: 'GET /assets/image.png' } as unknown as Event; - expect(filter(event, {})).toEqual(event); + it('ignores build asset requests under the configured `baseURL`', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/shop/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/shop/_nuxt/entry.js.map').isRecording()).toBe(false); + expect(startServerSpan('/shop/blog/_nuxt/entry.js.map').isRecording()).toBe(true); + }); + + it('keeps all requests when the build output is served from the root', () => { + globalWithNuxtPaths[NUXT_BUILD_ASSETS_DIR_GLOBAL] = '/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/user/jane.doe').isRecording()).toBe(true); + }); }); - it('handles events without transaction property', () => { - const event = { type: 'transaction' as const }; - expect(filter(event, {})).toEqual(event); + describe('with public files', () => { + const globalWithNuxtPaths = GLOBAL_OBJ as { + [NUXT_BASE_PATH_GLOBAL]?: string; + [NUXT_PUBLIC_FILES_GLOBAL]?: string[]; + }; + + beforeEach(() => { + globalWithNuxtPaths[NUXT_PUBLIC_FILES_GLOBAL] = ['/docs/guide.pdf', '/humans.txt']; + }); + + afterEach(() => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = undefined; + globalWithNuxtPaths[NUXT_PUBLIC_FILES_GLOBAL] = undefined; + }); + + it.each(['/docs/guide.pdf', '/humans.txt'])('ignores GET requests for public files (%s)', path => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(false); + }); + + it.each(['/docs/', '/docs/guide', '/docs/guide.pdf/', '/humans.txt.bak', '/blog/humans.txt'])( + 'keeps requests that only resemble a public file (%s)', + path => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(true); + }, + ); + + it('keeps other methods than GET, which reach the routes', () => { + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/humans.txt', 'POST').isRecording()).toBe(true); + }); + + it('ignores public files under the configured `baseURL`', () => { + globalWithNuxtPaths[NUXT_BASE_PATH_GLOBAL] = '/shop/'; + + init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/shop/humans.txt').isRecording()).toBe(false); + expect(startServerSpan('/humans.txt').isRecording()).toBe(true); + }); }); }); @@ -284,7 +389,6 @@ describe('Nuxt Server SDK', () => { }); const ids = client?.getEventProcessors().map(processor => processor.id); - expect(ids).toContain('NuxtLowQualityTransactionsFilter'); expect(ids).toContain('NuxtClientSourceMapErrorFilter'); }); diff --git a/packages/nuxt/test/vite/addServerConfig.test.ts b/packages/nuxt/test/vite/addServerConfig.test.ts index 5ac940f88463..d17e4af45ab5 100644 --- a/packages/nuxt/test/vite/addServerConfig.test.ts +++ b/packages/nuxt/test/vite/addServerConfig.test.ts @@ -115,6 +115,9 @@ describe('wrapEntryWithDynamicImport', () => { const addTemplateMock = vi.hoisted(() => vi.fn()); const addNitroPluginMock = vi.hoisted(() => vi.fn()); +const getNitroPublicFilePathsMock = vi.hoisted(() => vi.fn((): string[] => [])); + +vi.mock('../../src/vite/publicFiles', () => ({ getNitroPublicFilePaths: getNitroPublicFilePathsMock })); vi.mock('@nuxt/kit', () => ({ addTemplate: addTemplateMock, @@ -137,19 +140,28 @@ describe('addServerConfigPlugin', () => { } { const hooks: Record void> = {}; const nuxt = { - options: { rootDir: APP_ROOT, buildDir: path.join(APP_ROOT, '.nuxt'), nitro: {} }, + options: { + rootDir: APP_ROOT, + buildDir: path.join(APP_ROOT, '.nuxt'), + nitro: {}, + app: { baseURL: '/', buildAssetsDir: '/_nuxt/' }, + }, hook: (name: string, callback: (nitroConfig: NitroConfig) => void) => { - hooks[name] = callback; + const previous = hooks[name]; + hooks[name] = arg => { + previous?.(arg); + callback(arg); + }; }, } as unknown as Parameters[0]; return { nuxt, hooks }; } - function templateContents(filename: string): string { + function templateContents(filename: string, nuxt: Parameters[0]): string { const call = addTemplateMock.mock.calls.find(args => args[0]?.filename === filename); expect(call).toBeDefined(); - return call?.[0].getContents(); + return call?.[0].getContents({ nuxt }); } beforeEach(() => { @@ -162,9 +174,9 @@ describe('addServerConfigPlugin', () => { it('registers a plugin that evaluates the runtime flags before the config', () => { const { nuxt } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); - expect(templateContents('sentry-server-config-plugin.mjs')).toBe( + expect(templateContents('sentry-server-config-plugin.mjs', nuxt)).toBe( `import ${JSON.stringify(flagsDst)};\nimport ${JSON.stringify(APP_CONFIG)};\nexport default () => {};\n`, ); expect(addNitroPluginMock).toHaveBeenCalledWith(pluginDst); @@ -173,19 +185,45 @@ describe('addServerConfigPlugin', () => { it('derives the runtime flags from the build-time `import.meta` values', () => { const { nuxt } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); - const contents = templateContents('sentry-runtime-flags.mjs'); + const contents = templateContents('sentry-runtime-flags.mjs', nuxt); 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('passes the configured `app.baseURL` and `app.buildAssetsDir` to the server SDK', () => { + const { nuxt } = createFakeNuxt(); + nuxt.options.app.baseURL = '/shop/'; + nuxt.options.app.buildAssetsDir = '/assets/'; + + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); + + const contents = templateContents('sentry-runtime-flags.mjs', nuxt); + expect(contents).toContain('globalThis.__sentry_nuxt_base_path = "/shop/";'); + expect(contents).toContain('globalThis.__sentry_nuxt_build_assets_dir = "/assets/";'); + }); + + it('passes the public files that Nitro serves to the server SDK', () => { + getNitroPublicFilePathsMock.mockReturnValueOnce(['/humans.txt', '/docs/guide.pdf']); + const { nuxt, hooks } = createFakeNuxt(); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); + const nitro = { options: { preset: 'node-server', plugins: [] } }; + + hooks['nitro:init']!(nitro as never); + + expect(getNitroPublicFilePathsMock).toHaveBeenCalledWith(nitro, nuxt); + expect(templateContents('sentry-runtime-flags.mjs', nuxt)).toContain( + 'globalThis.__sentry_nuxt_public_files = ["/humans.txt","/docs/guide.pdf"];', + ); + }); + it('marks the config and the flags as side-effectful so tree shaking cannot drop them', () => { const { nuxt } = createFakeNuxt(); nuxt.options.nitro.moduleSideEffects = ['unenv/polyfill/']; - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); expect(nuxt.options.nitro.moduleSideEffects).toEqual(['unenv/polyfill/', APP_CONFIG, flagsDst]); }); @@ -194,14 +232,14 @@ describe('addServerConfigPlugin', () => { const { nuxt } = createFakeNuxt(); nuxt.options.nitro.moduleSideEffects = ['unenv/polyfill/']; - addServerConfigPlugin(nuxt, APP_CONFIG, false); + addServerConfigPlugin(nuxt, APP_CONFIG, false, false); expect(nuxt.options.nitro.moduleSideEffects).toEqual(['unenv/polyfill/']); }); it('inlines the config and both templates so the dev bundle transpiles them', () => { const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitroConfig: NitroConfig = { externals: { inline: ['@sentry/'] } }; hooks['nitro:config']!(nitroConfig); @@ -211,7 +249,7 @@ describe('addServerConfigPlugin', () => { it('leaves `externals` alone on Nitro v3, which has no such option', () => { const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, false); + addServerConfigPlugin(nuxt, APP_CONFIG, false, false); const nitroConfig: NitroConfig = { plugins: ['other-module-plugin.mjs'] }; hooks['nitro:config']!(nitroConfig); @@ -223,7 +261,7 @@ describe('addServerConfigPlugin', () => { it('moves its plugin to the front when other modules registered plugins first', () => { const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitroConfig: NitroConfig = { plugins: ['other-module-plugin.mjs', pluginDst] }; hooks['nitro:config']!(nitroConfig); @@ -233,7 +271,7 @@ describe('addServerConfigPlugin', () => { it('removes the plugin for explicitly configured Cloudflare presets', () => { const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitroConfig: NitroConfig = { preset: 'cloudflare_module', plugins: ['other-plugin.mjs', pluginDst] }; hooks['nitro:config']!(nitroConfig); @@ -247,13 +285,28 @@ describe('addServerConfigPlugin', () => { // after `nitro:config` ran, so the authoritative check uses `nitro:init`. const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitro = { options: { preset: 'cloudflare_pages', plugins: ['other-plugin.mjs', pluginDst] } }; hooks['nitro:init']!(nitro as never); expect(nitro.options.plugins).toEqual(['other-plugin.mjs']); - expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('sentryCloudflareNitroPlugin')); + expect(consoleWarnSpy).toHaveBeenCalledWith( + '[Sentry] Found `sentry.server.config.ts`, but the Nitro preset targets Cloudflare, where this file is not used. Set up the SDK in `sentry.cloudflare.config.ts` instead: https://docs.sentry.io/platforms/javascript/guides/nuxt/install/cloudflare-workers/', + ); + consoleWarnSpy.mockRestore(); + }); + + it('removes the plugin without a warning on Cloudflare when the app also has a `sentry.cloudflare.config` file', () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { nuxt, hooks } = createFakeNuxt(); + addServerConfigPlugin(nuxt, APP_CONFIG, true, true); + const nitro = { options: { preset: 'cloudflare_module', plugins: ['other-plugin.mjs', pluginDst] } }; + + hooks['nitro:init']!(nitro as never); + + expect(nitro.options.plugins).toEqual(['other-plugin.mjs']); + expect(consoleWarnSpy).not.toHaveBeenCalled(); consoleWarnSpy.mockRestore(); }); @@ -262,7 +315,7 @@ describe('addServerConfigPlugin', () => { const { nuxt, hooks } = createFakeNuxt(); const serverPlugins: string[] = []; addNitroPluginMock.mockImplementationOnce((plugin: string) => serverPlugins.push(plugin)); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitroConfig: NitroConfig = { preset: 'cloudflare_module', plugins: ['other-plugin.mjs'] }; hooks['nitro:config']!(nitroConfig); @@ -276,7 +329,7 @@ describe('addServerConfigPlugin', () => { it('keeps the plugin when the resolved preset is not Cloudflare', () => { const { nuxt, hooks } = createFakeNuxt(); - addServerConfigPlugin(nuxt, APP_CONFIG, true); + addServerConfigPlugin(nuxt, APP_CONFIG, true, false); const nitro = { options: { preset: 'node-server', plugins: ['other-plugin.mjs', pluginDst] } }; hooks['nitro:init']!(nitro as never); diff --git a/packages/nuxt/test/vite/cloudflare.test.ts b/packages/nuxt/test/vite/cloudflare.test.ts new file mode 100644 index 000000000000..b1b364fed1fc --- /dev/null +++ b/packages/nuxt/test/vite/cloudflare.test.ts @@ -0,0 +1,348 @@ +import type { Nuxt } from '@nuxt/schema'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { rollup, type RollupLog } from 'rollup'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { setupCloudflareEntry, wrapCloudflareEntryWithSentry } from '../../src/vite/cloudflare'; + +vi.mock('@nuxt/kit', () => ({ + createResolver: () => ({ resolve: (input: string) => input }), +})); + +type HookCallback = (arg: unknown) => void; + +describe('wrapCloudflareEntryWithSentry', () => { + let dir: string; + let entry: string; + let optionsFile: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'sentry-nuxt-cloudflare-')); + // Like the entry of Nitro, without a file extension. + entry = join(dir, 'entry'); + optionsFile = join(dir, 'sentry.cloudflare.config.mjs'); + writeFileSync(optionsFile, "export default () => ({ dsn: 'https://public@dsn.ingest.sentry.io/1337' });\n"); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it('wraps the default export and `$DurableObject` with the runtime wrappers and keeps the other exports', async () => { + writeFileSync( + `${entry}.mjs`, + "export default { fetch: () => 'response' };\nexport class $DurableObject {}\nexport const other = 'value';\n", + ); + + const bundle = await rollup({ + input: entry, + plugins: [ + wrapCloudflareEntryWithSentry(entry, optionsFile, '/shop/_nuxt/'), + { + name: 'wrapper-stub', + resolveId: source => (source === './runtime/utils/wrapCloudflareEntry' ? '\0wrapper-stub' : null), + load: id => + id === '\0wrapper-stub' + ? [ + 'export function wrapNitroCloudflareEntryWithSentry(optionsCallback, handler, buildAssetsPath) {', + ' return { optionsCallback, handler, buildAssetsPath };', + '}', + 'export function wrapNitroDurableObjectWithSentry(optionsCallback, DurableObjectClass) {', + ' return { optionsCallback, DurableObjectClass };', + '}', + ].join('\n') + : null, + }, + ], + }); + const { output } = await bundle.generate({ format: 'cjs', exports: 'named' }); + const exports: Record = {}; + // oxlint-disable-next-line typescript/no-implied-eval -- runs the generated bundle + new Function('exports', output[0].code)(exports); + + expect(output[0].exports).toEqual(['$DurableObject', 'default', 'other']); + expect(exports.default.handler.fetch()).toBe('response'); + expect(exports.default.optionsCallback()).toEqual({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + expect(exports.default.buildAssetsPath).toBe('/shop/_nuxt/'); + expect(exports.$DurableObject.DurableObjectClass.name).toBe('$DurableObject'); + expect(exports.$DurableObject.optionsCallback).toBe(exports.default.optionsCallback); + expect(exports.other).toBe('value'); + }); + + it('does not import `wrapNitroDurableObjectWithSentry` for an entry without `$DurableObject`', async () => { + writeFileSync(`${entry}.mjs`, 'export default {};\n'); + + const bundle = await rollup({ + input: entry, + plugins: [ + wrapCloudflareEntryWithSentry(entry, optionsFile), + { + name: 'wrapper-external', + resolveId: source => + source === './runtime/utils/wrapCloudflareEntry' ? { id: source, external: true } : null, + }, + ], + }); + const { output } = await bundle.generate({ format: 'es' }); + + expect(output[0].code).toContain('wrapNitroCloudflareEntryWithSentry('); + expect(output[0].code).not.toContain('wrapNitroDurableObjectWithSentry'); + }); + + it('wraps an entry that another plugin resolves first, as the Vite builder of Nitro 3 does', async () => { + // The export list of the `cloudflare-module` entry of Nitro 3. + writeFileSync( + `${entry}.mjs`, + [ + 'class $DurableObject {}', + "const cloudflare_module_default = { fetch: () => 'response' };", + 'export { $DurableObject, cloudflare_module_default as default };', + ].join('\n'), + ); + + const bundle = await rollup({ + input: entry, + plugins: [ + { + name: 'resolve-like-vite', + // Vite resolves a file with a query, and loads it from the path without the query. + resolveId: (source, importer) => + source === entry && !importer + ? `${entry}.mjs` + : source.endsWith('?sentry-cloudflare-original') + ? source + : null, + load: id => + id.endsWith('?sentry-cloudflare-original') ? readFileSync(id.slice(0, id.indexOf('?')), 'utf8') : null, + }, + wrapCloudflareEntryWithSentry(entry, optionsFile), + { + name: 'wrapper-stub', + resolveId: source => (source === './runtime/utils/wrapCloudflareEntry' ? '\0wrapper-stub' : null), + load: id => + id === '\0wrapper-stub' + ? [ + 'export function wrapNitroCloudflareEntryWithSentry(optionsCallback, handler) {', + ' return { optionsCallback, handler };', + '}', + 'export function wrapNitroDurableObjectWithSentry(optionsCallback, DurableObjectClass) {', + ' return { optionsCallback, DurableObjectClass };', + '}', + ].join('\n') + : null, + }, + ], + }); + const { output } = await bundle.generate({ format: 'cjs', exports: 'named' }); + const exports: Record = {}; + // oxlint-disable-next-line typescript/no-implied-eval -- runs the generated bundle + new Function('exports', output[0].code)(exports); + + expect(output[0].exports).toEqual(['$DurableObject', 'default']); + expect(exports.default.handler.fetch()).toBe('response'); + expect(exports.default.optionsCallback()).toEqual({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + expect(exports.$DurableObject.DurableObjectClass.name).toBe('$DurableObject'); + }); + + it('leaves an entry without a default export unwrapped and warns', async () => { + writeFileSync(`${entry}.mjs`, "addEventListener('fetch', () => {});\n"); + const warnings: RollupLog[] = []; + + const bundle = await rollup({ + input: entry, + plugins: [wrapCloudflareEntryWithSentry(entry, optionsFile)], + onwarn: warning => warnings.push(warning), + }); + const { output } = await bundle.generate({ format: 'es' }); + + expect(output[0].code).not.toContain('wrapNitroCloudflareEntryWithSentry'); + expect(warnings).toEqual([ + expect.objectContaining({ message: expect.stringContaining('The Nitro entry has no default export') }), + ]); + }); + + it('leaves an entry without a default export unwrapped and warns when another plugin resolves it first', async () => { + writeFileSync(`${entry}.mjs`, "addEventListener('fetch', () => {});\n"); + const warnings: RollupLog[] = []; + + const bundle = await rollup({ + input: entry, + plugins: [ + { + name: 'resolve-like-vite', + resolveId: (source, importer) => (source === entry && !importer ? `${entry}.mjs` : null), + }, + wrapCloudflareEntryWithSentry(entry, optionsFile), + ], + onwarn: warning => warnings.push(warning), + }); + const { output } = await bundle.generate({ format: 'es' }); + + expect(output[0].code).not.toContain('wrapNitroCloudflareEntryWithSentry'); + expect(warnings).toEqual([ + expect.objectContaining({ message: expect.stringContaining('The Nitro entry has no default export') }), + ]); + }); + + it('leaves other entries unwrapped', async () => { + const otherEntry = join(dir, 'other.mjs'); + writeFileSync(otherEntry, 'export default {};\n'); + + const bundle = await rollup({ input: otherEntry, plugins: [wrapCloudflareEntryWithSentry(entry, optionsFile)] }); + const { output } = await bundle.generate({ format: 'es' }); + + expect(output[0].code).not.toContain('wrapNitroCloudflareEntryWithSentry'); + }); +}); + +describe('setupCloudflareEntry', () => { + const app = { baseURL: '/', buildAssetsDir: '/_nuxt/' }; + let consoleWarnSpy: ReturnType; + + beforeEach(() => { + consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + consoleWarnSpy.mockRestore(); + }); + + it('wraps the entry and adds its Nitro plugin before the plugins of the app on a Cloudflare preset', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitro = { + options: { + preset: 'cloudflare-module', + entry: '/app/entry.mjs', + plugins: ['/app/server/plugins/sentry.ts'], + virtual: {}, + database: {}, + }, + hooks: { hook: vi.fn() }, + }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options).toEqual({ + preset: 'cloudflare-module', + entry: '/app/entry.mjs', + plugins: ['./runtime/plugins/cloudflare-entry.server', '/app/server/plugins/sentry.ts'], + rollupConfig: { output: {}, plugins: [expect.objectContaining({ name: 'sentry-nuxt-cloudflare-entry' })] }, + virtual: {}, + database: {}, + }); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + + it('adds its Nitro plugin before the plugins of the app in the prerenderer', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitroHooks: Record = {}; + const nitro = { + options: { + preset: 'cloudflare-module', + entry: '/app/entry.mjs', + plugins: [] as string[], + virtual: {}, + database: {}, + }, + hooks: { hook: (name: string, callback: HookCallback) => (nitroHooks[name] = callback) }, + }; + const prerenderConfig = { plugins: ['/app/server/plugins/sentry.ts'] }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + nitroHooks['prerender:config']?.(prerenderConfig); + + expect(prerenderConfig.plugins).toEqual([ + './runtime/plugins/cloudflare-entry.server', + '/app/server/plugins/sentry.ts', + ]); + }); + + it('leaves the `cloudflare-d1` databases out of the database instrumentation', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitro = { + options: { + preset: 'cloudflare-module', + entry: '/app/entry.mjs', + plugins: [] as string[], + virtual: { '#sentry/database-config.mjs': () => 'export const databaseConfig = {};' }, + database: { + default: { connector: 'cloudflare-d1', options: { bindingName: 'DB' } }, + hyperdrive: { connector: 'postgresql', options: { url: 'postgresql://localhost' } }, + }, + }, + hooks: { hook: vi.fn() }, + }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options.virtual['#sentry/database-config.mjs']()).toBe( + 'export const databaseConfig = {"hyperdrive":{"connector":"postgresql","options":{"url":"postgresql://localhost"}}};', + ); + }); + + it('does nothing on a non-Cloudflare preset', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitro = { options: { preset: 'node-server', entry: '/app/entry.mjs', plugins: [] as string[] } }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options).toEqual({ preset: 'node-server', entry: '/app/entry.mjs', plugins: [] }); + }); + + it('does nothing in dev, where the `cloudflare-dev` preset runs the dev entry of Nitro', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitro = { + options: { preset: 'cloudflare-dev', dev: true, entry: '/app/nitro-dev.mjs', plugins: [] as string[] }, + }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options).toEqual({ preset: 'cloudflare-dev', dev: true, entry: '/app/nitro-dev.mjs', plugins: [] }); + expect(consoleWarnSpy).not.toHaveBeenCalled(); + }); + + it('warns and leaves a `sentryCloudflareNitroPlugin` of the app on with the `cloudflare-worker` preset', () => { + const callbacks: HookCallback[] = []; + const nuxt = { options: { app }, hook: (_name: string, callback: HookCallback) => callbacks.push(callback) }; + const nitro = { + options: { preset: 'cloudflare-worker', entry: '/app/entry.mjs', plugins: ['/app/server/plugins/sentry.ts'] }, + }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options).toEqual({ + preset: 'cloudflare-worker', + entry: '/app/entry.mjs', + plugins: ['/app/server/plugins/sentry.ts'], + }); + expect(consoleWarnSpy).toHaveBeenCalledWith( + '[Sentry] The Worker of the `cloudflare-worker` preset has no default export, so Sentry cannot wrap it with `withSentry`. Use the `cloudflare-module` preset to set up the SDK from `sentry.cloudflare.config.ts`.', + ); + }); + + it('does nothing when Nuxt prepares the types', () => { + const callbacks: HookCallback[] = []; + const nuxt = { + options: { _prepare: true }, + hook: (_name: string, callback: HookCallback) => callbacks.push(callback), + }; + const nitro = { options: { preset: 'cloudflare-module', entry: '/app/entry.mjs', plugins: [] as string[] } }; + + setupCloudflareEntry(nuxt as unknown as Nuxt, '/app/sentry.cloudflare.config.ts'); + callbacks.forEach(callback => callback(nitro)); + + expect(nitro.options).toEqual({ preset: 'cloudflare-module', entry: '/app/entry.mjs', plugins: [] }); + }); +}); diff --git a/packages/nuxt/test/vite/databaseConfig.test.ts b/packages/nuxt/test/vite/databaseConfig.test.ts index df66e7f180c3..bb2d445434c1 100644 --- a/packages/nuxt/test/vite/databaseConfig.test.ts +++ b/packages/nuxt/test/vite/databaseConfig.test.ts @@ -1,9 +1,10 @@ -import type { NitroConfig } from 'nitropack/types'; +import type { Nitro, NitroConfig } from 'nitropack/types'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SentryNuxtModuleOptions } from '../../src/common/types'; -import { addDatabaseInstrumentation } from '../../src/vite/databaseConfig'; +import { addDatabaseInstrumentation, skipDatabaseInstrumentation } from '../../src/vite/databaseConfig'; -vi.mock('@sentry/core', () => ({ +vi.mock('@sentry/core', async () => ({ + ...(await vi.importActual('@sentry/core')), consoleSandbox: (callback: () => void) => callback(), })); @@ -79,3 +80,34 @@ describe('addDatabaseInstrumentation', () => { }); }); }); + +describe('skipDatabaseInstrumentation', () => { + it('replaces the database config of the instrumentation with one without the databases of the connector', () => { + const nitro = { + options: { + virtual: { '#sentry/database-config.mjs': () => 'export const databaseConfig = {};' }, + database: { + default: { connector: 'cloudflare-d1', options: { bindingName: 'DB' } }, + users: { connector: 'cloudflare-d1', options: { bindingName: 'USERS_DB' } }, + analytics: { connector: 'postgresql', options: { url: 'postgresql://localhost' } }, + }, + }, + }; + + skipDatabaseInstrumentation(nitro as unknown as Nitro, 'cloudflare-d1'); + + expect(nitro.options.virtual['#sentry/database-config.mjs']()).toBe( + 'export const databaseConfig = {"analytics":{"connector":"postgresql","options":{"url":"postgresql://localhost"}}};', + ); + }); + + it('does nothing when the database instrumentation is not set up', () => { + const nitro = { + options: { virtual: {}, database: { default: { connector: 'cloudflare-d1', options: { bindingName: 'DB' } } } }, + }; + + skipDatabaseInstrumentation(nitro as unknown as Nitro, 'cloudflare-d1'); + + expect(nitro.options.virtual).toEqual({}); + }); +}); diff --git a/packages/nuxt/test/vite/nitroServer.test.ts b/packages/nuxt/test/vite/nitroServer.test.ts index 3543a469575b..b8fc85f98a44 100644 --- a/packages/nuxt/test/vite/nitroServer.test.ts +++ b/packages/nuxt/test/vite/nitroServer.test.ts @@ -33,7 +33,7 @@ function createFakeNuxt(): { callbacks.set(name, [...(callbacks.get(name) ?? []), callback]); }); const nuxt = { - options: { rootDir: APP_ROOT, buildDir: `${APP_ROOT}/.nuxt`, nitro: {} }, + options: { rootDir: APP_ROOT, buildDir: `${APP_ROOT}/.nuxt`, nitro: {}, app: { baseURL: '/' } }, hook, hooks: { hook }, } as unknown as Nuxt; @@ -67,7 +67,7 @@ describe('setupNitroServer', () => { ({ serverApi, handler, updateRouteName, tunnel, storage }) => { const { nuxt } = createFakeNuxt(); - setupNitroServer(nuxt, serverApi, SERVER_CONFIG, MODULE_OPTIONS); + setupNitroServer(nuxt, serverApi, SERVER_CONFIG, MODULE_OPTIONS, false); expect(addNitroPluginMock).toHaveBeenCalledTimes(6); expect(addNitroPluginMock).toHaveBeenNthCalledWith(1, `${APP_ROOT}/.nuxt/sentry-server-config-plugin.mjs`); @@ -85,10 +85,28 @@ describe('setupNitroServer', () => { expect(addNitroPluginMock).not.toHaveBeenCalled(); }); + it('registers the server plugins without the server config plugin when there is no server config file', () => { + const { nuxt, callHook } = createFakeNuxt(); + const nitro = { options: { preset: 'cloudflare-module', plugins: [] }, hooks: { hook: vi.fn() } }; + + setupNitroServer(nuxt, 'nitro2', undefined, MODULE_OPTIONS, true); + callHook('nitro:init', nitro); + + expect(addNitroPluginMock).toHaveBeenCalledTimes(5); + expect(addNitroPluginMock).toHaveBeenNthCalledWith(1, './runtime/plugins/handler-legacy.server'); + expect(addNitroPluginMock).toHaveBeenNthCalledWith(2, './runtime/plugins/update-route-name-legacy.server'); + expect(addNitroPluginMock).toHaveBeenNthCalledWith(3, './runtime/plugins/tunnel-legacy.server'); + expect(addNitroPluginMock).toHaveBeenNthCalledWith(4, './runtime/plugins/sentry.server'); + expect(addNitroPluginMock).toHaveBeenNthCalledWith(5, './runtime/plugins/storage-legacy.server'); + expect(addTemplateMock).not.toHaveBeenCalled(); + expect(nitro.hooks.hook).toHaveBeenCalledTimes(1); + expect(nitro.hooks.hook).toHaveBeenCalledWith('rollup:before', expect.any(Function)); + }); + it('instruments the middleware and adds the config shim once Nitro initializes', () => { const { nuxt, callHook } = createFakeNuxt(); - const nitro = { options: { preset: 'node-server', plugins: [] }, hooks: { hook: vi.fn() } }; - setupNitroServer(nuxt, 'nitro2', SERVER_CONFIG, MODULE_OPTIONS); + const nitro = { options: { preset: 'node-server', plugins: [], publicAssets: [] }, hooks: { hook: vi.fn() } }; + setupNitroServer(nuxt, 'nitro2', SERVER_CONFIG, MODULE_OPTIONS, false); callHook('nitro:init', nitro); diff --git a/packages/nuxt/test/vite/orchestrion.test.ts b/packages/nuxt/test/vite/orchestrion.test.ts index 5ab7ffd794d2..ef601917a333 100644 --- a/packages/nuxt/test/vite/orchestrion.test.ts +++ b/packages/nuxt/test/vite/orchestrion.test.ts @@ -70,7 +70,7 @@ describe('setupOrchestrion', () => { expect(nitroConfig.externals.inline).toEqual(['ioredis', 'custom-dependency', 'mysql', 'standard-as-callback']); }); - it('adds the plugin on a Cloudflare preset even without a server config file', async () => { + it('adds the plugin with the workerd channel facade on a Cloudflare preset even without a server config file', async () => { const { setupOrchestrion } = await import('../../src/vite/orchestrion'); const mockNuxt = createMockNuxt(); const nitroConfig = { preset: 'cloudflare_module' }; @@ -78,7 +78,9 @@ describe('setupOrchestrion', () => { setupOrchestrion(mockNuxt as unknown as Nuxt, false); await mockNuxt.triggerHook('nitro:config', nitroConfig); - expect(mockSentryOrchestrionPlugin).toHaveBeenCalledWith({}); + expect(mockSentryOrchestrionPlugin).toHaveBeenCalledWith({ + dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel', + }); }); it('adds the plugin on a non-Cloudflare preset when a server config exists', async () => { diff --git a/packages/nuxt/test/vite/publicFiles.test.ts b/packages/nuxt/test/vite/publicFiles.test.ts new file mode 100644 index 000000000000..998e1569ecf1 --- /dev/null +++ b/packages/nuxt/test/vite/publicFiles.test.ts @@ -0,0 +1,108 @@ +import type { Nuxt } from '@nuxt/schema'; +import type { Nitro } from 'nitropack'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getLayerPublicFilePaths, getNitroPublicFilePaths } from '../../src/vite/publicFiles'; + +const getLayerDirectoriesMock = vi.hoisted(() => vi.fn()); + +vi.mock('@nuxt/kit', () => ({ getLayerDirectories: getLayerDirectoriesMock })); + +let rootDir: string; + +function writeFiles(dir: string, files: string[]): string { + for (const file of files) { + fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); + fs.writeFileSync(path.join(dir, file), ''); + } + return dir; +} + +function createNuxt(baseURL = '/'): Nuxt { + return { options: { buildDir: path.join(rootDir, '.nuxt'), app: { baseURL } } } as unknown as Nuxt; +} + +function createNitro(publicAssets: { dir: string; baseURL?: string }[]): Nitro { + return { options: { publicAssets } } as unknown as Nitro; +} + +beforeEach(() => { + rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-nuxt-public-files-')); +}); + +afterEach(() => { + fs.rmSync(rootDir, { recursive: true, force: true }); +}); + +describe('getNitroPublicFilePaths', () => { + it('returns the files of all public dirs, also nested ones', () => { + const publicDir = writeFiles(path.join(rootDir, 'public'), ['humans.txt', 'docs/guide.pdf']); + const layerDir = writeFiles(path.join(rootDir, 'layer/public'), ['terms.html']); + + const paths = getNitroPublicFilePaths(createNitro([{ dir: publicDir }, { dir: layerDir }]), createNuxt()); + + expect(paths.sort()).toEqual(['/docs/guide.pdf', '/humans.txt', '/terms.html']); + }); + + it('prefixes the files with the `baseURL` of their public dir', () => { + const publicDir = writeFiles(path.join(rootDir, 'content'), ['guide.pdf']); + + expect(getNitroPublicFilePaths(createNitro([{ dir: publicDir, baseURL: '/docs/' }]), createNuxt())).toEqual([ + '/docs/guide.pdf', + ]); + }); + + it('percent-encodes the file names like the request path', () => { + const publicDir = writeFiles(path.join(rootDir, 'public'), [ + 'my file.pdf', + 'café.txt', + 'docs/100%.txt', + 'a#b?c.txt', + '[id].txt', + ]); + + expect( + getNitroPublicFilePaths(createNitro([{ dir: publicDir, baseURL: '/caf%C3%A9/' }]), createNuxt()).sort(), + ).toEqual([ + '/caf%C3%A9/[id].txt', + '/caf%C3%A9/a%23b%3Fc.txt', + '/caf%C3%A9/caf%C3%A9.txt', + '/caf%C3%A9/docs/100%25.txt', + '/caf%C3%A9/my%20file.pdf', + ]); + }); + + it('skips the client build, which the build asset filter covers', () => { + const clientBuildDir = writeFiles(path.join(rootDir, '.nuxt/dist/client'), ['_nuxt/builds/latest.json']); + + expect(getNitroPublicFilePaths(createNitro([{ dir: clientBuildDir }]), createNuxt())).toEqual([]); + }); + + it('skips files that the HTTP integration ignores as static assets', () => { + const publicDir = writeFiles(path.join(rootDir, 'public'), ['favicon.ico', 'robots.txt', 'logo.svg', 'humans.txt']); + + expect(getNitroPublicFilePaths(createNitro([{ dir: publicDir }]), createNuxt())).toEqual(['/humans.txt']); + }); + + it('keeps metadata files that the HTTP integration only ignores at the root, under a `baseURL`', () => { + const publicDir = writeFiles(path.join(rootDir, 'public'), ['robots.txt']); + + expect(getNitroPublicFilePaths(createNitro([{ dir: publicDir }]), createNuxt('/shop/'))).toEqual(['/robots.txt']); + }); + + it('returns no paths for a public dir that does not exist', () => { + expect(getNitroPublicFilePaths(createNitro([{ dir: path.join(rootDir, 'missing') }]), createNuxt())).toEqual([]); + }); +}); + +describe('getLayerPublicFilePaths', () => { + it('returns the files of the public dirs of all layers', () => { + const publicDir = writeFiles(path.join(rootDir, 'public'), ['humans.txt']); + const layerDir = writeFiles(path.join(rootDir, 'layer/public'), ['docs/guide.pdf', 'favicon.ico']); + getLayerDirectoriesMock.mockReturnValue([{ public: `${publicDir}/` }, { public: `${layerDir}/` }]); + + expect(getLayerPublicFilePaths(createNuxt()).sort()).toEqual(['/docs/guide.pdf', '/humans.txt']); + }); +}); diff --git a/packages/nuxt/test/vite/sourceMapDeletion.test.ts b/packages/nuxt/test/vite/sourceMapDeletion.test.ts index 4bc4427a4569..73f180cd5c83 100644 --- a/packages/nuxt/test/vite/sourceMapDeletion.test.ts +++ b/packages/nuxt/test/vite/sourceMapDeletion.test.ts @@ -151,60 +151,85 @@ describe('getFallbackFilesToDelete', () => { async function matchFallbackFiles( preset: Preset, sides: { client: boolean; server: boolean }, - nuxtRoot = projectDir, + { nuxtRoot = projectDir, viteBuilder = true }: { nuxtRoot?: string; viteBuilder?: boolean } = {}, ): Promise { const { outputDirs, clientMaps, serverMaps } = PRESETS[preset]; writeFiles([...clientMaps, ...serverMaps, ...UNDEPLOYED_MAPS], nuxtRoot); const globs = getFallbackFilesToDelete({ ...sides, - outputDirs: { - publicDir: path.join(nuxtRoot, outputDirs.publicDir), - serverDir: path.join(nuxtRoot, outputDirs.serverDir), - }, + serverDir: path.join(nuxtRoot, outputDirs.serverDir), + publicDir: viteBuilder ? undefined : path.join(nuxtRoot, outputDirs.publicDir), }); const files = globs.length > 0 ? await globFiles(globs) : []; return files.map(file => path.relative(nuxtRoot, file).split(path.sep).join('/')).sort(); } + it.each(Object.keys(PRESETS) as Preset[])('matches only the server source maps of the %s preset', async preset => { + await expect(matchFallbackFiles(preset, { client: true, server: true })).resolves.toEqual( + PRESETS[preset].serverMaps, + ); + }); + + // The Vite plugin removes the client maps Sentry enabled before they reach the public dir. it.each(Object.keys(PRESETS) as Preset[])( - 'matches the client and server source maps in the output of the %s preset', + 'matches nothing in the %s preset when Sentry enabled only the client source maps', async preset => { - const { clientMaps, serverMaps } = PRESETS[preset]; - - await expect(matchFallbackFiles(preset, { client: true, server: true })).resolves.toEqual( - [...clientMaps, ...serverMaps].sort(), - ); + await expect(matchFallbackFiles(preset, { client: true, server: false })).resolves.toEqual([]); }, ); + // No Vite plugin runs with webpack or rspack, so the public dir still holds the client maps. it.each(Object.keys(PRESETS) as Preset[])( - 'matches only the client source maps of the %s preset when Sentry enabled only those', + 'matches the client and server source maps of the %s preset with a builder other than Vite', async preset => { - await expect(matchFallbackFiles(preset, { client: true, server: false })).resolves.toEqual( - [...PRESETS[preset].clientMaps].sort(), + const { clientMaps, serverMaps } = PRESETS[preset]; + + await expect(matchFallbackFiles(preset, { client: true, server: true }, { viteBuilder: false })).resolves.toEqual( + [...clientMaps, ...serverMaps].sort(), ); }, ); it.each(Object.keys(PRESETS) as Preset[])( - 'matches only the server source maps of the %s preset when Sentry enabled only those', + 'matches only the client source maps of the %s preset with a builder other than Vite when Sentry enabled only those', async preset => { - await expect(matchFallbackFiles(preset, { client: false, server: true })).resolves.toEqual( - PRESETS[preset].serverMaps, - ); + await expect( + matchFallbackFiles(preset, { client: true, server: false }, { viteBuilder: false }), + ).resolves.toEqual([...PRESETS[preset].clientMaps].sort()); }, ); it('matches the output of a Nuxt app in a subdirectory of the working directory', async () => { const nuxtRoot = path.join(projectDir, 'apps', 'shop'); - await expect(matchFallbackFiles('node-server', { client: true, server: false }, nuxtRoot)).resolves.toEqual( - PRESETS['node-server'].clientMaps, + await expect(matchFallbackFiles('node-server', { client: false, server: true }, { nuxtRoot })).resolves.toEqual( + PRESETS['node-server'].serverMaps, ); }); it('returns no globs before Nitro reported its output directories', () => { expect(getFallbackFilesToDelete({ client: true, server: true })).toEqual([]); }); + + describe('with `sourcemaps.delete`', () => { + const output = { serverDir: path.join('.output', 'server'), publicDir: path.join('.output', 'public') }; + + it('covers both sides with `true`, also when the user enabled the source maps', () => { + const fallback = { + client: false, + server: false, + serverDir: path.join(projectDir, output.serverDir), + publicDir: path.join(projectDir, output.publicDir), + }; + + expect(getFallbackFilesToDelete(fallback, true)).toEqual(['.output/public/**/*.map', '.output/server/**/*.map']); + }); + + it('returns no globs with `false`, also when Sentry enabled the source maps', () => { + const fallback = { client: true, server: true, serverDir: path.join(projectDir, output.serverDir) }; + + expect(getFallbackFilesToDelete(fallback, false)).toEqual([]); + }); + }); }); diff --git a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts index 1312b359c639..b0722f380fc3 100644 --- a/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts +++ b/packages/nuxt/test/vite/sourceMaps-nuxtHooks.test.ts @@ -1,5 +1,6 @@ import type { Nuxt } from '@nuxt/schema'; import type * as BundlerPluginsCore from '@sentry/bundler-plugins/core'; +import type { SentryVitePluginInternalOptions } from '@sentry/bundler-plugins/vite'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -8,17 +9,27 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, type MockInstanc import { NUXT_RELEASE_RUNTIME_CONFIG_KEY, setupSourceMaps } from '../../src/vite/sourceMaps'; import type { SourceMapSetting } from '../../src/vite/sourceMapSettings'; -const { mockSentryVitePlugin, mockSentryRollupPlugin, mockDeleteArtifacts, mockCreateSentryBuildPluginManager } = - vi.hoisted(() => { - const deleteArtifacts = vi.fn().mockResolvedValue(undefined); +const { + capturedViteOptions, + mockSentryVitePlugin, + mockSentryRollupPlugin, + mockDeleteArtifacts, + mockCreateSentryBuildPluginManager, +} = vi.hoisted(() => { + const deleteArtifacts = vi.fn().mockResolvedValue(undefined); + const captured: { options?: SentryVitePluginInternalOptions } = {}; - return { - mockSentryVitePlugin: vi.fn(() => [{ name: 'sentry-vite-plugin' }]), - mockSentryRollupPlugin: vi.fn(() => ({ name: 'sentry-rollup-plugin' })), - mockDeleteArtifacts: deleteArtifacts, - mockCreateSentryBuildPluginManager: vi.fn(() => ({ deleteArtifacts })), - }; - }); + return { + capturedViteOptions: captured, + mockSentryVitePlugin: vi.fn((options: SentryVitePluginInternalOptions) => { + captured.options = options; + return [{ name: 'sentry-vite-plugin' }]; + }), + mockSentryRollupPlugin: vi.fn(() => ({ name: 'sentry-rollup-plugin' })), + mockDeleteArtifacts: deleteArtifacts, + mockCreateSentryBuildPluginManager: vi.fn(() => ({ deleteArtifacts })), + }; +}); vi.mock('@sentry/bundler-plugins/core', async importOriginal => ({ ...(await importOriginal()), @@ -64,6 +75,7 @@ function createMockNuxt(options: { _prepare?: boolean; dev?: boolean; sourcemap?: SourceMapSetting | { server?: SourceMapSetting; client?: SourceMapSetting }; + builder?: string; }) { const hooks: Record = {}; @@ -72,6 +84,7 @@ function createMockNuxt(options: { _prepare: options._prepare ?? false, dev: options.dev ?? false, sourcemap: options.sourcemap ?? { server: undefined, client: undefined }, + builder: options.builder, runtimeConfig: { public: {} as Record }, }, hook: (name: string, callback: HookCallback) => { @@ -89,7 +102,7 @@ function createMockNuxt(options: { } describe('setupSourceMaps hooks', () => { - const defaultFilesToDeleteAfterUpload = ['.output/public/**/*.map', '.output/server/**/*.map']; + const defaultFilesToDeleteAfterUpload = ['.output/server/**/*.map']; const consoleLogSpy = vi.spyOn(console, 'log'); const consoleWarnSpy = vi.spyOn(console, 'warn'); @@ -106,6 +119,14 @@ describe('setupSourceMaps hooks', () => { mockSentryRollupPlugin.mockClear(); mockCreateSentryBuildPluginManager.mockClear(); mockDeleteArtifacts.mockClear(); + capturedViteOptions.options = undefined; + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); + }); + + afterEach(() => { + vi.unstubAllEnvs(); }); describe('removed `unstable_sentryBundlerPluginOptions`', () => { @@ -166,6 +187,29 @@ describe('setupSourceMaps hooks', () => { }); }); + // The Vite server runs no Nitro, so no Rollup plugin uploads the server maps. + it('adds a Sentry Vite plugin for the server build on the Vite server', async () => { + const mockNuxt = createMockNuxt({ _prepare: false, dev: false }); + const { mockAddVitePlugin } = createMockAddVitePlugin(); + + setupSourceMaps({ release: { name: '1.2.3' } }, mockNuxt as unknown as Nuxt, mockAddVitePlugin, true, true); + + expect(mockAddVitePlugin).toHaveBeenCalledWith([{ name: 'sentry-vite-plugin' }], { + dev: false, + build: true, + server: false, + }); + expect(mockAddVitePlugin).toHaveBeenCalledWith([{ name: 'sentry-vite-plugin' }], { + dev: false, + build: true, + client: false, + }); + // The client config plugin hands the release to the browser SDK only, so the server bundle needs it. + expect(mockSentryVitePlugin).toHaveBeenLastCalledWith( + expect.objectContaining({ release: expect.not.objectContaining({ inject: false }) }), + ); + }); + it.each([ { label: 'prepare mode', @@ -309,9 +353,9 @@ describe('setupSourceMaps hooks', () => { expect(mockSentryVitePlugin).toHaveBeenCalledWith({ applicationKey: undefined, - org: undefined, - project: undefined, - authToken: undefined, + org: 'org', + project: 'project', + authToken: 'token', telemetry: true, url: undefined, headers: undefined, @@ -326,7 +370,8 @@ describe('setupSourceMaps hooks', () => { assets: undefined, ignore: undefined, filesToDeleteAfterUpload: undefined, - deleteSourcemapsAfterUpload: false, + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), rewriteSources: expect.any(Function), }, }); @@ -354,6 +399,233 @@ describe('setupSourceMaps hooks', () => { }); }); + describe('client source map deletion', () => { + function getDeleteOption(environment?: string): boolean | undefined { + const value = capturedViteOptions.options?.sourcemaps?.deleteSourcemapsAfterUpload; + return typeof value === 'function' ? value(environment) : value; + } + + function getSdkEnabledSourceMaps(environment?: string): boolean | undefined { + const value = capturedViteOptions.options?.sourcemaps?.sdkEnabledSourceMaps; + return typeof value === 'function' ? value(environment) : value; + } + + // The Vite plugin reads the option in its `config` hook, which runs after `modules:done`. + it('asks the Vite plugin to delete the client source maps Sentry enabled', async () => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); + + setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + expect(mockNuxt.options.sourcemap).toEqual({ client: 'hidden', server: true }); + expect(getDeleteOption()).toBe(true); + expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + }); + + // The plugin then also removes the maps of chunks that the user's `assets` or `ignore` leave out. + it('tells the Vite plugin that Sentry enabled the client source maps', async () => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); + + setupSourceMaps( + { sourcemaps: { assets: ['.nuxt/dist/client/_nuxt/entry*'] } }, + mockNuxt as unknown as Nuxt, + vi.fn(), + ); + await mockNuxt.triggerHook('modules:done'); + + expect(capturedViteOptions.options?.sourcemaps?.assets).toEqual(['.nuxt/dist/client/_nuxt/entry*']); + expect(getSdkEnabledSourceMaps()).toBe(true); + }); + + // With the Vite environment API, the plugin also decides for the server environments. + it.each([ + { environment: undefined, sdkEnabled: true }, + { environment: 'client', sdkEnabled: true }, + { environment: 'ssr', sdkEnabled: false }, + { environment: 'nitro', sdkEnabled: false }, + ])('answers for the client only, in the $environment environment', async ({ environment, sdkEnabled }) => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); + + setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + expect(getDeleteOption(environment)).toBe(sdkEnabled ? true : undefined); + expect(getSdkEnabledSourceMaps(environment)).toBe(sdkEnabled); + }); + + it.each([ + { label: 'Sentry enabled', server: undefined, sourcemaps: {}, expected: true, sdkEnabled: true }, + { label: 'Nuxt enabled', server: true, sourcemaps: {}, expected: undefined, sdkEnabled: false }, + { label: 'Nuxt enabled', server: true, sourcemaps: { delete: true }, expected: true, sdkEnabled: true }, + { label: 'Sentry enabled', server: undefined, sourcemaps: { delete: false }, expected: false, sdkEnabled: true }, + { + label: 'Sentry enabled', + server: undefined, + sourcemaps: { filesToDeleteAfterUpload: 'x/**' }, + expected: undefined, + sdkEnabled: true, + }, + ] as const)( + 'on the Vite server, decides for the $label server maps in the ssr environment with $sourcemaps', + async ({ server, sourcemaps, expected, sdkEnabled }) => { + const mockNuxt = createMockNuxt({ sourcemap: { client: true, server } }); + + setupSourceMaps({ sourcemaps }, mockNuxt as unknown as Nuxt, vi.fn(), false, true); + await mockNuxt.triggerHook('modules:done'); + + for (const environment of ['ssr', undefined]) { + expect(getDeleteOption(environment)).toBe(expected); + expect(getSdkEnabledSourceMaps(environment)).toBe(sdkEnabled); + } + }, + ); + + it.each([['hidden'], [true], [false]] as const)( + 'keeps the client source maps of a `sourcemap.client: %s` the user set', + async client => { + const mockNuxt = createMockNuxt({ sourcemap: { client, server: true } }); + + setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + expect(getDeleteOption()).toBeUndefined(); + expect(getSdkEnabledSourceMaps()).toBe(false); + }, + ); + + it.each([ + { deleteSourcemapsAfterUpload: true, client: 'hidden' as const, expected: undefined }, + { deleteSourcemapsAfterUpload: false, client: undefined, expected: true }, + ])( + 'ignores a user-set `deleteSourcemapsAfterUpload: $deleteSourcemapsAfterUpload`', + async ({ deleteSourcemapsAfterUpload, client, expected }) => { + const mockNuxt = createMockNuxt({ sourcemap: { client, server: true } }); + + setupSourceMaps({ sourcemaps: { deleteSourcemapsAfterUpload } }, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + expect(getDeleteOption()).toBe(expected); + expect(getDeleteOption('client')).toBe(expected); + expect(getDeleteOption('ssr')).toBeUndefined(); + }, + ); + + // Today's glob deleted these maps, also when the user uploads by hand. + it('deletes the client source maps Sentry enabled when only the upload is disabled', async () => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); + + setupSourceMaps({ sourcemaps: { disable: 'disable-upload' } }, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + expect(capturedViteOptions.options?.sourcemaps?.disable).toBe('disable-upload'); + expect(getDeleteOption()).toBe(true); + expect(getSdkEnabledSourceMaps()).toBe(true); + }); + + describe('with the new source map options', () => { + async function runBuild( + sourcemaps: NonNullable[0]['sourcemaps']>, + sourcemap: { client?: SourceMapSetting; server?: SourceMapSetting } = {}, + ) { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: undefined, ...sourcemap } }); + + setupSourceMaps({ sourcemaps }, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + await mockNuxt.triggerHook('nitro:config', { rollupConfig: { plugins: [], output: {} }, dev: false }); + await mockNuxt.triggerHook('nitro:init', createMockNitro()); + await mockNuxt.triggerHook('close'); + + return mockNuxt; + } + + function expectFilesDeletedAfterBuild(filesToDeleteAfterUpload: string[]): void { + expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, + ); + } + + it.each([{ upload: false }, { injectDebugIds: false }])( + 'adds the plugins, turns no source maps on and deletes none with %j', + async sourcemaps => { + const mockNuxt = await runBuild(sourcemaps); + + expect(mockNuxt.options.sourcemap).toEqual({ client: undefined, server: undefined }); + expect(mockSentryVitePlugin).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }), + ); + expect(mockSentryRollupPlugin).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining(sourcemaps) }), + ); + expect(getDeleteOption()).toBeUndefined(); + expect(getSdkEnabledSourceMaps()).toBe(false); + expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled(); + }, + ); + + it('keeps the source maps of a manual upload with `upload: false` and `delete: false`', async () => { + const mockNuxt = await runBuild({ upload: false, delete: false }); + + expect(mockNuxt.options.sourcemap).toEqual({ client: 'hidden', server: 'hidden' }); + expect(getDeleteOption()).toBe(false); + expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled(); + }); + + it('keeps the source maps Sentry enabled with `delete: false`, but deletes the user-set files', async () => { + await runBuild({ delete: false, filesToDeleteAfterUpload: ['extra/**/*.map'] }); + + expect(getDeleteOption()).toBe(false); + expectFilesDeletedAfterBuild(['extra/**/*.map']); + }); + + it('deletes the source maps the user enabled with `delete: true`', async () => { + await runBuild({ delete: true }, { client: true, server: true }); + + expect(getDeleteOption()).toBe(true); + expect(getSdkEnabledSourceMaps()).toBe(true); + expectFilesDeletedAfterBuild(['.output/server/**/*.map']); + }); + + it('deletes the user-set files next to the source maps with `delete: true`', async () => { + await runBuild({ delete: true, filesToDeleteAfterUpload: ['extra/**/*.map'] }); + + expectFilesDeletedAfterBuild(['.output/server/**/*.map', 'extra/**/*.map']); + }); + + // Nitro still needs the maps of the SSR build, so neither plugin gets the option itself. + it.each([true, false])('applies `delete: %s` to the client environment only', async value => { + await runBuild({ delete: value, deleteSourcemapsAfterUpload: !value }); + + expect(capturedViteOptions.options?.sourcemaps?.delete).toBeUndefined(); + expect(getDeleteOption('client')).toBe(value); + expect(getDeleteOption('ssr')).toBeUndefined(); + expect(getSdkEnabledSourceMaps('ssr')).toBe(false); + expect(mockSentryRollupPlugin).toHaveBeenCalledWith( + expect.objectContaining({ + sourcemaps: expect.objectContaining({ delete: undefined, deleteSourcemapsAfterUpload: false }), + }), + ); + }); + }); + + // A broad glob also matches the SSR build's maps, which Nitro still needs. + it('applies only the user-set `filesToDeleteAfterUpload`, after the build', async () => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); + const filesToDeleteAfterUpload = ['.output/**/*.map']; + + setupSourceMaps({ sourcemaps: { filesToDeleteAfterUpload } }, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + await mockNuxt.triggerHook('close'); + + expect(capturedViteOptions.options?.sourcemaps?.filesToDeleteAfterUpload).toBeUndefined(); + expect(getDeleteOption()).toBeUndefined(); + expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( + expect.objectContaining({ sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload }) }), + { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, + ); + }); + }); + describe('close hook', () => { it('deletes source maps after the build using fallback patterns', async () => { const mockNuxt = createMockNuxt({ @@ -387,12 +659,7 @@ describe('setupSourceMaps hooks', () => { await mockNuxt.triggerHook('nitro:init', createMockNitro()); await mockNuxt.triggerHook('close'); - expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ filesToDeleteAfterUpload: ['.output/public/**/*.map'] }), - }), - { buildTool: 'nuxt', loggerPrefix: '[Sentry Nuxt]' }, - ); + expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled(); }); it('uses user-provided deletion patterns after the build', async () => { @@ -466,6 +733,43 @@ describe('setupSourceMaps hooks', () => { expect(nitroConfig.rollupConfig.plugins.length).toBeGreaterThan(0); }); + it.each<{ + label: string; + del: boolean; + sourceMap: true | 'hidden' | 'inline'; + output: { sourcemap?: boolean }; + expected: unknown; + }>([ + { label: 'switches visible server maps to hidden', del: true, sourceMap: true, output: {}, expected: 'hidden' }, + { + label: 'keeps visible server maps without `delete: true`', + del: false, + sourceMap: true, + output: {}, + expected: true, + }, + { label: 'keeps hidden server maps', del: true, sourceMap: 'hidden', output: {}, expected: 'hidden' }, + { label: 'keeps inline server maps', del: true, sourceMap: 'inline', output: {}, expected: 'inline' }, + { + label: 'keeps `nitro.sourceMap` when `rollupConfig.output.sourcemap` overrides it', + del: true, + sourceMap: true, + output: { sourcemap: true }, + expected: true, + }, + ])('$label', async ({ del, sourceMap, output, expected }) => { + const mockNuxt = createMockNuxt({ _prepare: false, dev: false, sourcemap: { server: sourceMap } }); + const { mockAddVitePlugin } = createMockAddVitePlugin(); + + setupSourceMaps({ sourcemaps: { delete: del } }, mockNuxt as unknown as Nuxt, mockAddVitePlugin); + await mockNuxt.triggerHook('modules:done'); + + const nitroConfig = { rollupConfig: { plugins: [] as unknown[], output }, dev: false, sourceMap }; + await mockNuxt.triggerHook('nitro:config', nitroConfig); + + expect(nitroConfig.sourceMap).toBe(expected); + }); + it.each([ { label: 'prepare mode', @@ -541,35 +845,33 @@ describe('setupSourceMaps hooks', () => { expect(remainingFiles()).toEqual([PUBLIC_CHUNK, SSR_BUILD_MAP]); }); - it('deletes only the public source maps with the fallback patterns and keeps the SSR build maps', async () => { + // The Vite plugin never writes the client maps Sentry enabled, and Nitro still needs the SSR build maps. + it('deletes nothing with the fallback patterns', async () => { const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: undefined } }); const nitro = createMockNitro(); setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); await mockNuxt.triggerHook('modules:done'); await mockNuxt.triggerHook('nitro:init', nitro); - const deletionPlugin = findDeletionPlugin(nitro); - await deletionPlugin?.buildStart(); + await findDeletionPlugin(nitro)?.buildStart(); - expect(deletionPlugin).toBeDefined(); - expect(remainingFiles()).toEqual([PUBLIC_CHUNK, SSR_BUILD_MAP]); + expect(remainingFiles()).toEqual([PUBLIC_MAP, PUBLIC_CHUNK, SSR_BUILD_MAP]); }); - it('deletes the public source maps of a preset that writes the public files outside of `.output`', async () => { - const netlifyPublicMap = 'dist/_nuxt/entry.DxB3kLmA.js.map'; - fs.mkdirSync(path.dirname(path.join(rootDir, netlifyPublicMap)), { recursive: true }); - fs.writeFileSync(path.join(rootDir, netlifyPublicMap), ''); - const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: true } }); - const nitro = createMockNitro({ - output: { publicDir: 'dist', serverDir: '.netlify/functions-internal/server' }, + // No Vite plugin runs with webpack or rspack, so the client maps Sentry enabled reach the public dir. + it('deletes the client source maps Sentry enabled with a builder other than Vite', async () => { + const mockNuxt = createMockNuxt({ + sourcemap: { client: undefined, server: undefined }, + builder: '@nuxt/webpack-builder', }); + const nitro = createMockNitro(); setupSourceMaps({}, mockNuxt as unknown as Nuxt, vi.fn()); await mockNuxt.triggerHook('modules:done'); await mockNuxt.triggerHook('nitro:init', nitro); await findDeletionPlugin(nitro)?.buildStart(); - expect(fs.existsSync(path.join(rootDir, netlifyPublicMap))).toBe(false); + expect(remainingFiles()).toEqual([PUBLIC_CHUNK, SSR_BUILD_MAP]); }); it.each([ @@ -591,6 +893,22 @@ describe('setupSourceMaps hooks', () => { }); describe('debug logging', () => { + it.each(['@nuxt/vite-builder', '@nuxt/webpack-builder'])( + 'names the option that keeps the source maps Sentry enabled with %s', + async builder => { + const mockNuxt = createMockNuxt({ sourcemap: { client: undefined, server: undefined }, builder }); + + setupSourceMaps({ debug: true }, mockNuxt as unknown as Nuxt, vi.fn()); + await mockNuxt.triggerHook('modules:done'); + + for (const side of ['client', 'server']) { + expect(consoleLogSpy).toHaveBeenCalledWith( + `[Sentry] We enabled \`'hidden'\` source maps for your ${side}-side build. Sentry deletes them after the upload, unless you set \`sourcemaps.filesToDeleteAfterUpload\`.`, + ); + } + }, + ); + it('logs a [Sentry] message in production mode', async () => { const mockNuxt = createMockNuxt({ _prepare: false, dev: false }); const { mockAddVitePlugin, getValidationPlugin } = createMockAddVitePlugin(); diff --git a/packages/nuxt/test/vite/sourceMaps.test.ts b/packages/nuxt/test/vite/sourceMaps.test.ts index 89b1c44acd10..e6df2bfc5305 100644 --- a/packages/nuxt/test/vite/sourceMaps.test.ts +++ b/packages/nuxt/test/vite/sourceMaps.test.ts @@ -22,10 +22,7 @@ vi.mock('@sentry/core', async importOriginal => { }; }); -const NODE_SERVER_OUTPUT_DIRS = { - publicDir: path.join(process.cwd(), '.output', 'public'), - serverDir: path.join(process.cwd(), '.output', 'server'), -}; +const NODE_SERVER_DIR = path.join(process.cwd(), '.output', 'server'); describe('getPluginOptions', () => { beforeEach(() => { @@ -221,13 +218,13 @@ describe('getPluginOptions', () => { name: 'both client and server fallback are true', clientFallback: true, serverFallback: true, - expected: ['.output/public/**/*.map', '.output/server/**/*.map'], + expected: ['.output/server/**/*.map'], }, { name: 'only client fallback is true', clientFallback: true, serverFallback: false, - expected: ['.output/public/**/*.map'], + expected: undefined, }, { name: 'only server fallback is true', @@ -239,7 +236,7 @@ describe('getPluginOptions', () => { name: 'both fallbacks are true, but Nitro is not set up yet', clientFallback: true, serverFallback: true, - outputDirs: null, + serverDir: null, expected: undefined, }, { @@ -260,11 +257,11 @@ describe('getPluginOptions', () => { }, ])( 'sets filesToDeleteAfterUpload correctly when $name', - ({ clientFallback, serverFallback, customOptions = {}, outputDirs = NODE_SERVER_OUTPUT_DIRS, expected }) => { + ({ clientFallback, serverFallback, customOptions = {}, serverDir = NODE_SERVER_DIR, expected }) => { const options = getPluginOptions(customOptions as SentryNuxtModuleOptions, { client: clientFallback, server: serverFallback, - outputDirs: outputDirs ?? undefined, + serverDir: serverDir ?? undefined, }); expect(options?.sourcemaps?.filesToDeleteAfterUpload).toEqual(expected); @@ -409,10 +406,14 @@ describe('change Nuxt source map settings', () => { // @ts-expect-error - Nuxt types don't accept `undefined` but we want to test this case nuxt = { options: { sourcemap: { client: undefined } } }; sentryModuleOptions = {}; + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); }); afterEach(() => { consoleLogSpy.mockRestore(); + vi.unstubAllEnvs(); }); it.each([ @@ -462,6 +463,54 @@ describe('change Nuxt source map settings', () => { expect(previousUserSourcemapSetting.server).toBe(expectedReturn); }); + it.each([ + [{ upload: false }, undefined], + [{ injectDebugIds: false }, undefined], + [{ upload: false, delete: true }, undefined], + [{ injectDebugIds: false, delete: false }, undefined], + [{ upload: false, delete: false }, 'hidden'], + [{ delete: true }, 'hidden'], + [{ disable: 'disable-upload' }, 'hidden'], + [{ disable: true, upload: true }, 'hidden'], + ] as const)('with unset source maps and `sourcemaps: %j` it sets both sides to %s', (sourcemaps, expected) => { + // @ts-expect-error - Nuxt types don't accept `undefined` but we want to test this case + nuxt.options.sourcemap = { client: undefined, server: undefined }; + const previousUserSourcemapSetting = changeNuxtSourceMapSettings(nuxt as Nuxt, { sourcemaps }); + + expect(nuxt.options.sourcemap).toEqual({ client: expected, server: expected }); + expect(previousUserSourcemapSetting).toEqual({ client: 'unset', server: 'unset' }); + }); + + it.each([ + [{ SENTRY_AUTH_TOKEN: '' }, {}, undefined], + [{ SENTRY_ORG: '' }, {}, undefined], + [{ SENTRY_PROJECT: '' }, {}, undefined], + [{ SENTRY_AUTH_TOKEN: '' }, { authToken: 'token' }, 'hidden'], + [{ SENTRY_ORG: '', SENTRY_AUTH_TOKEN: 'sntrys_token' }, {}, 'hidden'], + [{ SENTRY_AUTH_TOKEN: '' }, { sourcemaps: { delete: false } }, 'hidden'], + [{ SENTRY_AUTH_TOKEN: '' }, { sourcemaps: { disable: 'disable-upload' } }, 'hidden'], + ] as const)( + 'with the environment %j and the options %j it sets unset source maps to %s', + (env, moduleOptions, expected) => { + for (const [key, value] of Object.entries(env)) { + vi.stubEnv(key, value); + } + // @ts-expect-error - Nuxt types don't accept `undefined` but we want to test this case + nuxt.options.sourcemap = { client: undefined, server: undefined }; + changeNuxtSourceMapSettings(nuxt as Nuxt, moduleOptions); + + expect(nuxt.options.sourcemap).toEqual({ client: expected, server: expected }); + }, + ); + + it('leaves `nuxt.options.sourcemap` unset when Sentry turns no source maps on', () => { + // @ts-expect-error - Nuxt types don't accept `undefined` but we want to test this case + nuxt.options.sourcemap = undefined; + changeNuxtSourceMapSettings(nuxt as Nuxt, { sourcemaps: { upload: false } }); + + expect(nuxt.options.sourcemap).toEqual({ client: undefined, server: undefined }); + }); + it("sets client and server to 'hidden' if nuxt.options.sourcemap not set", () => { // @ts-expect-error - Nuxt types don't accept `undefined` but we want to test this case nuxt.options.sourcemap = undefined; diff --git a/packages/nuxt/test/vite/utils.test.ts b/packages/nuxt/test/vite/utils.test.ts index fa1673c4dcd3..4ca6f2d3ff16 100644 --- a/packages/nuxt/test/vite/utils.test.ts +++ b/packages/nuxt/test/vite/utils.test.ts @@ -7,6 +7,7 @@ import { constructFunctionReExport, constructWrappedFunctionExportQuery, extractFunctionReexportQueryParameters, + findCloudflareOptionsFile, findDefaultSdkInitFile, getFilenameFromNodeStartCommand, QUERY_END_INDICATOR, @@ -190,6 +191,31 @@ describe('findDefaultSdkInitFile', () => { }); }); +describe('findCloudflareOptionsFile', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it.each(['ts', 'js', 'mjs', 'cjs', 'mts', 'cts'])( + 'returns the sentry.cloudflare.config.%s file if it exists', + async ext => { + vi.mocked(fs.existsSync).mockImplementation(filePath => { + return !(filePath instanceof URL) && filePath.toString().includes(`sentry.cloudflare.config.${ext}`); + }); + + const result = await findCloudflareOptionsFile(); + expect(result).toMatch(path.join('packages', 'nuxt', `sentry.cloudflare.config.${ext}`)); + }, + ); + + it('returns undefined if no sentry.cloudflare.config file exists', async () => { + vi.mocked(fs.existsSync).mockReturnValue(false); + + const result = await findCloudflareOptionsFile(); + expect(result).toBeUndefined(); + }); +}); + describe('toImportSpecifier', () => { it('builds a relative specifier Node accepts', () => { expect(toImportSpecifier(path.join('/my', 'app'), path.join('/my', 'app', '.nuxt', 'dev', 'config.mjs'))).toBe( diff --git a/packages/nuxt/tsconfig.test.json b/packages/nuxt/tsconfig.test.json index 3477e66e93ca..f3e764584f2a 100644 --- a/packages/nuxt/tsconfig.test.json +++ b/packages/nuxt/tsconfig.test.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig.json", - "include": ["test/**/*"], + "include": ["test/**/*", "src/runtime/utils/cloudflareWorkers.d.ts"], "compilerOptions": { // should include all types from `./tsconfig.json` plus types for all test frameworks used diff --git a/packages/opentelemetry/package.json b/packages/opentelemetry/package.json index 94794a298e04..758032186ab8 100644 --- a/packages/opentelemetry/package.json +++ b/packages/opentelemetry/package.json @@ -27,7 +27,7 @@ "access": "public" }, "dependencies": { - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0" }, "peerDependencies": { diff --git a/packages/profiling-node/package.json b/packages/profiling-node/package.json index 489b33306650..dac65ee44546 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.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/node-cpu-profiler": "^2.4.4", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0" diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 97662e8e3ead..57646010f2ee 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.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/react": "11.17.0", diff --git a/packages/react-router/src/client/sdk.ts b/packages/react-router/src/client/sdk.ts index e2e62516d7e6..809ffb928e15 100644 --- a/packages/react-router/src/client/sdk.ts +++ b/packages/react-router/src/client/sdk.ts @@ -4,7 +4,7 @@ import type { Client } from '@sentry/core'; import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, - _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, + applyBrowserTunnelDefaults, consoleSandbox, GLOBAL_OBJ, setTag, diff --git a/packages/react-router/src/cloudflare/index.ts b/packages/react-router/src/cloudflare/index.ts index 79f55e7100f5..3b9a3a376d25 100644 --- a/packages/react-router/src/cloudflare/index.ts +++ b/packages/react-router/src/cloudflare/index.ts @@ -1,7 +1,8 @@ export * from '../client'; export { wrapSentryHandleRequest } from '../server/wrapSentryHandleRequest'; -export { setTunnelBasePath as _INTERNAL_setTunnelBasePath } from '../server/tunnelRoute'; +export { setTunnelBasePath } from '../server/tunnelRoute'; +// Prefixed because only the code `sentryReactRouter()` injects imports it. export { injectClientRelease as _INTERNAL_injectClientRelease } from '../server/clientRelease'; export { createSentryServerInstrumentation, diff --git a/packages/react-router/src/server/index.ts b/packages/react-router/src/server/index.ts index f68be9ed45e9..2ec87bcf8c19 100644 --- a/packages/react-router/src/server/index.ts +++ b/packages/react-router/src/server/index.ts @@ -9,7 +9,8 @@ export { createSentryHandleRequest, type SentryHandleRequestOptions } from './cr export type { SentryWebStreamHandleRequestOptions } from './handleRequestTypes'; export { createSentryHandleError, type SentryHandleErrorOptions } from './createSentryHandleError'; export { getMetaTagTransformer } from './getMetaTagTransformer'; -export { setTunnelBasePath as _INTERNAL_setTunnelBasePath } from './tunnelRoute'; +export { setTunnelBasePath } from './tunnelRoute'; +// Prefixed because only the code `sentryReactRouter()` injects imports it. export { injectClientRelease as _INTERNAL_injectClientRelease } from './clientRelease'; // React Router instrumentation API support diff --git a/packages/react-router/src/server/tunnelRoute.ts b/packages/react-router/src/server/tunnelRoute.ts index 1d10aa356f19..e37752d4e4bb 100644 --- a/packages/react-router/src/server/tunnelRoute.ts +++ b/packages/react-router/src/server/tunnelRoute.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; /** * Serves the managed tunnel under the app's `basename`, which React Router leaves in the request URL. diff --git a/packages/react-router/src/vite/makeCustomSentryVitePlugins.ts b/packages/react-router/src/vite/makeCustomSentryVitePlugins.ts index 031575465433..0522109ed041 100644 --- a/packages/react-router/src/vite/makeCustomSentryVitePlugins.ts +++ b/packages/react-router/src/vite/makeCustomSentryVitePlugins.ts @@ -1,5 +1,5 @@ import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; -import { warnOnRemovedBuildOptions } from '@sentry/core'; +import { warnOnConflictingSourceMapOptions, warnOnRemovedBuildOptions } from '@sentry/core'; import { type Plugin } from 'vite'; import type { SentryReactRouterBuildOptions } from './types'; @@ -8,6 +8,8 @@ import type { SentryReactRouterBuildOptions } from './types'; */ export async function makeCustomSentryVitePlugins(options: SentryReactRouterBuildOptions): Promise { warnOnRemovedBuildOptions(options, ['unstable_sentryVitePluginOptions']); + // The Vite plugin does not get the user's source map options. + warnOnConflictingSourceMapOptions(options.sourcemaps); const { debug, diff --git a/packages/react-router/src/vite/makeTunnelBasePathPlugin.ts b/packages/react-router/src/vite/makeTunnelBasePathPlugin.ts index c9e1c41886ec..743f65f88874 100644 --- a/packages/react-router/src/vite/makeTunnelBasePathPlugin.ts +++ b/packages/react-router/src/vite/makeTunnelBasePathPlugin.ts @@ -17,7 +17,7 @@ export function makeTunnelBasePathPlugin(): Plugin { return { code: `${code} -import { _INTERNAL_setTunnelBasePath as __sentrySetTunnelBasePath } from '@sentry/react-router'; +import { setTunnelBasePath as __sentrySetTunnelBasePath } from '@sentry/react-router'; __sentrySetTunnelBasePath(typeof basename === 'string' ? basename : undefined); `, map: null, diff --git a/packages/react-router/test/vite/makeCustomSentryVitePlugins.test.ts b/packages/react-router/test/vite/makeCustomSentryVitePlugins.test.ts index aac3a264037d..c6f356caf703 100644 --- a/packages/react-router/test/vite/makeCustomSentryVitePlugins.test.ts +++ b/packages/react-router/test/vite/makeCustomSentryVitePlugins.test.ts @@ -154,4 +154,17 @@ describe('makeCustomSentryVitePlugins', () => { consoleWarnSpy.mockRestore(); }); + + // The Vite plugin gets none of the user's source map options, so it cannot warn itself. + it('warns about conflicting source map options', async () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + await makeCustomSentryVitePlugins({ sourcemaps: { delete: false, filesToDeleteAfterUpload: ['build/**/*.map'] } }); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('`sourcemaps.filesToDeleteAfterUpload` still deletes the files'), + ); + + consoleWarnSpy.mockRestore(); + }); }); diff --git a/packages/react/.oxlintrc.json b/packages/react/.oxlintrc.json index 0f2462e486a8..9c181965eaa9 100644 --- a/packages/react/.oxlintrc.json +++ b/packages/react/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "plugins": ["react"], "env": { "browser": true diff --git a/packages/react/package.json b/packages/react/package.json index 568b81ef4786..c9d6d7cfd823 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -59,7 +59,7 @@ "dependencies": { "@sentry/browser": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0" + "@sentry/conventions": "^0.36.0" }, "peerDependencies": { "react": "17.x || 18.x || 19.x", diff --git a/packages/remix/package.json b/packages/remix/package.json index 3a8e4f3519d9..a41571f05781 100644 --- a/packages/remix/package.json +++ b/packages/remix/package.json @@ -78,7 +78,7 @@ "@remix-run/router": "^1.23.4", "@sentry/browser": "11.17.0", "@sentry/bundler-plugins": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/react": "11.17.0", diff --git a/packages/remix/src/utils/utils.ts b/packages/remix/src/utils/utils.ts index 73b097b2ede0..ec9e96e6a4ba 100644 --- a/packages/remix/src/utils/utils.ts +++ b/packages/remix/src/utils/utils.ts @@ -95,7 +95,12 @@ export function convertRemixRouteIdToPath(routeId: string): string { return routePath; } -/** Check if running in Cloudflare Workers environment. */ +/** + * Check if running in Cloudflare Workers environment. + * + * Not `isCloudflareWorkers()` from `@sentry/server-utils`: any import of that package pulls `node:async_hooks` + * into Hydrogen builds. + */ export function isCloudflareEnv(): boolean { // eslint-disable-next-line no-restricted-globals return typeof navigator !== 'undefined' && navigator?.userAgent?.includes('Cloudflare'); diff --git a/packages/remix/src/v3/server/middleware.ts b/packages/remix/src/v3/server/middleware.ts index 4e070eabbdac..7a274b155e2e 100644 --- a/packages/remix/src/v3/server/middleware.ts +++ b/packages/remix/src/v3/server/middleware.ts @@ -11,7 +11,7 @@ import { updateSpanName, winterCGRequestToRequestData, } from '@sentry/core'; -import { _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest } from '@sentry/core/server'; +import { handleServedTunnelRequest } from '@sentry/core/server'; import { formatRouteTiming } from '../routeTiming'; import type { MatcherLike, MiddlewareLike, NextFunctionLike, RequestContextLike } from '../types'; diff --git a/packages/remix/src/vite/sourceMaps.ts b/packages/remix/src/vite/sourceMaps.ts index 288edb9fef9b..05f729af2b21 100644 --- a/packages/remix/src/vite/sourceMaps.ts +++ b/packages/remix/src/vite/sourceMaps.ts @@ -1,3 +1,4 @@ +import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import { resolveSourceMapsFeatures } from '@sentry/core'; import type { Plugin, UserConfig } from 'vite'; @@ -58,8 +59,9 @@ export function makeAddSentryVitePlugin( // Called when the bundler plugin decides, after `makeEnableSourceMapsPlugin` ran. // Without an upload the user uploads the maps by hand, so they stay. // The SDK never read the user's `deleteSourcemapsAfterUpload`. `delete` replaces it. + // A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. deleteSourcemapsAfterUpload: - sourcemaps?.delete === undefined + sourcemaps?.delete === undefined && sourcemaps?.filesToDeleteAfterUpload === undefined ? () => (state.sdkEnabledSourceMaps && resolveSourceMapsFeatures(sourcemaps).upload ? true : undefined) : undefined, sdkEnabledSourceMaps: () => state.sdkEnabledSourceMaps, @@ -150,7 +152,13 @@ export function getUpdatedSourceMapSettings( // Without an upload, Sentry only turns source maps on when `sourcemaps.delete: false` keeps them. // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. - if (!(upload || legacyDisable === 'disable-upload' || (sourcemaps?.delete === false && injectDebugIds))) { + if ( + !( + (upload && hasSourceMapUploadCredentials(sentryPluginOptions)) || + legacyDisable === 'disable-upload' || + (sourcemaps?.delete === false && injectDebugIds) + ) + ) { return undefined; } diff --git a/packages/remix/test/v3/instrument.test.ts b/packages/remix/test/v3/instrument.test.ts index cf22efc91609..519762aeef45 100644 --- a/packages/remix/test/v3/instrument.test.ts +++ b/packages/remix/test/v3/instrument.test.ts @@ -18,7 +18,7 @@ const tunnelResponse = new Response(null, { status: 200 }); // Answers only `TUNNEL_URL`, like a server with the managed tunnel at that path. vi.mock('@sentry/core/server', () => ({ - _INTERNAL_handleServedTunnelRequest: (request: Request) => + handleServedTunnelRequest: (request: Request) => request.url === TUNNEL_URL ? Promise.resolve(tunnelResponse) : undefined, })); diff --git a/packages/remix/test/v3/middleware.test.ts b/packages/remix/test/v3/middleware.test.ts index e0f1866e78fd..aeb782aa2ab6 100644 --- a/packages/remix/test/v3/middleware.test.ts +++ b/packages/remix/test/v3/middleware.test.ts @@ -16,7 +16,7 @@ vi.mock('@sentry/core', async importOriginal => ({ vi.mock('@sentry/core/server', async importOriginal => ({ ...(await importOriginal()), - _INTERNAL_handleServedTunnelRequest: handleServedTunnelRequest, + handleServedTunnelRequest: handleServedTunnelRequest, })); import { sentryRemixMiddleware } from '../../src/v3/server/middleware'; diff --git a/packages/remix/test/vite/index.test.ts b/packages/remix/test/vite/index.test.ts index 9c55ed67a7d4..9f4514061b86 100644 --- a/packages/remix/test/vite/index.test.ts +++ b/packages/remix/test/vite/index.test.ts @@ -104,7 +104,7 @@ describe('sentryRemixVitePlugin', () => { // The bundler plugin reads the option when its own `config` hook runs, which comes after ours. it('enables hidden source maps and asks the bundler plugin to delete them', () => { - const config = runConfigHooks(sentryRemixVitePlugin(), {}); + const config = runConfigHooks(sentryRemixVitePlugin({ authToken: 'token', org: 'org', project: 'project' }), {}); expect(config.build?.sourcemap).toBe('hidden'); expect(deleteOptionInConfigHook).toBe(true); diff --git a/packages/remix/test/vite/sourceMaps.test.ts b/packages/remix/test/vite/sourceMaps.test.ts index a090e5910f28..3e2dd7796461 100644 --- a/packages/remix/test/vite/sourceMaps.test.ts +++ b/packages/remix/test/vite/sourceMaps.test.ts @@ -1,6 +1,6 @@ import type { SentryVitePluginInternalOptions } from '@sentry/bundler-plugins/vite'; import type { UserConfig } from 'vite'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SourceMapState } from '../../src/vite/sourceMaps'; import { getUpdatedSourceMapSettings, @@ -27,7 +27,21 @@ beforeEach(() => { delete process.env.SENTRY_AUTH_TOKEN; }); +function stubUploadCredentials(): void { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); +} + +afterEach(() => { + vi.unstubAllEnvs(); +}); + describe('makeEnableSourceMapsPlugin', () => { + beforeEach(() => { + stubUploadCredentials(); + }); + it('returns a build-time plugin that updates the source map setting', () => { const plugin = makeEnableSourceMapsPlugin({}); @@ -58,6 +72,7 @@ describe('makeEnableSourceMapsPlugin', () => { describe('getUpdatedSourceMapSettings', () => { beforeEach(() => { + stubUploadCredentials(); vi.spyOn(console, 'warn').mockImplementation(() => undefined); vi.spyOn(console, 'log').mockImplementation(() => undefined); }); @@ -98,6 +113,16 @@ describe('getUpdatedSourceMapSettings', () => { expect(getUpdatedSourceMapSettings({}, { sourcemaps })).toBe(expected); }); + it.each([ + [{}, undefined], + [{ disable: 'disable-upload' }, 'hidden'], + [{ delete: false }, 'hidden'], + ] as const)('without upload credentials, with an unset setting and %j it returns %s', (sourcemaps, expected) => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + + expect(getUpdatedSourceMapSettings({}, { sourcemaps })).toBe(expected); + }); + it('leaves the Vite config alone when it turns no source maps on', () => { const state: SourceMapState = { sdkEnabledSourceMaps: true }; const plugin = makeEnableSourceMapsPlugin({ sourcemaps: { upload: false } }, state); @@ -225,15 +250,15 @@ describe('makeAddSentryVitePlugin', () => { }, ); - it('passes a user-set filesToDeleteAfterUpload through and still deletes the maps the SDK enabled', () => { - makeAddSentryVitePlugin( - { sourcemaps: { filesToDeleteAfterUpload: ['./dist/**/*.map'] } }, - { sdkEnabledSourceMaps: true }, - ); + it.each([[['./dist/**/*.map']], [[]]])( + 'lets a user-set `filesToDeleteAfterUpload: %j` replace the deletion', + files => { + makeAddSentryVitePlugin({ sourcemaps: { filesToDeleteAfterUpload: files } }, { sdkEnabledSourceMaps: true }); - expect(capturedOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(['./dist/**/*.map']); - expect(getDeleteOption()).toBe(true); - }); + expect(capturedOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(files); + expect(getDeleteOption()).toBeUndefined(); + }, + ); it('tells the bundler plugin whether the SDK enabled the source maps', () => { const state: SourceMapState = { sdkEnabledSourceMaps: false }; diff --git a/packages/replay-canvas/.oxlintrc.json b/packages/replay-canvas/.oxlintrc.json index 4cd4930fa802..c996f1bd946a 100644 --- a/packages/replay-canvas/.oxlintrc.json +++ b/packages/replay-canvas/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"] + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"] } diff --git a/packages/replay-canvas/package.json b/packages/replay-canvas/package.json index 94f7220945d2..55f3e29b456f 100644 --- a/packages/replay-canvas/package.json +++ b/packages/replay-canvas/package.json @@ -54,7 +54,7 @@ "homepage": "https://docs.sentry.io/platforms/javascript/session-replay/", "devDependencies": { "@sentry-internal/rollup-utils": "11.17.0", - "@sentry/rrweb": "2.46.0" + "@sentry/rrweb": "2.47.0" }, "dependencies": { "@sentry/replay": "11.17.0", diff --git a/packages/replay-internal/.oxlintrc.json b/packages/replay-internal/.oxlintrc.json index 21ef9701c095..f8fd22159b3b 100644 --- a/packages/replay-internal/.oxlintrc.json +++ b/packages/replay-internal/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "overrides": [ { "files": ["test.setup.ts", "vitest.config.ts"], diff --git a/packages/replay-internal/package.json b/packages/replay-internal/package.json index 7645e4b90eaa..6cf435ed47e6 100644 --- a/packages/replay-internal/package.json +++ b/packages/replay-internal/package.json @@ -68,9 +68,9 @@ "devDependencies": { "@sentry-internal/replay-worker": "11.17.0", "@sentry-internal/rollup-utils": "11.17.0", - "@sentry/conventions": "^0.35.0", - "@sentry/rrweb": "2.46.0", - "@sentry/rrweb-snapshot": "2.46.0", + "@sentry/conventions": "^0.36.0", + "@sentry/rrweb": "2.47.0", + "@sentry/rrweb-snapshot": "2.47.0", "fflate": "0.8.3", "jsdom-worker": "^0.3.0" }, diff --git a/packages/replay-worker/.oxlintrc.json b/packages/replay-worker/.oxlintrc.json index 280567c4e7fc..02dbf044dd01 100644 --- a/packages/replay-worker/.oxlintrc.json +++ b/packages/replay-worker/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "ignorePatterns": ["examples/worker.js"], "overrides": [ { diff --git a/packages/server-utils/package.json b/packages/server-utils/package.json index 0f5370425746..8f8fef6c0473 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.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0" }, "devDependencies": { diff --git a/packages/server-utils/src/ai/langchain/utils.ts b/packages/server-utils/src/ai/langchain/utils.ts index aca00ad5e507..c20f7f7b4739 100644 --- a/packages/server-utils/src/ai/langchain/utils.ts +++ b/packages/server-utils/src/ai/langchain/utils.ts @@ -444,17 +444,14 @@ export function extractLlmResponseAttributes( if (Array.isArray(llmResult.generations)) { const finishReasons = llmResult.generations .flat() - .map(g => { - // v1 uses generationInfo.finish_reason - if (g.generationInfo?.finish_reason) { - return g.generationInfo.finish_reason; - } - // v0.3+ uses generation_info.finish_reason - if (g.generation_info?.finish_reason) { - return g.generation_info.finish_reason; - } - return null; - }) + .map( + g => + // v1 uses generationInfo, v0.3+ uses generation_info. The OpenAI Responses API sets neither and only + // reports it on the message. + g.generationInfo?.finish_reason || + g.generation_info?.finish_reason || + g.message?.response_metadata?.finish_reason, + ) .filter((r): r is string => typeof r === 'string'); if (finishReasons.length > 0) { diff --git a/packages/server-utils/src/ai/mistral/streaming.ts b/packages/server-utils/src/ai/mistral/streaming.ts index cb5f097a44a8..10e0ca754b05 100644 --- a/packages/server-utils/src/ai/mistral/streaming.ts +++ b/packages/server-utils/src/ai/mistral/streaming.ts @@ -203,6 +203,7 @@ function wrapReader( */ function instrumentedSource(readable: ReadableStreamLike): ReadableStream { // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic. + // oxlint-disable-next-line typescript/no-non-null-assertion -- only called when `getReader` is a function const reader = readable.getReader!(); return new ReadableStream({ diff --git a/packages/server-utils/src/exports.ts b/packages/server-utils/src/exports.ts index d9fae4eb0f29..94e49d229749 100644 --- a/packages/server-utils/src/exports.ts +++ b/packages/server-utils/src/exports.ts @@ -6,6 +6,7 @@ export * from './ai'; export { getSqlQuerySummary, sanitizeSqlQuery, getSqlQueryAttributes, getSqlSpanName } from './utils/sql'; export type { SqlDialect } from './utils/sql'; export { isBun, isCloudflareWorkers, isDeno } from './utils/runtime'; +export { collectInstalledModules } from './utils/installedModules'; export { instrumentPostgresJsSql } from './integrations/postgresjs-wrapper'; export type { PostgresConnectionContext } from './integrations/postgresjs-wrapper'; diff --git a/packages/server-utils/src/index.request-handler.ts b/packages/server-utils/src/index.request-handler.ts index 73e0902cc088..3b55eebb0529 100644 --- a/packages/server-utils/src/index.request-handler.ts +++ b/packages/server-utils/src/index.request-handler.ts @@ -2,3 +2,4 @@ // it on workers without the `nodejs_compat` compatibility flag. export { wrapServerRequestHandler } from './utils/wrapServerRequestHandler'; export type { ServerRequestHandlerConfig } from './utils/wrapServerRequestHandler'; +export { addServerTimingTraceHeader } from './utils/serverTimingTraceHeader'; diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 8d7fcad8d800..7a3fccd1fadb 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -69,11 +69,9 @@ export { piDurableIntegration } from './integrations/pi-durable'; export type { FlueOptions } from './ai/flue'; export { mastraIntegration } from './integrations/mastra'; export { mcpServerIntegration } from './integrations/mcp-server'; -export { - instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, - makeServeTunnelIntegration, -} from './integrations/serveTunnel'; -export { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer'; +export { instrumentTunnelServers, makeServeTunnelIntegration } from './integrations/serveTunnel'; +export { instrumentTunnelServer } from './utils/tunnelServer'; +export { createGetModuleFromFilename } from './utils/module'; export { SentryMastraExporter } from './ai/mastra'; export { lruMemoizerIntegration } from './integrations/lru-memoizer'; export { mongoIntegration } from './integrations/mongodb'; diff --git a/packages/server-utils/src/integrations/amqplib.ts b/packages/server-utils/src/integrations/amqplib.ts index dcd0346cac1e..11655bd0f1b6 100644 --- a/packages/server-utils/src/integrations/amqplib.ts +++ b/packages/server-utils/src/integrations/amqplib.ts @@ -377,6 +377,7 @@ function handleAck(data: AmqpChannelContext, isRejected: boolean, endOperation: endConsumerSpan(message, isRejected, endOperation, requeueResolved); } else if (endOperation !== END_OP.Reject && allUpToOrRequeue) { for (let i = 0; i <= msgIndex; i++) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop endConsumerSpan(spansNotEnded[i]!.msg, isRejected, endOperation, requeueResolved); } spansNotEnded.splice(0, msgIndex + 1); @@ -428,6 +429,7 @@ function checkConsumeTimeoutOnChannel(channel: ChannelLike): void { const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? []; let i: number; for (i = 0; i < spansNotEnded.length; i++) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop const currMessage = spansNotEnded[i]!; const timeFromConsumeMs = (currentTime - currMessage.timeOfConsume) * 1000; if (timeFromConsumeMs < CONSUME_TIMEOUT_MS) { diff --git a/packages/server-utils/src/integrations/anthropic.ts b/packages/server-utils/src/integrations/anthropic.ts index 5570fa31dbd5..0bf1335bfcb9 100644 --- a/packages/server-utils/src/integrations/anthropic.ts +++ b/packages/server-utils/src/integrations/anthropic.ts @@ -251,6 +251,8 @@ function wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: }, error => { // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal. + // The thread emits 'abort' and 'end' only after it awaits `_responseProps()` itself, which is after this handler, + // so the listeners cannot miss them. if (signal.aborted) { instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd); } else { diff --git a/packages/server-utils/src/integrations/bullmq/tracer.ts b/packages/server-utils/src/integrations/bullmq/tracer.ts index 5722b013e451..aa46e8daa028 100644 --- a/packages/server-utils/src/integrations/bullmq/tracer.ts +++ b/packages/server-utils/src/integrations/bullmq/tracer.ts @@ -11,6 +11,7 @@ const PRODUCER_OPERATIONS = new Set(['add', 'addbulk', 'addflow', 'addbulkflows' const CONSUMER_OPERATIONS = new Set(['process']); function getOperation(name: string): string { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `split` always returns at least one item return name.split(' ')[0]!.toLowerCase(); } diff --git a/packages/server-utils/src/integrations/graphql/utils.ts b/packages/server-utils/src/integrations/graphql/utils.ts index fea30e942e72..42400208f1d7 100644 --- a/packages/server-utils/src/integrations/graphql/utils.ts +++ b/packages/server-utils/src/integrations/graphql/utils.ts @@ -125,9 +125,9 @@ function redactGraphqlDocument(document: GraphqlDocumentNode | undefined): strin } let out = body; - // Reverse index loop (not `for...of`) so we splice back-to-front; `i` is bounded by the loop, so - // `ranges[i]` is always present and the `!` just satisfies `noUncheckedIndexedAccess`. + // Reverse index loop (not `for...of`) so we splice back-to-front. for (let i = ranges.length - 1; i >= 0; i--) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop const { start, end, kind } = ranges[i]!; const replacement = kind === 'String' || kind === 'BlockString' ? '"*"' : '*'; out = out.slice(0, start) + replacement + out.slice(end); diff --git a/packages/server-utils/src/integrations/hapi/hapi-utils.ts b/packages/server-utils/src/integrations/hapi/hapi-utils.ts index e5d8f7cd8279..79b343622028 100644 --- a/packages/server-utils/src/integrations/hapi/hapi-utils.ts +++ b/packages/server-utils/src/integrations/hapi/hapi-utils.ts @@ -250,8 +250,8 @@ function wrapExtMethods( pluginName?: string, ): T { if (Array.isArray(method)) { - for (let i = 0; i < method.length; i++) { - method[i] = wrapExtMethods(method[i]!, extPoint); + for (const [i, m] of method.entries()) { + method[i] = wrapExtMethods(m, extPoint); } return method; } else if (isPatchableExtMethod(method)) { @@ -280,8 +280,8 @@ function wrapExtMethods( export function wrapRouteArguments(args: unknown[], pluginName?: string): void { const route = args[0] as PatchableServerRoute | PatchableServerRoute[]; if (Array.isArray(route)) { - for (let i = 0; i < route.length; i++) { - route[i] = wrapRouteHandler(route[i]!, pluginName); + for (const [i, r] of route.entries()) { + route[i] = wrapRouteHandler(r, pluginName); } } else { args[0] = wrapRouteHandler(route, pluginName); @@ -297,8 +297,7 @@ export function wrapRouteArguments(args: unknown[], pluginName?: string): void { export function wrapExtArguments(args: unknown[], pluginName?: string): void { if (Array.isArray(args[0])) { const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[]; - for (let i = 0; i < eventsList.length; i++) { - const eventObj = eventsList[i]!; + for (const [i, eventObj] of eventsList.entries()) { if (isLifecycleExtType(eventObj.type)) { const lifecycleEventObj = eventObj as ServerExtEventsRequestObject; const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName); diff --git a/packages/server-utils/src/integrations/hono/isMiddleware.ts b/packages/server-utils/src/integrations/hono/isMiddleware.ts index ee7ad8d08afa..1675cfcb3930 100644 --- a/packages/server-utils/src/integrations/hono/isMiddleware.ts +++ b/packages/server-utils/src/integrations/hono/isMiddleware.ts @@ -1,7 +1,8 @@ import type { HonoRoute } from './honoTypes'; -// Hono stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers +// Hono 4 stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers // for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper. +// Hono 5 does not wrap them. // See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226 const COMPOSED_HANDLER = '__COMPOSED_HANDLER'; diff --git a/packages/server-utils/src/integrations/hono/middlewareHandlers.ts b/packages/server-utils/src/integrations/hono/middlewareHandlers.ts index 520e11ee9d38..66eb7563f000 100644 --- a/packages/server-utils/src/integrations/hono/middlewareHandlers.ts +++ b/packages/server-utils/src/integrations/hono/middlewareHandlers.ts @@ -23,6 +23,7 @@ import { getMiddlewareFlags } from './isMiddleware'; import { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult'; import { resolveRouteName } from './resolveRouteName'; import { type SentryHonoMiddlewareOptions } from './types'; +import { unwrapThrownValue } from './unwrapThrownValue'; import { CLIENT_ADDRESS, CLIENT_PORT, @@ -148,8 +149,9 @@ export function captureContextError( shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'], ): void { if (context.error) { - if ((shouldHandleError ?? defaultShouldHandleError)(context.error)) { - captureException(context.error, { + const error = unwrapThrownValue(context.error); + if ((shouldHandleError ?? defaultShouldHandleError)(error)) { + captureException(error, { mechanism: { handled: false, type: 'auto.http.hono.context_error' }, }); } diff --git a/packages/server-utils/src/integrations/hono/patchRoute.ts b/packages/server-utils/src/integrations/hono/patchRoute.ts index b63add8f582a..4ec1811ebd96 100644 --- a/packages/server-utils/src/integrations/hono/patchRoute.ts +++ b/packages/server-utils/src/integrations/hono/patchRoute.ts @@ -98,13 +98,17 @@ export function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): Route return handle; } +// Hono 5 registers `onError()` and `notFound()` handlers as `(c, next)` middleware routes with these +// methods. Like on Hono 4, they get no middleware span. +const ERROR_AND_NOT_FOUND_METHODS = new Set(['@ERROR', '@NOT_FOUND']); + /** * Wraps the middleware handlers of a sub-app's routes in spans. */ export function wrapSubAppMiddleware(routes: HonoRoute[]): void { const middlewareFlags = getMiddlewareFlags(routes); for (const [i, route] of routes.entries()) { - if (middlewareFlags[i] && typeof route.handler === 'function') { + if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === 'function') { route.handler = wrapMiddlewareWithSpan(route.handler); } } diff --git a/packages/server-utils/src/integrations/hono/unwrapThrownValue.ts b/packages/server-utils/src/integrations/hono/unwrapThrownValue.ts new file mode 100644 index 000000000000..ebf3203b42e6 --- /dev/null +++ b/packages/server-utils/src/integrations/hono/unwrapThrownValue.ts @@ -0,0 +1,23 @@ +import { isError } from '@sentry/core'; + +/** + * Returns the value that a handler threw, so that `shouldHandleError` and the event get that value + * and not Hono's wrapper. + * + * Hono 5 wraps a thrown non-Error before its error handlers run: + * `new Error(typeof err === 'string' ? err : undefined, { cause: err })`. + * The wrapper has no marker, so it is found by its shape. A user error with the same shape is also unwrapped. + */ +export function unwrapThrownValue(error: unknown): unknown { + if (!isError(error) || error.constructor !== Error || !('cause' in error)) { + return error; + } + + const { cause } = error; + if (isError(cause)) { + return error; + } + + const wrapperMessage = typeof cause === 'string' ? cause : ''; + return error.message === wrapperMessage ? cause : error; +} diff --git a/packages/server-utils/src/integrations/mongodb/mongodb-span.ts b/packages/server-utils/src/integrations/mongodb/mongodb-span.ts index 7c243081295c..8425def8eed1 100644 --- a/packages/server-utils/src/integrations/mongodb/mongodb-span.ts +++ b/packages/server-utils/src/integrations/mongodb/mongodb-span.ts @@ -13,7 +13,7 @@ import { } from '@sentry/conventions/attributes'; import { DB } from '@sentry/conventions/op'; import type { Span, SpanAttributes } from '@sentry/core'; -import { getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core'; +import { getActiveSpan, getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core'; const DB_SYSTEM_VALUE_MONGODB = 'mongodb'; @@ -46,15 +46,11 @@ function scrubStatement(value: unknown): unknown { } if (isCommandObj(value)) { - const initial: Record = {}; - return Object.entries(value) - .map(([key, element]) => [key, scrubStatement(element)]) - .reduce((prev, current) => { - if (isCommandEntry(current)) { - prev[current[0]] = current[1]; - } - return prev; - }, initial); + const scrubbed: Record = {}; + for (const key of Object.keys(value)) { + scrubbed[key] = scrubStatement(value[key]); + } + return scrubbed; } // A value like string or number, possibly contains PII, scrub it. @@ -69,10 +65,6 @@ function isBuffer(value: unknown): boolean { return typeof Buffer !== 'undefined' && Buffer.isBuffer(value); } -function isCommandEntry(value: unknown): value is [string, unknown] { - return Array.isArray(value); -} - /** * Build span attributes for a mongodb v4+ command from the connection * context, namespace and command. @@ -137,7 +129,9 @@ export function getSpanAttributes( } } - if (commandObj) { + // The statement is only sent with a recording span. Skip it otherwise, as the + // serialization walks the whole command, which is expensive for large write payloads. + if (commandObj && getActiveSpan()?.isRecording()) { try { attributes[DB_QUERY_TEXT] = serializeDbStatement(commandObj); } catch { diff --git a/packages/server-utils/src/integrations/pino.ts b/packages/server-utils/src/integrations/pino.ts index b9c2d9750b12..c970fa3fc0c3 100644 --- a/packages/server-utils/src/integrations/pino.ts +++ b/packages/server-utils/src/integrations/pino.ts @@ -1,7 +1,7 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import type { IntegrationFn, LogSeverityLevel } from '@sentry/core'; import { - _INTERNAL_captureLog, + captureLogEvent, addExceptionMechanism, captureException, captureMessage, @@ -147,7 +147,7 @@ const _pinoIntegration = defineIntegration((userOptions: DeepPartial= 0; i--) { + // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop const engineSpan = pendingEngineSpans[i]!; const parentSpan = prismaSpanRegistry.get(engineSpan.parent_span_id); if (!parentSpan) { diff --git a/packages/server-utils/src/integrations/serveTunnel.ts b/packages/server-utils/src/integrations/serveTunnel.ts index 345192b2e3dc..77d462d16656 100644 --- a/packages/server-utils/src/integrations/serveTunnel.ts +++ b/packages/server-utils/src/integrations/serveTunnel.ts @@ -1,8 +1,8 @@ import type { ServerTunnelOptions } from '@sentry/core'; import { defineIntegration } from '@sentry/core'; import { - _INTERNAL_handleServedNodeTunnelRequest as handleServedNodeTunnelRequest, - _INTERNAL_setNodeTunnelHandler as setNodeTunnelHandler, + handleServedNodeTunnelRequest, + setNodeTunnelHandler, HTTP_ON_SERVER_REQUEST, serveTunnelIntegration as coreServeTunnelIntegration, } from '@sentry/core/server'; diff --git a/packages/server-utils/src/integrations/vercel-ai/extract.ts b/packages/server-utils/src/integrations/vercel-ai/extract.ts new file mode 100644 index 000000000000..8e5772e81d34 --- /dev/null +++ b/packages/server-utils/src/integrations/vercel-ai/extract.ts @@ -0,0 +1,112 @@ +/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */ + +import { isObjectLike, stringify } from '@sentry/core'; +import { mapObjectValues } from './util'; + +/** + * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on + * the server and does not show its separator, so this one is our choice. It only makes the recorded text + * easier to read: the answer spans stay correct with any separator, because we add each part's offset. + */ +const EXTRACT_STATE_SEPARATOR = '\n\n'; +const BLOB_SUBSTITUTE = '[Blob substitute]'; + +interface ExtractState { + request: { state?: string; images?: string[]; documents?: string[] }; + /** For each AI SDK state part, the offset of its text in `request.state`, or `'image'` for an image part. */ + parts: (number | 'image' | undefined)[]; +} + +/** + * Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK + * also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the + * offset of each part, so that the answer spans point into the joined `state`. + */ +export function toExtractState(state: unknown): ExtractState { + const images: string[] = []; + const documents: string[] = []; + // Each text gets a separator in front, which is cut off from the start of `state` at the end. + let joined = ''; + + const parts = (Array.isArray(state) ? state : [{ type: 'json', value: state }]).map(part => { + if (!isObjectLike(part)) { + return undefined; + } + if (part.type === 'file') { + if (String(part.mediaType).split('/')[0] === 'image') { + images.push(BLOB_SUBSTITUTE); + return 'image' as const; + } + if (part.mediaType === 'application/pdf') { + documents.push(BLOB_SUBSTITUTE); + } + return undefined; + } + const text = part.type === 'text' ? part.text : stringify(part.value); + if (typeof text !== 'string') { + return undefined; + } + joined += EXTRACT_STATE_SEPARATOR + text; + return joined.length - text.length - EXTRACT_STATE_SEPARATOR.length; + }); + + return { + request: { + state: joined ? joined.slice(EXTRACT_STATE_SEPARATOR.length) : undefined, + images: images.length ? images : undefined, + documents: documents.length ? documents : undefined, + }, + parts, + }; +} + +/** + * The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string. + */ +export function toExtractFields(fields: unknown): unknown { + return isObjectLike(fields) + ? mapObjectValues(fields, field => ({ + ...field, + instructions: field.instructions === null ? undefined : stringify(field.instructions), + })) + : fields; +} + +/** + * The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of + * `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`. + */ +export function toExtractAnswers( + answers: Record, + parts: ExtractState['parts'], +): Record { + return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => { + const mapped: Record = { ...rest, p_null: pNull }; + const span = toExtractSpan(source, parts); + if (span) { + mapped.source = 'input'; + mapped.span = span; + } else if (isObjectLike(source) && parts[Number(source.part)] === 'image') { + mapped.source = 'image'; + } + if (Array.isArray(items)) { + const confidences = items.map(item => (isObjectLike(item) ? item.confidence : undefined)); + if (confidences.every(confidence => typeof confidence === 'number')) { + mapped.confidences = confidences; + } + const spans = items.map(item => toExtractSpan(isObjectLike(item) ? item.source : undefined, parts)); + if (spans.some(Boolean)) { + mapped.spans = spans; + } + } + return mapped; + }); +} + +function toExtractSpan(source: unknown, parts: ExtractState['parts']): [number, number] | null { + if (!isObjectLike(source) || source.type !== 'text') { + return null; + } + const offset = parts[Number(source.part)]; + return typeof offset === 'number' ? [offset + Number(source.start), offset + Number(source.end)] : null; +} diff --git a/packages/server-utils/src/integrations/vercel-ai/util.ts b/packages/server-utils/src/integrations/vercel-ai/util.ts index 7a9437b21293..1a70c5d1d771 100644 --- a/packages/server-utils/src/integrations/vercel-ai/util.ts +++ b/packages/server-utils/src/integrations/vercel-ai/util.ts @@ -190,3 +190,13 @@ function accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string return undefined; } } + +/** Maps each object value of `record` and keeps the other values as they are. */ +export function mapObjectValues( + record: Record, + fn: (value: Record, key: string) => unknown, +): Record { + return Object.fromEntries( + Object.entries(record).map(([key, value]) => [key, isObjectLike(value) ? fn(value, key) : value]), + ); +} diff --git a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts index 5ec78e4e7e03..fc710a939650 100644 --- a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts +++ b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts @@ -34,6 +34,7 @@ import { GEN_AI_DECIDE, GEN_AI_EMBEDDINGS, GEN_AI_EXECUTE_TOOL, + GEN_AI_EXTRACT, GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT, GEN_AI_RERANK, @@ -71,7 +72,16 @@ import { import { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai'; import { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants'; import { bindTracingChannelToSpan } from '../../tracing-channel'; -import { asNumber, asString, isReadableStream, type StreamedModelCallResult, sum, tapModelCallStream } from './util'; +import { toExtractAnswers, toExtractFields, toExtractState } from './extract'; +import { + asNumber, + asString, + isReadableStream, + mapObjectValues, + type StreamedModelCallResult, + sum, + tapModelCallStream, +} from './util'; /** * The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to @@ -90,6 +100,7 @@ const GEN_AI_OPERATION_SPAN_OPS = { // oxlint-disable-next-line typescript/no-deprecated rerank: GEN_AI_RERANK, decide: GEN_AI_DECIDE, + extract: GEN_AI_EXTRACT, invoke_agent: GEN_AI_INVOKE_AGENT, execute_tool: GEN_AI_EXECUTE_TOOL, // The model-call op matches the Vercel AI OTel integration (`gen_ai.generate_content`) rather than @@ -282,7 +293,8 @@ export type ChannelEventType = | 'embedMany' | 'rerank' | 'experimental_evaluate' - | 'experimental_decide'; + | 'experimental_decide' + | 'experimental_extract'; /** * The context object the AI SDK passes through one tracing-channel call. It is the same object @@ -606,6 +618,21 @@ function startSpanFromEvent( } : {}), }); + case 'experimental_extract': + return startGenAiSpan('extract', modelId, { + ...baseAttributes, + ...(recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields)) + ? { + [GEN_AI_INPUT_MESSAGES]: stringify([ + { + ...toExtractState(event.state).request, + fields: toExtractFields(event.fields), + reference_date: event.referenceDate, + }, + ]), + } + : {}), + }); default: // Unknown event type: opt out rather than open a span we can't shape correctly. return undefined; @@ -808,7 +835,7 @@ export function enrichSpanOnEnd(span: Span, data: VercelAiChannelMessage): void span.setAttributes(providerAttributes); if (recordOutputs) { - const outputMessages = getOutputMessages(type, result, finishReason); + const outputMessages = getOutputMessages(type, result, finishReason, data.event); if (outputMessages) { span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages); } @@ -819,10 +846,16 @@ function getOutputMessages( type: ChannelEventType, result: Record, finishReason: string | undefined, + event: Record, ): string | undefined { if (type === 'experimental_evaluate' || type === 'experimental_decide') { return getEvaluationOutputMessages(withProviderAnswerFields(result)); } + if (type === 'experimental_extract') { + return isObjectLike(result.answers) + ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }]) + : undefined; + } // `languageModelCall` exposes the response as a `content` parts array; top-level results expose // `text` + `toolCalls`. Both normalize into the OTel `gen_ai.output.messages` assistant message. const parts = @@ -850,20 +883,15 @@ function withProviderAnswerFields(result: Record): unknown { return answers; } - return Object.fromEntries( - Object.entries(answers).map(([id, answer]) => { - if (!isObjectLike(answer)) { - return [id, answer]; - } - const openrouterAnswer = openrouterById?.[id]; - const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {}; - const { - confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence), - legend = isObjectLike(fields.legend) ? fields.legend : undefined, - } = answer; - return [id, { ...answer, confidence, legend }]; - }), - ); + return mapObjectValues(answers, (answer, id) => { + const openrouterAnswer = openrouterById?.[id]; + const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {}; + const { + confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence), + legend = isObjectLike(fields.legend) ? fields.legend : undefined, + } = answer; + return { ...answer, confidence, legend }; + }); } /** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */ diff --git a/packages/server-utils/src/integrations/winston.ts b/packages/server-utils/src/integrations/winston.ts index ff4c1310a381..f0d18f81b56f 100644 --- a/packages/server-utils/src/integrations/winston.ts +++ b/packages/server-utils/src/integrations/winston.ts @@ -1,7 +1,7 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; /* eslint-disable @typescript-eslint/ban-ts-comment */ import type { LogSeverityLevel } from '@sentry/core'; -import { _INTERNAL_captureLog, debug, isObjectLike } from '@sentry/core'; +import { captureLogEvent, debug, isObjectLike } from '@sentry/core'; import { DEBUG_BUILD } from '../debug-build'; const DEFAULT_CAPTURED_LEVELS: Array = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']; @@ -107,7 +107,7 @@ export function createSentryWinstonTransport=4.0.0 <5', filePath: /^dist\/(?:cjs\/)?context\.js$/ }, + module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\/(?:cjs\/)?context\.js$/ }, functionQuery: { className: 'Context' }, }, { // `app.request(...)` — Hono's internal dispatch for sub-app-to-sub-app fetches. A class-field // arrow, hence `astQuery` instead of `methodName`. channelName: 'request', - module: { name: 'hono', versionRange: '>=4.0.0 <5', filePath: /^dist\/(?:cjs\/)?hono-base\.js$/ }, + module: { name: 'hono', versionRange: '>=4.0.0 <6', filePath: /^dist\/(?:cjs\/)?hono-base\.js$/ }, astQuery: "PropertyDefinition[key.name='request'] > ArrowFunctionExpression", functionQuery: { kind: 'Auto' }, }, diff --git a/packages/server-utils/src/utils/installedModules.ts b/packages/server-utils/src/utils/installedModules.ts new file mode 100644 index 000000000000..4095c96f1428 --- /dev/null +++ b/packages/server-utils/src/utils/installedModules.ts @@ -0,0 +1,142 @@ +type ModuleInfo = Record; +interface PackageJson { + name?: string; + version?: string; + dependencies?: ModuleInfo; + devDependencies?: ModuleInfo; +} + +const NODE_MODULES = '/node_modules/'; + +/** + * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact + * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise. + */ +export function collectInstalledModules({ + readFile, + entryPath, + cwd, + loadedFiles = [], +}: { + readFile: (path: string) => string | undefined; + entryPath?: string; + cwd?: string; + /** + * Paths of files the process has already loaded, such as the keys of the CommonJS module cache. Packages these files + * belong to are added too, which covers transitive dependencies that are not in `package.json`. + */ + loadedFiles?: string[]; +}): ModuleInfo { + const read = (dir: string): PackageJson | undefined => { + try { + return JSON.parse(readFile(join(dir, 'package.json')) || 'null') || undefined; + } catch { + return undefined; + } + }; + + const entryDir = entryPath && dirname(toPosix(entryPath)); + const cwdDir = cwd && toPosix(cwd); + // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime. + const appRoot = findAppRoot( + read, + entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir], + ); + + const resolveFrom = + entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir) + ? entryDir + : appRoot || entryDir || cwdDir; + const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : []; + const resolve = (name: string): string | undefined => { + for (const dir of nodeModulesDirs) { + const version = read(join(dir, name))?.version; + if (version) { + return version; + } + } + return undefined; + }; + + const pkg = appRoot ? read(appRoot) : undefined; + const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies }; + const installed: ModuleInfo = {}; + const seen = new Set(); + + for (const file of loadedFiles) { + const path = toPosix(file); + const start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length; + const [first = '', second] = path.slice(start).split('/'); + const name = first.startsWith('@') ? `${first}/${second}` : first; + const dir = path.slice(0, start) + name; + if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) { + continue; + } + seen.add(dir); + const version = read(dir)?.version; + if (version && installed[name] !== version) { + // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves. + installed[name] = (name in installed && resolve(name)) || installed[name] || version; + } + } + + for (const name of Object.keys(declared)) { + const version = resolve(name); + if (version) { + installed[name] = version; + } + } + + return { ...declared, ...installed }; +} + +/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */ +function findAppRoot( + read: (dir: string) => PackageJson | undefined, + startDirs: Array, +): string | undefined { + for (const startDir of startDirs) { + const root = + startDir && !inNodeModules(startDir) + ? ancestors(startDir).find(dir => { + const pkg = read(dir); + return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies); + }) + : undefined; + if (root) { + return root; + } + } + return undefined; +} + +function inNodeModules(dir: string): boolean { + return `${dir}/`.includes(NODE_MODULES); +} + +/** `dir` and its parents, up to the root. */ +function ancestors(dir: string): string[] { + const dirs = [dir]; + for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) { + dirs.push(parent); + } + return dirs; +} + +// Minimal POSIX helpers: all paths are converted with `toPosix` first. +function dirname(path: string): string { + const index = path.lastIndexOf('/'); + return index > 0 ? path.slice(0, index) : index === 0 ? '/' : path; +} + +function join(dir: string, name: string): string { + return dir.endsWith('/') ? dir + name : `${dir}/${name}`; +} + +function isIn(path: string, dir: string): boolean { + return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`); +} + +function toPosix(path: string): string { + return path.replace(/\\/g, '/'); +} diff --git a/packages/node/src/utils/module.ts b/packages/server-utils/src/utils/module.ts similarity index 100% rename from packages/node/src/utils/module.ts rename to packages/server-utils/src/utils/module.ts diff --git a/packages/server-utils/src/utils/serverTimingTraceHeader.ts b/packages/server-utils/src/utils/serverTimingTraceHeader.ts new file mode 100644 index 000000000000..fc970f9c162f --- /dev/null +++ b/packages/server-utils/src/utils/serverTimingTraceHeader.ts @@ -0,0 +1,63 @@ +import type { Client } from '@sentry/core'; +import { debug, getTraceServerTimingHeader, isSharedCacheable } from '@sentry/core'; +import { DEBUG_BUILD } from '../debug-build'; + +const SERVER_TIMING_HEADER = 'server-timing'; + +const enabledClients = new WeakSet(); + +/** + * Sends the trace of the request in a `Server-Timing` header of the document responses that + * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The + * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request` + * handlers. Framework SDKs turn it on; it is off by default. + */ +export function addServerTimingTraceHeader(client: Client): void { + enabledClients.add(client); +} + +/** + * Adds the trace of the current context to the `Server-Timing` header of a document response that + * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling + * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of + * the app is left alone. + * + * A `fetch` response has immutable headers, so it is copied then. + */ +export function withServerTimingTraceHeader(client: Client, response: R): R { + if (!response || !enabledClients.has(client)) { + return response; + } + + try { + const headers = response.headers; + const getHeader = (name: string): string | undefined => headers.get(name) ?? undefined; + if (!getHeader('content-type')?.toLowerCase().startsWith('text/html') || isSharedCacheable(getHeader)) { + return response; + } + + const existingValue = getHeader(SERVER_TIMING_HEADER); + if (existingValue?.includes('sentry-trace')) { + return response; + } + + const traceHeader = getTraceServerTimingHeader(); + if (!traceHeader) { + return response; + } + + const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader; + try { + headers.set(SERVER_TIMING_HEADER, value); + return response; + } catch { + // Passing the original response as the init keeps its status, status text and headers. + const copy = new Response(response.body, response); + copy.headers.set(SERVER_TIMING_HEADER, value); + return copy as R; + } + } catch (e) { + DEBUG_BUILD && debug.warn('Failed to add the trace to the Server-Timing header', e); + return response; + } +} diff --git a/packages/server-utils/src/utils/sql.ts b/packages/server-utils/src/utils/sql.ts index 77f86d79ae3b..632e2b94f3e6 100644 --- a/packages/server-utils/src/utils/sql.ts +++ b/packages/server-utils/src/utils/sql.ts @@ -157,8 +157,9 @@ function extractTableNames(sql: string): string[] { let match: RegExpExecArray | null; while ((match = TOKEN_RE.exec(sql)) !== null) { - if (match[1] || match[2]) { - tables.push((match[1] || match[2])!); + const table = match[1] || match[2]; + if (table) { + tables.push(table); continue; } @@ -336,7 +337,7 @@ function stripLiteralsAndComments(sql: string, dialect: SqlDialect | SqlLexerRul let i = 0; while (i < sql.length) { - const char = sql[i]!; + const char = sql.charAt(i); const next = sql[i + 1]; if ((char === '-' && next === '-') || ((isMysql || rules.hashComments) && char === '#')) { diff --git a/packages/server-utils/src/utils/tunnelServer.ts b/packages/server-utils/src/utils/tunnelServer.ts index 6cda5779396f..2aaacc4513f0 100644 --- a/packages/server-utils/src/utils/tunnelServer.ts +++ b/packages/server-utils/src/utils/tunnelServer.ts @@ -1,8 +1,5 @@ import { debug } from '@sentry/core'; -import { - _INTERNAL_handleServedNodeTunnelRequest as handleServedNodeTunnelRequest, - _INTERNAL_httpServerHandlesTunnel as httpServerHandlesTunnel, -} from '@sentry/core/server'; +import { handleServedNodeTunnelRequest, httpServerHandlesTunnel } from '@sentry/core/server'; import { DEBUG_BUILD } from '../debug-build'; type TunnelServer = { emit(event: string, ...data: unknown[]): boolean }; diff --git a/packages/server-utils/src/utils/wrapServerRequestHandler.ts b/packages/server-utils/src/utils/wrapServerRequestHandler.ts index 3afe35e55b7e..f234324f9be3 100644 --- a/packages/server-utils/src/utils/wrapServerRequestHandler.ts +++ b/packages/server-utils/src/utils/wrapServerRequestHandler.ts @@ -32,7 +32,7 @@ import { } from '@sentry/core'; import type { ServerRequestOptions } from '@sentry/core/server'; import { - _INTERNAL_isServedTunnelRequest as isServedTunnelRequest, + isServedTunnelRequest, classifyResponseStreaming, getClientIPAddress, isStaticAssetRequest, @@ -40,6 +40,7 @@ import { } from '@sentry/core/server'; import { DEBUG_BUILD } from '../debug-build'; import { monitorStream } from './monitorStream'; +import { withServerTimingTraceHeader } from './serverTimingTraceHeader'; export interface ServerRequestHandlerConfig { request: Request; @@ -185,7 +186,7 @@ export async function wrapServerRequestHandler { expect(getConversationIdMetadataFromConfig({})).toEqual({}); }); }); + +describe('extractLlmResponseAttributes finish reasons', () => { + it('reads the finish reason from message response_metadata for the OpenAI Responses API', () => { + const result = { + generations: [ + [ + { + text: 'hi', + message: { response_metadata: { finish_reason: 'completed', normalized_finish_reason: 'stop' } }, + }, + ], + ], + }; + + expect(extractLlmResponseAttributes(result, false)).toMatchObject({ + [GEN_AI_RESPONSE_FINISH_REASONS]: '["completed"]', + }); + }); + + it('prefers generationInfo over message response_metadata', () => { + const result = { + generations: [ + [ + { + text: 'hi', + generationInfo: { finish_reason: 'stop' }, + message: { response_metadata: { finish_reason: 'other' } }, + }, + ], + ], + }; + + expect(extractLlmResponseAttributes(result, false)).toMatchObject({ + [GEN_AI_RESPONSE_FINISH_REASONS]: '["stop"]', + }); + }); +}); diff --git a/packages/server-utils/test/integrations/hono/captureContextError.test.ts b/packages/server-utils/test/integrations/hono/captureContextError.test.ts new file mode 100644 index 000000000000..754255060c9e --- /dev/null +++ b/packages/server-utils/test/integrations/hono/captureContextError.test.ts @@ -0,0 +1,47 @@ +import * as SentryCore from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { captureContextError } from '../../../src/integrations/hono/middlewareHandlers'; + +// oxlint-disable-next-line typescript/no-explicit-any +const contextWithError = (error: unknown): any => ({ req: {}, error }); + +describe('captureContextError', () => { + let captureExceptionSpy: ReturnType; + + beforeEach(() => { + captureExceptionSpy = vi.spyOn(SentryCore, 'captureException').mockReturnValue('event-id'); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('captures the value inside the Hono 5 non-Error wrapper with the context error mechanism', () => { + const thrown = { code: 'ECONNRESET', retryable: true }; + + captureContextError(contextWithError(new Error(undefined, { cause: thrown }))); + + expect(captureExceptionSpy).toHaveBeenCalledTimes(1); + expect(captureExceptionSpy).toHaveBeenCalledWith(thrown, { + mechanism: { handled: false, type: 'auto.http.hono.context_error' }, + }); + }); + + it('gives the unwrapped value to shouldHandleError', () => { + const shouldHandleError = vi.fn(() => false); + + captureContextError( + contextWithError(new Error('Payment provider timed out', { cause: 'Payment provider timed out' })), + shouldHandleError, + ); + + expect(shouldHandleError).toHaveBeenCalledWith('Payment provider timed out'); + expect(captureExceptionSpy).not.toHaveBeenCalled(); + }); + + it('does not capture a wrapped object with a 4xx status', () => { + captureContextError(contextWithError(new Error(undefined, { cause: { status: 404, reason: 'Order not found' } }))); + + expect(captureExceptionSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/server-utils/test/integrations/hono/unwrapThrownValue.test.ts b/packages/server-utils/test/integrations/hono/unwrapThrownValue.test.ts new file mode 100644 index 000000000000..6f5efd7c96dd --- /dev/null +++ b/packages/server-utils/test/integrations/hono/unwrapThrownValue.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; +import { unwrapThrownValue } from '../../../src/integrations/hono/unwrapThrownValue'; + +// A copy of the wrapper that Hono 5 makes for a thrown non-Error. +const toError = (err: unknown): Error => + err instanceof Error ? err : new Error(typeof err === 'string' ? err : undefined, { cause: err }); + +describe('unwrapThrownValue', () => { + describe('unwraps the Hono 5 non-Error wrapper', () => { + it('returns a thrown string', () => { + expect(unwrapThrownValue(toError('Payment provider timed out'))).toBe('Payment provider timed out'); + }); + + it('returns a thrown plain object', () => { + const thrown = { code: 'ECONNRESET', retryable: true }; + + expect(unwrapThrownValue(toError(thrown))).toBe(thrown); + }); + + it.each([{ thrown: undefined }, { thrown: null }, { thrown: 0 }, { thrown: false }, { thrown: '' }])( + 'returns a thrown falsy value $thrown', + ({ thrown }) => { + expect(unwrapThrownValue(toError(thrown))).toBe(thrown); + }, + ); + }); + + describe('does not unwrap other errors', () => { + it('returns an Error with no cause', () => { + const error = new Error('Payment provider timed out'); + + expect(unwrapThrownValue(error)).toBe(error); + }); + + it('returns an Error with no message and no cause', () => { + const error = new Error(); + + expect(unwrapThrownValue(error)).toBe(error); + }); + + it.each([ + { message: 'Checkout failed', error: new Error('Checkout failed', { cause: new Error('Card declined') }) }, + { message: 'no', error: new Error(undefined, { cause: new Error('Card declined') }) }, + ])('returns an Error whose cause is an Error ($message message)', ({ error }) => { + expect(unwrapThrownValue(error)).toBe(error); + }); + + it('returns an Error subclass with a non-Error cause', () => { + class CheckoutError extends Error {} + const error = new CheckoutError('', { cause: { code: 'ECONNRESET' } }); + + expect(unwrapThrownValue(error)).toBe(error); + }); + + it.each([ + { cause: 'a string', error: new Error('Checkout failed', { cause: 'Card declined' }) }, + { cause: 'an object', error: new Error('Checkout failed', { cause: { code: 'ECONNRESET' } }) }, + ])('returns an Error whose message does not match its cause ($cause)', ({ error }) => { + expect(unwrapThrownValue(error)).toBe(error); + }); + + it('returns a value that is not an Error', () => { + expect(unwrapThrownValue('Payment provider timed out')).toBe('Payment provider timed out'); + }); + }); +}); diff --git a/packages/server-utils/test/integrations/mongodb.test.ts b/packages/server-utils/test/integrations/mongodb.test.ts new file mode 100644 index 000000000000..d604058bd367 --- /dev/null +++ b/packages/server-utils/test/integrations/mongodb.test.ts @@ -0,0 +1,74 @@ +import { DB_QUERY_TEXT } from '@sentry/conventions/attributes'; +import { getCurrentScope, setCurrentClient, startSpan } from '@sentry/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { getV3SpanAttributes, getV4SpanAttributes } from '../../src/integrations/mongodb/mongodb-span'; +import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; + +const ORIGIN = 'auto.db.mongo'; +const NAMESPACE = { db: 'app', collection: 'users' }; +const CONNECTION = { address: 'localhost:27017' }; +const UPDATE_COMMAND = { + update: 'users', + updates: [{ q: { _id: 'abc' }, u: { $set: { profile: { name: 'Jane', tags: ['a', 'b'] } } } }], +}; +const SCRUBBED_UPDATE_COMMAND = + '{"update":"?","updates":[{"q":{"_id":"?"},"u":{"$set":{"profile":{"name":"?","tags":["?","?"]}}}}]}'; + +function initClient(tracesSampleRate: number | undefined): void { + const client = new TestClient(getDefaultTestClientOptions({ dsn: 'https://key@sentry.io/1', tracesSampleRate })); + setCurrentClient(client); + client.init(); +} + +describe('mongodb span attributes', () => { + afterEach(() => { + getCurrentScope().setClient(undefined); + }); + + it('adds the scrubbed statement when the parent span is sampled', () => { + initClient(1.0); + + const attributes = startSpan({ name: 'parent' }, () => + getV4SpanAttributes(CONNECTION, NAMESPACE, UPDATE_COMMAND, 'update', ORIGIN), + ); + + expect(attributes[DB_QUERY_TEXT]).toBe(SCRUBBED_UPDATE_COMMAND); + }); + + it('adds the scrubbed statement for a v3 command when the parent span is sampled', () => { + initClient(1.0); + + const attributes = startSpan({ name: 'parent' }, () => + getV3SpanAttributes( + 'app.users', + undefined, + { q: { _id: 'abc' }, u: { $set: { name: 'Jane' } } }, + 'update', + ORIGIN, + ), + ); + + expect(attributes[DB_QUERY_TEXT]).toBe('{"_id":"?"}'); + }); + + it('does not serialize the command when there is no parent span', () => { + initClient(1.0); + + const attributes = getV4SpanAttributes(CONNECTION, NAMESPACE, UPDATE_COMMAND, 'update', ORIGIN); + + expect(attributes).not.toHaveProperty(DB_QUERY_TEXT); + }); + + it.each([ + ['tracesSampleRate is 0', 0], + ['tracesSampleRate is not set', undefined], + ])('does not serialize the command when %s', (_, tracesSampleRate) => { + initClient(tracesSampleRate); + + const attributes = startSpan({ name: 'parent' }, () => + getV4SpanAttributes(CONNECTION, NAMESPACE, UPDATE_COMMAND, 'update', ORIGIN), + ); + + expect(attributes).not.toHaveProperty(DB_QUERY_TEXT); + }); +}); diff --git a/packages/server-utils/test/integrations/vercel-ai/extract.test.ts b/packages/server-utils/test/integrations/vercel-ai/extract.test.ts new file mode 100644 index 000000000000..534d8c107b1e --- /dev/null +++ b/packages/server-utils/test/integrations/vercel-ai/extract.test.ts @@ -0,0 +1,210 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + GEN_AI_INPUT_MESSAGES, + GEN_AI_OPERATION_NAME, + GEN_AI_OUTPUT_MESSAGES, + GEN_AI_PROVIDER_NAME, + GEN_AI_REQUEST_MODEL, + GEN_AI_RESPONSE_MODEL, + GEN_AI_USAGE_INPUT_TOKENS, + GEN_AI_USAGE_OUTPUT_TOKENS, + GEN_AI_USAGE_TOTAL_TOKENS, + SENTRY_OP, + SENTRY_ORIGIN, + SENTRY_SEGMENT_NAME_SOURCE, +} from '@sentry/conventions/attributes'; +import { GEN_AI_EXTRACT } from '@sentry/conventions/op'; +import { + getMainCarrier, + SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, + setCurrentClient, + spanToStaticSpanJSON, +} from '@sentry/core'; +import type { Span } from '@sentry/core'; +import { createSpanFromMessage, enrichSpanOnEnd } from '../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber'; +import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; + +type Message = Parameters[0]; + +const fields = { invoiceNumber: { type: 'text', instructions: 'The invoice number' } }; +const answers = { invoiceNumber: { type: 'text', value: 'INV-2291', confidence: 0.98 } }; + +describe('Vercel AI extract spans', () => { + let endedSpans: Span[]; + + beforeEach(() => { + getMainCarrier().__SENTRY__ = undefined; + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + }), + ); + setCurrentClient(client); + client.init(); + endedSpans = []; + client.on('spanEnd', span => endedSpans.push(span)); + }); + + afterEach(() => { + getMainCarrier().__SENTRY__ = undefined; + }); + + function runExtract(event: Message['event'], result: Message['result']): ReturnType { + const message = { type: 'experimental_extract', event, result } satisfies Message; + const span = createSpanFromMessage(message, {} as Parameters[1])!; + enrichSpanOnEnd(span, message); + span.end(); + return spanToStaticSpanJSON(endedSpans[0]!); + } + + it('creates an extract span with inputs, outputs and usage', () => { + const json = runExtract( + { + provider: 'gateway', + modelId: 'cloudflare/clairic', + state: 'Invoice INV-2291 from Northwind Supply', + fields, + referenceDate: '2026-01-15', + recordInputs: true, + recordOutputs: true, + }, + { + answers, + usage: { inputTokens: 50, outputTokens: 4, totalTokens: 54 }, + response: { modelId: 'clairic' }, + }, + ); + + expect(json.description).toBe('extract cloudflare/clairic'); + expect(json.op).toBe(GEN_AI_EXTRACT); + expect(json.data).toEqual({ + [SENTRY_ORIGIN]: 'auto.ai.vercelai', + [SENTRY_OP]: GEN_AI_EXTRACT, + [SENTRY_SEGMENT_NAME_SOURCE]: 'custom', + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: 1, + [GEN_AI_OPERATION_NAME]: 'extract', + [GEN_AI_PROVIDER_NAME]: 'gateway', + 'vercel.ai.model.provider': 'gateway', + [GEN_AI_REQUEST_MODEL]: 'cloudflare/clairic', + [GEN_AI_INPUT_MESSAGES]: JSON.stringify([ + { state: 'Invoice INV-2291 from Northwind Supply', fields, reference_date: '2026-01-15' }, + ]), + [GEN_AI_USAGE_INPUT_TOKENS]: 50, + [GEN_AI_USAGE_OUTPUT_TOKENS]: 4, + [GEN_AI_USAGE_TOTAL_TOKENS]: 54, + [GEN_AI_RESPONSE_MODEL]: 'clairic', + [GEN_AI_OUTPUT_MESSAGES]: JSON.stringify([{ answers }]), + }); + }); + + it('maps a multi-part state and its answers to the provider shape', () => { + const json = runExtract( + { + provider: 'gateway', + modelId: 'cloudflare/clairic', + state: [ + { type: 'text', text: 'Total: $1,080.' }, + { type: 'file', mediaType: 'image', data: new Uint8Array([1, 2, 3]) }, + { type: 'text', text: 'Ship to Oslo, Bergen.' }, + { type: 'file', mediaType: 'application/pdf', data: new Uint8Array([4, 5, 6]) }, + ], + fields, + recordInputs: true, + recordOutputs: true, + }, + { + answers: { + city: { type: 'text', value: 'Oslo', pNull: 0.01, source: { type: 'text', part: 2, start: 8, end: 12 } }, + cities: { + type: 'list', + value: ['Oslo', 'Bergen'], + items: [ + { confidence: 0.9, source: { type: 'text', part: 2, start: 8, end: 12 } }, + { confidence: 0.8, source: { type: 'file', part: 1 } }, + ], + }, + logo: { type: 'text', value: 'Northwind', source: { type: 'file', part: 1 } }, + }, + }, + ); + + expect(json.data?.[GEN_AI_INPUT_MESSAGES]).toBe( + JSON.stringify([ + { + state: 'Total: $1,080.\n\nShip to Oslo, Bergen.', + images: ['[Blob substitute]'], + documents: ['[Blob substitute]'], + fields, + }, + ]), + ); + expect(json.data?.[GEN_AI_OUTPUT_MESSAGES]).toBe( + JSON.stringify([ + { + answers: { + city: { type: 'text', value: 'Oslo', p_null: 0.01, source: 'input', span: [24, 28] }, + cities: { type: 'list', value: ['Oslo', 'Bergen'], confidences: [0.9, 0.8], spans: [[24, 28], null] }, + logo: { type: 'text', value: 'Northwind', source: 'image' }, + }, + }, + ]), + ); + }); + + it('records non-string field instructions as a string', () => { + const json = runExtract( + { + provider: 'gateway', + modelId: 'cloudflare/clairic', + state: 'Invoice INV-2291', + fields: { + invoiceNumber: { type: 'text', instructions: { hint: 'starts with INV' } }, + total: { type: 'number', instructions: null }, + }, + recordInputs: true, + }, + undefined, + ); + + expect(json.data?.[GEN_AI_INPUT_MESSAGES]).toBe( + JSON.stringify([ + { + state: 'Invoice INV-2291', + fields: { + invoiceNumber: { type: 'text', instructions: '{"hint":"starts with INV"}' }, + total: { type: 'number' }, + }, + }, + ]), + ); + }); + + it('does not record inputs or outputs when recording is off', () => { + const json = runExtract( + { + provider: 'gateway', + modelId: 'cloudflare/clairic', + state: 'Invoice INV-2291 from Northwind Supply', + fields, + recordInputs: false, + recordOutputs: false, + }, + { answers }, + ); + + expect(json.op).toBe(GEN_AI_EXTRACT); + expect(json.data?.[GEN_AI_INPUT_MESSAGES]).toBeUndefined(); + expect(json.data?.[GEN_AI_OUTPUT_MESSAGES]).toBeUndefined(); + }); + + // `ai` >= 7.0.163 replaces the inputs with empty values when `recordInputs` is false. + it('does not record stripped inputs', () => { + const json = runExtract( + { provider: 'gateway', modelId: 'cloudflare/clairic', state: '', fields: {}, recordInputs: true }, + undefined, + ); + + expect(json.data?.[GEN_AI_INPUT_MESSAGES]).toBeUndefined(); + }); +}); diff --git a/packages/server-utils/test/orchestrion/hono.test.ts b/packages/server-utils/test/orchestrion/hono.test.ts new file mode 100644 index 000000000000..6c1ffaaec90e --- /dev/null +++ b/packages/server-utils/test/orchestrion/hono.test.ts @@ -0,0 +1,42 @@ +import { createCodeTransformer } from '@apm-js-collab/code-transformer-bundler-plugins/core'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { honoConfig } from '../../src/orchestrion/config/hono'; + +const CONTEXT_CODE = 'export class Context { constructor(req) { this.req = req; } }\n'; +const HONO_BASE_CODE = 'export class Hono { request = (input) => input; }\n'; + +// The orchestrion matcher (`semifies`) and node-semver differ on prereleases: only `semifies` accepts +// `5.0.0-rc.1` in `>=4.0.0 <6`. This test fails if the matcher changes that. +describe('hono orchestrion config versionRange', () => { + const transformer = createCodeTransformer({ instrumentations: honoConfig }); + let root: string; + + // The code transformer reads the version from the `package.json` on disk. + const transformHono = (version: string, file: string, code: string): ReturnType => { + const dir = join(root, version, 'node_modules', 'hono'); + mkdirSync(join(dir, 'dist'), { recursive: true }); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'hono', version, type: 'module' })); + return transformer.transform(code, join(dir, file)); + }; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'orch-hono-')); + }); + + afterAll(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it.each(['4.0.0', '4.13.13', '5.0.0-rc.0', '5.0.0-rc.1', '5.0.0'])('instruments hono %s', version => { + expect(transformHono(version, 'dist/context.js', CONTEXT_CODE)?.code).toContain('orchestrion:hono:context'); + expect(transformHono(version, 'dist/hono-base.js', HONO_BASE_CODE)?.code).toContain('orchestrion:hono:request'); + }); + + it.each(['3.12.12', '6.0.0-rc.0', '6.0.0'])('does not instrument hono %s', version => { + expect(transformHono(version, 'dist/context.js', CONTEXT_CODE)).toBeNull(); + expect(transformHono(version, 'dist/hono-base.js', HONO_BASE_CODE)).toBeNull(); + }); +}); diff --git a/packages/server-utils/test/utils/installedModules.test.ts b/packages/server-utils/test/utils/installedModules.test.ts new file mode 100644 index 000000000000..d487abc0bfea --- /dev/null +++ b/packages/server-utils/test/utils/installedModules.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest'; +import { collectInstalledModules } from '../../src/utils/installedModules'; + +function makeFs(files: Record): (path: string) => string | undefined { + return path => { + const content = files[path]; + if (content === undefined) { + return undefined; + } + return typeof content === 'string' ? content : JSON.stringify(content); + }; +} + +describe('collectInstalledModules', () => { + it('resolves declared dependencies to their installed versions and keeps the range of the rest', () => { + const readFile = makeFs({ + '/app/package.json': { + name: 'app', + dependencies: { express: '^4.0.0', '@scope/lib': '^2.0.0' }, + devDependencies: { vitest: '^3.0.0' }, + }, + '/app/node_modules/express/package.json': { name: 'express', version: '4.21.2' }, + '/app/node_modules/@scope/lib/package.json': { name: '@scope/lib', version: '2.3.4' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' })).toEqual({ + express: '4.21.2', + '@scope/lib': '2.3.4', + vitest: '^3.0.0', + }); + }); + + it('resolves packages hoisted to a monorepo root', () => { + const readFile = makeFs({ + '/repo/package.json': { name: 'repo', devDependencies: { turbo: '^2.0.0' } }, + '/repo/apps/api/package.json': { name: 'api', dependencies: { hono: '^4.0.0' } }, + '/repo/node_modules/hono/package.json': { version: '4.6.0' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/repo/apps/api/dist/server.mjs', cwd: '/repo' })).toEqual({ + hono: '4.6.0', + }); + }); + + it('skips package.json files that only configure a build output folder', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: { koa: '^2.0.0' } }, + '/app/dist/package.json': { type: 'module' }, + '/app/node_modules/koa/package.json': { version: '2.15.3' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/app/dist/index.js' })).toEqual({ koa: '2.15.3' }); + }); + + it('uses cwd when the entry file is inside node_modules', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: { next: '^15.0.0', react: '^19.0.0' } }, + '/app/node_modules/next/package.json': { name: 'next', version: '15.1.0' }, + '/app/node_modules/react/package.json': { name: 'react', version: '19.1.0' }, + '/app/node_modules/next/node_modules/react/package.json': { name: 'react', version: '18.3.1' }, + }); + + expect( + collectInstalledModules({ readFile, entryPath: '/app/node_modules/next/dist/bin/next', cwd: '/app' }), + ).toEqual({ next: '15.1.0', react: '19.1.0' }); + }); + + it('prefers cwd when the entry file is outside of it', () => { + const readFile = makeFs({ + '/var/runtime/package.json': { name: 'lambda-runtime', dependencies: { 'aws-sdk': '^2.0.0' } }, + '/var/task/package.json': { name: 'app', dependencies: { pg: '^8.0.0' } }, + '/var/task/node_modules/pg/package.json': { version: '8.13.1' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/var/runtime/index.mjs', cwd: '/var/task' })).toEqual({ + pg: '8.13.1', + }); + }); + + it('uses the entry file when cwd has no package.json', () => { + const readFile = makeFs({ + '/srv/app/package.json': { name: 'app', dependencies: { pg: '^8.0.0' } }, + '/srv/app/node_modules/pg/package.json': { version: '8.13.1' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: '/srv/app/index.js', cwd: '/' })).toEqual({ + pg: '8.13.1', + }); + }); + + it('adds loaded packages from node_modules, including pnpm and Bun stores, and ignores other files', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app', dependencies: {} }, + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/package.json': { version: '4.3.7' }, + '/app/node_modules/.bun/@scope+pkg@1.0.0/node_modules/@scope/pkg/package.json': { version: '1.0.0' }, + '/usr/lib/node_modules/pm2/package.json': { version: '5.0.0' }, + }); + + expect( + collectInstalledModules({ + readFile, + entryPath: '/app/index.js', + loadedFiles: [ + '/app/index.js', + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/index.js', + '/app/node_modules/.pnpm/debug@4.3.7/node_modules/debug/src/node.js', + '/app/node_modules/.bun/@scope+pkg@1.0.0/node_modules/@scope/pkg/index.js', + '/usr/lib/node_modules/pm2/index.js', + ], + }), + ).toEqual({ debug: '4.3.7', '@scope/pkg': '1.0.0' }); + }); + + it('prefers the version that the app resolves when several versions of a package are loaded', () => { + const readFile = makeFs({ + '/app/package.json': { name: 'app' }, + '/app/node_modules/ms/package.json': { version: '2.1.3' }, + '/app/node_modules/.pnpm/ms@2.0.0/node_modules/ms/package.json': { version: '2.0.0' }, + '/app/node_modules/.pnpm/ms@2.1.3/node_modules/ms/package.json': { version: '2.1.3' }, + }); + + expect( + collectInstalledModules({ + readFile, + entryPath: '/app/index.js', + loadedFiles: [ + '/app/node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js', + '/app/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js', + ], + }), + ).toEqual({ ms: '2.1.3' }); + }); + + it('handles Windows paths', () => { + const readFile = makeFs({ + 'C:/app/package.json': { name: 'app', dependencies: { express: '^4.0.0' } }, + 'C:/app/node_modules/express/package.json': { version: '4.21.2' }, + }); + + expect(collectInstalledModules({ readFile, entryPath: 'C:\\app\\index.js' })).toEqual({ + express: '4.21.2', + }); + }); + + it('returns nothing without a package.json', () => { + expect(collectInstalledModules({ readFile: () => undefined, entryPath: '/app/index.js', cwd: '/' })).toEqual({}); + }); +}); diff --git a/packages/node/test/utils/module.test.ts b/packages/server-utils/test/utils/module.test.ts similarity index 96% rename from packages/node/test/utils/module.test.ts rename to packages/server-utils/test/utils/module.test.ts index 73404c37673e..230354d8b234 100644 --- a/packages/node/test/utils/module.test.ts +++ b/packages/server-utils/test/utils/module.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { createGetModuleFromFilename } from '../../src'; +import { createGetModuleFromFilename } from '../../src/utils/module'; describe('createGetModuleFromFilename', () => { it.each([ diff --git a/packages/server-utils/test/utils/serverTimingTraceHeader.test.ts b/packages/server-utils/test/utils/serverTimingTraceHeader.test.ts new file mode 100644 index 000000000000..0435c3bac763 --- /dev/null +++ b/packages/server-utils/test/utils/serverTimingTraceHeader.test.ts @@ -0,0 +1,135 @@ +import type { Client } from '@sentry/core'; +import { setCurrentClient, withIsolationScope } from '@sentry/core'; +import { beforeAll, describe, expect, it } from 'vitest'; +import { setAsyncLocalStorageAsyncContextStrategy } from '../../src/async-context'; +import { addServerTimingTraceHeader } from '../../src/utils/serverTimingTraceHeader'; +import { wrapServerRequestHandler } from '../../src/utils/wrapServerRequestHandler'; +import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; + +const TRACE_ID = '12312012123120121231201212312012'; +const INCOMING_TRACE = `${TRACE_ID}-1121201211212012-1`; + +function setup({ enabled = true, tracesSampleRate = 1 }: { enabled?: boolean; tracesSampleRate?: number } = {}): { + client: Client; + serve: (handler: () => Response | Promise, headers?: Record) => Promise; +} { + const client = new TestClient( + getDefaultTestClientOptions({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate, + beforeSendTransaction: () => null, + }), + ); + setCurrentClient(client); + client.init(); + if (enabled) { + addServerTimingTraceHeader(client); + } + + const serve = ( + handler: () => Response | Promise, + headers: Record = {}, + ): Promise => + withIsolationScope(isolationScope => + wrapServerRequestHandler( + { + request: new Request('https://example.com/user/5', { headers }), + client, + isolationScope, + options: {}, + origin: 'auto.http.test', + }, + handler, + ), + ); + return { client, serve }; +} + +const html = (init: ResponseInit = {}): Response => + new Response('', { ...init, headers: { 'content-type': 'text/html; charset=utf-8', ...init.headers } }); + +describe('addServerTimingTraceHeader', () => { + beforeAll(() => { + setAsyncLocalStorageAsyncContextStrategy(); + }); + + it('adds the trace of the request to a document response', async () => { + const { serve } = setup(); + + const response = await serve(() => html(), { 'sentry-trace': INCOMING_TRACE }); + + const value = response.headers.get('server-timing'); + expect(value).toMatch(new RegExp(`^sentry-trace;desc="${TRACE_ID}-[0-9a-f]{16}-1", baggage;desc=".*"$`)); + }); + + it('adds the trace when tracing is off', async () => { + const { serve } = setup({ tracesSampleRate: undefined as unknown as number }); + + const response = await serve(() => html(), { 'sentry-trace': INCOMING_TRACE }); + + expect(response.headers.get('server-timing')).toContain(`sentry-trace;desc="${TRACE_ID}-`); + }); + + it('does nothing for a client that did not turn it on', async () => { + const { serve } = setup({ enabled: false }); + + const response = await serve(() => html()); + + expect(response.headers.get('server-timing')).toBeNull(); + }); + + it('skips responses that are not documents', async () => { + const { serve } = setup(); + + const response = await serve(() => Response.json({ ok: true })); + + expect(response.headers.get('server-timing')).toBeNull(); + }); + + it.each([ + ['Cache-Control: public, max-age=60', { 'cache-control': 'public, max-age=60' }], + ['Cache-Control: s-maxage=60', { 'cache-control': 's-maxage=60' }], + ['CDN-Cache-Control: max-age=60', { 'cdn-cache-control': 'max-age=60' }], + ])('skips a document shared caches may store (%s)', async (_, headers) => { + const { serve } = setup(); + + const response = await serve(() => html({ headers })); + + expect(response.headers.get('server-timing')).toBeNull(); + }); + + it('keeps entries of the app', async () => { + const { serve } = setup(); + + const response = await serve(() => html({ headers: { 'server-timing': 'db;dur=53' } })); + + expect(response.headers.get('server-timing')).toMatch(/^db;dur=53, sentry-trace;desc="/); + }); + + it('leaves a sentry-trace entry of the app alone', async () => { + const { serve } = setup(); + + const response = await serve(() => html({ headers: { 'server-timing': 'sentry-trace;desc="own"' } })); + + expect(response.headers.get('server-timing')).toBe('sentry-trace;desc="own"'); + }); + + it('copies a response with immutable headers', async () => { + const { serve } = setup(); + const original = html({ status: 201, statusText: 'Created' }); + Object.defineProperty(original.headers, 'set', { + value: () => { + throw new TypeError('immutable'); + }, + }); + + const response = await serve(() => original); + + expect(response).not.toBe(original); + expect(response.status).toBe(201); + expect(response.statusText).toBe('Created'); + expect(response.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(response.headers.get('server-timing')).toContain('sentry-trace;desc="'); + expect(await response.text()).toBe(''); + }); +}); diff --git a/packages/solid/.oxlintrc.json b/packages/solid/.oxlintrc.json index ed17064b99bc..2082a098f763 100644 --- a/packages/solid/.oxlintrc.json +++ b/packages/solid/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true } diff --git a/packages/solid/package.json b/packages/solid/package.json index 3f3ae969067f..87d4e22ed160 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -99,7 +99,7 @@ "dependencies": { "@sentry/browser": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/node": "11.17.0" }, "peerDependencies": { diff --git a/packages/solid/src/solid2/server/cloudflare.ts b/packages/solid/src/solid2/server/cloudflare.ts index f7b05cfb736d..88fcae00b71f 100644 --- a/packages/solid/src/solid2/server/cloudflare.ts +++ b/packages/solid/src/solid2/server/cloudflare.ts @@ -1,7 +1,15 @@ import type { CloudflareOptions } from '@sentry/cloudflare'; -import { defineCloudflareOptions as defineCloudflareOptionsBase } from '@sentry/cloudflare'; -import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata } from '@sentry/core'; +import { addServerTimingTraceHeader, defineCloudflareOptions as defineCloudflareOptionsBase } from '@sentry/cloudflare'; +import type { Integration } from '@sentry/core'; +import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, defineIntegration } from '@sentry/core'; import { solidServerErrorsIntegration } from './errors'; +import { solidServerTracePropagationIntegration } from './tracePropagation'; + +// Sends the trace to the browser on every document response, so the pageload continues it, as `init` does on Node. +const serverTimingTraceHeaderIntegration = defineIntegration((): Integration => ({ + name: 'SolidServerTimingTraceHeader' as const, + setup: addServerTimingTraceHeader, +})); /** * Defines the Sentry options for a Solid 2 app on Cloudflare Workers, like `defineCloudflareOptions` of @@ -36,7 +44,12 @@ export const defineCloudflareOptions: typeof defineCloudflareOptionsBase = ( if (opts.defaultIntegrations === undefined) { const userIntegrations = opts.integrations; opts.integrations = defaults => { - const withSolid = [...defaults, solidServerErrorsIntegration()]; + const withSolid = [ + ...defaults, + solidServerErrorsIntegration(), + solidServerTracePropagationIntegration(), + serverTimingTraceHeaderIntegration(), + ]; return typeof userIntegrations === 'function' ? userIntegrations(withSolid) : [...withSolid, ...(userIntegrations ?? [])]; diff --git a/packages/solid/test/solid2/server/cloudflare.test.ts b/packages/solid/test/solid2/server/cloudflare.test.ts index f4ed08fedc79..470f1f330af0 100644 --- a/packages/solid/test/solid2/server/cloudflare.test.ts +++ b/packages/solid/test/solid2/server/cloudflare.test.ts @@ -18,7 +18,14 @@ describe('defineCloudflareOptions', () => { const options = defineCloudflareOptions({ dsn: 'https://public@dsn.ingest.sentry.io/1337' })({}); expect(options?.defaultIntegrations).toBeUndefined(); - expect(setupIntegrationNames(options)).toEqual(expect.arrayContaining(['Dedupe', 'SolidServerErrors'])); + expect(setupIntegrationNames(options)).toEqual( + expect.arrayContaining([ + 'Dedupe', + 'SolidServerErrors', + 'SolidServerTracePropagation', + 'SolidServerTimingTraceHeader', + ]), + ); }); it('builds the defaults from options changed after the options are defined', () => { diff --git a/packages/solidstart/package.json b/packages/solidstart/package.json index 17b9dc008fca..8c87e1ef20cb 100644 --- a/packages/solidstart/package.json +++ b/packages/solidstart/package.json @@ -91,7 +91,7 @@ "@sentry/server-utils": "11.17.0", "@sentry/solid": "11.17.0", "@sentry/bundler-plugins": "11.17.0", - "@sentry/conventions": "0.35.0", + "@sentry/conventions": "0.36.0", "h3": "^1.15.10" }, "devDependencies": { diff --git a/packages/solidstart/src/common/tunnel.ts b/packages/solidstart/src/common/tunnel.ts index 16f846a83dd0..c96b4542a7b2 100644 --- a/packages/solidstart/src/common/tunnel.ts +++ b/packages/solidstart/src/common/tunnel.ts @@ -1,17 +1,25 @@ import type { Options } from '@sentry/core'; -import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults } from '@sentry/core'; +import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; -/** Set on the server by `withSentry` to the app's `server.baseURL`. */ +/** Holds the app's `server.baseURL` on SolidStart 1 servers. Set by the server bundle and the `instrument.server` file. */ export const TUNNEL_BASE_PATH_GLOBAL = '__sentry_solidstart_base_path'; declare const __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__: string | undefined; +/** + * Returns the app's base path without a trailing slash. The build defines it where it bundles the SDK: in the browser + * and in the SolidStart 2 server. The SolidStart 1 server loads the SDK as an external module and reads the global. + */ +export function getBasePath(): string { + return typeof __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ !== 'undefined' + ? __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ + : ((GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] ?? ''); +} + /** * Serves the browser's managed tunnel under the app's base path, which `withSentry` (SolidStart 1) or * `sentrySolidStart` (SolidStart 2) defines at build time. A `basePath` the user set wins. */ export function applyTunnelBasePath(options: Pick): void { - const basePath = - typeof __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ !== 'undefined' ? __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ : ''; - options.tunnel = applyBrowserTunnelDefaults(options.tunnel, { basePath }); + options.tunnel = applyBrowserTunnelDefaults(options.tunnel, { basePath: getBasePath() }); } diff --git a/packages/solidstart/src/config/withSentry.ts b/packages/solidstart/src/config/withSentry.ts index fa30caad3551..965d22836070 100644 --- a/packages/solidstart/src/config/withSentry.ts +++ b/packages/solidstart/src/config/withSentry.ts @@ -1,9 +1,4 @@ -import { - _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, - debug, - GLOBAL_OBJ, - stringifyForCodeInjection, -} from '@sentry/core'; +import { normalizeTunnelBasePath, debug, GLOBAL_OBJ, stringifyForCodeInjection } from '@sentry/core'; import { INSTRUMENTED_MODULE_NAMES } from '@sentry/server-utils/orchestrion/config'; import { commonJSInteropOptions, diff --git a/packages/solidstart/src/nitro/tunnelPlugin.ts b/packages/solidstart/src/nitro/tunnelPlugin.ts index 857dfa8f66af..14d1a0249cd4 100644 --- a/packages/solidstart/src/nitro/tunnelPlugin.ts +++ b/packages/solidstart/src/nitro/tunnelPlugin.ts @@ -1,5 +1,5 @@ import { GLOBAL_OBJ } from '@sentry/core'; -import { _INTERNAL_setTunnelDefaults as setTunnelDefaults } from '@sentry/core/server'; +import { setTunnelDefaults } from '@sentry/core/server'; import type { NitroAppPlugin } from 'nitropack'; import { TUNNEL_BASE_PATH_GLOBAL } from '../common/tunnel'; diff --git a/packages/solidstart/src/server/sdk.ts b/packages/solidstart/src/server/sdk.ts index a020ed727b18..bbd7e4ecdbe6 100644 --- a/packages/solidstart/src/server/sdk.ts +++ b/packages/solidstart/src/server/sdk.ts @@ -1,7 +1,9 @@ -import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata } from '@sentry/core'; +import { URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, escapeStringForRegex } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; import { init as initNodeSdk } from '@sentry/node'; -import { filterLowQualityTransactions } from './utils'; +import { getBasePath } from '../common/tunnel'; /** * Initializes the server side of the Solid Start SDK @@ -9,10 +11,21 @@ import { filterLowQualityTransactions } from './utils'; export function init(options: NodeOptions): NodeClient | undefined { const opts = { ..._INTERNAL_captureOptionsSetByUser(options), + ignoreSpans: [...(options.ignoreSpans || []), getBuildAssetRequestFilter()], }; applySdkMetadata(opts, 'solidstart', ['solidstart', 'node']); - filterLowQualityTransactions(opts); return initNodeSdk(opts); } + +/** + * SolidStart serves its client build under `/_build/`. Matches `url.path`, because a span name has no path + * yet when `ignoreSpans` runs. + */ +function getBuildAssetRequestFilter(): NonNullable[number] { + const basePath = getBasePath(); + // A full URL as the base (a CDN) is not part of the request path. + const pathPrefix = basePath.includes('://') ? '' : basePath; + return { op: HTTP_SERVER, attributes: { [URL_PATH]: new RegExp(`^${escapeStringForRegex(pathPrefix)}/_build/`) } }; +} diff --git a/packages/solidstart/src/server/utils.ts b/packages/solidstart/src/server/utils.ts index 8276c32da9e0..56353ab5c421 100644 --- a/packages/solidstart/src/server/utils.ts +++ b/packages/solidstart/src/server/utils.ts @@ -1,7 +1,3 @@ -import type { EventProcessor, Options } from '@sentry/core'; -import { debug } from '@sentry/core'; -import { getGlobalScope } from '@sentry/node'; - /** * Determines if a thrown "error" is a redirect Response which Solid Start users can throw to redirect to another route. * see: https://docs.solidjs.com/solid-router/reference/data-apis/response-helpers#redirect @@ -16,33 +12,3 @@ export function isRedirect(error: unknown): boolean { const hasValidStatus = error.status >= 300 && error.status <= 308; return hasValidLocation && hasValidStatus; } - -/** - * Filter function for low quality transactions - * - * Exported only for tests - */ -export function lowQualityTransactionsFilter(options: Options): EventProcessor { - return Object.assign( - (event => { - if (event.type !== 'transaction') { - return event; - } - // Filter out transactions for build assets - if (event.transaction?.match(/^GET \/_build\//)) { - options.debug && debug.log('SolidStartLowQualityTransactionsFilter filtered transaction', event.transaction); - return null; - } - return event; - }) satisfies EventProcessor, - { id: 'SolidStartLowQualityTransactionsFilter' }, - ); -} - -/** - * Adds an event processor to filter out low quality transactions, - * e.g. to filter out transactions for build assets - */ -export function filterLowQualityTransactions(options: Options): void { - getGlobalScope().addEventProcessor(lowQualityTransactionsFilter(options)); -} diff --git a/packages/solidstart/src/vite/buildInstrumentationFile.ts b/packages/solidstart/src/vite/buildInstrumentationFile.ts index 6fbbb60e1615..fe0a6412bdf2 100644 --- a/packages/solidstart/src/vite/buildInstrumentationFile.ts +++ b/packages/solidstart/src/vite/buildInstrumentationFile.ts @@ -1,18 +1,30 @@ -import { consoleSandbox } from '@sentry/core'; +import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core'; import * as fs from 'fs'; import * as path from 'path'; import type { Plugin, UserConfig } from 'vite'; +import { TUNNEL_BASE_PATH_GLOBAL } from '../common/tunnel'; import type { SentrySolidStartPluginOptions } from './types'; /** * A Sentry plugin for SolidStart to build the server * `instrument.server.ts` file. */ -export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPluginOptions = {}): Plugin { +export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPluginOptions = {}, basePath = ''): Plugin { + let instrumentationFile: string | undefined; + return { name: 'sentry-solidstart-build-instrumentation-file', apply: 'build', enforce: 'post', + // `node --import` loads this file before the server bundle, so the file sets the base path for `Sentry.init` itself. + banner(chunk) { + // Vite reports module IDs with forward slashes, also on Windows. + const isInstrumentationFile = + !!chunk.facadeModuleId && path.resolve(chunk.facadeModuleId) === instrumentationFile; + return basePath && isInstrumentationFile + ? `globalThis.${TUNNEL_BASE_PATH_GLOBAL} = ${stringifyForCodeInjection(basePath)};` + : ''; + }, async config(config: UserConfig, { command }) { const instrumentationFilePath = options.instrumentation || './src/instrument.server.ts'; const router = (config as UserConfig & { router: { target: string; name: string; root: string } }).router; @@ -42,7 +54,8 @@ export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPlug return config; } - input.push(path.resolve(router.root, instrumentationFilePath)); + instrumentationFile = path.resolve(router.root, instrumentationFilePath); + input.push(instrumentationFile); return { ...config, diff --git a/packages/solidstart/src/vite/sentrySolidStart.ts b/packages/solidstart/src/vite/sentrySolidStart.ts index 7b8a8da33e44..e3b998c007a0 100644 --- a/packages/solidstart/src/vite/sentrySolidStart.ts +++ b/packages/solidstart/src/vite/sentrySolidStart.ts @@ -1,6 +1,7 @@ import { - _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, + normalizeTunnelBasePath, type BuildTimeOptionsBase, + resolveSourceMapsFeatures, stringifyForCodeInjection, warnOnRemovedBuildOptions, } from '@sentry/core'; @@ -8,6 +9,7 @@ import { setupSentryNitroModule } from '@sentry/nitro'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import type { Plugin, UserConfig } from 'vite'; import { getNitroRuntimeFilePath, getRuntimeRelease } from './release'; +import type { SourceMapState } from './sourceMaps'; import { makeAddSentryVitePluginSolidStart2, makeEnableSourceMapsVitePlugin } from './sourceMaps'; /** @@ -62,10 +64,15 @@ export function sentrySolidStart(options: SentrySolidStartOptions = {}): Plugin[ plugins.push(makeReleaseDefinePlugin(runtimeRelease)); } - if (options.sourcemaps?.disable !== true) { + // TODO(v12): Add the Sentry plugin with `sourcemaps.disable: true` too, like with the options that replace it. + if (resolveSourceMapsFeatures(options.sourcemaps).legacyDisable !== true) { + const sourceMapState: SourceMapState = { sdkEnabledSourceMaps: false }; + + // The bundler plugin decides on the `build.sourcemap` it finds in its own `config` hook, + // so the plugin that sets it has to come first. plugins.push( - ...makeAddSentryVitePluginSolidStart2(options, runtimeRelease), - ...makeEnableSourceMapsVitePlugin(options), + ...makeEnableSourceMapsVitePlugin(options, sourceMapState), + ...makeAddSentryVitePluginSolidStart2(options, sourceMapState, runtimeRelease), ); } diff --git a/packages/solidstart/src/vite/sentrySolidStartVite.ts b/packages/solidstart/src/vite/sentrySolidStartVite.ts index 449855d95c0b..5f0d26b6ddb8 100644 --- a/packages/solidstart/src/vite/sentrySolidStartVite.ts +++ b/packages/solidstart/src/vite/sentrySolidStartVite.ts @@ -1,6 +1,7 @@ -import { stringifyForCodeInjection, warnOnRemovedBuildOptions } from '@sentry/core'; +import { resolveSourceMapsFeatures, stringifyForCodeInjection, warnOnRemovedBuildOptions } from '@sentry/core'; import type { Plugin, UserConfig } from 'vite'; import { makeBuildInstrumentationFilePlugin } from './buildInstrumentationFile'; +import type { SourceMapState } from './sourceMaps'; import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps'; import type { SentrySolidStartPluginOptions } from './types'; @@ -9,7 +10,6 @@ import type { SentrySolidStartPluginOptions } from './types'; */ export const sentrySolidStartVite = ( options: SentrySolidStartPluginOptions = {}, - viteConfig: UserConfig, tunnelBasePath = '', runtimeRelease?: string, ): Plugin[] => { @@ -26,15 +26,20 @@ export const sentrySolidStartVite = ( ]; if (options.autoInjectServerSentry !== 'experimental_dynamic-import') { - sentryPlugins.push(makeBuildInstrumentationFilePlugin(options)); + sentryPlugins.push(makeBuildInstrumentationFilePlugin(options, tunnelBasePath)); } if (process.env.NODE_ENV !== 'development') { - if (options.sourcemaps?.disable !== true) { - const sourceMapsPlugin = makeAddSentryVitePlugin(options, viteConfig, runtimeRelease); - const enableSourceMapsPlugin = makeEnableSourceMapsVitePlugin(options); + // TODO(v12): Add the Sentry plugin with `sourcemaps.disable: true` too, like with the options that replace it. + if (resolveSourceMapsFeatures(options.sourcemaps).legacyDisable !== true) { + const sourceMapState: SourceMapState = { sdkEnabledSourceMaps: false }; - sentryPlugins.push(...sourceMapsPlugin, ...enableSourceMapsPlugin); + // The bundler plugin decides on the `build.sourcemap` it finds in its own `config` hook, + // so the plugin that sets it has to come first. + sentryPlugins.push( + ...makeEnableSourceMapsVitePlugin(options, sourceMapState), + ...makeAddSentryVitePlugin(options, sourceMapState, runtimeRelease), + ); } } @@ -51,7 +56,7 @@ export const addSentryPluginToVite = ( runtimeRelease?: string, ): UserConfig => { const plugins = Array.isArray(config.plugins) ? [...config.plugins] : []; - plugins.unshift(sentrySolidStartVite(options, config, tunnelBasePath, runtimeRelease)); + plugins.unshift(sentrySolidStartVite(options, tunnelBasePath, runtimeRelease)); return { ...config, diff --git a/packages/solidstart/src/vite/sourceMaps.ts b/packages/solidstart/src/vite/sourceMaps.ts index 732164e694ce..ce621b78adb8 100644 --- a/packages/solidstart/src/vite/sourceMaps.ts +++ b/packages/solidstart/src/vite/sourceMaps.ts @@ -1,12 +1,69 @@ -import { type SentryVitePluginOptions, sentryVitePlugin } from '@sentry/bundler-plugins/vite'; +import { type SentryVitePluginInternalOptions, sentryVitePlugin } from '@sentry/bundler-plugins/vite'; +import { resolveSourceMapsFeatures } from '@sentry/core'; import type { Plugin, UserConfig } from 'vite'; import type { SentrySolidStartOptions } from './sentrySolidStart'; import type { SentrySolidStartPluginOptions } from './types'; -// `debug` is all the source map setting logic needs, and all the two majors' option types share. -type SourceMapSettingOptions = { debug?: boolean }; +// What the source map setting logic needs, and the two majors' option types share. +type SourceMapSettingOptions = { + debug?: boolean; + sourcemaps?: { + disable?: boolean | 'disable-upload'; + upload?: boolean; + injectDebugIds?: boolean; + delete?: boolean; + deleteSourcemapsAfterUpload?: boolean; + }; +}; + +/** Shared by the two plugins of one build. */ +export type SourceMapState = { + /** The SDK turned on hidden source maps because the user did not set `build.sourcemap`. */ + sdkEnabledSourceMaps: boolean; +}; + +type SourceMapsOptions = SentrySolidStartPluginOptions['sourcemaps']; + +/** + * The bundler plugin calls these when it decides, after `makeEnableSourceMapsVitePlugin` ran. + * It passes the name of an environment with its own `build.sourcemap`, and `undefined` for the + * top-level setting. The SDK only turns on the top-level maps: Nitro's environments get their + * setting from Nitro, and `@sentry/nitro` handles their maps. + * + * With `keepWhenUploadDisabled`, maps the SDK turned on stay with `disable: 'disable-upload'`. + * A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. + * + * With `sourcemaps.delete` the bundler plugin ignores `deleteSourcemapsAfterUpload` and warns if + * the user set it, so it only gets the user's value then. + */ +function makeSourceMapDeletionOptions( + sourcemaps: SourceMapsOptions, + state: SourceMapState, + { keepWhenUploadDisabled }: { keepWhenUploadDisabled: boolean }, +): { + deleteSourcemapsAfterUpload: boolean | undefined | ((environment?: string) => boolean | undefined); + sdkEnabledSourceMaps: (environment?: string) => boolean; +} { + const sdkEnabledSourceMaps = (environment?: string): boolean => + environment === undefined && state.sdkEnabledSourceMaps; + + // TODO(v12): Remove along with `sourcemaps.disable`. + const keepSdkEnabledSourceMaps = keepWhenUploadDisabled && !!resolveSourceMapsFeatures(sourcemaps).legacyDisable; -type FilesToDeleteAfterUpload = string | string[] | undefined; + return { + deleteSourcemapsAfterUpload: + sourcemaps?.delete !== undefined + ? sourcemaps.deleteSourcemapsAfterUpload + : environment => + sourcemaps?.deleteSourcemapsAfterUpload ?? + (sdkEnabledSourceMaps(environment) && + !keepSdkEnabledSourceMaps && + sourcemaps?.filesToDeleteAfterUpload === undefined + ? true + : undefined), + sdkEnabledSourceMaps, + }; +} /** * A Sentry plugin for adding the @sentry/bundler-plugins/vite plugin to automatically upload source maps to Sentry. @@ -16,7 +73,7 @@ type FilesToDeleteAfterUpload = string | string[] | undefined; */ export function makeAddSentryVitePlugin( options: SentrySolidStartPluginOptions, - viteConfig: UserConfig, + state: SourceMapState = { sdkEnabledSourceMaps: false }, runtimeRelease?: string, ): Plugin[] { const { @@ -36,26 +93,7 @@ export function makeAddSentryVitePlugin( telemetry, } = options; - let updatedFilesToDeleteAfterUpload: string[] | undefined = undefined; - - if ( - typeof sourcemaps?.filesToDeleteAfterUpload === 'undefined' && - // Only if source maps were previously not set, we update the "filesToDeleteAfterUpload" (as we override the setting with "hidden") - typeof viteConfig.build?.sourcemap === 'undefined' - ) { - // For .output, .vercel, .netlify etc. - updatedFilesToDeleteAfterUpload = ['.*/**/*.map']; - - debug && - // eslint-disable-next-line no-console - console.log( - `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify( - updatedFilesToDeleteAfterUpload, - )}\` to delete generated source maps after they were uploaded to Sentry.`, - ); - } - - const pluginOptions: SentryVitePluginOptions = { + const pluginOptions: SentryVitePluginInternalOptions = { applicationKey, authToken: authToken ?? process.env.SENTRY_AUTH_TOKEN, bundleSizeOptimizations, @@ -71,7 +109,7 @@ export function makeAddSentryVitePlugin( url: sentryUrl, sourcemaps: { ...sourcemaps, - filesToDeleteAfterUpload: sourcemaps?.filesToDeleteAfterUpload ?? updatedFilesToDeleteAfterUpload, + ...makeSourceMapDeletionOptions(sourcemaps, state, { keepWhenUploadDisabled: false }), }, _metaOptions: { telemetry: { @@ -106,6 +144,7 @@ export function makeAddSentryVitePlugin( */ export function makeAddSentryVitePluginSolidStart2( options: SentrySolidStartOptions, + state: SourceMapState = { sdkEnabledSourceMaps: false }, runtimeRelease?: string, ): Plugin[] { // Everything not destructured out is field-for-field what `sentryVitePlugin` accepts, so it is @@ -122,38 +161,7 @@ export function makeAddSentryVitePluginSolidStart2( ...passthroughOptions } = options; - // Deferred because the default depends on whether the user set `build.sourcemap` themselves, - // which is only known once Vite resolves its config. - let resolveFilesToDeleteAfterUpload: - | ((value: FilesToDeleteAfterUpload | PromiseLike) => void) - | undefined; - const filesToDeleteAfterUploadPromise = new Promise(resolve => { - resolveFilesToDeleteAfterUpload = resolve; - }); - - const configPlugin: Plugin = { - name: 'sentry-solidstart-files-to-delete-after-upload', - apply: 'build', - enforce: 'post', - config(config) { - const userFilesToDelete = sourcemaps?.filesToDeleteAfterUpload; - - // Only clean up source maps we turned on ourselves. - if (typeof userFilesToDelete === 'undefined' && typeof config.build?.sourcemap === 'undefined') { - if (debug) { - // eslint-disable-next-line no-console - console.log( - '[Sentry] Automatically setting `sourcemaps.filesToDeleteAfterUpload: ["./**/*.map"]` to delete generated source maps after they were uploaded to Sentry.', - ); - } - resolveFilesToDeleteAfterUpload?.(['./**/*.map']); - } else { - resolveFilesToDeleteAfterUpload?.(userFilesToDelete); - } - }, - }; - - const pluginOptions: SentryVitePluginOptions = { + const pluginOptions: SentryVitePluginInternalOptions = { ...passthroughOptions, authToken: authToken ?? process.env.SENTRY_AUTH_TOKEN, debug: debug ?? false, @@ -163,7 +171,8 @@ export function makeAddSentryVitePluginSolidStart2( url: sentryUrl, sourcemaps: { ...sourcemaps, - filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, + // `@sentry/nitro` keeps the server maps with `disable-upload`, so the client maps stay too. + ...makeSourceMapDeletionOptions(sourcemaps, state, { keepWhenUploadDisabled: true }), }, _metaOptions: { telemetry: { @@ -173,11 +182,10 @@ export function makeAddSentryVitePluginSolidStart2( }; if (!runtimeRelease) { - return [configPlugin, ...(sentryVitePlugin(pluginOptions) as Plugin[])]; + return sentryVitePlugin(pluginOptions) as Plugin[]; } return [ - configPlugin, ...scopePlugins(sentryVitePlugin(withoutReleaseInjection(pluginOptions)), { applyToEnvironment: environment => environment.config.consumer === 'client', }), @@ -187,7 +195,7 @@ export function makeAddSentryVitePluginSolidStart2( ]; } -function withoutReleaseInjection(options: SentryVitePluginOptions): SentryVitePluginOptions { +function withoutReleaseInjection(options: SentryVitePluginInternalOptions): SentryVitePluginInternalOptions { return { ...options, release: { ...options.release, inject: false } }; } @@ -202,20 +210,22 @@ function scopePlugins( * A Sentry plugin for SolidStart to enable "hidden" source maps if they are unset. Used by both * SolidStart majors. */ -export function makeEnableSourceMapsVitePlugin(options: SourceMapSettingOptions): Plugin[] { +export function makeEnableSourceMapsVitePlugin( + options: SourceMapSettingOptions, + state: SourceMapState = { sdkEnabledSourceMaps: false }, +): Plugin[] { return [ { name: 'sentry-solidstart-update-source-map-setting', apply: 'build', enforce: 'post', config(viteConfig) { + const sourcemap = getUpdatedSourceMapSettings(viteConfig, options); + state.sdkEnabledSourceMaps = sourcemap !== viteConfig.build?.sourcemap; + // Return only what changed: Vite concatenates arrays when merging a `config` return value, // so echoing the whole config back would duplicate every array the user had. - return { - build: { - sourcemap: getUpdatedSourceMapSettings(viteConfig, options), - }, - }; + return sourcemap === undefined ? {} : { build: { sourcemap } }; }, }, ]; @@ -231,17 +241,19 @@ export function makeEnableSourceMapsVitePlugin(options: SourceMapSettingOptions) * - keep this setting (don't do anything - like deletion - besides uploading) * * 3. Users didn't set source maps generation - * - we enable 'hidden' source maps generation - * - configure `filesToDeleteAfterUpload` to delete all .map files (we emit a log about this) + * - we enable 'hidden' source maps generation when Sentry uploads the maps, or when + * `sourcemaps.delete: false` keeps them for a manual upload. Otherwise we leave it unset + * - without `sourcemaps.delete` we pass `deleteSourcemapsAfterUpload: true`, so the maps never + * reach the build output * * --> only exported for testing */ export function getUpdatedSourceMapSettings( viteConfig: UserConfig, sentryPluginOptions?: SourceMapSettingOptions, -): boolean | 'inline' | 'hidden' { +): boolean | 'inline' | 'hidden' | undefined { const viteSourceMap = viteConfig?.build?.sourcemap; - let updatedSourceMapSetting = viteSourceMap; + let updatedSourceMapSetting: boolean | 'inline' | 'hidden' | undefined = viteSourceMap; const settingKey = 'vite.build.sourcemap'; const debug = sentryPluginOptions?.debug; @@ -268,13 +280,32 @@ export function getUpdatedSourceMapSettings( `[Sentry] We discovered \`${settingKey}\` is set to \`${viteSourceMap.toString()}\`. Sentry will keep this source map setting. This will un-minify the code snippet on the Sentry Issue page.`, ); } else { - updatedSourceMapSetting = 'hidden'; + updatedSourceMapSetting = undefined; - debug && - // eslint-disable-next-line no-console - console.log( - `[Sentry] Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`, - ); + const sourcemaps = sentryPluginOptions?.sourcemaps; + const { injectDebugIds, upload, legacyDisable } = resolveSourceMapsFeatures(sourcemaps); + + // Without an upload, Sentry only turns source maps on when `sourcemaps.delete: false` keeps them. + // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. + if (upload || legacyDisable === 'disable-upload' || (sourcemaps?.delete === false && injectDebugIds)) { + updatedSourceMapSetting = 'hidden'; + + const keepsSourceMaps = + sourcemaps?.delete === false || + (sourcemaps?.delete === undefined && sourcemaps?.deleteSourcemapsAfterUpload === false); + // With `disable-upload`, SolidStart 2 keeps the maps and SolidStart 1 removes them. + const deletionMessage = keepsSourceMaps + ? ' The source maps stay in the build output.' + : legacyDisable === 'disable-upload' + ? '' + : ' Sentry removes the source maps from the build output.'; + + debug && + // eslint-disable-next-line no-console + console.log( + `[Sentry] Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`.${deletionMessage}`, + ); + } } return updatedSourceMapSetting; diff --git a/packages/solidstart/test/common/tunnel.test.ts b/packages/solidstart/test/common/tunnel.test.ts index 25263d12d950..f70d9c9d91c4 100644 --- a/packages/solidstart/test/common/tunnel.test.ts +++ b/packages/solidstart/test/common/tunnel.test.ts @@ -1,5 +1,28 @@ +import { GLOBAL_OBJ } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { applyTunnelBasePath } from '../../src/common/tunnel'; +import { applyTunnelBasePath, getBasePath, TUNNEL_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; + +describe('getBasePath', () => { + afterEach(() => { + vi.unstubAllGlobals(); + (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] = undefined; + }); + + it('prefers the defined base path over the global', () => { + vi.stubGlobal('__SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__', '/app'); + (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] = '/other'; + + expect(getBasePath()).toBe('/app'); + }); + + it('falls back to the global, then to no base path', () => { + expect(getBasePath()).toBe(''); + + (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] = '/app'; + + expect(getBasePath()).toBe('/app'); + }); +}); describe('applyTunnelBasePath', () => { afterEach(() => { diff --git a/packages/solidstart/test/config/withSentry.test.ts b/packages/solidstart/test/config/withSentry.test.ts index 1812ad3ce344..583081ac4bcd 100644 --- a/packages/solidstart/test/config/withSentry.test.ts +++ b/packages/solidstart/test/config/withSentry.test.ts @@ -161,9 +161,9 @@ describe('withSentry()', () => { expect(names).toEqual([ 'sentry-solidstart-tunnel-base-path', 'sentry-solidstart-build-instrumentation-file', + 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', 'sentry-vite-upload-staging', - 'sentry-solidstart-update-source-map-setting', ]); }); @@ -186,9 +186,9 @@ describe('withSentry()', () => { expect(names).toEqual([ 'sentry-solidstart-tunnel-base-path', 'sentry-solidstart-build-instrumentation-file', + 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', 'sentry-vite-upload-staging', - 'sentry-solidstart-update-source-map-setting', 'my-test-plugin', ]); }); @@ -215,9 +215,9 @@ describe('withSentry()', () => { expect(names).toEqual([ 'sentry-solidstart-tunnel-base-path', 'sentry-solidstart-build-instrumentation-file', + 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', 'sentry-vite-upload-staging', - 'sentry-solidstart-update-source-map-setting', 'my-test-plugin', ]); }); diff --git a/packages/solidstart/test/server/sdk.test.ts b/packages/solidstart/test/server/sdk.test.ts index 3439af33284d..38b19053c4af 100644 --- a/packages/solidstart/test/server/sdk.test.ts +++ b/packages/solidstart/test/server/sdk.test.ts @@ -1,9 +1,11 @@ -import type { EventProcessor } from '@sentry/core'; -import { getGlobalScope, Scope, SDK_VERSION } from '@sentry/node'; +import { SENTRY_OP, URL_PATH } from '@sentry/conventions/attributes'; +import { HTTP_SERVER } from '@sentry/conventions/op'; +import { SDK_VERSION } from '@sentry/node'; import * as SentryNode from '@sentry/node'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { GLOBAL_OBJ } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { TUNNEL_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; import { init as solidStartInit } from '../../src/server'; -import { lowQualityTransactionsFilter } from '../../src/server/utils'; const browserInit = vi.spyOn(SentryNode, 'init'); @@ -37,52 +39,76 @@ describe('Initialize Solid Start SDK', () => { expect(browserInit).toHaveBeenLastCalledWith(expect.objectContaining(expectedMetadata)); }); - describe('lowQualityTransactionsFilter', () => { - const options = { debug: false }; - const filter = lowQualityTransactionsFilter(options); + describe('ignoreSpans', () => { + const startServerSpan = (path: string): SentryNode.Span => + SentryNode.startInactiveSpan({ + name: 'GET', + forceTransaction: true, + attributes: { [SENTRY_OP]: HTTP_SERVER, [URL_PATH]: path }, + }); - describe('filters out low quality transactions', () => { - it.each(['GET /_build/some_asset.js', 'GET /_build/app.js', 'GET /_build/assets/logo.png'])( - 'filters out low quality transaction: (%s)', - transaction => { - const event = { type: 'transaction' as const, transaction }; - expect(filter(event, {})).toBeNull(); - }, - ); - }); + it.each(['/_build/assets/app.js', '/_build/assets/app.js.map', '/_build/.vite/manifest.json'])( + 'ignores build asset requests (%s)', + path => { + solidStartInit({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan(path).isRecording()).toBe(false); + }, + ); + + it.each(['/', '/_server', '/users/jane.doe', '/api/data.json', '/blog/_build/'])( + 'keeps route requests (%s)', + path => { + solidStartInit({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); - describe('keeps high quality transactions', () => { - it.each(['GET /', 'POST /_server'])('does not filter out route transactions (%s)', transaction => { - const event = { type: 'transaction' as const, transaction }; - expect(filter(event, {})).toEqual(event); + expect(startServerSpan(path).isRecording()).toBe(true); + }, + ); + + it('merges the default with user-provided ignoreSpans', () => { + solidStartInit({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + ignoreSpans: [{ attributes: { [URL_PATH]: '/health' } }], }); - }); - it('does not filter non-transaction events', () => { - const event = { type: 'error' as const, transaction: 'GET /_build/app.js' } as any; - expect(filter(event, {})).toEqual(event); + expect(startServerSpan('/health').isRecording()).toBe(false); + expect(startServerSpan('/_build/assets/app.js.map').isRecording()).toBe(false); }); - it('handles events without transaction property', () => { - const event = { type: 'transaction' as const }; - expect(filter(event, {})).toEqual(event); - }); - }); + describe('with a base path', () => { + afterEach(() => { + vi.unstubAllGlobals(); + (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] = undefined; + }); - it('registers an event processor', () => { - let passedEventProcessors: EventProcessor[] = []; - const addEventProcessor = vi - .spyOn(getGlobalScope(), 'addEventProcessor') - .mockImplementation((eventProcessor: EventProcessor) => { - passedEventProcessors = [...passedEventProcessors, eventProcessor]; - return new Scope(); + it('ignores build asset requests under the defined base path (SolidStart 2)', () => { + vi.stubGlobal('__SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__', '/app'); + + solidStartInit({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/app/_build/assets/app.js.map').isRecording()).toBe(false); + expect(startServerSpan('/_build/assets/app.js.map').isRecording()).toBe(true); + expect(startServerSpan('/app/users/_build/').isRecording()).toBe(true); }); - solidStartInit({ - dsn: 'https://public@dsn.ingest.sentry.io/1337', - }); + it('ignores build asset requests under the base path global (SolidStart 1)', () => { + (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] = '/shop.v2'; + + solidStartInit({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); - expect(addEventProcessor).toHaveBeenCalledTimes(1); - expect(passedEventProcessors[0]?.id).toEqual('SolidStartLowQualityTransactionsFilter'); + expect(startServerSpan('/shop.v2/_build/assets/app.js.map').isRecording()).toBe(false); + expect(startServerSpan('/shopxv2/_build/assets/app.js.map').isRecording()).toBe(true); + }); + + it('ignores build asset requests at the root when the base is a full URL', () => { + // `normalizeTunnelBasePath` turns `base: 'https://cdn.example.com/'` into this. + vi.stubGlobal('__SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__', '/https://cdn.example.com'); + + solidStartInit({ dsn: 'https://public@dsn.ingest.sentry.io/1337', tracesSampleRate: 1 }); + + expect(startServerSpan('/_build/assets/app.js.map').isRecording()).toBe(false); + }); + }); }); }); diff --git a/packages/solidstart/test/vite/buildInstrumentation.test.ts b/packages/solidstart/test/vite/buildInstrumentation.test.ts index 465f2801da55..727fbaa98449 100644 --- a/packages/solidstart/test/vite/buildInstrumentation.test.ts +++ b/packages/solidstart/test/vite/buildInstrumentation.test.ts @@ -136,6 +136,33 @@ describe('makeBuildInstrumentationFilePlugin()', () => { expect(config).toEqual(viteConfig); }); + describe('banner', () => { + type BannerHook = (chunk: { facadeModuleId: string | null }) => string; + + async function getBanner(basePath?: string): Promise { + const plugin = makeBuildInstrumentationFilePlugin({}, basePath); + // @ts-expect-error - this is always defined and always a function + await plugin.config(viteConfig, { command: 'build' }); + return plugin.banner as BannerHook; + } + + it('sets the base path in the instrumentation file, which `node --import` loads before the server', async () => { + const banner = await getBanner('/app'); + + expect(banner({ facadeModuleId: '/some/project/path/src/instrument.server.ts' })).toBe( + 'globalThis.__sentry_solidstart_base_path = "/app";', + ); + expect(banner({ facadeModuleId: '/path/to/entry1.js' })).toBe(''); + expect(banner({ facadeModuleId: null })).toBe(''); + }); + + it('adds nothing without a base path', async () => { + const banner = await getBanner(); + + expect(banner({ facadeModuleId: '/some/project/path/src/instrument.server.ts' })).toBe(''); + }); + }); + it("logs a warning if the instrumentation file doesn't exist", async () => { const error = new Error("File doesn't exist."); fsAccessMock.mockRejectedValueOnce(error); diff --git a/packages/solidstart/test/vite/sentrySolidStart.test.ts b/packages/solidstart/test/vite/sentrySolidStart.test.ts index 29c4626ab1a2..c72ed1e5f427 100644 --- a/packages/solidstart/test/vite/sentrySolidStart.test.ts +++ b/packages/solidstart/test/vite/sentrySolidStart.test.ts @@ -59,10 +59,9 @@ describe('sentrySolidStart()', () => { 'sentry-solidstart-server-entry', // `sentryOrchestrionPlugin` spreads the upstream code-transformer plugin, which brings its name. 'code-transformer', - 'sentry-solidstart-files-to-delete-after-upload', + 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', 'sentry-vite-upload-staging', - 'sentry-solidstart-update-source-map-setting', ]); }); @@ -73,6 +72,12 @@ describe('sentrySolidStart()', () => { expect(names).not.toContain('code-transformer'); }); + it.each([{ upload: false }, { injectDebugIds: false }])('keeps the source maps plugins with %j', sourcemaps => { + const names = sentrySolidStart({ sourcemaps }).map(plugin => plugin.name); + + expect(names).toContain('sentry-solidstart-update-source-map-setting'); + }); + it('omits the source maps plugins when source maps are disabled', () => { const names = sentrySolidStart({ sourcemaps: { disable: true } }).map(plugin => plugin.name); diff --git a/packages/solidstart/test/vite/sentrySolidStartVite.test.ts b/packages/solidstart/test/vite/sentrySolidStartVite.test.ts index 3273693769cf..6d1c76c851f0 100644 --- a/packages/solidstart/test/vite/sentrySolidStartVite.test.ts +++ b/packages/solidstart/test/vite/sentrySolidStartVite.test.ts @@ -10,15 +10,12 @@ vi.spyOn(console, 'warn').mockImplementation(() => { }); function getSentrySolidStartVitePlugins(options?: Parameters[0]): Plugin[] { - return sentrySolidStartVite( - { - project: 'project', - org: 'org', - authToken: 'token', - ...options, - }, - {}, - ); + return sentrySolidStartVite({ + project: 'project', + org: 'org', + authToken: 'token', + ...options, + }); } describe('sentrySolidStartVite()', () => { @@ -28,9 +25,9 @@ describe('sentrySolidStartVite()', () => { expect(names).toEqual([ 'sentry-solidstart-tunnel-base-path', 'sentry-solidstart-build-instrumentation-file', + 'sentry-solidstart-update-source-map-setting', 'sentry-vite-plugin', 'sentry-vite-upload-staging', - 'sentry-solidstart-update-source-map-setting', ]); }); diff --git a/packages/solidstart/test/vite/sourceMaps.test.ts b/packages/solidstart/test/vite/sourceMaps.test.ts index 5d50aea8d222..05544278e713 100644 --- a/packages/solidstart/test/vite/sourceMaps.test.ts +++ b/packages/solidstart/test/vite/sourceMaps.test.ts @@ -1,7 +1,10 @@ -import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; +import type { SentryVitePluginInternalOptions } from '@sentry/bundler-plugins/vite'; +import { escapeStringForRegex } from '@sentry/core'; import type { Plugin, UserConfig } from 'vite'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { sentrySolidStart } from '../../src/vite/sentrySolidStart'; +import { sentrySolidStartVite } from '../../src/vite/sentrySolidStartVite'; +import type { SourceMapState } from '../../src/vite/sourceMaps'; import { getUpdatedSourceMapSettings, makeAddSentryVitePlugin, @@ -9,25 +12,46 @@ import { makeEnableSourceMapsVitePlugin, } from '../../src/vite/sourceMaps'; -const mockedSentryVitePlugin = { - name: 'sentry-vite-debug-id-upload-plugin', - writeBundle: vi.fn(), -}; +let lastPluginOptions: SentryVitePluginInternalOptions | undefined; -// Captured so tests can await the deferred `filesToDeleteAfterUpload` promise, which -// `toHaveBeenCalledWith` can only match by identity. -let lastPluginOptions: SentryVitePluginOptions | undefined; +/** What the options returned when the mocked Sentry plugin's `config` hook ran. */ +let optionsAtSentryConfigHook: { deletion?: boolean; sdkEnabled?: boolean } | undefined; -const sentryVitePluginSpy = vi.fn((options: SentryVitePluginOptions) => { +const sentryVitePluginSpy = vi.fn((options: SentryVitePluginInternalOptions): Plugin[] => { lastPluginOptions = options; - return [mockedSentryVitePlugin]; + return [ + { + name: 'sentry-vite-debug-id-upload-plugin', + config() { + optionsAtSentryConfigHook = { deletion: getDeleteOption(), sdkEnabled: getSdkEnabledOption() }; + }, + }, + ]; }); -/** Runs a plugin's `config` hook the way Vite does. */ -function runConfigHook(plugin: Plugin, config: UserConfig = {}): void { - const hook = plugin.config; - const handler = typeof hook === 'function' ? hook : hook?.handler; - handler?.call({} as never, config, { command: 'build', mode: 'production' }); +/** Runs each plugin's `config` hook in order over one config, merging `build` the way Vite does. */ +function runConfigHooks(plugins: Plugin[], config: UserConfig): UserConfig { + for (const plugin of plugins) { + const hook = plugin.config; + const handler = typeof hook === 'function' ? hook : hook?.handler; + const contributed = handler?.call({} as never, config, { command: 'build', mode: 'production' }) as + | UserConfig + | undefined; + if (contributed?.build) { + config.build = { ...config.build, ...contributed.build }; + } + } + return config; +} + +function getDeleteOption(environment?: string): boolean | undefined { + const value = lastPluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload; + return typeof value === 'function' ? value(environment) : value; +} + +function getSdkEnabledOption(environment?: string): boolean | undefined { + const value = lastPluginOptions?.sourcemaps?.sdkEnabledSourceMaps; + return typeof value === 'function' ? value(environment) : value; } vi.mock('@sentry/bundler-plugins/vite', async () => { @@ -35,12 +59,13 @@ vi.mock('@sentry/bundler-plugins/vite', async () => { return { ...original, - sentryVitePlugin: (options: SentryVitePluginOptions) => sentryVitePluginSpy(options), + sentryVitePlugin: (options: SentryVitePluginInternalOptions) => sentryVitePluginSpy(options), }; }); beforeEach(() => { vi.clearAllMocks(); + optionsAtSentryConfigHook = undefined; }); describe('makeSourceMapsVitePlugin()', () => { @@ -73,26 +98,44 @@ describe('makeSourceMapsVitePlugin()', () => { expect(contributed).toEqual({ build: { sourcemap: 'hidden' } }); }); + + it('records that it enabled source maps', () => { + const state: SourceMapState = { sdkEnabledSourceMaps: false }; + + runConfigHooks(makeEnableSourceMapsVitePlugin({}, state), {}); + + expect(state.sdkEnabledSourceMaps).toBe(true); + }); + + it.each([['hidden'], ['inline'], [true], [false]] as const)( + 'does not record a `%s` setting the user made', + setting => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + const state: SourceMapState = { sdkEnabledSourceMaps: true }; + + runConfigHooks(makeEnableSourceMapsVitePlugin({}, state), { build: { sourcemap: setting } }); + + expect(state.sdkEnabledSourceMaps).toBe(false); + }, + ); }); describe('makeAddSentryVitePlugin()', () => { it('passes user-specified vite plugin options to vite plugin', () => { - makeAddSentryVitePlugin( - { - org: 'my-org', - authToken: 'my-token', - applicationKey: 'my-app-key', - sentryUrl: 'https://my.sentry.io', - moduleMetadata: { team: 'sdk' }, - sourcemaps: { - filesToDeleteAfterUpload: ['baz/*.js'], - }, - bundleSizeOptimizations: { - excludeTracing: true, - }, + makeAddSentryVitePlugin({ + org: 'my-org', + authToken: 'my-token', + applicationKey: 'my-app-key', + sentryUrl: 'https://my.sentry.io', + moduleMetadata: { team: 'sdk' }, + sourcemaps: { + filesToDeleteAfterUpload: ['baz/*.js'], }, - {}, - ); + bundleSizeOptimizations: { + excludeTracing: true, + }, + }); expect(sentryVitePluginSpy).toHaveBeenCalledWith( expect.objectContaining({ @@ -104,6 +147,8 @@ describe('makeAddSentryVitePlugin()', () => { moduleMetadata: { team: 'sdk' }, sourcemaps: { filesToDeleteAfterUpload: ['baz/*.js'], + deleteSourcemapsAfterUpload: expect.any(Function), + sdkEnabledSourceMaps: expect.any(Function), }, bundleSizeOptimizations: { excludeTracing: true, @@ -111,69 +156,6 @@ describe('makeAddSentryVitePlugin()', () => { }), ); }); - - it('should update `filesToDeleteAfterUpload` if source map generation was previously not defined', () => { - makeAddSentryVitePlugin( - { - org: 'my-org', - authToken: 'my-token', - bundleSizeOptimizations: { - excludeTracing: true, - }, - }, - {}, - ); - - expect(sentryVitePluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: ['.*/**/*.map'], - }), - }), - ); - }); - - it('should not update `filesToDeleteAfterUpload` if source map generation was previously enabled', () => { - makeAddSentryVitePlugin( - { - org: 'my-org', - authToken: 'my-token', - bundleSizeOptimizations: { - excludeTracing: true, - }, - }, - { build: { sourcemap: true } }, - ); - - expect(sentryVitePluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: undefined, - }), - }), - ); - }); - - it('should not update `filesToDeleteAfterUpload` if source map generation was previously disabled', () => { - makeAddSentryVitePlugin( - { - org: 'my-org', - authToken: 'my-token', - bundleSizeOptimizations: { - excludeTracing: true, - }, - }, - { build: { sourcemap: false } }, - ); - - expect(sentryVitePluginSpy).toHaveBeenCalledWith( - expect.objectContaining({ - sourcemaps: expect.objectContaining({ - filesToDeleteAfterUpload: undefined, - }), - }), - ); - }); }); describe('makeAddSentryVitePluginSolidStart2()', () => { @@ -221,35 +203,6 @@ describe('makeAddSentryVitePluginSolidStart2()', () => { ); }); - // `filesToDeleteAfterUpload` is resolved through a deferred promise, because the default depends - // on whether the user set `build.sourcemap` themselves - only known once Vite resolves its config. - it('resolves `filesToDeleteAfterUpload` to the user-specified value', async () => { - const plugins = makeAddSentryVitePluginSolidStart2({ - sourcemaps: { filesToDeleteAfterUpload: ['custom/**/*.map'] }, - }); - - runConfigHook(plugins[0]!); - - await expect(lastPluginOptions?.sourcemaps?.filesToDeleteAfterUpload).resolves.toEqual(['custom/**/*.map']); - }); - - // Only clean up source maps the SDK turned on itself. - it('defaults `filesToDeleteAfterUpload` only when the user left `build.sourcemap` unset', async () => { - const plugins = makeAddSentryVitePluginSolidStart2({ org: 'my-org' }); - - runConfigHook(plugins[0]!); - - await expect(lastPluginOptions?.sourcemaps?.filesToDeleteAfterUpload).resolves.toEqual(['./**/*.map']); - }); - - it('leaves `filesToDeleteAfterUpload` unset when the user configured `build.sourcemap`', async () => { - const plugins = makeAddSentryVitePluginSolidStart2({ org: 'my-org' }); - - runConfigHook(plugins[0]!, { build: { sourcemap: true } }); - - await expect(lastPluginOptions?.sourcemaps?.filesToDeleteAfterUpload).resolves.toBeUndefined(); - }); - it('warns when the removed `unstable_sentryVitePluginOptions` is still set', () => { const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); @@ -272,7 +225,11 @@ describe('release injection when the server adds the release to the page', () => } it('injects the release into the SolidStart 1 server builds only', () => { - const [clientPlugin, serverPlugin] = makeAddSentryVitePlugin({ release: { name: 'my-release' } }, {}, 'my-release'); + const [clientPlugin, serverPlugin] = makeAddSentryVitePlugin( + { release: { name: 'my-release' } }, + { sdkEnabledSourceMaps: false }, + 'my-release', + ); expect(sentryVitePluginSpy).toHaveBeenCalledWith( expect.objectContaining({ release: { name: 'my-release', inject: false } }), @@ -285,7 +242,11 @@ describe('release injection when the server adds the release to the page', () => }); it('injects the release into the SolidStart 2 server environments only', () => { - const [, clientPlugin, serverPlugin] = makeAddSentryVitePluginSolidStart2({}, 'my-release'); + const [clientPlugin, serverPlugin] = makeAddSentryVitePluginSolidStart2( + {}, + { sdkEnabledSourceMaps: false }, + 'my-release', + ); expect(sentryVitePluginSpy).toHaveBeenCalledWith(expect.objectContaining({ release: { inject: false } })); expect(appliesToEnvironment(clientPlugin!, 'client')).toBe(true); @@ -295,10 +256,153 @@ describe('release injection when the server adds the release to the page', () => }); it('keeps one plugin for all builds when the server adds no release', () => { - const plugins = makeAddSentryVitePlugin({ release: { name: 'my-release', inject: false } }, {}); + const plugins = makeAddSentryVitePlugin({ release: { name: 'my-release', inject: false } }); expect(sentryVitePluginSpy).toHaveBeenCalledTimes(1); - expect(plugins).toEqual([mockedSentryVitePlugin]); + expect(plugins).toEqual([expect.objectContaining({ name: 'sentry-vite-debug-id-upload-plugin' })]); + expect(plugins[0]).not.toHaveProperty('apply'); + }); +}); + +describe.each([ + ['makeAddSentryVitePlugin', makeAddSentryVitePlugin], + ['makeAddSentryVitePluginSolidStart2', makeAddSentryVitePluginSolidStart2], +] as const)('%s() source map deletion', (_name, makePlugin) => { + it('asks for deletion once the SDK enabled the source maps', () => { + const state: SourceMapState = { sdkEnabledSourceMaps: false }; + makePlugin({}, state); + + expect(getDeleteOption()).toBeUndefined(); + state.sdkEnabledSourceMaps = true; + expect(getDeleteOption()).toBe(true); + }); + + it.each([true, false])('passes a user-set `deleteSourcemapsAfterUpload: %s` through', value => { + makePlugin({ sourcemaps: { deleteSourcemapsAfterUpload: value } }, { sdkEnabledSourceMaps: !value }); + + expect(getDeleteOption()).toBe(value); + }); + + it.each([[['./dist/**/*.map']], [[]]])( + 'lets a user-set `filesToDeleteAfterUpload: %j` replace the deletion', + files => { + makePlugin({ sourcemaps: { filesToDeleteAfterUpload: files } }, { sdkEnabledSourceMaps: true }); + + expect(lastPluginOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(files); + expect(getDeleteOption()).toBeUndefined(); + }, + ); + + it('lets a user-set `deleteSourcemapsAfterUpload: true` win over the user glob', () => { + makePlugin( + { sourcemaps: { deleteSourcemapsAfterUpload: true, filesToDeleteAfterUpload: ['./dist/**/*.map'] } }, + { sdkEnabledSourceMaps: true }, + ); + + expect(getDeleteOption()).toBe(true); + }); + + // Nitro gives its environments their own `build.sourcemap`, and `@sentry/nitro` reads those + // maps after the build. + it.each([ + [undefined, true, true], + ['nitro', undefined, false], + ['ssr', undefined, false], + ])('answers for the `%s` environment', (environment, deletion, sdkEnabled) => { + makePlugin({}, { sdkEnabledSourceMaps: true }); + + expect(getDeleteOption(environment)).toBe(deletion); + expect(getSdkEnabledOption(environment)).toBe(sdkEnabled); + }); + + it.each([undefined, 'nitro', 'ssr'])( + 'passes a user-set `deleteSourcemapsAfterUpload` to the `%s` environment', + environment => { + makePlugin({ sourcemaps: { deleteSourcemapsAfterUpload: true } }, { sdkEnabledSourceMaps: true }); + + expect(getDeleteOption(environment)).toBe(true); + }, + ); + + // Makes the plugin remove all of the maps, also those a user's `assets` or `ignore` leave out. + it('tells the bundler plugin whether the SDK enabled the source maps', () => { + const state: SourceMapState = { sdkEnabledSourceMaps: false }; + makePlugin({ sourcemaps: { assets: ['./dist/client/**'] } }, state); + + expect(getSdkEnabledOption()).toBe(false); + state.sdkEnabledSourceMaps = true; + expect(getSdkEnabledOption()).toBe(true); + expect(getDeleteOption()).toBe(true); + }); +}); + +describe.each([ + ['makeAddSentryVitePlugin', makeAddSentryVitePlugin], + ['makeAddSentryVitePluginSolidStart2', makeAddSentryVitePluginSolidStart2], +] as const)('%s() with the new source map options', (_name, makePlugin) => { + it('passes them through', () => { + makePlugin({ sourcemaps: { upload: false, injectDebugIds: true, delete: false } }); + + expect(lastPluginOptions?.sourcemaps).toEqual( + expect.objectContaining({ upload: false, injectDebugIds: true, delete: false }), + ); + }); + + // The bundler plugin warns when both options are set, so it must only see what the user set. + it.each([ + [{ delete: true }, undefined], + [{ delete: false, deleteSourcemapsAfterUpload: true }, true], + ] as const)('with %j it passes `deleteSourcemapsAfterUpload: %s`', (sourcemaps, expected) => { + makePlugin({ sourcemaps }, { sdkEnabledSourceMaps: true }); + + expect(lastPluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBe(expected); + }); + + it("deletes the maps the SDK enabled when `upload: true` replaces `disable: 'disable-upload'`", () => { + makePlugin({ sourcemaps: { disable: 'disable-upload', upload: true } }, { sdkEnabledSourceMaps: true }); + + expect(getDeleteOption()).toBe(true); + }); +}); + +it('makeAddSentryVitePlugin() asks for deletion when only the upload is disabled', () => { + makeAddSentryVitePlugin({ sourcemaps: { disable: 'disable-upload' } }, { sdkEnabledSourceMaps: true }); + + expect(getDeleteOption()).toBe(true); + expect(getSdkEnabledOption()).toBe(true); +}); + +it('makeAddSentryVitePluginSolidStart2() keeps the source maps when only the upload is disabled', () => { + makeAddSentryVitePluginSolidStart2({ sourcemaps: { disable: 'disable-upload' } }, { sdkEnabledSourceMaps: true }); + + expect(getDeleteOption()).toBeUndefined(); +}); + +// Vinxi passes its router to every SolidStart 1 `config` hook. +const vinxiClientConfig = { router: { target: 'client', name: 'client', root: '.' } } as UserConfig; + +// The bundler plugin reads the option when its own `config` hook runs, which comes after ours. +describe.each([ + ['sentrySolidStart', () => sentrySolidStart()], + ['sentrySolidStartVite', () => sentrySolidStartVite()], +] as const)('%s() in plugin order', (_name, getPlugins) => { + beforeEach(() => { + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + + it('enables hidden source maps and asks the bundler plugin to delete them', () => { + const config = runConfigHooks(getPlugins(), { ...vinxiClientConfig }); + + expect(config.build?.sourcemap).toBe('hidden'); + expect(optionsAtSentryConfigHook).toEqual({ deletion: true, sdkEnabled: true }); + }); + + it('keeps source maps the user enabled', () => { + const config = runConfigHooks(getPlugins(), { ...vinxiClientConfig, build: { sourcemap: 'hidden' } }); + + expect(config.build?.sourcemap).toBe('hidden'); + expect(optionsAtSentryConfigHook).toEqual({ deletion: undefined, sdkEnabled: false }); }); }); @@ -371,6 +475,34 @@ describe('getUpdatedSourceMapSettings', () => { }, ); + it.each([ + [{ upload: false }, undefined], + [{ injectDebugIds: false }, undefined], + [{ upload: true }, 'hidden'], + [{ disable: true, upload: true }, 'hidden'], + [{ disable: 'disable-upload' }, 'hidden'], + [{ delete: true }, 'hidden'], + [{ delete: false }, 'hidden'], + [{ upload: false, delete: false }, 'hidden'], + [{ upload: false, delete: true }, undefined], + [{ injectDebugIds: false, delete: false }, undefined], + ] as const)('with an unset setting and %j it returns %s', (sourcemaps, expected) => { + expect(getUpdatedSourceMapSettings({}, { sourcemaps })).toBe(expected); + }); + + it.each([ + [{}, 'Sentry removes the source maps from the build output.'], + [{ delete: true }, 'Sentry removes the source maps from the build output.'], + [{ delete: false }, 'The source maps stay in the build output.'], + [{ deleteSourcemapsAfterUpload: false }, 'The source maps stay in the build output.'], + [{ disable: 'disable-upload' }, "`vite.build.sourcemap: 'hidden'`."], + ] as const)('with %j it logs %s', (sourcemaps, message) => { + getUpdatedSourceMapSettings({}, { debug: true, sourcemaps }); + + // eslint-disable-next-line no-console + expect(console.log).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`${escapeStringForRegex(message)}$`))); + }); + it('should set sourcemap to hidden when build config is empty', () => { const result = getUpdatedSourceMapSettings({}, { debug: true }); diff --git a/packages/svelte/.oxlintrc.json b/packages/svelte/.oxlintrc.json index ed17064b99bc..2082a098f763 100644 --- a/packages/svelte/.oxlintrc.json +++ b/packages/svelte/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true } diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 9d5647d083af..316a67a0f8fe 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -33,7 +33,7 @@ }, "dependencies": { "@sentry/browser": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "magic-string": "~0.30.0" }, diff --git a/packages/sveltekit/package.json b/packages/sveltekit/package.json index 5ce9556a2d10..7ea3a395cdab 100644 --- a/packages/sveltekit/package.json +++ b/packages/sveltekit/package.json @@ -73,7 +73,7 @@ "@opentelemetry/api": "^1.9.1", "@sentry/cloudflare": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/node": "11.17.0", "@sentry/server-runtime-injection": "11.17.0", "@sentry/server-utils": "11.17.0", diff --git a/packages/sveltekit/src/common/tunnel.ts b/packages/sveltekit/src/common/tunnel.ts index bab63d505b77..877fdd6ce9f9 100644 --- a/packages/sveltekit/src/common/tunnel.ts +++ b/packages/sveltekit/src/common/tunnel.ts @@ -1,5 +1,5 @@ import type { Options } from '@sentry/core'; -import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; +import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; /** Set by `sentrySvelteKit()` to the app's `paths.base`. */ export const TUNNEL_BASE_PATH_GLOBAL = '__sentry_sveltekit_base_path'; diff --git a/packages/sveltekit/src/server-common/handle.ts b/packages/sveltekit/src/server-common/handle.ts index 3b88f6c45720..d8fab504e24d 100644 --- a/packages/sveltekit/src/server-common/handle.ts +++ b/packages/sveltekit/src/server-common/handle.ts @@ -26,8 +26,8 @@ import { _INTERNAL_getCacheOriginMetaTags, _INTERNAL_getReleaseMetaTag as renderReleaseMetaTag, _INTERNAL_getRootSpanSentryTrace, - _INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest, - _INTERNAL_setTunnelDefaults as setTunnelDefaults, + handleServedTunnelRequest, + setTunnelDefaults, } from '@sentry/core/server'; import { getTunnelBasePath } from '../common/tunnel'; import type { GlobalWithSentryValues } from '../vite/injectGlobalValues'; diff --git a/packages/sveltekit/src/vite/sourceMaps.ts b/packages/sveltekit/src/vite/sourceMaps.ts index 65ee6b13e797..573bbbad603c 100644 --- a/packages/sveltekit/src/vite/sourceMaps.ts +++ b/packages/sveltekit/src/vite/sourceMaps.ts @@ -1,6 +1,11 @@ -import { escapeStringForRegex, resolveSourceMapsFeatures, uuid4 } from '@sentry/core'; +import { + escapeStringForRegex, + resolveSourceMapsFeatures, + uuid4, + warnOnConflictingSourceMapOptions, +} from '@sentry/core'; import { getSentryRelease } from '@sentry/node'; -import { addDebugIdToEmittedArtifacts } from '@sentry/bundler-plugins/core'; +import { addDebugIdToEmittedArtifacts, hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import * as child_process from 'child_process'; @@ -52,6 +57,8 @@ export async function makeCustomSentryVitePlugins( }, ): Promise { const { getAdapterOutputDir, getKitConfig } = deps; + // The plugin does not get `sourcemaps.delete`. + warnOnConflictingSourceMapOptions(options?.sourcemaps); const defaultPluginOptions: SentryVitePluginOptions = { release: { @@ -398,7 +405,7 @@ export function _getUpdatedSourceMapSettings( } else if ( // TODO(v12): Remove the `disable-upload` case along with `sourcemaps.disable`. legacyDisable === 'disable-upload' || - upload || + (upload && hasSourceMapUploadCredentials(sentryPluginOptions)) || (deleteOption === false && injectDebugIds) ) { updatedSourceMapSetting = 'hidden'; diff --git a/packages/sveltekit/test/server-common/handle.test.ts b/packages/sveltekit/test/server-common/handle.test.ts index c34bdceb1bce..880155d35646 100644 --- a/packages/sveltekit/test/server-common/handle.test.ts +++ b/packages/sveltekit/test/server-common/handle.test.ts @@ -3,7 +3,7 @@ import { SENTRY_SEGMENT_NAME_SOURCE, HTTP_ROUTE } from '@sentry/conventions/attr import { getCapturedScopesOnSpan, getRootSpan, getSpanDescendants, spanIsSampled, spanToJSON } from '@sentry/core'; import * as SentryCore from '@sentry/core'; import { NodeClient, serveTunnelIntegration, setCurrentClient } from '@sentry/node'; -import { _INTERNAL_resetTunnelDefaults } from '@sentry/core/server'; +import { resetTunnelDefaults } from '@sentry/core/server'; import { TUNNEL_BASE_PATH_GLOBAL } from '../../src/common/tunnel'; import type { Handle } from '../../src/server-common/handleTypes'; import { redirect } from '@sveltejs/kit'; @@ -168,7 +168,7 @@ describe('sentryHandle with the managed tunnel', () => { afterEach(() => { vi.unstubAllGlobals(); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('answers tunnel requests without resolving the route', async () => { diff --git a/packages/sveltekit/test/vite/sourceMaps.test.ts b/packages/sveltekit/test/vite/sourceMaps.test.ts index 9c732cd79211..f7d94632508d 100644 --- a/packages/sveltekit/test/vite/sourceMaps.test.ts +++ b/packages/sveltekit/test/vite/sourceMaps.test.ts @@ -5,7 +5,7 @@ import * as os from 'os'; import * as path from 'path'; import type { Plugin } from 'vite'; import * as vite from 'vite'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { ViteUserConfig } from 'vitest/config'; import { _getUpdatedSourceMapSettings, makeCustomSentryVitePlugins } from '../../src/vite/sourceMaps'; @@ -47,6 +47,8 @@ beforeEach(() => { vi.clearAllMocks(); }); +const CREDENTIALS = { authToken: 'token', org: 'org', project: 'project' }; + async function getSentryViteSubPlugin(name: string): Promise { const plugins = await makeCustomSentryVitePlugins( { @@ -294,6 +296,20 @@ describe('makeCustomSentryVitePlugins()', () => { }); }); + // The bundler plugin does not get `sourcemaps.delete`. + it('warns about conflicting source map options', async () => { + const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await makeCustomSentryVitePlugins( + { sourcemaps: { delete: false, filesToDeleteAfterUpload: ['./build/**/*.map'] } }, + { getAdapterOutputDir: async () => '.svelte-kit/output', getKitConfig: async () => ({}) }, + ); + + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('`sourcemaps.filesToDeleteAfterUpload` still deletes the files'), + ); + }); + it('catches errors while uploading source maps', async () => { mockedMainPlugin.writeBundle.mockImplementationOnce(() => { throw new Error('test error'); @@ -369,7 +385,10 @@ describe('_getUpdatedSourceMapSettings', () => { it.each([[undefined], ['invalid'], ['something'], [null]])( 'should set sourcemap to hidden when value is %s', input => { - const result = _getUpdatedSourceMapSettings({ build: { sourcemap: input as any } }, { debug: true }); + const result = _getUpdatedSourceMapSettings( + { build: { sourcemap: input as any } }, + { ...CREDENTIALS, debug: true }, + ); expect(result).toBe('hidden'); // eslint-disable-next-line no-console @@ -382,7 +401,7 @@ describe('_getUpdatedSourceMapSettings', () => { ); it('should set sourcemap to hidden when build config is empty', () => { - const result = _getUpdatedSourceMapSettings({}, { debug: true }); + const result = _getUpdatedSourceMapSettings({}, { ...CREDENTIALS, debug: true }); expect(result).toBe('hidden'); // eslint-disable-next-line no-console @@ -401,6 +420,10 @@ describe('_getUpdatedSourceMapSettings with the source map options', () => { vi.spyOn(console, 'log').mockImplementation(() => {}); }); + afterEach(() => { + vi.unstubAllEnvs(); + }); + it.each([ [{ upload: false }, undefined], [{ injectDebugIds: false }, undefined], @@ -411,6 +434,16 @@ describe('_getUpdatedSourceMapSettings with the source map options', () => { [{ disable: true }, undefined], [{ disable: 'disable-upload' }, 'hidden'], ] as const)('with an unset setting and %j it returns %s', (sourcemaps, expected) => { + expect(_getUpdatedSourceMapSettings({}, { ...CREDENTIALS, sourcemaps })).toBe(expected); + }); + + it.each([ + [{}, undefined], + [{ disable: 'disable-upload' }, 'hidden'], + [{ delete: false }, 'hidden'], + ] as const)('without upload credentials, with an unset setting and %j it returns %s', (sourcemaps, expected) => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + expect(_getUpdatedSourceMapSettings({}, { sourcemaps })).toBe(expected); }); diff --git a/packages/tanstackstart-react/package.json b/packages/tanstackstart-react/package.json index 2b219559c7e8..0628c6b74294 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.17.0", - "@sentry/conventions": "^0.35.0", + "@sentry/conventions": "^0.36.0", "@sentry/core": "11.17.0", "@sentry/node": "11.17.0", "@sentry/react": "11.17.0", diff --git a/packages/tanstackstart-react/src/client/index.ts b/packages/tanstackstart-react/src/client/index.ts index ad7946b233b4..7c0a629c08c7 100644 --- a/packages/tanstackstart-react/src/client/index.ts +++ b/packages/tanstackstart-react/src/client/index.ts @@ -68,4 +68,4 @@ export function registerSentryServerTunnelRoute(_path: string): void {} * * @internal */ -export function _INTERNAL_setTunnelRoute(_tunnelRoute?: unknown, _basePath?: string): void {} +export function setTunnelRoute(_tunnelRoute?: unknown, _basePath?: string): void {} diff --git a/packages/tanstackstart-react/src/client/tunnelRoute.ts b/packages/tanstackstart-react/src/client/tunnelRoute.ts index e612d1b6219b..641b98bec7c2 100644 --- a/packages/tanstackstart-react/src/client/tunnelRoute.ts +++ b/packages/tanstackstart-react/src/client/tunnelRoute.ts @@ -1,4 +1,4 @@ -import { _INTERNAL_applyBrowserTunnelDefaults as applyBrowserTunnelDefaults, consoleSandbox } from '@sentry/core'; +import { applyBrowserTunnelDefaults, consoleSandbox } from '@sentry/core'; import type { BrowserOptions as ReactBrowserOptions } from '@sentry/react'; declare const __SENTRY_TANSTACKSTART_TUNNEL_ROUTE__: string | true | undefined; diff --git a/packages/tanstackstart-react/src/index.types.ts b/packages/tanstackstart-react/src/index.types.ts index b06807027a1c..49721046ba19 100644 --- a/packages/tanstackstart-react/src/index.types.ts +++ b/packages/tanstackstart-react/src/index.types.ts @@ -49,4 +49,4 @@ export declare const sentryGlobalRequestMiddleware: typeof serverSdk.sentryGloba export declare const sentryGlobalFunctionMiddleware: typeof serverSdk.sentryGlobalFunctionMiddleware; export declare const createSentryTunnelRoute: typeof serverSdk.createSentryTunnelRoute; export declare const registerSentryServerTunnelRoute: typeof serverSdk.registerSentryServerTunnelRoute; -export declare const _INTERNAL_setTunnelRoute: typeof serverSdk._INTERNAL_setTunnelRoute; +export declare const setTunnelRoute: typeof serverSdk.setTunnelRoute; diff --git a/packages/tanstackstart-react/src/server/index.ts b/packages/tanstackstart-react/src/server/index.ts index 611a216bde08..ba40c0b8223d 100644 --- a/packages/tanstackstart-react/src/server/index.ts +++ b/packages/tanstackstart-react/src/server/index.ts @@ -9,12 +9,9 @@ export { init } from './sdk'; export { wrapFetchWithSentry } from './wrapFetchWithSentry'; export { wrapMiddlewaresWithSentry } from './middleware'; export { sentryGlobalRequestMiddleware, sentryGlobalFunctionMiddleware } from './globalMiddleware'; +// Prefixed because only the code the Vite plugin injects imports it. export { addReleaseMetaTag as _INTERNAL_addReleaseMetaTag } from './releaseMetaTag'; -export { - createSentryTunnelRoute, - registerSentryServerTunnelRoute, - setTunnelRoute as _INTERNAL_setTunnelRoute, -} from './tunnelRoute'; +export { createSentryTunnelRoute, registerSentryServerTunnelRoute, setTunnelRoute } from './tunnelRoute'; /** * A no-op stub of the replay integration for the server. Router setup code is shared between client and server, diff --git a/packages/tanstackstart-react/src/server/sdk.ts b/packages/tanstackstart-react/src/server/sdk.ts index e7f7d62db2f4..0e90f3a50e44 100644 --- a/packages/tanstackstart-react/src/server/sdk.ts +++ b/packages/tanstackstart-react/src/server/sdk.ts @@ -1,10 +1,7 @@ import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, consoleSandbox, debug, getClient } from '@sentry/core'; import type { NodeClient, NodeOptions } from '@sentry/node'; -import { - _INTERNAL_installTunnelHooks as installTunnelHooks, - getDefaultIntegrations as getDefaultNodeIntegrations, - init as initNodeSdk, -} from '@sentry/node'; +import { getDefaultIntegrations as getDefaultNodeIntegrations, init as initNodeSdk } from '@sentry/node'; +import { instrumentTunnelServers } from '@sentry/server-utils'; /** * Initializes the server side of the TanStack Start React SDK @@ -47,7 +44,7 @@ export function init(options: NodeOptions): NodeClient | undefined { const client = initNodeSdk(sentryOptions); // `tunnelRoute` enables the tunnel when the server entry loads, after this preload, so the servers must be ready to // answer it already. - installTunnelHooks(); + instrumentTunnelServers(); return client; } diff --git a/packages/tanstackstart-react/src/server/tunnelRoute.ts b/packages/tanstackstart-react/src/server/tunnelRoute.ts index b1f87d3751fd..60bfea79f88e 100644 --- a/packages/tanstackstart-react/src/server/tunnelRoute.ts +++ b/packages/tanstackstart-react/src/server/tunnelRoute.ts @@ -1,10 +1,7 @@ import { URL_PATH } from '@sentry/conventions/attributes'; import type { ServerTunnelOptions } from '@sentry/core'; import { dsnToString, escapeStringForRegex, getClient, handleTunnelRequest } from '@sentry/core'; -import { - _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, - _INTERNAL_setTunnelDefaults as setTunnelDefaults, -} from '@sentry/core/server'; +import { forwardTunnelRequest, setTunnelDefaults } from '@sentry/core/server'; const registeredTunnelRoutePaths = new Set(); diff --git a/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts b/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts index 478c426f9ecb..b4abf2c0f61e 100644 --- a/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts +++ b/packages/tanstackstart-react/src/vite/nitroSourceMaps.ts @@ -1,9 +1,12 @@ import { readFile } from 'node:fs/promises'; import * as path from 'node:path'; import type { BuildEnvironmentOptions, Plugin, ResolvedConfig } from 'vite'; +import { sentryEnablesSourceMaps } from './sentryEnablesSourceMaps'; +import type { SentryTanstackStartOptions } from './sentryTanstackStart'; +import type { SourceMapState } from './sourceMaps'; /** `nitro/vite` builds the final server in an environment with this name. */ -const NITRO_ENVIRONMENT = 'nitro'; +export const NITRO_ENVIRONMENT = 'nitro'; /** The environment Vite passes to `applyToEnvironment`. */ export type PluginEnvironment = Parameters>[0]; @@ -27,12 +30,6 @@ type Nitro = { }; }; -/** - * Tells the plugin that deletes source maps after the upload whether the source maps of an environment are only - * there because Sentry enabled them. - */ -export type SourceMapsEnablerApi = { hasSentryEnabledSourceMaps(environmentName: string): boolean }; - /** * Whether Nitro bundles the output of this environment again. With `nitro/vite`, every server environment besides * `nitro` is a Nitro service, such as TanStack Start's `ssr` environment. @@ -49,11 +46,12 @@ export function isNitroService(environment: PluginEnvironment): boolean { * Keeps the sources in the source maps of Nitro's server build. Enables these source maps, unless a Nitro config * source or `build.rolldownOptions.output.sourcemap` of the Vite config sets them, or the Vite config disables them. */ -export function makeEnableNitroSourceMapsPlugin({ debug }: { debug?: boolean }): Plugin & { - api: SourceMapsEnablerApi; +export function makeEnableNitroSourceMapsPlugin( + options: SentryTanstackStartOptions, + state: SourceMapState, +): Plugin & { nitro: { name: string; setup: (nitro: Nitro) => void }; } { - let enabledSourceMaps = false; let viteConfigPreventsSourceMaps = false; return { @@ -61,10 +59,8 @@ export function makeEnableNitroSourceMapsPlugin({ debug }: { debug?: boolean }): apply: 'build', // The `config` hook must run before the one of `nitro/vite`, which runs the Nitro modules. enforce: 'pre', - api: { - hasSentryEnabledSourceMaps: environmentName => enabledSourceMaps && environmentName === NITRO_ENVIRONMENT, - }, config(viteConfig) { + state.sdkEnabledNitroSourceMaps = false; // Nitro overrides `build.sourcemap` for its environments, but `false` shows that the user wants no source maps. viteConfigPreventsSourceMaps = viteConfig.build?.sourcemap === false || hasOutputSourceMapSetting(viteConfig.build); @@ -79,13 +75,21 @@ export function makeEnableNitroSourceMapsPlugin({ debug }: { debug?: boolean }): const layers = nitro.options._c12?.layers; // Without the config sources, Sentry cannot tell if the user disabled source maps. - if (!layers || viteConfigPreventsSourceMaps || layers.some(layer => hasNitroSourceMapSetting(layer.config))) { + if ( + !layers || + viteConfigPreventsSourceMaps || + layers.some(layer => hasNitroSourceMapSetting(layer.config)) || + !sentryEnablesSourceMaps(options) + ) { return; } nitro.options.sourcemap = 'hidden'; - enabledSourceMaps = true; - logDebug(debug, "Enabled source map generation for the Nitro server build with `nitro.sourcemap: 'hidden'`."); + state.sdkEnabledNitroSourceMaps = true; + logDebug( + options.debug, + "Enabled source map generation for the Nitro server build with `nitro.sourcemap: 'hidden'`.", + ); }, }, }; @@ -118,7 +122,7 @@ export function makeComposeNitroServiceSourceMapsPlugin(): Plugin { } /** The output directories of the environments that Nitro bundles again. Empty in a build without Nitro. */ -export function getNitroServiceOutDirs(config: ResolvedConfig): string[] { +function getNitroServiceOutDirs(config: ResolvedConfig): string[] { if (!(NITRO_ENVIRONMENT in config.environments)) { return []; } @@ -140,9 +144,13 @@ function isInDirectory(file: string, directory: string): boolean { /** `output.sourcemap` of the bundler config overrides `build.sourcemap` in the build output. */ export function hasOutputSourceMapSetting( - build: Pick | undefined, + build: Pick | undefined, ): boolean { - return [build?.rolldownOptions?.output ?? []].flat().some(output => output.sourcemap !== undefined); + // Vite 8 still accepts `rollupOptions` in the user config. + // oxlint-disable-next-line typescript/no-deprecated + return [build?.rolldownOptions?.output ?? [], build?.rollupOptions?.output ?? []] + .flat() + .some(output => output.sourcemap !== undefined); } /** In a Nitro config, `output.sourcemap` of the bundler config overrides `sourcemap` in the build output. */ diff --git a/packages/tanstackstart-react/src/vite/sentryEnablesSourceMaps.ts b/packages/tanstackstart-react/src/vite/sentryEnablesSourceMaps.ts new file mode 100644 index 000000000000..3cf3121b020f --- /dev/null +++ b/packages/tanstackstart-react/src/vite/sentryEnablesSourceMaps.ts @@ -0,0 +1,12 @@ +import { hasSourceMapUploadCredentials } from '@sentry/bundler-plugins/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; +import type { SentryTanstackStartOptions } from './sentryTanstackStart'; + +/** + * Whether Sentry turns on source maps that the user did not set: when it can upload them, or when + * `sourcemaps.delete: false` keeps them for a manual upload. + */ +export function sentryEnablesSourceMaps(options: SentryTanstackStartOptions): boolean { + const { injectDebugIds, upload } = resolveSourceMapsFeatures(options.sourcemaps); + return (upload && hasSourceMapUploadCredentials(options)) || (options.sourcemaps?.delete === false && injectDebugIds); +} diff --git a/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts b/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts index 0a7d9a8e0d73..730ac94ee39f 100644 --- a/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts +++ b/packages/tanstackstart-react/src/vite/sentryTanstackStart.ts @@ -1,4 +1,5 @@ import type { BuildTimeOptionsBase, ReactComponentAnnotationOptions } from '@sentry/core'; +import { resolveSourceMapsFeatures } from '@sentry/core'; import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; import type { Plugin } from 'vite'; import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware'; @@ -6,7 +7,7 @@ import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugi import { getRuntimeRelease } from './release'; import { makeRoutePatternPlugin } from './routePatterns'; import { makeServerInstrumentationPlugin } from './serverInstrumentation'; -import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps'; +import { createSourceMapState, makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps'; import type { TunnelRouteOptions } from './tunnelRoute'; import { makeServerEntryTunnelPlugin, makeTunnelBasePathPlugin, makeTunnelRoutePlugin } from './tunnelRoute'; @@ -119,22 +120,31 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P // (CommonJS) deps via `ssr.noExternal`, which the `vite dev` SSR module runner can't evaluate. plugins.push(sentryOrchestrionPlugin({ buildTimeInstrumentation: options.buildTimeInstrumentation })); + // The bundler plugin decides on the source map setting in its own `config` hook, so the plugins that enable source + // maps come first. + const sourceMapState = createSourceMapState(); + const { injectDebugIds, upload } = resolveSourceMapsFeatures(options.sourcemaps); + // Sentry turns source maps on to upload them, or when `sourcemaps.delete: false` keeps them for a manual upload. + if (upload || (options.sourcemaps?.delete === false && injectDebugIds)) { + plugins.push( + ...makeEnableSourceMapsVitePlugin(options, sourceMapState), + makeEnableNitroSourceMapsPlugin(options, sourceMapState), + ); + } + // The server entry hands the release to the SDK at runtime, so it changes no content hash of the startup chunks. const bundlerPluginOptions = release ? { ...options, release: { ...options.release, name: release, inject: false } } : options; - plugins.push(...makeAddSentryVitePlugin(bundlerPluginOptions), makeComposeNitroServiceSourceMapsPlugin()); + plugins.push( + ...makeAddSentryVitePlugin(bundlerPluginOptions, sourceMapState), + makeComposeNitroServiceSourceMapsPlugin(), + ); // middleware auto-instrumentation if (options.autoInstrumentMiddleware !== false) { plugins.push(makeAutoInstrumentMiddlewarePlugin({ enabled: true, debug: options.debug })); } - // source maps - const sourceMapsDisabled = options.sourcemaps?.disable === true || options.sourcemaps?.disable === 'disable-upload'; - if (!sourceMapsDisabled) { - plugins.push(...makeEnableSourceMapsVitePlugin(options), makeEnableNitroSourceMapsPlugin(options)); - } - return plugins; } diff --git a/packages/tanstackstart-react/src/vite/sourceMaps.ts b/packages/tanstackstart-react/src/vite/sourceMaps.ts index c263011142ae..cc61338d7c5b 100644 --- a/packages/tanstackstart-react/src/vite/sourceMaps.ts +++ b/packages/tanstackstart-react/src/vite/sourceMaps.ts @@ -1,17 +1,15 @@ import { sentryVitePlugin } from '@sentry/bundler-plugins/vite'; import * as path from 'node:path'; -import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; +import type { Plugin, UserConfig } from 'vite'; import { - getNitroServiceOutDirs, hasOutputSourceMapSetting, isNitroService, + NITRO_ENVIRONMENT, type PluginEnvironment, - type SourceMapsEnablerApi, } from './nitroSourceMaps'; +import { sentryEnablesSourceMaps } from './sentryEnablesSourceMaps'; import type { SentryTanstackStartOptions } from './sentryTanstackStart'; -type FilesToDeleteAfterUpload = string | string[] | undefined; - /** TanStack Router and Start split route files into virtual modules, e.g. `index.tsx?tss-serverfn-split`. */ const TANSTACK_SPLIT_QUERY_REGEX = /\?ts[rs]-[^/]*$/; @@ -37,10 +35,37 @@ export function rewriteTanstackStartSource(source: string, _map: unknown, contex return path.relative(process.cwd(), absolutePath).split(path.sep).join('/'); } +/** Shared by the source map plugins of one build. */ +export type SourceMapState = { + /** The SDK set the top-level `build.sourcemap` to `'hidden'`. */ + sdkEnabledSourceMaps: boolean; + /** The SDK set the `sourcemap` option of Nitro to `'hidden'`. */ + sdkEnabledNitroSourceMaps: boolean; +}; + +export function createSourceMapState(): SourceMapState { + return { sdkEnabledSourceMaps: false, sdkEnabledNitroSourceMaps: false }; +} + +/** + * Whether the SDK turned on the source maps that the bundler plugin decides on. The plugin passes the name of an + * environment with its own `build.sourcemap`, and `undefined` for the top-level setting. With `nitro/vite`, the `ssr` + * service has its own setting too: Nitro reads its maps after the build, so they stay. + */ +function hasSdkEnabledSourceMaps(state: SourceMapState, environment: string | undefined): boolean { + if (environment === undefined) { + return state.sdkEnabledSourceMaps; + } + return environment === NITRO_ENVIRONMENT && state.sdkEnabledNitroSourceMaps; +} + /** * A Sentry plugin for adding the @sentry/bundler-plugins/vite to automatically upload source maps to Sentry. */ -export function makeAddSentryVitePlugin(options: SentryTanstackStartOptions): Plugin[] { +export function makeAddSentryVitePlugin( + options: SentryTanstackStartOptions, + state: SourceMapState = createSourceMapState(), +): Plugin[] { const { applicationKey, authToken, @@ -59,42 +84,6 @@ export function makeAddSentryVitePlugin(options: SentryTanstackStartOptions): Pl reactComponentAnnotation, } = options; - // defer resolving the filesToDeleteAfterUpload until we got access to the Vite config - let resolveFilesToDeleteAfterUpload: ((value: FilesToDeleteAfterUpload) => void) | undefined; - const filesToDeleteAfterUploadPromise = new Promise(resolve => { - resolveFilesToDeleteAfterUpload = resolve; - }); - - const configPlugin: Plugin = { - name: 'sentry-tanstackstart-files-to-delete-after-upload-plugin', - apply: 'build', - enforce: 'post', - configResolved(config) { - if (sourcemaps?.filesToDeleteAfterUpload !== undefined) { - resolveFilesToDeleteAfterUpload?.(sourcemaps.filesToDeleteAfterUpload); - return; - } - - if (!isVite8OrLater(this.meta.viteVersion)) { - // eslint-disable-next-line no-console - console.warn( - `[Sentry] TanStack Start requires Vite 8 or later. With an older Vite, Sentry deletes the source maps it generated only in \`build.outDir\` of each environment, so source maps in other output directories can stay in the build output.`, - ); - } - - const filesToDelete = getSentryEnabledSourceMapGlobs(config); - if (debug) { - // eslint-disable-next-line no-console - console.log( - filesToDelete.length > 0 - ? `[Sentry] Automatically setting \`sourcemaps.filesToDeleteAfterUpload: ${JSON.stringify(filesToDelete)}\` to delete generated source maps after they were uploaded to Sentry.` - : '[Sentry] No source maps are deleted after the upload, because Sentry did not enable source map generation for this build.', - ); - } - resolveFilesToDeleteAfterUpload?.(filesToDelete); - }, - }; - const sentryPlugins = sentryVitePlugin({ applicationKey, authToken: authToken ?? process.env.SENTRY_AUTH_TOKEN, @@ -110,10 +99,21 @@ export function makeAddSentryVitePlugin(options: SentryTanstackStartOptions): Pl sourcemaps: { assets: sourcemaps?.assets, disable: sourcemaps?.disable, + upload: sourcemaps?.upload, + injectDebugIds: sourcemaps?.injectDebugIds, + delete: sourcemaps?.delete, ignore: sourcemaps?.ignore, rewriteSources: sourcemaps?.rewriteSources ?? rewriteTanstackStartSource, resolveSourceMap: sourcemaps?.resolveSourceMap, - filesToDeleteAfterUpload: filesToDeleteAfterUploadPromise, + filesToDeleteAfterUpload: sourcemaps?.filesToDeleteAfterUpload, + // Called when the bundler plugin decides, after the SDK's enable plugins ran. + // The SDK never read the user's `deleteSourcemapsAfterUpload`. `delete` replaces it. + // A user's own `filesToDeleteAfterUpload` replaces the SDK's deletion. + deleteSourcemapsAfterUpload: + sourcemaps?.delete === undefined && sourcemaps?.filesToDeleteAfterUpload === undefined + ? environment => hasSdkEnabledSourceMaps(state, environment) || undefined + : undefined, + sdkEnabledSourceMaps: environment => hasSdkEnabledSourceMaps(state, environment), }, reactComponentAnnotation: { enabled: reactComponentAnnotation?.enabled ?? undefined, @@ -130,77 +130,28 @@ export function makeAddSentryVitePlugin(options: SentryTanstackStartOptions): Pl // Nitro bundles the output of its services again. Debug IDs from a service would end up in Nitro's output and point // to the service's source maps instead of Nitro's. - const scopedSentryPlugins = sentryPlugins.map(plugin => ({ + return sentryPlugins.map(plugin => ({ ...plugin, applyToEnvironment: (environment: PluginEnvironment) => !isNitroService(environment), })); - - return [configPlugin, ...scopedSentryPlugins]; -} - -/** - * Globs for the source maps in the output directories that only have source maps because Sentry enabled them. A glob - * such as `./**\/*.map` does not enter dot directories like `.output`, where Nitro puts the client build. - */ -function getSentryEnabledSourceMapGlobs(config: ResolvedConfig): string[] { - const serviceOutDirs = getNitroServiceOutDirs(config); - const outDirs = Object.entries(config.environments) - .filter(([name]) => hasSentryEnabledSourceMaps(config, name)) - .filter(([, environment]) => !hasOutputSourceMapSetting(environment.build)) - .flatMap(([, environment]) => getOutputDirs(config.root, environment.build)) - .filter(outDir => !serviceOutDirs.includes(outDir)); - - return [...new Set(outDirs)].map(outDir => { - const relativeOutDir = path.relative(process.cwd(), outDir).split(path.sep).join('/'); - return `${relativeOutDir || '.'}/**/*.map`; - }); -} - -/** `output.dir` takes precedence over `build.outDir`. Nitro sets only `output.dir` for its server build. */ -function getOutputDirs(root: string, build: ResolvedConfig['environments'][string]['build']): string[] { - // Vite 7 has no `rolldownOptions`. - const outputs = [build.rolldownOptions?.output ?? {}].flat(); - return outputs.map(output => path.resolve(root, output.dir ?? build.outDir)); -} - -/** Vite tells plugins its version since Vite 7. */ -function isVite8OrLater(viteVersion: string | undefined): boolean { - return Number(viteVersion?.split('.')[0]) >= 8; -} - -function hasSentryEnabledSourceMaps(config: ResolvedConfig, environmentName: string): boolean { - return config.plugins.some(plugin => - (plugin.api as Partial | undefined)?.hasSentryEnabledSourceMaps?.(environmentName), - ); } /** * A Sentry plugin for TanStack Start React to enable "hidden" source maps if they are unset. */ -export function makeEnableSourceMapsVitePlugin(options: SentryTanstackStartOptions): Plugin[] { - let enabledSourceMaps = false; - let environmentsWithSourceMapSetting: string[] = []; - - const api: SourceMapsEnablerApi = { - hasSentryEnabledSourceMaps: environmentName => - enabledSourceMaps && !environmentsWithSourceMapSetting.includes(environmentName), - }; - +export function makeEnableSourceMapsVitePlugin( + options: SentryTanstackStartOptions, + state: SourceMapState = createSourceMapState(), +): Plugin[] { return [ { name: 'sentry-tanstackstart-react-source-maps', apply: 'build', enforce: 'post', - api, config(viteConfig) { const sourcemap = getUpdatedSourceMapSettings(viteConfig, options); - enabledSourceMaps = sourcemap !== viteConfig.build?.sourcemap; - // The setting of an environment overrides the top-level setting, e.g. `nitro/vite` sets it for its environments. - environmentsWithSourceMapSetting = Object.entries(viteConfig.environments ?? {}) - .filter(([, environment]) => environment?.build?.sourcemap !== undefined) - .map(([name]) => name); - - return { build: { sourcemap } }; + state.sdkEnabledSourceMaps = sourcemap !== viteConfig.build?.sourcemap; + return sourcemap === undefined ? {} : { build: { sourcemap } }; }, }, ]; @@ -216,8 +167,10 @@ export function makeEnableSourceMapsVitePlugin(options: SentryTanstackStartOptio * - keep this setting (don't do anything - like deletion - besides uploading) * * 3. Users didn't set source maps generation - * - we enable 'hidden' source maps generation - * - configure `filesToDeleteAfterUpload` to delete these .map files after the upload (we emit a log about this) + * - we enable 'hidden' source maps generation when Sentry can upload them, or when `sourcemaps.delete: false` + * keeps them for a manual upload + * - without `sourcemaps.delete` we pass `deleteSourcemapsAfterUpload: true`, so the bundler plugin removes + * these .map files from the build output * * @internal Only exported for testing. */ @@ -264,11 +217,16 @@ export function getUpdatedSourceMapSettings( return undefined; } - // If the user did not specify a source map setting, we enable 'hidden' by default + if (!sentryEnablesSourceMaps(sentryPluginOptions ?? {})) { + return undefined; + } + if (debug) { // eslint-disable-next-line no-console console.log( - `[Sentry] Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be deleted after they were uploaded to Sentry.`, + `[Sentry] Enabled source map generation in the build options with \`${settingKey}: 'hidden'\`. The source maps will be ${ + sentryPluginOptions?.sourcemaps?.delete === false ? 'kept in' : 'removed from' + } the build output.`, ); } diff --git a/packages/tanstackstart-react/src/vite/tunnelRoute.ts b/packages/tanstackstart-react/src/vite/tunnelRoute.ts index 27c00efda7eb..aa3c36dd9e3a 100644 --- a/packages/tanstackstart-react/src/vite/tunnelRoute.ts +++ b/packages/tanstackstart-react/src/vite/tunnelRoute.ts @@ -1,9 +1,6 @@ import type { ServerTunnelOptions } from '@sentry/core'; -import { _INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath, stringifyForCodeInjection } from '@sentry/core'; -import { - _INTERNAL_forwardTunnelRequest as forwardTunnelRequest, - _INTERNAL_setTunnelDefaults as setTunnelDefaults, -} from '@sentry/core/server'; +import { normalizeTunnelBasePath, stringifyForCodeInjection } from '@sentry/core'; +import { forwardTunnelRequest, setTunnelDefaults } from '@sentry/core/server'; import type { Plugin } from 'vite'; import { getServerReleaseCode } from './release'; @@ -205,7 +202,7 @@ export function makeServerEntryTunnelPlugin( const setTunnelRoute = `setTunnelRoute(${tunnelOptions}, ${stringifyForCodeInjection(getBasePath())});\n`; if (!release) { - return `import { _INTERNAL_setTunnelRoute as setTunnelRoute } from ${stringifyForCodeInjection(sdk)}; + return `import { setTunnelRoute } from ${stringifyForCodeInjection(sdk)}; export * from ${original}; export { default } from ${original}; ${setTunnelRoute}`; @@ -213,7 +210,7 @@ ${setTunnelRoute}`; // The release module comes first, so the release is set when the original entry initializes the SDK. return `import ${stringifyForCodeInjection(RELEASE_MODULE_ID)}; -import { _INTERNAL_addReleaseMetaTag as addReleaseMetaTag, _INTERNAL_setTunnelRoute as setTunnelRoute } from ${stringifyForCodeInjection(sdk)}; +import { _INTERNAL_addReleaseMetaTag as addReleaseMetaTag, setTunnelRoute } from ${stringifyForCodeInjection(sdk)}; import serverEntry from ${original}; export * from ${original}; export default addReleaseMetaTag(serverEntry, ${stringifyForCodeInjection(release)}); diff --git a/packages/tanstackstart-react/test/server/setTunnelRoute.test.ts b/packages/tanstackstart-react/test/server/setTunnelRoute.test.ts index e8575146b42a..983a57fb4c95 100644 --- a/packages/tanstackstart-react/test/server/setTunnelRoute.test.ts +++ b/packages/tanstackstart-react/test/server/setTunnelRoute.test.ts @@ -1,6 +1,6 @@ import type { Client } from '@sentry/core'; import { getCurrentScope, getTunnelPath, makeDsn } from '@sentry/core'; -import { _INTERNAL_resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; +import { resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; import { afterEach, describe, expect, it } from 'vitest'; import { setTunnelRoute } from '../../src/server/tunnelRoute'; @@ -19,7 +19,7 @@ function setClient(managedTunnel: object | undefined): void { describe('setTunnelRoute', () => { afterEach(() => { getCurrentScope().setClient(undefined); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); it('enables `tunnelRoute` on the client like `serveTunnelIntegration` would, dropping its spans from the start', () => { diff --git a/packages/tanstackstart-react/test/vite/nitroSourceMaps.test.ts b/packages/tanstackstart-react/test/vite/nitroSourceMaps.test.ts index c3deb2e93e57..db4274ac2a20 100644 --- a/packages/tanstackstart-react/test/vite/nitroSourceMaps.test.ts +++ b/packages/tanstackstart-react/test/vite/nitroSourceMaps.test.ts @@ -10,6 +10,18 @@ import { makeEnableNitroSourceMapsPlugin, type PluginEnvironment, } from '../../src/vite/nitroSourceMaps'; +import { createSourceMapState } from '../../src/vite/sourceMaps'; + +// Sentry only turns source maps on when the plugin can upload them. +beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); const SSR_OUT_DIR = 'node_modules/.nitro/vite/services/ssr'; @@ -69,31 +81,39 @@ describe('Nitro source map config', () => { layers: NitroConfig[] | undefined, { debug, viteConfig = {} }: { debug?: boolean; viteConfig?: UserConfig } = {}, ) { - const plugin = makeEnableNitroSourceMapsPlugin({ debug }); + const state = createSourceMapState(); + const plugin = makeEnableNitroSourceMapsPlugin({ debug }, state); (plugin.config as (config: UserConfig) => void)(viteConfig); const nitro = { options: { sourcemap: false, experimental: {}, _c12: layers && { layers: layers.map(config => ({ config })) } }, }; plugin.nitro.setup(nitro); - return { plugin, nitroOptions: { sourcemap: nitro.options.sourcemap, experimental: nitro.options.experimental } }; + return { state, nitroOptions: { sourcemap: nitro.options.sourcemap, experimental: nitro.options.experimental } }; } it('enables hidden source maps with their sources when no config source sets them', () => { - const { plugin, nitroOptions } = setup([{}, {}]); + const { state, nitroOptions } = setup([{}, {}]); expect(nitroOptions).toEqual({ sourcemap: 'hidden', experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(true); - expect(plugin.api.hasSentryEnabledSourceMaps('client')).toBe(false); + expect(state.sdkEnabledNitroSourceMaps).toBe(true); + }); + + it('keeps the source maps off without an auth token, with the sources', () => { + vi.stubEnv('SENTRY_AUTH_TOKEN', ''); + const { state, nitroOptions } = setup([{}, {}]); + + expect(nitroOptions).toEqual({ sourcemap: false, experimental: { sourcemapMinify: false } }); + expect(state.sdkEnabledNitroSourceMaps).toBe(false); }); it.each([false, true, 'hidden'])( 'keeps the setting `sourcemap: %s` of a config source, with the sources', sourcemap => { - const { plugin, nitroOptions } = setup([{}, { sourcemap }]); + const { state, nitroOptions } = setup([{}, { sourcemap }]); expect(nitroOptions).toEqual({ sourcemap: false, experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(false); + expect(state.sdkEnabledNitroSourceMaps).toBe(false); }, ); @@ -101,34 +121,34 @@ describe('Nitro source map config', () => { { label: '`rollupConfig.output.sourcemap`', layer: { rollupConfig: { output: { sourcemap: true } } } }, { label: '`rolldownConfig.output.sourcemap`', layer: { rolldownConfig: { output: { sourcemap: false } } } }, ])('keeps the source maps when a config source sets $label', ({ layer }) => { - const { plugin, nitroOptions } = setup([{}, layer]); + const { state, nitroOptions } = setup([{}, layer]); expect(nitroOptions).toEqual({ sourcemap: false, experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(false); + expect(state.sdkEnabledNitroSourceMaps).toBe(false); }); it.each([ { label: '`build.sourcemap: false`', build: { sourcemap: false } }, { label: '`build.rolldownOptions.output.sourcemap`', build: { rolldownOptions: { output: { sourcemap: true } } } }, ])('keeps the source maps when the Vite config sets $label', ({ build }) => { - const { plugin, nitroOptions } = setup([{}], { viteConfig: { build } }); + const { state, nitroOptions } = setup([{}], { viteConfig: { build } }); expect(nitroOptions).toEqual({ sourcemap: false, experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(false); + expect(state.sdkEnabledNitroSourceMaps).toBe(false); }); it('enables source maps when the Vite config sets `build.sourcemap: true`, which Nitro overrides', () => { - const { plugin, nitroOptions } = setup([{}], { viteConfig: { build: { sourcemap: true } } }); + const { state, nitroOptions } = setup([{}], { viteConfig: { build: { sourcemap: true } } }); expect(nitroOptions).toEqual({ sourcemap: 'hidden', experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(true); + expect(state.sdkEnabledNitroSourceMaps).toBe(true); }); it('does not enable source maps when Nitro does not expose its config sources', () => { - const { plugin, nitroOptions } = setup(undefined); + const { state, nitroOptions } = setup(undefined); expect(nitroOptions).toEqual({ sourcemap: false, experimental: { sourcemapMinify: false } }); - expect(plugin.api.hasSentryEnabledSourceMaps('nitro')).toBe(false); + expect(state.sdkEnabledNitroSourceMaps).toBe(false); }); it('logs that it enabled source maps in debug mode', () => { diff --git a/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts b/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts index be54bc6fabc3..f2676730f560 100644 --- a/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts +++ b/packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts @@ -6,13 +6,6 @@ import { makeServerInstrumentationPlugin } from '../../src/vite/serverInstrument import { makeAddSentryVitePlugin } from '../../src/vite/sourceMaps'; import { makeServerEntryTunnelPlugin, makeTunnelRoutePlugin } from '../../src/vite/tunnelRoute'; -const mockSourceMapsConfigPlugin: Plugin = { - name: 'sentry-tanstackstart-files-to-delete-after-upload-plugin', - apply: 'build', - enforce: 'pre', - config: vi.fn(), -}; - const mockSentryVitePlugin: Plugin = { name: 'sentry-vite-debug-id-upload-plugin', writeBundle: vi.fn(), @@ -85,7 +78,8 @@ vi.mock('../../src/vite/routePatterns', () => ({ })); vi.mock('../../src/vite/sourceMaps', () => ({ - makeAddSentryVitePlugin: vi.fn(() => [mockSourceMapsConfigPlugin, mockSentryVitePlugin]), + createSourceMapState: vi.fn(() => ({ sdkEnabledSourceMaps: false, sdkEnabledNitroSourceMaps: false })), + makeAddSentryVitePlugin: vi.fn(() => [mockSentryVitePlugin]), makeEnableSourceMapsVitePlugin: vi.fn(() => [mockEnableSourceMapsPlugin]), })); @@ -133,11 +127,10 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, - mockSentryVitePlugin, - mockComposeNitroServiceSourceMapsPlugin, mockEnableSourceMapsPlugin, mockEnableNitroSourceMapsPlugin, + mockSentryVitePlugin, + mockComposeNitroServiceSourceMapsPlugin, ]); }); @@ -177,7 +170,6 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, ]); @@ -195,12 +187,32 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, ]); }); + it.each([{ upload: false }, { injectDebugIds: false }, { injectDebugIds: false, delete: false }])( + 'returns no enable source maps plugin with sourcemaps %j', + sourcemaps => { + const plugins = sentryTanstackStart({ autoInstrumentMiddleware: false, sourcemaps }); + + expect(plugins).not.toContain(mockEnableSourceMapsPlugin); + expect(plugins).not.toContain(mockEnableNitroSourceMapsPlugin); + expect(plugins).toContain(mockSentryVitePlugin); + }, + ); + + it.each([{ upload: false, delete: false }, { delete: true }, { disable: true, upload: true }])( + 'returns the enable source maps plugins with sourcemaps %j', + sourcemaps => { + const plugins = sentryTanstackStart({ autoInstrumentMiddleware: false, sourcemaps }); + + expect(plugins).toContain(mockEnableSourceMapsPlugin); + expect(plugins).toContain(mockEnableNitroSourceMapsPlugin); + }, + ); + it('returns Sentry Vite plugins and enable source maps plugin when sourcemaps.disable is false', () => { const plugins = sentryTanstackStart({ autoInstrumentMiddleware: false, @@ -213,11 +225,10 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, - mockSentryVitePlugin, - mockComposeNitroServiceSourceMapsPlugin, mockEnableSourceMapsPlugin, mockEnableNitroSourceMapsPlugin, + mockSentryVitePlugin, + mockComposeNitroServiceSourceMapsPlugin, ]); }); }); @@ -232,7 +243,6 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, mockMiddlewarePlugin, @@ -251,7 +261,6 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, mockMiddlewarePlugin, @@ -270,7 +279,6 @@ describe('sentryTanstackStart()', () => { mockServerEntryTunnelPlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, ]); @@ -299,10 +307,13 @@ describe('sentryTanstackStart()', () => { expect(getRuntimeRelease).toHaveBeenCalledWith(options); expect(makeServerEntryTunnelPlugin).toHaveBeenCalledWith(undefined, expect.any(Function), 'my-app@1.2.3'); expect(makeServerInstrumentationPlugin).toHaveBeenCalledWith({ debug: undefined, release: 'my-app@1.2.3' }); - expect(makeAddSentryVitePlugin).toHaveBeenCalledWith({ - release: { create: false, name: 'my-app@1.2.3', inject: false }, - sourcemaps: { disable: true }, - }); + expect(makeAddSentryVitePlugin).toHaveBeenCalledWith( + { + release: { create: false, name: 'my-app@1.2.3', inject: false }, + sourcemaps: { disable: true }, + }, + expect.any(Object), + ); }); it('passes the options to the bundler plugin as they are without a release to hand over', () => { @@ -311,7 +322,7 @@ describe('sentryTanstackStart()', () => { sentryTanstackStart(options); expect(makeServerEntryTunnelPlugin).toHaveBeenCalledWith(undefined, expect.any(Function), undefined); - expect(makeAddSentryVitePlugin).toHaveBeenCalledWith(options); + expect(makeAddSentryVitePlugin).toHaveBeenCalledWith(options, expect.any(Object)); }); it('resolves no release in development mode', () => { @@ -341,7 +352,6 @@ describe('sentryTanstackStart()', () => { mockTunnelRoutePlugin, mockServerInstrumentationPlugin, mockOrchestrionPlugin, - mockSourceMapsConfigPlugin, mockSentryVitePlugin, mockComposeNitroServiceSourceMapsPlugin, mockMiddlewarePlugin, diff --git a/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts b/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts index 7effcf3012f7..7d9230016013 100644 --- a/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts +++ b/packages/tanstackstart-react/test/vite/sourceMapScenarios.test.ts @@ -1,14 +1,25 @@ // @vitest-environment node -import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; -import type { BuildEnvironmentOptions, Plugin, ResolvedConfig, UserConfig } from 'vite'; +import type { SentryVitePluginInternalOptions } from '@sentry/bundler-plugins/vite'; +import type { BuildEnvironmentOptions, Plugin, UserConfig } from 'vite'; import { mergeConfig } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { sentryTanstackStart } from '../../src/vite/sentryTanstackStart'; +import { sentryTanstackStart, type SentryTanstackStartOptions } from '../../src/vite/sentryTanstackStart'; -let sentryVitePluginOptions: SentryVitePluginOptions | undefined; +// Sentry only turns source maps on when the plugin can upload them. +beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +let sentryVitePluginOptions: SentryVitePluginInternalOptions | undefined; vi.mock('@sentry/bundler-plugins/vite', () => ({ - sentryVitePlugin: (options: SentryVitePluginOptions) => { + sentryVitePlugin: (options: SentryVitePluginInternalOptions) => { sentryVitePluginOptions = options; return []; }, @@ -26,32 +37,44 @@ type NitroModulePlugin = Plugin & { nitro: { setup(nitro: unknown): void } }; const ENVIRONMENT_NAMES = ['client', 'ssr', 'nitro'] as const; -function findPlugin(plugins: Plugin[], name: string): T { - const plugin = plugins.find(plugin => plugin.name === name); - expect(plugin).toBeDefined(); - return plugin as T; -} - function callConfigHook(plugin: Plugin, config: UserConfig): UserConfig { return (plugin.config as (config: UserConfig) => UserConfig | undefined)(config) ?? {}; } /** The source map setting that applies to the output of an environment. */ function getOutputSourceMapSetting(build: BuildEnvironmentOptions): unknown { - const output = build.rolldownOptions?.output; - return (Array.isArray(output) ? undefined : output?.sourcemap) ?? build.sourcemap; + return getOwnOutputSourceMapSetting(build) ?? build.sourcemap; +} + +/** Like the bundler plugin, reads `rolldownOptions` and falls back to `rollupOptions`. */ +function getOwnOutputSourceMapSetting(build: BuildEnvironmentOptions): unknown { + const output = (build.rolldownOptions ?? build.rollupOptions)?.output; + return Array.isArray(output) ? undefined : output?.sourcemap; } /** * Runs Sentry's source map plugins in the order of a build with `nitro/vite`, which configures Nitro between the * `config` hooks of the Sentry plugins with `enforce: 'pre'` and `enforce: 'post'`. */ -async function build({ vite = {}, nitro: nitroOptions = {} }: { vite?: UserConfig; nitro?: NitroOptions }) { - const plugins = sentryTanstackStart({}); - const nitroPlugin = findPlugin(plugins, 'sentry-tanstackstart-nitro-source-maps'); +function build({ + vite = {}, + nitro: nitroOptions = {}, + options = {}, +}: { + vite?: UserConfig; + nitro?: NitroOptions; + options?: SentryTanstackStartOptions; +}) { + const plugins = sentryTanstackStart(options); + // Not added when source maps are disabled. + const nitroPlugin = plugins.find(plugin => plugin.name === 'sentry-tanstackstart-nitro-source-maps') as + | NitroModulePlugin + | undefined; const viteConfig = structuredClone(vite); - callConfigHook(nitroPlugin, viteConfig); + if (nitroPlugin) { + callConfigHook(nitroPlugin, viteConfig); + } const nitro = { options: { @@ -60,7 +83,7 @@ async function build({ vite = {}, nitro: nitroOptions = {} }: { vite?: UserConfi _c12: { layers: [{ config: nitroOptions }] }, }, }; - nitroPlugin.nitro.setup(nitro); + nitroPlugin?.nitro.setup(nitro); const nitroOutput = { ...nitroOptions.rollupConfig?.output, ...nitroOptions.rolldownConfig?.output }; const configWithNitro: UserConfig = mergeConfig(viteConfig, { @@ -75,37 +98,49 @@ async function build({ vite = {}, nitro: nitroOptions = {} }: { vite?: UserConfi }, }, }); - const userConfig: UserConfig = mergeConfig( - configWithNitro, - callConfigHook(findPlugin(plugins, 'sentry-tanstackstart-react-source-maps'), configWithNitro), - ); + const enablePlugin = plugins.find(plugin => plugin.name === 'sentry-tanstackstart-react-source-maps'); + const userConfig: UserConfig = enablePlugin + ? mergeConfig(configWithNitro, callConfigHook(enablePlugin, configWithNitro)) + : configWithNitro; const environments = Object.fromEntries( ENVIRONMENT_NAMES.map(name => [ name, - { - consumer: name === 'client' ? 'client' : 'server', - build: mergeConfig({ outDir: 'dist', ...userConfig.build }, userConfig.environments?.[name]?.build ?? {}), - }, + mergeConfig({ outDir: 'dist', ...userConfig.build }, userConfig.environments?.[name]?.build ?? {}), ]), - ); - const resolvedConfig = { root: process.cwd(), plugins, environments } as unknown as ResolvedConfig; - const deletionPlugin = findPlugin(plugins, 'sentry-tanstackstart-files-to-delete-after-upload-plugin'); - (deletionPlugin.configResolved as (this: unknown, config: ResolvedConfig) => void).call( - { meta: { viteVersion: '8.3.4' } }, - resolvedConfig, - ); + ) as Record<(typeof ENVIRONMENT_NAMES)[number], BuildEnvironmentOptions>; return { - client: getOutputSourceMapSetting(environments.client!.build), - ssr: getOutputSourceMapSetting(environments.ssr!.build), - nitro: getOutputSourceMapSetting(environments.nitro!.build), - filesToDelete: await sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload, + client: getOutputSourceMapSetting(environments.client), + ssr: getOutputSourceMapSetting(environments.ssr), + nitro: getOutputSourceMapSetting(environments.nitro), + deleted: ENVIRONMENT_NAMES.filter(name => isDeletedByBundlerPlugin(userConfig, name, environments[name])), }; } -const CLIENT_MAPS = '.output/public/**/*.map'; -const SERVER_MAPS = '.output/server/**/*.map'; +/** + * Mirrors the decision of the bundler plugin: it passes the name of an environment with its own `build.sourcemap` to + * the function options. It removes the maps of an output with its own `sourcemap` if they are hidden, or if + * `sdkEnabledSourceMaps` is true and they are not inline. + */ +function isDeletedByBundlerPlugin(userConfig: UserConfig, name: string, build: BuildEnvironmentOptions): boolean { + const environment = userConfig.environments?.[name]?.build?.sourcemap !== undefined ? name : undefined; + const { deleteSourcemapsAfterUpload, sdkEnabledSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; + const deleteOption = + typeof deleteSourcemapsAfterUpload === 'function' + ? deleteSourcemapsAfterUpload(environment) + : deleteSourcemapsAfterUpload; + const sdkEnabled = + typeof sdkEnabledSourceMaps === 'function' ? sdkEnabledSourceMaps(environment) : sdkEnabledSourceMaps; + const outputSourceMap = getOwnOutputSourceMapSetting(build); + if (deleteOption !== true) { + return false; + } + if (outputSourceMap === undefined) { + return build.sourcemap !== false; + } + return outputSourceMap === 'hidden' || (sdkEnabled === true && outputSourceMap === true); +} describe('source map scenarios of a build with Nitro', () => { beforeEach(() => { @@ -118,72 +153,154 @@ describe('source map scenarios of a build with Nitro', () => { vi.restoreAllMocks(); }); - it.each<{ label: string; vite?: UserConfig; nitro?: NitroOptions; expected: Awaited> }>([ + it.each<{ label: string; vite?: UserConfig; nitro?: NitroOptions; expected: ReturnType }>([ { label: 'nothing', - expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', filesToDelete: [CLIENT_MAPS, SERVER_MAPS] }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, }, { label: 'nitro({ sourcemap: true })', nitro: { sourcemap: true }, - expected: { client: 'hidden', ssr: true, nitro: true, filesToDelete: [CLIENT_MAPS] }, + expected: { client: 'hidden', ssr: true, nitro: true, deleted: ['client'] }, }, { label: 'nitro({ sourcemap: false })', nitro: { sourcemap: false }, - expected: { client: 'hidden', ssr: false, nitro: false, filesToDelete: [CLIENT_MAPS] }, + expected: { client: 'hidden', ssr: false, nitro: false, deleted: ['client'] }, }, { label: 'nitro({ rollupConfig: { output: { sourcemap: true } } })', nitro: { rollupConfig: { output: { sourcemap: true } } }, - expected: { client: 'hidden', ssr: false, nitro: true, filesToDelete: [CLIENT_MAPS] }, + expected: { client: 'hidden', ssr: false, nitro: true, deleted: ['client'] }, }, { label: 'nitro({ rolldownConfig: { output: { sourcemap: true } } })', nitro: { rolldownConfig: { output: { sourcemap: true } } }, - expected: { client: 'hidden', ssr: false, nitro: true, filesToDelete: [CLIENT_MAPS] }, + expected: { client: 'hidden', ssr: false, nitro: true, deleted: ['client'] }, }, { label: 'build.sourcemap: true', vite: { build: { sourcemap: true } }, - expected: { client: true, ssr: 'hidden', nitro: 'hidden', filesToDelete: [SERVER_MAPS] }, + expected: { client: true, ssr: 'hidden', nitro: 'hidden', deleted: ['nitro'] }, }, { label: "build.sourcemap: 'hidden'", vite: { build: { sourcemap: 'hidden' } }, - expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', filesToDelete: [SERVER_MAPS] }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: ['nitro'] }, }, { label: 'build.sourcemap: false', vite: { build: { sourcemap: false } }, - expected: { client: false, ssr: false, nitro: false, filesToDelete: [] }, + expected: { client: false, ssr: false, nitro: false, deleted: [] }, }, { label: 'environments.client.build.sourcemap: true', vite: { environments: { client: { build: { sourcemap: true } } } }, - expected: { client: true, ssr: 'hidden', nitro: 'hidden', filesToDelete: [SERVER_MAPS] }, + expected: { client: true, ssr: 'hidden', nitro: 'hidden', deleted: ['nitro'] }, }, { label: 'environments.client.build.sourcemap: false', vite: { environments: { client: { build: { sourcemap: false } } } }, - expected: { client: false, ssr: 'hidden', nitro: 'hidden', filesToDelete: [SERVER_MAPS] }, + expected: { client: false, ssr: 'hidden', nitro: 'hidden', deleted: ['nitro'] }, }, { label: 'build.rolldownOptions.output.sourcemap: true', vite: { build: { rolldownOptions: { output: { sourcemap: true } } } }, - expected: { client: true, ssr: true, nitro: true, filesToDelete: [] }, + expected: { client: true, ssr: true, nitro: true, deleted: [] }, }, { label: 'build.rolldownOptions.output.sourcemap: false', vite: { build: { rolldownOptions: { output: { sourcemap: false } } } }, - expected: { client: false, ssr: false, nitro: false, filesToDelete: [] }, + expected: { client: false, ssr: false, nitro: false, deleted: [] }, }, { label: 'environments.client.build.rolldownOptions.output.sourcemap: true', vite: { environments: { client: { build: { rolldownOptions: { output: { sourcemap: true } } } } } }, - expected: { client: true, ssr: 'hidden', nitro: 'hidden', filesToDelete: [SERVER_MAPS] }, + expected: { client: true, ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, + }, + { + label: "environments.client.build.rolldownOptions.output.sourcemap: 'hidden'", + vite: { environments: { client: { build: { rolldownOptions: { output: { sourcemap: 'hidden' } } } } } }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, + }, + { + label: 'environments.client.build.rollupOptions.output.sourcemap: true', + vite: { environments: { client: { build: { rollupOptions: { output: { sourcemap: true } } } } } }, + expected: { client: true, ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, + }, + { + label: "environments.client.build.rollupOptions.output.sourcemap: 'hidden'", + vite: { environments: { client: { build: { rollupOptions: { output: { sourcemap: 'hidden' } } } } } }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, + }, + ])('deletes the expected source maps when the user sets $label', scenario => { + expect(build(scenario)).toEqual(scenario.expected); + }); + + it.each<{ label: string; options: SentryTanstackStartOptions; expected: ReturnType }>([ + { + label: "sourcemaps.disable: 'disable-upload'", + options: { sourcemaps: { disable: 'disable-upload' } }, + expected: { client: undefined, ssr: false, nitro: false, deleted: [] }, }, - ])('keeps the source maps of the user and deletes the others when the user sets $label', async scenario => { - await expect(build(scenario)).resolves.toEqual(scenario.expected); + { + label: 'sourcemaps.deleteSourcemapsAfterUpload: false, which it ignores', + options: { sourcemaps: { deleteSourcemapsAfterUpload: false } }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: ['client', 'nitro'] }, + }, + { + label: 'sourcemaps.filesToDeleteAfterUpload', + options: { sourcemaps: { filesToDeleteAfterUpload: ['.output/**/*.map'] } }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden', deleted: [] }, + }, + ])('follows the Sentry option $label', ({ options, expected }) => { + expect(build({ options })).toEqual(expected); + }); + + it.each<{ + label: string; + sourcemaps: NonNullable; + expected: { client: unknown; ssr: unknown; nitro: unknown }; + }>([ + { + label: 'upload: false', + sourcemaps: { upload: false }, + expected: { client: undefined, ssr: false, nitro: false }, + }, + { + label: 'injectDebugIds: false', + sourcemaps: { injectDebugIds: false }, + expected: { client: undefined, ssr: false, nitro: false }, + }, + { + label: 'upload: false and delete: false', + sourcemaps: { upload: false, delete: false }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden' }, + }, + { + label: 'injectDebugIds: false and delete: false', + sourcemaps: { injectDebugIds: false, delete: false }, + expected: { client: undefined, ssr: false, nitro: false }, + }, + { + label: 'delete: false', + sourcemaps: { delete: false }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden' }, + }, + { + label: 'delete: true', + sourcemaps: { delete: true }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden' }, + }, + { + label: 'upload: true next to disable: true', + sourcemaps: { disable: true, upload: true }, + expected: { client: 'hidden', ssr: 'hidden', nitro: 'hidden' }, + }, + ])('turns the expected source maps on with sourcemaps $label', ({ sourcemaps, expected }) => { + const { client, ssr, nitro } = build({ options: { sourcemaps } }); + + expect({ client, ssr, nitro }).toEqual(expected); + expect(sentryVitePluginOptions?.sourcemaps).toEqual(expect.objectContaining(sourcemaps)); }); }); diff --git a/packages/tanstackstart-react/test/vite/sourceMaps.test.ts b/packages/tanstackstart-react/test/vite/sourceMaps.test.ts index 12ccae09beb2..a10bc169cc57 100644 --- a/packages/tanstackstart-react/test/vite/sourceMaps.test.ts +++ b/packages/tanstackstart-react/test/vite/sourceMaps.test.ts @@ -1,31 +1,43 @@ // @vitest-environment node -import type { SentryVitePluginOptions } from '@sentry/bundler-plugins/vite'; -import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; +import type { SentryVitePluginInternalOptions } from '@sentry/bundler-plugins/vite'; +import type { UserConfig } from 'vite'; +import type { SentryTanstackStartOptions } from '../../src/vite/sentryTanstackStart'; import { mergeConfig } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as path from 'path'; import { + createSourceMapState, getUpdatedSourceMapSettings, makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin, rewriteTanstackStartSource, } from '../../src/vite/sourceMaps'; -import type { SentryTanstackStartOptions } from '../../src/vite/sentryTanstackStart'; + +// Sentry only turns source maps on when the plugin can upload them. +beforeEach(() => { + vi.stubEnv('SENTRY_AUTH_TOKEN', 'token'); + vi.stubEnv('SENTRY_ORG', 'org'); + vi.stubEnv('SENTRY_PROJECT', 'project'); +}); + +afterEach(() => { + vi.unstubAllEnvs(); +}); const mockedSentryVitePlugin = { name: 'sentry-vite-debug-id-upload-plugin', writeBundle: vi.fn(), }; -let sentryVitePluginOptions: SentryVitePluginOptions | undefined; +let sentryVitePluginOptions: SentryVitePluginInternalOptions | undefined; -const sentryVitePluginSpy = vi.fn((options: SentryVitePluginOptions) => { +const sentryVitePluginSpy = vi.fn((options: SentryVitePluginInternalOptions) => { sentryVitePluginOptions = options; return [mockedSentryVitePlugin]; }); vi.mock('@sentry/bundler-plugins/vite', () => ({ - sentryVitePlugin: (options: SentryVitePluginOptions) => sentryVitePluginSpy(options), + sentryVitePlugin: (options: SentryVitePluginInternalOptions) => sentryVitePluginSpy(options), })); beforeEach(() => { @@ -47,34 +59,32 @@ describe('makeEnableSourceMapsVitePlugin()', () => { }); it.each([ - { label: 'the user set no source maps', userConfig: {}, expected: { client: true, ssr: true } }, + { label: 'the user set no source maps', userConfig: {}, expected: true }, + { label: 'the user set `build.sourcemap`', userConfig: { build: { sourcemap: true } }, expected: false }, + { label: 'the user set `build.sourcemap: false`', userConfig: { build: { sourcemap: false } }, expected: false }, { - label: 'the user set `build.sourcemap`', - userConfig: { build: { sourcemap: true } }, - expected: { client: false, ssr: false }, + label: 'the user set `build.rolldownOptions.output.sourcemap`', + userConfig: { build: { rolldownOptions: { output: { sourcemap: true } } } }, + expected: false, }, { - label: 'the user set the source maps of an environment', - userConfig: { environments: { client: { build: { sourcemap: true } } } }, - expected: { client: false, ssr: true }, + label: "an environment output sets `sourcemap: 'hidden'`", + userConfig: { environments: { client: { build: { rolldownOptions: { output: { sourcemap: 'hidden' } } } } } }, + expected: true, }, { - label: 'the user set `build.rolldownOptions.output.sourcemap`', - userConfig: { build: { rolldownOptions: { output: { sourcemap: true } } } }, - expected: { client: false, ssr: false }, + label: 'an environment output sets `sourcemap: true`', + userConfig: { environments: { client: { build: { rollupOptions: { output: { sourcemap: true } } } } } }, + expected: true, }, - ] as const)( - 'tells which environments only have source maps because of Sentry when $label', - ({ userConfig, expected }) => { - const plugin = makeEnableSourceMapsVitePlugin({})[0]!; - (plugin.config as (config: UserConfig) => UserConfig)(structuredClone(userConfig) as UserConfig); + ] as const)('records whether it enabled the source maps when $label', ({ userConfig, expected }) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const state = { ...createSourceMapState(), sdkEnabledSourceMaps: !expected }; + const plugin = makeEnableSourceMapsVitePlugin({}, state)[0]!; + (plugin.config as (config: UserConfig) => UserConfig)(structuredClone(userConfig) as UserConfig); - expect({ - client: plugin.api.hasSentryEnabledSourceMaps('client'), - ssr: plugin.api.hasSentryEnabledSourceMaps('ssr'), - }).toEqual(expected); - }, - ); + expect(state.sdkEnabledSourceMaps).toBe(expected); + }); it.each([undefined, false, true, 'hidden', 'inline'] as const)( 'preserves user config without duplicating arrays when sourcemap is %s', @@ -106,9 +116,9 @@ describe('makeEnableSourceMapsVitePlugin()', () => { }); describe('makeAddSentryVitePlugin()', () => { - it('passes user-specified vite plugin options to vite plugin', async () => { + it('passes user-specified vite plugin options to vite plugin', () => { const errorHandler = vi.fn(); - const plugins = makeAddSentryVitePlugin({ + makeAddSentryVitePlugin({ org: 'my-org', authToken: 'my-token', sentryUrl: 'https://custom.sentry.io', @@ -133,16 +143,7 @@ describe('makeAddSentryVitePlugin()', () => { }, }); - // The filesToDeleteAfterUpload is now a Promise that resolves when the config hook runs - expect(sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload).toBeInstanceOf(Promise); - - // Trigger the configResolved hook to resolve the Promise - const configPlugin = plugins.find(p => p.name === 'sentry-tanstackstart-files-to-delete-after-upload-plugin'); - (configPlugin?.configResolved as (config: ResolvedConfig) => void)({} as ResolvedConfig); - - // Verify the Promise resolves to the user-specified value - const resolvedFilesToDelete = await sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload; - expect(resolvedFilesToDelete).toEqual(['baz/*.js']); + expect(sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(['baz/*.js']); expect(sentryVitePluginSpy).toHaveBeenCalledWith( expect.objectContaining({ @@ -195,21 +196,6 @@ describe('makeAddSentryVitePlugin()', () => { ); }); - it('returns Sentry Vite plugins and config plugin', () => { - const plugins = makeAddSentryVitePlugin({ - org: 'my-org', - authToken: 'my-token', - }); - - expect(plugins.length).toBeGreaterThanOrEqual(2); - - const configPlugin = plugins.find(p => p.name === 'sentry-tanstackstart-files-to-delete-after-upload-plugin'); - expect(configPlugin).toBeDefined(); - expect(configPlugin?.apply).toBe('build'); - expect(configPlugin?.enforce).toBe('post'); - expect(typeof configPlugin?.configResolved).toBe('function'); - }); - it.each([ { name: 'client', consumer: 'client', expected: true }, { name: 'ssr', consumer: 'server', expected: false }, @@ -227,161 +213,120 @@ describe('makeAddSentryVitePlugin()', () => { }, ); - describe('default filesToDeleteAfterUpload', () => { - type TestEnvironment = { - consumer: 'client' | 'server'; - outDir: string; - outputDir?: string; - outputSourceMap?: boolean; - }; - - const NITRO_ENVIRONMENTS: Record = { - client: { consumer: 'client', outDir: '.output/public' }, - ssr: { consumer: 'server', outDir: 'node_modules/.nitro/vite/services/ssr' }, - // Nitro sets the output directory of its server build with `output.dir` only. - nitro: { consumer: 'server', outDir: 'dist', outputDir: '.output/server' }, - }; - - /** A plugin that enabled the source maps of the given environments, like the Sentry plugins that enable them. */ - function sourceMapsEnabler(environmentNames: string[]): Plugin { + describe('deleteSourcemapsAfterUpload', () => { + /** Calls the function options like the bundler plugin, which passes an environment with its own setting. */ + function decide(environment?: string) { + const { deleteSourcemapsAfterUpload, sdkEnabledSourceMaps } = sentryVitePluginOptions?.sourcemaps ?? {}; return { - name: 'source-maps-enabler', - api: { hasSentryEnabledSourceMaps: (environmentName: string) => environmentNames.includes(environmentName) }, + delete: + typeof deleteSourcemapsAfterUpload === 'function' + ? deleteSourcemapsAfterUpload(environment) + : deleteSourcemapsAfterUpload, + sdkEnabled: + typeof sdkEnabledSourceMaps === 'function' ? sdkEnabledSourceMaps(environment) : sdkEnabledSourceMaps, }; } - function resolveFilesToDelete( - environments: Record, - { - sentryEnabledEnvironments = Object.keys(environments), - options = {}, - viteVersion = '8.3.1', - }: { sentryEnabledEnvironments?: string[]; options?: SentryTanstackStartOptions; viteVersion?: string } = {}, - ): Promise { - const isVite7 = viteVersion.startsWith('7.'); - const plugins = makeAddSentryVitePlugin(options); - const config = { - root: process.cwd(), - plugins: [...plugins, sourceMapsEnabler(sentryEnabledEnvironments)], - environments: Object.fromEntries( - Object.entries(environments).map(([name, { consumer, outDir, outputDir, outputSourceMap }]) => [ - name, - { - consumer, - build: { - outDir, - ...(!isVite7 && { rolldownOptions: { output: { dir: outputDir, sourcemap: outputSourceMap } } }), - }, - }, - ]), - ), - } as unknown as ResolvedConfig; - - const configPlugin = plugins.find(p => p.name === 'sentry-tanstackstart-files-to-delete-after-upload-plugin'); - (configPlugin?.configResolved as (this: unknown, config: ResolvedConfig) => void).call( - { meta: { viteVersion } }, - config, - ); + it('reads the state when the bundler plugin decides, not when the plugin is created', () => { + const state = createSourceMapState(); + makeAddSentryVitePlugin({}, state); - return Promise.resolve(sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload); - } + expect(decide()).toEqual({ delete: undefined, sdkEnabled: false }); + state.sdkEnabledSourceMaps = true; + expect(decide()).toEqual({ delete: true, sdkEnabled: true }); + }); it.each([ { - label: 'a Nitro build, but not in the Nitro service output', - environments: NITRO_ENVIRONMENTS, - expected: ['.output/public/**/*.map', '.output/server/**/*.map'], + label: 'the SDK enabled the top-level source maps', + state: { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: false }, + expected: { top: true, ssr: undefined, nitro: undefined }, }, { - label: 'a build without Nitro', - environments: { - client: { consumer: 'client', outDir: 'dist/client' }, - ssr: { consumer: 'server', outDir: 'dist/server' }, - }, - expected: ['dist/client/**/*.map', 'dist/server/**/*.map'], + label: 'the SDK enabled the Nitro source maps', + state: { sdkEnabledSourceMaps: false, sdkEnabledNitroSourceMaps: true }, + expected: { top: undefined, ssr: undefined, nitro: true }, }, { - label: 'environments that share an output directory once', - environments: { - client: { consumer: 'client', outDir: 'dist' }, - ssr: { consumer: 'server', outDir: 'dist' }, - }, - expected: ['dist/**/*.map'], + label: 'the SDK enabled both', + state: { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }, + expected: { top: true, ssr: undefined, nitro: true }, }, - ] as const)('deletes the source maps in each output directory of $label', async ({ environments, expected }) => { - await expect(resolveFilesToDelete(environments)).resolves.toEqual(expected); + { + label: 'the user enabled all source maps', + state: { sdkEnabledSourceMaps: false, sdkEnabledNitroSourceMaps: false }, + expected: { top: undefined, ssr: undefined, nitro: undefined }, + }, + ])('asks for deletion of the source maps the SDK enabled when $label', ({ state, expected }) => { + makeAddSentryVitePlugin({}, state); + + expect({ top: decide().delete, ssr: decide('ssr').delete, nitro: decide('nitro').delete }).toEqual(expected); + expect({ + top: decide().sdkEnabled, + ssr: decide('ssr').sdkEnabled, + nitro: decide('nitro').sdkEnabled, + }).toEqual({ top: expected.top === true, ssr: false, nitro: expected.nitro === true }); + }); + + // A client environment with its own setting was set by the user, because the SDK sets only the top level. + it('keeps the source maps of an environment that the user configured', () => { + makeAddSentryVitePlugin({}, { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }); + + expect(decide('client')).toEqual({ delete: undefined, sdkEnabled: false }); }); it.each([ - { label: 'the client', sentryEnabledEnvironments: ['nitro'], expected: ['.output/server/**/*.map'] }, - { label: 'the Nitro server', sentryEnabledEnvironments: ['client'], expected: ['.output/public/**/*.map'] }, - { label: 'any environment', sentryEnabledEnvironments: [], expected: [] }, + [true, false, undefined], + [false, true, true], ])( - 'keeps the source maps of $label when Sentry did not enable them', - async ({ sentryEnabledEnvironments, expected }) => { - await expect(resolveFilesToDelete(NITRO_ENVIRONMENTS, { sentryEnabledEnvironments })).resolves.toEqual( - expected, + 'ignores a user-set `deleteSourcemapsAfterUpload: %s` (SDK enabled the maps: %s)', + (value, sdkEnabled, expected) => { + makeAddSentryVitePlugin( + { sourcemaps: { deleteSourcemapsAfterUpload: value } }, + { sdkEnabledSourceMaps: sdkEnabled, sdkEnabledNitroSourceMaps: sdkEnabled }, ); - }, - ); - - it.each([true, false])( - 'keeps the source maps of an environment that sets `output.sourcemap: %s`', - async outputSourceMap => { - const environments = { - ...NITRO_ENVIRONMENTS, - client: { ...NITRO_ENVIRONMENTS.client!, outputSourceMap }, - }; - await expect(resolveFilesToDelete(environments)).resolves.toEqual(['.output/server/**/*.map']); + expect([decide().delete, decide('ssr').delete, decide('nitro').delete]).toEqual([ + expected, + undefined, + expected, + ]); }, ); - it('warns and deletes the source maps in `build.outDir` with Vite 7', async () => { - const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - const environments = { - client: { consumer: 'client', outDir: 'dist/client' }, - ssr: { consumer: 'server', outDir: 'dist/server' }, - } as const; - - await expect(resolveFilesToDelete(environments, { viteVersion: '7.3.2' })).resolves.toEqual([ - 'dist/client/**/*.map', - 'dist/server/**/*.map', - ]); - expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('TanStack Start requires Vite 8 or later.')); - consoleWarnSpy.mockRestore(); - }); + it('passes the new source map options through', () => { + makeAddSentryVitePlugin({ sourcemaps: { upload: false, injectDebugIds: true, delete: false } }); - it('does not warn with Vite 8', async () => { - const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - - await resolveFilesToDelete(NITRO_ENVIRONMENTS); - - expect(consoleWarnSpy).not.toHaveBeenCalled(); - consoleWarnSpy.mockRestore(); - }); - - it('logs the default in debug mode', async () => { - const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); - - await resolveFilesToDelete(NITRO_ENVIRONMENTS, { options: { debug: true } }); - - expect(consoleSpy).toHaveBeenCalledWith( - '[Sentry] Automatically setting `sourcemaps.filesToDeleteAfterUpload: [".output/public/**/*.map",".output/server/**/*.map"]` to delete generated source maps after they were uploaded to Sentry.', + expect(sentryVitePluginOptions?.sourcemaps).toEqual( + expect.objectContaining({ upload: false, injectDebugIds: true, delete: false }), ); - consoleSpy.mockRestore(); }); - it('logs that it deletes no source maps when Sentry enabled none', async () => { - const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + it.each([{ delete: true }, { delete: false, deleteSourcemapsAfterUpload: true }] as const)( + 'passes no `deleteSourcemapsAfterUpload` with %j', + sourcemaps => { + makeAddSentryVitePlugin({ sourcemaps }, { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }); - await resolveFilesToDelete(NITRO_ENVIRONMENTS, { sentryEnabledEnvironments: [], options: { debug: true } }); + expect(sentryVitePluginOptions?.sourcemaps?.deleteSourcemapsAfterUpload).toBeUndefined(); + }, + ); - expect(consoleSpy).toHaveBeenCalledWith( - '[Sentry] No source maps are deleted after the upload, because Sentry did not enable source map generation for this build.', - ); - consoleSpy.mockRestore(); - }); + it.each([[['dist/**/*.map']], [[]]])( + 'lets a user-set `filesToDeleteAfterUpload: %j` replace the deletion', + files => { + makeAddSentryVitePlugin( + { sourcemaps: { filesToDeleteAfterUpload: files } }, + { sdkEnabledSourceMaps: true, sdkEnabledNitroSourceMaps: true }, + ); + + expect(sentryVitePluginOptions?.sourcemaps?.filesToDeleteAfterUpload).toEqual(files); + expect([decide().delete, decide('ssr').delete, decide('nitro').delete]).toEqual([ + undefined, + undefined, + undefined, + ]); + }, + ); }); it('passes rewriteSources to the vite plugin', () => { @@ -508,6 +453,42 @@ describe('getUpdatedSourceMapSettings', () => { expect(result).toBe('hidden'); }); + + it.each([true, false])('should set sourcemap to hidden with `sourcemaps.delete: %s`', value => { + expect(getUpdatedSourceMapSettings({}, { sourcemaps: { delete: value } })).toBe('hidden'); + }); + + it.each<[Record, SentryTanstackStartOptions, 'hidden' | undefined]>([ + [{ SENTRY_AUTH_TOKEN: '' }, {}, undefined], + [{ SENTRY_ORG: '' }, {}, undefined], + [{ SENTRY_PROJECT: '' }, {}, undefined], + [{ SENTRY_AUTH_TOKEN: '' }, { authToken: 'token' }, 'hidden'], + [{ SENTRY_ORG: '', SENTRY_AUTH_TOKEN: 'sntrys_token' }, {}, 'hidden'], + [{ SENTRY_AUTH_TOKEN: '' }, { sourcemaps: { delete: false } }, 'hidden'], + [{ SENTRY_AUTH_TOKEN: '' }, { sourcemaps: { upload: false, delete: false } }, 'hidden'], + ])('with the environment %j and the options %j it sets unset source maps to %s', (env, options, expected) => { + for (const [key, value] of Object.entries(env)) { + vi.stubEnv(key, value); + } + expect(getUpdatedSourceMapSettings({}, options)).toBe(expected); + }); + + it.each([ + [undefined, 'removed from'], + [true, 'removed from'], + [false, 'kept in'], + ] as const)('should log where the source maps go with `sourcemaps.delete: %s`', (value, expected) => { + getUpdatedSourceMapSettings({}, { debug: true, sourcemaps: { delete: value } }); + + // eslint-disable-next-line no-console + expect(console.log).toHaveBeenCalledWith( + `[Sentry] Enabled source map generation in the build options with \`vite.build.sourcemap: 'hidden'\`. The source maps will be ${expected} the build output.`, + ); + }); + + it('should keep an explicit setting with `sourcemaps.delete: true`', () => { + expect(getUpdatedSourceMapSettings({ build: { sourcemap: true } }, { sourcemaps: { delete: true } })).toBe(true); + }); }); describe('rewriteTanstackStartSource', () => { diff --git a/packages/tanstackstart-react/test/vite/tunnelRoute.test.ts b/packages/tanstackstart-react/test/vite/tunnelRoute.test.ts index 6bffffb37435..6aee3bb58ed3 100644 --- a/packages/tanstackstart-react/test/vite/tunnelRoute.test.ts +++ b/packages/tanstackstart-react/test/vite/tunnelRoute.test.ts @@ -1,6 +1,6 @@ import type { Client } from '@sentry/core'; import { getCurrentScope, getTunnelPath, makeDsn } from '@sentry/core'; -import { _INTERNAL_resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; +import { resetTunnelDefaults, serveTunnelIntegration } from '@sentry/core/server'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { @@ -120,7 +120,7 @@ describe('server entry tunnel vite plugin', () => { const load = setup(undefined, '', undefined, 'my-app@1.2.3'); expect(await load(USER_ENTRY)).toBe(`import "virtual:sentry-tanstackstart-release"; -import { _INTERNAL_addReleaseMetaTag as addReleaseMetaTag, _INTERNAL_setTunnelRoute as setTunnelRoute } from "${SDK_ID}"; +import { _INTERNAL_addReleaseMetaTag as addReleaseMetaTag, setTunnelRoute } from "${SDK_ID}"; import serverEntry from "${USER_ENTRY}?sentry-tunnel-original"; export * from "${USER_ENTRY}?sentry-tunnel-original"; export default addReleaseMetaTag(serverEntry, "my-app@1.2.3"); @@ -161,7 +161,7 @@ setTunnelRoute(undefined, ""); const load = setup(undefined, '', resolve); expect(await load('/app/node_modules/@tanstack/react-start/dist/default-entry/esm/server.js')).toContain( - `import { _INTERNAL_setTunnelRoute as setTunnelRoute } from "${SDK_ID}";`, + `import { setTunnelRoute } from "${SDK_ID}";`, ); expect(resolve).toHaveBeenCalledWith('@sentry/tanstackstart-react', '/app/package.json', { skipSelf: true }); }); @@ -206,7 +206,7 @@ describe('server entry tunnel vite plugin in `vite dev`', () => { afterEach(() => { getCurrentScope().setClient(undefined); - _INTERNAL_resetTunnelDefaults(); + resetTunnelDefaults(); }); /** Sets a client, with `serveTunnelIntegration` set up when `managedTunnel` is given. */ diff --git a/packages/vercel-edge/.oxlintrc.json b/packages/vercel-edge/.oxlintrc.json index 4a3a8ff955c7..56afe1d9a078 100644 --- a/packages/vercel-edge/.oxlintrc.json +++ b/packages/vercel-edge/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "jsPlugins": [ { "name": "sdk", diff --git a/packages/vercel-edge/src/logs/exports.ts b/packages/vercel-edge/src/logs/exports.ts index 5a7e065eb3ee..e375098d4620 100644 --- a/packages/vercel-edge/src/logs/exports.ts +++ b/packages/vercel-edge/src/logs/exports.ts @@ -1,5 +1,5 @@ import type { Log, LogSeverityLevel, ParameterizedString } from '@sentry/core'; -import { _INTERNAL_captureLog } from '@sentry/core'; +import { captureLogEvent } from '@sentry/core'; /** * Capture a log with the given level. @@ -15,7 +15,7 @@ function captureLog( attributes?: Log['attributes'], severityNumber?: Log['severityNumber'], ): void { - _INTERNAL_captureLog({ level, message, attributes, severityNumber }); + captureLogEvent({ level, message, attributes, severityNumber }); } /** diff --git a/packages/vue/.oxlintrc.json b/packages/vue/.oxlintrc.json index ed17064b99bc..2082a098f763 100644 --- a/packages/vue/.oxlintrc.json +++ b/packages/vue/.oxlintrc.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"], + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"], "env": { "browser": true } diff --git a/packages/vue/package.json b/packages/vue/package.json index 9539de1df752..80d18837081a 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -46,7 +46,7 @@ "dependencies": { "@sentry/browser": "11.17.0", "@sentry/core": "11.17.0", - "@sentry/conventions": "^0.35.0" + "@sentry/conventions": "^0.36.0" }, "peerDependencies": { "@tanstack/vue-router": "^1.64.0", diff --git a/packages/vue/src/integration.ts b/packages/vue/src/integration.ts index 21835f8234dc..a29831185b81 100644 --- a/packages/vue/src/integration.ts +++ b/packages/vue/src/integration.ts @@ -43,6 +43,7 @@ export const vueIntegration = defineIntegration((integrationOptions: Partial getRouterFromApp(app) : captureRouterFromVue(Vue!); setRouteProvider(createVueRouteProvider(getRouter), client); } diff --git a/packages/wasm/.oxlintrc.json b/packages/wasm/.oxlintrc.json index 4cd4930fa802..c996f1bd946a 100644 --- a/packages/wasm/.oxlintrc.json +++ b/packages/wasm/.oxlintrc.json @@ -1,4 +1,4 @@ { "$schema": "../../node_modules/oxlint/configuration_schema.json", - "extends": ["../../.oxlintrc.base.json"] + "extends": ["../../.oxlintrc.base.json", "../../.oxlintrc.no-node-builtins.json"] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ebbe5574343f..b134682d772d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -296,8 +296,8 @@ importers: specifier: 11.17.0 version: link:../../packages/browser-utils '@sentry/conventions': - specifier: 0.35.0 - version: 0.35.0 + specifier: 0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../../packages/core @@ -308,11 +308,11 @@ importers: specifier: 11.17.0 version: link:../../packages/replay-canvas '@sentry/rrweb': - specifier: 2.46.0 - version: 2.46.0 + specifier: 2.47.0 + version: 2.47.0 '@sentry/rrweb-types': - specifier: ^2.46.0 - version: 2.46.0 + specifier: ^2.47.0 + version: 2.47.0 '@sentry/wasm': specifier: 11.17.0 version: link:../../packages/wasm @@ -356,8 +356,8 @@ importers: specifier: 11.17.0 version: link:../../packages/bun '@sentry/conventions': - specifier: 0.35.0 - version: 0.35.0 + specifier: 0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../../packages/core @@ -527,8 +527,8 @@ importers: specifier: 11.17.0 version: link:../../packages/cloudflare '@sentry/conventions': - specifier: 0.35.0 - version: 0.35.0 + specifier: 0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../../packages/core @@ -563,8 +563,8 @@ importers: specifier: 11.17.0 version: link:../node-integration-tests '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../../packages/core @@ -703,8 +703,8 @@ importers: specifier: 11.17.0 version: link:../../packages/aws-serverless '@sentry/conventions': - specifier: 0.35.0 - version: 0.35.0 + specifier: 0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../../packages/core @@ -891,6 +891,9 @@ importers: ws: specifier: ^8.20.1 version: 8.22.2 + yaml: + specifier: ^2.9.0 + version: 2.9.0 yargs: specifier: ^18.2.0 version: 18.2.0 @@ -936,8 +939,8 @@ importers: dev-packages/test-utils: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 express: specifier: ^4.22.3 version: 4.22.3(supports-color@10.0.0) @@ -967,8 +970,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1031,8 +1034,8 @@ importers: specifier: 11.17.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1049,6 +1052,12 @@ importers: '@sentry-internal/rollup-utils': specifier: 11.17.0 version: link:../../dev-packages/rollup-utils + '@sentry/bun': + specifier: 11.17.0 + version: link:../bun + '@sentry/deno': + specifier: 11.17.0 + version: link:../deno astro: specifier: ^4.16.19 version: 4.16.19(@types/node@20.19.43)(less@4.2.0(supports-color@10.0.0))(lightningcss@1.33.0)(rollup@4.68.3)(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(supports-color@10.0.0)(terser@5.51.2)(typescript@7.0.2) @@ -1059,8 +1068,8 @@ importers: packages/aws-serverless: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1093,8 +1102,8 @@ importers: specifier: 11.17.0 version: link:../browser-utils '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1121,8 +1130,8 @@ importers: packages/browser-utils: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1140,8 +1149,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1223,8 +1232,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1260,8 +1269,8 @@ importers: packages/core: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 devDependencies: '@sentry-internal/rollup-utils': specifier: 11.17.0 @@ -1276,8 +1285,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1298,8 +1307,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1323,8 +1332,8 @@ importers: specifier: 11.17.0 version: link:../bun '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1351,8 +1360,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1494,8 +1503,8 @@ importers: packages/google-cloud-serverless: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1534,8 +1543,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1584,8 +1593,8 @@ importers: packages/nestjs: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1630,8 +1639,8 @@ importers: specifier: 11.17.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1688,8 +1697,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1725,8 +1734,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1781,8 +1790,8 @@ importers: specifier: 11.17.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1842,8 +1851,8 @@ importers: packages/opentelemetry: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1858,8 +1867,8 @@ importers: packages/profiling-node: dependencies: '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1883,8 +1892,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -1950,8 +1959,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2011,8 +2020,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2082,8 +2091,8 @@ importers: specifier: 11.17.0 version: link:../../dev-packages/rollup-utils '@sentry/rrweb': - specifier: 2.46.0 - version: 2.46.0 + specifier: 2.47.0 + version: 2.47.0 packages/replay-internal: dependencies: @@ -2101,14 +2110,14 @@ importers: specifier: 11.17.0 version: link:../../dev-packages/rollup-utils '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/rrweb': - specifier: 2.46.0 - version: 2.46.0 + specifier: 2.47.0 + version: 2.47.0 '@sentry/rrweb-snapshot': - specifier: 2.46.0 - version: 2.46.0 + specifier: 2.47.0 + version: 2.47.0 fflate: specifier: 0.8.3 version: 0.8.3 @@ -2173,8 +2182,8 @@ importers: specifier: ^1.9.1 version: 1.10.0 '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2207,8 +2216,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2265,8 +2274,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: 0.35.0 - version: 0.35.0 + specifier: 0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2335,8 +2344,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2372,8 +2381,8 @@ importers: specifier: 11.17.0 version: link:../cloudflare '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2436,8 +2445,8 @@ importers: specifier: 11.17.0 version: link:../bundler-plugins '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -2504,8 +2513,8 @@ importers: specifier: 11.17.0 version: link:../browser '@sentry/conventions': - specifier: ^0.35.0 - version: 0.35.0 + specifier: ^0.36.0 + version: 0.36.0 '@sentry/core': specifier: 11.17.0 version: link:../core @@ -7705,8 +7714,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.35.0': - resolution: {integrity: sha512-bq2ecu6zaBni0gG5bHN9cY7fmUsOW49ntjGZ6VA69PVAa1Uk1NvgF1SdTGoVC0zkqQKziTnxzOs9KuuVlpb26w==} + '@sentry/conventions@0.36.0': + resolution: {integrity: sha512-FedIjtJSiTZa3VARAds2ok7Q9Xt2LjrZJ1SeaxMvGhRgMw4V+eOaECGa/JbJWe30tw6yehE1W7T4HmgK5XJRTQ==} engines: {node: '>=14'} '@sentry/node-cpu-profiler@2.4.4': @@ -7717,17 +7726,17 @@ packages: resolution: {integrity: sha512-tF8eI4Z5YP6l7piLcy4BeGv6J96Y2ttssAAVFPgdzxzsT9i+S2olqGWgA9qav6+Gzs6E5pC9PAkObp2eDftabQ==} engines: {node: '>=18'} - '@sentry/rrdom@2.46.0': - resolution: {integrity: sha512-Ii5Oj2/eRo/cCi/4CmXHViscTFuAcAfV2icR4r+/d6HXC2/V48eejux5GZbcjxPipHAWfFXOTtm3rxBCtDtDaQ==} + '@sentry/rrdom@2.47.0': + resolution: {integrity: sha512-T+Cs6uTN0ZUYLq1QK+1tH+66o5bPNff0UxZaybFoBxfXZ7Vb3Pyjh3Mk2F1bFmm15CNwHQNCu+J6LV6zr/bEgg==} - '@sentry/rrweb-snapshot@2.46.0': - resolution: {integrity: sha512-Z9BTdBdIiQMNLBvCTvIx0vVSnH01nscK2zZ8UJSxncf9HcJ3ox0fjZ2+h6XBmSxJo0VK95qrXCeBmU9X27X/4w==} + '@sentry/rrweb-snapshot@2.47.0': + resolution: {integrity: sha512-evQPMB/UyZxxLaYhu8K5n6DGBpgs2r0yZbcrqVEj5Wo2x9FgDvJSkDicsn9w5OWrBxKgxhYB1k/5z9n+CRX4Rg==} - '@sentry/rrweb-types@2.46.0': - resolution: {integrity: sha512-U+kgUzIR4QkucJaU9CfL0YvOStfNthA8auoymcd7NeAXmN0xdEOAq+C/oxqawf7PqEk5XTpWeD160giqfgRtJw==} + '@sentry/rrweb-types@2.47.0': + resolution: {integrity: sha512-iQ8oNOHQFaS8oAwzuAyaiZy8ZVUrBMXJ4fcTA6QRBH2bRbWYyspjzw3OGa/C65fNewVgUSQyrkDivyz9PWpknw==} - '@sentry/rrweb@2.46.0': - resolution: {integrity: sha512-8r7BcYy/wPo6gGSAjtx3uuVEGinXHYRyDtXGh80GXK48mRziV6c8iDj2LiE98V7ZY1YDx6Br6SdrU9CWEt4gxA==} + '@sentry/rrweb@2.47.0': + resolution: {integrity: sha512-6I2Z9ZbC3zhTRAkqHREN3ter7qq9NSoLiLdrjY5M1t1JrKgpMxn3dTDjMLau7SdOoG9K+fFwICdnSbbMKgnwxQ==} '@shikijs/core@1.29.2': resolution: {integrity: sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ==} @@ -25456,7 +25465,7 @@ snapshots: transitivePeerDependencies: - chokidar - '@sentry/conventions@0.35.0': {} + '@sentry/conventions@0.36.0': {} '@sentry/node-cpu-profiler@2.4.4': dependencies: @@ -25468,22 +25477,22 @@ snapshots: detect-libc: 2.1.2 node-abi: 3.89.0 - '@sentry/rrdom@2.46.0': + '@sentry/rrdom@2.47.0': dependencies: - '@sentry/rrweb-snapshot': 2.46.0 + '@sentry/rrweb-snapshot': 2.47.0 - '@sentry/rrweb-snapshot@2.46.0': {} + '@sentry/rrweb-snapshot@2.47.0': {} - '@sentry/rrweb-types@2.46.0': + '@sentry/rrweb-types@2.47.0': dependencies: - '@sentry/rrweb-snapshot': 2.46.0 + '@sentry/rrweb-snapshot': 2.47.0 '@types/css-font-loading-module': 0.0.7 - '@sentry/rrweb@2.46.0': + '@sentry/rrweb@2.47.0': dependencies: - '@sentry/rrdom': 2.46.0 - '@sentry/rrweb-snapshot': 2.46.0 - '@sentry/rrweb-types': 2.46.0 + '@sentry/rrdom': 2.47.0 + '@sentry/rrweb-snapshot': 2.47.0 + '@sentry/rrweb-types': 2.47.0 '@types/css-font-loading-module': 0.0.7 '@xstate/fsm': 1.6.5 base64-arraybuffer: 1.0.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 902a3950f327..8d9017e275af 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -121,6 +121,8 @@ allowBuilds: vue-demi: true workerd: true minimumReleaseAgeExclude: + # Globs for the packages this repo publishes, so a new release installs at once. A pinned version stops + # matching at the next bump. - '@sentry/*' - sentry - '@apm-js-collab/code-transformer-bundler-plugins@0.7.6'