CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sentry--utils

Deprecated utilities package for Sentry JavaScript SDKs - all functionality moved to @sentry/core

Pending
Overview
Eval results
Files

environment.mddocs/

Environment & Browser Detection

DEPRECATED: Import all functions from @sentry/core instead of @sentry/utils.

Environment detection utilities for determining runtime capabilities and platform-specific features across browsers and Node.js environments.

Capabilities

Runtime Environment Detection

Core functions for detecting the current JavaScript runtime environment.

/**
 * Detects if code is running in a browser environment
 * @returns True if running in browser
 */
function isBrowser(): boolean;

/**
 * Detects if code is running in Node.js environment
 * @returns True if running in Node.js
 */
function isNodeEnv(): boolean;

/**
 * Detects if code is running as a browser bundle (vs. server-side rendering)
 * @returns True if running as browser bundle
 */
function isBrowserBundle(): boolean;

Usage Examples:

import { isBrowser, isNodeEnv, isBrowserBundle } from "@sentry/core";

// Platform-specific initialization
if (isBrowser()) {
  // Browser-only code
  setupBrowserInstrumentation();
  registerServiceWorker();
} else if (isNodeEnv()) {
  // Node.js-only code
  setupNodeInstrumentation();
  loadServerConfig();
}

// Bundle detection for SSR
function initializeApp() {
  if (isBrowserBundle()) {
    // Client-side hydration
    ReactDOM.hydrate(<App />, document.getElementById('root'));
  } else {
    // Server-side rendering
    return ReactDOMServer.renderToString(<App />);
  }
}

Browser API Support Detection

Functions for detecting support for specific browser APIs and features.

/**
 * Checks if the Fetch API is available
 * @returns True if fetch is supported
 */
function supportsFetch(): boolean;

/**
 * Checks if native fetch is available (not polyfilled)
 * @returns True if native fetch is supported
 */
function supportsNativeFetch(): boolean;

/**
 * Checks if History API is available (pushState, replaceState)
 * @returns True if History API is supported
 */
function supportsHistory(): boolean;

/**
 * Checks if Referrer Policy is supported
 * @returns True if referrer policy is supported
 */
function supportsReferrerPolicy(): boolean;

/**
 * Checks if ReportingObserver API is available
 * @returns True if ReportingObserver is supported
 */
function supportsReportingObserver(): boolean;

Usage Examples:

import { 
  supportsFetch, 
  supportsNativeFetch, 
  supportsHistory 
} from "@sentry/core";

// Conditional network request setup
function setupNetworkMonitoring() {
  if (supportsFetch()) {
    // Use fetch for network requests
    addFetchInstrumentation();
  } else {
    // Fallback to XMLHttpRequest
    addXHRInstrumentation();
  }
  
  // Prefer native fetch for better performance
  if (supportsNativeFetch()) {
    console.log('Using native fetch API');
  } else {
    console.log('Using fetch polyfill');
  }
}

// History API for single-page apps
function setupRouting() {
  if (supportsHistory()) {
    // Use pushState/replaceState for routing
    window.addEventListener('popstate', handleRouteChange);
  } else {
    // Fallback to hash-based routing
    window.addEventListener('hashchange', handleHashChange);
  }
}

Error API Support Detection

Functions for detecting support for various error-related browser APIs.

/**
 * Checks if DOMError constructor is available
 * @returns True if DOMError is supported
 */
function supportsDOMError(): boolean;

/**
 * Checks if DOMException constructor is available  
 * @returns True if DOMException is supported
 */
function supportsDOMException(): boolean;

/**
 * Checks if ErrorEvent constructor is available
 * @returns True if ErrorEvent is supported
 */
function supportsErrorEvent(): boolean;

Usage Example:

import { 
  supportsDOMError, 
  supportsDOMException, 
  supportsErrorEvent 
} from "@sentry/core";

function setupErrorHandling() {
  // Enhanced error categorization based on support
  window.addEventListener('error', (event) => {
    let errorType = 'generic';
    
    if (supportsErrorEvent() && event instanceof ErrorEvent) {
      errorType = 'ErrorEvent';
    } else if (supportsDOMError() && event.error instanceof DOMError) {
      errorType = 'DOMError';  
    } else if (supportsDOMException() && event.error instanceof DOMException) {
      errorType = 'DOMException';
    }
    
    console.log(`Captured ${errorType}:`, event.error);
  });
}

Function Detection

Utilities for detecting native vs. wrapped functions.

