source-map-support.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping');
  2. var path = require('path');
  3. const { fileURLToPath, pathToFileURL } = require('url');
  4. var util = require('util');
  5. var fs;
  6. try {
  7. fs = require('fs');
  8. if (!fs.existsSync || !fs.readFileSync) {
  9. // fs doesn't have all methods we need
  10. fs = null;
  11. }
  12. } catch (err) {
  13. /* nop */
  14. }
  15. /**
  16. * Requires a module which is protected against bundler minification.
  17. *
  18. * @param {NodeModule} mod
  19. * @param {string} request
  20. */
  21. function dynamicRequire(mod, request) {
  22. return mod.require(request);
  23. }
  24. /**
  25. * @typedef {{
  26. * enabled: boolean;
  27. * originalValue: any;
  28. * installedValue: any;
  29. * }} HookState
  30. * Used for installing and uninstalling hooks
  31. */
  32. // Increment this if the format of sharedData changes in a breaking way.
  33. var sharedDataVersion = 1;
  34. /**
  35. * @template T
  36. * @param {T} defaults
  37. * @returns {T}
  38. */
  39. function initializeSharedData(defaults) {
  40. var sharedDataKey = 'source-map-support/sharedData';
  41. if (typeof Symbol !== 'undefined') {
  42. sharedDataKey = Symbol.for(sharedDataKey);
  43. }
  44. var sharedData = this[sharedDataKey];
  45. if (!sharedData) {
  46. sharedData = { version: sharedDataVersion };
  47. if (Object.defineProperty) {
  48. Object.defineProperty(this, sharedDataKey, { value: sharedData });
  49. } else {
  50. this[sharedDataKey] = sharedData;
  51. }
  52. }
  53. if (sharedDataVersion !== sharedData.version) {
  54. throw new Error("Multiple incompatible instances of source-map-support were loaded");
  55. }
  56. for (var key in defaults) {
  57. if (!(key in sharedData)) {
  58. sharedData[key] = defaults[key];
  59. }
  60. }
  61. return sharedData;
  62. }
  63. // If multiple instances of source-map-support are loaded into the same
  64. // context, they shouldn't overwrite each other. By storing handlers, caches,
  65. // and other state on a shared object, different instances of
  66. // source-map-support can work together in a limited way. This does require
  67. // that future versions of source-map-support continue to support the fields on
  68. // this object. If this internal contract ever needs to be broken, increment
  69. // sharedDataVersion. (This version number is not the same as any of the
  70. // package's version numbers, which should reflect the *external* API of
  71. // source-map-support.)
  72. var sharedData = initializeSharedData({
  73. // Only install once if called multiple times
  74. // Remember how the environment looked before installation so we can restore if able
  75. /** @type {HookState} */
  76. errorPrepareStackTraceHook: undefined,
  77. /** @type {HookState} */
  78. processEmitHook: undefined,
  79. /** @type {HookState} */
  80. moduleResolveFilenameHook: undefined,
  81. /** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */
  82. onConflictingLibraryRedirectArr: [],
  83. // If true, the caches are reset before a stack trace formatting operation
  84. emptyCacheBetweenOperations: false,
  85. // Maps a file path to a string containing the file contents
  86. fileContentsCache: Object.create(null),
  87. // Maps a file path to a source map for that file
  88. /** @type {Record<string, {url: string, map: TraceMap}} */
  89. sourceMapCache: Object.create(null),
  90. // Priority list of retrieve handlers
  91. retrieveFileHandlers: [],
  92. retrieveMapHandlers: [],
  93. // Priority list of internally-implemented handlers.
  94. // When resetting state, we must keep these.
  95. internalRetrieveFileHandlers: [],
  96. internalRetrieveMapHandlers: [],
  97. });
  98. // Supports {browser, node, auto}
  99. var environment = "auto";
  100. // Regex for detecting source maps
  101. var reSourceMap = /^data:application\/json[^,]+base64,/;
  102. function isInBrowser() {
  103. if (environment === "browser")
  104. return true;
  105. if (environment === "node")
  106. return false;
  107. return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
  108. }
  109. function hasGlobalProcessEventEmitter() {
  110. return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
  111. }
  112. function tryFileURLToPath(v) {
  113. if(isFileUrl(v)) {
  114. return fileURLToPath(v);
  115. }
  116. return v;
  117. }
  118. // TODO un-copy these from resolve-uri; see if they can be exported from that lib
  119. function isFileUrl(input) {
  120. return input.startsWith('file:');
  121. }
  122. function isAbsoluteUrl(input) {
  123. return schemeRegex.test(input);
  124. }
  125. // Matches the scheme of a URL, eg "http://"
  126. const schemeRegex = /^[\w+.-]+:\/\//;
  127. function isSchemeRelativeUrl(input) {
  128. return input.startsWith('//');
  129. }
  130. // #region Caches
  131. /** @param {string} pathOrFileUrl */
  132. function getCacheKey(pathOrFileUrl) {
  133. if(pathOrFileUrl.startsWith('node:')) return pathOrFileUrl;
  134. if(isFileUrl(pathOrFileUrl)) {
  135. // Must normalize spaces to %20, stuff like that
  136. return new URL(pathOrFileUrl).toString();
  137. } else {
  138. try {
  139. return pathToFileURL(pathOrFileUrl).toString();
  140. } catch {
  141. return pathOrFileUrl;
  142. }
  143. }
  144. }
  145. function getFileContentsCache(key) {
  146. return sharedData.fileContentsCache[getCacheKey(key)];
  147. }
  148. function hasFileContentsCacheFromKey(key) {
  149. return Object.prototype.hasOwnProperty.call(sharedData.fileContentsCache, key);
  150. }
  151. function getFileContentsCacheFromKey(key) {
  152. return sharedData.fileContentsCache[key];
  153. }
  154. function setFileContentsCache(key, value) {
  155. return sharedData.fileContentsCache[getCacheKey(key)] = value;
  156. }
  157. function getSourceMapCache(key) {
  158. return sharedData.sourceMapCache[getCacheKey(key)];
  159. }
  160. function setSourceMapCache(key, value) {
  161. return sharedData.sourceMapCache[getCacheKey(key)] = value;
  162. }
  163. function clearCaches() {
  164. sharedData.fileContentsCache = Object.create(null);
  165. sharedData.sourceMapCache = Object.create(null);
  166. }
  167. // #endregion Caches
  168. function handlerExec(list, internalList) {
  169. return function(arg) {
  170. for (var i = 0; i < list.length; i++) {
  171. var ret = list[i](arg);
  172. if (ret) {
  173. return ret;
  174. }
  175. }
  176. for (var i = 0; i < internalList.length; i++) {
  177. var ret = internalList[i](arg);
  178. if (ret) {
  179. return ret;
  180. }
  181. }
  182. return null;
  183. };
  184. }
  185. var retrieveFile = handlerExec(sharedData.retrieveFileHandlers, sharedData.internalRetrieveFileHandlers);
  186. sharedData.internalRetrieveFileHandlers.push(function(path) {
  187. // Trim the path to make sure there is no extra whitespace.
  188. path = path.trim();
  189. if (/^file:/.test(path)) {
  190. // existsSync/readFileSync can't handle file protocol, but once stripped, it works
  191. path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
  192. return drive ?
  193. '' : // file:///C:/dir/file -> C:/dir/file
  194. '/'; // file:///root-dir/file -> /root-dir/file
  195. });
  196. }
  197. const key = getCacheKey(path);
  198. if(hasFileContentsCacheFromKey(key)) {
  199. return getFileContentsCacheFromKey(key);
  200. }
  201. var contents = '';
  202. try {
  203. if (!fs) {
  204. // Use SJAX if we are in the browser
  205. var xhr = new XMLHttpRequest();
  206. xhr.open('GET', path, /** async */ false);
  207. xhr.send(null);
  208. if (xhr.readyState === 4 && xhr.status === 200) {
  209. contents = xhr.responseText;
  210. }
  211. } else if (fs.existsSync(path)) {
  212. // Otherwise, use the filesystem
  213. contents = fs.readFileSync(path, 'utf8');
  214. }
  215. } catch (er) {
  216. /* ignore any errors */
  217. }
  218. return setFileContentsCache(path, contents);
  219. });
  220. // Support URLs relative to a directory, but be careful about a protocol prefix
  221. // in case we are in the browser (i.e. directories may start with "http://" or "file:///")
  222. function supportRelativeURL(file, url) {
  223. if(!file) return url;
  224. // given that this happens within error formatting codepath, probably best to
  225. // fallback instead of throwing if anything goes wrong
  226. try {
  227. // if should output a URL
  228. if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) {
  229. if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
  230. return new URL(url, file).toString();
  231. }
  232. if(path.isAbsolute(url)) {
  233. return new URL(pathToFileURL(url), file).toString();
  234. }
  235. // url is relative path or URL
  236. return new URL(url.replace(/\\/g, '/'), file).toString();
  237. }
  238. // if should output a path (unless URL is something like https://)
  239. if(path.isAbsolute(file)) {
  240. if(isFileUrl(url)) {
  241. return fileURLToPath(url);
  242. }
  243. if(isSchemeRelativeUrl(url)) {
  244. return fileURLToPath(new URL(url, 'file://'));
  245. }
  246. if(isAbsoluteUrl(url)) {
  247. // url is a non-file URL
  248. // Go with the URL
  249. return url;
  250. }
  251. if(path.isAbsolute(url)) {
  252. // Normalize at all? decodeURI or normalize slashes?
  253. return path.normalize(url);
  254. }
  255. // url is relative path or URL
  256. return path.join(file, '..', decodeURI(url));
  257. }
  258. // If we get here, file is relative.
  259. // Shouldn't happen since node identifies modules with absolute paths or URLs.
  260. // But we can take a stab at returning something meaningful anyway.
  261. if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
  262. return url;
  263. }
  264. return path.join(file, '..', url);
  265. } catch(e) {
  266. return url;
  267. }
  268. }
  269. // Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path
  270. function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) {
  271. try {
  272. if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) {
  273. if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl;
  274. if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString();
  275. } else if(path.isAbsolute(matchStyleOf)) {
  276. if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) {
  277. return fileURLToPath(new URL(pathOrUrl, 'file://'));
  278. }
  279. }
  280. return pathOrUrl;
  281. } catch(e) {
  282. return pathOrUrl;
  283. }
  284. }
  285. function retrieveSourceMapURL(source) {
  286. var fileData;
  287. if (isInBrowser()) {
  288. try {
  289. var xhr = new XMLHttpRequest();
  290. xhr.open('GET', source, false);
  291. xhr.send(null);
  292. fileData = xhr.readyState === 4 ? xhr.responseText : null;
  293. // Support providing a sourceMappingURL via the SourceMap header
  294. var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
  295. xhr.getResponseHeader("X-SourceMap");
  296. if (sourceMapHeader) {
  297. return sourceMapHeader;
  298. }
  299. } catch (e) {
  300. }
  301. }
  302. // Get the URL of the source map
  303. fileData = retrieveFile(tryFileURLToPath(source));
  304. var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
  305. // Keep executing the search to find the *last* sourceMappingURL to avoid
  306. // picking up sourceMappingURLs from comments, strings, etc.
  307. var lastMatch, match;
  308. while (match = re.exec(fileData)) lastMatch = match;
  309. if (!lastMatch) return null;
  310. return lastMatch[1];
  311. };
  312. // Can be overridden by the retrieveSourceMap option to install. Takes a
  313. // generated source filename; returns a {map, optional url} object, or null if
  314. // there is no source map. The map field may be either a string or the parsed
  315. // JSON object (ie, it must be a valid argument to the SourceMapConsumer
  316. // constructor).
  317. /** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */
  318. var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers);
  319. sharedData.internalRetrieveMapHandlers.push(function(source) {
  320. var sourceMappingURL = retrieveSourceMapURL(source);
  321. if (!sourceMappingURL) return null;
  322. // Read the contents of the source map
  323. var sourceMapData;
  324. if (reSourceMap.test(sourceMappingURL)) {
  325. // Support source map URL as a data url
  326. var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
  327. sourceMapData = Buffer.from(rawData, "base64").toString();
  328. sourceMappingURL = source;
  329. } else {
  330. // Support source map URLs relative to the source URL
  331. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  332. sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL));
  333. }
  334. if (!sourceMapData) {
  335. return null;
  336. }
  337. return {
  338. url: sourceMappingURL,
  339. map: sourceMapData
  340. };
  341. });
  342. function mapSourcePosition(position) {
  343. var sourceMap = getSourceMapCache(position.source);
  344. if (!sourceMap) {
  345. // Call the (overrideable) retrieveSourceMap function to get the source map.
  346. var urlAndMap = retrieveSourceMap(position.source);
  347. if (urlAndMap) {
  348. sourceMap = setSourceMapCache(position.source, {
  349. url: urlAndMap.url,
  350. map: new AnyMap(urlAndMap.map, urlAndMap.url)
  351. });
  352. // Overwrite trace-mapping's resolutions, because they do not handle
  353. // Windows paths the way we want.
  354. // TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping?
  355. sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s));
  356. // Load all sources stored inline with the source map into the file cache
  357. // to pretend like they are already loaded. They may not exist on disk.
  358. if (sourceMap.map.sourcesContent) {
  359. sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) {
  360. var contents = sourceMap.map.sourcesContent[i];
  361. if (contents) {
  362. setFileContentsCache(resolvedSource, contents);
  363. }
  364. });
  365. }
  366. } else {
  367. sourceMap = setSourceMapCache(position.source, {
  368. url: null,
  369. map: null
  370. });
  371. }
  372. }
  373. // Resolve the source URL relative to the URL of the source map
  374. if (sourceMap && sourceMap.map) {
  375. var originalPosition = originalPositionFor(sourceMap.map, position);
  376. // Only return the original position if a matching line was found. If no
  377. // matching line is found then we return position instead, which will cause
  378. // the stack trace to print the path and line for the compiled file. It is
  379. // better to give a precise location in the compiled file than a vague
  380. // location in the original file.
  381. if (originalPosition.source !== null) {
  382. // originalPosition.source has *already* been resolved against sourceMap.url
  383. // so is *already* as absolute as possible.
  384. // However, we want to ensure we output in same format as input: URL or native path
  385. originalPosition.source = matchStyleOfPathOrUrl(
  386. position.source, originalPosition.source);
  387. return originalPosition;
  388. }
  389. }
  390. return position;
  391. }
  392. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  393. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  394. function mapEvalOrigin(origin) {
  395. // Most eval() calls are in this format
  396. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  397. if (match) {
  398. var position = mapSourcePosition({
  399. source: match[2],
  400. line: +match[3],
  401. column: match[4] - 1
  402. });
  403. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  404. position.line + ':' + (position.column + 1) + ')';
  405. }
  406. // Parse nested eval() calls using recursion
  407. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  408. if (match) {
  409. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  410. }
  411. // Make sure we still return useful information if we didn't find anything
  412. return origin;
  413. }
  414. // This is copied almost verbatim from the V8 source code at
  415. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  416. // Update 2022-04-29:
  417. // https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179
  418. // https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804
  419. // https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750
  420. // The implementation of wrapCallSite() used to just forward to the actual source
  421. // code of CallSite.prototype.toString but unfortunately a new release of V8
  422. // did something to the prototype chain and broke the shim. The only fix I
  423. // could find was copy/paste.
  424. function CallSiteToString() {
  425. var fileName;
  426. var fileLocation = "";
  427. if (this.isNative()) {
  428. fileLocation = "native";
  429. } else {
  430. fileName = this.getScriptNameOrSourceURL();
  431. if (!fileName && this.isEval()) {
  432. fileLocation = this.getEvalOrigin();
  433. fileLocation += ", "; // Expecting source position to follow.
  434. }
  435. if (fileName) {
  436. fileLocation += fileName;
  437. } else {
  438. // Source code does not originate from a file and is not native, but we
  439. // can still get the source position inside the source string, e.g. in
  440. // an eval string.
  441. fileLocation += "<anonymous>";
  442. }
  443. var lineNumber = this.getLineNumber();
  444. if (lineNumber != null) {
  445. fileLocation += ":" + lineNumber;
  446. var columnNumber = this.getColumnNumber();
  447. if (columnNumber) {
  448. fileLocation += ":" + columnNumber;
  449. }
  450. }
  451. }
  452. var line = "";
  453. var isAsync = this.isAsync ? this.isAsync() : false;
  454. if(isAsync) {
  455. line += 'async ';
  456. var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false;
  457. var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false;
  458. if(isPromiseAny || isPromiseAll) {
  459. line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index ';
  460. var promiseIndex = this.getPromiseIndex();
  461. line += promiseIndex + ')';
  462. }
  463. }
  464. var functionName = this.getFunctionName();
  465. var addSuffix = true;
  466. var isConstructor = this.isConstructor();
  467. var isMethodCall = !(this.isToplevel() || isConstructor);
  468. if (isMethodCall) {
  469. var typeName = this.getTypeName();
  470. // Fixes shim to be backward compatable with Node v0 to v4
  471. if (typeName === "[object Object]") {
  472. typeName = "null";
  473. }
  474. var methodName = this.getMethodName();
  475. if (functionName) {
  476. if (typeName && functionName.indexOf(typeName) != 0) {
  477. line += typeName + ".";
  478. }
  479. line += functionName;
  480. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  481. line += " [as " + methodName + "]";
  482. }
  483. } else {
  484. line += typeName + "." + (methodName || "<anonymous>");
  485. }
  486. } else if (isConstructor) {
  487. line += "new " + (functionName || "<anonymous>");
  488. } else if (functionName) {
  489. line += functionName;
  490. } else {
  491. line += fileLocation;
  492. addSuffix = false;
  493. }
  494. if (addSuffix) {
  495. line += " (" + fileLocation + ")";
  496. }
  497. return line;
  498. }
  499. function cloneCallSite(frame) {
  500. var object = {};
  501. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  502. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  503. });
  504. object.toString = CallSiteToString;
  505. return object;
  506. }
  507. function wrapCallSite(frame, state) {
  508. // provides interface backward compatibility
  509. if (state === undefined) {
  510. state = { nextPosition: null, curPosition: null }
  511. }
  512. if(frame.isNative()) {
  513. state.curPosition = null;
  514. return frame;
  515. }
  516. // Most call sites will return the source file from getFileName(), but code
  517. // passed to eval() ending in "//# sourceURL=..." will return the source file
  518. // from getScriptNameOrSourceURL() instead
  519. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  520. if (source) {
  521. // v8 does not expose its internal isWasm, etc methods, so we do this instead.
  522. if(source.startsWith('wasm://')) {
  523. state.curPosition = null;
  524. return frame;
  525. }
  526. var line = frame.getLineNumber();
  527. var column = frame.getColumnNumber() - 1;
  528. // Fix position in Node where some (internal) code is prepended.
  529. // See https://github.com/evanw/node-source-map-support/issues/36
  530. // Header removed in node at ^10.16 || >=11.11.0
  531. // v11 is not an LTS candidate, we can just test the one version with it.
  532. // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
  533. var 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)/;
  534. var headerLength = noHeader.test(process.version) ? 0 : 62;
  535. if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
  536. column -= headerLength;
  537. }
  538. var position = mapSourcePosition({
  539. source: source,
  540. line: line,
  541. column: column
  542. });
  543. state.curPosition = position;
  544. frame = cloneCallSite(frame);
  545. var originalFunctionName = frame.getFunctionName;
  546. frame.getFunctionName = function() {
  547. if (state.nextPosition == null) {
  548. return originalFunctionName();
  549. }
  550. return state.nextPosition.name || originalFunctionName();
  551. };
  552. frame.getFileName = function() { return position.source; };
  553. frame.getLineNumber = function() { return position.line; };
  554. frame.getColumnNumber = function() { return position.column + 1; };
  555. frame.getScriptNameOrSourceURL = function() { return position.source; };
  556. return frame;
  557. }
  558. // Code called using eval() needs special handling
  559. var origin = frame.isEval() && frame.getEvalOrigin();
  560. if (origin) {
  561. origin = mapEvalOrigin(origin);
  562. frame = cloneCallSite(frame);
  563. frame.getEvalOrigin = function() { return origin; };
  564. return frame;
  565. }
  566. // If we get here then we were unable to change the source position
  567. return frame;
  568. }
  569. var kIsNodeError = undefined;
  570. try {
  571. // Get a deliberate ERR_INVALID_ARG_TYPE
  572. // TODO is there a better way to reliably get an instance of NodeError?
  573. path.resolve(123);
  574. } catch(e) {
  575. const symbols = Object.getOwnPropertySymbols(e);
  576. const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0});
  577. if(symbol) kIsNodeError = symbol;
  578. }
  579. const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err);
  580. /** @param {HookState} hookState */
  581. function createPrepareStackTrace(hookState) {
  582. return prepareStackTrace;
  583. // This function is part of the V8 stack trace API, for more info see:
  584. // https://v8.dev/docs/stack-trace-api
  585. function prepareStackTrace(error, stack) {
  586. if(!hookState.enabled) return hookState.originalValue.apply(this, arguments);
  587. if (sharedData.emptyCacheBetweenOperations) {
  588. clearCaches();
  589. }
  590. // node gives its own errors special treatment. Mimic that behavior
  591. // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128
  592. // https://github.com/nodejs/node/pull/39182
  593. var errorString;
  594. if (kIsNodeError) {
  595. if(kIsNodeError in error) {
  596. errorString = `${error.name} [${error.code}]: ${error.message}`;
  597. } else {
  598. errorString = ErrorPrototypeToString(error);
  599. }
  600. } else {
  601. var name = error.name || 'Error';
  602. var message = error.message || '';
  603. errorString = message ? name + ": " + message : name;
  604. }
  605. var state = { nextPosition: null, curPosition: null };
  606. var processedStack = [];
  607. for (var i = stack.length - 1; i >= 0; i--) {
  608. processedStack.push('\n at ' + wrapCallSite(stack[i], state));
  609. state.nextPosition = state.curPosition;
  610. }
  611. state.curPosition = state.nextPosition = null;
  612. return errorString + processedStack.reverse().join('');
  613. }
  614. }
  615. // Generate position and snippet of original source with pointer
  616. function getErrorSource(error) {
  617. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  618. if (match) {
  619. var source = match[1];
  620. var line = +match[2];
  621. var column = +match[3];
  622. // Support the inline sourceContents inside the source map
  623. var contents = getFileContentsCache(source);
  624. const sourceAsPath = tryFileURLToPath(source);
  625. // Support files on disk
  626. if (!contents && fs && fs.existsSync(sourceAsPath)) {
  627. try {
  628. contents = fs.readFileSync(sourceAsPath, 'utf8');
  629. } catch (er) {
  630. contents = '';
  631. }
  632. }
  633. // Format the line from the original source code like node does
  634. if (contents) {
  635. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  636. if (code) {
  637. return source + ':' + line + '\n' + code + '\n' +
  638. new Array(column).join(' ') + '^';
  639. }
  640. }
  641. }
  642. return null;
  643. }
  644. function printFatalErrorUponExit (error) {
  645. var source = getErrorSource(error);
  646. // Ensure error is printed synchronously and not truncated
  647. if (process.stderr._handle && process.stderr._handle.setBlocking) {
  648. process.stderr._handle.setBlocking(true);
  649. }
  650. if (source) {
  651. console.error(source);
  652. }
  653. // Matches node's behavior for colorized output
  654. console.error(
  655. util.inspect(error, {
  656. customInspect: false,
  657. colors: process.stderr.isTTY
  658. })
  659. );
  660. }
  661. function shimEmitUncaughtException () {
  662. const originalValue = process.emit;
  663. var hook = sharedData.processEmitHook = {
  664. enabled: true,
  665. originalValue,
  666. installedValue: undefined
  667. };
  668. var isTerminatingDueToFatalException = false;
  669. var fatalException;
  670. process.emit = sharedData.processEmitHook.installedValue = function (type) {
  671. const hadListeners = originalValue.apply(this, arguments);
  672. if(hook.enabled) {
  673. if (type === 'uncaughtException' && !hadListeners) {
  674. isTerminatingDueToFatalException = true;
  675. fatalException = arguments[1];
  676. process.exit(1);
  677. }
  678. if (type === 'exit' && isTerminatingDueToFatalException) {
  679. printFatalErrorUponExit(fatalException);
  680. }
  681. }
  682. return hadListeners;
  683. };
  684. }
  685. var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0);
  686. var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0);
  687. exports.wrapCallSite = wrapCallSite;
  688. exports.getErrorSource = getErrorSource;
  689. exports.mapSourcePosition = mapSourcePosition;
  690. exports.retrieveSourceMap = retrieveSourceMap;
  691. exports.install = function(options) {
  692. options = options || {};
  693. if (options.environment) {
  694. environment = options.environment;
  695. if (["node", "browser", "auto"].indexOf(environment) === -1) {
  696. throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
  697. }
  698. }
  699. // Use dynamicRequire to avoid including in browser bundles
  700. var Module = dynamicRequire(module, 'module');
  701. // Redirect subsequent imports of "source-map-support"
  702. // to this package
  703. const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options;
  704. if(redirectConflictingLibrary) {
  705. if (!sharedData.moduleResolveFilenameHook) {
  706. const originalValue = Module._resolveFilename;
  707. const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = {
  708. enabled: true,
  709. originalValue,
  710. installedValue: undefined,
  711. }
  712. Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) {
  713. if (moduleResolveFilenameHook.enabled) {
  714. // Match all source-map-support entrypoints: source-map-support, source-map-support/register
  715. let requestRedirect;
  716. if (request === 'source-map-support') {
  717. requestRedirect = './';
  718. } else if (request === 'source-map-support/register') {
  719. requestRedirect = './register';
  720. }
  721. if (requestRedirect !== undefined) {
  722. const newRequest = require.resolve(requestRedirect);
  723. for (const cb of sharedData.onConflictingLibraryRedirectArr) {
  724. cb(request, parent, isMain, options, newRequest);
  725. }
  726. request = newRequest;
  727. }
  728. }
  729. return originalValue.call(this, request, parent, isMain, options);
  730. }
  731. }
  732. if (onConflictingLibraryRedirect) {
  733. sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect);
  734. }
  735. }
  736. // Allow sources to be found by methods other than reading the files
  737. // directly from disk.
  738. if (options.retrieveFile) {
  739. if (options.overrideRetrieveFile) {
  740. sharedData.retrieveFileHandlers.length = 0;
  741. }
  742. sharedData.retrieveFileHandlers.unshift(options.retrieveFile);
  743. }
  744. // Allow source maps to be found by methods other than reading the files
  745. // directly from disk.
  746. if (options.retrieveSourceMap) {
  747. if (options.overrideRetrieveSourceMap) {
  748. sharedData.retrieveMapHandlers.length = 0;
  749. }
  750. sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap);
  751. }
  752. // Support runtime transpilers that include inline source maps
  753. if (options.hookRequire && !isInBrowser()) {
  754. var $compile = Module.prototype._compile;
  755. if (!$compile.__sourceMapSupport) {
  756. Module.prototype._compile = function(content, filename) {
  757. setFileContentsCache(filename, content);
  758. setSourceMapCache(filename, undefined);
  759. return $compile.call(this, content, filename);
  760. };
  761. Module.prototype._compile.__sourceMapSupport = true;
  762. }
  763. }
  764. // Configure options
  765. if (!sharedData.emptyCacheBetweenOperations) {
  766. sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  767. options.emptyCacheBetweenOperations : false;
  768. }
  769. // Install the error reformatter
  770. if (!sharedData.errorPrepareStackTraceHook) {
  771. const originalValue = Error.prepareStackTrace;
  772. sharedData.errorPrepareStackTraceHook = {
  773. enabled: true,
  774. originalValue,
  775. installedValue: undefined
  776. };
  777. Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook);
  778. }
  779. if (!sharedData.processEmitHook) {
  780. var installHandler = 'handleUncaughtExceptions' in options ?
  781. options.handleUncaughtExceptions : true;
  782. // Do not override 'uncaughtException' with our own handler in Node.js
  783. // Worker threads. Workers pass the error to the main thread as an event,
  784. // rather than printing something to stderr and exiting.
  785. try {
  786. // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
  787. var worker_threads = dynamicRequire(module, 'worker_threads');
  788. if (worker_threads.isMainThread === false) {
  789. installHandler = false;
  790. }
  791. } catch(e) {}
  792. // Provide the option to not install the uncaught exception handler. This is
  793. // to support other uncaught exception handlers (in test frameworks, for
  794. // example). If this handler is not installed and there are no other uncaught
  795. // exception handlers, uncaught exceptions will be caught by node's built-in
  796. // exception handler and the process will still be terminated. However, the
  797. // generated JavaScript code will be shown above the stack trace instead of
  798. // the original source code.
  799. if (installHandler && hasGlobalProcessEventEmitter()) {
  800. shimEmitUncaughtException();
  801. }
  802. }
  803. };
  804. exports.uninstall = function() {
  805. if(sharedData.processEmitHook) {
  806. // Disable behavior
  807. sharedData.processEmitHook.enabled = false;
  808. // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
  809. if(process.emit === sharedData.processEmitHook.installedValue) {
  810. process.emit = sharedData.processEmitHook.originalValue;
  811. }
  812. sharedData.processEmitHook = undefined;
  813. }
  814. if(sharedData.errorPrepareStackTraceHook) {
  815. // Disable behavior
  816. sharedData.errorPrepareStackTraceHook.enabled = false;
  817. // If possible or necessary, remove our hook function.
  818. // In vanilla environments, prepareStackTrace is `undefined`.
  819. // We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function.
  820. // If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both.
  821. if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') {
  822. Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue;
  823. }
  824. sharedData.errorPrepareStackTraceHook = undefined;
  825. }
  826. if (sharedData.moduleResolveFilenameHook) {
  827. // Disable behavior
  828. sharedData.moduleResolveFilenameHook.enabled = false;
  829. // If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
  830. var Module = dynamicRequire(module, 'module');
  831. if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) {
  832. Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue;
  833. }
  834. sharedData.moduleResolveFilenameHook = undefined;
  835. }
  836. sharedData.onConflictingLibraryRedirectArr.length = 0;
  837. }
  838. exports.resetRetrieveHandlers = function() {
  839. sharedData.retrieveFileHandlers.length = 0;
  840. sharedData.retrieveMapHandlers.length = 0;
  841. }