stack.js (1610B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 // A few wrappers for stack-manipulation. This version of the module 6 // is used in chrome code. 7 8 "use strict"; 9 10 /** 11 * Return the Nth path from the stack excluding substr. 12 * 13 * @param {number} 14 * n the Nth path from the stack to describe. 15 * @param {string} substr 16 * A segment of the path that should be excluded. 17 */ 18 function getNthPathExcluding(n, substr) { 19 let stack = Components.stack.formattedStack.split("\n"); 20 21 // Remove this method from the stack 22 stack = stack.splice(1); 23 24 stack = stack.map(line => { 25 if (line.includes(" -> ")) { 26 return line.split(" -> ")[1]; 27 } 28 return line; 29 }); 30 31 if (substr) { 32 stack = stack.filter(line => { 33 return line && !line.includes(substr); 34 }); 35 } 36 37 if (!stack[n]) { 38 n = 0; 39 } 40 return stack[n] || ""; 41 } 42 43 /** 44 * Return a stack object that can be serialized and, when 45 * deserialized, passed to callFunctionWithAsyncStack. 46 */ 47 function getStack() { 48 return Components.stack.caller; 49 } 50 51 /** 52 * Like Cu.callFunctionWithAsyncStack but handles the isWorker case 53 * -- |Cu| isn't defined in workers. 54 */ 55 function callFunctionWithAsyncStack(callee, stack, id) { 56 if (isWorker) { 57 return callee(); 58 } 59 return Cu.callFunctionWithAsyncStack(callee, stack, id); 60 } 61 62 exports.callFunctionWithAsyncStack = callFunctionWithAsyncStack; 63 exports.getNthPathExcluding = getNthPathExcluding; 64 exports.getStack = getStack;