@jexkcode/baileys 1.2.0 → 1.3.1

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.
@@ -0,0 +1,253 @@
1
+ // JAP@Add --- MockWASocket: offline test harness for WhatsApp bots.
2
+ //
3
+ // Test bot logic without a real WhatsApp account: no network, no ban risk,
4
+ // no phone nearby, fully CI-safe.
5
+ //
6
+ // What this IS: a stand-in for the `sock` object your bot code receives —
7
+ // same event surface (`sock.ev`), same `sendMessage()` signature, producing
8
+ // REAL proto.WebMessageInfo objects via the same generateWAMessage() pipeline
9
+ // the live socket uses. Inject incoming messages, capture outgoing ones,
10
+ // assert on the conversation — fully offline, CI-safe.
11
+ //
12
+ // What this is NOT (honest scope): it does not talk to WhatsApp, does not
13
+ // validate server behaviour (rate limits, session state, encryption), and
14
+ // media messages are built with a stub uploader (fake URLs, real structure).
15
+ //
16
+ // ```js
17
+ // import { createMockSocket } from '@japofc/baileys'
18
+ //
19
+ // const mock = createMockSocket()
20
+ // myBotSetup(mock.sock) // your real bot code, unchanged
21
+ // await mock.receiveText('628@s.whatsapp.net', '!ping')
22
+ // const out = await mock.waitForReply()
23
+ // assert.equal(out.content.text, 'pong! 🏓')
24
+ // ```
25
+ import { EventEmitter } from 'events';
26
+ import { randomBytes } from 'crypto';
27
+ import { generateWAMessage, generateWAMessageFromContent } from './messages.js';
28
+ import { unixTimestampSeconds } from './generics.js';
29
+ const DEFAULT_ME = '628000000000@s.whatsapp.net';
30
+ const genId = () => 'MOCK' + randomBytes(8).toString('hex').toUpperCase();
31
+ // Stub uploader so image/video/etc. content builds offline with real structure.
32
+ const stubUpload = async () => ({
33
+ mediaUrl: 'https://mock.local/media',
34
+ directPath: '/mock/direct-path',
35
+ handle: undefined
36
+ });
37
+ const stubMediaOptions = {
38
+ upload: stubUpload,
39
+ mediaCache: undefined,
40
+ options: {}
41
+ };
42
+ /**
43
+ * Create an offline mock WhatsApp socket for testing bot logic.
44
+ *
45
+ * Options:
46
+ * - `me` own jid (default '628000000000@s.whatsapp.net')
47
+ * - `pushName` own display name for outgoing messages (default 'MockBot')
48
+ * - `autoConnect` emit a connection.update open event on creation (default true)
49
+ */
50
+ export const createMockSocket = (options = {}) => {
51
+ const { me = DEFAULT_ME, pushName = 'MockBot', autoConnect = true } = options;
52
+ const emitter = new EventEmitter();
53
+ emitter.setMaxListeners(0);
54
+ /** Every message "sent" by the bot, in order: { jid, content, options, message } */
55
+ const outbox = [];
56
+ /** Every raw event emitted, in order: { event, data } — full audit trail */
57
+ const eventLog = [];
58
+ /** Read receipts requested via readMessages */
59
+ const readReceipts = [];
60
+ /** Presence updates sent via sendPresenceUpdate */
61
+ const presenceLog = [];
62
+ let connectionState = 'close';
63
+ let waiters = [];
64
+ const ev = {
65
+ on: (event, listener) => { emitter.on(event, listener); return ev; },
66
+ off: (event, listener) => { emitter.off(event, listener); return ev; },
67
+ once: (event, listener) => { emitter.once(event, listener); return ev; },
68
+ removeAllListeners: (event) => { emitter.removeAllListeners(event); return ev; },
69
+ emit: (event, data) => {
70
+ eventLog.push({ event, data });
71
+ return emitter.emit(event, data);
72
+ },
73
+ // parity helpers some consumers use
74
+ process: (handler) => {
75
+ const listener = (map) => handler(map);
76
+ emitter.on('event', listener);
77
+ return () => emitter.off('event', listener);
78
+ },
79
+ buffer: () => { },
80
+ flush: () => false,
81
+ isBuffering: () => false
82
+ };
83
+ const settleWaiters = () => {
84
+ if (!waiters.length || !outbox.length) {
85
+ return;
86
+ }
87
+ const pending = waiters;
88
+ waiters = [];
89
+ for (const w of pending) {
90
+ const idx = outbox.findIndex((entry, i) => i >= w.fromIndex && (!w.filter || w.filter(entry)));
91
+ if (idx !== -1) {
92
+ clearTimeout(w.timer);
93
+ w.resolve(outbox[idx]);
94
+ }
95
+ else {
96
+ waiters.push(w);
97
+ }
98
+ }
99
+ };
100
+ /** The mock `sock` — hand this to your bot code in place of makeWASocket(). */
101
+ const sock = {
102
+ ev,
103
+ user: { id: me, name: pushName },
104
+ authState: { creds: { me: { id: me, name: pushName }, registered: true } },
105
+ type: 'md',
106
+ ws: { readyState: 1, close: () => { } },
107
+ sendMessage: async (jid, content, opts = {}) => {
108
+ if (!jid || typeof jid !== 'string') {
109
+ throw new Error('mock sendMessage: jid must be a string');
110
+ }
111
+ // Build a REAL WAMessage through the same pipeline as the live socket
112
+ const message = await generateWAMessage(jid, content, {
113
+ userJid: me,
114
+ logger: undefined,
115
+ ...stubMediaOptions,
116
+ ...opts
117
+ });
118
+ message.pushName = pushName;
119
+ message.key.fromMe = true;
120
+ const entry = { jid, content, options: opts, message };
121
+ outbox.push(entry);
122
+ // mirror what the live socket does: our own send comes back as an upsert
123
+ ev.emit('messages.upsert', { messages: [message], type: 'notify' });
124
+ settleWaiters();
125
+ return message;
126
+ },
127
+ readMessages: async (keys) => {
128
+ readReceipts.push(...(keys || []));
129
+ },
130
+ sendPresenceUpdate: async (type, toJid) => {
131
+ presenceLog.push({ type, toJid: toJid ?? null });
132
+ },
133
+ presenceSubscribe: async () => { },
134
+ groupMetadata: async (jid) => ({
135
+ id: jid,
136
+ subject: 'Mock Group',
137
+ owner: me,
138
+ participants: [{ id: me, admin: 'superadmin' }],
139
+ creation: unixTimestampSeconds(new Date())
140
+ }),
141
+ onWhatsApp: async (...jids) => jids.map((jid) => ({
142
+ jid: jid.includes('@') ? jid : `${jid}@s.whatsapp.net`,
143
+ exists: true
144
+ })),
145
+ profilePictureUrl: async () => undefined,
146
+ updateMediaMessage: async (msg) => msg,
147
+ relayMessage: async (jid, content, opts = {}) => {
148
+ const message = generateWAMessageFromContent(jid, content, {
149
+ userJid: me,
150
+ messageId: opts.messageId ?? genId()
151
+ });
152
+ outbox.push({ jid, content, options: opts, message });
153
+ settleWaiters();
154
+ return message.key.id;
155
+ },
156
+ end: () => {
157
+ connectionState = 'close';
158
+ ev.emit('connection.update', { connection: 'close' });
159
+ },
160
+ logout: async () => {
161
+ connectionState = 'close';
162
+ ev.emit('connection.update', { connection: 'close' });
163
+ }
164
+ };
165
+ // ---------- test-driver API ----------
166
+ /** Inject an incoming message built from raw WAMessage fields. */
167
+ const receiveMessage = async (msg) => {
168
+ if (!msg?.key?.remoteJid) {
169
+ throw new Error('receiveMessage: msg.key.remoteJid is required');
170
+ }
171
+ ev.emit('messages.upsert', { messages: [msg], type: 'notify' });
172
+ // give handlers a microtask turn so awaited bot logic runs
173
+ await new Promise((resolve) => setImmediate(resolve));
174
+ return msg;
175
+ };
176
+ /**
177
+ * Inject an incoming TEXT message from `fromJid`.
178
+ * In a group, pass `{ groupJid }` — `fromJid` becomes the participant.
179
+ */
180
+ const receiveText = async (fromJid, text, opts = {}) => {
181
+ const { groupJid, pushName: senderName = 'Tester', quoted } = opts;
182
+ const remoteJid = groupJid ?? fromJid;
183
+ const msg = {
184
+ key: {
185
+ remoteJid,
186
+ fromMe: false,
187
+ id: genId(),
188
+ ...(groupJid ? { participant: fromJid } : {})
189
+ },
190
+ pushName: senderName,
191
+ messageTimestamp: unixTimestampSeconds(new Date()),
192
+ message: quoted
193
+ ? { extendedTextMessage: { text, contextInfo: { quotedMessage: quoted.message, stanzaId: quoted.key?.id, participant: quoted.key?.participant ?? quoted.key?.remoteJid } } }
194
+ : { conversation: text }
195
+ };
196
+ return receiveMessage(msg);
197
+ };
198
+ /**
199
+ * Wait for the next outgoing message (optionally matching `filter`),
200
+ * starting AFTER messages already in the outbox. Rejects after `timeoutMs`.
201
+ */
202
+ const waitForReply = (filter, timeoutMs = 2000) => new Promise((resolve, reject) => {
203
+ const fromIndex = 0;
204
+ const existing = outbox.findIndex((entry) => !filter || filter(entry));
205
+ if (existing !== -1) {
206
+ resolve(outbox[existing]);
207
+ return;
208
+ }
209
+ const timer = setTimeout(() => {
210
+ waiters = waiters.filter((w) => w.timer !== timer);
211
+ reject(new Error(`waitForReply: no matching outgoing message within ${timeoutMs}ms`));
212
+ }, timeoutMs);
213
+ waiters.push({ filter, fromIndex, resolve, reject, timer });
214
+ });
215
+ /** Simulate connection lifecycle events. */
216
+ const connect = () => {
217
+ connectionState = 'open';
218
+ ev.emit('connection.update', { connection: 'open' });
219
+ };
220
+ const disconnect = (error) => {
221
+ connectionState = 'close';
222
+ ev.emit('connection.update', { connection: 'close', lastDisconnect: { error, date: new Date() } });
223
+ };
224
+ /** Reset captured state between tests (listeners stay attached). */
225
+ const reset = () => {
226
+ outbox.length = 0;
227
+ eventLog.length = 0;
228
+ readReceipts.length = 0;
229
+ presenceLog.length = 0;
230
+ for (const w of waiters) {
231
+ clearTimeout(w.timer);
232
+ w.reject(new Error('mock reset'));
233
+ }
234
+ waiters = [];
235
+ };
236
+ if (autoConnect) {
237
+ connect();
238
+ }
239
+ return {
240
+ sock,
241
+ outbox,
242
+ eventLog,
243
+ readReceipts,
244
+ presenceLog,
245
+ receiveText,
246
+ receiveMessage,
247
+ waitForReply,
248
+ connect,
249
+ disconnect,
250
+ reset,
251
+ get connectionState() { return connectionState; }
252
+ };
253
+ };
@@ -0,0 +1,12 @@
1
+ export type TranscriptionProvider = (audio: Buffer, meta?: { mimetype?: string }) => Promise<{ text: string }>;
2
+ export declare const customProvider: (fn: (audio: Buffer, meta?: any) => Promise<{ text: string } | string> | { text: string } | string) => TranscriptionProvider;
3
+ export interface WhisperProviderOptions {
4
+ apiKey: string;
5
+ model?: string;
6
+ baseUrl?: string;
7
+ language?: string;
8
+ fileName?: string;
9
+ }
10
+ export declare const openAIWhisperProvider: (opts: WhisperProviderOptions) => TranscriptionProvider;
11
+ export declare const transcribeAudio: (audio: Buffer, opts?: { provider?: TranscriptionProvider; mimetype?: string }) => Promise<{ text: string }>;
12
+ export declare const transcribeMessage: (sock: any, webMessage: any, opts?: { provider?: TranscriptionProvider; download?: (keys: any) => Promise<any> }) => Promise<{ text: string; seconds: number | null; ptt: boolean }>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * JAP@Add --- voice-note transcription with pluggable providers.
3
+ *
4
+ * WhatsApp generates transcripts on-device only — there is no transcript API
5
+ * on the wire. So this module downloads the voice note and hands it to a
6
+ * *provider function* you choose: any `(audioBuffer, { mimetype }) => { text }`.
7
+ * Ships with an OpenAI-compatible Whisper provider; bring your own for local
8
+ * models (faster-whisper sidecar, etc).
9
+ *
10
+ * ```js
11
+ * import { transcribeMessage, openAIWhisperProvider } from '@japofc/baileys'
12
+ * const provider = openAIWhisperProvider({ apiKey: process.env.OPENAI_API_KEY })
13
+ * sock.ev.on('messages.upsert', async ({ messages }) => {
14
+ * for (const m of messages) {
15
+ * if (m.message?.audioMessage?.ptt) console.log(await transcribeMessage(sock, m, { provider }))
16
+ * }
17
+ * })
18
+ * ```
19
+ */
20
+ import { Boom } from '@hapi/boom';
21
+ import { downloadContentFromMessage } from './messages-media.js';
22
+
23
+ const streamToBuffer = async (stream) => {
24
+ const chunks = [];
25
+ for await (const chunk of stream) {
26
+ chunks.push(chunk);
27
+ }
28
+ return Buffer.concat(chunks);
29
+ };
30
+
31
+ const needProvider = (provider) => {
32
+ if (typeof provider !== 'function') {
33
+ throw new Boom('transcription needs { provider } — see customProvider() / openAIWhisperProvider()', { statusCode: 400 });
34
+ }
35
+ };
36
+
37
+ /** Wrap any async `(audioBuffer, meta) => { text } | string` fn into a provider. */
38
+ export const customProvider = (fn) => {
39
+ if (typeof fn !== 'function') {
40
+ throw new Boom('customProvider(fn) needs a function', { statusCode: 400 });
41
+ }
42
+ return async (audio, meta = {}) => {
43
+ const res = await fn(audio, meta);
44
+ const text = typeof res === 'string' ? res : res?.text;
45
+ if (!text || typeof text !== 'string') {
46
+ throw new Boom('transcription provider returned no text', { statusCode: 502 });
47
+ }
48
+ return { text };
49
+ };
50
+ };
51
+
52
+ /** OpenAI-compatible `/v1/audio/transcriptions` endpoint (cloud or local clone). */
53
+ export const openAIWhisperProvider = ({ apiKey, model = 'whisper-1', baseUrl = 'https://api.openai.com/v1', language, fileName = 'voice.ogg' } = {}) => {
54
+ if (!apiKey || typeof apiKey !== 'string') {
55
+ throw new Boom('openAIWhisperProvider needs { apiKey }', { statusCode: 400 });
56
+ }
57
+ return async (audio, { mimetype = 'audio/ogg' } = {}) => {
58
+ const form = new FormData();
59
+ form.append('model', model);
60
+ form.append('file', new Blob([audio], { type: mimetype }), fileName);
61
+ if (language) {
62
+ form.append('language', language);
63
+ }
64
+ const res = await fetch(`${baseUrl}/audio/transcriptions`, {
65
+ method: 'POST',
66
+ headers: { Authorization: `Bearer ${apiKey}` },
67
+ body: form
68
+ });
69
+ if (!res.ok) {
70
+ throw new Boom(`transcription failed: HTTP ${res.status}`, { statusCode: 502 });
71
+ }
72
+ const { text } = await res.json();
73
+ if (!text || typeof text !== 'string') {
74
+ throw new Boom('transcription endpoint returned no text', { statusCode: 502 });
75
+ }
76
+ return { text };
77
+ };
78
+ };
79
+
80
+ /** Transcribe a raw audio buffer with any provider. */
81
+ export const transcribeAudio = async (audio, { provider, mimetype } = {}) => {
82
+ if (!Buffer.isBuffer(audio) || !audio.length) {
83
+ throw new Boom('transcribeAudio(audio) needs a non-empty audio Buffer', { statusCode: 400 });
84
+ }
85
+ needProvider(provider);
86
+ return provider(audio, { mimetype });
87
+ };
88
+
89
+ /**
90
+ * Download + transcribe a voice-note/audio WAMessage.
91
+ * `download` override exists for tests (default hits the WA media CDN).
92
+ */
93
+ export const transcribeMessage = async (sock, webMessage, { provider, download } = {}) => {
94
+ const audio = webMessage?.message?.audioMessage;
95
+ if (!audio?.mediaKey) {
96
+ throw new Boom('transcribeMessage needs a voice-note/audio WAMessage', { statusCode: 400 });
97
+ }
98
+ needProvider(provider);
99
+ const dl = download || ((keys) => downloadContentFromMessage(keys, 'audio', {}));
100
+ const stream = await dl({ mediaKey: audio.mediaKey, directPath: audio.directPath, url: audio.url });
101
+ const buf = await streamToBuffer(stream);
102
+ const { text } = await provider(buf, { mimetype: audio.mimetype });
103
+ if (!text || typeof text !== 'string') {
104
+ throw new Boom('transcription provider returned no text', { statusCode: 502 });
105
+ }
106
+ return { text, seconds: audio.seconds ?? null, ptt: audio.ptt ?? false };
107
+ };
@@ -0,0 +1,3 @@
1
+ export declare const USERNAME_QUERY_IDS: Record<string, string>;
2
+ export declare const USERNAME_CHECK_RESULT: { SUCCESS: 'SUCCESS'; INVALID: 'INVALID' };
3
+ export declare const attachUsernameApi: (sock: any, config?: { usernameQueryIds?: Record<string, string> }) => any;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Username (baca-saja) — dipasang ke socket lewat attachUsernameApi(sock, config).
3
+ * Diport dari J.AP (@japofc/baileys, MIT), tanpa fungsi yang MENGUBAH akun
4
+ * (set / reserve / delete / pin) dan tanpa auto-rotate dari repo luar.
5
+ *
6
+ * ⚠ checkUsername / getMyUsername / getUsernameRecommendations memakai GraphQL query_id yang
7
+ * ditangkap dari WA Web dan bisa diganti WhatsApp kapan saja. Kalau error "bad request", ganti id-nya:
8
+ * makeWASocket({ usernameQueryIds: { CHECK: '<id baru>' } }) atau sock.setUsernameQueryIds({...})
9
+ * findUserByUsername & fetchContactUsernames pakai USync (tanpa query_id).
10
+ */
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { executeWMexQuery } from '../Socket/mex.js';
13
+
14
+ export const USERNAME_QUERY_IDS = {
15
+ CHECK: '26124072630599520',
16
+ CHECK_MULTI: '27134626522840290',
17
+ GET: '32618050064506056',
18
+ GET_RECOMMENDATIONS: '26077456248616956'
19
+ };
20
+ export const USERNAME_CHECK_RESULT = { SUCCESS: 'SUCCESS', INVALID: 'INVALID' };
21
+
22
+ export const attachUsernameApi = (sock, config = {}) => {
23
+ const { query, generateMessageTag, executeUSyncQuery } = sock;
24
+ const queryIds = { ...USERNAME_QUERY_IDS, ...(config?.usernameQueryIds ?? {}) };
25
+
26
+ const mexQuery = async (variables, queryId, dataPath) => {
27
+ try {
28
+ return await executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
29
+ }
30
+ catch (err) {
31
+ const status = err?.output?.statusCode;
32
+ if (status === 400 || /bad request/i.test(String(err?.message ?? ''))) {
33
+ throw Object.assign(new Error(`${err.message} — kemungkinan query_id (${queryId}) sudah diganti WhatsApp. ` +
34
+ 'Ganti lewat sock.setUsernameQueryIds({ CHECK: \'<id baru>\' }).'), { cause: err, output: err?.output });
35
+ }
36
+ throw err;
37
+ }
38
+ };
39
+
40
+ sock.getUsernameQueryIds = () => ({ ...queryIds });
41
+ sock.setUsernameQueryIds = (patch = {}) => {
42
+ for (const [k, v] of Object.entries(patch)) {
43
+ if (typeof v === 'string' && v) queryIds[k] = v;
44
+ }
45
+ return { ...queryIds };
46
+ };
47
+ sock.checkUsername = async (username, includeSuggestions = true) => {
48
+ const data = await mexQuery({ username, include_suggestions: includeSuggestions }, queryIds.CHECK, 'xwa2_username_check');
49
+ if (data?.result === USERNAME_CHECK_RESULT.SUCCESS) return { available: true, username };
50
+ return {
51
+ available: false, username,
52
+ suggestions: data?.suggestions ?? [],
53
+ rejectionReasons: data?.rejection_reasons ?? [],
54
+ suggestionsEligible: data?.suggestions_eligible ?? true
55
+ };
56
+ };
57
+ sock.checkUsernameMulti = (usernames) => mexQuery({ usernames }, queryIds.CHECK_MULTI, 'xwa2_username_check_multi');
58
+ sock.getMyUsername = async () => (await mexQuery({}, queryIds.GET, 'xwa2_username_get'))?.username ?? null;
59
+ sock.getUsernameRecommendations = (source = null) => mexQuery(source ? { source } : {}, queryIds.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations');
60
+ sock.findUserByUsername = async (username, pin) => {
61
+ const user = new USyncUser().withUsername(username);
62
+ if (pin) user.withUsernameKey(pin);
63
+ const result = await executeUSyncQuery(new USyncQuery().withContactProtocol().withUser(user));
64
+ const entry = result?.list?.[0];
65
+ return entry ? { jid: entry.id, contact: Boolean(entry.contact) } : null;
66
+ };
67
+ sock.fetchContactUsernames = async (...jids) => {
68
+ const q = new USyncQuery().withUsernameProtocol();
69
+ for (const jid of jids) q.withUser(new USyncUser().withId(jid));
70
+ return (await executeUSyncQuery(q))?.list ?? [];
71
+ };
72
+ return sock;
73
+ };
package/lib/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./Defaults/index.js";
6
6
  export * from "./WABinary/index.js";
7
7
  export * from "./WAM/index.js";
8
8
  export * from "./WAUSync/index.js";
9
+ export { A2UI, sendA2UIWidget } from "./Builders/A2UI.js";
9
10
  export { makeWASocket };
10
11
  export default makeWASocket;
11
12
  import makeWASocket from './Socket/index.js';
package/lib/index.js CHANGED
@@ -7,6 +7,7 @@ export * from './Defaults/index.js';
7
7
  export * from './WABinary/index.js';
8
8
  export * from './WAM/index.js';
9
9
  export * from './WAUSync/index.js';
10
+ export { A2UI, sendA2UIWidget } from './Builders/A2UI.js';
10
11
  export { makeWASocket };
11
12
  export default makeWASocket;
12
13
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jexkcode/baileys",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "JexkCode Baileys - Enhanced WhatsApp Web API with interactive messages, albums, newsletter support, and AIRich responses.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",