Skip to content

ref: Replace global __DEBUG_BUILD__ type with DEBUG_BUILD const in individual packages #9657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 27, 2023
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
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Pro tip: If any of your breakpoints are in code run by multiple tests, and you r

## Debug Build Flags

Throughout the codebase, you will find the `__DEBUG_BUILD__` flag guarding various code sections. This flag serves two purposes:
Throughout the codebase, you will find a `__DEBUG_BUILD__` constant. This flag serves two purposes:

1. It enables us to remove debug code from our minified CDN bundles during build, by replacing the flag with `false` before tree-shaking occurs.
2. It enables users to remove Sentry debug code from their production bundles during their own build. When we build our npm packages, we replace the flag with `(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)`. If the user does nothing, this evaluates to `true` and logging is included. But if the user runs their own replacement during build (again replacing the flag with `false`), the build will tree-shake the logging away, just as our bundle builds do.
Expand Down
9 changes: 5 additions & 4 deletions packages/browser/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
} from '@sentry/types';
import { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';

import { DEBUG_BUILD } from './debug-build';
import { eventFromException, eventFromMessage } from './eventbuilder';
import { WINDOW } from './helpers';
import type { BrowserTransportOptions } from './transports/types';
Expand Down Expand Up @@ -96,7 +97,7 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {
*/
public captureUserFeedback(feedback: UserFeedback): void {
if (!this._isEnabled()) {
__DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');
DEBUG_BUILD && logger.warn('SDK not enabled, will not capture user feedback.');
return;
}

Expand All @@ -123,17 +124,17 @@ export class BrowserClient extends BaseClient<BrowserClientOptions> {
const outcomes = this._clearOutcomes();

if (outcomes.length === 0) {
__DEBUG_BUILD__ && logger.log('No outcomes to send');
DEBUG_BUILD && logger.log('No outcomes to send');
return;
}

// This is really the only place where we want to check for a DSN and only send outcomes then
if (!this._dsn) {
__DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');
DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');
return;
}

__DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);
DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);

const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));
void this._sendEnvelope(envelope);
Expand Down
8 changes: 8 additions & 0 deletions packages/browser/src/debug-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare const __DEBUG_BUILD__: boolean;

/**
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
*
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
*/
export const DEBUG_BUILD = __DEBUG_BUILD__;
3 changes: 2 additions & 1 deletion packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
severityLevelFromString,
} from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { getClient } from '../exports';
import { WINDOW } from '../helpers';

