@zetagoaurum-socket/wasocket 3.1.0 → 3.2.7

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 (96) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +81 -60
  3. package/WAProto/index.js +56886 -17506
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +1 -1
  6. package/lib/Defaults/index.js +50 -9
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +64 -0
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +34 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +69 -0
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +51 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +53 -0
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  33. package/lib/Signal/libsignal.js +51 -29
  34. package/lib/Socket/business.d.ts +3 -2
  35. package/lib/Socket/chats.d.ts +215 -28
  36. package/lib/Socket/chats.js +185 -70
  37. package/lib/Socket/chats.js.bak +981 -0
  38. package/lib/Socket/dugong.d.ts +254 -0
  39. package/lib/Socket/dugong.js +432 -141
  40. package/lib/Socket/groups.js +20 -23
  41. package/lib/Socket/index.js +2 -15
  42. package/lib/Socket/messages-recv.d.ts +56 -55
  43. package/lib/Socket/messages-recv.js +370 -112
  44. package/lib/Socket/messages-send.d.ts +3 -2
  45. package/lib/Socket/messages-send.js +464 -377
  46. package/lib/Socket/newsletter.js +175 -28
  47. package/lib/Socket/socket.js +204 -176
  48. package/lib/Socket/usync.d.ts +3 -3
  49. package/lib/Types/GroupMetadata.d.ts +1 -0
  50. package/lib/Types/Newsletter.d.ts +97 -86
  51. package/lib/Types/Newsletter.js +38 -32
  52. package/lib/Types/USync.d.ts +25 -0
  53. package/lib/Types/USync.js +2 -0
  54. package/lib/Utils/anti-crash.js +20 -0
  55. package/lib/Utils/auto-contact.js +74 -0
  56. package/lib/Utils/chat-utils.js +17 -3
  57. package/lib/Utils/generics.js +68 -31
  58. package/lib/Utils/generics.js.bak +433 -0
  59. package/lib/Utils/history.js +6 -1
  60. package/lib/Utils/index.js +0 -1
  61. package/lib/Utils/link-preview.js +4 -2
  62. package/lib/Utils/messages-media.js +145 -57
  63. package/lib/Utils/messages.js +89 -305
  64. package/lib/Utils/signal.js +48 -46
  65. package/lib/Utils/use-multi-file-auth-state.js +45 -6
  66. package/lib/Utils/validate-connection.js +91 -65
  67. package/lib/Utils/validate-connection.js.bak +237 -0
  68. package/lib/WABinary/constants.d.ts +27 -24
  69. package/lib/WABinary/encode.js +160 -123
  70. package/lib/WABinary/generic-utils.d.ts +2 -0
  71. package/lib/WABinary/generic-utils.js +124 -36
  72. package/lib/WABinary/jid-utils.js +5 -26
  73. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  74. package/lib/index.d.ts +1 -0
  75. package/lib/index.js +9 -0
  76. package/package.json +105 -100
  77. package/WAProto/GenerateStatics.sh +0 -4
  78. package/WAProto/WAProto.proto +0 -3344
  79. package/WAProto/index.d.ts +0 -37016
  80. package/WASignalGroup/GroupProtocol.js +0 -1697
  81. package/WASignalGroup/ciphertext_message.js +0 -16
  82. package/WASignalGroup/group_cipher.js +0 -120
  83. package/WASignalGroup/group_session_builder.js +0 -46
  84. package/WASignalGroup/index.js +0 -5
  85. package/WASignalGroup/keyhelper.js +0 -21
  86. package/WASignalGroup/protobufs.js +0 -3
  87. package/WASignalGroup/queue_job.js +0 -69
  88. package/WASignalGroup/sender_chain_key.js +0 -50
  89. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  90. package/WASignalGroup/sender_key_message.js +0 -92
  91. package/WASignalGroup/sender_key_name.js +0 -70
  92. package/WASignalGroup/sender_key_record.js +0 -56
  93. package/WASignalGroup/sender_key_state.js +0 -129
  94. package/lib/Utils/rate-limiter.js +0 -55
  95. package/lib/WAUSync/Fall +0 -1
  96. package/lib/WAUSync/Protocols/Fal +0 -1
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeSignedDeviceIdentity = exports.configureSuccessfulPairing = exports.generateRegistrationNode = exports.generateLoginNode = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const crypto_1 = require("crypto");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Defaults_1 = require("../Defaults");
8
+ const WABinary_1 = require("../WABinary");
9
+ const crypto_2 = require("./crypto");
10
+ const generics_1 = require("./generics");
11
+ const signal_1 = require("./signal");
12
+
13
+ const getUserAgent = (config) => {
14
+ return {
15
+ appVersion: {
16
+ primary: config.version[0],
17
+ secondary: config.version[1],
18
+ tertiary: config.version[2],
19
+ },
20
+ platform: WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB,
21
+ releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
22
+ osVersion: '0.1',
23
+ device: 'Desktop',
24
+ osBuildNumber: '0.1',
25
+ localeLanguageIso6391: 'en',
26
+ mnc: '000',
27
+ mcc: '000',
28
+ localeCountryIso31661Alpha2: config.countryCode || 'US'
29
+ };
30
+ };
31
+
32
+ exports.Browsers = {
33
+ iOS: (browser) => ["ios", browser, "18.2"],
34
+ ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
35
+ macOS: (browser) => ['Mac OS', browser, '14.4.1'],
36
+ baileys: (browser) => ['Baileys', browser, '6.5.0'],
37
+ windows: (browser) => ['Windows', browser, '10.0.22631']
38
+ };
39
+
40
+ const PLATFORM_MAP = {
41
+ 'Mac OS': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
42
+ 'Windows': WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
43
+ };
44
+
45
+ const getWebInfo = (config) => {
46
+ let webSubPlatform = WAProto_1.proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
47
+ if (config.syncFullHistory && PLATFORM_MAP[config.browser[0]] && config.browser[1] === 'Desktop') {
48
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
49
+ }
50
+ return { webSubPlatform };
51
+ };
52
+
53
+ const getClientPayload = (config) => {
54
+ const payload = {
55
+ connectType: WAProto_1.proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
56
+ connectReason: WAProto_1.proto.ClientPayload.ConnectReason.USER_ACTIVATED,
57
+ userAgent: getUserAgent(config),
58
+ };
59
+ payload.webInfo = getWebInfo(config);
60
+ return payload;
61
+ };
62
+
63
+ const generateLoginNode = (userJid, config) => {
64
+ const { user, device } = (0, WABinary_1.jidDecode)(userJid);
65
+ const payload = {
66
+ ...getClientPayload(config),
67
+ passive: true,
68
+ pull: true,
69
+ username: +user,
70
+ device: device,
71
+ lidDbMigrated: false
72
+ };
73
+ return WAProto_1.proto.ClientPayload.fromObject(payload);
74
+ };
75
+ exports.generateLoginNode = generateLoginNode;
76
+
77
+ const getPlatformType = (platform) => {
78
+ const platformType = platform.toUpperCase();
79
+ return WAProto_1.proto.DeviceProps.PlatformType[platformType] || WAProto_1.proto.DeviceProps.PlatformType.CHROME;
80
+ };
81
+
82
+ const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
83
+ const appVersionBuf = (0, crypto_1.createHash)('md5')
84
+ .update(config.version.join('.'))
85
+ .digest();
86
+
87
+ const companion = {
88
+ os: config.browser[0],
89
+ platformType: getPlatformType(config.browser[1]),
90
+ requireFullSync: config.syncFullHistory,
91
+ historySyncConfig: {
92
+ storageQuotaMb: 10240,
93
+ inlineInitialPayloadInE2EeMsg: true,
94
+ recentSyncDaysLimit: undefined,
95
+ supportCallLogHistory: false,
96
+ supportBotUserAgentChatHistory: true,
97
+ supportCagReactionsAndPolls: true,
98
+ supportBizHostedMsg: true,
99
+ supportRecentSyncChunkMessageCountTuning: true,
100
+ supportHostedGroupMsg: true,
101
+ supportFbidBotChatHistory: true,
102
+ supportAddOnHistorySyncMigration: undefined,
103
+ supportMessageAssociation: true,
104
+ supportGroupHistory: false,
105
+ onDemandReady: undefined,
106
+ supportGuestChat: undefined
107
+ },
108
+ version: {
109
+ primary: 10,
110
+ secondary: 15,
111
+ tertiary: 7
112
+ }
113
+ };
114
+
115
+ const companionProto = WAProto_1.proto.DeviceProps.encode(companion).finish();
116
+
117
+ const registerPayload = {
118
+ ...getClientPayload(config),
119
+ passive: false,
120
+ pull: false,
121
+ devicePairingData: {
122
+ buildHash: appVersionBuf,
123
+ deviceProps: companionProto,
124
+ eRegid: (0, generics_1.encodeBigEndian)(registrationId),
125
+ eKeytype: Defaults_1.KEY_BUNDLE_TYPE,
126
+ eIdent: signedIdentityKey.public,
127
+ eSkeyId: (0, generics_1.encodeBigEndian)(signedPreKey.keyId, 3),
128
+ eSkeyVal: signedPreKey.keyPair.public,
129
+ eSkeySig: signedPreKey.signature,
130
+ },
131
+ };
132
+ return WAProto_1.proto.ClientPayload.fromObject(registerPayload);
133
+ };
134
+ exports.generateRegistrationNode = generateRegistrationNode;
135
+
136
+ const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
137
+ const msgId = stanza.attrs.id;
138
+ const pairSuccessNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-success');
139
+ const deviceIdentityNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device-identity');
140
+ const platformNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'platform');
141
+ const deviceNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'device');
142
+ const businessNode = (0, WABinary_1.getBinaryNodeChild)(pairSuccessNode, 'biz');
143
+
144
+ if (!deviceIdentityNode || !deviceNode) {
145
+ throw new boom_1.Boom('Missing device-identity or device in pair success node', { data: stanza });
146
+ }
147
+
148
+ const bizName = businessNode?.attrs.name;
149
+ const jid = deviceNode.attrs.jid;
150
+ const lid = deviceNode.attrs.lid;
151
+
152
+ const { details, hmac, accountType } = WAProto_1.proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
153
+
154
+ let hmacPrefix = Buffer.from([]);
155
+ if (accountType !== undefined && accountType === WAProto_1.proto.ADVEncryptionType.HOSTED) {
156
+ hmacPrefix = Buffer.from([0x06, 0x05]);
157
+ }
158
+
159
+ const advSign = (0, crypto_2.hmacSign)(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
160
+ if (Buffer.compare(hmac, advSign) !== 0) {
161
+ throw new boom_1.Boom('Invalid account signature');
162
+ }
163
+
164
+ const account = WAProto_1.proto.ADVSignedDeviceIdentity.decode(details);
165
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
166
+
167
+ const deviceIdentity = WAProto_1.proto.ADVDeviceIdentity.decode(deviceDetails);
168
+
169
+ const accountSignaturePrefix = deviceIdentity.deviceType === WAProto_1.proto.ADVEncryptionType.HOSTED
170
+ ? Buffer.from([0x06, 0x05])
171
+ : Buffer.from([0x06, 0x00]);
172
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
173
+
174
+ if (!crypto_2.Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
175
+ throw new boom_1.Boom('Failed to verify account signature');
176
+ }
177
+
178
+ const deviceMsg = Buffer.concat([
179
+ Buffer.from([0x06, 0x01]),
180
+ deviceDetails,
181
+ signedIdentityKey.public,
182
+ accountSignatureKey
183
+ ]);
184
+ account.deviceSignature = crypto_2.Curve.sign(signedIdentityKey.private, deviceMsg);
185
+
186
+ const identity = (0, signal_1.createSignalIdentity)(jid, accountSignatureKey);
187
+ const accountEnc = (0, exports.encodeSignedDeviceIdentity)(account, false);
188
+
189
+ const reply = {
190
+ tag: 'iq',
191
+ attrs: {
192
+ to: WABinary_1.S_WHATSAPP_NET,
193
+ type: 'result',
194
+ id: msgId,
195
+ },
196
+ content: [
197
+ {
198
+ tag: 'pair-device-sign',
199
+ attrs: {},
200
+ content: [
201
+ {
202
+ tag: 'device-identity',
203
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
204
+ content: accountEnc
205
+ }
206
+ ]
207
+ }
208
+ ]
209
+ };
210
+
211
+ const authUpdate = {
212
+ account,
213
+ me: { id: jid, name: bizName, lid },
214
+ signalIdentities: [
215
+ ...(signalIdentities || []),
216
+ identity
217
+ ],
218
+ platform: platformNode?.attrs.name
219
+ };
220
+
221
+ return {
222
+ creds: authUpdate,
223
+ reply
224
+ };
225
+ };
226
+ exports.configureSuccessfulPairing = configureSuccessfulPairing;
227
+
228
+ const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
229
+ account = { ...account };
230
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
231
+ account.accountSignatureKey = null;
232
+ }
233
+ return WAProto_1.proto.ADVSignedDeviceIdentity
234
+ .encode(account)
235
+ .finish();
236
+ };
237
+ exports.encodeSignedDeviceIdentity = encodeSignedDeviceIdentity;
@@ -1,27 +1,30 @@
1
1
  export declare const TAGS: {
2
- LIST_EMPTY: number;
3
- DICTIONARY_0: number;
4
- DICTIONARY_1: number;
5
- DICTIONARY_2: number;
6
- DICTIONARY_3: number;
7
- AD_JID: number;
8
- LIST_8: number;
9
- LIST_16: number;
10
- JID_PAIR: number;
11
- HEX_8: number;
12
- BINARY_8: number;
13
- BINARY_20: number;
14
- BINARY_32: number;
15
- NIBBLE_8: number;
16
- PACKED_MAX: number;
17
- SINGLE_BYTE_MAX: number;
18
- STREAM_END: number;
19
- };
20
- export declare const DOUBLE_BYTE_TOKENS: string[][];
21
- export declare const SINGLE_BYTE_TOKENS: (string | null)[];
2
+ LIST_EMPTY: number
3
+ DICTIONARY_0: number
4
+ DICTIONARY_1: number
5
+ DICTIONARY_2: number
6
+ DICTIONARY_3: number
7
+ INTEROP_JID: number
8
+ FB_JID: number
9
+ AD_JID: number
10
+ LIST_8: number
11
+ LIST_16: number
12
+ JID_PAIR: number
13
+ HEX_8: number
14
+ BINARY_8: number
15
+ BINARY_20: number
16
+ BINARY_32: number
17
+ NIBBLE_8: number
18
+ PACKED_MAX: number
19
+ }
20
+
21
+ export declare const DOUBLE_BYTE_TOKENS: string[][]
22
+
23
+ export declare const SINGLE_BYTE_TOKENS: (string | null)[]
24
+
22
25
  export declare const TOKEN_MAP: {
23
26
  [token: string]: {
24
- dict?: number;
25
- index: number;
26
- };
27
- };
27
+ dict?: number
28
+ index: number
29
+ }
30
+ }
@@ -1,228 +1,265 @@
1
- "use strict";
1
+ "use strict"
2
+
2
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
5
6
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
+ desc = { enumerable: true, get: function() { return m[k] } }
7
8
  }
