chat-adapter-wwebjs 0.1.2 → 0.1.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/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Attachment, FileUpload, AdapterPostableMessage, CardElement, ChatInstance, Message as Message$1, Logger, Author, Adapter, LockScope, ChannelVisibility, WebhookOptions, RawMessage, EmojiValue, FetchOptions, FetchResult, ThreadInfo, ChannelInfo, ListThreadsResult, UserInfo, FormattedContent, BaseFormatConverter, Root } from 'chat';
1
+ import { Attachment, FileUpload, AdapterPostableMessage, CardElement, ChatInstance, Message as Message$1, Logger, Author, Adapter, LockScope, ModalElement, ChannelVisibility, WebhookOptions, RawMessage, StreamChunk, EmojiValue, FetchOptions, FetchResult, ThreadInfo, ChannelInfo, ListThreadsResult, ListThreadsOptions, UserInfo, FormattedContent, BaseFormatConverter, Root } from 'chat';
2
2
  import { MessageMedia, Message, Client, ClientOptions, PollVote, Call, GroupNotification } from 'whatsapp-web.js';
3
3
 
4
4
  /** Describe an inbound message's media as a Chat SDK attachment. */
@@ -9,8 +9,8 @@ declare function download(message: Message, maxBytes?: number): Promise<Buffer>;
9
9
  declare function toMediaList(message: AdapterPostableMessage, maxBytes?: number): Promise<MessageMedia[]>;
10
10
  /**
11
11
  * Convert a single attachment or file upload into WhatsApp media. An attachment
12
- * given only by `url` is fetched from the host's own network, so never pass one
13
- * an end user chose.
12
+ * given only by `url` is fetched over HTTPS, and never from a private or
13
+ * internal address.
14
14
  */
15
15
  declare function toMedia(source: Attachment | FileUpload, maxBytes?: number): Promise<MessageMedia>;
16
16
  /** WhatsApp renders a caption on every media kind except audio. */
