@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,152 +1,152 @@
1
- import { promisify } from 'util'
2
- import { inflate } from 'zlib'
3
- import * as constants from './constants.js'
4
- import { jidEncode, WAJIDDomains } from './jid-utils.js'
5
-
6
- const inflatePromise = promisify(inflate)
7
-
8
- export const decompressingIfRequired = async (buffer) => {
9
- if (2 & buffer.readUInt8()) buffer = await inflatePromise(buffer.slice(1))
10
- else buffer = buffer.slice(1)
11
- return buffer
12
- }
13
-
14
- export const decodeBinaryNode = async (buff) =>
15
- decodeDecompressedBinaryNode(await decompressingIfRequired(buff), constants)
16
-
17
- export const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
18
- const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
19
-
20
- const checkEOS = (n) => { if (indexRef.index + n > buffer.length) throw new Error('end of stream') }
21
- const next = () => { const v = buffer[indexRef.index]; indexRef.index += 1; return v }
22
- const readByte = () => { checkEOS(1); return next() }
23
- const readBytes = (n) => { checkEOS(n); const v = buffer.slice(indexRef.index, indexRef.index + n); indexRef.index += n; return v }
24
- const readStringFromChars = (n) => readBytes(n).toString('utf-8')
25
-
26
- const readInt = (n, le = false) => {
27
- checkEOS(n)
28
- let val = 0
29
- for (let i = 0; i < n; i++) val |= next() << ((le ? i : n - 1 - i) * 8)
30
- return val
31
- }
32
-
33
- const readInt20 = () => { checkEOS(3); return ((next() & 15) << 16) | (next() << 8) | next() }
34
-
35
- const unpackHex = (v) => {
36
- if (v >= 0 && v < 16) return v < 10 ? '0'.charCodeAt(0) + v : 'A'.charCodeAt(0) + v - 10
37
- throw new Error('invalid hex: ' + v)
38
- }
39
-
40
- const unpackNibble = (v) => {
41
- if (v >= 0 && v <= 9) return '0'.charCodeAt(0) + v
42
- if (v === 10) return '-'.charCodeAt(0)
43
- if (v === 11) return '.'.charCodeAt(0)
44
- if (v === 15) return '\0'.charCodeAt(0)
45
- throw new Error('invalid nibble: ' + v)
46
- }
47
-
48
- const unpackByte = (tag, v) => {
49
- if (tag === TAGS.NIBBLE_8) return unpackNibble(v)
50
- if (tag === TAGS.HEX_8) return unpackHex(v)
51
- throw new Error('unknown tag: ' + tag)
52
- }
53
-
54
- const readPacked8 = (tag) => {
55
- const startByte = readByte()
56
- let value = ''
57
- for (let i = 0; i < (startByte & 127); i++) {
58
- const cur = readByte()
59
- value += String.fromCharCode(unpackByte(tag, (cur & 0xf0) >> 4))
60
- value += String.fromCharCode(unpackByte(tag, cur & 0x0f))
61
- }
62
- if (startByte >> 7 !== 0) value = value.slice(0, -1)
63
- return value
64
- }
65
-
66
- const isListTag = (tag) => tag === TAGS.LIST_EMPTY || tag === TAGS.LIST_8 || tag === TAGS.LIST_16
67
-
68
- const readListSize = (tag) => {
69
- switch (tag) {
70
- case TAGS.LIST_EMPTY: return 0
71
- case TAGS.LIST_8: return readByte()
72
- case TAGS.LIST_16: return readInt(2)
73
- default: throw new Error('invalid tag for list size: ' + tag)
74
- }
75
- }
76
-
77
- const readJidPair = () => {
78
- const i = readString(readByte())
79
- const j = readString(readByte())
80
- if (j) return (i || '') + '@' + j
81
- throw new Error('invalid jid pair: ' + i + ', ' + j)
82
- }
83
-
84
- const readAdJid = () => {
85
- const domainType = Number(readByte())
86
- const device = readByte()
87
- const user = readString(readByte())
88
- const server =
89
- domainType === WAJIDDomains.LID ? 'lid' :
90
- domainType === WAJIDDomains.HOSTED ? 'hosted' :
91
- domainType === WAJIDDomains.HOSTED_LID ? 'hosted.lid' :
92
- 's.whatsapp.net'
93
- return jidEncode(user, server, device)
94
- }
95
-
96
- const getTokenDouble = (i1, i2) => {
97
- const dict = DOUBLE_BYTE_TOKENS[i1]
98
- if (!dict) throw new Error(`invalid double token dict (${i1})`)
99
- const val = dict[i2]
100
- if (val === undefined) throw new Error(`invalid double token (${i2})`)
101
- return val
102
- }
103
-
104
- const readString = (tag) => {
105
- if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) return SINGLE_BYTE_TOKENS[tag] ?? ''
106
- switch (tag) {
107
- case TAGS.DICTIONARY_0:
108
- case TAGS.DICTIONARY_1:
109
- case TAGS.DICTIONARY_2:
110
- case TAGS.DICTIONARY_3: return getTokenDouble(tag - TAGS.DICTIONARY_0, readByte())
111
- case TAGS.LIST_EMPTY: return ''
112
- case TAGS.BINARY_8: return readStringFromChars(readByte())
113
- case TAGS.BINARY_20: return readStringFromChars(readInt20())
114
- case TAGS.BINARY_32: return readStringFromChars(readInt(4))
115
- case TAGS.JID_PAIR: return readJidPair()
116
- case TAGS.AD_JID: return readAdJid()
117
- case TAGS.HEX_8:
118
- case TAGS.NIBBLE_8: return readPacked8(tag)
119
- default: throw new Error('invalid string with tag: ' + tag)
120
- }
121
- }
122
-
123
- const readList = (tag) => {
124
- const size = readListSize(tag)
125
- const items = []
126
- for (let i = 0; i < size; i++) items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
127
- return items
128
- }
129
-
130
- const listSize = readListSize(readByte())
131
- const header = readString(readByte())
132
- if (!listSize || !header.length) throw new Error('invalid node')
133
-
134
- const attrs = {}
135
- const attributesLength = (listSize - 1) >> 1
136
- for (let i = 0; i < attributesLength; i++) attrs[readString(readByte())] = readString(readByte())
137
-
138
- let data
139
- if (listSize % 2 === 0) {
140
- const tag = readByte()
141
- data = isListTag(tag) ? readList(tag) : (() => {
142
- switch (tag) {
143
- case TAGS.BINARY_8: return readBytes(readByte())
144
- case TAGS.BINARY_20: return readBytes(readInt20())
145
- case TAGS.BINARY_32: return readBytes(readInt(4))
146
- default: return readString(tag)
147
- }
148
- })()
149
- }
150
-
151
- return { tag: header, attrs, content: data }
1
+ import { promisify } from 'util'
2
+ import { inflate } from 'zlib'
3
+ import * as constants from './constants.js'
4
+ import { jidEncode, WAJIDDomains } from './jid-utils.js'
5
+
6
+ const inflatePromise = promisify(inflate)
7
+
8
+ export const decompressingIfRequired = async (buffer) => {
9
+ if (2 & buffer.readUInt8()) buffer = await inflatePromise(buffer.slice(1))
10
+ else buffer = buffer.slice(1)
11
+ return buffer
12
+ }
13
+
14
+ export const decodeBinaryNode = async (buff) =>
15
+ decodeDecompressedBinaryNode(await decompressingIfRequired(buff), constants)
16
+
17
+ export const decodeDecompressedBinaryNode = (buffer, opts, indexRef = { index: 0 }) => {
18
+ const { DOUBLE_BYTE_TOKENS, SINGLE_BYTE_TOKENS, TAGS } = opts
19
+
20
+ const checkEOS = (n) => { if (indexRef.index + n > buffer.length) throw new Error('end of stream') }
21
+ const next = () => { const v = buffer[indexRef.index]; indexRef.index += 1; return v }
22
+ const readByte = () => { checkEOS(1); return next() }
23
+ const readBytes = (n) => { checkEOS(n); const v = buffer.slice(indexRef.index, indexRef.index + n); indexRef.index += n; return v }
24
+ const readStringFromChars = (n) => readBytes(n).toString('utf-8')
25
+
26
+ const readInt = (n, le = false) => {
27
+ checkEOS(n)
28
+ let val = 0
29
+ for (let i = 0; i < n; i++) val |= next() << ((le ? i : n - 1 - i) * 8)
30
+ return val
31
+ }
32
+
33
+ const readInt20 = () => { checkEOS(3); return ((next() & 15) << 16) | (next() << 8) | next() }
34
+
35
+ const unpackHex = (v) => {
36
+ if (v >= 0 && v < 16) return v < 10 ? '0'.charCodeAt(0) + v : 'A'.charCodeAt(0) + v - 10
37
+ throw new Error('invalid hex: ' + v)
38
+ }
39
+
40
+ const unpackNibble = (v) => {
41
+ if (v >= 0 && v <= 9) return '0'.charCodeAt(0) + v
42
+ if (v === 10) return '-'.charCodeAt(0)
43
+ if (v === 11) return '.'.charCodeAt(0)
44
+ if (v === 15) return '\0'.charCodeAt(0)
45
+ throw new Error('invalid nibble: ' + v)
46
+ }
47
+
48
+ const unpackByte = (tag, v) => {
49
+ if (tag === TAGS.NIBBLE_8) return unpackNibble(v)
50
+ if (tag === TAGS.HEX_8) return unpackHex(v)
51
+ throw new Error('unknown tag: ' + tag)
52
+ }
53
+
54
+ const readPacked8 = (tag) => {
55
+ const startByte = readByte()
56
+ let value = ''
57
+ for (let i = 0; i < (startByte & 127); i++) {
58
+ const cur = readByte()
59
+ value += String.fromCharCode(unpackByte(tag, (cur & 0xf0) >> 4))
60
+ value += String.fromCharCode(unpackByte(tag, cur & 0x0f))
61
+ }
62
+ if (startByte >> 7 !== 0) value = value.slice(0, -1)
63
+ return value
64
+ }
65
+
66
+ const isListTag = (tag) => tag === TAGS.LIST_EMPTY || tag === TAGS.LIST_8 || tag === TAGS.LIST_16
67
+
68
+ const readListSize = (tag) => {
69
+ switch (tag) {
70
+ case TAGS.LIST_EMPTY: return 0
71
+ case TAGS.LIST_8: return readByte()
72
+ case TAGS.LIST_16: return readInt(2)
73
+ default: throw new Error('invalid tag for list size: ' + tag)
74
+ }
75
+ }
76
+
77
+ const readJidPair = () => {
78
+ const i = readString(readByte())
79
+ const j = readString(readByte())
80
+ if (j) return (i || '') + '@' + j
81
+ throw new Error('invalid jid pair: ' + i + ', ' + j)
82
+ }
83
+
84
+ const readAdJid = () => {
85
+ const domainType = Number(readByte())
86
+ const device = readByte()
87
+ const user = readString(readByte())
88
+ const server =
89
+ domainType === WAJIDDomains.LID ? 'lid' :
90
+ domainType === WAJIDDomains.HOSTED ? 'hosted' :
91
+ domainType === WAJIDDomains.HOSTED_LID ? 'hosted.lid' :
92
+ 's.whatsapp.net'
93
+ return jidEncode(user, server, device)
94
+ }
95
+
96
+ const getTokenDouble = (i1, i2) => {
97
+ const dict = DOUBLE_BYTE_TOKENS[i1]
98
+ if (!dict) throw new Error(`invalid double token dict (${i1})`)
99
+ const val = dict[i2]
100
+ if (val === undefined) throw new Error(`invalid double token (${i2})`)
101
+ return val
102
+ }
103
+
104
+ const readString = (tag) => {
105
+ if (tag >= 1 && tag < SINGLE_BYTE_TOKENS.length) return SINGLE_BYTE_TOKENS[tag] ?? ''
106
+ switch (tag) {
107
+ case TAGS.DICTIONARY_0:
108
+ case TAGS.DICTIONARY_1:
109
+ case TAGS.DICTIONARY_2:
110
+ case TAGS.DICTIONARY_3: return getTokenDouble(tag - TAGS.DICTIONARY_0, readByte())
111
+ case TAGS.LIST_EMPTY: return ''
112
+ case TAGS.BINARY_8: return readStringFromChars(readByte())
113
+ case TAGS.BINARY_20: return readStringFromChars(readInt20())
114
+ case TAGS.BINARY_32: return readStringFromChars(readInt(4))
115
+ case TAGS.JID_PAIR: return readJidPair()
116
+ case TAGS.AD_JID: return readAdJid()
117
+ case TAGS.HEX_8:
118
+ case TAGS.NIBBLE_8: return readPacked8(tag)
119
+ default: throw new Error('invalid string with tag: ' + tag)
120
+ }
121
+ }
122
+
123
+ const readList = (tag) => {
124
+ const size = readListSize(tag)
125
+ const items = []
126
+ for (let i = 0; i < size; i++) items.push(decodeDecompressedBinaryNode(buffer, opts, indexRef))
127
+ return items
128
+ }
129
+
130
+ const listSize = readListSize(readByte())
131
+ const header = readString(readByte())
132
+ if (!listSize || !header.length) throw new Error('invalid node')
133
+
134
+ const attrs = {}
135
+ const attributesLength = (listSize - 1) >> 1
136
+ for (let i = 0; i < attributesLength; i++) attrs[readString(readByte())] = readString(readByte())
137
+
138
+ let data
139
+ if (listSize % 2 === 0) {
140
+ const tag = readByte()
141
+ data = isListTag(tag) ? readList(tag) : (() => {
142
+ switch (tag) {
143
+ case TAGS.BINARY_8: return readBytes(readByte())
144
+ case TAGS.BINARY_20: return readBytes(readInt20())
145
+ case TAGS.BINARY_32: return readBytes(readInt(4))
146
+ default: return readString(tag)
147
+ }
148
+ })()
149
+ }
150
+
151
+ return { tag: header, attrs, content: data }
152
152
  }
