@zervonexx/baileys 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4124 -4112
  3. package/WAProto/WAProto.json +1 -0
  4. package/WAProto/WAProto.proto +7160 -0
  5. package/WAProto/WAProtoCompile.js +264 -322
  6. package/WAProto/index.js +55 -95
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +249 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +17 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +195 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +3 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +944 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +187 -192
  126. package/WAProto/fetcher.js +0 -68
  127. package/WAProto/parser.js +0 -334
@@ -1,323 +1,265 @@
1
- import { readFileSync, writeFileSync, existsSync } from 'fs'
2
- import { fileURLToPath } from 'url'
3
- import Long from 'long'
4
-
5
- const MAXSAFE = 0x1fffffffffffff
6
-
7
- const KIND = [
8
- { k: 'varint', s: 'int' }, { k: 'varint', s: 'zigzag' }, { k: 'varint', s: 'bool' },
9
- { k: 'i64', s: 'long' }, { k: 'i64', s: 'double' }, { k: 'i32', s: 'int' }, { k: 'i32', s: 'float' },
10
- { k: 'string' }, { k: 'bytes' }, { k: 'varint', s: 'enum' }, { k: 'varint', s: 'long' }, { k: 'varint', s: 'zigzaglong' },
11
- ]
12
-
13
- const SCALAR_TC = {
14
- int32: 0, uint32: 0, sint32: 1, bool: 2, fixed64: 3, sfixed64: 3, double: 4,
15
- fixed32: 5, sfixed32: 5, float: 6, string: 7, bytes: 8, int64: 10, uint64: 10, sint64: 11,
16
- }
17
-
18
- const isLongLike = v => v !== null && typeof v === 'object' && 'low' in v && 'high' in v
19
- const longToBigInt = v => (v.unsigned ? BigInt(v.high >>> 0) : BigInt(v.high | 0)) * 4294967296n + BigInt(v.low >>> 0)
20
- const anyToBigInt = v => typeof v === 'bigint' ? v : isLongLike(v) ? longToBigInt(v) : BigInt(Math.trunc(Number(v)))
21
- const zigzagEncode = v => { const b = anyToBigInt(v); return BigInt.asUintN(64, b << 1n ^ b >> 63n) }
22
- const toLong = big => Long.fromString(BigInt.asIntN(64, big).toString())
23
- const numOrBigInt = b => b <= 9007199254740991n && b >= -9007199254740991n ? Number(b) : toLong(b)
24
- const wireType = f => f.k === 'varint' ? 0 : f.k === 'i64' ? 1 : f.k === 'i32' ? 5 : 2
25
-
26
- const toBuffer = v => {
27
- if (v == null) return Buffer.alloc(0)
28
- if (Buffer.isBuffer(v)) return v
29
- if (typeof v === 'string') return Buffer.from(v, 'base64')
30
- if (v?.type === 'Buffer' && Array.isArray(v.data)) return Buffer.from(v.data)
31
- if (v instanceof Uint8Array) return Buffer.from(v)
32
- if (typeof v === 'object') return Buffer.from(JSON.stringify(v))
33
- return Buffer.alloc(0)
34
- }
35
-
36
- const anyToFloat = v => {
37
- if (typeof v === 'number') return v
38
- if (typeof v === 'bigint') return Number(v)
39
- if (isLongLike(v)) return v.toNumber()
40
- if (typeof v === 'string') return parseFloat(v)
41
- if (v == null) return 0
42
- return Number(v)
43
- }
44
-
45
- const B64_JSON = function () { return this.toString('base64') }
46
- const tagBytes = b => (Object.defineProperty(b, 'toJSON', { value: B64_JSON, enumerable: false, configurable: true }), b)
47
-
48
- class Writer {
49
- constructor() { this.buf = new Uint8Array(256); this.len = 0 }
50
- _grow(n) {
51
- if (this.len + n <= this.buf.length) return
52
- let cap = this.buf.length * 2
53
- while (cap < this.len + n) cap *= 2
54
- const next = new Uint8Array(cap)
55
- next.set(this.buf.subarray(0, this.len))
56
- this.buf = next
57
- }
58
- byte(b) { this._grow(1); this.buf[this.len++] = b }
59
- raw(u) { this._grow(u.length); this.buf.set(u, this.len); this.len += u.length }
60
- tag(f, wire) { this.varintNum(f * 8 + wire) }
61
- varintNum(n) { this._grow(10); while (n > 0x7f) { this.buf[this.len++] = (n & 0x7f) | 0x80; n = Math.floor(n / 128) }; this.buf[this.len++] = n }
62
- varintBig(v) { this._grow(10); let n = BigInt.asUintN(64, v); while (n > 0x7fn) { this.buf[this.len++] = Number((n & 0x7fn) | 0x80n); n >>= 7n }; this.buf[this.len++] = Number(n) }
63
- vint(v) { typeof v === 'number' && v >= 0 && v <= MAXSAFE && Number.isInteger(v) ? this.varintNum(v) : this.varintBig(anyToBigInt(v)) }
64
- fixed32(v) { this._grow(4); const n = Number(BigInt.asUintN(32, anyToBigInt(v))) >>> 0; this.buf[this.len++] = n & 0xff; this.buf[this.len++] = (n >>> 8) & 0xff; this.buf[this.len++] = (n >>> 16) & 0xff; this.buf[this.len++] = (n >>> 24) & 0xff }
65
- fixed64(v) { this._grow(8); const b = Buffer.allocUnsafe(8); b.writeBigUInt64LE(BigInt.asUintN(64, anyToBigInt(v))); this.raw(b) }
66
- float(v) { this._grow(4); const b = Buffer.allocUnsafe(4); b.writeFloatLE(anyToFloat(v)); this.raw(b) }
67
- double(v) { this._grow(8); const b = Buffer.allocUnsafe(8); b.writeDoubleLE(anyToFloat(v)); this.raw(b) }
68
- finish() { return Buffer.from(this.buf.buffer, this.buf.byteOffset, this.len) }
69
- }
70
-
71
- class Reader {
72
- constructor(buf) { this.buf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); this.p = 0; this.len = this.buf.length }
73
- _check(n) { if (this.p + n > this.len) throw new RangeError(`[WAProto] buffer overread: need ${n} bytes at ${this.p}, have ${this.len - this.p}`) }
74
- varint() {
75
- let r = 0, mult = 1, b, n = 0
76
- do {
77
- if (this.p >= this.len) throw new RangeError('[WAProto] varint: unexpected end of buffer')
78
- b = this.buf[this.p++]; r += (b & 0x7f) * mult; mult *= 128; n++
79
- if (n > 10) throw new RangeError('[WAProto] varint: too many bytes')
80
- } while (b & 0x80)
81
- return r > Number.MAX_SAFE_INTEGER ? Number(BigInt.asIntN(64, BigInt(Math.trunc(r)))) : r
82
- }
83
- varintBig() {
84
- let r = 0n, s = 0n, b, n = 0
85
- do {
86
- if (this.p >= this.len) throw new RangeError('[WAProto] varintBig: unexpected end of buffer')
87
- b = this.buf[this.p++]; r |= BigInt(b & 0x7f) << s; s += 7n; n++
88
- if (n > 10) throw new RangeError('[WAProto] varintBig: too many bytes')
89
- } while (b & 0x80)
90
- return r
91
- }
92
- skipVarint() { let n = 0; while (this.p < this.len && this.buf[this.p++] & 0x80) { if (++n > 10) throw new RangeError('[WAProto] skipVarint overflow') } }
93
- u32() { this._check(4); const p = this.p; this.p += 4; return (this.buf[p] | this.buf[p + 1] << 8 | this.buf[p + 2] << 16 | this.buf[p + 3] << 24) >>> 0 }
94
- slice(len) { if (len < 0 || this.p + len > this.len) throw new RangeError(`[WAProto] slice: invalid length ${len} at ${this.p}`); const s = this.buf.subarray(this.p, this.p + len); this.p += len; return s }
95
- read8() { this._check(8); const b = this.buf.subarray(this.p, this.p + 8); this.p += 8; return b }
96
- read4() { this._check(4); const b = this.buf.subarray(this.p, this.p + 4); this.p += 4; return b }
97
- }
98
-
99
- function buildTable(rawTable, msgNames) {
100
- const TABLE = {}
101
- for (const [full, fields] of Object.entries(rawTable)) {
102
- const order = fields.map(([name, id, tc, flags = 0, enumName]) => {
103
- const base = tc >= 100 ? { k: 'msg', msg: msgNames[tc - 100] } : KIND[tc]
104
- const f = { name, id, ...base, rep: !!(flags & 1), packed: !!(flags & 2) }
105
- if (tc === 9 && enumName) f.enumName = enumName
106
- return f
107
- })
108
- TABLE[full] = { order, byId: Object.fromEntries(order.map(f => [f.id, f])) }
109
- }
110
- return TABLE
111
- }
112
-
113
- function makeCodec(TABLE, enumIndex) {
114
- function resolveEnum(f, v) {
115
- if (typeof v !== 'string') return v
116
- if (f.enumName && enumIndex[f.enumName]) { const n = enumIndex[f.enumName][v]; if (n !== undefined) return n }
117
- const n = Number(v)
118
- return Number.isFinite(n) ? n : undefined
119
- }
120
-
121
- function writeScalar(w, f, v) {
122
- switch (f.k) {
123
- case 'varint':
124
- if (f.s === 'bool') w.byte(v ? 1 : 0)
125
- else if (f.s === 'zigzag' || f.s === 'zigzaglong') w.varintBig(zigzagEncode(v))
126
- else w.vint(v)
127
- break
128
- case 'i64': f.s === 'double' ? w.double(v) : w.fixed64(v); break
129
- case 'i32': f.s === 'float' ? w.float(v) : w.fixed32(v); break
130
- case 'string': { const b = Buffer.from(String(v), 'utf8'); w.varintNum(b.length); w.raw(b); break }
131
- case 'bytes': { const b = toBuffer(v); w.varintNum(b.length); w.raw(b); break }
132
- case 'msg': { const s = new Writer(); encodeMsg(s, TABLE[f.msg], v); const b = s.finish(); w.varintNum(b.length); w.raw(b); break }
133
- }
134
- }
135
-
136
- function encodeMsg(w, T, obj) {
137
- if (!T) throw new Error('[WAProto] Unknown message in table')
138
- for (const f of T.order) {
139
- let v = obj[f.name]
140
- if (v == null) continue
141
- if (f.s === 'enum') {
142
- if (f.rep) { v = (Array.isArray(v) ? v : [v]).map(x => resolveEnum(f, x)).filter(x => x !== undefined); if (!v.length) continue }
143
- else { v = resolveEnum(f, v); if (v === undefined) continue }
144
- }
145
- if (f.rep) {
146
- if (!Array.isArray(v)) v = [v]
147
- if (f.packed && (f.k === 'varint' || f.k === 'i64' || f.k === 'i32')) {
148
- const s = new Writer()
149
- for (const item of v) writeScalar(s, f, item)
150
- const b = s.finish()
151
- w.tag(f.id, 2); w.varintNum(b.length); w.raw(b)
152
- } else { const wt = wireType(f); for (const item of v) { w.tag(f.id, wt); writeScalar(w, f, item) } }
153
- } else { w.tag(f.id, wireType(f)); writeScalar(w, f, v) }
154
- }
155
- }
156
-
157
- function readScalar(r, f) {
158
- switch (f.k) {
159
- case 'varint': {
160
- if (f.s === 'bool') return !!r.varint()
161
- if (f.s === 'zigzag') { const u = r.varintBig(); return numOrBigInt(u >> 1n ^ -(u & 1n)) }
162
- if (f.s === 'zigzaglong') { const u = r.varintBig(); return toLong(u >> 1n ^ -(u & 1n)) }
163
- if (f.s === 'enum') return r.varint() | 0
164
- if (f.s === 'long') return toLong(r.varintBig())
165
- return r.varint()
166
- }
167
- case 'i64': { const b = Buffer.from(r.read8()); return f.s === 'double' ? b.readDoubleLE(0) : toLong(b.readBigUInt64LE(0)) }
168
- case 'i32': { if (f.s === 'float') { const b = Buffer.from(r.read4()); return b.readFloatLE(0) }; return r.u32() }
169
- case 'string': { const len = r.varint(); return Buffer.from(r.slice(len)).toString('utf8') }
170
- case 'bytes': return tagBytes(Buffer.from(r.slice(r.varint())))
171
- case 'msg': return decodeMsg(f.msg, r.slice(r.varint()))
172
- }
173
- }
174
-
175
- function skip(r, wire) {
176
- if (wire === 0) r.skipVarint()
177
- else if (wire === 2) { const n = r.varint(); r.slice(n) }
178
- else if (wire === 1) r.read8()
179
- else if (wire === 5) r.read4()
180
- }
181
-
182
- function decodeMsg(msgName, buf) {
183
- const T = TABLE[msgName]
184
- if (!T) throw new Error(`[WAProto] Unknown message: ${msgName}`)
185
- const obj = {}, r = new Reader(buf)
186
- while (r.p < r.len) {
187
- let tag, id, wire
188
- try { tag = r.varint(); id = tag >>> 3; wire = tag & 7 } catch { break }
189
- const f = T.byId[id]
190
- if (!f) { try { skip(r, wire) } catch { break }; continue }
191
- try {
192
- if (f.rep && wire === 2 && (f.k === 'varint' || f.k === 'i64' || f.k === 'i32')) {
193
- const len = r.varint(), end = r.p + len
194
- const arr = obj[f.name] || (obj[f.name] = [])
195
- while (r.p < end) arr.push(readScalar(r, f))
196
- } else {
197
- const val = readScalar(r, f)
198
- if (f.rep) (obj[f.name] || (obj[f.name] = [])).push(val)
199
- else obj[f.name] = val
200
- }
201
- } catch (e) {
202
- console.warn('[WAProto] decode error:', e.message)
203
- break
204
- }
205
- }
206
- return obj
207
- }
208
-
209
- return {
210
- encode: (msgName, obj) => { const w = new Writer(); encodeMsg(w, TABLE[msgName], obj ?? {}); return w.finish() },
211
- decode: (msgName, buf) => decodeMsg(msgName, buf),
212
- }
213
- }
214
-
215
- export async function generateTable(protoPath, outPath) {
216
- const pb = await import('protobufjs')
217
- const protobuf = pb.default || pb
218
- const root = await protobuf.load(protoPath)
219
- const msgNames = []
220
- const msgIndex = n => { let i = msgNames.indexOf(n); return i < 0 ? msgNames.push(n) - 1 : i }
221
- const t = {}, e = {}
222
- const build = ns => {
223
- for (const o of Object.values(ns.nested ?? {})) {
224
- const full = o.fullName.replace(/^\./, '')
225
- if (o.values) e[full] = o.values
226
- if (o.fieldsArray) {
227
- const fs = []
228
- for (const f of o.fieldsArray) {
229
- if (f.map) continue
230
- const rt = f.resolvedType
231
- let tc, enumName
232
- if (rt?.fieldsArray !== undefined && rt?.values === undefined) tc = 100 + msgIndex(rt.fullName.replace(/^\./, ''))
233
- else if (rt?.values) { tc = 9; enumName = rt.fullName.replace(/^\./, '') }
234
- else tc = SCALAR_TC[f.type]
235
- const numeric = tc < 100 && tc !== 7 && tc !== 8
236
- const flags = (f.repeated ? 1 : 0) | (f.repeated && numeric && f.packed !== false ? 2 : 0)
237
- if (tc === 9) fs.push([f.name, f.id, 9, flags, enumName])
238
- else if (flags) fs.push([f.name, f.id, tc, flags])
239
- else fs.push([f.name, f.id, tc])
240
- }
241
- fs.sort((a, b) => a[1] - b[1])
242
- t[full] = fs
243
- }
244
- if (o.nested) build(o)
245
- }
246
- }
247
- build(root)
248
- const tmp = outPath + '.tmp'
249
- writeFileSync(tmp, JSON.stringify({ m: msgNames, t, e }))
250
- const { renameSync } = await import('fs')
251
- renameSync(tmp, outPath)
252
- return { types: Object.keys(t).length, enums: Object.keys(e).length }
253
- }
254
-
255
- function makeProto(tablePath) {
256
- const { m, t, e } = JSON.parse(readFileSync(tablePath, 'utf8'))
257
- const TABLE = buildTable(t, m)
258
- const codec = makeCodec(TABLE, e)
259
- const proto = {}
260
- const nodeFor = path => { let c = proto; for (const p of path) c = c[p] ?? (c[p] = {}); return c }
261
- const reorder = (full, o) => {
262
- if (!o || typeof o !== 'object') return o ?? {}
263
- const T = TABLE[full]
264
- if (!T) return o
265
- const result = {}
266
- for (const f of T.order) {
267
- if (!(f.name in o) || o[f.name] == null) continue
268
- if (o[f.name] === '') continue
269
- if (f.k === 'msg' && f.msg && typeof o[f.name] === 'object') {
270
- result[f.name] = Array.isArray(o[f.name])
271
- ? o[f.name].map(item => reorder(f.msg, item))
272
- : reorder(f.msg, o[f.name])
273
- } else {
274
- result[f.name] = o[f.name]
275
- }
276
- }
277
- return result
278
- }
279
- for (const full of Object.keys(t)) {
280
- const node = nodeFor(full.replace(/^proto\./, '').split('.'))
281
- node.encode = o => ({ finish: () => codec.encode(full, o ?? {}) })
282
- node.decode = b => codec.decode(full, b)
283
- node.create = o => reorder(full, o)
284
- node.fromObject = o => reorder(full, o)
285
- node.toObject = o => o ?? {}
286
- node.verify = () => null
287
- node.name = full.split('.').pop()
288
- node.fields = Object.fromEntries(TABLE[full].order.map(f => [f.name, { type: f.s ?? f.k, id: f.id, repeated: f.rep ?? false, ...(f.msg && { msgType: f.msg.split('.').pop() }) }]))
289
- }
290
- for (const [full, values] of Object.entries(e)) {
291
- const node = nodeFor(full.replace(/^proto\./, '').split('.'))
292
- for (const [k, v] of Object.entries(values)) { node[k] = v; node[v] = k }
293
- }
294
- return { proto, codec }
295
- }
296
-
297
- const isGeneratorRun = process.argv[1] && (process.argv[1] === fileURLToPath(import.meta.url) || process.argv.includes('--generate'))
298
-
299
- if (isGeneratorRun) {
300
- const protoPath = fileURLToPath(new URL('./WAProto.proto', import.meta.url))
301
- const outPath = fileURLToPath(new URL('./WAProto.json', import.meta.url))
302
- generateTable(protoPath, outPath)
303
- .then(r => { process.stdout.write(`[WAProto] Generated: ${r.types} types, ${r.enums} enums\n`); process.exit(0) })
304
- .catch(err => { process.stderr.write(err.message + '\n'); process.exit(1) })
305
- }
306
-
307
- const tablePath = fileURLToPath(new URL('./WAProto.json', import.meta.url))
308
- const built = { proto: {}, codec: null }
309
-
310
- export let codec = null
311
- export function _reloadProto() {
312
- if (!existsSync(tablePath)) return
313
- const loaded = makeProto(tablePath)
314
- for (const key of Object.keys(built.proto)) delete built.proto[key]
315
- Object.assign(built.proto, loaded.proto)
316
- built.codec = loaded.codec
317
- codec = loaded.codec
318
- }
319
-
320
- if (!isGeneratorRun && existsSync(tablePath)) _reloadProto()
321
-
322
- export const proto = built.proto
1
+ import { readFileSync } from 'fs'
2
+ import { fileURLToPath } from 'url'
3
+ import Long from 'long'
4
+
5
+ const MAXSAFE = 0x1fffffffffffff
6
+
7
+ const KIND = [
8
+ { k: 'varint', s: 'int' }, { k: 'varint', s: 'zigzag' }, { k: 'varint', s: 'bool' },
9
+ { k: 'i64', s: 'long' }, { k: 'i64', s: 'double' }, { k: 'i32', s: 'int' }, { k: 'i32', s: 'float' },
10
+ { k: 'string' }, { k: 'bytes' }, { k: 'varint', s: 'enum' }, { k: 'varint', s: 'long' }, { k: 'varint', s: 'zigzaglong' },
11
+ ]
12
+
13
+ const isLongLike = v => v !== null && typeof v === 'object' && 'low' in v && 'high' in v
14
+ const longToBigInt = v => (v.unsigned ? BigInt(v.high >>> 0) : BigInt(v.high | 0)) * 4294967296n + BigInt(v.low >>> 0)
15
+ const anyToBigInt = v => typeof v === 'bigint' ? v : isLongLike(v) ? longToBigInt(v) : BigInt(Math.trunc(Number(v)))
16
+ const zigzagEncode = v => { const b = anyToBigInt(v); return BigInt.asUintN(64, b << 1n ^ b >> 63n) }
17
+ const toLong = big => Long.fromString(BigInt.asIntN(64, big).toString())
18
+ const numOrBigInt = b => b <= 9007199254740991n && b >= -9007199254740991n ? Number(b) : toLong(b)
19
+ const wireType = f => f.k === 'varint' ? 0 : f.k === 'i64' ? 1 : f.k === 'i32' ? 5 : 2
20
+
21
+ const toBuffer = v => {
22
+ if (v == null) return Buffer.alloc(0)
23
+ if (Buffer.isBuffer(v)) return v
24
+ if (typeof v === 'string') return Buffer.from(v, 'base64')
25
+ if (v?.type === 'Buffer' && Array.isArray(v.data)) return Buffer.from(v.data)
26
+ if (v instanceof Uint8Array) return Buffer.from(v)
27
+ if (typeof v === 'object') return Buffer.from(JSON.stringify(v))
28
+ return Buffer.alloc(0)
29
+ }
30
+
31
+ const anyToFloat = v => {
32
+ if (typeof v === 'number') return v
33
+ if (typeof v === 'bigint') return Number(v)
34
+ if (isLongLike(v)) return v.toNumber()
35
+ if (typeof v === 'string') return parseFloat(v)
36
+ if (v == null) return 0
37
+ return Number(v)
38
+ }
39
+
40
+ const B64_JSON = function () { return this.toString('base64') }
41
+ const tagBytes = b => (Object.defineProperty(b, 'toJSON', { value: B64_JSON, enumerable: false, configurable: true }), b)
42
+
43
+ class Writer {
44
+ constructor() { this.buf = new Uint8Array(256); this.len = 0 }
45
+ _grow(n) {
46
+ if (this.len + n <= this.buf.length) return
47
+ let cap = this.buf.length * 2
48
+ while (cap < this.len + n) cap *= 2
49
+ const next = new Uint8Array(cap)
50
+ next.set(this.buf.subarray(0, this.len))
51
+ this.buf = next
52
+ }
53
+ byte(b) { this._grow(1); this.buf[this.len++] = b }
54
+ raw(u) { this._grow(u.length); this.buf.set(u, this.len); this.len += u.length }
55
+ tag(f, wire) { this.varintNum(f * 8 + wire) }
56
+ varintNum(n) { this._grow(10); while (n > 0x7f) { this.buf[this.len++] = (n & 0x7f) | 0x80; n = Math.floor(n / 128) }; this.buf[this.len++] = n }
57
+ varintBig(v) { this._grow(10); let n = BigInt.asUintN(64, v); while (n > 0x7fn) { this.buf[this.len++] = Number((n & 0x7fn) | 0x80n); n >>= 7n }; this.buf[this.len++] = Number(n) }
58
+ vint(v) { typeof v === 'number' && v >= 0 && v <= MAXSAFE && Number.isInteger(v) ? this.varintNum(v) : this.varintBig(anyToBigInt(v)) }
59
+ fixed32(v) { this._grow(4); const n = Number(BigInt.asUintN(32, anyToBigInt(v))) >>> 0; this.buf[this.len++] = n & 0xff; this.buf[this.len++] = (n >>> 8) & 0xff; this.buf[this.len++] = (n >>> 16) & 0xff; this.buf[this.len++] = (n >>> 24) & 0xff }
60
+ fixed64(v) { this._grow(8); const b = Buffer.allocUnsafe(8); b.writeBigUInt64LE(BigInt.asUintN(64, anyToBigInt(v))); this.raw(b) }
61
+ float(v) { this._grow(4); const b = Buffer.allocUnsafe(4); b.writeFloatLE(anyToFloat(v)); this.raw(b) }
62
+ double(v) { this._grow(8); const b = Buffer.allocUnsafe(8); b.writeDoubleLE(anyToFloat(v)); this.raw(b) }
63
+ finish() { return Buffer.from(this.buf.buffer, this.buf.byteOffset, this.len) }
64
+ }
65
+
66
+ class Reader {
67
+ constructor(buf) { this.buf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); this.p = 0; this.len = this.buf.length }
68
+ _check(n) { if (this.p + n > this.len) throw new RangeError(`[WAProto] buffer overread: need ${n} bytes at ${this.p}, have ${this.len - this.p}`) }
69
+ varint() {
70
+ let r = 0, mult = 1, b, n = 0
71
+ do {
72
+ if (this.p >= this.len) throw new RangeError('[WAProto] varint: unexpected end of buffer')
73
+ b = this.buf[this.p++]; r += (b & 0x7f) * mult; mult *= 128; n++
74
+ if (n > 10) throw new RangeError('[WAProto] varint: too many bytes')
75
+ } while (b & 0x80)
76
+ return r > Number.MAX_SAFE_INTEGER ? Number(BigInt.asIntN(64, BigInt(Math.trunc(r)))) : r
77
+ }
78
+ varintBig() {
79
+ let r = 0n, s = 0n, b, n = 0
80
+ do {
81
+ if (this.p >= this.len) throw new RangeError('[WAProto] varintBig: unexpected end of buffer')
82
+ b = this.buf[this.p++]; r |= BigInt(b & 0x7f) << s; s += 7n; n++
83
+ if (n > 10) throw new RangeError('[WAProto] varintBig: too many bytes')
84
+ } while (b & 0x80)
85
+ return r
86
+ }
87
+ skipVarint() { let n = 0; while (this.p < this.len && this.buf[this.p++] & 0x80) { if (++n > 10) throw new RangeError('[WAProto] skipVarint overflow') } }
88
+ u32() { this._check(4); const p = this.p; this.p += 4; return (this.buf[p] | this.buf[p + 1] << 8 | this.buf[p + 2] << 16 | this.buf[p + 3] << 24) >>> 0 }
89
+ slice(len) { if (len < 0 || this.p + len > this.len) throw new RangeError(`[WAProto] slice: invalid length ${len} at ${this.p}`); const s = this.buf.subarray(this.p, this.p + len); this.p += len; return s }
90
+ read8() { this._check(8); const b = this.buf.subarray(this.p, this.p + 8); this.p += 8; return b }
91
+ read4() { this._check(4); const b = this.buf.subarray(this.p, this.p + 4); this.p += 4; return b }
92
+ }
93
+
94
+ function buildTable(rawTable, msgNames) {
95
+ const TABLE = {}
96
+ for (const [full, fields] of Object.entries(rawTable)) {
97
+ const order = fields.map(([name, id, tc, flags = 0, enumName]) => {
98
+ const base = tc >= 100 ? { k: 'msg', msg: msgNames[tc - 100] } : KIND[tc]
99
+ const f = { name, id, ...base, rep: !!(flags & 1), packed: !!(flags & 2) }
100
+ if (tc === 9 && enumName) f.enumName = enumName
101
+ return f
102
+ })
103
+ TABLE[full] = { order, byId: Object.fromEntries(order.map(f => [f.id, f])) }
104
+ }
105
+ return TABLE
106
+ }
107
+
108
+ function makeCodec(TABLE, enumIndex) {
109
+ function resolveEnum(f, v) {
110
+ if (typeof v !== 'string') return v
111
+ if (f.enumName && enumIndex[f.enumName]) { const n = enumIndex[f.enumName][v]; if (n !== undefined) return n }
112
+ const n = Number(v)
113
+ return Number.isFinite(n) ? n : undefined
114
+ }
115
+
116
+ function writeScalar(w, f, v) {
117
+ switch (f.k) {
118
+ case 'varint':
119
+ if (f.s === 'bool') w.byte(v ? 1 : 0)
120
+ else if (f.s === 'zigzag' || f.s === 'zigzaglong') w.varintBig(zigzagEncode(v))
121
+ else w.vint(v)
122
+ break
123
+ case 'i64': f.s === 'double' ? w.double(v) : w.fixed64(v); break
124
+ case 'i32': f.s === 'float' ? w.float(v) : w.fixed32(v); break
125
+ case 'string': { const b = Buffer.from(String(v), 'utf8'); w.varintNum(b.length); w.raw(b); break }
126
+ case 'bytes': { const b = toBuffer(v); w.varintNum(b.length); w.raw(b); break }
127
+ case 'msg': { const s = new Writer(); encodeMsg(s, TABLE[f.msg], v); const b = s.finish(); w.varintNum(b.length); w.raw(b); break }
128
+ }
129
+ }
130
+
131
+ function encodeMsg(w, T, obj) {
132
+ if (!T) throw new Error('[WAProto] Unknown message in table')
133
+ for (const f of T.order) {
134
+ let v = obj[f.name]
135
+ if (v == null) continue
136
+ if (f.s === 'enum') {
137
+ if (f.rep) { v = (Array.isArray(v) ? v : [v]).map(x => resolveEnum(f, x)).filter(x => x !== undefined); if (!v.length) continue }
138
+ else { v = resolveEnum(f, v); if (v === undefined) continue }
139
+ }
140
+ if (f.rep) {
141
+ if (!Array.isArray(v)) v = [v]
142
+ if (f.packed && (f.k === 'varint' || f.k === 'i64' || f.k === 'i32')) {
143
+ const s = new Writer()
144
+ for (const item of v) writeScalar(s, f, item)
145
+ const b = s.finish()
146
+ w.tag(f.id, 2); w.varintNum(b.length); w.raw(b)
147
+ } else { const wt = wireType(f); for (const item of v) { w.tag(f.id, wt); writeScalar(w, f, item) } }
148
+ } else { w.tag(f.id, wireType(f)); writeScalar(w, f, v) }
149
+ }
150
+ }
151
+
152
+ function readScalar(r, f) {
153
+ switch (f.k) {
154
+ case 'varint': {
155
+ if (f.s === 'bool') return !!r.varint()
156
+ if (f.s === 'zigzag') { const u = r.varintBig(); return numOrBigInt(u >> 1n ^ -(u & 1n)) }
157
+ if (f.s === 'zigzaglong') { const u = r.varintBig(); return toLong(u >> 1n ^ -(u & 1n)) }
158
+ if (f.s === 'enum') return r.varint() | 0
159
+ if (f.s === 'long') return toLong(r.varintBig())
160
+ return r.varint()
161
+ }
162
+ case 'i64': { const b = Buffer.from(r.read8()); return f.s === 'double' ? b.readDoubleLE(0) : toLong(b.readBigUInt64LE(0)) }
163
+ case 'i32': { if (f.s === 'float') { const b = Buffer.from(r.read4()); return b.readFloatLE(0) }; return r.u32() }
164
+ case 'string': { const len = r.varint(); return Buffer.from(r.slice(len)).toString('utf8') }
165
+ case 'bytes': return tagBytes(Buffer.from(r.slice(r.varint())))
166
+ case 'msg': return decodeMsg(f.msg, r.slice(r.varint()))
167
+ }
168
+ }
169
+
170
+ function skip(r, wire) {
171
+ if (wire === 0) r.skipVarint()
172
+ else if (wire === 2) { const n = r.varint(); r.slice(n) }
173
+ else if (wire === 1) r.read8()
174
+ else if (wire === 5) r.read4()
175
+ }
176
+
177
+ function decodeMsg(msgName, buf) {
178
+ const T = TABLE[msgName]
179
+ if (!T) throw new Error(`[WAProto] Unknown message: ${msgName}`)
180
+ const obj = {}, r = new Reader(buf)
181
+ while (r.p < r.len) {
182
+ let tag, id, wire
183
+ try { tag = r.varint(); id = tag >>> 3; wire = tag & 7 } catch { break }
184
+ const f = T.byId[id]
185
+ if (!f) { try { skip(r, wire) } catch { break }; continue }
186
+ try {
187
+ if (f.rep && wire === 2 && (f.k === 'varint' || f.k === 'i64' || f.k === 'i32')) {
188
+ const len = r.varint(), end = r.p + len
189
+ const arr = obj[f.name] || (obj[f.name] = [])
190
+ while (r.p < end) arr.push(readScalar(r, f))
191
+ } else {
192
+ const val = readScalar(r, f)
193
+ if (f.rep) (obj[f.name] || (obj[f.name] = [])).push(val)
194
+ else obj[f.name] = val
195
+ }
196
+ } catch (e) {
197
+ console.warn('[WAProto] decode error:', e.message)
198
+ break
199
+ }
200
+ }
201
+ return obj
202
+ }
203
+
204
+ return {
205
+ encode: (msgName, obj) => { const w = new Writer(); encodeMsg(w, TABLE[msgName], obj ?? {}); return w.finish() },
206
+ decode: (msgName, buf) => decodeMsg(msgName, buf),
207
+ }
208
+ }
209
+
210
+ function makeProto(tablePath) {
211
+ const { m, t, e } = JSON.parse(readFileSync(tablePath, 'utf8'))
212
+ const TABLE = buildTable(t, m)
213
+ const codec = makeCodec(TABLE, e)
214
+ const proto = {}
215
+ const nodeFor = path => { let c = proto; for (const p of path) c = c[p] ?? (c[p] = {}); return c }
216
+ const reorder = (full, o) => {
217
+ if (!o || typeof o !== 'object') return o ?? {}
218
+ const T = TABLE[full]
219
+ if (!T) return o
220
+ const result = {}
221
+ for (const f of T.order) {
222
+ if (!(f.name in o) || o[f.name] == null) continue
223
+ if (o[f.name] === '') continue
224
+ if (f.k === 'msg' && f.msg && typeof o[f.name] === 'object') {
225
+ result[f.name] = Array.isArray(o[f.name])
226
+ ? o[f.name].map(item => reorder(f.msg, item))
227
+ : reorder(f.msg, o[f.name])
228
+ } else {
229
+ result[f.name] = o[f.name]
230
+ }
231
+ }
232
+ return result
233
+ }
234
+ for (const full of Object.keys(t)) {
235
+ const node = nodeFor(full.replace(/^proto\./, '').split('.'))
236
+ node.encode = o => ({ finish: () => codec.encode(full, o ?? {}) })
237
+ node.decode = b => codec.decode(full, b)
238
+ node.create = o => reorder(full, o)
239
+ node.fromObject = o => reorder(full, o)
240
+ node.toObject = o => o ?? {}
241
+ node.verify = () => null
242
+ node.name = full.split('.').pop()
243
+ node.fields = Object.fromEntries(TABLE[full].order.map(f => [f.name, { type: f.s ?? f.k, id: f.id, repeated: f.rep ?? false, ...(f.msg && { msgType: f.msg.split('.').pop() }) }]))
244
+ }
245
+ for (const [full, values] of Object.entries(e)) {
246
+ const node = nodeFor(full.replace(/^proto\./, '').split('.'))
247
+ for (const [k, v] of Object.entries(values)) { node[k] = v; node[v] = k }
248
+ }
249
+ return { proto, codec }
250
+ }
251
+
252
+ const tablePath = fileURLToPath(new URL('./WAProto.json', import.meta.url))
253
+ const built = { proto: {}, codec: null }
254
+
255
+ export let codec = null
256
+ export function _reloadProto() {
257
+ const loaded = makeProto(tablePath)
258
+ for (const key of Object.keys(built.proto)) delete built.proto[key]
259
+ Object.assign(built.proto, loaded.proto)
260
+ built.codec = loaded.codec
261
+ codec = loaded.codec
262
+ }
263
+
264
+ export const proto = built.proto
323
265
  export default built