or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-source-map-support

Fixes stack traces for files with source maps

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/source-map-support@0.5.x

To install, run

npx @tessl/cli install tessl/npm-source-map-support@0.5.0

0

# Source Map Support

1

2

Source Map Support provides source map support for stack traces in Node.js via the V8 stack trace API. It uses the source-map module to replace the paths and line numbers of source-mapped files with their original paths and line numbers, making compile-to-JavaScript languages more of a first-class citizen in the Node.js ecosystem.

3

4

## Package Information

5

6

- **Package Name**: source-map-support

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install source-map-support`

10

11

## Core Imports

12

13

```javascript

14

const sourceMapSupport = require('source-map-support');

15

```

16

17

ES6 import:

18

19

```javascript

20

import sourceMapSupport from 'source-map-support';

21

```

22

23

Convenience imports:

24

25

```javascript

26

// Auto-install with default options

27

require('source-map-support/register');

28

29

// Auto-install with hookRequire enabled

30

require('source-map-support/register-hook-require');

31

```

32

33

For browser environments:

34

35

```html

36

<script src="browser-source-map-support.js"></script>

37

```

38

39

## Basic Usage

40

41

```javascript

42

const sourceMapSupport = require('source-map-support');

43

44

// Install with default options

45

sourceMapSupport.install();

46

47

// Install with custom options

48

sourceMapSupport.install({

49

handleUncaughtExceptions: true,

50

environment: 'node',

51

hookRequire: false

52

});

53

```

54

55

**CLI Usage:**

56

57

```bash

58

node -r source-map-support/register compiled.js

59

```

60

61

**Programmatic Auto-install:**

62

63

```javascript

64

// Simply require the register module

65

require('source-map-support/register');

66

67

// ES6 equivalent

68

import 'source-map-support/register';

69

```

70

71

## Architecture

72

73

Source Map Support is built around several key components that work together to provide seamless source map integration:

74

75

- **V8 Stack Trace API Integration**: Hooks into Node.js's `Error.prepareStackTrace` to intercept and modify stack traces before they're formatted

76

- **Source Map Consumer**: Uses the `source-map` library to parse and query source map files for position mapping

77

- **File/Map Retrieval System**: Extensible handler system for loading source files and source maps from various sources (filesystem, HTTP, inline, custom)

78

- **Error Formatter**: Replaces generated file positions with original source positions and provides source context for better debugging

79

- **Uncaught Exception Handler**: Optionally installs process-level exception handling to format unhandled errors with source-mapped stack traces

80

- **Environment Detection**: Automatically detects Node.js vs browser environments and adapts behavior accordingly

81

82

The package works by:

83

1. Installing a custom `Error.prepareStackTrace` function that processes each stack frame

84

2. For each frame, checking if source maps are available for the file

85

3. If found, mapping the generated position to the original source position

86

4. Formatting the final stack trace to show original file paths and line numbers

87

88

## Capabilities

89

90

### Install Source Map Support

91

92

Installs source map support for stack traces and uncaught exceptions with customizable options.

93

94

```javascript { .api }

95

/**

96

* Installs source map support for stack traces and uncaught exceptions

97

* @param {Object} [options] - Configuration options

98

* @param {boolean} [options.handleUncaughtExceptions=true] - Whether to handle uncaught exceptions

99

* @param {Function} [options.retrieveSourceMap] - Custom source map retrieval function

100

* @param {Function} [options.retrieveFile] - Custom file retrieval function

101

* @param {boolean} [options.overrideRetrieveSourceMap=false] - Replace default source map handlers

102

* @param {boolean} [options.overrideRetrieveFile=false] - Replace default file handlers

103

* @param {string} [options.environment='auto'] - Environment type: 'node', 'browser', or 'auto'

104

* @param {boolean} [options.hookRequire=false] - Monitor source files for inline source maps

105

* @param {boolean} [options.emptyCacheBetweenOperations=false] - Reset caches between operations

106

*/

107

function install(options);

108

```

109

110

**Usage Examples:**

111

112

```javascript

113

const sourceMapSupport = require('source-map-support');

114

115

// Basic installation

116

sourceMapSupport.install();

117

118

// Custom configuration

119

sourceMapSupport.install({

120

handleUncaughtExceptions: false,

121

environment: 'node',

122

hookRequire: true,

123

retrieveSourceMap: function(source) {

124

// Custom logic to retrieve source maps

125

return { url: 'custom.map', map: mapContent };

126

}

127

});

128

```

129

130

### Wrap Call Site

131

132

Wraps a V8 CallSite object to provide source-mapped information for stack traces.

133

134

```javascript { .api }

135

/**

136

* Wraps a V8 CallSite object to provide source-mapped information

137

* @param {CallSite} frame - V8 CallSite object

138

* @param {Object} [state] - State object for tracking position information

139

* @returns {CallSite} Modified CallSite object with source-mapped information

140

*/

141

function wrapCallSite(frame, state);

142

```

143

144

### Get Error Source

145

146

Extracts source information from error stack traces, providing formatted source location and code snippets.

147

148

```javascript { .api }

149

/**

150

* Extracts source information from error stack traces

151

* @param {Error} error - Error object with stack trace

152

* @returns {string|null} Formatted source location and code snippet, or null if unavailable

153

*/

154

function getErrorSource(error);

155

```

156

157

**Usage Example:**

158

159

```javascript

160

