or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-utilities.mddata-processing.mdenvelopes.mdenvironment.mderror-handling.mdindex.mdinstrumentation.mdlogging.mdstack-processing.mdtype-guards.md

index.mddocs/

0

# @sentry/utils

1

2

**DEPRECATED NOTICE**: The `@sentry/utils` package is deprecated as of version 8.55.0. All functionality has been moved to `@sentry/core`. This package now serves only as a compatibility layer during the migration period.

3

4

@sentry/utils provides common utilities used internally by all Sentry JavaScript SDKs. While deprecated, it contains over 160 utility functions and classes for error handling, performance monitoring, browser compatibility, envelope creation, instrumentation handlers, and various helper functions that were previously shared across different Sentry SDK packages.

5

6

## Package Information

7

8

- **Package Name**: @sentry/utils

9

- **Package Type**: npm

10

- **Language**: TypeScript

11

- **Installation**: `npm install @sentry/utils` (deprecated - use `@sentry/core` instead)

12

- **Node.js requirement**: >=14.18

13

14

## Core Imports

15

16

**Deprecated imports** (migrate to @sentry/core):

17

18

```typescript

19

import {

20

SentryError,

21

logger,

22

normalize,

23

uuid4,

24

addInstrumentationHandler,

25

isError,

26

isBrowser

27

} from "@sentry/utils";

28

```

29

30

**Recommended migration** (import from @sentry/core instead):

31

32

```typescript

33

import {

34

SentryError,

35

logger,

36

normalize,

37

uuid4,

38

addInstrumentationHandler,

39

isError,

40

isBrowser

41

} from "@sentry/core";

42

```

43

44

For CommonJS:

45

46

```javascript

47

const { SentryError, logger, normalize } = require("@sentry/utils"); // deprecated

48

const { SentryError, logger, normalize } = require("@sentry/core"); // recommended

49

```

50

51

## Basic Usage

52

53

**Note**: All examples show deprecated usage. Replace `@sentry/utils` imports with `@sentry/core`.

54

55

```typescript

56

import { SentryError, logger, normalize, uuid4 } from "@sentry/utils";

57

58

// Create Sentry-specific errors

59

const error = new SentryError("Custom error message");

60

61

// Use the logger

62

logger.info("Processing data...");

63

64

// Normalize data for transmission

65

const normalized = normalize({ user: "john", data: largeObject }, 3);

66

67

// Generate unique identifiers

68

const eventId = uuid4();

69

70

// Check environment

71

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

72

if (isBrowser()) {

73

// Browser-specific logic

74

} else if (isNodeEnv()) {

75

// Node.js-specific logic

76

}

77

```

78

79

## Architecture

80

81

@sentry/utils is organized around several key areas:

82

83

- **Error Processing**: Exception handling, error type detection, and error normalization

84

- **Instrumentation**: Event handlers for console, fetch, errors, and unhandled rejections

85

- **Environment Detection**: Browser/Node.js detection and feature support checking

86

- **Data Processing**: Normalization, serialization, and data structure manipulation

87

- **Logging**: Centralized logging with console sandboxing

88

- **Stack Processing**: Stack frame parsing, filtering, and manipulation utilities

89

- **Envelope System**: Data packaging for transmission to Sentry servers

90

- **Tracing**: Trace propagation and baggage header processing

91

- **Helper Functions**: UUID generation, path utilities, URL processing, and type guards

92

93

## Capabilities

94

95

### Error Handling & Processing

96

97

Core error processing functionality for detecting, normalizing, and enriching error data before transmission to Sentry.

98

99

```typescript { .api }

100

class SentryError extends Error {

101

constructor(message: string, logLevel?: string);

102

}

103

104

function isError(wat: unknown): wat is Error;

105

function isErrorEvent(wat: unknown): wat is ErrorEvent;

106

function isDOMError(wat: unknown): wat is DOMError;

107

function isDOMException(wat: unknown): wat is DOMException;

108

function exceptionFromError(parser: StackParser, ex: Error): Exception;

109

function applyAggregateErrorsToEvent(

110

exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,

111

parser: StackParser,

112

maxValueLimit: number,

113

key: string,

114

limit: number,

115

event: Event,

116

hint?: EventHint,

117

): void;

118

```

