summaryrefslogtreecommitdiffstats
path: root/devtools/client/webconsole/actions/input.js
blob: f93d4013465a53a50ac38f9f3d2451a1ca7c5726 (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
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
/* 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/. */

"use strict";

const {
  Utils: WebConsoleUtils,
} = require("resource://devtools/client/webconsole/utils.js");
const {
  EVALUATE_EXPRESSION,
  SET_TERMINAL_INPUT,
  SET_TERMINAL_EAGER_RESULT,
  EDITOR_PRETTY_PRINT,
  HELP_URL,
} = require("resource://devtools/client/webconsole/constants.js");
const {
  getAllPrefs,
} = require("resource://devtools/client/webconsole/selectors/prefs.js");
const ResourceCommand = require("resource://devtools/shared/commands/resource/resource-command.js");
const l10n = require("resource://devtools/client/webconsole/utils/l10n.js");

loader.lazyServiceGetter(
  this,
  "clipboardHelper",
  "@mozilla.org/widget/clipboardhelper;1",
  "nsIClipboardHelper"
);
loader.lazyRequireGetter(
  this,
  "messagesActions",
  "resource://devtools/client/webconsole/actions/messages.js"
);
loader.lazyRequireGetter(
  this,
  "historyActions",
  "resource://devtools/client/webconsole/actions/history.js"
);
loader.lazyRequireGetter(
  this,
  "ConsoleCommand",
  "resource://devtools/client/webconsole/types.js",
  true
);
loader.lazyRequireGetter(
  this,
  "netmonitorBlockingActions",
  "resource://devtools/client/netmonitor/src/actions/request-blocking.js"
);

loader.lazyRequireGetter(
  this,
  ["saveScreenshot", "captureAndSaveScreenshot"],
  "resource://devtools/client/shared/screenshot.js",
  true
);
loader.lazyRequireGetter(
  this,
  "createSimpleTableMessage",
  "resource://devtools/client/webconsole/utils/messages.js",
  true
);
loader.lazyRequireGetter(
  this,
  "getSelectedTarget",
  "resource://devtools/shared/commands/target/selectors/targets.js",
  true
);

async function getMappedExpression(hud, expression) {
  let mapResult;
  try {
    mapResult = await hud.getMappedExpression(expression);
  } catch (e) {
    console.warn("Error when calling getMappedExpression", e);
  }

  let mapped = null;
  if (mapResult) {
    ({ expression, mapped } = mapResult);
  }
  return { expression, mapped };
}

function evaluateExpression(expression, from = "input") {
  return async ({ dispatch, webConsoleUI, hud, commands }) => {
    if (!expression) {
      expression = hud.getInputSelection() || hud.getInputValue();
    }
    if (!expression) {
      return null;
    }

    // We use the messages action as it's doing additional transformation on the message.
    const { messages } = dispatch(
      messagesActions.messagesAdd([
        new ConsoleCommand({
          messageText: expression,
          timeStamp: Date.now(),
        }),
      ])
    );
    const [consoleCommandMessage] = messages;

    dispatch({
      type: EVALUATE_EXPRESSION,
      expression,
      from,
    });

    WebConsoleUtils.usageCount++;

    let mapped;
    ({ expression, mapped } = await getMappedExpression(hud, expression));

    // Even if the evaluation fails,
    // we still need to pass the error response to onExpressionEvaluated.
    const onSettled = res => res;

    const response = await commands.scriptCommand
      .execute(expression, {
        frameActor: hud.getSelectedFrameActorID(),
        selectedNodeActor: webConsoleUI.getSelectedNodeActorID(),
        selectedTargetFront: getSelectedTarget(
          webConsoleUI.hud.commands.targetCommand.store.getState()
        ),
        mapped,
        // Allow breakpoints to be triggerred and the evaluated source to be shown in debugger UI
        disableBreaks: false,
      })
      .then(onSettled, onSettled);

    const serverConsoleCommandTimestamp = response.startTime;

    // In case of remote debugging, it might happen that the debuggee page does not have
    // the exact same clock time as the client. This could cause some ordering issues
    // where the result message is displayed *before* the expression that lead to it.
    if (
      serverConsoleCommandTimestamp &&
      consoleCommandMessage.timeStamp > serverConsoleCommandTimestamp
    ) {
      // If we're in such case, we remove the original command message, and add it again,
      // with the timestamp coming from the server.
      dispatch(messagesActions.messageRemove(consoleCommandMessage.id));
      dispatch(
        messagesActions.messagesAdd([
          new ConsoleCommand({
            messageText: expression,
            timeStamp: serverConsoleCommandTimestamp,
          }),
        ])
      );
    }

    return dispatch(onExpressionEvaluated(response));
  };
}

/**
 * The JavaScript evaluation response handler.
 *
 * @private
 * @param {Object} response
 *        The message received from the server.
 */
function onExpressionEvaluated(response) {
  return async ({ dispatch, webConsoleUI }) => {
    if (response.error) {
      console.error(`Evaluation error`, response.error, ": ", response.message);
      return;
    }

    // If the evaluation was a top-level await expression that was rejected, there will
    // be an uncaught exception reported, so we don't need to do anything.
    if (response.topLevelAwaitRejected === true) {
      return;
    }

    if (!response.helperResult) {
      webConsoleUI.wrapper.dispatchMessageAdd(response);
      return;
    }

    await dispatch(handleHelperResult(response));
  };
}

function handleHelperResult(response) {
  // eslint-disable-next-line complexity
  return async ({ dispatch, hud, toolbox, webConsoleUI, getState }) => {
    const { result, helperResult } = response;
    const helperHasRawOutput = !!helperResult?.rawOutput;

    if (helperResult?.type) {
      switch (helperResult.type) {
        case "exception":
          dispatch(
            messagesActions.messagesAdd([
              {
                message: {
                  level: "error",
                  arguments: [helperResult.message],
                  chromeContext: true,
                },
                resourceType: ResourceCommand.TYPES.CONSOLE_MESSAGE,
              },
            ])
          );
          break;
        case "clearOutput":
          dispatch(messagesActions.messagesClear());
          break;
        case "clearHistory":
          dispatch(historyActions.clearHistory());
          break;
        case "historyOutput":
          const history = getState().history.entries || [];
          const columns = new Map([
            ["_index", "(index)"],
            ["expression", "Expressions"],
          ]);
          dispatch(
            messagesActions.messagesAdd([
              {
                ...createSimpleTableMessage(
                  columns,
                  history.map((expression, index) => {
                    return { _index: index, expression };
                  })
                ),
              },
            ])
          );
          break;
        case "inspectObject": {
          const objectActor = helperResult.object;
          if (hud.toolbox && !helperResult.forceExpandInConsole) {
            hud.toolbox.inspectObjectActor(objectActor);
          } else {
            webConsoleUI.inspectObjectActor(objectActor);
          }
          break;
        }
        case "help":
          hud.openLink(HELP_URL);
          break;
        case "copyValueToClipboard":
          clipboardHelper.copyString(helperResult.value);
          dispatch(
            messagesActions.messagesAdd([
              {
                resourceType: ResourceCommand.TYPES.PLATFORM_MESSAGE,
                message: l10n.getStr(
                  "webconsole.message.commands.copyValueToClipboard"
                ),
              },
            ])
          );
          break;
        case "screenshotOutput":
          const { args, value } = helperResult;
          const targetFront =
            getSelectedTarget(hud.commands.targetCommand.store.getState()) ||
            hud.currentTarget;
          let screenshotMessages;

          // @backward-compat { version 87 } The screenshot-content actor isn't available
          // in older server.
          // With an old server, the console actor captures the screenshot when handling
          // the command, and send it to the client which only needs to save it to a file.
          // With a new server, the server simply acknowledges the command,
          // and the client will drive the whole screenshot process (capture and save).
          if (targetFront.hasActor("screenshotContent")) {
            screenshotMessages = await captureAndSaveScreenshot(
              targetFront,
              webConsoleUI.getPanelWindow(),
              args
            );
          } else {
            screenshotMessages = await saveScreenshot(
              webConsoleUI.getPanelWindow(),
              args,
              value
            );
          }

          if (screenshotMessages && screenshotMessages.length) {
            dispatch(
              messagesActions.messagesAdd(
                screenshotMessages.map(message => ({
                  message: {
                    level: message.level || "log",
                    arguments: [message.text],
                    chromeContext: true,
                  },
                  resourceType: ResourceCommand.TYPES.CONSOLE_MESSAGE,
                }))
              )
            );
          }
          break;
        case "blockURL":
          const blockURL = helperResult.args.url;
          // The console actor isn't able to block the request as the console actor runs in the content
          // process, while the request has to be blocked from the parent process.
          // Then, calling the Netmonitor action will only update the visual state of the Netmonitor,
          // but we also have to block the request via the NetworkParentActor.
          await hud.commands.networkCommand.blockRequestForUrl(blockURL);
          toolbox
            .getPanel("netmonitor")
            ?.panelWin.store.dispatch(
              netmonitorBlockingActions.addBlockedUrl(blockURL)
            );

          dispatch(
            messagesActions.messagesAdd([
              {
                resourceType: ResourceCommand.TYPES.PLATFORM_MESSAGE,
                message: l10n.getFormatStr(
                  "webconsole.message.commands.blockedURL",
                  [blockURL]
                ),
              },
            ])
          );
          break;
        case "unblockURL":
          const unblockURL = helperResult.args.url;
          await hud.commands.networkCommand.unblockRequestForUrl(unblockURL);
          toolbox
            .getPanel("netmonitor")
            ?.panelWin.store.dispatch(
              netmonitorBlockingActions.removeBlockedUrl(unblockURL)
            );

          dispatch(
            messagesActions.messagesAdd([
              {
                resourceType: ResourceCommand.TYPES.PLATFORM_MESSAGE,
                message: l10n.getFormatStr(
                  "webconsole.message.commands.unblockedURL",
                  [unblockURL]
                ),
              },
            ])
          );
          // early return as we already dispatched necessary messages.
          return;

        // Sent when using ":command --help or :command --usage"
        // to help discover command arguments.
        //
        // The remote runtime will tell us about the usage as it may
        // be different from the client one.
        case "usage":
          dispatch(
            messagesActions.messagesAdd([
              {
                resourceType: ResourceCommand.TYPES.PLATFORM_MESSAGE,
                message: helperResult.message,
              },
            ])
          );
          break;

        case "traceOutput":
          // Nothing in particular to do.
          // The JSTRACER_STATE resource will report the start/stop of the profiler.
          break;
      }
    }

    const hasErrorMessage =
      response.exceptionMessage ||
      (helperResult && helperResult.type === "error");

    // Hide undefined results coming from helper functions.
    const hasUndefinedResult =
      result && typeof result == "object" && result.type == "undefined";

    if (hasErrorMessage || helperHasRawOutput || !hasUndefinedResult) {
      dispatch(messagesActions.messagesAdd([response]));
    }
  };
}

function focusInput() {
  return ({ hud }) => {
    return hud.focusInput();
  };
}

function setInputValue(value) {
  return ({ hud }) => {
    return hud.setInputValue(value);
  };
}

/**
 * Request an eager evaluation from the server.
 *
 * @param {String} expression: The expression to evaluate.
 * @param {Boolean} force: When true, will request an eager evaluation again, even if
 *                         the expression is the same one than the one that was used in
 *                         the previous evaluation.
 */
function terminalInputChanged(expression, force = false) {
  return async ({ dispatch, webConsoleUI, hud, commands, getState }) => {
    const prefs = getAllPrefs(getState());
    if (!prefs.eagerEvaluation) {
      return null;
    }

    const { terminalInput = "" } = getState().history;

    // Only re-evaluate if the expression did change.
    if (
      (!terminalInput && !expression) ||
      (typeof terminalInput === "string" &&
        typeof expression === "string" &&
        expression.trim() === terminalInput.trim() &&
        !force)
    ) {
      return null;
    }

    dispatch({
      type: SET_TERMINAL_INPUT,
      expression: expression.trim(),
    });

    // There's no need to evaluate an empty string.
    if (!expression || !expression.trim()) {
      return dispatch({
        type: SET_TERMINAL_EAGER_RESULT,
        expression,
        result: null,
      });
    }

    let mapped;
    ({ expression, mapped } = await getMappedExpression(hud, expression));

    // We don't want to evaluate top-level await expressions (see Bug 1786805)
    if (mapped?.await) {
      return dispatch({
        type: SET_TERMINAL_EAGER_RESULT,
        expression,
        result: null,
      });
    }

    const response = await commands.scriptCommand.execute(expression, {
      frameActor: hud.getSelectedFrameActorID(),
      selectedNodeActor: webConsoleUI.getSelectedNodeActorID(),
      selectedTargetFront: getSelectedTarget(
        hud.commands.targetCommand.store.getState()
      ),
      mapped,
      eager: true,
    });

    return dispatch({
      type: SET_TERMINAL_EAGER_RESULT,
      result: getEagerEvaluationResult(response),
    });
  };
}

/**
 * Refresh the current eager evaluation by requesting a new eager evaluation.
 */
function updateInstantEvaluationResultForCurrentExpression() {
  return ({ getState, dispatch }) =>
    dispatch(terminalInputChanged(getState().history.terminalInput, true));
}

function getEagerEvaluationResult(response) {
  const result = response.exception || response.result;
  // Don't show syntax errors results to the user.
  if (result?.isSyntaxError || (result && result.type == "undefined")) {
    return null;
  }

  return result;
}

function prettyPrintEditor() {
  return {
    type: EDITOR_PRETTY_PRINT,
  };
}

module.exports = {
  evaluateExpression,
  focusInput,
  setInputValue,
  terminalInputChanged,
  updateInstantEvaluationResultForCurrentExpression,
  prettyPrintEditor,
};