@jexkcode/baileys 1.2.0 → 1.3.0

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,214 @@
1
+ /**
2
+ * JAP@Add --- drop-in auto-reconnect for direct makeWASocket users.
3
+ *
4
+ * The Framework Bot has always had exponential-backoff reconnect built in;
5
+ * plain-socket users had to hand-roll the same connection.update dance every
6
+ * project (the #1 beginner Baileys question). This wraps it once, correctly:
7
+ *
8
+ * const manager = autoReconnect(() => makeWASocketAuto({ auth: state }), {
9
+ * onSocket: (sock) => sock.ev.on('messages.upsert', handler),
10
+ * });
11
+ * await manager.start();
12
+ *
13
+ * - exponential backoff with jitter (1s base -> 30s cap)
14
+ * - never reconnects on DisconnectReason.loggedOut (session is dead; caller
15
+ * gets onLoggedOut to clean up creds)
16
+ * - restartRequired (post-pairing) reconnects immediately, not backed off
17
+ * - stop() cancels timers and closes the live socket
18
+ * - factory may be async (works with makeWASocketAuto) or sync
19
+ *
20
+ * @author J.AP
21
+ */
22
+ import { DisconnectReason } from '../Types/index.js';
23
+ import defaultLogger from './logger.js';
24
+
25
+ export const autoReconnect = (socketFactory, options = {}) => {
26
+ const {
27
+ onSocket,
28
+ onOpen,
29
+ onLoggedOut,
30
+ onGiveUp,
31
+ maxAttempts = Infinity,
32
+ baseDelayMs = 1000,
33
+ maxDelayMs = 30000,
34
+ jitter = 0.25,
35
+ logger = defaultLogger.child({ module: 'auto-reconnect' }),
36
+ } = options;
37
+
38
+ let sock = null;
39
+ let attempts = 0;
40
+ let timer = null;
41
+ let stopped = false;
42
+ let started = false;
43
+
44
+ const delayFor = (attempt) => {
45
+ const exp = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt - 1));
46
+ const wiggle = exp * jitter * (Math.random() * 2 - 1);
47
+ return Math.max(0, Math.round(exp + wiggle));
48
+ };
49
+
50
+ const scheduleRestart = (delay) => {
51
+ if (stopped || timer) {
52
+ return; // never two pending reconnects at once
53
+ }
54
+ timer = setTimeout(() => {
55
+ timer = null;
56
+ connect().catch((err) => logger.error({ err }, 'reconnect attempt failed'));
57
+ }, delay);
58
+ };
59
+
60
+ const connect = async () => {
61
+ if (stopped) {
62
+ return null;
63
+ }
64
+ // JAP@Fix (lifecycle): best-effort cleanup of the previous socket so a
65
+ // half-open ws never lingers next to its replacement.
66
+ const previous = sock;
67
+ if (previous) {
68
+ try {
69
+ await previous.end?.();
70
+ }
71
+ catch { /* already dead */ }
72
+ }
73
+ let current;
74
+ try {
75
+ current = await socketFactory();
76
+ }
77
+ catch (err) {
78
+ // JAP@Fix (lifecycle): a throwing factory (e.g. makeWASocketAuto's
79
+ // version fetch while offline) used to kill the chain permanently.
80
+ // Treat it like a failed connection: back off and try again.
81
+ attempts += 1;
82
+ if (attempts > maxAttempts) {
83
+ logger.error({ err, attempts: attempts - 1 }, 'socket factory failed and max attempts reached — giving up');
84
+ try {
85
+ onGiveUp?.({ reason: 'factory-failed', attempts: attempts - 1, error: err });
86
+ }
87
+ catch (cbErr) {
88
+ logger.warn({ err: cbErr }, 'onGiveUp handler threw');
89
+ }
90
+ return null;
91
+ }
92
+ const delay = delayFor(attempts);
93
+ logger.warn({ err, attempt: attempts, delay }, 'socket factory failed — retrying');
94
+ scheduleRestart(delay);
95
+ return null;
96
+ }
97
+ sock = current;
98
+ // JAP@Fix (race): a 'close' may be emitted more than once by the same
99
+ // socket, and a stale (already-replaced) socket can emit late events.
100
+ // Without these guards a double-close schedules two parallel reconnect
101
+ // chains, and every stale close spawns a ghost socket.
102
+ let closeHandled = false;
103
+ try {
104
+ onSocket?.(current);
105
+ }
106
+ catch (err) {
107
+ logger.warn({ err }, 'onSocket handler threw');
108
+ }
109
+ current.ev.on('connection.update', (update) => {
110
+ if (sock !== current) {
111
+ return; // stale socket — a newer one has replaced it
112
+ }
113
+ const { connection, lastDisconnect } = update;
114
+ if (connection === 'open') {
115
+ attempts = 0;
116
+ try {
117
+ onOpen?.(current);
118
+ }
119
+ catch (err) {
120
+ logger.warn({ err }, 'onOpen handler threw');
121
+ }
122
+ return;
123
+ }
124
+ if (connection !== 'close' || stopped || closeHandled) {
125
+ return;
126
+ }
127
+ closeHandled = true;
128
+ const statusCode = lastDisconnect?.error?.output?.statusCode;
129
+ if (statusCode === DisconnectReason.loggedOut) {
130
+ logger.info('session logged out — not reconnecting');
131
+ try {
132
+ onLoggedOut?.(lastDisconnect?.error);
133
+ }
134
+ catch (err) {
135
+ logger.warn({ err }, 'onLoggedOut handler threw');
136
+ }
137
+ return;
138
+ }
139
+ attempts += 1;
140
+ if (attempts > maxAttempts) {
141
+ logger.warn({ attempts: attempts - 1 }, 'max reconnect attempts reached — giving up');
142
+ try {
143
+ onGiveUp?.({ reason: 'max-attempts', attempts: attempts - 1, statusCode });
144
+ }
145
+ catch (cbErr) {
146
+ logger.warn({ err: cbErr }, 'onGiveUp handler threw');
147
+ }
148
+ return;
149
+ }
150
+ // JAP@Fix (lifecycle): restartRequired always reconnected with
151
+ // delay 0. Correct after pairing (single event), but when the
152
+ // server answers restartRequired on EVERY connect it becomes a
153
+ // tight spin loop (repro: 165 sockets in 200ms). Only the FIRST
154
+ // consecutive restartRequired is immediate; repeats back off.
155
+ const immediate = statusCode === DisconnectReason.restartRequired && attempts === 1;
156
+ const delay = immediate ? 0 : delayFor(attempts);
157
+ logger.info({ attempt: attempts, delay, statusCode }, 'scheduling reconnect');
158
+ scheduleRestart(delay);
159
+ });
160
+ return current;
161
+ };
162
+
163
+ // JAP@Fix (lifecycle): start() twice used to run two parallel reconnect
164
+ // chains forever (repro: 2 sockets immediately, 3 after one close storm).
165
+ // The public start() is now idempotent; connect() is the internal step.
166
+ const start = async () => {
167
+ if (started && !stopped) {
168
+ logger.warn('start() called while already running — returning the live socket');
169
+ return sock;
170
+ }
171
+ // JAP@Fix (lifecycle): start() after stop() used to return the dead
172
+ // socket silently (started stayed true, stopped stayed true, connect()
173
+ // no-oped). A stopped manager can now be restarted cleanly.
174
+ stopped = false;
175
+ started = true;
176
+ attempts = 0;
177
+ return connect();
178
+ };
179
+
180
+ const stop = async () => {
181
+ stopped = true;
182
+ if (timer) {
183
+ clearTimeout(timer);
184
+ timer = null;
185
+ }
186
+ try {
187
+ await sock?.end?.();
188
+ }
189
+ catch { /* socket may already be dead */ }
190
+ };
191
+
192
+ return {
193
+ start,
194
+ stop,
195
+ /** The live socket (replaced on every reconnect); null before start(). */
196
+ get socket() {
197
+ return sock;
198
+ },
199
+ /** JAP@Upgrade: current lifecycle status for dashboards/health probes. */
200
+ getStatus() {
201
+ return {
202
+ started,
203
+ stopped,
204
+ attempts,
205
+ reconnectPending: !!timer,
206
+ hasSocket: !!sock
207
+ };
208
+ },
209
+ /** Consecutive failed attempts since the last successful open. */
210
+ get attempts() {
211
+ return attempts;
212
+ },
213
+ };
214
+ };
@@ -0,0 +1,52 @@
1
+ import type { proto } from '../../WAProto/index.js';
2
+ /** Message kind used for placeholders + statistics. */
3
+ export type ExportMessageKind = 'text' | 'image' | 'video' | 'gif' | 'audio' | 'voice note' | 'sticker' | 'document' | 'location' | 'contact' | 'poll' | 'reaction' | 'protocol' | 'other';
4
+ export declare const classifyExportMessage: (msg: proto.IWebMessageInfo) => ExportMessageKind;
5
+ export type ExportChatOptions = {
6
+ /** Resolve a display name for a jid; falls back to pushName, then the number. */
7
+ resolveName?: (jid: string, msg: proto.IWebMessageInfo) => string | undefined | null;
8
+ /** 'omitted' (official style, default) renders `<Media omitted>`; 'descriptive' renders `<image: caption>` etc. */
9
+ mediaPlaceholders?: 'omitted' | 'descriptive';
10
+ /** Include reaction lines (official export skips them). Default false. */
11
+ includeReactions?: boolean;
12
+ /** Custom first line; pass '' to disable the encryption notice header. */
13
+ header?: string;
14
+ };
15
+ /**
16
+ * Render messages as an official-WhatsApp-style "Export chat" transcript:
17
+ * `DD/MM/YYYY, HH.MM - Sender: text` with `<Media omitted>` placeholders.
18
+ */
19
+ export declare const exportChatAsText: (messages: proto.IWebMessageInfo[], options?: ExportChatOptions) => string;
20
+ export type ExportedChatRow = {
21
+ id: string | null;
22
+ timestamp: number;
23
+ fromMe: boolean;
24
+ senderJid: string | null;
25
+ senderName: string;
26
+ kind: ExportMessageKind;
27
+ text: string | null;
28
+ };
29
+ /** Export as structured JSON rows, sorted oldest-first. */
30
+ export declare const exportChatAsJSON: (messages: proto.IWebMessageInfo[], options?: Pick<ExportChatOptions, 'resolveName'>) => ExportedChatRow[];
31
+ /** Export as CSV (same rows as exportChatAsJSON; RFC 4180 quoting). */
32
+ export declare const exportChatAsCSV: (messages: proto.IWebMessageInfo[], options?: Pick<ExportChatOptions, 'resolveName'>) => string;
33
+ export type ChatStatistics = {
34
+ total: number;
35
+ bySender: Record<string, number>;
36
+ byKind: Partial<Record<ExportMessageKind, number>>;
37
+ /** Message count per hour of day (local time), index 0-23. */
38
+ byHour: number[];
39
+ /** Message count per weekday (local time), index 0 (Sunday) - 6 (Saturday). */
40
+ byWeekday: number[];
41
+ firstTimestamp: number | null;
42
+ lastTimestamp: number | null;
43
+ topWords: Array<{ word: string; count: number }>;
44
+ };
45
+ /** Per-chat statistics: totals, per-sender/kind counts, busiest hour/day, top words. */
46
+ export declare const chatStatistics: (messages: proto.IWebMessageInfo[], options?: {
47
+ resolveName?: (jid: string, msg: proto.IWebMessageInfo) => string | undefined | null;
48
+ /** How many top words to return (default 10). */
49
+ topWords?: number;
50
+ /** Minimum word length counted (default 3). */
51
+ minWordLength?: number;
52
+ }) => ChatStatistics;
@@ -0,0 +1,248 @@
1
+ // JAP@Add --- Chat export & statistics (offline, pure logic)
2
+ //
3
+ // Mirrors the official WhatsApp "Export chat" text format from an array of
4
+ // WAMessage objects (e.g. collected via a store, anti-delete cache, or
5
+ // messages.upsert). Also produces JSON/CSV exports and per-chat statistics.
6
+ // No network, no media downloads — media messages are rendered as the same
7
+ // placeholders the official export uses ("<Media omitted>", or a descriptive
8
+ // tag with exportMediaPlaceholders: 'descriptive').
9
+ import { extractMessageText } from './message-search.js';
10
+ import { toNumber } from './generics.js';
11
+ const unwrap = (content) => {
12
+ if (!content) {
13
+ return content;
14
+ }
15
+ return (content.ephemeralMessage?.message ||
16
+ content.viewOnceMessage?.message ||
17
+ content.viewOnceMessageV2?.message ||
18
+ content.documentWithCaptionMessage?.message ||
19
+ content.editedMessage?.message ||
20
+ content);
21
+ };
22
+ /** Message kind used for placeholders + statistics. */
23
+ export const classifyExportMessage = (msg) => {
24
+ const c = unwrap(msg?.message);
25
+ if (!c) {
26
+ return 'other';
27
+ }
28
+ if (c.conversation || c.extendedTextMessage) {
29
+ return 'text';
30
+ }
31
+ if (c.imageMessage) {
32
+ return 'image';
33
+ }
34
+ if (c.videoMessage) {
35
+ return c.videoMessage.gifPlayback ? 'gif' : 'video';
36
+ }
37
+ if (c.audioMessage) {
38
+ return c.audioMessage.ptt ? 'voice note' : 'audio';
39
+ }
40
+ if (c.stickerMessage) {
41
+ return 'sticker';
42
+ }
43
+ if (c.documentMessage) {
44
+ return 'document';
45
+ }
46
+ if (c.locationMessage || c.liveLocationMessage) {
47
+ return 'location';
48
+ }
49
+ if (c.contactMessage || c.contactsArrayMessage) {
50
+ return 'contact';
51
+ }
52
+ if (c.pollCreationMessage || c.pollCreationMessageV2 || c.pollCreationMessageV3) {
53
+ return 'poll';
54
+ }
55
+ if (c.reactionMessage) {
56
+ return 'reaction';
57
+ }
58
+ if (c.protocolMessage) {
59
+ return 'protocol';
60
+ }
61
+ return 'other';
62
+ };
63
+ const MEDIA_KINDS = new Set(['image', 'video', 'gif', 'audio', 'voice note', 'sticker', 'document', 'location', 'contact']);
64
+ const pad = (n) => String(n).padStart(2, '0');
65
+ /** Official-style export timestamp: `DD/MM/YYYY, HH.MM` (24h). */
66
+ const formatStamp = (tsSeconds) => {
67
+ const d = new Date(tsSeconds * 1000);
68
+ return `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()}, ${pad(d.getHours())}.${pad(d.getMinutes())}`;
69
+ };
70
+ const timestampOf = (msg) => toNumber(msg?.messageTimestamp) || 0;
71
+ const senderNameOf = (msg, resolveName) => {
72
+ const jid = msg?.key?.participant || msg?.key?.remoteJid || '';
73
+ if (resolveName) {
74
+ const resolved = resolveName(jid, msg);
75
+ if (resolved) {
76
+ return resolved;
77
+ }
78
+ }
79
+ if (msg?.pushName) {
80
+ return msg.pushName;
81
+ }
82
+ return jid.split('@')[0] || 'unknown';
83
+ };
84
+ const lineTextOf = (msg, kind, mediaPlaceholders) => {
85
+ if (kind === 'text') {
86
+ return extractMessageText(msg) || '';
87
+ }
88
+ if (kind === 'poll') {
89
+ const c = unwrap(msg.message);
90
+ const poll = c.pollCreationMessage || c.pollCreationMessageV2 || c.pollCreationMessageV3;
91
+ return `POLL: ${poll?.name ?? ''}`.trim();
92
+ }
93
+ if (kind === 'reaction') {
94
+ const c = unwrap(msg.message);
95
+ return `reacted ${c.reactionMessage?.text ?? ''}`.trim();
96
+ }
97
+ if (MEDIA_KINDS.has(kind)) {
98
+ if (mediaPlaceholders === 'descriptive') {
99
+ const caption = extractMessageText(msg);
100
+ return caption ? `<${kind}: ${caption}>` : `<${kind}>`;
101
+ }
102
+ return '<Media omitted>';
103
+ }
104
+ return '';
105
+ };
106
+ const sortAscending = (messages) => [...messages].sort((a, b) => timestampOf(a) - timestampOf(b));
107
+ /**
108
+ * Render messages as an official-WhatsApp-style "Export chat" transcript.
109
+ *
110
+ * ```
111
+ * 14/09/2026, 10.32 - J.AP: halo!
112
+ * 14/09/2026, 10.33 - Rina: <Media omitted>
113
+ * ```
114
+ *
115
+ * Options:
116
+ * - `resolveName(jid, msg)` → display name (falls back to pushName, then number)
117
+ * - `mediaPlaceholders` → 'omitted' (default, official style) | 'descriptive'
118
+ * - `includeReactions` → include reaction lines (default false, like official)
119
+ * - `header` → custom first line; pass '' to disable
120
+ */
121
+ export const exportChatAsText = (messages, options = {}) => {
122
+ if (!Array.isArray(messages)) {
123
+ throw new TypeError('exportChatAsText: messages must be an array');
124
+ }
125
+ const { resolveName, mediaPlaceholders = 'omitted', includeReactions = false, header } = options;
126
+ const lines = [];
127
+ const headerLine = header !== undefined
128
+ ? header
129
+ : 'Messages and calls are end-to-end encrypted. Only people in this chat can read, listen to, or share them.';
130
+ if (headerLine) {
131
+ lines.push(`${messages.length ? formatStamp(timestampOf(sortAscending(messages)[0])) : ''} - ${headerLine}`.trim());
132
+ }
133
+ for (const msg of sortAscending(messages)) {
134
+ const kind = classifyExportMessage(msg);
135
+ if (kind === 'protocol' || kind === 'other') {
136
+ continue;
137
+ }
138
+ if (kind === 'reaction' && !includeReactions) {
139
+ continue;
140
+ }
141
+ const text = lineTextOf(msg, kind, mediaPlaceholders);
142
+ if (!text) {
143
+ continue;
144
+ }
145
+ const stamp = formatStamp(timestampOf(msg));
146
+ const who = senderNameOf(msg, resolveName);
147
+ // multi-line messages: official export keeps continuation lines bare
148
+ const [first, ...restLines] = String(text).split('\n');
149
+ lines.push(`${stamp} - ${who}: ${first}`);
150
+ for (const cont of restLines) {
151
+ lines.push(cont);
152
+ }
153
+ }
154
+ return lines.join('\n');
155
+ };
156
+ /** Export as structured JSON rows (stable shape for archiving/processing). */
157
+ export const exportChatAsJSON = (messages, options = {}) => {
158
+ if (!Array.isArray(messages)) {
159
+ throw new TypeError('exportChatAsJSON: messages must be an array');
160
+ }
161
+ const { resolveName } = options;
162
+ return sortAscending(messages).map((msg) => {
163
+ const kind = classifyExportMessage(msg);
164
+ return {
165
+ id: msg?.key?.id ?? null,
166
+ timestamp: timestampOf(msg),
167
+ fromMe: !!msg?.key?.fromMe,
168
+ senderJid: msg?.key?.participant || msg?.key?.remoteJid || null,
169
+ senderName: senderNameOf(msg, resolveName),
170
+ kind,
171
+ text: kind === 'text' ? (extractMessageText(msg) || '') : (extractMessageText(msg) || null)
172
+ };
173
+ });
174
+ };
175
+ const csvEscape = (value) => {
176
+ const s = value === null || value === undefined ? '' : String(value);
177
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
178
+ };
179
+ /** Export as CSV (same rows as exportChatAsJSON; RFC 4180 quoting). */
180
+ export const exportChatAsCSV = (messages, options = {}) => {
181
+ const rows = exportChatAsJSON(messages, options);
182
+ const headers = ['id', 'timestamp', 'fromMe', 'senderJid', 'senderName', 'kind', 'text'];
183
+ const out = [headers.join(',')];
184
+ for (const row of rows) {
185
+ out.push(headers.map((h) => csvEscape(row[h])).join(','));
186
+ }
187
+ return out.join('\n');
188
+ };
189
+ /**
190
+ * Per-chat statistics: totals, per-sender counts, per-kind counts, busiest
191
+ * hour/day, first/last timestamps, and the top words (≥ minWordLength,
192
+ * lowercased, mentions/URLs stripped).
193
+ */
194
+ export const chatStatistics = (messages, options = {}) => {
195
+ if (!Array.isArray(messages)) {
196
+ throw new TypeError('chatStatistics: messages must be an array');
197
+ }
198
+ const { resolveName, topWords = 10, minWordLength = 3 } = options;
199
+ const stats = {
200
+ total: 0,
201
+ bySender: {},
202
+ byKind: {},
203
+ byHour: Array.from({ length: 24 }, () => 0),
204
+ byWeekday: Array.from({ length: 7 }, () => 0),
205
+ firstTimestamp: null,
206
+ lastTimestamp: null,
207
+ topWords: []
208
+ };
209
+ const wordCounts = new Map();
210
+ for (const msg of messages) {
211
+ const kind = classifyExportMessage(msg);
212
+ if (kind === 'protocol' || kind === 'other') {
213
+ continue;
214
+ }
215
+ stats.total++;
216
+ const who = senderNameOf(msg, resolveName);
217
+ stats.bySender[who] = (stats.bySender[who] || 0) + 1;
218
+ stats.byKind[kind] = (stats.byKind[kind] || 0) + 1;
219
+ const ts = timestampOf(msg);
220
+ if (ts) {
221
+ const d = new Date(ts * 1000);
222
+ stats.byHour[d.getHours()]++;
223
+ stats.byWeekday[d.getDay()]++;
224
+ if (stats.firstTimestamp === null || ts < stats.firstTimestamp) {
225
+ stats.firstTimestamp = ts;
226
+ }
227
+ if (stats.lastTimestamp === null || ts > stats.lastTimestamp) {
228
+ stats.lastTimestamp = ts;
229
+ }
230
+ }
231
+ if (kind === 'text') {
232
+ const text = (extractMessageText(msg) || '')
233
+ .toLowerCase()
234
+ .replace(/https?:\/\/\S+/g, ' ')
235
+ .replace(/@\d{5,20}/g, ' ');
236
+ for (const word of text.split(/[^\p{L}\p{N}_']+/u)) {
237
+ if (word.length >= minWordLength) {
238
+ wordCounts.set(word, (wordCounts.get(word) || 0) + 1);
239
+ }
240
+ }
241
+ }
242
+ }
243
+ stats.topWords = [...wordCounts.entries()]
244
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
245
+ .slice(0, topWords)
246
+ .map(([word, count]) => ({ word, count }));
247
+ return stats;
248
+ };
@@ -22,4 +22,11 @@ export * from "./browser-utils.js";
22
22
  export * from "./companion-reg-client-utils.js";
23
23
  export * from "./identity-change-handler.js";
24
24
  export * from "./stanza-ack.js";
25
+ export * from "./mini-app.js";
26
+ export * from "./transcribe.js";
27
+ export * from "./auto-reconnect.js";
28
+ export * from "./mock-socket.js";
29
+ export * from "./chat-export.js";
30
+ export * from "./message-search.js";
31
+ export * from "./username.js";
25
32
  //# sourceMappingURL=index.d.ts.map
@@ -22,4 +22,11 @@ export * from './browser-utils.js';
22
22
  export * from './companion-reg-client-utils.js';
23
23
  export * from './identity-change-handler.js';
24
24
  export * from './stanza-ack.js';
25
+ export * from './mini-app.js';
26
+ export * from './transcribe.js';
27
+ export * from './auto-reconnect.js';
28
+ export * from './mock-socket.js';
29
+ export * from './chat-export.js';
30
+ export * from './message-search.js';
31
+ export * from './username.js';
25
32
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,44 @@
1
+ import type { WAMessage } from '../Types/index.js';
2
+ export type SearchMessageType = 'text' | 'image' | 'video' | 'document' | 'audio' | 'sticker' | 'location' | 'contact' | 'other';
3
+ export interface SearchOptions {
4
+ jid?: string;
5
+ fromDate?: Date;
6
+ toDate?: Date;
7
+ fromSender?: string;
8
+ fromMe?: boolean;
9
+ messageTypes?: SearchMessageType[];
10
+ limit?: number;
11
+ caseSensitive?: boolean;
12
+ }
13
+ export interface SearchResult {
14
+ message: WAMessage;
15
+ matchedText: string;
16
+ matchPosition: number;
17
+ relevanceScore: number;
18
+ }
19
+ export interface RegexSearchOptions {
20
+ jid?: string;
21
+ fromSender?: string;
22
+ fromMe?: boolean;
23
+ messageTypes?: SearchMessageType[];
24
+ limit?: number;
25
+ }
26
+ export declare const extractMessageText: (message: WAMessage) => string;
27
+ export declare const calculateRelevance: (query: string, text: string, position: number) => number;
28
+ export declare const searchMessages: (messages: WAMessage[], query: string, options?: SearchOptions) => SearchResult[];
29
+ export declare const searchMessagesRegex: (messages: WAMessage[], pattern: RegExp, options?: RegexSearchOptions) => SearchResult[];
30
+ export declare class MessageSearchManager {
31
+ private messages;
32
+ private messageIndex;
33
+ addMessages(messages: WAMessage[]): void;
34
+ removeMessages(messageIds: string[]): void;
35
+ clear(): void;
36
+ get count(): number;
37
+ search(query: string, options?: SearchOptions): SearchResult[];
38
+ searchRegex(pattern: RegExp, options?: RegexSearchOptions): SearchResult[];
39
+ getByJid(jid: string): WAMessage[];
40
+ getBySender(sender: string): WAMessage[];
41
+ getByType(type: SearchMessageType): WAMessage[];
42
+ getById(id: string): WAMessage | undefined;
43
+ }
44
+ export declare const createMessageSearch: () => MessageSearchManager;