summaryrefslogtreecommitdiff
path: root/devtools/shared/webconsole/client.js
blob: 4cc5deedf35e79b65167bb05763e3004e2e05d33 (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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* 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 DevToolsUtils = require("devtools/shared/DevToolsUtils");
const EventEmitter = require("devtools/shared/event-emitter");
const promise = require("promise");
const defer = require("devtools/shared/defer");
const {LongStringClient} = require("devtools/shared/client/main");

/**
 * A WebConsoleClient is used as a front end for the WebConsoleActor that is
 * created on the server, hiding implementation details.
 *
 * @param object debuggerClient
 *        The DebuggerClient instance we live for.
 * @param object response
 *        The response packet received from the "startListeners" request sent to
 *        the WebConsoleActor.
 */
function WebConsoleClient(debuggerClient, response) {
  this._actor = response.from;
  this._client = debuggerClient;
  this._longStrings = {};
  this.traits = response.traits || {};
  this.events = [];
  this._networkRequests = new Map();

  this.pendingEvaluationResults = new Map();
  this.onEvaluationResult = this.onEvaluationResult.bind(this);
  this.onNetworkEvent = this._onNetworkEvent.bind(this);
  this.onNetworkEventUpdate = this._onNetworkEventUpdate.bind(this);

  this._client.addListener("evaluationResult", this.onEvaluationResult);
  this._client.addListener("networkEvent", this.onNetworkEvent);
  this._client.addListener("networkEventUpdate", this.onNetworkEventUpdate);
  EventEmitter.decorate(this);
}

exports.WebConsoleClient = WebConsoleClient;

WebConsoleClient.prototype = {
  _longStrings: null,
  traits: null,

  /**
   * Holds the network requests currently displayed by the Web Console. Each key
   * represents the connection ID and the value is network request information.
   * @private
   * @type object
   */
  _networkRequests: null,

  getNetworkRequest(actorId) {
    return this._networkRequests.get(actorId);
  },

  hasNetworkRequest(actorId) {
    return this._networkRequests.has(actorId);
  },

  removeNetworkRequest(actorId) {
    this._networkRequests.delete(actorId);
  },

  getNetworkEvents() {
    return this._networkRequests.values();
  },

  get actor() {
    return this._actor;
  },

  /**
   * The "networkEvent" message type handler. We redirect any message to
   * the UI for displaying.
   *
   * @private
   * @param string type
   *        Message type.
   * @param object packet
   *        The message received from the server.
   */
  _onNetworkEvent: function (type, packet) {
    if (packet.from == this._actor) {
      let actor = packet.eventActor;
      let networkInfo = {
        _type: "NetworkEvent",
        timeStamp: actor.timeStamp,
        node: null,
        actor: actor.actor,
        discardRequestBody: true,
        discardResponseBody: true,
        startedDateTime: actor.startedDateTime,
        request: {
          url: actor.url,
          method: actor.method,
        },
        isXHR: actor.isXHR,
        cause: actor.cause,
        response: {},
        timings: {},
        // track the list of network event updates
        updates: [],
        private: actor.private,
        fromCache: actor.fromCache,
        fromServiceWorker: actor.fromServiceWorker
      };
      this._networkRequests.set(actor.actor, networkInfo);

      this.emit("networkEvent", networkInfo);
    }
  },

  /**
   * The "networkEventUpdate" message type handler. We redirect any message to
   * the UI for displaying.
   *
   * @private
   * @param string type
   *        Message type.
   * @param object packet
   *        The message received from the server.
   */
  _onNetworkEventUpdate: function (type, packet) {
    let networkInfo = this.getNetworkRequest(packet.from);
    if (!networkInfo) {
      return;
    }

    networkInfo.updates.push(packet.updateType);

    switch (packet.updateType) {
      case "requestHeaders":
        networkInfo.request.headersSize = packet.headersSize;
        break;
      case "requestPostData":
        networkInfo.discardRequestBody = packet.discardRequestBody;
        networkInfo.request.bodySize = packet.dataSize;
        break;
      case "responseStart":
        networkInfo.response.httpVersion = packet.response.httpVersion;
        networkInfo.response.status = packet.response.status;
        networkInfo.response.statusText = packet.response.statusText;
        networkInfo.response.headersSize = packet.response.headersSize;
        networkInfo.response.remoteAddress = packet.response.remoteAddress;
        networkInfo.response.remotePort = packet.response.remotePort;
        networkInfo.discardResponseBody = packet.response.discardResponseBody;
        break;
      case "responseContent":
        networkInfo.response.content = {
          mimeType: packet.mimeType,
        };
        networkInfo.response.bodySize = packet.contentSize;
        networkInfo.response.transferredSize = packet.transferredSize;
        networkInfo.discardResponseBody = packet.discardResponseBody;
        break;
      case "eventTimings":
        networkInfo.totalTime = packet.totalTime;
        break;
      case "securityInfo":
        networkInfo.securityInfo = packet.state;
        break;
    }

    this.emit("networkEventUpdate", {
      packet: packet,
      networkInfo
    });
  },

  /**
   * Retrieve the cached messages from the server.
   *
   * @see this.CACHED_MESSAGES
   * @param array types
   *        The array of message types you want from the server. See
   *        this.CACHED_MESSAGES for known types.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getCachedMessages: function (types, onResponse) {
    let packet = {
      to: this._actor,
      type: "getCachedMessages",
      messageTypes: types,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Inspect the properties of an object.
   *
   * @param string actor
   *        The WebConsoleObjectActor ID to send the request to.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  inspectObjectProperties: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "inspectProperties",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Evaluate a JavaScript expression.
   *
   * @param string string
   *        The code you want to evaluate.
   * @param function onResponse
   *        The function invoked when the response is received.
   * @param object [options={}]
   *        Options for evaluation:
   *
   *        - bindObjectActor: an ObjectActor ID. The OA holds a reference to
   *        a Debugger.Object that wraps a content object. This option allows
   *        you to bind |_self| to the D.O of the given OA, during string
   *        evaluation.
   *
   *        See: Debugger.Object.executeInGlobalWithBindings() for information
   *        about bindings.
   *
   *        Use case: the variable view needs to update objects and it does so
   *        by knowing the ObjectActor it inspects and binding |_self| to the
   *        D.O of the OA. As such, variable view sends strings like these for
   *        eval:
   *          _self["prop"] = value;
   *
   *        - frameActor: a FrameActor ID. The FA holds a reference to
   *        a Debugger.Frame. This option allows you to evaluate the string in
   *        the frame of the given FA.
   *
   *        - url: the url to evaluate the script as. Defaults to
   *        "debugger eval code".
   *
   *        - selectedNodeActor: the NodeActor ID of the current
   *        selection in the Inspector, if such a selection
   *        exists. This is used by helper functions that can
   *        reference the currently selected node in the Inspector,
   *        like $0.
   */
  evaluateJS: function (string, onResponse, options = {}) {
    let packet = {
      to: this._actor,
      type: "evaluateJS",
      text: string,
      bindObjectActor: options.bindObjectActor,
      frameActor: options.frameActor,
      url: options.url,
      selectedNodeActor: options.selectedNodeActor,
      selectedObjectActor: options.selectedObjectActor,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Evaluate a JavaScript expression asynchronously.
   * See evaluateJS for parameter and response information.
   */
  evaluateJSAsync: function (string, onResponse, options = {}) {
    // Pre-37 servers don't support async evaluation.
    if (!this.traits.evaluateJSAsync) {
      this.evaluateJS(string, onResponse, options);
      return;
    }

    let packet = {
      to: this._actor,
      type: "evaluateJSAsync",
      text: string,
      bindObjectActor: options.bindObjectActor,
      frameActor: options.frameActor,
      url: options.url,
      selectedNodeActor: options.selectedNodeActor,
      selectedObjectActor: options.selectedObjectActor,
    };

    this._client.request(packet, response => {
      // Null check this in case the client has been detached while waiting
      // for a response.
      if (this.pendingEvaluationResults) {
        this.pendingEvaluationResults.set(response.resultID, onResponse);
      }
    });
  },

  /**
   * Handler for the actors's unsolicited evaluationResult packet.
   */
  onEvaluationResult: function (notification, packet) {
    // The client on the main thread can receive notification packets from
    // multiple webconsole actors: the one on the main thread and the ones
    // on worker threads.  So make sure we should be handling this request.
    if (packet.from !== this._actor) {
      return;
    }

    // Find the associated callback based on this ID, and fire it.
    // In a sync evaluation, this would have already been called in
    // direct response to the client.request function.
    let onResponse = this.pendingEvaluationResults.get(packet.resultID);
    if (onResponse) {
      onResponse(packet);
      this.pendingEvaluationResults.delete(packet.resultID);
    } else {
      DevToolsUtils.reportException("onEvaluationResult",
        "No response handler for an evaluateJSAsync result (resultID: " +
                                    packet.resultID + ")");
    }
  },

  /**
   * Autocomplete a JavaScript expression.
   *
   * @param string string
   *        The code you want to autocomplete.
   * @param number cursor
   *        Cursor location inside the string. Index starts from 0.
   * @param function onResponse
   *        The function invoked when the response is received.
   * @param string frameActor
   *        The id of the frame actor that made the call.
   */
  autocomplete: function (string, cursor, onResponse, frameActor) {
    let packet = {
      to: this._actor,
      type: "autocomplete",
      text: string,
      cursor: cursor,
      frameActor: frameActor,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Clear the cache of messages (page errors and console API calls).
   */
  clearMessagesCache: function () {
    let packet = {
      to: this._actor,
      type: "clearMessagesCache",
    };
    this._client.request(packet);
  },

  /**
   * Get Web Console-related preferences on the server.
   *
   * @param array preferences
   *        An array with the preferences you want to retrieve.
   * @param function [onResponse]
   *        Optional function to invoke when the response is received.
   */
  getPreferences: function (preferences, onResponse) {
    let packet = {
      to: this._actor,
      type: "getPreferences",
      preferences: preferences,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Set Web Console-related preferences on the server.
   *
   * @param object preferences
   *        An object with the preferences you want to change.
   * @param function [onResponse]
   *        Optional function to invoke when the response is received.
   */
  setPreferences: function (preferences, onResponse) {
    let packet = {
      to: this._actor,
      type: "setPreferences",
      preferences: preferences,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the request headers from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getRequestHeaders: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getRequestHeaders",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the request cookies from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getRequestCookies: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getRequestCookies",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the request post data from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getRequestPostData: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getRequestPostData",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the response headers from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getResponseHeaders: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getResponseHeaders",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the response cookies from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getResponseCookies: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getResponseCookies",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the response content from the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getResponseContent: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getResponseContent",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the timing information for the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getEventTimings: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getEventTimings",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Retrieve the security information for the given NetworkEventActor.
   *
   * @param string actor
   *        The NetworkEventActor ID.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  getSecurityInfo: function (actor, onResponse) {
    let packet = {
      to: actor,
      type: "getSecurityInfo",
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Send a HTTP request with the given data.
   *
   * @param string data
   *        The details of the HTTP request.
   * @param function onResponse
   *        The function invoked when the response is received.
   */
  sendHTTPRequest: function (data, onResponse) {
    let packet = {
      to: this._actor,
      type: "sendHTTPRequest",
      request: data
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Start the given Web Console listeners.
   *
   * @see this.LISTENERS
   * @param array listeners
   *        Array of listeners you want to start. See this.LISTENERS for
   *        known listeners.
   * @param function onResponse
   *        Function to invoke when the server response is received.
   */
  startListeners: function (listeners, onResponse) {
    let packet = {
      to: this._actor,
      type: "startListeners",
      listeners: listeners,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Stop the given Web Console listeners.
   *
   * @see this.LISTENERS
   * @param array listeners
   *        Array of listeners you want to stop. See this.LISTENERS for
   *        known listeners.
   * @param function onResponse
   *        Function to invoke when the server response is received.
   */
  stopListeners: function (listeners, onResponse) {
    let packet = {
      to: this._actor,
      type: "stopListeners",
      listeners: listeners,
    };
    this._client.request(packet, onResponse);
  },

  /**
   * Return an instance of LongStringClient for the given long string grip.
   *
   * @param object grip
   *        The long string grip returned by the protocol.
   * @return object
   *         The LongStringClient for the given long string grip.
   */
  longString: function (grip) {
    if (grip.actor in this._longStrings) {
      return this._longStrings[grip.actor];
    }

    let client = new LongStringClient(this._client, grip);
    this._longStrings[grip.actor] = client;
    return client;
  },

  /**
   * Close the WebConsoleClient. This stops all the listeners on the server and
   * detaches from the console actor.
   *
   * @param function onResponse
   *        Function to invoke when the server response is received.
   */
  detach: function (onResponse) {
    this._client.removeListener("evaluationResult", this.onEvaluationResult);
    this._client.removeListener("networkEvent", this.onNetworkEvent);
    this._client.removeListener("networkEventUpdate",
                                this.onNetworkEventUpdate);
    this.stopListeners(null, onResponse);
    this._longStrings = null;
    this._client = null;
    this.pendingEvaluationResults.clear();
    this.pendingEvaluationResults = null;
    this.clearNetworkRequests();
    this._networkRequests = null;
  },

  clearNetworkRequests: function () {
    this._networkRequests.clear();
  },

  /**
   * Fetches the full text of a LongString.
   *
   * @param object | string stringGrip
   *        The long string grip containing the corresponding actor.
   *        If you pass in a plain string (by accident or because you're lazy),
   *        then a promise of the same string is simply returned.
   * @return object Promise
   *         A promise that is resolved when the full string contents
   *         are available, or rejected if something goes wrong.
   */
  getString: function (stringGrip) {
    // Make sure this is a long string.
    if (typeof stringGrip != "object" || stringGrip.type != "longString") {
      // Go home string, you're drunk.
      return promise.resolve(stringGrip);
    }

    // Fetch the long string only once.
    if (stringGrip._fullText) {
      return stringGrip._fullText.promise;
    }

    let deferred = stringGrip._fullText = defer();
    let { initial, length } = stringGrip;
    let longStringClient = this.longString(stringGrip);

    longStringClient.substring(initial.length, length, response => {
      if (response.error) {
        DevToolsUtils.reportException("getString",
            response.error + ": " + response.message);

        deferred.reject(response);
        return;
      }
      deferred.resolve(initial + response.substring);
    });

    return deferred.promise;
  }
};