智慧水务管理系统 - 精河县供水工程综合管理平台

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. "use strict";
  2. var protobuf = require("../light");
  3. var Type = protobuf.Type,
  4. Enum = protobuf.Enum,
  5. Field = protobuf.Field,
  6. Reader = protobuf.Reader,
  7. types = protobuf.types,
  8. util = protobuf.util;
  9. var textformat = protobuf.textformat = module.exports = {};
  10. /**
  11. * Maximum recursion depth for formatting length-delimited unknown fields.
  12. * @name unknownRecursionLimit
  13. * @type {number}
  14. */
  15. textformat.unknownRecursionLimit = 10;
  16. var punct = {
  17. "{": true,
  18. "}": true,
  19. "<": true,
  20. ">": true,
  21. ":": true,
  22. "[": true,
  23. "]": true,
  24. ",": true,
  25. ";": true,
  26. "-": true
  27. };
  28. var identRe = /^[A-Za-z_][A-Za-z0-9_]*$/,
  29. numberStartRe = /[0-9]/,
  30. wordCharRe = /[A-Za-z0-9_]/,
  31. hexRe = /^[0-9A-Fa-f]$/,
  32. octRe = /^[0-7]$/,
  33. floatRe = /^(?:[0-9]+\.[0-9]*(?:[eE][+-]?[0-9]+)?[fF]?|\.[0-9]+(?:[eE][+-]?[0-9]+)?[fF]?|[0-9]+[eE][+-]?[0-9]+[fF]?|[0-9]+[fF])/,
  34. hexIntRe = /^0[xX][0-9A-Fa-f]+/,
  35. octIntRe = /^0[0-7]+/,
  36. decIntRe = /^(?:0|[1-9][0-9]*)/;
  37. /**
  38. * Parses protobuf text format using the specified reflected message type.
  39. * @param {Type} type Reflected message type
  40. * @param {string} text Text format input
  41. * @returns {Message<{}>} Message instance
  42. * @private
  43. */
  44. function parseText(type, text) {
  45. if (!(type instanceof Type))
  46. throw TypeError("type must be a Type");
  47. type.root.resolveAll();
  48. var parser = new Parser(String(text));
  49. var object = parser.parseMessage(type, null, 0);
  50. parser.expectEnd();
  51. var err = verifyTextMessage(type, object),
  52. message;
  53. if (err)
  54. throw Error(err);
  55. message = type.create(object);
  56. return message;
  57. }
  58. /**
  59. * Text format options.
  60. * @interface ITextFormatOptions
  61. * @property {boolean} [unknowns=false] Also includes and formats unknown fields.
  62. */
  63. /**
  64. * Parses a message from protobuf text format using the specified reflected type.
  65. * @function fromText
  66. * @name fromText
  67. * @param {$protobuf.Type} type Reflected message type
  68. * @param {string} text Text format input
  69. * @returns {$protobuf.Message<{}>} Message instance
  70. */
  71. textformat.fromText = function fromText(type, text) {
  72. return parseText(type, text);
  73. };
  74. /**
  75. * Formats a message as protobuf text format using the specified reflected type.
  76. * @function toText
  77. * @name toText
  78. * @param {$protobuf.Type} type Reflected message type
  79. * @param {$protobuf.Message<{}>|Object.<string,*>} message Message instance or plain object
  80. * @param {ITextFormatOptions} [options] Text format options
  81. * @returns {string} Text format output
  82. */
  83. textformat.toText = function toText(type, message, options) {
  84. if (!(type instanceof Type))
  85. throw TypeError("type must be a Type");
  86. type.root.resolveAll();
  87. var lines = [];
  88. writeMessage(type, message, lines, 0, options || {}, 0);
  89. return lines.join("\n");
  90. };
  91. /**
  92. * Installs reflected {@link Type} convenience methods.
  93. * @function install
  94. * @name install
  95. * @returns {undefined}
  96. */
  97. textformat.install = function install() {
  98. /**
  99. * Parses a message of this type from protobuf text format. Convenience for {@link textformat.fromText}.
  100. * @param {string} text Text format input
  101. * @returns {Message<{}>} Message instance
  102. */
  103. Type.prototype.fromText = function fromText(text) {
  104. return textformat.fromText(this, text);
  105. };
  106. /**
  107. * Formats a message of this type as protobuf text format. Convenience for {@link textformat.toText}.
  108. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
  109. * @param {ITextFormatOptions} [options] Text format options
  110. * @returns {string} Text format output
  111. */
  112. Type.prototype.toText = function toText(message, options) {
  113. return textformat.toText(this, message, options);
  114. };
  115. };
  116. function Tokenizer(source) {
  117. this.source = source;
  118. this.pos = 0;
  119. this.len = source.length;
  120. this.line = 1;
  121. this.stack = [];
  122. }
  123. Tokenizer.prototype.error = function error(message) {
  124. return Error(message + " (line " + this.line + ")");
  125. };
  126. Tokenizer.prototype.peek = function peek() {
  127. var token = this.next();
  128. this.push(token);
  129. return token;
  130. };
  131. Tokenizer.prototype.push = function push(token) {
  132. if (token)
  133. this.stack.unshift(token);
  134. };
  135. Tokenizer.prototype.next = function next() {
  136. if (this.stack.length)
  137. return this.stack.shift();
  138. this.skipSpace();
  139. if (this.pos >= this.len)
  140. return null;
  141. var ch = this.source.charAt(this.pos);
  142. if (ch === "\"" || ch === "'")
  143. return this.readString(ch);
  144. if (ch === "." && numberStartRe.test(this.source.charAt(this.pos + 1)) || numberStartRe.test(ch))
  145. return this.readNumber();
  146. if (punct[ch]) {
  147. ++this.pos;
  148. return { type: "punct", value: ch, raw: ch, line: this.line };
  149. }
  150. return this.readWord();
  151. };
  152. Tokenizer.prototype.expect = function expect(value) {
  153. var token = this.next();
  154. if (!token || token.value !== value)
  155. throw this.error("expected '" + value + "'");
  156. return token;
  157. };
  158. Tokenizer.prototype.skip = function skip(value) {
  159. var token = this.next();
  160. if (token && token.value === value)
  161. return true;
  162. this.push(token);
  163. return false;
  164. };
  165. Tokenizer.prototype.skipSpace = function skipSpace() {
  166. var ch;
  167. while (this.pos < this.len) {
  168. ch = this.source.charAt(this.pos);
  169. if (ch === "#") {
  170. while (this.pos < this.len && this.source.charAt(this.pos) !== "\n")
  171. ++this.pos;
  172. } else if (ch === " " || ch === "\t" || ch === "\v" || ch === "\f" || ch === "\r") {
  173. ++this.pos;
  174. } else if (ch === "\n") {
  175. ++this.pos;
  176. ++this.line;
  177. } else
  178. break;
  179. }
  180. };
  181. Tokenizer.prototype.readWord = function readWord() {
  182. var start = this.pos,
  183. ch;
  184. while (this.pos < this.len) {
  185. ch = this.source.charAt(this.pos);
  186. if (ch === "#" || ch === "\"" || ch === "'" || punct[ch] || /\s/.test(ch))
  187. break;
  188. ++this.pos;
  189. }
  190. if (start === this.pos)
  191. throw this.error("illegal character '" + this.source.charAt(this.pos) + "'");
  192. var raw = this.source.substring(start, this.pos);
  193. return { type: "word", value: raw, raw: raw, line: this.line };
  194. };
  195. Tokenizer.prototype.readNumber = function readNumber() {
  196. var rest = this.source.substring(this.pos),
  197. matches = [
  198. floatRe.exec(rest),
  199. hexIntRe.exec(rest),
  200. octIntRe.exec(rest),
  201. decIntRe.exec(rest)
  202. ],
  203. raw = null;
  204. for (var i = 0; i < matches.length; ++i)
  205. if (matches[i] && (!raw || matches[i][0].length > raw.length))
  206. raw = matches[i][0];
  207. if (!raw)
  208. throw this.error("illegal number");
  209. this.pos += raw.length;
  210. if (this.pos < this.len && wordCharRe.test(this.source.charAt(this.pos)))
  211. throw this.error("illegal number '" + raw + this.source.charAt(this.pos) + "'");
  212. return { type: "number", value: raw, raw: raw, line: this.line };
  213. };
  214. Tokenizer.prototype.readString = function readString(quote) {
  215. var bytes = [],
  216. ch,
  217. code;
  218. ++this.pos;
  219. while (this.pos < this.len) {
  220. ch = this.source.charAt(this.pos++);
  221. if (ch === quote)
  222. return { type: "string", value: bytes, raw: quote, line: this.line };
  223. if (ch === "\n")
  224. throw this.error("illegal string");
  225. if (ch !== "\\") {
  226. code = ch.charCodeAt(0);
  227. if ((code & 0xFC00) === 0xD800 && this.pos < this.len) {
  228. var next = this.source.charCodeAt(this.pos);
  229. if ((next & 0xFC00) === 0xDC00) {
  230. ++this.pos;
  231. code = 0x10000 + ((code & 0x03FF) << 10) + (next & 0x03FF);
  232. }
  233. }
  234. pushUtf8(bytes, code);
  235. continue;
  236. }
  237. if (this.pos >= this.len)
  238. throw this.error("illegal string escape");
  239. ch = this.source.charAt(this.pos++);
  240. switch (ch) {
  241. case "a": bytes.push(7); break;
  242. case "b": bytes.push(8); break;
  243. case "f": bytes.push(12); break;
  244. case "n": bytes.push(10); break;
  245. case "r": bytes.push(13); break;
  246. case "t": bytes.push(9); break;
  247. case "v": bytes.push(11); break;
  248. case "?": bytes.push(63); break;
  249. case "\\": bytes.push(92); break;
  250. case "'": bytes.push(39); break;
  251. case "\"": bytes.push(34); break;
  252. case "x":
  253. case "X":
  254. bytes.push(this.readHexEscape());
  255. break;
  256. case "u":
  257. pushUtf8(bytes, this.readCodePoint(4));
  258. break;
  259. case "U":
  260. pushUtf8(bytes, this.readCodePoint(8));
  261. break;
  262. default:
  263. if (octRe.test(ch)) {
  264. bytes.push(this.readOctEscape(ch));
  265. break;
  266. }
  267. throw this.error("illegal string escape '\\" + ch + "'");
  268. }
  269. }
  270. throw this.error("unterminated string");
  271. };
  272. Tokenizer.prototype.readHexEscape = function readHexEscape() {
  273. var value = 0,
  274. count = 0,
  275. ch;
  276. while (count < 2 && this.pos < this.len && hexRe.test(ch = this.source.charAt(this.pos))) {
  277. value = value * 16 + parseInt(ch, 16);
  278. ++this.pos;
  279. ++count;
  280. }
  281. if (!count)
  282. throw this.error("illegal hex escape");
  283. return value;
  284. };
  285. Tokenizer.prototype.readOctEscape = function readOctEscape(first) {
  286. var value = parseInt(first, 8),
  287. count = 1,
  288. ch;
  289. while (count < 3 && this.pos < this.len && octRe.test(ch = this.source.charAt(this.pos))) {
  290. value = value * 8 + parseInt(ch, 8);
  291. ++this.pos;
  292. ++count;
  293. }
  294. return value & 255;
  295. };
  296. Tokenizer.prototype.readCodePoint = function readCodePoint(size) {
  297. var raw = this.source.substring(this.pos, this.pos + size);
  298. if (raw.length !== size || !/^[0-9A-Fa-f]+$/.test(raw))
  299. throw this.error("illegal unicode escape");
  300. this.pos += size;
  301. var code = parseInt(raw, 16);
  302. if (code > 0x10FFFF || code >= 0xD800 && code <= 0xDFFF)
  303. throw this.error("illegal unicode escape");
  304. return code;
  305. };
  306. function Parser(source) {
  307. this.tn = new Tokenizer(source);
  308. }
  309. Parser.prototype.error = function error(message) {
  310. throw this.tn.error(message);
  311. };
  312. Parser.prototype.expectEnd = function expectEnd() {
  313. var token = this.tn.next();
  314. if (token)
  315. this.error("unexpected token '" + token.value + "'");
  316. };
  317. Parser.prototype.parseMessage = function parseMessage(type, end, depth) {
  318. if (depth > util.recursionLimit)
  319. this.error("max depth exceeded");
  320. var object = {},
  321. seen = {};
  322. for (;;) {
  323. var token = this.tn.peek();
  324. if (!token) {
  325. if (end)
  326. this.error("expected '" + end + "'");
  327. return object;
  328. }
  329. if (end && token.value === end) {
  330. this.tn.next();
  331. return object;
  332. }
  333. if (isSeparator(token))
  334. this.error("unexpected separator");
  335. this.parseField(type, object, seen, depth);
  336. token = this.tn.peek();
  337. if (token && isSeparator(token)) {
  338. this.tn.next();
  339. token = this.tn.peek();
  340. if (token && isSeparator(token))
  341. this.error("unexpected separator");
  342. }
  343. }
  344. };
  345. Parser.prototype.parseField = function parseField(type, object, seen, depth) {
  346. var info = this.readFieldName(type);
  347. if (info.any) {
  348. this.parseAny(type, info.name, object, seen, depth);
  349. return;
  350. }
  351. if (!info.field) {
  352. this.skipReservedValue(depth);
  353. return;
  354. }
  355. var field = info.field.resolve();
  356. if (field.map) {
  357. this.parseMessageFieldDelimiter();
  358. this.parseMapField(field, object, depth);
  359. } else if (field.resolvedType instanceof Type) {
  360. this.parseMessageFieldDelimiter();
  361. if (this.tn.skip("[")) {
  362. if (!field.repeated)
  363. this.error(field.fullName + ": list value specified for singular field");
  364. if (!this.tn.skip("]")) {
  365. do {
  366. addField(object, seen, field, this.parseMessageValue(field.resolvedType, depth));
  367. } while (this.tn.skip(","));
  368. this.tn.expect("]");
  369. }
  370. } else
  371. addField(object, seen, field, this.parseMessageValue(field.resolvedType, depth));
  372. } else {
  373. this.tn.expect(":");
  374. if (this.tn.skip("[")) {
  375. if (!field.repeated)
  376. this.error(field.fullName + ": list value specified for singular field");
  377. if (!this.tn.skip("]")) {
  378. do {
  379. addField(object, seen, field, this.parseScalar(field));
  380. } while (this.tn.skip(","));
  381. this.tn.expect("]");
  382. }
  383. } else
  384. addField(object, seen, field, this.parseScalar(field));
  385. }
  386. };
  387. Parser.prototype.readFieldName = function readFieldName(type) {
  388. var token = this.tn.next();
  389. if (!token)
  390. this.error("expected field name");
  391. if (token.value === "[") {
  392. var bracketName = this.readBracketName();
  393. if (type.fullName === ".google.protobuf.Any" && bracketName.indexOf("/") >= 0)
  394. return { any: true, name: bracketName };
  395. return { field: lookupExtension(type, bracketName), name: bracketName };
  396. }
  397. if (token.type !== "word" || !identRe.test(token.value))
  398. this.error("illegal field name '" + token.value + "'");
  399. var field = lookupField(type, token.value);
  400. if (!field) {
  401. if (type.isReservedName(token.value))
  402. return { name: token.value };
  403. this.error(type.fullName + ": unknown field '" + token.value + "'");
  404. }
  405. return { field: field, name: token.value };
  406. };
  407. Parser.prototype.readBracketName = function readBracketName() {
  408. var parts = [],
  409. token;
  410. while (token = this.tn.next()) {
  411. if (token.value === "]")
  412. return parts.join("");
  413. parts.push(token.raw || token.value);
  414. }
  415. this.error("unterminated bracketed field name");
  416. return null;
  417. };
  418. Parser.prototype.parseAny = function parseAny(type, typeUrl, object, seen, depth) {
  419. this.parseMessageFieldDelimiter();
  420. validateTypeUrl(typeUrl);
  421. var typeName = typeUrl.substring(typeUrl.lastIndexOf("/") + 1),
  422. embeddedType = type.root.lookupType(typeName.charAt(0) === "." ? typeName : "." + typeName),
  423. embedded = this.parseMessageValue(embeddedType, depth),
  424. typeUrlField = lookupField(type, "type_url") || lookupField(type, "typeUrl"),
  425. valueField = lookupField(type, "value");
  426. addField(object, seen, typeUrlField, typeUrl);
  427. addField(object, seen, valueField, embeddedType.encode(embedded).finish());
  428. };
  429. Parser.prototype.parseMapField = function parseMapField(field, object, depth) {
  430. if (!object[field.name])
  431. object[field.name] = {};
  432. if (this.tn.skip("[")) {
  433. if (!this.tn.skip("]")) {
  434. do {
  435. addMapEntry(field, object[field.name], this.parseMapEntry(field, depth + 1));
  436. } while (this.tn.skip(","));
  437. this.tn.expect("]");
  438. }
  439. } else
  440. addMapEntry(field, object[field.name], this.parseMapEntry(field, depth + 1));
  441. };
  442. Parser.prototype.parseMessageFieldDelimiter = function parseMessageFieldDelimiter() {
  443. this.tn.skip(":");
  444. };
  445. Parser.prototype.parseMapEntry = function parseMapEntry(field, depth) {
  446. if (depth > util.recursionLimit)
  447. this.error("max depth exceeded");
  448. var end;
  449. if (this.tn.skip("{"))
  450. end = "}";
  451. else if (this.tn.skip("<"))
  452. end = ">";
  453. else
  454. this.error("expected map entry");
  455. var entry = {},
  456. token,
  457. valueField = mapValueField(field),
  458. keyField = mapKeyField(field);
  459. for (;;) {
  460. token = this.tn.peek();
  461. if (!token)
  462. this.error("expected '" + end + "'");
  463. if (token.value === end) {
  464. this.tn.next();
  465. return entry;
  466. }
  467. if (isSeparator(token))
  468. this.error("unexpected separator");
  469. token = this.tn.next();
  470. if (token.type !== "word")
  471. this.error("expected map field name");
  472. if (token.value === "key") {
  473. this.tn.expect(":");
  474. entry.key = this.parseScalar(keyField);
  475. } else if (token.value === "value") {
  476. if (valueField.resolvedType instanceof Type) {
  477. this.parseMessageFieldDelimiter();
  478. entry.value = this.parseMessageValue(valueField.resolvedType, depth);
  479. } else {
  480. this.tn.expect(":");
  481. entry.value = this.parseScalar(valueField);
  482. }
  483. } else
  484. this.error("unknown map field '" + token.value + "'");
  485. token = this.tn.peek();
  486. if (token && isSeparator(token)) {
  487. this.tn.next();
  488. token = this.tn.peek();
  489. if (token && isSeparator(token))
  490. this.error("unexpected separator");
  491. }
  492. }
  493. };
  494. Parser.prototype.parseMessageValue = function parseMessageValue(type, depth) {
  495. var end;
  496. if (this.tn.skip("{"))
  497. end = "}";
  498. else if (this.tn.skip("<"))
  499. end = ">";
  500. else
  501. this.error("expected message value");
  502. return this.parseMessage(type, end, depth + 1);
  503. };
  504. Parser.prototype.parseScalar = function parseScalar(field) {
  505. if (field.type === "string" || field.type === "bytes") {
  506. var bytes = this.readStringBytes();
  507. return field.type === "bytes" ? util.newBuffer(bytes) : utf8Read(bytes, true);
  508. }
  509. var sign = 1;
  510. if (this.tn.skip("-"))
  511. sign = -1;
  512. var token = this.tn.next();
  513. if (!token)
  514. this.error("expected value");
  515. if (field.resolvedType instanceof Enum)
  516. return parseEnum(field, token, sign);
  517. switch (field.type) {
  518. case "double":
  519. case "float":
  520. return parseFloatValue(token, sign);
  521. case "bool":
  522. return parseBool(token, sign);
  523. case "int32":
  524. case "sint32":
  525. case "sfixed32":
  526. return parseInteger(token, sign, false, 32);
  527. case "uint32":
  528. case "fixed32":
  529. return parseInteger(token, sign, true, 32);
  530. case "int64":
  531. case "sint64":
  532. case "sfixed64":
  533. return parseInteger(token, sign, false, 64);
  534. case "uint64":
  535. case "fixed64":
  536. return parseInteger(token, sign, true, 64);
  537. default:
  538. this.error(field.fullName + ": unsupported scalar type");
  539. }
  540. return undefined;
  541. };
  542. Parser.prototype.readStringBytes = function readStringBytes() {
  543. var token = this.tn.next(),
  544. bytes = [];
  545. if (!token || token.type !== "string")
  546. this.error("expected string");
  547. Array.prototype.push.apply(bytes, token.value);
  548. while ((token = this.tn.peek()) && token.type === "string") {
  549. token = this.tn.next();
  550. Array.prototype.push.apply(bytes, token.value);
  551. }
  552. return bytes;
  553. };
  554. Parser.prototype.skipReservedValue = function skipReservedValue(depth) {
  555. this.tn.skip(":");
  556. var token = this.tn.peek();
  557. if (!token)
  558. return;
  559. if (token.value === "{") {
  560. this.skipBalanced("{", "}", depth);
  561. } else if (token.value === "<") {
  562. this.skipBalanced("<", ">", depth);
  563. } else if (token.value === "[") {
  564. this.skipBalanced("[", "]", depth);
  565. } else if (token.type === "string") {
  566. this.readStringBytes();
  567. } else {
  568. if (token.value === "-")
  569. this.tn.next();
  570. this.tn.next();
  571. }
  572. };
  573. Parser.prototype.skipBalanced = function skipBalanced(open, close, depth) {
  574. var balance = 0,
  575. token;
  576. do {
  577. token = this.tn.next();
  578. if (!token)
  579. this.error("expected '" + close + "'");
  580. if (token.value === open) {
  581. if (depth + ++balance > util.recursionLimit)
  582. this.error("max depth exceeded");
  583. }
  584. else if (token.value === close)
  585. --balance;
  586. } while (balance);
  587. };
  588. function addField(object, seen, field, value) {
  589. if (field.repeated) {
  590. (object[field.name] || (object[field.name] = [])).push(value);
  591. return;
  592. }
  593. if (Object.prototype.hasOwnProperty.call(seen, field.name))
  594. throw Error(field.fullName + ": multiple values");
  595. if (field.partOf) {
  596. var oneofName = "$oneof:" + field.partOf.name;
  597. if (seen[oneofName])
  598. throw Error(field.partOf.name + ": multiple values");
  599. seen[oneofName] = true;
  600. }
  601. seen[field.name] = true;
  602. object[field.name] = value;
  603. }
  604. function addMapEntry(field, map, entry) {
  605. var keyField = mapKeyField(field),
  606. valueField = mapValueField(field),
  607. key = Object.prototype.hasOwnProperty.call(entry, "key")
  608. ? entry.key
  609. : defaultScalarValue(keyField),
  610. value = Object.prototype.hasOwnProperty.call(entry, "value")
  611. ? entry.value
  612. : defaultMapValue(valueField);
  613. map[mapKey(keyField, key)] = value;
  614. }
  615. function defaultMapValue(field) {
  616. if (field.resolvedType instanceof Type)
  617. return field.resolvedType.create();
  618. if (field.resolvedType instanceof Enum)
  619. return field.typeDefault;
  620. return defaultScalarValue(field);
  621. }
  622. function defaultScalarValue(field) {
  623. if (field.type === "string")
  624. return "";
  625. if (field.type === "bytes")
  626. return util.newBuffer([]);
  627. if (field.type === "bool")
  628. return false;
  629. return field.defaultValue;
  630. }
  631. function mapKeyField(field) {
  632. return {
  633. name: "key",
  634. fullName: field.fullName + ".key",
  635. type: field.keyType,
  636. resolvedType: null,
  637. defaultValue: field.keyType === "bool" ? false : field.keyType === "string" ? "" : 0
  638. };
  639. }
  640. function mapValueField(field) {
  641. return {
  642. name: "value",
  643. fullName: field.fullName + ".value",
  644. type: field.type,
  645. resolvedType: field.resolvedType,
  646. defaultValue: field.resolvedType instanceof Enum ? field.resolvedType.values[Object.keys(field.resolvedType.values)[0]] : field.typeDefault
  647. };
  648. }
  649. function mapKey(field, value) {
  650. if (types.long[field.type] !== undefined)
  651. return String(value);
  652. if (field.type === "bool")
  653. return value ? "true" : "false";
  654. return String(value);
  655. }
  656. function lookupField(type, name) {
  657. var fields = type.fieldsArray;
  658. for (var i = 0; i < fields.length; ++i) {
  659. var field = fields[i].resolve();
  660. if (field.name === name || underScore(field.name) === name)
  661. return field;
  662. if (field.delimited && field.resolvedType instanceof Type) {
  663. var groupName = field.resolvedType.name,
  664. lowerName = name.toLowerCase(),
  665. compactName = compact(name);
  666. if (groupName === name || underScore(groupName) === name
  667. || field.name.toLowerCase() === lowerName
  668. || groupName.toLowerCase() === lowerName
  669. || compact(field.name) === compactName
  670. || compact(groupName) === compactName)
  671. return field;
  672. }
  673. }
  674. return null;
  675. }
  676. function lookupExtension(type, name) {
  677. var fullName = name.charAt(0) === "." ? name : "." + name,
  678. camelName = camelCaseLastPath(fullName),
  679. field = type.get(fullName) || type.root.lookup(fullName, Field)
  680. || type.get(camelName) || type.root.lookup(camelName, Field);
  681. if (!field)
  682. field = lookupExtensionField(type, fullName);
  683. if (field && field.extend !== undefined && field.extensionField)
  684. field = field.extensionField;
  685. if (!field || field.parent !== type)
  686. throw Error(type.fullName + ": unknown extension '" + name + "'");
  687. return field;
  688. }
  689. function camelCaseLastPath(name) {
  690. var dot = name.lastIndexOf(".");
  691. return name.substring(0, dot + 1) + util.camelCase(name.substring(dot + 1));
  692. }
  693. function parseEnum(field, token, sign) {
  694. if (sign < 0) {
  695. if (token.type !== "number")
  696. throw Error(field.fullName + ": enum value expected");
  697. return checkEnumValue(field, parseInteger(token, sign, false, 32));
  698. }
  699. if (token.type === "word") {
  700. var value = field.resolvedType.values[token.value];
  701. if (value === undefined)
  702. throw Error(field.fullName + ": enum value expected");
  703. return value;
  704. }
  705. return checkEnumValue(field, parseInteger(token, sign, false, 32));
  706. }
  707. function parseBool(token, sign) {
  708. if (sign < 0)
  709. throw Error("bool value expected");
  710. if (token.type === "word") {
  711. switch (token.value) {
  712. case "true":
  713. case "True":
  714. case "t":
  715. return true;
  716. case "false":
  717. case "False":
  718. case "f":
  719. return false;
  720. }
  721. } else if (token.type === "number") {
  722. var value = parseInteger(token, 1, true, 32);
  723. if (value === 0)
  724. return false;
  725. if (value === 1)
  726. return true;
  727. }
  728. throw Error("bool value expected");
  729. }
  730. function parseFloatValue(token, sign) {
  731. if (token.type === "word") {
  732. switch (token.value.toLowerCase()) {
  733. case "inf":
  734. case "infinity":
  735. return sign * Infinity;
  736. case "nan":
  737. return NaN;
  738. }
  739. throw Error("float value expected");
  740. }
  741. if (token.type !== "number")
  742. throw Error("float value expected");
  743. var raw = token.value;
  744. if (/^0[xX]/.test(raw) || /^0[0-7]/.test(raw) && raw.length > 1)
  745. throw Error("float value expected");
  746. if (/[fF]$/.test(raw))
  747. raw = raw.substring(0, raw.length - 1);
  748. return sign * Number(raw);
  749. }
  750. function parseInteger(token, sign, unsigned, bits) {
  751. if (token.type !== "number")
  752. throw Error("integer value expected");
  753. if (sign < 0 && unsigned)
  754. throw Error("unsigned integer value expected");
  755. var raw = token.value,
  756. radix = 10,
  757. digits = raw;
  758. if (/^0[xX]/.test(raw)) {
  759. radix = 16;
  760. digits = raw.substring(2);
  761. } else if (/^0[0-7]/.test(raw) && raw.length > 1) {
  762. radix = 8;
  763. digits = raw.substring(1);
  764. } else if (!/^(?:0|[1-9][0-9]*)$/.test(raw))
  765. throw Error("integer value expected");
  766. if (typeof util.global.BigInt === "function")
  767. return parseIntegerBigInt(digits, radix, sign, unsigned, bits);
  768. var value = parseInt(digits, radix) * sign;
  769. if (bits === 64 && util.Long)
  770. return util.Long.fromString(String(value), unsigned);
  771. return value;
  772. }
  773. function parseIntegerBigInt(digits, radix, sign, unsigned, bits) {
  774. var value,
  775. BigInt = util.global.BigInt;
  776. if (radix === 16)
  777. value = BigInt("0x" + digits);
  778. else if (radix === 8)
  779. value = BigInt("0o" + digits);
  780. else
  781. value = BigInt(digits);
  782. if (sign < 0)
  783. value = -value;
  784. var min,
  785. max;
  786. if (bits === 32) {
  787. min = unsigned ? BigInt(0) : -BigInt(2147483648);
  788. max = unsigned ? BigInt(4294967295) : BigInt(2147483647);
  789. } else {
  790. min = unsigned ? BigInt(0) : -BigInt("9223372036854775808");
  791. max = unsigned ? BigInt("18446744073709551615") : BigInt("9223372036854775807");
  792. }
  793. if (value < min || value > max)
  794. throw Error((unsigned ? "unsigned " : "") + "integer value out of range");
  795. if (bits === 64 && util.Long)
  796. return util.Long.fromString(value.toString(), unsigned, 10);
  797. return Number(value);
  798. }
  799. function writeMessage(type, message, lines, indent, options, depth) {
  800. if (depth > util.recursionLimit)
  801. throw Error("max depth exceeded");
  802. var fields = type.fieldsArray.slice().sort(util.compareFieldsById);
  803. for (var i = 0; i < fields.length; ++i) {
  804. var field = fields[i].resolve(),
  805. value = message[field.name];
  806. if (value == null || !Object.prototype.hasOwnProperty.call(message, field.name))
  807. continue;
  808. if (field.map)
  809. writeMapField(field, value, lines, indent, options, depth);
  810. else if (field.repeated)
  811. for (var j = 0; j < value.length; ++j)
  812. writeField(field, value[j], lines, indent, options, depth);
  813. else
  814. writeField(field, value, lines, indent, options, depth);
  815. }
  816. if (options.unknowns && message.$unknowns != null && Object.prototype.hasOwnProperty.call(message, "$unknowns"))
  817. writeUnknowns(message.$unknowns, lines, indent);
  818. }
  819. function writeMapField(field, map, lines, indent, options, depth) {
  820. var keys = Object.keys(map).sort(),
  821. keyField = mapKeyField(field),
  822. valueField = mapValueField(field),
  823. name = formatFieldName(field),
  824. sp = spaces(indent);
  825. for (var i = 0; i < keys.length; ++i) {
  826. if (depth + 1 > util.recursionLimit)
  827. throw Error("max depth exceeded");
  828. var key = keyField.long ? util.longFromKey(keys[i], keyField.type === "uint64" || keyField.type === "fixed64") : keys[i];
  829. if (keyField.type === "bool")
  830. key = util.boolFromKey(keys[i]);
  831. lines.push(sp + name + " {");
  832. lines.push(spaces(indent + 2) + "key: " + formatScalar(keyField, key));
  833. if (valueField.resolvedType instanceof Type) {
  834. lines.push(spaces(indent + 2) + "value {");
  835. writeMessage(valueField.resolvedType, map[keys[i]], lines, indent + 4, options, depth + 2);
  836. lines.push(spaces(indent + 2) + "}");
  837. } else
  838. lines.push(spaces(indent + 2) + "value: " + formatScalar(valueField, map[keys[i]]));
  839. lines.push(sp + "}");
  840. }
  841. }
  842. function writeField(field, value, lines, indent, options, depth) {
  843. var name = formatFieldName(field),
  844. sp = spaces(indent);
  845. if (field.resolvedType instanceof Type) {
  846. lines.push(sp + name + " {");
  847. writeMessage(field.resolvedType, value, lines, indent + 2, options, depth + 1);
  848. lines.push(sp + "}");
  849. } else
  850. lines.push(sp + name + ": " + formatScalar(field, value));
  851. }
  852. function writeUnknowns(unknowns, lines, indent) {
  853. for (var i = 0; i < unknowns.length; ++i) {
  854. var reader = Reader.create(unknowns[i]);
  855. writeUnknownFieldSet(reader, lines, indent, undefined, textformat.unknownRecursionLimit);
  856. if (reader.pos !== reader.len)
  857. throw Error("invalid unknown field data");
  858. }
  859. }
  860. function writeUnknownFieldSet(reader, lines, indent, endGroup, recursionBudget) {
  861. if (recursionBudget < 0)
  862. throw Error("max depth exceeded");
  863. while (reader.pos < reader.len) {
  864. var tag = reader.tag(),
  865. fieldNumber = tag >>> 3,
  866. wireType = tag & 7;
  867. if (!fieldNumber)
  868. throw Error("illegal tag: field number 0");
  869. if (wireType === 4) {
  870. if (fieldNumber !== endGroup)
  871. throw Error("invalid end group tag");
  872. return;
  873. }
  874. writeUnknownField(reader, fieldNumber, wireType, lines, indent, recursionBudget);
  875. }
  876. if (endGroup !== undefined)
  877. throw Error("missing end group tag");
  878. }
  879. function writeUnknownField(reader, fieldNumber, wireType, lines, indent, recursionBudget) {
  880. var sp = spaces(indent),
  881. lo;
  882. switch (wireType) {
  883. case 0:
  884. lines.push(sp + fieldNumber + ": " + readUnknownVarint(reader));
  885. break;
  886. case 1:
  887. lo = reader.fixed32();
  888. lines.push(sp + fieldNumber + ": 0x" + hexPad(reader.fixed32(), 8) + hexPad(lo, 8));
  889. break;
  890. case 2:
  891. writeUnknownLengthDelimited(reader, fieldNumber, lines, indent, recursionBudget);
  892. break;
  893. case 3:
  894. lines.push(sp + fieldNumber + " {");
  895. writeUnknownFieldSet(reader, lines, indent + 2, fieldNumber, recursionBudget - 1);
  896. lines.push(sp + "}");
  897. break;
  898. case 5:
  899. lines.push(sp + fieldNumber + ": 0x" + hexPad(reader.fixed32(), 8));
  900. break;
  901. default:
  902. throw Error("invalid wire type " + wireType);
  903. }
  904. }
  905. function writeUnknownLengthDelimited(reader, fieldNumber, lines, indent, recursionBudget) {
  906. var value = reader.bytes(),
  907. nested = value.length && recursionBudget > 0
  908. ? tryFormatUnknownMessage(value, indent + 2, recursionBudget - 1)
  909. : null,
  910. sp = spaces(indent);
  911. if (nested) {
  912. lines.push(sp + fieldNumber + " {");
  913. for (var i = 0; i < nested.length; ++i)
  914. lines.push(nested[i]);
  915. lines.push(sp + "}");
  916. } else
  917. lines.push(sp + fieldNumber + ": " + quoteBytes(value));
  918. }
  919. function tryFormatUnknownMessage(bytes, indent, recursionBudget) {
  920. var reader = Reader.create(bytes),
  921. lines = [];
  922. try {
  923. writeUnknownFieldSet(reader, lines, indent, undefined, recursionBudget);
  924. return reader.pos === reader.len ? lines : null;
  925. } catch (e) {
  926. return null;
  927. }
  928. }
  929. function readUnknownVarint(reader) {
  930. var BigInt = util.global.BigInt;
  931. if (typeof BigInt !== "function")
  932. return String(reader.uint64());
  933. var value = BigInt(0),
  934. shift = BigInt(0),
  935. b;
  936. for (var i = 0; i < 10; ++i) {
  937. if (reader.pos >= reader.len)
  938. throw Error("invalid varint encoding");
  939. b = reader.buf[reader.pos++];
  940. value += BigInt(b & 127) << shift;
  941. if (b < 128)
  942. return value.toString();
  943. shift += BigInt(7);
  944. }
  945. throw Error("invalid varint encoding");
  946. }
  947. function hexPad(value, length) {
  948. var str = value.toString(16);
  949. while (str.length < length)
  950. str = "0" + str;
  951. return str;
  952. }
  953. function formatFieldName(field) {
  954. if (field.declaringField || field.name.charAt(0) === ".")
  955. return "[" + formatExtensionName(field) + "]";
  956. if (field.delimited && field.resolvedType instanceof Type && compact(field.name) === compact(field.resolvedType.name))
  957. return field.resolvedType.name;
  958. return underScore(field.name);
  959. }
  960. function formatExtensionName(field) {
  961. var name = field.name.replace(/^\./, ""),
  962. dot = name.lastIndexOf("."),
  963. path = name.substring(0, dot + 1),
  964. last = name.substring(dot + 1);
  965. if (field.delimited && field.resolvedType instanceof Type && field.resolvedType.group)
  966. last = last.toLowerCase();
  967. else
  968. last = underScore(last);
  969. return path + last;
  970. }
  971. function formatScalar(field, value) {
  972. if (field.resolvedType instanceof Enum) {
  973. var name = field.resolvedType.valuesById[value];
  974. return name === undefined ? String(value) : name;
  975. }
  976. switch (field.type) {
  977. case "string":
  978. return quoteBytes(utf8Bytes(String(value)));
  979. case "bytes":
  980. return quoteBytes(bytesValue(value));
  981. case "bool":
  982. return value ? "true" : "false";
  983. case "double":
  984. case "float":
  985. if (isNaN(value))
  986. return "nan";
  987. if (value === 0 && 1 / value === -Infinity)
  988. return "-0";
  989. if (value === Infinity)
  990. return "inf";
  991. if (value === -Infinity)
  992. return "-inf";
  993. return String(value);
  994. default:
  995. return String(value);
  996. }
  997. }
  998. function bytesValue(value) {
  999. if (typeof value === "string") {
  1000. var length = util.base64.length(value),
  1001. buffer = util.newBuffer(length);
  1002. util.base64.decode(value, buffer, 0);
  1003. return buffer;
  1004. }
  1005. return value;
  1006. }
  1007. function quoteBytes(bytes) {
  1008. var out = "\"",
  1009. oct;
  1010. for (var i = 0; i < bytes.length; ++i) {
  1011. var b = bytes[i];
  1012. switch (b) {
  1013. case 9: out += "\\t"; break;
  1014. case 10: out += "\\n"; break;
  1015. case 13: out += "\\r"; break;
  1016. case 34: out += "\\\""; break;
  1017. case 92: out += "\\\\"; break;
  1018. default:
  1019. if (b >= 32 && b <= 126)
  1020. out += String.fromCharCode(b);
  1021. else {
  1022. oct = b.toString(8);
  1023. out += "\\" + (oct.length < 2 ? "00" : oct.length < 3 ? "0" : "") + oct;
  1024. }
  1025. break;
  1026. }
  1027. }
  1028. return out + "\"";
  1029. }
  1030. function spaces(indent) {
  1031. var str = "";
  1032. while (str.length < indent)
  1033. str += " ";
  1034. return str;
  1035. }
  1036. function utf8Read(bytes, strict) {
  1037. if (strict && !validUtf8(bytes))
  1038. throw Error("invalid UTF-8 string");
  1039. var buffer = util.newBuffer(bytes);
  1040. return util.utf8.read(buffer, 0, buffer.length);
  1041. }
  1042. function validUtf8(bytes) {
  1043. for (var i = 0, b; i < bytes.length;) {
  1044. b = bytes[i++];
  1045. if (b <= 0x7F)
  1046. continue;
  1047. if (b >= 0xC2 && b <= 0xDF) {
  1048. if ((b = bytes[i++]) < 0x80 || b > 0xBF)
  1049. return false;
  1050. } else if (b === 0xE0) {
  1051. if ((b = bytes[i++]) < 0xA0 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1052. return false;
  1053. } else if (b >= 0xE1 && b <= 0xEC || b >= 0xEE && b <= 0xEF) {
  1054. if ((b = bytes[i++]) < 0x80 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1055. return false;
  1056. } else if (b === 0xED) {
  1057. if ((b = bytes[i++]) < 0x80 || b > 0x9F || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1058. return false;
  1059. } else if (b === 0xF0) {
  1060. if ((b = bytes[i++]) < 0x90 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1061. return false;
  1062. } else if (b >= 0xF1 && b <= 0xF3) {
  1063. if ((b = bytes[i++]) < 0x80 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1064. return false;
  1065. } else if (b === 0xF4) {
  1066. if ((b = bytes[i++]) < 0x80 || b > 0x8F || (b = bytes[i++]) < 0x80 || b > 0xBF || (b = bytes[i++]) < 0x80 || b > 0xBF)
  1067. return false;
  1068. } else
  1069. return false;
  1070. }
  1071. return true;
  1072. }
  1073. function utf8Bytes(str) {
  1074. var buffer = util.newBuffer(util.utf8.length(str));
  1075. util.utf8.write(str, buffer, 0);
  1076. return buffer;
  1077. }
  1078. function pushUtf8(bytes, code) {
  1079. if (code < 0x80) {
  1080. bytes.push(code);
  1081. } else if (code < 0x800) {
  1082. bytes.push(code >> 6 | 192, code & 63 | 128);
  1083. } else if (code < 0x10000) {
  1084. bytes.push(code >> 12 | 224, code >> 6 & 63 | 128, code & 63 | 128);
  1085. } else {
  1086. bytes.push(code >> 18 | 240, code >> 12 & 63 | 128, code >> 6 & 63 | 128, code & 63 | 128);
  1087. }
  1088. }
  1089. function verifyTextMessage(type, message) {
  1090. var fields = type.fieldsArray;
  1091. for (var i = 0; i < fields.length; ++i) {
  1092. var field = fields[i].resolve(),
  1093. value = message[field.name];
  1094. if (value == null || !Object.prototype.hasOwnProperty.call(message, field.name)) {
  1095. if (field.required)
  1096. return field.fullName + ": missing required field";
  1097. continue;
  1098. }
  1099. if (field.map) {
  1100. if (field.resolvedType instanceof Type)
  1101. for (var key in value)
  1102. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1103. var mapErr = verifyTextMessage(field.resolvedType, value[key]);
  1104. if (mapErr)
  1105. return mapErr;
  1106. }
  1107. } else if (field.repeated) {
  1108. if (field.resolvedType instanceof Type)
  1109. for (var j = 0; j < value.length; ++j) {
  1110. var repeatedErr = verifyTextMessage(field.resolvedType, value[j]);
  1111. if (repeatedErr)
  1112. return repeatedErr;
  1113. }
  1114. } else if (field.resolvedType instanceof Type) {
  1115. var err = verifyTextMessage(field.resolvedType, value);
  1116. if (err)
  1117. return err;
  1118. }
  1119. }
  1120. return null;
  1121. }
  1122. function isSeparator(token) {
  1123. return token.value === "," || token.value === ";";
  1124. }
  1125. function validateTypeUrl(typeUrl) {
  1126. for (var i = 0; i < typeUrl.length; ++i)
  1127. if (typeUrl.charAt(i) === "%") {
  1128. if (i + 2 >= typeUrl.length || !hexRe.test(typeUrl.charAt(i + 1)) || !hexRe.test(typeUrl.charAt(i + 2)))
  1129. throw Error("invalid Any type URL");
  1130. i += 2;
  1131. }
  1132. }
  1133. function lookupExtensionField(type, fullName) {
  1134. var fields = type.fieldsArray;
  1135. for (var i = 0; i < fields.length; ++i) {
  1136. var field = fields[i].resolve();
  1137. if (field.name.charAt(0) === "." && "." + formatExtensionName(field) === fullName)
  1138. return field;
  1139. }
  1140. return null;
  1141. }
  1142. function checkEnumValue(field, value) {
  1143. if (isClosedEnum(field) && field.resolvedType.valuesById[value] === undefined)
  1144. throw Error(field.fullName + ": enum value expected");
  1145. return value;
  1146. }
  1147. function isClosedEnum(field) {
  1148. return field.resolvedType
  1149. && field.resolvedType._features
  1150. && field.resolvedType._features.enum_type === "CLOSED";
  1151. }
  1152. function compact(str) {
  1153. return str.replace(/_/g, "").toLowerCase();
  1154. }
  1155. function underScore(str) {
  1156. return str.substring(0, 1)
  1157. + str.substring(1)
  1158. .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
  1159. }