const sourceMapSupport = require('source-map-support');

161

162

try {

163

// Some code that might throw

164

throw new Error('Something went wrong');

165

} catch (error) {

166

const sourceInfo = sourceMapSupport.getErrorSource(error);

167

if (sourceInfo) {

168

console.log('Source context:', sourceInfo);

169

}

170

}

171

```

172

173

### Map Source Position

174

175

Maps a generated source position to the original source position using available source maps.

176

177

```javascript { .api }

178

/**

179

* Maps a generated source position to original source position

180

* @param {Object} position - Position object with source, line, column properties

181

* @param {string} position.source - Source file path or URL

182

* @param {number} position.line - Line number (1-based)

183

* @param {number} position.column - Column number (0-based)

184

* @returns {Object} Object with mapped original position information

185

*/

186

function mapSourcePosition(position);

187

```

188

189

**Usage Example:**

190

191

```javascript

192

const sourceMapSupport = require('source-map-support');

193

194

const originalPosition = sourceMapSupport.mapSourcePosition({

195

source: '/path/to/compiled.js',

196

line: 15,

197

column: 10

198

});

199

200

console.log(originalPosition);

201

// {

202

// source: '/path/to/original.ts',

203

// line: 23,

204

// column: 5,

205

// name: 'originalFunction'

206

// }

207

```

208

209

### Retrieve Source Map

210

211

Retrieves the source map for a given source file, supporting both inline and external source maps.

212

213

```javascript { .api }

214

/**

215

* Retrieves source map for a given source file

216

* @param {string} source - Source file path or URL

217

* @returns {Object|null} Object with url and map properties, or null if no source map found

218

*/

219

function retrieveSourceMap(source);

220

```

221

222

**Usage Example:**

223

224

```javascript

225

const sourceMapSupport = require('source-map-support');

226

227

const sourceMap = sourceMapSupport.retrieveSourceMap('/path/to/compiled.js');

228

if (sourceMap) {

229

console.log('Source map URL:', sourceMap.url);

230

console.log('Source map data:', sourceMap.map);

231

}

232

```

233

234

### Reset Retrieve Handlers

235

236

Resets file and source map retrieval handlers to their original state, useful for testing or dynamic configuration.

237

238

```javascript { .api }

239

/**

240

* Resets file and source map retrieval handlers to their original state

241

*/

242

function resetRetrieveHandlers();

243

```

244

245

## Types

246

247

```javascript { .api }

248

/**

249

* Configuration options for install()

250

*/

251

interface InstallOptions {

252

/** Whether to handle uncaught exceptions (default: true) */

253

handleUncaughtExceptions: boolean;

254

/** Custom source map retrieval function */

255

retrieveSourceMap: (source: string) => { url: string, map: string } | null;

256

/** Custom file retrieval function */

257

retrieveFile: (path: string) => string | null;

258

/** Replace default source map handlers (default: false) */

259

overrideRetrieveSourceMap: boolean;

260

/** Replace default file handlers (default: false) */

261

overrideRetrieveFile: boolean;

262

/** Environment type: 'node', 'browser', or 'auto' (default: 'auto') */

263

environment: 'node' | 'browser' | 'auto';

264

/** Monitor source files for inline source maps (default: false) */

265

hookRequire: boolean;

266

/** Reset caches between operations (default: false) */

267

emptyCacheBetweenOperations: boolean;

268

}

269

270

/**

271

* Position object for source mapping

272

*/

273

interface Position {

274

/** Source file path or URL */

275

source: string;

276

/** Line number (1-based) */

277

line: number;

278

/** Column number (0-based) */

279

column: number;

280

}

281

282

/**

283

* Mapped position result

284

*/

285

interface MappedPosition {

286

/** Original source file path */

287

source: string;

288

/** Original line number */

289

line: number;

290

/** Original column number */

291

column: number;

292

/** Original symbol name, if available */

293

name?: string;

294

}

295

296

/**

297

* Source map retrieval result

298

*/

299

interface SourceMapResult {

300

/** URL or path to the source map */

301

url: string;

302

/** Source map content as string or parsed object */

303

map: string | Object;

304

}

305

```

306

307

## Error Handling

308

309

The module provides enhanced error stack traces by:

310

- Detecting source mapping URLs in generated files (`//# sourceMappingURL=...`)

311

- Loading and parsing source maps (inline or external)

312

- Mapping generated positions to original positions

313

- Formatting stack traces to show original file locations

314

- Providing source code context for errors when available

315

316

Common source map URL formats supported:

317

- External files: `//# sourceMappingURL=path/to/file.map`

318

- Inline maps: `//# sourceMappingURL=data:application/json;charset=utf-8;base64,<base64-encoded-map>`

319

320

## Platform-Specific Behavior

321

322

### Node.js Environment

323

- Uses filesystem APIs to read source map files

324

- Supports both absolute and relative paths

325

- Integrates with Node.js process and module systems

326

- Handles uncaught exceptions when enabled

327

328

### Browser Environment

329

- Uses XMLHttpRequest for loading external source maps

330

- Supports both relative and absolute URLs

331

- Works with bundled browser-source-map-support.js file

332

- Compatible with AMD/RequireJS

333

334

### Auto-Detection

335

The package automatically detects the environment based on available globals:

336

- Node.js: Presence of `process` and `require`

337

- Browser: Presence of `window` and `XMLHttpRequest`