sourcemap.mjs 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// Copyright 2013 the V8 project authors. 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 Google Inc. 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
// OWNER 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.

// This is a copy from blink dev tools, see:
// http://src.chromium.org/viewvc/blink/trunk/Source/devtools/front_end/SourceMap.js
// revision: 153407

// Added to make the file work without dev tools
export const WebInspector = {};
WebInspector.ParsedURL = {};
WebInspector.ParsedURL.completeURL = function(){};
// start of original file content

/*
 * Copyright (C) 2012 Google Inc. 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 Google Inc. 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
 * OWNER 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.
 */

/**
 * Implements Source Map V3 model. See http://code.google.com/p/closure-compiler/wiki/SourceMaps
 * for format description.
 * @constructor
 * @param {string} sourceMappingURL
 * @param {SourceMapV3} payload
 */
WebInspector.SourceMap = function(sourceMappingURL, payload)
{
    if (!WebInspector.SourceMap.prototype._base64Map) {
        const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        WebInspector.SourceMap.prototype._base64Map = {};
80
        for (let i = 0; i < base64Digits.length; ++i)
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
            WebInspector.SourceMap.prototype._base64Map[base64Digits.charAt(i)] = i;
    }

    this._sourceMappingURL = sourceMappingURL;
    this._reverseMappingsBySourceURL = {};
    this._mappings = [];
    this._sources = {};
    this._sourceContentByURL = {};
    this._parseMappingPayload(payload);
}

/**
 * @param {string} sourceMapURL
 * @param {string} compiledURL
 * @param {function(WebInspector.SourceMap)} callback
 */
WebInspector.SourceMap.load = function(sourceMapURL, compiledURL, callback)
{
    NetworkAgent.loadResourceForFrontend(WebInspector.resourceTreeModel.mainFrame.id, sourceMapURL, undefined, contentLoaded.bind(this));

    /**
     * @param {?Protocol.Error} error
     * @param {number} statusCode
     * @param {NetworkAgent.Headers} headers
     * @param {string} content
     */
    function contentLoaded(error, statusCode, headers, content)
    {
        if (error || !content || statusCode >= 400) {
110
            console.error(`Could not load content for ${sourceMapURL} : ${error || (`HTTP status code: ${statusCode}`)}`);
111 112 113 114 115 116 117
            callback(null);
            return;
        }

        if (content.slice(0, 3) === ")]}")
            content = content.substring(content.indexOf('\n'));
        try {
118 119
            const payload = /** @type {SourceMapV3} */ (JSON.parse(content));
            const baseURL = sourceMapURL.startsWith("data:") ? compiledURL : sourceMapURL;
120 121 122 123 124 125 126 127 128 129
            callback(new WebInspector.SourceMap(baseURL, payload));
        } catch(e) {
            console.error(e.message);
            callback(null);
        }
    }
}

