GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8964 lines
268 KiB

2 months ago
  1. /*!
  2. * protobuf.js v6.11.0 (c) 2016, daniel wirtz
  3. * compiled thu, 29 apr 2021 02:20:44 utc
  4. * licensed under the bsd-3-clause license
  5. * see: https://github.com/dcodeio/protobuf.js for details
  6. */
  7. (function(undefined){"use strict";(function prelude(modules, cache, entries) {
  8. // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS
  9. // sources through a conflict-free require shim and is again wrapped within an iife that
  10. // provides a minification-friendly `undefined` var plus a global "use strict" directive
  11. // so that minification can remove the directives of each module.
  12. function $require(name) {
  13. var $module = cache[name];
  14. if (!$module)
  15. modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);
  16. return $module.exports;
  17. }
  18. var protobuf = $require(entries[0]);
  19. // Expose globally
  20. protobuf.util.global.protobuf = protobuf;
  21. // Be nice to AMD
  22. if (typeof define === "function" && define.amd)
  23. define(["long"], function(Long) {
  24. if (Long && Long.isLong) {
  25. protobuf.util.Long = Long;
  26. protobuf.configure();
  27. }
  28. return protobuf;
  29. });
  30. // Be nice to CommonJS
  31. if (typeof module === "object" && module && module.exports)
  32. module.exports = protobuf;
  33. })/* end of prelude */({1:[function(require,module,exports){
  34. "use strict";
  35. module.exports = asPromise;
  36. /**
  37. * Callback as used by {@link util.asPromise}.
  38. * @typedef asPromiseCallback
  39. * @type {function}
  40. * @param {Error|null} error Error, if any
  41. * @param {...*} params Additional arguments
  42. * @returns {undefined}
  43. */
  44. /**
  45. * Returns a promise from a node-style callback function.
  46. * @memberof util
  47. * @param {asPromiseCallback} fn Function to call
  48. * @param {*} ctx Function context
  49. * @param {...*} params Function arguments
  50. * @returns {Promise<*>} Promisified function
  51. */
  52. function asPromise(fn, ctx/*, varargs */) {
  53. var params = new Array(arguments.length - 1),
  54. offset = 0,
  55. index = 2,
  56. pending = true;
  57. while (index < arguments.length)
  58. params[offset++] = arguments[index++];
  59. return new Promise(function executor(resolve, reject) {
  60. params[offset] = function callback(err/*, varargs */) {
  61. if (pending) {
  62. pending = false;
  63. if (err)
  64. reject(err);
  65. else {
  66. var params = new Array(arguments.length - 1),
  67. offset = 0;
  68. while (offset < params.length)
  69. params[offset++] = arguments[offset];
  70. resolve.apply(null, params);
  71. }
  72. }
  73. };
  74. try {
  75. fn.apply(ctx || null, params);
  76. } catch (err) {
  77. if (pending) {
  78. pending = false;
  79. reject(err);
  80. }
  81. }
  82. });
  83. }
  84. },{}],2:[function(require,module,exports){
  85. "use strict";
  86. /**
  87. * A minimal base64 implementation for number arrays.
  88. * @memberof util
  89. * @namespace
  90. */
  91. var base64 = exports;
  92. /**
  93. * Calculates the byte length of a base64 encoded string.
  94. * @param {string} string Base64 encoded string
  95. * @returns {number} Byte length
  96. */
  97. base64.length = function length(string) {
  98. var p = string.length;
  99. if (!p)
  100. return 0;
  101. var n = 0;
  102. while (--p % 4 > 1 && string.charAt(p) === "=")
  103. ++n;
  104. return Math.ceil(string.length * 3) / 4 - n;
  105. };
  106. // Base64 encoding table
  107. var b64 = new Array(64);
  108. // Base64 decoding table
  109. var s64 = new Array(123);
  110. // 65..90, 97..122, 48..57, 43, 47
  111. for (var i = 0; i < 64;)
  112. s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
  113. /**
  114. * Encodes a buffer to a base64 encoded string.
  115. * @param {Uint8Array} buffer Source buffer
  116. * @param {number} start Source start
  117. * @param {number} end Source end
  118. * @returns {string} Base64 encoded string
  119. */
  120. base64.encode = function encode(buffer, start, end) {
  121. var parts = null,
  122. chunk = [];
  123. var i = 0, // output index
  124. j = 0, // goto index
  125. t; // temporary
  126. while (start < end) {
  127. var b = buffer[start++];
  128. switch (j) {
  129. case 0:
  130. chunk[i++] = b64[b >> 2];
  131. t = (b & 3) << 4;
  132. j = 1;
  133. break;
  134. case 1:
  135. chunk[i++] = b64[t | b >> 4];
  136. t = (b & 15) << 2;
  137. j = 2;
  138. break;
  139. case 2:
  140. chunk[i++] = b64[t | b >> 6];
  141. chunk[i++] = b64[b & 63];
  142. j = 0;
  143. break;
  144. }
  145. if (i > 8191) {
  146. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  147. i = 0;
  148. }
  149. }
  150. if (j) {
  151. chunk[i++] = b64[t];
  152. chunk[i++] = 61;
  153. if (j === 1)
  154. chunk[i++] = 61;
  155. }
  156. if (parts) {
  157. if (i)
  158. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  159. return parts.join("");
  160. }
  161. return String.fromCharCode.apply(String, chunk.slice(0, i));
  162. };
  163. var invalidEncoding = "invalid encoding";
  164. /**
  165. * Decodes a base64 encoded string to a buffer.
  166. * @param {string} string Source string
  167. * @param {Uint8Array} buffer Destination buffer
  168. * @param {number} offset Destination offset
  169. * @returns {number} Number of bytes written
  170. * @throws {Error} If encoding is invalid
  171. */
  172. base64.decode = function decode(string, buffer, offset) {
  173. var start = offset;
  174. var j = 0, // goto index
  175. t; // temporary
  176. for (var i = 0; i < string.length;) {
  177. var c = string.charCodeAt(i++);
  178. if (c === 61 && j > 1)
  179. break;
  180. if ((c = s64[c]) === undefined)
  181. throw Error(invalidEncoding);
  182. switch (j) {
  183. case 0:
  184. t = c;
  185. j = 1;
  186. break;
  187. case 1:
  188. buffer[offset++] = t << 2 | (c & 48) >> 4;
  189. t = c;
  190. j = 2;
  191. break;
  192. case 2:
  193. buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
  194. t = c;
  195. j = 3;
  196. break;
  197. case 3:
  198. buffer[offset++] = (t & 3) << 6 | c;
  199. j = 0;
  200. break;
  201. }
  202. }
  203. if (j === 1)
  204. throw Error(invalidEncoding);
  205. return offset - start;
  206. };
  207. /**
  208. * Tests if the specified string appears to be base64 encoded.
  209. * @param {string} string String to test
  210. * @returns {boolean} `true` if probably base64 encoded, otherwise false
  211. */
  212. base64.test = function test(string) {
  213. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
  214. };
  215. },{}],3:[function(require,module,exports){
  216. "use strict";
  217. module.exports = codegen;
  218. /**
  219. * Begins generating a function.
  220. * @memberof util
  221. * @param {string[]} functionParams Function parameter names
  222. * @param {string} [functionName] Function name if not anonymous
  223. * @returns {Codegen} Appender that appends code to the function's body
  224. */
  225. function codegen(functionParams, functionName) {
  226. /* istanbul ignore if */
  227. if (typeof functionParams === "string") {
  228. functionName = functionParams;
  229. functionParams = undefined;
  230. }
  231. var body = [];
  232. /**
  233. * Appends code to the function's body or finishes generation.
  234. * @typedef Codegen
  235. * @type {function}
  236. * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
  237. * @param {...*} [formatParams] Format parameters
  238. * @returns {Codegen|Function} Itself or the generated function if finished
  239. * @throws {Error} If format parameter counts do not match
  240. */
  241. function Codegen(formatStringOrScope) {
  242. // note that explicit array handling below makes this ~50% faster
  243. // finish the function
  244. if (typeof formatStringOrScope !== "string") {
  245. var source = toString();
  246. if (codegen.verbose)
  247. console.log("codegen: " + source); // eslint-disable-line no-console
  248. source = "return " + source;
  249. if (formatStringOrScope) {
  250. var scopeKeys = Object.keys(formatStringOrScope),
  251. scopeParams = new Array(scopeKeys.length + 1),
  252. scopeValues = new Array(scopeKeys.length),
  253. scopeOffset = 0;
  254. while (scopeOffset < scopeKeys.length) {
  255. scopeParams[scopeOffset] = scopeKeys[scopeOffset];
  256. scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
  257. }
  258. scopeParams[scopeOffset] = source;
  259. return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func
  260. }
  261. return Function(source)(); // eslint-disable-line no-new-func
  262. }
  263. // otherwise append to body
  264. var formatParams = new Array(arguments.length - 1),
  265. formatOffset = 0;
  266. while (formatOffset < formatParams.length)
  267. formatParams[formatOffset] = arguments[++formatOffset];
  268. formatOffset = 0;
  269. formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {
  270. var value = formatParams[formatOffset++];
  271. switch ($1) {
  272. case "d": case "f": return String(Number(value));
  273. case "i": return String(Math.floor(value));
  274. case "j": return JSON.stringify(value);
  275. case "s": return String(value);
  276. }
  277. return "%";
  278. });
  279. if (formatOffset !== formatParams.length)
  280. throw Error("parameter count mismatch");
  281. body.push(formatStringOrScope);
  282. return Codegen;
  283. }
  284. function toString(functionNameOverride) {
  285. return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";
  286. }
  287. Codegen.toString = toString;
  288. return Codegen;
  289. }
  290. /**
  291. * Begins generating a function.
  292. * @memberof util
  293. * @function codegen
  294. * @param {string} [functionName] Function name if not anonymous
  295. * @returns {Codegen} Appender that appends code to the function's body
  296. * @variation 2
  297. */
  298. /**
  299. * When set to `true`, codegen will log generated code to console. Useful for debugging.
  300. * @name util.codegen.verbose
  301. * @type {boolean}
  302. */
  303. codegen.verbose = false;
  304. },{}],4:[function(require,module,exports){
  305. "use strict";
  306. module.exports = EventEmitter;
  307. /**
  308. * Constructs a new event emitter instance.
  309. * @classdesc A minimal event emitter.
  310. * @memberof util
  311. * @constructor
  312. */
  313. function EventEmitter() {
  314. /**
  315. * Registered listeners.
  316. * @type {Object.<string,*>}
  317. * @private
  318. */
  319. this._listeners = {};
  320. }
  321. /**
  322. * Registers an event listener.
  323. * @param {string} evt Event name
  324. * @param {function} fn Listener
  325. * @param {*} [ctx] Listener context
  326. * @returns {util.EventEmitter} `this`
  327. */
  328. EventEmitter.prototype.on = function on(evt, fn, ctx) {
  329. (this._listeners[evt] || (this._listeners[evt] = [])).push({
  330. fn : fn,
  331. ctx : ctx || this
  332. });
  333. return this;
  334. };
  335. /**
  336. * Removes an event listener or any matching listeners if arguments are omitted.
  337. * @param {string} [evt] Event name. Removes all listeners if omitted.
  338. * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
  339. * @returns {util.EventEmitter} `this`
  340. */
  341. EventEmitter.prototype.off = function off(evt, fn) {
  342. if (evt === undefined)
  343. this._listeners = {};
  344. else {
  345. if (fn === undefined)
  346. this._listeners[evt] = [];
  347. else {
  348. var listeners = this._listeners[evt];
  349. for (var i = 0; i < listeners.length;)
  350. if (listeners[i].fn === fn)
  351. listeners.splice(i, 1);
  352. else
  353. ++i;
  354. }
  355. }
  356. return this;
  357. };
  358. /**
  359. * Emits an event by calling its listeners with the specified arguments.
  360. * @param {string} evt Event name
  361. * @param {...*} args Arguments
  362. * @returns {util.EventEmitter} `this`
  363. */
  364. EventEmitter.prototype.emit = function emit(evt) {
  365. var listeners = this._listeners[evt];
  366. if (listeners) {
  367. var args = [],
  368. i = 1;
  369. for (; i < arguments.length;)
  370. args.push(arguments[i++]);
  371. for (i = 0; i < listeners.length;)
  372. listeners[i].fn.apply(listeners[i++].ctx, args);
  373. }
  374. return this;
  375. };
  376. },{}],5:[function(require,module,exports){
  377. "use strict";
  378. module.exports = fetch;
  379. var asPromise = require(1),
  380. inquire = require(7);
  381. var fs = inquire("fs");
  382. /**
  383. * Node-style callback as used by {@link util.fetch}.
  384. * @typedef FetchCallback
  385. * @type {function}
  386. * @param {?Error} error Error, if any, otherwise `null`
  387. * @param {string} [contents] File contents, if there hasn't been an error
  388. * @returns {undefined}
  389. */
  390. /**
  391. * Options as used by {@link util.fetch}.
  392. * @typedef FetchOptions
  393. * @type {Object}
  394. * @property {boolean} [binary=false] Whether expecting a binary response
  395. * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest
  396. */
  397. /**
  398. * Fetches the contents of a file.
  399. * @memberof util
  400. * @param {string} filename File path or url
  401. * @param {FetchOptions} options Fetch options
  402. * @param {FetchCallback} callback Callback function
  403. * @returns {undefined}
  404. */
  405. function fetch(filename, options, callback) {
  406. if (typeof options === "function") {
  407. callback = options;
  408. options = {};
  409. } else if (!options)
  410. options = {};
  411. if (!callback)
  412. return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this
  413. // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.
  414. if (!options.xhr && fs && fs.readFile)
  415. return fs.readFile(filename, function fetchReadFileCallback(err, contents) {
  416. return err && typeof XMLHttpRequest !== "undefined"
  417. ? fetch.xhr(filename, options, callback)
  418. : err
  419. ? callback(err)
  420. : callback(null, options.binary ? contents : contents.toString("utf8"));
  421. });
  422. // use the XHR version otherwise.
  423. return fetch.xhr(filename, options, callback);
  424. }
  425. /**
  426. * Fetches the contents of a file.
  427. * @name util.fetch
  428. * @function
  429. * @param {string} path File path or url
  430. * @param {FetchCallback} callback Callback function
  431. * @returns {undefined}
  432. * @variation 2
  433. */
  434. /**
  435. * Fetches the contents of a file.
  436. * @name util.fetch
  437. * @function
  438. * @param {string} path File path or url
  439. * @param {FetchOptions} [options] Fetch options
  440. * @returns {Promise<string|Uint8Array>} Promise
  441. * @variation 3
  442. */
  443. /**/
  444. fetch.xhr = function fetch_xhr(filename, options, callback) {
  445. var xhr = new XMLHttpRequest();
  446. xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {
  447. if (xhr.readyState !== 4)
  448. return undefined;
  449. // local cors security errors return status 0 / empty string, too. afaik this cannot be
  450. // reliably distinguished from an actually empty file for security reasons. feel free
  451. // to send a pull request if you are aware of a solution.
  452. if (xhr.status !== 0 && xhr.status !== 200)
  453. return callback(Error("status " + xhr.status));
  454. // if binary data is expected, make sure that some sort of array is returned, even if
  455. // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.
  456. if (options.binary) {
  457. var buffer = xhr.response;
  458. if (!buffer) {
  459. buffer = [];
  460. for (var i = 0; i < xhr.responseText.length; ++i)
  461. buffer.push(xhr.responseText.charCodeAt(i) & 255);
  462. }
  463. return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
  464. }
  465. return callback(null, xhr.responseText);
  466. };
  467. if (options.binary) {
  468. // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers
  469. if ("overrideMimeType" in xhr)
  470. xhr.overrideMimeType("text/plain; charset=x-user-defined");
  471. xhr.responseType = "arraybuffer";
  472. }
  473. xhr.open("GET", filename);
  474. xhr.send();
  475. };
  476. },{"1":1,"7":7}],6:[function(require,module,exports){
  477. "use strict";
  478. module.exports = factory(factory);
  479. /**
  480. * Reads / writes floats / doubles from / to buffers.
  481. * @name util.float
  482. * @namespace
  483. */
  484. /**
  485. * Writes a 32 bit float to a buffer using little endian byte order.
  486. * @name util.float.writeFloatLE
  487. * @function
  488. * @param {number} val Value to write
  489. * @param {Uint8Array} buf Target buffer
  490. * @param {number} pos Target buffer offset
  491. * @returns {undefined}
  492. */
  493. /**
  494. * Writes a 32 bit float to a buffer using big endian byte order.
  495. * @name util.float.writeFloatBE
  496. * @function
  497. * @param {number} val Value to write
  498. * @param {Uint8Array} buf Target buffer
  499. * @param {number} pos Target buffer offset
  500. * @returns {undefined}
  501. */
  502. /**
  503. * Reads a 32 bit float from a buffer using little endian byte order.
  504. * @name util.float.readFloatLE
  505. * @function
  506. * @param {Uint8Array} buf Source buffer
  507. * @param {number} pos Source buffer offset
  508. * @returns {number} Value read
  509. */
  510. /**
  511. * Reads a 32 bit float from a buffer using big endian byte order.
  512. * @name util.float.readFloatBE
  513. * @function
  514. * @param {Uint8Array} buf Source buffer
  515. * @param {number} pos Source buffer offset
  516. * @returns {number} Value read
  517. */
  518. /**
  519. * Writes a 64 bit double to a buffer using little endian byte order.
  520. * @name util.float.writeDoubleLE
  521. * @function
  522. * @param {number} val Value to write
  523. * @param {Uint8Array} buf Target buffer
  524. * @param {number} pos Target buffer offset
  525. * @returns {undefined}
  526. */
  527. /**
  528. * Writes a 64 bit double to a buffer using big endian byte order.
  529. * @name util.float.writeDoubleBE
  530. * @function
  531. * @param {number} val Value to write
  532. * @param {Uint8Array} buf Target buffer
  533. * @param {number} pos Target buffer offset
  534. * @returns {undefined}
  535. */
  536. /**
  537. * Reads a 64 bit double from a buffer using little endian byte order.
  538. * @name util.float.readDoubleLE
  539. * @function
  540. * @param {Uint8Array} buf Source buffer
  541. * @param {number} pos Source buffer offset
  542. * @returns {number} Value read
  543. */
  544. /**
  545. * Reads a 64 bit double from a buffer using big endian byte order.
  546. * @name util.float.readDoubleBE
  547. * @function
  548. * @param {Uint8Array} buf Source buffer
  549. * @param {number} pos Source buffer offset
  550. * @returns {number} Value read
  551. */
  552. // Factory function for the purpose of node-based testing in modified global environments
  553. function factory(exports) {
  554. // float: typed array
  555. if (typeof Float32Array !== "undefined") (function() {
  556. var f32 = new Float32Array([ -0 ]),
  557. f8b = new Uint8Array(f32.buffer),
  558. le = f8b[3] === 128;
  559. function writeFloat_f32_cpy(val, buf, pos) {
  560. f32[0] = val;
  561. buf[pos ] = f8b[0];
  562. buf[pos + 1] = f8b[1];
  563. buf[pos + 2] = f8b[2];
  564. buf[pos + 3] = f8b[3];
  565. }
  566. function writeFloat_f32_rev(val, buf, pos) {
  567. f32[0] = val;
  568. buf[pos ] = f8b[3];
  569. buf[pos + 1] = f8b[2];
  570. buf[pos + 2] = f8b[1];
  571. buf[pos + 3] = f8b[0];
  572. }
  573. /* istanbul ignore next */
  574. exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
  575. /* istanbul ignore next */
  576. exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
  577. function readFloat_f32_cpy(buf, pos) {
  578. f8b[0] = buf[pos ];
  579. f8b[1] = buf[pos + 1];
  580. f8b[2] = buf[pos + 2];
  581. f8b[3] = buf[pos + 3];
  582. return f32[0];
  583. }
  584. function readFloat_f32_rev(buf, pos) {
  585. f8b[3] = buf[pos ];
  586. f8b[2] = buf[pos + 1];
  587. f8b[1] = buf[pos + 2];
  588. f8b[0] = buf[pos + 3];
  589. return f32[0];
  590. }
  591. /* istanbul ignore next */
  592. exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
  593. /* istanbul ignore next */
  594. exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
  595. // float: ieee754
  596. })(); else (function() {
  597. function writeFloat_ieee754(writeUint, val, buf, pos) {
  598. var sign = val < 0 ? 1 : 0;
  599. if (sign)
  600. val = -val;
  601. if (val === 0)
  602. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
  603. else if (isNaN(val))
  604. writeUint(2143289344, buf, pos);
  605. else if (val > 3.4028234663852886e+38) // +-Infinity
  606. writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
  607. else if (val < 1.1754943508222875e-38) // denormal
  608. writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
  609. else {
  610. var exponent = Math.floor(Math.log(val) / Math.LN2),
  611. mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
  612. writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
  613. }
  614. }
  615. exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
  616. exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
  617. function readFloat_ieee754(readUint, buf, pos) {
  618. var uint = readUint(buf, pos),
  619. sign = (uint >> 31) * 2 + 1,
  620. exponent = uint >>> 23 & 255,
  621. mantissa = uint & 8388607;
  622. return exponent === 255
  623. ? mantissa
  624. ? NaN
  625. : sign * Infinity
  626. : exponent === 0 // denormal
  627. ? sign * 1.401298464324817e-45 * mantissa
  628. : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
  629. }
  630. exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
  631. exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
  632. })();
  633. // double: typed array
  634. if (typeof Float64Array !== "undefined") (function() {
  635. var f64 = new Float64Array([-0]),
  636. f8b = new Uint8Array(f64.buffer),
  637. le = f8b[7] === 128;
  638. function writeDouble_f64_cpy(val, buf, pos) {
  639. f64[0] = val;
  640. buf[pos ] = f8b[0];
  641. buf[pos + 1] = f8b[1];
  642. buf[pos + 2] = f8b[2];
  643. buf[pos + 3] = f8b[3];
  644. buf[pos + 4] = f8b[4];
  645. buf[pos + 5] = f8b[5];
  646. buf[pos + 6] = f8b[6];
  647. buf[pos + 7] = f8b[7];
  648. }
  649. function writeDouble_f64_rev(val, buf, pos) {
  650. f64[0] = val;
  651. buf[pos ] = f8b[7];
  652. buf[pos + 1] = f8b[6];
  653. buf[pos + 2] = f8b[5];
  654. buf[pos + 3] = f8b[4];
  655. buf[pos + 4] = f8b[3];
  656. buf[pos + 5] = f8b[2];
  657. buf[pos + 6] = f8b[1];
  658. buf[pos + 7] = f8b[0];
  659. }
  660. /* istanbul ignore next */
  661. exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
  662. /* istanbul ignore next */
  663. exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
  664. function readDouble_f64_cpy(buf, pos) {
  665. f8b[0] = buf[pos ];
  666. f8b[1] = buf[pos + 1];
  667. f8b[2] = buf[pos + 2];
  668. f8b[3] = buf[pos + 3];
  669. f8b[4] = buf[pos + 4];
  670. f8b[5] = buf[pos + 5];
  671. f8b[6] = buf[pos + 6];
  672. f8b[7] = buf[pos + 7];
  673. return f64[0];
  674. }
  675. function readDouble_f64_rev(buf, pos) {
  676. f8b[7] = buf[pos ];
  677. f8b[6] = buf[pos + 1];
  678. f8b[5] = buf[pos + 2];
  679. f8b[4] = buf[pos + 3];
  680. f8b[3] = buf[pos + 4];
  681. f8b[2] = buf[pos + 5];
  682. f8b[1] = buf[pos + 6];
  683. f8b[0] = buf[pos + 7];
  684. return f64[0];
  685. }
  686. /* istanbul ignore next */
  687. exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
  688. /* istanbul ignore next */
  689. exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
  690. // double: ieee754
  691. })(); else (function() {
  692. function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
  693. var sign = val < 0 ? 1 : 0;
  694. if (sign)
  695. val = -val;
  696. if (val === 0) {
  697. writeUint(0, buf, pos + off0);
  698. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
  699. } else if (isNaN(val)) {
  700. writeUint(0, buf, pos + off0);
  701. writeUint(2146959360, buf, pos + off1);
  702. } else if (val > 1.7976931348623157e+308) { // +-Infinity
  703. writeUint(0, buf, pos + off0);
  704. writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
  705. } else {
  706. var mantissa;
  707. if (val < 2.2250738585072014e-308) { // denormal
  708. mantissa = val / 5e-324;
  709. writeUint(mantissa >>> 0, buf, pos + off0);
  710. writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
  711. } else {
  712. var exponent = Math.floor(Math.log(val) / Math.LN2);
  713. if (exponent === 1024)
  714. exponent = 1023;
  715. mantissa = val * Math.pow(2, -exponent);
  716. writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
  717. writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
  718. }
  719. }
  720. }
  721. exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
  722. exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
  723. function readDouble_ieee754(readUint, off0, off1, buf, pos) {
  724. var lo = readUint(buf, pos + off0),
  725. hi = readUint(buf, pos + off1);
  726. var sign = (hi >> 31) * 2 + 1,
  727. exponent = hi >>> 20 & 2047,
  728. mantissa = 4294967296 * (hi & 1048575) + lo;
  729. return exponent === 2047
  730. ? mantissa
  731. ? NaN
  732. : sign * Infinity
  733. : exponent === 0 // denormal
  734. ? sign * 5e-324 * mantissa
  735. : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
  736. }
  737. exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
  738. exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
  739. })();
  740. return exports;
  741. }
  742. // uint helpers
  743. function writeUintLE(val, buf, pos) {
  744. buf[pos ] = val & 255;
  745. buf[pos + 1] = val >>> 8 & 255;
  746. buf[pos + 2] = val >>> 16 & 255;
  747. buf[pos + 3] = val >>> 24;
  748. }
  749. function writeUintBE(val, buf, pos) {
  750. buf[pos ] = val >>> 24;
  751. buf[pos + 1] = val >>> 16 & 255;
  752. buf[pos + 2] = val >>> 8 & 255;
  753. buf[pos + 3] = val & 255;
  754. }
  755. function readUintLE(buf, pos) {
  756. return (buf[pos ]
  757. | buf[pos + 1] << 8
  758. | buf[pos + 2] << 16
  759. | buf[pos + 3] << 24) >>> 0;
  760. }
  761. function readUintBE(buf, pos) {
  762. return (buf[pos ] << 24
  763. | buf[pos + 1] << 16
  764. | buf[pos + 2] << 8
  765. | buf[pos + 3]) >>> 0;
  766. }
  767. },{}],7:[function(require,module,exports){
  768. "use strict";
  769. module.exports = inquire;
  770. /**
  771. * Requires a module only if available.
  772. * @memberof util
  773. * @param {string} moduleName Module to require
  774. * @returns {?Object} Required module if available and not empty, otherwise `null`
  775. */
  776. function inquire(moduleName) {
  777. try {
  778. var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
  779. if (mod && (mod.length || Object.keys(mod).length))
  780. return mod;
  781. } catch (e) {} // eslint-disable-line no-empty
  782. return null;
  783. }
  784. },{}],8:[function(require,module,exports){
  785. "use strict";
  786. /**
  787. * A minimal path module to resolve Unix, Windows and URL paths alike.
  788. * @memberof util
  789. * @namespace
  790. */
  791. var path = exports;
  792. var isAbsolute =
  793. /**
  794. * Tests if the specified path is absolute.
  795. * @param {string} path Path to test
  796. * @returns {boolean} `true` if path is absolute
  797. */
  798. path.isAbsolute = function isAbsolute(path) {
  799. return /^(?:\/|\w+:)/.test(path);
  800. };
  801. var normalize =
  802. /**
  803. * Normalizes the specified path.
  804. * @param {string} path Path to normalize
  805. * @returns {string} Normalized path
  806. */
  807. path.normalize = function normalize(path) {
  808. path = path.replace(/\\/g, "/")
  809. .replace(/\/{2,}/g, "/");
  810. var parts = path.split("/"),
  811. absolute = isAbsolute(path),
  812. prefix = "";
  813. if (absolute)
  814. prefix = parts.shift() + "/";
  815. for (var i = 0; i < parts.length;) {
  816. if (parts[i] === "..") {
  817. if (i > 0 && parts[i - 1] !== "..")
  818. parts.splice(--i, 2);
  819. else if (absolute)
  820. parts.splice(i, 1);
  821. else
  822. ++i;
  823. } else if (parts[i] === ".")
  824. parts.splice(i, 1);
  825. else
  826. ++i;
  827. }
  828. return prefix + parts.join("/");
  829. };
  830. /**
  831. * Resolves the specified include path against the specified origin path.
  832. * @param {string} originPath Path to the origin file
  833. * @param {string} includePath Include path relative to origin path
  834. * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized
  835. * @returns {string} Path to the include file
  836. */
  837. path.resolve = function resolve(originPath, includePath, alreadyNormalized) {
  838. if (!alreadyNormalized)
  839. includePath = normalize(includePath);
  840. if (isAbsolute(includePath))
  841. return includePath;
  842. if (!alreadyNormalized)
  843. originPath = normalize(originPath);
  844. return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;
  845. };
  846. },{}],9:[function(require,module,exports){
  847. "use strict";
  848. module.exports = pool;
  849. /**
  850. * An allocator as used by {@link util.pool}.
  851. * @typedef PoolAllocator
  852. * @type {function}
  853. * @param {number} size Buffer size
  854. * @returns {Uint8Array} Buffer
  855. */
  856. /**
  857. * A slicer as used by {@link util.pool}.
  858. * @typedef PoolSlicer
  859. * @type {function}
  860. * @param {number} start Start offset
  861. * @param {number} end End offset
  862. * @returns {Uint8Array} Buffer slice
  863. * @this {Uint8Array}
  864. */
  865. /**
  866. * A general purpose buffer pool.
  867. * @memberof util
  868. * @function
  869. * @param {PoolAllocator} alloc Allocator
  870. * @param {PoolSlicer} slice Slicer
  871. * @param {number} [size=8192] Slab size
  872. * @returns {PoolAllocator} Pooled allocator
  873. */
  874. function pool(alloc, slice, size) {
  875. var SIZE = size || 8192;
  876. var MAX = SIZE >>> 1;
  877. var slab = null;
  878. var offset = SIZE;
  879. return function pool_alloc(size) {
  880. if (size < 1 || size > MAX)
  881. return alloc(size);
  882. if (offset + size > SIZE) {
  883. slab = alloc(SIZE);
  884. offset = 0;
  885. }
  886. var buf = slice.call(slab, offset, offset += size);
  887. if (offset & 7) // align to 32 bit
  888. offset = (offset | 7) + 1;
  889. return buf;
  890. };
  891. }
  892. },{}],10:[function(require,module,exports){
  893. "use strict";
  894. /**
  895. * A minimal UTF8 implementation for number arrays.
  896. * @memberof util
  897. * @namespace
  898. */
  899. var utf8 = exports;
  900. /**
  901. * Calculates the UTF8 byte length of a string.
  902. * @param {string} string String
  903. * @returns {number} Byte length
  904. */
  905. utf8.length = function utf8_length(string) {
  906. var len = 0,
  907. c = 0;
  908. for (var i = 0; i < string.length; ++i) {
  909. c = string.charCodeAt(i);
  910. if (c < 128)
  911. len += 1;
  912. else if (c < 2048)
  913. len += 2;
  914. else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
  915. ++i;
  916. len += 4;
  917. } else
  918. len += 3;
  919. }
  920. return len;
  921. };
  922. /**
  923. * Reads UTF8 bytes as a string.
  924. * @param {Uint8Array} buffer Source buffer
  925. * @param {number} start Source start
  926. * @param {number} end Source end
  927. * @returns {string} String read
  928. */
  929. utf8.read = function utf8_read(buffer, start, end) {
  930. var len = end - start;
  931. if (len < 1)
  932. return "";
  933. var parts = null,
  934. chunk = [],
  935. i = 0, // char offset
  936. t; // temporary
  937. while (start < end) {
  938. t = buffer[start++];
  939. if (t < 128)
  940. chunk[i++] = t;
  941. else if (t > 191 && t < 224)
  942. chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
  943. else if (t > 239 && t < 365) {
  944. t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
  945. chunk[i++] = 0xD800 + (t >> 10);
  946. chunk[i++] = 0xDC00 + (t & 1023);
  947. } else
  948. chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
  949. if (i > 8191) {
  950. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  951. i = 0;
  952. }
  953. }
  954. if (parts) {
  955. if (i)
  956. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  957. return parts.join("");
  958. }
  959. return String.fromCharCode.apply(String, chunk.slice(0, i));
  960. };
  961. /**
  962. * Writes a string as UTF8 bytes.
  963. * @param {string} string Source string
  964. * @param {Uint8Array} buffer Destination buffer
  965. * @param {number} offset Destination offset
  966. * @returns {number} Bytes written
  967. */
  968. utf8.write = function utf8_write(string, buffer, offset) {
  969. var start = offset,
  970. c1, // character 1
  971. c2; // character 2
  972. for (var i = 0; i < string.length; ++i) {
  973. c1 = string.charCodeAt(i);
  974. if (c1 < 128) {
  975. buffer[offset++] = c1;
  976. } else if (c1 < 2048) {
  977. buffer[offset++] = c1 >> 6 | 192;
  978. buffer[offset++] = c1 & 63 | 128;
  979. } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
  980. c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
  981. ++i;
  982. buffer[offset++] = c1 >> 18 | 240;
  983. buffer[offset++] = c1 >> 12 & 63 | 128;
  984. buffer[offset++] = c1 >> 6 & 63 | 128;
  985. buffer[offset++] = c1 & 63 | 128;
  986. } else {
  987. buffer[offset++] = c1 >> 12 | 224;
  988. buffer[offset++] = c1 >> 6 & 63 | 128;
  989. buffer[offset++] = c1 & 63 | 128;
  990. }
  991. }
  992. return offset - start;
  993. };
  994. },{}],11:[function(require,module,exports){
  995. "use strict";
  996. module.exports = common;
  997. var commonRe = /\/|\./;
  998. /**
  999. * Provides common type definitions.
  1000. * Can also be used to provide additional google types or your own custom types.
  1001. * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name
  1002. * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition
  1003. * @returns {undefined}
  1004. * @property {INamespace} google/protobuf/any.proto Any
  1005. * @property {INamespace} google/protobuf/duration.proto Duration
  1006. * @property {INamespace} google/protobuf/empty.proto Empty
  1007. * @property {INamespace} google/protobuf/field_mask.proto FieldMask
  1008. * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue
  1009. * @property {INamespace} google/protobuf/timestamp.proto Timestamp
  1010. * @property {INamespace} google/protobuf/wrappers.proto Wrappers
  1011. * @example
  1012. * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)
  1013. * protobuf.common("descriptor", descriptorJson);
  1014. *
  1015. * // manually provides a custom definition (uses my.foo namespace)
  1016. * protobuf.common("my/foo/bar.proto", myFooBarJson);
  1017. */
  1018. function common(name, json) {
  1019. if (!commonRe.test(name)) {
  1020. name = "google/protobuf/" + name + ".proto";
  1021. json = { nested: { google: { nested: { protobuf: { nested: json } } } } };
  1022. }
  1023. common[name] = json;
  1024. }
  1025. // Not provided because of limited use (feel free to discuss or to provide yourself):
  1026. //
  1027. // google/protobuf/descriptor.proto
  1028. // google/protobuf/source_context.proto
  1029. // google/protobuf/type.proto
  1030. //
  1031. // Stripped and pre-parsed versions of these non-bundled files are instead available as part of
  1032. // the repository or package within the google/protobuf directory.
  1033. common("any", {
  1034. /**
  1035. * Properties of a google.protobuf.Any message.
  1036. * @interface IAny
  1037. * @type {Object}
  1038. * @property {string} [typeUrl]
  1039. * @property {Uint8Array} [bytes]
  1040. * @memberof common
  1041. */
  1042. Any: {
  1043. fields: {
  1044. type_url: {
  1045. type: "string",
  1046. id: 1
  1047. },
  1048. value: {
  1049. type: "bytes",
  1050. id: 2
  1051. }
  1052. }
  1053. }
  1054. });
  1055. var timeType;
  1056. common("duration", {
  1057. /**
  1058. * Properties of a google.protobuf.Duration message.
  1059. * @interface IDuration
  1060. * @type {Object}
  1061. * @property {number|Long} [seconds]
  1062. * @property {number} [nanos]
  1063. * @memberof common
  1064. */
  1065. Duration: timeType = {
  1066. fields: {
  1067. seconds: {
  1068. type: "int64",
  1069. id: 1
  1070. },
  1071. nanos: {
  1072. type: "int32",
  1073. id: 2
  1074. }
  1075. }
  1076. }
  1077. });
  1078. common("timestamp", {
  1079. /**
  1080. * Properties of a google.protobuf.Timestamp message.
  1081. * @interface ITimestamp
  1082. * @type {Object}
  1083. * @property {number|Long} [seconds]
  1084. * @property {number} [nanos]
  1085. * @memberof common
  1086. */
  1087. Timestamp: timeType
  1088. });
  1089. common("empty", {
  1090. /**
  1091. * Properties of a google.protobuf.Empty message.
  1092. * @interface IEmpty
  1093. * @memberof common
  1094. */
  1095. Empty: {
  1096. fields: {}
  1097. }
  1098. });
  1099. common("struct", {
  1100. /**
  1101. * Properties of a google.protobuf.Struct message.
  1102. * @interface IStruct
  1103. * @type {Object}
  1104. * @property {Object.<string,IValue>} [fields]
  1105. * @memberof common
  1106. */
  1107. Struct: {
  1108. fields: {
  1109. fields: {
  1110. keyType: "string",
  1111. type: "Value",
  1112. id: 1
  1113. }
  1114. }
  1115. },
  1116. /**
  1117. * Properties of a google.protobuf.Value message.
  1118. * @interface IValue
  1119. * @type {Object}
  1120. * @property {string} [kind]
  1121. * @property {0} [nullValue]
  1122. * @property {number} [numberValue]
  1123. * @property {string} [stringValue]
  1124. * @property {boolean} [boolValue]
  1125. * @property {IStruct} [structValue]
  1126. * @property {IListValue} [listValue]
  1127. * @memberof common
  1128. */
  1129. Value: {
  1130. oneofs: {
  1131. kind: {
  1132. oneof: [
  1133. "nullValue",
  1134. "numberValue",
  1135. "stringValue",
  1136. "boolValue",
  1137. "structValue",
  1138. "listValue"
  1139. ]
  1140. }
  1141. },
  1142. fields: {
  1143. nullValue: {
  1144. type: "NullValue",
  1145. id: 1
  1146. },
  1147. numberValue: {
  1148. type: "double",
  1149. id: 2
  1150. },
  1151. stringValue: {
  1152. type: "string",
  1153. id: 3
  1154. },
  1155. boolValue: {
  1156. type: "bool",
  1157. id: 4
  1158. },
  1159. structValue: {
  1160. type: "Struct",
  1161. id: 5
  1162. },
  1163. listValue: {
  1164. type: "ListValue",
  1165. id: 6
  1166. }
  1167. }
  1168. },
  1169. NullValue: {
  1170. values: {
  1171. NULL_VALUE: 0
  1172. }
  1173. },
  1174. /**
  1175. * Properties of a google.protobuf.ListValue message.
  1176. * @interface IListValue
  1177. * @type {Object}
  1178. * @property {Array.<IValue>} [values]
  1179. * @memberof common
  1180. */
  1181. ListValue: {
  1182. fields: {
  1183. values: {
  1184. rule: "repeated",
  1185. type: "Value",
  1186. id: 1
  1187. }
  1188. }
  1189. }
  1190. });
  1191. common("wrappers", {
  1192. /**
  1193. * Properties of a google.protobuf.DoubleValue message.
  1194. * @interface IDoubleValue
  1195. * @type {Object}
  1196. * @property {number} [value]
  1197. * @memberof common
  1198. */
  1199. DoubleValue: {
  1200. fields: {
  1201. value: {
  1202. type: "double",
  1203. id: 1
  1204. }
  1205. }
  1206. },
  1207. /**
  1208. * Properties of a google.protobuf.FloatValue message.
  1209. * @interface IFloatValue
  1210. * @type {Object}
  1211. * @property {number} [value]
  1212. * @memberof common
  1213. */
  1214. FloatValue: {
  1215. fields: {
  1216. value: {
  1217. type: "float",
  1218. id: 1
  1219. }
  1220. }
  1221. },
  1222. /**
  1223. * Properties of a google.protobuf.Int64Value message.
  1224. * @interface IInt64Value
  1225. * @type {Object}
  1226. * @property {number|Long} [value]
  1227. * @memberof common
  1228. */
  1229. Int64Value: {
  1230. fields: {
  1231. value: {
  1232. type: "int64",
  1233. id: 1
  1234. }
  1235. }
  1236. },
  1237. /**
  1238. * Properties of a google.protobuf.UInt64Value message.
  1239. * @interface IUInt64Value
  1240. * @type {Object}
  1241. * @property {number|Long} [value]
  1242. * @memberof common
  1243. */
  1244. UInt64Value: {
  1245. fields: {
  1246. value: {
  1247. type: "uint64",
  1248. id: 1
  1249. }
  1250. }
  1251. },
  1252. /**
  1253. * Properties of a google.protobuf.Int32Value message.
  1254. * @interface IInt32Value
  1255. * @type {Object}
  1256. * @property {number} [value]
  1257. * @memberof common
  1258. */
  1259. Int32Value: {
  1260. fields: {
  1261. value: {
  1262. type: "int32",
  1263. id: 1
  1264. }
  1265. }
  1266. },
  1267. /**
  1268. * Properties of a google.protobuf.UInt32Value message.
  1269. * @interface IUInt32Value
  1270. * @type {Object}
  1271. * @property {number} [value]
  1272. * @memberof common
  1273. */
  1274. UInt32Value: {
  1275. fields: {
  1276. value: {
  1277. type: "uint32",
  1278. id: 1
  1279. }
  1280. }
  1281. },
  1282. /**
  1283. * Properties of a google.protobuf.BoolValue message.
  1284. * @interface IBoolValue
  1285. * @type {Object}
  1286. * @property {boolean} [value]
  1287. * @memberof common
  1288. */
  1289. BoolValue: {
  1290. fields: {
  1291. value: {
  1292. type: "bool",
  1293. id: 1
  1294. }
  1295. }
  1296. },
  1297. /**
  1298. * Properties of a google.protobuf.StringValue message.
  1299. * @interface IStringValue
  1300. * @type {Object}
  1301. * @property {string} [value]
  1302. * @memberof common
  1303. */
  1304. StringValue: {
  1305. fields: {
  1306. value: {
  1307. type: "string",
  1308. id: 1
  1309. }
  1310. }
  1311. },
  1312. /**
  1313. * Properties of a google.protobuf.BytesValue message.
  1314. * @interface IBytesValue
  1315. * @type {Object}
  1316. * @property {Uint8Array} [value]
  1317. * @memberof common
  1318. */
  1319. BytesValue: {
  1320. fields: {
  1321. value: {
  1322. type: "bytes",
  1323. id: 1
  1324. }
  1325. }
  1326. }
  1327. });
  1328. common("field_mask", {
  1329. /**
  1330. * Properties of a google.protobuf.FieldMask message.
  1331. * @interface IDoubleValue
  1332. * @type {Object}
  1333. * @property {number} [value]
  1334. * @memberof common
  1335. */
  1336. FieldMask: {
  1337. fields: {
  1338. paths: {
  1339. rule: "repeated",
  1340. type: "string",
  1341. id: 1
  1342. }
  1343. }
  1344. }
  1345. });
  1346. /**
  1347. * Gets the root definition of the specified common proto file.
  1348. *
  1349. * Bundled definitions are:
  1350. * - google/protobuf/any.proto
  1351. * - google/protobuf/duration.proto
  1352. * - google/protobuf/empty.proto
  1353. * - google/protobuf/field_mask.proto
  1354. * - google/protobuf/struct.proto
  1355. * - google/protobuf/timestamp.proto
  1356. * - google/protobuf/wrappers.proto
  1357. *
  1358. * @param {string} file Proto file name
  1359. * @returns {INamespace|null} Root definition or `null` if not defined
  1360. */
  1361. common.get = function get(file) {
  1362. return common[file] || null;
  1363. };
  1364. },{}],12:[function(require,module,exports){
  1365. "use strict";
  1366. /**
  1367. * Runtime message from/to plain object converters.
  1368. * @namespace
  1369. */
  1370. var converter = exports;
  1371. var Enum = require(15),
  1372. util = require(37);
  1373. /**
  1374. * Generates a partial value fromObject conveter.
  1375. * @param {Codegen} gen Codegen instance
  1376. * @param {Field} field Reflected field
  1377. * @param {number} fieldIndex Field index
  1378. * @param {string} prop Property reference
  1379. * @returns {Codegen} Codegen instance
  1380. * @ignore
  1381. */
  1382. function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
  1383. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1384. if (field.resolvedType) {
  1385. if (field.resolvedType instanceof Enum) { gen
  1386. ("switch(d%s){", prop);
  1387. for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
  1388. if (field.repeated && values[keys[i]] === field.typeDefault) gen
  1389. ("default:");
  1390. gen
  1391. ("case%j:", keys[i])
  1392. ("case %i:", values[keys[i]])
  1393. ("m%s=%j", prop, values[keys[i]])
  1394. ("break");
  1395. } gen
  1396. ("}");
  1397. } else gen
  1398. ("if(typeof d%s!==\"object\")", prop)
  1399. ("throw TypeError(%j)", field.fullName + ": object expected")
  1400. ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);
  1401. } else {
  1402. var isUnsigned = false;
  1403. switch (field.type) {
  1404. case "double":
  1405. case "float": gen
  1406. ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"
  1407. break;
  1408. case "uint32":
  1409. case "fixed32": gen
  1410. ("m%s=d%s>>>0", prop, prop);
  1411. break;
  1412. case "int32":
  1413. case "sint32":
  1414. case "sfixed32": gen
  1415. ("m%s=d%s|0", prop, prop);
  1416. break;
  1417. case "uint64":
  1418. isUnsigned = true;
  1419. // eslint-disable-line no-fallthrough
  1420. case "int64":
  1421. case "sint64":
  1422. case "fixed64":
  1423. case "sfixed64": gen
  1424. ("if(util.Long)")
  1425. ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)
  1426. ("else if(typeof d%s===\"string\")", prop)
  1427. ("m%s=parseInt(d%s,10)", prop, prop)
  1428. ("else if(typeof d%s===\"number\")", prop)
  1429. ("m%s=d%s", prop, prop)
  1430. ("else if(typeof d%s===\"object\")", prop)
  1431. ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
  1432. break;
  1433. case "bytes": gen
  1434. ("if(typeof d%s===\"string\")", prop)
  1435. ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)
  1436. ("else if(d%s.length)", prop)
  1437. ("m%s=d%s", prop, prop);
  1438. break;
  1439. case "string": gen
  1440. ("m%s=String(d%s)", prop, prop);
  1441. break;
  1442. case "bool": gen
  1443. ("m%s=Boolean(d%s)", prop, prop);
  1444. break;
  1445. /* default: gen
  1446. ("m%s=d%s", prop, prop);
  1447. break; */
  1448. }
  1449. }
  1450. return gen;
  1451. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1452. }
  1453. /**
  1454. * Generates a plain object to runtime message converter specific to the specified message type.
  1455. * @param {Type} mtype Message type
  1456. * @returns {Codegen} Codegen instance
  1457. */
  1458. converter.fromObject = function fromObject(mtype) {
  1459. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1460. var fields = mtype.fieldsArray;
  1461. var gen = util.codegen(["d"], mtype.name + "$fromObject")
  1462. ("if(d instanceof this.ctor)")
  1463. ("return d");
  1464. if (!fields.length) return gen
  1465. ("return new this.ctor");
  1466. gen
  1467. ("var m=new this.ctor");
  1468. for (var i = 0; i < fields.length; ++i) {
  1469. var field = fields[i].resolve(),
  1470. prop = util.safeProp(field.name);
  1471. // Map fields
  1472. if (field.map) { gen
  1473. ("if(d%s){", prop)
  1474. ("if(typeof d%s!==\"object\")", prop)
  1475. ("throw TypeError(%j)", field.fullName + ": object expected")
  1476. ("m%s={}", prop)
  1477. ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
  1478. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")
  1479. ("}")
  1480. ("}");
  1481. // Repeated fields
  1482. } else if (field.repeated) { gen
  1483. ("if(d%s){", prop)
  1484. ("if(!Array.isArray(d%s))", prop)
  1485. ("throw TypeError(%j)", field.fullName + ": array expected")
  1486. ("m%s=[]", prop)
  1487. ("for(var i=0;i<d%s.length;++i){", prop);
  1488. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")
  1489. ("}")
  1490. ("}");
  1491. // Non-repeated fields
  1492. } else {
  1493. if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)
  1494. ("if(d%s!=null){", prop); // !== undefined && !== null
  1495. genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);
  1496. if (!(field.resolvedType instanceof Enum)) gen
  1497. ("}");
  1498. }
  1499. } return gen
  1500. ("return m");
  1501. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1502. };
  1503. /**
  1504. * Generates a partial value toObject converter.
  1505. * @param {Codegen} gen Codegen instance
  1506. * @param {Field} field Reflected field
  1507. * @param {number} fieldIndex Field index
  1508. * @param {string} prop Property reference
  1509. * @returns {Codegen} Codegen instance
  1510. * @ignore
  1511. */
  1512. function genValuePartial_toObject(gen, field, fieldIndex, prop) {
  1513. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1514. if (field.resolvedType) {
  1515. if (field.resolvedType instanceof Enum) gen
  1516. ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);
  1517. else gen
  1518. ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);
  1519. } else {
  1520. var isUnsigned = false;
  1521. switch (field.type) {
  1522. case "double":
  1523. case "float": gen
  1524. ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);
  1525. break;
  1526. case "uint64":
  1527. isUnsigned = true;
  1528. // eslint-disable-line no-fallthrough
  1529. case "int64":
  1530. case "sint64":
  1531. case "fixed64":
  1532. case "sfixed64": gen
  1533. ("if(typeof m%s===\"number\")", prop)
  1534. ("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)
  1535. ("else") // Long-like
  1536. ("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop);
  1537. break;
  1538. case "bytes": gen
  1539. ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);
  1540. break;
  1541. default: gen
  1542. ("d%s=m%s", prop, prop);
  1543. break;
  1544. }
  1545. }
  1546. return gen;
  1547. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1548. }
  1549. /**
  1550. * Generates a runtime message to plain object converter specific to the specified message type.
  1551. * @param {Type} mtype Message type
  1552. * @returns {Codegen} Codegen instance
  1553. */
  1554. converter.toObject = function toObject(mtype) {
  1555. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1556. var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
  1557. if (!fields.length)
  1558. return util.codegen()("return {}");
  1559. var gen = util.codegen(["m", "o"], mtype.name + "$toObject")
  1560. ("if(!o)")
  1561. ("o={}")
  1562. ("var d={}");
  1563. var repeatedFields = [],
  1564. mapFields = [],
  1565. normalFields = [],
  1566. i = 0;
  1567. for (; i < fields.length; ++i)
  1568. if (!fields[i].partOf)
  1569. ( fields[i].resolve().repeated ? repeatedFields
  1570. : fields[i].map ? mapFields
  1571. : normalFields).push(fields[i]);
  1572. if (repeatedFields.length) { gen
  1573. ("if(o.arrays||o.defaults){");
  1574. for (i = 0; i < repeatedFields.length; ++i) gen
  1575. ("d%s=[]", util.safeProp(repeatedFields[i].name));
  1576. gen
  1577. ("}");
  1578. }
  1579. if (mapFields.length) { gen
  1580. ("if(o.objects||o.defaults){");
  1581. for (i = 0; i < mapFields.length; ++i) gen
  1582. ("d%s={}", util.safeProp(mapFields[i].name));
  1583. gen
  1584. ("}");
  1585. }
  1586. if (normalFields.length) { gen
  1587. ("if(o.defaults){");
  1588. for (i = 0; i < normalFields.length; ++i) {
  1589. var field = normalFields[i],
  1590. prop = util.safeProp(field.name);
  1591. if (field.resolvedType instanceof Enum) gen
  1592. ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
  1593. else if (field.long) gen
  1594. ("if(util.Long){")
  1595. ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)
  1596. ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)
  1597. ("}else")
  1598. ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());
  1599. else if (field.bytes) {
  1600. var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]";
  1601. gen
  1602. ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))
  1603. ("else{")
  1604. ("d%s=%s", prop, arrayDefault)
  1605. ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)
  1606. ("}");
  1607. } else gen
  1608. ("d%s=%j", prop, field.typeDefault); // also messages (=null)
  1609. } gen
  1610. ("}");
  1611. }
  1612. var hasKs2 = false;
  1613. for (i = 0; i < fields.length; ++i) {
  1614. var field = fields[i],
  1615. index = mtype._fieldsArray.indexOf(field),
  1616. prop = util.safeProp(field.name);
  1617. if (field.map) {
  1618. if (!hasKs2) { hasKs2 = true; gen
  1619. ("var ks2");
  1620. } gen
  1621. ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)
  1622. ("d%s={}", prop)
  1623. ("for(var j=0;j<ks2.length;++j){");
  1624. genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]")
  1625. ("}");
  1626. } else if (field.repeated) { gen
  1627. ("if(m%s&&m%s.length){", prop, prop)
  1628. ("d%s=[]", prop)
  1629. ("for(var j=0;j<m%s.length;++j){", prop);
  1630. genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")
  1631. ("}");
  1632. } else { gen
  1633. ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name); // !== undefined && !== null
  1634. genValuePartial_toObject(gen, field, /* sorted */ index, prop);
  1635. if (field.partOf) gen
  1636. ("if(o.oneofs)")
  1637. ("d%s=%j", util.safeProp(field.partOf.name), field.name);
  1638. }
  1639. gen
  1640. ("}");
  1641. }
  1642. return gen
  1643. ("return d");
  1644. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1645. };
  1646. },{"15":15,"37":37}],13:[function(require,module,exports){
  1647. "use strict";
  1648. module.exports = decoder;
  1649. var Enum = require(15),
  1650. types = require(36),
  1651. util = require(37);
  1652. function missing(field) {
  1653. return "missing required '" + field.name + "'";
  1654. }
  1655. /**
  1656. * Generates a decoder specific to the specified message type.
  1657. * @param {Type} mtype Message type
  1658. * @returns {Codegen} Codegen instance
  1659. */
  1660. function decoder(mtype) {
  1661. /* eslint-disable no-unexpected-multiline */
  1662. var gen = util.codegen(["r", "l"], mtype.name + "$decode")
  1663. ("if(!(r instanceof Reader))")
  1664. ("r=Reader.create(r)")
  1665. ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k,value" : ""))
  1666. ("while(r.pos<c){")
  1667. ("var t=r.uint32()");
  1668. if (mtype.group) gen
  1669. ("if((t&7)===4)")
  1670. ("break");
  1671. gen
  1672. ("switch(t>>>3){");
  1673. var i = 0;
  1674. for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  1675. var field = mtype._fieldsArray[i].resolve(),
  1676. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  1677. ref = "m" + util.safeProp(field.name); gen
  1678. ("case %i:", field.id);
  1679. // Map fields
  1680. if (field.map) { gen
  1681. ("if(%s===util.emptyObject)", ref)
  1682. ("%s={}", ref)
  1683. ("var c2 = r.uint32()+r.pos");
  1684. if (types.defaults[field.keyType] !== undefined) gen
  1685. ("k=%j", types.defaults[field.keyType]);
  1686. else gen
  1687. ("k=null");
  1688. if (types.defaults[type] !== undefined) gen
  1689. ("value=%j", types.defaults[type]);
  1690. else gen
  1691. ("value=null");
  1692. gen
  1693. ("while(r.pos<c2){")
  1694. ("var tag2=r.uint32()")
  1695. ("switch(tag2>>>3){")
  1696. ("case 1: k=r.%s(); break", field.keyType)
  1697. ("case 2:");
  1698. if (types.basic[type] === undefined) gen
  1699. ("value=types[%i].decode(r,r.uint32())", i); // can't be groups
  1700. else gen
  1701. ("value=r.%s()", type);
  1702. gen
  1703. ("break")
  1704. ("default:")
  1705. ("r.skipType(tag2&7)")
  1706. ("break")
  1707. ("}")
  1708. ("}");
  1709. if (types.long[field.keyType] !== undefined) gen
  1710. ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref);
  1711. else gen
  1712. ("%s[k]=value", ref);
  1713. // Repeated fields
  1714. } else if (field.repeated) { gen
  1715. ("if(!(%s&&%s.length))", ref, ref)
  1716. ("%s=[]", ref);
  1717. // Packable (always check for forward and backward compatiblity)
  1718. if (types.packed[type] !== undefined) gen
  1719. ("if((t&7)===2){")
  1720. ("var c2=r.uint32()+r.pos")
  1721. ("while(r.pos<c2)")
  1722. ("%s.push(r.%s())", ref, type)
  1723. ("}else");
  1724. // Non-packed
  1725. if (types.basic[type] === undefined) gen(field.resolvedType.group
  1726. ? "%s.push(types[%i].decode(r))"
  1727. : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);
  1728. else gen
  1729. ("%s.push(r.%s())", ref, type);
  1730. // Non-repeated
  1731. } else if (types.basic[type] === undefined) gen(field.resolvedType.group
  1732. ? "%s=types[%i].decode(r)"
  1733. : "%s=types[%i].decode(r,r.uint32())", ref, i);
  1734. else gen
  1735. ("%s=r.%s()", ref, type);
  1736. gen
  1737. ("break");
  1738. // Unknown fields
  1739. } gen
  1740. ("default:")
  1741. ("r.skipType(t&7)")
  1742. ("break")
  1743. ("}")
  1744. ("}");
  1745. // Field presence
  1746. for (i = 0; i < mtype._fieldsArray.length; ++i) {
  1747. var rfield = mtype._fieldsArray[i];
  1748. if (rfield.required) gen
  1749. ("if(!m.hasOwnProperty(%j))", rfield.name)
  1750. ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
  1751. }
  1752. return gen
  1753. ("return m");
  1754. /* eslint-enable no-unexpected-multiline */
  1755. }
  1756. },{"15":15,"36":36,"37":37}],14:[function(require,module,exports){
  1757. "use strict";
  1758. module.exports = encoder;
  1759. var Enum = require(15),
  1760. types = require(36),
  1761. util = require(37);
  1762. /**
  1763. * Generates a partial message type encoder.
  1764. * @param {Codegen} gen Codegen instance
  1765. * @param {Field} field Reflected field
  1766. * @param {number} fieldIndex Field index
  1767. * @param {string} ref Variable reference
  1768. * @returns {Codegen} Codegen instance
  1769. * @ignore
  1770. */
  1771. function genTypePartial(gen, field, fieldIndex, ref) {
  1772. return field.resolvedType.group
  1773. ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)
  1774. : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
  1775. }
  1776. /**
  1777. * Generates an encoder specific to the specified message type.
  1778. * @param {Type} mtype Message type
  1779. * @returns {Codegen} Codegen instance
  1780. */
  1781. function encoder(mtype) {
  1782. /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1783. var gen = util.codegen(["m", "w"], mtype.name + "$encode")
  1784. ("if(!w)")
  1785. ("w=Writer.create()");
  1786. var i, ref;
  1787. // "when a message is serialized its known fields should be written sequentially by field number"
  1788. var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);
  1789. for (var i = 0; i < fields.length; ++i) {
  1790. var field = fields[i].resolve(),
  1791. index = mtype._fieldsArray.indexOf(field),
  1792. type = field.resolvedType instanceof Enum ? "int32" : field.type,
  1793. wireType = types.basic[type];
  1794. ref = "m" + util.safeProp(field.name);
  1795. // Map fields
  1796. if (field.map) {
  1797. gen
  1798. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null
  1799. ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)
  1800. ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
  1801. if (wireType === undefined) gen
  1802. ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups
  1803. else gen
  1804. (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
  1805. gen
  1806. ("}")
  1807. ("}");
  1808. // Repeated fields
  1809. } else if (field.repeated) { gen
  1810. ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null
  1811. // Packed repeated
  1812. if (field.packed && types.packed[type] !== undefined) { gen
  1813. ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)
  1814. ("for(var i=0;i<%s.length;++i)", ref)
  1815. ("w.%s(%s[i])", type, ref)
  1816. ("w.ldelim()");
  1817. // Non-packed
  1818. } else { gen
  1819. ("for(var i=0;i<%s.length;++i)", ref);
  1820. if (wireType === undefined)
  1821. genTypePartial(gen, field, index, ref + "[i]");
  1822. else gen
  1823. ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
  1824. } gen
  1825. ("}");
  1826. // Non-repeated
  1827. } else {
  1828. if (field.optional) gen
  1829. ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null
  1830. if (wireType === undefined)
  1831. genTypePartial(gen, field, index, ref);
  1832. else gen
  1833. ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
  1834. }
  1835. }
  1836. return gen
  1837. ("return w");
  1838. /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
  1839. }
  1840. },{"15":15,"36":36,"37":37}],15:[function(require,module,exports){
  1841. "use strict";
  1842. module.exports = Enum;
  1843. // extends ReflectionObject
  1844. var ReflectionObject = require(24);
  1845. ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
  1846. var Namespace = require(23),
  1847. util = require(37);
  1848. /**
  1849. * Constructs a new enum instance.
  1850. * @classdesc Reflected enum.
  1851. * @extends ReflectionObject
  1852. * @constructor
  1853. * @param {string} name Unique name within its namespace
  1854. * @param {Object.<string,number>} [values] Enum values as an object, by name
  1855. * @param {Object.<string,*>} [options] Declared options
  1856. * @param {string} [comment] The comment for this enum
  1857. * @param {Object.<string,string>} [comments] The value comments for this enum
  1858. */
  1859. function Enum(name, values, options, comment, comments) {
  1860. ReflectionObject.call(this, name, options);
  1861. if (values && typeof values !== "object")
  1862. throw TypeError("values must be an object");
  1863. /**
  1864. * Enum values by id.
  1865. * @type {Object.<number,string>}
  1866. */
  1867. this.valuesById = {};
  1868. /**
  1869. * Enum values by name.
  1870. * @type {Object.<string,number>}
  1871. */
  1872. this.values = Object.create(this.valuesById); // toJSON, marker
  1873. /**
  1874. * Enum comment text.
  1875. * @type {string|null}
  1876. */
  1877. this.comment = comment;
  1878. /**
  1879. * Value comment texts, if any.
  1880. * @type {Object.<string,string>}
  1881. */
  1882. this.comments = comments || {};
  1883. /**
  1884. * Reserved ranges, if any.
  1885. * @type {Array.<number[]|string>}
  1886. */
  1887. this.reserved = undefined; // toJSON
  1888. // Note that values inherit valuesById on their prototype which makes them a TypeScript-
  1889. // compatible enum. This is used by pbts to write actual enum definitions that work for
  1890. // static and reflection code alike instead of emitting generic object definitions.
  1891. if (values)
  1892. for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
  1893. if (typeof values[keys[i]] === "number") // use forward entries only
  1894. this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];
  1895. }
  1896. /**
  1897. * Enum descriptor.
  1898. * @interface IEnum
  1899. * @property {Object.<string,number>} values Enum values
  1900. * @property {Object.<string,*>} [options] Enum options
  1901. */
  1902. /**
  1903. * Constructs an enum from an enum descriptor.
  1904. * @param {string} name Enum name
  1905. * @param {IEnum} json Enum descriptor
  1906. * @returns {Enum} Created enum
  1907. * @throws {TypeError} If arguments are invalid
  1908. */
  1909. Enum.fromJSON = function fromJSON(name, json) {
  1910. var enm = new Enum(name, json.values, json.options, json.comment, json.comments);
  1911. enm.reserved = json.reserved;
  1912. return enm;
  1913. };
  1914. /**
  1915. * Converts this enum to an enum descriptor.
  1916. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  1917. * @returns {IEnum} Enum descriptor
  1918. */
  1919. Enum.prototype.toJSON = function toJSON(toJSONOptions) {
  1920. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  1921. return util.toObject([
  1922. "options" , this.options,
  1923. "values" , this.values,
  1924. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  1925. "comment" , keepComments ? this.comment : undefined,
  1926. "comments" , keepComments ? this.comments : undefined
  1927. ]);
  1928. };
  1929. /**
  1930. * Adds a value to this enum.
  1931. * @param {string} name Value name
  1932. * @param {number} id Value id
  1933. * @param {string} [comment] Comment, if any
  1934. * @returns {Enum} `this`
  1935. * @throws {TypeError} If arguments are invalid
  1936. * @throws {Error} If there is already a value with this name or id
  1937. */
  1938. Enum.prototype.add = function add(name, id, comment) {
  1939. // utilized by the parser but not by .fromJSON
  1940. if (!util.isString(name))
  1941. throw TypeError("name must be a string");
  1942. if (!util.isInteger(id))
  1943. throw TypeError("id must be an integer");
  1944. if (this.values[name] !== undefined)
  1945. throw Error("duplicate name '" + name + "' in " + this);
  1946. if (this.isReservedId(id))
  1947. throw Error("id " + id + " is reserved in " + this);
  1948. if (this.isReservedName(name))
  1949. throw Error("name '" + name + "' is reserved in " + this);
  1950. if (this.valuesById[id] !== undefined) {
  1951. if (!(this.options && this.options.allow_alias))
  1952. throw Error("duplicate id " + id + " in " + this);
  1953. this.values[name] = id;
  1954. } else
  1955. this.valuesById[this.values[name] = id] = name;
  1956. this.comments[name] = comment || null;
  1957. return this;
  1958. };
  1959. /**
  1960. * Removes a value from this enum
  1961. * @param {string} name Value name
  1962. * @returns {Enum} `this`
  1963. * @throws {TypeError} If arguments are invalid
  1964. * @throws {Error} If `name` is not a name of this enum
  1965. */
  1966. Enum.prototype.remove = function remove(name) {
  1967. if (!util.isString(name))
  1968. throw TypeError("name must be a string");
  1969. var val = this.values[name];
  1970. if (val == null)
  1971. throw Error("name '" + name + "' does not exist in " + this);
  1972. delete this.valuesById[val];
  1973. delete this.values[name];
  1974. delete this.comments[name];
  1975. return this;
  1976. };
  1977. /**
  1978. * Tests if the specified id is reserved.
  1979. * @param {number} id Id to test
  1980. * @returns {boolean} `true` if reserved, otherwise `false`
  1981. */
  1982. Enum.prototype.isReservedId = function isReservedId(id) {
  1983. return Namespace.isReservedId(this.reserved, id);
  1984. };
  1985. /**
  1986. * Tests if the specified name is reserved.
  1987. * @param {string} name Name to test
  1988. * @returns {boolean} `true` if reserved, otherwise `false`
  1989. */
  1990. Enum.prototype.isReservedName = function isReservedName(name) {
  1991. return Namespace.isReservedName(this.reserved, name);
  1992. };
  1993. },{"23":23,"24":24,"37":37}],16:[function(require,module,exports){
  1994. "use strict";
  1995. module.exports = Field;
  1996. // extends ReflectionObject
  1997. var ReflectionObject = require(24);
  1998. ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
  1999. var Enum = require(15),
  2000. types = require(36),
  2001. util = require(37);
  2002. var Type; // cyclic
  2003. var ruleRe = /^required|optional|repeated$/;
  2004. /**
  2005. * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
  2006. * @name Field
  2007. * @classdesc Reflected message field.
  2008. * @extends FieldBase
  2009. * @constructor
  2010. * @param {string} name Unique name within its namespace
  2011. * @param {number} id Unique id within its namespace
  2012. * @param {string} type Value type
  2013. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  2014. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  2015. * @param {Object.<string,*>} [options] Declared options
  2016. */
  2017. /**
  2018. * Constructs a field from a field descriptor.
  2019. * @param {string} name Field name
  2020. * @param {IField} json Field descriptor
  2021. * @returns {Field} Created field
  2022. * @throws {TypeError} If arguments are invalid
  2023. */
  2024. Field.fromJSON = function fromJSON(name, json) {
  2025. return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
  2026. };
  2027. /**
  2028. * Not an actual constructor. Use {@link Field} instead.
  2029. * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.
  2030. * @exports FieldBase
  2031. * @extends ReflectionObject
  2032. * @constructor
  2033. * @param {string} name Unique name within its namespace
  2034. * @param {number} id Unique id within its namespace
  2035. * @param {string} type Value type
  2036. * @param {string|Object.<string,*>} [rule="optional"] Field rule
  2037. * @param {string|Object.<string,*>} [extend] Extended type if different from parent
  2038. * @param {Object.<string,*>} [options] Declared options
  2039. * @param {string} [comment] Comment associated with this field
  2040. */
  2041. function Field(name, id, type, rule, extend, options, comment) {
  2042. if (util.isObject(rule)) {
  2043. comment = extend;
  2044. options = rule;
  2045. rule = extend = undefined;
  2046. } else if (util.isObject(extend)) {
  2047. comment = options;
  2048. options = extend;
  2049. extend = undefined;
  2050. }
  2051. ReflectionObject.call(this, name, options);
  2052. if (!util.isInteger(id) || id < 0)
  2053. throw TypeError("id must be a non-negative integer");
  2054. if (!util.isString(type))
  2055. throw TypeError("type must be a string");
  2056. if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))
  2057. throw TypeError("rule must be a string rule");
  2058. if (extend !== undefined && !util.isString(extend))
  2059. throw TypeError("extend must be a string");
  2060. /**
  2061. * Field rule, if any.
  2062. * @type {string|undefined}
  2063. */
  2064. if (rule === "proto3_optional") {
  2065. rule = "optional";
  2066. }
  2067. this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON
  2068. /**
  2069. * Field type.
  2070. * @type {string}
  2071. */
  2072. this.type = type; // toJSON
  2073. /**
  2074. * Unique field id.
  2075. * @type {number}
  2076. */
  2077. this.id = id; // toJSON, marker
  2078. /**
  2079. * Extended type if different from parent.
  2080. * @type {string|undefined}
  2081. */
  2082. this.extend = extend || undefined; // toJSON
  2083. /**
  2084. * Whether this field is required.
  2085. * @type {boolean}
  2086. */
  2087. this.required = rule === "required";
  2088. /**
  2089. * Whether this field is optional.
  2090. * @type {boolean}
  2091. */
  2092. this.optional = !this.required;
  2093. /**
  2094. * Whether this field is repeated.
  2095. * @type {boolean}
  2096. */
  2097. this.repeated = rule === "repeated";
  2098. /**
  2099. * Whether this field is a map or not.
  2100. * @type {boolean}
  2101. */
  2102. this.map = false;
  2103. /**
  2104. * Message this field belongs to.
  2105. * @type {Type|null}
  2106. */
  2107. this.message = null;
  2108. /**
  2109. * OneOf this field belongs to, if any,
  2110. * @type {OneOf|null}
  2111. */
  2112. this.partOf = null;
  2113. /**
  2114. * The field type's default value.
  2115. * @type {*}
  2116. */
  2117. this.typeDefault = null;
  2118. /**
  2119. * The field's default value on prototypes.
  2120. * @type {*}
  2121. */
  2122. this.defaultValue = null;
  2123. /**
  2124. * Whether this field's value should be treated as a long.
  2125. * @type {boolean}
  2126. */
  2127. this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;
  2128. /**
  2129. * Whether this field's value is a buffer.
  2130. * @type {boolean}
  2131. */
  2132. this.bytes = type === "bytes";
  2133. /**
  2134. * Resolved type if not a basic type.
  2135. * @type {Type|Enum|null}
  2136. */
  2137. this.resolvedType = null;
  2138. /**
  2139. * Sister-field within the extended type if a declaring extension field.
  2140. * @type {Field|null}
  2141. */
  2142. this.extensionField = null;
  2143. /**
  2144. * Sister-field within the declaring namespace if an extended field.
  2145. * @type {Field|null}
  2146. */
  2147. this.declaringField = null;
  2148. /**
  2149. * Internally remembers whether this field is packed.
  2150. * @type {boolean|null}
  2151. * @private
  2152. */
  2153. this._packed = null;
  2154. /**
  2155. * Comment for this field.
  2156. * @type {string|null}
  2157. */
  2158. this.comment = comment;
  2159. }
  2160. /**
  2161. * Determines whether this field is packed. Only relevant when repeated and working with proto2.
  2162. * @name Field#packed
  2163. * @type {boolean}
  2164. * @readonly
  2165. */
  2166. Object.defineProperty(Field.prototype, "packed", {
  2167. get: function() {
  2168. // defaults to packed=true if not explicity set to false
  2169. if (this._packed === null)
  2170. this._packed = this.getOption("packed") !== false;
  2171. return this._packed;
  2172. }
  2173. });
  2174. /**
  2175. * @override
  2176. */
  2177. Field.prototype.setOption = function setOption(name, value, ifNotSet) {
  2178. if (name === "packed") // clear cached before setting
  2179. this._packed = null;
  2180. return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
  2181. };
  2182. /**
  2183. * Field descriptor.
  2184. * @interface IField
  2185. * @property {string} [rule="optional"] Field rule
  2186. * @property {string} type Field type
  2187. * @property {number} id Field id
  2188. * @property {Object.<string,*>} [options] Field options
  2189. */
  2190. /**
  2191. * Extension field descriptor.
  2192. * @interface IExtensionField
  2193. * @extends IField
  2194. * @property {string} extend Extended type
  2195. */
  2196. /**
  2197. * Converts this field to a field descriptor.
  2198. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2199. * @returns {IField} Field descriptor
  2200. */
  2201. Field.prototype.toJSON = function toJSON(toJSONOptions) {
  2202. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2203. return util.toObject([
  2204. "rule" , this.rule !== "optional" && this.rule || undefined,
  2205. "type" , this.type,
  2206. "id" , this.id,
  2207. "extend" , this.extend,
  2208. "options" , this.options,
  2209. "comment" , keepComments ? this.comment : undefined
  2210. ]);
  2211. };
  2212. /**
  2213. * Resolves this field's type references.
  2214. * @returns {Field} `this`
  2215. * @throws {Error} If any reference cannot be resolved
  2216. */
  2217. Field.prototype.resolve = function resolve() {
  2218. if (this.resolved)
  2219. return this;
  2220. if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it
  2221. this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
  2222. if (this.resolvedType instanceof Type)
  2223. this.typeDefault = null;
  2224. else // instanceof Enum
  2225. this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined
  2226. }
  2227. // use explicitly set default value if present
  2228. if (this.options && this.options["default"] != null) {
  2229. this.typeDefault = this.options["default"];
  2230. if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
  2231. this.typeDefault = this.resolvedType.values[this.typeDefault];
  2232. }
  2233. // remove unnecessary options
  2234. if (this.options) {
  2235. if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))
  2236. delete this.options.packed;
  2237. if (!Object.keys(this.options).length)
  2238. this.options = undefined;
  2239. }
  2240. // convert to internal data type if necesssary
  2241. if (this.long) {
  2242. this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");
  2243. /* istanbul ignore else */
  2244. if (Object.freeze)
  2245. Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)
  2246. } else if (this.bytes && typeof this.typeDefault === "string") {
  2247. var buf;
  2248. if (util.base64.test(this.typeDefault))
  2249. util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);
  2250. else
  2251. util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);
  2252. this.typeDefault = buf;
  2253. }
  2254. // take special care of maps and repeated fields
  2255. if (this.map)
  2256. this.defaultValue = util.emptyObject;
  2257. else if (this.repeated)
  2258. this.defaultValue = util.emptyArray;
  2259. else
  2260. this.defaultValue = this.typeDefault;
  2261. // ensure proper value on prototype
  2262. if (this.parent instanceof Type)
  2263. this.parent.ctor.prototype[this.name] = this.defaultValue;
  2264. return ReflectionObject.prototype.resolve.call(this);
  2265. };
  2266. /**
  2267. * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
  2268. * @typedef FieldDecorator
  2269. * @type {function}
  2270. * @param {Object} prototype Target prototype
  2271. * @param {string} fieldName Field name
  2272. * @returns {undefined}
  2273. */
  2274. /**
  2275. * Field decorator (TypeScript).
  2276. * @name Field.d
  2277. * @function
  2278. * @param {number} fieldId Field id
  2279. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type
  2280. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  2281. * @param {T} [defaultValue] Default value
  2282. * @returns {FieldDecorator} Decorator function
  2283. * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]
  2284. */
  2285. Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
  2286. // submessage: decorate the submessage and use its name as the type
  2287. if (typeof fieldType === "function")
  2288. fieldType = util.decorateType(fieldType).name;
  2289. // enum reference: create a reflected copy of the enum and keep reuseing it
  2290. else if (fieldType && typeof fieldType === "object")
  2291. fieldType = util.decorateEnum(fieldType).name;
  2292. return function fieldDecorator(prototype, fieldName) {
  2293. util.decorateType(prototype.constructor)
  2294. .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
  2295. };
  2296. };
  2297. /**
  2298. * Field decorator (TypeScript).
  2299. * @name Field.d
  2300. * @function
  2301. * @param {number} fieldId Field id
  2302. * @param {Constructor<T>|string} fieldType Field type
  2303. * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
  2304. * @returns {FieldDecorator} Decorator function
  2305. * @template T extends Message<T>
  2306. * @variation 2
  2307. */
  2308. // like Field.d but without a default value
  2309. // Sets up cyclic dependencies (called in index-light)
  2310. Field._configure = function configure(Type_) {
  2311. Type = Type_;
  2312. };
  2313. },{"15":15,"24":24,"36":36,"37":37}],17:[function(require,module,exports){
  2314. "use strict";
  2315. var protobuf = module.exports = require(18);
  2316. protobuf.build = "light";
  2317. /**
  2318. * A node-style callback as used by {@link load} and {@link Root#load}.
  2319. * @typedef LoadCallback
  2320. * @type {function}
  2321. * @param {Error|null} error Error, if any, otherwise `null`
  2322. * @param {Root} [root] Root, if there hasn't been an error
  2323. * @returns {undefined}
  2324. */
  2325. /**
  2326. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  2327. * @param {string|string[]} filename One or multiple files to load
  2328. * @param {Root} root Root namespace, defaults to create a new one if omitted.
  2329. * @param {LoadCallback} callback Callback function
  2330. * @returns {undefined}
  2331. * @see {@link Root#load}
  2332. */
  2333. function load(filename, root, callback) {
  2334. if (typeof root === "function") {
  2335. callback = root;
  2336. root = new protobuf.Root();
  2337. } else if (!root)
  2338. root = new protobuf.Root();
  2339. return root.load(filename, callback);
  2340. }
  2341. /**
  2342. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
  2343. * @name load
  2344. * @function
  2345. * @param {string|string[]} filename One or multiple files to load
  2346. * @param {LoadCallback} callback Callback function
  2347. * @returns {undefined}
  2348. * @see {@link Root#load}
  2349. * @variation 2
  2350. */
  2351. // function load(filename:string, callback:LoadCallback):undefined
  2352. /**
  2353. * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
  2354. * @name load
  2355. * @function
  2356. * @param {string|string[]} filename One or multiple files to load
  2357. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  2358. * @returns {Promise<Root>} Promise
  2359. * @see {@link Root#load}
  2360. * @variation 3
  2361. */
  2362. // function load(filename:string, [root:Root]):Promise<Root>
  2363. protobuf.load = load;
  2364. /**
  2365. * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
  2366. * @param {string|string[]} filename One or multiple files to load
  2367. * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
  2368. * @returns {Root} Root namespace
  2369. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  2370. * @see {@link Root#loadSync}
  2371. */
  2372. function loadSync(filename, root) {
  2373. if (!root)
  2374. root = new protobuf.Root();
  2375. return root.loadSync(filename);
  2376. }
  2377. protobuf.loadSync = loadSync;
  2378. // Serialization
  2379. protobuf.encoder = require(14);
  2380. protobuf.decoder = require(13);
  2381. protobuf.verifier = require(40);
  2382. protobuf.converter = require(12);
  2383. // Reflection
  2384. protobuf.ReflectionObject = require(24);
  2385. protobuf.Namespace = require(23);
  2386. protobuf.Root = require(29);
  2387. protobuf.Enum = require(15);
  2388. protobuf.Type = require(35);
  2389. protobuf.Field = require(16);
  2390. protobuf.OneOf = require(25);
  2391. protobuf.MapField = require(20);
  2392. protobuf.Service = require(33);
  2393. protobuf.Method = require(22);
  2394. // Runtime
  2395. protobuf.Message = require(21);
  2396. protobuf.wrappers = require(41);
  2397. // Utility
  2398. protobuf.types = require(36);
  2399. protobuf.util = require(37);
  2400. // Set up possibly cyclic reflection dependencies
  2401. protobuf.ReflectionObject._configure(protobuf.Root);
  2402. protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);
  2403. protobuf.Root._configure(protobuf.Type);
  2404. protobuf.Field._configure(protobuf.Type);
  2405. },{"12":12,"13":13,"14":14,"15":15,"16":16,"18":18,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"29":29,"33":33,"35":35,"36":36,"37":37,"40":40,"41":41}],18:[function(require,module,exports){
  2406. "use strict";
  2407. var protobuf = exports;
  2408. /**
  2409. * Build type, one of `"full"`, `"light"` or `"minimal"`.
  2410. * @name build
  2411. * @type {string}
  2412. * @const
  2413. */
  2414. protobuf.build = "minimal";
  2415. // Serialization
  2416. protobuf.Writer = require(42);
  2417. protobuf.BufferWriter = require(43);
  2418. protobuf.Reader = require(27);
  2419. protobuf.BufferReader = require(28);
  2420. // Utility
  2421. protobuf.util = require(39);
  2422. protobuf.rpc = require(31);
  2423. protobuf.roots = require(30);
  2424. protobuf.configure = configure;
  2425. /* istanbul ignore next */
  2426. /**
  2427. * Reconfigures the library according to the environment.
  2428. * @returns {undefined}
  2429. */
  2430. function configure() {
  2431. protobuf.util._configure();
  2432. protobuf.Writer._configure(protobuf.BufferWriter);
  2433. protobuf.Reader._configure(protobuf.BufferReader);
  2434. }
  2435. // Set up buffer utility according to the environment
  2436. configure();
  2437. },{"27":27,"28":28,"30":30,"31":31,"39":39,"42":42,"43":43}],19:[function(require,module,exports){
  2438. "use strict";
  2439. var protobuf = module.exports = require(17);
  2440. protobuf.build = "full";
  2441. // Parser
  2442. protobuf.tokenize = require(34);
  2443. protobuf.parse = require(26);
  2444. protobuf.common = require(11);
  2445. // Configure parser
  2446. protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);
  2447. },{"11":11,"17":17,"26":26,"34":34}],20:[function(require,module,exports){
  2448. "use strict";
  2449. module.exports = MapField;
  2450. // extends Field
  2451. var Field = require(16);
  2452. ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
  2453. var types = require(36),
  2454. util = require(37);
  2455. /**
  2456. * Constructs a new map field instance.
  2457. * @classdesc Reflected map field.
  2458. * @extends FieldBase
  2459. * @constructor
  2460. * @param {string} name Unique name within its namespace
  2461. * @param {number} id Unique id within its namespace
  2462. * @param {string} keyType Key type
  2463. * @param {string} type Value type
  2464. * @param {Object.<string,*>} [options] Declared options
  2465. * @param {string} [comment] Comment associated with this field
  2466. */
  2467. function MapField(name, id, keyType, type, options, comment) {
  2468. Field.call(this, name, id, type, undefined, undefined, options, comment);
  2469. /* istanbul ignore if */
  2470. if (!util.isString(keyType))
  2471. throw TypeError("keyType must be a string");
  2472. /**
  2473. * Key type.
  2474. * @type {string}
  2475. */
  2476. this.keyType = keyType; // toJSON, marker
  2477. /**
  2478. * Resolved key type if not a basic type.
  2479. * @type {ReflectionObject|null}
  2480. */
  2481. this.resolvedKeyType = null;
  2482. // Overrides Field#map
  2483. this.map = true;
  2484. }
  2485. /**
  2486. * Map field descriptor.
  2487. * @interface IMapField
  2488. * @extends {IField}
  2489. * @property {string} keyType Key type
  2490. */
  2491. /**
  2492. * Extension map field descriptor.
  2493. * @interface IExtensionMapField
  2494. * @extends IMapField
  2495. * @property {string} extend Extended type
  2496. */
  2497. /**
  2498. * Constructs a map field from a map field descriptor.
  2499. * @param {string} name Field name
  2500. * @param {IMapField} json Map field descriptor
  2501. * @returns {MapField} Created map field
  2502. * @throws {TypeError} If arguments are invalid
  2503. */
  2504. MapField.fromJSON = function fromJSON(name, json) {
  2505. return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);
  2506. };
  2507. /**
  2508. * Converts this map field to a map field descriptor.
  2509. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2510. * @returns {IMapField} Map field descriptor
  2511. */
  2512. MapField.prototype.toJSON = function toJSON(toJSONOptions) {
  2513. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2514. return util.toObject([
  2515. "keyType" , this.keyType,
  2516. "type" , this.type,
  2517. "id" , this.id,
  2518. "extend" , this.extend,
  2519. "options" , this.options,
  2520. "comment" , keepComments ? this.comment : undefined
  2521. ]);
  2522. };
  2523. /**
  2524. * @override
  2525. */
  2526. MapField.prototype.resolve = function resolve() {
  2527. if (this.resolved)
  2528. return this;
  2529. // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
  2530. if (types.mapKey[this.keyType] === undefined)
  2531. throw Error("invalid key type: " + this.keyType);
  2532. return Field.prototype.resolve.call(this);
  2533. };
  2534. /**
  2535. * Map field decorator (TypeScript).
  2536. * @name MapField.d
  2537. * @function
  2538. * @param {number} fieldId Field id
  2539. * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
  2540. * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
  2541. * @returns {FieldDecorator} Decorator function
  2542. * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
  2543. */
  2544. MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
  2545. // submessage value: decorate the submessage and use its name as the type
  2546. if (typeof fieldValueType === "function")
  2547. fieldValueType = util.decorateType(fieldValueType).name;
  2548. // enum reference value: create a reflected copy of the enum and keep reuseing it
  2549. else if (fieldValueType && typeof fieldValueType === "object")
  2550. fieldValueType = util.decorateEnum(fieldValueType).name;
  2551. return function mapFieldDecorator(prototype, fieldName) {
  2552. util.decorateType(prototype.constructor)
  2553. .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
  2554. };
  2555. };
  2556. },{"16":16,"36":36,"37":37}],21:[function(require,module,exports){
  2557. "use strict";
  2558. module.exports = Message;
  2559. var util = require(39);
  2560. /**
  2561. * Constructs a new message instance.
  2562. * @classdesc Abstract runtime message.
  2563. * @constructor
  2564. * @param {Properties<T>} [properties] Properties to set
  2565. * @template T extends object = object
  2566. */
  2567. function Message(properties) {
  2568. // not used internally
  2569. if (properties)
  2570. for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
  2571. this[keys[i]] = properties[keys[i]];
  2572. }
  2573. /**
  2574. * Reference to the reflected type.
  2575. * @name Message.$type
  2576. * @type {Type}
  2577. * @readonly
  2578. */
  2579. /**
  2580. * Reference to the reflected type.
  2581. * @name Message#$type
  2582. * @type {Type}
  2583. * @readonly
  2584. */
  2585. /*eslint-disable valid-jsdoc*/
  2586. /**
  2587. * Creates a new message of this type using the specified properties.
  2588. * @param {Object.<string,*>} [properties] Properties to set
  2589. * @returns {Message<T>} Message instance
  2590. * @template T extends Message<T>
  2591. * @this Constructor<T>
  2592. */
  2593. Message.create = function create(properties) {
  2594. return this.$type.create(properties);
  2595. };
  2596. /**
  2597. * Encodes a message of this type.
  2598. * @param {T|Object.<string,*>} message Message to encode
  2599. * @param {Writer} [writer] Writer to use
  2600. * @returns {Writer} Writer
  2601. * @template T extends Message<T>
  2602. * @this Constructor<T>
  2603. */
  2604. Message.encode = function encode(message, writer) {
  2605. return this.$type.encode(message, writer);
  2606. };
  2607. /**
  2608. * Encodes a message of this type preceeded by its length as a varint.
  2609. * @param {T|Object.<string,*>} message Message to encode
  2610. * @param {Writer} [writer] Writer to use
  2611. * @returns {Writer} Writer
  2612. * @template T extends Message<T>
  2613. * @this Constructor<T>
  2614. */
  2615. Message.encodeDelimited = function encodeDelimited(message, writer) {
  2616. return this.$type.encodeDelimited(message, writer);
  2617. };
  2618. /**
  2619. * Decodes a message of this type.
  2620. * @name Message.decode
  2621. * @function
  2622. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  2623. * @returns {T} Decoded message
  2624. * @template T extends Message<T>
  2625. * @this Constructor<T>
  2626. */
  2627. Message.decode = function decode(reader) {
  2628. return this.$type.decode(reader);
  2629. };
  2630. /**
  2631. * Decodes a message of this type preceeded by its length as a varint.
  2632. * @name Message.decodeDelimited
  2633. * @function
  2634. * @param {Reader|Uint8Array} reader Reader or buffer to decode
  2635. * @returns {T} Decoded message
  2636. * @template T extends Message<T>
  2637. * @this Constructor<T>
  2638. */
  2639. Message.decodeDelimited = function decodeDelimited(reader) {
  2640. return this.$type.decodeDelimited(reader);
  2641. };
  2642. /**
  2643. * Verifies a message of this type.
  2644. * @name Message.verify
  2645. * @function
  2646. * @param {Object.<string,*>} message Plain object to verify
  2647. * @returns {string|null} `null` if valid, otherwise the reason why it is not
  2648. */
  2649. Message.verify = function verify(message) {
  2650. return this.$type.verify(message);
  2651. };
  2652. /**
  2653. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  2654. * @param {Object.<string,*>} object Plain object
  2655. * @returns {T} Message instance
  2656. * @template T extends Message<T>
  2657. * @this Constructor<T>
  2658. */
  2659. Message.fromObject = function fromObject(object) {
  2660. return this.$type.fromObject(object);
  2661. };
  2662. /**
  2663. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  2664. * @param {T} message Message instance
  2665. * @param {IConversionOptions} [options] Conversion options
  2666. * @returns {Object.<string,*>} Plain object
  2667. * @template T extends Message<T>
  2668. * @this Constructor<T>
  2669. */
  2670. Message.toObject = function toObject(message, options) {
  2671. return this.$type.toObject(message, options);
  2672. };
  2673. /**
  2674. * Converts this message to JSON.
  2675. * @returns {Object.<string,*>} JSON object
  2676. */
  2677. Message.prototype.toJSON = function toJSON() {
  2678. return this.$type.toObject(this, util.toJSONOptions);
  2679. };
  2680. /*eslint-enable valid-jsdoc*/
  2681. },{"39":39}],22:[function(require,module,exports){
  2682. "use strict";
  2683. module.exports = Method;
  2684. // extends ReflectionObject
  2685. var ReflectionObject = require(24);
  2686. ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
  2687. var util = require(37);
  2688. /**
  2689. * Constructs a new service method instance.
  2690. * @classdesc Reflected service method.
  2691. * @extends ReflectionObject
  2692. * @constructor
  2693. * @param {string} name Method name
  2694. * @param {string|undefined} type Method type, usually `"rpc"`
  2695. * @param {string} requestType Request message type
  2696. * @param {string} responseType Response message type
  2697. * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed
  2698. * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed
  2699. * @param {Object.<string,*>} [options] Declared options
  2700. * @param {string} [comment] The comment for this method
  2701. * @param {Object.<string,*>} [parsedOptions] Declared options, properly parsed into an object
  2702. */
  2703. function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {
  2704. /* istanbul ignore next */
  2705. if (util.isObject(requestStream)) {
  2706. options = requestStream;
  2707. requestStream = responseStream = undefined;
  2708. } else if (util.isObject(responseStream)) {
  2709. options = responseStream;
  2710. responseStream = undefined;
  2711. }
  2712. /* istanbul ignore if */
  2713. if (!(type === undefined || util.isString(type)))
  2714. throw TypeError("type must be a string");
  2715. /* istanbul ignore if */
  2716. if (!util.isString(requestType))
  2717. throw TypeError("requestType must be a string");
  2718. /* istanbul ignore if */
  2719. if (!util.isString(responseType))
  2720. throw TypeError("responseType must be a string");
  2721. ReflectionObject.call(this, name, options);
  2722. /**
  2723. * Method type.
  2724. * @type {string}
  2725. */
  2726. this.type = type || "rpc"; // toJSON
  2727. /**
  2728. * Request type.
  2729. * @type {string}
  2730. */
  2731. this.requestType = requestType; // toJSON, marker
  2732. /**
  2733. * Whether requests are streamed or not.
  2734. * @type {boolean|undefined}
  2735. */
  2736. this.requestStream = requestStream ? true : undefined; // toJSON
  2737. /**
  2738. * Response type.
  2739. * @type {string}
  2740. */
  2741. this.responseType = responseType; // toJSON
  2742. /**
  2743. * Whether responses are streamed or not.
  2744. * @type {boolean|undefined}
  2745. */
  2746. this.responseStream = responseStream ? true : undefined; // toJSON
  2747. /**
  2748. * Resolved request type.
  2749. * @type {Type|null}
  2750. */
  2751. this.resolvedRequestType = null;
  2752. /**
  2753. * Resolved response type.
  2754. * @type {Type|null}
  2755. */
  2756. this.resolvedResponseType = null;
  2757. /**
  2758. * Comment for this method
  2759. * @type {string|null}
  2760. */
  2761. this.comment = comment;
  2762. /**
  2763. * Options properly parsed into an object
  2764. */
  2765. this.parsedOptions = parsedOptions;
  2766. }
  2767. /**
  2768. * Method descriptor.
  2769. * @interface IMethod
  2770. * @property {string} [type="rpc"] Method type
  2771. * @property {string} requestType Request type
  2772. * @property {string} responseType Response type
  2773. * @property {boolean} [requestStream=false] Whether requests are streamed
  2774. * @property {boolean} [responseStream=false] Whether responses are streamed
  2775. * @property {Object.<string,*>} [options] Method options
  2776. * @property {string} comment Method comments
  2777. * @property {Object.<string,*>} [parsedOptions] Method options properly parsed into an object
  2778. */
  2779. /**
  2780. * Constructs a method from a method descriptor.
  2781. * @param {string} name Method name
  2782. * @param {IMethod} json Method descriptor
  2783. * @returns {Method} Created method
  2784. * @throws {TypeError} If arguments are invalid
  2785. */
  2786. Method.fromJSON = function fromJSON(name, json) {
  2787. return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);
  2788. };
  2789. /**
  2790. * Converts this method to a method descriptor.
  2791. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2792. * @returns {IMethod} Method descriptor
  2793. */
  2794. Method.prototype.toJSON = function toJSON(toJSONOptions) {
  2795. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  2796. return util.toObject([
  2797. "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,
  2798. "requestType" , this.requestType,
  2799. "requestStream" , this.requestStream,
  2800. "responseType" , this.responseType,
  2801. "responseStream" , this.responseStream,
  2802. "options" , this.options,
  2803. "comment" , keepComments ? this.comment : undefined,
  2804. "parsedOptions" , this.parsedOptions,
  2805. ]);
  2806. };
  2807. /**
  2808. * @override
  2809. */
  2810. Method.prototype.resolve = function resolve() {
  2811. /* istanbul ignore if */
  2812. if (this.resolved)
  2813. return this;
  2814. this.resolvedRequestType = this.parent.lookupType(this.requestType);
  2815. this.resolvedResponseType = this.parent.lookupType(this.responseType);
  2816. return ReflectionObject.prototype.resolve.call(this);
  2817. };
  2818. },{"24":24,"37":37}],23:[function(require,module,exports){
  2819. "use strict";
  2820. module.exports = Namespace;
  2821. // extends ReflectionObject
  2822. var ReflectionObject = require(24);
  2823. ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
  2824. var Field = require(16),
  2825. util = require(37);
  2826. var Type, // cyclic
  2827. Service,
  2828. Enum;
  2829. /**
  2830. * Constructs a new namespace instance.
  2831. * @name Namespace
  2832. * @classdesc Reflected namespace.
  2833. * @extends NamespaceBase
  2834. * @constructor
  2835. * @param {string} name Namespace name
  2836. * @param {Object.<string,*>} [options] Declared options
  2837. */
  2838. /**
  2839. * Constructs a namespace from JSON.
  2840. * @memberof Namespace
  2841. * @function
  2842. * @param {string} name Namespace name
  2843. * @param {Object.<string,*>} json JSON object
  2844. * @returns {Namespace} Created namespace
  2845. * @throws {TypeError} If arguments are invalid
  2846. */
  2847. Namespace.fromJSON = function fromJSON(name, json) {
  2848. return new Namespace(name, json.options).addJSON(json.nested);
  2849. };
  2850. /**
  2851. * Converts an array of reflection objects to JSON.
  2852. * @memberof Namespace
  2853. * @param {ReflectionObject[]} array Object array
  2854. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2855. * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty
  2856. */
  2857. function arrayToJSON(array, toJSONOptions) {
  2858. if (!(array && array.length))
  2859. return undefined;
  2860. var obj = {};
  2861. for (var i = 0; i < array.length; ++i)
  2862. obj[array[i].name] = array[i].toJSON(toJSONOptions);
  2863. return obj;
  2864. }
  2865. Namespace.arrayToJSON = arrayToJSON;
  2866. /**
  2867. * Tests if the specified id is reserved.
  2868. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2869. * @param {number} id Id to test
  2870. * @returns {boolean} `true` if reserved, otherwise `false`
  2871. */
  2872. Namespace.isReservedId = function isReservedId(reserved, id) {
  2873. if (reserved)
  2874. for (var i = 0; i < reserved.length; ++i)
  2875. if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id)
  2876. return true;
  2877. return false;
  2878. };
  2879. /**
  2880. * Tests if the specified name is reserved.
  2881. * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
  2882. * @param {string} name Name to test
  2883. * @returns {boolean} `true` if reserved, otherwise `false`
  2884. */
  2885. Namespace.isReservedName = function isReservedName(reserved, name) {
  2886. if (reserved)
  2887. for (var i = 0; i < reserved.length; ++i)
  2888. if (reserved[i] === name)
  2889. return true;
  2890. return false;
  2891. };
  2892. /**
  2893. * Not an actual constructor. Use {@link Namespace} instead.
  2894. * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.
  2895. * @exports NamespaceBase
  2896. * @extends ReflectionObject
  2897. * @abstract
  2898. * @constructor
  2899. * @param {string} name Namespace name
  2900. * @param {Object.<string,*>} [options] Declared options
  2901. * @see {@link Namespace}
  2902. */
  2903. function Namespace(name, options) {
  2904. ReflectionObject.call(this, name, options);
  2905. /**
  2906. * Nested objects by name.
  2907. * @type {Object.<string,ReflectionObject>|undefined}
  2908. */
  2909. this.nested = undefined; // toJSON
  2910. /**
  2911. * Cached nested objects as an array.
  2912. * @type {ReflectionObject[]|null}
  2913. * @private
  2914. */
  2915. this._nestedArray = null;
  2916. }
  2917. function clearCache(namespace) {
  2918. namespace._nestedArray = null;
  2919. return namespace;
  2920. }
  2921. /**
  2922. * Nested objects of this namespace as an array for iteration.
  2923. * @name NamespaceBase#nestedArray
  2924. * @type {ReflectionObject[]}
  2925. * @readonly
  2926. */
  2927. Object.defineProperty(Namespace.prototype, "nestedArray", {
  2928. get: function() {
  2929. return this._nestedArray || (this._nestedArray = util.toArray(this.nested));
  2930. }
  2931. });
  2932. /**
  2933. * Namespace descriptor.
  2934. * @interface INamespace
  2935. * @property {Object.<string,*>} [options] Namespace options
  2936. * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors
  2937. */
  2938. /**
  2939. * Any extension field descriptor.
  2940. * @typedef AnyExtensionField
  2941. * @type {IExtensionField|IExtensionMapField}
  2942. */
  2943. /**
  2944. * Any nested object descriptor.
  2945. * @typedef AnyNestedObject
  2946. * @type {IEnum|IType|IService|AnyExtensionField|INamespace}
  2947. */
  2948. // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)
  2949. /**
  2950. * Converts this namespace to a namespace descriptor.
  2951. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  2952. * @returns {INamespace} Namespace descriptor
  2953. */
  2954. Namespace.prototype.toJSON = function toJSON(toJSONOptions) {
  2955. return util.toObject([
  2956. "options" , this.options,
  2957. "nested" , arrayToJSON(this.nestedArray, toJSONOptions)
  2958. ]);
  2959. };
  2960. /**
  2961. * Adds nested objects to this namespace from nested object descriptors.
  2962. * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors
  2963. * @returns {Namespace} `this`
  2964. */
  2965. Namespace.prototype.addJSON = function addJSON(nestedJson) {
  2966. var ns = this;
  2967. /* istanbul ignore else */
  2968. if (nestedJson) {
  2969. for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
  2970. nested = nestedJson[names[i]];
  2971. ns.add( // most to least likely
  2972. ( nested.fields !== undefined
  2973. ? Type.fromJSON
  2974. : nested.values !== undefined
  2975. ? Enum.fromJSON
  2976. : nested.methods !== undefined
  2977. ? Service.fromJSON
  2978. : nested.id !== undefined
  2979. ? Field.fromJSON
  2980. : Namespace.fromJSON )(names[i], nested)
  2981. );
  2982. }
  2983. }
  2984. return this;
  2985. };
  2986. /**
  2987. * Gets the nested object of the specified name.
  2988. * @param {string} name Nested object name
  2989. * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist
  2990. */
  2991. Namespace.prototype.get = function get(name) {
  2992. return this.nested && this.nested[name]
  2993. || null;
  2994. };
  2995. /**
  2996. * Gets the values of the nested {@link Enum|enum} of the specified name.
  2997. * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
  2998. * @param {string} name Nested enum name
  2999. * @returns {Object.<string,number>} Enum values
  3000. * @throws {Error} If there is no such enum
  3001. */
  3002. Namespace.prototype.getEnum = function getEnum(name) {
  3003. if (this.nested && this.nested[name] instanceof Enum)
  3004. return this.nested[name].values;
  3005. throw Error("no such enum: " + name);
  3006. };
  3007. /**
  3008. * Adds a nested object to this namespace.
  3009. * @param {ReflectionObject} object Nested object to add
  3010. * @returns {Namespace} `this`
  3011. * @throws {TypeError} If arguments are invalid
  3012. * @throws {Error} If there is already a nested object with this name
  3013. */
  3014. Namespace.prototype.add = function add(object) {
  3015. if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))
  3016. throw TypeError("object must be a valid nested object");
  3017. if (!this.nested)
  3018. this.nested = {};
  3019. else {
  3020. var prev = this.get(object.name);
  3021. if (prev) {
  3022. if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
  3023. // replace plain namespace but keep existing nested elements and options
  3024. var nested = prev.nestedArray;
  3025. for (var i = 0; i < nested.length; ++i)
  3026. object.add(nested[i]);
  3027. this.remove(prev);
  3028. if (!this.nested)
  3029. this.nested = {};
  3030. object.setOptions(prev.options, true);
  3031. } else
  3032. throw Error("duplicate name '" + object.name + "' in " + this);
  3033. }
  3034. }
  3035. this.nested[object.name] = object;
  3036. object.onAdd(this);
  3037. return clearCache(this);
  3038. };
  3039. /**
  3040. * Removes a nested object from this namespace.
  3041. * @param {ReflectionObject} object Nested object to remove
  3042. * @returns {Namespace} `this`
  3043. * @throws {TypeError} If arguments are invalid
  3044. * @throws {Error} If `object` is not a member of this namespace
  3045. */
  3046. Namespace.prototype.remove = function remove(object) {
  3047. if (!(object instanceof ReflectionObject))
  3048. throw TypeError("object must be a ReflectionObject");
  3049. if (object.parent !== this)
  3050. throw Error(object + " is not a member of " + this);
  3051. delete this.nested[object.name];
  3052. if (!Object.keys(this.nested).length)
  3053. this.nested = undefined;
  3054. object.onRemove(this);
  3055. return clearCache(this);
  3056. };
  3057. /**
  3058. * Defines additial namespaces within this one if not yet existing.
  3059. * @param {string|string[]} path Path to create
  3060. * @param {*} [json] Nested types to create from JSON
  3061. * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty
  3062. */
  3063. Namespace.prototype.define = function define(path, json) {
  3064. if (util.isString(path))
  3065. path = path.split(".");
  3066. else if (!Array.isArray(path))
  3067. throw TypeError("illegal path");
  3068. if (path && path.length && path[0] === "")
  3069. throw Error("path must be relative");
  3070. var ptr = this;
  3071. while (path.length > 0) {
  3072. var part = path.shift();
  3073. if (ptr.nested && ptr.nested[part]) {
  3074. ptr = ptr.nested[part];
  3075. if (!(ptr instanceof Namespace))
  3076. throw Error("path conflicts with non-namespace objects");
  3077. } else
  3078. ptr.add(ptr = new Namespace(part));
  3079. }
  3080. if (json)
  3081. ptr.addJSON(json);
  3082. return ptr;
  3083. };
  3084. /**
  3085. * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
  3086. * @returns {Namespace} `this`
  3087. */
  3088. Namespace.prototype.resolveAll = function resolveAll() {
  3089. var nested = this.nestedArray, i = 0;
  3090. while (i < nested.length)
  3091. if (nested[i] instanceof Namespace)
  3092. nested[i++].resolveAll();
  3093. else
  3094. nested[i++].resolve();
  3095. return this.resolve();
  3096. };
  3097. /**
  3098. * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
  3099. * @param {string|string[]} path Path to look up
  3100. * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
  3101. * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked
  3102. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  3103. */
  3104. Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {
  3105. /* istanbul ignore next */
  3106. if (typeof filterTypes === "boolean") {
  3107. parentAlreadyChecked = filterTypes;
  3108. filterTypes = undefined;
  3109. } else if (filterTypes && !Array.isArray(filterTypes))
  3110. filterTypes = [ filterTypes ];
  3111. if (util.isString(path) && path.length) {
  3112. if (path === ".")
  3113. return this.root;
  3114. path = path.split(".");
  3115. } else if (!path.length)
  3116. return this;
  3117. // Start at root if path is absolute
  3118. if (path[0] === "")
  3119. return this.root.lookup(path.slice(1), filterTypes);
  3120. // Test if the first part matches any nested object, and if so, traverse if path contains more
  3121. var found = this.get(path[0]);
  3122. if (found) {
  3123. if (path.length === 1) {
  3124. if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)
  3125. return found;
  3126. } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))
  3127. return found;
  3128. // Otherwise try each nested namespace
  3129. } else
  3130. for (var i = 0; i < this.nestedArray.length; ++i)
  3131. if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))
  3132. return found;
  3133. // If there hasn't been a match, try again at the parent
  3134. if (this.parent === null || parentAlreadyChecked)
  3135. return null;
  3136. return this.parent.lookup(path, filterTypes);
  3137. };
  3138. /**
  3139. * Looks up the reflection object at the specified path, relative to this namespace.
  3140. * @name NamespaceBase#lookup
  3141. * @function
  3142. * @param {string|string[]} path Path to look up
  3143. * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked
  3144. * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
  3145. * @variation 2
  3146. */
  3147. // lookup(path: string, [parentAlreadyChecked: boolean])
  3148. /**
  3149. * Looks up the {@link Type|type} at the specified path, relative to this namespace.
  3150. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  3151. * @param {string|string[]} path Path to look up
  3152. * @returns {Type} Looked up type
  3153. * @throws {Error} If `path` does not point to a type
  3154. */
  3155. Namespace.prototype.lookupType = function lookupType(path) {
  3156. var found = this.lookup(path, [ Type ]);
  3157. if (!found)
  3158. throw Error("no such type: " + path);
  3159. return found;
  3160. };
  3161. /**
  3162. * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
  3163. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  3164. * @param {string|string[]} path Path to look up
  3165. * @returns {Enum} Looked up enum
  3166. * @throws {Error} If `path` does not point to an enum
  3167. */
  3168. Namespace.prototype.lookupEnum = function lookupEnum(path) {
  3169. var found = this.lookup(path, [ Enum ]);
  3170. if (!found)
  3171. throw Error("no such Enum '" + path + "' in " + this);
  3172. return found;
  3173. };
  3174. /**
  3175. * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
  3176. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  3177. * @param {string|string[]} path Path to look up
  3178. * @returns {Type} Looked up type or enum
  3179. * @throws {Error} If `path` does not point to a type or enum
  3180. */
  3181. Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {
  3182. var found = this.lookup(path, [ Type, Enum ]);
  3183. if (!found)
  3184. throw Error("no such Type or Enum '" + path + "' in " + this);
  3185. return found;
  3186. };
  3187. /**
  3188. * Looks up the {@link Service|service} at the specified path, relative to this namespace.
  3189. * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
  3190. * @param {string|string[]} path Path to look up
  3191. * @returns {Service} Looked up service
  3192. * @throws {Error} If `path` does not point to a service
  3193. */
  3194. Namespace.prototype.lookupService = function lookupService(path) {
  3195. var found = this.lookup(path, [ Service ]);
  3196. if (!found)
  3197. throw Error("no such Service '" + path + "' in " + this);
  3198. return found;
  3199. };
  3200. // Sets up cyclic dependencies (called in index-light)
  3201. Namespace._configure = function(Type_, Service_, Enum_) {
  3202. Type = Type_;
  3203. Service = Service_;
  3204. Enum = Enum_;
  3205. };
  3206. },{"16":16,"24":24,"37":37}],24:[function(require,module,exports){
  3207. "use strict";
  3208. module.exports = ReflectionObject;
  3209. ReflectionObject.className = "ReflectionObject";
  3210. var util = require(37);
  3211. var Root; // cyclic
  3212. /**
  3213. * Constructs a new reflection object instance.
  3214. * @classdesc Base class of all reflection objects.
  3215. * @constructor
  3216. * @param {string} name Object name
  3217. * @param {Object.<string,*>} [options] Declared options
  3218. * @abstract
  3219. */
  3220. function ReflectionObject(name, options) {
  3221. if (!util.isString(name))
  3222. throw TypeError("name must be a string");
  3223. if (options && !util.isObject(options))
  3224. throw TypeError("options must be an object");
  3225. /**
  3226. * Options.
  3227. * @type {Object.<string,*>|undefined}
  3228. */
  3229. this.options = options; // toJSON
  3230. /**
  3231. * Parsed Options.
  3232. * @type {Array.<Object.<string,*>>|undefined}
  3233. */
  3234. this.parsedOptions = null;
  3235. /**
  3236. * Unique name within its namespace.
  3237. * @type {string}
  3238. */
  3239. this.name = name;
  3240. /**
  3241. * Parent namespace.
  3242. * @type {Namespace|null}
  3243. */
  3244. this.parent = null;
  3245. /**
  3246. * Whether already resolved or not.
  3247. * @type {boolean}
  3248. */
  3249. this.resolved = false;
  3250. /**
  3251. * Comment text, if any.
  3252. * @type {string|null}
  3253. */
  3254. this.comment = null;
  3255. /**
  3256. * Defining file name.
  3257. * @type {string|null}
  3258. */
  3259. this.filename = null;
  3260. }
  3261. Object.defineProperties(ReflectionObject.prototype, {
  3262. /**
  3263. * Reference to the root namespace.
  3264. * @name ReflectionObject#root
  3265. * @type {Root}
  3266. * @readonly
  3267. */
  3268. root: {
  3269. get: function() {
  3270. var ptr = this;
  3271. while (ptr.parent !== null)
  3272. ptr = ptr.parent;
  3273. return ptr;
  3274. }
  3275. },
  3276. /**
  3277. * Full name including leading dot.
  3278. * @name ReflectionObject#fullName
  3279. * @type {string}
  3280. * @readonly
  3281. */
  3282. fullName: {
  3283. get: function() {
  3284. var path = [ this.name ],
  3285. ptr = this.parent;
  3286. while (ptr) {
  3287. path.unshift(ptr.name);
  3288. ptr = ptr.parent;
  3289. }
  3290. return path.join(".");
  3291. }
  3292. }
  3293. });
  3294. /**
  3295. * Converts this reflection object to its descriptor representation.
  3296. * @returns {Object.<string,*>} Descriptor
  3297. * @abstract
  3298. */
  3299. ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {
  3300. throw Error(); // not implemented, shouldn't happen
  3301. };
  3302. /**
  3303. * Called when this object is added to a parent.
  3304. * @param {ReflectionObject} parent Parent added to
  3305. * @returns {undefined}
  3306. */
  3307. ReflectionObject.prototype.onAdd = function onAdd(parent) {
  3308. if (this.parent && this.parent !== parent)
  3309. this.parent.remove(this);
  3310. this.parent = parent;
  3311. this.resolved = false;
  3312. var root = parent.root;
  3313. if (root instanceof Root)
  3314. root._handleAdd(this);
  3315. };
  3316. /**
  3317. * Called when this object is removed from a parent.
  3318. * @param {ReflectionObject} parent Parent removed from
  3319. * @returns {undefined}
  3320. */
  3321. ReflectionObject.prototype.onRemove = function onRemove(parent) {
  3322. var root = parent.root;
  3323. if (root instanceof Root)
  3324. root._handleRemove(this);
  3325. this.parent = null;
  3326. this.resolved = false;
  3327. };
  3328. /**
  3329. * Resolves this objects type references.
  3330. * @returns {ReflectionObject} `this`
  3331. */
  3332. ReflectionObject.prototype.resolve = function resolve() {
  3333. if (this.resolved)
  3334. return this;
  3335. if (this.root instanceof Root)
  3336. this.resolved = true; // only if part of a root
  3337. return this;
  3338. };
  3339. /**
  3340. * Gets an option value.
  3341. * @param {string} name Option name
  3342. * @returns {*} Option value or `undefined` if not set
  3343. */
  3344. ReflectionObject.prototype.getOption = function getOption(name) {
  3345. if (this.options)
  3346. return this.options[name];
  3347. return undefined;
  3348. };
  3349. /**
  3350. * Sets an option.
  3351. * @param {string} name Option name
  3352. * @param {*} value Option value
  3353. * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set
  3354. * @returns {ReflectionObject} `this`
  3355. */
  3356. ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {
  3357. if (!ifNotSet || !this.options || this.options[name] === undefined)
  3358. (this.options || (this.options = {}))[name] = value;
  3359. return this;
  3360. };
  3361. /**
  3362. * Sets a parsed option.
  3363. * @param {string} name parsed Option name
  3364. * @param {*} value Option value
  3365. * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value
  3366. * @returns {ReflectionObject} `this`
  3367. */
  3368. ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {
  3369. if (!this.parsedOptions) {
  3370. this.parsedOptions = [];
  3371. }
  3372. var parsedOptions = this.parsedOptions;
  3373. if (propName) {
  3374. // If setting a sub property of an option then try to merge it
  3375. // with an existing option
  3376. var opt = parsedOptions.find(function (opt) {
  3377. return Object.prototype.hasOwnProperty.call(opt, name);
  3378. });
  3379. if (opt) {
  3380. // If we found an existing option - just merge the property value
  3381. var newValue = opt[name];
  3382. util.setProperty(newValue, propName, value);
  3383. } else {
  3384. // otherwise, create a new option, set it's property and add it to the list
  3385. opt = {};
  3386. opt[name] = util.setProperty({}, propName, value);
  3387. parsedOptions.push(opt);
  3388. }
  3389. } else {
  3390. // Always create a new option when setting the value of the option itself
  3391. var newOpt = {};
  3392. newOpt[name] = value;
  3393. parsedOptions.push(newOpt);
  3394. }
  3395. return this;
  3396. };
  3397. /**
  3398. * Sets multiple options.
  3399. * @param {Object.<string,*>} options Options to set
  3400. * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set
  3401. * @returns {ReflectionObject} `this`
  3402. */
  3403. ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {
  3404. if (options)
  3405. for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)
  3406. this.setOption(keys[i], options[keys[i]], ifNotSet);
  3407. return this;
  3408. };
  3409. /**
  3410. * Converts this instance to its string representation.
  3411. * @returns {string} Class name[, space, full name]
  3412. */
  3413. ReflectionObject.prototype.toString = function toString() {
  3414. var className = this.constructor.className,
  3415. fullName = this.fullName;
  3416. if (fullName.length)
  3417. return className + " " + fullName;
  3418. return className;
  3419. };
  3420. // Sets up cyclic dependencies (called in index-light)
  3421. ReflectionObject._configure = function(Root_) {
  3422. Root = Root_;
  3423. };
  3424. },{"37":37}],25:[function(require,module,exports){
  3425. "use strict";
  3426. module.exports = OneOf;
  3427. // extends ReflectionObject
  3428. var ReflectionObject = require(24);
  3429. ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
  3430. var Field = require(16),
  3431. util = require(37);
  3432. /**
  3433. * Constructs a new oneof instance.
  3434. * @classdesc Reflected oneof.
  3435. * @extends ReflectionObject
  3436. * @constructor
  3437. * @param {string} name Oneof name
  3438. * @param {string[]|Object.<string,*>} [fieldNames] Field names
  3439. * @param {Object.<string,*>} [options] Declared options
  3440. * @param {string} [comment] Comment associated with this field
  3441. */
  3442. function OneOf(name, fieldNames, options, comment) {
  3443. if (!Array.isArray(fieldNames)) {
  3444. options = fieldNames;
  3445. fieldNames = undefined;
  3446. }
  3447. ReflectionObject.call(this, name, options);
  3448. /* istanbul ignore if */
  3449. if (!(fieldNames === undefined || Array.isArray(fieldNames)))
  3450. throw TypeError("fieldNames must be an Array");
  3451. /**
  3452. * Field names that belong to this oneof.
  3453. * @type {string[]}
  3454. */
  3455. this.oneof = fieldNames || []; // toJSON, marker
  3456. /**
  3457. * Fields that belong to this oneof as an array for iteration.
  3458. * @type {Field[]}
  3459. * @readonly
  3460. */
  3461. this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent
  3462. /**
  3463. * Comment for this field.
  3464. * @type {string|null}
  3465. */
  3466. this.comment = comment;
  3467. }
  3468. /**
  3469. * Oneof descriptor.
  3470. * @interface IOneOf
  3471. * @property {Array.<string>} oneof Oneof field names
  3472. * @property {Object.<string,*>} [options] Oneof options
  3473. */
  3474. /**
  3475. * Constructs a oneof from a oneof descriptor.
  3476. * @param {string} name Oneof name
  3477. * @param {IOneOf} json Oneof descriptor
  3478. * @returns {OneOf} Created oneof
  3479. * @throws {TypeError} If arguments are invalid
  3480. */
  3481. OneOf.fromJSON = function fromJSON(name, json) {
  3482. return new OneOf(name, json.oneof, json.options, json.comment);
  3483. };
  3484. /**
  3485. * Converts this oneof to a oneof descriptor.
  3486. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  3487. * @returns {IOneOf} Oneof descriptor
  3488. */
  3489. OneOf.prototype.toJSON = function toJSON(toJSONOptions) {
  3490. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  3491. return util.toObject([
  3492. "options" , this.options,
  3493. "oneof" , this.oneof,
  3494. "comment" , keepComments ? this.comment : undefined
  3495. ]);
  3496. };
  3497. /**
  3498. * Adds the fields of the specified oneof to the parent if not already done so.
  3499. * @param {OneOf} oneof The oneof
  3500. * @returns {undefined}
  3501. * @inner
  3502. * @ignore
  3503. */
  3504. function addFieldsToParent(oneof) {
  3505. if (oneof.parent)
  3506. for (var i = 0; i < oneof.fieldsArray.length; ++i)
  3507. if (!oneof.fieldsArray[i].parent)
  3508. oneof.parent.add(oneof.fieldsArray[i]);
  3509. }
  3510. /**
  3511. * Adds a field to this oneof and removes it from its current parent, if any.
  3512. * @param {Field} field Field to add
  3513. * @returns {OneOf} `this`
  3514. */
  3515. OneOf.prototype.add = function add(field) {
  3516. /* istanbul ignore if */
  3517. if (!(field instanceof Field))
  3518. throw TypeError("field must be a Field");
  3519. if (field.parent && field.parent !== this.parent)
  3520. field.parent.remove(field);
  3521. this.oneof.push(field.name);
  3522. this.fieldsArray.push(field);
  3523. field.partOf = this; // field.parent remains null
  3524. addFieldsToParent(this);
  3525. return this;
  3526. };
  3527. /**
  3528. * Removes a field from this oneof and puts it back to the oneof's parent.
  3529. * @param {Field} field Field to remove
  3530. * @returns {OneOf} `this`
  3531. */
  3532. OneOf.prototype.remove = function remove(field) {
  3533. /* istanbul ignore if */
  3534. if (!(field instanceof Field))
  3535. throw TypeError("field must be a Field");
  3536. var index = this.fieldsArray.indexOf(field);
  3537. /* istanbul ignore if */
  3538. if (index < 0)
  3539. throw Error(field + " is not a member of " + this);
  3540. this.fieldsArray.splice(index, 1);
  3541. index = this.oneof.indexOf(field.name);
  3542. /* istanbul ignore else */
  3543. if (index > -1) // theoretical
  3544. this.oneof.splice(index, 1);
  3545. field.partOf = null;
  3546. return this;
  3547. };
  3548. /**
  3549. * @override
  3550. */
  3551. OneOf.prototype.onAdd = function onAdd(parent) {
  3552. ReflectionObject.prototype.onAdd.call(this, parent);
  3553. var self = this;
  3554. // Collect present fields
  3555. for (var i = 0; i < this.oneof.length; ++i) {
  3556. var field = parent.get(this.oneof[i]);
  3557. if (field && !field.partOf) {
  3558. field.partOf = self;
  3559. self.fieldsArray.push(field);
  3560. }
  3561. }
  3562. // Add not yet present fields
  3563. addFieldsToParent(this);
  3564. };
  3565. /**
  3566. * @override
  3567. */
  3568. OneOf.prototype.onRemove = function onRemove(parent) {
  3569. for (var i = 0, field; i < this.fieldsArray.length; ++i)
  3570. if ((field = this.fieldsArray[i]).parent)
  3571. field.parent.remove(field);
  3572. ReflectionObject.prototype.onRemove.call(this, parent);
  3573. };
  3574. /**
  3575. * Decorator function as returned by {@link OneOf.d} (TypeScript).
  3576. * @typedef OneOfDecorator
  3577. * @type {function}
  3578. * @param {Object} prototype Target prototype
  3579. * @param {string} oneofName OneOf name
  3580. * @returns {undefined}
  3581. */
  3582. /**
  3583. * OneOf decorator (TypeScript).
  3584. * @function
  3585. * @param {...string} fieldNames Field names
  3586. * @returns {OneOfDecorator} Decorator function
  3587. * @template T extends string
  3588. */
  3589. OneOf.d = function decorateOneOf() {
  3590. var fieldNames = new Array(arguments.length),
  3591. index = 0;
  3592. while (index < arguments.length)
  3593. fieldNames[index] = arguments[index++];
  3594. return function oneOfDecorator(prototype, oneofName) {
  3595. util.decorateType(prototype.constructor)
  3596. .add(new OneOf(oneofName, fieldNames));
  3597. Object.defineProperty(prototype, oneofName, {
  3598. get: util.oneOfGetter(fieldNames),
  3599. set: util.oneOfSetter(fieldNames)
  3600. });
  3601. };
  3602. };
  3603. },{"16":16,"24":24,"37":37}],26:[function(require,module,exports){
  3604. "use strict";
  3605. module.exports = parse;
  3606. parse.filename = null;
  3607. parse.defaults = { keepCase: false };
  3608. var tokenize = require(34),
  3609. Root = require(29),
  3610. Type = require(35),
  3611. Field = require(16),
  3612. MapField = require(20),
  3613. OneOf = require(25),
  3614. Enum = require(15),
  3615. Service = require(33),
  3616. Method = require(22),
  3617. types = require(36),
  3618. util = require(37);
  3619. var base10Re = /^[1-9][0-9]*$/,
  3620. base10NegRe = /^-?[1-9][0-9]*$/,
  3621. base16Re = /^0[x][0-9a-fA-F]+$/,
  3622. base16NegRe = /^-?0[x][0-9a-fA-F]+$/,
  3623. base8Re = /^0[0-7]+$/,
  3624. base8NegRe = /^-?0[0-7]+$/,
  3625. numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,
  3626. nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,
  3627. typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
  3628. fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;
  3629. /**
  3630. * Result object returned from {@link parse}.
  3631. * @interface IParserResult
  3632. * @property {string|undefined} package Package name, if declared
  3633. * @property {string[]|undefined} imports Imports, if any
  3634. * @property {string[]|undefined} weakImports Weak imports, if any
  3635. * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`)
  3636. * @property {Root} root Populated root instance
  3637. */
  3638. /**
  3639. * Options modifying the behavior of {@link parse}.
  3640. * @interface IParseOptions
  3641. * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case
  3642. * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.
  3643. * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.
  3644. */
  3645. /**
  3646. * Options modifying the behavior of JSON serialization.
  3647. * @interface IToJSONOptions
  3648. * @property {boolean} [keepComments=false] Serializes comments.
  3649. */
  3650. /**
  3651. * Parses the given .proto source and returns an object with the parsed contents.
  3652. * @param {string} source Source contents
  3653. * @param {Root} root Root to populate
  3654. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  3655. * @returns {IParserResult} Parser result
  3656. * @property {string} filename=null Currently processing file name for error reporting, if known
  3657. * @property {IParseOptions} defaults Default {@link IParseOptions}
  3658. */
  3659. function parse(source, root, options) {
  3660. /* eslint-disable callback-return */
  3661. if (!(root instanceof Root)) {
  3662. options = root;
  3663. root = new Root();
  3664. }
  3665. if (!options)
  3666. options = parse.defaults;
  3667. var preferTrailingComment = options.preferTrailingComment || false;
  3668. var tn = tokenize(source, options.alternateCommentMode || false),
  3669. next = tn.next,
  3670. push = tn.push,
  3671. peek = tn.peek,
  3672. skip = tn.skip,
  3673. cmnt = tn.cmnt;
  3674. var head = true,
  3675. pkg,
  3676. imports,
  3677. weakImports,
  3678. syntax,
  3679. isProto3 = false;
  3680. var ptr = root;
  3681. var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;
  3682. /* istanbul ignore next */
  3683. function illegal(token, name, insideTryCatch) {
  3684. var filename = parse.filename;
  3685. if (!insideTryCatch)
  3686. parse.filename = null;
  3687. return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");
  3688. }
  3689. function readString() {
  3690. var values = [],
  3691. token;
  3692. do {
  3693. /* istanbul ignore if */
  3694. if ((token = next()) !== "\"" && token !== "'")
  3695. throw illegal(token);
  3696. values.push(next());
  3697. skip(token);
  3698. token = peek();
  3699. } while (token === "\"" || token === "'");
  3700. return values.join("");
  3701. }
  3702. function readValue(acceptTypeRef) {
  3703. var token = next();
  3704. switch (token) {
  3705. case "'":
  3706. case "\"":
  3707. push(token);
  3708. return readString();
  3709. case "true": case "TRUE":
  3710. return true;
  3711. case "false": case "FALSE":
  3712. return false;
  3713. }
  3714. try {
  3715. return parseNumber(token, /* insideTryCatch */ true);
  3716. } catch (e) {
  3717. /* istanbul ignore else */
  3718. if (acceptTypeRef && typeRefRe.test(token))
  3719. return token;
  3720. /* istanbul ignore next */
  3721. throw illegal(token, "value");
  3722. }
  3723. }
  3724. function readRanges(target, acceptStrings) {
  3725. var token, start;
  3726. do {
  3727. if (acceptStrings && ((token = peek()) === "\"" || token === "'"))
  3728. target.push(readString());
  3729. else
  3730. target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]);
  3731. } while (skip(",", true));
  3732. skip(";");
  3733. }
  3734. function parseNumber(token, insideTryCatch) {
  3735. var sign = 1;
  3736. if (token.charAt(0) === "-") {
  3737. sign = -1;
  3738. token = token.substring(1);
  3739. }
  3740. switch (token) {
  3741. case "inf": case "INF": case "Inf":
  3742. return sign * Infinity;
  3743. case "nan": case "NAN": case "Nan": case "NaN":
  3744. return NaN;
  3745. case "0":
  3746. return 0;
  3747. }
  3748. if (base10Re.test(token))
  3749. return sign * parseInt(token, 10);
  3750. if (base16Re.test(token))
  3751. return sign * parseInt(token, 16);
  3752. if (base8Re.test(token))
  3753. return sign * parseInt(token, 8);
  3754. /* istanbul ignore else */
  3755. if (numberRe.test(token))
  3756. return sign * parseFloat(token);
  3757. /* istanbul ignore next */
  3758. throw illegal(token, "number", insideTryCatch);
  3759. }
  3760. function parseId(token, acceptNegative) {
  3761. switch (token) {
  3762. case "max": case "MAX": case "Max":
  3763. return 536870911;
  3764. case "0":
  3765. return 0;
  3766. }
  3767. /* istanbul ignore if */
  3768. if (!acceptNegative && token.charAt(0) === "-")
  3769. throw illegal(token, "id");
  3770. if (base10NegRe.test(token))
  3771. return parseInt(token, 10);
  3772. if (base16NegRe.test(token))
  3773. return parseInt(token, 16);
  3774. /* istanbul ignore else */
  3775. if (base8NegRe.test(token))
  3776. return parseInt(token, 8);
  3777. /* istanbul ignore next */
  3778. throw illegal(token, "id");
  3779. }
  3780. function parsePackage() {
  3781. /* istanbul ignore if */
  3782. if (pkg !== undefined)
  3783. throw illegal("package");
  3784. pkg = next();
  3785. /* istanbul ignore if */
  3786. if (!typeRefRe.test(pkg))
  3787. throw illegal(pkg, "name");
  3788. ptr = ptr.define(pkg);
  3789. skip(";");
  3790. }
  3791. function parseImport() {
  3792. var token = peek();
  3793. var whichImports;
  3794. switch (token) {
  3795. case "weak":
  3796. whichImports = weakImports || (weakImports = []);
  3797. next();
  3798. break;
  3799. case "public":
  3800. next();
  3801. // eslint-disable-line no-fallthrough
  3802. default:
  3803. whichImports = imports || (imports = []);
  3804. break;
  3805. }
  3806. token = readString();
  3807. skip(";");
  3808. whichImports.push(token);
  3809. }
  3810. function parseSyntax() {
  3811. skip("=");
  3812. syntax = readString();
  3813. isProto3 = syntax === "proto3";
  3814. /* istanbul ignore if */
  3815. if (!isProto3 && syntax !== "proto2")
  3816. throw illegal(syntax, "syntax");
  3817. skip(";");
  3818. }
  3819. function parseCommon(parent, token) {
  3820. switch (token) {
  3821. case "option":
  3822. parseOption(parent, token);
  3823. skip(";");
  3824. return true;
  3825. case "message":
  3826. parseType(parent, token);
  3827. return true;
  3828. case "enum":
  3829. parseEnum(parent, token);
  3830. return true;
  3831. case "service":
  3832. parseService(parent, token);
  3833. return true;
  3834. case "extend":
  3835. parseExtension(parent, token);
  3836. return true;
  3837. }
  3838. return false;
  3839. }
  3840. function ifBlock(obj, fnIf, fnElse) {
  3841. var trailingLine = tn.line;
  3842. if (obj) {
  3843. if(typeof obj.comment !== "string") {
  3844. obj.comment = cmnt(); // try block-type comment
  3845. }
  3846. obj.filename = parse.filename;
  3847. }
  3848. if (skip("{", true)) {
  3849. var token;
  3850. while ((token = next()) !== "}")
  3851. fnIf(token);
  3852. skip(";", true);
  3853. } else {
  3854. if (fnElse)
  3855. fnElse();
  3856. skip(";");
  3857. if (obj && (typeof obj.comment !== "string" || preferTrailingComment))
  3858. obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment
  3859. }
  3860. }
  3861. function parseType(parent, token) {
  3862. /* istanbul ignore if */
  3863. if (!nameRe.test(token = next()))
  3864. throw illegal(token, "type name");
  3865. var type = new Type(token);
  3866. ifBlock(type, function parseType_block(token) {
  3867. if (parseCommon(type, token))
  3868. return;
  3869. switch (token) {
  3870. case "map":
  3871. parseMapField(type, token);
  3872. break;
  3873. case "required":
  3874. case "repeated":
  3875. parseField(type, token);
  3876. break;
  3877. case "optional":
  3878. /* istanbul ignore if */
  3879. if (isProto3) {
  3880. parseField(type, "proto3_optional");
  3881. } else {
  3882. parseField(type, "optional");
  3883. }
  3884. break;
  3885. case "oneof":
  3886. parseOneOf(type, token);
  3887. break;
  3888. case "extensions":
  3889. readRanges(type.extensions || (type.extensions = []));
  3890. break;
  3891. case "reserved":
  3892. readRanges(type.reserved || (type.reserved = []), true);
  3893. break;
  3894. default:
  3895. /* istanbul ignore if */
  3896. if (!isProto3 || !typeRefRe.test(token))
  3897. throw illegal(token);
  3898. push(token);
  3899. parseField(type, "optional");
  3900. break;
  3901. }
  3902. });
  3903. parent.add(type);
  3904. }
  3905. function parseField(parent, rule, extend) {
  3906. var type = next();
  3907. if (type === "group") {
  3908. parseGroup(parent, rule);
  3909. return;
  3910. }
  3911. /* istanbul ignore if */
  3912. if (!typeRefRe.test(type))
  3913. throw illegal(type, "type");
  3914. var name = next();
  3915. /* istanbul ignore if */
  3916. if (!nameRe.test(name))
  3917. throw illegal(name, "name");
  3918. name = applyCase(name);
  3919. skip("=");
  3920. var field = new Field(name, parseId(next()), type, rule, extend);
  3921. ifBlock(field, function parseField_block(token) {
  3922. /* istanbul ignore else */
  3923. if (token === "option") {
  3924. parseOption(field, token);
  3925. skip(";");
  3926. } else
  3927. throw illegal(token);
  3928. }, function parseField_line() {
  3929. parseInlineOptions(field);
  3930. });
  3931. if (rule === "proto3_optional") {
  3932. // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior
  3933. var oneof = new OneOf("_" + name);
  3934. field.setOption("proto3_optional", true);
  3935. oneof.add(field);
  3936. parent.add(oneof);
  3937. } else {
  3938. parent.add(field);
  3939. }
  3940. // JSON defaults to packed=true if not set so we have to set packed=false explicity when
  3941. // parsing proto2 descriptors without the option, where applicable. This must be done for
  3942. // all known packable types and anything that could be an enum (= is not a basic type).
  3943. if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))
  3944. field.setOption("packed", false, /* ifNotSet */ true);
  3945. }
  3946. function parseGroup(parent, rule) {
  3947. var name = next();
  3948. /* istanbul ignore if */
  3949. if (!nameRe.test(name))
  3950. throw illegal(name, "name");
  3951. var fieldName = util.lcFirst(name);
  3952. if (name === fieldName)
  3953. name = util.ucFirst(name);
  3954. skip("=");
  3955. var id = parseId(next());
  3956. var type = new Type(name);
  3957. type.group = true;
  3958. var field = new Field(fieldName, id, name, rule);
  3959. field.filename = parse.filename;
  3960. ifBlock(type, function parseGroup_block(token) {
  3961. switch (token) {
  3962. case "option":
  3963. parseOption(type, token);
  3964. skip(";");
  3965. break;
  3966. case "required":
  3967. case "repeated":
  3968. parseField(type, token);
  3969. break;
  3970. case "optional":
  3971. /* istanbul ignore if */
  3972. if (isProto3) {
  3973. parseField(type, "proto3_optional");
  3974. } else {
  3975. parseField(type, "optional");
  3976. }
  3977. break;
  3978. /* istanbul ignore next */
  3979. default:
  3980. throw illegal(token); // there are no groups with proto3 semantics
  3981. }
  3982. });
  3983. parent.add(type)
  3984. .add(field);
  3985. }
  3986. function parseMapField(parent) {
  3987. skip("<");
  3988. var keyType = next();
  3989. /* istanbul ignore if */
  3990. if (types.mapKey[keyType] === undefined)
  3991. throw illegal(keyType, "type");
  3992. skip(",");
  3993. var valueType = next();
  3994. /* istanbul ignore if */
  3995. if (!typeRefRe.test(valueType))
  3996. throw illegal(valueType, "type");
  3997. skip(">");
  3998. var name = next();
  3999. /* istanbul ignore if */
  4000. if (!nameRe.test(name))
  4001. throw illegal(name, "name");
  4002. skip("=");
  4003. var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);
  4004. ifBlock(field, function parseMapField_block(token) {
  4005. /* istanbul ignore else */
  4006. if (token === "option") {
  4007. parseOption(field, token);
  4008. skip(";");
  4009. } else
  4010. throw illegal(token);
  4011. }, function parseMapField_line() {
  4012. parseInlineOptions(field);
  4013. });
  4014. parent.add(field);
  4015. }
  4016. function parseOneOf(parent, token) {
  4017. /* istanbul ignore if */
  4018. if (!nameRe.test(token = next()))
  4019. throw illegal(token, "name");
  4020. var oneof = new OneOf(applyCase(token));
  4021. ifBlock(oneof, function parseOneOf_block(token) {
  4022. if (token === "option") {
  4023. parseOption(oneof, token);
  4024. skip(";");
  4025. } else {
  4026. push(token);
  4027. parseField(oneof, "optional");
  4028. }
  4029. });
  4030. parent.add(oneof);
  4031. }
  4032. function parseEnum(parent, token) {
  4033. /* istanbul ignore if */
  4034. if (!nameRe.test(token = next()))
  4035. throw illegal(token, "name");
  4036. var enm = new Enum(token);
  4037. ifBlock(enm, function parseEnum_block(token) {
  4038. switch(token) {
  4039. case "option":
  4040. parseOption(enm, token);
  4041. skip(";");
  4042. break;
  4043. case "reserved":
  4044. readRanges(enm.reserved || (enm.reserved = []), true);
  4045. break;
  4046. default:
  4047. parseEnumValue(enm, token);
  4048. }
  4049. });
  4050. parent.add(enm);
  4051. }
  4052. function parseEnumValue(parent, token) {
  4053. /* istanbul ignore if */
  4054. if (!nameRe.test(token))
  4055. throw illegal(token, "name");
  4056. skip("=");
  4057. var value = parseId(next(), true),
  4058. dummy = {};
  4059. ifBlock(dummy, function parseEnumValue_block(token) {
  4060. /* istanbul ignore else */
  4061. if (token === "option") {
  4062. parseOption(dummy, token); // skip
  4063. skip(";");
  4064. } else
  4065. throw illegal(token);
  4066. }, function parseEnumValue_line() {
  4067. parseInlineOptions(dummy); // skip
  4068. });
  4069. parent.add(token, value, dummy.comment);
  4070. }
  4071. function parseOption(parent, token) {
  4072. var isCustom = skip("(", true);
  4073. /* istanbul ignore if */
  4074. if (!typeRefRe.test(token = next()))
  4075. throw illegal(token, "name");
  4076. var name = token;
  4077. var option = name;
  4078. var propName;
  4079. if (isCustom) {
  4080. skip(")");
  4081. name = "(" + name + ")";
  4082. option = name;
  4083. token = peek();
  4084. if (fqTypeRefRe.test(token)) {
  4085. propName = token.substr(1); //remove '.' before property name
  4086. name += token;
  4087. next();
  4088. }
  4089. }
  4090. skip("=");
  4091. var optionValue = parseOptionValue(parent, name);
  4092. setParsedOption(parent, option, optionValue, propName);
  4093. }
  4094. function parseOptionValue(parent, name) {
  4095. if (skip("{", true)) { // { a: "foo" b { c: "bar" } }
  4096. var result = {};
  4097. while (!skip("}", true)) {
  4098. /* istanbul ignore if */
  4099. if (!nameRe.test(token = next()))
  4100. throw illegal(token, "name");
  4101. var value;
  4102. var propName = token;
  4103. if (peek() === "{")
  4104. value = parseOptionValue(parent, name + "." + token);
  4105. else {
  4106. skip(":");
  4107. if (peek() === "{")
  4108. value = parseOptionValue(parent, name + "." + token);
  4109. else {
  4110. value = readValue(true);
  4111. setOption(parent, name + "." + token, value);
  4112. }
  4113. }
  4114. var prevValue = result[propName];
  4115. if (prevValue)
  4116. value = [].concat(prevValue).concat(value);
  4117. result[propName] = value;
  4118. skip(",", true);
  4119. }
  4120. return result;
  4121. }
  4122. var simpleValue = readValue(true);
  4123. setOption(parent, name, simpleValue);
  4124. return simpleValue;
  4125. // Does not enforce a delimiter to be universal
  4126. }
  4127. function setOption(parent, name, value) {
  4128. if (parent.setOption)
  4129. parent.setOption(name, value);
  4130. }
  4131. function setParsedOption(parent, name, value, propName) {
  4132. if (parent.setParsedOption)
  4133. parent.setParsedOption(name, value, propName);
  4134. }
  4135. function parseInlineOptions(parent) {
  4136. if (skip("[", true)) {
  4137. do {
  4138. parseOption(parent, "option");
  4139. } while (skip(",", true));
  4140. skip("]");
  4141. }
  4142. return parent;
  4143. }
  4144. function parseService(parent, token) {
  4145. /* istanbul ignore if */
  4146. if (!nameRe.test(token = next()))
  4147. throw illegal(token, "service name");
  4148. var service = new Service(token);
  4149. ifBlock(service, function parseService_block(token) {
  4150. if (parseCommon(service, token))
  4151. return;
  4152. /* istanbul ignore else */
  4153. if (token === "rpc")
  4154. parseMethod(service, token);
  4155. else
  4156. throw illegal(token);
  4157. });
  4158. parent.add(service);
  4159. }
  4160. function parseMethod(parent, token) {
  4161. // Get the comment of the preceding line now (if one exists) in case the
  4162. // method is defined across multiple lines.
  4163. var commentText = cmnt();
  4164. var type = token;
  4165. /* istanbul ignore if */
  4166. if (!nameRe.test(token = next()))
  4167. throw illegal(token, "name");
  4168. var name = token,
  4169. requestType, requestStream,
  4170. responseType, responseStream;
  4171. skip("(");
  4172. if (skip("stream", true))
  4173. requestStream = true;
  4174. /* istanbul ignore if */
  4175. if (!typeRefRe.test(token = next()))
  4176. throw illegal(token);
  4177. requestType = token;
  4178. skip(")"); skip("returns"); skip("(");
  4179. if (skip("stream", true))
  4180. responseStream = true;
  4181. /* istanbul ignore if */
  4182. if (!typeRefRe.test(token = next()))
  4183. throw illegal(token);
  4184. responseType = token;
  4185. skip(")");
  4186. var method = new Method(name, type, requestType, responseType, requestStream, responseStream);
  4187. method.comment = commentText;
  4188. ifBlock(method, function parseMethod_block(token) {
  4189. /* istanbul ignore else */
  4190. if (token === "option") {
  4191. parseOption(method, token);
  4192. skip(";");
  4193. } else
  4194. throw illegal(token);
  4195. });
  4196. parent.add(method);
  4197. }
  4198. function parseExtension(parent, token) {
  4199. /* istanbul ignore if */
  4200. if (!typeRefRe.test(token = next()))
  4201. throw illegal(token, "reference");
  4202. var reference = token;
  4203. ifBlock(null, function parseExtension_block(token) {
  4204. switch (token) {
  4205. case "required":
  4206. case "repeated":
  4207. parseField(parent, token, reference);
  4208. break;
  4209. case "optional":
  4210. /* istanbul ignore if */
  4211. if (isProto3) {
  4212. parseField(parent, "proto3_optional", reference);
  4213. } else {
  4214. parseField(parent, "optional", reference);
  4215. }
  4216. break;
  4217. default:
  4218. /* istanbul ignore if */
  4219. if (!isProto3 || !typeRefRe.test(token))
  4220. throw illegal(token);
  4221. push(token);
  4222. parseField(parent, "optional", reference);
  4223. break;
  4224. }
  4225. });
  4226. }
  4227. var token;
  4228. while ((token = next()) !== null) {
  4229. switch (token) {
  4230. case "package":
  4231. /* istanbul ignore if */
  4232. if (!head)
  4233. throw illegal(token);
  4234. parsePackage();
  4235. break;
  4236. case "import":
  4237. /* istanbul ignore if */
  4238. if (!head)
  4239. throw illegal(token);
  4240. parseImport();
  4241. break;
  4242. case "syntax":
  4243. /* istanbul ignore if */
  4244. if (!head)
  4245. throw illegal(token);
  4246. parseSyntax();
  4247. break;
  4248. case "option":
  4249. parseOption(ptr, token);
  4250. skip(";");
  4251. break;
  4252. default:
  4253. /* istanbul ignore else */
  4254. if (parseCommon(ptr, token)) {
  4255. head = false;
  4256. continue;
  4257. }
  4258. /* istanbul ignore next */
  4259. throw illegal(token);
  4260. }
  4261. }
  4262. parse.filename = null;
  4263. return {
  4264. "package" : pkg,
  4265. "imports" : imports,
  4266. weakImports : weakImports,
  4267. syntax : syntax,
  4268. root : root
  4269. };
  4270. }
  4271. /**
  4272. * Parses the given .proto source and returns an object with the parsed contents.
  4273. * @name parse
  4274. * @function
  4275. * @param {string} source Source contents
  4276. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4277. * @returns {IParserResult} Parser result
  4278. * @property {string} filename=null Currently processing file name for error reporting, if known
  4279. * @property {IParseOptions} defaults Default {@link IParseOptions}
  4280. * @variation 2
  4281. */
  4282. },{"15":15,"16":16,"20":20,"22":22,"25":25,"29":29,"33":33,"34":34,"35":35,"36":36,"37":37}],27:[function(require,module,exports){
  4283. "use strict";
  4284. module.exports = Reader;
  4285. var util = require(39);
  4286. var BufferReader; // cyclic
  4287. var LongBits = util.LongBits,
  4288. utf8 = util.utf8;
  4289. /* istanbul ignore next */
  4290. function indexOutOfRange(reader, writeLength) {
  4291. return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
  4292. }
  4293. /**
  4294. * Constructs a new reader instance using the specified buffer.
  4295. * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
  4296. * @constructor
  4297. * @param {Uint8Array} buffer Buffer to read from
  4298. */
  4299. function Reader(buffer) {
  4300. /**
  4301. * Read buffer.
  4302. * @type {Uint8Array}
  4303. */
  4304. this.buf = buffer;
  4305. /**
  4306. * Read buffer position.
  4307. * @type {number}
  4308. */
  4309. this.pos = 0;
  4310. /**
  4311. * Read buffer length.
  4312. * @type {number}
  4313. */
  4314. this.len = buffer.length;
  4315. }
  4316. var create_array = typeof Uint8Array !== "undefined"
  4317. ? function create_typed_array(buffer) {
  4318. if (buffer instanceof Uint8Array || Array.isArray(buffer))
  4319. return new Reader(buffer);
  4320. throw Error("illegal buffer");
  4321. }
  4322. /* istanbul ignore next */
  4323. : function create_array(buffer) {
  4324. if (Array.isArray(buffer))
  4325. return new Reader(buffer);
  4326. throw Error("illegal buffer");
  4327. };
  4328. var create = function create() {
  4329. return util.Buffer
  4330. ? function create_buffer_setup(buffer) {
  4331. return (Reader.create = function create_buffer(buffer) {
  4332. return util.Buffer.isBuffer(buffer)
  4333. ? new BufferReader(buffer)
  4334. /* istanbul ignore next */
  4335. : create_array(buffer);
  4336. })(buffer);
  4337. }
  4338. /* istanbul ignore next */
  4339. : create_array;
  4340. };
  4341. /**
  4342. * Creates a new reader using the specified buffer.
  4343. * @function
  4344. * @param {Uint8Array|Buffer} buffer Buffer to read from
  4345. * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
  4346. * @throws {Error} If `buffer` is not a valid buffer
  4347. */
  4348. Reader.create = create();
  4349. Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
  4350. /**
  4351. * Reads a varint as an unsigned 32 bit value.
  4352. * @function
  4353. * @returns {number} Value read
  4354. */
  4355. Reader.prototype.uint32 = (function read_uint32_setup() {
  4356. var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
  4357. return function read_uint32() {
  4358. value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
  4359. value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
  4360. value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
  4361. value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
  4362. value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
  4363. /* istanbul ignore if */
  4364. if ((this.pos += 5) > this.len) {
  4365. this.pos = this.len;
  4366. throw indexOutOfRange(this, 10);
  4367. }
  4368. return value;
  4369. };
  4370. })();
  4371. /**
  4372. * Reads a varint as a signed 32 bit value.
  4373. * @returns {number} Value read
  4374. */
  4375. Reader.prototype.int32 = function read_int32() {
  4376. return this.uint32() | 0;
  4377. };
  4378. /**
  4379. * Reads a zig-zag encoded varint as a signed 32 bit value.
  4380. * @returns {number} Value read
  4381. */
  4382. Reader.prototype.sint32 = function read_sint32() {
  4383. var value = this.uint32();
  4384. return value >>> 1 ^ -(value & 1) | 0;
  4385. };
  4386. /* eslint-disable no-invalid-this */
  4387. function readLongVarint() {
  4388. // tends to deopt with local vars for octet etc.
  4389. var bits = new LongBits(0, 0);
  4390. var i = 0;
  4391. if (this.len - this.pos > 4) { // fast route (lo)
  4392. for (; i < 4; ++i) {
  4393. // 1st..4th
  4394. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  4395. if (this.buf[this.pos++] < 128)
  4396. return bits;
  4397. }
  4398. // 5th
  4399. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
  4400. bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
  4401. if (this.buf[this.pos++] < 128)
  4402. return bits;
  4403. i = 0;
  4404. } else {
  4405. for (; i < 3; ++i) {
  4406. /* istanbul ignore if */
  4407. if (this.pos >= this.len)
  4408. throw indexOutOfRange(this);
  4409. // 1st..3th
  4410. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  4411. if (this.buf[this.pos++] < 128)
  4412. return bits;
  4413. }
  4414. // 4th
  4415. bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
  4416. return bits;
  4417. }
  4418. if (this.len - this.pos > 4) { // fast route (hi)
  4419. for (; i < 5; ++i) {
  4420. // 6th..10th
  4421. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  4422. if (this.buf[this.pos++] < 128)
  4423. return bits;
  4424. }
  4425. } else {
  4426. for (; i < 5; ++i) {
  4427. /* istanbul ignore if */
  4428. if (this.pos >= this.len)
  4429. throw indexOutOfRange(this);
  4430. // 6th..10th
  4431. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  4432. if (this.buf[this.pos++] < 128)
  4433. return bits;
  4434. }
  4435. }
  4436. /* istanbul ignore next */
  4437. throw Error("invalid varint encoding");
  4438. }
  4439. /* eslint-enable no-invalid-this */
  4440. /**
  4441. * Reads a varint as a signed 64 bit value.
  4442. * @name Reader#int64
  4443. * @function
  4444. * @returns {Long} Value read
  4445. */
  4446. /**
  4447. * Reads a varint as an unsigned 64 bit value.
  4448. * @name Reader#uint64
  4449. * @function
  4450. * @returns {Long} Value read
  4451. */
  4452. /**
  4453. * Reads a zig-zag encoded varint as a signed 64 bit value.
  4454. * @name Reader#sint64
  4455. * @function
  4456. * @returns {Long} Value read
  4457. */
  4458. /**
  4459. * Reads a varint as a boolean.
  4460. * @returns {boolean} Value read
  4461. */
  4462. Reader.prototype.bool = function read_bool() {
  4463. return this.uint32() !== 0;
  4464. };
  4465. function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
  4466. return (buf[end - 4]
  4467. | buf[end - 3] << 8
  4468. | buf[end - 2] << 16
  4469. | buf[end - 1] << 24) >>> 0;
  4470. }
  4471. /**
  4472. * Reads fixed 32 bits as an unsigned 32 bit integer.
  4473. * @returns {number} Value read
  4474. */
  4475. Reader.prototype.fixed32 = function read_fixed32() {
  4476. /* istanbul ignore if */
  4477. if (this.pos + 4 > this.len)
  4478. throw indexOutOfRange(this, 4);
  4479. return readFixed32_end(this.buf, this.pos += 4);
  4480. };
  4481. /**
  4482. * Reads fixed 32 bits as a signed 32 bit integer.
  4483. * @returns {number} Value read
  4484. */
  4485. Reader.prototype.sfixed32 = function read_sfixed32() {
  4486. /* istanbul ignore if */
  4487. if (this.pos + 4 > this.len)
  4488. throw indexOutOfRange(this, 4);
  4489. return readFixed32_end(this.buf, this.pos += 4) | 0;
  4490. };
  4491. /* eslint-disable no-invalid-this */
  4492. function readFixed64(/* this: Reader */) {
  4493. /* istanbul ignore if */
  4494. if (this.pos + 8 > this.len)
  4495. throw indexOutOfRange(this, 8);
  4496. return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
  4497. }
  4498. /* eslint-enable no-invalid-this */
  4499. /**
  4500. * Reads fixed 64 bits.
  4501. * @name Reader#fixed64
  4502. * @function
  4503. * @returns {Long} Value read
  4504. */
  4505. /**
  4506. * Reads zig-zag encoded fixed 64 bits.
  4507. * @name Reader#sfixed64
  4508. * @function
  4509. * @returns {Long} Value read
  4510. */
  4511. /**
  4512. * Reads a float (32 bit) as a number.
  4513. * @function
  4514. * @returns {number} Value read
  4515. */
  4516. Reader.prototype.float = function read_float() {
  4517. /* istanbul ignore if */
  4518. if (this.pos + 4 > this.len)
  4519. throw indexOutOfRange(this, 4);
  4520. var value = util.float.readFloatLE(this.buf, this.pos);
  4521. this.pos += 4;
  4522. return value;
  4523. };
  4524. /**
  4525. * Reads a double (64 bit float) as a number.
  4526. * @function
  4527. * @returns {number} Value read
  4528. */
  4529. Reader.prototype.double = function read_double() {
  4530. /* istanbul ignore if */
  4531. if (this.pos + 8 > this.len)
  4532. throw indexOutOfRange(this, 4);
  4533. var value = util.float.readDoubleLE(this.buf, this.pos);
  4534. this.pos += 8;
  4535. return value;
  4536. };
  4537. /**
  4538. * Reads a sequence of bytes preceeded by its length as a varint.
  4539. * @returns {Uint8Array} Value read
  4540. */
  4541. Reader.prototype.bytes = function read_bytes() {
  4542. var length = this.uint32(),
  4543. start = this.pos,
  4544. end = this.pos + length;
  4545. /* istanbul ignore if */
  4546. if (end > this.len)
  4547. throw indexOutOfRange(this, length);
  4548. this.pos += length;
  4549. if (Array.isArray(this.buf)) // plain array
  4550. return this.buf.slice(start, end);
  4551. return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
  4552. ? new this.buf.constructor(0)
  4553. : this._slice.call(this.buf, start, end);
  4554. };
  4555. /**
  4556. * Reads a string preceeded by its byte length as a varint.
  4557. * @returns {string} Value read
  4558. */
  4559. Reader.prototype.string = function read_string() {
  4560. var bytes = this.bytes();
  4561. return utf8.read(bytes, 0, bytes.length);
  4562. };
  4563. /**
  4564. * Skips the specified number of bytes if specified, otherwise skips a varint.
  4565. * @param {number} [length] Length if known, otherwise a varint is assumed
  4566. * @returns {Reader} `this`
  4567. */
  4568. Reader.prototype.skip = function skip(length) {
  4569. if (typeof length === "number") {
  4570. /* istanbul ignore if */
  4571. if (this.pos + length > this.len)
  4572. throw indexOutOfRange(this, length);
  4573. this.pos += length;
  4574. } else {
  4575. do {
  4576. /* istanbul ignore if */
  4577. if (this.pos >= this.len)
  4578. throw indexOutOfRange(this);
  4579. } while (this.buf[this.pos++] & 128);
  4580. }
  4581. return this;
  4582. };
  4583. /**
  4584. * Skips the next element of the specified wire type.
  4585. * @param {number} wireType Wire type received
  4586. * @returns {Reader} `this`
  4587. */
  4588. Reader.prototype.skipType = function(wireType) {
  4589. switch (wireType) {
  4590. case 0:
  4591. this.skip();
  4592. break;
  4593. case 1:
  4594. this.skip(8);
  4595. break;
  4596. case 2:
  4597. this.skip(this.uint32());
  4598. break;
  4599. case 3:
  4600. while ((wireType = this.uint32() & 7) !== 4) {
  4601. this.skipType(wireType);
  4602. }
  4603. break;
  4604. case 5:
  4605. this.skip(4);
  4606. break;
  4607. /* istanbul ignore next */
  4608. default:
  4609. throw Error("invalid wire type " + wireType + " at offset " + this.pos);
  4610. }
  4611. return this;
  4612. };
  4613. Reader._configure = function(BufferReader_) {
  4614. BufferReader = BufferReader_;
  4615. Reader.create = create();
  4616. BufferReader._configure();
  4617. var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
  4618. util.merge(Reader.prototype, {
  4619. int64: function read_int64() {
  4620. return readLongVarint.call(this)[fn](false);
  4621. },
  4622. uint64: function read_uint64() {
  4623. return readLongVarint.call(this)[fn](true);
  4624. },
  4625. sint64: function read_sint64() {
  4626. return readLongVarint.call(this).zzDecode()[fn](false);
  4627. },
  4628. fixed64: function read_fixed64() {
  4629. return readFixed64.call(this)[fn](true);
  4630. },
  4631. sfixed64: function read_sfixed64() {
  4632. return readFixed64.call(this)[fn](false);
  4633. }
  4634. });
  4635. };
  4636. },{"39":39}],28:[function(require,module,exports){
  4637. "use strict";
  4638. module.exports = BufferReader;
  4639. // extends Reader
  4640. var Reader = require(27);
  4641. (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
  4642. var util = require(39);
  4643. /**
  4644. * Constructs a new buffer reader instance.
  4645. * @classdesc Wire format reader using node buffers.
  4646. * @extends Reader
  4647. * @constructor
  4648. * @param {Buffer} buffer Buffer to read from
  4649. */
  4650. function BufferReader(buffer) {
  4651. Reader.call(this, buffer);
  4652. /**
  4653. * Read buffer.
  4654. * @name BufferReader#buf
  4655. * @type {Buffer}
  4656. */
  4657. }
  4658. BufferReader._configure = function () {
  4659. /* istanbul ignore else */
  4660. if (util.Buffer)
  4661. BufferReader.prototype._slice = util.Buffer.prototype.slice;
  4662. };
  4663. /**
  4664. * @override
  4665. */
  4666. BufferReader.prototype.string = function read_string_buffer() {
  4667. var len = this.uint32(); // modifies pos
  4668. return this.buf.utf8Slice
  4669. ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))
  4670. : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len));
  4671. };
  4672. /**
  4673. * Reads a sequence of bytes preceeded by its length as a varint.
  4674. * @name BufferReader#bytes
  4675. * @function
  4676. * @returns {Buffer} Value read
  4677. */
  4678. BufferReader._configure();
  4679. },{"27":27,"39":39}],29:[function(require,module,exports){
  4680. "use strict";
  4681. module.exports = Root;
  4682. // extends Namespace
  4683. var Namespace = require(23);
  4684. ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";
  4685. var Field = require(16),
  4686. Enum = require(15),
  4687. OneOf = require(25),
  4688. util = require(37);
  4689. var Type, // cyclic
  4690. parse, // might be excluded
  4691. common; // "
  4692. /**
  4693. * Constructs a new root namespace instance.
  4694. * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.
  4695. * @extends NamespaceBase
  4696. * @constructor
  4697. * @param {Object.<string,*>} [options] Top level options
  4698. */
  4699. function Root(options) {
  4700. Namespace.call(this, "", options);
  4701. /**
  4702. * Deferred extension fields.
  4703. * @type {Field[]}
  4704. */
  4705. this.deferred = [];
  4706. /**
  4707. * Resolved file names of loaded files.
  4708. * @type {string[]}
  4709. */
  4710. this.files = [];
  4711. }
  4712. /**
  4713. * Loads a namespace descriptor into a root namespace.
  4714. * @param {INamespace} json Nameespace descriptor
  4715. * @param {Root} [root] Root namespace, defaults to create a new one if omitted
  4716. * @returns {Root} Root namespace
  4717. */
  4718. Root.fromJSON = function fromJSON(json, root) {
  4719. if (!root)
  4720. root = new Root();
  4721. if (json.options)
  4722. root.setOptions(json.options);
  4723. return root.addJSON(json.nested);
  4724. };
  4725. /**
  4726. * Resolves the path of an imported file, relative to the importing origin.
  4727. * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
  4728. * @function
  4729. * @param {string} origin The file name of the importing file
  4730. * @param {string} target The file name being imported
  4731. * @returns {string|null} Resolved path to `target` or `null` to skip the file
  4732. */
  4733. Root.prototype.resolvePath = util.path.resolve;
  4734. /**
  4735. * Fetch content from file path or url
  4736. * This method exists so you can override it with your own logic.
  4737. * @function
  4738. * @param {string} path File path or url
  4739. * @param {FetchCallback} callback Callback function
  4740. * @returns {undefined}
  4741. */
  4742. Root.prototype.fetch = util.fetch;
  4743. // A symbol-like function to safely signal synchronous loading
  4744. /* istanbul ignore next */
  4745. function SYNC() {} // eslint-disable-line no-empty-function
  4746. /**
  4747. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  4748. * @param {string|string[]} filename Names of one or multiple files to load
  4749. * @param {IParseOptions} options Parse options
  4750. * @param {LoadCallback} callback Callback function
  4751. * @returns {undefined}
  4752. */
  4753. Root.prototype.load = function load(filename, options, callback) {
  4754. if (typeof options === "function") {
  4755. callback = options;
  4756. options = undefined;
  4757. }
  4758. var self = this;
  4759. if (!callback)
  4760. return util.asPromise(load, self, filename, options);
  4761. var sync = callback === SYNC; // undocumented
  4762. // Finishes loading by calling the callback (exactly once)
  4763. function finish(err, root) {
  4764. /* istanbul ignore if */
  4765. if (!callback)
  4766. return;
  4767. var cb = callback;
  4768. callback = null;
  4769. if (sync)
  4770. throw err;
  4771. cb(err, root);
  4772. }
  4773. // Bundled definition existence checking
  4774. function getBundledFileName(filename) {
  4775. var idx = filename.lastIndexOf("google/protobuf/");
  4776. if (idx > -1) {
  4777. var altname = filename.substring(idx);
  4778. if (altname in common) return altname;
  4779. }
  4780. return null;
  4781. }
  4782. // Processes a single file
  4783. function process(filename, source) {
  4784. try {
  4785. if (util.isString(source) && source.charAt(0) === "{")
  4786. source = JSON.parse(source);
  4787. if (!util.isString(source))
  4788. self.setOptions(source.options).addJSON(source.nested);
  4789. else {
  4790. parse.filename = filename;
  4791. var parsed = parse(source, self, options),
  4792. resolved,
  4793. i = 0;
  4794. if (parsed.imports)
  4795. for (; i < parsed.imports.length; ++i)
  4796. if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))
  4797. fetch(resolved);
  4798. if (parsed.weakImports)
  4799. for (i = 0; i < parsed.weakImports.length; ++i)
  4800. if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))
  4801. fetch(resolved, true);
  4802. }
  4803. } catch (err) {
  4804. finish(err);
  4805. }
  4806. if (!sync && !queued)
  4807. finish(null, self); // only once anyway
  4808. }
  4809. // Fetches a single file
  4810. function fetch(filename, weak) {
  4811. // Skip if already loaded / attempted
  4812. if (self.files.indexOf(filename) > -1)
  4813. return;
  4814. self.files.push(filename);
  4815. // Shortcut bundled definitions
  4816. if (filename in common) {
  4817. if (sync)
  4818. process(filename, common[filename]);
  4819. else {
  4820. ++queued;
  4821. setTimeout(function() {
  4822. --queued;
  4823. process(filename, common[filename]);
  4824. });
  4825. }
  4826. return;
  4827. }
  4828. // Otherwise fetch from disk or network
  4829. if (sync) {
  4830. var source;
  4831. try {
  4832. source = util.fs.readFileSync(filename).toString("utf8");
  4833. } catch (err) {
  4834. if (!weak)
  4835. finish(err);
  4836. return;
  4837. }
  4838. process(filename, source);
  4839. } else {
  4840. ++queued;
  4841. self.fetch(filename, function(err, source) {
  4842. --queued;
  4843. /* istanbul ignore if */
  4844. if (!callback)
  4845. return; // terminated meanwhile
  4846. if (err) {
  4847. /* istanbul ignore else */
  4848. if (!weak)
  4849. finish(err);
  4850. else if (!queued) // can't be covered reliably
  4851. finish(null, self);
  4852. return;
  4853. }
  4854. process(filename, source);
  4855. });
  4856. }
  4857. }
  4858. var queued = 0;
  4859. // Assembling the root namespace doesn't require working type
  4860. // references anymore, so we can load everything in parallel
  4861. if (util.isString(filename))
  4862. filename = [ filename ];
  4863. for (var i = 0, resolved; i < filename.length; ++i)
  4864. if (resolved = self.resolvePath("", filename[i]))
  4865. fetch(resolved);
  4866. if (sync)
  4867. return self;
  4868. if (!queued)
  4869. finish(null, self);
  4870. return undefined;
  4871. };
  4872. // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined
  4873. /**
  4874. * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
  4875. * @function Root#load
  4876. * @param {string|string[]} filename Names of one or multiple files to load
  4877. * @param {LoadCallback} callback Callback function
  4878. * @returns {undefined}
  4879. * @variation 2
  4880. */
  4881. // function load(filename:string, callback:LoadCallback):undefined
  4882. /**
  4883. * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
  4884. * @function Root#load
  4885. * @param {string|string[]} filename Names of one or multiple files to load
  4886. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4887. * @returns {Promise<Root>} Promise
  4888. * @variation 3
  4889. */
  4890. // function load(filename:string, [options:IParseOptions]):Promise<Root>
  4891. /**
  4892. * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
  4893. * @function Root#loadSync
  4894. * @param {string|string[]} filename Names of one or multiple files to load
  4895. * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
  4896. * @returns {Root} Root namespace
  4897. * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
  4898. */
  4899. Root.prototype.loadSync = function loadSync(filename, options) {
  4900. if (!util.isNode)
  4901. throw Error("not supported");
  4902. return this.load(filename, options, SYNC);
  4903. };
  4904. /**
  4905. * @override
  4906. */
  4907. Root.prototype.resolveAll = function resolveAll() {
  4908. if (this.deferred.length)
  4909. throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
  4910. return "'extend " + field.extend + "' in " + field.parent.fullName;
  4911. }).join(", "));
  4912. return Namespace.prototype.resolveAll.call(this);
  4913. };
  4914. // only uppercased (and thus conflict-free) children are exposed, see below
  4915. var exposeRe = /^[A-Z]/;
  4916. /**
  4917. * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.
  4918. * @param {Root} root Root instance
  4919. * @param {Field} field Declaring extension field witin the declaring type
  4920. * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise
  4921. * @inner
  4922. * @ignore
  4923. */
  4924. function tryHandleExtension(root, field) {
  4925. var extendedType = field.parent.lookup(field.extend);
  4926. if (extendedType) {
  4927. var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);
  4928. sisterField.declaringField = field;
  4929. field.extensionField = sisterField;
  4930. extendedType.add(sisterField);
  4931. return true;
  4932. }
  4933. return false;
  4934. }
  4935. /**
  4936. * Called when any object is added to this root or its sub-namespaces.
  4937. * @param {ReflectionObject} object Object added
  4938. * @returns {undefined}
  4939. * @private
  4940. */
  4941. Root.prototype._handleAdd = function _handleAdd(object) {
  4942. if (object instanceof Field) {
  4943. if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)
  4944. if (!tryHandleExtension(this, object))
  4945. this.deferred.push(object);
  4946. } else if (object instanceof Enum) {
  4947. if (exposeRe.test(object.name))
  4948. object.parent[object.name] = object.values; // expose enum values as property of its parent
  4949. } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {
  4950. if (object instanceof Type) // Try to handle any deferred extensions
  4951. for (var i = 0; i < this.deferred.length;)
  4952. if (tryHandleExtension(this, this.deferred[i]))
  4953. this.deferred.splice(i, 1);
  4954. else
  4955. ++i;
  4956. for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace
  4957. this._handleAdd(object._nestedArray[j]);
  4958. if (exposeRe.test(object.name))
  4959. object.parent[object.name] = object; // expose namespace as property of its parent
  4960. }
  4961. // The above also adds uppercased (and thus conflict-free) nested types, services and enums as
  4962. // properties of namespaces just like static code does. This allows using a .d.ts generated for
  4963. // a static module with reflection-based solutions where the condition is met.
  4964. };
  4965. /**
  4966. * Called when any object is removed from this root or its sub-namespaces.
  4967. * @param {ReflectionObject} object Object removed
  4968. * @returns {undefined}
  4969. * @private
  4970. */
  4971. Root.prototype._handleRemove = function _handleRemove(object) {
  4972. if (object instanceof Field) {
  4973. if (/* an extension field */ object.extend !== undefined) {
  4974. if (/* already handled */ object.extensionField) { // remove its sister field
  4975. object.extensionField.parent.remove(object.extensionField);
  4976. object.extensionField = null;
  4977. } else { // cancel the extension
  4978. var index = this.deferred.indexOf(object);
  4979. /* istanbul ignore else */
  4980. if (index > -1)
  4981. this.deferred.splice(index, 1);
  4982. }
  4983. }
  4984. } else if (object instanceof Enum) {
  4985. if (exposeRe.test(object.name))
  4986. delete object.parent[object.name]; // unexpose enum values
  4987. } else if (object instanceof Namespace) {
  4988. for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace
  4989. this._handleRemove(object._nestedArray[i]);
  4990. if (exposeRe.test(object.name))
  4991. delete object.parent[object.name]; // unexpose namespaces
  4992. }
  4993. };
  4994. // Sets up cyclic dependencies (called in index-light)
  4995. Root._configure = function(Type_, parse_, common_) {
  4996. Type = Type_;
  4997. parse = parse_;
  4998. common = common_;
  4999. };
  5000. },{"15":15,"16":16,"23":23,"25":25,"37":37}],30:[function(require,module,exports){
  5001. "use strict";
  5002. module.exports = {};
  5003. /**
  5004. * Named roots.
  5005. * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
  5006. * Can also be used manually to make roots available accross modules.
  5007. * @name roots
  5008. * @type {Object.<string,Root>}
  5009. * @example
  5010. * // pbjs -r myroot -o compiled.js ...
  5011. *
  5012. * // in another module:
  5013. * require("./compiled.js");
  5014. *
  5015. * // in any subsequent module:
  5016. * var root = protobuf.roots["myroot"];
  5017. */
  5018. },{}],31:[function(require,module,exports){
  5019. "use strict";
  5020. /**
  5021. * Streaming RPC helpers.
  5022. * @namespace
  5023. */
  5024. var rpc = exports;
  5025. /**
  5026. * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
  5027. * @typedef RPCImpl
  5028. * @type {function}
  5029. * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
  5030. * @param {Uint8Array} requestData Request data
  5031. * @param {RPCImplCallback} callback Callback function
  5032. * @returns {undefined}
  5033. * @example
  5034. * function rpcImpl(method, requestData, callback) {
  5035. * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
  5036. * throw Error("no such method");
  5037. * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
  5038. * callback(err, responseData);
  5039. * });
  5040. * }
  5041. */
  5042. /**
  5043. * Node-style callback as used by {@link RPCImpl}.
  5044. * @typedef RPCImplCallback
  5045. * @type {function}
  5046. * @param {Error|null} error Error, if any, otherwise `null`
  5047. * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
  5048. * @returns {undefined}
  5049. */
  5050. rpc.Service = require(32);
  5051. },{"32":32}],32:[function(require,module,exports){
  5052. "use strict";
  5053. module.exports = Service;
  5054. var util = require(39);
  5055. // Extends EventEmitter
  5056. (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
  5057. /**
  5058. * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
  5059. *
  5060. * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
  5061. * @typedef rpc.ServiceMethodCallback
  5062. * @template TRes extends Message<TRes>
  5063. * @type {function}
  5064. * @param {Error|null} error Error, if any
  5065. * @param {TRes} [response] Response message
  5066. * @returns {undefined}
  5067. */
  5068. /**
  5069. * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
  5070. * @typedef rpc.ServiceMethod
  5071. * @template TReq extends Message<TReq>
  5072. * @template TRes extends Message<TRes>
  5073. * @type {function}
  5074. * @param {TReq|Properties<TReq>} request Request message or plain object
  5075. * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
  5076. * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
  5077. */
  5078. /**
  5079. * Constructs a new RPC service instance.
  5080. * @classdesc An RPC service as returned by {@link Service#create}.
  5081. * @exports rpc.Service
  5082. * @extends util.EventEmitter
  5083. * @constructor
  5084. * @param {RPCImpl} rpcImpl RPC implementation
  5085. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  5086. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  5087. */
  5088. function Service(rpcImpl, requestDelimited, responseDelimited) {
  5089. if (typeof rpcImpl !== "function")
  5090. throw TypeError("rpcImpl must be a function");
  5091. util.EventEmitter.call(this);
  5092. /**
  5093. * RPC implementation. Becomes `null` once the service is ended.
  5094. * @type {RPCImpl|null}
  5095. */
  5096. this.rpcImpl = rpcImpl;
  5097. /**
  5098. * Whether requests are length-delimited.
  5099. * @type {boolean}
  5100. */
  5101. this.requestDelimited = Boolean(requestDelimited);
  5102. /**
  5103. * Whether responses are length-delimited.
  5104. * @type {boolean}
  5105. */
  5106. this.responseDelimited = Boolean(responseDelimited);
  5107. }
  5108. /**
  5109. * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
  5110. * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
  5111. * @param {Constructor<TReq>} requestCtor Request constructor
  5112. * @param {Constructor<TRes>} responseCtor Response constructor
  5113. * @param {TReq|Properties<TReq>} request Request message or plain object
  5114. * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
  5115. * @returns {undefined}
  5116. * @template TReq extends Message<TReq>
  5117. * @template TRes extends Message<TRes>
  5118. */
  5119. Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
  5120. if (!request)
  5121. throw TypeError("request must be specified");
  5122. var self = this;
  5123. if (!callback)
  5124. return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
  5125. if (!self.rpcImpl) {
  5126. setTimeout(function() { callback(Error("already ended")); }, 0);
  5127. return undefined;
  5128. }
  5129. try {
  5130. return self.rpcImpl(
  5131. method,
  5132. requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
  5133. function rpcCallback(err, response) {
  5134. if (err) {
  5135. self.emit("error", err, method);
  5136. return callback(err);
  5137. }
  5138. if (response === null) {
  5139. self.end(/* endedByRPC */ true);
  5140. return undefined;
  5141. }
  5142. if (!(response instanceof responseCtor)) {
  5143. try {
  5144. response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
  5145. } catch (err) {
  5146. self.emit("error", err, method);
  5147. return callback(err);
  5148. }
  5149. }
  5150. self.emit("data", response, method);
  5151. return callback(null, response);
  5152. }
  5153. );
  5154. } catch (err) {
  5155. self.emit("error", err, method);
  5156. setTimeout(function() { callback(err); }, 0);
  5157. return undefined;
  5158. }
  5159. };
  5160. /**
  5161. * Ends this service and emits the `end` event.
  5162. * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
  5163. * @returns {rpc.Service} `this`
  5164. */
  5165. Service.prototype.end = function end(endedByRPC) {
  5166. if (this.rpcImpl) {
  5167. if (!endedByRPC) // signal end to rpcImpl
  5168. this.rpcImpl(null, null, null);
  5169. this.rpcImpl = null;
  5170. this.emit("end").off();
  5171. }
  5172. return this;
  5173. };
  5174. },{"39":39}],33:[function(require,module,exports){
  5175. "use strict";
  5176. module.exports = Service;
  5177. // extends Namespace
  5178. var Namespace = require(23);
  5179. ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
  5180. var Method = require(22),
  5181. util = require(37),
  5182. rpc = require(31);
  5183. /**
  5184. * Constructs a new service instance.
  5185. * @classdesc Reflected service.
  5186. * @extends NamespaceBase
  5187. * @constructor
  5188. * @param {string} name Service name
  5189. * @param {Object.<string,*>} [options] Service options
  5190. * @throws {TypeError} If arguments are invalid
  5191. */
  5192. function Service(name, options) {
  5193. Namespace.call(this, name, options);
  5194. /**
  5195. * Service methods.
  5196. * @type {Object.<string,Method>}
  5197. */
  5198. this.methods = {}; // toJSON, marker
  5199. /**
  5200. * Cached methods as an array.
  5201. * @type {Method[]|null}
  5202. * @private
  5203. */
  5204. this._methodsArray = null;
  5205. }
  5206. /**
  5207. * Service descriptor.
  5208. * @interface IService
  5209. * @extends INamespace
  5210. * @property {Object.<string,IMethod>} methods Method descriptors
  5211. */
  5212. /**
  5213. * Constructs a service from a service descriptor.
  5214. * @param {string} name Service name
  5215. * @param {IService} json Service descriptor
  5216. * @returns {Service} Created service
  5217. * @throws {TypeError} If arguments are invalid
  5218. */
  5219. Service.fromJSON = function fromJSON(name, json) {
  5220. var service = new Service(name, json.options);
  5221. /* istanbul ignore else */
  5222. if (json.methods)
  5223. for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)
  5224. service.add(Method.fromJSON(names[i], json.methods[names[i]]));
  5225. if (json.nested)
  5226. service.addJSON(json.nested);
  5227. service.comment = json.comment;
  5228. return service;
  5229. };
  5230. /**
  5231. * Converts this service to a service descriptor.
  5232. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  5233. * @returns {IService} Service descriptor
  5234. */
  5235. Service.prototype.toJSON = function toJSON(toJSONOptions) {
  5236. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  5237. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  5238. return util.toObject([
  5239. "options" , inherited && inherited.options || undefined,
  5240. "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},
  5241. "nested" , inherited && inherited.nested || undefined,
  5242. "comment" , keepComments ? this.comment : undefined
  5243. ]);
  5244. };
  5245. /**
  5246. * Methods of this service as an array for iteration.
  5247. * @name Service#methodsArray
  5248. * @type {Method[]}
  5249. * @readonly
  5250. */
  5251. Object.defineProperty(Service.prototype, "methodsArray", {
  5252. get: function() {
  5253. return this._methodsArray || (this._methodsArray = util.toArray(this.methods));
  5254. }
  5255. });
  5256. function clearCache(service) {
  5257. service._methodsArray = null;
  5258. return service;
  5259. }
  5260. /**
  5261. * @override
  5262. */
  5263. Service.prototype.get = function get(name) {
  5264. return this.methods[name]
  5265. || Namespace.prototype.get.call(this, name);
  5266. };
  5267. /**
  5268. * @override
  5269. */
  5270. Service.prototype.resolveAll = function resolveAll() {
  5271. var methods = this.methodsArray;
  5272. for (var i = 0; i < methods.length; ++i)
  5273. methods[i].resolve();
  5274. return Namespace.prototype.resolve.call(this);
  5275. };
  5276. /**
  5277. * @override
  5278. */
  5279. Service.prototype.add = function add(object) {
  5280. /* istanbul ignore if */
  5281. if (this.get(object.name))
  5282. throw Error("duplicate name '" + object.name + "' in " + this);
  5283. if (object instanceof Method) {
  5284. this.methods[object.name] = object;
  5285. object.parent = this;
  5286. return clearCache(this);
  5287. }
  5288. return Namespace.prototype.add.call(this, object);
  5289. };
  5290. /**
  5291. * @override
  5292. */
  5293. Service.prototype.remove = function remove(object) {
  5294. if (object instanceof Method) {
  5295. /* istanbul ignore if */
  5296. if (this.methods[object.name] !== object)
  5297. throw Error(object + " is not a member of " + this);
  5298. delete this.methods[object.name];
  5299. object.parent = null;
  5300. return clearCache(this);
  5301. }
  5302. return Namespace.prototype.remove.call(this, object);
  5303. };
  5304. /**
  5305. * Creates a runtime service using the specified rpc implementation.
  5306. * @param {RPCImpl} rpcImpl RPC implementation
  5307. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  5308. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  5309. * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.
  5310. */
  5311. Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {
  5312. var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
  5313. for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {
  5314. var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
  5315. rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({
  5316. m: method,
  5317. q: method.resolvedRequestType.ctor,
  5318. s: method.resolvedResponseType.ctor
  5319. });
  5320. }
  5321. return rpcService;
  5322. };
  5323. },{"22":22,"23":23,"31":31,"37":37}],34:[function(require,module,exports){
  5324. "use strict";
  5325. module.exports = tokenize;
  5326. var delimRe = /[\s{}=;:[\],'"()<>]/g,
  5327. stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
  5328. stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
  5329. var setCommentRe = /^ *[*/]+ */,
  5330. setCommentAltRe = /^\s*\*?\/*/,
  5331. setCommentSplitRe = /\n/g,
  5332. whitespaceRe = /\s/,
  5333. unescapeRe = /\\(.?)/g;
  5334. var unescapeMap = {
  5335. "0": "\0",
  5336. "r": "\r",
  5337. "n": "\n",
  5338. "t": "\t"
  5339. };
  5340. /**
  5341. * Unescapes a string.
  5342. * @param {string} str String to unescape
  5343. * @returns {string} Unescaped string
  5344. * @property {Object.<string,string>} map Special characters map
  5345. * @memberof tokenize
  5346. */
  5347. function unescape(str) {
  5348. return str.replace(unescapeRe, function($0, $1) {
  5349. switch ($1) {
  5350. case "\\":
  5351. case "":
  5352. return $1;
  5353. default:
  5354. return unescapeMap[$1] || "";
  5355. }
  5356. });
  5357. }
  5358. tokenize.unescape = unescape;
  5359. /**
  5360. * Gets the next token and advances.
  5361. * @typedef TokenizerHandleNext
  5362. * @type {function}
  5363. * @returns {string|null} Next token or `null` on eof
  5364. */
  5365. /**
  5366. * Peeks for the next token.
  5367. * @typedef TokenizerHandlePeek
  5368. * @type {function}
  5369. * @returns {string|null} Next token or `null` on eof
  5370. */
  5371. /**
  5372. * Pushes a token back to the stack.
  5373. * @typedef TokenizerHandlePush
  5374. * @type {function}
  5375. * @param {string} token Token
  5376. * @returns {undefined}
  5377. */
  5378. /**
  5379. * Skips the next token.
  5380. * @typedef TokenizerHandleSkip
  5381. * @type {function}
  5382. * @param {string} expected Expected token
  5383. * @param {boolean} [optional=false] If optional
  5384. * @returns {boolean} Whether the token matched
  5385. * @throws {Error} If the token didn't match and is not optional
  5386. */
  5387. /**
  5388. * Gets the comment on the previous line or, alternatively, the line comment on the specified line.
  5389. * @typedef TokenizerHandleCmnt
  5390. * @type {function}
  5391. * @param {number} [line] Line number
  5392. * @returns {string|null} Comment text or `null` if none
  5393. */
  5394. /**
  5395. * Handle object returned from {@link tokenize}.
  5396. * @interface ITokenizerHandle
  5397. * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)
  5398. * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)
  5399. * @property {TokenizerHandlePush} push Pushes a token back to the stack
  5400. * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws
  5401. * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any
  5402. * @property {number} line Current line number
  5403. */
  5404. /**
  5405. * Tokenizes the given .proto source and returns an object with useful utility functions.
  5406. * @param {string} source Source contents
  5407. * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.
  5408. * @returns {ITokenizerHandle} Tokenizer handle
  5409. */
  5410. function tokenize(source, alternateCommentMode) {
  5411. /* eslint-disable callback-return */
  5412. source = source.toString();
  5413. var offset = 0,
  5414. length = source.length,
  5415. line = 1,
  5416. commentType = null,
  5417. commentText = null,
  5418. commentLine = 0,
  5419. commentLineEmpty = false,
  5420. commentIsLeading = false;
  5421. var stack = [];
  5422. var stringDelim = null;
  5423. /* istanbul ignore next */
  5424. /**
  5425. * Creates an error for illegal syntax.
  5426. * @param {string} subject Subject
  5427. * @returns {Error} Error created
  5428. * @inner
  5429. */
  5430. function illegal(subject) {
  5431. return Error("illegal " + subject + " (line " + line + ")");
  5432. }
  5433. /**
  5434. * Reads a string till its end.
  5435. * @returns {string} String read
  5436. * @inner
  5437. */
  5438. function readString() {
  5439. var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
  5440. re.lastIndex = offset - 1;
  5441. var match = re.exec(source);
  5442. if (!match)
  5443. throw illegal("string");
  5444. offset = re.lastIndex;
  5445. push(stringDelim);
  5446. stringDelim = null;
  5447. return unescape(match[1]);
  5448. }
  5449. /**
  5450. * Gets the character at `pos` within the source.
  5451. * @param {number} pos Position
  5452. * @returns {string} Character
  5453. * @inner
  5454. */
  5455. function charAt(pos) {
  5456. return source.charAt(pos);
  5457. }
  5458. /**
  5459. * Sets the current comment text.
  5460. * @param {number} start Start offset
  5461. * @param {number} end End offset
  5462. * @param {boolean} isLeading set if a leading comment
  5463. * @returns {undefined}
  5464. * @inner
  5465. */
  5466. function setComment(start, end, isLeading) {
  5467. commentType = source.charAt(start++);
  5468. commentLine = line;
  5469. commentLineEmpty = false;
  5470. commentIsLeading = isLeading;
  5471. var lookback;
  5472. if (alternateCommentMode) {
  5473. lookback = 2; // alternate comment parsing: "//" or "/*"
  5474. } else {
  5475. lookback = 3; // "///" or "/**"
  5476. }
  5477. var commentOffset = start - lookback,
  5478. c;
  5479. do {
  5480. if (--commentOffset < 0 ||
  5481. (c = source.charAt(commentOffset)) === "\n") {
  5482. commentLineEmpty = true;
  5483. break;
  5484. }
  5485. } while (c === " " || c === "\t");
  5486. var lines = source
  5487. .substring(start, end)
  5488. .split(setCommentSplitRe);
  5489. for (var i = 0; i < lines.length; ++i)
  5490. lines[i] = lines[i]
  5491. .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "")
  5492. .trim();
  5493. commentText = lines
  5494. .join("\n")
  5495. .trim();
  5496. }
  5497. function isDoubleSlashCommentLine(startOffset) {
  5498. var endOffset = findEndOfLine(startOffset);
  5499. // see if remaining line matches comment pattern
  5500. var lineText = source.substring(startOffset, endOffset);
  5501. // look for 1 or 2 slashes since startOffset would already point past
  5502. // the first slash that started the comment.
  5503. var isComment = /^\s*\/{1,2}/.test(lineText);
  5504. return isComment;
  5505. }
  5506. function findEndOfLine(cursor) {
  5507. // find end of cursor's line
  5508. var endOffset = cursor;
  5509. while (endOffset < length && charAt(endOffset) !== "\n") {
  5510. endOffset++;
  5511. }
  5512. return endOffset;
  5513. }
  5514. /**
  5515. * Obtains the next token.
  5516. * @returns {string|null} Next token or `null` on eof
  5517. * @inner
  5518. */
  5519. function next() {
  5520. if (stack.length > 0)
  5521. return stack.shift();
  5522. if (stringDelim)
  5523. return readString();
  5524. var repeat,
  5525. prev,
  5526. curr,
  5527. start,
  5528. isDoc,
  5529. isLeadingComment = offset === 0;
  5530. do {
  5531. if (offset === length)
  5532. return null;
  5533. repeat = false;
  5534. while (whitespaceRe.test(curr = charAt(offset))) {
  5535. if (curr === "\n") {
  5536. isLeadingComment = true;
  5537. ++line;
  5538. }
  5539. if (++offset === length)
  5540. return null;
  5541. }
  5542. if (charAt(offset) === "/") {
  5543. if (++offset === length) {
  5544. throw illegal("comment");
  5545. }
  5546. if (charAt(offset) === "/") { // Line
  5547. if (!alternateCommentMode) {
  5548. // check for triple-slash comment
  5549. isDoc = charAt(start = offset + 1) === "/";
  5550. while (charAt(++offset) !== "\n") {
  5551. if (offset === length) {
  5552. return null;
  5553. }
  5554. }
  5555. ++offset;
  5556. if (isDoc) {
  5557. setComment(start, offset - 1, isLeadingComment);
  5558. }
  5559. ++line;
  5560. repeat = true;
  5561. } else {
  5562. // check for double-slash comments, consolidating consecutive lines
  5563. start = offset;
  5564. isDoc = false;
  5565. if (isDoubleSlashCommentLine(offset)) {
  5566. isDoc = true;
  5567. do {
  5568. offset = findEndOfLine(offset);
  5569. if (offset === length) {
  5570. break;
  5571. }
  5572. offset++;
  5573. } while (isDoubleSlashCommentLine(offset));
  5574. } else {
  5575. offset = Math.min(length, findEndOfLine(offset) + 1);
  5576. }
  5577. if (isDoc) {
  5578. setComment(start, offset, isLeadingComment);
  5579. }
  5580. line++;
  5581. repeat = true;
  5582. }
  5583. } else if ((curr = charAt(offset)) === "*") { /* Block */
  5584. // check for /** (regular comment mode) or /* (alternate comment mode)
  5585. start = offset + 1;
  5586. isDoc = alternateCommentMode || charAt(start) === "*";
  5587. do {
  5588. if (curr === "\n") {
  5589. ++line;
  5590. }
  5591. if (++offset === length) {
  5592. throw illegal("comment");
  5593. }
  5594. prev = curr;
  5595. curr = charAt(offset);
  5596. } while (prev !== "*" || curr !== "/");
  5597. ++offset;
  5598. if (isDoc) {
  5599. setComment(start, offset - 2, isLeadingComment);
  5600. }
  5601. repeat = true;
  5602. } else {
  5603. return "/";
  5604. }
  5605. }
  5606. } while (repeat);
  5607. // offset !== length if we got here
  5608. var end = offset;
  5609. delimRe.lastIndex = 0;
  5610. var delim = delimRe.test(charAt(end++));
  5611. if (!delim)
  5612. while (end < length && !delimRe.test(charAt(end)))
  5613. ++end;
  5614. var token = source.substring(offset, offset = end);
  5615. if (token === "\"" || token === "'")
  5616. stringDelim = token;
  5617. return token;
  5618. }
  5619. /**
  5620. * Pushes a token back to the stack.
  5621. * @param {string} token Token
  5622. * @returns {undefined}
  5623. * @inner
  5624. */
  5625. function push(token) {
  5626. stack.push(token);
  5627. }
  5628. /**
  5629. * Peeks for the next token.
  5630. * @returns {string|null} Token or `null` on eof
  5631. * @inner
  5632. */
  5633. function peek() {
  5634. if (!stack.length) {
  5635. var token = next();
  5636. if (token === null)
  5637. return null;
  5638. push(token);
  5639. }
  5640. return stack[0];
  5641. }
  5642. /**
  5643. * Skips a token.
  5644. * @param {string} expected Expected token
  5645. * @param {boolean} [optional=false] Whether the token is optional
  5646. * @returns {boolean} `true` when skipped, `false` if not
  5647. * @throws {Error} When a required token is not present
  5648. * @inner
  5649. */
  5650. function skip(expected, optional) {
  5651. var actual = peek(),
  5652. equals = actual === expected;
  5653. if (equals) {
  5654. next();
  5655. return true;
  5656. }
  5657. if (!optional)
  5658. throw illegal("token '" + actual + "', '" + expected + "' expected");
  5659. return false;
  5660. }
  5661. /**
  5662. * Gets a comment.
  5663. * @param {number} [trailingLine] Line number if looking for a trailing comment
  5664. * @returns {string|null} Comment text
  5665. * @inner
  5666. */
  5667. function cmnt(trailingLine) {
  5668. var ret = null;
  5669. if (trailingLine === undefined) {
  5670. if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) {
  5671. ret = commentIsLeading ? commentText : null;
  5672. }
  5673. } else {
  5674. /* istanbul ignore else */
  5675. if (commentLine < trailingLine) {
  5676. peek();
  5677. }
  5678. if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) {
  5679. ret = commentIsLeading ? null : commentText;
  5680. }
  5681. }
  5682. return ret;
  5683. }
  5684. return Object.defineProperty({
  5685. next: next,
  5686. peek: peek,
  5687. push: push,
  5688. skip: skip,
  5689. cmnt: cmnt
  5690. }, "line", {
  5691. get: function() { return line; }
  5692. });
  5693. /* eslint-enable callback-return */
  5694. }
  5695. },{}],35:[function(require,module,exports){
  5696. "use strict";
  5697. module.exports = Type;
  5698. // extends Namespace
  5699. var Namespace = require(23);
  5700. ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";
  5701. var Enum = require(15),
  5702. OneOf = require(25),
  5703. Field = require(16),
  5704. MapField = require(20),
  5705. Service = require(33),
  5706. Message = require(21),
  5707. Reader = require(27),
  5708. Writer = require(42),
  5709. util = require(37),
  5710. encoder = require(14),
  5711. decoder = require(13),
  5712. verifier = require(40),
  5713. converter = require(12),
  5714. wrappers = require(41);
  5715. /**
  5716. * Constructs a new reflected message type instance.
  5717. * @classdesc Reflected message type.
  5718. * @extends NamespaceBase
  5719. * @constructor
  5720. * @param {string} name Message name
  5721. * @param {Object.<string,*>} [options] Declared options
  5722. */
  5723. function Type(name, options) {
  5724. Namespace.call(this, name, options);
  5725. /**
  5726. * Message fields.
  5727. * @type {Object.<string,Field>}
  5728. */
  5729. this.fields = {}; // toJSON, marker
  5730. /**
  5731. * Oneofs declared within this namespace, if any.
  5732. * @type {Object.<string,OneOf>}
  5733. */
  5734. this.oneofs = undefined; // toJSON
  5735. /**
  5736. * Extension ranges, if any.
  5737. * @type {number[][]}
  5738. */
  5739. this.extensions = undefined; // toJSON
  5740. /**
  5741. * Reserved ranges, if any.
  5742. * @type {Array.<number[]|string>}
  5743. */
  5744. this.reserved = undefined; // toJSON
  5745. /*?
  5746. * Whether this type is a legacy group.
  5747. * @type {boolean|undefined}
  5748. */
  5749. this.group = undefined; // toJSON
  5750. /**
  5751. * Cached fields by id.
  5752. * @type {Object.<number,Field>|null}
  5753. * @private
  5754. */
  5755. this._fieldsById = null;
  5756. /**
  5757. * Cached fields as an array.
  5758. * @type {Field[]|null}
  5759. * @private
  5760. */
  5761. this._fieldsArray = null;
  5762. /**
  5763. * Cached oneofs as an array.
  5764. * @type {OneOf[]|null}
  5765. * @private
  5766. */
  5767. this._oneofsArray = null;
  5768. /**
  5769. * Cached constructor.
  5770. * @type {Constructor<{}>}
  5771. * @private
  5772. */
  5773. this._ctor = null;
  5774. }
  5775. Object.defineProperties(Type.prototype, {
  5776. /**
  5777. * Message fields by id.
  5778. * @name Type#fieldsById
  5779. * @type {Object.<number,Field>}
  5780. * @readonly
  5781. */
  5782. fieldsById: {
  5783. get: function() {
  5784. /* istanbul ignore if */
  5785. if (this._fieldsById)
  5786. return this._fieldsById;
  5787. this._fieldsById = {};
  5788. for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
  5789. var field = this.fields[names[i]],
  5790. id = field.id;
  5791. /* istanbul ignore if */
  5792. if (this._fieldsById[id])
  5793. throw Error("duplicate id " + id + " in " + this);
  5794. this._fieldsById[id] = field;
  5795. }
  5796. return this._fieldsById;
  5797. }
  5798. },
  5799. /**
  5800. * Fields of this message as an array for iteration.
  5801. * @name Type#fieldsArray
  5802. * @type {Field[]}
  5803. * @readonly
  5804. */
  5805. fieldsArray: {
  5806. get: function() {
  5807. return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
  5808. }
  5809. },
  5810. /**
  5811. * Oneofs of this message as an array for iteration.
  5812. * @name Type#oneofsArray
  5813. * @type {OneOf[]}
  5814. * @readonly
  5815. */
  5816. oneofsArray: {
  5817. get: function() {
  5818. return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
  5819. }
  5820. },
  5821. /**
  5822. * The registered constructor, if any registered, otherwise a generic constructor.
  5823. * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
  5824. * @name Type#ctor
  5825. * @type {Constructor<{}>}
  5826. */
  5827. ctor: {
  5828. get: function() {
  5829. return this._ctor || (this.ctor = Type.generateConstructor(this)());
  5830. },
  5831. set: function(ctor) {
  5832. // Ensure proper prototype
  5833. var prototype = ctor.prototype;
  5834. if (!(prototype instanceof Message)) {
  5835. (ctor.prototype = new Message()).constructor = ctor;
  5836. util.merge(ctor.prototype, prototype);
  5837. }
  5838. // Classes and messages reference their reflected type
  5839. ctor.$type = ctor.prototype.$type = this;
  5840. // Mix in static methods
  5841. util.merge(ctor, Message, true);
  5842. this._ctor = ctor;
  5843. // Messages have non-enumerable default values on their prototype
  5844. var i = 0;
  5845. for (; i < /* initializes */ this.fieldsArray.length; ++i)
  5846. this._fieldsArray[i].resolve(); // ensures a proper value
  5847. // Messages have non-enumerable getters and setters for each virtual oneof field
  5848. var ctorProperties = {};
  5849. for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)
  5850. ctorProperties[this._oneofsArray[i].resolve().name] = {
  5851. get: util.oneOfGetter(this._oneofsArray[i].oneof),
  5852. set: util.oneOfSetter(this._oneofsArray[i].oneof)
  5853. };
  5854. if (i)
  5855. Object.defineProperties(ctor.prototype, ctorProperties);
  5856. }
  5857. }
  5858. });
  5859. /**
  5860. * Generates a constructor function for the specified type.
  5861. * @param {Type} mtype Message type
  5862. * @returns {Codegen} Codegen instance
  5863. */
  5864. Type.generateConstructor = function generateConstructor(mtype) {
  5865. /* eslint-disable no-unexpected-multiline */
  5866. var gen = util.codegen(["p"], mtype.name);
  5867. // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype
  5868. for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
  5869. if ((field = mtype._fieldsArray[i]).map) gen
  5870. ("this%s={}", util.safeProp(field.name));
  5871. else if (field.repeated) gen
  5872. ("this%s=[]", util.safeProp(field.name));
  5873. return gen
  5874. ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null
  5875. ("this[ks[i]]=p[ks[i]]");
  5876. /* eslint-enable no-unexpected-multiline */
  5877. };
  5878. function clearCache(type) {
  5879. type._fieldsById = type._fieldsArray = type._oneofsArray = null;
  5880. delete type.encode;
  5881. delete type.decode;
  5882. delete type.verify;
  5883. return type;
  5884. }
  5885. /**
  5886. * Message type descriptor.
  5887. * @interface IType
  5888. * @extends INamespace
  5889. * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors
  5890. * @property {Object.<string,IField>} fields Field descriptors
  5891. * @property {number[][]} [extensions] Extension ranges
  5892. * @property {number[][]} [reserved] Reserved ranges
  5893. * @property {boolean} [group=false] Whether a legacy group or not
  5894. */
  5895. /**
  5896. * Creates a message type from a message type descriptor.
  5897. * @param {string} name Message name
  5898. * @param {IType} json Message type descriptor
  5899. * @returns {Type} Created message type
  5900. */
  5901. Type.fromJSON = function fromJSON(name, json) {
  5902. var type = new Type(name, json.options);
  5903. type.extensions = json.extensions;
  5904. type.reserved = json.reserved;
  5905. var names = Object.keys(json.fields),
  5906. i = 0;
  5907. for (; i < names.length; ++i)
  5908. type.add(
  5909. ( typeof json.fields[names[i]].keyType !== "undefined"
  5910. ? MapField.fromJSON
  5911. : Field.fromJSON )(names[i], json.fields[names[i]])
  5912. );
  5913. if (json.oneofs)
  5914. for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)
  5915. type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));
  5916. if (json.nested)
  5917. for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {
  5918. var nested = json.nested[names[i]];
  5919. type.add( // most to least likely
  5920. ( nested.id !== undefined
  5921. ? Field.fromJSON
  5922. : nested.fields !== undefined
  5923. ? Type.fromJSON
  5924. : nested.values !== undefined
  5925. ? Enum.fromJSON
  5926. : nested.methods !== undefined
  5927. ? Service.fromJSON
  5928. : Namespace.fromJSON )(names[i], nested)
  5929. );
  5930. }
  5931. if (json.extensions && json.extensions.length)
  5932. type.extensions = json.extensions;
  5933. if (json.reserved && json.reserved.length)
  5934. type.reserved = json.reserved;
  5935. if (json.group)
  5936. type.group = true;
  5937. if (json.comment)
  5938. type.comment = json.comment;
  5939. return type;
  5940. };
  5941. /**
  5942. * Converts this message type to a message type descriptor.
  5943. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
  5944. * @returns {IType} Message type descriptor
  5945. */
  5946. Type.prototype.toJSON = function toJSON(toJSONOptions) {
  5947. var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
  5948. var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
  5949. return util.toObject([
  5950. "options" , inherited && inherited.options || undefined,
  5951. "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
  5952. "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},
  5953. "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,
  5954. "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
  5955. "group" , this.group || undefined,
  5956. "nested" , inherited && inherited.nested || undefined,
  5957. "comment" , keepComments ? this.comment : undefined
  5958. ]);
  5959. };
  5960. /**
  5961. * @override
  5962. */
  5963. Type.prototype.resolveAll = function resolveAll() {
  5964. var fields = this.fieldsArray, i = 0;
  5965. while (i < fields.length)
  5966. fields[i++].resolve();
  5967. var oneofs = this.oneofsArray; i = 0;
  5968. while (i < oneofs.length)
  5969. oneofs[i++].resolve();
  5970. return Namespace.prototype.resolveAll.call(this);
  5971. };
  5972. /**
  5973. * @override
  5974. */
  5975. Type.prototype.get = function get(name) {
  5976. return this.fields[name]
  5977. || this.oneofs && this.oneofs[name]
  5978. || this.nested && this.nested[name]
  5979. || null;
  5980. };
  5981. /**
  5982. * Adds a nested object to this type.
  5983. * @param {ReflectionObject} object Nested object to add
  5984. * @returns {Type} `this`
  5985. * @throws {TypeError} If arguments are invalid
  5986. * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id
  5987. */
  5988. Type.prototype.add = function add(object) {
  5989. if (this.get(object.name))
  5990. throw Error("duplicate name '" + object.name + "' in " + this);
  5991. if (object instanceof Field && object.extend === undefined) {
  5992. // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
  5993. // The root object takes care of adding distinct sister-fields to the respective extended
  5994. // type instead.
  5995. // avoids calling the getter if not absolutely necessary because it's called quite frequently
  5996. if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])
  5997. throw Error("duplicate id " + object.id + " in " + this);
  5998. if (this.isReservedId(object.id))
  5999. throw Error("id " + object.id + " is reserved in " + this);
  6000. if (this.isReservedName(object.name))
  6001. throw Error("name '" + object.name + "' is reserved in " + this);
  6002. if (object.parent)
  6003. object.parent.remove(object);
  6004. this.fields[object.name] = object;
  6005. object.message = this;
  6006. object.onAdd(this);
  6007. return clearCache(this);
  6008. }
  6009. if (object instanceof OneOf) {
  6010. if (!this.oneofs)
  6011. this.oneofs = {};
  6012. this.oneofs[object.name] = object;
  6013. object.onAdd(this);
  6014. return clearCache(this);
  6015. }
  6016. return Namespace.prototype.add.call(this, object);
  6017. };
  6018. /**
  6019. * Removes a nested object from this type.
  6020. * @param {ReflectionObject} object Nested object to remove
  6021. * @returns {Type} `this`
  6022. * @throws {TypeError} If arguments are invalid
  6023. * @throws {Error} If `object` is not a member of this type
  6024. */
  6025. Type.prototype.remove = function remove(object) {
  6026. if (object instanceof Field && object.extend === undefined) {
  6027. // See Type#add for the reason why extension fields are excluded here.
  6028. /* istanbul ignore if */
  6029. if (!this.fields || this.fields[object.name] !== object)
  6030. throw Error(object + " is not a member of " + this);
  6031. delete this.fields[object.name];
  6032. object.parent = null;
  6033. object.onRemove(this);
  6034. return clearCache(this);
  6035. }
  6036. if (object instanceof OneOf) {
  6037. /* istanbul ignore if */
  6038. if (!this.oneofs || this.oneofs[object.name] !== object)
  6039. throw Error(object + " is not a member of " + this);
  6040. delete this.oneofs[object.name];
  6041. object.parent = null;
  6042. object.onRemove(this);
  6043. return clearCache(this);
  6044. }
  6045. return Namespace.prototype.remove.call(this, object);
  6046. };
  6047. /**
  6048. * Tests if the specified id is reserved.
  6049. * @param {number} id Id to test
  6050. * @returns {boolean} `true` if reserved, otherwise `false`
  6051. */
  6052. Type.prototype.isReservedId = function isReservedId(id) {
  6053. return Namespace.isReservedId(this.reserved, id);
  6054. };
  6055. /**
  6056. * Tests if the specified name is reserved.
  6057. * @param {string} name Name to test
  6058. * @returns {boolean} `true` if reserved, otherwise `false`
  6059. */
  6060. Type.prototype.isReservedName = function isReservedName(name) {
  6061. return Namespace.isReservedName(this.reserved, name);
  6062. };
  6063. /**
  6064. * Creates a new message of this type using the specified properties.
  6065. * @param {Object.<string,*>} [properties] Properties to set
  6066. * @returns {Message<{}>} Message instance
  6067. */
  6068. Type.prototype.create = function create(properties) {
  6069. return new this.ctor(properties);
  6070. };
  6071. /**
  6072. * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
  6073. * @returns {Type} `this`
  6074. */
  6075. Type.prototype.setup = function setup() {
  6076. // Sets up everything at once so that the prototype chain does not have to be re-evaluated
  6077. // multiple times (V8, soft-deopt prototype-check).
  6078. var fullName = this.fullName,
  6079. types = [];
  6080. for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)
  6081. types.push(this._fieldsArray[i].resolve().resolvedType);
  6082. // Replace setup methods with type-specific generated functions
  6083. this.encode = encoder(this)({
  6084. Writer : Writer,
  6085. types : types,
  6086. util : util
  6087. });
  6088. this.decode = decoder(this)({
  6089. Reader : Reader,
  6090. types : types,
  6091. util : util
  6092. });
  6093. this.verify = verifier(this)({
  6094. types : types,
  6095. util : util
  6096. });
  6097. this.fromObject = converter.fromObject(this)({
  6098. types : types,
  6099. util : util
  6100. });
  6101. this.toObject = converter.toObject(this)({
  6102. types : types,
  6103. util : util
  6104. });
  6105. // Inject custom wrappers for common types
  6106. var wrapper = wrappers[fullName];
  6107. if (wrapper) {
  6108. var originalThis = Object.create(this);
  6109. // if (wrapper.fromObject) {
  6110. originalThis.fromObject = this.fromObject;
  6111. this.fromObject = wrapper.fromObject.bind(originalThis);
  6112. // }
  6113. // if (wrapper.toObject) {
  6114. originalThis.toObject = this.toObject;
  6115. this.toObject = wrapper.toObject.bind(originalThis);
  6116. // }
  6117. }
  6118. return this;
  6119. };
  6120. /**
  6121. * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
  6122. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  6123. * @param {Writer} [writer] Writer to encode to
  6124. * @returns {Writer} writer
  6125. */
  6126. Type.prototype.encode = function encode_setup(message, writer) {
  6127. return this.setup().encode(message, writer); // overrides this method
  6128. };
  6129. /**
  6130. * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
  6131. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  6132. * @param {Writer} [writer] Writer to encode to
  6133. * @returns {Writer} writer
  6134. */
  6135. Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {
  6136. return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
  6137. };
  6138. /**
  6139. * Decodes a message of this type.
  6140. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  6141. * @param {number} [length] Length of the message, if known beforehand
  6142. * @returns {Message<{}>} Decoded message
  6143. * @throws {Error} If the payload is not a reader or valid buffer
  6144. * @throws {util.ProtocolError<{}>} If required fields are missing
  6145. */
  6146. Type.prototype.decode = function decode_setup(reader, length) {
  6147. return this.setup().decode(reader, length); // overrides this method
  6148. };
  6149. /**
  6150. * Decodes a message of this type preceeded by its byte length as a varint.
  6151. * @param {Reader|Uint8Array} reader Reader or buffer to decode from
  6152. * @returns {Message<{}>} Decoded message
  6153. * @throws {Error} If the payload is not a reader or valid buffer
  6154. * @throws {util.ProtocolError} If required fields are missing
  6155. */
  6156. Type.prototype.decodeDelimited = function decodeDelimited(reader) {
  6157. if (!(reader instanceof Reader))
  6158. reader = Reader.create(reader);
  6159. return this.decode(reader, reader.uint32());
  6160. };
  6161. /**
  6162. * Verifies that field values are valid and that required fields are present.
  6163. * @param {Object.<string,*>} message Plain object to verify
  6164. * @returns {null|string} `null` if valid, otherwise the reason why it is not
  6165. */
  6166. Type.prototype.verify = function verify_setup(message) {
  6167. return this.setup().verify(message); // overrides this method
  6168. };
  6169. /**
  6170. * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
  6171. * @param {Object.<string,*>} object Plain object to convert
  6172. * @returns {Message<{}>} Message instance
  6173. */
  6174. Type.prototype.fromObject = function fromObject(object) {
  6175. return this.setup().fromObject(object);
  6176. };
  6177. /**
  6178. * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.
  6179. * @interface IConversionOptions
  6180. * @property {Function} [longs] Long conversion type.
  6181. * Valid values are `String` and `Number` (the global types).
  6182. * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
  6183. * @property {Function} [enums] Enum value conversion type.
  6184. * Only valid value is `String` (the global type).
  6185. * Defaults to copy the present value, which is the numeric id.
  6186. * @property {Function} [bytes] Bytes value conversion type.
  6187. * Valid values are `Array` and (a base64 encoded) `String` (the global types).
  6188. * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
  6189. * @property {boolean} [defaults=false] Also sets default values on the resulting object
  6190. * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`
  6191. * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`
  6192. * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any
  6193. * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings
  6194. */
  6195. /**
  6196. * Creates a plain object from a message of this type. Also converts values to other types if specified.
  6197. * @param {Message<{}>} message Message instance
  6198. * @param {IConversionOptions} [options] Conversion options
  6199. * @returns {Object.<string,*>} Plain object
  6200. */
  6201. Type.prototype.toObject = function toObject(message, options) {
  6202. return this.setup().toObject(message, options);
  6203. };
  6204. /**
  6205. * Decorator function as returned by {@link Type.d} (TypeScript).
  6206. * @typedef TypeDecorator
  6207. * @type {function}
  6208. * @param {Constructor<T>} target Target constructor
  6209. * @returns {undefined}
  6210. * @template T extends Message<T>
  6211. */
  6212. /**
  6213. * Type decorator (TypeScript).
  6214. * @param {string} [typeName] Type name, defaults to the constructor's name
  6215. * @returns {TypeDecorator<T>} Decorator function
  6216. * @template T extends Message<T>
  6217. */
  6218. Type.d = function decorateType(typeName) {
  6219. return function typeDecorator(target) {
  6220. util.decorateType(target, typeName);
  6221. };
  6222. };
  6223. },{"12":12,"13":13,"14":14,"15":15,"16":16,"20":20,"21":21,"23":23,"25":25,"27":27,"33":33,"37":37,"40":40,"41":41,"42":42}],36:[function(require,module,exports){
  6224. "use strict";
  6225. /**
  6226. * Common type constants.
  6227. * @namespace
  6228. */
  6229. var types = exports;
  6230. var util = require(37);
  6231. var s = [
  6232. "double", // 0
  6233. "float", // 1
  6234. "int32", // 2
  6235. "uint32", // 3
  6236. "sint32", // 4
  6237. "fixed32", // 5
  6238. "sfixed32", // 6
  6239. "int64", // 7
  6240. "uint64", // 8
  6241. "sint64", // 9
  6242. "fixed64", // 10
  6243. "sfixed64", // 11
  6244. "bool", // 12
  6245. "string", // 13
  6246. "bytes" // 14
  6247. ];
  6248. function bake(values, offset) {
  6249. var i = 0, o = {};
  6250. offset |= 0;
  6251. while (i < values.length) o[s[i + offset]] = values[i++];
  6252. return o;
  6253. }
  6254. /**
  6255. * Basic type wire types.
  6256. * @type {Object.<string,number>}
  6257. * @const
  6258. * @property {number} double=1 Fixed64 wire type
  6259. * @property {number} float=5 Fixed32 wire type
  6260. * @property {number} int32=0 Varint wire type
  6261. * @property {number} uint32=0 Varint wire type
  6262. * @property {number} sint32=0 Varint wire type
  6263. * @property {number} fixed32=5 Fixed32 wire type
  6264. * @property {number} sfixed32=5 Fixed32 wire type
  6265. * @property {number} int64=0 Varint wire type
  6266. * @property {number} uint64=0 Varint wire type
  6267. * @property {number} sint64=0 Varint wire type
  6268. * @property {number} fixed64=1 Fixed64 wire type
  6269. * @property {number} sfixed64=1 Fixed64 wire type
  6270. * @property {number} bool=0 Varint wire type
  6271. * @property {number} string=2 Ldelim wire type
  6272. * @property {number} bytes=2 Ldelim wire type
  6273. */
  6274. types.basic = bake([
  6275. /* double */ 1,
  6276. /* float */ 5,
  6277. /* int32 */ 0,
  6278. /* uint32 */ 0,
  6279. /* sint32 */ 0,
  6280. /* fixed32 */ 5,
  6281. /* sfixed32 */ 5,
  6282. /* int64 */ 0,
  6283. /* uint64 */ 0,
  6284. /* sint64 */ 0,
  6285. /* fixed64 */ 1,
  6286. /* sfixed64 */ 1,
  6287. /* bool */ 0,
  6288. /* string */ 2,
  6289. /* bytes */ 2
  6290. ]);
  6291. /**
  6292. * Basic type defaults.
  6293. * @type {Object.<string,*>}
  6294. * @const
  6295. * @property {number} double=0 Double default
  6296. * @property {number} float=0 Float default
  6297. * @property {number} int32=0 Int32 default
  6298. * @property {number} uint32=0 Uint32 default
  6299. * @property {number} sint32=0 Sint32 default
  6300. * @property {number} fixed32=0 Fixed32 default
  6301. * @property {number} sfixed32=0 Sfixed32 default
  6302. * @property {number} int64=0 Int64 default
  6303. * @property {number} uint64=0 Uint64 default
  6304. * @property {number} sint64=0 Sint32 default
  6305. * @property {number} fixed64=0 Fixed64 default
  6306. * @property {number} sfixed64=0 Sfixed64 default
  6307. * @property {boolean} bool=false Bool default
  6308. * @property {string} string="" String default
  6309. * @property {Array.<number>} bytes=Array(0) Bytes default
  6310. * @property {null} message=null Message default
  6311. */
  6312. types.defaults = bake([
  6313. /* double */ 0,
  6314. /* float */ 0,
  6315. /* int32 */ 0,
  6316. /* uint32 */ 0,
  6317. /* sint32 */ 0,
  6318. /* fixed32 */ 0,
  6319. /* sfixed32 */ 0,
  6320. /* int64 */ 0,
  6321. /* uint64 */ 0,
  6322. /* sint64 */ 0,
  6323. /* fixed64 */ 0,
  6324. /* sfixed64 */ 0,
  6325. /* bool */ false,
  6326. /* string */ "",
  6327. /* bytes */ util.emptyArray,
  6328. /* message */ null
  6329. ]);
  6330. /**
  6331. * Basic long type wire types.
  6332. * @type {Object.<string,number>}
  6333. * @const
  6334. * @property {number} int64=0 Varint wire type
  6335. * @property {number} uint64=0 Varint wire type
  6336. * @property {number} sint64=0 Varint wire type
  6337. * @property {number} fixed64=1 Fixed64 wire type
  6338. * @property {number} sfixed64=1 Fixed64 wire type
  6339. */
  6340. types.long = bake([
  6341. /* int64 */ 0,
  6342. /* uint64 */ 0,
  6343. /* sint64 */ 0,
  6344. /* fixed64 */ 1,
  6345. /* sfixed64 */ 1
  6346. ], 7);
  6347. /**
  6348. * Allowed types for map keys with their associated wire type.
  6349. * @type {Object.<string,number>}
  6350. * @const
  6351. * @property {number} int32=0 Varint wire type
  6352. * @property {number} uint32=0 Varint wire type
  6353. * @property {number} sint32=0 Varint wire type
  6354. * @property {number} fixed32=5 Fixed32 wire type
  6355. * @property {number} sfixed32=5 Fixed32 wire type
  6356. * @property {number} int64=0 Varint wire type
  6357. * @property {number} uint64=0 Varint wire type
  6358. * @property {number} sint64=0 Varint wire type
  6359. * @property {number} fixed64=1 Fixed64 wire type
  6360. * @property {number} sfixed64=1 Fixed64 wire type
  6361. * @property {number} bool=0 Varint wire type
  6362. * @property {number} string=2 Ldelim wire type
  6363. */
  6364. types.mapKey = bake([
  6365. /* int32 */ 0,
  6366. /* uint32 */ 0,
  6367. /* sint32 */ 0,
  6368. /* fixed32 */ 5,
  6369. /* sfixed32 */ 5,
  6370. /* int64 */ 0,
  6371. /* uint64 */ 0,
  6372. /* sint64 */ 0,
  6373. /* fixed64 */ 1,
  6374. /* sfixed64 */ 1,
  6375. /* bool */ 0,
  6376. /* string */ 2
  6377. ], 2);
  6378. /**
  6379. * Allowed types for packed repeated fields with their associated wire type.
  6380. * @type {Object.<string,number>}
  6381. * @const
  6382. * @property {number} double=1 Fixed64 wire type
  6383. * @property {number} float=5 Fixed32 wire type
  6384. * @property {number} int32=0 Varint wire type
  6385. * @property {number} uint32=0 Varint wire type
  6386. * @property {number} sint32=0 Varint wire type
  6387. * @property {number} fixed32=5 Fixed32 wire type
  6388. * @property {number} sfixed32=5 Fixed32 wire type
  6389. * @property {number} int64=0 Varint wire type
  6390. * @property {number} uint64=0 Varint wire type
  6391. * @property {number} sint64=0 Varint wire type
  6392. * @property {number} fixed64=1 Fixed64 wire type
  6393. * @property {number} sfixed64=1 Fixed64 wire type
  6394. * @property {number} bool=0 Varint wire type
  6395. */
  6396. types.packed = bake([
  6397. /* double */ 1,
  6398. /* float */ 5,
  6399. /* int32 */ 0,
  6400. /* uint32 */ 0,
  6401. /* sint32 */ 0,
  6402. /* fixed32 */ 5,
  6403. /* sfixed32 */ 5,
  6404. /* int64 */ 0,
  6405. /* uint64 */ 0,
  6406. /* sint64 */ 0,
  6407. /* fixed64 */ 1,
  6408. /* sfixed64 */ 1,
  6409. /* bool */ 0
  6410. ]);
  6411. },{"37":37}],37:[function(require,module,exports){
  6412. "use strict";
  6413. /**
  6414. * Various utility functions.
  6415. * @namespace
  6416. */
  6417. var util = module.exports = require(39);
  6418. var roots = require(30);
  6419. var Type, // cyclic
  6420. Enum;
  6421. util.codegen = require(3);
  6422. util.fetch = require(5);
  6423. util.path = require(8);
  6424. /**
  6425. * Node's fs module if available.
  6426. * @type {Object.<string,*>}
  6427. */
  6428. util.fs = util.inquire("fs");
  6429. /**
  6430. * Converts an object's values to an array.
  6431. * @param {Object.<string,*>} object Object to convert
  6432. * @returns {Array.<*>} Converted array
  6433. */
  6434. util.toArray = function toArray(object) {
  6435. if (object) {
  6436. var keys = Object.keys(object),
  6437. array = new Array(keys.length),
  6438. index = 0;
  6439. while (index < keys.length)
  6440. array[index] = object[keys[index++]];
  6441. return array;
  6442. }
  6443. return [];
  6444. };
  6445. /**
  6446. * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
  6447. * @param {Array.<*>} array Array to convert
  6448. * @returns {Object.<string,*>} Converted object
  6449. */
  6450. util.toObject = function toObject(array) {
  6451. var object = {},
  6452. index = 0;
  6453. while (index < array.length) {
  6454. var key = array[index++],
  6455. val = array[index++];
  6456. if (val !== undefined)
  6457. object[key] = val;
  6458. }
  6459. return object;
  6460. };
  6461. var safePropBackslashRe = /\\/g,
  6462. safePropQuoteRe = /"/g;
  6463. /**
  6464. * Tests whether the specified name is a reserved word in JS.
  6465. * @param {string} name Name to test
  6466. * @returns {boolean} `true` if reserved, otherwise `false`
  6467. */
  6468. util.isReserved = function isReserved(name) {
  6469. return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);
  6470. };
  6471. /**
  6472. * Returns a safe property accessor for the specified property name.
  6473. * @param {string} prop Property name
  6474. * @returns {string} Safe accessor
  6475. */
  6476. util.safeProp = function safeProp(prop) {
  6477. if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))
  6478. return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";
  6479. return "." + prop;
  6480. };
  6481. /**
  6482. * Converts the first character of a string to upper case.
  6483. * @param {string} str String to convert
  6484. * @returns {string} Converted string
  6485. */
  6486. util.ucFirst = function ucFirst(str) {
  6487. return str.charAt(0).toUpperCase() + str.substring(1);
  6488. };
  6489. var camelCaseRe = /_([a-z])/g;
  6490. /**
  6491. * Converts a string to camel case.
  6492. * @param {string} str String to convert
  6493. * @returns {string} Converted string
  6494. */
  6495. util.camelCase = function camelCase(str) {
  6496. return str.substring(0, 1)
  6497. + str.substring(1)
  6498. .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });
  6499. };
  6500. /**
  6501. * Compares reflected fields by id.
  6502. * @param {Field} a First field
  6503. * @param {Field} b Second field
  6504. * @returns {number} Comparison value
  6505. */
  6506. util.compareFieldsById = function compareFieldsById(a, b) {
  6507. return a.id - b.id;
  6508. };
  6509. /**
  6510. * Decorator helper for types (TypeScript).
  6511. * @param {Constructor<T>} ctor Constructor function
  6512. * @param {string} [typeName] Type name, defaults to the constructor's name
  6513. * @returns {Type} Reflected type
  6514. * @template T extends Message<T>
  6515. * @property {Root} root Decorators root
  6516. */
  6517. util.decorateType = function decorateType(ctor, typeName) {
  6518. /* istanbul ignore if */
  6519. if (ctor.$type) {
  6520. if (typeName && ctor.$type.name !== typeName) {
  6521. util.decorateRoot.remove(ctor.$type);
  6522. ctor.$type.name = typeName;
  6523. util.decorateRoot.add(ctor.$type);
  6524. }
  6525. return ctor.$type;
  6526. }
  6527. /* istanbul ignore next */
  6528. if (!Type)
  6529. Type = require(35);
  6530. var type = new Type(typeName || ctor.name);
  6531. util.decorateRoot.add(type);
  6532. type.ctor = ctor; // sets up .encode, .decode etc.
  6533. Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
  6534. Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
  6535. return type;
  6536. };
  6537. var decorateEnumIndex = 0;
  6538. /**
  6539. * Decorator helper for enums (TypeScript).
  6540. * @param {Object} object Enum object
  6541. * @returns {Enum} Reflected enum
  6542. */
  6543. util.decorateEnum = function decorateEnum(object) {
  6544. /* istanbul ignore if */
  6545. if (object.$type)
  6546. return object.$type;
  6547. /* istanbul ignore next */
  6548. if (!Enum)
  6549. Enum = require(15);
  6550. var enm = new Enum("Enum" + decorateEnumIndex++, object);
  6551. util.decorateRoot.add(enm);
  6552. Object.defineProperty(object, "$type", { value: enm, enumerable: false });
  6553. return enm;
  6554. };
  6555. /**
  6556. * Sets the value of a property by property path. If a value already exists, it is turned to an array
  6557. * @param {Object.<string,*>} dst Destination object
  6558. * @param {string} path dot '.' delimited path of the property to set
  6559. * @param {Object} value the value to set
  6560. * @returns {Object.<string,*>} Destination object
  6561. */
  6562. util.setProperty = function setProperty(dst, path, value) {
  6563. function setProp(dst, path, value) {
  6564. var part = path.shift();
  6565. if (path.length > 0) {
  6566. dst[part] = setProp(dst[part] || {}, path, value);
  6567. } else {
  6568. var prevValue = dst[part];
  6569. if (prevValue)
  6570. value = [].concat(prevValue).concat(value);
  6571. dst[part] = value;
  6572. }
  6573. return dst;
  6574. }
  6575. if (typeof dst !== "object")
  6576. throw TypeError("dst must be an object");
  6577. if (!path)
  6578. throw TypeError("path must be specified");
  6579. path = path.split(".");
  6580. return setProp(dst, path, value);
  6581. };
  6582. /**
  6583. * Decorator root (TypeScript).
  6584. * @name util.decorateRoot
  6585. * @type {Root}
  6586. * @readonly
  6587. */
  6588. Object.defineProperty(util, "decorateRoot", {
  6589. get: function() {
  6590. return roots["decorated"] || (roots["decorated"] = new (require(29))());
  6591. }
  6592. });
  6593. },{"15":15,"29":29,"3":3,"30":30,"35":35,"39":39,"5":5,"8":8}],38:[function(require,module,exports){
  6594. "use strict";
  6595. module.exports = LongBits;
  6596. var util = require(39);
  6597. /**
  6598. * Constructs new long bits.
  6599. * @classdesc Helper class for working with the low and high bits of a 64 bit value.
  6600. * @memberof util
  6601. * @constructor
  6602. * @param {number} lo Low 32 bits, unsigned
  6603. * @param {number} hi High 32 bits, unsigned
  6604. */
  6605. function LongBits(lo, hi) {
  6606. // note that the casts below are theoretically unnecessary as of today, but older statically
  6607. // generated converter code might still call the ctor with signed 32bits. kept for compat.
  6608. /**
  6609. * Low bits.
  6610. * @type {number}
  6611. */
  6612. this.lo = lo >>> 0;
  6613. /**
  6614. * High bits.
  6615. * @type {number}
  6616. */
  6617. this.hi = hi >>> 0;
  6618. }
  6619. /**
  6620. * Zero bits.
  6621. * @memberof util.LongBits
  6622. * @type {util.LongBits}
  6623. */
  6624. var zero = LongBits.zero = new LongBits(0, 0);
  6625. zero.toNumber = function() { return 0; };
  6626. zero.zzEncode = zero.zzDecode = function() { return this; };
  6627. zero.length = function() { return 1; };
  6628. /**
  6629. * Zero hash.
  6630. * @memberof util.LongBits
  6631. * @type {string}
  6632. */
  6633. var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
  6634. /**
  6635. * Constructs new long bits from the specified number.
  6636. * @param {number} value Value
  6637. * @returns {util.LongBits} Instance
  6638. */
  6639. LongBits.fromNumber = function fromNumber(value) {
  6640. if (value === 0)
  6641. return zero;
  6642. var sign = value < 0;
  6643. if (sign)
  6644. value = -value;
  6645. var lo = value >>> 0,
  6646. hi = (value - lo) / 4294967296 >>> 0;
  6647. if (sign) {
  6648. hi = ~hi >>> 0;
  6649. lo = ~lo >>> 0;
  6650. if (++lo > 4294967295) {
  6651. lo = 0;
  6652. if (++hi > 4294967295)
  6653. hi = 0;
  6654. }
  6655. }
  6656. return new LongBits(lo, hi);
  6657. };
  6658. /**
  6659. * Constructs new long bits from a number, long or string.
  6660. * @param {Long|number|string} value Value
  6661. * @returns {util.LongBits} Instance
  6662. */
  6663. LongBits.from = function from(value) {
  6664. if (typeof value === "number")
  6665. return LongBits.fromNumber(value);
  6666. if (util.isString(value)) {
  6667. /* istanbul ignore else */
  6668. if (util.Long)
  6669. value = util.Long.fromString(value);
  6670. else
  6671. return LongBits.fromNumber(parseInt(value, 10));
  6672. }
  6673. return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
  6674. };
  6675. /**
  6676. * Converts this long bits to a possibly unsafe JavaScript number.
  6677. * @param {boolean} [unsigned=false] Whether unsigned or not
  6678. * @returns {number} Possibly unsafe number
  6679. */
  6680. LongBits.prototype.toNumber = function toNumber(unsigned) {
  6681. if (!unsigned && this.hi >>> 31) {
  6682. var lo = ~this.lo + 1 >>> 0,
  6683. hi = ~this.hi >>> 0;
  6684. if (!lo)
  6685. hi = hi + 1 >>> 0;
  6686. return -(lo + hi * 4294967296);
  6687. }
  6688. return this.lo + this.hi * 4294967296;
  6689. };
  6690. /**
  6691. * Converts this long bits to a long.
  6692. * @param {boolean} [unsigned=false] Whether unsigned or not
  6693. * @returns {Long} Long
  6694. */
  6695. LongBits.prototype.toLong = function toLong(unsigned) {
  6696. return util.Long
  6697. ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
  6698. /* istanbul ignore next */
  6699. : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
  6700. };
  6701. var charCodeAt = String.prototype.charCodeAt;
  6702. /**
  6703. * Constructs new long bits from the specified 8 characters long hash.
  6704. * @param {string} hash Hash
  6705. * @returns {util.LongBits} Bits
  6706. */
  6707. LongBits.fromHash = function fromHash(hash) {
  6708. if (hash === zeroHash)
  6709. return zero;
  6710. return new LongBits(
  6711. ( charCodeAt.call(hash, 0)
  6712. | charCodeAt.call(hash, 1) << 8
  6713. | charCodeAt.call(hash, 2) << 16
  6714. | charCodeAt.call(hash, 3) << 24) >>> 0
  6715. ,
  6716. ( charCodeAt.call(hash, 4)
  6717. | charCodeAt.call(hash, 5) << 8
  6718. | charCodeAt.call(hash, 6) << 16
  6719. | charCodeAt.call(hash, 7) << 24) >>> 0
  6720. );
  6721. };
  6722. /**
  6723. * Converts this long bits to a 8 characters long hash.
  6724. * @returns {string} Hash
  6725. */
  6726. LongBits.prototype.toHash = function toHash() {
  6727. return String.fromCharCode(
  6728. this.lo & 255,
  6729. this.lo >>> 8 & 255,
  6730. this.lo >>> 16 & 255,
  6731. this.lo >>> 24 ,
  6732. this.hi & 255,
  6733. this.hi >>> 8 & 255,
  6734. this.hi >>> 16 & 255,
  6735. this.hi >>> 24
  6736. );
  6737. };
  6738. /**
  6739. * Zig-zag encodes this long bits.
  6740. * @returns {util.LongBits} `this`
  6741. */
  6742. LongBits.prototype.zzEncode = function zzEncode() {
  6743. var mask = this.hi >> 31;
  6744. this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
  6745. this.lo = ( this.lo << 1 ^ mask) >>> 0;
  6746. return this;
  6747. };
  6748. /**
  6749. * Zig-zag decodes this long bits.
  6750. * @returns {util.LongBits} `this`
  6751. */
  6752. LongBits.prototype.zzDecode = function zzDecode() {
  6753. var mask = -(this.lo & 1);
  6754. this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
  6755. this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
  6756. return this;
  6757. };
  6758. /**
  6759. * Calculates the length of this longbits when encoded as a varint.
  6760. * @returns {number} Length
  6761. */
  6762. LongBits.prototype.length = function length() {
  6763. var part0 = this.lo,
  6764. part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
  6765. part2 = this.hi >>> 24;
  6766. return part2 === 0
  6767. ? part1 === 0
  6768. ? part0 < 16384
  6769. ? part0 < 128 ? 1 : 2
  6770. : part0 < 2097152 ? 3 : 4
  6771. : part1 < 16384
  6772. ? part1 < 128 ? 5 : 6
  6773. : part1 < 2097152 ? 7 : 8
  6774. : part2 < 128 ? 9 : 10;
  6775. };
  6776. },{"39":39}],39:[function(require,module,exports){
  6777. "use strict";
  6778. var util = exports;
  6779. // used to return a Promise where callback is omitted
  6780. util.asPromise = require(1);
  6781. // converts to / from base64 encoded strings
  6782. util.base64 = require(2);
  6783. // base class of rpc.Service
  6784. util.EventEmitter = require(4);
  6785. // float handling accross browsers
  6786. util.float = require(6);
  6787. // requires modules optionally and hides the call from bundlers
  6788. util.inquire = require(7);
  6789. // converts to / from utf8 encoded strings
  6790. util.utf8 = require(10);
  6791. // provides a node-like buffer pool in the browser
  6792. util.pool = require(9);
  6793. // utility to work with the low and high bits of a 64 bit value
  6794. util.LongBits = require(38);
  6795. /**
  6796. * Whether running within node or not.
  6797. * @memberof util
  6798. * @type {boolean}
  6799. */
  6800. util.isNode = Boolean(typeof global !== "undefined"
  6801. && global
  6802. && global.process
  6803. && global.process.versions
  6804. && global.process.versions.node);
  6805. /**
  6806. * Global object reference.
  6807. * @memberof util
  6808. * @type {Object}
  6809. */
  6810. util.global = util.isNode && global
  6811. || typeof window !== "undefined" && window
  6812. || typeof self !== "undefined" && self
  6813. || this; // eslint-disable-line no-invalid-this
  6814. /**
  6815. * An immuable empty array.
  6816. * @memberof util
  6817. * @type {Array.<*>}
  6818. * @const
  6819. */
  6820. util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
  6821. /**
  6822. * An immutable empty object.
  6823. * @type {Object}
  6824. * @const
  6825. */
  6826. util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
  6827. /**
  6828. * Tests if the specified value is an integer.
  6829. * @function
  6830. * @param {*} value Value to test
  6831. * @returns {boolean} `true` if the value is an integer
  6832. */
  6833. util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
  6834. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  6835. };
  6836. /**
  6837. * Tests if the specified value is a string.
  6838. * @param {*} value Value to test
  6839. * @returns {boolean} `true` if the value is a string
  6840. */
  6841. util.isString = function isString(value) {
  6842. return typeof value === "string" || value instanceof String;
  6843. };
  6844. /**
  6845. * Tests if the specified value is a non-null object.
  6846. * @param {*} value Value to test
  6847. * @returns {boolean} `true` if the value is a non-null object
  6848. */
  6849. util.isObject = function isObject(value) {
  6850. return value && typeof value === "object";
  6851. };
  6852. /**
  6853. * Checks if a property on a message is considered to be present.
  6854. * This is an alias of {@link util.isSet}.
  6855. * @function
  6856. * @param {Object} obj Plain object or message instance
  6857. * @param {string} prop Property name
  6858. * @returns {boolean} `true` if considered to be present, otherwise `false`
  6859. */
  6860. util.isset =
  6861. /**
  6862. * Checks if a property on a message is considered to be present.
  6863. * @param {Object} obj Plain object or message instance
  6864. * @param {string} prop Property name
  6865. * @returns {boolean} `true` if considered to be present, otherwise `false`
  6866. */
  6867. util.isSet = function isSet(obj, prop) {
  6868. var value = obj[prop];
  6869. if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
  6870. return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
  6871. return false;
  6872. };
  6873. /**
  6874. * Any compatible Buffer instance.
  6875. * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
  6876. * @interface Buffer
  6877. * @extends Uint8Array
  6878. */
  6879. /**
  6880. * Node's Buffer class if available.
  6881. * @type {Constructor<Buffer>}
  6882. */
  6883. util.Buffer = (function() {
  6884. try {
  6885. var Buffer = util.inquire("buffer").Buffer;
  6886. // refuse to use non-node buffers if not explicitly assigned (perf reasons):
  6887. return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
  6888. } catch (e) {
  6889. /* istanbul ignore next */
  6890. return null;
  6891. }
  6892. })();
  6893. // Internal alias of or polyfull for Buffer.from.
  6894. util._Buffer_from = null;
  6895. // Internal alias of or polyfill for Buffer.allocUnsafe.
  6896. util._Buffer_allocUnsafe = null;
  6897. /**
  6898. * Creates a new buffer of whatever type supported by the environment.
  6899. * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
  6900. * @returns {Uint8Array|Buffer} Buffer
  6901. */
  6902. util.newBuffer = function newBuffer(sizeOrArray) {
  6903. /* istanbul ignore next */
  6904. return typeof sizeOrArray === "number"
  6905. ? util.Buffer
  6906. ? util._Buffer_allocUnsafe(sizeOrArray)
  6907. : new util.Array(sizeOrArray)
  6908. : util.Buffer
  6909. ? util._Buffer_from(sizeOrArray)
  6910. : typeof Uint8Array === "undefined"
  6911. ? sizeOrArray
  6912. : new Uint8Array(sizeOrArray);
  6913. };
  6914. /**
  6915. * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
  6916. * @type {Constructor<Uint8Array>}
  6917. */
  6918. util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
  6919. /**
  6920. * Any compatible Long instance.
  6921. * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
  6922. * @interface Long
  6923. * @property {number} low Low bits
  6924. * @property {number} high High bits
  6925. * @property {boolean} unsigned Whether unsigned or not
  6926. */
  6927. /**
  6928. * Long.js's Long class if available.
  6929. * @type {Constructor<Long>}
  6930. */
  6931. util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
  6932. || /* istanbul ignore next */ util.global.Long
  6933. || util.inquire("long");
  6934. /**
  6935. * Regular expression used to verify 2 bit (`bool`) map keys.
  6936. * @type {RegExp}
  6937. * @const
  6938. */
  6939. util.key2Re = /^true|false|0|1$/;
  6940. /**
  6941. * Regular expression used to verify 32 bit (`int32` etc.) map keys.
  6942. * @type {RegExp}
  6943. * @const
  6944. */
  6945. util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
  6946. /**
  6947. * Regular expression used to verify 64 bit (`int64` etc.) map keys.
  6948. * @type {RegExp}
  6949. * @const
  6950. */
  6951. util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
  6952. /**
  6953. * Converts a number or long to an 8 characters long hash string.
  6954. * @param {Long|number} value Value to convert
  6955. * @returns {string} Hash
  6956. */
  6957. util.longToHash = function longToHash(value) {
  6958. return value
  6959. ? util.LongBits.from(value).toHash()
  6960. : util.LongBits.zeroHash;
  6961. };
  6962. /**
  6963. * Converts an 8 characters long hash string to a long or number.
  6964. * @param {string} hash Hash
  6965. * @param {boolean} [unsigned=false] Whether unsigned or not
  6966. * @returns {Long|number} Original value
  6967. */
  6968. util.longFromHash = function longFromHash(hash, unsigned) {
  6969. var bits = util.LongBits.fromHash(hash);
  6970. if (util.Long)
  6971. return util.Long.fromBits(bits.lo, bits.hi, unsigned);
  6972. return bits.toNumber(Boolean(unsigned));
  6973. };
  6974. /**
  6975. * Merges the properties of the source object into the destination object.
  6976. * @memberof util
  6977. * @param {Object.<string,*>} dst Destination object
  6978. * @param {Object.<string,*>} src Source object
  6979. * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
  6980. * @returns {Object.<string,*>} Destination object
  6981. */
  6982. function merge(dst, src, ifNotSet) { // used by converters
  6983. for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
  6984. if (dst[keys[i]] === undefined || !ifNotSet)
  6985. dst[keys[i]] = src[keys[i]];
  6986. return dst;
  6987. }
  6988. util.merge = merge;
  6989. /**
  6990. * Converts the first character of a string to lower case.
  6991. * @param {string} str String to convert
  6992. * @returns {string} Converted string
  6993. */
  6994. util.lcFirst = function lcFirst(str) {
  6995. return str.charAt(0).toLowerCase() + str.substring(1);
  6996. };
  6997. /**
  6998. * Creates a custom error constructor.
  6999. * @memberof util
  7000. * @param {string} name Error name
  7001. * @returns {Constructor<Error>} Custom error constructor
  7002. */
  7003. function newError(name) {
  7004. function CustomError(message, properties) {
  7005. if (!(this instanceof CustomError))
  7006. return new CustomError(message, properties);
  7007. // Error.call(this, message);
  7008. // ^ just returns a new error instance because the ctor can be called as a function
  7009. Object.defineProperty(this, "message", { get: function() { return message; } });
  7010. /* istanbul ignore next */
  7011. if (Error.captureStackTrace) // node
  7012. Error.captureStackTrace(this, CustomError);
  7013. else
  7014. Object.defineProperty(this, "stack", { value: new Error().stack || "" });
  7015. if (properties)
  7016. merge(this, properties);
  7017. }
  7018. (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
  7019. Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
  7020. CustomError.prototype.toString = function toString() {
  7021. return this.name + ": " + this.message;
  7022. };
  7023. return CustomError;
  7024. }
  7025. util.newError = newError;
  7026. /**
  7027. * Constructs a new protocol error.
  7028. * @classdesc Error subclass indicating a protocol specifc error.
  7029. * @memberof util
  7030. * @extends Error
  7031. * @template T extends Message<T>
  7032. * @constructor
  7033. * @param {string} message Error message
  7034. * @param {Object.<string,*>} [properties] Additional properties
  7035. * @example
  7036. * try {
  7037. * MyMessage.decode(someBuffer); // throws if required fields are missing
  7038. * } catch (e) {
  7039. * if (e instanceof ProtocolError && e.instance)
  7040. * console.log("decoded so far: " + JSON.stringify(e.instance));
  7041. * }
  7042. */
  7043. util.ProtocolError = newError("ProtocolError");
  7044. /**
  7045. * So far decoded message instance.
  7046. * @name util.ProtocolError#instance
  7047. * @type {Message<T>}
  7048. */
  7049. /**
  7050. * A OneOf getter as returned by {@link util.oneOfGetter}.
  7051. * @typedef OneOfGetter
  7052. * @type {function}
  7053. * @returns {string|undefined} Set field name, if any
  7054. */
  7055. /**
  7056. * Builds a getter for a oneof's present field name.
  7057. * @param {string[]} fieldNames Field names
  7058. * @returns {OneOfGetter} Unbound getter
  7059. */
  7060. util.oneOfGetter = function getOneOf(fieldNames) {
  7061. var fieldMap = {};
  7062. for (var i = 0; i < fieldNames.length; ++i)
  7063. fieldMap[fieldNames[i]] = 1;
  7064. /**
  7065. * @returns {string|undefined} Set field name, if any
  7066. * @this Object
  7067. * @ignore
  7068. */
  7069. return function() { // eslint-disable-line consistent-return
  7070. for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
  7071. if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
  7072. return keys[i];
  7073. };
  7074. };
  7075. /**
  7076. * A OneOf setter as returned by {@link util.oneOfSetter}.
  7077. * @typedef OneOfSetter
  7078. * @type {function}
  7079. * @param {string|undefined} value Field name
  7080. * @returns {undefined}
  7081. */
  7082. /**
  7083. * Builds a setter for a oneof's present field name.
  7084. * @param {string[]} fieldNames Field names
  7085. * @returns {OneOfSetter} Unbound setter
  7086. */
  7087. util.oneOfSetter = function setOneOf(fieldNames) {
  7088. /**
  7089. * @param {string} name Field name
  7090. * @returns {undefined}
  7091. * @this Object
  7092. * @ignore
  7093. */
  7094. return function(name) {
  7095. for (var i = 0; i < fieldNames.length; ++i)
  7096. if (fieldNames[i] !== name)
  7097. delete this[fieldNames[i]];
  7098. };
  7099. };
  7100. /**
  7101. * Default conversion options used for {@link Message#toJSON} implementations.
  7102. *
  7103. * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
  7104. *
  7105. * - Longs become strings
  7106. * - Enums become string keys
  7107. * - Bytes become base64 encoded strings
  7108. * - (Sub-)Messages become plain objects
  7109. * - Maps become plain objects with all string keys
  7110. * - Repeated fields become arrays
  7111. * - NaN and Infinity for float and double fields become strings
  7112. *
  7113. * @type {IConversionOptions}
  7114. * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
  7115. */
  7116. util.toJSONOptions = {
  7117. longs: String,
  7118. enums: String,
  7119. bytes: String,
  7120. json: true
  7121. };
  7122. // Sets up buffer utility according to the environment (called in index-minimal)
  7123. util._configure = function() {
  7124. var Buffer = util.Buffer;
  7125. /* istanbul ignore if */
  7126. if (!Buffer) {
  7127. util._Buffer_from = util._Buffer_allocUnsafe = null;
  7128. return;
  7129. }
  7130. // because node 4.x buffers are incompatible & immutable
  7131. // see: https://github.com/dcodeIO/protobuf.js/pull/665
  7132. util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
  7133. /* istanbul ignore next */
  7134. function Buffer_from(value, encoding) {
  7135. return new Buffer(value, encoding);
  7136. };
  7137. util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
  7138. /* istanbul ignore next */
  7139. function Buffer_allocUnsafe(size) {
  7140. return new Buffer(size);
  7141. };
  7142. };
  7143. },{"1":1,"10":10,"2":2,"38":38,"4":4,"6":6,"7":7,"9":9}],40:[function(require,module,exports){
  7144. "use strict";
  7145. module.exports = verifier;
  7146. var Enum = require(15),
  7147. util = require(37);
  7148. function invalid(field, expected) {
  7149. return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";
  7150. }
  7151. /**
  7152. * Generates a partial value verifier.
  7153. * @param {Codegen} gen Codegen instance
  7154. * @param {Field} field Reflected field
  7155. * @param {number} fieldIndex Field index
  7156. * @param {string} ref Variable reference
  7157. * @returns {Codegen} Codegen instance
  7158. * @ignore
  7159. */
  7160. function genVerifyValue(gen, field, fieldIndex, ref) {
  7161. /* eslint-disable no-unexpected-multiline */
  7162. if (field.resolvedType) {
  7163. if (field.resolvedType instanceof Enum) { gen
  7164. ("switch(%s){", ref)
  7165. ("default:")
  7166. ("return%j", invalid(field, "enum value"));
  7167. for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen
  7168. ("case %i:", field.resolvedType.values[keys[j]]);
  7169. gen
  7170. ("break")
  7171. ("}");
  7172. } else {
  7173. gen
  7174. ("{")
  7175. ("var e=types[%i].verify(%s);", fieldIndex, ref)
  7176. ("if(e)")
  7177. ("return%j+e", field.name + ".")
  7178. ("}");
  7179. }
  7180. } else {
  7181. switch (field.type) {
  7182. case "int32":
  7183. case "uint32":
  7184. case "sint32":
  7185. case "fixed32":
  7186. case "sfixed32": gen
  7187. ("if(!util.isInteger(%s))", ref)
  7188. ("return%j", invalid(field, "integer"));
  7189. break;
  7190. case "int64":
  7191. case "uint64":
  7192. case "sint64":
  7193. case "fixed64":
  7194. case "sfixed64": gen
  7195. ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)
  7196. ("return%j", invalid(field, "integer|Long"));
  7197. break;
  7198. case "float":
  7199. case "double": gen
  7200. ("if(typeof %s!==\"number\")", ref)
  7201. ("return%j", invalid(field, "number"));
  7202. break;
  7203. case "bool": gen
  7204. ("if(typeof %s!==\"boolean\")", ref)
  7205. ("return%j", invalid(field, "boolean"));
  7206. break;
  7207. case "string": gen
  7208. ("if(!util.isString(%s))", ref)
  7209. ("return%j", invalid(field, "string"));
  7210. break;
  7211. case "bytes": gen
  7212. ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)
  7213. ("return%j", invalid(field, "buffer"));
  7214. break;
  7215. }
  7216. }
  7217. return gen;
  7218. /* eslint-enable no-unexpected-multiline */
  7219. }
  7220. /**
  7221. * Generates a partial key verifier.
  7222. * @param {Codegen} gen Codegen instance
  7223. * @param {Field} field Reflected field
  7224. * @param {string} ref Variable reference
  7225. * @returns {Codegen} Codegen instance
  7226. * @ignore
  7227. */
  7228. function genVerifyKey(gen, field, ref) {
  7229. /* eslint-disable no-unexpected-multiline */
  7230. switch (field.keyType) {
  7231. case "int32":
  7232. case "uint32":
  7233. case "sint32":
  7234. case "fixed32":
  7235. case "sfixed32": gen
  7236. ("if(!util.key32Re.test(%s))", ref)
  7237. ("return%j", invalid(field, "integer key"));
  7238. break;
  7239. case "int64":
  7240. case "uint64":
  7241. case "sint64":
  7242. case "fixed64":
  7243. case "sfixed64": gen
  7244. ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not
  7245. ("return%j", invalid(field, "integer|Long key"));
  7246. break;
  7247. case "bool": gen
  7248. ("if(!util.key2Re.test(%s))", ref)
  7249. ("return%j", invalid(field, "boolean key"));
  7250. break;
  7251. }
  7252. return gen;
  7253. /* eslint-enable no-unexpected-multiline */
  7254. }
  7255. /**
  7256. * Generates a verifier specific to the specified message type.
  7257. * @param {Type} mtype Message type
  7258. * @returns {Codegen} Codegen instance
  7259. */
  7260. function verifier(mtype) {
  7261. /* eslint-disable no-unexpected-multiline */
  7262. var gen = util.codegen(["m"], mtype.name + "$verify")
  7263. ("if(typeof m!==\"object\"||m===null)")
  7264. ("return%j", "object expected");
  7265. var oneofs = mtype.oneofsArray,
  7266. seenFirstField = {};
  7267. if (oneofs.length) gen
  7268. ("var p={}");
  7269. for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
  7270. var field = mtype._fieldsArray[i].resolve(),
  7271. ref = "m" + util.safeProp(field.name);
  7272. if (field.optional) gen
  7273. ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null
  7274. // map fields
  7275. if (field.map) { gen
  7276. ("if(!util.isObject(%s))", ref)
  7277. ("return%j", invalid(field, "object"))
  7278. ("var k=Object.keys(%s)", ref)
  7279. ("for(var i=0;i<k.length;++i){");
  7280. genVerifyKey(gen, field, "k[i]");
  7281. genVerifyValue(gen, field, i, ref + "[k[i]]")
  7282. ("}");
  7283. // repeated fields
  7284. } else if (field.repeated) { gen
  7285. ("if(!Array.isArray(%s))", ref)
  7286. ("return%j", invalid(field, "array"))
  7287. ("for(var i=0;i<%s.length;++i){", ref);
  7288. genVerifyValue(gen, field, i, ref + "[i]")
  7289. ("}");
  7290. // required or present fields
  7291. } else {
  7292. if (field.partOf) {
  7293. var oneofProp = util.safeProp(field.partOf.name);
  7294. if (seenFirstField[field.partOf.name] === 1) gen
  7295. ("if(p%s===1)", oneofProp)
  7296. ("return%j", field.partOf.name + ": multiple values");
  7297. seenFirstField[field.partOf.name] = 1;
  7298. gen
  7299. ("p%s=1", oneofProp);
  7300. }
  7301. genVerifyValue(gen, field, i, ref);
  7302. }
  7303. if (field.optional) gen
  7304. ("}");
  7305. }
  7306. return gen
  7307. ("return null");
  7308. /* eslint-enable no-unexpected-multiline */
  7309. }
  7310. },{"15":15,"37":37}],41:[function(require,module,exports){
  7311. "use strict";
  7312. /**
  7313. * Wrappers for common types.
  7314. * @type {Object.<string,IWrapper>}
  7315. * @const
  7316. */
  7317. var wrappers = exports;
  7318. var Message = require(21);
  7319. /**
  7320. * From object converter part of an {@link IWrapper}.
  7321. * @typedef WrapperFromObjectConverter
  7322. * @type {function}
  7323. * @param {Object.<string,*>} object Plain object
  7324. * @returns {Message<{}>} Message instance
  7325. * @this Type
  7326. */
  7327. /**
  7328. * To object converter part of an {@link IWrapper}.
  7329. * @typedef WrapperToObjectConverter
  7330. * @type {function}
  7331. * @param {Message<{}>} message Message instance
  7332. * @param {IConversionOptions} [options] Conversion options
  7333. * @returns {Object.<string,*>} Plain object
  7334. * @this Type
  7335. */
  7336. /**
  7337. * Common type wrapper part of {@link wrappers}.
  7338. * @interface IWrapper
  7339. * @property {WrapperFromObjectConverter} [fromObject] From object converter
  7340. * @property {WrapperToObjectConverter} [toObject] To object converter
  7341. */
  7342. // Custom wrapper for Any
  7343. wrappers[".google.protobuf.Any"] = {
  7344. fromObject: function(object) {
  7345. // unwrap value type if mapped
  7346. if (object && object["@type"]) {
  7347. // Only use fully qualified type name after the last '/'
  7348. var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1);
  7349. var type = this.lookup(name);
  7350. /* istanbul ignore else */
  7351. if (type) {
  7352. // type_url does not accept leading "."
  7353. var type_url = object["@type"].charAt(0) === "." ?
  7354. object["@type"].substr(1) : object["@type"];
  7355. // type_url prefix is optional, but path seperator is required
  7356. if (type_url.indexOf("/") === -1) {
  7357. type_url = "/" + type_url;
  7358. }
  7359. return this.create({
  7360. type_url: type_url,
  7361. value: type.encode(type.fromObject(object)).finish()
  7362. });
  7363. }
  7364. }
  7365. return this.fromObject(object);
  7366. },
  7367. toObject: function(message, options) {
  7368. // Default prefix
  7369. var googleApi = "type.googleapis.com/";
  7370. var prefix = "";
  7371. var name = "";
  7372. // decode value if requested and unmapped
  7373. if (options && options.json && message.type_url && message.value) {
  7374. // Only use fully qualified type name after the last '/'
  7375. name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
  7376. // Separate the prefix used
  7377. prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
  7378. var type = this.lookup(name);
  7379. /* istanbul ignore else */
  7380. if (type)
  7381. message = type.decode(message.value);
  7382. }
  7383. // wrap value if unmapped
  7384. if (!(message instanceof this.ctor) && message instanceof Message) {
  7385. var object = message.$type.toObject(message, options);
  7386. var messageName = message.$type.fullName[0] === "." ?
  7387. message.$type.fullName.substr(1) : message.$type.fullName;
  7388. // Default to type.googleapis.com prefix if no prefix is used
  7389. if (prefix === "") {
  7390. prefix = googleApi;
  7391. }
  7392. name = prefix + messageName;
  7393. object["@type"] = name;
  7394. return object;
  7395. }
  7396. return this.toObject(message, options);
  7397. }
  7398. };
  7399. },{"21":21}],42:[function(require,module,exports){
  7400. "use strict";
  7401. module.exports = Writer;
  7402. var util = require(39);
  7403. var BufferWriter; // cyclic
  7404. var LongBits = util.LongBits,
  7405. base64 = util.base64,
  7406. utf8 = util.utf8;
  7407. /**
  7408. * Constructs a new writer operation instance.
  7409. * @classdesc Scheduled writer operation.
  7410. * @constructor
  7411. * @param {function(*, Uint8Array, number)} fn Function to call
  7412. * @param {number} len Value byte length
  7413. * @param {*} val Value to write
  7414. * @ignore
  7415. */
  7416. function Op(fn, len, val) {
  7417. /**
  7418. * Function to call.
  7419. * @type {function(Uint8Array, number, *)}
  7420. */
  7421. this.fn = fn;
  7422. /**
  7423. * Value byte length.
  7424. * @type {number}
  7425. */
  7426. this.len = len;
  7427. /**
  7428. * Next operation.
  7429. * @type {Writer.Op|undefined}
  7430. */
  7431. this.next = undefined;
  7432. /**
  7433. * Value to write.
  7434. * @type {*}
  7435. */
  7436. this.val = val; // type varies
  7437. }
  7438. /* istanbul ignore next */
  7439. function noop() {} // eslint-disable-line no-empty-function
  7440. /**
  7441. * Constructs a new writer state instance.
  7442. * @classdesc Copied writer state.
  7443. * @memberof Writer
  7444. * @constructor
  7445. * @param {Writer} writer Writer to copy state from
  7446. * @ignore
  7447. */
  7448. function State(writer) {
  7449. /**
  7450. * Current head.
  7451. * @type {Writer.Op}
  7452. */
  7453. this.head = writer.head;
  7454. /**
  7455. * Current tail.
  7456. * @type {Writer.Op}
  7457. */
  7458. this.tail = writer.tail;
  7459. /**
  7460. * Current buffer length.
  7461. * @type {number}
  7462. */
  7463. this.len = writer.len;
  7464. /**
  7465. * Next state.
  7466. * @type {State|null}
  7467. */
  7468. this.next = writer.states;
  7469. }
  7470. /**
  7471. * Constructs a new writer instance.
  7472. * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
  7473. * @constructor
  7474. */
  7475. function Writer() {
  7476. /**
  7477. * Current length.
  7478. * @type {number}
  7479. */
  7480. this.len = 0;
  7481. /**
  7482. * Operations head.
  7483. * @type {Object}
  7484. */
  7485. this.head = new Op(noop, 0, 0);
  7486. /**
  7487. * Operations tail
  7488. * @type {Object}
  7489. */
  7490. this.tail = this.head;
  7491. /**
  7492. * Linked forked states.
  7493. * @type {Object|null}
  7494. */
  7495. this.states = null;
  7496. // When a value is written, the writer calculates its byte length and puts it into a linked
  7497. // list of operations to perform when finish() is called. This both allows us to allocate
  7498. // buffers of the exact required size and reduces the amount of work we have to do compared
  7499. // to first calculating over objects and then encoding over objects. In our case, the encoding
  7500. // part is just a linked list walk calling operations with already prepared values.
  7501. }
  7502. var create = function create() {
  7503. return util.Buffer
  7504. ? function create_buffer_setup() {
  7505. return (Writer.create = function create_buffer() {
  7506. return new BufferWriter();
  7507. })();
  7508. }
  7509. /* istanbul ignore next */
  7510. : function create_array() {
  7511. return new Writer();
  7512. };
  7513. };
  7514. /**
  7515. * Creates a new writer.
  7516. * @function
  7517. * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
  7518. */
  7519. Writer.create = create();
  7520. /**
  7521. * Allocates a buffer of the specified size.
  7522. * @param {number} size Buffer size
  7523. * @returns {Uint8Array} Buffer
  7524. */
  7525. Writer.alloc = function alloc(size) {
  7526. return new util.Array(size);
  7527. };
  7528. // Use Uint8Array buffer pool in the browser, just like node does with buffers
  7529. /* istanbul ignore else */
  7530. if (util.Array !== Array)
  7531. Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
  7532. /**
  7533. * Pushes a new operation to the queue.
  7534. * @param {function(Uint8Array, number, *)} fn Function to call
  7535. * @param {number} len Value byte length
  7536. * @param {number} val Value to write
  7537. * @returns {Writer} `this`
  7538. * @private
  7539. */
  7540. Writer.prototype._push = function push(fn, len, val) {
  7541. this.tail = this.tail.next = new Op(fn, len, val);
  7542. this.len += len;
  7543. return this;
  7544. };
  7545. function writeByte(val, buf, pos) {
  7546. buf[pos] = val & 255;
  7547. }
  7548. function writeVarint32(val, buf, pos) {
  7549. while (val > 127) {
  7550. buf[pos++] = val & 127 | 128;
  7551. val >>>= 7;
  7552. }
  7553. buf[pos] = val;
  7554. }
  7555. /**
  7556. * Constructs a new varint writer operation instance.
  7557. * @classdesc Scheduled varint writer operation.
  7558. * @extends Op
  7559. * @constructor
  7560. * @param {number} len Value byte length
  7561. * @param {number} val Value to write
  7562. * @ignore
  7563. */
  7564. function VarintOp(len, val) {
  7565. this.len = len;
  7566. this.next = undefined;
  7567. this.val = val;
  7568. }
  7569. VarintOp.prototype = Object.create(Op.prototype);
  7570. VarintOp.prototype.fn = writeVarint32;
  7571. /**
  7572. * Writes an unsigned 32 bit value as a varint.
  7573. * @param {number} value Value to write
  7574. * @returns {Writer} `this`
  7575. */
  7576. Writer.prototype.uint32 = function write_uint32(value) {
  7577. // here, the call to this.push has been inlined and a varint specific Op subclass is used.
  7578. // uint32 is by far the most frequently used operation and benefits significantly from this.
  7579. this.len += (this.tail = this.tail.next = new VarintOp(
  7580. (value = value >>> 0)
  7581. < 128 ? 1
  7582. : value < 16384 ? 2
  7583. : value < 2097152 ? 3
  7584. : value < 268435456 ? 4
  7585. : 5,
  7586. value)).len;
  7587. return this;
  7588. };
  7589. /**
  7590. * Writes a signed 32 bit value as a varint.
  7591. * @function
  7592. * @param {number} value Value to write
  7593. * @returns {Writer} `this`
  7594. */
  7595. Writer.prototype.int32 = function write_int32(value) {
  7596. return value < 0
  7597. ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
  7598. : this.uint32(value);
  7599. };
  7600. /**
  7601. * Writes a 32 bit value as a varint, zig-zag encoded.
  7602. * @param {number} value Value to write
  7603. * @returns {Writer} `this`
  7604. */
  7605. Writer.prototype.sint32 = function write_sint32(value) {
  7606. return this.uint32((value << 1 ^ value >> 31) >>> 0);
  7607. };
  7608. function writeVarint64(val, buf, pos) {
  7609. while (val.hi) {
  7610. buf[pos++] = val.lo & 127 | 128;
  7611. val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
  7612. val.hi >>>= 7;
  7613. }
  7614. while (val.lo > 127) {
  7615. buf[pos++] = val.lo & 127 | 128;
  7616. val.lo = val.lo >>> 7;
  7617. }
  7618. buf[pos++] = val.lo;
  7619. }
  7620. /**
  7621. * Writes an unsigned 64 bit value as a varint.
  7622. * @param {Long|number|string} value Value to write
  7623. * @returns {Writer} `this`
  7624. * @throws {TypeError} If `value` is a string and no long library is present.
  7625. */
  7626. Writer.prototype.uint64 = function write_uint64(value) {
  7627. var bits = LongBits.from(value);
  7628. return this._push(writeVarint64, bits.length(), bits);
  7629. };
  7630. /**
  7631. * Writes a signed 64 bit value as a varint.
  7632. * @function
  7633. * @param {Long|number|string} value Value to write
  7634. * @returns {Writer} `this`
  7635. * @throws {TypeError} If `value` is a string and no long library is present.
  7636. */
  7637. Writer.prototype.int64 = Writer.prototype.uint64;
  7638. /**
  7639. * Writes a signed 64 bit value as a varint, zig-zag encoded.
  7640. * @param {Long|number|string} value Value to write
  7641. * @returns {Writer} `this`
  7642. * @throws {TypeError} If `value` is a string and no long library is present.
  7643. */
  7644. Writer.prototype.sint64 = function write_sint64(value) {
  7645. var bits = LongBits.from(value).zzEncode();
  7646. return this._push(writeVarint64, bits.length(), bits);
  7647. };
  7648. /**
  7649. * Writes a boolish value as a varint.
  7650. * @param {boolean} value Value to write
  7651. * @returns {Writer} `this`
  7652. */
  7653. Writer.prototype.bool = function write_bool(value) {
  7654. return this._push(writeByte, 1, value ? 1 : 0);
  7655. };
  7656. function writeFixed32(val, buf, pos) {
  7657. buf[pos ] = val & 255;
  7658. buf[pos + 1] = val >>> 8 & 255;
  7659. buf[pos + 2] = val >>> 16 & 255;
  7660. buf[pos + 3] = val >>> 24;
  7661. }
  7662. /**
  7663. * Writes an unsigned 32 bit value as fixed 32 bits.
  7664. * @param {number} value Value to write
  7665. * @returns {Writer} `this`
  7666. */
  7667. Writer.prototype.fixed32 = function write_fixed32(value) {
  7668. return this._push(writeFixed32, 4, value >>> 0);
  7669. };
  7670. /**
  7671. * Writes a signed 32 bit value as fixed 32 bits.
  7672. * @function
  7673. * @param {number} value Value to write
  7674. * @returns {Writer} `this`
  7675. */
  7676. Writer.prototype.sfixed32 = Writer.prototype.fixed32;
  7677. /**
  7678. * Writes an unsigned 64 bit value as fixed 64 bits.
  7679. * @param {Long|number|string} value Value to write
  7680. * @returns {Writer} `this`
  7681. * @throws {TypeError} If `value` is a string and no long library is present.
  7682. */
  7683. Writer.prototype.fixed64 = function write_fixed64(value) {
  7684. var bits = LongBits.from(value);
  7685. return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
  7686. };
  7687. /**
  7688. * Writes a signed 64 bit value as fixed 64 bits.
  7689. * @function
  7690. * @param {Long|number|string} value Value to write
  7691. * @returns {Writer} `this`
  7692. * @throws {TypeError} If `value` is a string and no long library is present.
  7693. */
  7694. Writer.prototype.sfixed64 = Writer.prototype.fixed64;
  7695. /**
  7696. * Writes a float (32 bit).
  7697. * @function
  7698. * @param {number} value Value to write
  7699. * @returns {Writer} `this`
  7700. */
  7701. Writer.prototype.float = function write_float(value) {
  7702. return this._push(util.float.writeFloatLE, 4, value);
  7703. };
  7704. /**
  7705. * Writes a double (64 bit float).
  7706. * @function
  7707. * @param {number} value Value to write
  7708. * @returns {Writer} `this`
  7709. */
  7710. Writer.prototype.double = function write_double(value) {
  7711. return this._push(util.float.writeDoubleLE, 8, value);
  7712. };
  7713. var writeBytes = util.Array.prototype.set
  7714. ? function writeBytes_set(val, buf, pos) {
  7715. buf.set(val, pos); // also works for plain array values
  7716. }
  7717. /* istanbul ignore next */
  7718. : function writeBytes_for(val, buf, pos) {
  7719. for (var i = 0; i < val.length; ++i)
  7720. buf[pos + i] = val[i];
  7721. };
  7722. /**
  7723. * Writes a sequence of bytes.
  7724. * @param {Uint8Array|string} value Buffer or base64 encoded string to write
  7725. * @returns {Writer} `this`
  7726. */
  7727. Writer.prototype.bytes = function write_bytes(value) {
  7728. var len = value.length >>> 0;
  7729. if (!len)
  7730. return this._push(writeByte, 1, 0);
  7731. if (util.isString(value)) {
  7732. var buf = Writer.alloc(len = base64.length(value));
  7733. base64.decode(value, buf, 0);
  7734. value = buf;
  7735. }
  7736. return this.uint32(len)._push(writeBytes, len, value);
  7737. };
  7738. /**
  7739. * Writes a string.
  7740. * @param {string} value Value to write
  7741. * @returns {Writer} `this`
  7742. */
  7743. Writer.prototype.string = function write_string(value) {
  7744. var len = utf8.length(value);
  7745. return len
  7746. ? this.uint32(len)._push(utf8.write, len, value)
  7747. : this._push(writeByte, 1, 0);
  7748. };
  7749. /**
  7750. * Forks this writer's state by pushing it to a stack.
  7751. * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
  7752. * @returns {Writer} `this`
  7753. */
  7754. Writer.prototype.fork = function fork() {
  7755. this.states = new State(this);
  7756. this.head = this.tail = new Op(noop, 0, 0);
  7757. this.len = 0;
  7758. return this;
  7759. };
  7760. /**
  7761. * Resets this instance to the last state.
  7762. * @returns {Writer} `this`
  7763. */
  7764. Writer.prototype.reset = function reset() {
  7765. if (this.states) {
  7766. this.head = this.states.head;
  7767. this.tail = this.states.tail;
  7768. this.len = this.states.len;
  7769. this.states = this.states.next;
  7770. } else {
  7771. this.head = this.tail = new Op(noop, 0, 0);
  7772. this.len = 0;
  7773. }
  7774. return this;
  7775. };
  7776. /**
  7777. * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
  7778. * @returns {Writer} `this`
  7779. */
  7780. Writer.prototype.ldelim = function ldelim() {
  7781. var head = this.head,
  7782. tail = this.tail,
  7783. len = this.len;
  7784. this.reset().uint32(len);
  7785. if (len) {
  7786. this.tail.next = head.next; // skip noop
  7787. this.tail = tail;
  7788. this.len += len;
  7789. }
  7790. return this;
  7791. };
  7792. /**
  7793. * Finishes the write operation.
  7794. * @returns {Uint8Array} Finished buffer
  7795. */
  7796. Writer.prototype.finish = function finish() {
  7797. var head = this.head.next, // skip noop
  7798. buf = this.constructor.alloc(this.len),
  7799. pos = 0;
  7800. while (head) {
  7801. head.fn(head.val, buf, pos);
  7802. pos += head.len;
  7803. head = head.next;
  7804. }
  7805. // this.head = this.tail = null;
  7806. return buf;
  7807. };
  7808. Writer._configure = function(BufferWriter_) {
  7809. BufferWriter = BufferWriter_;
  7810. Writer.create = create();
  7811. BufferWriter._configure();
  7812. };
  7813. },{"39":39}],43:[function(require,module,exports){
  7814. "use strict";
  7815. module.exports = BufferWriter;
  7816. // extends Writer
  7817. var Writer = require(42);
  7818. (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
  7819. var util = require(39);
  7820. /**
  7821. * Constructs a new buffer writer instance.
  7822. * @classdesc Wire format writer using node buffers.
  7823. * @extends Writer
  7824. * @constructor
  7825. */
  7826. function BufferWriter() {
  7827. Writer.call(this);
  7828. }
  7829. BufferWriter._configure = function () {
  7830. /**
  7831. * Allocates a buffer of the specified size.
  7832. * @function
  7833. * @param {number} size Buffer size
  7834. * @returns {Buffer} Buffer
  7835. */
  7836. BufferWriter.alloc = util._Buffer_allocUnsafe;
  7837. BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set"
  7838. ? function writeBytesBuffer_set(val, buf, pos) {
  7839. buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
  7840. // also works for plain array values
  7841. }
  7842. /* istanbul ignore next */
  7843. : function writeBytesBuffer_copy(val, buf, pos) {
  7844. if (val.copy) // Buffer values
  7845. val.copy(buf, pos, 0, val.length);
  7846. else for (var i = 0; i < val.length;) // plain array values
  7847. buf[pos++] = val[i++];
  7848. };
  7849. };
  7850. /**
  7851. * @override
  7852. */
  7853. BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
  7854. if (util.isString(value))
  7855. value = util._Buffer_from(value, "base64");
  7856. var len = value.length >>> 0;
  7857. this.uint32(len);
  7858. if (len)
  7859. this._push(BufferWriter.writeBytesBuffer, len, value);
  7860. return this;
  7861. };
  7862. function writeStringBuffer(val, buf, pos) {
  7863. if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
  7864. util.utf8.write(val, buf, pos);
  7865. else if (buf.utf8Write)
  7866. buf.utf8Write(val, pos);
  7867. else
  7868. buf.write(val, pos);
  7869. }
  7870. /**
  7871. * @override
  7872. */
  7873. BufferWriter.prototype.string = function write_string_buffer(value) {
  7874. var len = util.Buffer.byteLength(value);
  7875. this.uint32(len);
  7876. if (len)
  7877. this._push(writeStringBuffer, len, value);
  7878. return this;
  7879. };
  7880. /**
  7881. * Finishes the write operation.
  7882. * @name BufferWriter#finish
  7883. * @function
  7884. * @returns {Buffer} Finished buffer
  7885. */
  7886. BufferWriter._configure();
  7887. },{"39":39,"42":42}]},{},[19])
  7888. })();
  7889. //# sourceMappingURL=protobuf.js.map