From cbfc0b0f36772012cdc4e2b9bcd764b575d688de Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Wed, 11 Jun 2025 19:32:46 +0300 Subject: [PATCH 1/4] Automatically detect Release name and version for Expo Web --- packages/core/src/js/integrations/release.ts | 69 +++++++++++++++++++- packages/core/src/js/tools/metroconfig.ts | 40 ++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) diff --git a/packages/core/src/js/integrations/release.ts b/packages/core/src/js/integrations/release.ts index f414f8a9ac..435add377e 100644 --- a/packages/core/src/js/integrations/release.ts +++ b/packages/core/src/js/integrations/release.ts @@ -1,9 +1,15 @@ import type { BaseTransportOptions, Client, ClientOptions, Event, EventHint, Integration } from '@sentry/core'; +import { isExpo, isWeb } from '../utils/environment'; import { NATIVE } from '../wrapper'; const INTEGRATION_NAME = 'Release'; +interface ExpoConfig { + name?: string; + version?: string; +} + /** Release integration responsible to load release from file. */ export const nativeReleaseIntegration = (): Integration => { return { @@ -15,6 +21,48 @@ export const nativeReleaseIntegration = (): Integration => { }; }; +/** + * Get Expo Web configuration name and version from environment variables + */ +function getExpoWebConfig(): ExpoConfig | null { + if (!isWeb() || !isExpo()) { + return null; + } + + try { + const processEnv = (globalThis as { process?: { env?: Record } }).process?.env; + + if (processEnv) { + const envConfig = { + name: processEnv.EXPO_PUBLIC_APP_NAME, + version: processEnv.EXPO_PUBLIC_APP_VERSION, + }; + + if (envConfig.name && envConfig.version) { + return envConfig; + } + } + } catch { + // Config detection failed, do nothing + } + + return null; +} + +/** + * Generates release string from Expo Web config + */ +function generateExpoWebRelease(config: ExpoConfig): string | null { + const name = config.name; + const version = config.version; + + if (!name || !version) { + return null; + } + + return `${name}@${version}`; +} + async function processEvent( event: Event, _: EventHint, @@ -23,8 +71,11 @@ async function processEvent( const options = client.getOptions(); /* - __sentry_release and __sentry_dist is set by the user with setRelease and setDist. If this is used then this is the strongest. - Otherwise we check for the release and dist in the options passed on init, as this is stronger than the release/dist from the native build. + Priority order: + 1. __sentry_release and __sentry_dist set by user with setRelease and setDist (strongest) + 2. release and dist in options passed on init + 3. Native release (mobile) + 4. Expo Web auto-detection (web only, no additional dependencies) */ if (typeof event.extra?.__sentry_release === 'string') { event.release = `${event.extra.__sentry_release}`; @@ -56,5 +107,19 @@ async function processEvent( // Something went wrong, we just continue } + if (!event.release && isExpo() && isWeb()) { + try { + const expoConfig = getExpoWebConfig(); + if (expoConfig) { + const autoRelease = generateExpoWebRelease(expoConfig); + if (autoRelease) { + event.release = autoRelease; + } + } + } catch { + // Something went wrong, we just continue + } + } + return event; } diff --git a/packages/core/src/js/tools/metroconfig.ts b/packages/core/src/js/tools/metroconfig.ts index 79c9fd43b0..1da2c1a1cd 100644 --- a/packages/core/src/js/tools/metroconfig.ts +++ b/packages/core/src/js/tools/metroconfig.ts @@ -16,6 +16,44 @@ import { withSentryMiddleware } from './metroMiddleware'; enableLogger(); +interface ExpoConfig { + name?: string; + version?: string; +} + +interface ExpoConfigResult { + exp: ExpoConfig; +} + +/** + * Try to inject Expo config name and version as environment variables. + * @param projectRoot The root directory of the Expo project. + */ +function injectExpoConfigAsEnvVars(projectRoot: string): void { + try { + let getConfigFunction: ((projectRoot: string) => ExpoConfigResult) | null = null; + + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-extraneous-dependencies + const expoConfig = require('@expo/config') as { getConfig: (projectRoot: string) => ExpoConfigResult }; + getConfigFunction = expoConfig.getConfig; + } catch { + // @expo/config not available, do nothing + } + + if (getConfigFunction) { + const { exp } = getConfigFunction(projectRoot); + + if (exp && typeof exp.name === 'string' && typeof exp.version === 'string') { + process.env.EXPO_PUBLIC_APP_NAME = exp.name; + process.env.EXPO_PUBLIC_APP_VERSION = exp.version; + } + } + } catch (error) { + logger.warn('Failed to inject Expo config as environment variables:', error); + } +} + export interface SentryMetroConfigOptions { /** * Annotates React components with Sentry data. @@ -88,6 +126,8 @@ export function getSentryExpoConfig( ): MetroConfig { setSentryMetroDevServerEnvFlag(); + injectExpoConfigAsEnvVars(projectRoot); + const getDefaultConfig = options.getDefaultConfig || loadExpoMetroConfigModule().getDefaultConfig; const config = getDefaultConfig(projectRoot, { ...options, From 51042993333a816af2ddc7d4fc7faae53a296c45 Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Wed, 11 Jun 2025 19:37:35 +0300 Subject: [PATCH 2/4] Add changelog entry --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7887a382c..807bb343cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ > make sure you follow our [migration guide](https://docs.sentry.io/platforms/react-native/migration/) first. +## Unreleased + +### Features + +- Automatically detect Release name and version for Expo Web ([#4910](https://github.com/getsentry/sentry-react-native/pull/4910)) + ## 6.15.1 ### Dependencies From f891890f353f972a192dffb36e286ac3dcd16972 Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Wed, 11 Jun 2025 20:20:49 +0300 Subject: [PATCH 3/4] Adds tests --- .../core/test/integrations/release.test.ts | 181 +++++++++++++++++- packages/core/test/tools/metroconfig.test.ts | 78 ++++++++ 2 files changed, 254 insertions(+), 5 deletions(-) diff --git a/packages/core/test/integrations/release.test.ts b/packages/core/test/integrations/release.test.ts index be3a4f1b10..98436714db 100644 --- a/packages/core/test/integrations/release.test.ts +++ b/packages/core/test/integrations/release.test.ts @@ -4,15 +4,40 @@ import { nativeReleaseIntegration } from '../../src/js/integrations/release'; jest.mock('../../src/js/wrapper', () => ({ NATIVE: { - fetchNativeRelease: async () => ({ - build: 'native_build', - id: 'native_id', - version: 'native_version', - }), + fetchNativeRelease: jest.fn(), }, })); +jest.mock('../../src/js/utils/environment', () => ({ + isExpo: jest.fn(), + isWeb: jest.fn(), +})); + +import { isExpo, isWeb } from '../../src/js/utils/environment'; +import { NATIVE } from '../../src/js/wrapper'; + +const mockIsExpo = isExpo as jest.MockedFunction; +const mockIsWeb = isWeb as jest.MockedFunction; +const mockFetchNativeRelease = NATIVE.fetchNativeRelease as jest.MockedFunction; + describe('Tests the Release integration', () => { + beforeEach(() => { + mockIsExpo.mockReturnValue(false); + mockIsWeb.mockReturnValue(false); + + mockFetchNativeRelease.mockResolvedValue({ + build: 'native_build', + id: 'native_id', + version: 'native_version', + }); + + delete (globalThis as any).process; + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + test('Uses release from native SDK if release/dist are not present in options.', async () => { const releaseIntegration = nativeReleaseIntegration(); @@ -77,4 +102,150 @@ describe('Tests the Release integration', () => { expect(event?.release).toBe('sentry_release'); expect(event?.dist).toBe('sentry_dist'); }); + + describe('Expo Web Config Tests', () => { + beforeEach(() => { + // Mock native release to throw error so it falls back to Expo Web + mockFetchNativeRelease.mockRejectedValue(new Error('Native release failed')); + }); + + test('Uses Expo Web config when isExpo and isWeb are true and environment variables are set', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBe('MyExpoApp@1.2.3'); + }); + + test('Does not use Expo Web config when not in Expo environment', async () => { + mockIsExpo.mockReturnValue(false); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBeUndefined(); + }); + + test('Does not use Expo Web config when not in web environment', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(false); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBeUndefined(); + }); + + test('Does not use Expo Web config when app name is missing', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBeUndefined(); + }); + + test('Does not use Expo Web config when app version is missing', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBeUndefined(); + }); + + test('Does not use Expo Web config when process.env is not available', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + delete (globalThis as any).process; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { getOptions: () => ({}) } as Client); + + expect(event?.release).toBeUndefined(); + }); + + test('Prefers options release over Expo Web config', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!({}, {}, { + getOptions: () => ({ release: 'options_release' }), + } as Client); + + expect(event?.release).toBe('options_release'); + }); + + test('Prefers __sentry_release over Expo Web config', async () => { + mockIsExpo.mockReturnValue(true); + mockIsWeb.mockReturnValue(true); + + (globalThis as any).process = { + env: { + EXPO_PUBLIC_APP_NAME: 'MyExpoApp', + EXPO_PUBLIC_APP_VERSION: '1.2.3', + }, + }; + + const releaseIntegration = nativeReleaseIntegration(); + const event = await releaseIntegration.processEvent!( + { + extra: { + __sentry_release: 'sentry_release', + }, + }, + {}, + { getOptions: () => ({}) } as Client, + ); + + expect(event?.release).toBe('sentry_release'); + }); + }); }); diff --git a/packages/core/test/tools/metroconfig.test.ts b/packages/core/test/tools/metroconfig.test.ts index 2329509754..56dcfc359f 100644 --- a/packages/core/test/tools/metroconfig.test.ts +++ b/packages/core/test/tools/metroconfig.test.ts @@ -15,6 +15,16 @@ import { type MetroFrame = Parameters['symbolicator']>['customizeFrame']>[0]; +const mockGetConfig = jest.fn(); +jest.mock('@expo/config', () => ({ + getConfig: mockGetConfig, +})); + +const mockExpoGetDefaultConfig = jest.fn(); +jest.mock('expo/metro-config', () => ({ + getDefaultConfig: mockExpoGetDefaultConfig, +})); + describe('metroconfig', () => { beforeEach(() => { jest.clearAllMocks(); @@ -23,6 +33,16 @@ describe('metroconfig', () => { delete process.env[SENTRY_BABEL_TRANSFORMER_OPTIONS]; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete process.env[SENTRY_DEFAULT_BABEL_TRANSFORMER_PATH]; + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete process.env.EXPO_PUBLIC_APP_NAME; + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete process.env.EXPO_PUBLIC_APP_VERSION; + + // Reset mocks to default behavior + mockExpoGetDefaultConfig.mockReturnValue({ + transformer: { babelTransformerPath: 'default/babel/transformer' }, + }); + mockGetConfig.mockReset(); }); test('getSentryExpoConfig keeps compatible interface with Expos getDefaultConfig', () => { @@ -323,6 +343,64 @@ describe('metroconfig', () => { } }); }); + + describe('injectExpoConfigAsEnvVars', () => { + test('injects Expo config name and version as environment variables when config is available', () => { + mockGetConfig.mockReturnValue({ + exp: { + name: 'MyExpoApp', + version: '1.2.3', + }, + }); + + getSentryExpoConfig('/test/project/root'); + + expect(mockGetConfig).toHaveBeenCalledWith('/test/project/root'); + expect(process.env.EXPO_PUBLIC_APP_NAME).toBe('MyExpoApp'); + expect(process.env.EXPO_PUBLIC_APP_VERSION).toBe('1.2.3'); + }); + + test('does not inject environment variables when exp config is missing', () => { + mockGetConfig.mockReturnValue({}); + + getSentryExpoConfig('/test/project/root'); + + expect(process.env.EXPO_PUBLIC_APP_NAME).toBeUndefined(); + expect(process.env.EXPO_PUBLIC_APP_VERSION).toBeUndefined(); + }); + + test('handles @expo/config not being available gracefully', () => { + const originalModule = require('@expo/config'); + jest.doMock('@expo/config', () => { + throw new Error('Module not found'); + }); + + jest.resetModules(); + const { getSentryExpoConfig: freshGetSentryExpoConfig } = require('../../src/js/tools/metroconfig'); + + expect(() => { + freshGetSentryExpoConfig('/test/project/root'); + }).not.toThrow(); + + expect(process.env.EXPO_PUBLIC_APP_NAME).toBeUndefined(); + expect(process.env.EXPO_PUBLIC_APP_VERSION).toBeUndefined(); + + jest.doMock('@expo/config', () => originalModule); + }); + + test('handles getConfig throwing an error gracefully', () => { + mockGetConfig.mockImplementation(() => { + throw new Error('Config loading failed'); + }); + + expect(() => { + getSentryExpoConfig('/test/project/root'); + }).not.toThrow(); + + expect(process.env.EXPO_PUBLIC_APP_NAME).toBeUndefined(); + expect(process.env.EXPO_PUBLIC_APP_VERSION).toBeUndefined(); + }); + }); }); // function create mock metro frame From f2648bae3dfa6bb866b0785ac01dd2b78a77fcea Mon Sep 17 00:00:00 2001 From: Antonis Lilis Date: Fri, 27 Jun 2025 10:08:05 +0300 Subject: [PATCH 4/4] Use expo constants for production --- packages/core/src/js/integrations/release.ts | 50 +++++++++++++++++--- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/packages/core/src/js/integrations/release.ts b/packages/core/src/js/integrations/release.ts index 435add377e..29a4fd092b 100644 --- a/packages/core/src/js/integrations/release.ts +++ b/packages/core/src/js/integrations/release.ts @@ -10,6 +10,14 @@ interface ExpoConfig { version?: string; } +let Constants: { default?: { manifest?: unknown }; manifest?: unknown } | null = null; +try { + // eslint-disable-next-line import/no-extraneous-dependencies + Constants = require('expo-constants'); +} catch { + // expo-constants not available, do nothing +} + /** Release integration responsible to load release from file. */ export const nativeReleaseIntegration = (): Integration => { return { @@ -22,7 +30,7 @@ export const nativeReleaseIntegration = (): Integration => { }; /** - * Get Expo Web configuration name and version from environment variables + * Get Expo Web configuration name and version from environment variables or Constants */ function getExpoWebConfig(): ExpoConfig | null { if (!isWeb() || !isExpo()) { @@ -30,16 +38,44 @@ function getExpoWebConfig(): ExpoConfig | null { } try { + // Environment variables (development) const processEnv = (globalThis as { process?: { env?: Record } }).process?.env; - - if (processEnv) { - const envConfig = { + if (processEnv && processEnv?.EXPO_PUBLIC_APP_NAME && processEnv?.EXPO_PUBLIC_APP_VERSION) { + return { name: processEnv.EXPO_PUBLIC_APP_NAME, version: processEnv.EXPO_PUBLIC_APP_VERSION, }; + } + + // Expo-constants (production) + if (Constants) { + const constantsObj = Constants.default || Constants; - if (envConfig.name && envConfig.version) { - return envConfig; + if (constantsObj && typeof constantsObj === 'object' && 'manifest' in constantsObj) { + let manifest = constantsObj.manifest; + + if (typeof manifest === 'string') { + try { + manifest = JSON.parse(manifest) as unknown; + } catch { + return null; + } + } + + if ( + manifest && + typeof manifest === 'object' && + 'name' in manifest && + 'version' in manifest && + typeof (manifest as { name: unknown }).name === 'string' && + typeof (manifest as { version: unknown }).version === 'string' + ) { + const typedManifest = manifest as { name: string; version: string }; + return { + name: typedManifest.name, + version: typedManifest.version, + }; + } } } } catch { @@ -75,7 +111,7 @@ async function processEvent( 1. __sentry_release and __sentry_dist set by user with setRelease and setDist (strongest) 2. release and dist in options passed on init 3. Native release (mobile) - 4. Expo Web auto-detection (web only, no additional dependencies) + 4. Expo Web auto-detection */ if (typeof event.extra?.__sentry_release === 'string') { event.release = `${event.extra.__sentry_release}`;