119

120

[Error Handling](./error-handling.md)

121

122

### Instrumentation & Event Handling

123

124

Instrumentation handlers for automatically capturing console logs, network requests, errors, and other events.

125

126

```typescript { .api }

127

function addConsoleInstrumentationHandler(handler: (level: string, ...args: any[]) => void): void;

128

function addFetchInstrumentationHandler(handler: (data: FetchBreadcrumbData) => void): void;

129

function addGlobalErrorInstrumentationHandler(handler: (data: ErrorEventData) => void): void;

130

function addGlobalUnhandledRejectionInstrumentationHandler(handler: (data: UnhandledRejectionEventData) => void): void;

131

function resetInstrumentationHandlers(): void;

132

function triggerHandlers(type: string, data: any): void;

133

```

134

135

[Instrumentation](./instrumentation.md)

136

137

### Type Guards & Validation

138

139

Comprehensive type checking utilities for safe runtime type detection and validation.

140

141

```typescript { .api }

142

function isPlainObject(wat: unknown): wat is Record<string, any>;

143

function isPrimitive(wat: unknown): wat is Primitive;

144

function isString(wat: unknown): wat is string;

145

function isRegExp(wat: unknown): wat is RegExp;

146

function isThenable(wat: any): wat is PromiseLike<any>;

147

function isInstanceOf(wat: any, base: any): boolean;

148

function isElement(wat: unknown): wat is Element;

149

function isEvent(wat: unknown): wat is Event;

150

function isSyntheticEvent(wat: unknown): wat is { [key: string]: any };

151

```

152

153

[Type Guards](./type-guards.md)

154

155

### Environment & Browser Detection

156

157

Environment detection utilities for determining runtime capabilities and platform-specific features.

158

159

```typescript { .api }

160

function isBrowser(): boolean;

161

function isNodeEnv(): boolean;

162

function isBrowserBundle(): boolean;

163

function supportsFetch(): boolean;

164

function supportsNativeFetch(): boolean;

165

function supportsDOMError(): boolean;

166

function supportsDOMException(): boolean;

167

function supportsErrorEvent(): boolean;

168

function supportsHistory(): boolean;

169

function supportsReferrerPolicy(): boolean;

170

function supportsReportingObserver(): boolean;

171

```

172

173

[Environment Detection](./environment.md)

174

175

### Data Normalization & Processing

176

177

Data normalization and serialization utilities for preparing data structures for transmission.

178

179

```typescript { .api }

180

function normalize(input: any, depth?: number, maxProperties?: number): any;

181

function normalizeToSize(

182

object: { [key: string]: any },

183

minSize?: number,

184

maxSize?: number,

185

): { [key: string]: any };

186

function convertToPlainObject(input: any): PlainObject;

187

function dropUndefinedKeys(inputValue: { [key: string]: any }): { [key: string]: any };

188

function addNonEnumerableProperty(obj: any, name: string, value: any): void;

189

function objectify(wat: unknown): { [key: string]: any };

190

function arrayify(wat: unknown): any[];

191

function flatten<T>(arr: ReadonlyArray<T | ReadonlyArray<T>>): T[];

192

```

193

194

[Data Processing](./data-processing.md)

195

196

### Logging & Console

197

198

Centralized logging system with console sandboxing and original method preservation.

199

200

```typescript { .api }

201

interface Logger {

202

disable(): void;

203

enable(): void;

204

log(...args: any[]): void;

205

warn(...args: any[]): void;

206

error(...args: any[]): void;

207

}

208

209

declare const logger: Logger;

210

declare const CONSOLE_LEVELS: readonly string[];

211

declare const originalConsoleMethods: { [key in 'log' | 'warn' | 'error']: (...args: any[]) => void };

212

213

function consoleSandbox<T>(callback: () => T): T;

214

```

215

216

[Logging](./logging.md)

217

218

### Stack Processing & Parsing

219

220

Stack trace parsing, manipulation, and filtering utilities for error processing.

221

222

