You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

758 lines
25 KiB

2 years ago
  1. # Source Map JS
  2. [![NPM](https://nodei.co/npm/source-map-js.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map-js)
  3. Difference between original [source-map](https://github.com/mozilla/source-map):
  4. > TL,DR: it's fork of original source-map@0.6, but with perfomance optimizations.
  5. This journey starts from [source-map@0.7.0](https://github.com/mozilla/source-map/blob/master/CHANGELOG.md#070). Some part of it was rewritten to Rust and WASM and API became async.
  6. It's still a major block for many libraries like PostCSS or Sass for example because they need to migrate the whole API to the async way. This is the reason why 0.6.1 has 2x more downloads than 0.7.3 while it's faster several times.
  7. ![Downloads count](media/downloads.png)
  8. More important that WASM version has some optimizations in JS code too. This is why [community asked to create branch for 0.6 version](https://github.com/mozilla/source-map/issues/324) and port these optimizations but, sadly, the answer was «no». A bit later I discovered [the issue](https://github.com/mozilla/source-map/issues/370) created by [Ben Rothman (@benthemonkey)](https://github.com/benthemonkey) with no response at all.
  9. [Roman Dvornov (@lahmatiy)](https://github.com/lahmatiy) wrote a [serveral posts](https://t.me/gorshochekvarit/76) (russian, only, sorry) about source-map library in his own Telegram channel. He mentioned the article [«Maybe you don't need Rust and WASM to speed up your JS»](https://mrale.ph/blog/2018/02/03/maybe-you-dont-need-rust-to-speed-up-your-js.html) written by [Vyacheslav Egorov (@mraleph)](https://github.com/mraleph). This article contains optimizations and hacks that lead to almost the same performance compare to WASM implementation.
  10. I decided to fork the original source-map and port these optimizations from the article and several others PR from the original source-map.
  11. ---------
  12. This is a library to generate and consume the source map format
  13. [described here][format].
  14. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  15. ## Use with Node
  16. $ npm install source-map-js
  17. <!-- ## Use on the Web
  18. <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -->
  19. --------------------------------------------------------------------------------
  20. <!-- `npm run toc` to regenerate the Table of Contents -->
  21. <!-- START doctoc generated TOC please keep comment here to allow auto update -->
  22. <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
  23. ## Table of Contents
  24. - [Examples](#examples)
  25. - [Consuming a source map](#consuming-a-source-map)
  26. - [Generating a source map](#generating-a-source-map)
  27. - [With SourceNode (high level API)](#with-sourcenode-high-level-api)
  28. - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
  29. - [API](#api)
  30. - [SourceMapConsumer](#sourcemapconsumer)
  31. - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
  32. - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
  33. - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
  34. - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
  35. - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
  36. - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
  37. - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
  38. - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
  39. - [SourceMapGenerator](#sourcemapgenerator)
  40. - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
  41. - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
  42. - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
  43. - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
  44. - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
  45. - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
  46. - [SourceNode](#sourcenode)
  47. - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
  48. - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
  49. - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
  50. - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
  51. - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
  52. - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
  53. - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
  54. - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
  55. - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
  56. - [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
  57. - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
  58. <!-- END doctoc generated TOC please keep comment here to allow auto update -->
  59. ## Examples
  60. ### Consuming a source map
  61. ```js
  62. var rawSourceMap = {
  63. version: 3,
  64. file: 'min.js',
  65. names: ['bar', 'baz', 'n'],
  66. sources: ['one.js', 'two.js'],
  67. sourceRoot: 'http://example.com/www/js/',
  68. mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
  69. };
  70. var smc = new SourceMapConsumer(rawSourceMap);
  71. console.log(smc.sources);
  72. // [ 'http://example.com/www/js/one.js',
  73. // 'http://example.com/www/js/two.js' ]
  74. console.log(smc.originalPositionFor({
  75. line: 2,
  76. column: 28
  77. }));
  78. // { source: 'http://example.com/www/js/two.js',
  79. // line: 2,
  80. // column: 10,
  81. // name: 'n' }
  82. console.log(smc.generatedPositionFor({
  83. source: 'http://example.com/www/js/two.js',
  84. line: 2,
  85. column: 10
  86. }));
  87. // { line: 2, column: 28 }
  88. smc.eachMapping(function (m) {
  89. // ...
  90. });
  91. ```
  92. ### Generating a source map
  93. In depth guide:
  94. [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
  95. #### With SourceNode (high level API)
  96. ```js
  97. function compile(ast) {
  98. switch (ast.type) {
  99. case 'BinaryExpression':
  100. return new SourceNode(
  101. ast.location.line,
  102. ast.location.column,
  103. ast.location.source,
  104. [compile(ast.left), " + ", compile(ast.right)]
  105. );
  106. case 'Literal':
  107. return new SourceNode(
  108. ast.location.line,
  109. ast.location.column,
  110. ast.location.source,
  111. String(ast.value)
  112. );
  113. // ...
  114. default:
  115. throw new Error("Bad AST");
  116. }
  117. }
  118. var ast = parse("40 + 2", "add.js");
  119. console.log(compile(ast).toStringWithSourceMap({
  120. file: 'add.js'
  121. }));
  122. // { code: '40 + 2',
  123. // map: [object SourceMapGenerator] }
  124. ```
  125. #### With SourceMapGenerator (low level API)
  126. ```js
  127. var map = new SourceMapGenerator({
  128. file: "source-mapped.js"
  129. });
  130. map.addMapping({
  131. generated: {
  132. line: 10,
  133. column: 35
  134. },
  135. source: "foo.js",
  136. original: {
  137. line: 33,
  138. column: 2
  139. },
  140. name: "christopher"
  141. });
  142. console.log(map.toString());
  143. // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
  144. ```
  145. ## API
  146. Get a reference to the module:
  147. ```js
  148. // Node.js
  149. var sourceMap = require('source-map');
  150. // Browser builds
  151. var sourceMap = window.sourceMap;
  152. // Inside Firefox
  153. const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
  154. ```
  155. ### SourceMapConsumer
  156. A SourceMapConsumer instance represents a parsed source map which we can query
  157. for information about the original file positions by giving it a file position
  158. in the generated source.
  159. #### new SourceMapConsumer(rawSourceMap)
  160. The only parameter is the raw source map (either as a string which can be
  161. `JSON.parse`'d, or an object). According to the spec, source maps have the
  162. following attributes:
  163. * `version`: Which version of the source map spec this map is following.
  164. * `sources`: An array of URLs to the original source files.
  165. * `names`: An array of identifiers which can be referenced by individual
  166. mappings.
  167. * `sourceRoot`: Optional. The URL root from which all sources are relative.
  168. * `sourcesContent`: Optional. An array of contents of the original source files.
  169. * `mappings`: A string of base64 VLQs which contain the actual mappings.
  170. * `file`: Optional. The generated filename this source map is associated with.
  171. ```js
  172. var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
  173. ```
  174. #### SourceMapConsumer.prototype.computeColumnSpans()
  175. Compute the last column for each generated mapping. The last column is
  176. inclusive.
  177. ```js
  178. // Before:
  179. consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
  180. // [ { line: 2,
  181. // column: 1 },
  182. // { line: 2,
  183. // column: 10 },
  184. // { line: 2,
  185. // column: 20 } ]
  186. consumer.computeColumnSpans();
  187. // After:
  188. consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
  189. // [ { line: 2,
  190. // column: 1,
  191. // lastColumn: 9 },
  192. // { line: 2,
  193. // column: 10,
  194. // lastColumn: 19 },
  195. // { line: 2,
  196. // column: 20,
  197. // lastColumn: Infinity } ]
  198. ```
  199. #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
  200. Returns the original source, line, and column information for the generated
  201. source's line and column positions provided. The only argument is an object with
  202. the following properties:
  203. * `line`: The line number in the generated source. Line numbers in
  204. this library are 1-based (note that the underlying source map
  205. specification uses 0-based line numbers -- this library handles the
  206. translation).
  207. * `column`: The column number in the generated source. Column numbers
  208. in this library are 0-based.
  209. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
  210. `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
  211. element that is smaller than or greater than the one we are searching for,
  212. respectively, if the exact element cannot be found. Defaults to
  213. `SourceMapConsumer.GREATEST_LOWER_BOUND`.
  214. and an object is returned with the following properties:
  215. * `source`: The original source file, or null if this information is not
  216. available.
  217. * `line`: The line number in the original source, or null if this information is
  218. not available. The line number is 1-based.
  219. * `column`: The column number in the original source, or null if this
  220. information is not available. The column number is 0-based.
  221. * `name`: The original identifier, or null if this information is not available.
  222. ```js
  223. consumer.originalPositionFor({ line: 2, column: 10 })
  224. // { source: 'foo.coffee',
  225. // line: 2,
  226. // column: 2,
  227. // name: null }
  228. consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
  229. // { source: null,
  230. // line: null,
  231. // column: null,
  232. // name: null }
  233. ```
  234. #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
  235. Returns the generated line and column information for the original source,
  236. line, and column positions provided. The only argument is an object with
  237. the following properties:
  238. * `source`: The filename of the original source.
  239. * `line`: The line number in the original source. The line number is
  240. 1-based.
  241. * `column`: The column number in the original source. The column
  242. number is 0-based.
  243. and an object is returned with the following properties:
  244. * `line`: The line number in the generated source, or null. The line
  245. number is 1-based.
  246. * `column`: The column number in the generated source, or null. The
  247. column number is 0-based.
  248. ```js
  249. consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
  250. // { line: 1,
  251. // column: 56 }
  252. ```
  253. #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
  254. Returns all generated line and column information for the original source, line,
  255. and column provided. If no column is provided, returns all mappings
  256. corresponding to a either the line we are searching for or the next closest line
  257. that has any mappings. Otherwise, returns all mappings corresponding to the
  258. given line and either the column we are searching for or the next closest column
  259. that has any offsets.
  260. The only argument is an object with the following properties:
  261. * `source`: The filename of the original source.
  262. * `line`: The line number in the original source. The line number is
  263. 1-based.
  264. * `column`: Optional. The column number in the original source. The
  265. column number is 0-based.
  266. and an array of objects is returned, each with the following properties:
  267. * `line`: The line number in the generated source, or null. The line
  268. number is 1-based.
  269. * `column`: The column number in the generated source, or null. The
  270. column number is 0-based.
  271. ```js
  272. consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
  273. // [ { line: 2,
  274. // column: 1 },
  275. // { line: 2,
  276. // column: 10 },
  277. // { line: 2,
  278. // column: 20 } ]
  279. ```
  280. #### SourceMapConsumer.prototype.hasContentsOfAllSources()
  281. Return true if we have the embedded source content for every source listed in
  282. the source map, false otherwise.
  283. In other words, if this method returns `true`, then
  284. `consumer.sourceContentFor(s)` will succeed for every source `s` in
  285. `consumer.sources`.
  286. ```js
  287. // ...
  288. if (consumer.hasContentsOfAllSources()) {
  289. consumerReadyCallback(consumer);
  290. } else {
  291. fetchSources(consumer, consumerReadyCallback);
  292. }
  293. // ...
  294. ```
  295. #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
  296. Returns the original source content for the source provided. The only
  297. argument is the URL of the original source file.
  298. If the source content for the given source is not found, then an error is
  299. thrown. Optionally, pass `true` as the second param to have `null` returned
  300. instead.
  301. ```js
  302. consumer.sources
  303. // [ "my-cool-lib.clj" ]
  304. consumer.sourceContentFor("my-cool-lib.clj")
  305. // "..."
  306. consumer.sourceContentFor("this is not in the source map");
  307. // Error: "this is not in the source map" is not in the source map
  308. consumer.sourceContentFor("this is not in the source map", true);
  309. // null
  310. ```
  311. #### SourceMapConsumer.prototype.eachMapping(callback, context, order)
  312. Iterate over each mapping between an original source/line/column and a
  313. generated line/column in this source map.
  314. * `callback`: The function that is called with each mapping. Mappings have the
  315. form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
  316. name }`
  317. * `context`: Optional. If specified, this object will be the value of `this`
  318. every time that `callback` is called.
  319. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
  320. `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
  321. the mappings sorted by the generated file's line/column order or the
  322. original's source/line/column order, respectively. Defaults to
  323. `SourceMapConsumer.GENERATED_ORDER`.
  324. ```js
  325. consumer.eachMapping(function (m) { console.log(m); })
  326. // ...
  327. // { source: 'illmatic.js',
  328. // generatedLine: 1,
  329. // generatedColumn: 0,
  330. // originalLine: 1,
  331. // originalColumn: 0,
  332. // name: null }
  333. // { source: 'illmatic.js',
  334. // generatedLine: 2,
  335. // generatedColumn: 0,
  336. // originalLine: 2,
  337. // originalColumn: 0,
  338. // name: null }
  339. // ...
  340. ```
  341. ### SourceMapGenerator
  342. An instance of the SourceMapGenerator represents a source map which is being
  343. built incrementally.
  344. #### new SourceMapGenerator([startOfSourceMap])
  345. You may pass an object with the following properties:
  346. * `file`: The filename of the generated source that this source map is
  347. associated with.
  348. * `sourceRoot`: A root for all relative URLs in this source map.
  349. * `skipValidation`: Optional. When `true`, disables validation of mappings as
  350. they are added. This can improve performance but should be used with
  351. discretion, as a last resort. Even then, one should avoid using this flag when
  352. running tests, if possible.
  353. ```js
  354. var generator = new sourceMap.SourceMapGenerator({
  355. file: "my-generated-javascript-file.js",
  356. sourceRoot: "http://example.com/app/js/"
  357. });
  358. ```
  359. #### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
  360. Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
  361. * `sourceMapConsumer` The SourceMap.
  362. ```js
  363. var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
  364. ```
  365. #### SourceMapGenerator.prototype.addMapping(mapping)
  366. Add a single mapping from original source line and column to the generated
  367. source's line and column for this source map being created. The mapping object
  368. should have the following properties:
  369. * `generated`: An object with the generated line and column positions.
  370. * `original`: An object with the original line and column positions.
  371. * `source`: The original source file (relative to the sourceRoot).
  372. * `name`: An optional original token name for this mapping.
  373. ```js
  374. generator.addMapping({
  375. source: "module-one.scm",
  376. original: { line: 128, column: 0 },
  377. generated: { line: 3, column: 456 }
  378. })
  379. ```
  380. #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
  381. Set the source content for an original source file.
  382. * `sourceFile` the URL of the original source file.
  383. * `sourceContent` the content of the source file.
  384. ```js
  385. generator.setSourceContent("module-one.scm",
  386. fs.readFileSync("path/to/module-one.scm"))
  387. ```
  388. #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
  389. Applies a SourceMap for a source file to the SourceMap.
  390. Each mapping to the supplied source file is rewritten using the
  391. supplied SourceMap. Note: The resolution for the resulting mappings
  392. is the minimum of this map and the supplied map.
  393. * `sourceMapConsumer`: The SourceMap to be applied.
  394. * `sourceFile`: Optional. The filename of the source file.
  395. If omitted, sourceMapConsumer.file will be used, if it exists.
  396. Otherwise an error will be thrown.
  397. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap
  398. to be applied. If relative, it is relative to the SourceMap.
  399. This parameter is needed when the two SourceMaps aren't in the same
  400. directory, and the SourceMap to be applied contains relative source
  401. paths. If so, those relative source paths need to be rewritten
  402. relative to the SourceMap.
  403. If omitted, it is assumed that both SourceMaps are in the same directory,
  404. thus not needing any rewriting. (Supplying `'.'` has the same effect.)
  405. #### SourceMapGenerator.prototype.toString()
  406. Renders the source map being generated to a string.
  407. ```js
  408. generator.toString()
  409. // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
  410. ```
  411. ### SourceNode
  412. SourceNodes provide a way to abstract over interpolating and/or concatenating
  413. snippets of generated JavaScript source code, while maintaining the line and
  414. column information associated between those snippets and the original source
  415. code. This is useful as the final intermediate representation a compiler might
  416. use before outputting the generated JS and source map.
  417. #### new SourceNode([line, column, source[, chunk[, name]]])
  418. * `line`: The original line number associated with this source node, or null if
  419. it isn't associated with an original line. The line number is 1-based.
  420. * `column`: The original column number associated with this source node, or null
  421. if it isn't associated with an original column. The column number
  422. is 0-based.
  423. * `source`: The original source's filename; null if no filename is provided.
  424. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
  425. below.
  426. * `name`: Optional. The original identifier.
  427. ```js
  428. var node = new SourceNode(1, 2, "a.cpp", [
  429. new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
  430. new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
  431. new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
  432. ]);
  433. ```
  434. #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
  435. Creates a SourceNode from generated code and a SourceMapConsumer.
  436. * `code`: The generated code
  437. * `sourceMapConsumer` The SourceMap for the generated code
  438. * `relativePath` The optional path that relative sources in `sourceMapConsumer`
  439. should be relative to.
  440. ```js
  441. var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
  442. var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
  443. consumer);
  444. ```
  445. #### SourceNode.prototype.add(chunk)
  446. Add a chunk of generated JS to this source node.
  447. * `chunk`: A string snippet of generated JS code, another instance of
  448. `SourceNode`, or an array where each member is one of those things.
  449. ```js
  450. node.add(" + ");
  451. node.add(otherNode);
  452. node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
  453. ```
  454. #### SourceNode.prototype.prepend(chunk)
  455. Prepend a chunk of generated JS to this source node.
  456. * `chunk`: A string snippet of generated JS code, another instance of
  457. `SourceNode`, or an array where each member is one of those things.
  458. ```js
  459. node.prepend("/** Build Id: f783haef86324gf **/\n\n");
  460. ```
  461. #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
  462. Set the source content for a source file. This will be added to the
  463. `SourceMap` in the `sourcesContent` field.
  464. * `sourceFile`: The filename of the source file
  465. * `sourceContent`: The content of the source file
  466. ```js
  467. node.setSourceContent("module-one.scm",
  468. fs.readFileSync("path/to/module-one.scm"))
  469. ```
  470. #### SourceNode.prototype.walk(fn)
  471. Walk over the tree of JS snippets in this node and its children. The walking
  472. function is called once for each snippet of JS and is passed that snippet and
  473. the its original associated source's line/column location.
  474. * `fn`: The traversal function.
  475. ```js
  476. var node = new SourceNode(1, 2, "a.js", [
  477. new SourceNode(3, 4, "b.js", "uno"),
  478. "dos",
  479. [
  480. "tres",
  481. new SourceNode(5, 6, "c.js", "quatro")
  482. ]
  483. ]);
  484. node.walk(function (code, loc) { console.log("WALK:", code, loc); })
  485. // WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
  486. // WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
  487. // WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
  488. // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
  489. ```
  490. #### SourceNode.prototype.walkSourceContents(fn)
  491. Walk over the tree of SourceNodes. The walking function is called for each
  492. source file content and is passed the filename and source content.
  493. * `fn`: The traversal function.
  494. ```js
  495. var a = new SourceNode(1, 2, "a.js", "generated from a");
  496. a.setSourceContent("a.js", "original a");
  497. var b = new SourceNode(1, 2, "b.js", "generated from b");
  498. b.setSourceContent("b.js", "original b");
  499. var c = new SourceNode(1, 2, "c.js", "generated from c");
  500. c.setSourceContent("c.js", "original c");
  501. var node = new SourceNode(null, null, null, [a, b, c]);
  502. node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
  503. // WALK: a.js : original a
  504. // WALK: b.js : original b
  505. // WALK: c.js : original c
  506. ```
  507. #### SourceNode.prototype.join(sep)
  508. Like `Array.prototype.join` except for SourceNodes. Inserts the separator
  509. between each of this source node's children.
  510. * `sep`: The separator.
  511. ```js
  512. var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
  513. var operand = new SourceNode(3, 4, "a.rs", "=");
  514. var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
  515. var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
  516. var joinedNode = node.join(" ");
  517. ```
  518. #### SourceNode.prototype.replaceRight(pattern, replacement)
  519. Call `String.prototype.replace` on the very right-most source snippet. Useful
  520. for trimming white space from the end of a source node, etc.
  521. * `pattern`: The pattern to replace.
  522. * `replacement`: The thing to replace the pattern with.
  523. ```js
  524. // Trim trailing white space.
  525. node.replaceRight(/\s*$/, "");
  526. ```
  527. #### SourceNode.prototype.toString()
  528. Return the string representation of this source node. Walks over the tree and
  529. concatenates all the various snippets together to one string.
  530. ```js
  531. var node = new SourceNode(1, 2, "a.js", [
  532. new SourceNode(3, 4, "b.js", "uno"),
  533. "dos",
  534. [
  535. "tres",
  536. new SourceNode(5, 6, "c.js", "quatro")
  537. ]
  538. ]);
  539. node.toString()
  540. // 'unodostresquatro'
  541. ```
  542. #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
  543. Returns the string representation of this tree of source nodes, plus a
  544. SourceMapGenerator which contains all the mappings between the generated and
  545. original sources.
  546. The arguments are the same as those to `new SourceMapGenerator`.
  547. ```js
  548. var node = new SourceNode(1, 2, "a.js", [
  549. new SourceNode(3, 4, "b.js", "uno"),
  550. "dos",
  551. [
  552. "tres",
  553. new SourceNode(5, 6, "c.js", "quatro")
  554. ]
  555. ]);
  556. node.toStringWithSourceMap({ file: "my-output-file.js" })
  557. // { code: 'unodostresquatro',
  558. // map: [object SourceMapGenerator] }
  559. ```