/**
 * Checks if a function is a native browser/Node.js function (not wrapped or polyfilled)
 * @param func - Function to check
 * @returns True if function appears to be native
 */
function isNativeFunction(func: Function): boolean;

Usage Example:

import { isNativeFunction } from "@sentry/core";

function analyzeFunction(fn: Function) {
  if (isNativeFunction(fn)) {
    console.log('Native function detected');
    // Safe to instrument directly
    return instrumentNative(fn);
  } else {
    console.log('Wrapped or polyfilled function detected');
    // Use more careful instrumentation
    return instrumentSafely(fn);
  }
}

// Check if fetch is native or polyfilled
if (typeof fetch === 'function') {
  const isNative = isNativeFunction(fetch);
  console.log(`Fetch is ${isNative ? 'native' : 'polyfilled'}`);
}

Environment Detection Patterns

Feature Detection Strategy

Use feature detection instead of user agent parsing for reliable cross-browser support:

import { 
  isBrowser, 
  supportsFetch, 
  supportsHistory,
  supportsReportingObserver 
} from "@sentry/core";

interface BrowserCapabilities {
  hasNetworkAPI: boolean;
  hasRouting: boolean;
  hasReporting: boolean;
  platform: 'browser' | 'node' | 'unknown';
}

function detectCapabilities(): BrowserCapabilities {
  return {
    hasNetworkAPI: isBrowser() && supportsFetch(),
    hasRouting: isBrowser() && supportsHistory(),
    hasReporting: isBrowser() && supportsReportingObserver(),
    platform: isBrowser() ? 'browser' : (isNodeEnv() ? 'node' : 'unknown'),
  };
}

Progressive Enhancement

Use environment detection for progressive enhancement:

import { 
  isBrowser, 
  supportsFetch, 
  supportsReportingObserver 
} from "@sentry/core";

class MonitoringClient {
  private capabilities = detectCapabilities();
  
  init() {
    // Base functionality always available
    this.setupBasicErrorHandling();
    
    // Progressive enhancement based on environment
    if (this.capabilities.hasNetworkAPI) {
      this.setupNetworkMonitoring();
    }
    
    if (this.capabilities.hasReporting) {
      this.setupReportingObserver();
    }
  }
  
  private setupNetworkMonitoring() {
    if (supportsFetch()) {
      // Enhanced network monitoring with fetch
      addFetchInstrumentationHandler(this.handleNetworkEvent);
    }
  }
  
  private setupReportingObserver() {
    if (supportsReportingObserver()) {
      // Modern reporting API for deprecations, violations, etc.
      const observer = new ReportingObserver(this.handleReport);
      observer.observe();
    }
  }
}

Conditional Module Loading

Environment detection for conditional module loading:

import { isNodeEnv, isBrowser } from "@sentry/core";

async function loadPlatformSpecificModules() {
  if (isNodeEnv()) {
    // Node.js-specific modules
    const fs = await import('fs');
    const path = await import('path');
    return { fs, path };
  } else if (isBrowser()) {
    // Browser-specific modules  
    const { setupServiceWorker } = await import('./serviceWorker');
    const { initializeAnalytics } = await import('./analytics');
    return { setupServiceWorker, initializeAnalytics };
  }
  
  return {};
}

Environment Constants

// Global object reference (window in browser, global in Node.js)
declare const GLOBAL_OBJ: typeof globalThis;

/**
 * Gets a global singleton instance
 * @param name - Name of the singleton
 * @param creator - Function to create the singleton if it doesn't exist
 * @param obj - Global object to store the singleton (defaults to GLOBAL_OBJ)
 * @returns The singleton instance
 */
function getGlobalSingleton<T>(
  name: string,
  creator: () => T,
  obj?: any
): T;

Usage Example:

import { getGlobalSingleton, GLOBAL_OBJ } from "@sentry/core";

// Create a global logger singleton
const logger = getGlobalSingleton('__SENTRY_LOGGER__', () => {
  return new Logger({ level: 'info' });
});

// Access global object consistently
console.log('Global object:', GLOBAL_OBJ === window); // true in browser
console.log('Global object:', GLOBAL_OBJ === global); // true in Node.js

Migration Note: All environment detection functions have been moved from @sentry/utils to @sentry/core. Update your imports accordingly.

Install with Tessl CLI

npx tessl i tessl/npm-sentry--utils

docs

async-utilities.md

data-processing.md

envelopes.md

environment.md

error-handling.md

index.md

instrumentation.md

logging.md

stack-processing.md

type-guards.md

tile.json