Skip to content
Draft
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
24 changes: 22 additions & 2 deletions packages/browser/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ import type {
import type { BrowserClientReplayOptions } from '@sentry/core/browser';
import type { RouteProvider } from '@sentry/browser-utils';
import { setRouteProvider } from '@sentry/browser-utils';
import { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource, timestampInSeconds } from '@sentry/core';
import {
_INTERNAL_RELEASE_META_TAG_NAME,
addAutoIpAddressToSession,
applySdkMetadata,
Client,
getSDKSource,
timestampInSeconds,
} from '@sentry/core';
import { eventFromException, eventFromMessage } from './eventbuilder';
import { WINDOW } from './helpers';
import type { BrowserTransportOptions } from './transports/types';
Expand Down Expand Up @@ -250,10 +257,23 @@ export function applyDefaultOptions<T extends Partial<BrowserClientOptions>>(opt
release:
typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value
? __SENTRY_RELEASE__
: WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects
: (getReleaseFromMetaTag() ?? WINDOW.SENTRY_RELEASE?.id), // This supports the variable that sentry-webpack-plugin injects
sendClientReports: true,
// We default this to true, as it is the safer scenario
parentSpanIsAlwaysRootSpan: true,
...optionsArg,
};
}

/**
* Framework SDKs render the release into each page, so the content-hashed client chunks don't change on every
* release. The page comes from the server on every request, so it wins over `WINDOW.SENTRY_RELEASE`, which a cached
* chunk can set. It loses to `__SENTRY_RELEASE__`, which belongs to the one bundle that defined it, so a script
* embedded in another app's page keeps its own release.
*/
function getReleaseFromMetaTag(): string | undefined {
return (
WINDOW.document?.querySelector?.(`meta[name="${_INTERNAL_RELEASE_META_TAG_NAME}"]`)?.getAttribute('content') ||
undefined
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
);
}
59 changes: 59 additions & 0 deletions packages/browser/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,65 @@ describe('applyDefaultOptions', () => {
WINDOW.SENTRY_RELEASE = releaseBefore;
});

describe('`sentry-release` meta tag', () => {
afterEach(() => {
vi.unstubAllGlobals();
document.head.innerHTML = '';
});

function addReleaseMetaTag(content: string): void {
const meta = document.createElement('meta');
meta.name = 'sentry-release';
meta.content = content;
document.head.appendChild(meta);
}

it('picks up the release from the meta tag that framework SDKs render into the page', () => {
addReleaseMetaTag('page-release');

expect(applyDefaultOptions({}).release).toBe('page-release');
});

it('prefers the meta tag over WINDOW.SENTRY_RELEASE.id', () => {
const releaseBefore = WINDOW.SENTRY_RELEASE;
WINDOW.SENTRY_RELEASE = { id: 'chunk-release' };
addReleaseMetaTag('page-release');

expect(applyDefaultOptions({}).release).toBe('page-release');

WINDOW.SENTRY_RELEASE = releaseBefore;
});

it('lets a passed in release take precedence over the meta tag', () => {
addReleaseMetaTag('page-release');

expect(applyDefaultOptions({ release: '2.0.0' }).release).toBe('2.0.0');
});

it('lets a `__SENTRY_RELEASE__` define take precedence over the meta tag', () => {
vi.stubGlobal('__SENTRY_RELEASE__', 'bundle-release');
addReleaseMetaTag('page-release');

expect(applyDefaultOptions({}).release).toBe('bundle-release');
});

it('does not throw when `document` has no `querySelector`', () => {
vi.stubGlobal('document', {});

expect(() => applyDefaultOptions({})).not.toThrow();
});

it('ignores an empty meta tag', () => {
const releaseBefore = WINDOW.SENTRY_RELEASE;
WINDOW.SENTRY_RELEASE = { id: 'chunk-release' };
addReleaseMetaTag('');

expect(applyDefaultOptions({}).release).toBe('chunk-release');

WINDOW.SENTRY_RELEASE = releaseBefore;
});
});

