• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31/**
32 * @fileoverview Utilities to debug JSPB based proto objects.
33 */
34
35goog.provide('jspb.debug');
36
37goog.require('goog.array');
38goog.require('goog.asserts');
39goog.require('goog.object');
40goog.require('jspb.Map');
41goog.require('jspb.Message');
42
43
44/**
45 * Turns a proto into a human readable object that can i.e. be written to the
46 * console: `console.log(jspb.debug.dump(myProto))`.
47 * This function makes a best effort and may not work in all cases. It will not
48 * work in obfuscated and or optimized code.
49 * Use this in environments where {@see jspb.Message.prototype.toObject} is
50 * not available for code size reasons.
51 * @param {jspb.Message} message A jspb.Message.
52 * @return {Object}
53 */
54jspb.debug.dump = function(message) {
55  if (!goog.DEBUG) {
56    return null;
57  }
58  goog.asserts.assert(message instanceof jspb.Message,
59      'jspb.Message instance expected');
60  /** @type {Object} */
61  var object = message;
62  goog.asserts.assert(object['getExtension'],
63      'Only unobfuscated and unoptimized compilation modes supported.');
64  return /** @type {Object} */ (jspb.debug.dump_(message));
65};
66
67
68/**
69 * Recursively introspects a message and the values its getters return to
70 * make a best effort in creating a human readable representation of the
71 * message.
72 * @param {?} thing A jspb.Message, Array or primitive type to dump.
73 * @return {*}
74 * @private
75 */
76jspb.debug.dump_ = function(thing) {
77  var type = goog.typeOf(thing);
78  var message = thing;  // Copy because we don't want type inference on thing.
79  if (type == 'number' || type == 'string' || type == 'boolean' ||
80      type == 'null' || type == 'undefined') {
81    return thing;
82  }
83  if (typeof Uint8Array !== 'undefined') {
84    // Will fail on IE9, where Uint8Array doesn't exist.
85    if (message instanceof Uint8Array) {
86      return thing;
87    }
88  }
89
90  if (type == 'array') {
91    goog.asserts.assertArray(thing);
92    return goog.array.map(thing, jspb.debug.dump_);
93  }
94
95  if (message instanceof jspb.Map) {
96    var mapObject = {};
97    var entries = message.entries();
98    for (var entry = entries.next(); !entry.done; entry = entries.next()) {
99      mapObject[entry.value[0]] = jspb.debug.dump_(entry.value[1]);
100    }
101    return mapObject;
102  }
103
104  goog.asserts.assert(message instanceof jspb.Message,
105      'Only messages expected: ' + thing);
106  var ctor = message.constructor;
107  var messageName = ctor.name || ctor.displayName;
108  var object = {
109    '$name': messageName
110  };
111  for (var name in ctor.prototype) {
112    var match = /^get([A-Z]\w*)/.exec(name);
113    if (match && name != 'getExtension' &&
114        name != 'getJsPbMessageId') {
115      var has = 'has' + match[1];
116      if (!thing[has] || thing[has]()) {
117        var val = thing[name]();
118        object[jspb.debug.formatFieldName_(match[1])] = jspb.debug.dump_(val);
119      }
120    }
121  }
122  if (COMPILED && thing['extensionObject_']) {
123    object['$extensions'] = 'Recursive dumping of extensions not supported ' +
124        'in compiled code. Switch to uncompiled or dump extension object ' +
125        'directly';
126    return object;
127  }
128  var extensionsObject;
129  for (var id in ctor['extensions']) {
130    if (/^\d+$/.test(id)) {
131      var ext = ctor['extensions'][id];
132      var extVal = thing.getExtension(ext);
133      var fieldName = goog.object.getKeys(ext.fieldName)[0];
134      if (extVal != null) {
135        if (!extensionsObject) {
136          extensionsObject = object['$extensions'] = {};
137        }
138        extensionsObject[jspb.debug.formatFieldName_(fieldName)] =
139            jspb.debug.dump_(extVal);
140      }
141    }
142  }
143  return object;
144};
145
146
147/**
148 * Formats a field name for output as camelCase.
149 *
150 * @param {string} name Name of the field.
151 * @return {string}
152 * @private
153 */
154jspb.debug.formatFieldName_ = function(name) {
155  // Name may be in TitleCase.
156  return name.replace(/^[A-Z]/, function(c) {
157    return c.toLowerCase();
158  });
159};
160