Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

debuggability.js 32KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. "use strict";
  2. module.exports = function(Promise, Context,
  3. enableAsyncHooks, disableAsyncHooks) {
  4. var async = Promise._async;
  5. var Warning = require("./errors").Warning;
  6. var util = require("./util");
  7. var es5 = require("./es5");
  8. var canAttachTrace = util.canAttachTrace;
  9. var unhandledRejectionHandled;
  10. var possiblyUnhandledRejection;
  11. var bluebirdFramePattern =
  12. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  13. var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
  14. var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
  15. var stackFramePattern = null;
  16. var formatStack = null;
  17. var indentStackFrames = false;
  18. var printWarning;
  19. var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
  20. (false ||
  21. util.env("BLUEBIRD_DEBUG") ||
  22. util.env("NODE_ENV") === "development"));
  23. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  24. (debugging || util.env("BLUEBIRD_WARNINGS")));
  25. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  26. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  27. var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
  28. (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
  29. var deferUnhandledRejectionCheck;
  30. (function() {
  31. var promises = [];
  32. function unhandledRejectionCheck() {
  33. for (var i = 0; i < promises.length; ++i) {
  34. promises[i]._notifyUnhandledRejection();
  35. }
  36. unhandledRejectionClear();
  37. }
  38. function unhandledRejectionClear() {
  39. promises.length = 0;
  40. }
  41. if (typeof document === "object" && document.createElement) {
  42. deferUnhandledRejectionCheck = (function() {
  43. var iframeSetTimeout;
  44. function checkIframe() {
  45. if (document.body) {
  46. var iframe = document.createElement("iframe");
  47. document.body.appendChild(iframe);
  48. if (iframe.contentWindow &&
  49. iframe.contentWindow.setTimeout) {
  50. iframeSetTimeout = iframe.contentWindow.setTimeout;
  51. }
  52. document.body.removeChild(iframe);
  53. }
  54. }
  55. checkIframe();
  56. return function(promise) {
  57. promises.push(promise);
  58. if (iframeSetTimeout) {
  59. iframeSetTimeout(unhandledRejectionCheck, 1);
  60. } else {
  61. checkIframe();
  62. }
  63. };
  64. })();
  65. } else {
  66. deferUnhandledRejectionCheck = function(promise) {
  67. promises.push(promise);
  68. setTimeout(unhandledRejectionCheck, 1);
  69. };
  70. }
  71. es5.defineProperty(Promise, "_unhandledRejectionCheck", {
  72. value: unhandledRejectionCheck
  73. });
  74. es5.defineProperty(Promise, "_unhandledRejectionClear", {
  75. value: unhandledRejectionClear
  76. });
  77. })();
  78. Promise.prototype.suppressUnhandledRejections = function() {
  79. var target = this._target();
  80. target._bitField = ((target._bitField & (~1048576)) |
  81. 524288);
  82. };
  83. Promise.prototype._ensurePossibleRejectionHandled = function () {
  84. if ((this._bitField & 524288) !== 0) return;
  85. this._setRejectionIsUnhandled();
  86. deferUnhandledRejectionCheck(this);
  87. };
  88. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  89. fireRejectionEvent("rejectionHandled",
  90. unhandledRejectionHandled, undefined, this);
  91. };
  92. Promise.prototype._setReturnedNonUndefined = function() {
  93. this._bitField = this._bitField | 268435456;
  94. };
  95. Promise.prototype._returnedNonUndefined = function() {
  96. return (this._bitField & 268435456) !== 0;
  97. };
  98. Promise.prototype._notifyUnhandledRejection = function () {
  99. if (this._isRejectionUnhandled()) {
  100. var reason = this._settledValue();
  101. this._setUnhandledRejectionIsNotified();
  102. fireRejectionEvent("unhandledRejection",
  103. possiblyUnhandledRejection, reason, this);
  104. }
  105. };
  106. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  107. this._bitField = this._bitField | 262144;
  108. };
  109. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  110. this._bitField = this._bitField & (~262144);
  111. };
  112. Promise.prototype._isUnhandledRejectionNotified = function () {
  113. return (this._bitField & 262144) > 0;
  114. };
  115. Promise.prototype._setRejectionIsUnhandled = function () {
  116. this._bitField = this._bitField | 1048576;
  117. };
  118. Promise.prototype._unsetRejectionIsUnhandled = function () {
  119. this._bitField = this._bitField & (~1048576);
  120. if (this._isUnhandledRejectionNotified()) {
  121. this._unsetUnhandledRejectionIsNotified();
  122. this._notifyUnhandledRejectionIsHandled();
  123. }
  124. };
  125. Promise.prototype._isRejectionUnhandled = function () {
  126. return (this._bitField & 1048576) > 0;
  127. };
  128. Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
  129. return warn(message, shouldUseOwnTrace, promise || this);
  130. };
  131. Promise.onPossiblyUnhandledRejection = function (fn) {
  132. var context = Promise._getContext();
  133. possiblyUnhandledRejection = util.contextBind(context, fn);
  134. };
  135. Promise.onUnhandledRejectionHandled = function (fn) {
  136. var context = Promise._getContext();
  137. unhandledRejectionHandled = util.contextBind(context, fn);
  138. };
  139. var disableLongStackTraces = function() {};
  140. Promise.longStackTraces = function () {
  141. if (async.haveItemsQueued() && !config.longStackTraces) {
  142. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  143. }
  144. if (!config.longStackTraces && longStackTracesIsSupported()) {
  145. var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
  146. var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
  147. var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
  148. config.longStackTraces = true;
  149. disableLongStackTraces = function() {
  150. if (async.haveItemsQueued() && !config.longStackTraces) {
  151. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  152. }
  153. Promise.prototype._captureStackTrace = Promise_captureStackTrace;
  154. Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
  155. Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
  156. Context.deactivateLongStackTraces();
  157. config.longStackTraces = false;
  158. };
  159. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  160. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  161. Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
  162. Context.activateLongStackTraces();
  163. }
  164. };
  165. Promise.hasLongStackTraces = function () {
  166. return config.longStackTraces && longStackTracesIsSupported();
  167. };
  168. var legacyHandlers = {
  169. unhandledrejection: {
  170. before: function() {
  171. var ret = util.global.onunhandledrejection;
  172. util.global.onunhandledrejection = null;
  173. return ret;
  174. },
  175. after: function(fn) {
  176. util.global.onunhandledrejection = fn;
  177. }
  178. },
  179. rejectionhandled: {
  180. before: function() {
  181. var ret = util.global.onrejectionhandled;
  182. util.global.onrejectionhandled = null;
  183. return ret;
  184. },
  185. after: function(fn) {
  186. util.global.onrejectionhandled = fn;
  187. }
  188. }
  189. };
  190. var fireDomEvent = (function() {
  191. var dispatch = function(legacy, e) {
  192. if (legacy) {
  193. var fn;
  194. try {
  195. fn = legacy.before();
  196. return !util.global.dispatchEvent(e);
  197. } finally {
  198. legacy.after(fn);
  199. }
  200. } else {
  201. return !util.global.dispatchEvent(e);
  202. }
  203. };
  204. try {
  205. if (typeof CustomEvent === "function") {
  206. var event = new CustomEvent("CustomEvent");
  207. util.global.dispatchEvent(event);
  208. return function(name, event) {
  209. name = name.toLowerCase();
  210. var eventData = {
  211. detail: event,
  212. cancelable: true
  213. };
  214. var domEvent = new CustomEvent(name, eventData);
  215. es5.defineProperty(
  216. domEvent, "promise", {value: event.promise});
  217. es5.defineProperty(
  218. domEvent, "reason", {value: event.reason});
  219. return dispatch(legacyHandlers[name], domEvent);
  220. };
  221. } else if (typeof Event === "function") {
  222. var event = new Event("CustomEvent");
  223. util.global.dispatchEvent(event);
  224. return function(name, event) {
  225. name = name.toLowerCase();
  226. var domEvent = new Event(name, {
  227. cancelable: true
  228. });
  229. domEvent.detail = event;
  230. es5.defineProperty(domEvent, "promise", {value: event.promise});
  231. es5.defineProperty(domEvent, "reason", {value: event.reason});
  232. return dispatch(legacyHandlers[name], domEvent);
  233. };
  234. } else {
  235. var event = document.createEvent("CustomEvent");
  236. event.initCustomEvent("testingtheevent", false, true, {});
  237. util.global.dispatchEvent(event);
  238. return function(name, event) {
  239. name = name.toLowerCase();
  240. var domEvent = document.createEvent("CustomEvent");
  241. domEvent.initCustomEvent(name, false, true,
  242. event);
  243. return dispatch(legacyHandlers[name], domEvent);
  244. };
  245. }
  246. } catch (e) {}
  247. return function() {
  248. return false;
  249. };
  250. })();
  251. var fireGlobalEvent = (function() {
  252. if (util.isNode) {
  253. return function() {
  254. return process.emit.apply(process, arguments);
  255. };
  256. } else {
  257. if (!util.global) {
  258. return function() {
  259. return false;
  260. };
  261. }
  262. return function(name) {
  263. var methodName = "on" + name.toLowerCase();
  264. var method = util.global[methodName];
  265. if (!method) return false;
  266. method.apply(util.global, [].slice.call(arguments, 1));
  267. return true;
  268. };
  269. }
  270. })();
  271. function generatePromiseLifecycleEventObject(name, promise) {
  272. return {promise: promise};
  273. }
  274. var eventToObjectGenerator = {
  275. promiseCreated: generatePromiseLifecycleEventObject,
  276. promiseFulfilled: generatePromiseLifecycleEventObject,
  277. promiseRejected: generatePromiseLifecycleEventObject,
  278. promiseResolved: generatePromiseLifecycleEventObject,
  279. promiseCancelled: generatePromiseLifecycleEventObject,
  280. promiseChained: function(name, promise, child) {
  281. return {promise: promise, child: child};
  282. },
  283. warning: function(name, warning) {
  284. return {warning: warning};
  285. },
  286. unhandledRejection: function (name, reason, promise) {
  287. return {reason: reason, promise: promise};
  288. },
  289. rejectionHandled: generatePromiseLifecycleEventObject
  290. };
  291. var activeFireEvent = function (name) {
  292. var globalEventFired = false;
  293. try {
  294. globalEventFired = fireGlobalEvent.apply(null, arguments);
  295. } catch (e) {
  296. async.throwLater(e);
  297. globalEventFired = true;
  298. }
  299. var domEventFired = false;
  300. try {
  301. domEventFired = fireDomEvent(name,
  302. eventToObjectGenerator[name].apply(null, arguments));
  303. } catch (e) {
  304. async.throwLater(e);
  305. domEventFired = true;
  306. }
  307. return domEventFired || globalEventFired;
  308. };
  309. Promise.config = function(opts) {
  310. opts = Object(opts);
  311. if ("longStackTraces" in opts) {
  312. if (opts.longStackTraces) {
  313. Promise.longStackTraces();
  314. } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
  315. disableLongStackTraces();
  316. }
  317. }
  318. if ("warnings" in opts) {
  319. var warningsOption = opts.warnings;
  320. config.warnings = !!warningsOption;
  321. wForgottenReturn = config.warnings;
  322. if (util.isObject(warningsOption)) {
  323. if ("wForgottenReturn" in warningsOption) {
  324. wForgottenReturn = !!warningsOption.wForgottenReturn;
  325. }
  326. }
  327. }
  328. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  329. if (async.haveItemsQueued()) {
  330. throw new Error(
  331. "cannot enable cancellation after promises are in use");
  332. }
  333. Promise.prototype._clearCancellationData =
  334. cancellationClearCancellationData;
  335. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  336. Promise.prototype._onCancel = cancellationOnCancel;
  337. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  338. Promise.prototype._attachCancellationCallback =
  339. cancellationAttachCancellationCallback;
  340. Promise.prototype._execute = cancellationExecute;
  341. propagateFromFunction = cancellationPropagateFrom;
  342. config.cancellation = true;
  343. }
  344. if ("monitoring" in opts) {
  345. if (opts.monitoring && !config.monitoring) {
  346. config.monitoring = true;
  347. Promise.prototype._fireEvent = activeFireEvent;
  348. } else if (!opts.monitoring && config.monitoring) {
  349. config.monitoring = false;
  350. Promise.prototype._fireEvent = defaultFireEvent;
  351. }
  352. }
  353. if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
  354. var prev = config.asyncHooks;
  355. var cur = !!opts.asyncHooks;
  356. if (prev !== cur) {
  357. config.asyncHooks = cur;
  358. if (cur) {
  359. enableAsyncHooks();
  360. } else {
  361. disableAsyncHooks();
  362. }
  363. }
  364. }
  365. return Promise;
  366. };
  367. function defaultFireEvent() { return false; }
  368. Promise.prototype._fireEvent = defaultFireEvent;
  369. Promise.prototype._execute = function(executor, resolve, reject) {
  370. try {
  371. executor(resolve, reject);
  372. } catch (e) {
  373. return e;
  374. }
  375. };
  376. Promise.prototype._onCancel = function () {};
  377. Promise.prototype._setOnCancel = function (handler) { ; };
  378. Promise.prototype._attachCancellationCallback = function(onCancel) {
  379. ;
  380. };
  381. Promise.prototype._captureStackTrace = function () {};
  382. Promise.prototype._attachExtraTrace = function () {};
  383. Promise.prototype._dereferenceTrace = function () {};
  384. Promise.prototype._clearCancellationData = function() {};
  385. Promise.prototype._propagateFrom = function (parent, flags) {
  386. ;
  387. ;
  388. };
  389. function cancellationExecute(executor, resolve, reject) {
  390. var promise = this;
  391. try {
  392. executor(resolve, reject, function(onCancel) {
  393. if (typeof onCancel !== "function") {
  394. throw new TypeError("onCancel must be a function, got: " +
  395. util.toString(onCancel));
  396. }
  397. promise._attachCancellationCallback(onCancel);
  398. });
  399. } catch (e) {
  400. return e;
  401. }
  402. }
  403. function cancellationAttachCancellationCallback(onCancel) {
  404. if (!this._isCancellable()) return this;
  405. var previousOnCancel = this._onCancel();
  406. if (previousOnCancel !== undefined) {
  407. if (util.isArray(previousOnCancel)) {
  408. previousOnCancel.push(onCancel);
  409. } else {
  410. this._setOnCancel([previousOnCancel, onCancel]);
  411. }
  412. } else {
  413. this._setOnCancel(onCancel);
  414. }
  415. }
  416. function cancellationOnCancel() {
  417. return this._onCancelField;
  418. }
  419. function cancellationSetOnCancel(onCancel) {
  420. this._onCancelField = onCancel;
  421. }
  422. function cancellationClearCancellationData() {
  423. this._cancellationParent = undefined;
  424. this._onCancelField = undefined;
  425. }
  426. function cancellationPropagateFrom(parent, flags) {
  427. if ((flags & 1) !== 0) {
  428. this._cancellationParent = parent;
  429. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  430. if (branchesRemainingToCancel === undefined) {
  431. branchesRemainingToCancel = 0;
  432. }
  433. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  434. }
  435. if ((flags & 2) !== 0 && parent._isBound()) {
  436. this._setBoundTo(parent._boundTo);
  437. }
  438. }
  439. function bindingPropagateFrom(parent, flags) {
  440. if ((flags & 2) !== 0 && parent._isBound()) {
  441. this._setBoundTo(parent._boundTo);
  442. }
  443. }
  444. var propagateFromFunction = bindingPropagateFrom;
  445. function boundValueFunction() {
  446. var ret = this._boundTo;
  447. if (ret !== undefined) {
  448. if (ret instanceof Promise) {
  449. if (ret.isFulfilled()) {
  450. return ret.value();
  451. } else {
  452. return undefined;
  453. }
  454. }
  455. }
  456. return ret;
  457. }
  458. function longStackTracesCaptureStackTrace() {
  459. this._trace = new CapturedTrace(this._peekContext());
  460. }
  461. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  462. if (canAttachTrace(error)) {
  463. var trace = this._trace;
  464. if (trace !== undefined) {
  465. if (ignoreSelf) trace = trace._parent;
  466. }
  467. if (trace !== undefined) {
  468. trace.attachExtraTrace(error);
  469. } else if (!error.__stackCleaned__) {
  470. var parsed = parseStackAndMessage(error);
  471. util.notEnumerableProp(error, "stack",
  472. parsed.message + "\n" + parsed.stack.join("\n"));
  473. util.notEnumerableProp(error, "__stackCleaned__", true);
  474. }
  475. }
  476. }
  477. function longStackTracesDereferenceTrace() {
  478. this._trace = undefined;
  479. }
  480. function checkForgottenReturns(returnValue, promiseCreated, name, promise,
  481. parent) {
  482. if (returnValue === undefined && promiseCreated !== null &&
  483. wForgottenReturn) {
  484. if (parent !== undefined && parent._returnedNonUndefined()) return;
  485. if ((promise._bitField & 65535) === 0) return;
  486. if (name) name = name + " ";
  487. var handlerLine = "";
  488. var creatorLine = "";
  489. if (promiseCreated._trace) {
  490. var traceLines = promiseCreated._trace.stack.split("\n");
  491. var stack = cleanStack(traceLines);
  492. for (var i = stack.length - 1; i >= 0; --i) {
  493. var line = stack[i];
  494. if (!nodeFramePattern.test(line)) {
  495. var lineMatches = line.match(parseLinePattern);
  496. if (lineMatches) {
  497. handlerLine = "at " + lineMatches[1] +
  498. ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
  499. }
  500. break;
  501. }
  502. }
  503. if (stack.length > 0) {
  504. var firstUserLine = stack[0];
  505. for (var i = 0; i < traceLines.length; ++i) {
  506. if (traceLines[i] === firstUserLine) {
  507. if (i > 0) {
  508. creatorLine = "\n" + traceLines[i - 1];
  509. }
  510. break;
  511. }
  512. }
  513. }
  514. }
  515. var msg = "a promise was created in a " + name +
  516. "handler " + handlerLine + "but was not returned from it, " +
  517. "see http://goo.gl/rRqMUw" +
  518. creatorLine;
  519. promise._warn(msg, true, promiseCreated);
  520. }
  521. }
  522. function deprecated(name, replacement) {
  523. var message = name +
  524. " is deprecated and will be removed in a future version.";
  525. if (replacement) message += " Use " + replacement + " instead.";
  526. return warn(message);
  527. }
  528. function warn(message, shouldUseOwnTrace, promise) {
  529. if (!config.warnings) return;
  530. var warning = new Warning(message);
  531. var ctx;
  532. if (shouldUseOwnTrace) {
  533. promise._attachExtraTrace(warning);
  534. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  535. ctx.attachExtraTrace(warning);
  536. } else {
  537. var parsed = parseStackAndMessage(warning);
  538. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  539. }
  540. if (!activeFireEvent("warning", warning)) {
  541. formatAndLogError(warning, "", true);
  542. }
  543. }
  544. function reconstructStack(message, stacks) {
  545. for (var i = 0; i < stacks.length - 1; ++i) {
  546. stacks[i].push("From previous event:");
  547. stacks[i] = stacks[i].join("\n");
  548. }
  549. if (i < stacks.length) {
  550. stacks[i] = stacks[i].join("\n");
  551. }
  552. return message + "\n" + stacks.join("\n");
  553. }
  554. function removeDuplicateOrEmptyJumps(stacks) {
  555. for (var i = 0; i < stacks.length; ++i) {
  556. if (stacks[i].length === 0 ||
  557. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  558. stacks.splice(i, 1);
  559. i--;
  560. }
  561. }
  562. }
  563. function removeCommonRoots(stacks) {
  564. var current = stacks[0];
  565. for (var i = 1; i < stacks.length; ++i) {
  566. var prev = stacks[i];
  567. var currentLastIndex = current.length - 1;
  568. var currentLastLine = current[currentLastIndex];
  569. var commonRootMeetPoint = -1;
  570. for (var j = prev.length - 1; j >= 0; --j) {
  571. if (prev[j] === currentLastLine) {
  572. commonRootMeetPoint = j;
  573. break;
  574. }
  575. }
  576. for (var j = commonRootMeetPoint; j >= 0; --j) {
  577. var line = prev[j];
  578. if (current[currentLastIndex] === line) {
  579. current.pop();
  580. currentLastIndex--;
  581. } else {
  582. break;
  583. }
  584. }
  585. current = prev;
  586. }
  587. }
  588. function cleanStack(stack) {
  589. var ret = [];
  590. for (var i = 0; i < stack.length; ++i) {
  591. var line = stack[i];
  592. var isTraceLine = " (No stack trace)" === line ||
  593. stackFramePattern.test(line);
  594. var isInternalFrame = isTraceLine && shouldIgnore(line);
  595. if (isTraceLine && !isInternalFrame) {
  596. if (indentStackFrames && line.charAt(0) !== " ") {
  597. line = " " + line;
  598. }
  599. ret.push(line);
  600. }
  601. }
  602. return ret;
  603. }
  604. function stackFramesAsArray(error) {
  605. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  606. for (var i = 0; i < stack.length; ++i) {
  607. var line = stack[i];
  608. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  609. break;
  610. }
  611. }
  612. if (i > 0 && error.name != "SyntaxError") {
  613. stack = stack.slice(i);
  614. }
  615. return stack;
  616. }
  617. function parseStackAndMessage(error) {
  618. var stack = error.stack;
  619. var message = error.toString();
  620. stack = typeof stack === "string" && stack.length > 0
  621. ? stackFramesAsArray(error) : [" (No stack trace)"];
  622. return {
  623. message: message,
  624. stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
  625. };
  626. }
  627. function formatAndLogError(error, title, isSoft) {
  628. if (typeof console !== "undefined") {
  629. var message;
  630. if (util.isObject(error)) {
  631. var stack = error.stack;
  632. message = title + formatStack(stack, error);
  633. } else {
  634. message = title + String(error);
  635. }
  636. if (typeof printWarning === "function") {
  637. printWarning(message, isSoft);
  638. } else if (typeof console.log === "function" ||
  639. typeof console.log === "object") {
  640. console.log(message);
  641. }
  642. }
  643. }
  644. function fireRejectionEvent(name, localHandler, reason, promise) {
  645. var localEventFired = false;
  646. try {
  647. if (typeof localHandler === "function") {
  648. localEventFired = true;
  649. if (name === "rejectionHandled") {
  650. localHandler(promise);
  651. } else {
  652. localHandler(reason, promise);
  653. }
  654. }
  655. } catch (e) {
  656. async.throwLater(e);
  657. }
  658. if (name === "unhandledRejection") {
  659. if (!activeFireEvent(name, reason, promise) && !localEventFired) {
  660. formatAndLogError(reason, "Unhandled rejection ");
  661. }
  662. } else {
  663. activeFireEvent(name, promise);
  664. }
  665. }
  666. function formatNonError(obj) {
  667. var str;
  668. if (typeof obj === "function") {
  669. str = "[function " +
  670. (obj.name || "anonymous") +
  671. "]";
  672. } else {
  673. str = obj && typeof obj.toString === "function"
  674. ? obj.toString() : util.toString(obj);
  675. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  676. if (ruselessToString.test(str)) {
  677. try {
  678. var newStr = JSON.stringify(obj);
  679. str = newStr;
  680. }
  681. catch(e) {
  682. }
  683. }
  684. if (str.length === 0) {
  685. str = "(empty array)";
  686. }
  687. }
  688. return ("(<" + snip(str) + ">, no stack trace)");
  689. }
  690. function snip(str) {
  691. var maxChars = 41;
  692. if (str.length < maxChars) {
  693. return str;
  694. }
  695. return str.substr(0, maxChars - 3) + "...";
  696. }
  697. function longStackTracesIsSupported() {
  698. return typeof captureStackTrace === "function";
  699. }
  700. var shouldIgnore = function() { return false; };
  701. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  702. function parseLineInfo(line) {
  703. var matches = line.match(parseLineInfoRegex);
  704. if (matches) {
  705. return {
  706. fileName: matches[1],
  707. line: parseInt(matches[2], 10)
  708. };
  709. }
  710. }
  711. function setBounds(firstLineError, lastLineError) {
  712. if (!longStackTracesIsSupported()) return;
  713. var firstStackLines = (firstLineError.stack || "").split("\n");
  714. var lastStackLines = (lastLineError.stack || "").split("\n");
  715. var firstIndex = -1;
  716. var lastIndex = -1;
  717. var firstFileName;
  718. var lastFileName;
  719. for (var i = 0; i < firstStackLines.length; ++i) {
  720. var result = parseLineInfo(firstStackLines[i]);
  721. if (result) {
  722. firstFileName = result.fileName;
  723. firstIndex = result.line;
  724. break;
  725. }
  726. }
  727. for (var i = 0; i < lastStackLines.length; ++i) {
  728. var result = parseLineInfo(lastStackLines[i]);
  729. if (result) {
  730. lastFileName = result.fileName;
  731. lastIndex = result.line;
  732. break;
  733. }
  734. }
  735. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  736. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  737. return;
  738. }
  739. shouldIgnore = function(line) {
  740. if (bluebirdFramePattern.test(line)) return true;
  741. var info = parseLineInfo(line);
  742. if (info) {
  743. if (info.fileName === firstFileName &&
  744. (firstIndex <= info.line && info.line <= lastIndex)) {
  745. return true;
  746. }
  747. }
  748. return false;
  749. };
  750. }
  751. function CapturedTrace(parent) {
  752. this._parent = parent;
  753. this._promisesCreated = 0;
  754. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  755. captureStackTrace(this, CapturedTrace);
  756. if (length > 32) this.uncycle();
  757. }
  758. util.inherits(CapturedTrace, Error);
  759. Context.CapturedTrace = CapturedTrace;
  760. CapturedTrace.prototype.uncycle = function() {
  761. var length = this._length;
  762. if (length < 2) return;
  763. var nodes = [];
  764. var stackToIndex = {};
  765. for (var i = 0, node = this; node !== undefined; ++i) {
  766. nodes.push(node);
  767. node = node._parent;
  768. }
  769. length = this._length = i;
  770. for (var i = length - 1; i >= 0; --i) {
  771. var stack = nodes[i].stack;
  772. if (stackToIndex[stack] === undefined) {
  773. stackToIndex[stack] = i;
  774. }
  775. }
  776. for (var i = 0; i < length; ++i) {
  777. var currentStack = nodes[i].stack;
  778. var index = stackToIndex[currentStack];
  779. if (index !== undefined && index !== i) {
  780. if (index > 0) {
  781. nodes[index - 1]._parent = undefined;
  782. nodes[index - 1]._length = 1;
  783. }
  784. nodes[i]._parent = undefined;
  785. nodes[i]._length = 1;
  786. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  787. if (index < length - 1) {
  788. cycleEdgeNode._parent = nodes[index + 1];
  789. cycleEdgeNode._parent.uncycle();
  790. cycleEdgeNode._length =
  791. cycleEdgeNode._parent._length + 1;
  792. } else {
  793. cycleEdgeNode._parent = undefined;
  794. cycleEdgeNode._length = 1;
  795. }
  796. var currentChildLength = cycleEdgeNode._length + 1;
  797. for (var j = i - 2; j >= 0; --j) {
  798. nodes[j]._length = currentChildLength;
  799. currentChildLength++;
  800. }
  801. return;
  802. }
  803. }
  804. };
  805. CapturedTrace.prototype.attachExtraTrace = function(error) {
  806. if (error.__stackCleaned__) return;
  807. this.uncycle();
  808. var parsed = parseStackAndMessage(error);
  809. var message = parsed.message;
  810. var stacks = [parsed.stack];
  811. var trace = this;
  812. while (trace !== undefined) {
  813. stacks.push(cleanStack(trace.stack.split("\n")));
  814. trace = trace._parent;
  815. }
  816. removeCommonRoots(stacks);
  817. removeDuplicateOrEmptyJumps(stacks);
  818. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  819. util.notEnumerableProp(error, "__stackCleaned__", true);
  820. };
  821. var captureStackTrace = (function stackDetection() {
  822. var v8stackFramePattern = /^\s*at\s*/;
  823. var v8stackFormatter = function(stack, error) {
  824. if (typeof stack === "string") return stack;
  825. if (error.name !== undefined &&
  826. error.message !== undefined) {
  827. return error.toString();
  828. }
  829. return formatNonError(error);
  830. };
  831. if (typeof Error.stackTraceLimit === "number" &&
  832. typeof Error.captureStackTrace === "function") {
  833. Error.stackTraceLimit += 6;
  834. stackFramePattern = v8stackFramePattern;
  835. formatStack = v8stackFormatter;
  836. var captureStackTrace = Error.captureStackTrace;
  837. shouldIgnore = function(line) {
  838. return bluebirdFramePattern.test(line);
  839. };
  840. return function(receiver, ignoreUntil) {
  841. Error.stackTraceLimit += 6;
  842. captureStackTrace(receiver, ignoreUntil);
  843. Error.stackTraceLimit -= 6;
  844. };
  845. }
  846. var err = new Error();
  847. if (typeof err.stack === "string" &&
  848. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  849. stackFramePattern = /@/;
  850. formatStack = v8stackFormatter;
  851. indentStackFrames = true;
  852. return function captureStackTrace(o) {
  853. o.stack = new Error().stack;
  854. };
  855. }
  856. var hasStackAfterThrow;
  857. try { throw new Error(); }
  858. catch(e) {
  859. hasStackAfterThrow = ("stack" in e);
  860. }
  861. if (!("stack" in err) && hasStackAfterThrow &&
  862. typeof Error.stackTraceLimit === "number") {
  863. stackFramePattern = v8stackFramePattern;
  864. formatStack = v8stackFormatter;
  865. return function captureStackTrace(o) {
  866. Error.stackTraceLimit += 6;
  867. try { throw new Error(); }
  868. catch(e) { o.stack = e.stack; }
  869. Error.stackTraceLimit -= 6;
  870. };
  871. }
  872. formatStack = function(stack, error) {
  873. if (typeof stack === "string") return stack;
  874. if ((typeof error === "object" ||
  875. typeof error === "function") &&
  876. error.name !== undefined &&
  877. error.message !== undefined) {
  878. return error.toString();
  879. }
  880. return formatNonError(error);
  881. };
  882. return null;
  883. })([]);
  884. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  885. printWarning = function (message) {
  886. console.warn(message);
  887. };
  888. if (util.isNode && process.stderr.isTTY) {
  889. printWarning = function(message, isSoft) {
  890. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  891. console.warn(color + message + "\u001b[0m\n");
  892. };
  893. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  894. printWarning = function(message, isSoft) {
  895. console.warn("%c" + message,
  896. isSoft ? "color: darkorange" : "color: red");
  897. };
  898. }
  899. }
  900. var config = {
  901. warnings: warnings,
  902. longStackTraces: false,
  903. cancellation: false,
  904. monitoring: false,
  905. asyncHooks: false
  906. };
  907. if (longStackTraces) Promise.longStackTraces();
  908. return {
  909. asyncHooks: function() {
  910. return config.asyncHooks;
  911. },
  912. longStackTraces: function() {
  913. return config.longStackTraces;
  914. },
  915. warnings: function() {
  916. return config.warnings;
  917. },
  918. cancellation: function() {
  919. return config.cancellation;
  920. },
  921. monitoring: function() {
  922. return config.monitoring;
  923. },
  924. propagateFromFunction: function() {
  925. return propagateFromFunction;
  926. },
  927. boundValueFunction: function() {
  928. return boundValueFunction;
  929. },
  930. checkForgottenReturns: checkForgottenReturns,
  931. setBounds: setBounds,
  932. warn: warn,
  933. deprecated: deprecated,
  934. CapturedTrace: CapturedTrace,
  935. fireDomEvent: fireDomEvent,
  936. fireGlobalEvent: fireGlobalEvent
  937. };
  938. };