```typescript { .api }

223

interface StackFrame {

224

filename?: string;

225

function?: string;

226

module?: string;

227

platform?: string;

228

lineno?: number;

229

colno?: number;

230

abs_path?: string;

231

context_line?: string;

232

pre_context?: string[];

233

post_context?: string[];

234

in_app?: boolean;

235

instruction_addr?: string;

236

addr_mode?: string;

237

package?: string;

238

symbol?: string;

239

symbol_addr?: string;

240

trust?: string;

241

}

242

243

type StackLineParser = (line: string) => StackFrame | undefined;

244

type StackParser = (stack: string, skipFirst?: number) => StackFrame[];

245

246

function createStackParser(...parsers: StackLineParser[]): StackParser;

247

function getFramesFromEvent(event: Event): StackFrame[] | undefined;

248

function parseStackFrames(parser: StackParser, err: Error & { stacktrace?: string }): StackFrame[];

249

```

250

251

[Stack Processing](./stack-processing.md)

252

253

### Envelope System

254

255

Data packaging system for structuring and transmitting telemetry data to Sentry servers.

256

257

```typescript { .api }

258

type EnvelopeItemType = 'event' | 'transaction' | 'session' | 'attachment' | 'user_report' | 'profile';

259

260

interface EnvelopeItem<T = any> {

261

0: EnvelopeItemHeader;

262

1: T;

263

}

264

265

interface Envelope {

266

0: EnvelopeHeader;

267

1: EnvelopeItem[];

268

}

269

270

function createEnvelope<E extends Envelope>(

271

headers: E[0],

272

items?: E[1]

273

): E;

274

function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E;

275

function forEachEnvelopeItem<E extends Envelope>(

276

envelope: E,

277

callback: (item: E[1][number], type?: EnvelopeItemType) => boolean | void,

278

): boolean;

279

function serializeEnvelope(envelope: Envelope): string;

280

function parseEnvelope(env: string): Envelope;

281

```

282

283

[Envelopes](./envelopes.md)

284

285

### Promise & Async Utilities

286

287

Synchronous promise implementation and promise buffer management for reliable async operations.

288

289

```typescript { .api }

290

class SyncPromise<T> implements PromiseLike<T> {

291

constructor(

292

executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void

293

);

294

then<TResult1 = T, TResult2 = never>(

295

onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,

296

onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,

297

): SyncPromise<TResult1 | TResult2>;

298

catch<TResult = never>(

299

onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,

300

): SyncPromise<T | TResult>;

301

}

302

303

function resolvedSyncPromise<T>(value: T): SyncPromise<T>;

304

function rejectedSyncPromise<T = never>(value: any): SyncPromise<T>;

305

306

interface PromiseBuffer<T> {

307

$: Array<PromiseLike<T>>;

308

add(taskProducer: () => PromiseLike<T>): PromiseLike<T>;

309

drain(timeout?: number): PromiseLike<boolean>;

310

}

311

312

function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T>;

313

```

314

315

[Async Utilities](./async-utilities.md)

316

317

## Types

318

319

### Core Types

320

321

```typescript { .api }

322

interface InternalGlobal {

323

console?: Console;

324

__SENTRY__?: {

325

globalEventProcessors?: EventProcessor[];

326

hub?: Hub;

327

logger?: Logger;

328

};

329

}

330

331

type SdkSource = 'npm' | 'cdn' | 'loader';

332

333

interface RateLimits {

334

[category: string]: number;

335

}

336

337

interface AddRequestDataToEventOptions {

338

include?: {

339

cookies?: boolean;

340

data?: boolean;

341

headers?: boolean;

342

ip?: boolean;

343

query_string?: boolean;

344

url?: boolean;

345

user?: boolean;

346

};

347

deps?: {

348

cookie?: {

349

parse: (cookieStr: string) => Record<string, string>;

350

};

351

url?: {

352

parse: (urlStr: string) => {

353

query: string | null;

354

};

355

};

356

};

357

}

358

```

359

360

**Migration Notice**: All types, functions, and classes from @sentry/utils are deprecated. Import them from @sentry/core instead:

361

362

```typescript

363

// ❌ Deprecated

364

import { SentryError, Logger } from "@sentry/utils";

365

366

// ✅ Recommended

367

import { SentryError, Logger } from "@sentry/core";

368

```