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
14 changes: 13 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,19 @@
```json
["@sentry/react-native/expo", {
"useNativeInit": true,
"environment": "staging"
"options": {
"environment": "staging"
}
}]
```
- Generate `sentry.options.json` from the Expo config plugin `options` property ([#5804](https://github.com/getsentry/sentry-react-native/pull/5804/))
```json
["@sentry/react-native/expo", {
"useNativeInit": true,
"options": {
"dsn": "https://key@sentry.io/123",
"tracesSampleRate": 1.0
}
}]
```

Expand Down
12 changes: 6 additions & 6 deletions packages/core/plugin/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ export function writeSentryPropertiesTo(filepath: string, sentryProperties: stri

const SENTRY_OPTIONS_FILE_NAME = 'sentry.options.json';

export function writeSentryOptionsEnvironment(projectRoot: string, environment: string): void {
export function writeSentryOptions(projectRoot: string, pluginOptions: Record<string, unknown>): void {
const optionsFilePath = path.resolve(projectRoot, SENTRY_OPTIONS_FILE_NAME);

let options: Record<string, unknown> = {};
let existingOptions: Record<string, unknown> = {};
if (fs.existsSync(optionsFilePath)) {
try {
options = JSON.parse(fs.readFileSync(optionsFilePath, 'utf8'));
existingOptions = JSON.parse(fs.readFileSync(optionsFilePath, 'utf8'));
} catch (e) {
warnOnce(`Failed to parse ${SENTRY_OPTIONS_FILE_NAME}: ${e}. The environment will not be set.`);
warnOnce(`Failed to parse ${SENTRY_OPTIONS_FILE_NAME}: ${e}. These options will not be set.`);
return;
}
}

options.environment = environment;
fs.writeFileSync(optionsFilePath, `${JSON.stringify(options, null, 2)}\n`);
const mergedOptions = { ...existingOptions, ...pluginOptions };
fs.writeFileSync(optionsFilePath, `${JSON.stringify(mergedOptions, null, 2)}\n`);
}
18 changes: 11 additions & 7 deletions packages/core/plugin/src/withSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ExpoConfig } from '@expo/config-types';
import type { ConfigPlugin } from 'expo/config-plugins';
import { createRunOncePlugin, withDangerousMod } from 'expo/config-plugins';
import { bold, warnOnce } from './logger';
import { writeSentryOptionsEnvironment } from './utils';
import { writeSentryOptions } from './utils';
import { PLUGIN_NAME, PLUGIN_VERSION } from './version';
import { withSentryAndroid } from './withSentryAndroid';
import type { SentryAndroidGradlePluginOptions } from './withSentryAndroidGradlePlugin';
Expand All @@ -15,7 +15,7 @@ interface PluginProps {
authToken?: string;
url?: string;
useNativeInit?: boolean;
environment?: string;
options?: Record<string, unknown>;
experimental_android?: SentryAndroidGradlePluginOptions;
}

Expand All @@ -28,9 +28,13 @@ const withSentryPlugin: ConfigPlugin<PluginProps | void> = (config, props) => {
}

let cfg = config;
const environment = props?.environment ?? process.env.SENTRY_ENVIRONMENT;
const pluginOptions = props?.options ? { ...props.options } : {};
const environment = process.env.SENTRY_ENVIRONMENT;
if (environment) {
cfg = withSentryOptionsEnvironment(cfg, environment);
pluginOptions.environment = environment;
}
if (Object.keys(pluginOptions).length > 0) {
cfg = withSentryOptionsFile(cfg, pluginOptions);
}
if (sentryProperties !== null) {
try {
Expand Down Expand Up @@ -87,20 +91,20 @@ ${project ? `defaults.project=${project}` : missingProjectMessage}
${authToken ? `${existingAuthTokenMessage}\nauth.token=${authToken}` : missingAuthTokenMessage}`;
}

function withSentryOptionsEnvironment(config: ExpoConfig, environment: string): ExpoConfig {
function withSentryOptionsFile(config: ExpoConfig, pluginOptions: Record<string, unknown>): ExpoConfig {
// withDangerousMod requires a platform key, but sentry.options.json is at the project root.
// We apply to both platforms so it works with `expo prebuild --platform ios` or `--platform android`.
let cfg = withDangerousMod(config, [
'android',
mod => {
writeSentryOptionsEnvironment(mod.modRequest.projectRoot, environment);
writeSentryOptions(mod.modRequest.projectRoot, pluginOptions);
return mod;
},
]);
cfg = withDangerousMod(cfg, [
'ios',
mod => {
writeSentryOptionsEnvironment(mod.modRequest.projectRoot, environment);
writeSentryOptions(mod.modRequest.projectRoot, pluginOptions);
return mod;
},
]);
Expand Down
77 changes: 77 additions & 0 deletions packages/core/test/expo-plugin/writeSentryOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { writeSentryOptions } from '../../plugin/src/utils';

jest.mock('../../plugin/src/logger');

describe('writeSentryOptions', () => {
let tempDir: string;

beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentry-options-test-'));
});

afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});

test('creates sentry.options.json when file does not exist', () => {
writeSentryOptions(tempDir, { dsn: 'https://key@sentry.io/123', environment: 'staging' });

const filePath = path.join(tempDir, 'sentry.options.json');
const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content).toEqual({ dsn: 'https://key@sentry.io/123', environment: 'staging' });
});

test('merges options into existing sentry.options.json', () => {
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, JSON.stringify({ dsn: 'https://key@sentry.io/123', environment: 'production' }));

writeSentryOptions(tempDir, { environment: 'staging', debug: true });

const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content).toEqual({ dsn: 'https://key@sentry.io/123', environment: 'staging', debug: true });
});

test('plugin options take precedence over existing file values', () => {
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, JSON.stringify({ dsn: 'https://old@sentry.io/1', debug: false }));

writeSentryOptions(tempDir, { dsn: 'https://new@sentry.io/2' });

const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content.dsn).toBe('https://new@sentry.io/2');
expect(content.debug).toBe(false); // preserved from existing file
});

test('does not crash and warns when sentry.options.json contains invalid JSON', () => {
const { warnOnce } = require('../../plugin/src/logger');
const filePath = path.join(tempDir, 'sentry.options.json');
fs.writeFileSync(filePath, 'invalid json{{{');

writeSentryOptions(tempDir, { environment: 'staging' });

expect(warnOnce).toHaveBeenCalledWith(expect.stringContaining('Failed to parse'));
// File should remain unchanged
expect(fs.readFileSync(filePath, 'utf8')).toBe('invalid json{{{');
});

test('writes multiple options at once', () => {
writeSentryOptions(tempDir, {
dsn: 'https://key@sentry.io/123',
debug: true,
tracesSampleRate: 0.5,
environment: 'production',
});

const filePath = path.join(tempDir, 'sentry.options.json');
const content = JSON.parse(fs.readFileSync(filePath, 'utf8'));
expect(content).toEqual({
dsn: 'https://key@sentry.io/123',
debug: true,
tracesSampleRate: 0.5,
environment: 'production',
});
});
});

This file was deleted.

3 changes: 3 additions & 0 deletions samples/expo/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ yarn-error.*
/android
/ios

# Generated by @sentry/react-native expo plugin
sentry.options.json

# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli

Expand Down
24 changes: 20 additions & 4 deletions samples/expo/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": [
"**/*"
],
"assetBundlePatterns": ["**/*"],
Copy link
Collaborator

Choose a reason for hiding this comment

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

I wonder why each CI decides to change this format every run

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is an irrelevant formatting thing after running yarn fix locally. I can probably revert it but I guess it will come back

Copy link
Collaborator

Choose a reason for hiding this comment

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

No worries about that, maybe we can set some flag so yarn fix knows how to format these files.
But super low priority for doing that

"ios": {
"supportsTablet": true,
"bundleIdentifier": "io.sentry.expo.sample",
Expand Down Expand Up @@ -46,6 +44,24 @@
"project": "sentry-react-native",
"organization": "sentry-sdks",
"useNativeInit": true,
"options": {
"dsn": "https://1df17bd4e543fdb31351dee1768bb679@o447951.ingest.sentry.io/5428561",
"debug": true,
Copy link
Collaborator

Choose a reason for hiding this comment

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

q: What if the user sets enableNative: false here?

Copy link
Collaborator

Choose a reason for hiding this comment

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

What do you think of removing useNativeInit on v9 and move it inside options?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

q: What if the user sets enableNative: false here?

I think the native SDK would still be running (initialized by the native entry point), but JS wouldn't talk to it. That's the same outcome you'd get by manually putting enableNative: false in sentry.options.json today.

What do you think of removing useNativeInit on v9 and move it inside options?

Good idea 👍

"environment": "dev",
"enableUserInteractionTracing": true,
"enableAutoSessionTracking": true,
"sessionTrackingIntervalMillis": 30000,
"enableTracing": true,
"tracesSampleRate": 1.0,
"attachStacktrace": true,
"attachScreenshot": true,
"attachViewHierarchy": true,
"enableCaptureFailedRequests": true,
"profilesSampleRate": 1.0,
"replaysSessionSampleRate": 1.0,
"replaysOnErrorSampleRate": 1.0,
"spotlight": true
},
"experimental_android": {
"enableAndroidGradlePlugin": true,
"autoUploadProguardMapping": true,
Expand Down Expand Up @@ -90,4 +106,4 @@
"url": "https://u.expo.dev/00000000-0000-0000-0000-000000000000"
}
}
}
}
18 changes: 0 additions & 18 deletions samples/expo/sentry.options.json

This file was deleted.

Loading