@@ -30,22 +30,31 @@ interface WWebJSThreadId {
30
30
  /** Configuration for the whatsapp-web.js adapter. */
31
31
  interface WWebJSAdapterConfig {
32
32
  /**
33
- * Adapter identity used by Chat SDK serialization and thread ID prefixes.
34
- * Set a unique value per account when several run on one `Chat` instance.
35
- * Must not contain `:`. Defaults to `"wwebjs"`.
33
+ * Adapter identity used by Chat SDK serialization, thread ID prefixes and
34
+ * state keys. Set a unique value per account when several run on one `Chat`
35
+ * instance or share one state store. Must not contain `:`. Defaults to
36
+ * `"wwebjs"`.
36
37
  */
37
38
  adapterName?: string;
38
39
  /** Layers that change how cards are sent or messages received; see `numberedActions()`. */
39
40
  addons?: WWebJSAddon[];
40
41
  /**
41
42
  * Messages that arrived while the session was down are delivered once it is
42
- * back, up to this old, in order and each once. Defaults to 1 day; `false`
43
- * turns it off.
43
+ * back, up to this old, oldest first. A restart part-way through delivers
44
+ * them again rather than skip any, and the Chat SDK drops a repeat it has
45
+ * already handled. Defaults to 1 day; `false` turns it off.
44
46
  */
45
47
  catchUpMs?: number | false;
46
48
  /**
47
- * An existing whatsapp-web.js client to drive. When omitted the adapter
48
- * constructs one from {@link WWebJSAdapterConfig.clientOptions}.
49
+ * An existing whatsapp-web.js client, exposed as `adapter.client`. One
50
+ * already started is bridged as it is: `connect()` adopts its session
51
+ * without a second `initialize()`, its options and listeners are left alone,
52
+ * and its lifecycle stays yours — the adapter never reconnects or destroys
53
+ * it, nor closes it on a signal, and `disconnect()` only detaches the
54
+ * adapter. One never started is the adapter's to run, as if it had built
55
+ * it; {@link WWebJSAdapterConfig.manageClient} decides otherwise. When
56
+ * omitted the adapter constructs one from
57
+ * {@link WWebJSAdapterConfig.clientOptions}.
49
58
  */
50
59
  client?: Client;
51
60
  /**
@@ -70,6 +79,15 @@ interface WWebJSAdapterConfig {
70
79
  handleSignals?: boolean;
71
80
  /** Logger instance. Replaced by the Chat SDK logger once initialized. */
72
81
  logger?: Logger;
82
+ /**
83
+ * Force who runs a `client` you passed, whatever its state: `true` has the
84
+ * adapter reconnect it, destroy it on `disconnect()` and close it on a
85
+ * signal; `false` only bridges it. Decided by whether it was started when
86
+ * omitted.
87
+ */
88
+ manageClient?: boolean;
89
+ /** The few phrases a conversational modal sends, to put them in your users' language. */
90
+ modalTexts?: Partial<WWebJSModalTexts>;
73
91
  /**
74
92
  * Acknowledge inbound messages automatically, so the sender sees blue ticks
75
93
  * as soon as the bot receives them. Defaults to `false`.
@@ -101,6 +119,12 @@ interface WWebJSAdapterConfig {
101
119
  * reactions. Defaults to `false`.
102
120
  */
103
121
  receiveOwnMessages?: boolean;
122
+ /**
123
+ * Render what WhatsApp can only imitate: cards in its markup with their
124
+ * images as media, and modals as conversations. Off, a card is plain text
125
+ * and the adapter has no `openModal`. Defaults to `false`.
126
+ */
127
+ richContent?: boolean;
104
128
  /**
105
129
  * Start Chromium with {@link RECOMMENDED_CHROMIUM_ARGS}, which keep it lean
106
130
  * and steady in a container. Defaults to `true`.
@@ -119,13 +143,37 @@ interface WWebJSAdapterConfig {
119
143
  * minute; `false` turns it off.
120
144
  */
121
145
  watchdogIntervalMs?: number | false;
146
+ /**
147
+ * Commands, such as `"/help"`, whose messages reach `onSlashCommand` rather
148
+ * than the message handlers. `"/help me"` arrives as command `/help` with
149
+ * text `"me"`. Any other text starting with `/` stays a message.
150
+ */
151
+ slashCommands?: string[];
152
+ /**
153
+ * How a streamed reply reaches WhatsApp. `"buffer"` sends it once, whole;
154
+ * `"edit"` sends the first words and edits the message as the rest
155
+ * arrives, at most once a second. Defaults to `"buffer"`.
156
+ */
157
+ streaming?: "buffer" | "edit";
122
158
  /** Bot display name. Defaults to `"wwebjs-bot"`. */
123
159
  userName?: string;
124
160
  /**
125
161
  * Send audio as a voice note, played inline with a waveform, rather than as
126
- * a file. Defaults to `true`.
162
+ * a file: `true` for all audio, `"ogg"` for OGG/Opus only, which every
163
+ * phone plays as one, `false` for none. Defaults to `true`.
127
164
  */
128
- voiceNotes?: boolean;
165
+ voiceNotes?: boolean | "ogg";
166
+ }
167
+ /** The phrases a conversational modal sends; `cancel` and `skip` are the words people answer with. */
168
+ interface WWebJSModalTexts {
169
+ cancel: string;
170
+ cancelHint: string;
171
+ cancelled: string;
172
+ invalid: string;
173
+ noResults: string;
174
+ search: string;
175
+ skip: string;
176
+ skipHint: string;
129
177
  }
130
178
  /** What an addon is handed alongside each card or message. */
131
179
  interface WWebJSAddonContext {
@@ -255,6 +303,15 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
255
303
  /** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
256
304
  readonly client: Client;
257
305
  userName: string;
306
+ /**
307
+ * WhatsApp has no modals, so with `richContent` one becomes a conversation:
308
+ * each field is asked in turn, a select by number, and the answers reach
309
+ * `onModalSubmit`. `cancel`, or the modal's `closeLabel`, stops it. Absent
310
+ * otherwise, so the SDK knows a modal cannot open.
311
+ */
312
+ readonly openModal?: (triggerId: string, modal: ModalElement, contextId?: string) => Promise<{
313
+ viewId: string;
314
+ }>;
258
315
  private readonly _config;
259
316
  private readonly _converter;
260
317
  private readonly _ackHandlers;
@@ -271,8 +328,15 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
271
328
  private _state;
272
329
  private _watchdog?;
273
330
  private _strikes;
331
+ private readonly _owned;
332
+ private _attempts;
333
+ private _launch?;
334
+ private _unwatch?;
335
+ private _listeners;
274
336
  private _unsignal?;
275
337
  private _seen?;
338
+ private _behind?;
339
+ private readonly _recent;
276
340
  private _saving;
277
341
  constructor(config?: WWebJSAdapterConfig);
278
342
  /** Where the session stands; a health check reads `connection === "connected"`. */
@@ -287,7 +351,7 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
287
351
  * share one connection attempt.
288
352
  */
289
353
  connect(): Promise<void>;
290
- /** Close the browser session. */
354
+ /** Close the browser session, or only detach from a client the adapter does not manage. */
291
355
  disconnect(): Promise<void>;
292
356
  encodeThreadId(platformData: WWebJSThreadId): string;
293
357
  decodeThreadId(threadId: string): WWebJSThreadId;
@@ -304,16 +368,22 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
304
368
  postChannelMessage(channelId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
305
369
  reply(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
306
370
  editMessage(threadId: string, messageId: string, message: AdapterPostableMessage): Promise<RawMessage<Message>>;
307
- deleteMessage(_threadId: string, messageId: string): Promise<void>;
308
- addReaction(_threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
309
- removeReaction(_threadId: string, messageId: string, _emoji: EmojiValue | string): Promise<void>;
371
+ /** WhatsApp cannot stream, and editing twice a second as the SDK otherwise would floods the chat; the reply goes out once, whole. */
372
+ stream(threadId: string, textStream: AsyncIterable<string | StreamChunk>): Promise<RawMessage<Message> | null>;
373
+ deleteMessage(threadId: string, messageId: string): Promise<void>;
374
+ addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
375
+ removeReaction(threadId: string, messageId: string, _emoji: EmojiValue | string): Promise<void>;
310
376
  fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
311
377
  fetchChannelMessages(channelId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
312
- fetchMessage(_threadId: string, messageId: string): Promise<Message$1<Message> | null>;
378
+ fetchMessage(threadId: string, messageId: string): Promise<Message$1<Message> | null>;
313
379
  fetchThread(threadId: string): Promise<ThreadInfo>;
314
380
  fetchChannelInfo(channelId: string): Promise<ChannelInfo>;
315
- /** WhatsApp conversations are flat, so a channel never contains sub-threads. */
316
- listThreads(): Promise<ListThreadsResult<Message>>;
381
+ /** A WhatsApp chat is one flat conversation, so a channel holds just its own thread. */
382
+ listThreads(channelId: string): Promise<ListThreadsResult<Message>>;
383
+ /** Every chat the account has, newest first, with its latest message: an inbox's list. */
384
+ listChats(options?: ListThreadsOptions): Promise<ListThreadsResult<Message>>;
385
+ private _summaries;
386
+ private _openModal;
317
387
  getUser(userId: string): Promise<UserInfo | null>;
318
388
  /** A number, or its `@c.us` id, resolves to the chat WhatsApp uses for it — often a LID — so a DM is one thread whoever opened it. */
319
389
  openDM(userId: string): Promise<string>;
@@ -383,15 +453,34 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
383
453
  private _clientOptions;
384
454
  private _connect;
385
455
  private _open;
456
+ /** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
457
+ private _watchBrowser;
458
+ /** A client started elsewhere is up when its browser is connected and WhatsApp answers. */
459
+ private _running;
460
+ /** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
461
+ private _close;
462
+ /** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
463
+ private _killBrowser;
386
464
  private _listen;
465
+ private _unlisten;
466
+ private _onReady;
387
467
  private _onMessage;
468
+ private _formKey;
469
+ private _texts;
470
+ private _start;
471
+ /** A reply from someone filling in a modal answers it, before anything else sees it. */
472
+ private _answer;
473
+ /** WhatsApp has no slash commands, so a message naming a declared one becomes one. */
474
+ private _command;
388
475
  private _claimed;
389
476
  private _addons;
390
477
  private _context;
391
478
  private _seenKey;
392
479
  /** Writes run in turn, so an older position never lands after a newer one. */
393
480
  private _save;
481
+ /** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
394
482
  private _remember;
483
+ private _advance;
395
484
  /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
396
485
  private _catchUp;
397
486
  private _onEdit;
@@ -415,6 +504,7 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
415
504
  private _guard;
416
505
  private _isOwn;
417
506
  private _onDisconnected;
507
+ private _reconnects;
418
508
  private _reconnect;
419
509
  private _watch;
420
510
  /** Revives a session that died without an event, or a first connection that failed. */
@@ -428,6 +518,8 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
428
518
  private _page;
429
519
  private _findChat;
430
520
  private _requireChat;
521
+ /** A DM can be addressed by phone or by LID, so only a group's messages must match the thread exactly. */
522
+ private _findMessage;
431
523
  private _requireMessage;
432
524
  }
433
525
  /** Create a WhatsApp adapter backed by whatsapp-web.js. */
@@ -472,16 +564,20 @@ declare function toUser(chatId: string): string;
472
564
  /**
473
565
  * Rewrite Chat SDK mention tokens into WhatsApp's `@number` form and collect
474
566
  * the chat IDs WhatsApp needs alongside the body to render them as mentions.
567
+ * A bare `@number` stays text, so echoing what someone wrote pings no one.
475
568
  */
476
569
  declare function extractMentions(text: string): {
477
570
  mentions: string[];
478
571
  text: string;
479
572
  };
480
573
 
574
+ /** Opaque to the SDK; carries where a modal opens and for whom, since WhatsApp has no trigger of its own. */
575
+ declare function triggerIdOf(threadId: string, userId: string): string;
576
+
481
577
  interface NumberedActionsOptions {
482
578
  /** Also deliver the reply that picked an option as a message. Defaults to `false`. */
483
579
  keepMessage?: boolean;
484
- /** How long a card's options answer to their number or label. Defaults to 1 day. */
580
+ /** How long a card's options answer to their number or label; the first pick ends them. Defaults to 1 day. */
485
581
  ttlMs?: number;
486
582
  }
487
583
  /**
@@ -490,4 +586,4 @@ interface NumberedActionsOptions {
490
586
  */
491
587
  declare function numberedActions(options?: NumberedActionsOptions): WWebJSAddon;
492
588
 
493
- export { type NumberedActionsOptions, RECOMMENDED_CHROMIUM_ARGS, type WWebJSAck, type WWebJSAckHandler, type WWebJSAckStatus, WWebJSAdapter, type WWebJSAdapterConfig, type WWebJSAddon, type WWebJSAddonContext, type WWebJSCallHandler, type WWebJSConnection, WWebJSFormatConverter, type WWebJSGroupEvent, type WWebJSGroupEventHandler, type WWebJSGroupParticipant, type WWebJSPollVote, type WWebJSPollVoteHandler, type WWebJSSendEventArgs, type WWebJSSendLocationArgs, type WWebJSSendPollArgs, type WWebJSThreadId, createWWebJSAdapter, download, extractMentions, isAudio, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, numberedActions, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser };
589
+ export { type NumberedActionsOptions, RECOMMENDED_CHROMIUM_ARGS, type WWebJSAck, type WWebJSAckHandler, type WWebJSAckStatus, WWebJSAdapter, type WWebJSAdapterConfig, type WWebJSAddon, type WWebJSAddonContext, type WWebJSCallHandler, type WWebJSConnection, WWebJSFormatConverter, type WWebJSGroupEvent, type WWebJSGroupEventHandler, type WWebJSGroupParticipant, type WWebJSModalTexts, type WWebJSPollVote, type WWebJSPollVoteHandler, type WWebJSSendEventArgs, type WWebJSSendLocationArgs, type WWebJSSendPollArgs, type WWebJSThreadId, createWWebJSAdapter, download, extractMentions, isAudio, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, numberedActions, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser, triggerIdOf };