版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

908 строки
30 KiB

  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var path = require('path');
  4. var fs = require('fs');
  5. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  6. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  7. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
  8. const comma = ','.charCodeAt(0);
  9. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  10. const intToChar = new Uint8Array(64); // 64 possible chars.
  11. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  12. for (let i = 0; i < chars.length; i++) {
  13. const c = chars.charCodeAt(i);
  14. intToChar[i] = c;
  15. charToInt[c] = i;
  16. }
  17. function decode(mappings) {
  18. const state = new Int32Array(5);
  19. const decoded = [];
  20. let index = 0;
  21. do {
  22. const semi = indexOf(mappings, index);
  23. const line = [];
  24. let sorted = true;
  25. let lastCol = 0;
  26. state[0] = 0;
  27. for (let i = index; i < semi; i++) {
  28. let seg;
  29. i = decodeInteger(mappings, i, state, 0); // genColumn
  30. const col = state[0];
  31. if (col < lastCol)
  32. sorted = false;
  33. lastCol = col;
  34. if (hasMoreVlq(mappings, i, semi)) {
  35. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  36. i = decodeInteger(mappings, i, state, 2); // sourceLine
  37. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  38. if (hasMoreVlq(mappings, i, semi)) {
  39. i = decodeInteger(mappings, i, state, 4); // namesIndex
  40. seg = [col, state[1], state[2], state[3], state[4]];
  41. }
  42. else {
  43. seg = [col, state[1], state[2], state[3]];
  44. }
  45. }
  46. else {
  47. seg = [col];
  48. }
  49. line.push(seg);
  50. }
  51. if (!sorted)
  52. sort(line);
  53. decoded.push(line);
  54. index = semi + 1;
  55. } while (index <= mappings.length);
  56. return decoded;
  57. }
  58. function indexOf(mappings, index) {
  59. const idx = mappings.indexOf(';', index);
  60. return idx === -1 ? mappings.length : idx;
  61. }
  62. function decodeInteger(mappings, pos, state, j) {
  63. let value = 0;
  64. let shift = 0;
  65. let integer = 0;
  66. do {
  67. const c = mappings.charCodeAt(pos++);
  68. integer = charToInt[c];
  69. value |= (integer & 31) << shift;
  70. shift += 5;
  71. } while (integer & 32);
  72. const shouldNegate = value & 1;
  73. value >>>= 1;
  74. if (shouldNegate) {
  75. value = -0x80000000 | -value;
  76. }
  77. state[j] += value;
  78. return pos;
  79. }
  80. function hasMoreVlq(mappings, i, length) {
  81. if (i >= length)
  82. return false;
  83. return mappings.charCodeAt(i) !== comma;
  84. }
  85. function sort(line) {
  86. line.sort(sortComparator$1);
  87. }
  88. function sortComparator$1(a, b) {
  89. return a[0] - b[0];
  90. }
  91. // Matches the scheme of a URL, eg "http://"
  92. const schemeRegex = /^[\w+.-]+:\/\//;
  93. /**
  94. * Matches the parts of a URL:
  95. * 1. Scheme, including ":", guaranteed.
  96. * 2. User/password, including "@", optional.
  97. * 3. Host, guaranteed.
  98. * 4. Port, including ":", optional.
  99. * 5. Path, including "/", optional.
  100. * 6. Query, including "?", optional.
  101. * 7. Hash, including "#", optional.
  102. */
  103. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  104. /**
  105. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  106. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  107. *
  108. * 1. Host, optional.
  109. * 2. Path, which may include "/", guaranteed.
  110. * 3. Query, including "?", optional.
  111. * 4. Hash, including "#", optional.
  112. */
  113. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  114. var UrlType;
  115. (function (UrlType) {
  116. UrlType[UrlType["Empty"] = 1] = "Empty";
  117. UrlType[UrlType["Hash"] = 2] = "Hash";
  118. UrlType[UrlType["Query"] = 3] = "Query";
  119. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  120. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  121. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  122. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  123. })(UrlType || (UrlType = {}));
  124. function isAbsoluteUrl(input) {
  125. return schemeRegex.test(input);
  126. }
  127. function isSchemeRelativeUrl(input) {
  128. return input.startsWith('//');
  129. }
  130. function isAbsolutePath(input) {
  131. return input.startsWith('/');
  132. }
  133. function isFileUrl(input) {
  134. return input.startsWith('file:');
  135. }
  136. function isRelative(input) {
  137. return /^[.?#]/.test(input);
  138. }
  139. function parseAbsoluteUrl(input) {
  140. const match = urlRegex.exec(input);
  141. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  142. }
  143. function parseFileUrl(input) {
  144. const match = fileRegex.exec(input);
  145. const path = match[2];
  146. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  147. }
  148. function makeUrl(scheme, user, host, port, path, query, hash) {
  149. return {
  150. scheme,
  151. user,
  152. host,
  153. port,
  154. path,
  155. query,
  156. hash,
  157. type: UrlType.Absolute,
  158. };
  159. }
  160. function parseUrl(input) {
  161. if (isSchemeRelativeUrl(input)) {
  162. const url = parseAbsoluteUrl('http:' + input);
  163. url.scheme = '';
  164. url.type = UrlType.SchemeRelative;
  165. return url;
  166. }
  167. if (isAbsolutePath(input)) {
  168. const url = parseAbsoluteUrl('http://foo.com' + input);
  169. url.scheme = '';
  170. url.host = '';
  171. url.type = UrlType.AbsolutePath;
  172. return url;
  173. }
  174. if (isFileUrl(input))
  175. return parseFileUrl(input);
  176. if (isAbsoluteUrl(input))
  177. return parseAbsoluteUrl(input);
  178. const url = parseAbsoluteUrl('http://foo.com/' + input);
  179. url.scheme = '';
  180. url.host = '';
  181. url.type = input
  182. ? input.startsWith('?')
  183. ? UrlType.Query
  184. : input.startsWith('#')
  185. ? UrlType.Hash
  186. : UrlType.RelativePath
  187. : UrlType.Empty;
  188. return url;
  189. }
  190. function stripPathFilename(path) {
  191. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  192. // paths. It's not a file, so we can't strip it.
  193. if (path.endsWith('/..'))
  194. return path;
  195. const index = path.lastIndexOf('/');
  196. return path.slice(0, index + 1);
  197. }
  198. function mergePaths(url, base) {
  199. normalizePath(base, base.type);
  200. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  201. // path).
  202. if (url.path === '/') {
  203. url.path = base.path;
  204. }
  205. else {
  206. // Resolution happens relative to the base path's directory, not the file.
  207. url.path = stripPathFilename(base.path) + url.path;
  208. }
  209. }
  210. /**
  211. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  212. * "foo/.". We need to normalize to a standard representation.
  213. */
  214. function normalizePath(url, type) {
  215. const rel = type <= UrlType.RelativePath;
  216. const pieces = url.path.split('/');
  217. // We need to preserve the first piece always, so that we output a leading slash. The item at
  218. // pieces[0] is an empty string.
  219. let pointer = 1;
  220. // Positive is the number of real directories we've output, used for popping a parent directory.
  221. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  222. let positive = 0;
  223. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  224. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  225. // real directory, we won't need to append, unless the other conditions happen again.
  226. let addTrailingSlash = false;
  227. for (let i = 1; i < pieces.length; i++) {
  228. const piece = pieces[i];
  229. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  230. if (!piece) {
  231. addTrailingSlash = true;
  232. continue;
  233. }
  234. // If we encounter a real directory, then we don't need to append anymore.
  235. addTrailingSlash = false;
  236. // A current directory, which we can always drop.
  237. if (piece === '.')
  238. continue;
  239. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  240. // have an excess of parents, and we'll need to keep the "..".
  241. if (piece === '..') {
  242. if (positive) {
  243. addTrailingSlash = true;
  244. positive--;
  245. pointer--;
  246. }
  247. else if (rel) {
  248. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  249. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  250. pieces[pointer++] = piece;
  251. }
  252. continue;
  253. }
  254. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  255. // any popped or dropped directories.
  256. pieces[pointer++] = piece;
  257. positive++;
  258. }
  259. let path = '';
  260. for (let i = 1; i < pointer; i++) {
  261. path += '/' + pieces[i];
  262. }
  263. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  264. path += '/';
  265. }
  266. url.path = path;
  267. }
  268. /**
  269. * Attempts to resolve `input` URL/path relative to `base`.
  270. */
  271. function resolve$1(input, base) {
  272. if (!input && !base)
  273. return '';
  274. const url = parseUrl(input);
  275. let inputType = url.type;
  276. if (base && inputType !== UrlType.Absolute) {
  277. const baseUrl = parseUrl(base);
  278. const baseType = baseUrl.type;
  279. switch (inputType) {
  280. case UrlType.Empty:
  281. url.hash = baseUrl.hash;
  282. // fall through
  283. case UrlType.Hash:
  284. url.query = baseUrl.query;
  285. // fall through
  286. case UrlType.Query:
  287. case UrlType.RelativePath:
  288. mergePaths(url, baseUrl);
  289. // fall through
  290. case UrlType.AbsolutePath:
  291. // The host, user, and port are joined, you can't copy one without the others.
  292. url.user = baseUrl.user;
  293. url.host = baseUrl.host;
  294. url.port = baseUrl.port;
  295. // fall through
  296. case UrlType.SchemeRelative:
  297. // The input doesn't have a schema at least, so we need to copy at least that over.
  298. url.scheme = baseUrl.scheme;
  299. }
  300. if (baseType > inputType)
  301. inputType = baseType;
  302. }
  303. normalizePath(url, inputType);
  304. const queryHash = url.query + url.hash;
  305. switch (inputType) {
  306. // This is impossible, because of the empty checks at the start of the function.
  307. // case UrlType.Empty:
  308. case UrlType.Hash:
  309. case UrlType.Query:
  310. return queryHash;
  311. case UrlType.RelativePath: {
  312. // The first char is always a "/", and we need it to be relative.
  313. const path = url.path.slice(1);
  314. if (!path)
  315. return queryHash || '.';
  316. if (isRelative(base || input) && !isRelative(path)) {
  317. // If base started with a leading ".", or there is no base and input started with a ".",
  318. // then we need to ensure that the relative path starts with a ".". We don't know if
  319. // relative starts with a "..", though, so check before prepending.
  320. return './' + path + queryHash;
  321. }
  322. return path + queryHash;
  323. }
  324. case UrlType.AbsolutePath:
  325. return url.path + queryHash;
  326. default:
  327. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  328. }
  329. }
  330. function resolve(input, base) {
  331. // The base is always treated as a directory, if it's not empty.
  332. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  333. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  334. if (base && !base.endsWith('/'))
  335. base += '/';
  336. return resolve$1(input, base);
  337. }
  338. /**
  339. * Removes everything after the last "/", but leaves the slash.
  340. */
  341. function stripFilename(path) {
  342. if (!path)
  343. return '';
  344. const index = path.lastIndexOf('/');
  345. return path.slice(0, index + 1);
  346. }
  347. const COLUMN = 0;
  348. const SOURCES_INDEX = 1;
  349. const SOURCE_LINE = 2;
  350. const SOURCE_COLUMN = 3;
  351. const NAMES_INDEX = 4;
  352. function maybeSort(mappings, owned) {
  353. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  354. if (unsortedIndex === mappings.length)
  355. return mappings;
  356. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  357. // not, we do not want to modify the consumer's input array.
  358. if (!owned)
  359. mappings = mappings.slice();
  360. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  361. mappings[i] = sortSegments(mappings[i], owned);
  362. }
  363. return mappings;
  364. }
  365. function nextUnsortedSegmentLine(mappings, start) {
  366. for (let i = start; i < mappings.length; i++) {
  367. if (!isSorted(mappings[i]))
  368. return i;
  369. }
  370. return mappings.length;
  371. }
  372. function isSorted(line) {
  373. for (let j = 1; j < line.length; j++) {
  374. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  375. return false;
  376. }
  377. }
  378. return true;
  379. }
  380. function sortSegments(line, owned) {
  381. if (!owned)
  382. line = line.slice();
  383. return line.sort(sortComparator);
  384. }
  385. function sortComparator(a, b) {
  386. return a[COLUMN] - b[COLUMN];
  387. }
  388. let found = false;
  389. /**
  390. * A binary search implementation that returns the index if a match is found.
  391. * If no match is found, then the left-index (the index associated with the item that comes just
  392. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  393. * the next index:
  394. *
  395. * ```js
  396. * const array = [1, 3];
  397. * const needle = 2;
  398. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  399. *
  400. * assert.equal(index, 0);
  401. * array.splice(index + 1, 0, needle);
  402. * assert.deepEqual(array, [1, 2, 3]);
  403. * ```
  404. */
  405. function binarySearch(haystack, needle, low, high) {
  406. while (low <= high) {
  407. const mid = low + ((high - low) >> 1);
  408. const cmp = haystack[mid][COLUMN] - needle;
  409. if (cmp === 0) {
  410. found = true;
  411. return mid;
  412. }
  413. if (cmp < 0) {
  414. low = mid + 1;
  415. }
  416. else {
  417. high = mid - 1;
  418. }
  419. }
  420. found = false;
  421. return low - 1;
  422. }
  423. function upperBound(haystack, needle, index) {
  424. for (let i = index + 1; i < haystack.length; index = i++) {
  425. if (haystack[i][COLUMN] !== needle)
  426. break;
  427. }
  428. return index;
  429. }
  430. function lowerBound(haystack, needle, index) {
  431. for (let i = index - 1; i >= 0; index = i--) {
  432. if (haystack[i][COLUMN] !== needle)
  433. break;
  434. }
  435. return index;
  436. }
  437. function memoizedState() {
  438. return {
  439. lastKey: -1,
  440. lastNeedle: -1,
  441. lastIndex: -1,
  442. };
  443. }
  444. /**
  445. * This overly complicated beast is just to record the last tested line/column and the resulting
  446. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  447. */
  448. function memoizedBinarySearch(haystack, needle, state, key) {
  449. const { lastKey, lastNeedle, lastIndex } = state;
  450. let low = 0;
  451. let high = haystack.length - 1;
  452. if (key === lastKey) {
  453. if (needle === lastNeedle) {
  454. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  455. return lastIndex;
  456. }
  457. if (needle >= lastNeedle) {
  458. // lastIndex may be -1 if the previous needle was not found.
  459. low = lastIndex === -1 ? 0 : lastIndex;
  460. }
  461. else {
  462. high = lastIndex;
  463. }
  464. }
  465. state.lastKey = key;
  466. state.lastNeedle = needle;
  467. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  468. }
  469. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  470. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  471. const LEAST_UPPER_BOUND = -1;
  472. const GREATEST_LOWER_BOUND = 1;
  473. /**
  474. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  475. */
  476. let decodedMappings;
  477. /**
  478. * A higher-level API to find the source/line/column associated with a generated line/column
  479. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  480. * `source-map` library.
  481. */
  482. let originalPositionFor;
  483. class TraceMap {
  484. constructor(map, mapUrl) {
  485. const isString = typeof map === 'string';
  486. if (!isString && map._decodedMemo)
  487. return map;
  488. const parsed = (isString ? JSON.parse(map) : map);
  489. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  490. this.version = version;
  491. this.file = file;
  492. this.names = names;
  493. this.sourceRoot = sourceRoot;
  494. this.sources = sources;
  495. this.sourcesContent = sourcesContent;
  496. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  497. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  498. const { mappings } = parsed;
  499. if (typeof mappings === 'string') {
  500. this._encoded = mappings;
  501. this._decoded = undefined;
  502. }
  503. else {
  504. this._encoded = undefined;
  505. this._decoded = maybeSort(mappings, isString);
  506. }
  507. this._decodedMemo = memoizedState();
  508. this._bySources = undefined;
  509. this._bySourceMemos = undefined;
  510. }
  511. }
  512. (() => {
  513. decodedMappings = (map) => {
  514. return (map._decoded || (map._decoded = decode(map._encoded)));
  515. };
  516. originalPositionFor = (map, { line, column, bias }) => {
  517. line--;
  518. if (line < 0)
  519. throw new Error(LINE_GTR_ZERO);
  520. if (column < 0)
  521. throw new Error(COL_GTR_EQ_ZERO);
  522. const decoded = decodedMappings(map);
  523. // It's common for parent source maps to have pointers to lines that have no
  524. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  525. if (line >= decoded.length)
  526. return OMapping(null, null, null, null);
  527. const segments = decoded[line];
  528. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  529. if (index === -1)
  530. return OMapping(null, null, null, null);
  531. const segment = segments[index];
  532. if (segment.length === 1)
  533. return OMapping(null, null, null, null);
  534. const { names, resolvedSources } = map;
  535. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  536. };
  537. })();
  538. function OMapping(source, line, column, name) {
  539. return { source, line, column, name };
  540. }
  541. function traceSegmentInternal(segments, memo, line, column, bias) {
  542. let index = memoizedBinarySearch(segments, column, memo, line);
  543. if (found) {
  544. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  545. }
  546. else if (bias === LEAST_UPPER_BOUND)
  547. index++;
  548. if (index === -1 || index === segments.length)
  549. return -1;
  550. return index;
  551. }
  552. let errorFormatterInstalled = false;
  553. let fileContentsCache = {};
  554. let sourceMapCache = {};
  555. const reSourceMap = /^data:application\/json[^,]+base64,/;
  556. let retrieveFileHandlers = [];
  557. let retrieveMapHandlers = [];
  558. function globalProcessVersion() {
  559. if (typeof process === "object" && process !== null)
  560. return process.version;
  561. else
  562. return "";
  563. }
  564. function handlerExec(list) {
  565. return function(arg) {
  566. for (let i = 0; i < list.length; i++) {
  567. const ret = list[i](arg);
  568. if (ret)
  569. return ret;
  570. }
  571. return null;
  572. };
  573. }
  574. let retrieveFile = handlerExec(retrieveFileHandlers);
  575. retrieveFileHandlers.push((path2) => {
  576. path2 = path2.trim();
  577. if (path2.startsWith("file:")) {
  578. path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
  579. return drive ? "" : "/";
  580. });
  581. }
  582. if (path2 in fileContentsCache)
  583. return fileContentsCache[path2];
  584. let contents = "";
  585. try {
  586. if (fs__default["default"].existsSync(path2))
  587. contents = fs__default["default"].readFileSync(path2, "utf8");
  588. } catch (er) {
  589. }
  590. return fileContentsCache[path2] = contents;
  591. });
  592. function supportRelativeURL(file, url) {
  593. if (!file)
  594. return url;
  595. const dir = path__default["default"].dirname(file);
  596. const match = /^\w+:\/\/[^\/]*/.exec(dir);
  597. let protocol = match ? match[0] : "";
  598. const startPath = dir.slice(protocol.length);
  599. if (protocol && /^\/\w\:/.test(startPath)) {
  600. protocol += "/";
  601. return protocol + path__default["default"].resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
  602. }
  603. return protocol + path__default["default"].resolve(dir.slice(protocol.length), url);
  604. }
  605. function retrieveSourceMapURL(source) {
  606. const fileData = retrieveFile(source);
  607. if (!fileData)
  608. return null;
  609. const re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
  610. let lastMatch, match;
  611. while (match = re.exec(fileData))
  612. lastMatch = match;
  613. if (!lastMatch)
  614. return null;
  615. return lastMatch[1];
  616. }
  617. let retrieveSourceMap = handlerExec(retrieveMapHandlers);
  618. retrieveMapHandlers.push((source) => {
  619. let sourceMappingURL = retrieveSourceMapURL(source);
  620. if (!sourceMappingURL)
  621. return null;
  622. let sourceMapData;
  623. if (reSourceMap.test(sourceMappingURL)) {
  624. const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  625. sourceMapData = Buffer.from(rawData, "base64").toString();
  626. sourceMappingURL = source;
  627. } else {
  628. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  629. sourceMapData = retrieveFile(sourceMappingURL);
  630. }
  631. if (!sourceMapData)
  632. return null;
  633. return {
  634. url: sourceMappingURL,
  635. map: sourceMapData
  636. };
  637. });
  638. function mapSourcePosition(position) {
  639. var _a;
  640. if (!position.source)
  641. return position;
  642. let sourceMap = sourceMapCache[position.source];
  643. if (!sourceMap) {
  644. const urlAndMap = retrieveSourceMap(position.source);
  645. if (urlAndMap && urlAndMap.map) {
  646. sourceMap = sourceMapCache[position.source] = {
  647. url: urlAndMap.url,
  648. map: new TraceMap(urlAndMap.map)
  649. };
  650. if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) {
  651. sourceMap.map.sources.forEach((source, i) => {
  652. var _a2, _b;
  653. const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[i];
  654. if (contents && source && sourceMap.url) {
  655. const url = supportRelativeURL(sourceMap.url, source);
  656. fileContentsCache[url] = contents;
  657. }
  658. });
  659. }
  660. } else {
  661. sourceMap = sourceMapCache[position.source] = {
  662. url: null,
  663. map: null
  664. };
  665. }
  666. }
  667. if (sourceMap && sourceMap.map && sourceMap.url) {
  668. const originalPosition = originalPositionFor(sourceMap.map, position);
  669. if (originalPosition.source !== null) {
  670. originalPosition.source = supportRelativeURL(
  671. sourceMap.url,
  672. originalPosition.source
  673. );
  674. return originalPosition;
  675. }
  676. }
  677. return position;
  678. }
  679. function mapEvalOrigin(origin) {
  680. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  681. if (match) {
  682. const position = mapSourcePosition({
  683. name: null,
  684. source: match[2],
  685. line: +match[3],
  686. column: +match[4] - 1
  687. });
  688. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  689. }
  690. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  691. if (match)
  692. return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`;
  693. return origin;
  694. }
  695. function CallSiteToString() {
  696. let fileName;
  697. let fileLocation = "";
  698. if (this.isNative()) {
  699. fileLocation = "native";
  700. } else {
  701. fileName = this.getScriptNameOrSourceURL();
  702. if (!fileName && this.isEval()) {
  703. fileLocation = this.getEvalOrigin();
  704. fileLocation += ", ";
  705. }
  706. if (fileName) {
  707. fileLocation += fileName;
  708. } else {
  709. fileLocation += "<anonymous>";
  710. }
  711. const lineNumber = this.getLineNumber();
  712. if (lineNumber != null) {
  713. fileLocation += `:${lineNumber}`;
  714. const columnNumber = this.getColumnNumber();
  715. if (columnNumber)
  716. fileLocation += `:${columnNumber}`;
  717. }
  718. }
  719. let line = "";
  720. const functionName = this.getFunctionName();
  721. let addSuffix = true;
  722. const isConstructor = this.isConstructor();
  723. const isMethodCall = !(this.isToplevel() || isConstructor);
  724. if (isMethodCall) {
  725. let typeName = this.getTypeName();
  726. if (typeName === "[object Object]")
  727. typeName = "null";
  728. const methodName = this.getMethodName();
  729. if (functionName) {
  730. if (typeName && functionName.indexOf(typeName) !== 0)
  731. line += `${typeName}.`;
  732. line += functionName;
  733. if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1)
  734. line += ` [as ${methodName}]`;
  735. } else {
  736. line += `${typeName}.${methodName || "<anonymous>"}`;
  737. }
  738. } else if (isConstructor) {
  739. line += `new ${functionName || "<anonymous>"}`;
  740. } else if (functionName) {
  741. line += functionName;
  742. } else {
  743. line += fileLocation;
  744. addSuffix = false;
  745. }
  746. if (addSuffix)
  747. line += ` (${fileLocation})`;
  748. return line;
  749. }
  750. function cloneCallSite(frame) {
  751. const object = {};
  752. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  753. const key = name;
  754. object[key] = /^(?:is|get)/.test(name) ? function() {
  755. return frame[key].call(frame);
  756. } : frame[key];
  757. });
  758. object.toString = CallSiteToString;
  759. return object;
  760. }
  761. function wrapCallSite(frame, state) {
  762. if (state === void 0)
  763. state = { nextPosition: null, curPosition: null };
  764. if (frame.isNative()) {
  765. state.curPosition = null;
  766. return frame;
  767. }
  768. const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  769. if (source) {
  770. const line = frame.getLineNumber();
  771. let column = frame.getColumnNumber() - 1;
  772. const noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
  773. const headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
  774. if (line === 1 && column > headerLength && !frame.isEval())
  775. column -= headerLength;
  776. const position = mapSourcePosition({
  777. name: null,
  778. source,
  779. line,
  780. column
  781. });
  782. state.curPosition = position;
  783. frame = cloneCallSite(frame);
  784. const originalFunctionName = frame.getFunctionName;
  785. frame.getFunctionName = function() {
  786. if (state.nextPosition == null)
  787. return originalFunctionName();
  788. return state.nextPosition.name || originalFunctionName();
  789. };
  790. frame.getFileName = function() {
  791. return position.source;
  792. };
  793. frame.getLineNumber = function() {
  794. return position.line;
  795. };
  796. frame.getColumnNumber = function() {
  797. return position.column + 1;
  798. };
  799. frame.getScriptNameOrSourceURL = function() {
  800. return position.source;
  801. };
  802. return frame;
  803. }
  804. let origin = frame.isEval() && frame.getEvalOrigin();
  805. if (origin) {
  806. origin = mapEvalOrigin(origin);
  807. frame = cloneCallSite(frame);
  808. frame.getEvalOrigin = function() {
  809. return origin || void 0;
  810. };
  811. return frame;
  812. }
  813. return frame;
  814. }
  815. function prepareStackTrace(error, stack) {
  816. const name = error.name || "Error";
  817. const message = error.message || "";
  818. const errorString = `${name}: ${message}`;
  819. const state = { nextPosition: null, curPosition: null };
  820. const processedStack = [];
  821. for (let i = stack.length - 1; i >= 0; i--) {
  822. processedStack.push(`
  823. at ${wrapCallSite(stack[i], state)}`);
  824. state.nextPosition = state.curPosition;
  825. }
  826. state.curPosition = state.nextPosition = null;
  827. return errorString + processedStack.reverse().join("");
  828. }
  829. retrieveFileHandlers.slice(0);
  830. retrieveMapHandlers.slice(0);
  831. const install = function(options) {
  832. options = options || {};
  833. if (options.retrieveFile) {
  834. if (options.overrideRetrieveFile)
  835. retrieveFileHandlers.length = 0;
  836. retrieveFileHandlers.unshift(options.retrieveFile);
  837. }
  838. if (options.retrieveSourceMap) {
  839. if (options.overrideRetrieveSourceMap)
  840. retrieveMapHandlers.length = 0;
  841. retrieveMapHandlers.unshift(options.retrieveSourceMap);
  842. }
  843. if (!errorFormatterInstalled) {
  844. errorFormatterInstalled = true;
  845. Error.prepareStackTrace = prepareStackTrace;
  846. }
  847. };
  848. let SOURCEMAPPING_URL = "sourceMa";
  849. SOURCEMAPPING_URL += "ppingURL";
  850. const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
  851. const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
  852. const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
  853. function withInlineSourcemap(result) {
  854. const map = result.map;
  855. let code = result.code;
  856. if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
  857. return result;
  858. const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
  859. while (OTHER_SOURCE_MAP_REGEXP.test(code))
  860. code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
  861. const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
  862. result.code = `${code.trimEnd()}
  863. ${VITE_NODE_SOURCEMAPPING_SOURCE}
  864. //# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
  865. `;
  866. return result;
  867. }
  868. function extractSourceMap(code) {
  869. var _a;
  870. const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
  871. if (mapString)
  872. return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
  873. return null;
  874. }
  875. function installSourcemapsSupport(options) {
  876. install({
  877. retrieveSourceMap(source) {
  878. const map = options.getSourceMap(source);
  879. if (map) {
  880. return {
  881. url: source,
  882. map
  883. };
  884. }
  885. return null;
  886. }
  887. });
  888. }
  889. exports.extractSourceMap = extractSourceMap;
  890. exports.installSourcemapsSupport = installSourcemapsSupport;
  891. exports.withInlineSourcemap = withInlineSourcemap;