8
- Object.defineProperty(o, k2, desc);
9
+ Object.defineProperty(o, k2, desc)
9
10
  }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
13
+ }))
14
+
13
15
  var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v })
15
17
  }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
+ o["default"] = v
19
+ })
20
+
18
21
  var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.encodeBinaryNode = void 0;
27
- const constants = __importStar(require("./constants"));
28
- const jid_utils_1 = require("./jid-utils");
29
- const encodeBinaryNode = ({ tag, attrs, content }, opts = constants, buffer = [0]) => {
30
- const { TAGS, TOKEN_MAP } = opts;
31
- const pushByte = (value) => buffer.push(value & 0xff);
22
+ if (mod && mod.__esModule) return mod
23
+ var result = {}
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
25
+ __setModuleDefault(result, mod)
26
+ return result
27
+ }
28
+
29
+ Object.defineProperty(exports, "__esModule", { value: true })
30
+
31
+ const constants = __importStar(require("./constants"))
32
+ const jid_utils_1 = require("./jid-utils")
33
+
34
+ const encodeBinaryNode = (node, opts = constants, buffer = [0]) => {
35
+ const encoded = encodeBinaryNodeInner(node, opts, buffer)
36
+ return Buffer.from(encoded)
37
+ }
38
+
39
+ const encodeBinaryNodeInner = ({ tag, attrs, content }, opts, buffer) => {
40
+ const { TAGS, TOKEN_MAP } = opts
41
+ const pushByte = (value) => buffer.push(value & 0xff)
32
42
  const pushInt = (value, n, littleEndian = false) => {
33
43
  for (let i = 0; i < n; i++) {
34
- const curShift = littleEndian ? i : n - 1 - i;
35
- buffer.push((value >> (curShift * 8)) & 0xff);
44
+ const curShift = littleEndian ? i : n - 1 - i
45
+ buffer.push((value >> (curShift * 8)) & 0xff)
36
46
  }
37
- };
38
- const pushBytes = (bytes) => (bytes.forEach(b => buffer.push(b)));
47
+ }
48
+
49
+ const pushBytes = (bytes) => {
50
+ for (const b of bytes) {
51
+ buffer.push(b)
52
+ }
53
+ }
54
+
39
55
  const pushInt16 = (value) => {
40
- pushBytes([(value >> 8) & 0xff, value & 0xff]);
41
- };
42
- const pushInt20 = (value) => (pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff]));
56
+ pushBytes([(value >> 8) & 0xff, value & 0xff])
57
+ }
58
+
59
+ const pushInt20 = (value) => (pushBytes([(value >> 16) & 0x0f, (value >> 8) & 0xff, value & 0xff]))
43
60
  const writeByteLength = (length) => {
44
61
  if (length >= 4294967296) {
45
- throw new Error('string too large to encode: ' + length);
62
+ throw new Error('string too large to encode: ' + length)
46
63
  }
47
64
  if (length >= 1 << 20) {
48
- pushByte(TAGS.BINARY_32);
49
- pushInt(length, 4); // 32 bit integer
65
+ pushByte(TAGS.BINARY_32)
66
+ pushInt(length, 4) // 32 bit integer
50
67
  }
51
68
  else if (length >= 256) {
52
- pushByte(TAGS.BINARY_20);
53
- pushInt20(length);
69
+ pushByte(TAGS.BINARY_20)
70
+ pushInt20(length)
54
71
  }
55
72
  else {
56
- pushByte(TAGS.BINARY_8);
57
- pushByte(length);
73
+ pushByte(TAGS.BINARY_8)
74
+ pushByte(length)
58
75
  }
59
- };
76
+ }
77
+
60
78
  const writeStringRaw = (str) => {
61
- const bytes = Buffer.from(str, 'utf-8');
62
- writeByteLength(bytes.length);
63
- pushBytes(bytes);
64
- };
79
+ const bytes = Buffer.from(str, 'utf-8')
80
+ writeByteLength(bytes.length)
81
+ pushBytes(bytes)
82
+ }
83
+
65
84
  const writeJid = ({ domainType, device, user, server }) => {
66
85
  if (typeof device !== 'undefined') {
67
- pushByte(TAGS.AD_JID);
68
- pushByte(domainType || 0);
69
- pushByte(device || 0);
70
- writeString(user);
86
+ pushByte(TAGS.AD_JID)
87
+ pushByte(domainType || 0)
88
+ pushByte(device || 0)
89
+ writeString(user)
71
90
  }
72
91
  else {
73
- pushByte(TAGS.JID_PAIR);
92
+ pushByte(TAGS.JID_PAIR)
74
93
  if (user.length) {
75
- writeString(user);
94
+ writeString(user)
76
95
  }
77
96
  else {
78
- pushByte(TAGS.LIST_EMPTY);
97
+ pushByte(TAGS.LIST_EMPTY)
79
98
  }
80
- writeString(server);
99
+ writeString(server)
81
100
  }
82
- };
101
+ }
102
+
83
103
  const packNibble = (char) => {
84
104
  switch (char) {
85
105
  case '-':
86
- return 10;
106
+ return 10
87
107
  case '.':
88
- return 11;
108
+ return 11
89
109
  case '\0':
90
- return 15;
110
+ return 15
91
111
  default:
92
112
  if (char >= '0' && char <= '9') {
93
- return char.charCodeAt(0) - '0'.charCodeAt(0);
113
+ return char.charCodeAt(0) - '0'.charCodeAt(0)
94
114
  }
95
- throw new Error(`invalid byte for nibble "${char}"`);
115
+ throw new Error(`invalid byte for nibble "${char}"`)
96
116
  }
97
- };
117
+ }
118
+
98
119
  const packHex = (char) => {
99
120
  if (char >= '0' && char <= '9') {
100
- return char.charCodeAt(0) - '0'.charCodeAt(0);
121
+ return char.charCodeAt(0) - '0'.charCodeAt(0)
101
122
  }
102
123
  if (char >= 'A' && char <= 'F') {
103
- return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0);
124
+ return 10 + char.charCodeAt(0) - 'A'.charCodeAt(0)
104
125
  }
