summaryrefslogtreecommitdiffstats
path: root/devtools/shared/platform/stack.js
blob: 65ff64409171a71914973243cf14ac241c24ceba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// A few wrappers for stack-manipulation.  This version of the module
// is used in chrome code.

"use strict";

/**
 * Return the Nth path from the stack excluding substr.
 *
 * @param {Number}
 *        n the Nth path from the stack to describe.
 * @param {String} substr
 *        A segment of the path that should be excluded.
 */
function getNthPathExcluding(n, substr) {
  let stack = Components.stack.formattedStack.split("\n");

  // Remove this method from the stack
  stack = stack.splice(1);

  stack = stack.map(line => {
    if (line.includes(" -> ")) {
      return line.split(" -> ")[1];
    }
    return line;
  });

  if (substr) {
    stack = stack.filter(line => {
      return line && !line.includes(substr);
    });
  }

  if (!stack[n]) {
    n = 0;
  }
  return stack[n] || "";
}

/**
 * Return a stack object that can be serialized and, when
 * deserialized, passed to callFunctionWithAsyncStack.
 */
function getStack() {
  return Components.stack.caller;
}

/**
 * Like Cu.callFunctionWithAsyncStack but handles the isWorker case
 * -- |Cu| isn't defined in workers.
 */
function callFunctionWithAsyncStack(callee, stack, id) {
  if (isWorker) {
    return callee();
  }
  return Cu.callFunctionWithAsyncStack(callee, stack, id);
}

exports.callFunctionWithAsyncStack = callFunctionWithAsyncStack;
exports.getNthPathExcluding = getNthPathExcluding;
exports.getStack = getStack;