Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,36 @@ const clientChunkUrls = emittedJsFiles(CLIENT_OUTPUT).map(
);
assert.ok(clientChunkUrls.length > 0, `Expected client chunks in ${CLIENT_OUTPUT}`);

// --- The release reaches the client through the page, so that it changes no content hash ---

/** `release.name` in `vite.config.ts`. */
const RELEASE = 'test-release';

assert.deepEqual(
emittedJsFiles(CLIENT_OUTPUT).filter(file => fs.readFileSync(file, 'utf8').includes(RELEASE)),
[],
`Expected no client chunk in ${CLIENT_OUTPUT} to contain the release`,
);

const RELEASE_META_TAG = `<meta name="sentry-release" content="${RELEASE}"/></head>`;

// `vite.config.ts` prerenders `/prerendered` and renders the SPA shell at build time.
for (const page of ['_shell.html', path.join('prerendered', 'index.html')]) {
assert.ok(
fs.readFileSync(path.join(CLIENT_OUTPUT, page), 'utf8').includes(RELEASE_META_TAG),
`Expected the build to write the release at the end of the head of ${page}`,
);
}

const server = await startNodeServer({ entry: path.join(SERVER_OUTPUT, 'index.mjs'), port: 3030 });

try {
const html = await (await fetch(server.baseUrl)).text();
assert.ok(
html.includes(RELEASE_META_TAG),
'Expected the server to write the release at the end of the head of the page',
);
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

// Without this, a server that serves no public files at all would pass the 404 checks.
const chunkStatus = (await fetch(`${server.baseUrl}${clientChunkUrls[0]}`)).status;
assert.equal(chunkStatus, 200, `Expected the server to serve the client chunk ${clientChunkUrls[0]}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createFileRoute } from '@tanstack/react-router';

export const Route = createFileRoute('/prerendered')({
component: Prerendered,
});

function Prerendered() {
return <p>Prerendered at build time</p>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { defineConfig } from 'vite';

export default defineConfig({
plugins: [
tanstackStart(),
// Prerendering and the SPA shell render pages at build time, which must carry the release as well.
tanstackStart({ prerender: { enabled: true }, pages: [{ path: '/prerendered' }], spa: { enabled: true } }),
nitro(),
viteReact(),
sentryTanstackStart({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: 'https://public@dsn.ingest.sentry.io/1337',
tracesSampleRate: 1.0,
release: 'e2e-test',
tunnel: 'http://localhost:3031/', // proxy server
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/test-utils';

// `release.name` in `vite.config.ts`. The client `Sentry.init` sets no release, so it takes the one the server wrote
// into the page, as the build injects the release into no client chunk.
const RELEASE = 'test-release';

test('Sends client-side errors with the release of the build', async ({ page }) => {
const errorEventPromise = waitForError('tanstackstart-react', errorEvent => {
return errorEvent?.exception?.values?.[0]?.value === 'Sentry Client Test Error';
});

await page.goto('/');
await page.locator('html[data-hydrated="true"]').waitFor();
await page.locator('button').filter({ hasText: 'Break the client' }).click();

const errorEvent = await errorEventPromise;

expect(errorEvent.release).toBe(RELEASE);
});

test('Sends server-side errors with the release of the build', async ({ page }) => {
const errorEventPromise = waitForError('tanstackstart-react', errorEvent => {
return (
errorEvent?.exception?.values?.[0]?.value === 'Sentry API Route Test Error' &&
errorEvent?.exception?.values?.[0]?.mechanism?.type === 'auto.middleware.tanstackstart.request'
);
});

await page.goto('/');
await page.locator('html[data-hydrated="true"]').waitFor();
await page.locator('button').filter({ hasText: 'Break API route' }).click();

const errorEvent = await errorEventPromise;

expect(errorEvent.release).toBe(RELEASE);
});
18 changes: 18 additions & 0 deletions packages/tanstackstart-react/src/client/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { BrowserOptions as ReactBrowserOptions } from '@sentry/react';
import { WINDOW } from '@sentry/react';
import { RELEASE_META_TAG_NAME } from '../common/release';

/**
* Takes the release from the meta tag the server writes into each page, unless `Sentry.init()` sets one.
*/
export function applyReleaseFromMetaTag(options: ReactBrowserOptions): void {
if (options.release !== undefined) {
return;
}

const document = WINDOW.document as typeof WINDOW.document | undefined;
const release = document?.querySelector(`meta[name="${RELEASE_META_TAG_NAME}"]`)?.getAttribute('content');
if (release) {
options.release = release;
}
}
2 changes: 2 additions & 0 deletions packages/tanstackstart-react/src/client/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Client } from '@sentry/core';
import { applySdkMetadata } from '@sentry/core';
import type { BrowserOptions as ReactBrowserOptions } from '@sentry/react';
import { getDefaultIntegrations as getReactDefaultIntegrations, init as initReactSDK } from '@sentry/react';
import { applyReleaseFromMetaTag } from './release';
import { applyTunnelRouteOption } from './tunnelRoute';

/**
Expand All @@ -15,6 +16,7 @@ export function init(options: ReactBrowserOptions): Client | undefined {
...options,
};

applyReleaseFromMetaTag(sentryOptions);
applyTunnelRouteOption(sentryOptions);
applySdkMetadata(sentryOptions, 'tanstackstart-react', ['tanstackstart-react', 'react']);

Expand Down
2 changes: 2 additions & 0 deletions packages/tanstackstart-react/src/common/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/** The server writes the build's release into this meta tag, so that no content-hashed client file holds it. */
export const RELEASE_META_TAG_NAME = 'sentry-release';
1 change: 1 addition & 0 deletions packages/tanstackstart-react/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export { init } from './sdk';
export { wrapFetchWithSentry } from './wrapFetchWithSentry';
export { wrapMiddlewaresWithSentry } from './middleware';
export { sentryGlobalRequestMiddleware, sentryGlobalFunctionMiddleware } from './globalMiddleware';
export { addReleaseMetaTag as _INTERNAL_addReleaseMetaTag } from './releaseMetaTag';
export {
createSentryTunnelRoute,
registerSentryServerTunnelRoute,
Expand Down
139 changes: 139 additions & 0 deletions packages/tanstackstart-react/src/server/releaseMetaTag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { RELEASE_META_TAG_NAME } from '../common/release';
import type { ServerEntry } from './wrapFetchWithSentry';

const HEAD_CLOSING_TAG = new TextEncoder().encode('</head>');

// Bytes before `</head>` stream through while we search, so this only bounds the search in pages without a
// `</head>`. Inline styles and scripts can make `<head>` large, so it leaves plenty of room for them.
const MAX_BYTES_BEFORE_HEAD_END = 1024 * 1024;

/**
* Writes the release at the end of the `<head>` of each page the server entry renders, where the client SDK reads it.
* The `sentryTanstackStart` Vite plugin wraps the server entry with this when it builds the app.
*
* @internal Only the code the Vite plugin generates calls this, so its parameters can change at any time.
*/
export function addReleaseMetaTag<T extends ServerEntry>(serverEntry: T, release: string): T {
if (typeof serverEntry?.fetch !== 'function') {
return serverEntry;
}

const metaTag = new TextEncoder().encode(
`<meta name="${RELEASE_META_TAG_NAME}" content="${escapeAttribute(release)}"/>`,
);

return {
...serverEntry,
async fetch(...args: Parameters<ServerEntry['fetch']>) {
return injectMetaTag(await serverEntry.fetch(...args), metaTag);
},
};
}

function injectMetaTag(response: Response, metaTag: Uint8Array): Response {
if (
!response.body ||
!response.headers.get('content-type')?.startsWith('text/html') ||
response.headers.has('content-encoding')
) {
return response;
}

let pending: Uint8Array | undefined = new Uint8Array(0);
let searchedBytes = 0;

// The tag goes last in `<head>`: React 18 hydrates `<head>` children in order, so a tag before the app's own
// elements would be claimed for the first of them and shift the rest.
const body = response.body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
if (!pending) {
controller.enqueue(chunk);
return;
}

const buffered = concat(pending, chunk);
const headEnd = indexOfHeadClosingTag(buffered);
if (headEnd !== -1) {
controller.enqueue(buffered.subarray(0, headEnd));
controller.enqueue(metaTag);
controller.enqueue(buffered.subarray(headEnd));
pending = undefined;
return;
}

searchedBytes += chunk.length;
if (searchedBytes > MAX_BYTES_BEFORE_HEAD_END) {
controller.enqueue(buffered);
pending = undefined;
return;
}

// Hold back the bytes that could start a `</head>` split across chunks.
const heldBack = partialHeadClosingTagLength(buffered);
if (heldBack < buffered.length) {
controller.enqueue(buffered.subarray(0, buffered.length - heldBack));
}
pending = buffered.slice(buffered.length - heldBack);
},
flush(controller) {
if (pending?.length) {
controller.enqueue(pending);
}
},
}),
);

const headers = new Headers(response.headers);
headers.delete('content-length');

return new Response(body, { status: response.status, statusText: response.statusText, headers });
}

// `</head>` is ASCII, and UTF-8 never encodes an ASCII character as part of a multi-byte sequence, so matching
// bytes finds it the same way as in the decoded document.
function indexOfHeadClosingTag(bytes: Uint8Array): number {
for (let start = 0; start + HEAD_CLOSING_TAG.length <= bytes.length; start++) {
if (matchesHeadClosingTag(bytes, start, HEAD_CLOSING_TAG.length)) {
return start;
}
}
return -1;
}

function partialHeadClosingTagLength(bytes: Uint8Array): number {
for (let length = Math.min(HEAD_CLOSING_TAG.length - 1, bytes.length); length > 0; length--) {
if (matchesHeadClosingTag(bytes, bytes.length - length, length)) {
return length;
}
}
return 0;
}

function matchesHeadClosingTag(bytes: Uint8Array, start: number, length: number): boolean {
for (let i = 0; i < length; i++) {
if (toLowerCase(bytes[start + i] as number) !== HEAD_CLOSING_TAG[i]) {
return false;
}
}
return true;
}

function toLowerCase(byte: number): number {
return byte >= 0x41 && byte <= 0x5a ? byte + 0x20 : byte;
}

function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
if (!a.length) {
return b;
}

const result = new Uint8Array(a.length + b.length);
result.set(a);
result.set(b, a.length);
return result;
}

function escapeAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
20 changes: 20 additions & 0 deletions packages/tanstackstart-react/src/vite/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { resolveReleaseName } from '@sentry/bundler-plugins/core';
import { stringifyForCodeInjection } from '@sentry/core';
import type { SentryTanstackStartOptions } from './sentryTanstackStart';

/**
* The release the SDK delivers at runtime instead of the bundler plugin injecting it into the startup chunks, whose
* content hashes would change with every release. Undefined when `release.inject` is `false` or there is no release.
*/
export function getRuntimeRelease(options: SentryTanstackStartOptions): string | undefined {
if (options.release?.inject === false) {
return undefined;
}

return resolveReleaseName(options.release?.name);
}

/** Sets the release where the server SDK reads it on `init`, the same way the bundler plugin does. */
export function getServerReleaseCode(release: string): string {
return `globalThis.SENTRY_RELEASE = { id: ${stringifyForCodeInjection(release)} };\n`;
}
16 changes: 12 additions & 4 deletions packages/tanstackstart-react/src/vite/sentryTanstackStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';
import type { Plugin } from 'vite';
import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware';
import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugin } from './nitroSourceMaps';
import { getRuntimeRelease } from './release';
import { makeRoutePatternPlugin } from './routePatterns';
import { makeServerInstrumentationPlugin } from './serverInstrumentation';
import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps';
Expand Down Expand Up @@ -92,30 +93,37 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P
);
}

const isDevelopment = process.env.NODE_ENV === 'development';
const release = isDevelopment ? undefined : getRuntimeRelease(options);

const tunnelBasePath = makeTunnelBasePathPlugin();
const plugins: Plugin[] = [
makeRoutePatternPlugin(),
tunnelBasePath.plugin,
makeServerEntryTunnelPlugin(tunnelRoute, tunnelBasePath.getBasePath),
makeServerEntryTunnelPlugin(tunnelRoute, tunnelBasePath.getBasePath, release),
];

if (tunnelRoute) {
plugins.push(makeTunnelRoutePlugin(tunnelRoute, options.debug));
}

// only add build-time plugins in production builds
if (process.env.NODE_ENV === 'development') {
if (isDevelopment) {
return plugins;
}

plugins.push(makeServerInstrumentationPlugin({ debug: options.debug }));
plugins.push(makeServerInstrumentationPlugin({ debug: options.debug, release }));

// Runs the orchestrion code transform over the server bundle so instrumented DB drivers get
// `diagnostics_channel` publishers injected. Production-only: it force-bundles the instrumented
// (CommonJS) deps via `ssr.noExternal`, which the `vite dev` SSR module runner can't evaluate.
plugins.push(sentryOrchestrionPlugin({ buildTimeInstrumentation: options.buildTimeInstrumentation }));

plugins.push(...makeAddSentryVitePlugin(options), makeComposeNitroServiceSourceMapsPlugin());
// The server entry hands the release to the SDK at runtime, so it changes no content hash of the startup chunks.
const bundlerPluginOptions = release
? { ...options, release: { ...options.release, name: release, inject: false } }
: options;
plugins.push(...makeAddSentryVitePlugin(bundlerPluginOptions), makeComposeNitroServiceSourceMapsPlugin());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Silent release default change

Medium Severity

The bundler plugin now always gets release.inject: false, so client chunks no longer carry the release. Only Sentry.init from @sentry/tanstackstart-react reads the new sentry-release meta tag. Apps that still call Sentry.init from @sentry/browser or @sentry/react silently drop the browser release, so events no longer match uploaded source maps. That is a silent default change without a changelog or migration note.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 7ee6e89. Configure here.


// middleware auto-instrumentation
if (options.autoInstrumentMiddleware !== false) {
Expand Down
11 changes: 10 additions & 1 deletion packages/tanstackstart-react/src/vite/serverInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import type { Plugin } from 'vite';
import { logDebug } from './nitroSourceMaps';
import { getServerReleaseCode } from './release';

const FILE_NAMES = ['instrument.server.ts', 'instrument.server.mts', 'instrument.server.js', 'instrument.server.mjs'];
const DIRECTORIES = ['', 'src'];

const NITRO_PLUGIN_ID = '#sentry/tanstackstart-server-instrumentation';
const NITRO_RELEASE_PLUGIN_ID = '#sentry/tanstackstart-release';

/** The parts of the Nitro instance that this plugin uses. */
type Nitro = {
Expand Down Expand Up @@ -37,7 +39,7 @@ export function findServerInstrumentationFile(root: string): string | undefined
* Bundles the server instrumentation file into the Nitro build and loads it from a Nitro plugin, which runs when the
* server starts. Nitro only imports the server entry in the first request, which is too late to trace that request.
*/
export function makeServerInstrumentationPlugin({ debug }: { debug?: boolean }): Plugin & {
export function makeServerInstrumentationPlugin({ debug, release }: { debug?: boolean; release?: string }): Plugin & {
nitro: { name: string; setup: (nitro: Nitro) => void };
} {
return {
Expand Down Expand Up @@ -73,6 +75,13 @@ export function makeServerInstrumentationPlugin({ debug }: { debug?: boolean }):
// Before the plugins of the app, so they run with an initialized SDK.
nitro.options.plugins.unshift(NITRO_PLUGIN_ID);

if (release) {
// A plugin of its own, as Nitro drops virtual modules that are only imported for their side effects. Nitro
// imports the plugins in order, so the release is set when the file initializes the SDK.
nitro.options.virtual[NITRO_RELEASE_PLUGIN_ID] = `${getServerReleaseCode(release)}export default () => {};\n`;
nitro.options.plugins.unshift(NITRO_RELEASE_PLUGIN_ID);
}

logDebug(
debug,
`Bundled \`${path.relative(nitro.options.rootDir, file)}\` into the Nitro server build. The SDK initializes itself when the server starts, no \`node --import\` needed.`,
Expand Down
Loading
Loading