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.

822 lines
26 KiB

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