3 This is a library to generate and consume the source map format
4 [described here][format].
6 This library is written in the Asynchronous Module Definition format, and works
7 in the following environments:
9 * Modern Browsers supporting ECMAScript 5 (either after the build, or with an
10 AMD loader such as RequireJS)
12 * Inside Firefox (as a JSM file, after the build)
14 * With NodeJS versions 0.8.X and higher
18 $ npm install source-map
20 ## Building from Source (for everywhere else)
22 Install Node and then run
24 $ git clone https://fitzgen@github.com/mozilla/source-map.git
30 $ node Makefile.dryice.js
32 This should spew a bunch of stuff to stdout, and create the following files:
34 * `dist/source-map.js` - The unminified browser version.
36 * `dist/source-map.min.js` - The minified browser version.
38 * `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source.
42 ### Consuming a source map
47 names: ['bar', 'baz', 'n'],
48 sources: ['one.js', 'two.js'],
49 sourceRoot: 'http://example.com/www/js/',
50 mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
53 var smc = new SourceMapConsumer(rawSourceMap);
55 console.log(smc.sources);
56 // [ 'http://example.com/www/js/one.js',
57 // 'http://example.com/www/js/two.js' ]
59 console.log(smc.originalPositionFor({
63 // { source: 'http://example.com/www/js/two.js',
68 console.log(smc.generatedPositionFor({
69 source: 'http://example.com/www/js/two.js',
73 // { line: 2, column: 28 }
75 smc.eachMapping(function (m) {
79 ### Generating a source map
82 [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
84 #### With SourceNode (high level API)
86 function compile(ast) {
88 case 'BinaryExpression':
89 return new SourceNode(
93 [compile(ast.left), " + ", compile(ast.right)]
96 return new SourceNode(
104 throw new Error("Bad AST");
108 var ast = parse("40 + 2", "add.js");
109 console.log(compile(ast).toStringWithSourceMap({
113 // map: [object SourceMapGenerator] }
115 #### With SourceMapGenerator (low level API)
117 var map = new SourceMapGenerator({
118 file: "source-mapped.js"
134 console.log(map.toString());
135 // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
139 Get a reference to the module:
142 var sourceMap = require('source-map');
145 var sourceMap = window.sourceMap;
149 Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);
151 ### SourceMapConsumer
153 A SourceMapConsumer instance represents a parsed source map which we can query
154 for information about the original file positions by giving it a file position
155 in the generated source.
157 #### new SourceMapConsumer(rawSourceMap)
159 The only parameter is the raw source map (either as a string which can be
160 `JSON.parse`'d, or an object). According to the spec, source maps have the
161 following attributes:
163 * `version`: Which version of the source map spec this map is following.
165 * `sources`: An array of URLs to the original source files.
167 * `names`: An array of identifiers which can be referrenced by individual
170 * `sourceRoot`: Optional. The URL root from which all sources are relative.
172 * `sourcesContent`: Optional. An array of contents of the original source files.
174 * `mappings`: A string of base64 VLQs which contain the actual mappings.
176 * `file`: Optional. The generated filename this source map is associated with.
178 #### SourceMapConsumer.prototype.computeColumnSpans()
180 Compute the last column for each generated mapping. The last column is
183 #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
185 Returns the original source, line, and column information for the generated
186 source's line and column positions provided. The only argument is an object with
187 the following properties:
189 * `line`: The line number in the generated source.
191 * `column`: The column number in the generated source.
193 and an object is returned with the following properties:
195 * `source`: The original source file, or null if this information is not
198 * `line`: The line number in the original source, or null if this information is
201 * `column`: The column number in the original source, or null or null if this
202 information is not available.
204 * `name`: The original identifier, or null if this information is not available.
206 #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
208 Returns the generated line and column information for the original source,
209 line, and column positions provided. The only argument is an object with
210 the following properties:
212 * `source`: The filename of the original source.
214 * `line`: The line number in the original source.
216 * `column`: The column number in the original source.
218 and an object is returned with the following properties:
220 * `line`: The line number in the generated source, or null.
222 * `column`: The column number in the generated source, or null.
224 #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
226 Returns all generated line and column information for the original source
227 and line provided. The only argument is an object with the following
230 * `source`: The filename of the original source.
232 * `line`: The line number in the original source.
234 and an array of objects is returned, each with the following properties:
236 * `line`: The line number in the generated source, or null.
238 * `column`: The column number in the generated source, or null.
240 #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
242 Returns the original source content for the source provided. The only
243 argument is the URL of the original source file.
245 If the source content for the given source is not found, then an error is
246 thrown. Optionally, pass `true` as the second param to have `null` returned
249 #### SourceMapConsumer.prototype.eachMapping(callback, context, order)
251 Iterate over each mapping between an original source/line/column and a
252 generated line/column in this source map.
254 * `callback`: The function that is called with each mapping. Mappings have the
255 form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
258 * `context`: Optional. If specified, this object will be the value of `this`
259 every time that `callback` is called.
261 * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
262 `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
263 the mappings sorted by the generated file's line/column order or the
264 original's source/line/column order, respectively. Defaults to
265 `SourceMapConsumer.GENERATED_ORDER`.
267 ### SourceMapGenerator
269 An instance of the SourceMapGenerator represents a source map which is being
272 #### new SourceMapGenerator([startOfSourceMap])
274 You may pass an object with the following properties:
276 * `file`: The filename of the generated source that this source map is
279 * `sourceRoot`: A root for all relative URLs in this source map.
281 * `skipValidation`: Optional. When `true`, disables validation of mappings as
282 they are added. This can improve performance but should be used with
283 discretion, as a last resort. Even then, one should avoid using this flag when
284 running tests, if possible.
286 #### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
288 Creates a new SourceMapGenerator based on a SourceMapConsumer
290 * `sourceMapConsumer` The SourceMap.
292 #### SourceMapGenerator.prototype.addMapping(mapping)
294 Add a single mapping from original source line and column to the generated
295 source's line and column for this source map being created. The mapping object
296 should have the following properties:
298 * `generated`: An object with the generated line and column positions.
300 * `original`: An object with the original line and column positions.
302 * `source`: The original source file (relative to the sourceRoot).
304 * `name`: An optional original token name for this mapping.
306 #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
308 Set the source content for an original source file.
310 * `sourceFile` the URL of the original source file.
312 * `sourceContent` the content of the source file.
314 #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
316 Applies a SourceMap for a source file to the SourceMap.
317 Each mapping to the supplied source file is rewritten using the
318 supplied SourceMap. Note: The resolution for the resulting mappings
319 is the minimium of this map and the supplied map.
321 * `sourceMapConsumer`: The SourceMap to be applied.
323 * `sourceFile`: Optional. The filename of the source file.
324 If omitted, sourceMapConsumer.file will be used, if it exists.
325 Otherwise an error will be thrown.
327 * `sourceMapPath`: Optional. The dirname of the path to the SourceMap
328 to be applied. If relative, it is relative to the SourceMap.
330 This parameter is needed when the two SourceMaps aren't in the same
331 directory, and the SourceMap to be applied contains relative source
332 paths. If so, those relative source paths need to be rewritten
333 relative to the SourceMap.
335 If omitted, it is assumed that both SourceMaps are in the same directory,
336 thus not needing any rewriting. (Supplying `'.'` has the same effect.)
338 #### SourceMapGenerator.prototype.toString()
340 Renders the source map being generated to a string.
344 SourceNodes provide a way to abstract over interpolating and/or concatenating
345 snippets of generated JavaScript source code, while maintaining the line and
346 column information associated between those snippets and the original source
347 code. This is useful as the final intermediate representation a compiler might
348 use before outputting the generated JS and source map.
350 #### new SourceNode([line, column, source[, chunk[, name]]])
352 * `line`: The original line number associated with this source node, or null if
353 it isn't associated with an original line.
355 * `column`: The original column number associated with this source node, or null
356 if it isn't associated with an original column.
358 * `source`: The original source's filename; null if no filename is provided.
360 * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
363 * `name`: Optional. The original identifier.
365 #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
367 Creates a SourceNode from generated code and a SourceMapConsumer.
369 * `code`: The generated code
371 * `sourceMapConsumer` The SourceMap for the generated code
373 * `relativePath` The optional path that relative sources in `sourceMapConsumer`
374 should be relative to.
376 #### SourceNode.prototype.add(chunk)
378 Add a chunk of generated JS to this source node.
380 * `chunk`: A string snippet of generated JS code, another instance of
381 `SourceNode`, or an array where each member is one of those things.
383 #### SourceNode.prototype.prepend(chunk)
385 Prepend a chunk of generated JS to this source node.
387 * `chunk`: A string snippet of generated JS code, another instance of
388 `SourceNode`, or an array where each member is one of those things.
390 #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
392 Set the source content for a source file. This will be added to the
393 `SourceMap` in the `sourcesContent` field.
395 * `sourceFile`: The filename of the source file
397 * `sourceContent`: The content of the source file
399 #### SourceNode.prototype.walk(fn)
401 Walk over the tree of JS snippets in this node and its children. The walking
402 function is called once for each snippet of JS and is passed that snippet and
403 the its original associated source's line/column location.
405 * `fn`: The traversal function.
407 #### SourceNode.prototype.walkSourceContents(fn)
409 Walk over the tree of SourceNodes. The walking function is called for each
410 source file content and is passed the filename and source content.
412 * `fn`: The traversal function.
414 #### SourceNode.prototype.join(sep)
416 Like `Array.prototype.join` except for SourceNodes. Inserts the separator
417 between each of this source node's children.
419 * `sep`: The separator.
421 #### SourceNode.prototype.replaceRight(pattern, replacement)
423 Call `String.prototype.replace` on the very right-most source snippet. Useful
424 for trimming whitespace from the end of a source node, etc.
426 * `pattern`: The pattern to replace.
428 * `replacement`: The thing to replace the pattern with.
430 #### SourceNode.prototype.toString()
432 Return the string representation of this source node. Walks over the tree and
433 concatenates all the various snippets together to one string.
435 #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
437 Returns the string representation of this tree of source nodes, plus a
438 SourceMapGenerator which contains all the mappings between the generated and
441 The arguments are the same as those to `new SourceMapGenerator`.
445 [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
447 Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.
449 To add new tests, create a new file named `test/test-<your new test name>.js`
450 and export your test functions with names that start with "test", for example
452 exports["test doing the foo bar"] = function (assert, util) {
456 The new test will be located automatically when you run the suite.
458 The `util` argument is the test utility module located at `test/source-map/util`.
460 The `assert` argument is a cut down version of node's assert module. You have
461 access to the following assertion functions:
473 (The reason for the restricted set of test functions is because we need the
474 tests to run inside Firefox's test suite as well and so the assert module is
475 shimmed in that environment. See `build/assert-shim.js`.)
477 [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
478 [feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap
479 [Dryice]: https://github.com/mozilla/dryice