@arcaelas/whatsapp 1.0.2 → 1.0.3

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.
package/README.md CHANGED
@@ -55,10 +55,6 @@
55
55
  ```bash
56
56
  # core package
57
57
  yarn add @arcaelas/whatsapp
58
-
59
- # peer dependency (Baileys – WhatsApp MD layer)
60
- yarn add @whiskeysockets/baileys
61
- # plus any media codecs you wish (ffmpeg, sharp, etc.)
62
58
  ```
63
59
 
64
60
  > Node 18+ required. Works in ESM & TypeScript projects out of the box.
package/build/index.d.ts CHANGED
@@ -6,13 +6,23 @@ import EventEmitter from 'node:events';
6
6
  import Chat from './model/chat';
7
7
  import Message from './model/message';
8
8
  import Store, { Engine } from './static/Store';
9
- interface IWhatsApp<T extends 'qr' | 'code'> {
9
+ /**
10
+ * @description Estructura de configuración para iniciar sesión con WhatsApp.
11
+ */
12
+ interface IWhatsAppBase {
10
13
  phone: string;
11
14
  store?: Engine;
12
- loginType: T;
13
- qr: T extends 'qr' ? Noop<[QR: string]> : never;
14
- code: T extends 'code' ? Noop<[code: string]> : never;
15
15
  }
16
+ /**
17
+ * @description Configuración condicional según tipo de login.
18
+ */
19
+ type IWhatsApp<T extends 'qr' | 'code'> = IWhatsAppBase & {
20
+ loginType: T;
21
+ } & (T extends 'qr' ? {
22
+ qr: Noop<[qr: string]>;
23
+ } : {
24
+ code: Noop<[code: string]>;
25
+ });
16
26
  interface EventMap {
17
27
  error: [error: Error];
18
28
  open: [];
package/build/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var B=Object.create;var l=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var x=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},y=(o,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of C(r))!W.call(o,s)&&s!==t&&l(o,s,{get:()=>r[s],enumerable:!(i=M(r,s))||i.enumerable});return o};var p=(o,r,t)=>(t=o!=null?B(A(o)):{},y(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),P=o=>y(l({},"__esModule",{value:!0}),o);var q={};x(q,{default:()=>T});module.exports=P(q);var h=require("@arcaelas/utils"),w=require("async-mutex"),m=p(require("baileys")),f=p(require("node:events")),u=p(require("./model/chat")),g=p(require("./model/message")),k=p(require("./static/Store")),S=p(require("./static/useCache"));class T extends f.default{constructor(t){super({captureRejections:!0});this.options=t;this.store=new Map;this.mutex=new w.Mutex;this.on("error",i=>{this.listenerCount("error")===1&&console.error(i)}),this.store=new k.default(this.options.store??new Map),this.connect()}async tick(t){return this.mutex.acquire().then(()=>t(this.socket,this.store))}async documents(){return await this.tick(async(t,i)=>{const s={};for await(const n of i.document.values())s[n.key]=n.value;return s})}async chats(){return await this.tick(async(t,i)=>{const s=[];for await(const n of i.chat.values())s.push(new u.default(this,n));return s})}async messages(){return await this.tick(async(t,i)=>{const s=[];for await(const n of i.message.values())s.push(new g.default(this,n));return s})}async connect(){const t=(0,h.promify)(),{state:i,save:s}=await(0,S.default)(this.store),{version:n}=await m.fetchLatestBaileysVersion();if(this.socket=m.makeWASocket({version:n,syncFullHistory:!0,browser:m.Browsers.macOS("Descktop"),auth:{creds:i.creds,keys:m.makeCacheableSignalKeyStore(i.keys)},getMessage:async a=>{const e=await this.store.message.get(a.id);return e?e.message:void 0}}),this.socket.ev.process(async a=>{if(a["creds.update"]&&await s(),a["connection.update"]){const{connection:e,lastDisconnect:c}=a["connection.update"];if(e==="open")t.resolve(this.socket);else if(e==="close"&&c?.error?.output?.statusCode!==m.DisconnectReason.loggedOut){t.resolve(await this.connect());return}}await Promise.allSettled([].concat(a["messaging-history.set"]?.chats||[],a["chats.upsert"]||[]).map(async e=>{await this.store.chat.set(e),this.emit("chat:created",new u.default(this,e))})),await Promise.allSettled([].concat(a["chats.update"]||[]).map(async e=>{const c=await this.store.chat.get(e.id);if(c!==null){const d=(0,h.merge)(c,e);await this.store.chat.set(d),this.emit("chat:updated",new u.default(this,d))}}));for(const e of a["chats.delete"]??[])await this.store.chat.delete(e),this.emit("chat:deleted",e);await Promise.allSettled([].concat(a["messages.upsert"]?.messages||[]).map(async e=>{await this.store.message.set(e),this.emit("message:created",new g.default(this,e))})),await Promise.allSettled([].concat(a["messages.update"]||[]).map(async e=>{const c=await this.store.message.get(e.key.id);if(c!==null){const d=(0,h.merge)(c,e);await this.store.message.set(d),this.emit("message:updated",new g.default(this,d))}}))}),await this.socket.waitForSocketOpen(),await(0,h.sleep)(3e3),this.socket.authState.creds.registered)t.resolve(this.socket);else if(this.options.loginType==="code")await this.options.code(await this.socket.requestPairingCode(this.options.phone));else if(this.options.loginType==="qr"){const a=(0,h.promify)(),e=setTimeout(()=>a.reject("QR Timeout"),6e4);this.socket.ev.on("connection.update",async({qr:c})=>{if(c){clearTimeout(e);try{await this.options.qr(c),a.resolve(c)}catch(d){a.reject(d)}}}),await a}return t}}
1
+ "use strict";var T=Object.create;var l=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var q=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},y=(o,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of A(r))!W.call(o,s)&&s!==t&&l(o,s,{get:()=>r[s],enumerable:!(i=M(r,s))||i.enumerable});return o};var d=(o,r,t)=>(t=o!=null?T(C(o)):{},y(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),P=o=>y(l({},"__esModule",{value:!0}),o);var x={};q(x,{default:()=>S});module.exports=P(x);var h=require("@arcaelas/utils"),w=require("async-mutex"),m=d(require("baileys")),f=d(require("node:events")),u=d(require("./model/chat")),g=d(require("./model/message")),k=d(require("./static/Store")),B=d(require("./static/useCache"));class S extends f.default{constructor(t){super({captureRejections:!0});this.options=t;this.store=new Map;this.mutex=new w.Mutex;this.on("error",i=>{this.listenerCount("error")===1&&console.error(i)}),this.store=new k.default(this.options.store??new Map),this.connect()}async tick(t){return this.mutex.acquire().then(()=>t(this.socket,this.store))}async documents(){return await this.tick(async(t,i)=>{const s={};for await(const n of i.document.values())s[n.key]=n.value;return s})}async chats(){return await this.tick(async(t,i)=>{const s=[];for await(const n of i.chat.values())s.push(new u.default(this,n));return s})}async messages(){return await this.tick(async(t,i)=>{const s=[];for await(const n of i.message.values())s.push(new g.default(this,n));return s})}async connect(){const t=(0,h.promify)(),{state:i,save:s}=await(0,B.default)(this.store),{version:n}=await m.fetchLatestBaileysVersion();if(this.socket=m.makeWASocket({version:n,syncFullHistory:!0,browser:m.Browsers.macOS("Descktop"),auth:{creds:i.creds,keys:m.makeCacheableSignalKeyStore(i.keys)},getMessage:async a=>{const e=await this.store.message.get(a.id);return e?e.message:void 0}}),this.socket.ev.process(async a=>{if(a["creds.update"]&&await s(),a["connection.update"]){const{connection:e,lastDisconnect:c}=a["connection.update"];if(e==="open")t.resolve(this.socket);else if(e==="close"&&c?.error?.output?.statusCode!==m.DisconnectReason.loggedOut){t.resolve(await this.connect());return}}await Promise.allSettled([].concat(a["messaging-history.set"]?.chats||[],a["chats.upsert"]||[]).map(async e=>{await this.store.chat.set(e),this.emit("chat:created",new u.default(this,e))})),await Promise.allSettled([].concat(a["chats.update"]||[]).map(async e=>{const c=await this.store.chat.get(e.id);if(c!==null){const p=(0,h.merge)(c,e);await this.store.chat.set(p),this.emit("chat:updated",new u.default(this,p))}}));for(const e of a["chats.delete"]??[])await this.store.chat.delete(e),this.emit("chat:deleted",e);await Promise.allSettled([].concat(a["messages.upsert"]?.messages||[]).map(async e=>{await this.store.message.set(e),this.emit("message:created",new g.default(this,e))})),await Promise.allSettled([].concat(a["messages.update"]||[]).map(async e=>{const c=await this.store.message.get(e.key.id);if(c!==null){const p=(0,h.merge)(c,e);await this.store.message.set(p),this.emit("message:updated",new g.default(this,p))}}))}),await this.socket.waitForSocketOpen(),await(0,h.sleep)(3e3),this.socket.authState.creds.registered)t.resolve(this.socket);else if(this.options.loginType==="code")await this.options.code(await this.socket.requestPairingCode(this.options.phone));else if(this.options.loginType==="qr"){const a=(0,h.promify)(),e=setTimeout(()=>a.reject("QR Timeout"),6e4);this.socket.ev.on("connection.update",async({qr:c})=>{if(c){clearTimeout(e);try{await this.options.qr(c),a.resolve(c)}catch(p){a.reject(p)}}}),await a}return t}}
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import { merge, Noop, promify, sleep } from '@arcaelas/utils';\nimport { type Boom } from '@hapi/boom';\nimport { Mutex } from 'async-mutex';\nimport * as Baileys from 'baileys';\nimport EventEmitter from 'node:events';\nimport Chat from './model/chat';\nimport Message from './model/message';\nimport Store, { Engine } from './static/Store';\nimport useCache from './static/useCache';\n\ninterface IWhatsApp<T extends 'qr' | 'code'> {\n phone: string;\n store?: Engine;\n loginType: T;\n qr: T extends 'qr' ? Noop<[QR: string]> : never;\n code: T extends 'code' ? Noop<[code: string]> : never;\n}\n\ninterface EventMap {\n error: [error: Error]\n open: []\n close: []\n qr: [qr: string]\n code: [code: string]\n 'chat:created': [chat: Chat]\n 'chat:updated': [chat: Chat]\n 'chat:deleted': [id: string]\n 'message:created': [message: Message]\n 'message:updated': [message: Message]\n 'message:deleted': [id: string]\n}\n\n/**\n * @description\n * Client for WhatsApp Web.\n * @example\n * const client = new WhatsApp({\n * phone: '1234567890',\n * loginType: 'qr',\n * qr: (code) => console.log(code),\n * });\n */\nexport default class WhatsApp<T extends 'qr' | 'code'> extends EventEmitter<EventMap> {\n /**\n * @description\n * Socket for WhatsApp Web.\n */\n protected socket: Baileys.WASocket;\n /**\n * @description\n * Store for WhatsApp Web.\n */\n protected store: Store = new Map() as any;\n /**\n * @description\n * Mutex, used to prevent concurrent access to the socket.\n */\n protected readonly mutex = new Mutex();\n\n constructor(protected readonly options: IWhatsApp<T>) {\n super({ captureRejections: true });\n this.on('error', (error) => {\n if (this.listenerCount('error') === 1) {\n console.error(error);\n }\n });\n this.store = new Store(this.options.store ?? new Map() as any);\n this.connect();\n }\n\n /**\n * @description\n * Execute a function with the socket and store, means that the function will be executed only when the socket is ready.\n * @param func Function to execute.\n * @returns Result of the function.\n */\n async tick<T extends Noop<[socket: Baileys.WASocket, store: Store], any>>(func: T): Promise<Awaited<ReturnType<T>>> {\n return this.mutex.acquire().then(() => func(this.socket, this.store));\n }\n\n async documents(): Promise<Record<string, any>> {\n return await this.tick(async (_, store) => {\n const documents: Record<string, any> = {}\n for await (const document of store.document.values()) {\n documents[document.key] = document.value;\n }\n return documents;\n });\n }\n\n async chats(): Promise<Chat[]> {\n return await this.tick(async (_, store) => {\n const chats: Chat[] = [];\n for await (const chat of store.chat.values()) {\n chats.push(new Chat(this, chat));\n }\n return chats;\n });\n }\n\n async messages(): Promise<Message[]> {\n return await this.tick(async (_, store) => {\n const messages: Message[] = [];\n for await (const message of store.message.values()) {\n messages.push(new Message(this, message));\n }\n return messages;\n });\n }\n\n /**\n * @description\n * Connect to WhatsApp Web.\n * @returns Promise that resolves to the socket.\n */\n protected async connect() {\n const promise = promify<Baileys.WASocket>();\n const { state, save } = await useCache(this.store);\n const { version } = await Baileys.fetchLatestBaileysVersion();\n this.socket = Baileys.makeWASocket({\n version,\n syncFullHistory: true,\n browser: Baileys.Browsers.macOS('Descktop'),\n auth: {\n creds: state.creds,\n keys: Baileys.makeCacheableSignalKeyStore(state.keys),\n },\n getMessage: async (key) => {\n const message = await this.store.message.get(key.id!);\n return message ? message.message! : undefined;\n },\n });\n this.socket.ev.process(async (event) => {\n if (event['creds.update']) {\n await save();\n }\n if (event['connection.update']) {\n const { connection, lastDisconnect } = event['connection.update'];\n if (connection === 'open') promise.resolve(this.socket);\n else if (connection === 'close' && (lastDisconnect?.error as Boom)?.output?.statusCode !== Baileys.DisconnectReason.loggedOut) {\n promise.resolve(await this.connect());\n return\n }\n }\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.Chat[])\n .concat(event['messaging-history.set']?.chats || [], event['chats.upsert'] || [])\n .map(async chat => {\n await this.store.chat.set(chat);\n this.emit('chat:created', new Chat(this, chat));\n })\n );\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.ChatUpdate[])\n .concat(event['chats.update'] || [])\n .map(async update => {\n const payload = await this.store.chat.get(update.id!);\n if (payload !== null) {\n const chat = merge(payload, update) as Baileys.Chat;\n await this.store.chat.set(chat);\n this.emit('chat:updated', new Chat(this, chat));\n }\n })\n );\n for (const key of (event['chats.delete'] ?? []) as string[]) {\n await this.store.chat.delete(key);\n this.emit('chat:deleted', key);\n }\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.WAMessage[])\n .concat(event['messages.upsert']?.messages || [])\n .map(async message => {\n await this.store.message.set(message);\n this.emit('message:created', new Message(this, message));\n })\n );\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.WAMessageUpdate[])\n .concat(event['messages.update'] || [])\n .map(async message => {\n const payload = await this.store.message.get(message.key.id!);\n if (payload !== null) {\n const chat = merge(payload, message) as Baileys.WAProto.WebMessageInfo;\n await this.store.message.set(chat);\n this.emit('message:updated', new Message(this, chat));\n }\n })\n );\n // TODO: Handle messages.delete\n })\n\n await this.socket.waitForSocketOpen();\n await sleep(3000);\n\n if (this.socket.authState.creds.registered) {\n promise.resolve(this.socket);\n } else if (this.options.loginType === 'code') {\n await this.options.code(\n await this.socket.requestPairingCode(this.options.phone)\n );\n } else if (this.options.loginType === 'qr') {\n const _qr = promify<string>();\n const timeout = setTimeout(() => _qr.reject('QR Timeout'), 60000);\n this.socket.ev.on('connection.update', async ({ qr }) => {\n if (qr) {\n clearTimeout(timeout);\n try {\n await this.options.qr(qr);\n _qr.resolve(qr);\n } catch (error) {\n _qr.reject(error);\n }\n }\n });\n await _qr;\n }\n return promise;\n }\n}"],
5
- "mappings": "0jBAAA,IAAAA,E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AK,QAAQ,YAAc,OAClC,MAAM,KAAK,QAAQ,KACf,MAAM,KAAK,OAAO,mBAAmB,KAAK,QAAQ,KAAK,CAC3D,UACO,KAAK,QAAQ,YAAc,KAAM,CACxC,MAAMW,KAAM,WAAgB,EACtBC,EAAU,WAAW,IAAMD,EAAI,OAAO,YAAY,EAAG,GAAK,EAChE,KAAK,OAAO,GAAG,GAAG,oBAAqB,MAAO,CAAE,GAAAE,CAAG,IAAM,CACrD,GAAIA,EAAI,CACJ,aAAaD,CAAO,EACpB,GAAI,CACA,MAAM,KAAK,QAAQ,GAAGC,CAAE,EACxBF,EAAI,QAAQE,CAAE,CAClB,OAAS1B,EAAP,CACEwB,EAAI,OAAOxB,CAAK,CACpB,EAER,CAAC,EACD,MAAMwB,EAEV,OAAOX,CACX,CACJ",
4
+ "sourcesContent": ["import { merge, Noop, promify, sleep } from '@arcaelas/utils';\nimport { type Boom } from '@hapi/boom';\nimport { Mutex } from 'async-mutex';\nimport * as Baileys from 'baileys';\nimport EventEmitter from 'node:events';\nimport Chat from './model/chat';\nimport Message from './model/message';\nimport Store, { Engine } from './static/Store';\nimport useCache from './static/useCache';\n\n/**\n * @description Estructura de configuraci\u00F3n para iniciar sesi\u00F3n con WhatsApp.\n */\ninterface IWhatsAppBase {\n phone: string;\n store?: Engine;\n}\n\n/**\n * @description Configuraci\u00F3n condicional seg\u00FAn tipo de login.\n */\n// prettier-ignore\ntype IWhatsApp<T extends 'qr' | 'code'> = IWhatsAppBase & {\n loginType: T } & (\n T extends 'qr'\n ? { qr: Noop<[qr: string]> }\n : { code: Noop<[code: string]> }\n );\n\ninterface EventMap {\n error: [error: Error];\n open: [];\n close: [];\n qr: [qr: string];\n code: [code: string];\n 'chat:created': [chat: Chat];\n 'chat:updated': [chat: Chat];\n 'chat:deleted': [id: string];\n 'message:created': [message: Message];\n 'message:updated': [message: Message];\n 'message:deleted': [id: string];\n}\n\n/**\n * @description\n * Client for WhatsApp Web.\n * @example\n * const client = new WhatsApp({\n * phone: '1234567890',\n * loginType: 'qr',\n * qr: (code) => console.log(code),\n * });\n */\nexport default class WhatsApp<T extends 'qr' | 'code'> extends EventEmitter<EventMap> {\n /**\n * @description\n * Socket for WhatsApp Web.\n */\n protected socket: Baileys.WASocket;\n /**\n * @description\n * Store for WhatsApp Web.\n */\n protected store: Store = new Map() as any;\n /**\n * @description\n * Mutex, used to prevent concurrent access to the socket.\n */\n protected readonly mutex = new Mutex();\n\n constructor(protected readonly options: IWhatsApp<T>) {\n super({ captureRejections: true });\n this.on('error', (error) => {\n if (this.listenerCount('error') === 1) {\n console.error(error);\n }\n });\n this.store = new Store(this.options.store ?? (new Map() as any));\n this.connect();\n }\n\n /**\n * @description\n * Execute a function with the socket and store, means that the function will be executed only when the socket is ready.\n * @param func Function to execute.\n * @returns Result of the function.\n */\n async tick<T extends Noop<[socket: Baileys.WASocket, store: Store], any>>(func: T): Promise<Awaited<ReturnType<T>>> {\n return this.mutex.acquire().then(() => func(this.socket, this.store));\n }\n\n async documents(): Promise<Record<string, any>> {\n return await this.tick(async (_, store) => {\n const documents: Record<string, any> = {};\n for await (const document of store.document.values()) {\n documents[document.key] = document.value;\n }\n return documents;\n });\n }\n\n async chats(): Promise<Chat[]> {\n return await this.tick(async (_, store) => {\n const chats: Chat[] = [];\n for await (const chat of store.chat.values()) {\n chats.push(new Chat(this, chat));\n }\n return chats;\n });\n }\n\n async messages(): Promise<Message[]> {\n return await this.tick(async (_, store) => {\n const messages: Message[] = [];\n for await (const message of store.message.values()) {\n messages.push(new Message(this, message));\n }\n return messages;\n });\n }\n\n /**\n * @description\n * Connect to WhatsApp Web.\n * @returns Promise that resolves to the socket.\n */\n protected async connect() {\n const promise = promify<Baileys.WASocket>();\n const { state, save } = await useCache(this.store);\n const { version } = await Baileys.fetchLatestBaileysVersion();\n this.socket = Baileys.makeWASocket({\n version,\n syncFullHistory: true,\n browser: Baileys.Browsers.macOS('Descktop'),\n auth: {\n creds: state.creds,\n keys: Baileys.makeCacheableSignalKeyStore(state.keys),\n },\n getMessage: async (key) => {\n const message = await this.store.message.get(key.id!);\n return message ? message.message! : undefined;\n },\n });\n this.socket.ev.process(async (event) => {\n if (event['creds.update']) {\n await save();\n }\n if (event['connection.update']) {\n const { connection, lastDisconnect } = event['connection.update'];\n if (connection === 'open') promise.resolve(this.socket);\n else if (connection === 'close' && (lastDisconnect?.error as Boom)?.output?.statusCode !== Baileys.DisconnectReason.loggedOut) {\n promise.resolve(await this.connect());\n return;\n }\n }\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.Chat[])\n .concat(event['messaging-history.set']?.chats || [], event['chats.upsert'] || [])\n .map(async chat => {\n await this.store.chat.set(chat);\n this.emit('chat:created', new Chat(this, chat));\n })\n );\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.ChatUpdate[])\n .concat(event['chats.update'] || [])\n .map(async update => {\n const payload = await this.store.chat.get(update.id!);\n if (payload !== null) {\n const chat = merge(payload, update) as Baileys.Chat;\n await this.store.chat.set(chat);\n this.emit('chat:updated', new Chat(this, chat));\n }\n })\n );\n for (const key of (event['chats.delete'] ?? []) as string[]) {\n await this.store.chat.delete(key);\n this.emit('chat:deleted', key);\n }\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.WAMessage[])\n .concat(event['messages.upsert']?.messages || [])\n .map(async message => {\n await this.store.message.set(message);\n this.emit('message:created', new Message(this, message));\n })\n );\n // prettier-ignore\n await Promise.allSettled(\n ([] as Baileys.WAMessageUpdate[])\n .concat(event['messages.update'] || [])\n .map(async message => {\n const payload = await this.store.message.get(message.key.id!);\n if (payload !== null) {\n const chat = merge(payload, message) as Baileys.WAProto.WebMessageInfo;\n await this.store.message.set(chat);\n this.emit('message:updated', new Message(this, chat));\n }\n })\n );\n // TODO: Handle messages.delete\n });\n\n await this.socket.waitForSocketOpen();\n await sleep(3000);\n\n if (this.socket.authState.creds.registered) {\n promise.resolve(this.socket);\n } else if (this.options.loginType === 'code') {\n await this.options['code'](await this.socket.requestPairingCode(this.options.phone));\n } else if (this.options.loginType === 'qr') {\n const _qr = promify<string>();\n const timeout = setTimeout(() => _qr.reject('QR Timeout'), 60000);\n this.socket.ev.on('connection.update', async ({ qr }) => {\n if (qr) {\n clearTimeout(timeout);\n try {\n await this.options['qr'](qr);\n _qr.resolve(qr);\n } catch (error) {\n _qr.reject(error);\n }\n }\n });\n await _qr;\n }\n return promise;\n }\n}\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA4C,2BAE5CC,EAAsB,uBACtBC,EAAyB,sBACzBC,EAAyB,0BACzBC,EAAiB,2BACjBC,EAAoB,8BACpBC,EAA8B,6BAC9BC,EAAqB,gCA6CrB,MAAOT,UAAwD,EAAAU,OAAuB,CAiBlF,YAA+BC,EAAuB,CAClD,MAAM,CAAE,kBAAmB,EAAK,CAAC,EADN,aAAAA,EAP/B,KAAU,MAAe,IAAI,IAK7B,KAAmB,MAAQ,IAAI,QAI3B,KAAK,GAAG,QAAUC,GAAU,CACpB,KAAK,cAAc,OAAO,IAAM,GAChC,QAAQ,MAAMA,CAAK,CAE3B,CAAC,EACD,KAAK,MAAQ,IAAI,EAAAC,QAAM,KAAK,QAAQ,OAAU,IAAI,GAAa,EAC/D,KAAK,QAAQ,CACjB,CAQA,MAAM,KAAoEC,EAA0C,CAChH,OAAO,KAAK,MAAM,QAAQ,EAAE,KAAK,IAAMA,EAAK,KAAK,OAAQ,KAAK,KAAK,CAAC,CACxE,CAEA,MAAM,WAA0C,CAC5C,OAAO,MAAM,KAAK,KAAK,MAAOC,EAAGC,IAAU,CACvC,MAAMC,EAAiC,CAAC,EACxC,gBAAiBC,KAAYF,EAAM,SAAS,OAAO,EAC/CC,EAAUC,EAAS,GAAG,EAAIA,EAAS,MAEvC,OAAOD,CACX,CAAC,CACL,CAEA,MAAM,OAAyB,CAC3B,OAAO,MAAM,KAAK,KAAK,MAAOF,EAAGC,IAA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ASZ,CAAO,EACnC,MAAM,KAAK,MAAM,QAAQ,IAAIH,CAAI,EACjC,KAAK,KAAK,kBAAmB,IAAI,EAAAI,QAAQ,KAAMJ,CAAI,CAAC,EAE5D,CAAC,CACT,CAEJ,CAAC,EAED,MAAM,KAAK,OAAO,kBAAkB,EACpC,QAAM,SAAM,GAAI,EAEZ,KAAK,OAAO,UAAU,MAAM,WAC5BK,EAAQ,QAAQ,KAAK,MAAM,UACpB,KAAK,QAAQ,YAAc,OAClC,MAAM,KAAK,QAAQ,KAAQ,MAAM,KAAK,OAAO,mBAAmB,KAAK,QAAQ,KAAK,CAAC,UAC5E,KAAK,QAAQ,YAAc,KAAM,CACxC,MAAMW,KAAM,WAAgB,EACtBC,EAAU,WAAW,IAAMD,EAAI,OAAO,YAAY,EAAG,GAAK,EAChE,KAAK,OAAO,GAAG,GAAG,oBAAqB,MAAO,CAAE,GAAAE,CAAG,IAAM,CACrD,GAAIA,EAAI,CACJ,aAAaD,CAAO,EACpB,GAAI,CACA,MAAM,KAAK,QAAQ,GAAMC,CAAE,EAC3BF,EAAI,QAAQE,CAAE,CAClB,OAAS1B,EAAP,CACEwB,EAAI,OAAOxB,CAAK,CACpB,EAER,CAAC,EACD,MAAMwB,EAEV,OAAOX,CACX,CACJ",
6
6
  "names": ["src_exports", "__export", "WhatsApp", "__toCommonJS", "import_utils", "import_async_mutex", "Baileys", "import_node_events", "import_chat", "import_message", "import_Store", "import_useCache", "EventEmitter", "options", "error", "Store", "func", "_", "store", "documents", "document", "chats", "chat", "Chat", "messages", "message", "Message", "promise", "state", "save", "useCache", "version", "key", "event", "connection", "lastDisconnect", "update", "payload", "_qr", "timeout", "qr"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "license": "ISC",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "name": "@arcaelas/whatsapp",
5
5
  "homepage": "https://github.com/arcaelas/whatsapp",
6
6
  "description": "A small box of tools, which are implemented in different factions of the library.",