/
commandLineExposed.js
519 lines (448 loc) · 15.9 KB
/
commandLineExposed.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false, evil:true, forin: false*/
/*global Firebug:true, FBTrace:true, Components:true, define:true */
define([
"firebug/lib/wrapper",
"firebug/debugger/debuggerLib",
"firebug/lib/object",
"firebug/console/commandLineAPI",
"firebug/lib/locale",
],
function(Wrapper, DebuggerLib, Obj, CommandLineAPI, Locale) {
"use strict";
// ********************************************************************************************* //
// Constants
const Cu = Components.utils;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
var commandLineCache = new WeakMap();
// ********************************************************************************************* //
// Command Line APIs
// List of command line APIs
var commandNames = ["$", "$$", "$n", "$x", "cd", "clear", "inspect", "keys",
"values", "debug", "undebug", "monitor", "unmonitor", "traceCalls", "untraceCalls",
"traceAll", "untraceAll", "copy" /*, "memoryProfile", "memoryProfileEnd"*/];
// List of shortcuts for some console methods
var consoleShortcuts = ["dir", "dirxml", "table"];
// List of console variables.
var props = ["$0", "$1", "$2", "$3", "$4", "$p", "$_"];
// Registered commands, name -> config object.
var userCommands = Object.create(null);
// List of command line APIs to auto-complete, kept equal to the concatenation
// of the above minus trace*.
var completionList = [
"$", "$$", "$n", "$x", "cd", "clear", "inspect", "keys",
"values", "debug", "undebug", "monitor", "unmonitor", "copy"
].concat(consoleShortcuts, props);
var unsortedCompletionList = true;
// ********************************************************************************************* //
// Command Line Implementation
/**
* Returns a command line object (bundled with passed window through closure). The object
* provides all necessary APIs as described here:
* http://getfirebug.com/wiki/index.php/Command_Line_API
*
* @param {Object} context
* @param {Object} win
*/
function createFirebugCommandLine(context, win)
{
var contentView = Wrapper.getContentView(win);
if (!contentView)
{
if (FBTrace.DBG_COMMANDLINE || FBTrace.DBG_ERRORS)
FBTrace.sysout("createFirebugCommandLine ERROR no contentView " + context.getName());
return null;
}
// The debuggee global.
var dglobal = DebuggerLib.getDebuggeeGlobal(context, win);
var commandLine = commandLineCache.get(win.document);
if (commandLine)
return copyCommandLine(commandLine, dglobal);
// The commandLine object.
commandLine = dglobal.makeDebuggeeValue(Object.create(null));
var console = Firebug.ConsoleExposed.createFirebugConsole(context, win);
// The command line API instance.
var commands = CommandLineAPI.getCommandLineAPI(context);
// Helpers for command creation.
function createCommandHandler(command)
{
var wrappedCommand = function()
{
try
{
return command.apply(null, arguments);
}
catch(ex)
{
throw new Error(ex.message, ex.fileName, ex.lineNumber);
}
};
return dglobal.makeDebuggeeValue(wrappedCommand);
}
function createVariableHandler(handler)
{
var object = dglobal.makeDebuggeeValue({});
object.handle = function()
{
try
{
return handler(context);
}
catch(ex)
{
throw new Error(ex.message, ex.fileName, ex.lineNumber);
}
};
return object;
}
function createUserCommandHandler(config, name)
{
return function()
{
try
{
return config.handler.call(null, context, arguments);
}
catch (exc)
{
Firebug.Console.log(exc, context, "errorMessage");
if (FBTrace.DBG_ERRORS)
{
FBTrace.sysout("commandLine.api; EXCEPTION when executing " +
"a command: " + name + ", " + exc, exc);
}
}
};
}
// Define command line methods.
for (var commandName in commands)
{
var command = commands[commandName];
commandLine[commandName] = createCommandHandler(command);
}
// Register shortcut.
consoleShortcuts.forEach(function(name)
{
var command = console[name].bind(console);
commandLine[name] = createCommandHandler(command);
});
// Register user commands.
for (var name in userCommands)
{
var config = userCommands[name];
var command = createUserCommandHandler(config, name);
if (userCommands[name].getter)
commandLine[name] = createVariableHandler(command);
else
commandLine[name] = createCommandHandler(command);
}
commandLineCache.set(win.document, commandLine);
// Return a copy so the original one is preserved from changes.
return copyCommandLine(commandLine, dglobal);
}
// ********************************************************************************************* //
// User Commands
/**
* Registers a command.
*
* @param {string} name The name of the command
* @param {object} config The configuration. See some examples in commandLineHelp.js
* and commandLineInclude.js
*/
function registerCommand(name, config)
{
if (commandNames[name] || consoleShortcuts[name] || props[name] || userCommands[name])
{
if (FBTrace.DBG_ERRORS)
{
FBTrace.sysout("firebug.registerCommand; ERROR This command is already " +
"registered: " + name);
}
return false;
}
userCommands[name] = config;
completionList.push(name);
unsortedCompletionList = true;
return true;
}
/**
* Unregisters a command.
*
* @param {string} name The name of the command to unregister
*/
function unregisterCommand(name)
{
if (!userCommands[name])
{
if (FBTrace.DBG_ERRORS)
{
FBTrace.sysout("firebug.unregisterCommand; ERROR This command is not " +
"registered: " + name);
}
return false;
}
delete userCommands[name];
var ind = completionList.indexOf(name);
if (ind !== -1)
completionList.splice(ind, 1);
return true;
}
/**
* Returns true if the scope is specific of the commands bindings.
*
* @param {Scope} scope
* @param {Window} win The (wrapped) window
*
* @return {boolean}
*/
function isCommandLineScope(scope, win)
{
var commandLine = commandLineCache.get(win.document);
// This should never occur.
if (!commandLine && (FBTrace.DBG_COMMANDLINE || FBTrace.DBG_ERRORS))
FBTrace.sysout("CommandLineExposed.isCommandLineScope; could not get commandLine");
// Test whether the scope is an object and if its object contains commandLine functions
return scope.type === "object" && commandLine && commandLine.cd === scope.getVariable("cd");
}
/**
* Evaluates an expression in the thread of the webpage, so the Firebug UI is not frozen
* when the expression calls a function which will be paused.
*
*
* @param {object} context
* @param {Window} win
* @param {string} expr The expression (transformed if needed)
* @param {string} origExpr The expression as typed by the user
* @param {function} onSuccess The function to trigger in case of success
* @param {function} onError The function to trigger in case of exception
*
* @see CommandLine.evaluate
*/
function evaluateInPageContext(context, win)
{
executeInWindowContext(win, evaluate, arguments);
}
/**
* Evaluates an expression.
*
* @param {object} context
* @param {Window} win
* @param {string} expr The expression (transformed if needed)
* @param {string} origExpr The expression as typed by the user
* @param {function} onSuccess The function to trigger in case of success
* @param {function} onError The function to trigger in case of exception
*/
function evaluate(context, win, expr, origExpr, onSuccess, onError)
{
var result;
var contentView = Wrapper.getContentView(win);
var commandLine = createFirebugCommandLine(context, win);
var dglobal = DebuggerLib.getDebuggeeGlobal(context, win);
var resObj;
updateVars(commandLine, dglobal, context);
removeConflictingNames(commandLine, context, contentView);
resObj = dglobal.evalInGlobalWithBindings(expr, commandLine);
var unwrap = function(obj)
{
return DebuggerLib.unwrapDebuggeeValue(obj, contentView, dglobal);
};
// In case of abnormal termination, as if by the "slow script" dialog box,
// do not print anything in the console.
if (!resObj)
{
if (FBTrace.DBG_ERROR)
FBTrace.sysout("CommandLineExposed.evaluate; something went wrong when evaluating this"+
" expression: "+expr);
return;
}
if (resObj.hasOwnProperty("return"))
{
result = unwrap(resObj.return);
if (resObj.return && resObj.return.handle)
{
resObj.return.handle();
// Do not print anything in the console in case of getter commands.
return;
}
}
else if (resObj.hasOwnProperty("yield"))
{
result = unwrap(resObj.yield);
}
else if (resObj.hasOwnProperty("throw"))
{
// Change source and line number of exceptions from commandline code
// create new error since properties of nsIXPCException are not modifiable.
// Example of code raising nsIXPCException: `alert({toString: function(){ throw "blah"; }})`
// xxxFlorent: FIXME: we can't get the right stack trace with this example:
// function a(){
// throw new Error("error");
// }
// <ENTER>
// a();
// <ENTER>
var exc = unwrap(resObj.throw);
if (exc === null || exc === undefined)
return;
if (typeof exc !== "object")
{
exc = new Error(exc, null, null);
exc.fileName = exc.lineNumber = exc.stack = null;
}
var shouldModify = false, isXPCException = false;
var fileName = exc.filename || exc.fileName || "";
var isInternalError = fileName.lastIndexOf("chrome://", 0) === 0;
var lineNumber = null;
var stack = null;
var splitStack;
var isFileNameMasked = DebuggerLib.isFrameLocationEval(fileName);
if (isInternalError || isFileNameMasked)
{
shouldModify = true;
isXPCException = (exc.filename !== undefined);
// Lie and show the pre-transformed expression instead.
fileName = "data:,/* " + Locale.$STR("commandline.errorSourceHeader") + " */"+
encodeURIComponent("\n"+origExpr);
if (isInternalError && typeof exc.stack === "string")
{
splitStack = exc.stack.split("\n");
var correctionSucceeded = correctStackTrace(splitStack);
if (correctionSucceeded)
{
// correct the line number so we take into account the comment prepended above
lineNumber = findLineNumberInExceptionStack(splitStack) + 1;
// correct the first trace
splitStack.splice(0, 1, "@" + fileName + ":" + lineNumber);
stack = splitStack.join("\n");
}
else
shouldModify = false;
}
else
{
// correct the line number so we take into account the comment prepended above
lineNumber = exc.lineNumber + 1;
}
}
result = new Error();
if (shouldModify)
{
result.stack = stack;
result.source = origExpr;
result.message = exc.message;
result.lineNumber = lineNumber;
result.fileName = fileName;
// The error message can also contain post-transform details about the
// source, but it's harder to lie about. Make it prettier, at least.
if (typeof result.message === "string")
result.message = result.message.replace(/__fb_scopedVars\(/g, "<get closure>(");
if (!isXPCException)
result.name = exc.name;
}
else
{
Obj.getPropertyNames(exc).forEach(function(prop)
{
result[prop] = exc[prop];
});
result.stack = exc.stack;
result.source = exc.source;
}
executeInWindowContext(window, onError, [result, context]);
return;
}
executeInWindowContext(window, onSuccess, [result, context]);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Helpers (not accessible from web content)
function copyCommandLine(commandLine, dglobal)
{
var copy = dglobal.makeDebuggeeValue(Object.create(null));
for (var name in commandLine)
copy[name] = commandLine[name];
return copy;
}
function findLineNumberInExceptionStack(splitStack)
{
var m = splitStack[0].match(/:(\d+)$/);
return m !== null ? +m[1] : null;
}
function correctStackTrace(splitStack)
{
var filename = Components.stack.filename;
// remove the frames over the evaluated expression
for (var i = 0; i < splitStack.length-1 &&
splitStack[i+1].indexOf(evaluate.name + "@" + filename, 0) === -1 ; i++);
if (i >= splitStack.length)
return false;
splitStack.splice(0, i);
return true;
}
function updateVars(commandLine, dglobal, context)
{
var htmlPanel = context.getPanel("html", true);
var vars = htmlPanel ? htmlPanel.getInspectorVars() : null;
for (var prop in vars)
commandLine[prop] = dglobal.makeDebuggeeValue(vars[prop]);
vars = Firebug.CommandLine.getAccessorVars(context);
for (var prop in vars)
commandLine[prop] = dglobal.makeDebuggeeValue(vars[prop]);
}
function removeConflictingNames(commandLine, context, contentView)
{
for (var name in commandLine)
{
// Note: we cannot trust contentView.hasOwnProperty, so we use the "in" operator.
if (name in contentView)
delete commandLine[name];
}
}
/**
* Executes a function in another window execution context.
*
* Useful when we have to pause some debuggee functions without freezing
* the Firebug UI.
*
* @param {Window} win The window having the thread in which we want to execute the function
* @param {function} func The function to execute
* @param {Array or Array-Like object} args The arguments to pass to the function
*/
function executeInWindowContext(win, func, args)
{
var listener = function()
{
win.document.removeEventListener("firebugCommandLine", listener);
func.apply(null, args);
};
win.document.addEventListener("firebugCommandLine", listener);
var event = document.createEvent("Events");
event.initEvent("firebugCommandLine", true, false);
win.document.dispatchEvent(event);
}
function getAutoCompletionList()
{
if (unsortedCompletionList)
{
unsortedCompletionList = false;
completionList.sort();
}
return completionList;
}
// ********************************************************************************************* //
// Registration
Firebug.CommandLineExposed =
{
createFirebugCommandLine: createFirebugCommandLine,
commands: commandNames,
consoleShortcuts: consoleShortcuts,
properties: props,
userCommands: userCommands,
registerCommand: registerCommand,
unregisterCommand: unregisterCommand,
isCommandLineScope: isCommandLineScope,
evaluate: evaluateInPageContext,
getAutoCompletionList: getAutoCompletionList,
};
return Firebug.CommandLineExposed;
// ********************************************************************************************* //
});