master d775db97c6d1 cached
14 files
18.8 KB
4.9k tokens
4 symbols
1 requests
Download .txt
Repository: novocaine/sourcemapped-stacktrace
Branch: master
Commit: d775db97c6d1
Files: 14
Total size: 18.8 KB

Directory structure:
gitextract_l1zd_6h9/

├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── demo/
│   ├── .babelrc
│   ├── .gitignore
│   ├── bork.es6
│   ├── bork_coffee.coffee
│   ├── make.sh
│   └── smst.html
├── index.d.ts
├── package.json
├── sourcemapped-stacktrace.js
└── webpack.config.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules
dist


================================================
FILE: .npmignore
================================================
node_modules


================================================
FILE: LICENSE
================================================
Copyright (c) 2016, James Salter
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of sourcemapped-stacktrace nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


================================================
FILE: README.md
================================================
This is a simple module for applying source maps to JS stack traces in the browser. 

## The problem this solves

You have Error.stack() in JS (maybe you're logging a trace, or you're looking at
traces in Jasmine or Mocha), and you need to apply a sourcemap so you can
understand whats happening because you're using some fancy compiled-to-js thing
like coffeescript or traceur. Unfortunately, the browser only applies sourcemaps when the
trace is viewed in its console, not to the underlying stack object, so you're
out of luck.

## Demo

http://novocaine.github.io/sourcemapped-stacktrace-demo/public_html/smst.html

## Install from npm

```
npm install sourcemapped-stacktrace
```

https://www.npmjs.com/package/sourcemapped-stacktrace

The npm bundle contains dist/sourcemapped-stacktrace.js, if that's what you're
after. The built product is not held in this repo.

## Setup

Include sourcemapped-stacktrace.js into your page using either an AMD module
loader or a plain old script include. As an AMD module it exposes the method
'mapStackTrace'. If an AMD loader is not found this function will be set on
window.sourceMappedStackTrace.mapStackTrace.

## API 

### mapStackTrace(stack, done [, opts])

Re-map entries in a stacktrace using sourcemaps if available.

**Arguments:**

- *stack*: (str) The stacktrace from the browser.

- *done*: Callback invoked with the transformed stacktrace (an Array of Strings) passed as the first argument

- *opts*: Optional options object containing:
  - *filter*: Function that filters each stacktrace line.
              It is invoked with _(line)_ and should return truthy/ falsy value.
              Sources which do not pass the filter won't be processed.
  - *cacheGlobally*: Boolean. If `true`, sourcemaps are cached across multiple `mapStackTrace()` calls,
                     allowing for better performance if called repeatedly, or when browser's cache is disabled.
                     Defaults to `false`.
  - *sync*: Boolean. Whether to use synchronous ajax to load the sourcemaps.

**Supported browsers**
  - Chrome
  - Firefox
  - Safari
  - Internet Explorer 11 and up
  - Microsoft Edge

## Example

```javascript
try {
  // break something
  bork();
} catch (e) {
  // pass e.stack to window.mapStackTrace
  window.mapStackTrace(e.stack, function(mappedStack) {
    // do what you want with mappedStack here
    console.log(mappedStack.join("\n"));
  }, {
    filter: function (line) {
      // process only sources containing `spec.js`
      return /(spec\.js)/.test(line);
    }
  });
}
```

## Longer Explanation

Several modern browsers support sourcemaps when viewing stack traces from errors in their native console, but as of the time of writing there is no support for applying a sourcemap to the (highly non-standardised) [Error.prototype.stack](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack). Error.prototype.stack can be used for logging errors and for displaying errors in test frameworks, and it is not very convenient to have unmapped traces in either of those use cases.

