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
@@ -1 +1,4 @@
export const APP_NAME = 'react-router-7-framework-spa';

// Set in `vite.config.ts`.
export const RELEASE = 'react-router-7-framework-spa-e2e';
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from '@playwright/test';
import { RELEASE } from '../constants';

const CLIENT_BUILD = path.join(process.cwd(), 'build/client');

test.describe('release', () => {
test('is in the SPA fallback page that the build renders', () => {
const html = readFileSync(path.join(CLIENT_BUILD, 'index.html'), 'utf8');

expect(html).toContain(`<meta name="sentry-release" content="${RELEASE}"/>`);
});

test('is not in the content-hashed client assets', () => {
expect(filesContaining(path.join(CLIENT_BUILD, 'assets'), RELEASE)).toEqual([]);
});
});

function filesContaining(dir: string, text: string): string[] {
return readdirSync(dir, { recursive: true, withFileTypes: true })
.filter(entry => entry.isFile())
.map(entry => path.join(entry.parentPath, entry.name))
.filter(file => readFileSync(file, 'utf8').includes(text));
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { reactRouter } from '@react-router/dev/vite';
import { sentryReactRouter } from '@sentry/react-router/vite';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [reactRouter()],
export default defineConfig(config => {
return {
plugins: [
reactRouter(),
sentryReactRouter(
{ release: { name: 'react-router-7-framework-spa-e2e' }, sourcemaps: { disable: true } },
config,
),
],
};
});
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export const APP_NAME = 'react-router-7-framework';

// Set in `vite.config.ts`.
export const RELEASE = 'react-router-7-framework-e2e';
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from '@playwright/test';
import { RELEASE } from '../constants';

const CLIENT_BUILD = path.join(process.cwd(), 'build/client');

test.describe('release', () => {
test('is in the page that the build prerenders', () => {
const html = readFileSync(path.join(CLIENT_BUILD, 'performance/static/index.html'), 'utf8');

expect(html).toContain(`<meta name="sentry-release" content="${RELEASE}"/>`);
});

test('is not in the content-hashed client assets', () => {
expect(filesContaining(path.join(CLIENT_BUILD, 'assets'), RELEASE)).toEqual([]);
});
});

function filesContaining(dir: string, text: string): string[] {
return readdirSync(dir, { recursive: true, withFileTypes: true })
.filter(entry => entry.isFile())
.map(entry => path.join(entry.parentPath, entry.name))
.filter(file => readFileSync(file, 'utf8').includes(text));
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { reactRouter } from '@react-router/dev/vite';
import { sentryReactRouter } from '@sentry/react-router/vite';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [reactRouter()],
export default defineConfig(config => {
return {
plugins: [
reactRouter(),
sentryReactRouter(
{
release: { name: 'react-router-7-framework-e2e' },
sourcemaps: { disable: true },
// The app is instrumented at runtime by `instrument.mjs`, and only uses the plugin for the release.
buildTimeInstrumentation: false,
},
config,
),
],
};
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ import { getRuntime } from '@sentry-internal/test-utils';
export const RUNTIME = getRuntime();

export const APP_NAME = 'react-router-8-framework';

// Set in the Vite configs.
export const RELEASE = 'react-router-8-framework-e2e';
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/test-utils';
import { APP_NAME, RELEASE } from './constants';

test.describe('release', () => {
test('is not in the content-hashed client assets', () => {
const filesWithRelease = readdirSync(path.join(process.cwd(), 'build/client/assets'), {
recursive: true,
withFileTypes: true,
})
.filter(entry => entry.isFile())
.map(entry => path.join(entry.parentPath, entry.name))
.filter(file => readFileSync(file, 'utf8').includes(RELEASE));

expect(filesWithRelease).toEqual([]);
});

test('reaches browser events through the page', async ({ page }) => {
const errorPromise = waitForError(APP_NAME, errorEvent => {
return errorEvent?.exception?.values?.[0]?.value === '¡Madre mía!';
});

await page.goto('/errors/client');
await page.locator('#throw-on-click').click();

const error = await errorPromise;

expect(error.release).toBe(RELEASE);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig(async config => ({
reactRouter(),
sentryCloudflareVitePlugin(),
...((await sentryReactRouter(
{ sourcemaps: { disable: true } },
{ release: { name: 'react-router-8-framework-e2e' }, sourcemaps: { disable: true } },
config,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
)) as any[]),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { defineConfig } from 'vite';

export default defineConfig(config => {
return {
plugins: [reactRouter(), sentryReactRouter({ sourcemaps: { disable: true } }, config)],
plugins: [
reactRouter(),
sentryReactRouter({ release: { name: 'react-router-8-framework-e2e' }, sourcemaps: { disable: true } }, config),
],
};
});
13 changes: 12 additions & 1 deletion packages/react-router/src/client/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BrowserOptions } from '@sentry/browser';
import { init as browserInit } from '@sentry/browser';
import { init as browserInit, WINDOW } from '@sentry/browser';
import type { Client } from '@sentry/core';
import {
applySdkMetadata,
Expand All @@ -8,6 +8,7 @@ import {
GLOBAL_OBJ,
setTag,
} from '@sentry/core';
import { RELEASE_META_TAG_NAME } from '../common/utils';

const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';

Expand Down Expand Up @@ -41,6 +42,16 @@ export function init(options: BrowserOptions): Client | undefined {
basePath: GLOBAL_OBJ_WITH_ROUTER_CONTEXT.__reactRouterContext?.basename,
});

// The Vite plugin keeps the release out of the content-hashed client chunks and has the server put it in the page.
if (options.release === undefined) {
const release = WINDOW.document
?.querySelector<HTMLMetaElement>(`meta[name="${RELEASE_META_TAG_NAME}"]`)
?.getAttribute('content');
if (release) {
options.release = release;
}
}
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved

applySdkMetadata(options, 'react-router', ['react-router', 'browser']);

const client = browserInit(options);
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/src/cloudflare/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from '../client';

export { wrapSentryHandleRequest } from '../server/wrapSentryHandleRequest';
export { setTunnelBasePath as _INTERNAL_setTunnelBasePath } from '../server/tunnelRoute';
export { injectClientRelease as _INTERNAL_injectClientRelease } from '../server/clientRelease';
export {
createSentryServerInstrumentation,
type CreateSentryServerInstrumentationOptions,
Expand Down
3 changes: 3 additions & 0 deletions packages/react-router/src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { captureException, debug } from '@sentry/core';
import { DEBUG_BUILD } from './debug-build';

/** The `name` of the meta tag that carries the release from the server to the browser SDK. */
export const RELEASE_META_TAG_NAME = 'sentry-release';

/**
* Extracts pathname from request URL.
* Falls back to '<unknown>' with DEBUG warning if URL cannot be parsed.
Expand Down
62 changes: 62 additions & 0 deletions packages/react-router/src/server/clientRelease.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { consoleSandbox } from '@sentry/core';
import { RELEASE_META_TAG_NAME } from '../common/utils';
import { injectIntoHead } from './headTagInjector';

type HandleDocumentRequest = (...args: unknown[]) => unknown;

type ServerBuildEntry = { module: { default?: unknown } };

/**
* Wraps the server build's document request handler, so every HTML document it renders carries the release in a
* meta tag. The Vite plugin calls this from the server build, after it turned off the bundler plugin's release
* injection, so the release stays out of the content-hashed client chunks.
*
* Any `handleRequest` gets the tag, including the default one and one that does not use the SDK's helpers. SPA mode
* and prerendering render their HTML through the same handler at build time.
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
*/
export function injectClientRelease(entry: ServerBuildEntry | undefined, release: string): void {
const handleRequest = entry?.module?.default;
if (!entry || typeof handleRequest !== 'function') {
// The client build left the release out, so without the tag browser events have no release.
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[Sentry] Could not find the request handler in the React Router server build, so browser events will not have a release. Pass `release` to `Sentry.init` in `entry.client`.',
);
});
return;
}

const tag = `<meta name="${RELEASE_META_TAG_NAME}" content="${escapeAttribute(release)}"/>`;

async function sentryHandleRequestWithRelease(this: unknown, ...args: unknown[]): Promise<unknown> {
const response = await (handleRequest as HandleDocumentRequest).apply(this, args);
return addTagToDocument(response, tag);
}

entry.module = { ...entry.module, default: sentryHandleRequestWithRelease };
}

function addTagToDocument(response: unknown, tag: string): unknown {
if (!(response instanceof Response) || !response.body || response.headers.has('content-encoding')) {
return response;
}

const contentType = response.headers.get('content-type');
if (contentType && !contentType.includes('text/html')) {
return response;
}

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

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

function escapeAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
45 changes: 45 additions & 0 deletions packages/react-router/src/server/headTagInjector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,51 @@ export function createHeadTagInjector(getTags: () => string): { push(text: strin
};
}

/**
* Injects `tags` before the first `</head>` of an HTML `ReadableStream`.
*/
export function injectIntoHead(body: ReadableStream, tags: string): ReadableStream {
const injector = createHeadTagInjector(() => tags);

const reader = body.getReader();
const encoder = new TextEncoder();
// A single streaming decoder carries incomplete multi-byte sequences across chunk
// boundaries. A fresh, non-streaming decoder per chunk would flush a split character
// as U+FFFD, corrupting the response (see https://github.com/whatwg/encoding/issues/184).
const decoder = new TextDecoder();

// Not a TransformStream: workerd only supports a custom transformer from compatibility date
// 2024-11-11, and Hydrogen's MiniOxygen runs with an older one.
return new ReadableStream({
async pull(controller) {
// `pull` is not called again until a chunk is enqueued, so keep reading while text is held back.
for (;;) {
const { done, value } = await reader.read();

if (done) {
const rest = injector.push(decoder.decode()) + injector.flush();
if (rest) {
controller.enqueue(encoder.encode(rest));
}
controller.close();
return;
}

const html = value instanceof Uint8Array ? decoder.decode(value, { stream: true }) : String(value);
const out = injector.push(html);

if (out) {
controller.enqueue(encoder.encode(out));
return;
}
}
},
cancel(reason) {
return reader.cancel(reason);
},
});
}

function longestPartialTagSuffix(text: string): number {
for (let length = Math.min(HEAD_CLOSING_TAG.length - 1, text.length); length > 0; length--) {
if (text.endsWith(HEAD_CLOSING_TAG.slice(0, length))) {
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type { SentryWebStreamHandleRequestOptions } from './handleRequestTypes';
export { createSentryHandleError, type SentryHandleErrorOptions } from './createSentryHandleError';
export { getMetaTagTransformer } from './getMetaTagTransformer';
export { setTunnelBasePath as _INTERNAL_setTunnelBasePath } from './tunnelRoute';
export { injectClientRelease as _INTERNAL_injectClientRelease } from './clientRelease';

// React Router instrumentation API support
export {
Expand Down
42 changes: 2 additions & 40 deletions packages/react-router/src/server/injectTraceMetaTags.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getTraceMetaTags } from '@sentry/core';
import { createHeadTagInjector } from './headTagInjector';
import { injectIntoHead } from './headTagInjector';
import { isPrerenderRequest } from './serverBuild';

/**
Expand All @@ -16,43 +16,5 @@ export function injectTraceMetaTags(body: ReadableStream): ReadableStream {
// Resolved now, while the request's async context is still active. Runtimes like workerd run
// stream callbacks outside of it, where there is no client and no trace data.
const traceMetaTags = getTraceMetaTags();
const injector = createHeadTagInjector(() => traceMetaTags);

const reader = body.getReader();
const encoder = new TextEncoder();
// A single streaming decoder carries incomplete multi-byte sequences across chunk
// boundaries. A fresh, non-streaming decoder per chunk would flush a split character
// as U+FFFD, corrupting the response (see https://github.com/whatwg/encoding/issues/184).
const decoder = new TextDecoder();

// Not a TransformStream: workerd only supports a custom transformer from compatibility date
// 2024-11-11, and Hydrogen's MiniOxygen runs with an older one.
return new ReadableStream({
async pull(controller) {
// `pull` is not called again until a chunk is enqueued, so keep reading while text is held back.
for (;;) {
const { done, value } = await reader.read();

if (done) {
const rest = injector.push(decoder.decode()) + injector.flush();
if (rest) {
controller.enqueue(encoder.encode(rest));
}
controller.close();
return;
}

const html = value instanceof Uint8Array ? decoder.decode(value, { stream: true }) : String(value);
const out = injector.push(html);

if (out) {
controller.enqueue(encoder.encode(out));
return;
}
}
},
cancel(reason) {
return reader.cancel(reason);
},
});
return injectIntoHead(body, traceMetaTags);
}
Loading
Loading