105
126
  if (char >= 'a' && char <= 'f') {
106
- return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0);
127
+ return 10 + char.charCodeAt(0) - 'a'.charCodeAt(0)
107
128
  }
108
129
  if (char === '\0') {
109
- return 15;
130
+ return 15
110
131
  }
111
- throw new Error(`Invalid hex char "${char}"`);
112
- };
132
+ throw new Error(`Invalid hex char "${char}"`)
133
+ }
134
+
113
135
  const writePackedBytes = (str, type) => {
114
136
  if (str.length > TAGS.PACKED_MAX) {
115
- throw new Error('Too many bytes to pack');
137
+ throw new Error('Too many bytes to pack')
116
138
  }
117
- pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8);
118
- let roundedLength = Math.ceil(str.length / 2.0);
139
+ pushByte(type === 'nibble' ? TAGS.NIBBLE_8 : TAGS.HEX_8)
140
+ let roundedLength = Math.ceil(str.length / 2.0)
119
141
  if (str.length % 2 !== 0) {
120
- roundedLength |= 128;
142
+ roundedLength |= 128
121
143
  }
122
- pushByte(roundedLength);
123
- const packFunction = type === 'nibble' ? packNibble : packHex;
144
+ pushByte(roundedLength)
145
+ const packFunction = type === 'nibble' ? packNibble : packHex
124
146
  const packBytePair = (v1, v2) => {
125
- const result = (packFunction(v1) << 4) | packFunction(v2);
126
- return result;
127
- };
128
- const strLengthHalf = Math.floor(str.length / 2);
147
+ const result = (packFunction(v1) << 4) | packFunction(v2)
148
+ return result
149
+ }
150
+ const strLengthHalf = Math.floor(str.length / 2)
129
151
  for (let i = 0; i < strLengthHalf; i++) {
130
- pushByte(packBytePair(str[2 * i], str[2 * i + 1]));
152
+ pushByte(packBytePair(str[2 * i], str[2 * i + 1]))
131
153
  }