This module fetches all the scripts referenced by the stack trace, determines
whether they have an applicable sourcemap, fetches the sourcemap from the
server, then uses the [Mozilla source-map library](https://github.com/mozilla/source-map/) to do the mapping. Browsers that support sourcemaps don't offer a standardised sourcemap API, so we have to do all that work ourselves.

The nice part about doing it ourselves is that the library could be extended to
work in browsers that don't support sourcemaps, which could be good for
logging and debugging problems. Currently, only Chrome and Firefox are supported, but it
would be easy to support those formats by ripping off [stacktrace.js](https://github.com/stacktracejs/stacktrace.js/).

## Known issues

* Doesn't support exception formats of any browser other than Chrome and
  Firefox
* Only supports JS containing //# sourceMappingURL= declarations (i.e. no
  support for the SourceMap: HTTP header (yet)
* Some prominent sourcemap generators (including CoffeeScript, Traceur, Babel)
  don't emit a list of 'names' in the source-map, which means that frames from transpiled code will have (unknown) instead of the original function name. Those generators should support this feature better.


================================================
FILE: demo/.babelrc
================================================
{
  "presets": ["es2015"]
}


================================================
FILE: demo/.gitignore
================================================
bork.babel.js
bork_coffee.js
*.map
sourcemapped-stacktrace.js


================================================
FILE: demo/bork.es6
================================================
class BabelBorker {
    bork() {
        throw new Error("bork from es6");
    }
}

window.babel_bork = () => new BabelBorker().bork()


================================================
FILE: demo/bork_coffee.coffee
================================================
class CoffeeBorker
  bork: () ->
    throw new Error("Bork from coffeescript")
    
window.coffee_bork = () -> new CoffeeBorker().bork()


================================================
FILE: demo/make.sh
================================================
# (don't forget to run npm install first, to update dist/smst.js)
babel bork.es6 -s true > bork.babel.js
coffee -c -m bork_coffee.coffee
cp ../dist/sourcemapped-stacktrace.js .


================================================
FILE: demo/smst.html
================================================
<!DOCTYPE html>
<html>
  <!--<script type="text/javascript"
    src="https://rawgithub.com/novocaine/sourcemapped-stacktrace/master/dist/sourcemapped-stacktrace.js"></script>-->
  <script type="text/javascript" src="sourcemapped-stacktrace.js"></script>
  <script type="text/javascript" src="bork_coffee.js"></script>
  <script type="text/javascript" src="bork.babel.js"></script>
<body>
  <p>A demo of printing a stack trace from an error thrown within transpiled
    code.
  </p>

  <button type="button" onclick="errorAndPrint(coffee_bork)">
    Throw an error in sourcemapped code from coffeescript
  </button>
  <button type="button" onclick="errorAndPrint(babel_bork)">
    Throw an error in sourcemapped code from babel
  </button>

  <p>Source-mapped Stack trace (pointing to original code):</p>

  <pre id="mapped">
  </pre>

  <p>Unmapped Stack trace (pointing to transpiled code):</p>

  <pre id="unmapped">
  </pre>

  <p>Alternatively, try throwing and not catching, to compare the trace in your
  browser's console: </p>
  <button type="button" onclick="coffee_bork()">Throw uncaught</button>

    <script type="text/javascript">
      var errorAndPrint = function(bork_func) {
        try {
          bork_func();
        } catch (e) {
          // display unmapped trace
          var unmapped = document.getElementById("unmapped");
          unmapped.innerHTML = "";
          var unmappedNode = document.createTextNode(e.stack);
          unmapped.appendChild(unmappedNode);

          // invoke smst
          sourceMappedStackTrace.mapStackTrace(e.stack, function(mappedStack) {
            // mappedStack is an array of strings, one per frame in e.stack
            var mappedElem = document.getElementById("mapped");
            mappedElem.innerHTML = "";
            var textNode = document.createTextNode(e.message + "\n" + 
              mappedStack.join("\n"));
            mappedElem.appendChild(textNode);
          });
        }
      }
    </script>

</body>
</html>


================================================
FILE: index.d.ts
================================================
declare module 'sourcemapped-stacktrace' {

    export interface MapStackTraceOptions {
        /** Filter function applied to each stackTrace line. Lines which do not pass the filter won't be processesd. */
        filter?: (line: string) => boolean
        /** Whether to cache sourcemaps globally across multiple calls. */
        cacheGlobally?: boolean
        /** Whether to use synchronous ajax to load the sourcemaps. */
        sync?: boolean
    }
    
    /**
     * Re-map entries in a stacktrace using sourcemaps if available.
     *
     * @param stack The stacktrace from the browser (`error.stack`).
     * @param done Callback invoked with the transformed stacktrace.
     * @param opts Options object.
     */
    export function mapStackTrace(stack: string | undefined, done: (mappedStack: string[]) => void, opts?: MapStackTraceOptions): void

}


================================================
FILE: package.json
================================================
{
  "name": "sourcemapped-stacktrace",
  "version": "1.1.11",
  "homepage": "https://github.com/novocaine/sourcemapped-stacktrace",
  "license": "BSD-3-Clause",
  "author": {
    "name": "James Salter",
    "email": "iteration@gmail.com"
  },
  "main": "dist/sourcemapped-stacktrace.js",
  "description": "A simple module for applying source maps to JS stack traces in the browser.",
  "dependencies": {
    "source-map": "0.5.6"
  },
  "devDependencies": {
    "babel-preset-es2015": "^6.9.0",
    "webpack": "^1.12.0"
  },
  "repository": {
    "type": "git",
    "url": "http://github.com/novocaine/sourcemapped-stacktrace"
  },
  "scripts": {
    "prepublish": "webpack"
  }
}


================================================
FILE: sourcemapped-stacktrace.js
================================================
/*
 * sourcemapped-stacktrace.js
 * created by James Salter <iteration@gmail.com> (2014)
 *
 * https://github.com/novocaine/sourcemapped-stacktrace
 *
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/*global define */

// note we only include source-map-consumer, not the whole source-map library,
// which includes gear for generating source maps that we don't need
define(['source-map/lib/source-map-consumer'],
function(source_map_consumer) {

  var global_mapForUri = {};

  /**
   * Re-map entries in a stacktrace using sourcemaps if available.
   *
   * @param {str} stack - The stacktrace from the browser.
   * @param {function} done - Callback invoked with the transformed stacktrace
   *                          (an Array of Strings) passed as the first
   *                          argument
   * @param {Object} [opts] - Optional options object.
   * @param {Function} [opts.filter] - Filter function applied to each stackTrace line.
   *                                   Lines which do not pass the filter won't be processesd.
   * @param {boolean} [opts.cacheGlobally] - Whether to cache sourcemaps globally across multiple calls.
   * @param {boolean} [opts.sync] - Whether to use synchronous ajax to load the sourcemaps.
   * @param {string} [opts.traceFormat] - If `error.stack` is formatted according to chrome or
   *                                      Firefox's style.  Can be either `"chrome"`, `"firefox"`
   *                                      or `undefined` (default).  If `undefined`, this library
   *                                      will guess based on `navigator.userAgent`.
   */
  var mapStackTrace = function(stack, done, opts) {
    var lines;
    var line;
    var mapForUri = {};
    var rows = {};
    var fields;
    var uri;
    var expected_fields;
    var regex;
    var skip_lines;

    var fetcher = new Fetcher(opts);

    var traceFormat = opts && opts.traceFormat;
    if (traceFormat !== "chrome" && traceFormat !== "firefox") {
      if (traceFormat) {
        throw new Error("unknown traceFormat \"" + traceFormat + "\" :(");
      } else if (isChromeOrEdge() || isIE11Plus()) {
        traceFormat = "chrome";
      } else if (isFirefox() || isSafari()) {
        traceFormat = "firefox";
      } else {
        throw new Error("unknown browser :(");
      }
    }

    if (traceFormat === "chrome") {
      regex = /^ +at.+\((.*):([0-9]+):([0-9]+)/;
      expected_fields = 4;
      // (skip first line containing exception message)
      skip_lines = 1;
    } else {
      regex = /@(.*):([0-9]+):([0-9]+)/;
      expected_fields = 4;
      skip_lines = 0;
    }

    lines = stack.split("\n").slice(skip_lines);

    for (var i=0; i < lines.length; i++) {
      line = lines[i];
      if ( opts && opts.filter && !opts.filter(line) ) continue;
      
      fields = line.match(regex);
      if (fields && fields.length === expected_fields) {
        rows[i] = fields;
        uri = fields[1];
        if (!uri.match(/<anonymous>/)) {
          fetcher.fetchScript(uri);
        }
      }
    }

    fetcher.sem.whenReady(function() {
      var result = processSourceMaps(lines, rows, fetcher.mapForUri, traceFormat);
      done(result);
    });
  };

  var isChromeOrEdge = function() {
    return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  };

  var isFirefox = function() {
    return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  };  

  var isSafari = function() {
    return navigator.userAgent.toLowerCase().indexOf('safari') > -1;
  };
		
  var isIE11Plus = function() {
   	return document.documentMode && document.documentMode >= 11;
  };


  var Semaphore = function() {
    this.count = 0;
    this.pending = [];
  };

  Semaphore.prototype.incr = function() {
    this.count++;
  };

  Semaphore.prototype.decr = function() {
    this.count--;
    this.flush();
  };

  Semaphore.prototype.whenReady = function(fn) {
    this.pending.push(fn);
    this.flush();
  };

  Semaphore.prototype.flush = function() {
    if (this.count === 0) {
        this.pending.forEach(function(fn) { fn(); });
        this.pending = [];
    }
  };


  var Fetcher = function(opts) {
    this.sem = new Semaphore();
    this.sync = opts && opts.sync;
    this.mapForUri = opts && opts.cacheGlobally ? global_mapForUri : {};
  };

  Fetcher.prototype.ajax = function(uri, callback) {
    var xhr = createXMLHTTPObject();
    var that = this;
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        callback.call(that, xhr, uri);
      }
    };
    xhr.open("GET", uri, !this.sync);
    xhr.send();
  }

  Fetcher.prototype.fetchScript = function(uri) {
    if (!(uri in this.mapForUri)) {
      this.sem.incr();
      this.mapForUri[uri] = null;
    } else {
      return;
    }

    this.ajax(uri, this.onScriptLoad);
  };

  var absUrlRegex = new RegExp('^(?:[a-z]+:)?//', 'i');

  Fetcher.prototype.onScriptLoad = function(xhr, uri) {
    if (xhr.status === 200 || (uri.slice(0, 7) === "file://" && xhr.status === 0)) {
      // find .map in file.
      //
      // attempt to find it at the very end of the file, but tolerate trailing
      // whitespace inserted by some packers.
      var match = xhr.responseText.match("//# [s]ourceMappingURL=(.*)[\\s]*$", "m");
      if (match && match.length === 2) {
        // get the map
        var mapUri = match[1];

        var embeddedSourceMap = mapUri.match("data:application/json;(charset=[^;]+;)?base64,(.*)");

        if (embeddedSourceMap && embeddedSourceMap[2]) {
          this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(atob(embeddedSourceMap[2]));
          this.sem.decr();
        } else {
          if (!absUrlRegex.test(mapUri)) {
            // relative url; according to sourcemaps spec is 'source origin'
            var origin;
            var lastSlash = uri.lastIndexOf('/');
            if (lastSlash !== -1) {
              origin = uri.slice(0, lastSlash + 1);
              mapUri = origin + mapUri;
              // note if lastSlash === -1, actual script uri has no slash
              // somehow, so no way to use it as a prefix... we give up and try
              // as absolute
            }
          }

          this.ajax(mapUri, function(xhr) {
            if (xhr.status === 200 || (mapUri.slice(0, 7) === "file://" && xhr.status === 0)) {
              this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(xhr.responseText);
            }
            this.sem.decr();
          });
        }
      } else {
        // no map
        this.sem.decr();
      }
    } else {
      // HTTP error fetching uri of the script
      this.sem.decr();
    }
  };

  var processSourceMaps = function(lines, rows, mapForUri, traceFormat) {
    var result = [];
    var map;
    var origName = traceFormat === "chrome" ? origNameChrome : origNameFirefox;
    for (var i=0; i < lines.length; i++) {
      var row = rows[i];
      if (row) {
        var uri = row[1];
        var line = parseInt(row[2], 10);
        var column = parseInt(row[3], 10);
        map = mapForUri[uri];

        if (map) {
          // we think we have a map for that uri. call source-map library
          var origPos = map.originalPositionFor(
            { line: line, column: column });
          result.push(formatOriginalPosition(origPos.source,
            origPos.line, origPos.column, origPos.name || origName(lines[i])));
        } else {
          // we can't find a map for that url, but we parsed the row.
          // reformat unchanged line for consistency with the sourcemapped
          // lines.
          result.push(formatOriginalPosition(uri, line, column, origName(lines[i])));
        }
      } else {
        // we weren't able to parse the row, push back what we were given
        result.push(lines[i]);
      }
    }

    return result;
  };

  function origNameChrome(origLine) {
    var match = / +at +([^ ]*).*/.exec(origLine);
    return match && match[1];
  }

  function origNameFirefox(origLine) {
    var match = /([^@]*)@.*/.exec(origLine);
    return match && match[1];
  }

  var formatOriginalPosition = function(source, line, column, name) {
    // mimic chrome's format
    return "    at " + (name ? name : "(unknown)") +
      " (" + source + ":" + line + ":" + column + ")";
  };

  // xmlhttprequest boilerplate
  var XMLHttpFactories = [
	function () {return new XMLHttpRequest();},
	function () {return new ActiveXObject("Msxml2.XMLHTTP");},
	function () {return new ActiveXObject("Msxml3.XMLHTTP");},
	function () {return new ActiveXObject("Microsoft.XMLHTTP");}
  ];

  function createXMLHTTPObject() {
      var xmlhttp = false;
      for (var i=0;i<XMLHttpFactories.length;i++) {
          try {
              xmlhttp = XMLHttpFactories[i]();
          }
          catch (e) {
              continue;
          }
          break;
      }
      return xmlhttp;
  }

  return {
    mapStackTrace: mapStackTrace
  }
});


================================================
FILE: webpack.config.js
================================================
module.exports = {
  context: __dirname,
  entry: "./sourcemapped-stacktrace.js",
  output: {
    library: "sourceMappedStackTrace",
    libraryTarget: "umd",
    path: __dirname + "/dist",
    filename: "sourcemapped-stacktrace.js"
  }
};
Download .txt
gitextract_l1zd_6h9/

├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── demo/
│   ├── .babelrc
│   ├── .gitignore
│   ├── bork.es6
│   ├── bork_coffee.coffee
│   ├── make.sh
│   └── smst.html
├── index.d.ts
├── package.json
├── sourcemapped-stacktrace.js
└── webpack.config.js
Download .txt
SYMBOL INDEX (4 symbols across 2 files)

FILE: index.d.ts
  type MapStackTraceOptions (line 3) | interface MapStackTraceOptions {

FILE: sourcemapped-stacktrace.js
  function origNameChrome (line 251) | function origNameChrome(origLine) {
  function origNameFirefox (line 256) | function origNameFirefox(origLine) {
  function createXMLHTTPObject (line 275) | function createXMLHTTPObject() {
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (21K chars).
[
  {
    "path": ".gitignore",
    "chars": 18,
    "preview": "node_modules\ndist\n"
  },
  {
    "path": ".npmignore",
    "chars": 13,
    "preview": "node_modules\n"
  },
  {
    "path": "LICENSE",
    "chars": 1493,
    "preview": "Copyright (c) 2016, James Salter\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or withou"
  },
  {
    "path": "README.md",
    "chars": 4344,
    "preview": "This is a simple module for applying source maps to JS stack traces in the browser. \n\n## The problem this solves\n\nYou ha"
  },
  {
    "path": "demo/.babelrc",
    "chars": 28,
    "preview": "{\n  \"presets\": [\"es2015\"]\n}\n"
  },
  {
    "path": "demo/.gitignore",
    "chars": 62,
    "preview": "bork.babel.js\nbork_coffee.js\n*.map\nsourcemapped-stacktrace.js\n"
  },
  {
    "path": "demo/bork.es6",
    "chars": 135,
    "preview": "class BabelBorker {\n    bork() {\n        throw new Error(\"bork from es6\");\n    }\n}\n\nwindow.babel_bork = () => new BabelB"
  },
  {
    "path": "demo/bork_coffee.coffee",
    "chars": 137,
    "preview": "class CoffeeBorker\n  bork: () ->\n    throw new Error(\"Bork from coffeescript\")\n    \nwindow.coffee_bork = () -> new Coffe"
  },
  {
    "path": "demo/make.sh",
    "chars": 177,
    "preview": "# (don't forget to run npm install first, to update dist/smst.js)\nbabel bork.es6 -s true > bork.babel.js\ncoffee -c -m bo"
  },
  {
    "path": "demo/smst.html",
    "chars": 1997,
    "preview": "<!DOCTYPE html>\n<html>\n  <!--<script type=\"text/javascript\"\n    src=\"https://rawgithub.com/novocaine/sourcemapped-stackt"
  },
  {
    "path": "index.d.ts",
    "chars": 866,
    "preview": "declare module 'sourcemapped-stacktrace' {\n\n    export interface MapStackTraceOptions {\n        /** Filter function appl"
  },
  {
    "path": "package.json",
    "chars": 681,
    "preview": "{\n  \"name\": \"sourcemapped-stacktrace\",\n  \"version\": \"1.1.11\",\n  \"homepage\": \"https://github.com/novocaine/sourcemapped-s"
  },
  {
    "path": "sourcemapped-stacktrace.js",
    "chars": 9021,
    "preview": "/*\n * sourcemapped-stacktrace.js\n * created by James Salter <iteration@gmail.com> (2014)\n *\n * https://github.com/novoca"
  },
  {
    "path": "webpack.config.js",
    "chars": 240,
    "preview": "module.exports = {\n  context: __dirname,\n  entry: \"./sourcemapped-stacktrace.js\",\n  output: {\n    library: \"sourceMapped"
  }
]

About this extraction

This page contains the full source code of the novocaine/sourcemapped-stacktrace GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (18.8 KB), approximately 4.9k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!