From 7a263408de1b60e60b6220ca3e36d9b3e4aa047d Mon Sep 17 00:00:00 2001 From: Ger Hobbelt Date: Wed, 30 Oct 2019 00:42:36 +0100 Subject: [PATCH] add `prettier` task for standardized code formatting => easier cross-branch/fork code comparison and merging (#397) 1. add eslint prettier integration so that npm run lint catches issues 2. re-runs npm run lint on the project to catch issues prettier introduced 3. add npm run lint to the travis.yml --- .eslintrc.js | 129 ++-- .travis.yml | 9 +- CHANGELOG.md | 197 +++--- CODE_OF_CONDUCT.md | 5 +- CONTRIBUTING.md | 33 +- README.md | 295 ++++---- bench/bench-dom-bindings.js | 34 +- bench/bench.html | 80 +-- bench/bench.js | 117 ++-- lib/array-set.js | 4 +- lib/base64-vlq.js | 4 +- lib/base64.js | 4 +- lib/binary-search.js | 10 +- lib/mapping-list.js | 9 +- lib/read-wasm-browser.js | 13 +- lib/read-wasm.js | 4 +- lib/source-map-consumer.js | 264 +++++--- lib/source-map-generator.js | 96 ++- lib/source-node.js | 82 ++- lib/util.js | 35 +- lib/wasm.js | 91 ++- package.json | 6 +- source-map.d.ts | 574 ++++++++-------- test/run-tests.js | 21 +- test/test-api.js | 4 +- test/test-array-set.js | 12 +- test/test-base64-vlq.js | 2 +- test/test-binary-search.js | 74 +- test/test-dog-fooding.js | 442 +++++++++++- test/test-nested-consumer-usage.js | 26 +- test/test-source-map-consumer.js | 1004 +++++++++++++++++++++------- test/test-source-map-generator.js | 205 ++++-- test/test-source-node.js | 418 ++++++------ test/test-util.js | 173 +++-- test/util.js | 322 ++++----- 35 files changed, 3082 insertions(+), 1716 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index ce74b583..ecad6e9e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,21 +1,24 @@ "use strict"; module.exports = { - "env": { - "node": true, - "es6": true + env: { + node: true, + es6: true }, - "parserOptions": { - "ecmaVersion": 9 + plugins: ["prettier"], + extends: ["prettier"], + + parserOptions: { + ecmaVersion: 9 }, - "globals": { - "fetch": false, - "WebAssembly": false + globals: { + fetch: false, + WebAssembly: false }, - "rules": { + rules: { // Require spacing around => "arrow-spacing": "error", @@ -26,17 +29,17 @@ module.exports = { "block-spacing": "error", // No newline before open brace for a block - "brace-style": ["error", "1tbs", { "allowSingleLine": true }], + "brace-style": ["error", "1tbs", { allowSingleLine: true }], // No space before always a space after a comma - "comma-spacing": ["error", {"after": true, "before": false}], + "comma-spacing": ["error", { after: true, before: false }], // Commas at the end of the line not the start "comma-style": "error", // Warn about cyclomatic complexity in functions. // XXX Get this down to 20? - "complexity": ["error", 25], + complexity: ["error", 25], // Don't require spaces around computed properties "computed-property-spacing": ["error", "never"], @@ -45,7 +48,7 @@ module.exports = { "consistent-return": "error", // Require braces around blocks that start a new line - "curly": ["error", "multi-line"], + curly: ["error", "multi-line"], // Encourage the use of dot notation whenever possible. "dot-notation": "error", @@ -57,17 +60,20 @@ module.exports = { "func-call-spacing": "error", // Require function* name() - "generator-star-spacing": ["error", {"after": true, "before": false}], + "generator-star-spacing": ["error", { after: true, before: false }], // Two space indent // "indent": ["error", 2, { "SwitchCase": 1 }], // Space after colon not before in property declarations - "key-spacing": ["error", { - "afterColon": true, - "beforeColon": false, - "mode": "minimum" - }], + "key-spacing": [ + "error", + { + afterColon: true, + beforeColon: false, + mode: "minimum" + } + ], // Require spaces before and after keywords "keyword-spacing": "error", @@ -125,7 +131,7 @@ module.exports = { "no-else-return": "error", // No empty statements - "no-empty": ["error", {"allowEmptyCatch": true}], + "no-empty": ["error", { allowEmptyCatch: true }], // No empty character classes in regex "no-empty-character-class": "error", @@ -163,7 +169,7 @@ module.exports = { // Disallow the use of the __iterator__ property "no-iterator": "error", - // No labels + // No labels "no-labels": "error", // Disallow unnecessary nested blocks @@ -176,12 +182,17 @@ module.exports = { // "no-mixed-spaces-and-tabs": "error", // No unnecessary spacing - "no-multi-spaces": ["error", { exceptions: { - "ArrayExpression": true, - "AssignmentExpression": true, - "ObjectExpression": true, - "VariableDeclarator": true - } }], + "no-multi-spaces": [ + "error", + { + exceptions: { + ArrayExpression: true, + AssignmentExpression: true, + ObjectExpression: true, + VariableDeclarator: true + } + } + ], // No reassigning native JS objects "no-native-reassign": "error", @@ -250,10 +261,13 @@ module.exports = { "no-unsafe-negation": "error", // No declaring variables that are never used - "no-unused-vars": ["error", { - "args": "none", - "vars": "local" - }], + "no-unused-vars": [ + "error", + { + args: "none", + vars: "local" + } + ], // No using variables before defined "no-use-before-define": ["error", "nofunc"], @@ -278,48 +292,58 @@ module.exports = { "no-with": "error", // Require object-literal shorthand with ES6 method syntax - "object-shorthand": ["error", "always", { "avoidQuotes": true }], + "object-shorthand": ["error", "always", { avoidQuotes: true }], // Use const instead of let where possible "prefer-const": "error", // Require double-quotes everywhere, except where quotes are escaped // or template literals are used. - "quotes": ["error", "double", { - "allowTemplateLiterals": true, - "avoidEscape": true - }], + quotes: [ + "error", + "double", + { + allowTemplateLiterals: true, + avoidEscape: true + } + ], // No spacing inside rest or spread expressions "rest-spread-spacing": "error", // Always require semicolon at end of statement - "semi": ["error", "always"], + semi: ["error", "always"], // Require space before blocks "space-before-blocks": "error", // Never use spaces before function parentheses - "space-before-function-paren": ["error", { - "anonymous": "never", - "asyncArrow": "always", - "named": "never" - }], + "space-before-function-paren": [ + "error", + { + anonymous: "never", + asyncArrow: "always", + named: "never" + } + ], // No space padding in parentheses "space-in-parens": ["error", "never"], // Require spaces around operators - "space-infix-ops": ["error", { "int32Hint": true }], + "space-infix-ops": ["error", { int32Hint: true }], // ++ and -- should not need spacing - "space-unary-ops": ["error", { - "nonwords": false, - "overrides": { - "typeof": false // We tend to use typeof as a function call - }, - "words": true - }], + "space-unary-ops": [ + "error", + { + nonwords: false, + overrides: { + typeof: false // We tend to use typeof as a function call + }, + words: true + } + ], // Requires or disallows a whitespace (space or tab) beginning a comment "spaced-comment": "error", @@ -328,6 +352,9 @@ module.exports = { "use-isnan": "error", // Only check typeof against valid results - "valid-typeof": "error" + "valid-typeof": "error", + + "prettier/prettier": "error", + "max-len": ["error", { code: 120, ignoreUrls: true }] } }; diff --git a/.travis.yml b/.travis.yml index 0bc39f18..e354e457 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,14 +7,15 @@ node_js: - "9" install: -- npm install -- npm install coveralls + - npm install + - npm install coveralls script: -- npm run coverage + - npm run coverage + - npm run lint after_success: -- nyc report --reporter=text-lcov | coveralls + - nyc report --reporter=text-lcov | coveralls cache: directories: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c8b8061..35f97a9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,376 +4,375 @@ ### Breaking changes -* [#350](https://github.com/mozilla/source-map/pull/350) - +- [#350](https://github.com/mozilla/source-map/pull/350) - Change browser detection logic for WASM loading. -* [#363](https://github.com/mozilla/source-map/pull/363) - +- [#363](https://github.com/mozilla/source-map/pull/363) - Change WASM loading detection to rely on `package.json#browser` field. -* [#362](https://github.com/mozilla/source-map/pull/362) - +- [#362](https://github.com/mozilla/source-map/pull/362) - Remove the `dist/` bundle. -* [#371](https://github.com/mozilla/source-map/pull/371) - +- [#371](https://github.com/mozilla/source-map/pull/371) - Reimplement sourcemap URL processing using the WHATWG URL API. ### Nonbreaking changes: -* [#339](https://github.com/mozilla/source-map/pull/339) - +- [#339](https://github.com/mozilla/source-map/pull/339) - Allow initializing the consumer `mappings.wasm` file as an `ArrayBuffer`. ### Internal Improvements: -* [#347](https://github.com/mozilla/source-map/pull/347) - +- [#347](https://github.com/mozilla/source-map/pull/347) - Improve tests. -* [#352](https://github.com/mozilla/source-map/pull/352) - +- [#352](https://github.com/mozilla/source-map/pull/352) - Improve documentation. -* [#361](https://github.com/mozilla/source-map/pull/361) - +- [#361](https://github.com/mozilla/source-map/pull/361) - Use newer Webpack CLI when bundling. -* [#364](https://github.com/mozilla/source-map/pull/364) - +- [#364](https://github.com/mozilla/source-map/pull/364) - Convert `IndexedSourceMapConsumer` implementation to pass more through - to `BasicSourceMapConsumer`. -* [#366](https://github.com/mozilla/source-map/pull/366) - + to `BasicSourceMapConsumer`. +- [#366](https://github.com/mozilla/source-map/pull/366) - Normalize internal URL representation to be easier to follow. -* [#341](https://github.com/mozilla/source-map/pull/341) - +- [#341](https://github.com/mozilla/source-map/pull/341) - Use async functions to simplify `SourceMapConsumer.with` implementation. - ## 0.7.3 -* Fix a bug where nested uses of `SourceMapConsumer` could result in a +- Fix a bug where nested uses of `SourceMapConsumer` could result in a `TypeError`. [#338](https://github.com/mozilla/source-map/issues/338) [#330](https://github.com/mozilla/source-map/issues/330) [#319](https://github.com/mozilla/source-map/issues/319) ## 0.7.2 -* Another 3x speed up in `SourceMapConsumer`. Read about it here: +- Another 3x speed up in `SourceMapConsumer`. Read about it here: http://fitzgeraldnick.com/2018/02/26/speed-without-wizardry.html ## 0.7.1 -* Updated TypeScript typings. [#321][] +- Updated TypeScript typings. [#321][] [#321]: https://github.com/mozilla/source-map/pull/321 ## 0.7.0 -* `SourceMapConsumer` now uses WebAssembly, and is **much** faster! Read about +- `SourceMapConsumer` now uses WebAssembly, and is **much** faster! Read about it here: https://hacks.mozilla.org/2018/01/oxidizing-source-maps-with-rust-and-webassembly/ -* **Breaking change:** `new SourceMapConsumer` now returns a `Promise` object +- **Breaking change:** `new SourceMapConsumer` now returns a `Promise` object that resolves to the newly constructed `SourceMapConsumer` instance, rather than returning the new instance immediately. -* **Breaking change:** when you're done using a `SourceMapConsumer` instance, +- **Breaking change:** when you're done using a `SourceMapConsumer` instance, you must call `SourceMapConsumer.prototype.destroy` on it. After calling `destroy`, you must not use the instance again. -* **Breaking change:** `SourceMapConsumer` used to be able to handle lines, +- **Breaking change:** `SourceMapConsumer` used to be able to handle lines, columns numbers and source and name indices up to `2^53 - 1` (aka `Number.MAX_SAFE_INTEGER`). It can now only handle them up to `2^32 - 1`. -* **Breaking change:** The `source-map` library now uses modern ECMAScript-isms: +- **Breaking change:** The `source-map` library now uses modern ECMAScript-isms: `let`, arrow functions, `async`, etc. Use Babel to compile it down to ECMAScript 5 if you need to support older JavaScript environments. -* **Breaking change:** Drop support for Node < 8. If you want to support older -versions of node, please use v0.6 or below. +- **Breaking change:** Drop support for Node < 8. If you want to support older + versions of node, please use v0.6 or below. ## 0.5.6 -* Fix for regression when people were using numbers as names in source maps. See +- Fix for regression when people were using numbers as names in source maps. See #236. ## 0.5.5 -* Fix "regression" of unsupported, implementation behavior that half the world +- Fix "regression" of unsupported, implementation behavior that half the world happens to have come to depend on. See #235. -* Fix regression involving function hoisting in SpiderMonkey. See #233. +- Fix regression involving function hoisting in SpiderMonkey. See #233. ## 0.5.4 -* Large performance improvements to source-map serialization. See #228 and #229. +- Large performance improvements to source-map serialization. See #228 and #229. ## 0.5.3 -* Do not include unnecessary distribution files. See +- Do not include unnecessary distribution files. See commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. ## 0.5.2 -* Include browser distributions of the library in package.json's `files`. See +- Include browser distributions of the library in package.json's `files`. See issue #212. ## 0.5.1 -* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See +- Fix latent bugs in IndexedSourceMapConsumer.prototype.\_parseMappings. See ff05274becc9e6e1295ed60f3ea090d31d843379. ## 0.5.0 -* Node 0.8 is no longer supported. +- Node 0.8 is no longer supported. -* Use webpack instead of dryice for bundling. +- Use webpack instead of dryice for bundling. -* Big speedups serializing source maps. See pull request #203. +- Big speedups serializing source maps. See pull request #203. -* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that +- Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that explicitly start with the source root. See issue #199. ## 0.4.4 -* Fix an issue where using a `SourceMapGenerator` after having created a +- Fix an issue where using a `SourceMapGenerator` after having created a `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See issue #191. -* Fix an issue with where `SourceMapGenerator` would mistakenly consider +- Fix an issue with where `SourceMapGenerator` would mistakenly consider different mappings as duplicates of each other and avoid generating them. See issue #192. ## 0.4.3 -* A very large number of performance improvements, particularly when parsing +- A very large number of performance improvements, particularly when parsing source maps. Collectively about 75% of time shaved off of the source map parsing benchmark! -* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy +- Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy searching in the presence of a column option. See issue #177. -* Fix a bug with joining a source and its source root when the source is above +- Fix a bug with joining a source and its source root when the source is above the root. See issue #182. -* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to +- Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to determine when all sources' contents are inlined into the source map. See issue #190. ## 0.4.2 -* Add an `.npmignore` file so that the benchmarks aren't pulled down by +- Add an `.npmignore` file so that the benchmarks aren't pulled down by dependent projects. Issue #169. -* Add an optional `column` argument to +- Add an optional `column` argument to `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines with no mappings. Issues #172 and #173. ## 0.4.1 -* Fix accidentally defining a global variable. #170. +- Fix accidentally defining a global variable. #170. ## 0.4.0 -* The default direction for fuzzy searching was changed back to its original +- The default direction for fuzzy searching was changed back to its original direction. See #164. -* There is now a `bias` option you can supply to `SourceMapConsumer` to control +- There is now a `bias` option you can supply to `SourceMapConsumer` to control the fuzzy searching direction. See #167. -* About an 8% speed up in parsing source maps. See #159. +- About an 8% speed up in parsing source maps. See #159. -* Added a benchmark for parsing and generating source maps. +- Added a benchmark for parsing and generating source maps. ## 0.3.0 -* Change the default direction that searching for positions fuzzes when there is +- Change the default direction that searching for positions fuzzes when there is not an exact match. See #154. -* Support for environments using json2.js for JSON serialization. See #156. +- Support for environments using json2.js for JSON serialization. See #156. ## 0.2.0 -* Support for consuming "indexed" source maps which do not have any remote +- Support for consuming "indexed" source maps which do not have any remote sections. See pull request #127. This introduces a minor backwards incompatibility if you are monkey patching `SourceMapConsumer.prototype` methods. ## 0.1.43 -* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue +- Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue #148 for some discussion and issues #150, #151, and #152 for implementations. ## 0.1.42 -* Fix an issue where `SourceNode`s from different versions of the source-map +- Fix an issue where `SourceNode`s from different versions of the source-map library couldn't be used in conjunction with each other. See issue #142. ## 0.1.41 -* Fix a bug with getting the source content of relative sources with a "./" +- Fix a bug with getting the source content of relative sources with a "./" prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). -* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the +- Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the column span of each mapping. -* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find +- Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find all generated positions associated with a given original source and line. ## 0.1.40 -* Performance improvements for parsing source maps in SourceMapConsumer. +- Performance improvements for parsing source maps in SourceMapConsumer. ## 0.1.39 -* Fix a bug where setting a source's contents to null before any source content +- Fix a bug where setting a source's contents to null before any source content had been set before threw a TypeError. See issue #131. ## 0.1.38 -* Fix a bug where finding relative paths from an empty path were creating +- Fix a bug where finding relative paths from an empty path were creating absolute paths. See issue #129. ## 0.1.37 -* Fix a bug where if the source root was an empty string, relative source paths +- Fix a bug where if the source root was an empty string, relative source paths would turn into absolute source paths. Issue #124. ## 0.1.36 -* Allow the `names` mapping property to be an empty string. Issue #121. +- Allow the `names` mapping property to be an empty string. Issue #121. ## 0.1.35 -* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` +- A third optional parameter was added to `SourceNode.fromStringWithSourceMap` to specify a path that relative sources in the second parameter should be relative to. Issue #105. -* If no file property is given to a `SourceMapGenerator`, then the resulting +- If no file property is given to a `SourceMapGenerator`, then the resulting source map will no longer have a `null` file property. The property will simply not exist. Issue #104. -* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. +- Fixed a bug where consecutive newlines were ignored in `SourceNode`s. Issue #116. ## 0.1.34 -* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. +- Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. -* Fix bug involving source contents and the +- Fix bug involving source contents and the `SourceMapGenerator.prototype.applySourceMap`. Issue #100. ## 0.1.33 -* Fix some edge cases surrounding path joining and URL resolution. +- Fix some edge cases surrounding path joining and URL resolution. -* Add a third parameter for relative path to +- Add a third parameter for relative path to `SourceMapGenerator.prototype.applySourceMap`. -* Fix issues with mappings and EOLs. +- Fix issues with mappings and EOLs. ## 0.1.32 -* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns +- Fixed a bug where SourceMapConsumer couldn't handle negative relative columns (issue 92). -* Fixed test runner to actually report number of failed tests as its process +- Fixed test runner to actually report number of failed tests as its process exit code. -* Fixed a typo when reporting bad mappings (issue 87). +- Fixed a typo when reporting bad mappings (issue 87). ## 0.1.31 -* Delay parsing the mappings in SourceMapConsumer until queried for a source +- Delay parsing the mappings in SourceMapConsumer until queried for a source location. -* Support Sass source maps (which at the time of writing deviate from the spec +- Support Sass source maps (which at the time of writing deviate from the spec in small ways) in SourceMapConsumer. ## 0.1.30 -* Do not join source root with a source, when the source is a data URI. +- Do not join source root with a source, when the source is a data URI. -* Extend the test runner to allow running single specific test files at a time. +- Extend the test runner to allow running single specific test files at a time. -* Performance improvements in `SourceNode.prototype.walk` and +- Performance improvements in `SourceNode.prototype.walk` and `SourceMapConsumer.prototype.eachMapping`. -* Source map browser builds will now work inside Workers. +- Source map browser builds will now work inside Workers. -* Better error messages when attempting to add an invalid mapping to a +- Better error messages when attempting to add an invalid mapping to a `SourceMapGenerator`. ## 0.1.29 -* Allow duplicate entries in the `names` and `sources` arrays of source maps +- Allow duplicate entries in the `names` and `sources` arrays of source maps (usually from TypeScript) we are parsing. Fixes github issue 72. ## 0.1.28 -* Skip duplicate mappings when creating source maps from SourceNode; github +- Skip duplicate mappings when creating source maps from SourceNode; github issue 75. ## 0.1.27 -* Don't throw an error when the `file` property is missing in SourceMapConsumer, +- Don't throw an error when the `file` property is missing in SourceMapConsumer, we don't use it anyway. ## 0.1.26 -* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. +- Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. ## 0.1.25 -* Make compatible with browserify +- Make compatible with browserify ## 0.1.24 -* Fix issue with absolute paths and `file://` URIs. See +- Fix issue with absolute paths and `file://` URIs. See https://bugzilla.mozilla.org/show_bug.cgi?id=885597 ## 0.1.23 -* Fix issue with absolute paths and sourcesContent, github issue 64. +- Fix issue with absolute paths and sourcesContent, github issue 64. ## 0.1.22 -* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. +- Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. ## 0.1.21 -* Fixed handling of sources that start with a slash so that they are relative to +- Fixed handling of sources that start with a slash so that they are relative to the source root's host. ## 0.1.20 -* Fixed github issue #43: absolute URLs aren't joined with the source root +- Fixed github issue #43: absolute URLs aren't joined with the source root anymore. ## 0.1.19 -* Using Travis CI to run tests. +- Using Travis CI to run tests. ## 0.1.18 -* Fixed a bug in the handling of sourceRoot. +- Fixed a bug in the handling of sourceRoot. ## 0.1.17 -* Added SourceNode.fromStringWithSourceMap. +- Added SourceNode.fromStringWithSourceMap. ## 0.1.16 -* Added missing documentation. +- Added missing documentation. -* Fixed the generating of empty mappings in SourceNode. +- Fixed the generating of empty mappings in SourceNode. ## 0.1.15 -* Added SourceMapGenerator.applySourceMap. +- Added SourceMapGenerator.applySourceMap. ## 0.1.14 -* The sourceRoot is now handled consistently. +- The sourceRoot is now handled consistently. ## 0.1.13 -* Added SourceMapGenerator.fromSourceMap. +- Added SourceMapGenerator.fromSourceMap. ## 0.1.12 -* SourceNode now generates empty mappings too. +- SourceNode now generates empty mappings too. ## 0.1.11 -* Added name support to SourceNode. +- Added name support to SourceNode. ## 0.1.10 -* Added sourcesContent support to the customer and generator. +- Added sourcesContent support to the customer and generator. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 498baa3f..0d424fd8 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,10 +1,11 @@ # Community Participation Guidelines -This repository is governed by Mozilla's code of conduct and etiquette guidelines. +This repository is governed by Mozilla's code of conduct and etiquette guidelines. For more details, please read the -[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). +[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). ## How to Report + For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. + ## Table of Contents - [Filing Issues](#filing-issues) @@ -21,21 +22,19 @@ very appreciated. - - ## Filing Issues If you are filing an issue for a bug or other misbehavior, please provide: -* **A test case.** The more minimal the better, but sometimes a larger test case +- **A test case.** The more minimal the better, but sometimes a larger test case cannot be helped. This should be in the form of a gist, node script, repository, etc. -* **Steps to reproduce the bug.** The more exact and specific the better. +- **Steps to reproduce the bug.** The more exact and specific the better. -* **The result you expected.** +- **The result you expected.** -* **The actual result.** +- **The actual result.** ## Building From Source @@ -51,7 +50,7 @@ Next, run This will create the following files: -* `dist/source-map.js` - The plain browser build. +- `dist/source-map.js` - The plain browser build. ## Submitting Pull Requests @@ -93,15 +92,15 @@ suite. The `assert` argument is a cut down version of node's assert module. You have access to the following assertion functions: -* `doesNotThrow` +- `doesNotThrow` -* `equal` +- `equal` -* `ok` +- `ok` -* `strictEqual` +- `strictEqual` -* `throws` +- `throws` (The reason for the restricted set of test functions is because we need the tests to run inside Firefox's test suite as well and Firefox has a shimmed @@ -111,7 +110,7 @@ There are additional test utilities and helpers in `./test/util.js` which you can use as well: ```js -var util = require('./util'); +var util = require("./util"); ``` ## Checking code coverage @@ -125,17 +124,17 @@ $ open coverage/index.html ``` This will allow you to browse to red sections of the code that need -more attention. Even more cool, however, is to run: +more attention. Even more cool, however, is to run: ```shell $ npm run dev ``` -(On some operating systems, this may pop up a request for node to be able to open a socket. Click "Allow" or the equivalent.) +(On some operating systems, this may pop up a request for node to be able to open a socket. Click "Allow" or the equivalent.) This will run the coverage tools, and monitor all of the files in the project, re-running the coverage tools and refreshing the browser when -any files change. There will be a small web server running on port 4103 to enable this. Control-C to stop. +any files change. There will be a small web server running on port 4103 to enable this. Control-C to stop. ## Updating the `lib/mappings.wasm` WebAssembly Module diff --git a/README.md b/README.md index 435467b0..81a7d240 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,13 @@ This is a library to generate and consume the source map format }); --------------------------------------------------------------------------------- +--- + ## Table of Contents - [Examples](#examples) @@ -79,36 +80,39 @@ This is a library to generate and consume the source map format ```js const rawSourceMap = { version: 3, - file: 'min.js', - names: ['bar', 'baz', 'n'], - sources: ['one.js', 'two.js'], - sourceRoot: 'http://example.com/www/js/', - mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' + file: "min.js", + names: ["bar", "baz", "n"], + sources: ["one.js", "two.js"], + sourceRoot: "http://example.com/www/js/", + mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => { - console.log(consumer.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] - console.log(consumer.originalPositionFor({ - line: 2, - column: 28 - })); + console.log( + consumer.originalPositionFor({ + line: 2, + column: 28 + }) + ); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } - console.log(consumer.generatedPositionFor({ - source: 'http://example.com/www/js/two.js', - line: 2, - column: 10 - })); + console.log( + consumer.generatedPositionFor({ + source: "http://example.com/www/js/two.js", + line: 2, + column: 10 + }) + ); // { line: 2, column: 28 } - consumer.eachMapping(function (m) { + consumer.eachMapping(function(m) { // ... }); @@ -126,30 +130,26 @@ In depth guide: ```js function compile(ast) { switch (ast.type) { - case 'BinaryExpression': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - [compile(ast.left), " + ", compile(ast.right)] - ); - case 'Literal': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - String(ast.value) - ); - // ... - default: - throw new Error("Bad AST"); + case "BinaryExpression": + return new SourceNode(ast.location.line, ast.location.column, ast.location.source, [ + compile(ast.left), + " + ", + compile(ast.right) + ]); + case "Literal": + return new SourceNode(ast.location.line, ast.location.column, ast.location.source, String(ast.value)); + // ... + default: + throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); -console.log(compile(ast).toStringWithSourceMap({ - file: 'add.js' -})); +console.log( + compile(ast).toStringWithSourceMap({ + file: "add.js" + }) +); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` @@ -184,7 +184,7 @@ Get a reference to the module: ```js // Node.js -var sourceMap = require('source-map'); +var sourceMap = require("source-map"); // Browser builds var sourceMap = window.sourceMap; @@ -207,7 +207,7 @@ calling `initialize` before constructing any `SourceMapConsumer`s. The options object has the following properties: -* `"lib/mappings.wasm"`: A `String` containing the URL of the +- `"lib/mappings.wasm"`: A `String` containing the URL of the `lib/mappings.wasm` file, or an `ArrayBuffer` with the contents of `lib/mappings.wasm`. ```js @@ -222,20 +222,20 @@ The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: -* `version`: Which version of the source map spec this map is following. +- `version`: Which version of the source map spec this map is following. -* `sources`: An array of URLs to the original source files. +- `sources`: An array of URLs to the original source files. -* `names`: An array of identifiers which can be referenced by individual +- `names`: An array of identifiers which can be referenced by individual mappings. -* `sourceRoot`: Optional. The URL root from which all sources are relative. +- `sourceRoot`: Optional. The URL root from which all sources are relative. -* `sourcesContent`: Optional. An array of contents of the original source files. +- `sourcesContent`: Optional. An array of contents of the original source files. -* `mappings`: A string of base64 VLQs which contain the actual mappings. +- `mappings`: A string of base64 VLQs which contain the actual mappings. -* `file`: Optional. The generated filename this source map is associated with. +- `file`: Optional. The generated filename this source map is associated with. The promise of the constructed souce map consumer is returned. @@ -254,8 +254,7 @@ to call `destroy`. #### SourceMapConsumer.with Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` -(see the `SourceMapConsumer` constructor for details. Then, invoke the `async -function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait +(see the `SourceMapConsumer` constructor for details. Then, invoke the `async function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait for `f` to complete, call `destroy` on the consumer, and return `f`'s return value. @@ -265,17 +264,13 @@ By using `with`, you do not have to remember to manually call `destroy` on the consumer, since it will be called automatically once `f` completes. ```js -const xSquared = await SourceMapConsumer.with( - myRawSourceMap, - null, - async function (consumer) { - // Use `consumer` inside here and don't worry about remembering - // to call `destroy`. - - const x = await whatever(consumer); - return x * x; - } -); +const xSquared = await SourceMapConsumer.with(myRawSourceMap, null, async function(consumer) { + // Use `consumer` inside here and don't worry about remembering + // to call `destroy`. + + const x = await whatever(consumer); + return x * x; +}); // You may not use that `consumer` anymore out here; it has // been destroyed. But you can use `xSquared`. @@ -300,7 +295,7 @@ inclusive. ```js // Before: -consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); // [ { line: 2, // column: 1 }, // { line: 2, @@ -311,7 +306,7 @@ consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) consumer.computeColumnSpans(); // After: -consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); // [ { line: 2, // column: 1, // lastColumn: 9 }, @@ -329,41 +324,44 @@ Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: -* `line`: The line number in the generated source. Line numbers in +- `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). -* `column`: The column number in the generated source. Column numbers +- `column`: The column number in the generated source. Column numbers in this library are 0-based. -* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or +- `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, - respectively, if the exact element cannot be found. Defaults to + respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: -* `source`: The original source file, or null if this information is not +- `source`: The original source file, or null if this information is not available. -* `line`: The line number in the original source, or null if this information is - not available. The line number is 1-based. +- `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. -* `column`: The column number in the original source, or null if this - information is not available. The column number is 0-based. +- `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. -* `name`: The original identifier, or null if this information is not available. +- `name`: The original identifier, or null if this information is not available. ```js -consumer.originalPositionFor({ line: 2, column: 10 }) +consumer.originalPositionFor({ line: 2, column: 10 }); // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } -consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +consumer.originalPositionFor({ + line: 99999999999999999, + column: 999999999999999 +}); // { source: null, // line: null, // column: null, @@ -376,24 +374,24 @@ Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: -* `source`: The filename of the original source. +- `source`: The filename of the original source. -* `line`: The line number in the original source. The line number is +- `line`: The line number in the original source. The line number is 1-based. -* `column`: The column number in the original source. The column +- `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: -* `line`: The line number in the generated source, or null. The line +- `line`: The line number in the generated source, or null. The line number is 1-based. -* `column`: The column number in the generated source, or null. The +- `column`: The column number in the generated source, or null. The column number is 0-based. ```js -consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }); // { line: 1, // column: 56 } ``` @@ -409,24 +407,24 @@ that has any offsets. The only argument is an object with the following properties: -* `source`: The filename of the original source. +- `source`: The filename of the original source. -* `line`: The line number in the original source. The line number is +- `line`: The line number in the original source. The line number is 1-based. -* `column`: Optional. The column number in the original source. The +- `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: -* `line`: The line number in the generated source, or null. The line +- `line`: The line number in the generated source, or null. The line number is 1-based. -* `column`: The column number in the generated source, or null. The +- `column`: The column number in the generated source, or null. The column number is 0-based. ```js -consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }); // [ { line: 2, // column: 1 }, // { line: 2, @@ -464,10 +462,10 @@ thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js -consumer.sources +consumer.sources; // [ "my-cool-lib.clj" ] -consumer.sourceContentFor("my-cool-lib.clj") +consumer.sourceContentFor("my-cool-lib.clj"); // "..." consumer.sourceContentFor("this is not in the source map"); @@ -482,21 +480,22 @@ consumer.sourceContentFor("this is not in the source map", true); Iterate over each mapping between an original source/line/column and a generated line/column in this source map. -* `callback`: The function that is called with each mapping. Mappings have the - form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, - name }` +- `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` -* `context`: Optional. If specified, this object will be the value of `this` +- `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. -* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or +- `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js -consumer.eachMapping(function (m) { console.log(m); }) +consumer.eachMapping(function(m) { + console.log(m); +}); // ... // { source: 'illmatic.js', // generatedLine: 1, @@ -512,6 +511,7 @@ consumer.eachMapping(function (m) { console.log(m); }) // name: null } // ... ``` + ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being @@ -521,12 +521,12 @@ built incrementally. You may pass an object with the following properties: -* `file`: The filename of the generated source that this source map is +- `file`: The filename of the generated source that this source map is associated with. -* `sourceRoot`: A root for all relative URLs in this source map. +- `sourceRoot`: A root for all relative URLs in this source map. -* `skipValidation`: Optional. When `true`, disables validation of mappings as +- `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. @@ -542,7 +542,7 @@ var generator = new sourceMap.SourceMapGenerator({ Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. -* `sourceMapConsumer` The SourceMap. +- `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); @@ -554,33 +554,32 @@ Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: -* `generated`: An object with the generated line and column positions. +- `generated`: An object with the generated line and column positions. -* `original`: An object with the original line and column positions. +- `original`: An object with the original line and column positions. -* `source`: The original source file (relative to the sourceRoot). +- `source`: The original source file (relative to the sourceRoot). -* `name`: An optional original token name for this mapping. +- `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } -}) +}); ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. -* `sourceFile` the URL of the original source file. +- `sourceFile` the URL of the original source file. -* `sourceContent` the content of the source file. +- `sourceContent` the content of the source file. ```js -generator.setSourceContent("module-one.scm", - fs.readFileSync("path/to/module-one.scm")) +generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")); ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) @@ -590,13 +589,13 @@ Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. -* `sourceMapConsumer`: The SourceMap to be applied. +- `sourceMapConsumer`: The SourceMap to be applied. -* `sourceFile`: Optional. The filename of the source file. +- `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. -* `sourceMapPath`: Optional. The dirname of the path to the SourceMap +- `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same @@ -612,7 +611,7 @@ is the minimum of this map and the supplied map. Renders the source map being generated to a string. ```js -generator.toString() +generator.toString(); // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` @@ -626,25 +625,25 @@ use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) -* `line`: The original line number associated with this source node, or null if - it isn't associated with an original line. The line number is 1-based. +- `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. -* `column`: The original column number associated with this source node, or null - if it isn't associated with an original column. The column number +- `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number is 0-based. -* `source`: The original source's filename; null if no filename is provided. +- `source`: The original source's filename; null if no filename is provided. -* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see +- `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. -* `name`: Optional. The original identifier. +- `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), - new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n") ]); ``` @@ -652,11 +651,11 @@ var node = new SourceNode(1, 2, "a.cpp", [ Creates a SourceNode from generated code and a SourceMapConsumer. -* `code`: The generated code +- `code`: The generated code -* `sourceMapConsumer` The SourceMap for the generated code +- `sourceMapConsumer` The SourceMap for the generated code -* `relativePath` The optional path that relative sources in `sourceMapConsumer` +- `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js @@ -668,8 +667,8 @@ const node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file Add a chunk of generated JS to this source node. -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. +- `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); @@ -681,8 +680,8 @@ node.add([leftHandOperandNode, " + ", rightHandOperandNode]); Prepend a chunk of generated JS to this source node. -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. +- `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); @@ -693,13 +692,12 @@ node.prepend("/** Build Id: f783haef86324gf **/\n\n"); Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. -* `sourceFile`: The filename of the source file +- `sourceFile`: The filename of the source file -* `sourceContent`: The content of the source file +- `sourceContent`: The content of the source file ```js -node.setSourceContent("module-one.scm", - fs.readFileSync("path/to/module-one.scm")) +node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")); ``` #### SourceNode.prototype.walk(fn) @@ -708,19 +706,18 @@ Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. -* `fn`: The traversal function. +- `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] + ["tres", new SourceNode(5, 6, "c.js", "quatro")] ]); -node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +node.walk(function(code, loc) { + console.log("WALK:", code, loc); +}); // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } @@ -732,7 +729,7 @@ node.walk(function (code, loc) { console.log("WALK:", code, loc); }) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. -* `fn`: The traversal function. +- `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); @@ -743,7 +740,9 @@ var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); -node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +node.walkSourceContents(function(source, contents) { + console.log("WALK:", source, ":", contents); +}); // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c @@ -754,14 +753,14 @@ node.walkSourceContents(function (source, contents) { console.log("WALK:", sourc Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. -* `sep`: The separator. +- `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); -var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var node = new SourceNode(null, null, null, [lhs, operand, rhs]); var joinedNode = node.join(" "); ``` @@ -770,9 +769,9 @@ var joinedNode = node.join(" "); Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. -* `pattern`: The pattern to replace. +- `pattern`: The pattern to replace. -* `replacement`: The thing to replace the pattern with. +- `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. @@ -788,13 +787,10 @@ concatenates all the various snippets together to one string. var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] + ["tres", new SourceNode(5, 6, "c.js", "quatro")] ]); -node.toString() +node.toString(); // 'unodostresquatro' ``` @@ -810,13 +806,10 @@ The arguments are the same as those to `new SourceMapGenerator`. var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] + ["tres", new SourceNode(5, 6, "c.js", "quatro")] ]); -node.toStringWithSourceMap({ file: "my-output-file.js" }) +node.toStringWithSourceMap({ file: "my-output-file.js" }); // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` diff --git a/bench/bench-dom-bindings.js b/bench/bench-dom-bindings.js index b4650a42..fe321eb5 100644 --- a/bench/bench-dom-bindings.js +++ b/bench/bench-dom-bindings.js @@ -1,5 +1,5 @@ sourceMap.SourceMapConsumer.initialize({ - "lib/mappings.wasm": "../lib/mappings.wasm?bust_cache=" + String(Math.random()).replace(/0\./, ""), + "lib/mappings.wasm": "../lib/mappings.wasm?bust_cache=" + String(Math.random()).replace(/0\./, "") }); function bindRange(labelId, updater) { @@ -68,28 +68,28 @@ const updateImplAndBrowser = () => { implAndBrowserInput.addEventListener("input", updateImplAndBrowser); updateImplAndBrowser(); - // Run a benchmark when the given button is clicked and display results in the // given element. function benchOnClick(button, results, benchName, bencher) { - button.addEventListener("click", async function (e) { - e.preventDefault(); + button.addEventListener( + "click", + async function(e) { + e.preventDefault(); - const buttons = [...document.querySelectorAll("button")]; - buttons.forEach(b => b.setAttribute("disabled", true)); - results.innerHTML = ""; - await new Promise(r => requestAnimationFrame(r)); + const buttons = [...document.querySelectorAll("button")]; + buttons.forEach(b => b.setAttribute("disabled", true)); + results.innerHTML = ""; + await new Promise(r => requestAnimationFrame(r)); - var stats = await bencher(); + var stats = await bencher(); - buttons.forEach(b => b.removeAttribute("disabled")); + buttons.forEach(b => b.removeAttribute("disabled")); - const csv = stats - .xs - .map(x => `"${implAndBrowser}",${testSourceMap.mappings.length},"${benchName}",${x}`) - .join("\n"); + const csv = stats.xs + .map(x => `"${implAndBrowser}",${testSourceMap.mappings.length},"${benchName}",${x}`) + .join("\n"); - results.innerHTML = ` + results.innerHTML = ` @@ -110,7 +110,9 @@ function benchOnClick(button, results, benchName, bencher) {
${csv}
`; - }, false); + }, + false + ); } for (let bench of Object.keys(benchmarks)) { diff --git a/bench/bench.html b/bench/bench.html index 0edbeff5..6445ab52 100644 --- a/bench/bench.html +++ b/bench/bench.html @@ -24,46 +24,46 @@

Benchmark mozilla/source-map

-

- -

-

- -

-

- -

-

- -

-

- -

+

+ +

+

+ +

+

+ +

+

+ +

+

+ +

diff --git a/bench/bench.js b/bench/bench.js index 82804f91..c896de4d 100644 --- a/bench/bench.js +++ b/bench/bench.js @@ -15,13 +15,13 @@ if (!console.profile) { var __benchmarkResults = []; var benchmarkBlackbox = [].push.bind(__benchmarkResults); -const now = typeof window === "object" && window.performance && window.performance.now - ? () => window.performance.now() - : () => now(); +const now = + typeof window === "object" && window.performance && window.performance.now + ? () => window.performance.now() + : () => now(); -const yieldForTick = typeof setTimeout === "function" - ? () => new Promise(resolve => setTimeout(resolve, 1)) - : () => Promise.resolve(); +const yieldForTick = + typeof setTimeout === "function" ? () => new Promise(resolve => setTimeout(resolve, 1)) : () => Promise.resolve(); // Benchmark running an action n times. async function benchmark(setup, action, tearDown = () => {}) { @@ -70,7 +70,7 @@ var benchmarks = { "SourceMapGenerator#toString": () => { let smg; return benchmark( - async function () { + async function() { var smc = await new sourceMap.SourceMapConsumer(testSourceMap); smg = sourceMap.SourceMapGenerator.fromSourceMap(smc); smc.destroy(); @@ -84,16 +84,18 @@ var benchmarks = { "set.first.breakpoint": () => { let testMapping; return benchmark( - async function () { + async function() { testMapping = await getTestMapping(); }, - async function () { + async function() { let smc = await new sourceMap.SourceMapConsumer(testSourceMap); - benchmarkBlackbox(smc.allGeneratedPositionsFor({ - source: testMapping.source, - line: testMapping.originalLine, - }).length); + benchmarkBlackbox( + smc.allGeneratedPositionsFor({ + source: testMapping.source, + line: testMapping.originalLine + }).length + ); smc.destroy(); } @@ -103,16 +105,18 @@ var benchmarks = { "first.pause.at.exception": () => { let testMapping; return benchmark( - async function () { + async function() { testMapping = await getTestMapping(); }, - async function () { + async function() { let smc = await new sourceMap.SourceMapConsumer(testSourceMap); - benchmarkBlackbox(smc.originalPositionFor({ - line: testMapping.generatedLine, - column: testMapping.generatedColumn, - })); + benchmarkBlackbox( + smc.originalPositionFor({ + line: testMapping.generatedLine, + column: testMapping.generatedColumn + }) + ); smc.destroy(); } @@ -123,71 +127,72 @@ var benchmarks = { let testMapping; let smc; return benchmark( - async function () { + async function() { testMapping = await getTestMapping(); smc = await new sourceMap.SourceMapConsumer(testSourceMap); }, - async function () { - benchmarkBlackbox(smc.allGeneratedPositionsFor({ - source: testMapping.source, - line: testMapping.originalLine, - })); + async function() { + benchmarkBlackbox( + smc.allGeneratedPositionsFor({ + source: testMapping.source, + line: testMapping.originalLine + }) + ); }, - function () { + function() { smc.destroy(); } - ) + ); }, "subsequent.pausing.at.exceptions": () => { let testMapping; let smc; return benchmark( - async function () { + async function() { testMapping = await getTestMapping(); smc = await new sourceMap.SourceMapConsumer(testSourceMap); }, - async function () { - benchmarkBlackbox(smc.originalPositionFor({ - line: testMapping.generatedLine, - column: testMapping.generatedColumn, - })); + async function() { + benchmarkBlackbox( + smc.originalPositionFor({ + line: testMapping.generatedLine, + column: testMapping.generatedColumn + }) + ); }, - function () { + function() { smc.destroy(); } ); }, "parse.and.iterate": () => { - return benchmark( - noop, - async function () { - const smc = await new sourceMap.SourceMapConsumer(testSourceMap); - - let maxLine = 0; - let maxCol = 0; - smc.eachMapping(m => { - maxLine = Math.max(maxLine, m.generatedLine); - maxLine = Math.max(maxLine, m.originalLine); - maxCol = Math.max(maxCol, m.generatedColumn); - maxCol = Math.max(maxCol, m.originalColumn); - }); - benchmarkBlackbox(maxLine); - benchmarkBlackbox(maxCol); - - smc.destroy(); - } - ); + return benchmark(noop, async function() { + const smc = await new sourceMap.SourceMapConsumer(testSourceMap); + + let maxLine = 0; + let maxCol = 0; + smc.eachMapping(m => { + maxLine = Math.max(maxLine, m.generatedLine); + maxLine = Math.max(maxLine, m.originalLine); + maxCol = Math.max(maxCol, m.generatedColumn); + maxCol = Math.max(maxCol, m.originalColumn); + }); + benchmarkBlackbox(maxLine); + benchmarkBlackbox(maxCol); + + smc.destroy(); + }); }, "iterate.already.parsed": () => { let smc; return benchmark( - async function () { + async function() { smc = await new sourceMap.SourceMapConsumer(testSourceMap); }, - async function () { + async function() { let maxLine = 0; let maxCol = 0; smc.eachMapping(m => { @@ -199,7 +204,7 @@ var benchmarks = { benchmarkBlackbox(maxLine); benchmarkBlackbox(maxCol); }, - function () { + function() { smc.destroy(); } ); diff --git a/lib/array-set.js b/lib/array-set.js index 40171b9a..d2ed9cd1 100644 --- a/lib/array-set.js +++ b/lib/array-set.js @@ -60,7 +60,7 @@ class ArraySet { * @param String aStr */ has(aStr) { - return this._set.has(aStr); + return this._set.has(aStr); } /** @@ -71,7 +71,7 @@ class ArraySet { indexOf(aStr) { const idx = this._set.get(aStr); if (idx >= 0) { - return idx; + return idx; } throw new Error('"' + aStr + '" is not in the set.'); } diff --git a/lib/base64-vlq.js b/lib/base64-vlq.js index 77c14bf2..2daed1eb 100644 --- a/lib/base64-vlq.js +++ b/lib/base64-vlq.js @@ -67,9 +67,7 @@ const VLQ_CONTINUATION_BIT = VLQ_BASE; * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; + return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } /** diff --git a/lib/base64.js b/lib/base64.js index b9ca3199..f664eaa8 100644 --- a/lib/base64.js +++ b/lib/base64.js @@ -5,7 +5,9 @@ * http://opensource.org/licenses/BSD-3-Clause */ -const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); +const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split( + "" +); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. diff --git a/lib/binary-search.js b/lib/binary-search.js index bc29a44b..db65ccd1 100644 --- a/lib/binary-search.js +++ b/lib/binary-search.js @@ -87,8 +87,14 @@ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { return -1; } - let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); + let index = recursiveSearch( + -1, + aHaystack.length, + aNeedle, + aHaystack, + aCompare, + aBias || exports.GREATEST_LOWER_BOUND + ); if (index < 0) { return -1; } diff --git a/lib/mapping-list.js b/lib/mapping-list.js index 70568610..ece3c2cc 100644 --- a/lib/mapping-list.js +++ b/lib/mapping-list.js @@ -17,8 +17,11 @@ function generatedPositionAfter(mappingA, mappingB) { const lineB = mappingB.generatedLine; const columnA = mappingA.generatedColumn; const columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + return ( + lineB > lineA || + (lineB == lineA && columnB >= columnA) || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0 + ); } /** @@ -31,7 +34,7 @@ class MappingList { this._array = []; this._sorted = true; // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; + this._last = { generatedLine: -1, generatedColumn: 0 }; } /** diff --git a/lib/read-wasm-browser.js b/lib/read-wasm-browser.js index 10478bc1..a4fb29c2 100644 --- a/lib/read-wasm-browser.js +++ b/lib/read-wasm-browser.js @@ -4,17 +4,18 @@ let mappingsWasm = null; module.exports = function readWasm() { if (typeof mappingsWasm === "string") { - return fetch(mappingsWasm) - .then(response => response.arrayBuffer()); + return fetch(mappingsWasm).then(response => response.arrayBuffer()); } if (mappingsWasm instanceof ArrayBuffer) { return Promise.resolve(mappingsWasm); } - throw new Error("You must provide the string URL or ArrayBuffer contents " + - "of lib/mappings.wasm by calling " + - "SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " + - "before using SourceMapConsumer"); + throw new Error( + "You must provide the string URL or ArrayBuffer contents " + + "of lib/mappings.wasm by calling " + + "SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " + + "before using SourceMapConsumer" + ); }; module.exports.initialize = input => { diff --git a/lib/read-wasm.js b/lib/read-wasm.js index 18df8525..2ce01a75 100644 --- a/lib/read-wasm.js +++ b/lib/read-wasm.js @@ -21,5 +21,7 @@ module.exports = function readWasm() { }; module.exports.initialize = _ => { - console.debug("SourceMapConsumer.initialize is a no-op when running in node.js"); + console.debug( + "SourceMapConsumer.initialize is a no-op when running in node.js" + ); }; diff --git a/lib/source-map-consumer.js b/lib/source-map-consumer.js index 9b68e393..bc9fb5d2 100644 --- a/lib/source-map-consumer.js +++ b/lib/source-map-consumer.js @@ -203,9 +203,12 @@ class BasicSourceMapConsumer extends SourceMapConsumer { that._names = ArraySet.fromArray(names.map(String), true); that._sources = ArraySet.fromArray(sources, true); - that._absoluteSources = ArraySet.fromArray(that._sources.toArray().map(function(s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); - }), true); + that._absoluteSources = ArraySet.fromArray( + that._sources.toArray().map(function(s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }), + true + ); that.sourceRoot = sourceRoot; that.sourcesContent = sourcesContent; @@ -237,7 +240,11 @@ class BasicSourceMapConsumer extends SourceMapConsumer { } // Treat the source as map-relative overall by default. - const sourceAsMapRelative = util.computeSourceURL(null, aSource, this._sourceMapURL); + const sourceAsMapRelative = util.computeSourceURL( + null, + aSource, + this._sourceMapURL + ); if (this._absoluteSources.has(sourceAsMapRelative)) { const index = this._absoluteSources.indexOf(sourceAsMapRelative); this._sourceLookupCache.set(aSource, index); @@ -245,7 +252,11 @@ class BasicSourceMapConsumer extends SourceMapConsumer { } // Fall back to treating the source as sourceRoot-relative. - const sourceAsSourceRootRelative = util.computeSourceURL(this.sourceRoot, aSource, this._sourceMapURL); + const sourceAsSourceRootRelative = util.computeSourceURL( + this.sourceRoot, + aSource, + this._sourceMapURL + ); if (this._absoluteSources.has(sourceAsSourceRootRelative)) { const index = this._absoluteSources.indexOf(sourceAsSourceRootRelative); this._sourceLookupCache.set(aSource, index); @@ -291,7 +302,11 @@ class BasicSourceMapConsumer extends SourceMapConsumer { const size = aStr.length; const mappingsBufPtr = this._wasm.exports.allocate_mappings(size); - const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size); + const mappingsBuf = new Uint8Array( + this._wasm.exports.memory.buffer, + mappingsBufPtr, + size + ); for (let i = 0; i < size; i++) { mappingsBuf[i] = aStr.charCodeAt(i); } @@ -305,7 +320,8 @@ class BasicSourceMapConsumer extends SourceMapConsumer { // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`. switch (error) { case 1: - msg += "the mappings contained a negative line, column, source index, or name index"; + msg += + "the mappings contained a negative line, column, source index, or name index"; break; case 2: msg += "the mappings contained a number larger than 2**32"; @@ -348,14 +364,14 @@ class BasicSourceMapConsumer extends SourceMapConsumer { }, () => { switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - this._wasm.exports.by_generated_location(this._getMappingsPtr()); - break; - case SourceMapConsumer.ORIGINAL_ORDER: - this._wasm.exports.by_original_location(this._getMappingsPtr()); - break; - default: - throw new Error("Unknown order of iteration."); + case SourceMapConsumer.GENERATED_ORDER: + this._wasm.exports.by_generated_location(this._getMappingsPtr()); + break; + case SourceMapConsumer.ORIGINAL_ORDER: + this._wasm.exports.by_original_location(this._getMappingsPtr()); + break; + default: + throw new Error("Unknown order of iteration."); } } ); @@ -390,9 +406,10 @@ class BasicSourceMapConsumer extends SourceMapConsumer { mappings.push({ line: m.generatedLine, column: m.generatedColumn, - lastColumn, + lastColumn }); - }, () => { + }, + () => { this._wasm.exports.all_generated_locations_for( this._getMappingsPtr(), source, @@ -464,20 +481,27 @@ class BasicSourceMapConsumer extends SourceMapConsumer { throw new Error("Column numbers must be >= 0"); } - let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + let bias = util.getArg( + aArgs, + "bias", + SourceMapConsumer.GREATEST_LOWER_BOUND + ); if (bias == null) { bias = SourceMapConsumer.GREATEST_LOWER_BOUND; } let mapping; - this._wasm.withMappingCallback(m => mapping = m, () => { - this._wasm.exports.original_location_for( - this._getMappingsPtr(), - needle.generatedLine - 1, - needle.generatedColumn, - bias - ); - }); + this._wasm.withMappingCallback( + m => (mapping = m), + () => { + this._wasm.exports.original_location_for( + this._getMappingsPtr(), + needle.generatedLine - 1, + needle.generatedColumn, + bias + ); + } + ); if (mapping) { if (mapping.generatedLine === needle.generatedLine) { @@ -516,8 +540,12 @@ class BasicSourceMapConsumer extends SourceMapConsumer { if (!this.sourcesContent) { return false; } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function(sc) { return sc == null; }); + return ( + this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function(sc) { + return sc == null; + }) + ); } /** @@ -594,21 +622,28 @@ class BasicSourceMapConsumer extends SourceMapConsumer { throw new Error("Column numbers must be >= 0"); } - let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND); + let bias = util.getArg( + aArgs, + "bias", + SourceMapConsumer.GREATEST_LOWER_BOUND + ); if (bias == null) { bias = SourceMapConsumer.GREATEST_LOWER_BOUND; } let mapping; - this._wasm.withMappingCallback(m => mapping = m, () => { - this._wasm.exports.generated_location_for( - this._getMappingsPtr(), - needle.source, - needle.originalLine - 1, - needle.originalColumn, - bias - ); - }); + this._wasm.withMappingCallback( + m => (mapping = m), + () => { + this._wasm.exports.generated_location_for( + this._getMappingsPtr(), + needle.source, + needle.originalLine - 1, + needle.originalColumn, + bias + ); + } + ); if (mapping) { if (mapping.source === needle.source) { @@ -619,7 +654,7 @@ class BasicSourceMapConsumer extends SourceMapConsumer { return { line: util.getArg(mapping, "generatedLine", null), column: util.getArg(mapping, "generatedColumn", null), - lastColumn, + lastColumn }; } } @@ -703,35 +738,46 @@ class IndexedSourceMapConsumer extends SourceMapConsumer { line: -1, column: 0 }; - return Promise.all(sections.map(s => { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error("Support for url field in sections not implemented."); - } - const offset = util.getArg(s, "offset"); - const offsetLine = util.getArg(offset, "line"); - const offsetColumn = util.getArg(offset, "column"); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error("Section offsets must be ordered and non-overlapping."); - } - lastOffset = offset; - - const cons = new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL); - return cons.then(consumer => { - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer - }; - }); - })).then(s => { + return Promise.all( + sections.map(s => { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error( + "Support for url field in sections not implemented." + ); + } + const offset = util.getArg(s, "offset"); + const offsetLine = util.getArg(offset, "line"); + const offsetColumn = util.getArg(offset, "column"); + + if ( + offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column) + ) { + throw new Error( + "Section offsets must be ordered and non-overlapping." + ); + } + lastOffset = offset; + + const cons = new SourceMapConsumer( + util.getArg(s, "map"), + aSourceMapURL + ); + return cons.then(consumer => { + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer + }; + }); + }) + ).then(s => { that._sections = s; return that; }); @@ -778,16 +824,17 @@ class IndexedSourceMapConsumer extends SourceMapConsumer { // Find the section containing the generated position we're trying to map // to an original position. - const sectionIndex = binarySearch.search(needle, this._sections, - function(aNeedle, section) { - const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } + const sectionIndex = binarySearch.search(needle, this._sections, function( + aNeedle, + section + ) { + const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } - return (aNeedle.generatedColumn - - section.generatedOffset.generatedColumn); - }); + return aNeedle.generatedColumn - section.generatedOffset.generatedColumn; + }); const section = this._sections[sectionIndex]; if (!section) { @@ -800,12 +847,12 @@ class IndexedSourceMapConsumer extends SourceMapConsumer { } return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - + line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), + column: + needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), + ? section.generatedOffset.generatedColumn - 1 + : 0), bias: aArgs.bias }); } @@ -919,8 +966,9 @@ class IndexedSourceMapConsumer extends SourceMapConsumer { if (!section) return []; - return section.consumer.allGeneratedPositionsFor(aArgs).map( - generatedPosition => { + return section.consumer + .allGeneratedPositionsFor(aArgs) + .map(generatedPosition => { const lineShift = section.generatedOffset.generatedLine - 1; const columnShift = section.generatedOffset.generatedColumn - 1; @@ -942,42 +990,43 @@ class IndexedSourceMapConsumer extends SourceMapConsumer { generatedPosition.line += lineShift; return generatedPosition; - } - ); + }); } eachMapping(aCallback, aContext, aOrder) { this._sections.forEach((section, index) => { const nextSection = - index + 1 < this._sections.length - ? this._sections[index + 1] - : null; + index + 1 < this._sections.length ? this._sections[index + 1] : null; const { generatedOffset } = section; const lineShift = generatedOffset.generatedLine - 1; const columnShift = generatedOffset.generatedColumn - 1; - section.consumer.eachMapping(function(mapping) { - if (mapping.generatedLine === 1) { - mapping.generatedColumn += columnShift; + section.consumer.eachMapping( + function(mapping) { + if (mapping.generatedLine === 1) { + mapping.generatedColumn += columnShift; - if (typeof mapping.lastGeneratedColumn === "number") { - mapping.lastGeneratedColumn += columnShift; + if (typeof mapping.lastGeneratedColumn === "number") { + mapping.lastGeneratedColumn += columnShift; + } } - } - if ( - mapping.lastGeneratedColumn === Infinity && - nextSection && - mapping.generatedLine === nextSection.generatedOffset.generatedLine - ) { - mapping.lastGeneratedColumn = - nextSection.generatedOffset.generatedColumn - 2; - } - mapping.generatedLine += lineShift; + if ( + mapping.lastGeneratedColumn === Infinity && + nextSection && + mapping.generatedLine === nextSection.generatedOffset.generatedLine + ) { + mapping.lastGeneratedColumn = + nextSection.generatedOffset.generatedColumn - 2; + } + mapping.generatedLine += lineShift; - aCallback.call(this, mapping); - }, aContext, aOrder); + aCallback.call(this, mapping); + }, + aContext, + aOrder + ); }); } @@ -1005,7 +1054,8 @@ function _factory(aSourceMap, aSourceMapURL) { sourceMap = util.parseSourceMapInput(aSourceMap); } - const consumer = sourceMap.sections != null + const consumer = + sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); return Promise.resolve(consumer); diff --git a/lib/source-map-generator.js b/lib/source-map-generator.js index 670bcdf2..b34f5c84 100644 --- a/lib/source-map-generator.js +++ b/lib/source-map-generator.js @@ -180,7 +180,7 @@ class SourceMapGenerator { if (aSourceMapConsumer.file == null) { throw new Error( "SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " + - 'or the source map\'s "file" property. Both were omitted.' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; @@ -192,9 +192,8 @@ class SourceMapGenerator { } // Applying the SourceMap can add and remove items from the sources and // the names array. - const newSources = this._mappings.toArray().length > 0 - ? new ArraySet() - : this._sources; + const newSources = + this._mappings.toArray().length > 0 ? new ArraySet() : this._sources; const newNames = new ArraySet(); // Find mappings for the "sourceFile" @@ -231,7 +230,6 @@ class SourceMapGenerator { if (name != null && !newNames.has(name)) { newNames.add(name); } - }, this); this._sources = newSources; this._names = newNames; @@ -267,33 +265,53 @@ class SourceMapGenerator { // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { - throw new Error( - "original.line and original.column are not numbers -- you probably meant to omit " + - "the original mapping entirely and only map the generated position. If so, pass " + - "null for the original mapping instead of an object with empty or null values." - ); + if ( + aOriginal && + typeof aOriginal.line !== "number" && + typeof aOriginal.column !== "number" + ) { + throw new Error( + "original.line and original.column are not numbers -- you probably meant to omit " + + "the original mapping entirely and only map the generated position. If so, pass " + + "null for the original mapping instead of an object with empty or null values." + ); } - if (aGenerated && "line" in aGenerated && "column" in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { + if ( + aGenerated && + "line" in aGenerated && + "column" in aGenerated && + aGenerated.line > 0 && + aGenerated.column >= 0 && + !aOriginal && + !aSource && + !aName + ) { // Case 1. - - } else if (aGenerated && "line" in aGenerated && "column" in aGenerated - && aOriginal && "line" in aOriginal && "column" in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { + } else if ( + aGenerated && + "line" in aGenerated && + "column" in aGenerated && + aOriginal && + "line" in aOriginal && + "column" in aOriginal && + aGenerated.line > 0 && + aGenerated.column >= 0 && + aOriginal.line > 0 && + aOriginal.column >= 0 && + aSource + ) { // Cases 2 and 3. - } else { - throw new Error("Invalid mapping: " + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); + throw new Error( + "Invalid mapping: " + + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + }) + ); } } @@ -326,14 +344,17 @@ class SourceMapGenerator { previousGeneratedLine++; } } else if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + if ( + !util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1]) + ) { continue; } next += ","; } - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); + next += base64VLQ.encode( + mapping.generatedColumn - previousGeneratedColumn + ); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { @@ -342,12 +363,14 @@ class SourceMapGenerator { previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); + next += base64VLQ.encode( + mapping.originalLine - 1 - previousOriginalLine + ); previousOriginalLine = mapping.originalLine - 1; - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); + next += base64VLQ.encode( + mapping.originalColumn - previousOriginalColumn + ); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { @@ -395,7 +418,10 @@ class SourceMapGenerator { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + map.sourcesContent = this._generateSourcesContent( + map.sources, + map.sourceRoot + ); } return map; diff --git a/lib/source-node.js b/lib/source-node.js index 8a7a157e..512c6c8f 100644 --- a/lib/source-node.js +++ b/lib/source-node.js @@ -52,7 +52,11 @@ class SourceNode { * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ - static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + static fromStringWithSourceMap( + aGeneratedCode, + aSourceMapConsumer, + aRelativePath + ) { // The SourceNode we want to fill with the generated code // and the SourceMap const node = new SourceNode(); @@ -70,13 +74,15 @@ class SourceNode { return lineContents + newLine; function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; + return remainingLinesIndex < remainingLines.length + ? remainingLines[remainingLinesIndex++] + : undefined; } }; // We need to remember the position of "remainingLines" - let lastGeneratedLine = 1, lastGeneratedColumn = 0; + let lastGeneratedLine = 1, + lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. @@ -99,10 +105,13 @@ class SourceNode { // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" nextLine = remainingLines[remainingLinesIndex] || ""; - const code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); + const code = nextLine.substr( + 0, + mapping.generatedColumn - lastGeneratedColumn + ); + remainingLines[remainingLinesIndex] = nextLine.substr( + mapping.generatedColumn - lastGeneratedColumn + ); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue @@ -120,7 +129,9 @@ class SourceNode { if (lastGeneratedColumn < mapping.generatedColumn) { nextLine = remainingLines[remainingLinesIndex] || ""; node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr( + mapping.generatedColumn + ); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; @@ -155,11 +166,15 @@ class SourceNode { const source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); + node.add( + new SourceNode( + mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name + ) + ); } } } @@ -181,7 +196,8 @@ class SourceNode { } } else { throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + + aChunk ); } return this; @@ -202,7 +218,8 @@ class SourceNode { this.children.unshift(aChunk); } else { throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + + aChunk ); } return this; @@ -222,10 +239,12 @@ class SourceNode { if (chunk[isSourceNode]) { chunk.walk(aFn); } else if (chunk !== "") { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); + aFn(chunk, { + source: this.source, + line: this.line, + column: this.column, + name: this.name + }); } } } @@ -264,7 +283,10 @@ class SourceNode { if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === "string") { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + this.children[this.children.length - 1] = lastChild.replace( + aPattern, + aReplacement + ); } else { this.children.push("".replace(aPattern, aReplacement)); } @@ -331,13 +353,17 @@ class SourceNode { let lastOriginalName = null; this.walk(function(chunk, original) { generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if (lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { + if ( + original.source !== null && + original.line !== null && + original.column !== null + ) { + if ( + lastOriginalSource !== original.source || + lastOriginalLine !== original.line || + lastOriginalColumn !== original.column || + lastOriginalName !== original.name + ) { map.addMapping({ source: original.source, original: { diff --git a/lib/util.js b/lib/util.js index 430ec4de..1f810af1 100644 --- a/lib/util.js +++ b/lib/util.js @@ -23,15 +23,14 @@ function getArg(aArgs, aName, aDefaultValue) { } else if (arguments.length === 3) { return aDefaultValue; } - throw new Error('"' + aName + '" is a required argument.'); - + throw new Error('"' + aName + '" is a required argument.'); } exports.getArg = getArg; const supportsNullProto = (function() { const obj = Object.create(null); return !("__proto__" in obj); -}()); +})(); function identity(s) { return s; @@ -76,15 +75,17 @@ function isProtoString(s) { } /* eslint-disable no-multi-spaces */ - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { + if ( + s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */ + ) { return false; } /* eslint-enable no-multi-spaces */ @@ -203,7 +204,7 @@ function withBase(url, base) { function buildUniqueSegment(prefix, str) { let id = 0; do { - const ident = prefix + (id++); + const ident = prefix + id++; if (str.indexOf(ident) === -1) return ident; } while (true); } @@ -337,14 +338,18 @@ function join(aRoot, aPath) { return normalize(aPath); } if (rootType === "scheme-relative") { - return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL.length); + return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice( + PROTOCOL.length + ); } if (pathType === "path-absolute") { return normalize(aPath); } if (rootType === "path-absolute") { - return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL_AND_HOST.length); + return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice( + PROTOCOL_AND_HOST.length + ); } const base = buildSafeBase(aPath + aRoot); diff --git a/lib/wasm.js b/lib/wasm.js index 88b18bea..a85c2f8d 100644 --- a/lib/wasm.js +++ b/lib/wasm.js @@ -22,7 +22,8 @@ module.exports = function wasm() { const callbackStack = []; - cachedWasm = readWasm().then(buffer => { + cachedWasm = readWasm() + .then(buffer => { return WebAssembly.instantiate(buffer, { env: { mapping_callback( @@ -64,44 +65,74 @@ module.exports = function wasm() { callbackStack[callbackStack.length - 1](mapping); }, - start_all_generated_locations_for() { console.time("all_generated_locations_for"); }, - end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); }, + start_all_generated_locations_for() { + console.time("all_generated_locations_for"); + }, + end_all_generated_locations_for() { + console.timeEnd("all_generated_locations_for"); + }, - start_compute_column_spans() { console.time("compute_column_spans"); }, - end_compute_column_spans() { console.timeEnd("compute_column_spans"); }, + start_compute_column_spans() { + console.time("compute_column_spans"); + }, + end_compute_column_spans() { + console.timeEnd("compute_column_spans"); + }, - start_generated_location_for() { console.time("generated_location_for"); }, - end_generated_location_for() { console.timeEnd("generated_location_for"); }, + start_generated_location_for() { + console.time("generated_location_for"); + }, + end_generated_location_for() { + console.timeEnd("generated_location_for"); + }, - start_original_location_for() { console.time("original_location_for"); }, - end_original_location_for() { console.timeEnd("original_location_for"); }, + start_original_location_for() { + console.time("original_location_for"); + }, + end_original_location_for() { + console.timeEnd("original_location_for"); + }, - start_parse_mappings() { console.time("parse_mappings"); }, - end_parse_mappings() { console.timeEnd("parse_mappings"); }, + start_parse_mappings() { + console.time("parse_mappings"); + }, + end_parse_mappings() { + console.timeEnd("parse_mappings"); + }, - start_sort_by_generated_location() { console.time("sort_by_generated_location"); }, - end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); }, + start_sort_by_generated_location() { + console.time("sort_by_generated_location"); + }, + end_sort_by_generated_location() { + console.timeEnd("sort_by_generated_location"); + }, - start_sort_by_original_location() { console.time("sort_by_original_location"); }, - end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); }, + start_sort_by_original_location() { + console.time("sort_by_original_location"); + }, + end_sort_by_original_location() { + console.timeEnd("sort_by_original_location"); + } } }); - }).then(Wasm => { - return { - exports: Wasm.instance.exports, - withMappingCallback: (mappingCallback, f) => { - callbackStack.push(mappingCallback); - try { - f(); - } finally { - callbackStack.pop(); + }) + .then(Wasm => { + return { + exports: Wasm.instance.exports, + withMappingCallback: (mappingCallback, f) => { + callbackStack.push(mappingCallback); + try { + f(); + } finally { + callbackStack.pop(); + } } - } - }; - }).then(null, e => { - cachedWasm = null; - throw e; - }); + }; + }) + .then(null, e => { + cachedWasm = null; + throw e; + }); return cachedWasm; }; diff --git a/package.json b/package.json index 878fc676..83528132 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ }, "license": "BSD-3-Clause", "scripts": { - "lint": "eslint *.js lib/ test/", + "lint": "eslint --fix *.js lib/ test/", "prebuild": "npm run lint", "test": "node test/run-tests.js", "coverage": "nyc node test/run-tests.js", @@ -74,6 +74,7 @@ "dev:watch": "watch 'npm run coverage' lib/ test/", "predev": "npm run setup", "dev": "npm-run-all -p --silent dev:*", + "prettier": "prettier --write --print-width=120 *.{js,ts,json,md} lib/*.js test/*.js bench/bench*", "clean": "rm -rf coverage .nyc_output", "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" }, @@ -83,6 +84,9 @@ "live-server": "^1.2.0", "npm-run-all": "^4.1.2", "nyc": "^11.7.1", + "prettier": "1.18.2", + "eslint-config-prettier": "^6.5.0", + "eslint-plugin-prettier": "^3.1.1", "watch": "^1.0.2" }, "nyc": { diff --git a/source-map.d.ts b/source-map.d.ts index e856c66e..e4da538d 100644 --- a/source-map.d.ts +++ b/source-map.d.ts @@ -7,364 +7,366 @@ export type SourceMapUrl = string; export interface StartOfSourceMap { - file?: string; - sourceRoot?: string; - skipValidation?: boolean; + file?: string; + sourceRoot?: string; + skipValidation?: boolean; } export interface RawSourceMap { - version: number; - sources: string[]; - names: string[]; - sourceRoot?: string; - sourcesContent?: string[]; - mappings: string; - file: string; + version: number; + sources: string[]; + names: string[]; + sourceRoot?: string; + sourcesContent?: string[]; + mappings: string; + file: string; } export interface RawIndexMap extends StartOfSourceMap { - version: number; - sections: RawSection[]; + version: number; + sections: RawSection[]; } export interface RawSection { - offset: Position; - map: RawSourceMap; + offset: Position; + map: RawSourceMap; } export interface Position { - line: number; - column: number; + line: number; + column: number; } export interface NullablePosition { - line: number | null; - column: number | null; - lastColumn: number | null; + line: number | null; + column: number | null; + lastColumn: number | null; } export interface MappedPosition { - source: string; - line: number; - column: number; - name?: string; + source: string; + line: number; + column: number; + name?: string; } export interface NullableMappedPosition { - source: string | null; - line: number | null; - column: number | null; - name: string | null; + source: string | null; + line: number | null; + column: number | null; + name: string | null; } export interface MappingItem { - source: string; - generatedLine: number; - generatedColumn: number; - lastGeneratedColumn: number | null; - originalLine: number; - originalColumn: number; - name: string; + source: string; + generatedLine: number; + generatedColumn: number; + lastGeneratedColumn: number | null; + originalLine: number; + originalColumn: number; + name: string; } export interface Mapping { - generated: Position; - original: Position; - source: string; - name?: string; + generated: Position; + original: Position; + source: string; + name?: string; } export interface CodeWithSourceMap { - code: string; - map: SourceMapGenerator; + code: string; + map: SourceMapGenerator; } export interface SourceMapConsumer { - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - computeColumnSpans(): void; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition; - - /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[]; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - hasContentsOfAllSources(): boolean; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param callback - * The function that is called with each mapping. - * @param context - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param order - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; - /** - * Free this source map consumer's associated wasm data that is manually-managed. - * Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy. - */ - destroy(): void; + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + computeColumnSpans(): void; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[]; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + hasContentsOfAllSources(): boolean; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param callback + * The function that is called with each mapping. + * @param context + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param order + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; + /** + * Free this source map consumer's associated wasm data that is manually-managed. + * Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy. + */ + destroy(): void; } export interface SourceMapConsumerConstructor { - prototype: SourceMapConsumer; - - GENERATED_ORDER: number; - ORIGINAL_ORDER: number; - GREATEST_LOWER_BOUND: number; - LEAST_UPPER_BOUND: number; - - new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise; - new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise; - new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise; - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param sourceMap - * The source map that will be consumed. - */ - fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise; - - /** - * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` - * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async - * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait - * for `f` to complete, call `destroy` on the consumer, and return `f`'s return - * value. - * - * You must not use the consumer after `f` completes! - * - * By using `with`, you do not have to remember to manually call `destroy` on - * the consumer, since it will be called automatically once `f` completes. - * - * ```js - * const xSquared = await SourceMapConsumer.with( - * myRawSourceMap, - * null, - * async function (consumer) { - * // Use `consumer` inside here and don't worry about remembering - * // to call `destroy`. - * - * const x = await whatever(consumer); - * return x * x; - * } - * ); - * - * // You may not use that `consumer` anymore out here; it has - * // been destroyed. But you can use `xSquared`. - * console.log(xSquared); - * ``` - */ - with(rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise | T): Promise; + prototype: SourceMapConsumer; + + GENERATED_ORDER: number; + ORIGINAL_ORDER: number; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + + new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise; + new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise; + new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise< + BasicSourceMapConsumer | IndexedSourceMapConsumer + >; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise; + + /** + * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` + * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async + * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait + * for `f` to complete, call `destroy` on the consumer, and return `f`'s return + * value. + * + * You must not use the consumer after `f` completes! + * + * By using `with`, you do not have to remember to manually call `destroy` on + * the consumer, since it will be called automatically once `f` completes. + * + * ```js + * const xSquared = await SourceMapConsumer.with( + * myRawSourceMap, + * null, + * async function (consumer) { + * // Use `consumer` inside here and don't worry about remembering + * // to call `destroy`. + * + * const x = await whatever(consumer); + * return x * x; + * } + * ); + * + * // You may not use that `consumer` anymore out here; it has + * // been destroyed. But you can use `xSquared`. + * console.log(xSquared); + * ``` + */ + with( + rawSourceMap: RawSourceMap | RawIndexMap | string, + sourceMapUrl: SourceMapUrl | null | undefined, + callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise | T + ): Promise; } export const SourceMapConsumer: SourceMapConsumerConstructor; export interface BasicSourceMapConsumer extends SourceMapConsumer { - file: string; - sourceRoot: string; - sources: string[]; - sourcesContent: string[]; + file: string; + sourceRoot: string; + sources: string[]; + sourcesContent: string[]; } export interface BasicSourceMapConsumerConstructor { - prototype: BasicSourceMapConsumer; + prototype: BasicSourceMapConsumer; - new (rawSourceMap: RawSourceMap | string): Promise; + new (rawSourceMap: RawSourceMap | string): Promise; - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param sourceMap - * The source map that will be consumed. - */ - fromSourceMap(sourceMap: SourceMapGenerator): Promise; + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param sourceMap + * The source map that will be consumed. + */ + fromSourceMap(sourceMap: SourceMapGenerator): Promise; } export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor; export interface IndexedSourceMapConsumer extends SourceMapConsumer { - sources: string[]; + sources: string[]; } export interface IndexedSourceMapConsumerConstructor { - prototype: IndexedSourceMapConsumer; + prototype: IndexedSourceMapConsumer; - new (rawSourceMap: RawIndexMap | string): Promise; + new (rawSourceMap: RawIndexMap | string): Promise; } export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor; export class SourceMapGenerator { - constructor(startOfSourceMap?: StartOfSourceMap); - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param sourceMapConsumer The SourceMap. - */ - static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - addMapping(mapping: Mapping): void; - - /** - * Set the source content for a source file. - */ - setSourceContent(sourceFile: string, sourceContent: string): void; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param sourceMapConsumer The source map to be applied. - * @param sourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param sourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ - applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; - - toString(): string; - - toJSON(): RawSourceMap; + constructor(startOfSourceMap?: StartOfSourceMap); + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param sourceMapConsumer The SourceMap. + */ + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + addMapping(mapping: Mapping): void; + + /** + * Set the source content for a source file. + */ + setSourceContent(sourceFile: string, sourceContent: string): void; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param sourceMapConsumer The source map to be applied. + * @param sourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param sourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + + toString(): string; + + toJSON(): RawSourceMap; } export class SourceNode { - children: SourceNode[]; - sourceContents: any; - line: number; - column: number; - source: string; - name: string; + children: SourceNode[]; + sourceContents: any; + line: number; + column: number; + source: string; + name: string; - constructor(); - constructor( - line: number | null, - column: number | null, - source: string | null, - chunks?: Array<(string | SourceNode)> | SourceNode | string, - name?: string - ); + constructor(); + constructor( + line: number | null, + column: number | null, + source: string | null, + chunks?: Array | SourceNode | string, + name?: string + ); - static fromStringWithSourceMap( - code: string, - sourceMapConsumer: SourceMapConsumer, - relativePath?: string - ): SourceNode; + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; - add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + add(chunk: Array | SourceNode | string): SourceNode; - prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode; + prepend(chunk: Array | SourceNode | string): SourceNode; - setSourceContent(sourceFile: string, sourceContent: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; - walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; - walkSourceContents(fn: (file: string, content: string) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; - join(sep: string): SourceNode; + join(sep: string): SourceNode; - replaceRight(pattern: string, replacement: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; - toString(): string; + toString(): string; - toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; } diff --git a/test/run-tests.js b/test/run-tests.js index c43d34dd..2a98f4cc 100755 --- a/test/run-tests.js +++ b/test/run-tests.js @@ -37,25 +37,26 @@ async function run(tests) { function isTestFile(f) { const testToRun = process.argv[2]; - return testToRun - ? path.basename(testToRun) === f - : /^test\-.*?\.js/.test(f); + return testToRun ? path.basename(testToRun) === f : /^test\-.*?\.js/.test(f); } function toRelativeModule(f) { return "./" + f.replace(/\.js$/, ""); } -const requires = fs.readdirSync(__dirname) +const requires = fs + .readdirSync(__dirname) .filter(isTestFile) .map(toRelativeModule); -run(requires.map(require).map(function(mod, i) { - return { - name: requires[i], - testCase: mod - }; -})).then( +run( + requires.map(require).map(function(mod, i) { + return { + name: requires[i], + testCase: mod + }; + }) +).then( code => process.exit(code), e => { console.error(e); diff --git a/test/test-api.js b/test/test-api.js index a4068ca9..0f4621b3 100644 --- a/test/test-api.js +++ b/test/test-api.js @@ -7,7 +7,9 @@ const sourceMap = require("../source-map"); -exports["test that the api is properly exposed in the top level"] = function(assert) { +exports["test that the api is properly exposed in the top level"] = function( + assert +) { assert.equal(typeof sourceMap.SourceMapGenerator, "function"); assert.equal(typeof sourceMap.SourceMapConsumer, "function"); assert.equal(typeof sourceMap.SourceNode, "function"); diff --git a/test/test-array-set.js b/test/test-array-set.js index ef59fff2..27af44ea 100644 --- a/test/test-array-set.js +++ b/test/test-array-set.js @@ -37,7 +37,13 @@ exports["test .at() indexing"] = function(assert) { }; exports["test creating from an array"] = function(assert) { - const set = ArraySet.fromArray(["foo", "bar", "baz", "quux", "hasOwnProperty"]); + const set = ArraySet.fromArray([ + "foo", + "bar", + "baz", + "quux", + "hasOwnProperty" + ]); assert.ok(set.has("foo")); assert.ok(set.has("bar")); @@ -56,7 +62,9 @@ exports["test creating from an array"] = function(assert) { assert.strictEqual(set.at(3), "quux"); }; -exports["test that you can add __proto__; see github issue #30"] = function(assert) { +exports["test that you can add __proto__; see github issue #30"] = function( + assert +) { const set = new ArraySet(); set.add("__proto__"); assert.ok(set.has("__proto__")); diff --git a/test/test-base64-vlq.js b/test/test-base64-vlq.js index 1d79cef5..e0ed0478 100644 --- a/test/test-base64-vlq.js +++ b/test/test-base64-vlq.js @@ -514,7 +514,7 @@ const vlqs = [ { number: 252, encoded: "4P" }, { number: 253, encoded: "6P" }, { number: 254, encoded: "8P" }, - { number: 255, encoded: "+P" }, + { number: 255, encoded: "+P" } ]; exports["test normal encoding and decoding"] = function(assert) { diff --git a/test/test-binary-search.js b/test/test-binary-search.js index 5a31aea7..af325948 100644 --- a/test/test-binary-search.js +++ b/test/test-binary-search.js @@ -19,7 +19,10 @@ exports["test too high with default (glb) bias"] = function(assert) { binarySearch.search(needle, haystack, numberCompare); }); - assert.equal(haystack[binarySearch.search(needle, haystack, numberCompare)], 20); + assert.equal( + haystack[binarySearch.search(needle, haystack, numberCompare)], + 20 + ); }; exports["test too low with default (glb) bias"] = function(assert) { @@ -41,8 +44,15 @@ exports["test too high with lub bias"] = function(assert) { binarySearch.search(needle, haystack, numberCompare); }); - assert.equal(binarySearch.search(needle, haystack, numberCompare, - binarySearch.LEAST_UPPER_BOUND), -1); + assert.equal( + binarySearch.search( + needle, + haystack, + numberCompare, + binarySearch.LEAST_UPPER_BOUND + ), + -1 + ); }; exports["test too low with lub bias"] = function(assert) { @@ -53,44 +63,82 @@ exports["test too low with lub bias"] = function(assert) { binarySearch.search(needle, haystack, numberCompare); }); - assert.equal(haystack[binarySearch.search(needle, haystack, numberCompare, - binarySearch.LEAST_UPPER_BOUND)], 2); + assert.equal( + haystack[ + binarySearch.search( + needle, + haystack, + numberCompare, + binarySearch.LEAST_UPPER_BOUND + ) + ], + 2 + ); }; exports["test exact search"] = function(assert) { const needle = 4; const haystack = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; - assert.equal(haystack[binarySearch.search(needle, haystack, numberCompare)], 4); + assert.equal( + haystack[binarySearch.search(needle, haystack, numberCompare)], + 4 + ); }; exports["test fuzzy search with default (glb) bias"] = function(assert) { const needle = 19; const haystack = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; - assert.equal(haystack[binarySearch.search(needle, haystack, numberCompare)], 18); + assert.equal( + haystack[binarySearch.search(needle, haystack, numberCompare)], + 18 + ); }; exports["test fuzzy search with lub bias"] = function(assert) { const needle = 19; const haystack = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; - assert.equal(haystack[binarySearch.search(needle, haystack, numberCompare, - binarySearch.LEAST_UPPER_BOUND)], 20); + assert.equal( + haystack[ + binarySearch.search( + needle, + haystack, + numberCompare, + binarySearch.LEAST_UPPER_BOUND + ) + ], + 20 + ); }; exports["test multiple matches"] = function(assert) { const needle = 5; const haystack = [1, 1, 2, 5, 5, 5, 13, 21]; - assert.equal(binarySearch.search(needle, haystack, numberCompare, - binarySearch.LEAST_UPPER_BOUND), 3); + assert.equal( + binarySearch.search( + needle, + haystack, + numberCompare, + binarySearch.LEAST_UPPER_BOUND + ), + 3 + ); }; exports["test multiple matches at the beginning"] = function(assert) { const needle = 1; const haystack = [1, 1, 2, 5, 5, 5, 13, 21]; - assert.equal(binarySearch.search(needle, haystack, numberCompare, - binarySearch.LEAST_UPPER_BOUND), 0); + assert.equal( + binarySearch.search( + needle, + haystack, + numberCompare, + binarySearch.LEAST_UPPER_BOUND + ), + 0 + ); }; diff --git a/test/test-dog-fooding.js b/test/test-dog-fooding.js index 1186785b..fbe6449b 100644 --- a/test/test-dog-fooding.js +++ b/test/test-dog-fooding.js @@ -6,8 +6,10 @@ */ const util = require("./util"); -const SourceMapConsumer = require("../lib/source-map-consumer").SourceMapConsumer; -const SourceMapGenerator = require("../lib/source-map-generator").SourceMapGenerator; +const SourceMapConsumer = require("../lib/source-map-consumer") + .SourceMapConsumer; +const SourceMapGenerator = require("../lib/source-map-generator") + .SourceMapGenerator; exports["test eating our own dog food"] = async function(assert) { const smg = new SourceMapGenerator({ @@ -48,55 +50,425 @@ exports["test eating our own dog food"] = async function(assert) { const smc = await new SourceMapConsumer(smg.toString()); // Exact - util.assertMapping(2, 2, "/wu/tang/gza.coffee", 1, 0, null, null, smc, assert); - util.assertMapping(3, 2, "/wu/tang/gza.coffee", 2, 0, null, null, smc, assert); - util.assertMapping(4, 2, "/wu/tang/gza.coffee", 3, 0, null, null, smc, assert); - util.assertMapping(5, 2, "/wu/tang/gza.coffee", 4, 0, null, null, smc, assert); - util.assertMapping(6, 12, "/wu/tang/gza.coffee", 5, 10, null, null, smc, assert); + util.assertMapping( + 2, + 2, + "/wu/tang/gza.coffee", + 1, + 0, + null, + null, + smc, + assert + ); + util.assertMapping( + 3, + 2, + "/wu/tang/gza.coffee", + 2, + 0, + null, + null, + smc, + assert + ); + util.assertMapping( + 4, + 2, + "/wu/tang/gza.coffee", + 3, + 0, + null, + null, + smc, + assert + ); + util.assertMapping( + 5, + 2, + "/wu/tang/gza.coffee", + 4, + 0, + null, + null, + smc, + assert + ); + util.assertMapping( + 6, + 12, + "/wu/tang/gza.coffee", + 5, + 10, + null, + null, + smc, + assert + ); // Fuzzy // Generated to original with default (glb) bias. util.assertMapping(2, 0, null, null, null, null, null, smc, assert, true); - util.assertMapping(2, 9, "/wu/tang/gza.coffee", 1, 0, null, null, smc, assert, true); + util.assertMapping( + 2, + 9, + "/wu/tang/gza.coffee", + 1, + 0, + null, + null, + smc, + assert, + true + ); util.assertMapping(3, 0, null, null, null, null, null, smc, assert, true); - util.assertMapping(3, 9, "/wu/tang/gza.coffee", 2, 0, null, null, smc, assert, true); + util.assertMapping( + 3, + 9, + "/wu/tang/gza.coffee", + 2, + 0, + null, + null, + smc, + assert, + true + ); util.assertMapping(4, 0, null, null, null, null, null, smc, assert, true); - util.assertMapping(4, 9, "/wu/tang/gza.coffee", 3, 0, null, null, smc, assert, true); + util.assertMapping( + 4, + 9, + "/wu/tang/gza.coffee", + 3, + 0, + null, + null, + smc, + assert, + true + ); util.assertMapping(5, 0, null, null, null, null, null, smc, assert, true); - util.assertMapping(5, 9, "/wu/tang/gza.coffee", 4, 0, null, null, smc, assert, true); + util.assertMapping( + 5, + 9, + "/wu/tang/gza.coffee", + 4, + 0, + null, + null, + smc, + assert, + true + ); util.assertMapping(6, 0, null, null, null, null, null, smc, assert, true); util.assertMapping(6, 9, null, null, null, null, null, smc, assert, true); - util.assertMapping(6, 13, "/wu/tang/gza.coffee", 5, 10, null, null, smc, assert, true); + util.assertMapping( + 6, + 13, + "/wu/tang/gza.coffee", + 5, + 10, + null, + null, + smc, + assert, + true + ); // Generated to original with lub bias. - util.assertMapping(2, 0, "/wu/tang/gza.coffee", 1, 0, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(2, 9, null, null, null, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(3, 0, "/wu/tang/gza.coffee", 2, 0, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(3, 9, null, null, null, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(4, 0, "/wu/tang/gza.coffee", 3, 0, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(4, 9, null, null, null, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(5, 0, "/wu/tang/gza.coffee", 4, 0, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(5, 9, null, null, null, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(6, 0, "/wu/tang/gza.coffee", 5, 10, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(6, 9, "/wu/tang/gza.coffee", 5, 10, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); - util.assertMapping(6, 13, null, null, null, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, true); + util.assertMapping( + 2, + 0, + "/wu/tang/gza.coffee", + 1, + 0, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 2, + 9, + null, + null, + null, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 3, + 0, + "/wu/tang/gza.coffee", + 2, + 0, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 3, + 9, + null, + null, + null, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 4, + 0, + "/wu/tang/gza.coffee", + 3, + 0, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 4, + 9, + null, + null, + null, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 5, + 0, + "/wu/tang/gza.coffee", + 4, + 0, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 5, + 9, + null, + null, + null, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 6, + 0, + "/wu/tang/gza.coffee", + 5, + 10, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 6, + 9, + "/wu/tang/gza.coffee", + 5, + 10, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); + util.assertMapping( + 6, + 13, + null, + null, + null, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + true + ); // Original to generated with default (glb) bias - util.assertMapping(2, 2, "/wu/tang/gza.coffee", 1, 1, null, null, smc, assert, null, true); - util.assertMapping(3, 2, "/wu/tang/gza.coffee", 2, 3, null, null, smc, assert, null, true); - util.assertMapping(4, 2, "/wu/tang/gza.coffee", 3, 6, null, null, smc, assert, null, true); - util.assertMapping(5, 2, "/wu/tang/gza.coffee", 4, 9, null, null, smc, assert, null, true); - util.assertMapping(5, 2, "/wu/tang/gza.coffee", 5, 9, null, null, smc, assert, null, true); - util.assertMapping(6, 12, "/wu/tang/gza.coffee", 6, 19, null, null, smc, assert, null, true); + util.assertMapping( + 2, + 2, + "/wu/tang/gza.coffee", + 1, + 1, + null, + null, + smc, + assert, + null, + true + ); + util.assertMapping( + 3, + 2, + "/wu/tang/gza.coffee", + 2, + 3, + null, + null, + smc, + assert, + null, + true + ); + util.assertMapping( + 4, + 2, + "/wu/tang/gza.coffee", + 3, + 6, + null, + null, + smc, + assert, + null, + true + ); + util.assertMapping( + 5, + 2, + "/wu/tang/gza.coffee", + 4, + 9, + null, + null, + smc, + assert, + null, + true + ); + util.assertMapping( + 5, + 2, + "/wu/tang/gza.coffee", + 5, + 9, + null, + null, + smc, + assert, + null, + true + ); + util.assertMapping( + 6, + 12, + "/wu/tang/gza.coffee", + 6, + 19, + null, + null, + smc, + assert, + null, + true + ); // Original to generated with lub bias. - util.assertMapping(3, 2, "/wu/tang/gza.coffee", 1, 1, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); - util.assertMapping(4, 2, "/wu/tang/gza.coffee", 2, 3, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); - util.assertMapping(5, 2, "/wu/tang/gza.coffee", 3, 6, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); - util.assertMapping(6, 12, "/wu/tang/gza.coffee", 4, 9, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); - util.assertMapping(6, 12, "/wu/tang/gza.coffee", 5, 9, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); - util.assertMapping(null, null, "/wu/tang/gza.coffee", 6, 19, null, SourceMapConsumer.LEAST_UPPER_BOUND, smc, assert, null, true); + util.assertMapping( + 3, + 2, + "/wu/tang/gza.coffee", + 1, + 1, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); + util.assertMapping( + 4, + 2, + "/wu/tang/gza.coffee", + 2, + 3, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); + util.assertMapping( + 5, + 2, + "/wu/tang/gza.coffee", + 3, + 6, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); + util.assertMapping( + 6, + 12, + "/wu/tang/gza.coffee", + 4, + 9, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); + util.assertMapping( + 6, + 12, + "/wu/tang/gza.coffee", + 5, + 9, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); + util.assertMapping( + null, + null, + "/wu/tang/gza.coffee", + 6, + 19, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + smc, + assert, + null, + true + ); smc.destroy(); }; diff --git a/test/test-nested-consumer-usage.js b/test/test-nested-consumer-usage.js index f8477a61..91fb512b 100644 --- a/test/test-nested-consumer-usage.js +++ b/test/test-nested-consumer-usage.js @@ -1,4 +1,4 @@ -const {SourceMapConsumer, SourceMapGenerator} = require("../"); +const { SourceMapConsumer, SourceMapGenerator } = require("../"); const TS_MAP = { version: 3, @@ -9,7 +9,8 @@ const TS_MAP = { mappings: ";;AAKA;IACE,MAAM,CAAC,EAAC,MAAM,EAAE,SAAS,EAAC,CAAC;AAC7B,CAAC;AAFD,yBAEC", sourcesContent: [ - "\ntype Cheese = {\n readonly cheese: string\n}\n\nexport default function Cheese(): Cheese {\n return {cheese: 'stilton'};\n}\n" + "\ntype Cheese = {\n readonly cheese: string\n}\n\nexport default function Cheese(): Cheese {\n" + + " return {cheese: 'stilton'};\n}\n" ] }; @@ -26,18 +27,15 @@ const BABEL_MAP = { "default" ], mappings: + // eslint-disable-next-line "AAAA;;AACAA,OAAOC,cAAP,CAAsBC,OAAtB,EAA+B,YAA/B,EAA6C,EAAEC,OAAO,IAAT,EAA7C;AACA,SAASC,MAAT,GAAkB;AACd,WAAO,EAAEC,QAAQ,SAAV,EAAP;AACH;AACDH,QAAQI,OAAR,GAAkBF,MAAlB", sourcesContent: [ - '"use strict";\nObject.defineProperty(exports, "__esModule", { value: true });\nfunction Cheese() {\n return { cheese: \'stilton\' };\n}\nexports.default = Cheese;\n//# sourceMappingURL=blah.js.map' + '"use strict";\nObject.defineProperty(exports, "__esModule", { value: true });\nfunction Cheese() {\n' + + " return { cheese: 'stilton' };\n}\nexports.default = Cheese;\n//# sourceMappingURL=blah.js.map" ] }; - -async function composeSourceMaps( - tsMap, - babelMap, - tsFileName, -) { +async function composeSourceMaps(tsMap, babelMap, tsFileName) { const tsConsumer = await new SourceMapConsumer(tsMap); const babelConsumer = await new SourceMapConsumer(babelMap); const map = new SourceMapGenerator(); @@ -48,25 +46,25 @@ async function composeSourceMaps( generatedColumn, originalLine, originalColumn, - name, + name }) => { if (originalLine) { const original = tsConsumer.originalPositionFor({ line: originalLine, - column: originalColumn, + column: originalColumn }); if (original.line) { map.addMapping({ generated: { line: generatedLine, - column: generatedColumn, + column: generatedColumn }, original: { line: original.line, - column: original.column, + column: original.column }, source: tsFileName, - name, + name }); } } diff --git a/test/test-source-map-consumer.js b/test/test-source-map-consumer.js index 3d86b39e..c8d2b8e1 100644 --- a/test/test-source-map-consumer.js +++ b/test/test-source-map-consumer.js @@ -6,37 +6,51 @@ */ const util = require("./util"); -const SourceMapConsumer = require("../lib/source-map-consumer").SourceMapConsumer; -const IndexedSourceMapConsumer = require("../lib/source-map-consumer").IndexedSourceMapConsumer; -const BasicSourceMapConsumer = require("../lib/source-map-consumer").BasicSourceMapConsumer; -const SourceMapGenerator = require("../lib/source-map-generator").SourceMapGenerator; - -exports["test that we can instantiate with a string or an object"] = async function(assert) { +const SourceMapConsumer = require("../lib/source-map-consumer") + .SourceMapConsumer; +const IndexedSourceMapConsumer = require("../lib/source-map-consumer") + .IndexedSourceMapConsumer; +const BasicSourceMapConsumer = require("../lib/source-map-consumer") + .BasicSourceMapConsumer; +const SourceMapGenerator = require("../lib/source-map-generator") + .SourceMapGenerator; + +exports[ + "test that we can instantiate with a string or an object" +] = async function(assert) { let map = await new SourceMapConsumer(util.testMap); map = await new SourceMapConsumer(JSON.stringify(util.testMap)); assert.ok(true); map.destroy(); }; -exports["test that the object returned from await new SourceMapConsumer inherits from SourceMapConsumer"] = async function(assert) { +exports[ + "test that the object returned from await new SourceMapConsumer inherits from SourceMapConsumer" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMap); assert.ok(map instanceof SourceMapConsumer); map.destroy(); }; -exports["test that a BasicSourceMapConsumer is returned for sourcemaps without sections"] = async function(assert) { +exports[ + "test that a BasicSourceMapConsumer is returned for sourcemaps without sections" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMap); assert.ok(map instanceof BasicSourceMapConsumer); map.destroy(); }; -exports["test that an IndexedSourceMapConsumer is returned for sourcemaps with sections"] = async function(assert) { +exports[ + "test that an IndexedSourceMapConsumer is returned for sourcemaps with sections" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMap); assert.ok(map instanceof IndexedSourceMapConsumer); map.destroy(); }; -exports["test that the `sources` field has the original sources"] = async function(assert) { +exports[ + "test that the `sources` field has the original sources" +] = async function(assert) { let map; let sources; @@ -76,7 +90,9 @@ exports["test that the `sources` field has the original sources"] = async functi map.destroy(); }; -exports["test that the source root is reflected in a mapping's source field"] = async function(assert) { +exports[ + "test that the source root is reflected in a mapping's source field" +] = async function(assert) { let map; let mapping; @@ -95,7 +111,6 @@ exports["test that the source root is reflected in a mapping's source field"] = assert.equal(mapping.source, "/the/root/one.js"); map.destroy(); - map = await new SourceMapConsumer(util.testMapNoSourceRoot); mapping = map.originalPositionFor({ @@ -111,7 +126,6 @@ exports["test that the source root is reflected in a mapping's source field"] = assert.equal(mapping.source, "one.js"); map.destroy(); - map = await new SourceMapConsumer(util.testMapEmptySourceRoot); mapping = map.originalPositionFor({ @@ -134,10 +148,40 @@ exports["test mapping tokens back exactly"] = async function(assert) { util.assertMapping(1, 1, "/the/root/one.js", 1, 1, null, null, map, assert); util.assertMapping(1, 5, "/the/root/one.js", 1, 5, null, null, map, assert); util.assertMapping(1, 9, "/the/root/one.js", 1, 11, null, null, map, assert); - util.assertMapping(1, 18, "/the/root/one.js", 1, 21, "bar", null, map, assert); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 21, + "bar", + null, + map, + assert + ); util.assertMapping(1, 21, "/the/root/one.js", 2, 3, null, null, map, assert); - util.assertMapping(1, 28, "/the/root/one.js", 2, 10, "baz", null, map, assert); - util.assertMapping(1, 32, "/the/root/one.js", 2, 14, "bar", null, map, assert); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 10, + "baz", + null, + map, + assert + ); + util.assertMapping( + 1, + 32, + "/the/root/one.js", + 2, + 14, + "bar", + null, + map, + assert + ); util.assertMapping(2, 1, "/the/root/two.js", 1, 1, null, null, map, assert); util.assertMapping(2, 5, "/the/root/two.js", 1, 5, null, null, map, assert); @@ -149,16 +193,48 @@ exports["test mapping tokens back exactly"] = async function(assert) { map.destroy(); }; -exports["test mapping tokens back exactly in indexed source map"] = async function(assert) { +exports[ + "test mapping tokens back exactly in indexed source map" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMap); util.assertMapping(1, 1, "/the/root/one.js", 1, 1, null, null, map, assert); util.assertMapping(1, 5, "/the/root/one.js", 1, 5, null, null, map, assert); util.assertMapping(1, 9, "/the/root/one.js", 1, 11, null, null, map, assert); - util.assertMapping(1, 18, "/the/root/one.js", 1, 21, "bar", null, map, assert); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 21, + "bar", + null, + map, + assert + ); util.assertMapping(1, 21, "/the/root/one.js", 2, 3, null, null, map, assert); - util.assertMapping(1, 28, "/the/root/one.js", 2, 10, "baz", null, map, assert); - util.assertMapping(1, 32, "/the/root/one.js", 2, 14, "bar", null, map, assert); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 10, + "baz", + null, + map, + assert + ); + util.assertMapping( + 1, + 32, + "/the/root/one.js", + 2, + 14, + "bar", + null, + map, + assert + ); util.assertMapping(2, 1, "/the/root/two.js", 1, 1, null, null, map, assert); util.assertMapping(2, 5, "/the/root/two.js", 1, 5, null, null, map, assert); @@ -174,50 +250,328 @@ exports["test mapping tokens fuzzy"] = async function(assert) { const map = await new SourceMapConsumer(util.testMap); // Finding original positions with default (glb) bias. - util.assertMapping(1, 20, "/the/root/one.js", 1, 21, "bar", null, map, assert, true); - util.assertMapping(1, 30, "/the/root/one.js", 2, 10, "baz", null, map, assert, true); - util.assertMapping(2, 12, "/the/root/two.js", 1, 11, null, null, map, assert, true); + util.assertMapping( + 1, + 20, + "/the/root/one.js", + 1, + 21, + "bar", + null, + map, + assert, + true + ); + util.assertMapping( + 1, + 30, + "/the/root/one.js", + 2, + 10, + "baz", + null, + map, + assert, + true + ); + util.assertMapping( + 2, + 12, + "/the/root/two.js", + 1, + 11, + null, + null, + map, + assert, + true + ); // Finding original positions with lub bias. - util.assertMapping(1, 16, "/the/root/one.js", 1, 21, "bar", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); - util.assertMapping(1, 26, "/the/root/one.js", 2, 10, "baz", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); - util.assertMapping(2, 6, "/the/root/two.js", 1, 11, null, SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); + util.assertMapping( + 1, + 16, + "/the/root/one.js", + 1, + 21, + "bar", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); + util.assertMapping( + 1, + 26, + "/the/root/one.js", + 2, + 10, + "baz", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); + util.assertMapping( + 2, + 6, + "/the/root/two.js", + 1, + 11, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); // Finding generated positions with default (glb) bias. - util.assertMapping(1, 18, "/the/root/one.js", 1, 22, "bar", null, map, assert, null, true); - util.assertMapping(1, 28, "/the/root/one.js", 2, 13, "baz", null, map, assert, null, true); - util.assertMapping(2, 9, "/the/root/two.js", 1, 16, null, null, map, assert, null, true); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 22, + "bar", + null, + map, + assert, + null, + true + ); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 13, + "baz", + null, + map, + assert, + null, + true + ); + util.assertMapping( + 2, + 9, + "/the/root/two.js", + 1, + 16, + null, + null, + map, + assert, + null, + true + ); // Finding generated positions with lub bias. - util.assertMapping(1, 18, "/the/root/one.js", 1, 20, "bar", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); - util.assertMapping(1, 28, "/the/root/one.js", 2, 7, "baz", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); - util.assertMapping(2, 9, "/the/root/two.js", 1, 6, null, SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 20, + "bar", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 7, + "baz", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); + util.assertMapping( + 2, + 9, + "/the/root/two.js", + 1, + 6, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); map.destroy(); }; -exports["test mapping tokens fuzzy in indexed source map"] = async function(assert) { +exports["test mapping tokens fuzzy in indexed source map"] = async function( + assert +) { const map = await new SourceMapConsumer(util.indexedTestMap); // Finding original positions with default (glb) bias. - util.assertMapping(1, 20, "/the/root/one.js", 1, 21, "bar", null, map, assert, true); - util.assertMapping(1, 30, "/the/root/one.js", 2, 10, "baz", null, map, assert, true); - util.assertMapping(2, 12, "/the/root/two.js", 1, 11, null, null, map, assert, true); + util.assertMapping( + 1, + 20, + "/the/root/one.js", + 1, + 21, + "bar", + null, + map, + assert, + true + ); + util.assertMapping( + 1, + 30, + "/the/root/one.js", + 2, + 10, + "baz", + null, + map, + assert, + true + ); + util.assertMapping( + 2, + 12, + "/the/root/two.js", + 1, + 11, + null, + null, + map, + assert, + true + ); // Finding original positions with lub bias. - util.assertMapping(1, 16, "/the/root/one.js", 1, 21, "bar", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); - util.assertMapping(1, 26, "/the/root/one.js", 2, 10, "baz", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); - util.assertMapping(2, 6, "/the/root/two.js", 1, 11, null, SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, true); + util.assertMapping( + 1, + 16, + "/the/root/one.js", + 1, + 21, + "bar", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); + util.assertMapping( + 1, + 26, + "/the/root/one.js", + 2, + 10, + "baz", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); + util.assertMapping( + 2, + 6, + "/the/root/two.js", + 1, + 11, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + true + ); // Finding generated positions with default (glb) bias. - util.assertMapping(1, 18, "/the/root/one.js", 1, 22, "bar", null, map, assert, null, true); - util.assertMapping(1, 28, "/the/root/one.js", 2, 13, "baz", null, map, assert, null, true); - util.assertMapping(2, 9, "/the/root/two.js", 1, 16, null, null, map, assert, null, true); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 22, + "bar", + null, + map, + assert, + null, + true + ); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 13, + "baz", + null, + map, + assert, + null, + true + ); + util.assertMapping( + 2, + 9, + "/the/root/two.js", + 1, + 16, + null, + null, + map, + assert, + null, + true + ); // Finding generated positions with lub bias. - util.assertMapping(1, 18, "/the/root/one.js", 1, 20, "bar", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); - util.assertMapping(1, 28, "/the/root/one.js", 2, 7, "baz", SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); - util.assertMapping(2, 9, "/the/root/two.js", 1, 6, null, SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); + util.assertMapping( + 1, + 18, + "/the/root/one.js", + 1, + 20, + "bar", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); + util.assertMapping( + 1, + 28, + "/the/root/one.js", + 2, + 7, + "baz", + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); + util.assertMapping( + 2, + 9, + "/the/root/two.js", + 1, + 6, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); map.destroy(); }; @@ -251,13 +605,29 @@ exports["test mappings and end of lines"] = async function(assert) { util.assertMapping(1, 1, "bar.js", 2, 1, null, null, map, assert, null, true); // When finding generated positions with, mappings end at the end of the source. - util.assertMapping(null, null, "bar.js", 3, 1, null, SourceMapConsumer.LEAST_UPPER_BOUND, map, assert, null, true); + util.assertMapping( + null, + null, + "bar.js", + 3, + 1, + null, + SourceMapConsumer.LEAST_UPPER_BOUND, + map, + assert, + null, + true + ); map.destroy(); }; -exports["test creating source map consumers with )]}' prefix"] = async function(assert) { - const map = await new SourceMapConsumer(")]}'\n" + JSON.stringify(util.testMap)); +exports["test creating source map consumers with )]}' prefix"] = async function( + assert +) { + const map = await new SourceMapConsumer( + ")]}'\n" + JSON.stringify(util.testMap) + ); assert.ok(true); map.destroy(); }; @@ -271,7 +641,10 @@ exports["test eachMapping"] = async function(assert) { map.eachMapping(function(mapping) { assert.ok(mapping.generatedLine >= previousLine); - assert.ok(mapping.source === "/the/root/one.js" || mapping.source === "/the/root/two.js"); + assert.ok( + mapping.source === "/the/root/one.js" || + mapping.source === "/the/root/two.js" + ); if (mapping.generatedLine === previousLine) { assert.ok(mapping.generatedColumn >= previousColumn); @@ -297,7 +670,11 @@ exports["test eachMapping"] = async function(assert) { map = await new SourceMapConsumer(util.mapWithSourcelessMapping); map.eachMapping(function(mapping) { - assert.ok(mapping.source === null || (typeof mapping.originalColumn === "number" && typeof mapping.originalLine === "number")); + assert.ok( + mapping.source === null || + (typeof mapping.originalColumn === "number" && + typeof mapping.originalLine === "number") + ); }); map.destroy(); }; @@ -333,7 +710,9 @@ exports["test eachMapping for indexed source maps"] = async function(assert) { map.destroy(); }; -exports["test eachMapping for indexed source maps with column offsets"] = async function(assert) { +exports[ + "test eachMapping for indexed source maps with column offsets" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMapColumnOffset); map.computeColumnSpans(); let previousLine = -Infinity; @@ -364,63 +743,77 @@ exports["test eachMapping for indexed source maps with column offsets"] = async map.destroy(); }; -exports["test iterating over mappings in a different order"] = async function(assert) { +exports["test iterating over mappings in a different order"] = async function( + assert +) { const map = await new SourceMapConsumer(util.testMap); let previousLine = -Infinity; let previousColumn = -Infinity; let previousSource = ""; - map.eachMapping(function(mapping) { - assert.ok(mapping.source >= previousSource); + map.eachMapping( + function(mapping) { + assert.ok(mapping.source >= previousSource); - if (mapping.source === previousSource) { - assert.ok(mapping.originalLine >= previousLine); + if (mapping.source === previousSource) { + assert.ok(mapping.originalLine >= previousLine); - if (mapping.originalLine === previousLine) { - assert.ok(mapping.originalColumn >= previousColumn); - previousColumn = mapping.originalColumn; + if (mapping.originalLine === previousLine) { + assert.ok(mapping.originalColumn >= previousColumn); + previousColumn = mapping.originalColumn; + } else { + previousLine = mapping.originalLine; + previousColumn = -Infinity; + } } else { - previousLine = mapping.originalLine; + previousSource = mapping.source; + previousLine = -Infinity; previousColumn = -Infinity; } - } else { - previousSource = mapping.source; - previousLine = -Infinity; - previousColumn = -Infinity; - } - }, null, SourceMapConsumer.ORIGINAL_ORDER); + }, + null, + SourceMapConsumer.ORIGINAL_ORDER + ); map.destroy(); }; -exports["test iterating over mappings in a different order in indexed source maps"] = async function(assert) { +exports[ + "test iterating over mappings in a different order in indexed source maps" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMap); let previousLine = -Infinity; let previousColumn = -Infinity; let previousSource = ""; - map.eachMapping(function(mapping) { - assert.ok(mapping.source >= previousSource); - - if (mapping.source === previousSource) { - assert.ok(mapping.originalLine >= previousLine); - - if (mapping.originalLine === previousLine) { - assert.ok(mapping.originalColumn >= previousColumn); - previousColumn = mapping.originalColumn; + map.eachMapping( + function(mapping) { + assert.ok(mapping.source >= previousSource); + + if (mapping.source === previousSource) { + assert.ok(mapping.originalLine >= previousLine); + + if (mapping.originalLine === previousLine) { + assert.ok(mapping.originalColumn >= previousColumn); + previousColumn = mapping.originalColumn; + } else { + previousLine = mapping.originalLine; + previousColumn = -Infinity; + } } else { - previousLine = mapping.originalLine; + previousSource = mapping.source; + previousLine = -Infinity; previousColumn = -Infinity; } - } else { - previousSource = mapping.source; - previousLine = -Infinity; - previousColumn = -Infinity; - } - }, null, SourceMapConsumer.ORIGINAL_ORDER); + }, + null, + SourceMapConsumer.ORIGINAL_ORDER + ); map.destroy(); }; -exports["test that we can set the context for `this` in eachMapping"] = async function(assert) { +exports[ + "test that we can set the context for `this` in eachMapping" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMap); const context = {}; map.eachMapping(function() { @@ -429,7 +822,9 @@ exports["test that we can set the context for `this` in eachMapping"] = async fu map.destroy(); }; -exports["test that we can set the context for `this` in eachMapping in indexed source maps"] = async function(assert) { +exports[ + "test that we can set the context for `this` in eachMapping in indexed source maps" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMap); const context = {}; map.eachMapping(function() { @@ -438,25 +833,47 @@ exports["test that we can set the context for `this` in eachMapping in indexed s map.destroy(); }; -exports["test that the `sourcesContent` field has the original sources"] = async function(assert) { +exports[ + "test that the `sourcesContent` field has the original sources" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMapWithSourcesContent); const sourcesContent = map.sourcesContent; - assert.equal(sourcesContent[0], " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(sourcesContent[1], " TWO.inc = function (n) {\n return n + 1;\n };"); + assert.equal( + sourcesContent[0], + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + sourcesContent[1], + " TWO.inc = function (n) {\n return n + 1;\n };" + ); assert.equal(sourcesContent.length, 2); map.destroy(); }; -exports["test that we can get the original sources for the sources"] = async function(assert) { +exports[ + "test that we can get the original sources for the sources" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMapWithSourcesContent); const sources = map.sources; - assert.equal(map.sourceContentFor(sources[0]), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor(sources[1]), " TWO.inc = function (n) {\n return n + 1;\n };"); - assert.equal(map.sourceContentFor("one.js"), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor("two.js"), " TWO.inc = function (n) {\n return n + 1;\n };"); + assert.equal( + map.sourceContentFor(sources[0]), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor(sources[1]), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); + assert.equal( + map.sourceContentFor("one.js"), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor("two.js"), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); assert.throws(function() { map.sourceContentFor(""); }, Error); @@ -470,14 +887,28 @@ exports["test that we can get the original sources for the sources"] = async fun map.destroy(); }; -exports["test that we can get the original source content with relative source paths"] = async function(assert) { +exports[ + "test that we can get the original source content with relative source paths" +] = async function(assert) { const map = await new SourceMapConsumer(util.testMapRelativeSources); const sources = map.sources; - assert.equal(map.sourceContentFor(sources[0]), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor(sources[1]), " TWO.inc = function (n) {\n return n + 1;\n };"); - assert.equal(map.sourceContentFor("one.js"), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor("two.js"), " TWO.inc = function (n) {\n return n + 1;\n };"); + assert.equal( + map.sourceContentFor(sources[0]), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor(sources[1]), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); + assert.equal( + map.sourceContentFor("one.js"), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor("two.js"), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); assert.throws(function() { map.sourceContentFor(""); }, Error); @@ -491,14 +922,28 @@ exports["test that we can get the original source content with relative source p map.destroy(); }; -exports["test that we can get the original source content for the sources on an indexed source map"] = async function(assert) { +exports[ + "test that we can get the original source content for the sources on an indexed source map" +] = async function(assert) { const map = await new SourceMapConsumer(util.indexedTestMap); const sources = map.sources; - assert.equal(map.sourceContentFor(sources[0]), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor(sources[1]), " TWO.inc = function (n) {\n return n + 1;\n };"); - assert.equal(map.sourceContentFor("one.js"), " ONE.foo = function (bar) {\n return baz(bar);\n };"); - assert.equal(map.sourceContentFor("two.js"), " TWO.inc = function (n) {\n return n + 1;\n };"); + assert.equal( + map.sourceContentFor(sources[0]), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor(sources[1]), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); + assert.equal( + map.sourceContentFor("one.js"), + " ONE.foo = function (bar) {\n return baz(bar);\n };" + ); + assert.equal( + map.sourceContentFor("two.js"), + " TWO.inc = function (n) {\n return n + 1;\n };" + ); assert.throws(function() { map.sourceContentFor(""); }, Error); @@ -512,12 +957,16 @@ exports["test that we can get the original source content for the sources on an map.destroy(); }; -exports["test hasContentsOfAllSources, single source with contents"] = async function(assert) { +exports[ + "test hasContentsOfAllSources, single source with contents" +] = async function(assert) { // Has one source: foo.js (with contents). const mapWithContents = new SourceMapGenerator(); - mapWithContents.addMapping({ source: "foo.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); + mapWithContents.addMapping({ + source: "foo.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); mapWithContents.setSourceContent("foo.js", "content of foo.js"); const consumer = await new SourceMapConsumer(mapWithContents.toJSON()); @@ -525,26 +974,36 @@ exports["test hasContentsOfAllSources, single source with contents"] = async fun consumer.destroy(); }; -exports["test hasContentsOfAllSources, single source without contents"] = async function(assert) { +exports[ + "test hasContentsOfAllSources, single source without contents" +] = async function(assert) { // Has one source: foo.js (without contents). const mapWithoutContents = new SourceMapGenerator(); - mapWithoutContents.addMapping({ source: "foo.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); + mapWithoutContents.addMapping({ + source: "foo.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); const consumer = await new SourceMapConsumer(mapWithoutContents.toJSON()); assert.ok(!consumer.hasContentsOfAllSources()); consumer.destroy(); }; -exports["test hasContentsOfAllSources, two sources with contents"] = async function(assert) { +exports[ + "test hasContentsOfAllSources, two sources with contents" +] = async function(assert) { // Has two sources: foo.js (with contents) and bar.js (with contents). const mapWithBothContents = new SourceMapGenerator(); - mapWithBothContents.addMapping({ source: "foo.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); - mapWithBothContents.addMapping({ source: "bar.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); + mapWithBothContents.addMapping({ + source: "foo.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); + mapWithBothContents.addMapping({ + source: "bar.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); mapWithBothContents.setSourceContent("foo.js", "content of foo.js"); mapWithBothContents.setSourceContent("bar.js", "content of bar.js"); const consumer = await new SourceMapConsumer(mapWithBothContents.toJSON()); @@ -552,15 +1011,21 @@ exports["test hasContentsOfAllSources, two sources with contents"] = async funct consumer.destroy(); }; -exports["test hasContentsOfAllSources, two sources one with and one without contents"] = async function(assert) { +exports[ + "test hasContentsOfAllSources, two sources one with and one without contents" +] = async function(assert) { // Has two sources: foo.js (with contents) and bar.js (without contents). const mapWithoutSomeContents = new SourceMapGenerator(); - mapWithoutSomeContents.addMapping({ source: "foo.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); - mapWithoutSomeContents.addMapping({ source: "bar.js", - original: { line: 1, column: 10 }, - generated: { line: 1, column: 10 } }); + mapWithoutSomeContents.addMapping({ + source: "foo.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); + mapWithoutSomeContents.addMapping({ + source: "bar.js", + original: { line: 1, column: 10 }, + generated: { line: 1, column: 10 } + }); mapWithoutSomeContents.setSourceContent("foo.js", "content of foo.js"); const consumer = await new SourceMapConsumer(mapWithoutSomeContents.toJSON()); assert.ok(!consumer.hasContentsOfAllSources()); @@ -583,7 +1048,6 @@ exports["test sourceRoot + generatedPositionFor"] = async function(assert) { source: "bang.coffee" }); - map = await new SourceMapConsumer(map.toString(), "http://example.com/"); // Should handle without sourceRoot. @@ -619,7 +1083,9 @@ exports["test sourceRoot + generatedPositionFor"] = async function(assert) { map.destroy(); }; -exports["test sourceRoot + generatedPositionFor for path above the root"] = async function(assert) { +exports[ + "test sourceRoot + generatedPositionFor for path above the root" +] = async function(assert) { let map = new SourceMapGenerator({ sourceRoot: "foo/bar", file: "baz.js" @@ -646,7 +1112,10 @@ exports["test sourceRoot + generatedPositionFor for path above the root"] = asyn }; exports["test index map + generatedPositionFor"] = async function(assert) { - const map = await new SourceMapConsumer(util.indexedTestMapColumnOffset, "http://example.com/"); + const map = await new SourceMapConsumer( + util.indexedTestMapColumnOffset, + "http://example.com/" + ); map.computeColumnSpans(); let pos = map.generatedPositionFor({ @@ -749,7 +1218,9 @@ exports["test allGeneratedPositionsFor for line"] = async function(assert) { map.destroy(); }; -exports["test allGeneratedPositionsFor for line fuzzy"] = async function(assert) { +exports["test allGeneratedPositionsFor for line fuzzy"] = async function( + assert +) { let map = new SourceMapGenerator({ file: "generated.js" }); @@ -783,7 +1254,9 @@ exports["test allGeneratedPositionsFor for line fuzzy"] = async function(assert) map.destroy(); }; -exports["test allGeneratedPositionsFor for empty source map"] = async function(assert) { +exports["test allGeneratedPositionsFor for empty source map"] = async function( + assert +) { let map = new SourceMapGenerator({ file: "generated.js" }); @@ -831,7 +1304,9 @@ exports["test allGeneratedPositionsFor for column"] = async function(assert) { map.destroy(); }; -exports["test allGeneratedPositionsFor for column fuzzy"] = async function(assert) { +exports["test allGeneratedPositionsFor for column fuzzy"] = async function( + assert +) { let map = new SourceMapGenerator({ file: "generated.js" }); @@ -863,7 +1338,9 @@ exports["test allGeneratedPositionsFor for column fuzzy"] = async function(asser map.destroy(); }; -exports["test allGeneratedPositionsFor for column on different line fuzzy"] = async function(assert) { +exports[ + "test allGeneratedPositionsFor for column on different line fuzzy" +] = async function(assert) { let map = new SourceMapGenerator({ file: "generated.js" }); @@ -891,7 +1368,9 @@ exports["test allGeneratedPositionsFor for column on different line fuzzy"] = as map.destroy(); }; -exports["test allGeneratedPositionsFor for index map"] = async function(assert) { +exports["test allGeneratedPositionsFor for index map"] = async function( + assert +) { const map = await new SourceMapConsumer(util.indexedTestMapColumnOffset); map.computeColumnSpans(); @@ -905,7 +1384,7 @@ exports["test allGeneratedPositionsFor for index map"] = async function(assert) { line: 1, column: 21, - lastColumn: 27, + lastColumn: 27 } ]); @@ -933,7 +1412,7 @@ exports["test allGeneratedPositionsFor for index map"] = async function(assert) { line: 1, column: 71, - lastColumn: 77, + lastColumn: 77 } ]); @@ -947,7 +1426,7 @@ exports["test allGeneratedPositionsFor for index map"] = async function(assert) { line: 1, column: 78, - lastColumn: Infinity, + lastColumn: Infinity } ]); @@ -1038,7 +1517,7 @@ exports["test sourceRoot + originalPositionFor"] = async function(assert) { const pos = map.originalPositionFor({ line: 2, - column: 2, + column: 2 }); // Should always have the prepended source root @@ -1058,16 +1537,18 @@ exports["test source resolution with sourceMapURL"] = async function(assert) { map.addMapping({ original: { line: 1, column: 1 }, generated: { line: 2, column: 2 }, - source: "original.js", + source: "original.js" }); map = await new SourceMapConsumer(map.toString(), "http://cdn.example.com"); const sources = map.sources; - assert.equal(sources.length, 1, - "Should only be one source."); - assert.equal(sources[0], "http://cdn.example.com/original.js", - "Should be joined with the source map URL."); + assert.equal(sources.length, 1, "Should only be one source."); + assert.equal( + sources[0], + "http://cdn.example.com/original.js", + "Should be joined with the source map URL." + ); map.destroy(); }; @@ -1086,17 +1567,23 @@ exports["test sourceRoot prepending"] = async function(assert) { map = await new SourceMapConsumer(map.toString()); const sources = map.sources; - assert.equal(sources.length, 1, - "Should only be one source."); - assert.equal(sources[0], "http://example.com/foo/bar/original.js", - "Source include the source root."); + assert.equal(sources.length, 1, "Should only be one source."); + assert.equal( + sources[0], + "http://example.com/foo/bar/original.js", + "Source include the source root." + ); map.destroy(); }; -exports["test indexed source map errors when sections are out of order by line"] = async function(assert) { +exports[ + "test indexed source map errors when sections are out of order by line" +] = async function(assert) { // Make a deep copy of the indexedTestMap - const misorderedIndexedTestMap = JSON.parse(JSON.stringify(util.indexedTestMap)); + const misorderedIndexedTestMap = JSON.parse( + JSON.stringify(util.indexedTestMap) + ); misorderedIndexedTestMap.sections[0].offset = { line: 2, @@ -1114,13 +1601,13 @@ exports["test indexed source map errors when sections are out of order by line"] exports["test github issue #64"] = async function(assert) { const map = await new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sourceRoot": "http://example.com/", - "sources": ["/a"], - "names": [], - "mappings": "AACA", - "sourcesContent": ["foo"] + version: 3, + file: "foo.js", + sourceRoot: "http://example.com/", + sources: ["/a"], + names: [], + mappings: "AACA", + sourcesContent: ["foo"] }); assert.equal(map.sourceContentFor("a"), "foo"); @@ -1130,31 +1617,37 @@ exports["test github issue #64"] = async function(assert) { }; exports["test full source content with sourceMapURL"] = async function(assert) { - const map = await new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sourceRoot": "", - "sources": ["original.js"], - "names": [], - "mappings": "AACA", - "sourcesContent": ["yellow warbler"] - }, "http://cdn.example.com"); - - assert.equal(map.sourceContentFor("http://cdn.example.com/original.js"), "yellow warbler", - "Source content should be found using full URL"); + const map = await new SourceMapConsumer( + { + version: 3, + file: "foo.js", + sourceRoot: "", + sources: ["original.js"], + names: [], + mappings: "AACA", + sourcesContent: ["yellow warbler"] + }, + "http://cdn.example.com" + ); + + assert.equal( + map.sourceContentFor("http://cdn.example.com/original.js"), + "yellow warbler", + "Source content should be found using full URL" + ); map.destroy(); }; exports["test bug 885597"] = async function(assert) { const map = await new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sourceRoot": "file:///Users/AlGore/Invented/The/Internet/", - "sources": ["/a"], - "names": [], - "mappings": "AACA", - "sourcesContent": ["foo"] + version: 3, + file: "foo.js", + sourceRoot: "file:///Users/AlGore/Invented/The/Internet/", + sources: ["/a"], + names: [], + mappings: "AACA", + sourcesContent: ["foo"] }); const s = map.sources[0]; @@ -1165,12 +1658,12 @@ exports["test bug 885597"] = async function(assert) { exports["test github issue #72, duplicate sources"] = async function(assert) { const map = await new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sources": ["source1.js", "source1.js", "source3.js"], - "names": [], - "mappings": ";EAAC;;IAEE;;MEEE", - "sourceRoot": "http://example.com" + version: 3, + file: "foo.js", + sources: ["source1.js", "source1.js", "source3.js"], + names: [], + mappings: ";EAAC;;IAEE;;MEEE", + sourceRoot: "http://example.com" }); let pos = map.originalPositionFor({ @@ -1202,12 +1695,12 @@ exports["test github issue #72, duplicate sources"] = async function(assert) { exports["test github issue #72, duplicate names"] = async function(assert) { const map = await new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sources": ["source.js"], - "names": ["name1", "name1", "name3"], - "mappings": ";EAACA;;IAEEA;;MAEEE", - "sourceRoot": "http://example.com" + version: 3, + file: "foo.js", + sources: ["source.js"], + names: ["name1", "name1", "name3"], + mappings: ";EAACA;;IAEEA;;MAEEE", + sourceRoot: "http://example.com" }); let pos = map.originalPositionFor({ @@ -1303,13 +1796,13 @@ exports["test SourceMapConsumer.fromSourceMap"] = async function(assert) { exports["test issue #191"] = async function(assert) { const generator = new SourceMapGenerator({ file: "a.css" }); generator.addMapping({ - source: "b.css", + source: "b.css", original: { - line: 1, + line: 1, column: 0 }, generated: { - line: 1, + line: 1, column: 0 } }); @@ -1320,21 +1813,25 @@ exports["test issue #191"] = async function(assert) { // throw. generator.toJSON(); - assert.ok(true, "Using a SourceMapGenerator again after creating a " + - "SourceMapConsumer from it should not throw"); + assert.ok( + true, + "Using a SourceMapGenerator again after creating a SourceMapConsumer from it should not throw" + ); consumer.destroy(); }; -exports["test sources where their prefix is the source root: issue #199"] = async function(assert) { +exports[ + "test sources where their prefix is the source root: issue #199" +] = async function(assert) { const testSourceMap = { - "version": 3, - "sources": ["/source/app/app/app.js"], - "names": ["System"], - "mappings": "AAAAA", - "file": "app/app.js", - "sourcesContent": ["'use strict';"], - "sourceRoot": "/source/" + version: 3, + sources: ["/source/app/app/app.js"], + names: ["System"], + mappings: "AAAAA", + file: "app/app.js", + sourcesContent: ["'use strict';"], + sourceRoot: "/source/" }; const consumer = await new SourceMapConsumer(testSourceMap); @@ -1349,14 +1846,16 @@ exports["test sources where their prefix is the source root: issue #199"] = asyn consumer.destroy(); }; -exports["test sources where their prefix is the source root and the source root is a url: issue #199"] = async function(assert) { +exports[ + "test sources where their prefix is the source root and the source root is a url: issue #199" +] = async function(assert) { const testSourceMap = { - "version": 3, - "sources": ["http://example.com/source/app/app/app.js"], - "names": ["System"], - "mappings": "AAAAA", - "sourcesContent": ["'use strict';"], - "sourceRoot": "http://example.com/source/" + version: 3, + sources: ["http://example.com/source/app/app/app.js"], + names: ["System"], + mappings: "AAAAA", + sourcesContent: ["'use strict';"], + sourceRoot: "http://example.com/source/" }; const consumer = await new SourceMapConsumer(testSourceMap); @@ -1371,12 +1870,14 @@ exports["test sources where their prefix is the source root and the source root consumer.destroy(); }; -exports["test consuming names and sources that are numbers"] = async function(assert) { +exports["test consuming names and sources that are numbers"] = async function( + assert +) { const testSourceMap = { - "version": 3, - "sources": [0], - "names": [1], - "mappings": "AAAAA", + version: 3, + sources: [0], + names: [1], + mappings: "AAAAA" }; const consumer = await new SourceMapConsumer(testSourceMap); @@ -1394,15 +1895,17 @@ exports["test consuming names and sources that are numbers"] = async function(as consumer.destroy(); }; -exports["test non-normalized sourceRoot (from issue #227)"] = async function(assert) { +exports["test non-normalized sourceRoot (from issue #227)"] = async function( + assert +) { const consumer = await new SourceMapConsumer({ version: 3, - sources: [ "index.js" ], + sources: ["index.js"], names: [], mappings: ";;AAAA,IAAI,OAAO,MAAP", file: "index.js", sourceRoot: "./src/", - sourcesContent: [ 'var name = "Mark"\n' ] + sourcesContent: ['var name = "Mark"\n'] }); assert.doesNotThrow(() => { // Before the fix, this threw an exception. @@ -1415,7 +1918,7 @@ exports["test non-normalized sourceRoot (from issue #227)"] = async function(ass exports["test webpack URL resolution"] = async function(assert) { const map = { version: 3, - sources: ["webpack:///webpack/bootstrap 67e184f9679733298d44"], + sources: ["webpack:///webpack/bootstrap 67e184f9679733298d44"], names: [], mappings: "CAAS", file: "static/js/manifest.b7cf97680f7a50fa150f.js", @@ -1424,38 +1927,54 @@ exports["test webpack URL resolution"] = async function(assert) { const consumer = await new SourceMapConsumer(map); assert.equal(consumer.sources.length, 1); - assert.equal(consumer.sources[0], "webpack:///webpack/bootstrap%2067e184f9679733298d44"); + assert.equal( + consumer.sources[0], + "webpack:///webpack/bootstrap%2067e184f9679733298d44" + ); consumer.destroy(); }; -exports["test webpack URL resolution with sourceMapURL"] = async function(assert) { +exports["test webpack URL resolution with sourceMapURL"] = async function( + assert +) { const map = { version: 3, - sources: ["webpack:///webpack/bootstrap 67e184f9679733298d44"], + sources: ["webpack:///webpack/bootstrap 67e184f9679733298d44"], names: [], mappings: "CAAS", file: "static/js/manifest.b7cf97680f7a50fa150f.js", sourceRoot: "" }; - const consumer = await new SourceMapConsumer(map, "http://www.example.com/q.js.map"); + const consumer = await new SourceMapConsumer( + map, + "http://www.example.com/q.js.map" + ); assert.equal(consumer.sources.length, 1); - assert.equal(consumer.sources[0], "webpack:///webpack/bootstrap%2067e184f9679733298d44"); + assert.equal( + consumer.sources[0], + "webpack:///webpack/bootstrap%2067e184f9679733298d44" + ); consumer.destroy(); }; -exports["test relative webpack URL resolution with sourceMapURL"] = async function(assert) { +exports[ + "test relative webpack URL resolution with sourceMapURL" +] = async function(assert) { const map = { version: 3, - sources: ["webpack/bootstrap.js"], + sources: ["webpack/bootstrap.js"], names: [], mappings: "CAAS", file: "static/js/manifest.b7cf97680f7a50fa150f.js", sourceRoot: "webpack:///" }; - const consumer = await new SourceMapConsumer(map, "http://www.example.com/q.js.map"); + const consumer = await new SourceMapConsumer( + map, + "http://www.example.com/q.js.map" + ); assert.equal(consumer.sources.length, 1); assert.equal(consumer.sources[0], "webpack:///webpack/bootstrap.js"); @@ -1463,33 +1982,46 @@ exports["test relative webpack URL resolution with sourceMapURL"] = async functi consumer.destroy(); }; -exports["test basic URL resolution with sourceMapURL"] = async function(assert) { +exports["test basic URL resolution with sourceMapURL"] = async function( + assert +) { const map = { version: 3, - sources: ["something.js"], + sources: ["something.js"], names: [], mappings: "CAAS", file: "static/js/manifest.b7cf97680f7a50fa150f.js", sourceRoot: "src" }; - const consumer = await new SourceMapConsumer(map, "http://www.example.com/x/q.js.map"); + const consumer = await new SourceMapConsumer( + map, + "http://www.example.com/x/q.js.map" + ); assert.equal(consumer.sources.length, 1); - assert.equal(consumer.sources[0], "http://www.example.com/x/src/something.js"); + assert.equal( + consumer.sources[0], + "http://www.example.com/x/src/something.js" + ); consumer.destroy(); }; -exports["test absolute sourceURL resolution with sourceMapURL"] = async function(assert) { +exports[ + "test absolute sourceURL resolution with sourceMapURL" +] = async function(assert) { const map = { version: 3, - sources: ["something.js"], + sources: ["something.js"], names: [], mappings: "CAAS", file: "static/js/manifest.b7cf97680f7a50fa150f.js", sourceRoot: "http://www.example.com/src" }; - const consumer = await new SourceMapConsumer(map, "http://www.example.com/x/q.js.map"); + const consumer = await new SourceMapConsumer( + map, + "http://www.example.com/x/q.js.map" + ); assert.equal(consumer.sources.length, 1); assert.equal(consumer.sources[0], "http://www.example.com/src/something.js"); @@ -1500,10 +2032,10 @@ exports["test absolute sourceURL resolution with sourceMapURL"] = async function exports["test line numbers > 2**32"] = async function(assert) { const map = await new SourceMapConsumer({ version: 3, - sources: ["something.js"], + sources: ["something.js"], names: [], mappings: "C+/////DAS", - file: "foo.js", + file: "foo.js" }); let error; @@ -1521,10 +2053,10 @@ exports["test line numbers > 2**32"] = async function(assert) { exports["test line numbers < 0"] = async function(assert) { const map = await new SourceMapConsumer({ version: 3, - sources: ["something.js"], + sources: ["something.js"], names: [], mappings: "CDAS", - file: "foo.js", + file: "foo.js" }); let error; @@ -1541,7 +2073,9 @@ exports["test line numbers < 0"] = async function(assert) { exports["test SourceMapConsumer.with"] = async function(assert) { let consumer = null; - const six = await SourceMapConsumer.with(util.testMap, null, async function(c) { + const six = await SourceMapConsumer.with(util.testMap, null, async function( + c + ) { // Don't keep references to the consumer around at home, kids. consumer = c; diff --git a/test/test-source-map-generator.js b/test/test-source-map-generator.js index 383a828e..4af47f98 100644 --- a/test/test-source-map-generator.js +++ b/test/test-source-map-generator.js @@ -5,8 +5,10 @@ * http://opensource.org/licenses/BSD-3-Clause */ -const SourceMapGenerator = require("../lib/source-map-generator").SourceMapGenerator; -const SourceMapConsumer = require("../lib/source-map-consumer").SourceMapConsumer; +const SourceMapGenerator = require("../lib/source-map-generator") + .SourceMapGenerator; +const SourceMapConsumer = require("../lib/source-map-consumer") + .SourceMapConsumer; const SourceNode = require("../lib/source-node").SourceNode; const util = require("./util"); @@ -116,7 +118,9 @@ exports["test adding mappings with skipValidation"] = function(assert) { }, /Invalid mapping/); }; -exports["test that the correct mappings are being generated"] = function(assert) { +exports["test that the correct mappings are being generated"] = function( + assert +) { let map = new SourceMapGenerator({ file: "min.js", sourceRoot: "/the/root" @@ -199,7 +203,9 @@ exports["test that the correct mappings are being generated"] = function(assert) util.assertEqualMaps(assert, map, util.testMap); }; -exports["test that adding a mapping with an empty string name does not break generation"] = function(assert) { +exports[ + "test that adding a mapping with an empty string name does not break generation" +] = function(assert) { const map = new SourceMapGenerator({ file: "generated-foo.js", sourceRoot: "." @@ -269,18 +275,34 @@ exports["test .fromSourceMap with empty mappings"] = async function(assert) { util.assertEqualMaps(assert, map.toJSON(), util.testMapEmptyMappings); }; -exports["test .fromSourceMap with empty mappings and relative sources"] = async function(assert) { - const smc = await new SourceMapConsumer(util.testMapEmptyMappingsRelativeSources); +exports[ + "test .fromSourceMap with empty mappings and relative sources" +] = async function(assert) { + const smc = await new SourceMapConsumer( + util.testMapEmptyMappingsRelativeSources + ); const map = SourceMapGenerator.fromSourceMap(smc); smc.destroy(); - util.assertEqualMaps(assert, map.toJSON(), util.testMapEmptyMappingsRelativeSources_generatedExpected); + util.assertEqualMaps( + assert, + map.toJSON(), + util.testMapEmptyMappingsRelativeSources_generatedExpected + ); }; -exports["test .fromSourceMap with multiple sources where mappings refers only to single source"] = async function(assert) { - const smc = await new SourceMapConsumer(util.testMapMultiSourcesMappingRefersSingleSourceOnly); +exports[ + "test .fromSourceMap with multiple sources where mappings refers only to single source" +] = async function(assert) { + const smc = await new SourceMapConsumer( + util.testMapMultiSourcesMappingRefersSingleSourceOnly + ); const map = SourceMapGenerator.fromSourceMap(smc); smc.destroy(); - util.assertEqualMaps(assert, map.toJSON(), util.testMapMultiSourcesMappingRefersSingleSourceOnly); + util.assertEqualMaps( + assert, + map.toJSON(), + util.testMapMultiSourcesMappingRefersSingleSourceOnly + ); }; exports["test applySourceMap"] = async function(assert) { @@ -345,7 +367,9 @@ exports["test applySourceMap"] = async function(assert) { util.assertEqualMaps(assert, actualMap, expectedMap); }; -exports["test applySourceMap throws when file is missing"] = async function(assert) { +exports["test applySourceMap throws when file is missing"] = async function( + assert +) { const map = new SourceMapGenerator({ file: "test.js" }); @@ -363,7 +387,9 @@ exports["test applySourceMap throws when file is missing"] = async function(asse assert.ok(error instanceof Error); }; -exports["test the two additional parameters of applySourceMap"] = async function(assert) { +exports[ + "test the two additional parameters of applySourceMap" +] = async function(assert) { // Assume the following directory structure: // // http://foo.org/ @@ -402,10 +428,7 @@ exports["test the two additional parameters of applySourceMap"] = async function original: { line: 22, column: 22 }, source: "http://www.example.com/baz.coffee" }); - bundleMap.setSourceContent( - "http://www.example.com/baz.coffee", - "baz coffee" - ); + bundleMap.setSourceContent("http://www.example.com/baz.coffee", "baz coffee"); bundleMap = await new SourceMapConsumer(bundleMap.toJSON()); let minifiedMap = new SourceMapGenerator({ @@ -463,50 +486,78 @@ exports["test the two additional parameters of applySourceMap"] = async function return map.toJSON(); }; - util.assertEqualMaps(assert, actualMap("../temp/temp_maps"), expectedMap([ - "coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); + util.assertEqualMaps( + assert, + actualMap("../temp/temp_maps"), + expectedMap([ + "coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); - util.assertEqualMaps(assert, actualMap("/app/temp/temp_maps"), expectedMap([ - "/app/coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); + util.assertEqualMaps( + assert, + actualMap("/app/temp/temp_maps"), + expectedMap([ + "/app/coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); - util.assertEqualMaps(assert, actualMap("http://foo.org/app/temp/temp_maps"), expectedMap([ - "http://foo.org/app/coffee/foo.coffee", - "http://foo.org/bar.coffee", - "http://www.example.com/baz.coffee" - ])); + util.assertEqualMaps( + assert, + actualMap("http://foo.org/app/temp/temp_maps"), + expectedMap([ + "http://foo.org/app/coffee/foo.coffee", + "http://foo.org/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); // If the third parameter is omitted or set to the current working // directory we get incorrect source paths: - util.assertEqualMaps(assert, actualMap(), expectedMap([ - "../coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); - - util.assertEqualMaps(assert, actualMap(""), expectedMap([ - "../coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); - - util.assertEqualMaps(assert, actualMap("."), expectedMap([ - "../coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); - - util.assertEqualMaps(assert, actualMap("./"), expectedMap([ - "../coffee/foo.coffee", - "/bar.coffee", - "http://www.example.com/baz.coffee" - ])); + util.assertEqualMaps( + assert, + actualMap(), + expectedMap([ + "../coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); + + util.assertEqualMaps( + assert, + actualMap(""), + expectedMap([ + "../coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); + + util.assertEqualMaps( + assert, + actualMap("."), + expectedMap([ + "../coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); + + util.assertEqualMaps( + assert, + actualMap("./"), + expectedMap([ + "../coffee/foo.coffee", + "/bar.coffee", + "http://www.example.com/baz.coffee" + ]) + ); bundleMap.destroy(); minifiedMap.destroy(); @@ -692,7 +743,9 @@ exports["test ignore duplicate mappings."] = function(assert) { util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); }; -exports["test github issue #72, check for duplicate names or sources"] = function(assert) { +exports[ + "test github issue #72, check for duplicate names or sources" +] = function(assert) { const map = new SourceMapGenerator({ file: "test.js" }); @@ -717,7 +770,9 @@ exports["test github issue #72, check for duplicate names or sources"] = functio }); }; -exports["test setting sourcesContent to null when already null"] = function(assert) { +exports["test setting sourcesContent to null when already null"] = function( + assert +) { const smg = new SourceMapGenerator({ file: "foo.js" }); assert.doesNotThrow(function() { smg.setSourceContent("bar.js", null); @@ -771,7 +826,7 @@ exports["test applySourceMap with unexact match"] = async function(assert) { exports["test applySourceMap with empty mappings"] = async function(assert) { let consumer = await new SourceMapConsumer(util.testMapEmptyMappings); - const generator = SourceMapGenerator.fromSourceMap(consumer); + const generator = SourceMapGenerator.fromSourceMap(consumer); consumer.destroy(); consumer = await new SourceMapConsumer(util.testMapEmptyMappings); @@ -781,16 +836,26 @@ exports["test applySourceMap with empty mappings"] = async function(assert) { util.assertEqualMaps(assert, generator.toJSON(), util.testMapEmptyMappings); }; -exports["test applySourceMap with empty mappings and relative sources"] = async function(assert) { - let consumer = await new SourceMapConsumer(util.testMapEmptyMappingsRelativeSources); - const generator = SourceMapGenerator.fromSourceMap(consumer); +exports[ + "test applySourceMap with empty mappings and relative sources" +] = async function(assert) { + let consumer = await new SourceMapConsumer( + util.testMapEmptyMappingsRelativeSources + ); + const generator = SourceMapGenerator.fromSourceMap(consumer); consumer.destroy(); - consumer = await new SourceMapConsumer(util.testMapEmptyMappingsRelativeSources); + consumer = await new SourceMapConsumer( + util.testMapEmptyMappingsRelativeSources + ); generator.applySourceMap(consumer); consumer.destroy(); - util.assertEqualMaps(assert, generator.toJSON(), util.testMapEmptyMappingsRelativeSources_generatedExpected); + util.assertEqualMaps( + assert, + generator.toJSON(), + util.testMapEmptyMappingsRelativeSources_generatedExpected + ); }; exports["test issue #192"] = async function(assert) { @@ -798,22 +863,26 @@ exports["test issue #192"] = async function(assert) { generator.addMapping({ source: "a.js", generated: { line: 1, column: 10 }, - original: { line: 1, column: 10 }, + original: { line: 1, column: 10 } }); generator.addMapping({ source: "b.js", generated: { line: 1, column: 10 }, - original: { line: 2, column: 20 }, + original: { line: 2, column: 20 } }); const consumer = await new SourceMapConsumer(generator.toJSON()); let n = 0; - consumer.eachMapping(function() { n++; }); + consumer.eachMapping(function() { + n++; + }); - assert.equal(n, 2, - "Should not de-duplicate mappings that have the same " + - "generated positions, but different original positions."); + assert.equal( + n, + 2, + "Should not de-duplicate mappings that have the same generated positions, but different original positions." + ); consumer.destroy(); }; diff --git a/test/test-source-node.js b/test/test-source-node.js index 337952c3..d024c047 100644 --- a/test/test-source-node.js +++ b/test/test-source-node.js @@ -6,8 +6,10 @@ */ const util = require("./util"); -const SourceMapGenerator = require("../lib/source-map-generator").SourceMapGenerator; -const SourceMapConsumer = require("../lib/source-map-consumer").SourceMapConsumer; +const SourceMapGenerator = require("../lib/source-map-generator") + .SourceMapGenerator; +const SourceMapConsumer = require("../lib/source-map-consumer") + .SourceMapConsumer; const SourceNode = require("../lib/source-node").SourceNode; function forEachNewline(fn) { @@ -27,10 +29,11 @@ exports["test .add()"] = function(assert) { node.add(new SourceNode(null, null, null)); // Adding an array works. - node.add(["function foo() {", - new SourceNode(null, null, null, - "return 10;"), - "}"]); + node.add([ + "function foo() {", + new SourceNode(null, null, null, "return 10;"), + "}" + ]); // Adding other stuff doesn't. assert.throws(function() { @@ -56,10 +59,11 @@ exports["test .prepend()"] = function(assert) { assert.equal(node.children.length, 2); // Prepending an array works. - node.prepend(["function foo() {", - new SourceNode(null, null, null, - "return 10;"), - "}"]); + node.prepend([ + "function foo() {", + new SourceNode(null, null, null, "return 10;"), + "}" + ]); assert.equal(node.children[0], "function foo() {"); assert.equal(node.children[1], "return 10;"); assert.equal(node.children[2], "}"); @@ -77,34 +81,45 @@ exports["test .prepend()"] = function(assert) { }; exports["test .toString()"] = function(assert) { - assert.equal((new SourceNode(null, null, null, - ["function foo() {", - new SourceNode(null, null, null, "return 10;"), - "}"])).toString(), - "function foo() {return 10;}"); + assert.equal( + new SourceNode(null, null, null, [ + "function foo() {", + new SourceNode(null, null, null, "return 10;"), + "}" + ]).toString(), + "function foo() {return 10;}" + ); }; exports["test .join()"] = function(assert) { - assert.equal((new SourceNode(null, null, null, - ["a", "b", "c", "d"])).join(", ").toString(), - "a, b, c, d"); + assert.equal( + new SourceNode(null, null, null, ["a", "b", "c", "d"]) + .join(", ") + .toString(), + "a, b, c, d" + ); }; exports["test .walk()"] = function(assert) { - const node = new SourceNode(null, null, null, - ["(function () {\n", - " ", new SourceNode(1, 0, "a.js", ["someCall()"]), ";\n", - " ", new SourceNode(2, 0, "b.js", ["if (foo) bar()"]), ";\n", - "}());"]); + const node = new SourceNode(null, null, null, [ + "(function () {\n", + " ", + new SourceNode(1, 0, "a.js", ["someCall()"]), + ";\n", + " ", + new SourceNode(2, 0, "b.js", ["if (foo) bar()"]), + ";\n", + "}());" + ]); const expected = [ - { str: "(function () {\n", source: null, line: null, column: null }, - { str: " ", source: null, line: null, column: null }, - { str: "someCall()", source: "a.js", line: 1, column: 0 }, - { str: ";\n", source: null, line: null, column: null }, - { str: " ", source: null, line: null, column: null }, - { str: "if (foo) bar()", source: "b.js", line: 2, column: 0 }, - { str: ";\n", source: null, line: null, column: null }, - { str: "}());", source: null, line: null, column: null }, + { str: "(function () {\n", source: null, line: null, column: null }, + { str: " ", source: null, line: null, column: null }, + { str: "someCall()", source: "a.js", line: 1, column: 0 }, + { str: ";\n", source: null, line: null, column: null }, + { str: " ", source: null, line: null, column: null }, + { str: "if (foo) bar()", source: "b.js", line: 2, column: 0 }, + { str: ";\n", source: null, line: null, column: null }, + { str: "}());", source: null, line: null, column: null } ]; let i = 0; node.walk(function(chunk, loc) { @@ -125,38 +140,49 @@ exports["test .replaceRight"] = function(assert) { assert.equal(node.toString(), "hello universe"); // Nested - node = new SourceNode(null, null, null, - [new SourceNode(null, null, null, "hey sexy mama, "), - new SourceNode(null, null, null, "want to kill all humans?")]); + node = new SourceNode(null, null, null, [ + new SourceNode(null, null, null, "hey sexy mama, "), + new SourceNode(null, null, null, "want to kill all humans?") + ]); node.replaceRight(/kill all humans/, "watch Futurama"); assert.equal(node.toString(), "hey sexy mama, want to watch Futurama?"); }; -exports["test .toStringWithSourceMap()"] = forEachNewline(async function(assert, nl) { - const node = new SourceNode(null, null, null, - ["(function () {" + nl, - " ", - new SourceNode(1, 0, "a.js", "someCall", "originalCall"), - new SourceNode(1, 8, "a.js", "()"), - ";" + nl, - " ", new SourceNode(2, 0, "b.js", ["if (foo) bar()"]), ";" + nl, - "}());"]); +exports["test .toStringWithSourceMap()"] = forEachNewline(async function( + assert, + nl +) { + const node = new SourceNode(null, null, null, [ + "(function () {" + nl, + " ", + new SourceNode(1, 0, "a.js", "someCall", "originalCall"), + new SourceNode(1, 8, "a.js", "()"), + ";" + nl, + " ", + new SourceNode(2, 0, "b.js", ["if (foo) bar()"]), + ";" + nl, + "}());" + ]); const result = node.toStringWithSourceMap({ file: "foo.js" }); - assert.equal(result.code, [ - "(function () {", - " someCall();", - " if (foo) bar();", - "}());" - ].join(nl)); + assert.equal( + result.code, + ["(function () {", " someCall();", " if (foo) bar();", "}());"].join(nl) + ); let map = result.map; const mapWithoutOptions = node.toStringWithSourceMap().map; - assert.ok(map instanceof SourceMapGenerator, "map instanceof SourceMapGenerator"); - assert.ok(mapWithoutOptions instanceof SourceMapGenerator, "mapWithoutOptions instanceof SourceMapGenerator"); + assert.ok( + map instanceof SourceMapGenerator, + "map instanceof SourceMapGenerator" + ); + assert.ok( + mapWithoutOptions instanceof SourceMapGenerator, + "mapWithoutOptions instanceof SourceMapGenerator" + ); assert.ok(!("file" in mapWithoutOptions)); mapWithoutOptions._file = "foo.js"; util.assertEqualMaps(assert, map.toJSON(), mapWithoutOptions.toJSON()); @@ -209,13 +235,13 @@ exports["test .toStringWithSourceMap()"] = forEachNewline(async function(assert, map.destroy(); }); -exports["test .fromStringWithSourceMap()"] = forEachNewline(async function(assert, nl) { +exports["test .fromStringWithSourceMap()"] = forEachNewline(async function( + assert, + nl +) { const testCode = util.testGeneratedCode.replace(/\n/g, nl); let map = await new SourceMapConsumer(util.testMap); - const node = SourceNode.fromStringWithSourceMap( - testCode, - map - ); + const node = SourceNode.fromStringWithSourceMap(testCode, map); map.destroy(); const result = node.toStringWithSourceMap({ @@ -225,69 +251,85 @@ exports["test .fromStringWithSourceMap()"] = forEachNewline(async function(asser const code = result.code; assert.equal(code, testCode); - assert.ok(map instanceof SourceMapGenerator, "map instanceof SourceMapGenerator"); + assert.ok( + map instanceof SourceMapGenerator, + "map instanceof SourceMapGenerator" + ); map = map.toJSON(); assert.equal(map.version, util.testMap.version); assert.equal(map.file, util.testMap.file); assert.equal(map.mappings, util.testMap.mappings); }); -exports["test .fromStringWithSourceMap() empty map"] = forEachNewline(async function(assert, nl) { - let map = await new SourceMapConsumer(util.emptyMap); - const node = SourceNode.fromStringWithSourceMap( - util.testGeneratedCode.replace(/\n/g, nl), - map - ); - map.destroy(); - - const result = node.toStringWithSourceMap({ - file: "min.js" - }); - map = result.map; - const code = result.code; - - assert.equal(code, util.testGeneratedCode.replace(/\n/g, nl)); - assert.ok(map instanceof SourceMapGenerator, "map instanceof SourceMapGenerator"); - map = map.toJSON(); - assert.equal(map.version, util.emptyMap.version); - assert.equal(map.file, util.emptyMap.file); - assert.equal(map.mappings.length, util.emptyMap.mappings.length); - assert.equal(map.mappings, util.emptyMap.mappings); -}); +exports["test .fromStringWithSourceMap() empty map"] = forEachNewline( + async function(assert, nl) { + let map = await new SourceMapConsumer(util.emptyMap); + const node = SourceNode.fromStringWithSourceMap( + util.testGeneratedCode.replace(/\n/g, nl), + map + ); + map.destroy(); -exports["test .fromStringWithSourceMap() complex version"] = forEachNewline(async function(assert, nl) { - let input = new SourceNode(null, null, null, [ - "(function() {" + nl, + const result = node.toStringWithSourceMap({ + file: "min.js" + }); + map = result.map; + const code = result.code; + + assert.equal(code, util.testGeneratedCode.replace(/\n/g, nl)); + assert.ok( + map instanceof SourceMapGenerator, + "map instanceof SourceMapGenerator" + ); + map = map.toJSON(); + assert.equal(map.version, util.emptyMap.version); + assert.equal(map.file, util.emptyMap.file); + assert.equal(map.mappings.length, util.emptyMap.mappings.length); + assert.equal(map.mappings, util.emptyMap.mappings); + } +); + +exports["test .fromStringWithSourceMap() complex version"] = forEachNewline( + async function(assert, nl) { + let input = new SourceNode(null, null, null, [ + "(function() {" + nl, " var Test = {};" + nl, - " ", new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };" + nl), - " ", new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), nl, + " ", + new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };" + nl), + " ", + new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), + nl, "}());" + nl, - "/* Generated Source */"]); - input = input.toStringWithSourceMap({ - file: "foo.js" - }); - - let map = await new SourceMapConsumer(input.map.toString()); - const node = SourceNode.fromStringWithSourceMap( - input.code, - map - ); - map.destroy(); - - const result = node.toStringWithSourceMap({ - file: "foo.js" - }); - map = result.map; - const code = result.code; + "/* Generated Source */" + ]); + input = input.toStringWithSourceMap({ + file: "foo.js" + }); - assert.equal(code, input.code); - assert.ok(map instanceof SourceMapGenerator, "map instanceof SourceMapGenerator"); - map = map.toJSON(); - const inputMap = input.map.toJSON(); - util.assertEqualMaps(assert, map, inputMap); -}); + let map = await new SourceMapConsumer(input.map.toString()); + const node = SourceNode.fromStringWithSourceMap(input.code, map); + map.destroy(); -exports["test .fromStringWithSourceMap() third argument"] = async function(assert) { + const result = node.toStringWithSourceMap({ + file: "foo.js" + }); + map = result.map; + const code = result.code; + + assert.equal(code, input.code); + assert.ok( + map instanceof SourceMapGenerator, + "map instanceof SourceMapGenerator" + ); + map = map.toJSON(); + const inputMap = input.map.toJSON(); + util.assertEqualMaps(assert, map, inputMap); + } +); + +exports["test .fromStringWithSourceMap() third argument"] = async function( + assert +) { // Assume the following directory structure: // // http://foo.org/ @@ -316,11 +358,9 @@ exports["test .fromStringWithSourceMap() third argument"] = async function(asser const app = new SourceNode(); const map = await new SourceMapConsumer(coffeeBundle.map.toString()); - app.add(SourceNode.fromStringWithSourceMap( - coffeeBundle.code, - map, - relativePath - )); + app.add( + SourceNode.fromStringWithSourceMap(coffeeBundle.code, map, relativePath) + ); map.destroy(); app.add(foo); @@ -335,36 +375,23 @@ exports["test .fromStringWithSourceMap() third argument"] = async function(asser }); }; - await test("../coffee/maps", [ - "../coffee/foo.coffee", - "foo.js" - ]); + await test("../coffee/maps", ["../coffee/foo.coffee", "foo.js"]); // If the third parameter is omitted or set to the current working // directory we get incorrect source paths: - await test(undefined, [ - "../foo.coffee", - "foo.js" - ]); + await test(undefined, ["../foo.coffee", "foo.js"]); - await test("", [ - "../foo.coffee", - "foo.js" - ]); + await test("", ["../foo.coffee", "foo.js"]); - await test(".", [ - "../foo.coffee", - "foo.js" - ]); + await test(".", ["../foo.coffee", "foo.js"]); - await test("./", [ - "../foo.coffee", - "foo.js" - ]); + await test("./", ["../foo.coffee", "foo.js"]); }; -exports["test .toStringWithSourceMap() merging duplicate mappings"] = forEachNewline(function(assert, nl) { +exports[ + "test .toStringWithSourceMap() merging duplicate mappings" +] = forEachNewline(function(assert, nl) { let input = new SourceNode(null, null, null, [ new SourceNode(1, 0, "a.js", "(function"), new SourceNode(1, 0, "a.js", "() {" + nl), @@ -383,13 +410,16 @@ exports["test .toStringWithSourceMap() merging duplicate mappings"] = forEachNew file: "foo.js" }); - assert.equal(input.code, [ - "(function() {", - " var Test = {};", - "Test.A = { value: 1234 };", - "}());", - "/* Generated Source */" - ].join(nl)); + assert.equal( + input.code, + [ + "(function() {", + " var Test = {};", + "Test.A = { value: 1234 };", + "}());", + "/* Generated Source */" + ].join(nl) + ); let correctMap = new SourceMapGenerator({ file: "foo.js" @@ -447,9 +477,16 @@ exports["test .toStringWithSourceMap() merging duplicate mappings"] = forEachNew util.assertEqualMaps(assert, inputMap, correctMap); }); -exports["test .toStringWithSourceMap() multi-line SourceNodes"] = forEachNewline(function(assert, nl) { +exports[ + "test .toStringWithSourceMap() multi-line SourceNodes" +] = forEachNewline(function(assert, nl) { let input = new SourceNode(null, null, null, [ - new SourceNode(1, 0, "a.js", "(function() {" + nl + "var nextLine = 1;" + nl + "anotherLine();" + nl), + new SourceNode( + 1, + 0, + "a.js", + "(function() {" + nl + "var nextLine = 1;" + nl + "anotherLine();" + nl + ), new SourceNode(2, 2, "b.js", "Test.call(this, 123);" + nl), new SourceNode(2, 2, "b.js", "this['stuff'] = 'v';" + nl), new SourceNode(2, 2, "b.js", "anotherLine();" + nl), @@ -461,23 +498,26 @@ exports["test .toStringWithSourceMap() multi-line SourceNodes"] = forEachNewline file: "foo.js" }); - assert.equal(input.code, [ - "(function() {", - "var nextLine = 1;", - "anotherLine();", - "Test.call(this, 123);", - "this['stuff'] = 'v';", - "anotherLine();", - "/*", - "Generated", - "Source", - "*/", - "anotherLine();", - "/*", - "Generated", - "Source", - "*/" - ].join(nl)); + assert.equal( + input.code, + [ + "(function() {", + "var nextLine = 1;", + "anotherLine();", + "Test.call(this, 123);", + "this['stuff'] = 'v';", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/", + "anotherLine();", + "/*", + "Generated", + "Source", + "*/" + ].join(nl) + ); let correctMap = new SourceMapGenerator({ file: "foo.js" @@ -529,22 +569,19 @@ exports["test .toStringWithSourceMap() with empty string"] = function(assert) { assert.equal(result.code, ""); }; -exports["test .toStringWithSourceMap() with consecutive newlines"] = forEachNewline(function(assert, nl) { +exports[ + "test .toStringWithSourceMap() with consecutive newlines" +] = forEachNewline(function(assert, nl) { let input = new SourceNode(null, null, null, [ "/***/" + nl + nl, new SourceNode(1, 0, "a.js", "'use strict';" + nl), - new SourceNode(2, 0, "a.js", "a();"), + new SourceNode(2, 0, "a.js", "a();") ]); input = input.toStringWithSourceMap({ file: "foo.js" }); - assert.equal(input.code, [ - "/***/", - "", - "'use strict';", - "a();", - ].join(nl)); + assert.equal(input.code, ["/***/", "", "'use strict';", "a();"].join(nl)); let correctMap = new SourceMapGenerator({ file: "foo.js" @@ -565,20 +602,28 @@ exports["test .toStringWithSourceMap() with consecutive newlines"] = forEachNewl util.assertEqualMaps(assert, inputMap, correctMap); }); -exports["test setSourceContent with toStringWithSourceMap"] = async function(assert) { +exports["test setSourceContent with toStringWithSourceMap"] = async function( + assert +) { const aNode = new SourceNode(1, 1, "a.js", "a"); aNode.setSourceContent("a.js", "someContent"); - const node = new SourceNode(null, null, null, - ["(function () {\n", - " ", aNode, - " ", new SourceNode(1, 1, "b.js", "b"), - "}());"]); + const node = new SourceNode(null, null, null, [ + "(function () {\n", + " ", + aNode, + " ", + new SourceNode(1, 1, "b.js", "b"), + "}());" + ]); node.setSourceContent("b.js", "otherContent"); let map = node.toStringWithSourceMap({ file: "foo.js" }).map; - assert.ok(map instanceof SourceMapGenerator, "map instanceof SourceMapGenerator"); + assert.ok( + map instanceof SourceMapGenerator, + "map instanceof SourceMapGenerator" + ); map = await new SourceMapConsumer(map.toString()); assert.equal(map.sources.length, 2); @@ -594,11 +639,14 @@ exports["test setSourceContent with toStringWithSourceMap"] = async function(ass exports["test walkSourceContents"] = function(assert) { const aNode = new SourceNode(1, 1, "a.js", "a"); aNode.setSourceContent("a.js", "someContent"); - const node = new SourceNode(null, null, null, - ["(function () {\n", - " ", aNode, - " ", new SourceNode(1, 1, "b.js", "b"), - "}());"]); + const node = new SourceNode(null, null, null, [ + "(function () {\n", + " ", + aNode, + " ", + new SourceNode(1, 1, "b.js", "b"), + "}());" + ]); node.setSourceContent("b.js", "otherContent"); const results = []; node.walkSourceContents(function(sourceFile, sourceContent) { @@ -615,15 +663,13 @@ exports["test from issue 258"] = async function(assert) { const node = new SourceNode(); const reactCode = - ";require(0);\n//# sourceMappingURL=/index.ios.map?platform=ios&dev=false&minify=true"; + ";require(0);\n//# sourceMappingURL=/index.ios.map?platform=ios&dev=false&minify=true"; const reactMap = - '{"version":3,"file":"/index.ios.bundle?platform=ios&dev=false&minify=true","sections":[{"offset":{"line":0,"column":0},"map":{"version":3,"sources":["require-0.js"],"names":[],"mappings":"AAAA;","file":"require-0.js","sourcesContent":[";require(0);"]}}]}'; + // eslint-disable-next-line + '{"version":3,"file":"/index.ios.bundle?platform=ios&dev=false&minify=true","sections":[{"offset":{"line":0,"column":0},"map":{"version":3,"sources":["require-0.js"],"names":[],"mappings":"AAAA;","file":"require-0.js","sourcesContent":[";require(0);"]}}]}'; const map = await new SourceMapConsumer(reactMap); - node.add(SourceNode.fromStringWithSourceMap( - reactCode, - map - )); + node.add(SourceNode.fromStringWithSourceMap(reactCode, map)); map.destroy(); }; diff --git a/test/test-util.js b/test/test-util.js index 1e335989..9404f061 100644 --- a/test/test-util.js +++ b/test/test-util.js @@ -40,9 +40,18 @@ exports["test normalize()"] = function(assert) { assert.equal(libUtil.normalize(".///.././../a/b//./.."), "a/b/"); - assert.equal(libUtil.normalize("http://www.example.com"), "http://www.example.com/"); - assert.equal(libUtil.normalize("http://www.example.com/"), "http://www.example.com/"); - assert.equal(libUtil.normalize("http://www.example.com/./..//a/b/c/.././d//"), "http://www.example.com//a/b/d//"); + assert.equal( + libUtil.normalize("http://www.example.com"), + "http://www.example.com/" + ); + assert.equal( + libUtil.normalize("http://www.example.com/"), + "http://www.example.com/" + ); + assert.equal( + libUtil.normalize("http://www.example.com/./..//a/b/c/.././d//"), + "http://www.example.com//a/b/d//" + ); }; exports["test join()"] = function(assert) { @@ -62,10 +71,12 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("a", "./b"), "a/b"); assert.equal(libUtil.join("a/b", "./c"), "a/b/c"); - assert.equal(libUtil.join("a", "http://www.example.com"), "http://www.example.com/"); + assert.equal( + libUtil.join("a", "http://www.example.com"), + "http://www.example.com/" + ); assert.equal(libUtil.join("a", "data:foo,bar"), "data:foo,bar"); - assert.equal(libUtil.join("", "b"), "b"); assert.equal(libUtil.join(".", "b"), "b"); assert.equal(libUtil.join("", "b/"), "b/"); @@ -83,12 +94,17 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("", "./b"), "b"); assert.equal(libUtil.join(".", "./b"), "b"); - assert.equal(libUtil.join("", "http://www.example.com"), "http://www.example.com/"); - assert.equal(libUtil.join(".", "http://www.example.com"), "http://www.example.com/"); + assert.equal( + libUtil.join("", "http://www.example.com"), + "http://www.example.com/" + ); + assert.equal( + libUtil.join(".", "http://www.example.com"), + "http://www.example.com/" + ); assert.equal(libUtil.join("", "data:foo,bar"), "data:foo,bar"); assert.equal(libUtil.join(".", "data:foo,bar"), "data:foo,bar"); - assert.equal(libUtil.join("..", "b"), "../b"); assert.equal(libUtil.join("..", "b/"), "../b/"); assert.equal(libUtil.join("..", "b//"), "../b//"); @@ -99,10 +115,12 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("..", "."), "../"); assert.equal(libUtil.join("..", "./b"), "../b"); - assert.equal(libUtil.join("..", "http://www.example.com"), "http://www.example.com/"); + assert.equal( + libUtil.join("..", "http://www.example.com"), + "http://www.example.com/" + ); assert.equal(libUtil.join("..", "data:foo,bar"), "data:foo,bar"); - assert.equal(libUtil.join("a", ""), "a/"); assert.equal(libUtil.join("a", "."), "a/"); assert.equal(libUtil.join("a/", ""), "a/"); @@ -132,7 +150,6 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("//www.example.com", ""), "//www.example.com/"); assert.equal(libUtil.join("//www.example.com", "."), "//www.example.com/"); - assert.equal(libUtil.join("http://foo.org/a", "b"), "http://foo.org/a/b"); assert.equal(libUtil.join("http://foo.org/a/", "b"), "http://foo.org/a/b"); assert.equal(libUtil.join("http://foo.org/a//", "b"), "http://foo.org/a//b"); @@ -143,15 +160,26 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("http://foo.org/a", ".."), "http://foo.org/"); assert.equal(libUtil.join("http://foo.org/a", "../b"), "http://foo.org/b"); - assert.equal(libUtil.join("http://foo.org/a/b", "../c"), "http://foo.org/a/c"); + assert.equal( + libUtil.join("http://foo.org/a/b", "../c"), + "http://foo.org/a/c" + ); assert.equal(libUtil.join("http://foo.org/a", "."), "http://foo.org/a/"); assert.equal(libUtil.join("http://foo.org/a", "./b"), "http://foo.org/a/b"); - assert.equal(libUtil.join("http://foo.org/a/b", "./c"), "http://foo.org/a/b/c"); - - assert.equal(libUtil.join("http://foo.org/a", "http://www.example.com"), "http://www.example.com/"); - assert.equal(libUtil.join("http://foo.org/a", "data:foo,bar"), "data:foo,bar"); - + assert.equal( + libUtil.join("http://foo.org/a/b", "./c"), + "http://foo.org/a/b/c" + ); + + assert.equal( + libUtil.join("http://foo.org/a", "http://www.example.com"), + "http://www.example.com/" + ); + assert.equal( + libUtil.join("http://foo.org/a", "data:foo,bar"), + "data:foo,bar" + ); assert.equal(libUtil.join("http://foo.org", "a"), "http://foo.org/a"); assert.equal(libUtil.join("http://foo.org/", "a"), "http://foo.org/a"); @@ -160,18 +188,39 @@ exports["test join()"] = function(assert) { assert.equal(libUtil.join("http://foo.org/", "/a"), "http://foo.org/a"); assert.equal(libUtil.join("http://foo.org//", "/a"), "http://foo.org/a"); - assert.equal(libUtil.join("http://www.example.com", "//foo.org/bar"), "http://foo.org/bar"); - assert.equal(libUtil.join("//www.example.com", "//foo.org/bar"), "//foo.org/bar"); + assert.equal( + libUtil.join("http://www.example.com", "//foo.org/bar"), + "http://foo.org/bar" + ); + assert.equal( + libUtil.join("//www.example.com", "//foo.org/bar"), + "//foo.org/bar" + ); }; // TODO Issue #128: Define and test this function properly. exports["test relative()"] = function(assert) { assert.equal(libUtil.relative("/the/root", "/the/root/one.js"), "one.js"); - assert.equal(libUtil.relative("http://the/root", "http://the/root/one.js"), "one.js"); - assert.equal(libUtil.relative("/the/root", "/the/rootone.js"), "../rootone.js"); - assert.equal(libUtil.relative("http://the/root", "http://the/rootone.js"), "../rootone.js"); - assert.equal(libUtil.relative("/the/root", "/therootone.js"), "../../therootone.js"); - assert.equal(libUtil.relative("http://the/root", "/therootone.js"), "/therootone.js"); + assert.equal( + libUtil.relative("http://the/root", "http://the/root/one.js"), + "one.js" + ); + assert.equal( + libUtil.relative("/the/root", "/the/rootone.js"), + "../rootone.js" + ); + assert.equal( + libUtil.relative("http://the/root", "http://the/rootone.js"), + "../rootone.js" + ); + assert.equal( + libUtil.relative("/the/root", "/therootone.js"), + "../../therootone.js" + ); + assert.equal( + libUtil.relative("http://the/root", "/therootone.js"), + "/therootone.js" + ); assert.equal(libUtil.relative("", "/the/root/one.js"), "/the/root/one.js"); assert.equal(libUtil.relative(".", "/the/root/one.js"), "/the/root/one.js"); @@ -184,34 +233,70 @@ exports["test relative()"] = function(assert) { exports["test computeSourceURL"] = function(assert) { // Tests with sourceMapURL. - assert.equal(libUtil.computeSourceURL("", "src/test.js", "http://example.com"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL(undefined, "src/test.js", "http://example.com"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("src", "test.js", "http://example.com"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("src/", "test.js", "http://example.com"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("src", "/test.js", "http://example.com"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("http://mozilla.com", "src/test.js", "http://example.com"), - "http://mozilla.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("", "test.js", "http://example.com/src/test.js.map"), - "http://example.com/src/test.js"); - assert.equal(libUtil.computeSourceURL("", "/test.js", "http://example.com/src/test.js.map"), - "http://example.com/test.js"); + assert.equal( + libUtil.computeSourceURL("", "src/test.js", "http://example.com"), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL(undefined, "src/test.js", "http://example.com"), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL("src", "test.js", "http://example.com"), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL("src/", "test.js", "http://example.com"), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL("src", "/test.js", "http://example.com"), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL( + "http://mozilla.com", + "src/test.js", + "http://example.com" + ), + "http://mozilla.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL( + "", + "test.js", + "http://example.com/src/test.js.map" + ), + "http://example.com/src/test.js" + ); + assert.equal( + libUtil.computeSourceURL( + "", + "/test.js", + "http://example.com/src/test.js.map" + ), + "http://example.com/test.js" + ); // Legacy code won't pass in the sourceMapURL. assert.equal(libUtil.computeSourceURL("", "src/test.js"), "src/test.js"); - assert.equal(libUtil.computeSourceURL(undefined, "src/test.js"), "src/test.js"); + assert.equal( + libUtil.computeSourceURL(undefined, "src/test.js"), + "src/test.js" + ); assert.equal(libUtil.computeSourceURL("src", "test.js"), "src/test.js"); assert.equal(libUtil.computeSourceURL("src/", "test.js"), "src/test.js"); assert.equal(libUtil.computeSourceURL("src", "/test.js"), "src/test.js"); assert.equal(libUtil.computeSourceURL("src", "../test.js"), "test.js"); - assert.equal(libUtil.computeSourceURL("src/dir", "../././../test.js"), "test.js"); + assert.equal( + libUtil.computeSourceURL("src/dir", "../././../test.js"), + "test.js" + ); // This gives different results with the old algorithm and the new // spec-compliant algorithm. - assert.equal(libUtil.computeSourceURL("http://example.com/dir", "/test.js"), - "http://example.com/dir/test.js"); + assert.equal( + libUtil.computeSourceURL("http://example.com/dir", "/test.js"), + "http://example.com/dir/test.js" + ); }; diff --git a/test/util.js b/test/util.js index 3f2c25c9..7a84a246 100644 --- a/test/util.js +++ b/test/util.js @@ -26,22 +26,24 @@ const util = require("../lib/util"); // // ONE.foo=function(a){return baz(a);}; // TWO.inc=function(a){return a+1;}; -exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n" + - " TWO.inc=function(a){return a+1;};"; +exports.testGeneratedCode = + " ONE.foo=function(a){return baz(a);};\n TWO.inc=function(a){return a+1;};"; exports.testMap = { version: 3, file: "min.js", names: ["bar", "baz", "n"], sources: ["one.js", "two.js"], sourceRoot: "/the/root", - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" + mappings: + "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; exports.testMapNoSourceRoot = { version: 3, file: "min.js", names: ["bar", "baz", "n"], sources: ["one.js", "two.js"], - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" + mappings: + "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; exports.testMapEmptySourceRoot = { version: 3, @@ -49,7 +51,8 @@ exports.testMapEmptySourceRoot = { names: ["bar", "baz", "n"], sources: ["one.js", "two.js"], sourceRoot: "", - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" + mappings: + "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; exports.testMapSingleSource = { version: 3, @@ -64,10 +67,7 @@ exports.testMapEmptyMappings = { file: "min.js", names: [], sources: ["one.js", "two.js"], - sourcesContent: [ - " ONE.foo = 1;", - " TWO.inc = 2;" - ], + sourcesContent: [" ONE.foo = 1;", " TWO.inc = 2;"], sourceRoot: "", mappings: "" }; @@ -76,10 +76,7 @@ exports.testMapEmptyMappingsRelativeSources = { file: "min.js", names: [], sources: ["./one.js", "./two.js"], - sourcesContent: [ - " ONE.foo = 1;", - " TWO.inc = 2;" - ], + sourcesContent: [" ONE.foo = 1;", " TWO.inc = 2;"], sourceRoot: "/the/root", mappings: "" }; @@ -88,20 +85,17 @@ exports.testMapEmptyMappingsRelativeSources_generatedExpected = { file: "min.js", names: [], sources: ["one.js", "two.js"], - sourcesContent: [ - " ONE.foo = 1;", - " TWO.inc = 2;" - ], + sourcesContent: [" ONE.foo = 1;", " TWO.inc = 2;"], sourceRoot: "/the/root", mappings: "" }; exports.testMapMultiSourcesMappingRefersSingleSourceOnly = { - version: 3, - file: "min.js", - names: ["bar", "baz"], - sources: ["one.js", "withoutMappings.js"], - sourceRoot: "", - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID" + version: 3, + file: "min.js", + names: ["bar", "baz"], + sources: ["one.js", "withoutMappings.js"], + sourceRoot: "", + mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID" }; // This mapping is identical to above, but uses the indexed format instead. exports.indexedTestMap = { @@ -115,18 +109,11 @@ exports.indexedTestMap = { }, map: { version: 3, - sources: [ - "one.js" - ], + sources: ["one.js"], sourcesContent: [ - " ONE.foo = function (bar) {\n" + - " return baz(bar);\n" + - " };", - ], - names: [ - "bar", - "baz" + " ONE.foo = function (bar) {\n return baz(bar);\n };" ], + names: ["bar", "baz"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID", file: "min.js", sourceRoot: "/the/root" @@ -139,17 +126,9 @@ exports.indexedTestMap = { }, map: { version: 3, - sources: [ - "two.js" - ], - sourcesContent: [ - " TWO.inc = function (n) {\n" + - " return n + 1;\n" + - " };" - ], - names: [ - "n" - ], + sources: ["two.js"], + sourcesContent: [" TWO.inc = function (n) {\n return n + 1;\n };"], + names: ["n"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOA", file: "min.js", sourceRoot: "/the/root" @@ -168,18 +147,11 @@ exports.indexedTestMapDifferentSourceRoots = { }, map: { version: 3, - sources: [ - "one.js" - ], + sources: ["one.js"], sourcesContent: [ - " ONE.foo = function (bar) {\n" + - " return baz(bar);\n" + - " };", - ], - names: [ - "bar", - "baz" + " ONE.foo = function (bar) {\n return baz(bar);\n };" ], + names: ["bar", "baz"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID", file: "min.js", sourceRoot: "/the/root" @@ -192,17 +164,9 @@ exports.indexedTestMapDifferentSourceRoots = { }, map: { version: 3, - sources: [ - "two.js" - ], - sourcesContent: [ - " TWO.inc = function (n) {\n" + - " return n + 1;\n" + - " };" - ], - names: [ - "n" - ], + sources: ["two.js"], + sourcesContent: [" TWO.inc = function (n) {\n return n + 1;\n };"], + names: ["n"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOA", file: "min.js", sourceRoot: "/different/root" @@ -221,18 +185,11 @@ exports.indexedTestMapColumnOffset = { }, map: { version: 3, - sources: [ - "one.js" - ], + sources: ["one.js"], sourcesContent: [ - " ONE.foo = function (bar) {\n" + - " return baz(bar);\n" + - " };", - ], - names: [ - "bar", - "baz" + " ONE.foo = function (bar) {\n return baz(bar);\n };" ], + names: ["bar", "baz"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID", file: "min.js", sourceRoot: "/the/root" @@ -247,17 +204,9 @@ exports.indexedTestMapColumnOffset = { }, map: { version: 3, - sources: [ - "two.js" - ], - sourcesContent: [ - " TWO.inc = function (n) {\n" + - " return n + 1;\n" + - " };" - ], - names: [ - "n" - ], + sources: ["two.js"], + sourcesContent: [" TWO.inc = function (n) {\n return n + 1;\n };"], + names: ["n"], mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOA", file: "min.js", sourceRoot: "/the/root" @@ -271,15 +220,12 @@ exports.testMapWithSourcesContent = { names: ["bar", "baz", "n"], sources: ["one.js", "two.js"], sourcesContent: [ - " ONE.foo = function (bar) {\n" + - " return baz(bar);\n" + - " };", - " TWO.inc = function (n) {\n" + - " return n + 1;\n" + - " };" + " ONE.foo = function (bar) {\n return baz(bar);\n };", + " TWO.inc = function (n) {\n return n + 1;\n };" ], sourceRoot: "/the/root", - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" + mappings: + "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; exports.testMapRelativeSources = { version: 3, @@ -287,15 +233,12 @@ exports.testMapRelativeSources = { names: ["bar", "baz", "n"], sources: ["./one.js", "./two.js"], sourcesContent: [ - " ONE.foo = function (bar) {\n" + - " return baz(bar);\n" + - " };", - " TWO.inc = function (n) {\n" + - " return n + 1;\n" + - " };" + " ONE.foo = function (bar) {\n return baz(bar);\n };", + " TWO.inc = function (n) {\n return n + 1;\n };" ], sourceRoot: "/the/root", - mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" + mappings: + "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA" }; exports.emptyMap = { version: 3, @@ -312,29 +255,57 @@ exports.mapWithSourcelessMapping = { mappings: "AAgCA,C" }; - -function assertMapping(generatedLine, generatedColumn, originalSource, - originalLine, originalColumn, name, bias, map, assert, - dontTestGenerated, dontTestOriginal) { +function assertMapping( + generatedLine, + generatedColumn, + originalSource, + originalLine, + originalColumn, + name, + bias, + map, + assert, + dontTestGenerated, + dontTestOriginal +) { if (!dontTestOriginal) { const origMapping = map.originalPositionFor({ line: generatedLine, column: generatedColumn, bias }); - assert.equal(origMapping.name, name, - "Incorrect name, expected " + JSON.stringify(name) - + ", got " + JSON.stringify(origMapping.name)); - assert.equal(origMapping.line, originalLine, - "Incorrect line, expected " + JSON.stringify(originalLine) - + ", got " + JSON.stringify(origMapping.line)); - assert.equal(origMapping.column, originalColumn, - "Incorrect column, expected " + JSON.stringify(originalColumn) - + ", got " + JSON.stringify(origMapping.column)); + assert.equal( + origMapping.name, + name, + "Incorrect name, expected " + + JSON.stringify(name) + + ", got " + + JSON.stringify(origMapping.name) + ); + assert.equal( + origMapping.line, + originalLine, + "Incorrect line, expected " + + JSON.stringify(originalLine) + + ", got " + + JSON.stringify(origMapping.line) + ); + assert.equal( + origMapping.column, + originalColumn, + "Incorrect column, expected " + + JSON.stringify(originalColumn) + + ", got " + + JSON.stringify(origMapping.column) + ); let expectedSource; - if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) { + if ( + originalSource && + map.sourceRoot && + originalSource.indexOf(map.sourceRoot) === 0 + ) { expectedSource = originalSource; } else if (originalSource) { expectedSource = map.sourceRoot @@ -344,9 +315,14 @@ function assertMapping(generatedLine, generatedColumn, originalSource, expectedSource = null; } - assert.equal(origMapping.source, expectedSource, - "Incorrect source, expected " + JSON.stringify(expectedSource) - + ", got " + JSON.stringify(origMapping.source)); + assert.equal( + origMapping.source, + expectedSource, + "Incorrect source, expected " + + JSON.stringify(expectedSource) + + ", got " + + JSON.stringify(origMapping.source) + ); } if (!dontTestGenerated) { @@ -356,12 +332,22 @@ function assertMapping(generatedLine, generatedColumn, originalSource, column: originalColumn, bias }); - assert.equal(genMapping.line, generatedLine, - "Incorrect line, expected " + JSON.stringify(generatedLine) - + ", got " + JSON.stringify(genMapping.line)); - assert.equal(genMapping.column, generatedColumn, - "Incorrect column, expected " + JSON.stringify(generatedColumn) - + ", got " + JSON.stringify(genMapping.column)); + assert.equal( + genMapping.line, + generatedLine, + "Incorrect line, expected " + + JSON.stringify(generatedLine) + + ", got " + + JSON.stringify(genMapping.line) + ); + assert.equal( + genMapping.column, + generatedColumn, + "Incorrect column, expected " + + JSON.stringify(generatedColumn) + + ", got " + + JSON.stringify(genMapping.column) + ); } } exports.assertMapping = assertMapping; @@ -369,40 +355,74 @@ exports.assertMapping = assertMapping; function assertEqualMaps(assert, actualMap, expectedMap) { assert.equal(actualMap.version, expectedMap.version, "version mismatch"); assert.equal(actualMap.file, expectedMap.file, "file mismatch"); - assert.equal(actualMap.names.length, - expectedMap.names.length, - "names length mismatch: " + - actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + assert.equal( + actualMap.names.length, + expectedMap.names.length, + "names length mismatch: " + + actualMap.names.join(", ") + + " != " + + expectedMap.names.join(", ") + ); for (let i = 0; i < actualMap.names.length; i++) { - assert.equal(actualMap.names[i], - expectedMap.names[i], - "names[" + i + "] mismatch: " + - actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); + assert.equal( + actualMap.names[i], + expectedMap.names[i], + "names[" + + i + + "] mismatch: " + + actualMap.names.join(", ") + + " != " + + expectedMap.names.join(", ") + ); } - assert.equal(actualMap.sources.length, - expectedMap.sources.length, - "sources length mismatch: " + - actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + assert.equal( + actualMap.sources.length, + expectedMap.sources.length, + "sources length mismatch: " + + actualMap.sources.join(", ") + + " != " + + expectedMap.sources.join(", ") + ); for (let i = 0; i < actualMap.sources.length; i++) { - assert.equal(actualMap.sources[i], - expectedMap.sources[i], - "sources[" + i + "] length mismatch: " + - actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); + assert.equal( + actualMap.sources[i], + expectedMap.sources[i], + "sources[" + + i + + "] length mismatch: " + + actualMap.sources.join(", ") + + " != " + + expectedMap.sources.join(", ") + ); } - assert.equal(actualMap.sourceRoot, - expectedMap.sourceRoot, - "sourceRoot mismatch: " + - actualMap.sourceRoot + " != " + expectedMap.sourceRoot); - assert.equal(actualMap.mappings, expectedMap.mappings, - "mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings); + assert.equal( + actualMap.sourceRoot, + expectedMap.sourceRoot, + "sourceRoot mismatch: " + + actualMap.sourceRoot + + " != " + + expectedMap.sourceRoot + ); + assert.equal( + actualMap.mappings, + expectedMap.mappings, + "mappings mismatch:\nActual: " + + actualMap.mappings + + "\nExpected: " + + expectedMap.mappings + ); if (actualMap.sourcesContent) { - assert.equal(actualMap.sourcesContent.length, - expectedMap.sourcesContent.length, - "sourcesContent length mismatch"); + assert.equal( + actualMap.sourcesContent.length, + expectedMap.sourcesContent.length, + "sourcesContent length mismatch" + ); for (let i = 0; i < actualMap.sourcesContent.length; i++) { - assert.equal(actualMap.sourcesContent[i], - expectedMap.sourcesContent[i], - "sourcesContent[" + i + "] mismatch"); + assert.equal( + actualMap.sourcesContent[i], + expectedMap.sourcesContent[i], + "sourcesContent[" + i + "] mismatch" + ); } } }