index.mjs 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  1. /*!
  2. * TSBuffer v2.2.10
  3. * -----------------------------------------
  4. * MIT LICENSE
  5. * KingWorks (C) Copyright 2025
  6. * https://github.com/k8w/tsbuffer
  7. */
  8. import 'k8w-extend-native';
  9. import { __assign } from 'tslib';
  10. import { TSBufferValidator } from 'tsbuffer-validator';
  11. import { SchemaType } from 'tsbuffer-schema';
  12. var Base64Util = /** @class */ (function () {
  13. function Base64Util() {
  14. }
  15. Base64Util.bufferToBase64 = function (buf) {
  16. if (typeof Buffer !== "undefined") {
  17. return Buffer.from(buf).toString("base64");
  18. }
  19. var base64 = "";
  20. var len = buf.length;
  21. for (var i = 0; i < len; i += 3) {
  22. base64 += base64Chars[buf[i] >> 2];
  23. base64 += base64Chars[((buf[i] & 3) << 4) | (buf[i + 1] >> 4)];
  24. base64 += base64Chars[((buf[i + 1] & 15) << 2) | (buf[i + 2] >> 6)];
  25. base64 += base64Chars[buf[i + 2] & 63];
  26. }
  27. if (len % 3 === 2) {
  28. base64 = base64.substring(0, base64.length - 1) + "=";
  29. }
  30. else if (len % 3 === 1) {
  31. base64 = base64.substring(0, base64.length - 2) + "==";
  32. }
  33. return base64;
  34. };
  35. Base64Util.base64ToBuffer = function (base64) {
  36. if (typeof Buffer !== "undefined") {
  37. return new Uint8Array(Buffer.from(base64, "base64"));
  38. }
  39. var bufferLength = base64.length * 0.75, len = base64.length, p = 0;
  40. var encoded1, encoded2, encoded3, encoded4;
  41. if (base64[base64.length - 1] === "=") {
  42. bufferLength--;
  43. if (base64[base64.length - 2] === "=") {
  44. bufferLength--;
  45. }
  46. }
  47. var buf = new Uint8Array(bufferLength);
  48. for (var i = 0; i < len; i += 4) {
  49. encoded1 = lookup[base64.charCodeAt(i)];
  50. encoded2 = lookup[base64.charCodeAt(i + 1)];
  51. encoded3 = lookup[base64.charCodeAt(i + 2)];
  52. encoded4 = lookup[base64.charCodeAt(i + 3)];
  53. buf[p++] = (encoded1 << 2) | (encoded2 >> 4);
  54. buf[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  55. buf[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  56. }
  57. return buf;
  58. };
  59. return Base64Util;
  60. }());
  61. /*base64*/
  62. var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  63. // Use a lookup table to find the index.
  64. var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
  65. for (var i = 0; i < base64Chars.length; i++) {
  66. lookup[base64Chars.charCodeAt(i)] = i;
  67. }
  68. /*end*/
  69. var CoderUtil = /** @class */ (function () {
  70. function CoderUtil() {
  71. }
  72. CoderUtil.isJsonCompatible = function (schema, type, protoHelper) {
  73. var _this = this;
  74. var schemaInfo = schema;
  75. var key = type === "encode" ? "isJsonEncodable" : "isJsonDecodable";
  76. if (schemaInfo[key] === undefined) {
  77. // Just for avoding circular recursive, the value should be overwriten below
  78. schemaInfo[key] = true;
  79. switch (schema.type) {
  80. case SchemaType.Array:
  81. schemaInfo[key] = this.isJsonCompatible(schema.elementType, type, protoHelper);
  82. break;
  83. case SchemaType.Tuple:
  84. schemaInfo[key] = schema.elementTypes.every(function (v) {
  85. return _this.isJsonCompatible(v, type, protoHelper);
  86. });
  87. break;
  88. case SchemaType.Interface:
  89. var flatSchema = protoHelper.getFlatInterfaceSchema(schema);
  90. schemaInfo[key] = flatSchema.properties.every(function (v) {
  91. return _this.isJsonCompatible(v.type, type, protoHelper);
  92. });
  93. if (flatSchema.indexSignature) {
  94. schemaInfo[key] =
  95. schemaInfo[key] &&
  96. this.isJsonCompatible(flatSchema.indexSignature.type, type, protoHelper);
  97. }
  98. break;
  99. case SchemaType.IndexedAccess:
  100. case SchemaType.Reference: {
  101. var parsed = protoHelper.parseReference(schema);
  102. schemaInfo[key] = this.isJsonCompatible(parsed, type, protoHelper);
  103. break;
  104. }
  105. case SchemaType.Union:
  106. case SchemaType.Intersection:
  107. schemaInfo[key] = schema.members.every(function (v) {
  108. return _this.isJsonCompatible(v.type, type, protoHelper);
  109. });
  110. break;
  111. case SchemaType.NonNullable:
  112. schemaInfo[key] = this.isJsonCompatible(schema.target, type, protoHelper);
  113. break;
  114. case SchemaType.Pick:
  115. case SchemaType.Partial:
  116. case SchemaType.Omit:
  117. case SchemaType.Overwrite: {
  118. var parsed = protoHelper.parseMappedType(schema);
  119. if (parsed.type === SchemaType.Interface) {
  120. var flatSchema_1 = protoHelper.getFlatInterfaceSchema(schema);
  121. schemaInfo[key] = flatSchema_1.properties.every(function (v) {
  122. return _this.isJsonCompatible(v.type, type, protoHelper);
  123. });
  124. if (flatSchema_1.indexSignature) {
  125. schemaInfo[key] =
  126. schemaInfo[key] &&
  127. this.isJsonCompatible(flatSchema_1.indexSignature.type, type, protoHelper);
  128. }
  129. }
  130. else if (parsed.type === SchemaType.Union || parsed.type === SchemaType.Intersection) {
  131. schemaInfo[key] = parsed.members.every(function (v) {
  132. return _this.isJsonCompatible(v.type, type, protoHelper);
  133. });
  134. }
  135. break;
  136. }
  137. case SchemaType.Custom:
  138. case SchemaType.Date:
  139. case SchemaType.Buffer:
  140. schemaInfo[key] = false;
  141. break;
  142. default:
  143. schemaInfo[key] = true;
  144. break;
  145. }
  146. }
  147. return schemaInfo[key];
  148. };
  149. return CoderUtil;
  150. }());
  151. /** @internal */
  152. var IdBlockUtil = /** @class */ (function () {
  153. function IdBlockUtil() {
  154. }
  155. IdBlockUtil.getPayloadLengthInfo = function (parsedSchema, protoHelper) {
  156. switch (parsedSchema.type) {
  157. case SchemaType.Boolean:
  158. case SchemaType.Enum:
  159. return { lengthType: LengthType.Varint };
  160. case SchemaType.Number:
  161. if (!parsedSchema.scalarType ||
  162. parsedSchema.scalarType.includes("64") ||
  163. parsedSchema.scalarType === "double") {
  164. return { lengthType: LengthType.Bit64 };
  165. }
  166. else if (parsedSchema.scalarType && parsedSchema.scalarType.startsWith("big")) {
  167. return { lengthType: LengthType.LengthDelimited };
  168. }
  169. else {
  170. return { lengthType: LengthType.Varint };
  171. }
  172. case SchemaType.Buffer:
  173. case SchemaType.String:
  174. case SchemaType.Any:
  175. case SchemaType.Object:
  176. return { lengthType: LengthType.LengthDelimited };
  177. case SchemaType.Interface:
  178. case SchemaType.Pick:
  179. case SchemaType.Partial:
  180. case SchemaType.Omit:
  181. case SchemaType.Union:
  182. case SchemaType.Intersection:
  183. return { lengthType: LengthType.IdBlock };
  184. case SchemaType.Array:
  185. case SchemaType.Overwrite:
  186. case SchemaType.Tuple:
  187. return {
  188. lengthType: LengthType.LengthDelimited,
  189. needLengthPrefix: true,
  190. };
  191. case SchemaType.Literal:
  192. return {
  193. lengthType: LengthType.LengthDelimited,
  194. needLengthPrefix: false,
  195. };
  196. case SchemaType.Date:
  197. return { lengthType: LengthType.Varint };
  198. case SchemaType.NonNullable:
  199. return this.getPayloadLengthInfo(protoHelper.parseReference(parsedSchema.target), protoHelper);
  200. case SchemaType.Custom:
  201. return { lengthType: LengthType.LengthDelimited };
  202. default:
  203. // @ts-expect-error
  204. throw new Error("Unrecognized schema type: ".concat(parsedSchema.type));
  205. }
  206. };
  207. return IdBlockUtil;
  208. }());
  209. /** @internal */
  210. var LengthType;
  211. (function (LengthType) {
  212. LengthType[LengthType["LengthDelimited"] = 0] = "LengthDelimited";
  213. LengthType[LengthType["Varint"] = 1] = "Varint";
  214. LengthType[LengthType["Bit64"] = 2] = "Bit64";
  215. LengthType[LengthType["IdBlock"] = 3] = "IdBlock";
  216. })(LengthType || (LengthType = {}));
  217. /** @internal */
  218. var SchemaUtil = /** @class */ (function () {
  219. function SchemaUtil() {
  220. }
  221. /** type类型是否能编码为该literal */
  222. SchemaUtil.canBeLiteral = function (schema, literal) {
  223. var _this = this;
  224. if (schema.type === SchemaType.Union) {
  225. return schema.members.some(function (v) { return _this.canBeLiteral(v.type, literal); });
  226. }
  227. if (schema.type === SchemaType.Any) {
  228. return true;
  229. }
  230. if (schema.type === SchemaType.Literal && schema.literal === literal) {
  231. return true;
  232. }
  233. return false;
  234. };
  235. return SchemaUtil;
  236. }());
  237. var TypedArrays = {
  238. Int8Array: Int8Array,
  239. Int16Array: Int16Array,
  240. Int32Array: Int32Array,
  241. Uint8Array: Uint8Array,
  242. Uint16Array: Uint16Array,
  243. Uint32Array: Uint32Array,
  244. Float32Array: Float32Array,
  245. Float64Array: Float64Array,
  246. };
  247. /**!
  248. * From [protobuf.js](https://github.com/protobufjs/protobuf.js/blob/master/lib/utf8/index.js)
  249. */
  250. var Utf8CoderJS = {
  251. measureLength: function (str) {
  252. var len = 0, c = 0;
  253. for (var i = 0; i < str.length; ++i) {
  254. c = str.charCodeAt(i);
  255. if (c < 128)
  256. len += 1;
  257. else if (c < 2048)
  258. len += 2;
  259. else if ((c & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
  260. ++i;
  261. len += 4;
  262. }
  263. else
  264. len += 3;
  265. }
  266. return len;
  267. },
  268. write: function (str, buf, pos) {
  269. var start = pos, c1, // character 1
  270. c2; // character 2
  271. for (var i = 0; i < str.length; ++i) {
  272. c1 = str.charCodeAt(i);
  273. if (c1 < 128) {
  274. buf[pos++] = c1;
  275. }
  276. else if (c1 < 2048) {
  277. buf[pos++] = (c1 >> 6) | 192;
  278. buf[pos++] = (c1 & 63) | 128;
  279. }
  280. else if ((c1 & 0xfc00) === 0xd800 && ((c2 = str.charCodeAt(i + 1)) & 0xfc00) === 0xdc00) {
  281. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  282. ++i;
  283. buf[pos++] = (c1 >> 18) | 240;
  284. buf[pos++] = ((c1 >> 12) & 63) | 128;
  285. buf[pos++] = ((c1 >> 6) & 63) | 128;
  286. buf[pos++] = (c1 & 63) | 128;
  287. }
  288. else {
  289. buf[pos++] = (c1 >> 12) | 224;
  290. buf[pos++] = ((c1 >> 6) & 63) | 128;
  291. buf[pos++] = (c1 & 63) | 128;
  292. }
  293. }
  294. return pos - start;
  295. },
  296. read: function (buf, pos, length) {
  297. if (length < 1) {
  298. return "";
  299. }
  300. var str = "";
  301. for (var i = pos, end = pos + length; i < end;) {
  302. var t = buf[i++];
  303. if (t <= 0x7f) {
  304. str += String.fromCharCode(t);
  305. }
  306. else if (t >= 0xc0 && t < 0xe0) {
  307. str += String.fromCharCode(((t & 0x1f) << 6) | (buf[i++] & 0x3f));
  308. }
  309. else if (t >= 0xe0 && t < 0xf0) {
  310. str += String.fromCharCode(((t & 0xf) << 12) | ((buf[i++] & 0x3f) << 6) | (buf[i++] & 0x3f));
  311. }
  312. else if (t >= 0xf0) {
  313. var t2 = (((t & 7) << 18) |
  314. ((buf[i++] & 0x3f) << 12) |
  315. ((buf[i++] & 0x3f) << 6) |
  316. (buf[i++] & 0x3f)) -
  317. 0x10000;
  318. str += String.fromCharCode(0xd800 + (t2 >> 10));
  319. str += String.fromCharCode(0xdc00 + (t2 & 0x3ff));
  320. }
  321. }
  322. return str;
  323. },
  324. };
  325. var Utf8CoderNode = {
  326. measureLength: function (str) { return Buffer.byteLength(str, "utf-8"); },
  327. write: function (str, buf, pos) {
  328. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).write(str, pos, "utf-8");
  329. },
  330. read: function (buf, pos, length) {
  331. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString("utf-8", pos, pos + length);
  332. },
  333. };
  334. /**
  335. * 自动判断环境,选择使用NodeJS Native方法编码或是JS编码
  336. */
  337. var Utf8Coder = typeof Buffer !== "undefined" && Buffer.from && Buffer.prototype.write
  338. ? Utf8CoderNode
  339. : Utf8CoderJS;
  340. /** @internal */
  341. var Varint64 = /** @class */ (function () {
  342. function Varint64(high, low, byteLength) {
  343. this.uint32s = new Uint32Array([high, low]);
  344. if (byteLength !== undefined) {
  345. this._byteLength = byteLength;
  346. }
  347. }
  348. Varint64.from = function (value) {
  349. if (value === 0) {
  350. return this.Zero;
  351. }
  352. var sign = value < 0;
  353. if (sign) {
  354. value = -value;
  355. }
  356. var lo = value >>> 0, hi = ((value - lo) / 4294967296) >>> 0;
  357. if (sign) {
  358. hi = ~hi >>> 0;
  359. lo = ~lo >>> 0;
  360. if (++lo > 4294967295) {
  361. lo = 0;
  362. if (++hi > 4294967295)
  363. hi = 0;
  364. }
  365. }
  366. return new Varint64(hi, lo);
  367. };
  368. Varint64.prototype.toNumber = function (unsigned) {
  369. if (!unsigned && this.uint32s[0] >>> 31) {
  370. var low = (~this.uint32s[1] + 1) >>> 0, high = ~this.uint32s[0] >>> 0;
  371. if (!low)
  372. high = (high + 1) >>> 0;
  373. return -(low + high * 4294967296);
  374. }
  375. return this.uint32s[1] + this.uint32s[0] * 4294967296;
  376. };
  377. Varint64.prototype.zzEncode = function () {
  378. var mask = this.uint32s[0] >> 31;
  379. this.uint32s[0] = (((this.uint32s[0] << 1) | (this.uint32s[1] >>> 31)) ^ mask) >>> 0;
  380. this.uint32s[1] = ((this.uint32s[1] << 1) ^ mask) >>> 0;
  381. return this;
  382. };
  383. Varint64.prototype.zzDecode = function () {
  384. var mask = -(this.uint32s[1] & 1);
  385. this.uint32s[1] = (((this.uint32s[1] >>> 1) | (this.uint32s[0] << 31)) ^ mask) >>> 0;
  386. this.uint32s[0] = ((this.uint32s[0] >>> 1) ^ mask) >>> 0;
  387. return this;
  388. };
  389. Object.defineProperty(Varint64.prototype, "byteLength", {
  390. get: function () {
  391. if (this._byteLength === undefined) {
  392. var part0 = this.uint32s[1], part1 = ((this.uint32s[1] >>> 28) | (this.uint32s[0] << 4)) >>> 0, part2 = this.uint32s[0] >>> 24;
  393. this._byteLength =
  394. part2 === 0
  395. ? part1 === 0
  396. ? part0 < 16384
  397. ? part0 < 128
  398. ? 1
  399. : 2
  400. : part0 < 2097152
  401. ? 3
  402. : 4
  403. : part1 < 16384
  404. ? part1 < 128
  405. ? 5
  406. : 6
  407. : part1 < 2097152
  408. ? 7
  409. : 8
  410. : part2 < 128
  411. ? 9
  412. : 10;
  413. }
  414. return this._byteLength;
  415. },
  416. enumerable: false,
  417. configurable: true
  418. });
  419. /**
  420. * 编码
  421. * @param buf
  422. * @param pos
  423. * @returns 编码后最新的pos
  424. */
  425. Varint64.prototype.writeToBuffer = function (buf, pos) {
  426. while (this.uint32s[0]) {
  427. buf[pos++] = (this.uint32s[1] & 127) | 128;
  428. this.uint32s[1] = ((this.uint32s[1] >>> 7) | (this.uint32s[0] << 25)) >>> 0;
  429. this.uint32s[0] >>>= 7;
  430. }
  431. while (this.uint32s[1] > 127) {
  432. buf[pos++] = (this.uint32s[1] & 127) | 128;
  433. this.uint32s[1] = this.uint32s[1] >>> 7;
  434. }
  435. buf[pos++] = this.uint32s[1];
  436. return pos;
  437. };
  438. Varint64.readFromBuffer = function (buf, pos) {
  439. var startPos = pos;
  440. var hi = 0, lo = 0;
  441. var i = 0;
  442. if (buf.byteLength - pos > 4) {
  443. // fast route (lo)
  444. for (; i < 4; ++i) {
  445. // 1st..4th
  446. lo = (lo | ((buf[pos] & 127) << (i * 7))) >>> 0;
  447. if (buf[pos++] < 128)
  448. return new Varint64(hi, lo, pos - startPos);
  449. }
  450. // 5th
  451. lo = (lo | ((buf[pos] & 127) << 28)) >>> 0;
  452. hi = (hi | ((buf[pos] & 127) >> 4)) >>> 0;
  453. if (buf[pos++] < 128)
  454. return new Varint64(hi, lo, pos - startPos);
  455. i = 0;
  456. }
  457. else {
  458. for (; i < 3; ++i) {
  459. /* istanbul ignore if */
  460. if (pos >= buf.byteLength)
  461. throw new Error("Read varint error: index out of range");
  462. // 1st..3th
  463. lo = (lo | ((buf[pos] & 127) << (i * 7))) >>> 0;
  464. if (buf[pos++] < 128)
  465. return new Varint64(hi, lo, pos - startPos);
  466. }
  467. // 4th
  468. lo = (lo | ((buf[pos++] & 127) << (i * 7))) >>> 0;
  469. return new Varint64(hi, lo, pos - startPos);
  470. }
  471. if (buf.byteLength - pos > 4) {
  472. // fast route (hi)
  473. for (; i < 5; ++i) {
  474. // 6th..10th
  475. hi = (hi | ((buf[pos] & 127) << (i * 7 + 3))) >>> 0;
  476. if (buf[pos++] < 128)
  477. return new Varint64(hi, lo, pos - startPos);
  478. }
  479. }
  480. else {
  481. for (; i < 5; ++i) {
  482. /* istanbul ignore if */
  483. if (pos >= buf.byteLength)
  484. throw new Error("Read varint error: index out of range");
  485. // 6th..10th
  486. hi = (hi | ((buf[pos] & 127) << (i * 7 + 3))) >>> 0;
  487. if (buf[pos++] < 128)
  488. return new Varint64(hi, lo, pos - startPos);
  489. }
  490. }
  491. /* istanbul ignore next */
  492. throw Error("invalid varint encoding");
  493. };
  494. Varint64.Zero = new Varint64(0, 0);
  495. return Varint64;
  496. }());
  497. var BufferReader = /** @class */ (function () {
  498. function BufferReader() {
  499. this._pos = 0;
  500. }
  501. BufferReader.prototype.load = function (buf, pos) {
  502. if (pos === void 0) { pos = 0; }
  503. this._buf = buf;
  504. this._pos = pos;
  505. this._view = new DataView(buf.buffer);
  506. };
  507. BufferReader.prototype.readVarint = function () {
  508. var varint = Varint64.readFromBuffer(this._buf, this._pos);
  509. this._pos += varint.byteLength;
  510. return varint;
  511. };
  512. BufferReader.prototype.readUint = function () {
  513. return this.readVarint().toNumber(true);
  514. };
  515. BufferReader.prototype.readInt = function () {
  516. return this.readVarint().zzDecode().toNumber();
  517. };
  518. BufferReader.prototype.readDouble = function () {
  519. var pos = this._pos;
  520. this._pos += 8;
  521. return this._view.getFloat64(this._buf.byteOffset + pos);
  522. };
  523. BufferReader.prototype.readString = function () {
  524. var strByteLength = this.readUint();
  525. var str = Utf8Coder.read(this._buf, this._pos, strByteLength);
  526. this._pos += strByteLength;
  527. return str;
  528. };
  529. BufferReader.prototype.readBuffer = function () {
  530. var bufByteLength = this.readUint();
  531. var buf = this._buf.subarray(this._pos, this._pos + bufByteLength);
  532. this._pos += bufByteLength;
  533. return buf;
  534. };
  535. BufferReader.prototype.skip = function (byteLength) {
  536. this._pos += byteLength;
  537. };
  538. BufferReader.prototype.skipByLengthType = function (lengthType) {
  539. if (lengthType === LengthType.Bit64) {
  540. this._pos += 8;
  541. }
  542. else if (lengthType === LengthType.Varint) {
  543. this.readVarint();
  544. }
  545. else if (lengthType === LengthType.LengthDelimited) {
  546. var bufByteLength = this.readUint();
  547. this._pos += bufByteLength;
  548. }
  549. else if (lengthType === LengthType.IdBlock) {
  550. this.skipIdBlock();
  551. }
  552. else {
  553. throw new Error("Unknown lengthType: " + lengthType);
  554. }
  555. };
  556. BufferReader.prototype.skipIdBlock = function () {
  557. var idNum = this.readUint();
  558. for (var i = 0; i < idNum; ++i) {
  559. var id = this.readUint();
  560. var lengthType = id & 3;
  561. this.skipByLengthType(lengthType);
  562. }
  563. };
  564. BufferReader.prototype.readBoolean = function () {
  565. var value = this._view.getUint8(this._buf.byteOffset + this._pos++);
  566. if (value === 255) {
  567. return true;
  568. }
  569. else if (value === 0) {
  570. return false;
  571. }
  572. else {
  573. throw new Error("Invalid boolean encoding [".concat(value, "] at pos ").concat(this._pos - 1));
  574. }
  575. };
  576. Object.defineProperty(BufferReader.prototype, "unreadByteLength", {
  577. get: function () {
  578. return this._buf.byteLength - this._pos;
  579. },
  580. enumerable: false,
  581. configurable: true
  582. });
  583. BufferReader.prototype.dispose = function () {
  584. this._buf = this._view = undefined;
  585. };
  586. return BufferReader;
  587. }());
  588. /** @internal */
  589. var Decoder = /** @class */ (function () {
  590. function Decoder(options) {
  591. this._options = options;
  592. this._reader = new BufferReader();
  593. this._validator = options.validator;
  594. }
  595. Decoder.prototype.decode = function (buffer, schema) {
  596. this._reader.load(buffer);
  597. return this._read(schema);
  598. };
  599. Decoder.prototype.decodeJSON = function (json, schema) {
  600. var _this = this;
  601. if (json === null ||
  602. CoderUtil.isJsonCompatible(schema, "decode", this._validator.protoHelper)) {
  603. return json;
  604. }
  605. // 递归 只处理 ArrayBuffer、Date、ObjectId
  606. switch (schema.type) {
  607. case SchemaType.Array:
  608. if (!Array.isArray(json)) {
  609. break;
  610. }
  611. return json.map(function (v) { return _this.decodeJSON(v, schema.elementType); });
  612. case SchemaType.Tuple:
  613. if (!Array.isArray(json)) {
  614. break;
  615. }
  616. return json.map(function (v, i) { return _this.decodeJSON(v, schema.elementTypes[i]); });
  617. case SchemaType.Interface:
  618. if (json.constructor !== Object) {
  619. break;
  620. }
  621. json = Object.assign({}, json);
  622. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  623. var _loop_1 = function (key) {
  624. var property = flatSchema.properties.find(function (v) { return v.name === key; });
  625. if (property) {
  626. json[key] = this_1.decodeJSON(json[key], property.type);
  627. }
  628. else if (flatSchema.indexSignature) {
  629. json[key] = this_1.decodeJSON(json[key], flatSchema.indexSignature.type);
  630. }
  631. };
  632. var this_1 = this;
  633. for (var key in json) {
  634. _loop_1(key);
  635. }
  636. return json;
  637. case SchemaType.Date:
  638. if (typeof json !== "string" && typeof json !== "number") {
  639. break;
  640. }
  641. return new Date(json);
  642. case SchemaType.Partial:
  643. case SchemaType.Pick:
  644. case SchemaType.Omit:
  645. case SchemaType.Overwrite:
  646. var parsed = this._validator.protoHelper.parseMappedType(schema);
  647. if (parsed.type === SchemaType.Interface) {
  648. if (json.constructor !== Object) {
  649. break;
  650. }
  651. json = Object.assign({}, json);
  652. var flatSchema_1 = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  653. var _loop_2 = function (key) {
  654. var property = flatSchema_1.properties.find(function (v) { return v.name === key; });
  655. if (property) {
  656. json[key] = this_2.decodeJSON(json[key], property.type);
  657. }
  658. else if (flatSchema_1.indexSignature) {
  659. json[key] = this_2.decodeJSON(json[key], flatSchema_1.indexSignature.type);
  660. }
  661. };
  662. var this_2 = this;
  663. for (var key in json) {
  664. _loop_2(key);
  665. }
  666. return json;
  667. }
  668. else if (parsed.type === SchemaType.Union || parsed.type === SchemaType.Intersection) {
  669. for (var _i = 0, _a = parsed.members; _i < _a.length; _i++) {
  670. var member = _a[_i];
  671. json = this.decodeJSON(json, member.type);
  672. }
  673. return json;
  674. }
  675. break;
  676. case SchemaType.Buffer:
  677. if (typeof json !== "string") {
  678. break;
  679. }
  680. var uint8Arr = Base64Util.base64ToBuffer(json);
  681. return this._getBufferValue(uint8Arr, schema);
  682. case SchemaType.IndexedAccess:
  683. case SchemaType.Reference:
  684. case SchemaType.Keyof:
  685. return this.decodeJSON(json, this._validator.protoHelper.parseReference(schema));
  686. case SchemaType.Union:
  687. case SchemaType.Intersection: {
  688. // 逐个编码 然后合并 (失败的会原值返回,所以不影响结果)
  689. for (var _b = 0, _c = schema.members; _b < _c.length; _b++) {
  690. var member = _c[_b];
  691. json = this.decodeJSON(json, member.type);
  692. }
  693. return json;
  694. }
  695. case SchemaType.NonNullable:
  696. return this.decodeJSON(json, schema.target);
  697. case SchemaType.Custom:
  698. if (schema.decodeJSON) {
  699. return schema.decodeJSON(json);
  700. }
  701. break;
  702. default:
  703. schema.type;
  704. }
  705. return json;
  706. };
  707. Decoder.prototype._read = function (schema) {
  708. switch (schema.type) {
  709. case SchemaType.Boolean:
  710. return this._reader.readBoolean();
  711. case SchemaType.Number:
  712. return this._readNumber(schema);
  713. case SchemaType.String:
  714. return this._reader.readString();
  715. case SchemaType.Array: {
  716. var output = [];
  717. // 数组长度:Varint
  718. var length_1 = this._reader.readUint();
  719. for (var i = 0; i < length_1; ++i) {
  720. var item = this._read(schema.elementType);
  721. output.push(item);
  722. }
  723. return output;
  724. }
  725. case SchemaType.Tuple: {
  726. if (schema.elementTypes.length > 64) {
  727. throw new Error("Elements oversized, maximum supported tuple elements is 64, now get " +
  728. schema.elementTypes.length);
  729. }
  730. var output = [];
  731. // PayloadMask: Varint64
  732. var payloadMask = this._reader.readVarint();
  733. // 计算maskIndices
  734. var maskIndices = [];
  735. // Low
  736. for (var i = 0; i < 32; ++i) {
  737. if (payloadMask.uint32s[1] & (1 << i)) {
  738. maskIndices.push(i);
  739. }
  740. }
  741. // High
  742. for (var i = 0; i < 32; ++i) {
  743. if (payloadMask.uint32s[0] & (1 << i)) {
  744. maskIndices.push(i + 32);
  745. }
  746. }
  747. if (!maskIndices.length) {
  748. return [];
  749. }
  750. var maxIndex = maskIndices.last();
  751. for (var i = 0, nextMaskIndex = 0, next = maskIndices[0]; i <= maxIndex; ++i) {
  752. if (i === next) {
  753. output[i] = this._read(schema.elementTypes[i]);
  754. ++nextMaskIndex;
  755. next = maskIndices[nextMaskIndex];
  756. }
  757. else {
  758. output[i] = undefined;
  759. }
  760. }
  761. // undefined as null
  762. for (var i = 0; i < schema.elementTypes.length; ++i) {
  763. if (this._undefinedAsNull(output[i], schema.elementTypes[i], schema.optionalStartIndex !== undefined && i >= schema.optionalStartIndex)) {
  764. output[i] = null;
  765. }
  766. }
  767. return output;
  768. }
  769. case SchemaType.Enum:
  770. var enumId_1 = this._reader.readVarint().toNumber();
  771. var enumItem = schema.members.find(function (v) { return v.id === enumId_1; });
  772. if (!enumItem) {
  773. throw new Error("Invalid enum encoding: unexpected id ".concat(enumId_1));
  774. }
  775. return enumItem.value;
  776. case SchemaType.Any:
  777. case SchemaType.Object:
  778. var jsonStr = this._reader.readString();
  779. if (jsonStr === "undefined") {
  780. return undefined;
  781. }
  782. return JSON.parse(jsonStr);
  783. case SchemaType.Literal:
  784. return schema.literal;
  785. case SchemaType.Interface:
  786. return this._readInterface(schema);
  787. case SchemaType.Buffer:
  788. var uint8Arr = this._reader.readBuffer();
  789. return this._getBufferValue(uint8Arr, schema);
  790. case SchemaType.IndexedAccess:
  791. case SchemaType.Reference:
  792. case SchemaType.Keyof:
  793. return this._read(this._validator.protoHelper.parseReference(schema));
  794. case SchemaType.Partial:
  795. case SchemaType.Pick:
  796. case SchemaType.Omit:
  797. case SchemaType.Overwrite:
  798. var parsed = this._validator.protoHelper.parseMappedType(schema);
  799. if (parsed.type === SchemaType.Interface) {
  800. return this._readPureMappedType(schema);
  801. }
  802. else {
  803. return this._readUnionOrIntersection(parsed);
  804. }
  805. case SchemaType.Union:
  806. case SchemaType.Intersection:
  807. return this._readUnionOrIntersection(schema);
  808. case SchemaType.Date:
  809. return new Date(this._reader.readUint());
  810. case SchemaType.NonNullable:
  811. return this._read(schema.target);
  812. case SchemaType.Custom:
  813. if (!schema.decode) {
  814. throw new Error("Missing decode method for CustomTypeSchema");
  815. }
  816. var buf = this._reader.readBuffer();
  817. return schema.decode(buf);
  818. default:
  819. // @ts-expect-error
  820. throw new Error("Unrecognized schema type: ".concat(schema.type));
  821. }
  822. };
  823. /**
  824. * PureMappedType 每一层的target 都是MappedType或Interface(最终层)
  825. */
  826. Decoder.prototype._readPureMappedType = function (schema) {
  827. var output;
  828. var overwrite;
  829. if (schema.type === "Overwrite") {
  830. // Overwrite Block
  831. overwrite = this._read(schema.overwrite);
  832. }
  833. var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
  834. if (parsedTarget.type === "Interface") {
  835. output = this._readInterface(parsedTarget);
  836. }
  837. else if (parsedTarget.type === "Pick" ||
  838. parsedTarget.type === "Omit" ||
  839. parsedTarget.type === "Partial" ||
  840. parsedTarget.type === "Overwrite") {
  841. output = this._readPureMappedType(parsedTarget);
  842. }
  843. else {
  844. throw new Error("Invalid PureMappedType child: " + schema.type);
  845. }
  846. // filter key
  847. if (schema.type === "Pick") {
  848. // 把Pick以外的剔除
  849. for (var key in output) {
  850. if (schema.keys.indexOf(key) === -1) {
  851. delete output[key];
  852. }
  853. }
  854. }
  855. else if (schema.type === "Omit") {
  856. // 剔除Omit
  857. for (var key in output) {
  858. if (schema.keys.indexOf(key) > -1) {
  859. delete output[key];
  860. }
  861. }
  862. }
  863. else if (schema.type === "Overwrite") {
  864. Object.assign(output, overwrite);
  865. }
  866. // Partial 原样返回
  867. return output;
  868. };
  869. Decoder.prototype._readNumber = function (schema) {
  870. // 默认为double
  871. var scalarType = schema.scalarType || "double";
  872. switch (scalarType) {
  873. // 定长编码
  874. case "double":
  875. return this._reader.readDouble();
  876. // Varint编码
  877. case "int":
  878. return this._reader.readInt();
  879. case "uint":
  880. return this._reader.readUint();
  881. default:
  882. throw new Error("Scalar type not support : " + scalarType);
  883. }
  884. };
  885. Decoder.prototype._readInterface = function (schema) {
  886. var output = {};
  887. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  888. // BlockID数量
  889. var blockIdNum = this._reader.readUint();
  890. var _loop_3 = function (i) {
  891. // ReadBlock
  892. var readBlockId = this_3._reader.readUint();
  893. var lengthType = readBlockId & 3;
  894. var blockId = readBlockId >> 2;
  895. // indexSignature
  896. if (blockId === 0) {
  897. if (flatSchema.indexSignature) {
  898. var type = flatSchema.indexSignature.type;
  899. var fieldName = this_3._reader.readString();
  900. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(type));
  901. output[fieldName] = this_3._read(type);
  902. }
  903. // indexSignature未定义,可能是新协议,此处兼容,根据lengthType跳过
  904. else {
  905. // skip fieldName
  906. this_3._reader.skipByLengthType(LengthType.LengthDelimited);
  907. // skipPayload
  908. this_3._reader.skipByLengthType(lengthType);
  909. }
  910. }
  911. // extend block
  912. else if (blockId <= 9) {
  913. var extendId_1 = blockId - 1;
  914. var extend = schema.extends && schema.extends.find(function (v) { return v.id === extendId_1; });
  915. if (extend) {
  916. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(extend.type));
  917. var extendValue = this_3._read(extend.type);
  918. Object.assign(output, extendValue);
  919. }
  920. // 未知的extendId 可能是新协议 跳过
  921. else {
  922. // skipPayload
  923. this_3._reader.skipByLengthType(lengthType);
  924. }
  925. }
  926. // property
  927. else {
  928. var propertyId_1 = blockId - 10;
  929. var property = schema.properties && schema.properties.find(function (v) { return v.id === propertyId_1; });
  930. if (property) {
  931. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(property.type));
  932. output[property.name] = this_3._read(property.type);
  933. }
  934. // 未知的PropertyID 可能是新协议 跳过
  935. else {
  936. // skipPayload
  937. this_3._reader.skipByLengthType(lengthType);
  938. }
  939. }
  940. };
  941. var this_3 = this;
  942. for (var i = 0; i < blockIdNum; ++i) {
  943. _loop_3();
  944. }
  945. // Literal property 由于不编码 将其补回
  946. // undefined as null
  947. for (var _i = 0, _a = flatSchema.properties; _i < _a.length; _i++) {
  948. var property = _a[_i];
  949. if (output.hasOwnProperty(property.name)) {
  950. continue;
  951. }
  952. // Literal
  953. var parsedType = this._validator.protoHelper.parseReference(property.type);
  954. if (parsedType.type === "Literal") {
  955. output[property.name] = parsedType.literal;
  956. continue;
  957. }
  958. // undefined as null
  959. if (this._undefinedAsNull(output[property.name], parsedType, property.optional)) {
  960. output[property.name] = null;
  961. continue;
  962. }
  963. }
  964. return output;
  965. };
  966. /** @internal 是否该null值小于当做undefined编码 */
  967. Decoder.prototype._undefinedAsNull = function (value, type, isOptional) {
  968. return (value === undefined &&
  969. this._options.undefinedAsNull &&
  970. !SchemaUtil.canBeLiteral(type, undefined) &&
  971. !isOptional &&
  972. SchemaUtil.canBeLiteral(type, null));
  973. };
  974. Decoder.prototype._skipIdLengthPrefix = function (parsedSchema) {
  975. var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
  976. if (lengthInfo.needLengthPrefix) {
  977. // skip length prefix
  978. this._reader.skipByLengthType(LengthType.Varint);
  979. }
  980. };
  981. Decoder.prototype._readUnionOrIntersection = function (schema) {
  982. var output;
  983. var idNum = this._reader.readUint();
  984. var _loop_4 = function (i) {
  985. var readId = this_4._reader.readUint();
  986. var lengthType = readId & 3;
  987. var id = readId >> 2;
  988. var member = schema.members.find(function (v) { return v.id === id; });
  989. // 不可识别的Member,可能是新协议,跳过使兼容
  990. if (!member) {
  991. this_4._reader.skipByLengthType(lengthType);
  992. return "continue";
  993. }
  994. this_4._skipIdLengthPrefix(this_4._validator.protoHelper.parseReference(member.type));
  995. var value = this_4._read(member.type);
  996. if (this_4._isObject(output) && this_4._isObject(value)) {
  997. Object.assign(output, value);
  998. }
  999. else {
  1000. output = value;
  1001. }
  1002. };
  1003. var this_4 = this;
  1004. for (var i = 0; i < idNum; ++i) {
  1005. _loop_4();
  1006. }
  1007. if (this._undefinedAsNull(output, schema)) {
  1008. output = null;
  1009. }
  1010. return output;
  1011. };
  1012. Decoder.prototype._isObject = function (value) {
  1013. return typeof value === "object" && value !== null;
  1014. };
  1015. Decoder.prototype._getBufferValue = function (uint8Arr, schema) {
  1016. if (schema.arrayType) {
  1017. if (schema.arrayType === "BigInt64Array" || schema.arrayType === "BigUint64Array") {
  1018. throw new Error("Unsupported arrayType: " + schema.arrayType);
  1019. }
  1020. // Uint8Array 性能最高
  1021. else if (schema.arrayType === "Uint8Array") {
  1022. return uint8Arr;
  1023. }
  1024. // 其余TypedArray 可能需要内存拷贝 性能次之
  1025. else {
  1026. var typedArr = TypedArrays[schema.arrayType];
  1027. // 字节对齐,可以直接转,无需拷贝内存
  1028. if (uint8Arr.byteOffset % typedArr.BYTES_PER_ELEMENT === 0) {
  1029. return new typedArr(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.byteLength / typedArr.BYTES_PER_ELEMENT);
  1030. }
  1031. // 字节不对齐,不能直接转,只能拷贝内存后再生成
  1032. else {
  1033. var arrBuf = uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
  1034. return new typedArr(arrBuf);
  1035. }
  1036. }
  1037. }
  1038. else {
  1039. return uint8Arr.byteLength === uint8Arr.buffer.byteLength && uint8Arr.byteOffset === 0
  1040. ? uint8Arr.buffer
  1041. : uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
  1042. }
  1043. };
  1044. return Decoder;
  1045. }());
  1046. /** @internal */
  1047. var Config = {
  1048. interface: {
  1049. maxExtendsNum: 9,
  1050. },
  1051. };
  1052. /**
  1053. * 用Op来串联 next
  1054. * Op包含 function next length
  1055. * 先度量长度再执行编码
  1056. * 一次性编码
  1057. * 使用BufferPool
  1058. * writer.uint32(xx).string(xxx).finish();
  1059. * @internal
  1060. */
  1061. var BufferWriter = /** @class */ (function () {
  1062. function BufferWriter() {
  1063. this._ops = [];
  1064. }
  1065. Object.defineProperty(BufferWriter.prototype, "ops", {
  1066. get: function () {
  1067. return this._ops;
  1068. },
  1069. enumerable: false,
  1070. configurable: true
  1071. });
  1072. BufferWriter.prototype.clear = function () {
  1073. this._ops = [];
  1074. };
  1075. BufferWriter.prototype.push = function (req) {
  1076. this._ops.push(this.req2op(req));
  1077. return this;
  1078. };
  1079. BufferWriter.prototype.req2op = function (req) {
  1080. if (req.type === "string" || req.type === "buffer") {
  1081. var valueLength = this.measureLength(req);
  1082. // Length
  1083. this.push({ type: "varint", value: Varint64.from(valueLength) });
  1084. // Value
  1085. return __assign(__assign({}, req), { length: valueLength });
  1086. }
  1087. else {
  1088. var length_1 = this.measureLength(req);
  1089. return __assign(__assign({}, req), { length: length_1 });
  1090. }
  1091. };
  1092. BufferWriter.prototype.measureLength = function (req) {
  1093. switch (req.type) {
  1094. case "varint":
  1095. return req.value.byteLength;
  1096. case "string":
  1097. return Utf8Coder.measureLength(req.value);
  1098. case "buffer":
  1099. return req.value.byteLength;
  1100. case "double":
  1101. return 8;
  1102. case "boolean":
  1103. return 1;
  1104. default:
  1105. return NaN;
  1106. }
  1107. };
  1108. BufferWriter.prototype.finish = function () {
  1109. var byteLength = this._ops.sum(function (v) { return v.length; });
  1110. var pos = 0;
  1111. var buf = new Uint8Array(byteLength);
  1112. var view = new DataView(buf.buffer);
  1113. for (var _i = 0, _a = this._ops; _i < _a.length; _i++) {
  1114. var op = _a[_i];
  1115. switch (op.type) {
  1116. case "varint":
  1117. var newPos = op.value.writeToBuffer(buf, pos);
  1118. if (newPos !== pos + op.length) {
  1119. throw new Error("Error varint measuredLength ".concat(op.length, ", actual is ").concat(newPos - pos, ", value is ").concat(op.value.toNumber()));
  1120. }
  1121. break;
  1122. case "double":
  1123. view.setFloat64(buf.byteOffset + pos, op.value);
  1124. break;
  1125. case "string":
  1126. var encLen = Utf8Coder.write(op.value, buf, pos);
  1127. if (encLen !== op.length) {
  1128. throw new Error("Expect ".concat(op.length, " bytes but encoded ").concat(encLen, " bytes"));
  1129. }
  1130. break;
  1131. case "buffer":
  1132. buf.subarray(pos, pos + op.length).set(op.value);
  1133. break;
  1134. case "boolean":
  1135. view.setUint8(buf.byteOffset + pos, op.value ? 255 : 0);
  1136. break;
  1137. }
  1138. pos += op.length;
  1139. }
  1140. return buf;
  1141. };
  1142. return BufferWriter;
  1143. }());
  1144. /** @internal */
  1145. var Encoder = /** @class */ (function () {
  1146. function Encoder(options) {
  1147. this._options = options;
  1148. this._writer = new BufferWriter();
  1149. this._validator = options.validator;
  1150. }
  1151. Encoder.prototype.encode = function (value, schema) {
  1152. this._writer.clear();
  1153. this._write(value, schema);
  1154. return this._writer.finish();
  1155. };
  1156. Encoder.prototype.encodeJSON = function (value, schema) {
  1157. var _this = this;
  1158. // JSON 能直接传输的类型,直接跳过
  1159. if (typeof value !== "object" ||
  1160. value === null ||
  1161. CoderUtil.isJsonCompatible(schema, "encode", this._validator.protoHelper)) {
  1162. return value;
  1163. }
  1164. switch (schema.type) {
  1165. case SchemaType.Array:
  1166. if (!Array.isArray(value)) {
  1167. break;
  1168. }
  1169. return value.map(function (v) { return _this.encodeJSON(v, schema.elementType); });
  1170. case SchemaType.Tuple: {
  1171. if (!Array.isArray(value)) {
  1172. break;
  1173. }
  1174. return value.map(function (v, i) { return _this.encodeJSON(v, schema.elementTypes[i]); });
  1175. }
  1176. case SchemaType.Interface: {
  1177. if (value.constructor !== Object) {
  1178. break;
  1179. }
  1180. value = Object.assign({}, value);
  1181. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  1182. var _loop_1 = function (key) {
  1183. var property = flatSchema.properties.find(function (v) { return v.name === key; });
  1184. if (property) {
  1185. value[key] = this_1.encodeJSON(value[key], property.type);
  1186. }
  1187. else if (flatSchema.indexSignature) {
  1188. value[key] = this_1.encodeJSON(value[key], flatSchema.indexSignature.type);
  1189. }
  1190. };
  1191. var this_1 = this;
  1192. for (var key in value) {
  1193. _loop_1(key);
  1194. }
  1195. return value;
  1196. }
  1197. case SchemaType.Partial:
  1198. case SchemaType.Pick:
  1199. case SchemaType.Omit:
  1200. case SchemaType.Overwrite:
  1201. var parsed = this._validator.protoHelper.parseMappedType(schema);
  1202. return this.encodeJSON(value, parsed);
  1203. case SchemaType.Buffer:
  1204. if (!(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {
  1205. break;
  1206. }
  1207. if (schema.arrayType) {
  1208. if (schema.arrayType === "Uint8Array") {
  1209. return Base64Util.bufferToBase64(value);
  1210. }
  1211. var view = value;
  1212. var buf = view.byteLength === view.buffer.byteLength && view.byteOffset === 0
  1213. ? view.buffer
  1214. : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
  1215. return Base64Util.bufferToBase64(new Uint8Array(buf));
  1216. }
  1217. else {
  1218. return Base64Util.bufferToBase64(new Uint8Array(value));
  1219. }
  1220. case SchemaType.IndexedAccess:
  1221. case SchemaType.Reference:
  1222. case SchemaType.Keyof:
  1223. return this.encodeJSON(value, this._validator.protoHelper.parseReference(schema));
  1224. case SchemaType.Union:
  1225. case SchemaType.Intersection: {
  1226. // 逐个编码 然后合并 (失败的会原值返回,所以不影响结果)
  1227. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1228. var member = _a[_i];
  1229. value = this.encodeJSON(value, member.type);
  1230. }
  1231. return value;
  1232. }
  1233. case SchemaType.NonNullable:
  1234. return this.encodeJSON(value, schema.target);
  1235. case SchemaType.Date:
  1236. if (!(value instanceof Date)) {
  1237. break;
  1238. }
  1239. return value.toJSON();
  1240. case SchemaType.Custom:
  1241. if (schema.encodeJSON) {
  1242. return schema.encodeJSON(value);
  1243. }
  1244. else if (typeof (value === null || value === void 0 ? void 0 : value.toJSON) === "function") {
  1245. return value.toJSON();
  1246. }
  1247. else if (typeof (value === null || value === void 0 ? void 0 : value.toString) === "function") {
  1248. return value.toString();
  1249. }
  1250. return value;
  1251. default:
  1252. schema.type;
  1253. }
  1254. return value;
  1255. };
  1256. Encoder.prototype._write = function (value, schema, options) {
  1257. switch (schema.type) {
  1258. case SchemaType.Boolean:
  1259. this._writer.push({ type: "boolean", value: value });
  1260. break;
  1261. case SchemaType.Number:
  1262. this._writeNumber(value, schema);
  1263. break;
  1264. case SchemaType.String:
  1265. this._writer.push({ type: "string", value: value });
  1266. break;
  1267. case SchemaType.Array: {
  1268. var _v = value;
  1269. // 数组长度:Varint
  1270. this._writer.push({ type: "varint", value: Varint64.from(_v.length) });
  1271. // Element Payload
  1272. for (var i = 0; i < _v.length; ++i) {
  1273. this._write(_v[i], schema.elementType);
  1274. }
  1275. break;
  1276. }
  1277. case SchemaType.Tuple: {
  1278. if (schema.elementTypes.length > 64) {
  1279. throw new Error("Elements oversized, maximum supported tuple elements is 64, now get " +
  1280. schema.elementTypes.length);
  1281. }
  1282. var _v = value;
  1283. // 计算maskPos(要编码的值的index)
  1284. var maskIndices = [];
  1285. for (var i = 0; i < _v.length; ++i) {
  1286. // undefined 不编码
  1287. // null as undefined
  1288. if (_v[i] === undefined || this._nullAsUndefined(_v[i], schema.elementTypes[i])) {
  1289. continue;
  1290. }
  1291. maskIndices.push(i);
  1292. }
  1293. // 生成PayloadMask:Varint64
  1294. var lo = 0;
  1295. var hi = 0;
  1296. for (var _i = 0, maskIndices_1 = maskIndices; _i < maskIndices_1.length; _i++) {
  1297. var v = maskIndices_1[_i];
  1298. if (v < 32) {
  1299. lo |= 1 << v;
  1300. }
  1301. else {
  1302. hi |= 1 << (v - 32);
  1303. }
  1304. }
  1305. this._writer.push({ type: "varint", value: new Varint64(hi, lo) });
  1306. // Element Payload
  1307. for (var _a = 0, maskIndices_2 = maskIndices; _a < maskIndices_2.length; _a++) {
  1308. var i = maskIndices_2[_a];
  1309. this._write(_v[i], schema.elementTypes[i]);
  1310. }
  1311. break;
  1312. }
  1313. case SchemaType.Enum:
  1314. var enumItem = schema.members.find(function (v) { return v.value === value; });
  1315. if (!enumItem) {
  1316. throw new Error("Unexpect enum value: ".concat(value));
  1317. }
  1318. this._writer.push({ type: "varint", value: Varint64.from(enumItem.id) });
  1319. break;
  1320. case SchemaType.Any:
  1321. if (value === undefined) {
  1322. this._writer.push({ type: "string", value: "undefined" });
  1323. }
  1324. else {
  1325. this._writer.push({ type: "string", value: JSON.stringify(value) });
  1326. }
  1327. break;
  1328. case SchemaType.Object:
  1329. this._writer.push({ type: "string", value: JSON.stringify(value) });
  1330. break;
  1331. case SchemaType.Literal:
  1332. break;
  1333. case SchemaType.Interface:
  1334. this._writeInterface(value, schema, options);
  1335. break;
  1336. case SchemaType.Buffer:
  1337. this._writeBuffer(value);
  1338. break;
  1339. case SchemaType.IndexedAccess:
  1340. case SchemaType.Reference:
  1341. case SchemaType.Keyof:
  1342. this._write(value, this._validator.protoHelper.parseReference(schema), options);
  1343. break;
  1344. case SchemaType.Partial:
  1345. case SchemaType.Pick:
  1346. case SchemaType.Omit:
  1347. case SchemaType.Overwrite:
  1348. var parsed = this._validator.protoHelper.parseMappedType(schema);
  1349. if (parsed.type === SchemaType.Interface) {
  1350. this._writePureMappedType(value, schema, options);
  1351. }
  1352. else if (parsed.type === SchemaType.Union) {
  1353. this._writeUnion(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
  1354. }
  1355. else if (parsed.type === SchemaType.Intersection) {
  1356. this._writeIntersection(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
  1357. }
  1358. break;
  1359. case SchemaType.Union:
  1360. this._writeUnion(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
  1361. break;
  1362. case SchemaType.Intersection:
  1363. this._writeIntersection(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
  1364. break;
  1365. case SchemaType.Date:
  1366. this._writer.push({ type: "varint", value: Varint64.from(value.getTime()) });
  1367. break;
  1368. case SchemaType.NonNullable:
  1369. this._write(value, schema.target, options);
  1370. break;
  1371. case SchemaType.Custom:
  1372. if (!schema.encode) {
  1373. throw new Error("Missing encode method for CustomTypeSchema");
  1374. }
  1375. var buf = schema.encode(value);
  1376. // 以 Buffer 形式写入
  1377. this._writeBuffer(buf);
  1378. break;
  1379. default:
  1380. // @ts-expect-error
  1381. throw new Error("Unrecognized schema type: ".concat(schema.type));
  1382. }
  1383. };
  1384. Encoder.prototype._writePureMappedType = function (value, schema, options) {
  1385. if (!options) {
  1386. options = {};
  1387. }
  1388. if (schema.type === "Pick") {
  1389. // 已存在 取交集
  1390. if (options.pickFields) {
  1391. var newPickFields = {};
  1392. for (var _i = 0, _a = schema.keys; _i < _a.length; _i++) {
  1393. var v = _a[_i];
  1394. if (options.pickFields[v]) {
  1395. newPickFields[v] = 1;
  1396. }
  1397. }
  1398. options.pickFields = newPickFields;
  1399. }
  1400. // 不存在 初始化
  1401. else {
  1402. options.pickFields = {};
  1403. for (var _b = 0, _c = schema.keys; _b < _c.length; _b++) {
  1404. var v = _c[_b];
  1405. options.pickFields[v] = 1;
  1406. }
  1407. }
  1408. }
  1409. else if (schema.type === "Omit") {
  1410. // 不存在 初始化
  1411. if (!(options === null || options === void 0 ? void 0 : options.skipFields)) {
  1412. if (!options) {
  1413. options = {};
  1414. }
  1415. options.skipFields = {};
  1416. }
  1417. // 取并集
  1418. for (var _d = 0, _e = schema.keys; _d < _e.length; _d++) {
  1419. var v = _e[_d];
  1420. options.skipFields[v] = 1;
  1421. }
  1422. }
  1423. else if (schema.type === "Overwrite") {
  1424. var parsed = this._parseOverwrite(value, schema);
  1425. // 写入Overwrite部分
  1426. this._write(parsed.overwriteValue, parsed.overwrite, options);
  1427. }
  1428. else if (schema.type === "Partial") ;
  1429. else {
  1430. // @ts-expect-error
  1431. throw new Error("Invalid PureMappedType child: " + schema.type);
  1432. }
  1433. // Write Interface
  1434. var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
  1435. if (parsedTarget.type === "Interface") {
  1436. this._writeInterface(value, parsedTarget, options);
  1437. }
  1438. else {
  1439. this._writePureMappedType(value, parsedTarget, options);
  1440. }
  1441. };
  1442. Encoder.prototype._writeNumber = function (value, schema) {
  1443. // 默认为double
  1444. var scalarType = schema.scalarType || "double";
  1445. switch (scalarType) {
  1446. // 定长编码
  1447. case "double":
  1448. this._writer.push({ type: scalarType, value: value });
  1449. break;
  1450. // Varint编码
  1451. case "int":
  1452. this._writer.push({ type: "varint", value: Varint64.from(value).zzEncode() });
  1453. break;
  1454. case "uint":
  1455. this._writer.push({ type: "varint", value: Varint64.from(value) });
  1456. break;
  1457. default:
  1458. throw new Error("Scalar type not support : " + scalarType);
  1459. }
  1460. };
  1461. Encoder.prototype._writeInterface = function (value, schema, options) {
  1462. // skipFields默认值
  1463. if (!options) {
  1464. options = {};
  1465. }
  1466. if (!options.skipFields) {
  1467. options.skipFields = {};
  1468. }
  1469. // 记录起始op位置,用于最后插入BlockID数量
  1470. var opStartOps = this._writer.ops.length;
  1471. var blockIdCount = 0;
  1472. // 以下,interface
  1473. // extends
  1474. if (schema.extends) {
  1475. // 支持的继承数量有上限
  1476. if (schema.extends.length > Config.interface.maxExtendsNum) {
  1477. throw new Error("Max support ".concat(Config.interface.maxExtendsNum, " extends, actual: ").concat(schema.extends.length));
  1478. }
  1479. for (var _i = 0, _a = schema.extends; _i < _a.length; _i++) {
  1480. var extend = _a[_i];
  1481. // BlockID = extend.id + 1
  1482. var blockId = extend.id + 1;
  1483. this._writer.push({ type: "varint", value: Varint64.from(blockId) });
  1484. var blockIdPos = this._writer.ops.length - 1;
  1485. // 写入extend interface前 writeOps的长度
  1486. var opsLengthBeforeWrite = this._writer.ops.length;
  1487. // extend Block
  1488. var parsedExtend = this._validator.protoHelper.parseReference(extend.type);
  1489. this._writeInterface(value, parsedExtend, __assign(__assign({}, options), {
  1490. // 确保indexSignature是在最小层级编码
  1491. skipIndexSignature: !!schema.indexSignature || options.skipIndexSignature }));
  1492. // 写入前后writeOps只增加了一个(block length),说明该extend并未写入任何property字段,取消编码这个block
  1493. if (this._writer.ops.length === opsLengthBeforeWrite + 1) {
  1494. // 移除BlockID
  1495. this._writer.ops.splice(this._writer.ops.length - 2, 2);
  1496. }
  1497. // extend写入成功 blockId数量+1
  1498. else {
  1499. ++blockIdCount;
  1500. this._processIdWithLengthType(blockIdPos, extend.type);
  1501. }
  1502. }
  1503. }
  1504. // property
  1505. if (schema.properties) {
  1506. for (var _b = 0, _c = schema.properties; _b < _c.length; _b++) {
  1507. var property = _c[_b];
  1508. var parsedType = this._validator.protoHelper.parseReference(property.type);
  1509. var propValue = value[property.name];
  1510. // PickFields
  1511. if (options.pickFields && !options.pickFields[property.name]) {
  1512. continue;
  1513. }
  1514. // Literal不编码 直接跳过
  1515. if (parsedType.type === "Literal") {
  1516. options.skipFields[property.name] = 1;
  1517. continue;
  1518. }
  1519. // null as undefined
  1520. if (this._nullAsUndefined(propValue, property.type)) {
  1521. propValue = undefined;
  1522. }
  1523. // undefined不编码
  1524. if (propValue === undefined) {
  1525. continue;
  1526. }
  1527. // SkipFields
  1528. if (options.skipFields[property.name]) {
  1529. continue;
  1530. }
  1531. options.skipFields[property.name] = 1;
  1532. var blockId = property.id + Config.interface.maxExtendsNum + 1;
  1533. // BlockID (propertyID)
  1534. this._writer.push({ type: "varint", value: Varint64.from(blockId) });
  1535. var blockIdPos = this._writer.ops.length - 1;
  1536. // Value Payload
  1537. this._write(propValue, parsedType);
  1538. ++blockIdCount;
  1539. this._processIdWithLengthType(blockIdPos, parsedType);
  1540. }
  1541. }
  1542. // indexSignature
  1543. if (!options.skipIndexSignature) {
  1544. var flat = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  1545. if (flat.indexSignature) {
  1546. for (var key in value) {
  1547. if (value[key] === undefined ||
  1548. this._nullAsUndefined(value[key], flat.indexSignature.type)) {
  1549. continue;
  1550. }
  1551. // PickFields
  1552. if (options.pickFields && !options.pickFields[key]) {
  1553. continue;
  1554. }
  1555. // SkipFields
  1556. if (options.skipFields[key]) {
  1557. continue;
  1558. }
  1559. options.skipFields[key] = 1;
  1560. // BlockID == 0
  1561. this._writer.push({ type: "varint", value: Varint64.from(0) });
  1562. var blockIdPos = this._writer.ops.length - 1;
  1563. // 字段名
  1564. this._writer.push({ type: "string", value: key });
  1565. var lengthPrefixPos = this._writer.ops.length;
  1566. // Value Payload
  1567. this._write(value[key], flat.indexSignature.type);
  1568. ++blockIdCount;
  1569. this._processIdWithLengthType(blockIdPos, flat.indexSignature.type, lengthPrefixPos);
  1570. }
  1571. }
  1572. }
  1573. this._writer.ops.splice(opStartOps, 0, this._writer.req2op({ type: "varint", value: Varint64.from(blockIdCount) }));
  1574. };
  1575. /** @internal 是否该null值小于当做undefined编码 */
  1576. Encoder.prototype._nullAsUndefined = function (value, type) {
  1577. return value === null && this._options.nullAsUndefined && !SchemaUtil.canBeLiteral(type, null);
  1578. // && SchemaUtil.canBeLiteral(type, undefined) 一定为true 因为先validate过了
  1579. };
  1580. Encoder.prototype._parseOverwrite = function (value, schema) {
  1581. var skipFields = {};
  1582. // 解引用
  1583. var target = this._validator.protoHelper.parseReference(schema.target);
  1584. var overwrite = this._validator.protoHelper.parseReference(schema.overwrite);
  1585. var flatTarget = this._validator.protoHelper.getFlatInterfaceSchema(target);
  1586. var flatOverwrite = this._validator.protoHelper.getFlatInterfaceSchema(overwrite);
  1587. // 先区分哪些字段进入Target块,哪些字段进入Overwrite块
  1588. var overwriteValue = {};
  1589. var targetValue = {};
  1590. // Overwrite块 property
  1591. if (flatOverwrite.properties) {
  1592. // 只要Overwrite中有此Property,即在Overwrite块编码
  1593. for (var _i = 0, _a = flatOverwrite.properties; _i < _a.length; _i++) {
  1594. var property = _a[_i];
  1595. // undefined不编码,跳过SkipFIelds
  1596. if (value[property.name] !== undefined && !skipFields[property.name]) {
  1597. overwriteValue[property.name] = value[property.name];
  1598. skipFields[property.name] = 1;
  1599. }
  1600. }
  1601. }
  1602. // Target块 property
  1603. if (flatTarget.properties) {
  1604. for (var _b = 0, _c = flatTarget.properties; _b < _c.length; _b++) {
  1605. var property = _c[_b];
  1606. // undefined不编码,跳过SkipFields
  1607. if (value[property.name] !== undefined && !skipFields[property.name]) {
  1608. targetValue[property.name] = value[property.name];
  1609. skipFields[property.name] = 1;
  1610. }
  1611. }
  1612. }
  1613. // indexSignature
  1614. var indexSignatureWriteValue; // indexSignature要写入的目标(overwrite或target)
  1615. var indexSignature;
  1616. // IndexSignature,优先使用Overwrite的
  1617. if (flatOverwrite.indexSignature) {
  1618. indexSignature = flatOverwrite.indexSignature;
  1619. indexSignatureWriteValue = overwriteValue;
  1620. }
  1621. else if (flatTarget.indexSignature) {
  1622. indexSignature = flatTarget.indexSignature;
  1623. indexSignatureWriteValue = targetValue;
  1624. }
  1625. if (indexSignature) {
  1626. for (var key in value) {
  1627. if (skipFields[key]) {
  1628. continue;
  1629. }
  1630. indexSignatureWriteValue[key] = value[key];
  1631. skipFields[key] = 1;
  1632. }
  1633. }
  1634. // 编码,此处不再需要SkipFields,因为已经筛选过
  1635. return {
  1636. target: target,
  1637. targetValue: targetValue,
  1638. overwrite: overwrite,
  1639. overwriteValue: overwriteValue,
  1640. };
  1641. };
  1642. Encoder.prototype._writeUnion = function (value, schema, skipFields, unionProperties) {
  1643. // 计算unionProperties
  1644. // if (!unionProperties) {
  1645. // unionProperties = skipFields ? Object.keys(skipFields) : [];
  1646. // }
  1647. // this._validator.protoHelper.getUnionProperties(schema).forEach(v => {
  1648. // unionProperties!.binaryInsert(v, true);
  1649. // })
  1650. if (skipFields === void 0) { skipFields = {}; }
  1651. // 记住编码起点
  1652. var encodeStartPos = this._writer.ops.length;
  1653. var idNum = 0;
  1654. // null as undefined
  1655. if (this._nullAsUndefined(value, schema)) {
  1656. value = undefined;
  1657. }
  1658. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1659. var member = _a[_i];
  1660. // 验证该member是否可以编码
  1661. var vRes = this._validator.validate(value, member.type, {
  1662. // 禁用excessPropertyChecks(以代替unionProperties)
  1663. excessPropertyChecks: false,
  1664. // 启用strictNullChecks(null as undefined已经前置处理)
  1665. // strictNullChecks: true
  1666. });
  1667. if (vRes.isSucc) {
  1668. // 编码
  1669. // Part2: ID
  1670. this._writer.push({ type: "varint", value: Varint64.from(member.id) });
  1671. var idPos = this._writer.ops.length - 1;
  1672. // Part3: Payload
  1673. if (member.type.type === "Union") {
  1674. this._writeUnion(value, member.type, skipFields);
  1675. }
  1676. else {
  1677. this._write(value, member.type, {
  1678. skipFields: skipFields,
  1679. });
  1680. }
  1681. idNum++;
  1682. this._processIdWithLengthType(idPos, member.type);
  1683. // 非object的value,类型一定互斥,只编码一个足矣
  1684. if (typeof value !== "object") {
  1685. break;
  1686. }
  1687. }
  1688. }
  1689. // 已经编码
  1690. if (idNum > 0) {
  1691. // 前置ID数量
  1692. this._writer.ops.splice(encodeStartPos, 0, this._writer.req2op({ type: "varint", value: Varint64.from(idNum) }));
  1693. return;
  1694. }
  1695. else {
  1696. // 未编码,没有任何条件满足,抛出异常
  1697. throw new Error("Non member is satisfied for union type");
  1698. }
  1699. };
  1700. Encoder.prototype._writeIntersection = function (value, schema, skipFields) {
  1701. if (skipFields === void 0) { skipFields = {}; }
  1702. // ID数量(member数量)
  1703. this._writer.push({ type: "varint", value: Varint64.from(schema.members.length) });
  1704. // 按Member依次编码
  1705. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1706. var member = _a[_i];
  1707. // ID
  1708. this._writer.push({ type: "varint", value: Varint64.from(member.id) });
  1709. var idPos = this._writer.ops.length - 1;
  1710. // 编码块 - 为每个 member 创建新的 skipFields
  1711. var memberSkipFields = __assign({}, skipFields);
  1712. this._write(value, member.type, {
  1713. skipFields: memberSkipFields,
  1714. });
  1715. this._processIdWithLengthType(idPos, member.type);
  1716. }
  1717. };
  1718. Encoder.prototype._writeBuffer = function (value) {
  1719. // ArrayBuffer 转为Uint8Array
  1720. if (value instanceof ArrayBuffer) {
  1721. this._writer.push({ type: "buffer", value: new Uint8Array(value) });
  1722. }
  1723. // Uint8Array 直接写入
  1724. else if (value instanceof Uint8Array) {
  1725. this._writer.push({ type: "buffer", value: value });
  1726. }
  1727. // 其它TypedArray 转为Uint8Array
  1728. else {
  1729. var key = value.constructor.name;
  1730. var arrType = TypedArrays[key];
  1731. var uint8Arr = new Uint8Array(value.buffer, value.byteOffset, value.length * arrType.BYTES_PER_ELEMENT);
  1732. this._writer.push({ type: "buffer", value: uint8Arr });
  1733. }
  1734. };
  1735. // private _writeIdBlocks(blocks: IDBlockItem[]) {
  1736. // // 字段数量: Varint
  1737. // this._writer.push({ type: 'varint', value: Varint64.from(blocks.length) });
  1738. // // 依次编码
  1739. // for (let item of blocks) {
  1740. // // ID
  1741. // this._writer.push({ type: 'varint', value: Varint64.from(item.id) });
  1742. // // Payload
  1743. // this._write(item.value, item.schema)
  1744. // }
  1745. // }
  1746. /**
  1747. * 重新处理ID位,使其加入末位长度信息2Bit
  1748. * @param idPos
  1749. */
  1750. Encoder.prototype._processIdWithLengthType = function (idPos, payloadType, lengthPrefixPos) {
  1751. var idOp = this._writer.ops[idPos];
  1752. if (idOp.type !== "varint") {
  1753. throw new Error("Error idPos: " + idPos);
  1754. }
  1755. // 解引用
  1756. var parsedSchema = this._validator.protoHelper.parseReference(payloadType);
  1757. var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
  1758. var newId = (idOp.value.toNumber() << 2) + lengthInfo.lengthType;
  1759. this._writer.ops[idPos] = this._writer.req2op({
  1760. type: "varint",
  1761. value: Varint64.from(newId),
  1762. });
  1763. if (lengthInfo.needLengthPrefix) {
  1764. var payloadByteLength = this._writer.ops.filter(function (v, i) { return i > idPos; }).sum(function (v) { return v.length; });
  1765. this._writer.ops.splice(lengthPrefixPos == undefined ? idPos + 1 : lengthPrefixPos, 0, this._writer.req2op({
  1766. type: "varint",
  1767. value: Varint64.from(payloadByteLength),
  1768. }));
  1769. }
  1770. };
  1771. return Encoder;
  1772. }());
  1773. /**
  1774. * @public
  1775. */
  1776. var TSBuffer = /** @class */ (function () {
  1777. function TSBuffer(proto, options) {
  1778. /** @internal 默认配置 */
  1779. this._options = {
  1780. excessPropertyChecks: true,
  1781. strictNullChecks: false,
  1782. skipEncodeValidate: false,
  1783. skipDecodeValidate: false,
  1784. cloneProto: true,
  1785. };
  1786. // but `options.validatorOptions` has higher priority to validate process (don't affect encode)
  1787. this._options = __assign(__assign({}, this._options), options);
  1788. this._proto = this._options.cloneProto ? Object.merge({}, proto) : proto;
  1789. Object.assign(this._proto, Object.merge({}, options === null || options === void 0 ? void 0 : options.customTypes));
  1790. this._validator = new TSBufferValidator(this._proto, {
  1791. excessPropertyChecks: this._options.excessPropertyChecks,
  1792. strictNullChecks: this._options.strictNullChecks,
  1793. cloneProto: false,
  1794. });
  1795. this.validate = this._validator.validate.bind(this._validator);
  1796. this.prune = this._validator.prune.bind(this._validator);
  1797. this._encoder = new Encoder({
  1798. validator: this._validator,
  1799. // if !strictNullChecks, then encoder can convert null to undefined
  1800. nullAsUndefined: !this._options.strictNullChecks,
  1801. });
  1802. this._decoder = new Decoder({
  1803. validator: this._validator,
  1804. // if !strictNullChecks, then decoder can convert undefined to null
  1805. undefinedAsNull: !this._options.strictNullChecks,
  1806. });
  1807. }
  1808. /**
  1809. * 编码
  1810. * @param value - 要编码的值
  1811. * @param schemaOrId - Schema 或 SchemaID,例如`a/b.ts`下的`Test`类型,其ID为`a/b/Test`
  1812. */
  1813. TSBuffer.prototype.encode = function (value, schemaOrId, options) {
  1814. var _a;
  1815. var schema;
  1816. if (typeof schemaOrId === "string") {
  1817. schema = this._proto[schemaOrId];
  1818. if (!schema) {
  1819. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
  1820. }
  1821. }
  1822. else {
  1823. schema = schemaOrId;
  1824. }
  1825. // validate before encode
  1826. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
  1827. var vRes = this._validator.validate(value, schema, {
  1828. // 禁用excessPropertyChecks,因为不会编码excess property
  1829. excessPropertyChecks: false,
  1830. });
  1831. if (!vRes.isSucc) {
  1832. return vRes;
  1833. }
  1834. }
  1835. var buf;
  1836. try {
  1837. buf = this._encoder.encode(value, schema);
  1838. }
  1839. catch (e) {
  1840. return { isSucc: false, errMsg: e.message };
  1841. }
  1842. return { isSucc: true, buf: buf };
  1843. };
  1844. /**
  1845. * 解码
  1846. * @param buf - 待解码的二进制数据
  1847. * @param schemaOrId - Schema 或 SchemaID,例如`a/b.ts`下的`Test`类型,其ID为`a/b/Test`
  1848. */
  1849. TSBuffer.prototype.decode = function (buf, schemaOrId, options) {
  1850. var _a;
  1851. var schema;
  1852. if (typeof schemaOrId === "string") {
  1853. schema = this._proto[schemaOrId];
  1854. if (!schema) {
  1855. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
  1856. }
  1857. }
  1858. else {
  1859. schema = schemaOrId;
  1860. }
  1861. var value;
  1862. try {
  1863. value = this._decoder.decode(buf, schema);
  1864. }
  1865. catch (e) {
  1866. return { isSucc: false, errMsg: e.message, errPhase: "decode" };
  1867. }
  1868. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
  1869. var vRes = this._validator.validate(value, schema);
  1870. if (!vRes.isSucc) {
  1871. return __assign(__assign({}, vRes), { errPhase: "validate" });
  1872. }
  1873. }
  1874. return { isSucc: true, value: value };
  1875. };
  1876. /**
  1877. * 编码为 JSON Object,根据协议将 JSON 不支持的格式(如 ArrayBuffer、Date、ObjectId)转换成 JSON 可传输的格式
  1878. * @param value
  1879. * @param schemaOrId
  1880. * @param options
  1881. */
  1882. TSBuffer.prototype.encodeJSON = function (value, schemaOrId, options) {
  1883. var _a;
  1884. var schema;
  1885. if (typeof schemaOrId === "string") {
  1886. schema = this._proto[schemaOrId];
  1887. if (!schema) {
  1888. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
  1889. }
  1890. }
  1891. else {
  1892. schema = schemaOrId;
  1893. }
  1894. // validate before encode
  1895. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
  1896. var vRes = this._validator.prune(value, schema);
  1897. if (!vRes.isSucc) {
  1898. return vRes;
  1899. }
  1900. value = vRes.pruneOutput;
  1901. }
  1902. // TODO schema 里没有 Buffer 和 Custom 的自动跳过
  1903. var json;
  1904. try {
  1905. json = this._encoder.encodeJSON(value, schema);
  1906. }
  1907. catch (e) {
  1908. return { isSucc: false, errMsg: e.message };
  1909. }
  1910. return { isSucc: true, json: json };
  1911. };
  1912. /**
  1913. * 从 JSON Object 解码,根据协议将 ArrayBuffer、Date、ObjectId 等类型从 JSON 中还原
  1914. * @param json - JSON Object (是 JSON 对象,而非 JSON 字符串)
  1915. * @param schemaOrId
  1916. * @param options
  1917. */
  1918. TSBuffer.prototype.decodeJSON = function (json, schemaOrId, options) {
  1919. var _a;
  1920. var schema;
  1921. if (typeof schemaOrId === "string") {
  1922. schema = this._proto[schemaOrId];
  1923. if (!schema) {
  1924. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
  1925. }
  1926. }
  1927. else {
  1928. schema = schemaOrId;
  1929. }
  1930. // TODO schema 里没有 Buffer 和 Custom 的自动跳过
  1931. var value;
  1932. try {
  1933. value = this._decoder.decodeJSON(json, schema);
  1934. }
  1935. catch (e) {
  1936. return { isSucc: false, errMsg: e.message, errPhase: "decode" };
  1937. }
  1938. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
  1939. var vRes = this._validator.prune(value, schema);
  1940. if (!vRes.isSucc) {
  1941. vRes.errPhase = "validate";
  1942. return vRes;
  1943. }
  1944. return { isSucc: true, value: vRes.pruneOutput };
  1945. }
  1946. return { isSucc: true, value: value };
  1947. };
  1948. return TSBuffer;
  1949. }());
  1950. export { Base64Util, TSBuffer };