it('passed in release takes precedence over WINDOW.SENTRY_RELEASE.id', () => {
const releaseBefore = WINDOW.SENTRY_RELEASE;

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export { parseSampleRate } from './utils/parseSampleRate';
export { applySdkMetadata, captureOptionsSetByUser as _INTERNAL_captureOptionsSetByUser } from './utils/sdkMetadata';
export { getTraceData } from './utils/traceData';
export { matchesTracePropagationTargets, shouldPropagateTraceForUrl } from './utils/tracePropagationTargets';
export { getTraceMetaTags } from './utils/meta';
export { getTraceMetaTags, RELEASE_META_TAG_NAME as _INTERNAL_RELEASE_META_TAG_NAME } from './utils/meta';
export { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME, _INTERNAL_RENDER_START_META_TAG_NAME } from './utils/cacheOrigin';
export { getTraceServerTimingHeader, isSharedCacheable } from './utils/serverTiming';
export { debounce } from './utils/debounce';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export { wrapMcpServerWithSentry } from './integrations/mcp-server';
export { isNodeEnv, loadModule } from './utils/node';
export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace';
export { vercelWaitUntil } from './utils/vercelWaitUntil';
export { getReleaseMetaTag as _INTERNAL_getReleaseMetaTag } from './utils/meta';
export {
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRenderStart,
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/utils/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,21 @@ export function getTraceMetaTags(traceData?: SerializedTraceData): string {
.join('')
);
}

/**
* The name of the meta tag that gives the release to the browser SDK. Framework SDKs write it into each page
* instead of injecting the release into the client chunks, where it would change their content hashes on every
* release.
*/
export const RELEASE_META_TAG_NAME = 'sentry-release';

/**
* Returns the meta tag that gives `release` to the browser SDK.
*/
export function getReleaseMetaTag(release: string): string {
return `<meta name="${RELEASE_META_TAG_NAME}" content="${escapeHtmlAttribute(release)}"/>`;
}

function escapeHtmlAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
12 changes: 11 additions & 1 deletion packages/core/test/lib/utils/meta.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getTraceMetaTags } from '../../../src/utils/meta';
import { getReleaseMetaTag, getTraceMetaTags } from '../../../src/utils/meta';
import * as TraceDataModule from '../../../src/utils/traceData';

describe('getTraceMetaTags', () => {
Expand Down Expand Up @@ -50,3 +50,13 @@ describe('getTraceMetaTags', () => {
expect(getTraceDataSpy).not.toHaveBeenCalled();
});
});

describe('getReleaseMetaTag', () => {
it('renders the release as a `sentry-release` meta tag', () => {
expect(getReleaseMetaTag('1.2.3')).toBe('<meta name="sentry-release" content="1.2.3"/>');
});

it('escapes the release so it cannot end the attribute or the tag', () => {
expect(getReleaseMetaTag('a"b<c>&d')).toBe('<meta name="sentry-release" content="a&quot;b&lt;c&gt;&amp;d"/>');
});
});
13 changes: 1 addition & 12 deletions 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, WINDOW } from '@sentry/browser';
import { init as browserInit } from '@sentry/browser';
import type { Client } from '@sentry/core';
import {
applySdkMetadata,
Expand All @@ -8,7 +8,6 @@ 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 @@ -42,16 +41,6 @@ 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;
}
}

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

const client = browserInit(options);
Expand Down
3 changes: 0 additions & 3 deletions packages/react-router/src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
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
8 changes: 2 additions & 6 deletions packages/react-router/src/server/clientRelease.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { consoleSandbox } from '@sentry/core';
import { RELEASE_META_TAG_NAME } from '../common/utils';
import { _INTERNAL_getReleaseMetaTag as getReleaseMetaTag } from '@sentry/core/server';
import { injectIntoHead } from './headTagInjector';

type HandleDocumentRequest = (...args: unknown[]) => unknown;
Expand Down Expand Up @@ -27,7 +27,7 @@ export function injectClientRelease(entry: ServerBuildEntry | undefined, release
return;
}

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

async function sentryHandleRequestWithRelease(this: unknown, ...args: unknown[]): Promise<unknown> {
const response = await (handleRequest as HandleDocumentRequest).apply(this, args);
Expand Down Expand Up @@ -56,7 +56,3 @@ function addTagToDocument(response: unknown, tag: string): unknown {
headers,
});
}

function escapeAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
15 changes: 0 additions & 15 deletions packages/solidstart/src/client/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import type { Client, Integration } from '@sentry/core';
import { applySdkMetadata } from '@sentry/core';
import type { BrowserOptions } from '@sentry/solid';
import { RELEASE_META_TAG_NAME } from '../common/release';
import { applyTunnelBasePath } from '../common/tunnel';
import {
browserTracingIntegration,
getDefaultIntegrations as getDefaultSolidIntegrations,
init as initSolidSDK,
WINDOW,
} from '@sentry/solid';

// Treeshakable guard to remove all code related to tracing
Expand All @@ -22,25 +20,12 @@ export function init(options: BrowserOptions): Client | undefined {
...options,
};

const releaseFromPage = opts.release === undefined ? getReleaseFromMetaTag() : undefined;
if (releaseFromPage) {
opts.release = releaseFromPage;
}

applyTunnelBasePath(opts);
applySdkMetadata(opts, 'solidstart', ['solidstart', 'solid']);

return initSolidSDK(opts);
}

/**
* The Sentry SolidStart build plugins add this tag to the page, instead of writing the release into the client
* chunks where it would change their content hashes on every release.
*/
function getReleaseFromMetaTag(): string | undefined {
return WINDOW.document?.querySelector<HTMLMetaElement>(`meta[name="${RELEASE_META_TAG_NAME}"]`)?.content || undefined;
}

