index.js 82 KB

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