Expand Down Expand Up @@ -148,7 +149,7 @@ function _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerDa
let maxStringLength =
typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;
if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {
__DEBUG_BUILD__ &&
DEBUG_BUILD &&
logger.warn(
`\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,
);
Expand Down
4 changes: 3 additions & 1 deletion packages/browser/src/integrations/dedupe.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { Event, Exception, Integration, StackFrame } from '@sentry/types';
import { logger } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';

/** Deduplication filter */
export class Dedupe implements Integration {
/**
Expand Down Expand Up @@ -40,7 +42,7 @@ export class Dedupe implements Integration {
// Juuust in case something goes wrong
try {
if (_shouldDropEvent(currentEvent, this._previousEvent)) {
__DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');
DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');
return null;
}
} catch (_oO) {} // eslint-disable-line no-empty
Expand Down
3 changes: 2 additions & 1 deletion packages/browser/src/integrations/globalhandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from '@sentry/utils';

import type { BrowserClient } from '../client';
import { DEBUG_BUILD } from '../debug-build';
import { eventFromUnknownInput } from '../eventbuilder';
import { shouldIgnoreOnError } from '../helpers';

Expand Down Expand Up @@ -254,7 +255,7 @@ function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column
}

function globalHandlerLog(type: string): void {
__DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);
DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);
}

function getHubAndOptions(): [Hub, StackParser, boolean | undefined] {
Expand Down
15 changes: 8 additions & 7 deletions packages/browser/src/profiling/hubextensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import type { Transaction } from '@sentry/types';
import { logger, timestampInSeconds, uuid4 } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../helpers';
import type { JSSelfProfile } from './jsSelfProfiling';
import {
Expand All @@ -21,7 +22,7 @@ import {
*/
export function onProfilingStartRouteTransaction(transaction: Transaction | undefined): Transaction | undefined {
if (!transaction) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log('[Profiling] Transaction is undefined, skipping profiling');
}
return transaction;
Expand Down Expand Up @@ -54,7 +55,7 @@ export function startProfileForTransaction(transaction: Transaction): Transactio
return transaction;
}

if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(`[Profiling] started profiling transaction: ${transaction.name || transaction.description}`);
}

Expand Down Expand Up @@ -85,7 +86,7 @@ export function startProfileForTransaction(transaction: Transaction): Transactio
return null;
}
if (processedProfile) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(
'[Profiling] profile for:',
transaction.name || transaction.description,
Expand All @@ -103,13 +104,13 @@ export function startProfileForTransaction(transaction: Transaction): Transactio
maxDurationTimeoutID = undefined;
}

if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(`[Profiling] stopped profiling of transaction: ${transaction.name || transaction.description}`);
}

// In case of an overlapping transaction, stopProfiling may return null and silently ignore the overlapping profile.
if (!profile) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(
`[Profiling] profiler returned null profile for: ${transaction.name || transaction.description}`,
'this may indicate an overlapping transaction or a call to stopProfiling with a profile title that was never started',
Expand All @@ -122,7 +123,7 @@ export function startProfileForTransaction(transaction: Transaction): Transactio
return null;
})
.catch(error => {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log('[Profiling] error while stopping profiler:', error);
}
return null;
Expand All @@ -131,7 +132,7 @@ export function startProfileForTransaction(transaction: Transaction): Transactio

// Enqueue a timeout to prevent profiles from running over max duration.
let maxDurationTimeoutID: number | undefined = WINDOW.setTimeout(() => {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(
'[Profiling] max profile duration elapsed, stopping profiling for:',
transaction.name || transaction.description,
Expand Down
9 changes: 4 additions & 5 deletions packages/browser/src/profiling/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { EventProcessor, Hub, Integration, Transaction } from '@sentry/type
import type { Profile } from '@sentry/types/src/profiling';
import { logger } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { startProfileForTransaction } from './hubextensions';
import type { ProfiledEvent } from './utils';
import {
Expand Down Expand Up @@ -78,14 +79,12 @@ export class BrowserProfilingIntegration implements Integration {
const start_timestamp = context && context['profile'] && context['profile']['start_timestamp'];

if (typeof profile_id !== 'string') {
__DEBUG_BUILD__ &&
logger.log('[Profiling] cannot find profile for a transaction without a profile context');
DEBUG_BUILD && logger.log('[Profiling] cannot find profile for a transaction without a profile context');
continue;
}

if (!profile_id) {
__DEBUG_BUILD__ &&
logger.log('[Profiling] cannot find profile for a transaction without a profile context');
DEBUG_BUILD && logger.log('[Profiling] cannot find profile for a transaction without a profile context');
continue;
}

Expand All @@ -96,7 +95,7 @@ export class BrowserProfilingIntegration implements Integration {

const profile = takeProfileFromGlobalCache(profile_id);
if (!profile) {
__DEBUG_BUILD__ && logger.log(`[Profiling] Could not retrieve profile for transaction: ${profile_id}`);
DEBUG_BUILD && logger.log(`[Profiling] Could not retrieve profile for transaction: ${profile_id}`);
continue;
}

Expand Down
28 changes: 14 additions & 14 deletions packages/browser/src/profiling/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { DebugImage, Envelope, Event, StackFrame, StackParser, Transaction
import type { Profile, ThreadCpuProfile } from '@sentry/types/src/profiling';
import { browserPerformanceTimeOrigin, forEachEnvelopeItem, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { getClient } from '../exports';
import { WINDOW } from '../helpers';
import type { JSSelfProfile, JSSelfProfiler, JSSelfProfilerConstructor, JSSelfProfileStack } from './jsSelfProfiling';
Expand Down Expand Up @@ -96,7 +97,7 @@ function getTraceId(event: Event): string {
// All profiles and transactions are rejected if this is the case and we want to
// warn users that this is happening if they enable debug flag
if (typeof traceId === 'string' && traceId.length !== 32) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`);
}
}
Expand Down Expand Up @@ -418,7 +419,7 @@ export function applyDebugMetadata(resource_paths: ReadonlyArray<string>): Debug
export function isValidSampleRate(rate: unknown): boolean {
// we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
if ((typeof rate !== 'number' && typeof rate !== 'boolean') || (typeof rate === 'number' && isNaN(rate))) {
__DEBUG_BUILD__ &&
DEBUG_BUILD &&
logger.warn(
`[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
rate,
Expand All @@ -434,16 +435,15 @@ export function isValidSampleRate(rate: unknown): boolean {

// in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
if (rate < 0 || rate > 1) {
__DEBUG_BUILD__ &&
logger.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`);
DEBUG_BUILD && logger.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`);
return false;
}
return true;
}

function isValidProfile(profile: JSSelfProfile): profile is JSSelfProfile & { profile_id: string } {
if (profile.samples.length < 2) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
// Log a warning if the profile has less than 2 samples so users can know why
// they are not seeing any profiling data and we cant avoid the back and forth
// of asking them to provide us with a dump of the profile data.
Expand All @@ -453,7 +453,7 @@ function isValidProfile(profile: JSSelfProfile): profile is JSSelfProfile & { pr
}

if (!profile.frames.length) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log('[Profiling] Discarding profile because it contains no frames');
}
return false;
Expand Down Expand Up @@ -483,7 +483,7 @@ export function startJSSelfProfile(): JSSelfProfiler | undefined {
const JSProfilerConstructor = WINDOW.Profiler;

if (!isJSProfilerSupported(JSProfilerConstructor)) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(
'[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.',
);
Expand All @@ -502,7 +502,7 @@ export function startJSSelfProfile(): JSSelfProfiler | undefined {
try {
return new JSProfilerConstructor({ sampleInterval: samplingIntervalMS, maxBufferSize: maxSamples });
} catch (e) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log(
"[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header.",
);
Expand All @@ -520,14 +520,14 @@ export function startJSSelfProfile(): JSSelfProfiler | undefined {
export function shouldProfileTransaction(transaction: Transaction): boolean {
// If constructor failed once, it will always fail, so we can early return.
if (PROFILING_CONSTRUCTOR_FAILED) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log('[Profiling] Profiling has been disabled for the duration of the current user session.');
}
return false;
}

if (!transaction.sampled) {
if (__DEBUG_BUILD__) {
if (DEBUG_BUILD) {
logger.log('[Profiling] Discarding profile because transaction was not sampled.');
}
return false;
Expand All @@ -536,7 +536,7 @@ export function shouldProfileTransaction(transaction: Transaction): boolean {
const client = getClient();
const options = client && client.getOptions();
if (!options) {
__DEBUG_BUILD__ && logger.log('[Profiling] Profiling disabled, no options found.');
DEBUG_BUILD && logger.log('[Profiling] Profiling disabled, no options found.');
return false;
}

Expand All @@ -546,13 +546,13 @@ export function shouldProfileTransaction(transaction: Transaction): boolean {
// Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
// only valid values are booleans or numbers between 0 and 1.)
if (!isValidSampleRate(profilesSampleRate)) {
__DEBUG_BUILD__ && logger.warn('[Profiling] Discarding profile because of invalid sample rate.');
DEBUG_BUILD && logger.warn('[Profiling] Discarding profile because of invalid sample rate.');
return false;
}

// if the function returned 0 (or false), or if `profileSampleRate` is 0, it's a sign the profile should be dropped
if (!profilesSampleRate) {
__DEBUG_BUILD__ &&
DEBUG_BUILD &&
logger.log(
'[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0',
);
Expand All @@ -564,7 +564,7 @@ export function shouldProfileTransaction(transaction: Transaction): boolean {
const sampled = profilesSampleRate === true ? true : Math.random() < profilesSampleRate;
// Check if we should sample this profile
if (!sampled) {
__DEBUG_BUILD__ &&
DEBUG_BUILD &&
logger.log(
`[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(
profilesSampleRate,
Expand Down
10 changes: 5 additions & 5 deletions packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {

import type { BrowserClientOptions, BrowserOptions } from './client';
import { BrowserClient } from './client';
import { DEBUG_BUILD } from './debug-build';
import type { ReportDialogOptions } from './helpers';
import { WINDOW, wrap as internalWrap } from './helpers';
import { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';
Expand Down Expand Up @@ -140,14 +141,14 @@ export function init(options: BrowserOptions = {}): void {
export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {
// doesn't work without a document (React Native)
if (!WINDOW.document) {
__DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');
DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');
return;
}

const { client, scope } = hub.getStackTop();
const dsn = options.dsn || (client && client.getDsn());
if (!dsn) {
__DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');
DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');
return;
}

Expand Down Expand Up @@ -189,7 +190,7 @@ export function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = g
if (injectionPoint) {
injectionPoint.appendChild(script);
} else {
__DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');
DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');
}
}

Expand Down Expand Up @@ -236,8 +237,7 @@ function startSessionOnHub(hub: Hub): void {
*/
function startSessionTracking(): void {
if (typeof WINDOW.document === 'undefined') {
__DEBUG_BUILD__ &&
logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
DEBUG_BUILD && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
return;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/transports/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isNativeFetch, logger } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../helpers';

let cachedFetchImpl: FetchImpl | undefined = undefined;
Expand Down Expand Up @@ -70,8 +71,7 @@ export function getNativeFetchImplementation(): FetchImpl {
}
document.head.removeChild(sandbox);
} catch (e) {
__DEBUG_BUILD__ &&
logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
DEBUG_BUILD && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);
}
}

Expand Down
Loading