Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / src / protobuf_js_5_common.js
1 /**
2  * @license
3  * Copyright 2017 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 /**
20  * @module
21  * @private
22  */
23
24 'use strict';
25
26 var camelCase = require('lodash.camelcase');
27 var client = require('./client');
28 var common = require('./common');
29
30 /**
31  * Get a function that deserializes a specific type of protobuf.
32  * @param {function()} cls The constructor of the message type to deserialize
33  * @param {bool=} binaryAsBase64 Deserialize bytes fields as base64 strings
34  *     instead of Buffers. Defaults to false
35  * @param {bool=} longsAsStrings Deserialize long values as strings instead of
36  *     objects. Defaults to true
37  * @return {function(Buffer):cls} The deserialization function
38  */
39 exports.deserializeCls = function deserializeCls(cls, options) {
40   /**
41    * Deserialize a buffer to a message object
42    * @param {Buffer} arg_buf The buffer to deserialize
43    * @return {cls} The resulting object
44    */
45   return function deserialize(arg_buf) {
46     // Convert to a native object with binary fields as Buffers (first argument)
47     // and longs as strings (second argument)
48     return cls.decode(arg_buf).toRaw(options.binaryAsBase64,
49                                      options.longsAsStrings);
50   };
51 };
52
53 var deserializeCls = exports.deserializeCls;
54
55 /**
56  * Get a function that serializes objects to a buffer by protobuf class.
57  * @param {function()} Cls The constructor of the message type to serialize
58  * @return {function(Cls):Buffer} The serialization function
59  */
60 exports.serializeCls = function serializeCls(Cls) {
61   /**
62    * Serialize an object to a Buffer
63    * @param {Object} arg The object to serialize
64    * @return {Buffer} The serialized object
65    */
66   return function serialize(arg) {
67     return Buffer.from(new Cls(arg).encode().toBuffer());
68   };
69 };
70
71 var serializeCls = exports.serializeCls;
72
73 /**
74  * Get the fully qualified (dotted) name of a ProtoBuf.Reflect value.
75  * @param {ProtoBuf.Reflect.Namespace} value The value to get the name of
76  * @return {string} The fully qualified name of the value
77  */
78 exports.fullyQualifiedName = function fullyQualifiedName(value) {
79   if (value === null || value === undefined) {
80     return '';
81   }
82   var name = value.name;
83   var parent_name = fullyQualifiedName(value.parent);
84   if (parent_name !== '') {
85     name = parent_name + '.' + name;
86   }
87   return name;
88 };
89
90 var fullyQualifiedName = exports.fullyQualifiedName;
91
92 /**
93  * Return a map from method names to method attributes for the service.
94  * @param {ProtoBuf.Reflect.Service} service The service to get attributes for
95  * @param {Object=} options Options to apply to these attributes
96  * @return {Object} The attributes map
97  */
98 exports.getProtobufServiceAttrs = function getProtobufServiceAttrs(service,
99                                                                    options) {
100   var prefix = '/' + fullyQualifiedName(service) + '/';
101   var binaryAsBase64, longsAsStrings;
102   if (options) {
103     binaryAsBase64 = options.binaryAsBase64;
104     longsAsStrings = options.longsAsStrings;
105   }
106   /* This slightly awkward construction is used to make sure we only use
107      lodash@3.10.1-compatible functions. A previous version used
108      _.fromPairs, which would be cleaner, but was introduced in lodash
109      version 4 */
110   return common.zipObject(service.children.map(function(method) {
111     return camelCase(method.name);
112   }), service.children.map(function(method) {
113     return {
114       originalName: method.name,
115       path: prefix + method.name,
116       requestStream: method.requestStream,
117       responseStream: method.responseStream,
118       requestType: method.resolvedRequestType,
119       responseType: method.resolvedResponseType,
120       requestSerialize: serializeCls(method.resolvedRequestType.build()),
121       requestDeserialize: deserializeCls(method.resolvedRequestType.build(),
122                                          options),
123       responseSerialize: serializeCls(method.resolvedResponseType.build()),
124       responseDeserialize: deserializeCls(method.resolvedResponseType.build(),
125                                           options)
126     };
127   }));
128 };
129
130 var getProtobufServiceAttrs = exports.getProtobufServiceAttrs;
131
132 /**
133  * Load a gRPC object from an existing ProtoBuf.Reflect object.
134  * @param {ProtoBuf.Reflect.Namespace} value The ProtoBuf object to load.
135  * @param {Object=} options Options to apply to the loaded object
136  * @return {Object<string, *>} The resulting gRPC object
137  */
138 exports.loadObject = function loadObject(value, options) {
139   var result = {};
140   if (!value) {
141     return value;
142   }
143   if (value.hasOwnProperty('ns')) {
144     return loadObject(value.ns, options);
145   }
146   if (value.className === 'Namespace') {
147     Object.keys(value.children).forEach(key => {
148       const child = value.children[key];
149       result[child.name] = loadObject(child, options);
150     });
151     return result;
152   } else if (value.className === 'Service') {
153     return client.makeClientConstructor(getProtobufServiceAttrs(value, options),
154                                         options);
155   } else if (value.className === 'Message' || value.className === 'Enum') {
156     return value.build();
157   } else {
158     return value;
159   }
160 };
161
162 /**
163  * The primary purpose of this method is to distinguish between reflection
164  * objects from different versions of ProtoBuf.js. This is just a heuristic,
165  * checking for properties that are (currently) specific to this version of
166  * ProtoBuf.js
167  * @param {Object} obj The object to check
168  * @return {boolean} Whether the object appears to be a Protobuf.js 5
169  *   ReflectionObject
170  */
171 exports.isProbablyProtobufJs5 = function isProbablyProtobufJs5(obj) {
172   return Array.isArray(obj.children) && (typeof obj.build === 'function');
173 };