function getDefaultIntegrations(options: BrowserOptions): Integration[] {
const integrations = getDefaultSolidIntegrations(options);

Expand Down
3 changes: 0 additions & 3 deletions packages/solidstart/src/common/release.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
/** Name of the `<meta>` tag through which the server hands the release to the browser SDK. */
export const RELEASE_META_TAG_NAME = 'sentry-release';

/** Set by the server bundle's banner on SolidStart 1, read by the Nitro plugin that adds the `<meta>` tag. */
export const RELEASE_GLOBAL = '__sentry_solidstart_release';
8 changes: 2 additions & 6 deletions packages/solidstart/src/nitro/releaseMetaTag.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RELEASE_META_TAG_NAME } from '../common/release';
import { _INTERNAL_getReleaseMetaTag as getReleaseMetaTag } from '@sentry/core/server';

const HEAD_OPENING_TAG = /<head(?:\s[^>]*)?>/i;

Expand Down Expand Up @@ -57,7 +57,7 @@ function injectIntoHtml(html: string, release: string): string | undefined {
}

const end = match.index + match[0].length;
return `${html.slice(0, end)}<meta name="${RELEASE_META_TAG_NAME}" content="${escapeAttribute(release)}">${html.slice(end)}`;
return `${html.slice(0, end)}${getReleaseMetaTag(release)}${html.slice(end)}`;
}

function injectIntoHtmlStream(body: ReadableStream<Uint8Array | string>, release: string): ReadableStream<Uint8Array> {
Expand Down Expand Up @@ -92,7 +92,3 @@ function injectIntoHtmlStream(body: ReadableStream<Uint8Array | string>, release
}),
);
}

function escapeAttribute(value: string): string {
return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
4 changes: 2 additions & 2 deletions packages/solidstart/test/nitro/releaseMetaTag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { describe, expect, it } from 'vitest';
import { addReleaseMetaTag } from '../../src/nitro/releaseMetaTag';

const META_TAG = '<meta name="sentry-release" content="1.0.0">';
const META_TAG = '<meta name="sentry-release" content="1.0.0"/>';

function streamOf(...chunks: string[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
Expand All @@ -25,7 +25,7 @@ describe('addReleaseMetaTag', () => {
const body = addReleaseMetaTag('<head></head>', '"><script>alert(1)</script>&', 'text/html');

expect(body).toBe(
'<head><meta name="sentry-release" content="&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;&amp;"></head>',
'<head><meta name="sentry-release" content="&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;&amp;"/></head>',
);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/solidstart/test/nitro/releaseMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('releaseMiddleware', () => {
);

await expect((response as Response).text()).resolves.toBe(
'<head><meta name="sentry-release" content="1.0.0"></head>',
'<head><meta name="sentry-release" content="1.0.0"/></head>',
);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/solidstart/test/nitro/releasePlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('releasePlugin', () => {

beforeResponse(event, response);

expect(response.body).toBe('<head><meta name="sentry-release" content="1.0.0"></head>');
expect(response.body).toBe('<head><meta name="sentry-release" content="1.0.0"/></head>');
expect(event.node.res.removeHeader).toHaveBeenCalledWith('content-length');
});

Expand Down
10 changes: 0 additions & 10 deletions packages/sveltekit/src/client/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { applySdkMetadata } from '@sentry/core';
import type { BrowserOptions } from '@sentry/svelte';
import { getDefaultIntegrations as getDefaultSvelteIntegrations, init as initSvelteSdk, WINDOW } from '@sentry/svelte';
import { applyTunnelBasePath } from '../common/tunnel';
import { RELEASE_META_TAG_NAME } from '../common/utils';
import { browserTracingIntegration as svelteKitBrowserTracingIntegration } from './browserTracingIntegration';

type WindowWithSentryFetchProxy = typeof WINDOW & {
Expand All @@ -24,11 +23,6 @@ export function init(options: BrowserOptions): Client | undefined {
...options,
};

const releaseFromPage = options.release === undefined ? getReleaseFromPage() : undefined;
if (releaseFromPage) {
opts.release = releaseFromPage;
}

applySdkMetadata(opts, 'sveltekit', ['sveltekit', 'svelte']);
applyTunnelBasePath(opts);

Expand All @@ -46,10 +40,6 @@ export function init(options: BrowserOptions): Client | undefined {
return client;
}

function getReleaseFromPage(): string | undefined {
return WINDOW.document?.querySelector<HTMLMetaElement>(`meta[name="${RELEASE_META_TAG_NAME}"]`)?.content || undefined;
}

function getDefaultIntegrations(options: BrowserOptions): Integration[] | undefined {
// This evaluates to true unless __SENTRY_TRACING__ is text-replaced with "false",
// in which case everything inside will get tree-shaken away
Expand Down
3 changes: 0 additions & 3 deletions packages/sveltekit/src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ import { isObjectLike } from '@sentry/core';

export const WRAPPED_MODULE_SUFFIX = '?sentry-auto-wrap';

/** `sentryHandle` puts the release into a `<meta>` tag with this name, where the client SDK reads it. */
export const RELEASE_META_TAG_NAME = 'sentry-release';

export type SentryWrappedFlag = {
/**
* If this flag is set, we know that the load event was already wrapped once
Expand Down
Loading
Loading