diff --git a/CHANGELOG.md b/CHANGELOG.md
index d2a731c60c07..accf3748aa61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,34 @@
- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott
+## 11.21.0
+
+### Important Changes
+
+- **feat(server-utils): Add opt-in TanStack AI integration for chat() ([#26874](https://github.com/getsentry/sentry-javascript/pull/26874), [#26877](https://github.com/getsentry/sentry-javascript/pull/26877), [#26878](https://github.com/getsentry/sentry-javascript/pull/26878))**
+
+The SDK now ships an opt-in integration for TanStack AI that instruments `chat()` calls, including spans for tool calls. You can also control input/output recording and add span hooks per call.
+
+### Other Changes
+
+- feat(nextjs): Continue injected trace meta tags in Pages Router pageloads ([#26927](https://github.com/getsentry/sentry-javascript/pull/26927))
+- fix(bundler-plugins): Keep identifier names in component annotation source maps ([#26944](https://github.com/getsentry/sentry-javascript/pull/26944))
+- fix(bundler-plugins): Read a class's base through an assignment ([#26967](https://github.com/getsentry/sentry-javascript/pull/26967))
+- fix(cloudflare): Detect decorated Agent classes after Babel memoizes their superclass ([#26975](https://github.com/getsentry/sentry-javascript/pull/26975))
+- fix(cloudflare): strip vinext internal data from recorded requests ([#26798](https://github.com/getsentry/sentry-javascript/pull/26798))
+
+
+ Internal Changes
+
+- perf(ci): balance Next.js E2E tests and avoid development ISR cache checks ([#26964](https://github.com/getsentry/sentry-javascript/pull/26964))
+- test(e2e): Add Effect metrics E2E tests ([#26930](https://github.com/getsentry/sentry-javascript/pull/26930))
+- test(nextjs): Add a Pages Router page to the Next.js 16 standalone E2E app ([#26924](https://github.com/getsentry/sentry-javascript/pull/26924))
+- test(node): Skip the postgres v4 caller frame assertion on Bun ([#26979](https://github.com/getsentry/sentry-javascript/pull/26979))
+
+
+
+Work in this release was contributed by @PCTEJA. Thank you for your contribution!
+
## 11.20.0
### Important Changes
diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts
index d2c26cef1d75..a5890ebde8c8 100644
--- a/dev-packages/bun-integration-tests/node-suites/excludes.ts
+++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts
@@ -135,6 +135,7 @@ export const NO_AUTO_INSTRUMENTATION = [
'suites/tracing/redis-cache/test.ts',
'suites/tracing/redis-dc/test.ts',
'suites/tracing/redis/test.ts',
+ 'suites/tracing/tanstack-ai/test.ts',
'suites/tracing/tedious/test.ts',
'suites/tracing/together-ai/test.ts',
'suites/tracing/together-ai/v1/test.ts',
diff --git a/dev-packages/e2e-tests/test-applications/effect-3-browser/public/index.html b/dev-packages/e2e-tests/test-applications/effect-3-browser/public/index.html
index 19d5c3d99a2f..e0ea20a49f1e 100644
--- a/dev-packages/e2e-tests/test-applications/effect-3-browser/public/index.html
+++ b/dev-packages/e2e-tests/test-applications/effect-3-browser/public/index.html
@@ -38,6 +38,12 @@
Log Tests
+
+
Navigation Test
Navigation Link
diff --git a/dev-packages/e2e-tests/test-applications/effect-3-browser/src/index.js b/dev-packages/e2e-tests/test-applications/effect-3-browser/src/index.js
index 9e288d79d174..1e41ea8c7e72 100644
--- a/dev-packages/e2e-tests/test-applications/effect-3-browser/src/index.js
+++ b/dev-packages/e2e-tests/test-applications/effect-3-browser/src/index.js
@@ -2,9 +2,10 @@
import * as Sentry from '@sentry/effect';
import * as Logger from 'effect/Logger';
import * as Layer from 'effect/Layer';
-import * as Runtime from 'effect/Runtime';
+import * as ManagedRuntime from 'effect/ManagedRuntime';
import * as LogLevel from 'effect/LogLevel';
import * as Effect from 'effect/Effect';
+import * as Metric from 'effect/Metric';
const LogLevelLayer = Logger.minimumLogLevel(LogLevel.Debug);
const AppLayer = Layer.mergeAll(
@@ -18,12 +19,20 @@ const AppLayer = Layer.mergeAll(
}),
Sentry.layerTracer,
Sentry.layerLogger,
+ Sentry.layerMetrics,
LogLevelLayer,
);
-const runtime = Layer.toRuntime(AppLayer).pipe(Effect.scoped, Effect.runSync);
+const ordersPlaced = Metric.counter('orders_placed').pipe(Metric.tagged('shop', 'e2e'));
+const queueDepth = Metric.gauge('queue_depth');
-const runEffect = fn => Runtime.runPromise(runtime)(fn());
+// ManagedRuntime keeps the layer scope open, so the `Sentry.layerMetrics` fiber keeps running
+const runtime = ManagedRuntime.make(AppLayer);
+
+// Builds the layer at page load, so Sentry is initialized before the first click
+Effect.runSync(runtime.runtimeEffect);
+
+const runEffect = fn => runtime.runPromise(fn());
document.getElementById('exception-button')?.addEventListener('click', () => {
throw new Error('I am an error!');
@@ -82,6 +91,17 @@ document.getElementById('log-context-button')?.addEventListener('click', async (
if (el) el.textContent = 'Log with context sent!';
});
+document.getElementById('metrics-button')?.addEventListener('click', async () => {
+ await runEffect(() =>
+ Effect.gen(function* () {
+ yield* Metric.update(ordersPlaced, 1);
+ yield* Metric.update(queueDepth, 7);
+ }),
+ );
+ const el = document.getElementById('metrics-result');
+ if (el) el.textContent = 'Metrics updated!';
+});
+
document.getElementById('navigation-link')?.addEventListener('click', () => {
document.getElementById('navigation-target')?.scrollIntoView({ behavior: 'smooth' });
});
diff --git a/dev-packages/e2e-tests/test-applications/effect-3-browser/tests/metrics.test.ts b/dev-packages/e2e-tests/test-applications/effect-3-browser/tests/metrics.test.ts
new file mode 100644
index 000000000000..b8ae536264c4
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/effect-3-browser/tests/metrics.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from '@playwright/test';
+import { waitForEnvelopeItem } from '@sentry-internal/test-utils';
+import type { SerializedMetricContainer } from '@sentry/core';
+
+test('sends Effect metrics', async ({ page }) => {
+ const metricContainerPromise = waitForEnvelopeItem('effect-3-browser', envelopeItem => {
+ return (
+ envelopeItem[0].type === 'trace_metric' &&
+ (envelopeItem[1] as SerializedMetricContainer).items.some(metric => metric.name === 'orders_placed')
+ );
+ });
+
+ await page.goto('/');
+ await page.locator('id=metrics-button').click();
+
+ await expect(page.locator('id=metrics-result')).toHaveText('Metrics updated!');
+
+ const metrics = ((await metricContainerPromise)[1] as SerializedMetricContainer).items;
+ expect(metrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'orders_placed',
+ type: 'counter',
+ value: 1,
+ attributes: expect.objectContaining({ shop: { value: 'e2e', type: 'string' } }),
+ }),
+ expect.objectContaining({ name: 'queue_depth', type: 'gauge', value: 7 }),
+ ]),
+ );
+});
diff --git a/dev-packages/e2e-tests/test-applications/effect-3-node/src/app.ts b/dev-packages/e2e-tests/test-applications/effect-3-node/src/app.ts
index 013e2328fe56..ab88e213b63c 100644
--- a/dev-packages/e2e-tests/test-applications/effect-3-node/src/app.ts
+++ b/dev-packages/e2e-tests/test-applications/effect-3-node/src/app.ts
@@ -6,6 +6,8 @@ import * as Cause from 'effect/Cause';
import * as Layer from 'effect/Layer';
import * as Logger from 'effect/Logger';
import * as LogLevel from 'effect/LogLevel';
+import * as Metric from 'effect/Metric';
+import * as MetricBoundaries from 'effect/MetricBoundaries';
import * as Tracer from 'effect/Tracer';
import { createServer } from 'http';
@@ -19,8 +21,17 @@ const SentryLayer = Layer.mergeAll(
}),
Sentry.layerTracer,
Sentry.layerLogger,
+ Sentry.layerMetrics,
);
+const ordersPlaced = Metric.counter('orders_placed').pipe(Metric.tagged('shop', 'e2e'));
+const queueDepth = Metric.gauge('queue_depth');
+const requestDuration = Metric.histogram(
+ 'request_duration_ms',
+ MetricBoundaries.linear({ start: 0, width: 50, count: 10 }),
+);
+const cacheLookups = Metric.frequency('cache_lookups');
+
const router = HttpRouter.empty.pipe(
HttpRouter.get('/test-success', HttpServerResponse.json({ version: 'v1' })),
@@ -110,6 +121,27 @@ const router = HttpRouter.empty.pipe(
}),
),
+ HttpRouter.get(
+ '/test-metric-counter',
+ Effect.gen(function* () {
+ yield* Metric.update(ordersPlaced, 1);
+ return yield* HttpServerResponse.json({ status: 'ok' });
+ }),
+ ),
+
+ HttpRouter.get(
+ '/test-metrics',
+ Effect.gen(function* () {
+ yield* Metric.update(queueDepth, 7);
+ yield* Metric.update(requestDuration, 120);
+ yield* Metric.update(requestDuration, 80);
+ yield* Metric.update(cacheLookups, 'hit');
+ yield* Metric.update(cacheLookups, 'hit');
+ yield* Metric.update(cacheLookups, 'miss');
+ return yield* HttpServerResponse.json({ status: 'ok' });
+ }),
+ ),
+
HttpRouter.catchAllCause(cause => {
const error = Cause.squash(cause);
Sentry.captureException(error);
diff --git a/dev-packages/e2e-tests/test-applications/effect-3-node/tests/metrics.test.ts b/dev-packages/e2e-tests/test-applications/effect-3-node/tests/metrics.test.ts
new file mode 100644
index 000000000000..10c64fb0b707
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/effect-3-node/tests/metrics.test.ts
@@ -0,0 +1,68 @@
+import { expect, test } from '@playwright/test';
+import { waitForEnvelopeItem, waitForMetric } from '@sentry-internal/test-utils';
+import type { SerializedMetricContainer } from '@sentry/core';
+
+test('sends the increase of an Effect counter since the last flush', async ({ baseURL }) => {
+ // `Sentry.layerMetrics` reads the Effect metrics every 10 seconds, and this test waits for two reads.
+ test.slow();
+
+ const firstMetricPromise = waitForMetric('effect-3-node', metric => metric.name === 'orders_placed');
+
+ await fetch(`${baseURL}/test-metric-counter`);
+
+ expect(await firstMetricPromise).toMatchObject({
+ type: 'counter',
+ value: 1,
+ attributes: { shop: { value: 'e2e', type: 'string' } },
+ });
+
+ const secondMetricPromise = waitForMetric('effect-3-node', metric => metric.name === 'orders_placed');
+
+ await fetch(`${baseURL}/test-metric-counter`);
+
+ expect(await secondMetricPromise).toMatchObject({ type: 'counter', value: 1 });
+});
+
+test('sends Effect gauges, histograms and frequencies', async ({ baseURL }) => {
+ const metricContainerPromise = waitForEnvelopeItem('effect-3-node', envelopeItem => {
+ return (
+ envelopeItem[0].type === 'trace_metric' &&
+ (envelopeItem[1] as SerializedMetricContainer).items.some(metric => metric.name === 'queue_depth')
+ );
+ });
+
+ await fetch(`${baseURL}/test-metrics`);
+
+ const metrics = ((await metricContainerPromise)[1] as SerializedMetricContainer).items;
+ expect(metrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: 'queue_depth', type: 'gauge', value: 7 }),
+ expect.objectContaining({ name: 'request_duration_ms.sum', type: 'gauge', value: 200 }),
+ expect.objectContaining({ name: 'request_duration_ms.count', type: 'gauge', value: 2 }),
+ expect.objectContaining({ name: 'request_duration_ms.min', type: 'gauge', value: 80 }),
+ expect.objectContaining({ name: 'request_duration_ms.max', type: 'gauge', value: 120 }),
+ expect.objectContaining({
+ name: 'cache_lookups',
+ type: 'counter',
+ value: 2,
+ attributes: expect.objectContaining({ word: { value: 'hit', type: 'string' } }),
+ }),
+ expect.objectContaining({
+ name: 'cache_lookups',
+ type: 'counter',
+ value: 1,
+ attributes: expect.objectContaining({ word: { value: 'miss', type: 'string' } }),
+ }),
+ ]),
+ );
+});
+
+test('sends the Effect runtime metrics, which Effect v3 records by default', async ({ baseURL }) => {
+ const metricPromise = waitForMetric('effect-3-node', metric => metric.name === 'effect_fiber_started');
+
+ await fetch(`${baseURL}/test-success`);
+
+ const metric = await metricPromise;
+ expect(metric.type).toBe('counter');
+ expect(metric.value).toBeGreaterThan(0);
+});
diff --git a/dev-packages/e2e-tests/test-applications/effect-4-browser/public/index.html b/dev-packages/e2e-tests/test-applications/effect-4-browser/public/index.html
index 19d5c3d99a2f..e0ea20a49f1e 100644
--- a/dev-packages/e2e-tests/test-applications/effect-4-browser/public/index.html
+++ b/dev-packages/e2e-tests/test-applications/effect-4-browser/public/index.html
@@ -38,6 +38,12 @@ Log Tests
+
+
Navigation Test
Navigation Link
diff --git a/dev-packages/e2e-tests/test-applications/effect-4-browser/src/index.js b/dev-packages/e2e-tests/test-applications/effect-4-browser/src/index.js
index 814657a980c0..2282a32a6911 100644
--- a/dev-packages/e2e-tests/test-applications/effect-4-browser/src/index.js
+++ b/dev-packages/e2e-tests/test-applications/effect-4-browser/src/index.js
@@ -2,6 +2,7 @@
import * as Sentry from '@sentry/effect';
import * as Layer from 'effect/Layer';
import * as ManagedRuntime from 'effect/ManagedRuntime';
+import * as Metric from 'effect/Metric';
import * as References from 'effect/References';
import * as Effect from 'effect/Effect';
@@ -16,9 +17,13 @@ const AppLayer = Layer.mergeAll(
}),
Sentry.layerLogger,
Sentry.layerTracer,
+ Sentry.layerMetrics,
Layer.succeed(References.MinimumLogLevel, 'Debug'),
);
+const ordersPlaced = Metric.counter('orders_placed', { attributes: { shop: 'e2e' } });
+const queueDepth = Metric.gauge('queue_depth');
+
// v4 pattern: ManagedRuntime creates a long-lived runtime from the layer
const runtime = ManagedRuntime.make(AppLayer);
@@ -84,6 +89,17 @@ document.getElementById('log-context-button')?.addEventListener('click', async (
if (el) el.textContent = 'Log with context sent!';
});
+document.getElementById('metrics-button')?.addEventListener('click', async () => {
+ await runEffect(() =>
+ Effect.gen(function* () {
+ yield* Metric.update(ordersPlaced, 1);
+ yield* Metric.update(queueDepth, 7);
+ }),
+ );
+ const el = document.getElementById('metrics-result');
+ if (el) el.textContent = 'Metrics updated!';
+});
+
document.getElementById('navigation-link')?.addEventListener('click', () => {
document.getElementById('navigation-target')?.scrollIntoView({ behavior: 'smooth' });
});
diff --git a/dev-packages/e2e-tests/test-applications/effect-4-browser/tests/metrics.test.ts b/dev-packages/e2e-tests/test-applications/effect-4-browser/tests/metrics.test.ts
new file mode 100644
index 000000000000..9e96f3e61ed7
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/effect-4-browser/tests/metrics.test.ts
@@ -0,0 +1,30 @@
+import { expect, test } from '@playwright/test';
+import { waitForEnvelopeItem } from '@sentry-internal/test-utils';
+import type { SerializedMetricContainer } from '@sentry/core';
+
+test('sends Effect metrics', async ({ page }) => {
+ const metricContainerPromise = waitForEnvelopeItem('effect-4-browser', envelopeItem => {
+ return (
+ envelopeItem[0].type === 'trace_metric' &&
+ (envelopeItem[1] as SerializedMetricContainer).items.some(metric => metric.name === 'orders_placed')
+ );
+ });
+
+ await page.goto('/');
+ await page.locator('id=metrics-button').click();
+
+ await expect(page.locator('id=metrics-result')).toHaveText('Metrics updated!');
+
+ const metrics = ((await metricContainerPromise)[1] as SerializedMetricContainer).items;
+ expect(metrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'orders_placed',
+ type: 'counter',
+ value: 1,
+ attributes: expect.objectContaining({ shop: { value: 'e2e', type: 'string' } }),
+ }),
+ expect.objectContaining({ name: 'queue_depth', type: 'gauge', value: 7 }),
+ ]),
+ );
+});
diff --git a/dev-packages/e2e-tests/test-applications/effect-4-node/src/app.ts b/dev-packages/e2e-tests/test-applications/effect-4-node/src/app.ts
index 0d86544264ae..4b29171798da 100644
--- a/dev-packages/e2e-tests/test-applications/effect-4-node/src/app.ts
+++ b/dev-packages/e2e-tests/test-applications/effect-4-node/src/app.ts
@@ -4,7 +4,9 @@ import * as Effect from 'effect/Effect';
import * as Cause from 'effect/Cause';
import * as Data from 'effect/Data';
import * as ErrorReporter from 'effect/ErrorReporter';
+import * as Fiber from 'effect/Fiber';
import * as Layer from 'effect/Layer';
+import * as Metric from 'effect/Metric';
import * as Tracer from 'effect/Tracer';
import * as References from 'effect/References';
import { HttpRouter, HttpServerResponse } from 'effect/http';
@@ -20,9 +22,17 @@ const SentryLayer = Layer.mergeAll(
}),
Sentry.layerLogger,
Sentry.layerTracer,
+ Sentry.layerMetrics,
Layer.succeed(References.MinimumLogLevel, 'Debug'),
);
+const ordersPlaced = Metric.counter('orders_placed', { attributes: { shop: 'e2e' } });
+const queueDepth = Metric.gauge('queue_depth');
+const requestDuration = Metric.histogram('request_duration_ms', {
+ boundaries: Metric.linearBoundaries({ start: 0, width: 50, count: 10 }),
+});
+const cacheLookups = Metric.frequency('cache_lookups');
+
class NotFoundError extends Data.TaggedError('NotFoundError')<{ readonly id: string }> {
readonly [ErrorReporter.ignore] = true;
}
@@ -216,6 +226,39 @@ const Routes = Layer.mergeAll(
return yield* HttpServerResponse.json({ message: 'Log with context sent' });
}),
),
+
+ HttpRouter.add(
+ 'GET',
+ '/test-metric-counter',
+ Effect.gen(function* () {
+ yield* Metric.update(ordersPlaced, 1);
+ return yield* HttpServerResponse.json({ status: 'ok' });
+ }),
+ ),
+
+ HttpRouter.add(
+ 'GET',
+ '/test-metrics',
+ Effect.gen(function* () {
+ yield* Metric.update(queueDepth, 7);
+ yield* Metric.update(requestDuration, 120);
+ yield* Metric.update(requestDuration, 80);
+ yield* Metric.update(cacheLookups, 'hit');
+ yield* Metric.update(cacheLookups, 'hit');
+ yield* Metric.update(cacheLookups, 'miss');
+ return yield* HttpServerResponse.json({ status: 'ok' });
+ }),
+ ),
+
+ HttpRouter.add(
+ 'GET',
+ '/test-runtime-metrics',
+ Effect.gen(function* () {
+ const fiber = yield* Effect.forkChild(Effect.sleep('10 millis'));
+ yield* Fiber.join(fiber);
+ return yield* HttpServerResponse.json({ status: 'ok' });
+ }).pipe(Metric.enableRuntimeMetrics),
+ ),
);
const HttpLayer = HttpRouter.serve(Routes).pipe(
diff --git a/dev-packages/e2e-tests/test-applications/effect-4-node/tests/metrics.test.ts b/dev-packages/e2e-tests/test-applications/effect-4-node/tests/metrics.test.ts
new file mode 100644
index 000000000000..2e41af02982f
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/effect-4-node/tests/metrics.test.ts
@@ -0,0 +1,66 @@
+import { expect, test } from '@playwright/test';
+import { waitForEnvelopeItem, waitForMetric } from '@sentry-internal/test-utils';
+import type { SerializedMetricContainer } from '@sentry/core';
+
+test('sends the increase of an Effect counter since the last flush', async ({ baseURL }) => {
+ // `Sentry.layerMetrics` reads the Effect metrics every 10 seconds, and this test waits for two reads.
+ test.slow();
+
+ const firstMetricPromise = waitForMetric('effect-4-node', metric => metric.name === 'orders_placed');
+
+ await fetch(`${baseURL}/test-metric-counter`);
+
+ expect(await firstMetricPromise).toMatchObject({
+ type: 'counter',
+ value: 1,
+ attributes: { shop: { value: 'e2e', type: 'string' } },
+ });
+
+ const secondMetricPromise = waitForMetric('effect-4-node', metric => metric.name === 'orders_placed');
+
+ await fetch(`${baseURL}/test-metric-counter`);
+
+ expect(await secondMetricPromise).toMatchObject({ type: 'counter', value: 1 });
+});
+
+test('sends Effect gauges, histograms and frequencies', async ({ baseURL }) => {
+ const metricContainerPromise = waitForEnvelopeItem('effect-4-node', envelopeItem => {
+ return (
+ envelopeItem[0].type === 'trace_metric' &&
+ (envelopeItem[1] as SerializedMetricContainer).items.some(metric => metric.name === 'queue_depth')
+ );
+ });
+
+ await fetch(`${baseURL}/test-metrics`);
+
+ const metrics = ((await metricContainerPromise)[1] as SerializedMetricContainer).items;
+ expect(metrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: 'queue_depth', type: 'gauge', value: 7 }),
+ expect.objectContaining({ name: 'request_duration_ms.sum', type: 'gauge', value: 200 }),
+ expect.objectContaining({ name: 'request_duration_ms.count', type: 'gauge', value: 2 }),
+ expect.objectContaining({ name: 'request_duration_ms.min', type: 'gauge', value: 80 }),
+ expect.objectContaining({ name: 'request_duration_ms.max', type: 'gauge', value: 120 }),
+ expect.objectContaining({
+ name: 'cache_lookups',
+ type: 'counter',
+ value: 2,
+ attributes: expect.objectContaining({ word: { value: 'hit', type: 'string' } }),
+ }),
+ expect.objectContaining({
+ name: 'cache_lookups',
+ type: 'counter',
+ value: 1,
+ attributes: expect.objectContaining({ word: { value: 'miss', type: 'string' } }),
+ }),
+ ]),
+ );
+});
+
+test('sends Effect runtime metrics when they are enabled', async ({ baseURL }) => {
+ const metricPromise = waitForMetric('effect-4-node', metric => metric.name === 'child_fibers_started');
+
+ await fetch(`${baseURL}/test-runtime-metrics`);
+
+ expect(await metricPromise).toMatchObject({ type: 'counter', value: 1 });
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-app-routing-instrumentation.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-app-routing-instrumentation.test.ts
index b246b99a65fb..ed56adb182e2 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-app-routing-instrumentation.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-app-routing-instrumentation.test.ts
@@ -48,139 +48,3 @@ test('Creates a navigation span for app router routes', async ({ page }) => {
expect(serverComponentSpan.trace_id).toBe(clientNavigationSpan.trace_id);
});
-
-test('Creates a navigation span for `router.push()`', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/router-push` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'router.push'
- );
- });
-
- await page.goto('/navigation');
- await page.waitForTimeout(3000);
- await page.getByText('router.push()').click();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for `router.replace()`', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/router-replace` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'router.replace'
- );
- });
-
- await page.goto('/navigation');
- await page.waitForTimeout(3000);
- await page.getByText('router.replace()').click();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for `router.back()`', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return span.name === `/navigation/:param/router-back` && getSpanOp(span) === 'navigation';
- });
-
- await page.goto('/navigation/1337/router-back');
- await page.waitForTimeout(3000);
- await page.getByText('Go back home').click();
- await page.waitForTimeout(3000);
- await page.getByText('router.back()').click();
-
- const navigationSpan = await navigationSpanPromise;
-
- expect(navigationSpan.attributes['navigation.type']?.value).toBe('router.back');
-});
-
-test('Creates a navigation span for `router.forward()`', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/router-push` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'router.forward'
- );
- });
-
- await page.goto('/navigation');
- await page.waitForTimeout(3000);
- await page.getByText('router.push()').click();
- await page.waitForTimeout(3000);
- await page.goBack();
- await page.waitForTimeout(3000);
- await page.getByText('router.forward()').click();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for ` `', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/link` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'router.push'
- );
- });
-
- await page.goto('/navigation');
- await page.getByText('Normal Link').click();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for ` `', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/link-replace` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'router.replace'
- );
- });
-
- await page.goto('/navigation');
- await page.waitForTimeout(3000);
- await page.getByText('Link Replace').click();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for browser-back', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/browser-back` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'browser.popstate'
- );
- });
-
- await page.goto('/navigation/42/browser-back');
- await page.waitForTimeout(3000);
- await page.getByText('Go back home').click();
- await page.waitForTimeout(3000);
- await page.goBack();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
-
-test('Creates a navigation span for browser-forward', async ({ page }) => {
- const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
- return (
- span.name === `/navigation/:param/router-push` &&
- getSpanOp(span) === 'navigation' &&
- span.attributes['navigation.type']?.value === 'browser.popstate'
- );
- });
-
- await page.goto('/navigation');
- await page.getByText('router.push()').click();
- await page.waitForTimeout(3000);
- await page.goBack();
- await page.waitForTimeout(3000);
- await page.goForward();
-
- expect(await navigationSpanPromise).toBeDefined();
-});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-browser-history-navigation.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-browser-history-navigation.test.ts
new file mode 100644
index 000000000000..1348935e9493
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-browser-history-navigation.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('Creates a navigation span for browser-back', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/browser-back` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'browser.popstate'
+ );
+ });
+
+ await page.goto('/navigation/42/browser-back');
+ await page.waitForTimeout(3000);
+ await page.getByText('Go back home').click();
+ await page.waitForTimeout(3000);
+ await page.goBack();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
+
+test('Creates a navigation span for browser-forward', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/router-push` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'browser.popstate'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.getByText('router.push()').click();
+ await page.waitForTimeout(3000);
+ await page.goBack();
+ await page.waitForTimeout(3000);
+ await page.goForward();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-link-navigation.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-link-navigation.test.ts
new file mode 100644
index 000000000000..c6c6a83ea31d
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-link-navigation.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('Creates a navigation span for ` `', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/link` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'router.push'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.getByText('Normal Link').click();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
+
+test('Creates a navigation span for ` `', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/link-replace` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'router.replace'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.waitForTimeout(3000);
+ await page.getByText('Link Replace').click();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-history-navigation.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-history-navigation.test.ts
new file mode 100644
index 000000000000..f73291ba35ca
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-history-navigation.test.ts
@@ -0,0 +1,38 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('Creates a navigation span for `router.back()`', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return span.name === `/navigation/:param/router-back` && getSpanOp(span) === 'navigation';
+ });
+
+ await page.goto('/navigation/1337/router-back');
+ await page.waitForTimeout(3000);
+ await page.getByText('Go back home').click();
+ await page.waitForTimeout(3000);
+ await page.getByText('router.back()').click();
+
+ const navigationSpan = await navigationSpanPromise;
+
+ expect(navigationSpan.attributes['navigation.type']?.value).toBe('router.back');
+});
+
+test('Creates a navigation span for `router.forward()`', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/router-push` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'router.forward'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.waitForTimeout(3000);
+ await page.getByText('router.push()').click();
+ await page.waitForTimeout(3000);
+ await page.goBack();
+ await page.waitForTimeout(3000);
+ await page.getByText('router.forward()').click();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-navigation.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-navigation.test.ts
new file mode 100644
index 000000000000..26d6dcbdc223
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-14/tests/client-router-navigation.test.ts
@@ -0,0 +1,34 @@
+import { expect, test } from '@playwright/test';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('Creates a navigation span for `router.push()`', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/router-push` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'router.push'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.waitForTimeout(3000);
+ await page.getByText('router.push()').click();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
+
+test('Creates a navigation span for `router.replace()`', async ({ page }) => {
+ const navigationSpanPromise = waitForStreamedSpan('nextjs-14', span => {
+ return (
+ span.name === `/navigation/:param/router-replace` &&
+ getSpanOp(span) === 'navigation' &&
+ span.attributes['navigation.type']?.value === 'router.replace'
+ );
+ });
+
+ await page.goto('/navigation');
+ await page.waitForTimeout(3000);
+ await page.getByText('router.replace()').click();
+
+ expect(await navigationSpanPromise).toBeDefined();
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/package.json b/dev-packages/e2e-tests/test-applications/nextjs-15/package.json
index b288477c39ca..9f57e90891d4 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-15/package.json
+++ b/dev-packages/e2e-tests/test-applications/nextjs-15/package.json
@@ -52,7 +52,8 @@
{
"build-command": "pnpm install",
"label": "nextjs-15 (development)",
- "assert-command": "pnpm test:dev"
+ "assert-command": "pnpm test:dev",
+ "test-shards": 2
},
{
"build-command": "E2E_RELEASE_NOT_INJECTED=1 pnpm test:build",
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts
new file mode 100644
index 000000000000..f9062896b5a7
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-15/tests/pages-router/injected-trace-meta-tags.test.ts
@@ -0,0 +1,73 @@
+import { expect, test } from '@playwright/test';
+import { URL_PATH } from '@sentry/conventions/attributes';
+import { PAGELOAD } from '@sentry/conventions/op';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+import { parseSemver } from '@sentry/core';
+
+const nextPackageJson = require('next/package.json');
+const nextjsVersion = nextPackageJson.version;
+const { major, minor } = parseSemver(nextjsVersion);
+
+// Another test loads this page in parallel, so the `[locale]` segment tells the pageload spans apart.
+const PAGE_PATH = '/injected-meta-tags/pages-router-client-trace-propagation';
+
+const INJECTED_TRACE_ID = '12345678901234567890123456789012';
+const INJECTED_PARENT_SPAN_ID = '1234567890123456';
+
+test('Should continue the trace of injected meta tags instead of the server trace in pages router', async ({
+ page,
+}) => {
+ test.skip(
+ major === 15 && minor !== undefined && minor < 3,
+ 'Next.js version does not support clientside instrumentation',
+ );
+
+ // Stands in for a mobile SDK that injects the tags into the document of a WebView. They go after the tags Next.js
+ // renders for the request, so the order of the tags cannot decide the outcome. Rewriting the response instead is
+ // not an option: Chrome denies a document fulfilled by Playwright the requests to the event proxy on localhost.
+ await page.addInitScript(
+ ({ sentryTrace, baggage }) => {
+ const observer = new MutationObserver(() => {
+ const head = document.head;
+ if (!head?.querySelector('meta[name="sentry-trace"]') || !head.querySelector('meta[name="baggage"]')) {
+ return;
+ }
+ observer.disconnect();
+ for (const [name, content] of [
+ ['sentry-trace', sentryTrace],
+ ['baggage', baggage],
+ ] as const) {
+ const meta = document.createElement('meta');
+ meta.name = name;
+ meta.content = content;
+ head.appendChild(meta);
+ }
+ });
+ observer.observe(document, { childList: true, subtree: true });
+ },
+ {
+ sentryTrace: `${INJECTED_TRACE_ID}-${INJECTED_PARENT_SPAN_ID}-1`,
+ baggage: `sentry-trace_id=${INJECTED_TRACE_ID},sentry-sampled=true,sentry-sample_rate=1,sentry-environment=qa`,
+ },
+ );
+
+ const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => {
+ return getSpanOp(span) === PAGELOAD && span.is_segment && span.attributes?.[URL_PATH]?.value === PAGE_PATH;
+ });
+
+ await page.goto(PAGE_PATH);
+
+ const pageloadSpan = await pageloadSpanPromise;
+
+ const sentryTraceTags = await page
+ .locator('meta[name="sentry-trace"]')
+ .evaluateAll(tags => tags.map(tag => tag.getAttribute('content')));
+
+ // The browser SDK falls back to the first `sentry-trace` tag. With the injected tag last, that fallback cannot be
+ // what makes this test pass.
+ expect(sentryTraceTags).toHaveLength(2);
+ expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID);
+ expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID);
+ expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID);
+ expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID);
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/package.json
index efa496b6b744..76c61a8f2f7e 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/package.json
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/package.json
@@ -26,6 +26,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
+ "@sentry/conventions": "0.36.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/pages/pages-router-ssr.tsx b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/pages/pages-router-ssr.tsx
new file mode 100644
index 000000000000..2fd4ade0e5de
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/pages/pages-router-ssr.tsx
@@ -0,0 +1,10 @@
+export default function Page() {
+ return Next.js 16 Standalone Output Test (Pages Router)
;
+}
+
+// Renders the page per request, so the document carries the trace of the request.
+export async function getServerSideProps() {
+ return {
+ props: {},
+ };
+}
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts
new file mode 100644
index 000000000000..6f6a757542c3
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16-standalone/tests/pages-router.test.ts
@@ -0,0 +1,79 @@
+import { expect, test } from '@playwright/test';
+import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';
+import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op';
+import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
+
+test('continues the server trace in the pageload of a Pages Router page', async ({ page }) => {
+ const serverSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => {
+ return span.name === 'GET /pages-router-ssr' && getSpanOp(span) === HTTP_SERVER && span.is_segment;
+ });
+
+ const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => {
+ return span.name === '/pages-router-ssr' && getSpanOp(span) === PAGELOAD && span.is_segment;
+ });
+
+ await page.goto('/pages-router-ssr');
+
+ const serverSpan = await serverSpanPromise;
+ const pageloadSpan = await pageloadSpanPromise;
+
+ expect(serverSpan.trace_id).toBeDefined();
+ expect(pageloadSpan.trace_id).toBe(serverSpan.trace_id);
+ expect(pageloadSpan.attributes[SENTRY_ORIGIN]?.value).toBe('auto.pageload.nextjs.pages_router_instrumentation');
+});
+
+const INJECTED_TRACE_ID = '12345678901234567890123456789012';
+const INJECTED_PARENT_SPAN_ID = '1234567890123456';
+
+test('continues the trace of injected meta tags instead of the server trace in a Pages Router page', async ({
+ page,
+}) => {
+ // Stands in for a mobile SDK that injects the tags into the document of a WebView. They go after the tags Next.js
+ // renders for the request, so the order of the tags cannot decide the outcome. Rewriting the response instead is
+ // not an option: Chrome denies a document fulfilled by Playwright the requests to the event proxy on localhost.
+ await page.addInitScript(
+ ({ sentryTrace, baggage }) => {
+ const observer = new MutationObserver(() => {
+ const head = document.head;
+ if (!head?.querySelector('meta[name="sentry-trace"]') || !head.querySelector('meta[name="baggage"]')) {
+ return;
+ }
+ observer.disconnect();
+ for (const [name, content] of [
+ ['sentry-trace', sentryTrace],
+ ['baggage', baggage],
+ ] as const) {
+ const meta = document.createElement('meta');
+ meta.name = name;
+ meta.content = content;
+ head.appendChild(meta);
+ }
+ });
+ observer.observe(document, { childList: true, subtree: true });
+ },
+ {
+ sentryTrace: `${INJECTED_TRACE_ID}-${INJECTED_PARENT_SPAN_ID}-1`,
+ baggage: `sentry-trace_id=${INJECTED_TRACE_ID},sentry-sampled=true,sentry-sample_rate=1,sentry-environment=qa`,
+ },
+ );
+
+ const pageloadSpanPromise = waitForStreamedSpan('nextjs-16-standalone', span => {
+ return span.name === '/pages-router-ssr' && getSpanOp(span) === PAGELOAD && span.is_segment;
+ });
+
+ await page.goto('/pages-router-ssr');
+
+ const pageloadSpan = await pageloadSpanPromise;
+
+ const sentryTraceTags = await page
+ .locator('meta[name="sentry-trace"]')
+ .evaluateAll(tags => tags.map(tag => tag.getAttribute('content')));
+
+ // The browser SDK falls back to the first `sentry-trace` tag. With the injected tag last, that fallback cannot be
+ // what makes this test pass.
+ expect(sentryTraceTags).toHaveLength(2);
+ expect(sentryTraceTags[0]).not.toContain(INJECTED_TRACE_ID);
+ expect(sentryTraceTags[1]).toContain(INJECTED_TRACE_ID);
+ expect(pageloadSpan.trace_id).toBe(INJECTED_TRACE_ID);
+ expect(pageloadSpan.parent_span_id).toBe(INJECTED_PARENT_SPAN_ID);
+});
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json
index 37c538447c0d..9789a08ab57b 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-16/package.json
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16/package.json
@@ -137,7 +137,8 @@
"runtime": "bun",
"build-command": "pnpm install",
"assert-command": "pnpm test:dev",
- "label": "nextjs-16 (bun, turbopack, development)"
+ "label": "nextjs-16 (bun, turbopack, development)",
+ "test-shards": 2
},
{
"runtime": "cloudflare",
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.static-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.static-lifecycle.test.ts
index 3c5b00ead2b7..8a6e3caa51c6 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.static-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.static-lifecycle.test.ts
@@ -49,6 +49,8 @@ test.describe('prerendered ISR pages', () => {
});
test('should create unique transactions for ISR pages on each visit', async ({ page, baseURL }) => {
+ test.skip(!isProductionBuild, 'ISR cache behavior requires a production build');
+
const traceIds: string[] = [];
const url = '/isr-test/laptop?test=unique-isr-traces';
diff --git a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.streaming-lifecycle.test.ts b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.streaming-lifecycle.test.ts
index a5e2207e8994..6566b7af714c 100644
--- a/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.streaming-lifecycle.test.ts
+++ b/dev-packages/e2e-tests/test-applications/nextjs-16/tests/isr-routes.streaming-lifecycle.test.ts
@@ -76,8 +76,7 @@ test.describe('prerendered ISR pages', () => {
});
test('should create unique traces for ISR pages on each visit', async ({ page, baseURL }) => {
- // The 5 page loads need about 17 s on an idle webpack dev server, and more while it compiles routes for other workers
- test.slow();
+ test.skip(!isProductionBuild, 'ISR cache behavior requires a production build');
const traceIds: string[] = [];
const url = '/isr-test/laptop?test=unique-isr-traces';
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 b15bd7ffb49a..199c9510906f 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
@@ -37,7 +37,7 @@
"optionalVariants": [
{
"build-command": "E2E_VINEXT_WORKERS_CACHE=1 pnpm test:build",
- "assert-command": "pnpm test tests/page-errors.test.ts",
+ "assert-command": "E2E_VINEXT_WORKERS_CACHE=1 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/tests/page-errors.test.ts b/dev-packages/e2e-tests/test-applications/vinext-cf-workers/tests/page-errors.test.ts
index a476a3059cd9..badb07585178 100644
--- 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
@@ -5,17 +5,18 @@ 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']),
+ // vinext's Workers Cache adapter renders the page in a second invocation, which has its own request span.
+ const requestSpanCount = process.env.E2E_VINEXT_WORKERS_CACHE ? 2 : 1;
+ const requestSpansPromise = collectStreamedSpans(
+ 'vinext-cf-workers',
+ spans => spans.filter(span => span.is_segment && span.name === 'GET /page-error').length === requestSpanCount,
);
- const response = await request.get('/page-error');
+ const response = await request.get('/page-error?token=secret-value-123');
expect(response.status()).toBe(500);
const errorEvent = await errorPromise;
- const requestSpans = await requestSpansPromise;
+ const requestSpans = (await requestSpansPromise).filter(span => span.is_segment);
expect(errorEvent.sdk?.name).toBe('sentry.javascript.nextjs');
expect(errorEvent.environment).toBe('qa');
@@ -25,4 +26,16 @@ test('Captures an error thrown while a page renders', async ({ request }) => {
type: 'auto.function.nextjs.on_request_error',
});
expect(errorEvent.contexts?.trace?.trace_id).toBe(requestSpans[0]?.trace_id);
+
+ // The second invocation's request carries vinext's internal data: the
+ // `__vinext_cache_key` query param and `x-vinext-internal-*` headers, which
+ // transport the original URL (including its token) unfiltered. None of it
+ // may land in the recorded error event or request spans.
+ expect(requestSpans).toHaveLength(requestSpanCount);
+ for (const recorded of [errorEvent.request, ...requestSpans.map(span => span.attributes)]) {
+ const serialized = JSON.stringify(recorded);
+ expect(serialized).not.toContain('x-vinext-internal-');
+ expect(serialized).not.toContain('__vinext_');
+ expect(serialized).not.toContain('secret-value-123');
+ }
});
diff --git a/dev-packages/node-integration-tests/package.json b/dev-packages/node-integration-tests/package.json
index 75d941241b26..1d1a3bde4801 100644
--- a/dev-packages/node-integration-tests/package.json
+++ b/dev-packages/node-integration-tests/package.json
@@ -70,6 +70,7 @@
"@sentry/server-utils": "11.20.0",
"@smithy/core": "3.38.1",
"@smithy/node-http-handler": "4.12.1",
+ "@tanstack/ai": "^1.8.0",
"@types/express": "^4.17.21",
"@types/node-schedule": "^2.1.8",
"@typesafe-ai/sdk": "^0.6.0",
diff --git a/dev-packages/node-integration-tests/suites/tracing/postgresjs-tracing-channel/test.ts b/dev-packages/node-integration-tests/suites/tracing/postgresjs-tracing-channel/test.ts
index 13f97d03d277..16077dce1390 100644
--- a/dev-packages/node-integration-tests/suites/tracing/postgresjs-tracing-channel/test.ts
+++ b/dev-packages/node-integration-tests/suites/tracing/postgresjs-tracing-channel/test.ts
@@ -15,6 +15,7 @@ import {
import { DB } from '@sentry/conventions/op';
import type { Event, SerializedStreamedSpanContainer } from '@sentry/core';
import { afterAll, describe, expect } from 'vitest';
+import { supports } from '../../../utils';
import { cleanupChildProcesses, createEsmTests, describeWithDockerCompose } from '../../../utils/runner';
// postgres >= 4 publishes `postgres:query` on `node:diagnostics_channel` itself, so these spans come from
@@ -261,17 +262,21 @@ describeWithDockerCompose('postgresjs v4 tracing channel', { workingDirectory: [
{
type: 'PostgresError',
value: 'relation "User" does not exist',
- stacktrace: {
- frames: expect.arrayContaining([
- // v4 rewrites the error stack to point at the caller rather than its own connection code.
- expect.objectContaining({
- module: 'scenario',
- filename: expect.stringMatching(/scenario\.mjs$/),
- lineno: expect.any(Number),
- colno: expect.any(Number),
- }),
- ]),
- },
+ // v4 rewrites the error stack to point at the caller rather than its own connection code.
+ // From 4.2.0 it takes the caller from the async stack trace of the query promise. Bun does
+ // not follow that promise chain, so the stack has no caller frame there.
+ ...(!supports({ runtimes: ['bun'] }) && {
+ stacktrace: {
+ frames: expect.arrayContaining([
+ expect.objectContaining({
+ module: 'scenario',
+ filename: expect.stringMatching(/scenario\.mjs$/),
+ lineno: expect.any(Number),
+ colno: expect.any(Number),
+ }),
+ ]),
+ },
+ }),
},
],
},
diff --git a/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument-with-options.mjs b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument-with-options.mjs
new file mode 100644
index 000000000000..6a708121bcf0
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument-with-options.mjs
@@ -0,0 +1,21 @@
+import * as Sentry from '@sentry/node';
+import { loggingTransport } from '@sentry-internal/node-integration-tests';
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ release: '1.0',
+ tracesSampleRate: 1.0,
+ transport: loggingTransport,
+ integrations: [
+ Sentry.tanstackAIIntegration({
+ recordInputs: ({ threadId }) => threadId === 'thread-plain',
+ recordOutputs: false,
+ onSpanStart: (span, { threadId }) => {
+ span.setAttribute('test.start', threadId);
+ },
+ onSpanEnd: (span, _call, { error }) => {
+ span.setAttribute('test.end', error ? 'error' : 'ok');
+ },
+ }),
+ ],
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument.mjs b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument.mjs
new file mode 100644
index 000000000000..384a2f4405e7
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/instrument.mjs
@@ -0,0 +1,16 @@
+import * as Sentry from '@sentry/node';
+import { loggingTransport } from '@sentry-internal/node-integration-tests';
+
+Sentry.init({
+ dsn: 'https://public@dsn.ingest.sentry.io/1337',
+ release: '1.0',
+ tracesSampleRate: 1.0,
+ transport: loggingTransport,
+ integrations: [
+ Sentry.tanstackAIIntegration({
+ onSpanEnd: (span, _call, { error }) => {
+ span.setAttribute('test.error', error?.message);
+ },
+ }),
+ ],
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario-errors.mjs b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario-errors.mjs
new file mode 100644
index 000000000000..c010c1f9458a
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario-errors.mjs
@@ -0,0 +1,53 @@
+import * as Sentry from '@sentry/node';
+import { chat, toolDefinition } from '@tanstack/ai';
+import { fakeText } from '@tanstack/ai/testing';
+
+const getWeather = toolDefinition({
+ name: 'get_weather',
+ description: 'Get the current weather for a city.',
+ inputSchema: { type: 'object', properties: { city: { type: 'string' } } },
+}).server(async () => {
+ throw new Error('Weather service down');
+});
+
+const adapter = fakeText({ model: 'fake-model' });
+adapter.setResponses([
+ { toolCalls: [{ id: 'call_1', name: 'get_weather', input: { city: 'Kyoto' } }] },
+ { text: 'I could not get the weather.' },
+ { error: 'Model overloaded' },
+]);
+
+const stopped = fakeText({ model: 'fake-model' });
+stopped.setResponses([{ text: 'A long answer.' }]);
+
+await Sentry.startSpan({ name: 'main' }, async () => {
+ await chat({
+ adapter,
+ threadId: 'thread-tool-error',
+ messages: [{ role: 'user', content: 'What is the weather in Kyoto?' }],
+ tools: [getWeather],
+ stream: false,
+ });
+
+ try {
+ await chat({
+ adapter,
+ threadId: 'thread-model-error',
+ messages: [{ role: 'user', content: 'Hi' }],
+ stream: false,
+ });
+ } catch {
+ // expected
+ }
+
+ // The app stops reading before the run completes and does not abort it.
+ for await (const chunk of chat({
+ adapter: stopped,
+ threadId: 'thread-stopped',
+ messages: [{ role: 'user', content: 'Hi' }],
+ })) {
+ if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
+ break;
+ }
+ }
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario.mjs b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario.mjs
new file mode 100644
index 000000000000..0b11b720e14a
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/scenario.mjs
@@ -0,0 +1,52 @@
+import * as Sentry from '@sentry/node';
+import { chat, toolDefinition } from '@tanstack/ai';
+import { fakeText } from '@tanstack/ai/testing';
+
+const getWeather = toolDefinition({
+ name: 'get_weather',
+ description: 'Get the current weather for a city.',
+ inputSchema: { type: 'object', properties: { city: { type: 'string' } } },
+}).server(async ({ city }) => ({ city, temperature: 21 }));
+
+const streamed = fakeText({ model: 'fake-model' });
+streamed.setResponses([
+ { text: 'Let me check.', toolCalls: [{ id: 'call_1', name: 'get_weather', input: { city: 'Kyoto' } }] },
+ { text: 'It is 21 degrees in Kyoto.' },
+]);
+
+const plain = fakeText({ model: 'fake-model' });
+plain.setResponses([{ text: 'Hello!' }]);
+
+const structured = fakeText({ model: 'fake-model' });
+structured.setResponses([{ text: '{"city":"Kyoto"}' }]);
+
+await Sentry.startSpan({ name: 'main' }, async () => {
+ // The run starts only when the stream is read, here outside of the span that `chat()` was called in.
+ const stream = Sentry.startSpan({ name: 'create-stream' }, () =>
+ chat({
+ adapter: streamed,
+ threadId: 'thread-stream',
+ systemPrompts: ['You are a weather assistant.'],
+ messages: [{ role: 'user', content: 'What is the weather in Kyoto?' }],
+ tools: [getWeather],
+ modelOptions: { temperature: 0.5 },
+ }),
+ );
+ for await (const _chunk of stream) {
+ // drain
+ }
+
+ await chat({
+ adapter: plain,
+ threadId: 'thread-plain',
+ messages: [{ role: 'user', content: 'Hi' }],
+ stream: false,
+ });
+
+ await chat({
+ adapter: structured,
+ threadId: 'thread-structured',
+ messages: [{ role: 'user', content: 'Which city?' }],
+ outputSchema: { type: 'object', properties: { city: { type: 'string' } } },
+ });
+});
diff --git a/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/test.ts b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/test.ts
new file mode 100644
index 000000000000..8080213e4a2f
--- /dev/null
+++ b/dev-packages/node-integration-tests/suites/tracing/tanstack-ai/test.ts
@@ -0,0 +1,196 @@
+import type { SerializedStreamedSpan } from '@sentry/core';
+import {
+ GEN_AI_CONVERSATION_ID,
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_OUTPUT_MESSAGES,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_REQUEST_TEMPERATURE,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ GEN_AI_TOOL_CALL_RESULT,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_USAGE_INPUT_TOKENS,
+ GEN_AI_USAGE_OUTPUT_TOKENS,
+ SENTRY_OP,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { GEN_AI_CHAT, GEN_AI_EXECUTE_TOOL, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';
+import { afterAll, describe, expect } from 'vitest';
+import { cleanupChildProcesses, createEsmTests } from '../../../utils/runner';
+
+const attr = (span: SerializedStreamedSpan | undefined, key: string): unknown => span?.attributes[key]?.value;
+
+/** The spans of the run with `threadId`, by op, in start order. */
+function runSpans(spans: SerializedStreamedSpan[], threadId: string) {
+ const run = spans
+ .filter(span => attr(span, GEN_AI_CONVERSATION_ID) === threadId)
+ .sort((a, b) => a.start_timestamp - b.start_timestamp);
+ for (const span of run) {
+ expect(attr(span, SENTRY_ORIGIN)).toBe('auto.ai.tanstack_ai');
+ }
+ const agent = run.find(span => attr(span, SENTRY_OP) === GEN_AI_INVOKE_AGENT)!;
+ const children = run.filter(span => span !== agent);
+ for (const child of children) {
+ expect(child.parent_span_id).toBe(agent.span_id);
+ }
+ return {
+ agent,
+ chats: children.filter(span => attr(span, SENTRY_OP) === GEN_AI_CHAT),
+ tools: children.filter(span => attr(span, SENTRY_OP) === GEN_AI_EXECUTE_TOOL),
+ };
+}
+
+describe('TanStack AI integration', () => {
+ afterAll(() => {
+ cleanupChildProcesses();
+ });
+
+ // `@tanstack/ai` is ESM-only.
+ createEsmTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('records the agent run, its model calls and its tool runs', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const spans = container.items;
+ const createStream = spans.find(span => span.name === 'create-stream')!;
+ const main = spans.find(span => span.is_segment)!;
+
+ const streamed = runSpans(spans, 'thread-stream');
+ expect(streamed.agent.parent_span_id).toBe(createStream.span_id);
+ expect(streamed.agent.name).toBe('invoke_agent');
+ expect(attr(streamed.agent, GEN_AI_PROVIDER_NAME)).toBe('fake');
+ expect(attr(streamed.agent, GEN_AI_USAGE_INPUT_TOKENS)).toBeUndefined();
+ expect(JSON.parse(String(attr(streamed.agent, GEN_AI_OUTPUT_MESSAGES)))).toEqual([
+ {
+ role: 'assistant',
+ parts: [{ type: 'text', content: 'It is 21 degrees in Kyoto.' }],
+ finish_reason: 'stop',
+ },
+ ]);
+
+ expect(streamed.chats.map(span => span.name)).toEqual(['chat fake-model', 'chat fake-model']);
+ const [toolCall, answer] = streamed.chats;
+ expect(attr(toolCall, GEN_AI_REQUEST_MODEL)).toBe('fake-model');
+ expect(attr(toolCall, GEN_AI_REQUEST_TEMPERATURE)).toBe(0.5);
+ expect(attr(toolCall, GEN_AI_RESPONSE_STREAMING)).toBe(true);
+ expect(attr(toolCall, GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK)).toBeGreaterThan(0);
+ expect(attr(toolCall, GEN_AI_RESPONSE_FINISH_REASONS)).toBe('["tool_calls"]');
+ expect(attr(toolCall, GEN_AI_USAGE_INPUT_TOKENS)).toBeGreaterThan(0);
+ expect(attr(toolCall, GEN_AI_USAGE_OUTPUT_TOKENS)).toBeGreaterThan(0);
+ expect(attr(toolCall, GEN_AI_TOOL_DEFINITIONS)).toContain('get_weather');
+ expect(attr(toolCall, GEN_AI_SYSTEM_INSTRUCTIONS)).toBe(
+ '[{"type":"text","content":"You are a weather assistant."}]',
+ );
+ expect(JSON.parse(String(attr(toolCall, GEN_AI_INPUT_MESSAGES)))).toEqual([
+ { role: 'user', parts: [{ type: 'text', content: 'What is the weather in Kyoto?' }] },
+ ]);
+ expect(JSON.parse(String(attr(toolCall, GEN_AI_OUTPUT_MESSAGES)))).toEqual([
+ {
+ role: 'assistant',
+ parts: [
+ { type: 'text', content: 'Let me check.' },
+ { type: 'tool_call', id: 'call_1', name: 'get_weather', arguments: '{"city":"Kyoto"}' },
+ ],
+ finish_reason: 'tool_calls',
+ },
+ ]);
+ expect(JSON.parse(String(attr(answer, GEN_AI_INPUT_MESSAGES)))).toHaveLength(3);
+ expect(attr(answer, GEN_AI_RESPONSE_FINISH_REASONS)).toBe('["stop"]');
+
+ expect(streamed.tools).toHaveLength(1);
+ const [tool] = streamed.tools;
+ expect(tool!.name).toBe('execute_tool get_weather');
+ expect(tool!.start_timestamp).toBeGreaterThanOrEqual(toolCall!.end_timestamp);
+ expect(tool!.end_timestamp).toBeLessThanOrEqual(answer!.start_timestamp);
+ expect(attr(tool, 'gen_ai.tool.call.id')).toBe('call_1');
+ expect(attr(tool, GEN_AI_TOOL_CALL_ARGUMENTS)).toBe('{"city":"Kyoto"}');
+ expect(attr(tool, GEN_AI_TOOL_CALL_RESULT)).toBe('{"city":"Kyoto","temperature":21}');
+
+ const plain = runSpans(spans, 'thread-plain');
+ expect(plain.agent.parent_span_id).toBe(main.span_id);
+ expect(plain.chats).toHaveLength(1);
+ expect(attr(plain.agent, GEN_AI_RESPONSE_STREAMING)).toBe(false);
+ expect(attr(plain.chats[0], GEN_AI_RESPONSE_STREAMING)).toBe(false);
+ expect(attr(plain.chats[0], GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK)).toBeUndefined();
+
+ const structured = runSpans(spans, 'thread-structured');
+ expect(structured.chats).toHaveLength(1);
+ expect(attr(structured.chats[0], GEN_AI_RESPONSE_STREAMING)).toBe(false);
+ expect(attr(structured.chats[0], GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK)).toBeUndefined();
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario-errors.mjs', 'instrument.mjs', (createRunner, test) => {
+ test('marks failed tool runs, model calls and stopped streams, and captures the tool error', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ event: {
+ exception: {
+ values: [
+ expect.objectContaining({
+ value: 'Weather service down',
+ mechanism: expect.objectContaining({ type: 'auto.ai.tanstack_ai', handled: false }),
+ }),
+ ],
+ },
+ },
+ })
+ .expect({
+ span: container => {
+ const toolError = runSpans(container.items, 'thread-tool-error');
+ expect(toolError.agent.status).toBe('ok');
+ expect(toolError.tools[0]!.status).toBe('error');
+ expect(attr(toolError.tools[0], GEN_AI_TOOL_CALL_RESULT)).toBeUndefined();
+
+ const modelError = runSpans(container.items, 'thread-model-error');
+ expect(modelError.agent.status).toBe('error');
+ expect(modelError.chats.map(span => span.status)).toEqual(['error']);
+ expect(attr(modelError.chats[0], 'test.error')).toBe('Model overloaded');
+
+ // `onAbort` ends these spans. Span streaming sends the `cancelled` status as `ok`.
+ const stopped = runSpans(container.items, 'thread-stopped');
+ expect(stopped.chats).toHaveLength(1);
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+
+ createEsmTests(__dirname, 'scenario.mjs', 'instrument-with-options.mjs', (createRunner, test) => {
+ test('decides the recording per call and runs the span hooks for every span', async () => {
+ await createRunner()
+ .unordered()
+ .expect({
+ span: container => {
+ const streamed = runSpans(container.items, 'thread-stream');
+ const plain = runSpans(container.items, 'thread-plain');
+ const all = [streamed.agent, ...streamed.chats, ...streamed.tools, plain.agent, ...plain.chats];
+
+ expect(all).toHaveLength(6);
+ for (const span of all) {
+ expect(attr(span, 'test.start')).toBe(attr(span, GEN_AI_CONVERSATION_ID));
+ expect(attr(span, 'test.end')).toBe('ok');
+ expect(attr(span, GEN_AI_OUTPUT_MESSAGES)).toBeUndefined();
+ }
+ expect(attr(streamed.chats[0], GEN_AI_INPUT_MESSAGES)).toBeUndefined();
+ expect(attr(streamed.tools[0], GEN_AI_TOOL_CALL_ARGUMENTS)).toBeUndefined();
+ expect(attr(streamed.tools[0], GEN_AI_TOOL_CALL_RESULT)).toBeUndefined();
+ expect(attr(plain.chats[0], GEN_AI_INPUT_MESSAGES)).toBeDefined();
+ },
+ })
+ .start()
+ .completed();
+ });
+ });
+});
diff --git a/packages/astro/src/index.server.ts b/packages/astro/src/index.server.ts
index 37fa15243c9d..473210567191 100644
--- a/packages/astro/src/index.server.ts
+++ b/packages/astro/src/index.server.ts
@@ -104,6 +104,7 @@ export {
mistralAIIntegration,
openAIIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
langChainIntegration,
diff --git a/packages/aws-serverless/src/index.ts b/packages/aws-serverless/src/index.ts
index 3d8b79f8d7ab..75469faf9db1 100644
--- a/packages/aws-serverless/src/index.ts
+++ b/packages/aws-serverless/src/index.ts
@@ -64,6 +64,7 @@ export {
mistralAIIntegration,
openAIIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
langChainIntegration,
diff --git a/packages/bun/src/index.ts b/packages/bun/src/index.ts
index 5c280f00bae4..0c56bc9a6841 100644
--- a/packages/bun/src/index.ts
+++ b/packages/bun/src/index.ts
@@ -88,6 +88,7 @@ export {
mistralAIIntegration,
openAIIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
langChainIntegration,
diff --git a/packages/bundler-plugins/src/core/component-annotation-oxc-ast.ts b/packages/bundler-plugins/src/core/component-annotation-oxc-ast.ts
index d4bf47387ad7..d59d3be8d0e8 100644
--- a/packages/bundler-plugins/src/core/component-annotation-oxc-ast.ts
+++ b/packages/bundler-plugins/src/core/component-annotation-oxc-ast.ts
@@ -47,12 +47,6 @@ export type ParseAstAsync = (code: string, options: { lang: 'jsx' | 'tsx' }) =>
export type MagicStringLike = {
appendLeft(offset: number, content: string): void;
toString(): string;
- generateMap?(options: {
- file?: string;
- source?: string;
- includeContent?: boolean;
- hires?: boolean | 'boundary';
- }): SourceMap | string;
};
export type ComponentAnnotationTransformMeta = {
diff --git a/packages/bundler-plugins/src/core/component-annotation-oxc.ts b/packages/bundler-plugins/src/core/component-annotation-oxc.ts
index 3efa49e929a4..53a125d30b15 100644
--- a/packages/bundler-plugins/src/core/component-annotation-oxc.ts
+++ b/packages/bundler-plugins/src/core/component-annotation-oxc.ts
@@ -1,12 +1,13 @@
import path from 'node:path';
-import MagicString from 'magic-string';
+import MagicString, { SourceMap } from 'magic-string';
import { KNOWN_INCOMPATIBLE_PLUGINS } from '../babel-plugin/constants';
import { stripQueryAndHashFromPath } from './utils';
-import { isAstNode } from './component-annotation-oxc-ast';
+import { isAstNode, walkAst } from './component-annotation-oxc-ast';
import { collectOxcComponentAnnotationInsertions } from './component-annotation-oxc-walk';
import type {
+ AstNode,
AttributeInsertion,
ComponentAnnotationTransformMeta,
ComponentAnnotationTransformResult,
@@ -85,15 +86,63 @@ function makeAttributeText(
return `${prefix}${attributeText}${suffix}`;
}
-function getMagicString(
- code: string,
- meta?: ComponentAnnotationTransformMeta,
-): { magicString: MagicStringLike; isNative: boolean } {
- if (meta?.magicString) {
- return { magicString: meta.magicString, isNative: true };
+function collectIdentifierNamesByOffset(ast: AstNode): Map {
+ const namesByOffset = new Map();
+
+ walkAst(ast, node => {
+ if (
+ (node.type === 'Identifier' || node.type === 'JSXIdentifier') &&
+ typeof node.name === 'string' &&
+ typeof node.start === 'number'
+ ) {
+ namesByOffset.set(node.start, node.name);
+ }
+ });
+
+ return namesByOffset;
+}
+
+// SWC, which runs after this transform in Next.js, takes names only from the
+// input map when it composes maps. Without names here, stack frames show
+// minified function names.
+function generateMapWithNames(magicString: MagicString, code: string, ast: AstNode, source: string): SourceMap {
+ const map = magicString.generateDecodedMap({
+ source,
+ includeContent: true,
+ hires: true,
+ });
+
+ const namesByOffset = collectIdentifierNamesByOffset(ast);
+ const lineOffsets = [0];
+ for (let i = code.indexOf('\n'); i !== -1; i = code.indexOf('\n', i + 1)) {
+ lineOffsets.push(i + 1);
}
- return { magicString: new MagicString(code), isNative: false };
+ const nameIndices = new Map();
+ for (const line of map.mappings) {
+ for (let i = 0; i < line.length; i++) {
+ const segment = line[i];
+ if (segment?.length !== 4) {
+ continue;
+ }
+
+ const [generatedColumn, sourceIndex, sourceLine, sourceColumn] = segment;
+ const name = namesByOffset.get((lineOffsets[sourceLine] ?? NaN) + sourceColumn);
+ if (name === undefined) {
+ continue;
+ }
+
+ let nameIndex = nameIndices.get(name);
+ if (nameIndex === undefined) {
+ nameIndex = map.names.push(name) - 1;
+ nameIndices.set(name, nameIndex);
+ }
+
+ line[i] = [generatedColumn, sourceIndex, sourceLine, sourceColumn, nameIndex];
+ }
+ }
+
+ return new SourceMap(map);
}
async function annotateWithOxcParser(
@@ -124,28 +173,28 @@ async function annotateWithOxcParser(
return null;
}
- const { magicString, isNative } = getMagicString(code, meta);
-
- for (const insertion of insertions) {
- magicString.appendLeft(insertion.offset, makeAttributeText(code, insertion.offset, insertion.attributes));
+ if (meta?.magicString) {
+ applyInsertions(meta.magicString, code, insertions);
+ return { code: meta.magicString as unknown as string };
}
- if (isNative) {
- return { code: magicString as unknown as string };
- }
+ const magicString = new MagicString(code);
+ applyInsertions(magicString, code, insertions);
return {
code: magicString.toString(),
// No `file`, because magic-string would then make `source` relative to it
// and drop the directory from `sources`.
- map: magicString.generateMap?.({
- source: idWithoutQueryAndHash,
- includeContent: true,
- hires: true,
- }),
+ map: generateMapWithNames(magicString, code, ast, idWithoutQueryAndHash),
};
}
+function applyInsertions(magicString: MagicStringLike, code: string, insertions: AttributeInsertion[]): void {
+ for (const insertion of insertions) {
+ magicString.appendLeft(insertion.offset, makeAttributeText(code, insertion.offset, insertion.attributes));
+ }
+}
+
export function createOxcComponentNameAnnotateHooks(
ignoredComponents: string[],
getParseAstAsync: () => Promise,
diff --git a/packages/bundler-plugins/src/rewriter/ast.ts b/packages/bundler-plugins/src/rewriter/ast.ts
index 49bd57b584e0..1ec522cf418d 100644
--- a/packages/bundler-plugins/src/rewriter/ast.ts
+++ b/packages/bundler-plugins/src/rewriter/ast.ts
@@ -99,6 +99,25 @@ export function declarationOf(node: BaseNode): BaseNode | null | undefined {
return node.type === 'ExportNamedDeclaration' ? (node as ExportNamedNode).declaration : node;
}
+/**
+ * The expression a class extends, looking through parentheses and through
+ * an assignment that caches it. Decorator transforms emit that assignment,
+ * as in `class A extends (_Base = Base)`.
+ */
+export function superClassTarget(superClass: BaseNode | null | undefined): BaseNode | null | undefined {
+ let node = superClass;
+ while (node) {
+ if (node.type === 'ParenthesizedExpression') {
+ node = (node as BaseNode & { expression?: BaseNode }).expression;
+ } else if (node.type === 'AssignmentExpression' && (node as BaseNode & { operator?: string }).operator === '=') {
+ node = (node as BaseNode & { right?: BaseNode }).right;
+ } else {
+ break;
+ }
+ }
+ return node;
+}
+
/** Whether `node` calls `methodName`, either bare (`fn()`) or as a member (`ns.fn()`). */
export function isCallToMethod(node: BaseNode, methodName: string): boolean {
if (node.type !== 'CallExpression') return false;
diff --git a/packages/bundler-plugins/src/rewriter/class-extends.ts b/packages/bundler-plugins/src/rewriter/class-extends.ts
index 4afce1447aee..6df3e6f45860 100644
--- a/packages/bundler-plugins/src/rewriter/class-extends.ts
+++ b/packages/bundler-plugins/src/rewriter/class-extends.ts
@@ -6,7 +6,7 @@ import type {
MemberExpressionNode,
ProgramBody,
} from './ast';
-import { declarationOf } from './ast';
+import { declarationOf, superClassTarget } from './ast';
/** A base class, named by the module it is imported from and its export name. */
export interface BaseClassRef {
@@ -81,11 +81,12 @@ function collectBaseImports(ast: ProgramBody, base: BaseClassRef): BaseBindings
}
function extendsBase(
- superClass: BaseNode | null | undefined,
+ node: BaseNode | null | undefined,
base: BaseClassRef,
bases: BaseBindings,
detected: Set,
): boolean {
+ const superClass = superClassTarget(node);
if (!superClass) return false;
if (superClass.type === 'Identifier') {
const name = (superClass as IdentifierNode).name;
diff --git a/packages/bundler-plugins/src/rewriter/module-shape.ts b/packages/bundler-plugins/src/rewriter/module-shape.ts
index 2b16b0f7ab77..05d8c2daa72b 100644
--- a/packages/bundler-plugins/src/rewriter/module-shape.ts
+++ b/packages/bundler-plugins/src/rewriter/module-shape.ts
@@ -9,7 +9,7 @@ import type {
MemberExpressionNode,
ProgramBody,
} from './ast';
-import { exportedName, isTypeOnlyExport } from './ast';
+import { exportedName, isTypeOnlyExport, superClassTarget } from './ast';
import { langFromId, parseModule } from './parse';
/** Binding name used for a module's default export. */
@@ -109,7 +109,8 @@ export function shapeFromSource(code: string, id: string): ModuleShape | undefin
return undefined;
}
-function superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined {
+function superRefFromNode(node: BaseNode | null | undefined): SuperRef | undefined {
+ const superClass = superClassTarget(node);
if (!superClass) return undefined;
if (superClass.type === 'Identifier') {
diff --git a/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts b/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts
index bc64b293c4af..a81a6a900542 100644
--- a/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts
+++ b/packages/bundler-plugins/test/core/component-annotation-oxc.test.ts
@@ -1,6 +1,6 @@
import { parseSync, transformAsync, traverse, types as t } from '@babel/core';
import { parse } from '@babel/parser';
-import MagicString from 'magic-string';
+import MagicString, { type SourceMap } from 'magic-string';
import { describe, expect, it, vi } from 'vitest';
import componentNameAnnotatePlugin, { experimentalComponentNameAnnotatePlugin } from '../../src/babel-plugin';
@@ -485,6 +485,18 @@ export const List = (props: Props) => {
await annotateWithBabel(code, id, ignoredComponents, true),
);
});
+
+ it('keeps identifier names in the source map', async () => {
+ const code = `export function LoginButton() {
+ function handleLogin() {}
+ return Log in ;
+}`;
+
+ const result = await annotateWithOxc(code, '/src/login-button.tsx', [], getParseAstAsync);
+ const map = result?.map as SourceMap;
+
+ expect(map.names).toEqual(['LoginButton', 'handleLogin', 'button', 'onClick']);
+ });
});
describe('createOxcComponentNameAnnotateHooks', () => {
diff --git a/packages/bundler-plugins/test/rewriter/class-extends.test.ts b/packages/bundler-plugins/test/rewriter/class-extends.test.ts
index a9774c65ac46..7c0b78a03511 100644
--- a/packages/bundler-plugins/test/rewriter/class-extends.test.ts
+++ b/packages/bundler-plugins/test/rewriter/class-extends.test.ts
@@ -64,6 +64,18 @@ describe('findClassesExtending', () => {
expect(findClassesExtending(parseModule(code.join('\n'), 'module.ts'), BASE)).toEqual(new Set());
});
+ it('finds a class whose base is cached in an assignment', () => {
+ const code = [
+ "import { WorkerEntrypoint } from 'cloudflare:workers';",
+ "import * as cf from 'cloudflare:workers';",
+ 'var _WE, _cf;',
+ 'class A extends (_WE = WorkerEntrypoint) {}',
+ 'class B extends (_cf = cf.WorkerEntrypoint) {}',
+ 'class C extends (_WE = A) {}',
+ ];
+ expect(find(code.join('\n'))).toEqual(new Set(['A', 'B', 'C']));
+ });
+
it('ignores classes without the base import', () => {
expect(find('class A extends B {}')).toEqual(new Set());
});
diff --git a/packages/bundler-plugins/test/rewriter/module-shape.test.ts b/packages/bundler-plugins/test/rewriter/module-shape.test.ts
index 13ebf2981c69..2fddb84d5ecd 100644
--- a/packages/bundler-plugins/test/rewriter/module-shape.test.ts
+++ b/packages/bundler-plugins/test/rewriter/module-shape.test.ts
@@ -20,6 +20,22 @@ describe('shapeFromAst', () => {
);
});
+ // Decorator transforms emit this form, e.g. Babel's for `@callable()`.
+ it('reads the superclass through an assignment that caches it', () => {
+ const shape = shapeFromAst(
+ parseModule(
+ ['var _B, _D;', 'class A extends (_B = B) {}', 'class C extends (_D = ns.D) {}'].join('\n'),
+ 'module.js',
+ ),
+ );
+ expect(shape.classes).toEqual(
+ new Map([
+ ['A', { kind: 'identifier', name: 'B' }],
+ ['C', { kind: 'member', object: 'ns', property: 'D' }],
+ ]),
+ );
+ });
+
it('collects named, default and namespace imports', () => {
const shape = shapeFromAst(
parseModule("import Def, { a as b, c } from 'm';\nimport * as ns from 'n';", 'module.js'),
diff --git a/packages/cloudflare/src/index.ts b/packages/cloudflare/src/index.ts
index 7d36839a6857..f57747d6b042 100644
--- a/packages/cloudflare/src/index.ts
+++ b/packages/cloudflare/src/index.ts
@@ -203,6 +203,7 @@ export {
redisIntegration,
SentryMastraExporter,
tediousIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
} from '@sentry/server-utils';
diff --git a/packages/cloudflare/src/vite/moduleShape.ts b/packages/cloudflare/src/vite/moduleShape.ts
index edb1a81c0dfb..8a4553548d16 100644
--- a/packages/cloudflare/src/vite/moduleShape.ts
+++ b/packages/cloudflare/src/vite/moduleShape.ts
@@ -18,6 +18,11 @@ interface MemberExpressionNode extends BaseNode {
property?: { type: string; name?: string };
}
+interface AssignmentExpressionNode extends BaseNode {
+ operator?: string;
+ right?: BaseNode;
+}
+
interface ImportSpecifierNode {
type: string;
imported?: { type: string; name?: string };
@@ -133,7 +138,20 @@ export function shapeFromAst(ast: ProgramBody): ModuleShape {
return shape;
}
-function superRefFromNode(superClass: BaseNode | null | undefined): SuperRef | undefined {
+/**
+ * Babel's decorator transform memoizes the superclass of a decorated class, so
+ * `class A extends Agent` reaches us as `class A extends (_Agent = Agent)`.
+ */
+export function unwrapSuperClass(superClass: BaseNode | null | undefined): BaseNode | undefined {
+ let node = superClass ?? undefined;
+ while (node?.type === 'AssignmentExpression' && (node as AssignmentExpressionNode).operator === '=') {
+ node = (node as AssignmentExpressionNode).right;
+ }
+ return node;
+}
+
+function superRefFromNode(rawSuperClass: BaseNode | null | undefined): SuperRef | undefined {
+ const superClass = unwrapSuperClass(rawSuperClass);
if (!superClass) return undefined;
if (superClass.type === 'Identifier') {
diff --git a/packages/cloudflare/src/vite/workerEntrypoint.ts b/packages/cloudflare/src/vite/workerEntrypoint.ts
index 35433f46b46d..0d0b3218178e 100644
--- a/packages/cloudflare/src/vite/workerEntrypoint.ts
+++ b/packages/cloudflare/src/vite/workerEntrypoint.ts
@@ -1,3 +1,4 @@
+import { unwrapSuperClass } from './moduleShape';
import type { BaseNode, ProgramBody } from './transform';
// ---------------------------------------------------------------------------
@@ -119,10 +120,11 @@ function collectWorkerEntrypointImports(ast: ProgramBody): WorkerEntrypointBases
* `ns.WorkerEntrypoint` member access off a namespace import.
*/
function extendsWorkerEntrypoint(
- superClass: BaseNode | null | undefined,
+ rawSuperClass: BaseNode | null | undefined,
bases: WorkerEntrypointBases,
detected: Set,
): boolean {
+ const superClass = unwrapSuperClass(rawSuperClass);
if (!superClass) return false;
if (superClass.type === 'Identifier') {
const name = (superClass as IdentifierNode).name;
diff --git a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts
index 37150a1a28bc..6b4f5788c4c9 100644
--- a/packages/cloudflare/src/wrapRequestHandlerWithInit.ts
+++ b/packages/cloudflare/src/wrapRequestHandlerWithInit.ts
@@ -27,6 +27,37 @@ function getRequestErrorMechanismType(context: ExecutionContextCompat | undefine
return isDurableObjectContext(context) ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';
}
+/**
+ * vinext's Workers Cache adapter issues its response-stage request with internal data:
+ * `__vinext_*` query parameters and `x-vinext-internal-*` headers, which can carry unfiltered
+ * query values. The SDK must not record them. Returns the original request when it carries no
+ * vinext data, so non-vinext traffic is untouched.
+ */
+function stripVinextInternalData(
+ request: Request | CfProperties>,
+): Request | CfProperties> {
+ if (!request.url.includes('__vinext_cache_key=')) {
+ return request;
+ }
+
+ try {
+ const url = new URL(request.url);
+ url.searchParams.delete('__vinext_cache_key');
+
+ const headers = new Headers(request.headers);
+ for (const name of [...headers.keys()]) {
+ if (name.startsWith('x-vinext-internal-')) {
+ headers.delete(name);
+ }
+ }
+
+ // No body: the handler reads the body of the original request.
+ return new Request(url.toString(), { method: request.method, headers, cf: request.cf });
+ } catch {
+ return request;
+ }
+}
+
export interface RequestHandlerWrapperOptions {
options: CloudflareOptions;
request: Request | CfProperties>;
@@ -119,7 +150,7 @@ export function wrapRequestHandlerWithInit(
// See: https://developers.cloudflare.com/workers/runtime-apis/performance/
return wrapServerRequestHandler(
{
- request,
+ request: stripVinextInternalData(request),
client,
// Without `AsyncLocalStorage`, `withInvocationIsolationScope` does not fork, and the scope it
// passes in is not the current one. The request data has to go on the current scope, where
diff --git a/packages/cloudflare/test/vite/agentClass.test.ts b/packages/cloudflare/test/vite/agentClass.test.ts
index 90fbea795d90..14c65a59a002 100644
--- a/packages/cloudflare/test/vite/agentClass.test.ts
+++ b/packages/cloudflare/test/vite/agentClass.test.ts
@@ -81,6 +81,20 @@ describe('detectAgentClasses', () => {
expect(await detect(code)).toContain('Leaf');
});
+ it('detects a class whose superclass Babel memoized into an assignment', async () => {
+ const code = [
+ "import { Agent } from 'agents';",
+ "import { MyBase } from './base';",
+ 'var _Agent, _MyBase;',
+ 'export class MyAgent extends (_Agent = Agent) {}',
+ 'export class DerivedAgent extends (_MyBase = MyBase) {}',
+ ].join('\n');
+ const modules = {
+ '/app/src/base.js': ["import { Agent } from 'agents';", 'export class MyBase extends Agent {}'].join('\n'),
+ };
+ expect(await detect(code, modules)).toEqual(new Set(['MyAgent', 'DerivedAgent']));
+ });
+
it('resolves a base class imported from another module', async () => {
const code = ["import { MyBase } from './base';", 'export class MyAgent extends MyBase {}'].join('\n');
const modules = {
diff --git a/packages/cloudflare/test/vite/transform.test.ts b/packages/cloudflare/test/vite/transform.test.ts
index bc99d7133f5b..7a6c9ff1fecb 100644
--- a/packages/cloudflare/test/vite/transform.test.ts
+++ b/packages/cloudflare/test/vite/transform.test.ts
@@ -857,6 +857,18 @@ describe('WorkerEntrypoint class wrapping (structural)', () => {
expect(result.code).toContain('export { __SENTRY_WRAPPED_AdminEntry__ as AdminEntry };');
});
+ it('wraps a class whose superclass Babel memoized into an assignment', () => {
+ const code = [
+ "import { WorkerEntrypoint } from 'cloudflare:workers';",
+ 'var _WorkerEntrypoint;',
+ 'export class AdminEntry extends (_WorkerEntrypoint = WorkerEntrypoint) {}',
+ ].join('\n');
+
+ const result = transform(code, ctx)!;
+ expect(result.code).toContain('const __SENTRY_WRAPPED_AdminEntry__ = __SENTRY__.withSentry(');
+ expect(result.code).toContain('export { __SENTRY_WRAPPED_AdminEntry__ as AdminEntry };');
+ });
+
it('wraps a class extending an aliased WorkerEntrypoint import', () => {
const code = [
"import { WorkerEntrypoint as WE } from 'cloudflare:workers';",
diff --git a/packages/deno/src/index.ts b/packages/deno/src/index.ts
index e76ae70e0ed1..1ef503d086e5 100644
--- a/packages/deno/src/index.ts
+++ b/packages/deno/src/index.ts
@@ -195,6 +195,7 @@ export {
openAIIntegration,
pinoIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
postgresIntegration,
diff --git a/packages/elysia/src/index.ts b/packages/elysia/src/index.ts
index 3e595fe76d4e..9dd1d86c3e06 100644
--- a/packages/elysia/src/index.ts
+++ b/packages/elysia/src/index.ts
@@ -63,6 +63,7 @@ export {
mistralAIIntegration,
openAIIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
langChainIntegration,
diff --git a/packages/google-cloud-serverless/src/index.ts b/packages/google-cloud-serverless/src/index.ts
index df6a6bd3f97c..6c46a3d6f913 100644
--- a/packages/google-cloud-serverless/src/index.ts
+++ b/packages/google-cloud-serverless/src/index.ts
@@ -64,6 +64,7 @@ export {
mistralAIIntegration,
openAIIntegration,
groqIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
langChainIntegration,
diff --git a/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts b/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts
index c37599e69fcb..8393ff9e6fc0 100644
--- a/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts
+++ b/packages/nextjs/src/client/routing/pagesRouterRoutingInstrumentation.ts
@@ -1,11 +1,18 @@
import type { Client } from '@sentry/core';
-import { debug, hasSpanStreamingEnabled, PAGELOAD_SPAN_NAME_FALLBACK, parseBaggageHeader } from '@sentry/core';
+import {
+ debug,
+ extractTraceparentData,
+ hasSpanStreamingEnabled,
+ PAGELOAD_SPAN_NAME_FALLBACK,
+ parseBaggageHeader,
+} from '@sentry/core';
import { startBrowserTracingPageLoadSpan, WINDOW } from '@sentry/react';
import type { NEXT_DATA } from 'next/dist/shared/lib/utils';
import type { ParsedUrlQuery } from 'querystring';
import { DEBUG_BUILD } from '../../common/debug-build';
import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
import { PAGELOAD } from '@sentry/conventions/op';
+import { getServerTimingEntry } from './traceMetaTags';
const globalObject = WINDOW;
@@ -113,10 +120,50 @@ export function pagesRouterInstrumentPageLoad(client: Client): void {
...(params && { ...params }),
},
},
- { sentryTrace, baggage },
+ // Turbopack does not wrap data fetchers, so `__NEXT_DATA__` has no trace and the header has to tell the tags apart.
+ getForeignTraceMetaTags(sentryTrace || getServerTimingEntry('sentry-trace')?.description) ?? {
+ sentryTrace,
+ baggage,
+ },
);
}
+/**
+ * Finds `sentry-trace` and `baggage` meta tags that belong to another trace than the one of the server
+ * request. Next.js renders the trace of the request into the same kind of tags, so a
+ * tag is only known to come from somewhere else, e.g. from a mobile SDK that wants its WebView to
+ * continue the trace of the app, when its trace ID differs.
+ */
+function getForeignTraceMetaTags(
+ serverSentryTrace: string | undefined,
+): { sentryTrace: string; baggage: string } | undefined {
+ const serverTraceId = extractTraceparentData(serverSentryTrace)?.traceId;
+ if (!serverTraceId) {
+ return undefined;
+ }
+
+ const metaContents = (name: string): string[] =>
+ Array.from(globalObject.document.querySelectorAll(`meta[name="${name}"]`))
+ .map(tag => tag.getAttribute('content'))
+ .filter((content): content is string => !!content);
+
+ for (const sentryTrace of metaContents('sentry-trace')) {
+ const traceId = extractTraceparentData(sentryTrace)?.traceId;
+ if (!traceId || traceId === serverTraceId) {
+ continue;
+ }
+
+ // Without a baggage of its own, the browser SDK would fall back to the first `baggage` tag of the
+ // document, which can be the one of the server trace, and combine two traces.
+ const baggage = metaContents('baggage').find(value => parseBaggageHeader(value)?.['sentry-trace_id'] === traceId);
+ if (baggage) {
+ return { sentryTrace, baggage };
+ }
+ }
+
+ return undefined;
+}
+
/**
* Matches a pathname against the Pages Router build manifest, e.g. `/users/1` -> `/users/[id]`.
*
diff --git a/packages/nextjs/src/client/routing/traceMetaTags.ts b/packages/nextjs/src/client/routing/traceMetaTags.ts
index d17a67fc877d..35df2734792e 100644
--- a/packages/nextjs/src/client/routing/traceMetaTags.ts
+++ b/packages/nextjs/src/client/routing/traceMetaTags.ts
@@ -40,15 +40,20 @@ export function readTraceMetaTags(): TraceMetaTagValues | undefined {
return document && sentryTrace ? { sentryTrace, baggage: lastMetaContent(document, 'baggage') } : undefined;
}
+/** An entry of the `Server-Timing` header of the document, which a self-hosted server sends the trace in. */
+export function getServerTimingEntry(name: string): PerformanceServerTiming | undefined {
+ // The cast is required for the declaration build, which resolves `getEntriesByType('navigation')`
+ // to `PerformanceEntry[]` without `serverTiming`.
+ const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;
+ return navigation?.serverTiming?.find(entry => entry.name === name);
+}
+
/**
* Whether the response carried the trace in a `Server-Timing` header. The generic browser tracing
* integration continues it when it starts the pageload, so there is nothing to wait for.
*/
export function hasServerTimingTraceContext(): boolean {
- // The cast is required for the declaration build, which resolves `getEntriesByType('navigation')`
- // to `PerformanceEntry[]` without `serverTiming`.
- const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;
- return !!navigation?.serverTiming?.some(entry => entry.name === 'sentry-trace');
+ return !!getServerTimingEntry('sentry-trace');
}
/**
diff --git a/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts b/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts
index fb7dc10c3019..c393914439f6 100644
--- a/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts
+++ b/packages/nextjs/test/performance/pagesRouterInstrumentation.test.ts
@@ -58,6 +58,7 @@ describe('pagesRouterInstrumentPageLoad', () => {
props?: any;
navigatableRoutes?: string[];
hasNextData: boolean;
+ head?: string;
}) {
const nextDataContent: NEXT_DATA = {
props: pageProperties.props,
@@ -73,7 +74,7 @@ describe('pagesRouterInstrumentPageLoad', () => {
const dom = new JSDOM(
// Just an example of what a __NEXT_DATA__ tag might look like
pageProperties.hasNextData
- ? ``
+ ? `${pageProperties.head ?? ''}`
: 'No next data :( ',
{ url: pageProperties.url },
);
@@ -213,6 +214,118 @@ describe('pagesRouterInstrumentPageLoad', () => {
);
},
);
+
+ describe('with trace meta tags in the document', () => {
+ const SERVER_TRACE_ID = 'c82b8554881b4d28ad977de04a4fb40a';
+ const FOREIGN_TRACE_ID = '12345678901234567890123456789012';
+ const nextDataTrace = {
+ sentryTrace: `${SERVER_TRACE_ID}-a755953cd3394d5f-1`,
+ baggage: `sentry-trace_id=${SERVER_TRACE_ID},sentry-release=2.1.0,sentry-environment=myEnv`,
+ };
+ // Next.js renders these for the request, with the span that was active while the document rendered.
+ const serverMetaTags = ` `;
+ const foreignTrace = {
+ sentryTrace: `${FOREIGN_TRACE_ID}-1234567890123456-1`,
+ baggage: `sentry-trace_id=${FOREIGN_TRACE_ID},sentry-release=mobile`,
+ };
+ const foreignMetaTags = ` `;
+
+ function instrumentPageLoad(
+ head: string,
+ pageProps: Record = {
+ _sentryTraceData: nextDataTrace.sentryTrace,
+ _sentryBaggage: nextDataTrace.baggage,
+ },
+ route = '/some-page',
+ ): ReturnType {
+ setUpNextPage({ url: 'https://example.com/some-page', route, props: { pageProps }, hasNextData: true, head });
+ const emit = vi.fn();
+ pagesRouterInstrumentPageLoad({ emit, getOptions: () => ({}) } as unknown as Client);
+ return emit;
+ }
+
+ it.each([
+ ['before the meta tags of the server', `${foreignMetaTags}${serverMetaTags}`],
+ ['after the meta tags of the server', `${serverMetaTags}${foreignMetaTags}`],
+ ['without meta tags of the server', foreignMetaTags],
+ ])('continues the trace of meta tags that belong to another trace, %s', (_, head) => {
+ const emit = instrumentPageLoad(head);
+
+ expect(emit).toHaveBeenCalledTimes(1);
+ expect(emit).toHaveBeenCalledWith(
+ 'startPageLoadSpan',
+ expect.objectContaining({ name: '/some-page' }),
+ foreignTrace,
+ );
+ });
+
+ it.each([
+ ['the meta tags of the server', serverMetaTags],
+ ['an empty `sentry-trace` meta tag', ' '],
+ ['a `sentry-trace` meta tag without content', ' '],
+ ['an invalid `sentry-trace` meta tag', ' '],
+ [
+ 'a `sentry-trace` meta tag of another trace without its baggage',
+ `${serverMetaTags} `,
+ ],
+ ['only a `baggage` meta tag of another trace', ` `],
+ ['unrelated meta tags', ' '],
+ ])('keeps the `__NEXT_DATA__` trace with %s', (_, head) => {
+ const emit = instrumentPageLoad(head);
+
+ expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), nextDataTrace);
+ });
+
+ describe('when `__NEXT_DATA__` has no trace', () => {
+ const noTrace = { sentryTrace: undefined, baggage: undefined };
+
+ function setServerTimingTrace(sentryTrace: string): void {
+ vi.spyOn(performance, 'getEntriesByType').mockReturnValue([
+ {
+ serverTiming: [{ name: 'sentry-trace', description: sentryTrace, duration: 0 }],
+ } as unknown as PerformanceEntry,
+ ]);
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('continues the trace of meta tags that belong to another trace than the `Server-Timing` header', () => {
+ setServerTimingTrace(nextDataTrace.sentryTrace);
+ const emit = instrumentPageLoad(`${serverMetaTags}${foreignMetaTags}`, {});
+
+ expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), foreignTrace);
+ });
+
+ it('leaves the meta tags of the server to the browser SDK', () => {
+ setServerTimingTrace(nextDataTrace.sentryTrace);
+ const emit = instrumentPageLoad(serverMetaTags, {});
+
+ expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), noTrace);
+ });
+
+ it('leaves the meta tags to the browser SDK without a `Server-Timing` header', () => {
+ const emit = instrumentPageLoad(`${serverMetaTags}${foreignMetaTags}`, {});
+
+ expect(emit).toHaveBeenCalledWith('startPageLoadSpan', expect.anything(), noTrace);
+ });
+ });
+
+ it('still names an `/_error` pageload after the `__NEXT_DATA__` baggage', () => {
+ const emit = instrumentPageLoad(
+ foreignMetaTags,
+ { _sentryTraceData: nextDataTrace.sentryTrace, _sentryBaggage: 'sentry-transaction=GET /users/[id]' },
+ '/_error',
+ );
+
+ expect(emit).toHaveBeenCalledWith(
+ 'startPageLoadSpan',
+ expect.objectContaining({ name: '/users/[id]' }),
+ foreignTrace,
+ );
+ });
+ });
});
describe('pagesRouterInstrumentNavigation', () => {
diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts
index a536903d06dd..5e5e73c2dbc2 100644
--- a/packages/node/src/index.ts
+++ b/packages/node/src/index.ts
@@ -48,6 +48,7 @@ export {
nitroIntegration,
openAIIntegration,
pinoIntegration,
+ tanstackAIIntegration,
togetherAIIntegration,
typesafeIntegration,
postgresIntegration,
diff --git a/packages/server-utils/src/ai/tanstack-ai/constants.ts b/packages/server-utils/src/ai/tanstack-ai/constants.ts
new file mode 100644
index 000000000000..ab47bfc6420c
--- /dev/null
+++ b/packages/server-utils/src/ai/tanstack-ai/constants.ts
@@ -0,0 +1,9 @@
+export const TANSTACK_AI_INTEGRATION_NAME = 'TanStackAI' as const;
+
+export const TANSTACK_AI_ORIGIN = 'auto.ai.tanstack_ai';
+
+/**
+ * Marks our middleware, so a `chat()` call that already has it does not get a second one.
+ * `Symbol.for`, so that two copies of the SDK in one process see each other's middleware.
+ */
+export const TANSTACK_AI_MIDDLEWARE_BRAND = Symbol.for('sentry.tanstack-ai.middleware');
diff --git a/packages/server-utils/src/ai/tanstack-ai/index.ts b/packages/server-utils/src/ai/tanstack-ai/index.ts
new file mode 100644
index 000000000000..b366f1fb2a58
--- /dev/null
+++ b/packages/server-utils/src/ai/tanstack-ai/index.ts
@@ -0,0 +1,319 @@
+import type { Span, SpanStatus } from '@sentry/core';
+import {
+ captureException,
+ getActiveSpan,
+ SPAN_STATUS_ERROR,
+ startInactiveSpan,
+ stringify,
+ withActiveSpan,
+} from '@sentry/core';
+import {
+ GEN_AI_AGENT_NAME,
+ GEN_AI_CONVERSATION_ID,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ GEN_AI_REQUEST_MODEL,
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ GEN_AI_RESPONSE_ID,
+ GEN_AI_RESPONSE_MODEL,
+ GEN_AI_RESPONSE_STREAMING,
+ GEN_AI_TOOL_CALL_ARGUMENTS,
+ GEN_AI_TOOL_CALL_RESULT,
+ GEN_AI_TOOL_DEFINITIONS,
+ GEN_AI_TOOL_DESCRIPTION,
+ GEN_AI_TOOL_NAME,
+ SENTRY_ORIGIN,
+} from '@sentry/conventions/attributes';
+import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';
+import type { GenAiSpanHooks } from '../core/span-hooks';
+import { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';
+import { recordTimeToFirstChunk } from '../core/time-to-first-chunk';
+import type { GenAiCallOptions } from '../core/utils';
+import { getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, setOutputMessagesAttribute } from '../core/utils';
+import { TANSTACK_AI_MIDDLEWARE_BRAND, TANSTACK_AI_ORIGIN } from './constants';
+import type {
+ TanstackAICallInfo,
+ TanstackAIChatMiddleware,
+ TanstackAIMiddlewareConfig,
+ TanstackAIMiddlewareContext,
+} from './types';
+import { getInputAttributes, getProviderName, getRequestAttributes, getRunError, getUsageAttributes } from './utils';
+
+/**
+ * `call` is the options object of the `chat()` call. The recording options run when `chat()` is
+ * called. The hooks run for every span (`invoke_agent`, `chat` and `execute_tool`) while the run is
+ * read, which can be in another async context than the call. `onSpanEnd` gets the `error` of a
+ * failed run or tool.
+ */
+export type TanstackAIOptions = GenAiCallOptions & GenAiSpanHooks;
+
+// The chunks that carry model output. The adapters send `RUN_STARTED` before the provider answers.
+const OUTPUT_CHUNK_TYPES = new Set(['TEXT_MESSAGE_CONTENT', 'TOOL_CALL_START', 'REASONING_MESSAGE_CONTENT']);
+
+/**
+ * Makes the chat middleware for one `chat()` call. Call it when `chat()` is called: the parent of the
+ * `invoke_agent` span is the span that is active then, and the recording options are decided then.
+ * The middleware cannot make its spans active, so the spans of other work in the run do not nest
+ * below them.
+ */
+export function createTanstackAIMiddleware(
+ options: TanstackAIOptions,
+ call: TanstackAICallInfo,
+): TanstackAIChatMiddleware {
+ const parentSpan = getActiveSpan() ?? null;
+ const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
+ // `ctx.streaming` is also true when `chat()` returns a promise, because `chat()` reads the same stream
+ // inside. With `outputSchema`, `chat()` streams only with `stream: true`.
+ const streaming = call.outputSchema ? call.stream === true : call.stream !== false;
+
+ let agentSpan: Span | undefined;
+ let chatSpan: Span | undefined;
+ let outputText = '';
+ let outputToolCalls: Array<{ id: string; name?: string; arguments: unknown }> = [];
+ // `TOOL_CALL_END` has the arguments but not the name, which only `TOOL_CALL_START` has.
+ const toolCallNames = new Map();
+ const toolSpans = new Map();
+
+ const startSpan = (spanOptions: Parameters[0]): Span => {
+ const span = startInactiveSpan(spanOptions);
+ runGenAiSpanStart(options, span, call);
+ return span;
+ };
+
+ const endSpan = (span: Span, status?: SpanStatus, error?: unknown): void => {
+ if (status) {
+ span.setStatus(status);
+ }
+ runGenAiSpanEnd(options, span, call, status ? { error } : {});
+ span.end();
+ };
+
+ const endChatSpan = (status?: SpanStatus, error?: unknown): void => {
+ if (chatSpan) {
+ endSpan(chatSpan, status, error);
+ chatSpan = undefined;
+ }
+ };
+
+ const endRun = (status?: SpanStatus, error?: unknown): void => {
+ if (!agentSpan) {
+ return;
+ }
+ for (const span of toolSpans.values()) {
+ endSpan(span, status, error);
+ }
+ toolSpans.clear();
+ endChatSpan(status, error);
+ endSpan(agentSpan, status, error);
+ agentSpan = undefined;
+ };
+
+ const startChatSpan = (ctx: TanstackAIMiddlewareContext, config: TanstackAIMiddlewareConfig): Span => {
+ outputText = '';
+ outputToolCalls = [];
+ toolCallNames.clear();
+
+ return startSpan({
+ name: `chat ${ctx.model}`,
+ op: getGenAiSpanOp('chat'),
+ parentSpan: agentSpan,
+ attributes: {
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
+ [GEN_AI_OPERATION_NAME]: 'chat',
+ [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
+ [GEN_AI_REQUEST_MODEL]: ctx.model,
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
+ [GEN_AI_RESPONSE_STREAMING]: streaming,
+ ...getRequestAttributes(config.modelOptions),
+ // The `structuredOutput` call sends no tools, but its config still lists them.
+ ...(recordInputs && config.tools.length && ctx.phase !== 'structuredOutput'
+ ? {
+ [GEN_AI_TOOL_DEFINITIONS]: stringify(
+ config.tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
+ ),
+ }
+ : {}),
+ // A middleware can send the provider other messages than the history of the run.
+ ...(recordInputs ? getInputAttributes(config.providerMessages ?? config.messages, config.systemPrompts) : {}),
+ },
+ });
+ };
+
+ return {
+ name: 'sentry',
+ [TANSTACK_AI_MIDDLEWARE_BRAND]: true,
+
+ onConfig(ctx, config) {
+ // `init` runs once per run, before `onStart` and before any tool can run.
+ if (ctx.phase === 'init' && !agentSpan) {
+ const agentName = ctx.subagentName;
+ agentSpan = startSpan({
+ name: agentName ? `invoke_agent ${agentName}` : 'invoke_agent',
+ op: getGenAiSpanOp('invoke_agent'),
+ parentSpan,
+ attributes: {
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
+ [GEN_AI_OPERATION_NAME]: 'invoke_agent',
+ [GEN_AI_PROVIDER_NAME]: getProviderName(ctx),
+ [GEN_AI_REQUEST_MODEL]: ctx.model,
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
+ [GEN_AI_RESPONSE_STREAMING]: streaming,
+ [GEN_AI_AGENT_NAME]: agentName,
+ ...(recordInputs ? getInputAttributes(config.messages, config.systemPrompts) : {}),
+ },
+ });
+ }
+
+ // `beforeModel` starts each model call of the agent loop. `structuredOutput` starts the
+ // separate last call for `outputSchema`.
+ if (!agentSpan || (ctx.phase !== 'beforeModel' && ctx.phase !== 'structuredOutput')) {
+ return;
+ }
+ // A model call that completes ends its span at the `afterModel` boundary. A span that is still
+ // open here is of a call that failed and that a middleware retried with `ctx.retry()`.
+ endChatSpan({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
+ chatSpan = startChatSpan(ctx, config);
+ },
+
+ onChunk(ctx, chunk) {
+ if (!agentSpan) {
+ return;
+ }
+ if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {
+ // TanStack sets the call metadata of the `structuredOutput` call only after `onConfig`.
+ const provider = getProviderName(ctx);
+ chatSpan?.setAttribute(GEN_AI_PROVIDER_NAME, provider);
+ agentSpan.setAttribute(GEN_AI_PROVIDER_NAME, provider);
+ }
+ // A provider error ends the run with this chunk. `chat({ stream: false })` then throws and
+ // stops reading, so TanStack calls no terminal hook.
+ if (chunk.type === 'RUN_ERROR') {
+ endRun(getErrorStatus(ctx.signal), getRunError(chunk));
+ return;
+ }
+ // A run that stops at an interrupt ends with this chunk. For an interrupt at `beforeModel` or
+ // `afterModel`, TanStack calls no terminal hook.
+ if (chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt') {
+ endRun();
+ return;
+ }
+ if (!chatSpan) {
+ return;
+ }
+
+ if (streaming && OUTPUT_CHUNK_TYPES.has(chunk.type)) {
+ recordTimeToFirstChunk(chatSpan);
+ }
+
+ if (chunk.type === 'TEXT_MESSAGE_CONTENT' && recordOutputs && chunk.delta) {
+ outputText += chunk.delta;
+ } else if (chunk.type === 'TOOL_CALL_START' && chunk.toolCallId && chunk.toolCallName) {
+ toolCallNames.set(chunk.toolCallId, chunk.toolCallName);
+ } else if (chunk.type === 'TOOL_CALL_END' && recordOutputs && chunk.toolCallId) {
+ outputToolCalls.push({
+ id: chunk.toolCallId,
+ name: toolCallNames.get(chunk.toolCallId),
+ arguments: chunk.input ?? {},
+ });
+ } else if (chunk.type === 'RUN_FINISHED') {
+ // An adapter can report these only in the `metadata.tanstack` of the chunk. TanStack copies
+ // them into `callMetadata` before the middleware gets the chunk.
+ const responseModel = chunk.model ?? ctx.callMetadata?.model;
+ const responseId = chunk.responseId ?? ctx.callMetadata?.responseId;
+ const finishReason = chunk.finishReason ?? undefined;
+ if (finishReason) {
+ chatSpan.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, stringify([finishReason]));
+ }
+ // The agent span keeps the response of the last model call, which is the answer of the run.
+ for (const span of [chatSpan, agentSpan]) {
+ if (responseModel) {
+ span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel);
+ }
+ if (responseId) {
+ span.setAttribute(GEN_AI_RESPONSE_ID, responseId);
+ }
+ if (recordOutputs) {
+ setOutputMessagesAttribute(span, { responseText: outputText, toolCalls: outputToolCalls, finishReason });
+ }
+ }
+ }
+ },
+
+ // Runs after each model call and before the tools it asked for, so the `chat` span does not
+ // include the tools.
+ onInterruptBoundary(ctx) {
+ if (ctx.phase === 'afterModel') {
+ endChatSpan();
+ }
+ },
+
+ onUsage(_ctx, usage) {
+ chatSpan?.setAttributes(getUsageAttributes(usage));
+ },
+
+ // The guards run after all `onBeforeToolCall` decisions and after the input check, so `args`
+ // are the arguments that the tool gets.
+ onGuardToolCall(ctx, { toolName, toolCallId, args, tool }) {
+ // A client tool runs in the browser, not here.
+ if (!agentSpan || (tool && typeof tool.execute !== 'function')) {
+ return;
+ }
+ toolSpans.set(
+ toolCallId,
+ startSpan({
+ name: `execute_tool ${toolName}`,
+ op: getGenAiSpanOp('execute_tool'),
+ parentSpan: agentSpan,
+ attributes: {
+ [SENTRY_ORIGIN]: TANSTACK_AI_ORIGIN,
+ [GEN_AI_OPERATION_NAME]: 'execute_tool',
+ [GEN_AI_TOOL_NAME]: toolName,
+ [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: toolCallId,
+ [GEN_AI_CONVERSATION_ID]: ctx.threadId,
+ [GEN_AI_TOOL_DESCRIPTION]: tool?.description,
+ ...(recordInputs ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),
+ },
+ }),
+ );
+ },
+
+ onAfterToolCall(ctx, { toolCallId, ok, result, error }) {
+ const span = toolSpans.get(toolCallId);
+ if (!span) {
+ return;
+ }
+ toolSpans.delete(toolCallId);
+
+ if (recordOutputs && ok && result !== undefined) {
+ span.setAttribute(GEN_AI_TOOL_CALL_RESULT, typeof result === 'string' ? result : stringify(result));
+ }
+ if (ok) {
+ endSpan(span);
+ return;
+ }
+ // TanStack fails each tool that did not start yet with an `Operation aborted` error.
+ const status = getErrorStatus(ctx.signal);
+ if (status.message === 'internal_error') {
+ // TanStack gives a tool failure back to the model as the tool result, so the error handlers
+ // of the app never see it.
+ withActiveSpan(span, () => {
+ captureException(error, { mechanism: { type: TANSTACK_AI_ORIGIN, handled: false } });
+ });
+ }
+ endSpan(span, status, error);
+ },
+
+ onFinish() {
+ endRun();
+ },
+
+ // Also for an abort from a middleware, which leaves the signal of the caller alone.
+ onAbort() {
+ endRun({ code: SPAN_STATUS_ERROR, message: 'cancelled' });
+ },
+
+ onError(ctx, { error }) {
+ endRun(getErrorStatus(ctx.signal), error);
+ },
+ };
+}
diff --git a/packages/server-utils/src/ai/tanstack-ai/types.ts b/packages/server-utils/src/ai/tanstack-ai/types.ts
new file mode 100644
index 000000000000..a923333481a3
--- /dev/null
+++ b/packages/server-utils/src/ai/tanstack-ai/types.ts
@@ -0,0 +1,109 @@
+/**
+ * The parts of the `@tanstack/ai` 1.x chat middleware contract that we use. `@tanstack/ai` is not a
+ * dependency of this package, so these mirror `ChatMiddleware`, `ChatMiddlewareContext` and
+ * `ChatMiddlewareConfig`.
+ */
+
+import type { TANSTACK_AI_MIDDLEWARE_BRAND } from './constants';
+
+/** The options of a `chat()` call. The recording options and the span hooks get this object. */
+export interface TanstackAICallInfo {
+ threadId?: string;
+ stream?: boolean;
+ outputSchema?: unknown;
+ middleware?: unknown;
+ [key: string]: unknown;
+}
+
+/** Mirrors `TokenUsage`. */
+export interface TanstackAIUsage {
+ promptTokens?: number;
+ completionTokens?: number;
+ totalTokens?: number;
+ promptTokensDetails?: { cachedTokens?: number; cacheWriteTokens?: number };
+ completionTokensDetails?: { reasoningTokens?: number };
+}
+
+export interface TanstackAITool {
+ name: string;
+ description?: string;
+ inputSchema?: unknown;
+ execute?: unknown;
+}
+
+/** Mirrors `ModelMessage`. */
+export interface TanstackAIModelMessage {
+ role: 'user' | 'assistant' | 'tool';
+ content: string | null | Array<{ type: string; content?: string }>;
+ toolCalls?: Array<{ id: string; function?: { name: string; arguments: string } }>;
+ toolCallId?: string;
+}
+
+export type TanstackAISystemPrompt = string | { content: string };
+
+export interface TanstackAIMiddlewareContext {
+ phase: string;
+ /** The adapter name, for example `openai-chat`. */
+ provider: string;
+ model: string;
+ threadId: string;
+ subagentName?: string;
+ /** The metadata of the current model call. TanStack sets it when the model call starts. */
+ callMetadata?: { model?: string; responseId?: string; source?: { provider?: string } };
+ signal?: AbortSignal;
+}
+
+export interface TanstackAIMiddlewareConfig {
+ messages: TanstackAIModelMessage[];
+ /** The messages sent to the provider, when a middleware makes them different from `messages`. */
+ providerMessages?: TanstackAIModelMessage[];
+ systemPrompts: TanstackAISystemPrompt[];
+ tools: TanstackAITool[];
+ modelOptions?: Record;
+}
+
+/** A stream chunk: an AG-UI event, discriminated by `type`. */
+export interface TanstackAIChunk {
+ type: string;
+ delta?: string;
+ model?: string;
+ responseId?: string;
+ finishReason?: string | null;
+ toolCallId?: string;
+ toolCallName?: string;
+ input?: unknown;
+ /** `{ type: 'interrupt' }` on the `RUN_FINISHED` chunk of a run that stops at an interrupt. */
+ outcome?: { type: string };
+ /** The error of a `RUN_ERROR` chunk. */
+ error?: { message: string; code?: string };
+ message?: string;
+ code?: string;
+}
+
+export interface TanstackAIToolCallHookContext {
+ toolName: string;
+ toolCallId: string;
+ args: unknown;
+ tool?: TanstackAITool;
+}
+
+export interface TanstackAIAfterToolCallInfo {
+ toolCallId: string;
+ ok: boolean;
+ result?: unknown;
+ error?: unknown;
+}
+
+export interface TanstackAIChatMiddleware {
+ name: string;
+ [TANSTACK_AI_MIDDLEWARE_BRAND]: true;
+ onConfig(ctx: TanstackAIMiddlewareContext, config: TanstackAIMiddlewareConfig): void;
+ onChunk(ctx: TanstackAIMiddlewareContext, chunk: TanstackAIChunk): void;
+ onInterruptBoundary(ctx: TanstackAIMiddlewareContext): void;
+ onUsage(ctx: TanstackAIMiddlewareContext, usage: TanstackAIUsage): void;
+ onGuardToolCall(ctx: TanstackAIMiddlewareContext, hookCtx: TanstackAIToolCallHookContext): void;
+ onAfterToolCall(ctx: TanstackAIMiddlewareContext, info: TanstackAIAfterToolCallInfo): void;
+ onFinish(ctx: TanstackAIMiddlewareContext): void;
+ onAbort(ctx: TanstackAIMiddlewareContext): void;
+ onError(ctx: TanstackAIMiddlewareContext, info: { error: unknown }): void;
+}
diff --git a/packages/server-utils/src/ai/tanstack-ai/utils.ts b/packages/server-utils/src/ai/tanstack-ai/utils.ts
new file mode 100644
index 000000000000..b5c40dce737c
--- /dev/null
+++ b/packages/server-utils/src/ai/tanstack-ai/utils.ts
@@ -0,0 +1,109 @@
+import { stringify } from '@sentry/core';
+import {
+ GEN_AI_INPUT_MESSAGES,
+ GEN_AI_REQUEST_MAX_TOKENS,
+ GEN_AI_REQUEST_TEMPERATURE,
+ GEN_AI_REQUEST_TOP_P,
+ GEN_AI_SYSTEM_INSTRUCTIONS,
+ GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
+} from '@sentry/conventions/attributes';
+import { getTokenUsageAttributes } from '../core/utils';
+import type {
+ TanstackAIChunk,
+ TanstackAIMiddlewareContext,
+ TanstackAIModelMessage,
+ TanstackAISystemPrompt,
+ TanstackAIUsage,
+} from './types';
+
+/**
+ * `ctx.provider` is the adapter name, which for some adapters also names the API (for example
+ * `openrouter-responses`). The call metadata has the provider of the adapter, but only after the
+ * first model call started.
+ */
+export function getProviderName(ctx: TanstackAIMiddlewareContext): string {
+ return ctx.callMetadata?.source?.provider ?? ctx.provider;
+}
+
+export function getInputAttributes(
+ messages: ReadonlyArray,
+ systemPrompts: ReadonlyArray,
+): Record {
+ return {
+ [GEN_AI_INPUT_MESSAGES]: stringify(messages.map(toGenAiMessage)),
+ [GEN_AI_SYSTEM_INSTRUCTIONS]: systemPrompts.length
+ ? stringify(
+ systemPrompts.map(prompt => ({
+ type: 'text',
+ content: typeof prompt === 'string' ? prompt : prompt.content,
+ })),
+ )
+ : undefined,
+ };
+}
+
+/**
+ * TanStack AI has no common option for temperature, top p or max tokens. Each adapter takes them in
+ * `modelOptions` and passes them to the provider with the provider's key name (snake_case or camelCase,
+ * and `max_tokens` or `max_output_tokens`). So we take the first of the known keys that has a value.
+ */
+export function getRequestAttributes(modelOptions: Record = {}): Record {
+ const pick = (...keys: string[]): number | undefined => {
+ for (const key of keys) {
+ const value = modelOptions[key];
+ if (typeof value === 'number') {
+ return value;
+ }
+ }
+ return undefined;
+ };
+ return {
+ [GEN_AI_REQUEST_TEMPERATURE]: pick('temperature'),
+ [GEN_AI_REQUEST_TOP_P]: pick('top_p', 'topP'),
+ [GEN_AI_REQUEST_MAX_TOKENS]: pick('max_tokens', 'maxTokens', 'max_output_tokens', 'maxOutputTokens'),
+ };
+}
+
+export function getUsageAttributes(usage: TanstackAIUsage): Record {
+ const attributes = getTokenUsageAttributes(
+ usage.promptTokens,
+ usage.completionTokens,
+ usage.promptTokensDetails?.cacheWriteTokens,
+ usage.promptTokensDetails?.cachedTokens,
+ usage.totalTokens,
+ );
+ if (typeof usage.completionTokensDetails?.reasoningTokens === 'number') {
+ attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS] = usage.completionTokensDetails.reasoningTokens;
+ }
+ return attributes;
+}
+
+function toGenAiMessage(message: TanstackAIModelMessage): Record {
+ const parts: Array> = [];
+ const { content } = message;
+
+ if (message.role === 'tool') {
+ parts.push({ type: 'tool_call_response', id: message.toolCallId, result: content });
+ } else if (typeof content === 'string') {
+ parts.push({ type: 'text', content });
+ } else if (Array.isArray(content)) {
+ for (const part of content) {
+ // Media parts carry inline data or provider handles, so keep only their type.
+ parts.push(part.type === 'text' ? { type: 'text', content: part.content } : { type: part.type });
+ }
+ }
+ for (const toolCall of message.toolCalls ?? []) {
+ parts.push({
+ type: 'tool_call',
+ id: toolCall.id,
+ name: toolCall.function?.name,
+ arguments: toolCall.function?.arguments,
+ });
+ }
+ return { role: message.role, parts };
+}
+
+/** The error of a `RUN_ERROR` chunk. */
+export function getRunError(chunk: TanstackAIChunk): { message?: string; code?: string } {
+ return chunk.error ?? { message: chunk.message, code: chunk.code };
+}
diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts
index 7a3fccd1fadb..3bd0e0d1cbb6 100644
--- a/packages/server-utils/src/index.ts
+++ b/packages/server-utils/src/index.ts
@@ -66,6 +66,8 @@ export { createFlueInstrumentation } from './ai/flue';
export { flueIntegration } from './integrations/flue';
export { piAiIntegration } from './integrations/pi-ai';
export { piDurableIntegration } from './integrations/pi-durable';
+export { tanstackAIIntegration } from './integrations/tanstack-ai';
+export type { TanstackAIOptions } from './ai/tanstack-ai';
export type { FlueOptions } from './ai/flue';
export { mastraIntegration } from './integrations/mastra';
export { mcpServerIntegration } from './integrations/mcp-server';
diff --git a/packages/server-utils/src/integrations/tanstack-ai.ts b/packages/server-utils/src/integrations/tanstack-ai.ts
new file mode 100644
index 000000000000..bc65554ff81e
--- /dev/null
+++ b/packages/server-utils/src/integrations/tanstack-ai.ts
@@ -0,0 +1,82 @@
+import * as diagnosticsChannel from '../utils/diagnosticsChannel';
+import type { IntegrationFn } from '@sentry/core';
+import { consoleSandbox, defineIntegration, isObjectLike } from '@sentry/core';
+import type { TanstackAIOptions } from '../ai/tanstack-ai';
+import { createTanstackAIMiddleware } from '../ai/tanstack-ai';
+import { TANSTACK_AI_INTEGRATION_NAME, TANSTACK_AI_MIDDLEWARE_BRAND } from '../ai/tanstack-ai/constants';
+import { CHANNELS } from '../orchestrion/channels';
+import { tanstackAiModuleNames } from '../orchestrion/config/tanstack-ai';
+import { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';
+import type { OrchestrionChannelContext } from '../orchestrion/types';
+import { safeChannelCallback } from '../tracing-channel';
+
+const _tanstackAIIntegration = ((options: TanstackAIOptions = {}) => {
+ return {
+ name: TANSTACK_AI_INTEGRATION_NAME,
+ setup(client) {
+ // Adding the middleware starts no span, so the subscription does not need the binding.
+ invokeOrchestrionInstrumentation(client, tanstackAiModuleNames, instrumentTanstackAI, [options], {
+ requiresTracingChannelBinding: false,
+ });
+ },
+ };
+}) satisfies IntegrationFn;
+
+let warnedOtelMiddleware = false;
+
+function instrumentTanstackAI(options: TanstackAIOptions): void {
+ diagnosticsChannel.tracingChannel(CHANNELS.TANSTACK_AI_CHAT).start.subscribe(message => {
+ safeChannelCallback(() => {
+ const data = message as OrchestrionChannelContext;
+ const call = data.arguments[0];
+ if (!isObjectLike(call)) {
+ return;
+ }
+ const existing = call.middleware;
+ // `chat()` throws for middleware that is not an array. Leave that error to it.
+ if (existing !== undefined && !Array.isArray(existing)) {
+ return;
+ }
+ if (existing?.some(entry => isObjectLike(entry) && entry[TANSTACK_AI_MIDDLEWARE_BRAND])) {
+ return;
+ }
+ if (existing?.some(entry => isObjectLike(entry) && entry.name === 'otel')) {
+ warnOtelMiddleware();
+ }
+ // Last, so that it records the config and the chunks after the other middleware changed them.
+ // A copy, so that options which the app uses again do not collect one middleware per call.
+ data.arguments[0] = {
+ ...call,
+ middleware: [...(existing ?? []), createTanstackAIMiddleware(options, call)],
+ };
+ });
+ });
+}
+
+function warnOtelMiddleware(): void {
+ if (warnedOtelMiddleware) {
+ return;
+ }
+ warnedOtelMiddleware = true;
+ consoleSandbox(() => {
+ // eslint-disable-next-line no-console
+ console.warn(
+ "[Sentry] `tanstackAIIntegration` is active and a `chat()` call also uses TanStack's otelMiddleware, so each run is recorded twice. Remove otelMiddleware to avoid duplicate spans.",
+ );
+ });
+}
+
+/**
+ * Traces the `chat()` calls of TanStack AI (`@tanstack/ai` >= 1.0.0 < 2), through the
+ * `orchestrion:@tanstack/ai:chat` channel. Each call gets a `gen_ai.invoke_agent` span, with a
+ * `gen_ai.chat` span for each model call and a `gen_ai.execute_tool` span for each tool run.
+ * Needs the Sentry runtime hook (`--import`) or bundler plugin.
+ *
+ * @example
+ * ```javascript
+ * Sentry.init({
+ * integrations: [Sentry.tanstackAIIntegration({ recordInputs: true, recordOutputs: true })],
+ * });
+ * ```
+ */
+export const tanstackAIIntegration = defineIntegration(_tanstackAIIntegration);
diff --git a/packages/server-utils/src/orchestrion/channels.ts b/packages/server-utils/src/orchestrion/channels.ts
index 9456854e1201..7cba81286e3b 100644
--- a/packages/server-utils/src/orchestrion/channels.ts
+++ b/packages/server-utils/src/orchestrion/channels.ts
@@ -38,6 +38,7 @@ import { postgresJsChannels } from './config/postgres';
import { prismaChannels } from './config/prisma';
import { redisChannels } from './config/redis';
import { remixChannels } from './config/remix';
+import { tanstackAiChannels } from './config/tanstack-ai';
import { tediousChannels } from './config/tedious';
import { togetherAiChannels } from './config/together-ai';
import { typesafeChannels } from './config/typesafe';
@@ -100,6 +101,7 @@ export const CHANNELS = {
...prismaChannels,
...redisChannels,
...remixChannels,
+ ...tanstackAiChannels,
...tediousChannels,
...togetherAiChannels,
...typesafeChannels,
diff --git a/packages/server-utils/src/orchestrion/config/index.ts b/packages/server-utils/src/orchestrion/config/index.ts
index 9ef0d96ade50..91f6b139f553 100644
--- a/packages/server-utils/src/orchestrion/config/index.ts
+++ b/packages/server-utils/src/orchestrion/config/index.ts
@@ -45,6 +45,7 @@ import { prismaConfig } from './prisma';
import { redisConfig } from './redis';
import { remixConfig } from './remix';
import { remixV3Config } from './remix-v3';
+import { tanstackAiConfig } from './tanstack-ai';
import { tediousConfig } from './tedious';
import { togetherAiConfig } from './together-ai';
import { typesafeConfig } from './typesafe';
@@ -109,6 +110,7 @@ export const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [
...redisConfig,
...remixConfig,
...remixV3Config,
+ ...tanstackAiConfig,
...tediousConfig,
...togetherAiConfig,
...typesafeConfig,
diff --git a/packages/server-utils/src/orchestrion/config/tanstack-ai.ts b/packages/server-utils/src/orchestrion/config/tanstack-ai.ts
new file mode 100644
index 000000000000..fdd7f020f6e8
--- /dev/null
+++ b/packages/server-utils/src/orchestrion/config/tanstack-ai.ts
@@ -0,0 +1,19 @@
+import type { InstrumentationConfig } from '../apmTypes';
+import { getModuleNames } from './module-names';
+
+// `chat()` takes its middleware per call, and `@tanstack/ai` has no global middleware registry, so
+// the integration changes the options of each call. `chat` returns a stream or a promise, depending
+// on `stream`, but it runs nothing before it returns, so `Sync` is enough: we only need `start`.
+export const tanstackAiConfig = [
+ {
+ channelName: 'chat',
+ module: { name: '@tanstack/ai', versionRange: '>=1.0.0 <2.0.0', filePath: 'dist/esm/activities/chat/index.js' },
+ functionQuery: { functionName: 'chat', kind: 'Sync' },
+ },
+] satisfies InstrumentationConfig[];
+
+export const tanstackAiModuleNames = getModuleNames(tanstackAiConfig);
+
+export const tanstackAiChannels = {
+ TANSTACK_AI_CHAT: 'orchestrion:@tanstack/ai:chat',
+} as const;
diff --git a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts
index 2e60db9729c0..5a01b551e6b1 100644
--- a/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts
+++ b/packages/server-utils/test/orchestrion/moduleInjectedTransform.test.ts
@@ -44,7 +44,8 @@ describe('channel integration definitions', () => {
// `@nestjs/*` and `@remix-run/*` are covered by listeners in their own SDK packages.
// Each cron monitor is billed, so bundler-only SDKs must not install crons integrations for every app.
- const optIn = new Set(['cron', 'node-cron', 'node-schedule']);
+ // `@tanstack/ai` stays opt-in until the provider SDK calls of its adapters stop getting a second span.
+ const optIn = new Set(['cron', 'node-cron', 'node-schedule', '@tanstack/ai']);
const uncovered = [...configured].filter(
name => !defined.has(name) && !optIn.has(name) && !name.startsWith('@nestjs/') && !name.startsWith('@remix-run/'),
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e0258ab48e4c..ba3a29258177 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -729,6 +729,9 @@ importers:
'@smithy/node-http-handler':
specifier: 4.12.1
version: 4.12.1
+ '@tanstack/ai':
+ specifier: ^1.8.0
+ version: 1.8.0(@opentelemetry/api@1.9.0)(zod@4.6.7)
'@types/express':
specifier: ^4.17.21
version: 4.17.21
@@ -2584,6 +2587,14 @@ packages:
'@adobe/css-tools@4.4.3':
resolution: {integrity: sha512-VQKMkwriZbaOgVCby1UDY/LDk5fIjhQicCvVPFqfe+69fWaPWydbWJ3wRt59/YzIwda1I81loas3oCoHxnqvdA==}
+ '@ag-ui/core@1.0.0':
+ resolution: {integrity: sha512-yCRhsQvb4+lmGMrDsi4TOJxqKpm/kb3H64wwL+Z90jNVrkhy17RErfzsNgybfbjNKLM0nenEDYDVJsZHJJSigQ==}
+ peerDependencies:
+ zod: ^3.25.18 || ^4.0.0
+ peerDependenciesMeta:
+ zod:
+ optional: true
+
'@ai-sdk/gateway@3.0.142':
resolution: {integrity: sha512-Y1iwdxdebYXpoK5y/4CrcCfJGeFwEJWlEx+pMWIg/ZVWGi9KA+JXM7YBkhxcshpq/jAXx8YyQeFMyZr0TGfXZQ==}
engines: {node: '>=18'}
@@ -8154,6 +8165,26 @@ packages:
'@swc/helpers@0.5.15':
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
+ '@tanstack/ai-event-client@1.1.0':
+ resolution: {integrity: sha512-g4ctAzbvC1CuAjjTnp8iH5hlnFzVPJybVhuRMItUb5ISC4bQsrhUyhrsZ4QHW1brEpaAhfdss+MpdWux+7glUw==}
+
+ '@tanstack/ai-utils@1.1.0':
+ resolution: {integrity: sha512-li47v/794azVLourgteS/+jjH/ZF+cIp/3RMVA1VybtKAFiMy3ZGxREU10OzfUghMzYLdfpK2l6ahvlWxNVHug==}
+
+ '@tanstack/ai@1.8.0':
+ resolution: {integrity: sha512-y6Ya7qweT4U8gsi/t16cQkHXB2SLxmVJBvvjEPdkSvgDqGeea6LWRk3vpjzs12IsNAHK231DY9t4hTC0x3ZiAw==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.9.0'
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+
+ '@tanstack/devtools-event-client@0.4.4':
+ resolution: {integrity: sha512-6T5Yop/793YI+H+5J8Hsyj4kCih9sl4t3ElLgKioW5hk3ocn+ZdSJ94tT7vL7uabxSugWYBZlOTMPzEw2puvQw==}
+ engines: {node: '>=18'}
+ hasBin: true
+
'@tanstack/directive-functions-plugin@1.121.21':
resolution: {integrity: sha512-B9z/HbF7gJBaRHieyX7f2uQ4LpLLAVAEutBZipH6w+CYD6RHRJvSVPzECGHF7icFhNWTiJQL2QR6K07s59yzEw==}
engines: {node: '>=12'}
@@ -11630,6 +11661,9 @@ packages:
resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}
engines: {node: '>=8.6.0'}
+ fast-json-patch@3.1.2:
+ resolution: {integrity: sha512-Dhr5mVii8hIvjkp0Xdrun9B3GlXe3j+L4Ymv8J0h3Di996xoBi8qSDQ/sqSNKZd1NEqx55ZfcseG1MphW7MkHg==}
+
fast-json-stable-stringify@2.1.0:
resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}
@@ -18536,6 +18570,10 @@ snapshots:
'@adobe/css-tools@4.4.3': {}
+ '@ag-ui/core@1.0.0(zod@4.6.7)':
+ optionalDependencies:
+ zod: 4.6.7
+
'@ai-sdk/gateway@3.0.142(zod@4.6.7)':
dependencies:
'@ai-sdk/provider': 3.0.13
@@ -26117,6 +26155,28 @@ snapshots:
dependencies:
tslib: 2.8.1
+ '@tanstack/ai-event-client@1.1.0':
+ dependencies:
+ '@tanstack/devtools-event-client': 0.4.4
+
+ '@tanstack/ai-utils@1.1.0': {}
+
+ '@tanstack/ai@1.8.0(@opentelemetry/api@1.9.0)(zod@4.6.7)':
+ dependencies:
+ '@ag-ui/core': 1.0.0(zod@4.6.7)
+ '@cfworker/json-schema': 4.1.1
+ '@standard-schema/spec': 1.1.0
+ '@tanstack/ai-event-client': 1.1.0
+ '@tanstack/ai-utils': 1.1.0
+ fast-json-patch: 3.1.2
+ partial-json: 0.1.7
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ transitivePeerDependencies:
+ - zod
+
+ '@tanstack/devtools-event-client@0.4.4': {}
+
'@tanstack/directive-functions-plugin@1.121.21(supports-color@10.0.0)(vite@8.3.6(@types/node@20.19.43)(esbuild@0.28.1)(jiti@2.7.0)(less@4.2.0(supports-color@10.0.0))(sass@1.72.0)(stylus@0.59.0(supports-color@10.0.0))(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))':
dependencies:
'@babel/code-frame': 7.26.2
@@ -30489,6 +30549,8 @@ snapshots:
merge2: 1.4.1
micromatch: 4.0.8
+ fast-json-patch@3.1.2: {}
+
fast-json-stable-stringify@2.1.0: {}
fast-json-stringify@6.4.0: