uni-stacktracey.cjs.js 125.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

fxy060608's avatar
fxy060608 已提交
5
var fs = require('fs');
fxy060608's avatar
fxy060608 已提交
6
var path = require('path');
fxy060608's avatar
fxy060608 已提交
7
var os = require('os');
fxy060608's avatar
fxy060608 已提交
8 9 10

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

fxy060608's avatar
fxy060608 已提交
11
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
fxy060608's avatar
fxy060608 已提交
12
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
fxy060608's avatar
fxy060608 已提交
13
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
fxy060608's avatar
fxy060608 已提交
14

15
/*  ------------------------------------------------------------------------ */
fxy060608's avatar
fxy060608 已提交
16 17 18 19
const O = Object, isBrowser = 
/* eslint-disable */
typeof window !== 'undefined' &&
    /* eslint-disable */
20
    window.window === window &&
fxy060608's avatar
fxy060608 已提交
21
    /* eslint-disable */
22 23 24 25
    window.navigator, nodeRequire = isBrowser ? null : module.require, // to prevent bundlers from expanding the require call
lastOf = (x) => x[x.length - 1], nixSlashes$1 = (x) => x.replace(/\\/g, '/'), pathRoot = isBrowser ? window.location.href : nixSlashes$1(process.cwd()) + '/';
/*  ------------------------------------------------------------------------ */
class StackTracey {
26
    constructor(input, uniPlatform, offset) {
27 28 29 30 31 32 33 34 35 36 37 38 39 40
        this.itemsHeader = [];
        this.isMP = false;
        const originalInput = input, isParseableSyntaxError = input && input instanceof SyntaxError && !isBrowser;
        /*  new StackTracey ()            */
        if (!input) {
            input = new Error();
            offset = offset === undefined ? 1 : offset;
        }
        /*  new StackTracey (Error)      */
        if (input instanceof Error) {
            input = input.stack || '';
        }
        /*  new StackTracey (string)     */
        if (typeof input === 'string') {
41
            this.isMP = uniPlatform === 'mp-weixin';
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 80 81 82 83 84 85 86 87 88 89 90 91
            input = this.rawParse(input)
                .slice(offset)
                .map((x) => this.extractEntryMetadata(x));
        }
        /*  new StackTracey (array)      */
        if (Array.isArray(input)) {
            if (isParseableSyntaxError) {
                const rawLines = nodeRequire('util')
                    .inspect(originalInput)
                    .split('\n'), fileLine = rawLines[0].split(':'), line = fileLine.pop(), file = fileLine.join(':');
                if (file) {
                    input.unshift({
                        file: nixSlashes$1(file),
                        line: line,
                        column: (rawLines[2] || '').indexOf('^') + 1,
                        sourceLine: rawLines[1],
                        callee: '(syntax error)',
                        syntaxError: true,
                    });
                }
            }
            this.items = input;
        }
        else {
            this.items = [];
        }
    }
    extractEntryMetadata(e) {
        const decomposedPath = this.decomposePath(e.file || '');
        const fileRelative = decomposedPath[0];
        const externalDomain = decomposedPath[1];
        return O.assign(e, {
            calleeShort: e.calleeShort || lastOf((e.callee || '').split('.')),
            fileRelative: fileRelative,
            fileShort: this.shortenPath(fileRelative),
            fileName: lastOf((e.file || '').split('/')),
            thirdParty: this.isThirdParty(fileRelative, externalDomain) && !e.index,
            externalDomain: externalDomain,
        });
    }
    shortenPath(relativePath) {
        return relativePath
            .replace(/^node_modules\//, '')
            .replace(/^webpack\/bootstrap\//, '')
            .replace(/^__parcel_source_root\//, '');
    }
    decomposePath(fullPath) {
        let result = fullPath;
        if (isBrowser)
            result = result.replace(pathRoot, '');
92
        const externalDomainMatch = result.match(/^(http|https)\:\/\/?([^\/]+)\/{1,}(.*)/);
93 94 95 96
        const externalDomain = externalDomainMatch
            ? externalDomainMatch[2]
            : undefined;
        result = externalDomainMatch ? externalDomainMatch[3] : result;
97
        // if (!isBrowser) result = nodeRequire!('path').relative(pathRoot, result)
98 99 100 101 102 103 104 105 106 107 108
        return [
            nixSlashes$1(result).replace(/^.*\:\/\/?\/?/, ''),
            externalDomain,
        ];
    }
    isThirdParty(relativePath, externalDomain) {
        if (this.isMP) {
            if (typeof externalDomain === 'undefined')
                return false;
            return externalDomain !== 'usr';
        }
109 110 111 112
        return (
        // 由于 hello-uniapp web 端报错携带 hellouniapp.dcloud.net.cn
        // externalDomain ||
        relativePath[0] === '~' || // webpack-specific heuristic
113 114
            relativePath[0] === '/' || // external source
            relativePath.indexOf('@dcloudio') !== -1 ||
115
            relativePath.indexOf('weex-main-jsfm') !== -1 ||
116 117 118 119 120 121 122
            relativePath.indexOf('webpack/bootstrap') === 0);
    }
    rawParse(str) {
        const lines = (str || '').split('\n');
        const entries = lines.map((line, index) => {
            line = line.trim();
            let callee, fileLineColumn = [], native, planA, planB;
123 124 125
            if (line.indexOf('file:') !== -1) {
                line = line.replace(/file:\/\/(.*)www/, 'file://');
            }
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
            if ((planA = line.match(/at (.+) \(eval at .+ \((.+)\), .+\)/)) || // eval calls
                (planA = line.match(/at (.+) \((.+)\)/)) ||
                (line.slice(0, 3) !== 'at ' && (planA = line.match(/(.*)@(.*)/)))) {
                this.itemsHeader.push('%StacktraceyItem%');
                callee = planA[1];
                native = planA[2] === 'native';
                fileLineColumn = (planA[2].match(/(.*):(\d+):(\d+)/) ||
                    planA[2].match(/(.*):(\d+)/) ||
                    planA[2].match(/\[(.*)\]/) ||
                    []).slice(1);
            }
            else if ((planB = line.match(/^(at\s*)*(.*)\s+(.+):(\d+):(\d+)/))) {
                this.itemsHeader.push('%StacktraceyItem%');
                callee = planB[2].trim();
                fileLineColumn = planB.slice(3);
            }
            else {
                this.itemsHeader.push(line);
                return undefined;
            }
            /*  Detect things like Array.reduce
                TODO: detect more built-in types            */
            if (callee && !fileLineColumn[0]) {
                const type = callee.split('.')[0];
                if (type === 'Array') {
                    native = true;
                }
            }
            return {
                beforeParse: line,
                callee: callee || '',
fxy060608's avatar
fxy060608 已提交
157
                /* eslint-disable */
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
                index: isBrowser && fileLineColumn[0] === window.location.href,
                native: native || false,
                file: nixSlashes$1(fileLineColumn[0] || ''),
                line: parseInt(fileLineColumn[1] || '', 10) || undefined,
                column: parseInt(fileLineColumn[2] || '', 10) || undefined,
            };
        });
        return entries.filter((x) => x !== undefined);
    }
    maxColumnWidths() {
        return {
            callee: 30,
            file: 60,
            sourceLine: 80,
        };
    }
    asTable(opts) {
        const maxColumnWidths = (opts && opts.maxColumnWidths) || this.maxColumnWidths();
        const trimmed = this
            .filter((e) => !e.thirdParty)
            .map((e) => parseItem(e, maxColumnWidths, this.isMP));
        const trimmedThirdParty = this
            .filter((e) => e.thirdParty)
            .map((e) => parseItem(e, maxColumnWidths, this.isMP));
        return {
            items: trimmed.items,
            thirdPartyItems: trimmedThirdParty.items,
        };
    }
}
const trimEnd = (s, n) => s && (s.length > n ? s.slice(0, n - 1) + '' : s);
const trimStart = (s, n) => s && (s.length > n ? '' + s.slice(-(n - 1)) : s);
function parseItem(e, maxColumnWidths, isMP) {
191 192 193
    if (!e.parsed) {
        return e.beforeParse;
    }
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    const filePath = (isMP ? e.file && e.file : e.fileShort && e.fileShort) +
        `${e.line ? ':' + e.line : ''}` +
        `${e.column ? ':' + e.column : ''}`;
    return [
        'at ' + trimEnd(isMP ? e.callee : e.calleeShort, maxColumnWidths.callee),
        trimStart(filePath || '', maxColumnWidths.file),
        trimEnd((e.sourceLine || '').trim() || '', maxColumnWidths.sourceLine),
    ];
}
['map', 'filter', 'slice', 'concat'].forEach((method) => {
    StackTracey.prototype[method] = function ( /*...args */) {
        // no support for ...args in Node v4 :(
        return new StackTracey(this.items[method].apply(this.items, arguments));
    };
});
/*  ------------------------------------------------------------------------ */
fxy060608's avatar
fxy060608 已提交
210 211
var StackTracey$1 = StackTracey;

D
DCloud_LXH 已提交
212 213 214 215 216 217 218
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

fxy060608's avatar
fxy060608 已提交
219 220
const intToCharMap =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
D
DCloud_LXH 已提交
221 222 223 224

/**
 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
 */
fxy060608's avatar
fxy060608 已提交
225
var encode$1 = function (number) {
D
DCloud_LXH 已提交
226
  if (0 <= number && number < intToCharMap.length) {
fxy060608's avatar
fxy060608 已提交
227
    return intToCharMap[number]
D
DCloud_LXH 已提交
228
  }
fxy060608's avatar
fxy060608 已提交
229
  throw new TypeError('Must be between 0 and 63: ' + number)
D
DCloud_LXH 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
};

var base64$1 = {
	encode: encode$1
};

var base64 = base64$1;

/* -*- Mode: js; js-indent-level: 2; -*- */

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * Based on the Base 64 VLQ implementation in Closure Compiler:
 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
 *
 * Copyright 2011 The Closure Compiler 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.
 */



// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
//   Continuation
//   |    Sign
//   |    |
//   V    V
//   101011

const VLQ_BASE_SHIFT = 5;

// binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;

// binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1;

// binary: 100000
const VLQ_CONTINUATION_BIT = VLQ_BASE;

/**
 * Converts from a two-complement value to a value where the sign bit is
 * placed in the least significant bit.  For example, as decimals:
 *   1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
 *   2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
 */
function toVLQSigned(aValue) {
fxy060608's avatar
fxy060608 已提交
308
  return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0
D
DCloud_LXH 已提交
309 310 311 312 313 314
}

/**
 * Returns the base 64 VLQ encoded value.
 */
var encode = function base64VLQ_encode(aValue) {
fxy060608's avatar
fxy060608 已提交
315
  let encoded = '';
D
DCloud_LXH 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328
  let digit;

  let vlq = toVLQSigned(aValue);

  do {
    digit = vlq & VLQ_BASE_MASK;
    vlq >>>= VLQ_BASE_SHIFT;
    if (vlq > 0) {
      // There are still more digits in this value, so we must make sure the
      // continuation bit is marked.
      digit |= VLQ_CONTINUATION_BIT;
    }
    encoded += base64.encode(digit);
fxy060608's avatar
fxy060608 已提交
329
  } while (vlq > 0)
D
DCloud_LXH 已提交
330

fxy060608's avatar
fxy060608 已提交
331
  return encoded
D
DCloud_LXH 已提交
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
};

var base64Vlq = {
	encode: encode
};

function createCommonjsModule(fn) {
  var module = { exports: {} };
	return fn(module, module.exports), module.exports;
}

/* -*- Mode: js; js-indent-level: 2; -*- */

var util$1 = createCommonjsModule(function (module, exports) {
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/**
 * This is a helper function for getting values from parameter/options
 * objects.
 *
 * @param args The object we are extracting values from
 * @param name The name of the property we are getting.
 * @param defaultValue An optional value to return if the property is missing
 * from the object. If this is not specified and the property is missing, an
 * error will be thrown.
 */
function getArg(aArgs, aName, aDefaultValue) {
  if (aName in aArgs) {
fxy060608's avatar
fxy060608 已提交
364
    return aArgs[aName]
D
DCloud_LXH 已提交
365
  } else if (arguments.length === 3) {
fxy060608's avatar
fxy060608 已提交
366
    return aDefaultValue
D
DCloud_LXH 已提交
367
  }
fxy060608's avatar
fxy060608 已提交
368
  throw new Error('"' + aName + '" is a required argument.')
D
DCloud_LXH 已提交
369 370 371
}
exports.getArg = getArg;

fxy060608's avatar
fxy060608 已提交
372 373
const urlRegexp =
  /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
D
DCloud_LXH 已提交
374 375 376 377 378
const dataUrlRegexp = /^data:.+\,.+$/;

function urlParse(aUrl) {
  const match = aUrl.match(urlRegexp);
  if (!match) {
fxy060608's avatar
fxy060608 已提交
379
    return null
D
DCloud_LXH 已提交
380 381 382 383 384 385
  }
  return {
    scheme: match[1],
    auth: match[2],
    host: match[3],
    port: match[4],
fxy060608's avatar
fxy060608 已提交
386 387
    path: match[5],
  }
D
DCloud_LXH 已提交
388 389 390 391
}
exports.urlParse = urlParse;

function urlGenerate(aParsedUrl) {
fxy060608's avatar
fxy060608 已提交
392
  let url = '';
D
DCloud_LXH 已提交
393
  if (aParsedUrl.scheme) {
fxy060608's avatar
fxy060608 已提交
394
    url += aParsedUrl.scheme + ':';
D
DCloud_LXH 已提交
395
  }
fxy060608's avatar
fxy060608 已提交
396
  url += '//';
D
DCloud_LXH 已提交
397
  if (aParsedUrl.auth) {
fxy060608's avatar
fxy060608 已提交
398
    url += aParsedUrl.auth + '@';
D
DCloud_LXH 已提交
399 400 401 402 403
  }
  if (aParsedUrl.host) {
    url += aParsedUrl.host;
  }
  if (aParsedUrl.port) {
fxy060608's avatar
fxy060608 已提交
404
    url += ':' + aParsedUrl.port;
D
DCloud_LXH 已提交
405 406 407 408
  }
  if (aParsedUrl.path) {
    url += aParsedUrl.path;
  }
fxy060608's avatar
fxy060608 已提交
409
  return url
D
DCloud_LXH 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
}
exports.urlGenerate = urlGenerate;

const MAX_CACHED_INPUTS = 32;

/**
 * Takes some function `f(input) -> result` and returns a memoized version of
 * `f`.
 *
 * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
 * memoization is a dumb-simple, linear least-recently-used cache.
 */
function lruMemoize(f) {
  const cache = [];

fxy060608's avatar
fxy060608 已提交
425
  return function (input) {
D
DCloud_LXH 已提交
426 427 428 429 430
    for (let i = 0; i < cache.length; i++) {
      if (cache[i].input === input) {
        const temp = cache[0];
        cache[0] = cache[i];
        cache[i] = temp;
fxy060608's avatar
fxy060608 已提交
431
        return cache[0].result
D
DCloud_LXH 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445
      }
    }

    const result = f(input);

    cache.unshift({
      input,
      result,
    });

    if (cache.length > MAX_CACHED_INPUTS) {
      cache.pop();
    }

fxy060608's avatar
fxy060608 已提交
446 447
    return result
  }
D
DCloud_LXH 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

/**
 * Normalizes a path, or the path portion of a URL:
 *
 * - Replaces consecutive slashes with one slash.
 * - Removes unnecessary '.' parts.
 * - Removes unnecessary '<dir>/..' parts.
 *
 * Based on code in the Node.js 'path' core module.
 *
 * @param aPath The path or url to normalize.
 */
const normalize = lruMemoize(function normalize(aPath) {
  let path = aPath;
  const url = urlParse(aPath);
  if (url) {
    if (!url.path) {
fxy060608's avatar
fxy060608 已提交
466
      return aPath
D
DCloud_LXH 已提交
467 468 469 470 471 472 473 474 475 476 477 478
    }
    path = url.path;
  }
  const isAbsolute = exports.isAbsolute(path);

  // Split the path into parts between `/` characters. This is much faster than
  // using `.split(/\/+/g)`.
  const parts = [];
  let start = 0;
  let i = 0;
  while (true) {
    start = i;
fxy060608's avatar
fxy060608 已提交
479
    i = path.indexOf('/', start);
D
DCloud_LXH 已提交
480 481
    if (i === -1) {
      parts.push(path.slice(start));
fxy060608's avatar
fxy060608 已提交
482
      break
D
DCloud_LXH 已提交
483 484
    } else {
      parts.push(path.slice(start, i));
fxy060608's avatar
fxy060608 已提交
485
      while (i < path.length && path[i] === '/') {
D
DCloud_LXH 已提交
486 487 488 489 490 491 492 493
        i++;
      }
    }
  }

  let up = 0;
  for (i = parts.length - 1; i >= 0; i--) {
    const part = parts[i];
fxy060608's avatar
fxy060608 已提交
494
    if (part === '.') {
D
DCloud_LXH 已提交
495
      parts.splice(i, 1);
fxy060608's avatar
fxy060608 已提交
496
    } else if (part === '..') {
D
DCloud_LXH 已提交
497 498
      up++;
    } else if (up > 0) {
fxy060608's avatar
fxy060608 已提交
499
      if (part === '') {
D
DCloud_LXH 已提交
500 501 502 503 504 505 506 507 508 509 510
        // The first part is blank if the path is absolute. Trying to go
        // above the root is a no-op. Therefore we can remove all '..' parts
        // directly after the root.
        parts.splice(i + 1, up);
        up = 0;
      } else {
        parts.splice(i, 2);
        up--;
      }
    }
  }
fxy060608's avatar
fxy060608 已提交
511
  path = parts.join('/');
D
DCloud_LXH 已提交
512

fxy060608's avatar
fxy060608 已提交
513 514
  if (path === '') {
    path = isAbsolute ? '/' : '.';
D
DCloud_LXH 已提交
515 516 517 518
  }

  if (url) {
    url.path = path;
fxy060608's avatar
fxy060608 已提交
519
    return urlGenerate(url)
D
DCloud_LXH 已提交
520
  }
fxy060608's avatar
fxy060608 已提交
521
  return path
D
DCloud_LXH 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
});
exports.normalize = normalize;

/**
 * Joins two paths/URLs.
 *
 * @param aRoot The root path or URL.
 * @param aPath The path or URL to be joined with the root.
 *
 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
 *   scheme-relative URL: Then the scheme of aRoot, if any, is prepended
 *   first.
 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
 *   is updated with the result and aRoot is returned. Otherwise the result
 *   is returned.
 *   - If aPath is absolute, the result is aPath.
 *   - Otherwise the two paths are joined with a slash.
 * - Joining for example 'http://' and 'www.example.com' is also supported.
 */
function join(aRoot, aPath) {
fxy060608's avatar
fxy060608 已提交
542 543
  if (aRoot === '') {
    aRoot = '.';
D
DCloud_LXH 已提交
544
  }
fxy060608's avatar
fxy060608 已提交
545 546
  if (aPath === '') {
    aPath = '.';
D
DCloud_LXH 已提交
547 548 549 550
  }
  const aPathUrl = urlParse(aPath);
  const aRootUrl = urlParse(aRoot);
  if (aRootUrl) {
fxy060608's avatar
fxy060608 已提交
551
    aRoot = aRootUrl.path || '/';
D
DCloud_LXH 已提交
552 553 554 555 556 557 558
  }

  // `join(foo, '//www.example.org')`
  if (aPathUrl && !aPathUrl.scheme) {
    if (aRootUrl) {
      aPathUrl.scheme = aRootUrl.scheme;
    }
fxy060608's avatar
fxy060608 已提交
559
    return urlGenerate(aPathUrl)
D
DCloud_LXH 已提交
560 561 562
  }

  if (aPathUrl || aPath.match(dataUrlRegexp)) {
fxy060608's avatar
fxy060608 已提交
563
    return aPath
D
DCloud_LXH 已提交
564 565 566 567 568
  }

  // `join('http://', 'www.example.com')`
  if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
    aRootUrl.host = aPath;
fxy060608's avatar
fxy060608 已提交
569
    return urlGenerate(aRootUrl)
D
DCloud_LXH 已提交
570 571
  }

fxy060608's avatar
fxy060608 已提交
572 573 574 575
  const joined =
    aPath.charAt(0) === '/'
      ? aPath
      : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
D
DCloud_LXH 已提交
576 577 578

  if (aRootUrl) {
    aRootUrl.path = joined;
fxy060608's avatar
fxy060608 已提交
579
    return urlGenerate(aRootUrl)
D
DCloud_LXH 已提交
580
  }
fxy060608's avatar
fxy060608 已提交
581
  return joined
D
DCloud_LXH 已提交
582 583 584
}
exports.join = join;

fxy060608's avatar
fxy060608 已提交
585 586
exports.isAbsolute = function (aPath) {
  return aPath.charAt(0) === '/' || urlRegexp.test(aPath)
D
DCloud_LXH 已提交
587 588 589 590 591 592 593 594 595
};

/**
 * Make a path relative to a URL or another path.
 *
 * @param aRoot The root path or URL.
 * @param aPath The path or URL to be made relative to aRoot.
 */
function relative(aRoot, aPath) {
fxy060608's avatar
fxy060608 已提交
596 597
  if (aRoot === '') {
    aRoot = '.';
D
DCloud_LXH 已提交
598 599
  }

fxy060608's avatar
fxy060608 已提交
600
  aRoot = aRoot.replace(/\/$/, '');
D
DCloud_LXH 已提交
601 602 603 604 605 606

  // It is possible for the path to be above the root. In this case, simply
  // checking whether the root is a prefix of the path won't work. Instead, we
  // need to remove components from the root one by one, until either we find
  // a prefix that fits, or we run out of components to remove.
  let level = 0;
fxy060608's avatar
fxy060608 已提交
607 608
  while (aPath.indexOf(aRoot + '/') !== 0) {
    const index = aRoot.lastIndexOf('/');
D
DCloud_LXH 已提交
609
    if (index < 0) {
fxy060608's avatar
fxy060608 已提交
610
      return aPath
D
DCloud_LXH 已提交
611 612 613 614 615 616 617
    }

    // If the only part of the root that is left is the scheme (i.e. http://,
    // file:///, etc.), one or more slashes (/), or simply nothing at all, we
    // have exhausted all components, so the path is not relative to the root.
    aRoot = aRoot.slice(0, index);
    if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
fxy060608's avatar
fxy060608 已提交
618
      return aPath
D
DCloud_LXH 已提交
619 620 621 622 623 624
    }

    ++level;
  }

  // Make sure we add a "../" for each component we removed from the root.
fxy060608's avatar
fxy060608 已提交
625
  return Array(level + 1).join('../') + aPath.substr(aRoot.length + 1)
D
DCloud_LXH 已提交
626 627 628
}
exports.relative = relative;

fxy060608's avatar
fxy060608 已提交
629
const supportsNullProto = (function () {
D
DCloud_LXH 已提交
630
  const obj = Object.create(null);
fxy060608's avatar
fxy060608 已提交
631 632
  return !('__proto__' in obj)
})();
D
DCloud_LXH 已提交
633 634

function identity(s) {
fxy060608's avatar
fxy060608 已提交
635
  return s
D
DCloud_LXH 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648
}

/**
 * Because behavior goes wacky when you set `__proto__` on objects, we
 * have to prefix all the strings in our set with an arbitrary character.
 *
 * See https://github.com/mozilla/source-map/pull/31 and
 * https://github.com/mozilla/source-map/issues/30
 *
 * @param String aStr
 */
function toSetString(aStr) {
  if (isProtoString(aStr)) {
fxy060608's avatar
fxy060608 已提交
649
    return '$' + aStr
D
DCloud_LXH 已提交
650 651
  }

fxy060608's avatar
fxy060608 已提交
652
  return aStr
D
DCloud_LXH 已提交
653 654 655 656 657
}
exports.toSetString = supportsNullProto ? identity : toSetString;

function fromSetString(aStr) {
  if (isProtoString(aStr)) {
fxy060608's avatar
fxy060608 已提交
658
    return aStr.slice(1)
D
DCloud_LXH 已提交
659 660
  }

fxy060608's avatar
fxy060608 已提交
661
  return aStr
D
DCloud_LXH 已提交
662 663 664 665 666
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;

function isProtoString(s) {
  if (!s) {
fxy060608's avatar
fxy060608 已提交
667
    return false
D
DCloud_LXH 已提交
668 669 670 671 672
  }

  const length = s.length;

  if (length < 9 /* "__proto__".length */) {
fxy060608's avatar
fxy060608 已提交
673
    return false
D
DCloud_LXH 已提交
674 675 676
  }

  /* eslint-disable no-multi-spaces */
fxy060608's avatar
fxy060608 已提交
677 678 679 680 681 682 683 684 685 686 687 688
  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
D
DCloud_LXH 已提交
689 690 691 692 693
  }
  /* eslint-enable no-multi-spaces */

  for (let i = length - 10; i >= 0; i--) {
    if (s.charCodeAt(i) !== 36 /* '$' */) {
fxy060608's avatar
fxy060608 已提交
694
      return false
D
DCloud_LXH 已提交
695 696 697
    }
  }

fxy060608's avatar
fxy060608 已提交
698
  return true
D
DCloud_LXH 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711
}

/**
 * Comparator between two mappings where the original positions are compared.
 *
 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
 * mappings with the same original source/line/column, but different generated
 * line and column the same. Useful when searching for a mapping with a
 * stubbed out mapping.
 */
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  let cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
712
    return cmp
D
DCloud_LXH 已提交
713 714 715 716
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
717
    return cmp
D
DCloud_LXH 已提交
718 719 720 721
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0 || onlyCompareOriginal) {
fxy060608's avatar
fxy060608 已提交
722
    return cmp
D
DCloud_LXH 已提交
723 724 725 726
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
727
    return cmp
D
DCloud_LXH 已提交
728 729 730 731
  }

  cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
732
    return cmp
D
DCloud_LXH 已提交
733 734
  }

fxy060608's avatar
fxy060608 已提交
735
  return strcmp(mappingA.name, mappingB.name)
D
DCloud_LXH 已提交
736 737 738 739 740 741 742 743 744 745 746 747
}
exports.compareByOriginalPositions = compareByOriginalPositions;

/**
 * Comparator between two mappings with deflated source and name indices where
 * the generated positions are compared.
 *
 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
 * mappings with the same generated line and column, but different
 * source/name/original line and column the same. Useful when searching for a
 * mapping with a stubbed out mapping.
 */
fxy060608's avatar
fxy060608 已提交
748 749 750 751 752
function compareByGeneratedPositionsDeflated(
  mappingA,
  mappingB,
  onlyCompareGenerated
) {
D
DCloud_LXH 已提交
753 754
  let cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
755
    return cmp
D
DCloud_LXH 已提交
756 757 758 759
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0 || onlyCompareGenerated) {
fxy060608's avatar
fxy060608 已提交
760
    return cmp
D
DCloud_LXH 已提交
761 762 763 764
  }

  cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
765
    return cmp
D
DCloud_LXH 已提交
766 767 768 769
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
770
    return cmp
D
DCloud_LXH 已提交
771 772 773 774
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
775
    return cmp
D
DCloud_LXH 已提交
776 777
  }

fxy060608's avatar
fxy060608 已提交
778
  return strcmp(mappingA.name, mappingB.name)
D
DCloud_LXH 已提交
779
}
fxy060608's avatar
fxy060608 已提交
780 781
exports.compareByGeneratedPositionsDeflated =
  compareByGeneratedPositionsDeflated;
D
DCloud_LXH 已提交
782 783 784

function strcmp(aStr1, aStr2) {
  if (aStr1 === aStr2) {
fxy060608's avatar
fxy060608 已提交
785
    return 0
D
DCloud_LXH 已提交
786 787 788
  }

  if (aStr1 === null) {
fxy060608's avatar
fxy060608 已提交
789
    return 1 // aStr2 !== null
D
DCloud_LXH 已提交
790 791 792
  }

  if (aStr2 === null) {
fxy060608's avatar
fxy060608 已提交
793
    return -1 // aStr1 !== null
D
DCloud_LXH 已提交
794 795 796
  }

  if (aStr1 > aStr2) {
fxy060608's avatar
fxy060608 已提交
797
    return 1
D
DCloud_LXH 已提交
798 799
  }

fxy060608's avatar
fxy060608 已提交
800
  return -1
D
DCloud_LXH 已提交
801 802 803 804 805 806 807 808 809
}

/**
 * Comparator between two mappings with inflated source and name strings where
 * the generated positions are compared.
 */
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  let cmp = mappingA.generatedLine - mappingB.generatedLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
810
    return cmp
D
DCloud_LXH 已提交
811 812 813 814
  }

  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
815
    return cmp
D
DCloud_LXH 已提交
816 817 818 819
  }

  cmp = strcmp(mappingA.source, mappingB.source);
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
820
    return cmp
D
DCloud_LXH 已提交
821 822 823 824
  }

  cmp = mappingA.originalLine - mappingB.originalLine;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
825
    return cmp
D
DCloud_LXH 已提交
826 827 828 829
  }

  cmp = mappingA.originalColumn - mappingB.originalColumn;
  if (cmp !== 0) {
fxy060608's avatar
fxy060608 已提交
830
    return cmp
D
DCloud_LXH 已提交
831 832
  }

fxy060608's avatar
fxy060608 已提交
833
  return strcmp(mappingA.name, mappingB.name)
D
DCloud_LXH 已提交
834
}
fxy060608's avatar
fxy060608 已提交
835 836
exports.compareByGeneratedPositionsInflated =
  compareByGeneratedPositionsInflated;
D
DCloud_LXH 已提交
837 838 839 840 841 842 843

/**
 * Strip any JSON XSSI avoidance prefix from the string (as documented
 * in the source maps specification), and then parse the string as
 * JSON.
 */
function parseSourceMapInput(str) {
fxy060608's avatar
fxy060608 已提交
844
  return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''))
D
DCloud_LXH 已提交
845 846 847 848 849 850 851 852
}
exports.parseSourceMapInput = parseSourceMapInput;

/**
 * Compute the URL of a source given the the source root, the source's
 * URL, and the source map's URL.
 */
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
fxy060608's avatar
fxy060608 已提交
853
  sourceURL = sourceURL || '';
D
DCloud_LXH 已提交
854 855 856

  if (sourceRoot) {
    // This follows what Chrome does.
fxy060608's avatar
fxy060608 已提交
857 858
    if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
      sourceRoot += '/';
D
DCloud_LXH 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    }
    // The spec says:
    //   Line 4: An optional source root, useful for relocating source
    //   files on a server or removing repeated values in the
    //   “sources” entry.  This value is prepended to the individual
    //   entries in the “source” field.
    sourceURL = sourceRoot + sourceURL;
  }

  // Historically, SourceMapConsumer did not take the sourceMapURL as
  // a parameter.  This mode is still somewhat supported, which is why
  // this code block is conditional.  However, it's preferable to pass
  // the source map URL to SourceMapConsumer, so that this function
  // can implement the source URL resolution algorithm as outlined in
  // the spec.  This block is basically the equivalent of:
  //    new URL(sourceURL, sourceMapURL).toString()
  // ... except it avoids using URL, which wasn't available in the
  // older releases of node still supported by this library.
  //
  // The spec says:
  //   If the sources are not absolute URLs after prepending of the
  //   “sourceRoot”, the sources are resolved relative to the
  //   SourceMap (like resolving script src in a html document).
  if (sourceMapURL) {
    const parsed = urlParse(sourceMapURL);
    if (!parsed) {
fxy060608's avatar
fxy060608 已提交
885
      throw new Error('sourceMapURL could not be parsed')
D
DCloud_LXH 已提交
886 887 888
    }
    if (parsed.path) {
      // Strip the last path component, but keep the "/".
fxy060608's avatar
fxy060608 已提交
889
      const index = parsed.path.lastIndexOf('/');
D
DCloud_LXH 已提交
890 891 892 893 894 895 896
      if (index >= 0) {
        parsed.path = parsed.path.substring(0, index + 1);
      }
    }
    sourceURL = join(urlGenerate(parsed), sourceURL);
  }

fxy060608's avatar
fxy060608 已提交
897
  return normalize(sourceURL)
D
DCloud_LXH 已提交
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
}
exports.computeSourceURL = computeSourceURL;
});

/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

/**
 * A data structure which is a combination of an array and a set. Adding a new
 * member is O(1), testing for membership is O(1), and finding the index of an
 * element is O(1). Removing elements from the set is not supported. Only
 * strings are supported for membership.
 */
class ArraySet$2 {
  constructor() {
    this._array = [];
    this._set = new Map();
  }

  /**
   * Static method for creating ArraySet instances from an existing array.
   */
  static fromArray(aArray, aAllowDuplicates) {
    const set = new ArraySet$2();
    for (let i = 0, len = aArray.length; i < len; i++) {
      set.add(aArray[i], aAllowDuplicates);
    }
fxy060608's avatar
fxy060608 已提交
929
    return set
D
DCloud_LXH 已提交
930 931 932 933 934 935 936 937 938
  }

  /**
   * Return how many unique items are in this ArraySet. If duplicates have been
   * added, than those do not count towards the size.
   *
   * @returns Number
   */
  size() {
fxy060608's avatar
fxy060608 已提交
939
    return this._set.size
D
DCloud_LXH 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
  }

  /**
   * Add the given string to this set.
   *
   * @param String aStr
   */
  add(aStr, aAllowDuplicates) {
    const isDuplicate = this.has(aStr);
    const idx = this._array.length;
    if (!isDuplicate || aAllowDuplicates) {
      this._array.push(aStr);
    }
    if (!isDuplicate) {
      this._set.set(aStr, idx);
    }
  }

  /**
   * Is the given string a member of this set?
   *
   * @param String aStr
   */
  has(aStr) {
fxy060608's avatar
fxy060608 已提交
964
    return this._set.has(aStr)
D
DCloud_LXH 已提交
965 966 967 968 969 970 971 972 973 974
  }

  /**
   * What is the index of the given string in the array?
   *
   * @param String aStr
   */
  indexOf(aStr) {
    const idx = this._set.get(aStr);
    if (idx >= 0) {
fxy060608's avatar
fxy060608 已提交
975
      return idx
D
DCloud_LXH 已提交
976
    }
fxy060608's avatar
fxy060608 已提交
977
    throw new Error('"' + aStr + '" is not in the set.')
D
DCloud_LXH 已提交
978 979 980 981 982 983 984 985 986
  }

  /**
   * What is the element at the given index?
   *
   * @param Number aIdx
   */
  at(aIdx) {
    if (aIdx >= 0 && aIdx < this._array.length) {
fxy060608's avatar
fxy060608 已提交
987
      return this._array[aIdx]
D
DCloud_LXH 已提交
988
    }
fxy060608's avatar
fxy060608 已提交
989
    throw new Error('No element indexed by ' + aIdx)
D
DCloud_LXH 已提交
990 991 992 993 994 995 996 997
  }

  /**
   * Returns the array representation of this set (which has the proper indices
   * indicated by indexOf). Note that this is a copy of the internal array used
   * for storing the members so that no one can mess with internal state.
   */
  toArray() {
fxy060608's avatar
fxy060608 已提交
998
    return this._array.slice()
D
DCloud_LXH 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
  }
}
var ArraySet_1 = ArraySet$2;

var arraySet = {
	ArraySet: ArraySet_1
};

var util = util$1;

/* -*- Mode: js; js-indent-level: 2; -*- */

/*
 * Copyright 2014 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */



/**
 * Determine whether mappingB is after mappingA with respect to generated
 * position.
 */
function generatedPositionAfter(mappingA, mappingB) {
  // Optimized for most common case
  const lineA = mappingA.generatedLine;
  const lineB = mappingB.generatedLine;
  const columnA = mappingA.generatedColumn;
  const columnB = mappingB.generatedColumn;
fxy060608's avatar
fxy060608 已提交
1029 1030 1031 1032 1033
  return (
    lineB > lineA ||
    (lineB == lineA && columnB >= columnA) ||
    util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0
  )
D
DCloud_LXH 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
}

/**
 * A data structure to provide a sorted view of accumulated mappings in a
 * performance conscious manner. It trades a negligible overhead in general
 * case for a large speedup in case of mappings being added in order.
 */
class MappingList$1 {
  constructor() {
    this._array = [];
    this._sorted = true;
    // Serves as infimum
fxy060608's avatar
fxy060608 已提交
1046
    this._last = { generatedLine: -1, generatedColumn: 0 };
D
DCloud_LXH 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  }

  /**
   * Iterate through internal items. This method takes the same arguments that
   * `Array.prototype.forEach` takes.
   *
   * NOTE: The order of the mappings is NOT guaranteed.
   */
  unsortedForEach(aCallback, aThisArg) {
    this._array.forEach(aCallback, aThisArg);
  }

  /**
   * Add the given source mapping.
   *
   * @param Object aMapping
   */
  add(aMapping) {
    if (generatedPositionAfter(this._last, aMapping)) {
      this._last = aMapping;
      this._array.push(aMapping);
    } else {
      this._sorted = false;
      this._array.push(aMapping);
    }
  }

  /**
   * Returns the flat, sorted array of mappings. The mappings are sorted by
   * generated position.
   *
   * WARNING: This method returns internal data without copying, for
   * performance. The return value must NOT be mutated, and should be treated as
   * an immutable borrow. If you want to take ownership, you must make your own
   * copy.
   */
  toArray() {
    if (!this._sorted) {
      this._array.sort(util.compareByGeneratedPositionsInflated);
      this._sorted = true;
    }
fxy060608's avatar
fxy060608 已提交
1088
    return this._array
D
DCloud_LXH 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
  }
}

var MappingList_1 = MappingList$1;

var mappingList = {
	MappingList: MappingList_1
};

var base64VLQ = base64Vlq;

var require$$0$1 = arraySet;

var require$$1$1 = mappingList;

/* -*- Mode: js; js-indent-level: 2; -*- */

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */



const ArraySet$1 = require$$0$1.ArraySet;
const MappingList = require$$1$1.MappingList;

/**
 * An instance of the SourceMapGenerator represents a source map which is
 * being built incrementally. You may pass an object with the following
 * properties:
 *
 *   - file: The filename of the generated source.
 *   - sourceRoot: A root for all relative URLs in this source map.
 */
class SourceMapGenerator$1 {
  constructor(aArgs) {
    if (!aArgs) {
      aArgs = {};
    }
fxy060608's avatar
fxy060608 已提交
1130 1131 1132
    this._file = util.getArg(aArgs, 'file', null);
    this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
    this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
D
DCloud_LXH 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    this._sources = new ArraySet$1();
    this._names = new ArraySet$1();
    this._mappings = new MappingList();
    this._sourcesContents = null;
  }

  /**
   * Creates a new SourceMapGenerator based on a SourceMapConsumer
   *
   * @param aSourceMapConsumer The SourceMap.
   */
  static fromSourceMap(aSourceMapConsumer) {
    const sourceRoot = aSourceMapConsumer.sourceRoot;
    const generator = new SourceMapGenerator$1({
      file: aSourceMapConsumer.file,
fxy060608's avatar
fxy060608 已提交
1148
      sourceRoot,
D
DCloud_LXH 已提交
1149
    });
fxy060608's avatar
fxy060608 已提交
1150
    aSourceMapConsumer.eachMapping(function (mapping) {
D
DCloud_LXH 已提交
1151 1152 1153
      const newMapping = {
        generated: {
          line: mapping.generatedLine,
fxy060608's avatar
fxy060608 已提交
1154 1155
          column: mapping.generatedColumn,
        },
D
DCloud_LXH 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
      };

      if (mapping.source != null) {
        newMapping.source = mapping.source;
        if (sourceRoot != null) {
          newMapping.source = util.relative(sourceRoot, newMapping.source);
        }

        newMapping.original = {
          line: mapping.originalLine,
fxy060608's avatar
fxy060608 已提交
1166
          column: mapping.originalColumn,
D
DCloud_LXH 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175
        };

        if (mapping.name != null) {
          newMapping.name = mapping.name;
        }
      }

      generator.addMapping(newMapping);
    });
fxy060608's avatar
fxy060608 已提交
1176
    aSourceMapConsumer.sources.forEach(function (sourceFile) {
D
DCloud_LXH 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
      let sourceRelative = sourceFile;
      if (sourceRoot !== null) {
        sourceRelative = util.relative(sourceRoot, sourceFile);
      }

      if (!generator._sources.has(sourceRelative)) {
        generator._sources.add(sourceRelative);
      }

      const content = aSourceMapConsumer.sourceContentFor(sourceFile);
      if (content != null) {
        generator.setSourceContent(sourceFile, content);
      }
    });
fxy060608's avatar
fxy060608 已提交
1191
    return generator
D
DCloud_LXH 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
  }

  /**
   * 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(aArgs) {
fxy060608's avatar
fxy060608 已提交
1205 1206 1207 1208
    const generated = util.getArg(aArgs, 'generated');
    const original = util.getArg(aArgs, 'original', null);
    let source = util.getArg(aArgs, 'source', null);
    let name = util.getArg(aArgs, 'name', null);
D
DCloud_LXH 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

    if (!this._skipValidation) {
      this._validateMapping(generated, original, source, name);
    }

    if (source != null) {
      source = String(source);
      if (!this._sources.has(source)) {
        this._sources.add(source);
      }
    }

    if (name != null) {
      name = String(name);
      if (!this._names.has(name)) {
        this._names.add(name);
      }
    }

    this._mappings.add({
      generatedLine: generated.line,
      generatedColumn: generated.column,
      originalLine: original != null && original.line,
      originalColumn: original != null && original.column,
      source,
fxy060608's avatar
fxy060608 已提交
1234
      name,
D
DCloud_LXH 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    });
  }

  /**
   * Set the source content for a source file.
   */
  setSourceContent(aSourceFile, aSourceContent) {
    let source = aSourceFile;
    if (this._sourceRoot != null) {
      source = util.relative(this._sourceRoot, source);
    }

    if (aSourceContent != null) {
      // Add the source content to the _sourcesContents map.
      // Create a new _sourcesContents map if the property is null.
      if (!this._sourcesContents) {
        this._sourcesContents = Object.create(null);
      }
      this._sourcesContents[util.toSetString(source)] = aSourceContent;
    } else if (this._sourcesContents) {
      // Remove the source file from the _sourcesContents map.
      // If the _sourcesContents map is empty, set the property to null.
      delete this._sourcesContents[util.toSetString(source)];
      if (Object.keys(this._sourcesContents).length === 0) {
        this._sourcesContents = null;
      }
    }
  }

  /**
   * 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 aSourceMapConsumer The source map to be applied.
   * @param aSourceFile Optional. The filename of the source file.
   *        If omitted, SourceMapConsumer's file property will be used.
   * @param aSourceMapPath 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(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
    let sourceFile = aSourceFile;
    // If aSourceFile is omitted, we will use the file property of the SourceMap
    if (aSourceFile == null) {
      if (aSourceMapConsumer.file == null) {
        throw new Error(
fxy060608's avatar
fxy060608 已提交
1286 1287 1288
          'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
            'or the source map\'s "file" property. Both were omitted.'
        )
D
DCloud_LXH 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
      }
      sourceFile = aSourceMapConsumer.file;
    }
    const sourceRoot = this._sourceRoot;
    // Make "sourceFile" relative if an absolute Url is passed.
    if (sourceRoot != null) {
      sourceFile = util.relative(sourceRoot, sourceFile);
    }
    // Applying the SourceMap can add and remove items from the sources and
    // the names array.
fxy060608's avatar
fxy060608 已提交
1299 1300
    const newSources =
      this._mappings.toArray().length > 0 ? new ArraySet$1() : this._sources;
D
DCloud_LXH 已提交
1301 1302 1303
    const newNames = new ArraySet$1();

    // Find mappings for the "sourceFile"
fxy060608's avatar
fxy060608 已提交
1304
    this._mappings.unsortedForEach(function (mapping) {
D
DCloud_LXH 已提交
1305 1306 1307 1308
      if (mapping.source === sourceFile && mapping.originalLine != null) {
        // Check if it can be mapped by the source map, then update the mapping.
        const original = aSourceMapConsumer.originalPositionFor({
          line: mapping.originalLine,
fxy060608's avatar
fxy060608 已提交
1309
          column: mapping.originalColumn,
D
DCloud_LXH 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
        });
        if (original.source != null) {
          // Copy mapping
          mapping.source = original.source;
          if (aSourceMapPath != null) {
            mapping.source = util.join(aSourceMapPath, mapping.source);
          }
          if (sourceRoot != null) {
            mapping.source = util.relative(sourceRoot, mapping.source);
          }
          mapping.originalLine = original.line;
          mapping.originalColumn = original.column;
          if (original.name != null) {
            mapping.name = original.name;
          }
        }
      }

      const source = mapping.source;
      if (source != null && !newSources.has(source)) {
        newSources.add(source);
      }

      const name = mapping.name;
      if (name != null && !newNames.has(name)) {
        newNames.add(name);
      }
    }, this);
    this._sources = newSources;
    this._names = newNames;

    // Copy sourcesContents of applied map.
fxy060608's avatar
fxy060608 已提交
1342
    aSourceMapConsumer.sources.forEach(function (srcFile) {
D
DCloud_LXH 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
      const content = aSourceMapConsumer.sourceContentFor(srcFile);
      if (content != null) {
        if (aSourceMapPath != null) {
          srcFile = util.join(aSourceMapPath, srcFile);
        }
        if (sourceRoot != null) {
          srcFile = util.relative(sourceRoot, srcFile);
        }
        this.setSourceContent(srcFile, content);
      }
    }, this);
  }

  /**
   * A mapping can have one of the three levels of data:
   *
   *   1. Just the generated position.
   *   2. The Generated position, original position, and original source.
   *   3. Generated and original position, original source, as well as a name
   *      token.
   *
   * To maintain consistency, we validate that any new mapping being added falls
   * in to one of these categories.
   */
  _validateMapping(aGenerated, aOriginal, aSource, aName) {
    // When aOriginal is truthy but has empty values for .line and .column,
    // 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
fxy060608's avatar
fxy060608 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
    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
    ) ; 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 {
      throw new Error(
        'Invalid mapping: ' +
          JSON.stringify({
            generated: aGenerated,
            source: aSource,
            original: aOriginal,
            name: aName,
          })
      )
D
DCloud_LXH 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    }
  }

  /**
   * Serialize the accumulated mappings in to the stream of base 64 VLQs
   * specified by the source map format.
   */
  _serializeMappings() {
    let previousGeneratedColumn = 0;
    let previousGeneratedLine = 1;
    let previousOriginalColumn = 0;
    let previousOriginalLine = 0;
    let previousName = 0;
    let previousSource = 0;
fxy060608's avatar
fxy060608 已提交
1429
    let result = '';
D
DCloud_LXH 已提交
1430 1431 1432 1433 1434 1435 1436 1437
    let next;
    let mapping;
    let nameIdx;
    let sourceIdx;

    const mappings = this._mappings.toArray();
    for (let i = 0, len = mappings.length; i < len; i++) {
      mapping = mappings[i];
fxy060608's avatar
fxy060608 已提交
1438
      next = '';
D
DCloud_LXH 已提交
1439 1440 1441 1442

      if (mapping.generatedLine !== previousGeneratedLine) {
        previousGeneratedColumn = 0;
        while (mapping.generatedLine !== previousGeneratedLine) {
fxy060608's avatar
fxy060608 已提交
1443
          next += ';';
D
DCloud_LXH 已提交
1444 1445 1446
          previousGeneratedLine++;
        }
      } else if (i > 0) {
fxy060608's avatar
fxy060608 已提交
1447 1448 1449 1450
        if (
          !util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])
        ) {
          continue
D
DCloud_LXH 已提交
1451
        }
fxy060608's avatar
fxy060608 已提交
1452
        next += ',';
D
DCloud_LXH 已提交
1453 1454
      }

fxy060608's avatar
fxy060608 已提交
1455 1456 1457
      next += base64VLQ.encode(
        mapping.generatedColumn - previousGeneratedColumn
      );
D
DCloud_LXH 已提交
1458 1459 1460 1461 1462 1463 1464 1465
      previousGeneratedColumn = mapping.generatedColumn;

      if (mapping.source != null) {
        sourceIdx = this._sources.indexOf(mapping.source);
        next += base64VLQ.encode(sourceIdx - previousSource);
        previousSource = sourceIdx;

        // lines are stored 0-based in SourceMap spec version 3
fxy060608's avatar
fxy060608 已提交
1466 1467 1468
        next += base64VLQ.encode(
          mapping.originalLine - 1 - previousOriginalLine
        );
D
DCloud_LXH 已提交
1469 1470
        previousOriginalLine = mapping.originalLine - 1;

fxy060608's avatar
fxy060608 已提交
1471 1472 1473
        next += base64VLQ.encode(
          mapping.originalColumn - previousOriginalColumn
        );
D
DCloud_LXH 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        previousOriginalColumn = mapping.originalColumn;

        if (mapping.name != null) {
          nameIdx = this._names.indexOf(mapping.name);
          next += base64VLQ.encode(nameIdx - previousName);
          previousName = nameIdx;
        }
      }

      result += next;
    }

fxy060608's avatar
fxy060608 已提交
1486
    return result
D
DCloud_LXH 已提交
1487 1488 1489
  }

  _generateSourcesContent(aSources, aSourceRoot) {
fxy060608's avatar
fxy060608 已提交
1490
    return aSources.map(function (source) {
D
DCloud_LXH 已提交
1491
      if (!this._sourcesContents) {
fxy060608's avatar
fxy060608 已提交
1492
        return null
D
DCloud_LXH 已提交
1493 1494 1495 1496 1497 1498 1499
      }
      if (aSourceRoot != null) {
        source = util.relative(aSourceRoot, source);
      }
      const key = util.toSetString(source);
      return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
        ? this._sourcesContents[key]
fxy060608's avatar
fxy060608 已提交
1500 1501
        : null
    }, this)
D
DCloud_LXH 已提交
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
  }

  /**
   * Externalize the source map.
   */
  toJSON() {
    const map = {
      version: this._version,
      sources: this._sources.toArray(),
      names: this._names.toArray(),
fxy060608's avatar
fxy060608 已提交
1512
      mappings: this._serializeMappings(),
D
DCloud_LXH 已提交
1513 1514 1515 1516 1517 1518 1519 1520
    };
    if (this._file != null) {
      map.file = this._file;
    }
    if (this._sourceRoot != null) {
      map.sourceRoot = this._sourceRoot;
    }
    if (this._sourcesContents) {
fxy060608's avatar
fxy060608 已提交
1521 1522 1523 1524
      map.sourcesContent = this._generateSourcesContent(
        map.sources,
        map.sourceRoot
      );
D
DCloud_LXH 已提交
1525 1526
    }

fxy060608's avatar
fxy060608 已提交
1527
    return map
D
DCloud_LXH 已提交
1528 1529 1530 1531 1532 1533
  }

  /**
   * Render the source map being generated to a string.
   */
  toString() {
fxy060608's avatar
fxy060608 已提交
1534
    return JSON.stringify(this.toJSON())
D
DCloud_LXH 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
  }
}

SourceMapGenerator$1.prototype._version = 3;
var SourceMapGenerator_1 = SourceMapGenerator$1;

var sourceMapGenerator = {
	SourceMapGenerator: SourceMapGenerator_1
};

/* -*- Mode: js; js-indent-level: 2; -*- */

var binarySearch$1 = createCommonjsModule(function (module, exports) {
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;

/**
 * Recursive implementation of binary search.
 *
 * @param aLow Indices here and lower do not contain the needle.
 * @param aHigh Indices here and higher do not contain the needle.
 * @param aNeedle The element being searched for.
 * @param aHaystack The non-empty array being searched.
 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
 *     'binarySearch.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.
 */
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  // This function terminates when one of the following is true:
  //
  //   1. We find the exact element we are looking for.
  //
  //   2. We did not find the exact element, but we can return the index of
  //      the next-closest element.
  //
  //   3. We did not find the exact element, and there is no next-closest
  //      element than the one we are searching for, so we return -1.
  const mid = Math.floor((aHigh - aLow) / 2) + aLow;
  const cmp = aCompare(aNeedle, aHaystack[mid], true);
  if (cmp === 0) {
    // Found the element we are looking for.
fxy060608's avatar
fxy060608 已提交
1584
    return mid
D
DCloud_LXH 已提交
1585 1586 1587 1588
  } else if (cmp > 0) {
    // Our needle is greater than aHaystack[mid].
    if (aHigh - mid > 1) {
      // The element is in the upper half.
fxy060608's avatar
fxy060608 已提交
1589
      return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias)
D
DCloud_LXH 已提交
1590 1591 1592 1593 1594
    }

    // The exact needle element was not found in this haystack. Determine if
    // we are in termination case (3) or (2) and return the appropriate thing.
    if (aBias == exports.LEAST_UPPER_BOUND) {
fxy060608's avatar
fxy060608 已提交
1595
      return aHigh < aHaystack.length ? aHigh : -1
D
DCloud_LXH 已提交
1596
    }
fxy060608's avatar
fxy060608 已提交
1597
    return mid
D
DCloud_LXH 已提交
1598 1599 1600 1601 1602
  }

  // Our needle is less than aHaystack[mid].
  if (mid - aLow > 1) {
    // The element is in the lower half.
fxy060608's avatar
fxy060608 已提交
1603
    return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias)
D
DCloud_LXH 已提交
1604 1605 1606 1607
  }

  // we are in termination case (3) or (2) and return the appropriate thing.
  if (aBias == exports.LEAST_UPPER_BOUND) {
fxy060608's avatar
fxy060608 已提交
1608
    return mid
D
DCloud_LXH 已提交
1609
  }
fxy060608's avatar
fxy060608 已提交
1610
  return aLow < 0 ? -1 : aLow
D
DCloud_LXH 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
}

/**
 * This is an implementation of binary search which will always try and return
 * the index of the closest element if there is no exact hit. This is because
 * mappings between original and generated line/col pairs are single points,
 * and there is an implicit region between each of them, so a miss just means
 * that you aren't on the very start of a region.
 *
 * @param aNeedle The element you are looking for.
 * @param aHaystack The array that is being searched.
 * @param aCompare A function which takes the needle and an element in the
 *     array and returns -1, 0, or 1 depending on whether the needle is less
 *     than, equal to, or greater than the element, respectively.
 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
 *     'binarySearch.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 'binarySearch.GREATEST_LOWER_BOUND'.
 */
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  if (aHaystack.length === 0) {
fxy060608's avatar
fxy060608 已提交
1633
    return -1
D
DCloud_LXH 已提交
1634 1635
  }

fxy060608's avatar
fxy060608 已提交
1636 1637 1638 1639 1640 1641 1642 1643
  let index = recursiveSearch(
    -1,
    aHaystack.length,
    aNeedle,
    aHaystack,
    aCompare,
    aBias || exports.GREATEST_LOWER_BOUND
  );
D
DCloud_LXH 已提交
1644
  if (index < 0) {
fxy060608's avatar
fxy060608 已提交
1645
    return -1
D
DCloud_LXH 已提交
1646 1647 1648 1649 1650 1651 1652
  }

  // We have found either the exact element, or the next-closest element than
  // the one we are searching for. However, there may be more than one such
  // element. Make sure we always return the smallest of these.
  while (index - 1 >= 0) {
    if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
fxy060608's avatar
fxy060608 已提交
1653
      break
D
DCloud_LXH 已提交
1654 1655 1656 1657
    }
    --index;
  }

fxy060608's avatar
fxy060608 已提交
1658
  return index
D
DCloud_LXH 已提交
1659 1660 1661 1662 1663 1664 1665 1666
};
});

/* Determine browser vs node environment by testing the default top level context. Solution courtesy of: https://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser */

var readWasm$1 = createCommonjsModule(function (module) {
{
  // Node version of reading a wasm file into an array buffer.
fxy060608's avatar
fxy060608 已提交
1667
  const fs = fs__default["default"];
fxy060608's avatar
fxy060608 已提交
1668
  const path = path__default["default"];
D
DCloud_LXH 已提交
1669 1670 1671

  module.exports = function readWasm() {
    return new Promise((resolve, reject) => {
fxy060608's avatar
fxy060608 已提交
1672 1673 1674 1675 1676
      const wasmPath = path.join(
        __dirname,
        '../lib/source-map/lib',
        'mappings.wasm'
      );
D
DCloud_LXH 已提交
1677 1678 1679
      fs.readFile(wasmPath, null, (error, data) => {
        if (error) {
          reject(error);
fxy060608's avatar
fxy060608 已提交
1680
          return
D
DCloud_LXH 已提交
1681 1682 1683 1684
        }

        resolve(data.buffer);
      });
fxy060608's avatar
fxy060608 已提交
1685
    })
D
DCloud_LXH 已提交
1686 1687
  };

fxy060608's avatar
fxy060608 已提交
1688 1689 1690 1691
  module.exports.initialize = (_) => {
    console.debug(
      'SourceMapConsumer.initialize is a no-op when running in node.js'
    );
D
DCloud_LXH 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
  };
}
});

var readWasm = readWasm$1;

/**
 * Provide the JIT with a nice shape / hidden class.
 */
function Mapping() {
  this.generatedLine = 0;
  this.generatedColumn = 0;
  this.lastGeneratedColumn = null;
  this.source = null;
  this.originalLine = null;
  this.originalColumn = null;
  this.name = null;
}

let cachedWasm = null;

var wasm$1 = function wasm() {
  if (cachedWasm) {
fxy060608's avatar
fxy060608 已提交
1715
    return cachedWasm
D
DCloud_LXH 已提交
1716 1717 1718 1719
  }

  const callbackStack = [];

fxy060608's avatar
fxy060608 已提交
1720 1721
  cachedWasm = readWasm()
    .then((buffer) => {
D
DCloud_LXH 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
      return WebAssembly.instantiate(buffer, {
        env: {
          mapping_callback(
            generatedLine,
            generatedColumn,

            hasLastGeneratedColumn,
            lastGeneratedColumn,

            hasOriginal,
            source,
            originalLine,
            originalColumn,

            hasName,
            name
          ) {
            const mapping = new Mapping();
            // JS uses 1-based line numbers, wasm uses 0-based.
            mapping.generatedLine = generatedLine + 1;
            mapping.generatedColumn = generatedColumn;

            if (hasLastGeneratedColumn) {
              // JS uses inclusive last generated column, wasm uses exclusive.
              mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
            }

            if (hasOriginal) {
              mapping.source = source;
              // JS uses 1-based line numbers, wasm uses 0-based.
              mapping.originalLine = originalLine + 1;
              mapping.originalColumn = originalColumn;

              if (hasName) {
                mapping.name = name;
              }
            }

            callbackStack[callbackStack.length - 1](mapping);
          },

fxy060608's avatar
fxy060608 已提交
1763 1764 1765 1766 1767 1768
          start_all_generated_locations_for() {
            console.time('all_generated_locations_for');
          },
          end_all_generated_locations_for() {
            console.timeEnd('all_generated_locations_for');
          },
D
DCloud_LXH 已提交
1769

fxy060608's avatar
fxy060608 已提交
1770 1771 1772 1773 1774 1775
          start_compute_column_spans() {
            console.time('compute_column_spans');
          },
          end_compute_column_spans() {
            console.timeEnd('compute_column_spans');
          },
D
DCloud_LXH 已提交
1776

fxy060608's avatar
fxy060608 已提交
1777 1778 1779 1780 1781 1782
          start_generated_location_for() {
            console.time('generated_location_for');
          },
          end_generated_location_for() {
            console.timeEnd('generated_location_for');
          },
D
DCloud_LXH 已提交
1783

fxy060608's avatar
fxy060608 已提交
1784 1785 1786 1787 1788 1789
          start_original_location_for() {
            console.time('original_location_for');
          },
          end_original_location_for() {
            console.timeEnd('original_location_for');
          },
D
DCloud_LXH 已提交
1790

fxy060608's avatar
fxy060608 已提交
1791 1792 1793 1794 1795 1796
          start_parse_mappings() {
            console.time('parse_mappings');
          },
          end_parse_mappings() {
            console.timeEnd('parse_mappings');
          },
D
DCloud_LXH 已提交
1797

fxy060608's avatar
fxy060608 已提交
1798 1799 1800 1801 1802 1803
          start_sort_by_generated_location() {
            console.time('sort_by_generated_location');
          },
          end_sort_by_generated_location() {
            console.timeEnd('sort_by_generated_location');
          },
D
DCloud_LXH 已提交
1804

fxy060608's avatar
fxy060608 已提交
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
          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();
          }
        },
D
DCloud_LXH 已提交
1825
      }
fxy060608's avatar
fxy060608 已提交
1826 1827 1828 1829 1830
    })
    .then(null, (e) => {
      cachedWasm = null;
      throw e
    });
D
DCloud_LXH 已提交
1831

fxy060608's avatar
fxy060608 已提交
1832
  return cachedWasm
D
DCloud_LXH 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
};

var binarySearch = binarySearch$1;

var wasm = wasm$1;

/* -*- Mode: js; js-indent-level: 2; -*- */

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */



const ArraySet = require$$0$1.ArraySet;
 // eslint-disable-line no-unused-vars



fxy060608's avatar
fxy060608 已提交
1854
const INTERNAL = Symbol('smcInternal');
D
DCloud_LXH 已提交
1855 1856 1857 1858 1859 1860 1861

class SourceMapConsumer$1 {
  constructor(aSourceMap, aSourceMapURL) {
    // If the constructor was called by super(), just return Promise<this>.
    // Yes, this is a hack to retain the pre-existing API of the base-class
    // constructor also being an async factory function.
    if (aSourceMap == INTERNAL) {
fxy060608's avatar
fxy060608 已提交
1862
      return Promise.resolve(this)
D
DCloud_LXH 已提交
1863 1864
    }

fxy060608's avatar
fxy060608 已提交
1865
    return _factory(aSourceMap, aSourceMapURL)
D
DCloud_LXH 已提交
1866 1867 1868
  }

  static initialize(opts) {
fxy060608's avatar
fxy060608 已提交
1869
    readWasm.initialize(opts['lib/mappings.wasm']);
D
DCloud_LXH 已提交
1870 1871 1872
  }

  static fromSourceMap(aSourceMap, aSourceMapURL) {
fxy060608's avatar
fxy060608 已提交
1873
    return _factoryBSM(aSourceMap, aSourceMapURL)
D
DCloud_LXH 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
  }

  /**
   * 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);
   * ```
   */
  static async with(rawSourceMap, sourceMapUrl, f) {
    const consumer = await new SourceMapConsumer$1(rawSourceMap, sourceMapUrl);
    try {
fxy060608's avatar
fxy060608 已提交
1909
      return await f(consumer)
D
DCloud_LXH 已提交
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
    } finally {
      consumer.destroy();
    }
  }

  /**
   * Parse the mappings in a string in to a data structure which we can easily
   * query (the ordered arrays in the `this.__generatedMappings` and
   * `this.__originalMappings` properties).
   */
  _parseMappings(aStr, aSourceRoot) {
fxy060608's avatar
fxy060608 已提交
1921
    throw new Error('Subclasses must implement _parseMappings')
D
DCloud_LXH 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
  }

  /**
   * Iterate over each mapping between an original source/line/column and a
   * generated line/column in this source map.
   *
   * @param Function aCallback
   *        The function that is called with each mapping.
   * @param Object aContext
   *        Optional. If specified, this object will be the value of `this` every
   *        time that `aCallback` is called.
   * @param aOrder
   *        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(aCallback, aContext, aOrder) {
fxy060608's avatar
fxy060608 已提交
1941
    throw new Error('Subclasses must implement eachMapping')
D
DCloud_LXH 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
  }

  /**
   * 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.  The line number is 1-based.
   *   - 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 number is 1-based.
   *   - column: The column number in the generated source, or null.
   *    The column number is 0-based.
   */
  allGeneratedPositionsFor(aArgs) {
fxy060608's avatar
fxy060608 已提交
1967
    throw new Error('Subclasses must implement allGeneratedPositionsFor')
D
DCloud_LXH 已提交
1968 1969 1970
  }

  destroy() {
fxy060608's avatar
fxy060608 已提交
1971
    throw new Error('Subclasses must implement destroy')
D
DCloud_LXH 已提交
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
  }
}

/**
 * The version of the source mapping spec that we are consuming.
 */
SourceMapConsumer$1.prototype._version = 3;
SourceMapConsumer$1.GENERATED_ORDER = 1;
SourceMapConsumer$1.ORIGINAL_ORDER = 2;

SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;

var SourceMapConsumer_1 = SourceMapConsumer$1;

/**
 * A BasicSourceMapConsumer instance represents a parsed source map which we can
 * query for information about the original file positions by giving it a file
 * position in the generated source.
 *
 * The first parameter is the raw source map (either as a JSON string, or
 * already parsed to an object). According to the spec, source maps have the
 * following attributes:
 *
 *   - version: Which version of the source map spec this map is following.
 *   - sources: An array of URLs to the original source files.
 *   - names: An array of identifiers which can be referenced by individual mappings.
 *   - sourceRoot: Optional. The URL root from which all sources are relative.
 *   - sourcesContent: Optional. An array of contents of the original source files.
 *   - mappings: A string of base64 VLQs which contain the actual mappings.
 *   - file: Optional. The generated file this source map is associated with.
 *
 * Here is an example source map, taken from the source map spec[0]:
 *
 *     {
 *       version : 3,
 *       file: "out.js",
 *       sourceRoot : "",
 *       sources: ["foo.js", "bar.js"],
 *       names: ["src", "maps", "are", "fun"],
 *       mappings: "AA,AB;;ABCDE;"
 *     }
 *
 * The second parameter, if given, is a string whose value is the URL
 * at which the source map was found.  This URL is used to compute the
 * sources array.
 *
 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
 */
class BasicSourceMapConsumer extends SourceMapConsumer$1 {
  constructor(aSourceMap, aSourceMapURL) {
fxy060608's avatar
fxy060608 已提交
2023
    return super(INTERNAL).then((that) => {
D
DCloud_LXH 已提交
2024
      let sourceMap = aSourceMap;
fxy060608's avatar
fxy060608 已提交
2025
      if (typeof aSourceMap === 'string') {
D
DCloud_LXH 已提交
2026 2027 2028
        sourceMap = util.parseSourceMapInput(aSourceMap);
      }

fxy060608's avatar
fxy060608 已提交
2029 2030
      const version = util.getArg(sourceMap, 'version');
      let sources = util.getArg(sourceMap, 'sources');
D
DCloud_LXH 已提交
2031 2032
      // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
      // requires the array) to play nice here.
fxy060608's avatar
fxy060608 已提交
2033 2034 2035 2036 2037
      const names = util.getArg(sourceMap, 'names', []);
      let sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
      const sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
      const mappings = util.getArg(sourceMap, 'mappings');
      const file = util.getArg(sourceMap, 'file', null);
D
DCloud_LXH 已提交
2038 2039 2040 2041

      // Once again, Sass deviates from the spec and supplies the version as a
      // string rather than a number, so we use loose equality checking here.
      if (version != that._version) {
fxy060608's avatar
fxy060608 已提交
2042
        throw new Error('Unsupported version: ' + version)
D
DCloud_LXH 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
      }

      if (sourceRoot) {
        sourceRoot = util.normalize(sourceRoot);
      }

      sources = sources
        .map(String)
        // Some source maps produce relative source paths like "./foo.js" instead of
        // "foo.js".  Normalize these first so that future comparisons will succeed.
        // See bugzil.la/1090768.
        .map(util.normalize)
        // Always ensure that absolute sources are internally stored relative to
        // the source root, if the source root is absolute. Not doing this would
        // be particularly problematic when the source root is a prefix of the
        // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
fxy060608's avatar
fxy060608 已提交
2059 2060 2061 2062
        .map(function (source) {
          return sourceRoot &&
            util.isAbsolute(sourceRoot) &&
            util.isAbsolute(source)
D
DCloud_LXH 已提交
2063
            ? util.relative(sourceRoot, source)
fxy060608's avatar
fxy060608 已提交
2064
            : source
D
DCloud_LXH 已提交
2065 2066 2067 2068 2069 2070 2071 2072 2073
        });

      // Pass `true` below to allow duplicate names and sources. While source maps
      // are intended to be compressed and deduplicated, the TypeScript compiler
      // sometimes generates source maps with duplicates in them. See Github issue
      // #72 and bugzil.la/889492.
      that._names = ArraySet.fromArray(names.map(String), true);
      that._sources = ArraySet.fromArray(sources, true);

fxy060608's avatar
fxy060608 已提交
2074 2075
      that._absoluteSources = that._sources.toArray().map(function (s) {
        return util.computeSourceURL(sourceRoot, s, aSourceMapURL)
D
DCloud_LXH 已提交
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
      });

      that.sourceRoot = sourceRoot;
      that.sourcesContent = sourcesContent;
      that._mappings = mappings;
      that._sourceMapURL = aSourceMapURL;
      that.file = file;

      that._computedColumnSpans = false;
      that._mappingsPtr = 0;
      that._wasm = null;

fxy060608's avatar
fxy060608 已提交
2088
      return wasm().then((w) => {
D
DCloud_LXH 已提交
2089
        that._wasm = w;
fxy060608's avatar
fxy060608 已提交
2090 2091 2092
        return that
      })
    })
D
DCloud_LXH 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
  }

  /**
   * Utility function to find the index of a source.  Returns -1 if not
   * found.
   */
  _findSourceIndex(aSource) {
    let relativeSource = aSource;
    if (this.sourceRoot != null) {
      relativeSource = util.relative(this.sourceRoot, relativeSource);
    }

    if (this._sources.has(relativeSource)) {
fxy060608's avatar
fxy060608 已提交
2106
      return this._sources.indexOf(relativeSource)
D
DCloud_LXH 已提交
2107 2108 2109 2110 2111 2112
    }

    // Maybe aSource is an absolute URL as returned by |sources|.  In
    // this case we can't simply undo the transform.
    for (let i = 0; i < this._absoluteSources.length; ++i) {
      if (this._absoluteSources[i] == aSource) {
fxy060608's avatar
fxy060608 已提交
2113
        return i
D
DCloud_LXH 已提交
2114 2115 2116
      }
    }

fxy060608's avatar
fxy060608 已提交
2117
    return -1
D
DCloud_LXH 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
  }

  /**
   * Create a BasicSourceMapConsumer from a SourceMapGenerator.
   *
   * @param SourceMapGenerator aSourceMap
   *        The source map that will be consumed.
   * @param String aSourceMapURL
   *        The URL at which the source map can be found (optional)
   * @returns BasicSourceMapConsumer
   */
  static fromSourceMap(aSourceMap, aSourceMapURL) {
fxy060608's avatar
fxy060608 已提交
2130
    return new BasicSourceMapConsumer(aSourceMap.toString())
D
DCloud_LXH 已提交
2131 2132 2133
  }

  get sources() {
fxy060608's avatar
fxy060608 已提交
2134
    return this._absoluteSources.slice()
D
DCloud_LXH 已提交
2135 2136 2137 2138 2139 2140 2141
  }

  _getMappingsPtr() {
    if (this._mappingsPtr === 0) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }

fxy060608's avatar
fxy060608 已提交
2142
    return this._mappingsPtr
D
DCloud_LXH 已提交
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
  }

  /**
   * Parse the mappings in a string in to a data structure which we can easily
   * query (the ordered arrays in the `this.__generatedMappings` and
   * `this.__originalMappings` properties).
   */
  _parseMappings(aStr, aSourceRoot) {
    const size = aStr.length;

    const mappingsBufPtr = this._wasm.exports.allocate_mappings(size);
fxy060608's avatar
fxy060608 已提交
2154 2155 2156 2157 2158
    const mappingsBuf = new Uint8Array(
      this._wasm.exports.memory.buffer,
      mappingsBufPtr,
      size
    );
D
DCloud_LXH 已提交
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
    for (let i = 0; i < size; i++) {
      mappingsBuf[i] = aStr.charCodeAt(i);
    }

    const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr);

    if (!mappingsPtr) {
      const error = this._wasm.exports.get_last_error();
      let msg = `Error parsing mappings (code ${error}): `;

      // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`.
      switch (error) {
        case 1:
fxy060608's avatar
fxy060608 已提交
2172 2173 2174
          msg +=
            'the mappings contained a negative line, column, source index, or name index';
          break
D
DCloud_LXH 已提交
2175
        case 2:
fxy060608's avatar
fxy060608 已提交
2176 2177
          msg += 'the mappings contained a number larger than 2**32';
          break
D
DCloud_LXH 已提交
2178
        case 3:
fxy060608's avatar
fxy060608 已提交
2179 2180
          msg += 'reached EOF while in the middle of parsing a VLQ';
          break
D
DCloud_LXH 已提交
2181
        case 4:
fxy060608's avatar
fxy060608 已提交
2182 2183
          msg += 'invalid base 64 character while parsing a VLQ';
          break
D
DCloud_LXH 已提交
2184
        default:
fxy060608's avatar
fxy060608 已提交
2185 2186
          msg += 'unknown error code';
          break
D
DCloud_LXH 已提交
2187 2188
      }

fxy060608's avatar
fxy060608 已提交
2189
      throw new Error(msg)
D
DCloud_LXH 已提交
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
    }

    this._mappingsPtr = mappingsPtr;
  }

  eachMapping(aCallback, aContext, aOrder) {
    const context = aContext || null;
    const order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
    const sourceRoot = this.sourceRoot;

    this._wasm.withMappingCallback(
fxy060608's avatar
fxy060608 已提交
2201
      (mapping) => {
D
DCloud_LXH 已提交
2202 2203
        if (mapping.source !== null) {
          mapping.source = this._sources.at(mapping.source);
fxy060608's avatar
fxy060608 已提交
2204 2205 2206 2207 2208
          mapping.source = util.computeSourceURL(
            sourceRoot,
            mapping.source,
            this._sourceMapURL
          );
D
DCloud_LXH 已提交
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218

          if (mapping.name !== null) {
            mapping.name = this._names.at(mapping.name);
          }
        }

        aCallback.call(context, mapping);
      },
      () => {
        switch (order) {
fxy060608's avatar
fxy060608 已提交
2219 2220 2221 2222 2223 2224 2225 2226
          case SourceMapConsumer$1.GENERATED_ORDER:
            this._wasm.exports.by_generated_location(this._getMappingsPtr());
            break
          case SourceMapConsumer$1.ORIGINAL_ORDER:
            this._wasm.exports.by_original_location(this._getMappingsPtr());
            break
          default:
            throw new Error('Unknown order of iteration.')
D
DCloud_LXH 已提交
2227 2228 2229 2230 2231 2232
        }
      }
    );
  }

  allGeneratedPositionsFor(aArgs) {
fxy060608's avatar
fxy060608 已提交
2233 2234
    let source = util.getArg(aArgs, 'source');
    const originalLine = util.getArg(aArgs, 'line');
D
DCloud_LXH 已提交
2235 2236 2237 2238
    const originalColumn = aArgs.column || 0;

    source = this._findSourceIndex(source);
    if (source < 0) {
fxy060608's avatar
fxy060608 已提交
2239
      return []
D
DCloud_LXH 已提交
2240 2241 2242
    }

    if (originalLine < 1) {
fxy060608's avatar
fxy060608 已提交
2243
      throw new Error('Line numbers must be >= 1')
D
DCloud_LXH 已提交
2244 2245 2246
    }

    if (originalColumn < 0) {
fxy060608's avatar
fxy060608 已提交
2247
      throw new Error('Column numbers must be >= 0')
D
DCloud_LXH 已提交
2248 2249 2250 2251 2252
    }

    const mappings = [];

    this._wasm.withMappingCallback(
fxy060608's avatar
fxy060608 已提交
2253
      (m) => {
D
DCloud_LXH 已提交
2254 2255 2256 2257 2258 2259 2260 2261 2262
        let lastColumn = m.lastGeneratedColumn;
        if (this._computedColumnSpans && lastColumn === null) {
          lastColumn = Infinity;
        }
        mappings.push({
          line: m.generatedLine,
          column: m.generatedColumn,
          lastColumn,
        });
fxy060608's avatar
fxy060608 已提交
2263 2264
      },
      () => {
D
DCloud_LXH 已提交
2265 2266 2267 2268
        this._wasm.exports.all_generated_locations_for(
          this._getMappingsPtr(),
          source,
          originalLine - 1,
fxy060608's avatar
fxy060608 已提交
2269
          'column' in aArgs,
D
DCloud_LXH 已提交
2270 2271 2272 2273 2274
          originalColumn
        );
      }
    );

fxy060608's avatar
fxy060608 已提交
2275
    return mappings
D
DCloud_LXH 已提交
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
  }

  destroy() {
    if (this._mappingsPtr !== 0) {
      this._wasm.exports.free_mappings(this._mappingsPtr);
      this._mappingsPtr = 0;
    }
  }

  /**
   * Compute the last column for each generated mapping. The last column is
   * inclusive.
   */
  computeColumnSpans() {
    if (this._computedColumnSpans) {
fxy060608's avatar
fxy060608 已提交
2291
      return
D
DCloud_LXH 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
    }

    this._wasm.exports.compute_column_spans(this._getMappingsPtr());
    this._computedColumnSpans = true;
  }

  /**
   * 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.  The line number
   *     is 1-based.
   *   - column: The column number in the generated source.  The column
   *     number is 0-based.
   *   - 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.  The
   *     line number is 1-based.
   *   - column: The column number in the original source, or null.  The
   *     column number is 0-based.
   *   - name: The original identifier, or null.
   */
  originalPositionFor(aArgs) {
    const needle = {
fxy060608's avatar
fxy060608 已提交
2324 2325
      generatedLine: util.getArg(aArgs, 'line'),
      generatedColumn: util.getArg(aArgs, 'column'),
D
DCloud_LXH 已提交
2326 2327 2328
    };

    if (needle.generatedLine < 1) {
fxy060608's avatar
fxy060608 已提交
2329
      throw new Error('Line numbers must be >= 1')
D
DCloud_LXH 已提交
2330 2331 2332
    }

    if (needle.generatedColumn < 0) {
fxy060608's avatar
fxy060608 已提交
2333
      throw new Error('Column numbers must be >= 0')
D
DCloud_LXH 已提交
2334 2335
    }

fxy060608's avatar
fxy060608 已提交
2336 2337 2338 2339 2340
    let bias = util.getArg(
      aArgs,
      'bias',
      SourceMapConsumer$1.GREATEST_LOWER_BOUND
    );
D
DCloud_LXH 已提交
2341 2342 2343 2344 2345
    if (bias == null) {
      bias = SourceMapConsumer$1.GREATEST_LOWER_BOUND;
    }

    let mapping;
fxy060608's avatar
fxy060608 已提交
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
    this._wasm.withMappingCallback(
      (m) => (mapping = m),
      () => {
        this._wasm.exports.original_location_for(
          this._getMappingsPtr(),
          needle.generatedLine - 1,
          needle.generatedColumn,
          bias
        );
      }
    );
D
DCloud_LXH 已提交
2357 2358 2359

    if (mapping) {
      if (mapping.generatedLine === needle.generatedLine) {
fxy060608's avatar
fxy060608 已提交
2360
        let source = util.getArg(mapping, 'source', null);
D
DCloud_LXH 已提交
2361 2362
        if (source !== null) {
          source = this._sources.at(source);
fxy060608's avatar
fxy060608 已提交
2363 2364 2365 2366 2367
          source = util.computeSourceURL(
            this.sourceRoot,
            source,
            this._sourceMapURL
          );
D
DCloud_LXH 已提交
2368 2369
        }

fxy060608's avatar
fxy060608 已提交
2370
        let name = util.getArg(mapping, 'name', null);
D
DCloud_LXH 已提交
2371 2372 2373 2374 2375 2376
        if (name !== null) {
          name = this._names.at(name);
        }

        return {
          source,
fxy060608's avatar
fxy060608 已提交
2377 2378 2379 2380
          line: util.getArg(mapping, 'originalLine', null),
          column: util.getArg(mapping, 'originalColumn', null),
          name,
        }
D
DCloud_LXH 已提交
2381 2382 2383 2384 2385 2386 2387
      }
    }

    return {
      source: null,
      line: null,
      column: null,
fxy060608's avatar
fxy060608 已提交
2388 2389
      name: null,
    }
D
DCloud_LXH 已提交
2390 2391 2392 2393 2394 2395 2396 2397
  }

  /**
   * Return true if we have the source content for every source in the source
   * map, false otherwise.
   */
  hasContentsOfAllSources() {
    if (!this.sourcesContent) {
fxy060608's avatar
fxy060608 已提交
2398
      return false
D
DCloud_LXH 已提交
2399
    }
fxy060608's avatar
fxy060608 已提交
2400 2401 2402 2403 2404 2405
    return (
      this.sourcesContent.length >= this._sources.size() &&
      !this.sourcesContent.some(function (sc) {
        return sc == null
      })
    )
D
DCloud_LXH 已提交
2406 2407 2408 2409 2410 2411 2412 2413 2414
  }

  /**
   * 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(aSource, nullOnMissing) {
    if (!this.sourcesContent) {
fxy060608's avatar
fxy060608 已提交
2415
      return null
D
DCloud_LXH 已提交
2416 2417 2418 2419
    }

    const index = this._findSourceIndex(aSource);
    if (index >= 0) {
fxy060608's avatar
fxy060608 已提交
2420
      return this.sourcesContent[index]
D
DCloud_LXH 已提交
2421 2422 2423 2424 2425 2426 2427 2428
    }

    let relativeSource = aSource;
    if (this.sourceRoot != null) {
      relativeSource = util.relative(this.sourceRoot, relativeSource);
    }

    let url;
fxy060608's avatar
fxy060608 已提交
2429
    if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
D
DCloud_LXH 已提交
2430 2431 2432 2433
      // XXX: file:// URIs and absolute paths lead to unexpected behavior for
      // many users. We can help them out when they expect file:// URIs to
      // behave like it would if they were running a local HTTP server. See
      // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
fxy060608's avatar
fxy060608 已提交
2434 2435 2436
      const fileUriAbsPath = relativeSource.replace(/^file:\/\//, '');
      if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
        return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
D
DCloud_LXH 已提交
2437 2438
      }

fxy060608's avatar
fxy060608 已提交
2439 2440 2441 2442 2443
      if (
        (!url.path || url.path == '/') &&
        this._sources.has('/' + relativeSource)
      ) {
        return this.sourcesContent[this._sources.indexOf('/' + relativeSource)]
D
DCloud_LXH 已提交
2444 2445 2446 2447 2448 2449 2450 2451
      }
    }

    // This function is used recursively from
    // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
    // don't want to throw if we can't find the source - we just want to
    // return null, so we provide a flag to exit gracefully.
    if (nullOnMissing) {
fxy060608's avatar
fxy060608 已提交
2452
      return null
D
DCloud_LXH 已提交
2453 2454
    }

fxy060608's avatar
fxy060608 已提交
2455
    throw new Error('"' + relativeSource + '" is not in the SourceMap.')
D
DCloud_LXH 已提交
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
  }

  /**
   * 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.  The line number
   *     is 1-based.
   *   - column: The column number in the original source.  The column
   *     number is 0-based.
   *   - 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.  The
   *     line number is 1-based.
   *   - column: The column number in the generated source, or null.
   *     The column number is 0-based.
   */
  generatedPositionFor(aArgs) {
fxy060608's avatar
fxy060608 已提交
2482
    let source = util.getArg(aArgs, 'source');
D
DCloud_LXH 已提交
2483 2484 2485 2486 2487
    source = this._findSourceIndex(source);
    if (source < 0) {
      return {
        line: null,
        column: null,
fxy060608's avatar
fxy060608 已提交
2488 2489
        lastColumn: null,
      }
D
DCloud_LXH 已提交
2490 2491 2492 2493
    }

    const needle = {
      source,
fxy060608's avatar
fxy060608 已提交
2494 2495
      originalLine: util.getArg(aArgs, 'line'),
      originalColumn: util.getArg(aArgs, 'column'),
D
DCloud_LXH 已提交
2496 2497 2498
    };

    if (needle.originalLine < 1) {
fxy060608's avatar
fxy060608 已提交
2499
      throw new Error('Line numbers must be >= 1')
D
DCloud_LXH 已提交
2500 2501 2502
    }

    if (needle.originalColumn < 0) {
fxy060608's avatar
fxy060608 已提交
2503
      throw new Error('Column numbers must be >= 0')
D
DCloud_LXH 已提交
2504 2505
    }

fxy060608's avatar
fxy060608 已提交
2506 2507 2508 2509 2510
    let bias = util.getArg(
      aArgs,
      'bias',
      SourceMapConsumer$1.GREATEST_LOWER_BOUND
    );
D
DCloud_LXH 已提交
2511 2512 2513 2514 2515
    if (bias == null) {
      bias = SourceMapConsumer$1.GREATEST_LOWER_BOUND;
    }

    let mapping;
fxy060608's avatar
fxy060608 已提交
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    this._wasm.withMappingCallback(
      (m) => (mapping = m),
      () => {
        this._wasm.exports.generated_location_for(
          this._getMappingsPtr(),
          needle.source,
          needle.originalLine - 1,
          needle.originalColumn,
          bias
        );
      }
    );
D
DCloud_LXH 已提交
2528 2529 2530 2531 2532 2533 2534 2535

    if (mapping) {
      if (mapping.source === needle.source) {
        let lastColumn = mapping.lastGeneratedColumn;
        if (this._computedColumnSpans && lastColumn === null) {
          lastColumn = Infinity;
        }
        return {
fxy060608's avatar
fxy060608 已提交
2536 2537
          line: util.getArg(mapping, 'generatedLine', null),
          column: util.getArg(mapping, 'generatedColumn', null),
D
DCloud_LXH 已提交
2538
          lastColumn,
fxy060608's avatar
fxy060608 已提交
2539
        }
D
DCloud_LXH 已提交
2540 2541 2542 2543 2544 2545
      }
    }

    return {
      line: null,
      column: null,
fxy060608's avatar
fxy060608 已提交
2546 2547
      lastColumn: null,
    }
D
DCloud_LXH 已提交
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
  }
}

BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;

/**
 * An IndexedSourceMapConsumer instance represents a parsed source map which
 * we can query for information. It differs from BasicSourceMapConsumer in
 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
 * input.
 *
 * The first parameter is a raw source map (either as a JSON string, or already
 * parsed to an object). According to the spec for indexed source maps, they
 * have the following attributes:
 *
 *   - version: Which version of the source map spec this map is following.
 *   - file: Optional. The generated file this source map is associated with.
 *   - sections: A list of section definitions.
 *
 * Each value under the "sections" field has two fields:
 *   - offset: The offset into the original specified at which this section
 *       begins to apply, defined as an object with a "line" and "column"
 *       field.
 *   - map: A source map definition. This source map could also be indexed,
 *       but doesn't have to be.
 *
 * Instead of the "map" field, it's also possible to have a "url" field
 * specifying a URL to retrieve a source map from, but that's currently
 * unsupported.
 *
 * Here's an example source map, taken from the source map spec[0], but
 * modified to omit a section which uses the "url" field.
 *
 *  {
 *    version : 3,
 *    file: "app.js",
 *    sections: [{
 *      offset: {line:100, column:10},
 *      map: {
 *        version : 3,
 *        file: "section.js",
 *        sources: ["foo.js", "bar.js"],
 *        names: ["src", "maps", "are", "fun"],
 *        mappings: "AAAA,E;;ABCDE;"
 *      }
 *    }],
 *  }
 *
 * The second parameter, if given, is a string whose value is the URL
 * at which the source map was found.  This URL is used to compute the
 * sources array.
 *
 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
 */
class IndexedSourceMapConsumer extends SourceMapConsumer$1 {
  constructor(aSourceMap, aSourceMapURL) {
fxy060608's avatar
fxy060608 已提交
2605
    return super(INTERNAL).then((that) => {
D
DCloud_LXH 已提交
2606
      let sourceMap = aSourceMap;
fxy060608's avatar
fxy060608 已提交
2607
      if (typeof aSourceMap === 'string') {
D
DCloud_LXH 已提交
2608 2609 2610
        sourceMap = util.parseSourceMapInput(aSourceMap);
      }

fxy060608's avatar
fxy060608 已提交
2611 2612
      const version = util.getArg(sourceMap, 'version');
      const sections = util.getArg(sourceMap, 'sections');
D
DCloud_LXH 已提交
2613 2614

      if (version != that._version) {
fxy060608's avatar
fxy060608 已提交
2615
        throw new Error('Unsupported version: ' + version)
D
DCloud_LXH 已提交
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
      }

      that._sources = new ArraySet();
      that._names = new ArraySet();
      that.__generatedMappings = null;
      that.__originalMappings = null;
      that.__generatedMappingsUnsorted = null;
      that.__originalMappingsUnsorted = null;

      let lastOffset = {
        line: -1,
fxy060608's avatar
fxy060608 已提交
2627
        column: 0,
D
DCloud_LXH 已提交
2628
      };
fxy060608's avatar
fxy060608 已提交
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
      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');
D
DCloud_LXH 已提交
2641

fxy060608's avatar
fxy060608 已提交
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
          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$1(
            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) => {
D
DCloud_LXH 已提交
2669
        that._sections = s;
fxy060608's avatar
fxy060608 已提交
2670 2671 2672
        return that
      })
    })
D
DCloud_LXH 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
  }

  // `__generatedMappings` and `__originalMappings` are arrays that hold the
  // parsed mapping coordinates from the source map's "mappings" attribute. They
  // are lazily instantiated, accessed via the `_generatedMappings` and
  // `_originalMappings` getters respectively, and we only parse the mappings
  // and create these arrays once queried for a source location. We jump through
  // these hoops because there can be many thousands of mappings, and parsing
  // them is expensive, so we only want to do it if we must.
  //
  // Each object in the arrays is of the form:
  //
  //     {
  //       generatedLine: The line number in the generated code,
  //       generatedColumn: The column number in the generated code,
  //       source: The path to the original source file that generated this
  //               chunk of code,
  //       originalLine: The line number in the original source that
  //                     corresponds to this chunk of generated code,
  //       originalColumn: The column number in the original source that
  //                       corresponds to this chunk of generated code,
  //       name: The name of the original symbol which generated this chunk of
  //             code.
  //     }
  //
  // All properties except for `generatedLine` and `generatedColumn` can be
  // `null`.
  //
  // `_generatedMappings` is ordered by the generated positions.
  //
  // `_originalMappings` is ordered by the original positions.
  get _generatedMappings() {
    if (!this.__generatedMappings) {
      this._sortGeneratedMappings();
    }

fxy060608's avatar
fxy060608 已提交
2709
    return this.__generatedMappings
D
DCloud_LXH 已提交
2710 2711 2712 2713 2714 2715 2716
  }

  get _originalMappings() {
    if (!this.__originalMappings) {
      this._sortOriginalMappings();
    }

fxy060608's avatar
fxy060608 已提交
2717
    return this.__originalMappings
D
DCloud_LXH 已提交
2718 2719 2720 2721 2722 2723 2724
  }

  get _generatedMappingsUnsorted() {
    if (!this.__generatedMappingsUnsorted) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }

fxy060608's avatar
fxy060608 已提交
2725
    return this.__generatedMappingsUnsorted
D
DCloud_LXH 已提交
2726 2727 2728 2729 2730 2731 2732
  }

  get _originalMappingsUnsorted() {
    if (!this.__originalMappingsUnsorted) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }

fxy060608's avatar
fxy060608 已提交
2733
    return this.__originalMappingsUnsorted
D
DCloud_LXH 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
  }

  _sortGeneratedMappings() {
    const mappings = this._generatedMappingsUnsorted;
    mappings.sort(util.compareByGeneratedPositionsDeflated);
    this.__generatedMappings = mappings;
  }

  _sortOriginalMappings() {
    const mappings = this._originalMappingsUnsorted;
    mappings.sort(util.compareByOriginalPositions);
    this.__originalMappings = mappings;
  }

  /**
   * The list of original sources.
   */
  get sources() {
    const sources = [];
    for (let i = 0; i < this._sections.length; i++) {
      for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {
        sources.push(this._sections[i].consumer.sources[j]);
      }
    }
fxy060608's avatar
fxy060608 已提交
2758
    return sources
D
DCloud_LXH 已提交
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
  }

  /**
   * 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.  The line number
   *     is 1-based.
   *   - column: The column number in the generated source.  The column
   *     number is 0-based.
   *
   * 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.  The
   *     line number is 1-based.
   *   - column: The column number in the original source, or null.  The
   *     column number is 0-based.
   *   - name: The original identifier, or null.
   */
  originalPositionFor(aArgs) {
    const needle = {
fxy060608's avatar
fxy060608 已提交
2782 2783
      generatedLine: util.getArg(aArgs, 'line'),
      generatedColumn: util.getArg(aArgs, 'column'),
D
DCloud_LXH 已提交
2784 2785 2786 2787
    };

    // Find the section containing the generated position we're trying to map
    // to an original position.
fxy060608's avatar
fxy060608 已提交
2788 2789 2790 2791 2792 2793
    const sectionIndex = binarySearch.search(
      needle,
      this._sections,
      function (aNeedle, section) {
        const cmp =
          aNeedle.generatedLine - section.generatedOffset.generatedLine;
D
DCloud_LXH 已提交
2794
        if (cmp) {
fxy060608's avatar
fxy060608 已提交
2795
          return cmp
D
DCloud_LXH 已提交
2796 2797
        }

fxy060608's avatar
fxy060608 已提交
2798 2799 2800
        return aNeedle.generatedColumn - section.generatedOffset.generatedColumn
      }
    );
D
DCloud_LXH 已提交
2801 2802 2803 2804 2805 2806 2807
    const section = this._sections[sectionIndex];

    if (!section) {
      return {
        source: null,
        line: null,
        column: null,
fxy060608's avatar
fxy060608 已提交
2808 2809
        name: null,
      }
D
DCloud_LXH 已提交
2810 2811 2812
    }

    return section.consumer.originalPositionFor({
fxy060608's avatar
fxy060608 已提交
2813 2814 2815
      line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
      column:
        needle.generatedColumn -
D
DCloud_LXH 已提交
2816
        (section.generatedOffset.generatedLine === needle.generatedLine
fxy060608's avatar
fxy060608 已提交
2817 2818 2819 2820
          ? section.generatedOffset.generatedColumn - 1
          : 0),
      bias: aArgs.bias,
    })
D
DCloud_LXH 已提交
2821 2822 2823 2824 2825 2826 2827
  }

  /**
   * Return true if we have the source content for every source in the source
   * map, false otherwise.
   */
  hasContentsOfAllSources() {
fxy060608's avatar
fxy060608 已提交
2828 2829 2830
    return this._sections.every(function (s) {
      return s.consumer.hasContentsOfAllSources()
    })
D
DCloud_LXH 已提交
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843
  }

  /**
   * 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(aSource, nullOnMissing) {
    for (let i = 0; i < this._sections.length; i++) {
      const section = this._sections[i];

      const content = section.consumer.sourceContentFor(aSource, true);
      if (content) {
fxy060608's avatar
fxy060608 已提交
2844
        return content
D
DCloud_LXH 已提交
2845 2846 2847
      }
    }
    if (nullOnMissing) {
fxy060608's avatar
fxy060608 已提交
2848
      return null
D
DCloud_LXH 已提交
2849
    }
fxy060608's avatar
fxy060608 已提交
2850
    throw new Error('"' + aSource + '" is not in the SourceMap.')
D
DCloud_LXH 已提交
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
  }

  /**
   * 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.  The line number
   *     is 1-based.
   *   - 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 number is 1-based.
   *   - column: The column number in the generated source, or null.
   *     The column number is 0-based.
   */
  generatedPositionFor(aArgs) {
    for (let i = 0; i < this._sections.length; i++) {
      const section = this._sections[i];

      // Only consider this section if the requested source is in the list of
      // sources of the consumer.
fxy060608's avatar
fxy060608 已提交
2877 2878 2879 2880
      if (
        section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1
      ) {
        continue
D
DCloud_LXH 已提交
2881 2882 2883 2884
      }
      const generatedPosition = section.consumer.generatedPositionFor(aArgs);
      if (generatedPosition) {
        const ret = {
fxy060608's avatar
fxy060608 已提交
2885 2886
          line:
            generatedPosition.line +
D
DCloud_LXH 已提交
2887
            (section.generatedOffset.generatedLine - 1),
fxy060608's avatar
fxy060608 已提交
2888 2889
          column:
            generatedPosition.column +
D
DCloud_LXH 已提交
2890
            (section.generatedOffset.generatedLine === generatedPosition.line
fxy060608's avatar
fxy060608 已提交
2891 2892
              ? section.generatedOffset.generatedColumn - 1
              : 0),
D
DCloud_LXH 已提交
2893
        };
fxy060608's avatar
fxy060608 已提交
2894
        return ret
D
DCloud_LXH 已提交
2895 2896 2897 2898 2899
      }
    }

    return {
      line: null,
fxy060608's avatar
fxy060608 已提交
2900 2901
      column: null,
    }
D
DCloud_LXH 已提交
2902 2903 2904 2905 2906 2907 2908 2909
  }

  /**
   * Parse the mappings in a string in to a data structure which we can easily
   * query (the ordered arrays in the `this.__generatedMappings` and
   * `this.__originalMappings` properties).
   */
  _parseMappings(aStr, aSourceRoot) {
fxy060608's avatar
fxy060608 已提交
2910 2911
    const generatedMappings = (this.__generatedMappingsUnsorted = []);
    const originalMappings = (this.__originalMappingsUnsorted = []);
D
DCloud_LXH 已提交
2912 2913 2914 2915
    for (let i = 0; i < this._sections.length; i++) {
      const section = this._sections[i];

      const sectionMappings = [];
fxy060608's avatar
fxy060608 已提交
2916
      section.consumer.eachMapping((m) => sectionMappings.push(m));
D
DCloud_LXH 已提交
2917 2918 2919 2920 2921 2922 2923 2924

      for (let j = 0; j < sectionMappings.length; j++) {
        const mapping = sectionMappings[j];

        // TODO: test if null is correct here.  The original code used
        // `source`, which would actually have gotten used as null because
        // var's get hoisted.
        // See: https://github.com/mozilla/source-map/issues/333
fxy060608's avatar
fxy060608 已提交
2925 2926 2927 2928 2929
        let source = util.computeSourceURL(
          section.consumer.sourceRoot,
          null,
          this._sourceMapURL
        );
D
DCloud_LXH 已提交
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
        this._sources.add(source);
        source = this._sources.indexOf(source);

        let name = null;
        if (mapping.name) {
          this._names.add(mapping.name);
          name = this._names.indexOf(mapping.name);
        }

        // The mappings coming from the consumer for the section have
        // generated positions relative to the start of the section, so we
        // need to offset them to be relative to the start of the concatenated
        // generated file.
        const adjustedMapping = {
          source,
fxy060608's avatar
fxy060608 已提交
2945 2946 2947 2948
          generatedLine:
            mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
          generatedColumn:
            mapping.generatedColumn +
D
DCloud_LXH 已提交
2949
            (section.generatedOffset.generatedLine === mapping.generatedLine
fxy060608's avatar
fxy060608 已提交
2950 2951
              ? section.generatedOffset.generatedColumn - 1
              : 0),
D
DCloud_LXH 已提交
2952 2953
          originalLine: mapping.originalLine,
          originalColumn: mapping.originalColumn,
fxy060608's avatar
fxy060608 已提交
2954
          name,
D
DCloud_LXH 已提交
2955 2956 2957
        };

        generatedMappings.push(adjustedMapping);
fxy060608's avatar
fxy060608 已提交
2958
        if (typeof adjustedMapping.originalLine === 'number') {
D
DCloud_LXH 已提交
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970
          originalMappings.push(adjustedMapping);
        }
      }
    }
  }

  eachMapping(aCallback, aContext, aOrder) {
    const context = aContext || null;
    const order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;

    let mappings;
    switch (order) {
fxy060608's avatar
fxy060608 已提交
2971 2972 2973 2974 2975 2976 2977 2978
      case SourceMapConsumer$1.GENERATED_ORDER:
        mappings = this._generatedMappings;
        break
      case SourceMapConsumer$1.ORIGINAL_ORDER:
        mappings = this._originalMappings;
        break
      default:
        throw new Error('Unknown order of iteration.')
D
DCloud_LXH 已提交
2979 2980 2981
    }

    const sourceRoot = this.sourceRoot;
fxy060608's avatar
fxy060608 已提交
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
    mappings
      .map(function (mapping) {
        let source = null;
        if (mapping.source !== null) {
          source = this._sources.at(mapping.source);
          source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
        }
        return {
          source,
          generatedLine: mapping.generatedLine,
          generatedColumn: mapping.generatedColumn,
          originalLine: mapping.originalLine,
          originalColumn: mapping.originalColumn,
          name: mapping.name === null ? null : this._names.at(mapping.name),
        }
      }, this)
      .forEach(aCallback, context);
D
DCloud_LXH 已提交
2999 3000 3001 3002 3003 3004
  }

  /**
   * Find the mapping that best matches the hypothetical "needle" mapping that
   * we are searching for in the given "haystack" of mappings.
   */
fxy060608's avatar
fxy060608 已提交
3005
  _findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
D
DCloud_LXH 已提交
3006 3007 3008 3009 3010 3011
    // To return the position we are searching for, we must first find the
    // mapping for the given position and then return the opposite position it
    // points to. Because the mappings are sorted, we can use binary search to
    // find the best mapping.

    if (aNeedle[aLineName] <= 0) {
fxy060608's avatar
fxy060608 已提交
3012 3013 3014
      throw new TypeError(
        'Line must be greater than or equal to 1, got ' + aNeedle[aLineName]
      )
D
DCloud_LXH 已提交
3015 3016
    }
    if (aNeedle[aColumnName] < 0) {
fxy060608's avatar
fxy060608 已提交
3017 3018 3019
      throw new TypeError(
        'Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]
      )
D
DCloud_LXH 已提交
3020 3021
    }

fxy060608's avatar
fxy060608 已提交
3022
    return binarySearch.search(aNeedle, aMappings, aComparator, aBias)
D
DCloud_LXH 已提交
3023 3024 3025
  }

  allGeneratedPositionsFor(aArgs) {
fxy060608's avatar
fxy060608 已提交
3026
    const line = util.getArg(aArgs, 'line');
D
DCloud_LXH 已提交
3027 3028 3029 3030 3031 3032

    // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
    // returns the index of the closest mapping less than the needle. By
    // setting needle.originalColumn to 0, we thus find the last mapping for
    // the given line, provided such a mapping exists.
    const needle = {
fxy060608's avatar
fxy060608 已提交
3033
      source: util.getArg(aArgs, 'source'),
D
DCloud_LXH 已提交
3034
      originalLine: line,
fxy060608's avatar
fxy060608 已提交
3035
      originalColumn: util.getArg(aArgs, 'column', 0),
D
DCloud_LXH 已提交
3036 3037 3038 3039
    };

    needle.source = this._findSourceIndex(needle.source);
    if (needle.source < 0) {
fxy060608's avatar
fxy060608 已提交
3040
      return []
D
DCloud_LXH 已提交
3041 3042 3043
    }

    if (needle.originalLine < 1) {
fxy060608's avatar
fxy060608 已提交
3044
      throw new Error('Line numbers must be >= 1')
D
DCloud_LXH 已提交
3045 3046 3047
    }

    if (needle.originalColumn < 0) {
fxy060608's avatar
fxy060608 已提交
3048
      throw new Error('Column numbers must be >= 0')
D
DCloud_LXH 已提交
3049 3050 3051 3052
    }

    const mappings = [];

fxy060608's avatar
fxy060608 已提交
3053 3054 3055 3056 3057 3058 3059 3060
    let index = this._findMapping(
      needle,
      this._originalMappings,
      'originalLine',
      'originalColumn',
      util.compareByOriginalPositions,
      binarySearch.LEAST_UPPER_BOUND
    );
D
DCloud_LXH 已提交
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
    if (index >= 0) {
      let mapping = this._originalMappings[index];

      if (aArgs.column === undefined) {
        const originalLine = mapping.originalLine;

        // Iterate until either we run out of mappings, or we run into
        // a mapping for a different line than the one we found. Since
        // mappings are sorted, this is guaranteed to find all mappings for
        // the line we found.
        while (mapping && mapping.originalLine === originalLine) {
          let lastColumn = mapping.lastGeneratedColumn;
          if (this._computedColumnSpans && lastColumn === null) {
            lastColumn = Infinity;
          }
          mappings.push({
fxy060608's avatar
fxy060608 已提交
3077 3078
            line: util.getArg(mapping, 'generatedLine', null),
            column: util.getArg(mapping, 'generatedColumn', null),
D
DCloud_LXH 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
            lastColumn,
          });

          mapping = this._originalMappings[++index];
        }
      } else {
        const originalColumn = mapping.originalColumn;

        // Iterate until either we run out of mappings, or we run into
        // a mapping for a different line than the one we were searching for.
        // Since mappings are sorted, this is guaranteed to find all mappings for
        // the line we are searching for.
fxy060608's avatar
fxy060608 已提交
3091 3092 3093 3094 3095
        while (
          mapping &&
          mapping.originalLine === line &&
          mapping.originalColumn == originalColumn
        ) {
D
DCloud_LXH 已提交
3096 3097 3098 3099 3100
          let lastColumn = mapping.lastGeneratedColumn;
          if (this._computedColumnSpans && lastColumn === null) {
            lastColumn = Infinity;
          }
          mappings.push({
fxy060608's avatar
fxy060608 已提交
3101 3102
            line: util.getArg(mapping, 'generatedLine', null),
            column: util.getArg(mapping, 'generatedColumn', null),
D
DCloud_LXH 已提交
3103 3104 3105 3106 3107 3108 3109 3110
            lastColumn,
          });

          mapping = this._originalMappings[++index];
        }
      }
    }

fxy060608's avatar
fxy060608 已提交
3111
    return mappings
D
DCloud_LXH 已提交
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
  }

  destroy() {
    for (let i = 0; i < this._sections.length; i++) {
      this._sections[i].consumer.destroy();
    }
  }
}
var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;

/*
 * Cheat to get around inter-twingled classes.  `factory()` can be at the end
 * where it has access to non-hoisted classes, but it gets hoisted itself.
 */
function _factory(aSourceMap, aSourceMapURL) {
  let sourceMap = aSourceMap;
fxy060608's avatar
fxy060608 已提交
3128
  if (typeof aSourceMap === 'string') {
D
DCloud_LXH 已提交
3129 3130 3131
    sourceMap = util.parseSourceMapInput(aSourceMap);
  }

fxy060608's avatar
fxy060608 已提交
3132 3133
  const consumer =
    sourceMap.sections != null
D
DCloud_LXH 已提交
3134 3135
      ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
      : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
fxy060608's avatar
fxy060608 已提交
3136
  return Promise.resolve(consumer)
D
DCloud_LXH 已提交
3137 3138 3139
}

function _factoryBSM(aSourceMap, aSourceMapURL) {
fxy060608's avatar
fxy060608 已提交
3140
  return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL)
D
DCloud_LXH 已提交
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
}

var sourceMapConsumer = {
	SourceMapConsumer: SourceMapConsumer_1,
	BasicSourceMapConsumer: BasicSourceMapConsumer_1,
	IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
};

var require$$0 = sourceMapGenerator;

/* -*- Mode: js; js-indent-level: 2; -*- */

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

const SourceMapGenerator = require$$0.SourceMapGenerator;


// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
const REGEX_NEWLINE = /(\r?\n)/;

// Newline character code for charCodeAt() comparisons
const NEWLINE_CODE = 10;

// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
fxy060608's avatar
fxy060608 已提交
3172
const isSourceNode = '$$$isSourceNode$$$';
D
DCloud_LXH 已提交
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205

/**
 * SourceNodes provide a way to abstract over interpolating/concatenating
 * snippets of generated JavaScript source code while maintaining the line and
 * column information associated with the original source code.
 *
 * @param aLine The original line number.
 * @param aColumn The original column number.
 * @param aSource The original source's filename.
 * @param aChunks Optional. An array of strings which are snippets of
 *        generated JS, or other SourceNodes.
 * @param aName The original identifier.
 */
class SourceNode {
  constructor(aLine, aColumn, aSource, aChunks, aName) {
    this.children = [];
    this.sourceContents = {};
    this.line = aLine == null ? null : aLine;
    this.column = aColumn == null ? null : aColumn;
    this.source = aSource == null ? null : aSource;
    this.name = aName == null ? null : aName;
    this[isSourceNode] = true;
    if (aChunks != null) this.add(aChunks);
  }

  /**
   * Creates a SourceNode from generated code and a SourceMapConsumer.
   *
   * @param aGeneratedCode The generated code
   * @param aSourceMapConsumer The SourceMap for the generated code
   * @param aRelativePath Optional. The path that relative sources in the
   *        SourceMapConsumer should be relative to.
   */
fxy060608's avatar
fxy060608 已提交
3206 3207 3208 3209 3210
  static fromStringWithSourceMap(
    aGeneratedCode,
    aSourceMapConsumer,
    aRelativePath
  ) {
D
DCloud_LXH 已提交
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
    // The SourceNode we want to fill with the generated code
    // and the SourceMap
    const node = new SourceNode();

    // All even indices of this array are one line of the generated code,
    // while all odd indices are the newlines between two adjacent lines
    // (since `REGEX_NEWLINE` captures its match).
    // Processed fragments are accessed by calling `shiftNextLine`.
    const remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
    let remainingLinesIndex = 0;
fxy060608's avatar
fxy060608 已提交
3221
    const shiftNextLine = function () {
D
DCloud_LXH 已提交
3222 3223
      const lineContents = getNextLine();
      // The last line of a file might not have a newline.
fxy060608's avatar
fxy060608 已提交
3224 3225
      const newLine = getNextLine() || '';
      return lineContents + newLine
D
DCloud_LXH 已提交
3226 3227

      function getNextLine() {
fxy060608's avatar
fxy060608 已提交
3228 3229 3230
        return remainingLinesIndex < remainingLines.length
          ? remainingLines[remainingLinesIndex++]
          : undefined
D
DCloud_LXH 已提交
3231 3232 3233 3234
      }
    };

    // We need to remember the position of "remainingLines"
fxy060608's avatar
fxy060608 已提交
3235 3236
    let lastGeneratedLine = 1,
      lastGeneratedColumn = 0;
D
DCloud_LXH 已提交
3237 3238 3239 3240 3241 3242 3243

    // The generate SourceNodes we need a code range.
    // To extract it current and last mapping is used.
    // Here we store the last mapping.
    let lastMapping = null;
    let nextLine;

fxy060608's avatar
fxy060608 已提交
3244
    aSourceMapConsumer.eachMapping(function (mapping) {
D
DCloud_LXH 已提交
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
      if (lastMapping !== null) {
        // We add the code from "lastMapping" to "mapping":
        // First check if there is a new line in between.
        if (lastGeneratedLine < mapping.generatedLine) {
          // Associate first line with "lastMapping"
          addMappingWithCode(lastMapping, shiftNextLine());
          lastGeneratedLine++;
          lastGeneratedColumn = 0;
          // The remaining code is added without mapping
        } else {
          // There is no new line in between.
          // Associate the code between "lastGeneratedColumn" and
          // "mapping.generatedColumn" with "lastMapping"
fxy060608's avatar
fxy060608 已提交
3258 3259 3260 3261 3262 3263 3264 3265
          nextLine = remainingLines[remainingLinesIndex] || '';
          const code = nextLine.substr(
            0,
            mapping.generatedColumn - lastGeneratedColumn
          );
          remainingLines[remainingLinesIndex] = nextLine.substr(
            mapping.generatedColumn - lastGeneratedColumn
          );
D
DCloud_LXH 已提交
3266 3267 3268 3269
          lastGeneratedColumn = mapping.generatedColumn;
          addMappingWithCode(lastMapping, code);
          // No more remaining code, continue
          lastMapping = mapping;
fxy060608's avatar
fxy060608 已提交
3270
          return
D
DCloud_LXH 已提交
3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
        }
      }
      // We add the generated code until the first mapping
      // to the SourceNode without any mapping.
      // Each line is added as separate string.
      while (lastGeneratedLine < mapping.generatedLine) {
        node.add(shiftNextLine());
        lastGeneratedLine++;
      }
      if (lastGeneratedColumn < mapping.generatedColumn) {
fxy060608's avatar
fxy060608 已提交
3281
        nextLine = remainingLines[remainingLinesIndex] || '';
D
DCloud_LXH 已提交
3282
        node.add(nextLine.substr(0, mapping.generatedColumn));
fxy060608's avatar
fxy060608 已提交
3283 3284 3285
        remainingLines[remainingLinesIndex] = nextLine.substr(
          mapping.generatedColumn
        );
D
DCloud_LXH 已提交
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296
        lastGeneratedColumn = mapping.generatedColumn;
      }
      lastMapping = mapping;
    }, this);
    // We have processed all mappings.
    if (remainingLinesIndex < remainingLines.length) {
      if (lastMapping) {
        // Associate the remaining code in the current line with "lastMapping"
        addMappingWithCode(lastMapping, shiftNextLine());
      }
      // and add the remaining lines without any mapping
fxy060608's avatar
fxy060608 已提交
3297
      node.add(remainingLines.splice(remainingLinesIndex).join(''));
D
DCloud_LXH 已提交
3298 3299 3300
    }

    // Copy sourcesContent into SourceNode
fxy060608's avatar
fxy060608 已提交
3301
    aSourceMapConsumer.sources.forEach(function (sourceFile) {
D
DCloud_LXH 已提交
3302 3303 3304 3305 3306 3307 3308 3309 3310
      const content = aSourceMapConsumer.sourceContentFor(sourceFile);
      if (content != null) {
        if (aRelativePath != null) {
          sourceFile = util.join(aRelativePath, sourceFile);
        }
        node.setSourceContent(sourceFile, content);
      }
    });

fxy060608's avatar
fxy060608 已提交
3311
    return node
D
DCloud_LXH 已提交
3312 3313 3314 3315 3316 3317 3318 3319

    function addMappingWithCode(mapping, code) {
      if (mapping === null || mapping.source === undefined) {
        node.add(code);
      } else {
        const source = aRelativePath
          ? util.join(aRelativePath, mapping.source)
          : mapping.source;
fxy060608's avatar
fxy060608 已提交
3320 3321 3322 3323 3324 3325 3326 3327 3328
        node.add(
          new SourceNode(
            mapping.originalLine,
            mapping.originalColumn,
            source,
            code,
            mapping.name
          )
        );
D
DCloud_LXH 已提交
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
      }
    }
  }

  /**
   * Add a chunk of generated JS to this source node.
   *
   * @param aChunk A string snippet of generated JS code, another instance of
   *        SourceNode, or an array where each member is one of those things.
   */
  add(aChunk) {
    if (Array.isArray(aChunk)) {
fxy060608's avatar
fxy060608 已提交
3341
      aChunk.forEach(function (chunk) {
D
DCloud_LXH 已提交
3342 3343
        this.add(chunk);
      }, this);
fxy060608's avatar
fxy060608 已提交
3344
    } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
D
DCloud_LXH 已提交
3345 3346 3347 3348 3349
      if (aChunk) {
        this.children.push(aChunk);
      }
    } else {
      throw new TypeError(
fxy060608's avatar
fxy060608 已提交
3350 3351 3352
        'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' +
          aChunk
      )
D
DCloud_LXH 已提交
3353
    }
fxy060608's avatar
fxy060608 已提交
3354
    return this
D
DCloud_LXH 已提交
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
  }

  /**
   * Add a chunk of generated JS to the beginning of this source node.
   *
   * @param aChunk A string snippet of generated JS code, another instance of
   *        SourceNode, or an array where each member is one of those things.
   */
  prepend(aChunk) {
    if (Array.isArray(aChunk)) {
      for (let i = aChunk.length - 1; i >= 0; i--) {
        this.prepend(aChunk[i]);
      }
fxy060608's avatar
fxy060608 已提交
3368
    } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
D
DCloud_LXH 已提交
3369 3370 3371
      this.children.unshift(aChunk);
    } else {
      throw new TypeError(
fxy060608's avatar
fxy060608 已提交
3372 3373 3374
        'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' +
          aChunk
      )
D
DCloud_LXH 已提交
3375
    }
fxy060608's avatar
fxy060608 已提交
3376
    return this
D
DCloud_LXH 已提交
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
  }

  /**
   * 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.
   *
   * @param aFn The traversal function.
   */
  walk(aFn) {
    let chunk;
    for (let i = 0, len = this.children.length; i < len; i++) {
      chunk = this.children[i];
      if (chunk[isSourceNode]) {
        chunk.walk(aFn);
fxy060608's avatar
fxy060608 已提交
3392 3393 3394 3395 3396 3397 3398
      } else if (chunk !== '') {
        aFn(chunk, {
          source: this.source,
          line: this.line,
          column: this.column,
          name: this.name,
        });
D
DCloud_LXH 已提交
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
      }
    }
  }

  /**
   * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
   * each of `this.children`.
   *
   * @param aSep The separator.
   */
  join(aSep) {
    let newChildren;
    let i;
    const len = this.children.length;
    if (len > 0) {
      newChildren = [];
      for (i = 0; i < len - 1; i++) {
        newChildren.push(this.children[i]);
        newChildren.push(aSep);
      }
      newChildren.push(this.children[i]);
      this.children = newChildren;
    }
fxy060608's avatar
fxy060608 已提交
3422
    return this
D
DCloud_LXH 已提交
3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
  }

  /**
   * Call String.prototype.replace on the very right-most source snippet. Useful
   * for trimming whitespace from the end of a source node, etc.
   *
   * @param aPattern The pattern to replace.
   * @param aReplacement The thing to replace the pattern with.
   */
  replaceRight(aPattern, aReplacement) {
    const lastChild = this.children[this.children.length - 1];
    if (lastChild[isSourceNode]) {
      lastChild.replaceRight(aPattern, aReplacement);
fxy060608's avatar
fxy060608 已提交
3436 3437 3438 3439 3440
    } else if (typeof lastChild === 'string') {
      this.children[this.children.length - 1] = lastChild.replace(
        aPattern,
        aReplacement
      );
D
DCloud_LXH 已提交
3441
    } else {
fxy060608's avatar
fxy060608 已提交
3442
      this.children.push(''.replace(aPattern, aReplacement));
D
DCloud_LXH 已提交
3443
    }
fxy060608's avatar
fxy060608 已提交
3444
    return this
D
DCloud_LXH 已提交
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481
  }

  /**
   * Set the source content for a source file. This will be added to the SourceMapGenerator
   * in the sourcesContent field.
   *
   * @param aSourceFile The filename of the source file
   * @param aSourceContent The content of the source file
   */
  setSourceContent(aSourceFile, aSourceContent) {
    this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  }

  /**
   * Walk over the tree of SourceNodes. The walking function is called for each
   * source file content and is passed the filename and source content.
   *
   * @param aFn The traversal function.
   */
  walkSourceContents(aFn) {
    for (let i = 0, len = this.children.length; i < len; i++) {
      if (this.children[i][isSourceNode]) {
        this.children[i].walkSourceContents(aFn);
      }
    }

    const sources = Object.keys(this.sourceContents);
    for (let i = 0, len = sources.length; i < len; i++) {
      aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
    }
  }

  /**
   * Return the string representation of this source node. Walks over the tree
   * and concatenates all the various snippets together to one string.
   */
  toString() {
fxy060608's avatar
fxy060608 已提交
3482 3483
    let str = '';
    this.walk(function (chunk) {
D
DCloud_LXH 已提交
3484 3485
      str += chunk;
    });
fxy060608's avatar
fxy060608 已提交
3486
    return str
D
DCloud_LXH 已提交
3487 3488 3489 3490 3491 3492 3493 3494
  }

  /**
   * Returns the string representation of this source node along with a source
   * map.
   */
  toStringWithSourceMap(aArgs) {
    const generated = {
fxy060608's avatar
fxy060608 已提交
3495
      code: '',
D
DCloud_LXH 已提交
3496
      line: 1,
fxy060608's avatar
fxy060608 已提交
3497
      column: 0,
D
DCloud_LXH 已提交
3498 3499 3500 3501 3502 3503 3504
    };
    const map = new SourceMapGenerator(aArgs);
    let sourceMappingActive = false;
    let lastOriginalSource = null;
    let lastOriginalLine = null;
    let lastOriginalColumn = null;
    let lastOriginalName = null;
fxy060608's avatar
fxy060608 已提交
3505
    this.walk(function (chunk, original) {
D
DCloud_LXH 已提交
3506
      generated.code += chunk;
fxy060608's avatar
fxy060608 已提交
3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
      if (
        original.source !== null &&
        original.line !== null &&
        original.column !== null
      ) {
        if (
          lastOriginalSource !== original.source ||
          lastOriginalLine !== original.line ||
          lastOriginalColumn !== original.column ||
          lastOriginalName !== original.name
        ) {
D
DCloud_LXH 已提交
3518 3519 3520 3521
          map.addMapping({
            source: original.source,
            original: {
              line: original.line,
fxy060608's avatar
fxy060608 已提交
3522
              column: original.column,
D
DCloud_LXH 已提交
3523 3524 3525
            },
            generated: {
              line: generated.line,
fxy060608's avatar
fxy060608 已提交
3526
              column: generated.column,
D
DCloud_LXH 已提交
3527
            },
fxy060608's avatar
fxy060608 已提交
3528
            name: original.name,
D
DCloud_LXH 已提交
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539
          });
        }
        lastOriginalSource = original.source;
        lastOriginalLine = original.line;
        lastOriginalColumn = original.column;
        lastOriginalName = original.name;
        sourceMappingActive = true;
      } else if (sourceMappingActive) {
        map.addMapping({
          generated: {
            line: generated.line,
fxy060608's avatar
fxy060608 已提交
3540 3541
            column: generated.column,
          },
D
DCloud_LXH 已提交
3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
        });
        lastOriginalSource = null;
        sourceMappingActive = false;
      }
      for (let idx = 0, length = chunk.length; idx < length; idx++) {
        if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
          generated.line++;
          generated.column = 0;
          // Mappings end at eol
          if (idx + 1 === length) {
            lastOriginalSource = null;
            sourceMappingActive = false;
          } else if (sourceMappingActive) {
            map.addMapping({
              source: original.source,
              original: {
                line: original.line,
fxy060608's avatar
fxy060608 已提交
3559
                column: original.column,
D
DCloud_LXH 已提交
3560 3561 3562
              },
              generated: {
                line: generated.line,
fxy060608's avatar
fxy060608 已提交
3563
                column: generated.column,
D
DCloud_LXH 已提交
3564
              },
fxy060608's avatar
fxy060608 已提交
3565
              name: original.name,
D
DCloud_LXH 已提交
3566 3567 3568 3569 3570 3571 3572
            });
          }
        } else {
          generated.column++;
        }
      }
    });
fxy060608's avatar
fxy060608 已提交
3573
    this.walkSourceContents(function (sourceFile, sourceContent) {
D
DCloud_LXH 已提交
3574 3575 3576
      map.setSourceContent(sourceFile, sourceContent);
    });

fxy060608's avatar
fxy060608 已提交
3577
    return { code: generated.code, map }
D
DCloud_LXH 已提交
3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
  }
}

var SourceNode_1 = SourceNode;

var sourceNode = {
	SourceNode: SourceNode_1
};

var require$$1 = sourceMapConsumer;

var require$$2 = sourceNode;

/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

require$$0.SourceMapGenerator;
fxy060608's avatar
fxy060608 已提交
3598 3599
var SourceMapConsumer =
  require$$1.SourceMapConsumer;
D
DCloud_LXH 已提交
3600 3601
require$$2.SourceNode;

fxy060608's avatar
fxy060608 已提交
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
const splitRE = /\r?\n/;
const range = 2;
function posToNumber(source, pos) {
    if (typeof pos === 'number')
        return pos;
    const lines = source.split(splitRE);
    const { line, column } = pos;
    let start = 0;
    for (let i = 0; i < line - 1; i++) {
        start += lines[i].length + 1;
    }
    return start + column;
}
function generateCodeFrame(source, start = 0, end) {
    start = posToNumber(source, start);
    end = end || start;
    const lines = source.split(splitRE);
    let count = 0;
    const res = [];
    for (let i = 0; i < lines.length; i++) {
        count += lines[i].length + 1;
        if (count >= start) {
            for (let j = i - range; j <= i + range || end > count; j++) {
                if (j < 0 || j >= lines.length)
                    continue;
                const line = j + 1;
                res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}|  ${lines[j]}`);
                const lineLength = lines[j].length;
                if (j === i) {
                    // push underline
                    const pad = start - (count - lineLength) + 1;
                    const length = Math.max(1, end > count ? lineLength - pad : end - start);
                    res.push(`   |  ` + ' '.repeat(pad) + '^'.repeat(length));
                }
                else if (j > i) {
                    if (end > count) {
                        const length = Math.max(Math.min(end - count, lineLength), 1);
                        res.push(`   |  ` + '^'.repeat(length));
                    }
                    count += lineLength + 1;
                }
            }
            break;
        }
    }
    return res.join('\n');
}
const isWindows = os__default["default"].platform() === 'win32';
function normalizePath(id) {
    return isWindows ? id.replace(/\\/g, '/') : id;
}
function generateCodeFrameSourceMapConsumer(consumer, m, options = {}) {
    if (m.file) {
        const res = consumer.originalPositionFor({
            line: m.line,
            column: m.column,
        });
        if (res.source != null && res.line != null && res.column != null) {
            const code = consumer.sourceContentFor(res.source, true);
            if (code) {
                return {
                    type: m.type,
                    file: options.sourceRoot
fxy060608's avatar
fxy060608 已提交
3665
                        ? normalizePath(path__default["default"].relative(options.sourceRoot, res.source.replace('\\\\?\\', '')))
fxy060608's avatar
fxy060608 已提交
3666 3667 3668
                        : res.source,
                    line: res.line,
                    column: res.column,
fxy060608's avatar
fxy060608 已提交
3669 3670
                    message: m.message,
                    code: generateCodeFrame(code, { line: res.line, column: res.column }),
fxy060608's avatar
fxy060608 已提交
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
                };
            }
        }
    }
}
function initConsumer(filename) {
    if (fs__default["default"].existsSync(filename)) {
        return new SourceMapConsumer(fs__default["default"].readFileSync(filename, 'utf8'));
    }
    return Promise.resolve(undefined);
}
function generateCodeFrameWithSourceMapPath(filename, messages, options = {}) {
    if (typeof messages === 'string') {
        try {
            messages = JSON.parse(messages);
        }
        catch (e) { }
    }
    if (Array.isArray(messages) && messages.length) {
        return new Promise((resolve) => {
            initConsumer(filename).then((consumer) => {
                resolve(messages
                    .map((m) => {
                    if (m.file && consumer) {
                        const message = generateCodeFrameSourceMapConsumer(consumer, m, options);
                        if (message) {
                            return message;
                        }
                    }
                    if (!m.file) {
                        m.file = '';
                    }
                    return m;
                })
                    .filter(Boolean));
            });
        });
    }
    return Promise.resolve([]);
}

fxy060608's avatar
fxy060608 已提交
3712 3713 3714 3715
const nixSlashes = (x) => x.replace(/\\/g, '/');
const sourcemapCatch = {};
function stacktracey(stacktrace, opts) {
    const stack = opts.preset.parseStacktrace(stacktrace);
3716
    let parseStack = Promise.resolve();
fxy060608's avatar
fxy060608 已提交
3717
    stack.items.forEach((item, index) => {
3718
        const fn = (item, index) => {
D
DCloud_LXH 已提交
3719
            const { line = 0, column = 0, file, fileName, fileRelative } = item;
3720 3721 3722 3723
            if (item.thirdParty) {
                return Promise.resolve();
            }
            function _getSourceMapContent(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
3724
                return opts.preset
D
DCloud_LXH 已提交
3725
                    .getSourceMapContent(file, fileName, fileRelative)
fxy060608's avatar
fxy060608 已提交
3726
                    .then((content) => {
D
DCloud_LXH 已提交
3727 3728
                    if (content) {
                        return getConsumer(content).then((consumer) => {
3729
                            return parseSourceMapContent(consumer, {
fxy060608's avatar
fxy060608 已提交
3730 3731
                                line,
                                column,
fxy060608's avatar
fxy060608 已提交
3732
                            }, !!opts.withSourceContent);
fxy060608's avatar
fxy060608 已提交
3733
                        });
D
DCloud_LXH 已提交
3734
                    }
fxy060608's avatar
fxy060608 已提交
3735 3736
                });
            }
3737 3738 3739
            try {
                return _getSourceMapContent(file, fileName, fileRelative).then((sourceMapContent) => {
                    if (sourceMapContent) {
fxy060608's avatar
fxy060608 已提交
3740
                        const { source, sourcePath, sourceLine, sourceColumn, sourceContent, fileName = '', } = sourceMapContent;
3741 3742 3743 3744 3745 3746 3747 3748
                        stack.items[index] = Object.assign({}, item, {
                            file: source,
                            line: sourceLine,
                            column: sourceColumn,
                            fileShort: sourcePath,
                            fileRelative: source,
                            fileName,
                            thirdParty: isThirdParty(sourcePath),
3749
                            parsed: true,
fxy060608's avatar
fxy060608 已提交
3750
                            sourceContent,
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
                        });
                        /**
                         * 以 .js 结尾
                         * 包含 app-service.js 则需要再解析 两次
                         * 不包含 app-service.js 则无需再解析 一次
                         */
                        const curItem = stack.items[index];
                        if (stack.isMP &&
                            curItem.beforeParse.indexOf('app-service') !== -1) {
                            return fn(curItem, index);
                        }
                    }
                });
            }
fxy060608's avatar
fxy060608 已提交
3765 3766 3767 3768
            catch (error) {
                return Promise.resolve();
            }
        };
3769 3770 3771 3772 3773 3774 3775
        parseStack = parseStack.then(() => {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    fn(item, index).then(resolve);
                }, 0);
            });
        });
fxy060608's avatar
fxy060608 已提交
3776
    });
3777 3778
    const _promise = new Promise((resolve, reject) => {
        parseStack
fxy060608's avatar
fxy060608 已提交
3779 3780
            .then(() => {
            const parseError = opts.preset.asTableStacktrace({
D
DCloud_LXH 已提交
3781
                stack,
fxy060608's avatar
fxy060608 已提交
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
                maxColumnWidths: {
                    callee: 999,
                    file: 999,
                    sourceLine: 999,
                },
                stacktrace,
            });
            resolve(parseError);
        })
            .catch(() => {
            resolve(stacktrace);
        });
    });
3795
    return _promise;
fxy060608's avatar
fxy060608 已提交
3796
}
3797 3798 3799
function isThirdParty(relativePath) {
    return relativePath.indexOf('@dcloudio') !== -1;
}
D
DCloud_LXH 已提交
3800 3801
function getConsumer(content) {
    return new Promise((resolve, reject) => {
3802
        try {
D
DCloud_LXH 已提交
3803 3804
            if (SourceMapConsumer.with) {
                SourceMapConsumer.with(content, null, (consumer) => {
3805 3806 3807 3808 3809
                    resolve(consumer);
                });
            }
            else {
                // @ts-ignore
D
DCloud_LXH 已提交
3810
                const consumer = SourceMapConsumer(content);
D
DCloud_LXH 已提交
3811
                resolve(consumer);
3812
            }
D
DCloud_LXH 已提交
3813
        }
3814 3815
        catch (error) {
            reject();
D
DCloud_LXH 已提交
3816 3817 3818
        }
    });
}
fxy060608's avatar
fxy060608 已提交
3819 3820 3821 3822 3823
function getSourceMapContent(sourcemapUrl) {
    try {
        return (sourcemapCatch[sourcemapUrl] ||
            (sourcemapCatch[sourcemapUrl] = new Promise((resolve, reject) => {
                try {
D
DCloud_LXH 已提交
3824
                    if (/^[http|https]+:/i.test(sourcemapUrl)) {
fxy060608's avatar
fxy060608 已提交
3825 3826 3827
                        uni.request({
                            url: sourcemapUrl,
                            success: (res) => {
3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
                                if (res.statusCode === 200) {
                                    sourcemapCatch[sourcemapUrl] = res.data;
                                    resolve(sourcemapCatch[sourcemapUrl]);
                                }
                                else {
                                    resolve((sourcemapCatch[sourcemapUrl] = ''));
                                }
                            },
                            fail() {
                                resolve((sourcemapCatch[sourcemapUrl] = ''));
fxy060608's avatar
fxy060608 已提交
3838 3839 3840 3841
                            },
                        });
                    }
                    else {
fxy060608's avatar
fxy060608 已提交
3842
                        sourcemapCatch[sourcemapUrl] = fs__default["default"].readFileSync(sourcemapUrl, 'utf-8');
fxy060608's avatar
fxy060608 已提交
3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
                        resolve(sourcemapCatch[sourcemapUrl]);
                    }
                }
                catch (error) {
                    resolve('');
                }
            })));
    }
    catch (error) {
        return '';
    }
}
fxy060608's avatar
fxy060608 已提交
3855
function parseSourceMapContent(consumer, obj, withSourceContent) {
fxy060608's avatar
fxy060608 已提交
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867
    // source -> 'uni-app:///node_modules/@sentry/browser/esm/helpers.js'
    const { source, line: sourceLine, column: sourceColumn, } = consumer.originalPositionFor(obj);
    if (source) {
        const sourcePathSplit = source.split('/');
        const sourcePath = sourcePathSplit.slice(3).join('/');
        const fileName = sourcePathSplit.pop();
        return {
            source,
            sourcePath,
            sourceLine: sourceLine === null ? 0 : sourceLine,
            sourceColumn: sourceColumn === null ? 0 : sourceColumn,
            fileName,
fxy060608's avatar
fxy060608 已提交
3868 3869 3870
            sourceContent: withSourceContent
                ? consumer.sourceContentFor(source) || ''
                : '',
fxy060608's avatar
fxy060608 已提交
3871 3872 3873
        };
    }
}
3874
function joinItem(item) {
3875 3876 3877
    if (typeof item === 'string') {
        return item;
    }
3878 3879 3880 3881 3882
    const a = item[0];
    const b = item[1] ? `  ${item[1]}` : '';
    const c = item[2] ? ` ${item[2]}` : '';
    return `${a}${b}${c}`;
}
fxy060608's avatar
fxy060608 已提交
3883
function uniStracktraceyPreset(opts) {
3884
    const { base, sourceRoot, splitThirdParty, uniPlatform } = opts;
3885
    let stack;
fxy060608's avatar
fxy060608 已提交
3886
    return {
3887 3888 3889 3890 3891 3892 3893 3894
        /**
         *
         * 微信特殊处理
         * 微信解析步骤:
         *    1. //usr/app-service.js -> 'weixin/__APP__/app-service.map.map'
         *    2. //usr/pages/API/app-service.js -> 'weixin/pages/API/app-service.map.map'
         *    3. uni-list-item/uni-list-item.js -> ${base}/uni-list-item/uni-list-item.js.map
         */
D
DCloud_LXH 已提交
3895
        parseSourceMapUrl(file, fileName, fileRelative) {
3896
            // 组合 sourceMapUrl
D
DCloud_LXH 已提交
3897 3898 3899
            if (fileRelative.indexOf('(') !== -1)
                fileRelative = fileRelative.match(/\((.*)/)[1];
            if (!base || !fileRelative)
3900 3901
                return '';
            if (sourceRoot) {
D
DCloud_LXH 已提交
3902
                return `${fileRelative.replace(sourceRoot, base + '/')}.map`;
3903
            }
3904 3905 3906
            let baseAfter = '';
            if (stack.isMP) {
                if (fileRelative.indexOf('app-service.js') !== -1) {
3907
                    baseAfter = (base.match(/\w$/) ? '/' : '') + '__WEIXIN__';
3908 3909 3910 3911 3912 3913 3914 3915 3916
                    if (fileRelative === fileName) {
                        baseAfter += '/__APP__';
                    }
                    fileRelative = fileRelative.replace('.js', '.map');
                }
                if (baseAfter && !!fileRelative.match(/^\w/))
                    baseAfter += '/';
            }
            return `${base}${baseAfter}${fileRelative}.map`;
fxy060608's avatar
fxy060608 已提交
3917
        },
D
DCloud_LXH 已提交
3918
        getSourceMapContent(file, fileName, fileRelative) {
3919 3920 3921 3922 3923
            if (stack.isMP && fileRelative.indexOf('.js') === -1) {
                return Promise.resolve('');
            }
            const sourcemapUrl = this.parseSourceMapUrl(file, fileName, fileRelative);
            return Promise.resolve(getSourceMapContent(sourcemapUrl));
fxy060608's avatar
fxy060608 已提交
3924 3925
        },
        parseStacktrace(stacktrace) {
3926
            stack = new StackTracey$1(stacktrace, uniPlatform);
3927
            return stack;
fxy060608's avatar
fxy060608 已提交
3928
        },
D
DCloud_LXH 已提交
3929
        asTableStacktrace({ maxColumnWidths, stacktrace, stack }) {
fxy060608's avatar
fxy060608 已提交
3930
            const errorName = stacktrace.split('\n')[0];
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
            const lines = stack.asTable
                ? stack.asTable(maxColumnWidths ? { maxColumnWidths } : undefined)
                : { items: [], thirdPartyItems: [] };
            if (lines.items.length || lines.thirdPartyItems.length) {
                const { items: stackLines, thirdPartyItems: stackThirdPartyLines } = lines;
                const userError = stack.itemsHeader
                    .map((item) => {
                    if (item === '%StacktraceyItem%') {
                        const _stack = stackLines.shift();
                        return _stack ? joinItem(_stack) : '';
                    }
                    return item;
                })
                    .filter(Boolean)
                    .join('\n');
                const thirdParty = stackThirdPartyLines.length
                    ? stackThirdPartyLines.map(joinItem).join('\n')
                    : '';
                if (splitThirdParty) {
                    return {
                        userError,
                        thirdParty,
                    };
                }
                return userError + '\n' + thirdParty;
            }
            else {
3958 3959 3960 3961 3962 3963
                if (splitThirdParty) {
                    return {
                        userError: errorName,
                        thirdParty: '',
                    };
                }
3964 3965
                return errorName;
            }
fxy060608's avatar
fxy060608 已提交
3966 3967 3968 3969
        },
    };
}
function utsStracktraceyPreset(opts) {
fxy060608's avatar
fxy060608 已提交
3970
    const { inputRoot, outputRoot, sourceMapRoot } = opts;
fxy060608's avatar
fxy060608 已提交
3971 3972
    let errStack = [];
    return {
D
DCloud_LXH 已提交
3973
        parseSourceMapUrl(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
3974
            return path__default["default"].resolve(sourceMapRoot, path__default["default"].relative(outputRoot, file) + '.map');
fxy060608's avatar
fxy060608 已提交
3975
        },
D
DCloud_LXH 已提交
3976
        getSourceMapContent(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
3977
            // 根据 base,filename 组合 sourceMapUrl
D
DCloud_LXH 已提交
3978
            return Promise.resolve(getSourceMapContent(this.parseSourceMapUrl(file, fileName, fileRelative)));
fxy060608's avatar
fxy060608 已提交
3979 3980 3981 3982 3983 3984
        },
        parseStacktrace(str) {
            const lines = (str || '').split('\n');
            const entries = lines
                .map((line, index) => {
                line = line.trim();
fxy060608's avatar
fxy060608 已提交
3985 3986
                const matches = line.match(/\s*(.+\.kt):([0-9]+):([0-9]+):\s+(.*)/);
                if (matches) {
fxy060608's avatar
fxy060608 已提交
3987 3988 3989 3990
                    errStack.push('%StacktraceyItem%');
                }
                else {
                    errStack.push(line);
fxy060608's avatar
fxy060608 已提交
3991
                    return;
fxy060608's avatar
fxy060608 已提交
3992
                }
fxy060608's avatar
fxy060608 已提交
3993
                const fileName = matches[1].replace(/^.*(\\|\/|\:)/, '');
fxy060608's avatar
fxy060608 已提交
3994 3995
                return {
                    beforeParse: line,
fxy060608's avatar
fxy060608 已提交
3996
                    callee: '',
fxy060608's avatar
fxy060608 已提交
3997 3998
                    index: false,
                    native: false,
fxy060608's avatar
fxy060608 已提交
3999
                    file: nixSlashes(matches[1]),
fxy060608's avatar
fxy060608 已提交
4000 4001
                    line: parseInt(matches[2]),
                    column: parseInt(matches[3]),
fxy060608's avatar
fxy060608 已提交
4002
                    fileName,
fxy060608's avatar
fxy060608 已提交
4003 4004
                    fileShort: line,
                    errMsg: matches[4] || '',
fxy060608's avatar
fxy060608 已提交
4005 4006 4007 4008 4009 4010
                    calleeShort: '',
                    fileRelative: '',
                    thirdParty: false,
                };
            })
                .filter((x) => x !== undefined);
D
DCloud_LXH 已提交
4011
            return {
fxy060608's avatar
fxy060608 已提交
4012
                items: entries,
4013
                itemsHeader: [],
D
DCloud_LXH 已提交
4014
            };
fxy060608's avatar
fxy060608 已提交
4015
        },
D
DCloud_LXH 已提交
4016
        asTableStacktrace({ maxColumnWidths, stacktrace, stack }) {
fxy060608's avatar
fxy060608 已提交
4017 4018 4019 4020
            return errStack
                .map((item) => {
                if (item === '%StacktraceyItem%') {
                    const _stack = stack.items.shift();
fxy060608's avatar
fxy060608 已提交
4021
                    if (_stack) {
fxy060608's avatar
fxy060608 已提交
4022
                        return `at ${nixSlashes(path__default["default"].relative(inputRoot, _stack.file.replace('\\\\?\\', '')))}:${_stack.line}:${_stack.column}
fxy060608's avatar
fxy060608 已提交
4023 4024
${_stack.errMsg}`;
                    }
fxy060608's avatar
fxy060608 已提交
4025
                    return '';
fxy060608's avatar
fxy060608 已提交
4026 4027 4028 4029 4030 4031
                }
                return item;
            })
                .join('\n');
        },
    };
fxy060608's avatar
fxy060608 已提交
4032 4033
}

fxy060608's avatar
fxy060608 已提交
4034 4035 4036 4037
exports.SourceMapConsumer = SourceMapConsumer;
exports.generateCodeFrame = generateCodeFrame;
exports.generateCodeFrameSourceMapConsumer = generateCodeFrameSourceMapConsumer;
exports.generateCodeFrameWithSourceMapPath = generateCodeFrameWithSourceMapPath;
fxy060608's avatar
fxy060608 已提交
4038 4039 4040
exports.stacktracey = stacktracey;
exports.uniStracktraceyPreset = uniStracktraceyPreset;
exports.utsStracktraceyPreset = utsStracktraceyPreset;