@@ -1,140 +1,140 @@
1
- import * as constants from './constants.js'
2
- import { jidDecode } from './jid-utils.js'
3
-
4
- export const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
5
- encodeBinaryNodeInner(node, opts, buffer)
6
- return Buffer.from(buffer)
7
- }
8
-
9
- const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
10
- const { TAGS, TOKEN_MAP } = opts
11
-
12
- const pushByte = (v) => buffer.push(v & 0xff)
13
- const pushBytes = (bytes) => {
14
- if (bytes.length > 1000) { for (let i = 0; i < bytes.length; i++) buffer.push(bytes[i]) }
15
- else buffer.push(...bytes)
16
- }
17
- const pushInt = (v, n, le = false) => {
18
- for (let i = 0; i < n; i++) buffer.push((v >> ((le ? i : n - 1 - i) * 8)) & 0xff)
19
- }
20
- const pushInt16 = (v) => pushBytes([(v >> 8) & 0xff, v & 0xff])
21
- const pushInt20 = (v) => pushBytes([(v >> 16) & 0x0f, (v >> 8) & 0xff, v & 0xff])
22
-
23
- const writeByteLength = (length) => {
24
- if (length >= 4294967296) throw new Error('string too large to encode: ' + length)
25
- if (length >= 1 << 20) { pushByte(TAGS.BINARY_32); pushInt(length, 4) }
26
- else if (length >= 256) { pushByte(TAGS.BINARY_20); pushInt20(length) }
27
- else { pushByte(TAGS.BINARY_8); pushByte(length) }
28
- }
29
-
30
- const writeStringRaw = (str) => {
31
- const bytes = Buffer.from(str, 'utf-8')
32
- writeByteLength(bytes.length)
33
- pushBytes(bytes)
34
- }
35
-
36
- const writeJid = ({ domainType, device, user, server }) => {
37
- if (device !== undefined) {
38
- pushByte(TAGS.AD_JID)
39
- pushByte(domainType || 0)
40
- pushByte(device || 0)
41
- writeString(user)
42
- } else {
43
- pushByte(TAGS.JID_PAIR)
44
- if (user.length) writeString(user)
45
- else pushByte(TAGS.LIST_EMPTY)
46
- writeString(server)
47
- }
48
- }
49
-
50
- const packNibble = (char) => {
51
- if (char >= '0' && char <= '9') return char.charCodeAt(0) - 48
52
- if (char === '-') return 10
53
- if (char === '.') return 11
54
- if (char === '\0') return 15
55
- throw new Error(`invalid byte for nibble "${char}"`)
56
- }
57
-
58
- const packHex = (char) => {
59
- if (char >= '0' && char <= '9') return char.charCodeAt(0) - 48
60
- if (char >= 'A' && char <= 'F') return 10 + char.charCodeAt(0) - 65
61
- if (char >= 'a' && char <= 'f') return 10 + char.charCodeAt(0) - 97
62
- if (char === '\0') return 15
63
- throw new Error(`invalid hex char "${char}"`)
64
- }
65
-
66
- const writePackedBytes = (str, type) => {
67
- if (str.length > TAGS.PACKED_MAX) throw new Error('too many bytes to pack')
68
- pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
69
- const odd = str.length % 2 !== 0
70
- pushByte(odd ? (Math.ceil(str.length / 2) | 128) : Math.ceil(str.length / 2))
71
- const pack = type === 'nibble' ? packNibble : packHex
72
- for (let i = 0; i < Math.floor(str.length / 2); i++)
73
- buffer.push((pack(str[2 * i]) << 4) | pack(str[2 * i + 1]))
74
- if (odd) buffer.push((pack(str[str.length - 1]) << 4) | pack('\x00'))
75
- }
76
-
77
- const isNibble = (str) => {
78
- if (!str || str.length > TAGS.PACKED_MAX) return false
79
- for (const c of str) if (!(c >= '0' && c <= '9') && c !== '-' && c !== '.') return false
80
- return true
81
- }
82
-
83
- const isHex = (str) => {
84
- if (!str || str.length > TAGS.PACKED_MAX) return false
85
- for (const c of str) if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'F')) return false
86
- return true
87
- }
88
-
89
- const writeString = (str) => {
90
- if (str == null) { pushByte(TAGS.LIST_EMPTY); return }
91
- const tokenIndex = TOKEN_MAP[str]
92
- if (tokenIndex) {
93
- if (typeof tokenIndex.dict === 'number') pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
94
- pushByte(tokenIndex.index)
95
- } else if (isNibble(str)) {
96
- writePackedBytes(str, 'nibble')
97
- } else if (isHex(str)) {
98
- writePackedBytes(str, 'hex')
99
- } else if (str) {
100
- const decoded = jidDecode(str)
101
- if (decoded) writeJid(decoded)
102
- else writeStringRaw(str)
103
- }
104
- }
105
-
106
- const writeListStart = (size) => {
107
- if (size === 0) pushByte(TAGS.LIST_EMPTY)
108
- else if (size < 256) pushBytes([TAGS.LIST_8, size])
109
- else { pushByte(TAGS.LIST_16); pushInt16(size) }
110
- }
111
-
112
- if (!tag) throw new Error('invalid node: tag cannot be undefined')
113
-
114
- const validAttrs = Object.keys(attrs || {}).filter(k => attrs[k] != null)
115
- writeListStart(2 * validAttrs.length + 1 + (content !== undefined ? 1 : 0))
116
- writeString(tag)
117
-
118
- for (const key of validAttrs) {
119
- if (typeof attrs[key] === 'string') { writeString(key); writeString(attrs[key]) }
120
- }
121
-
122
- if (typeof content === 'string') {
123
- writeString(content)
124
- } else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
125
- writeByteLength(content.length)
126
- // large buffers overflow spread operator stack; push manually above threshold
127
- if (content.length > 10_000_000) {
128
- pushBytes([...content.slice(0, Math.min(1000, content.length))])
129
- for (let i = 1000; i < content.length; i++) buffer.push(content[i])
130
- } else {
131
- pushBytes(content)
132
- }
133
- } else if (Array.isArray(content)) {
134
- const valid = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string'))
135
- writeListStart(valid.length)
136
- for (const item of valid) encodeBinaryNodeInner(item, opts, buffer)
137
- } else if (content !== undefined) {
138
- throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
139
- }
1
+ import * as constants from './constants.js'
2
+ import { jidDecode } from './jid-utils.js'
3
+
4
+ export const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
5
+ encodeBinaryNodeInner(node, opts, buffer)
6
+ return Buffer.from(buffer)
7
+ }
8
+
9
+ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
10
+ const { TAGS, TOKEN_MAP } = opts
11
+
12
+ const pushByte = (v) => buffer.push(v & 0xff)
13
+ const pushBytes = (bytes) => {
14
+ if (bytes.length > 1000) { for (let i = 0; i < bytes.length; i++) buffer.push(bytes[i]) }
15
+ else buffer.push(...bytes)
16
+ }
17
+ const pushInt = (v, n, le = false) => {
18
+ for (let i = 0; i < n; i++) buffer.push((v >> ((le ? i : n - 1 - i) * 8)) & 0xff)
19
+ }
20
+ const pushInt16 = (v) => pushBytes([(v >> 8) & 0xff, v & 0xff])
21
+ const pushInt20 = (v) => pushBytes([(v >> 16) & 0x0f, (v >> 8) & 0xff, v & 0xff])
22
+
23
+ const writeByteLength = (length) => {
24
+ if (length >= 4294967296) throw new Error('string too large to encode: ' + length)
25
+ if (length >= 1 << 20) { pushByte(TAGS.BINARY_32); pushInt(length, 4) }
26
+ else if (length >= 256) { pushByte(TAGS.BINARY_20); pushInt20(length) }
27
+ else { pushByte(TAGS.BINARY_8); pushByte(length) }
28
+ }
29
+
30
+ const writeStringRaw = (str) => {
31
+ const bytes = Buffer.from(str, 'utf-8')
32
+ writeByteLength(bytes.length)
33
+ pushBytes(bytes)
34
+ }
35
+
36
+ const writeJid = ({ domainType, device, user, server }) => {
37
+ if (device !== undefined) {
38
+ pushByte(TAGS.AD_JID)
39
+ pushByte(domainType || 0)
40
+ pushByte(device || 0)
41
+ writeString(user)
42
+ } else {
43
+ pushByte(TAGS.JID_PAIR)
44
+ if (user.length) writeString(user)
45
+ else pushByte(TAGS.LIST_EMPTY)
46
+ writeString(server)
47
+ }
48
+ }
49
+
50
+ const packNibble = (char) => {
51
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - 48
52
+ if (char === '-') return 10
53
+ if (char === '.') return 11
54
+ if (char === '\0') return 15
55
+ throw new Error(`invalid byte for nibble "${char}"`)
56
+ }
57
+
58
+ const packHex = (char) => {
59
+ if (char >= '0' && char <= '9') return char.charCodeAt(0) - 48
60
+ if (char >= 'A' && char <= 'F') return 10 + char.charCodeAt(0) - 65
61
+ if (char >= 'a' && char <= 'f') return 10 + char.charCodeAt(0) - 97
62
+ if (char === '\0') return 15
63
+ throw new Error(`invalid hex char "${char}"`)
64
+ }
65
+
66
+ const writePackedBytes = (str, type) => {
67
+ if (str.length > TAGS.PACKED_MAX) throw new Error('too many bytes to pack')
68
+ pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
69
+ const odd = str.length % 2 !== 0
70
+ pushByte(odd ? (Math.ceil(str.length / 2) | 128) : Math.ceil(str.length / 2))
71
+ const pack = type === 'nibble' ? packNibble : packHex
72
+ for (let i = 0; i < Math.floor(str.length / 2); i++)
73
+ buffer.push((pack(str[2 * i]) << 4) | pack(str[2 * i + 1]))
74
+ if (odd) buffer.push((pack(str[str.length - 1]) << 4) | pack('\x00'))
75
+ }
76
+
77
+ const isNibble = (str) => {
78
+ if (!str || str.length > TAGS.PACKED_MAX) return false
79
+ for (const c of str) if (!(c >= '0' && c <= '9') && c !== '-' && c !== '.') return false
80
+ return true
81
+ }
82
+
83
+ const isHex = (str) => {
84
+ if (!str || str.length > TAGS.PACKED_MAX) return false
85
+ for (const c of str) if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'F')) return false
86
+ return true
87
+ }
88
+
89
+ const writeString = (str) => {
90
+ if (str == null) { pushByte(TAGS.LIST_EMPTY); return }
91
+ const tokenIndex = TOKEN_MAP[str]
92
+ if (tokenIndex) {
93
+ if (typeof tokenIndex.dict === 'number') pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
94
+ pushByte(tokenIndex.index)
95
+ } else if (isNibble(str)) {
96
+ writePackedBytes(str, 'nibble')
97
+ } else if (isHex(str)) {
98
+ writePackedBytes(str, 'hex')
99
+ } else if (str) {
100
+ const decoded = jidDecode(str)
101
+ if (decoded) writeJid(decoded)
102
+ else writeStringRaw(str)
103
+ }
104
+ }
105
+
106
+ const writeListStart = (size) => {
107
+ if (size === 0) pushByte(TAGS.LIST_EMPTY)
108
+ else if (size < 256) pushBytes([TAGS.LIST_8, size])
109
+ else { pushByte(TAGS.LIST_16); pushInt16(size) }
110
+ }
111
+
112
+ if (!tag) throw new Error('invalid node: tag cannot be undefined')
113
+
114
+ const validAttrs = Object.keys(attrs || {}).filter(k => attrs[k] != null)
115
+ writeListStart(2 * validAttrs.length + 1 + (content !== undefined ? 1 : 0))
116
+ writeString(tag)
117
+
118
+ for (const key of validAttrs) {
119
+ if (typeof attrs[key] === 'string') { writeString(key); writeString(attrs[key]) }
120
+ }
121
+
122
+ if (typeof content === 'string') {
123
+ writeString(content)
124
+ } else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
125
+ writeByteLength(content.length)
126
+ // large buffers overflow spread operator stack; push manually above threshold
127
+ if (content.length > 10_000_000) {
128
+ pushBytes([...content.slice(0, Math.min(1000, content.length))])
129
+ for (let i = 1000; i < content.length; i++) buffer.push(content[i])
130
+ } else {
131
+ pushBytes(content)
132
+ }
133
+ } else if (Array.isArray(content)) {
134
+ const valid = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string'))
135
+ writeListStart(valid.length)
136
+ for (const item of valid) encodeBinaryNodeInner(item, opts, buffer)
137
+ } else if (content !== undefined) {
138
+ throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
139
+ }
140
140
  }