132
154
  if (str.length % 2 !== 0) {
133
- pushByte(packBytePair(str[str.length - 1], '\x00'));
155
+ pushByte(packBytePair(str[str.length - 1], '\x00'))
134
156
  }
135
- };
157
+ }
158
+
136
159
  const isNibble = (str) => {
137
- if (str.length > TAGS.PACKED_MAX) {
138
- return false;
160
+ if (!str || str.length > TAGS.PACKED_MAX) {
161
+ return false
139
162
  }
140
- for (let i = 0; i < str.length; i++) {
141
- const char = str[i];
142
- const isInNibbleRange = char >= '0' && char <= '9';
163
+ for (const char of str) {
164
+ const isInNibbleRange = char >= '0' && char <= '9'
143
165
  if (!isInNibbleRange && char !== '-' && char !== '.') {
144
- return false;
166
+ return false
145
167
  }
146
168
  }
147
- return true;
148
- };
169
+ return true
170
+ }
171
+
149
172
  const isHex = (str) => {
150
- if (str.length > TAGS.PACKED_MAX) {
151
- return false;
173
+ if (!str || str.length > TAGS.PACKED_MAX) {
174
+ return false
152
175
  }
153
- for (let i = 0; i < str.length; i++) {
154
- const char = str[i];
155
- const isInNibbleRange = char >= '0' && char <= '9';
156
- if (!isInNibbleRange && !(char >= 'A' && char <= 'F') && !(char >= 'a' && char <= 'f')) {
157
- return false;
176
+ for (const char of str) {
177
+ const isInNibbleRange = char >= '0' && char <= '9'
178
+ if (!isInNibbleRange && !(char >= 'A' && char <= 'F')) {
179
+ return false
158
180
  }
159
181
  }
160
- return true;
161
- };
182
+ return true
183
+ }
184
+
162
185
  const writeString = (str) => {
163
- const tokenIndex = TOKEN_MAP[str];
186
+ if (str === undefined || str === null) {
187
+ pushByte(TAGS.LIST_EMPTY)
188
+ return
189
+ }
190
+ const tokenIndex = TOKEN_MAP[str]
164
191
  if (tokenIndex) {
165
192
  if (typeof tokenIndex.dict === 'number') {
166
- pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict);
193
+ pushByte(TAGS.DICTIONARY_0 + tokenIndex.dict)
167
194
  }
168
- pushByte(tokenIndex.index);
195
+ pushByte(tokenIndex.index)
169
196
  }
170
197
  else if (isNibble(str)) {
171
- writePackedBytes(str, 'nibble');
198
+ writePackedBytes(str, 'nibble')
172
199
  }
173
200
  else if (isHex(str)) {
174
- writePackedBytes(str, 'hex');
201
+ writePackedBytes(str, 'hex')
175
202
  }
176
203
  else if (str) {
177
- const decodedJid = (0, jid_utils_1.jidDecode)(str);
204
+ const decodedJid = (0, jid_utils_1.jidDecode)(str)
178
205
  if (decodedJid) {
179
- writeJid(decodedJid);
206
+ writeJid(decodedJid)
180
207
  }
181
208
  else {
182
- writeStringRaw(str);
209
+ writeStringRaw(str)
183
210
  }
184
211
  }
185
- };
212
+ }
213
+
186
214
  const writeListStart = (listSize) => {
187
215
  if (listSize === 0) {
188
- pushByte(TAGS.LIST_EMPTY);
216
+ pushByte(TAGS.LIST_EMPTY)
189
217
  }
190
218
  else if (listSize < 256) {
191
- pushBytes([TAGS.LIST_8, listSize]);
219
+ pushBytes([TAGS.LIST_8, listSize])
192
220
  }
193
221
  else {
194
- pushByte(TAGS.LIST_16);
195
- pushInt16(listSize);
222
+ pushByte(TAGS.LIST_16)
223
+ pushInt16(listSize)
196
224
  }
197
- };
198
- const validAttributes = Object.keys(attrs).filter(k => (typeof attrs[k] !== 'undefined' && attrs[k] !== null));
199
- writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0));
200
- writeString(tag);
225
+ }
226
+
227
+ if (!tag) {
228
+ throw new Error('Invalid node: tag cannot be undefined')
229
+ }
230
+
231
+ const validAttributes = Object.keys(attrs).filter(k => (typeof attrs[k] !== 'undefined' && attrs[k] !== null))
232
+ writeListStart(2 * validAttributes.length + 1 + (typeof content !== 'undefined' ? 1 : 0))
233
+ writeString(tag)
201
234
  for (const key of validAttributes) {
202
235
  if (typeof attrs[key] === 'string') {
203
- writeString(key);
204
- writeString(attrs[key]);
236
+ writeString(key)
237
+ writeString(attrs[key])
205
238
  }
206
239
  }