WebInspector.SourceMap.prototype = {
    /**
130
     * @return {string[]}
131
     */
132
    sources()
133 134 135 136 137 138 139 140
    {
        return Object.keys(this._sources);
    },

    /**
     * @param {string} sourceURL
     * @return {string|undefined}
     */
141
    sourceContent(sourceURL)
142 143 144 145 146 147 148 149 150
    {
        return this._sourceContentByURL[sourceURL];
    },

    /**
     * @param {string} sourceURL
     * @param {WebInspector.ResourceType} contentType
     * @return {WebInspector.ContentProvider}
     */
151
    sourceContentProvider(sourceURL, contentType)
152
    {
153 154 155 156
        const lastIndexOfDot = sourceURL.lastIndexOf(".");
        const extension = lastIndexOfDot !== -1 ? sourceURL.substr(lastIndexOfDot + 1) : "";
        const mimeType = WebInspector.ResourceType.mimeTypesForExtensions[extension.toLowerCase()];
        const sourceContent = this.sourceContent(sourceURL);
157 158 159 160 161 162 163 164
        if (sourceContent)
            return new WebInspector.StaticContentProvider(contentType, sourceContent, mimeType);
        return new WebInspector.CompilerSourceMappingContentProvider(sourceURL, contentType, mimeType);
    },

    /**
     * @param {SourceMapV3} mappingPayload
     */
165
    _parseMappingPayload(mappingPayload)
166 167 168 169 170 171 172 173 174 175
    {
        if (mappingPayload.sections)
            this._parseSections(mappingPayload.sections);
        else
            this._parseMap(mappingPayload, 0, 0);
    },

    /**
     * @param {Array.<SourceMapV3.Section>} sections
     */
176
    _parseSections(sections)
177
    {
178 179
        for (let i = 0; i < sections.length; ++i) {
            const section = sections[i];
180 181 182 183 184 185 186 187 188
            this._parseMap(section.map, section.offset.line, section.offset.column);
        }
    },

    /**
     * @param {number} lineNumber in compiled resource
     * @param {number} columnNumber in compiled resource
     * @return {?Array}
     */
189
    findEntry(lineNumber, columnNumber)
190
    {
191 192
        let first = 0;
        let count = this._mappings.length;
193
        while (count > 1) {
194 195 196
          const step = count >> 1;
          const middle = first + step;
          const mapping = this._mappings[middle];
197 198 199 200 201 202 203
          if (lineNumber < mapping[0] || (lineNumber === mapping[0] && columnNumber < mapping[1]))
              count = step;
          else {
              first = middle;
              count -= step;
          }
        }
204
        const entry = this._mappings[first];
205 206 207 208 209 210 211 212 213 214
        if (!first && entry && (lineNumber < entry[0] || (lineNumber === entry[0] && columnNumber < entry[1])))
            return null;
        return entry;
    },

    /**
     * @param {string} sourceURL of the originating resource
     * @param {number} lineNumber in the originating resource
     * @return {Array}
     */
215
    findEntryReversed(sourceURL, lineNumber)
216
    {
217
        const mappings = this._reverseMappingsBySourceURL[sourceURL];
218
        for ( ; lineNumber < mappings.length; ++lineNumber) {
219
            const mapping = mappings[lineNumber];
220 221 222 223 224 225 226 227 228
            if (mapping)
                return mapping;
        }
        return this._mappings[0];
    },

    /**
     * @override
     */
229
    _parseMap(map, lineNumber, columnNumber)
230
    {
231 232 233 234 235 236 237 238 239 240 241 242 243
        let sourceIndex = 0;
        let sourceLineNumber = 0;
        let sourceColumnNumber = 0;
        let nameIndex = 0;

        const sources = [];
        const originalToCanonicalURLMap = {};
        for (let i = 0; i < map.sources.length; ++i) {
            const originalSourceURL = map.sources[i];
            let sourceRoot = map.sourceRoot || "";
            if (sourceRoot && !sourceRoot.endsWith("/")) sourceRoot += "/";
            const href = sourceRoot + originalSourceURL;
            const url = WebInspector.ParsedURL.completeURL(this._sourceMappingURL, href) || href;
244 245 246 247
            originalToCanonicalURLMap[originalSourceURL] = url;
            sources.push(url);
            this._sources[url] = true;

248
            if (map.sourcesContent && map.sourcesContent[i]) {
249
                this._sourceContentByURL[url] = map.sourcesContent[i];
250
            }
251 252
        }

253 254
        const stringCharIterator = new WebInspector.SourceMap.StringCharIterator(map.mappings);
        let sourceURL = sources[sourceIndex];
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

        while (true) {
            if (stringCharIterator.peek() === ",")
                stringCharIterator.next();
            else {
                while (stringCharIterator.peek() === ";") {
                    lineNumber += 1;
                    columnNumber = 0;
                    stringCharIterator.next();
                }
                if (!stringCharIterator.hasNext())
                    break;
            }

            columnNumber += this._decodeVLQ(stringCharIterator);
            if (this._isSeparator(stringCharIterator.peek())) {
                this._mappings.push([lineNumber, columnNumber]);
                continue;
            }

275
            const sourceIndexDelta = this._decodeVLQ(stringCharIterator);
276 277 278 279 280 281 282 283 284 285 286 287
            if (sourceIndexDelta) {
                sourceIndex += sourceIndexDelta;
                sourceURL = sources[sourceIndex];
            }
            sourceLineNumber += this._decodeVLQ(stringCharIterator);
            sourceColumnNumber += this._decodeVLQ(stringCharIterator);
            if (!this._isSeparator(stringCharIterator.peek()))
                nameIndex += this._decodeVLQ(stringCharIterator);

            this._mappings.push([lineNumber, columnNumber, sourceURL, sourceLineNumber, sourceColumnNumber]);
        }

288 289 290 291 292
        for (let i = 0; i < this._mappings.length; ++i) {
            const mapping = this._mappings[i];
            const url = mapping[2];
            if (!url) continue;
            if (!this._reverseMappingsBySourceURL[url]) {
293
                this._reverseMappingsBySourceURL[url] = [];
294 295 296 297
            }
            const reverseMappings = this._reverseMappingsBySourceURL[url];
            const sourceLine = mapping[3];
            if (!reverseMappings[sourceLine]) {
298
                reverseMappings[sourceLine] = [mapping[0], mapping[1]];
299
            }
300 301 302 303 304 305 306
        }
    },

    /**
     * @param {string} char
     * @return {boolean}
     */
307
    _isSeparator(char)
308 309 310 311 312 313 314 315
    {
        return char === "," || char === ";";
    },

    /**
     * @param {WebInspector.SourceMap.StringCharIterator} stringCharIterator
     * @return {number}
     */
316
    _decodeVLQ(stringCharIterator)
317 318
    {
        // Read unsigned value.
319 320 321
        let result = 0;
        let shift = 0;
        let digit;
322
        do {
323
            digit = this._base64Map[stringCharIterator.next()];
324 325 326 327 328
            result += (digit & this._VLQ_BASE_MASK) << shift;
            shift += this._VLQ_BASE_SHIFT;
        } while (digit & this._VLQ_CONTINUATION_MASK);

        // Fix the sign.
329
        const negate = result & 1;
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        // Use unsigned right shift, so that the 32nd bit is properly shifted
        // to the 31st, and the 32nd becomes unset.
        result >>>= 1;
        if (negate) {
          // We need to OR 0x80000000 here to ensure the 32nd bit (the sign bit
          // in a 32bit int) is always set for negative numbers. If `result`
          // were 1, (meaning `negate` is true and all other bits were zeros),
          // `result` would now be 0. But -0 doesn't flip the 32nd bit as
          // intended. All other numbers will successfully set the 32nd bit
          // without issue, so doing this is a noop for them.
          return -result | 0x80000000;
        }
        return result;
    },

    _VLQ_BASE_SHIFT: 5,
    _VLQ_BASE_MASK: (1 << 5) - 1,
    _VLQ_CONTINUATION_MASK: 1 << 5
}

/**
 * @constructor
 * @param {string} string
 */
WebInspector.SourceMap.StringCharIterator = function(string)
{
    this._string = string;
    this._position = 0;
}

WebInspector.SourceMap.StringCharIterator.prototype = {
    /**
     * @return {string}
     */
364
    next()
365 366 367 368 369 370 371
    {
        return this._string.charAt(this._position++);
    },

    /**
     * @return {string}
     */
372
    peek()
373 374 375 376 377 378 379
    {
        return this._string.charAt(this._position);
    },

    /**
     * @return {boolean}
     */
380
    hasNext()
381 382 383 384
    {
        return this._position < this._string.length;
    }
}