207
240
  if (typeof content === 'string') {
208
- writeString(content);
241
+ writeString(content)
209
242
  }
210
243
  else if (Buffer.isBuffer(content) || content instanceof Uint8Array) {
211
- writeByteLength(content.length);
212
- pushBytes(content);
244
+ writeByteLength(content.length)
245
+ pushBytes(content)
213
246
  }
214
247
  else if (Array.isArray(content)) {
215
- writeListStart(content.length);
216
- for (const item of content) {
217
- (0, exports.encodeBinaryNode)(item, opts, buffer);
248
+ const validContent = content.filter(item => item && (item.tag || Buffer.isBuffer(item) || item instanceof Uint8Array || typeof item === 'string'))
249
+ writeListStart(validContent.length)
250
+ for (const item of validContent) {
251
+ encodeBinaryNodeInner(item, opts, buffer)
218
252
  }
219
253
  }
220
254
  else if (typeof content === 'undefined') {
221
255
  // do nothing
222
256
  }
223
257
  else {
224
- throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`);
258
+ throw new Error(`invalid children for header "${tag}": ${content} (${typeof content})`)
225
259
  }
226
- return Buffer.from(buffer);
227
- };
228
- exports.encodeBinaryNode = encodeBinaryNode;
260
+ return buffer
261
+ }
262
+
263
+ module.exports = {
264
+ encodeBinaryNode
265
+ }