@wppconnect-team/wppconnect 2.3.3 → 2.3.5

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/CHANGELOG.md CHANGED
@@ -1,3 +1,45 @@
1
+ ## <small>2.3.5 (2026-10-15)</small>
2
+
3
+ ### Bug Fixes
4
+
5
+ - **auth:** cancel pending QR attempts on close (#2915) ([1ada250](https://github.com/wppconnect-team/wppconnect/commit/1ada250)), closes [#2915](https://github.com/wppconnect-team/wppconnect/issues/2915)
6
+ - **browser:** tolerate slow WPP.isReady during injection (#2909) ([9ab531c](https://github.com/wppconnect-team/wppconnect/commit/9ab531c)), closes [#2909](https://github.com/wppconnect-team/wppconnect/issues/2909) [#2873](https://github.com/wppconnect-team/wppconnect/issues/2873)
7
+ - bump wa-js version to 4.7.1 (#2917) ([f988414](https://github.com/wppconnect-team/wppconnect/commit/f988414)), closes [#2917](https://github.com/wppconnect-team/wppconnect/issues/2917)
8
+
9
+ ### Build System
10
+
11
+ - **deps-dev:** bump handlebars from 4.7.9 to 4.7.10 (#2911) ([22184d9](https://github.com/wppconnect-team/wppconnect/commit/22184d9)), closes [#2911](https://github.com/wppconnect-team/wppconnect/issues/2911)
12
+ - **deps-dev:** bump markdown-it from 14.3.0 to 14.3.2 (#2901) ([820ef4e](https://github.com/wppconnect-team/wppconnect/commit/820ef4e)), closes [#2901](https://github.com/wppconnect-team/wppconnect/issues/2901)
13
+ - **deps-dev:** update commitlint monorepo to ^21.2.3 (#2903) ([6ab0ccc](https://github.com/wppconnect-team/wppconnect/commit/6ab0ccc)), closes [#2903](https://github.com/wppconnect-team/wppconnect/issues/2903)
14
+ - **deps-dev:** update dependency @babel/eslint-parser to ^7.29.9 (#2904) ([a1c771b](https://github.com/wppconnect-team/wppconnect/commit/a1c771b)), closes [#2904](https://github.com/wppconnect-team/wppconnect/issues/2904)
15
+ - **deps-dev:** update dependency concurrently to ^10.0.6 (#2913) ([2c44b8e](https://github.com/wppconnect-team/wppconnect/commit/2c44b8e)), closes [#2913](https://github.com/wppconnect-team/wppconnect/issues/2913)
16
+ - **deps-dev:** update dependency eslint to v10.12.0 (#2908) ([f115c57](https://github.com/wppconnect-team/wppconnect/commit/f115c57)), closes [#2908](https://github.com/wppconnect-team/wppconnect/issues/2908)
17
+ - **deps-dev:** update dependency globals to ^17.13.0 (#2910) ([c2b3f7b](https://github.com/wppconnect-team/wppconnect/commit/c2b3f7b)), closes [#2910](https://github.com/wppconnect-team/wppconnect/issues/2910)
18
+ - **deps-dev:** update dependency mocha to v12 (#2889) ([0d922dd](https://github.com/wppconnect-team/wppconnect/commit/0d922dd)), closes [#2889](https://github.com/wppconnect-team/wppconnect/issues/2889)
19
+ - **deps-dev:** update dependency release-it to ^21.1.1 (#2914) ([05b2463](https://github.com/wppconnect-team/wppconnect/commit/05b2463)), closes [#2914](https://github.com/wppconnect-team/wppconnect/issues/2914)
20
+ - **deps-dev:** update dependency typescript-eslint to ^8.71.2 (#2916) ([e1a8767](https://github.com/wppconnect-team/wppconnect/commit/e1a8767)), closes [#2916](https://github.com/wppconnect-team/wppconnect/issues/2916)
21
+ - **deps:** update dependency @img/sharp-win32-x64 to ^0.35.5 (#2905) ([3a313d7](https://github.com/wppconnect-team/wppconnect/commit/3a313d7)), closes [#2905](https://github.com/wppconnect-team/wppconnect/issues/2905)
22
+ - **deps:** update dependency sharp to v0.35.5 [security] (#2907) ([79fa1aa](https://github.com/wppconnect-team/wppconnect/commit/79fa1aa)), closes [#2907](https://github.com/wppconnect-team/wppconnect/issues/2907)
23
+
24
+ ## <small>2.3.4 (2026-10-02)</small>
25
+
26
+ ### Bug Fixes
27
+
28
+ - bump wa-js version to 4.6.1 (#2898) ([dd904d4](https://github.com/wppconnect-team/wppconnect/commit/dd904d4)), closes [#2898](https://github.com/wppconnect-team/wppconnect/issues/2898)
29
+
30
+ ### Build System
31
+
32
+ - **deps-dev:** bump browserslist from 4.28.2 to 4.28.8 (#2883) ([ff9f551](https://github.com/wppconnect-team/wppconnect/commit/ff9f551)), closes [#2883](https://github.com/wppconnect-team/wppconnect/issues/2883)
33
+ - **deps-dev:** bump fast-uri from 3.1.5 to 3.1.7 (#2884) ([824f6e1](https://github.com/wppconnect-team/wppconnect/commit/824f6e1)), closes [#2884](https://github.com/wppconnect-team/wppconnect/issues/2884)
34
+ - **deps:** bump brace-expansion (#2900) ([f32645b](https://github.com/wppconnect-team/wppconnect/commit/f32645b)), closes [#2900](https://github.com/wppconnect-team/wppconnect/issues/2900)
35
+ - **deps:** bump ip-address from 10.5.0 to 10.7.2 (#2897) ([505466e](https://github.com/wppconnect-team/wppconnect/commit/505466e)), closes [#2897](https://github.com/wppconnect-team/wppconnect/issues/2897)
36
+ - **deps:** bump js-yaml from 4.3.1 to 4.3.2 (#2893) ([39a1e46](https://github.com/wppconnect-team/wppconnect/commit/39a1e46)), closes [#2893](https://github.com/wppconnect-team/wppconnect/issues/2893)
37
+ - **deps:** update dependency serialize-javascript to v7.1.2 [security] (#2899) ([b96bbd1](https://github.com/wppconnect-team/wppconnect/commit/b96bbd1)), closes [#2899](https://github.com/wppconnect-team/wppconnect/issues/2899)
38
+
39
+ ### Continuous Integration
40
+
41
+ - list every commit type in release notes (#2902) ([954be8c](https://github.com/wppconnect-team/wppconnect/commit/954be8c)), closes [#2902](https://github.com/wppconnect-team/wppconnect/issues/2902)
42
+
1
43
  ## [2.3.3](https://github.com/wppconnect-team/wppconnect/compare/v2.3.2...v2.3.3) (2026-09-07)
2
44
 
3
45
  ### Bug Fixes
@@ -15,7 +15,12 @@ export declare class HostLayer {
15
15
  protected isInitialized: boolean;
16
16
  protected isInjected: boolean;
17
17
  protected pageLoadPromise?: Promise<void>;
18
+ protected pageLoadAbort?: AbortController;
19
+ protected injectionStartedAt?: number;
20
+ protected documentWatch?: Promise<void>;
21
+ protected isNavigating: boolean;
18
22
  protected isStarted: boolean;
23
+ protected qrLoopCancelled: boolean;
19
24
  protected isLogged: boolean;
20
25
  protected isInChat: boolean;
21
26
  protected checkStartInterval?: NodeJS.Timer;
@@ -28,11 +33,20 @@ export declare class HostLayer {
28
33
  constructor(page: Page, session?: string, options?: CreateConfig);
29
34
  protected log(level: LogLevel, message: string, meta?: object): void;
30
35
  protected initialize(): Promise<void>;
31
- protected afterPageLoad(): Promise<void>;
36
+ protected watchDocumentChanges(): Promise<void>;
37
+ protected afterPageLoad(signal?: AbortSignal): Promise<void>;
38
+ protected waitForNavigationCommit(signal?: AbortSignal): Promise<void>;
39
+ protected isInjectionExpired(): boolean;
32
40
  protected afterPageScriptInjected(): Promise<void>;
33
41
  start(): Promise<void>;
34
42
  protected checkStart(): Promise<void>;
35
43
  protected checkQrCode(): Promise<void>;
44
+ /**
45
+ * Stop QR attempts and suppress pending QR callbacks for this client.
46
+ * Create a new client to start pairing again.
47
+ * @category Host
48
+ */
49
+ cancelQrLoop(): void;
36
50
  protected loginByCode(phone: string): Promise<void>;
37
51
  protected onLinkCode(code: string): void;
38
52
  /**
@@ -33,7 +33,12 @@ class HostLayer {
33
33
  isInitialized = false;
34
34
  isInjected = false;
35
35
  pageLoadPromise;
36
+ pageLoadAbort;
37
+ injectionStartedAt;
38
+ documentWatch;
39
+ isNavigating = false;
36
40
  isStarted = false;
41
+ qrLoopCancelled = false;
37
42
  isLogged = false;
38
43
  isInChat = false;
39
44
  checkStartInterval = null;
@@ -68,37 +73,107 @@ class HostLayer {
68
73
  this.page.on('load', () => {
69
74
  this.log('verbose', 'Page loaded', { type: 'page' });
70
75
  this.isInjected = false;
76
+ // One budget per injection cycle, so a reload loop cannot extend it
77
+ this.injectionStartedAt ??= Date.now();
78
+ // Also aborted on document change; this covers pages without a CDP session
79
+ this.pageLoadAbort?.abort();
80
+ const abort = new AbortController();
81
+ this.pageLoadAbort = abort;
71
82
  const previousPageLoad = this.pageLoadPromise?.catch(() => undefined);
72
- const pageLoad = (previousPageLoad || Promise.resolve()).then(() => this.afterPageLoad());
83
+ const pageLoad = (previousPageLoad || Promise.resolve()).then(() => this.afterPageLoad(abort.signal));
73
84
  this.pageLoadPromise = pageLoad;
74
85
  void pageLoad.catch(() => undefined);
75
86
  });
87
+ this.documentWatch = this.watchDocumentChanges();
76
88
  this.isInitialized = true;
77
89
  }
78
- async afterPageLoad() {
90
+ async watchDocumentChanges() {
91
+ try {
92
+ // Page 'framenavigated' also fires on pushState; these CDP events only for a new document
93
+ const session = await this.page.createCDPSession();
94
+ await session.send('Page.enable');
95
+ const { frameTree } = await session.send('Page.getFrameTree');
96
+ let mainFrameId = frameTree.frame.id;
97
+ // Steps in flight fail from here on, before the new document exists
98
+ session.on('Page.frameStartedNavigating', (event) => {
99
+ if (event.frameId === mainFrameId &&
100
+ !/samedocument/i.test(event.navigationType)) {
101
+ this.isNavigating = true;
102
+ }
103
+ });
104
+ session.on('Page.frameNavigated', ({ frame }) => {
105
+ if (frame.parentId)
106
+ return;
107
+ mainFrameId = frame.id;
108
+ this.isNavigating = false;
109
+ this.isInjected = false;
110
+ this.pageLoadAbort?.abort();
111
+ });
112
+ }
113
+ catch (error) {
114
+ this.log('warn', 'Could not watch document changes', { error });
115
+ }
116
+ }
117
+ async afterPageLoad(signal) {
118
+ if (signal?.aborted) {
119
+ return;
120
+ }
79
121
  this.log('verbose', 'Injecting wapi.js');
80
- const options = {
81
- deviceName: this.options.deviceName,
82
- disableGoogleAnalytics: this.options.disableGoogleAnalytics,
83
- googleAnalyticsId: this.options.googleAnalyticsId,
84
- linkPreviewApiServers: this.options.linkPreviewApiServers,
85
- poweredBy: this.options.poweredBy,
86
- };
87
- await (0, helpers_1.evaluateAndReturn)(this.page, (options) => {
88
- window.WPPConfig = options;
89
- }, options);
90
122
  try {
91
- await (0, browser_1.injectApi)(this.page, this.onLoadingScreen);
92
- this.isInjected = true;
93
- this.log('verbose', 'wapi.js injected');
94
- this.afterPageScriptInjected();
123
+ await (0, browser_1.injectApi)(this.page, this.onLoadingScreen, {
124
+ timeout: this.options.injectionTimeout,
125
+ startedAt: this.injectionStartedAt,
126
+ signal,
127
+ config: {
128
+ deviceName: this.options.deviceName,
129
+ disableGoogleAnalytics: this.options.disableGoogleAnalytics,
130
+ googleAnalyticsId: this.options.googleAnalyticsId,
131
+ linkPreviewApiServers: this.options.linkPreviewApiServers,
132
+ poweredBy: this.options.poweredBy,
133
+ },
134
+ });
95
135
  }
96
136
  catch (error) {
137
+ if (this.isNavigating) {
138
+ await this.waitForNavigationCommit(signal);
139
+ }
140
+ // A newer document owns the page now; its injection decides the outcome
141
+ if (signal?.aborted) {
142
+ this.log('verbose', 'wapi.js injection superseded by page reload');
143
+ return;
144
+ }
145
+ const failure = this.isInjectionExpired() && !(error instanceof browser_1.InjectionTimeoutError)
146
+ ? new browser_1.InjectionTimeoutError(this.options.injectionTimeout, {
147
+ cause: error,
148
+ })
149
+ : error;
150
+ this.injectionStartedAt = undefined;
97
151
  this.log('verbose', 'wapi.js failed');
98
- this.log('error', error);
99
- throw error;
152
+ this.log('error', failure);
153
+ throw failure;
154
+ }
155
+ if (signal?.aborted) {
156
+ return;
157
+ }
158
+ this.injectionStartedAt = undefined;
159
+ this.isInjected = true;
160
+ this.log('verbose', 'wapi.js injected');
161
+ this.afterPageScriptInjected().catch((error) => this.log('error', error));
162
+ }
163
+ async waitForNavigationCommit(signal) {
164
+ while (this.isNavigating &&
165
+ !signal?.aborted &&
166
+ !this.page.isClosed() &&
167
+ !this.isInjectionExpired()) {
168
+ await (0, sleep_1.sleep)(50);
100
169
  }
101
170
  }
171
+ isInjectionExpired() {
172
+ const timeout = this.options.injectionTimeout;
173
+ return (timeout > 0 &&
174
+ this.injectionStartedAt !== undefined &&
175
+ Date.now() >= this.injectionStartedAt + timeout);
176
+ }
102
177
  async afterPageScriptInjected() {
103
178
  this.getWAVersion()
104
179
  .then((version) => {
@@ -125,23 +200,27 @@ class HostLayer {
125
200
  await (0, helpers_1.evaluateAndReturn)(this.page, () => {
126
201
  WPP.on('conn.auth_code_change', window.checkQrCode);
127
202
  }).catch(() => null);
128
- this.checkQrCode();
203
+ this.checkQrCode().catch((error) => this.log('error', error));
129
204
  }
130
- this.checkInChat();
205
+ this.checkInChat().catch((error) => this.log('error', error));
131
206
  }
132
207
  async start() {
133
208
  if (this.isStarted) {
134
209
  return;
135
210
  }
136
211
  this.isStarted = true;
212
+ await this.documentWatch;
137
213
  await (0, browser_1.initWhatsapp)(this.page, null, false, this.options.whatsappVersion, this.options.proxy, this.log.bind(this));
138
214
  await this.page.exposeFunction('checkQrCode', () => this.checkQrCode());
139
215
  await this.page.exposeFunction('onLinkCode', (code) => this.onLinkCode(code));
140
216
  await this.page.exposeFunction('onLinkCodeExpired', () => this.log('warn', 'Login by code expired; call refreshLinkCode() to retry'));
141
217
  await this.page.exposeFunction('onLinkCodeError', (message) => this.log('error', `Login by code failed: ${message}`));
142
218
  await this.page.exposeFunction('checkInChat', () => this.checkInChat());
143
- this.checkStartInterval = setInterval(() => this.checkStart(), 5000);
219
+ if (!this.qrLoopCancelled) {
220
+ this.checkStartInterval = setInterval(() => this.checkStart(), 5000);
221
+ }
144
222
  this.page.on('close', () => {
223
+ this.cancelQrLoop();
145
224
  clearInterval(this.checkStartInterval);
146
225
  });
147
226
  }
@@ -151,7 +230,11 @@ class HostLayer {
151
230
  .catch(() => null);
152
231
  }
153
232
  async checkQrCode() {
233
+ if (this.qrLoopCancelled || this.page.isClosed())
234
+ return;
154
235
  const needScan = await (0, auth_1.needsToScan)(this.page).catch(() => null);
236
+ if (this.qrLoopCancelled || this.page.isClosed())
237
+ return;
155
238
  // A navigation can invalidate the execution context while waiting for QR.
156
239
  // An unknown result is not proof that the session has registered.
157
240
  if (needScan === null)
@@ -162,6 +245,8 @@ class HostLayer {
162
245
  return;
163
246
  }
164
247
  const result = await this.getQrCode();
248
+ if (this.qrLoopCancelled || this.page.isClosed())
249
+ return;
165
250
  if (!result?.urlCode || this.urlCode === result.urlCode) {
166
251
  return;
167
252
  }
@@ -171,6 +256,8 @@ class HostLayer {
171
256
  if (this.options.logQR || this.catchQR) {
172
257
  qr = await (0, auth_1.asciiQr)(this.urlCode);
173
258
  }
259
+ if (this.qrLoopCancelled || this.page.isClosed())
260
+ return;
174
261
  if (this.options.logQR) {
175
262
  this.log('info', `Waiting for QRCode Scan (Attempt ${this.attempt})...:\n${qr}`, { code: this.urlCode });
176
263
  }
@@ -179,6 +266,15 @@ class HostLayer {
179
266
  }
180
267
  this.catchQR?.(result.base64Image, qr, this.attempt, result.urlCode);
181
268
  }
269
+ /**
270
+ * Stop QR attempts and suppress pending QR callbacks for this client.
271
+ * Create a new client to start pairing again.
272
+ * @category Host
273
+ */
274
+ cancelQrLoop() {
275
+ this.qrLoopCancelled = true;
276
+ clearInterval(this.checkStartInterval);
277
+ }
182
278
  async loginByCode(phone) {
183
279
  await (0, helpers_1.evaluateAndReturn)(this.page, async ({ phone }) => {
184
280
  await WPP.conn.startLinkDeviceCodeForPhoneNumber(phone);
@@ -295,11 +391,22 @@ class HostLayer {
295
391
  await (0, sleep_1.sleep)(50);
296
392
  continue;
297
393
  }
298
- await pageLoad;
299
- if (pageLoad === this.pageLoadPromise && this.isInjected) {
300
- await this.page.waitForFunction(() => WPP.isReady);
394
+ const failure = await pageLoad.then(() => null, (error) => ({ error }));
395
+ // Superseded by a newer load: wait for that injection instead
396
+ if (pageLoad !== this.pageLoadPromise) {
397
+ continue;
398
+ }
399
+ if (failure) {
400
+ throw failure.error;
401
+ }
402
+ if (this.isInjected) {
301
403
  return;
302
404
  }
405
+ // Superseded by a navigation whose 'load' has not fired yet
406
+ if (this.isInjectionExpired()) {
407
+ throw new browser_1.InjectionTimeoutError(this.options.injectionTimeout);
408
+ }
409
+ await (0, sleep_1.sleep)(50);
303
410
  }
304
411
  throw new Error('Page closed before WAPI injection completed');
305
412
  }
@@ -169,6 +169,7 @@ class Whatsapp extends business_layer_1.BusinessLayer {
169
169
  * @internal
170
170
  */
171
171
  async close() {
172
+ this.cancelQrLoop();
172
173
  const browser = this.page.browser();
173
174
  if (!this.page.isClosed()) {
174
175
  await this.page.close().catch(() => null);
@@ -67,6 +67,12 @@ export interface CreateConfig {
67
67
  * @default 180000 (3 minutes)
68
68
  */
69
69
  deviceSyncTimeout?: number;
70
+ /**
71
+ * Time in ms for wa-js to be injected and `WPP.isReady`, from the first page load (reloads share it).
72
+ * Exceeding it fails the page load with `InjectionTimeoutError`; 0 waits until ready or closed.
73
+ * @default 120000 (2 minutes)
74
+ */
75
+ injectionTimeout?: number;
70
76
  /**
71
77
  * Wait for in chat to return a instance of {@link Whatsapp}
72
78
  * @default false
@@ -16,6 +16,7 @@ exports.defaultOptions = {
16
16
  updatesLog: true,
17
17
  autoClose: 60000,
18
18
  deviceSyncTimeout: 180000,
19
+ injectionTimeout: 120000,
19
20
  createPathFileToken: true,
20
21
  waitForLogin: true,
21
22
  logger: logger_1.defaultLogger,
@@ -17,7 +17,27 @@ export declare function initWhatsapp(page: Page, token?: SessionToken, clear?: b
17
17
  password: string;
18
18
  }, log?: (level: LogLevel, message: string, meta?: object) => any): Promise<Page>;
19
19
  export declare function onLoadingScreen(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback): Promise<void>;
20
- export declare function injectApi(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback): Promise<void>;
20
+ export interface WaitForReadyOptions {
21
+ /** Milliseconds; 0 waits until ready, aborted or closed */
22
+ timeout?: number;
23
+ /** Epoch ms the timeout counts from; defaults to the call time */
24
+ startedAt?: number;
25
+ signal?: AbortSignal;
26
+ }
27
+ export interface InjectApiOptions extends WaitForReadyOptions {
28
+ /** Assigned to window.WPPConfig before wa-js loads */
29
+ config?: object;
30
+ }
31
+ export declare class InjectionTimeoutError extends Error {
32
+ readonly timeout: number;
33
+ name: string;
34
+ constructor(timeout: number, options?: ErrorOptions);
35
+ }
36
+ /**
37
+ * Waits for WAPI, Store and WPP.isReady on the current document
38
+ */
39
+ export declare function waitForWppReady(page: Page, options?: WaitForReadyOptions): Promise<void>;
40
+ export declare function injectApi(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback, options?: InjectApiOptions): Promise<void>;
21
41
  /**
22
42
  * Initializes browser, will try to use chrome as default
23
43
  * @param session
@@ -52,10 +52,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
52
52
  return (mod && mod.__esModule) ? mod : { "default": mod };
53
53
  };
54
54
  Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.InjectionTimeoutError = void 0;
55
56
  exports.unregisterServiceWorker = unregisterServiceWorker;
56
57
  exports.setWhatsappVersion = setWhatsappVersion;
57
58
  exports.initWhatsapp = initWhatsapp;
58
59
  exports.onLoadingScreen = onLoadingScreen;
60
+ exports.waitForWppReady = waitForWppReady;
59
61
  exports.injectApi = injectApi;
60
62
  exports.initBrowser = initBrowser;
61
63
  exports.getOrCreatePage = getOrCreatePage;
@@ -213,34 +215,117 @@ async function onLoadingScreen(page, onLoadingScreenCallBack) {
213
215
  PROGRESS_MESSAGE_NEW_THEME: "//*[@id='app']/div/div/div[2]",
214
216
  });
215
217
  }
216
- async function injectApi(page, onLoadingScreenCallBack) {
218
+ class InjectionTimeoutError extends Error {
219
+ timeout;
220
+ name = 'InjectionTimeoutError';
221
+ constructor(timeout, options) {
222
+ super(`WPP.isReady not reached after ${timeout}ms`, options);
223
+ this.timeout = timeout;
224
+ }
225
+ }
226
+ exports.InjectionTimeoutError = InjectionTimeoutError;
227
+ const isTimeoutError = (error) => error instanceof Error && error.name === 'TimeoutError';
228
+ /**
229
+ * Waits for WAPI, Store and WPP.isReady on the current document
230
+ */
231
+ async function waitForWppReady(page, options = {}) {
232
+ // Explicit timeout so puppeteer's 30s default never applies
233
+ const timeout = options.timeout ?? 0;
234
+ const startedAt = options.startedAt ?? Date.now();
235
+ const deadline = timeout > 0 ? startedAt + timeout : Infinity;
236
+ // puppeteer ignores a signal that is already aborted
237
+ options.signal?.throwIfAborted();
238
+ try {
239
+ await page.waitForFunction(() => {
240
+ return (typeof window.WAPI !== 'undefined' &&
241
+ typeof window.Store !== 'undefined' &&
242
+ !!window.WPP?.isReady);
243
+ }, {
244
+ // 0 would mean no limit to puppeteer
245
+ timeout: deadline === Infinity ? 0 : Math.max(deadline - Date.now(), 1),
246
+ signal: options.signal,
247
+ });
248
+ }
249
+ catch (error) {
250
+ if (isTimeoutError(error)) {
251
+ throw new InjectionTimeoutError(timeout, { cause: error });
252
+ }
253
+ // puppeteer's own 30s wait for an execution context: still loading
254
+ if (isTimeoutError(error?.cause) && !page.isClosed()) {
255
+ return waitForWppReady(page, { ...options, startedAt });
256
+ }
257
+ throw error;
258
+ }
259
+ }
260
+ async function injectApi(page, onLoadingScreenCallBack, options = {}) {
261
+ const timeout = options.timeout ?? 0;
262
+ const startedAt = options.startedAt ?? Date.now();
263
+ // Stops the remaining steps once superseded or out of time
264
+ const controller = new AbortController();
265
+ const abort = () => controller.abort();
266
+ if (options.signal?.aborted)
267
+ abort();
268
+ options.signal?.addEventListener('abort', abort);
269
+ let timer;
270
+ const expired = new Promise((_, reject) => {
271
+ if (timeout > 0) {
272
+ timer = setTimeout(() => {
273
+ reject(new InjectionTimeoutError(timeout));
274
+ abort();
275
+ }, startedAt + timeout - Date.now());
276
+ }
277
+ });
278
+ try {
279
+ // A step stuck in a starved renderer must not stretch the deadline
280
+ await Promise.race([
281
+ runInjection(page, onLoadingScreenCallBack, {
282
+ ...options,
283
+ startedAt,
284
+ signal: controller.signal,
285
+ }),
286
+ expired,
287
+ ]);
288
+ }
289
+ finally {
290
+ clearTimeout(timer);
291
+ options.signal?.removeEventListener('abort', abort);
292
+ }
293
+ }
294
+ async function runInjection(page, onLoadingScreenCallBack, options) {
295
+ const { signal } = options;
296
+ if (options.config) {
297
+ await page.evaluate((config) => {
298
+ window.WPPConfig = config;
299
+ }, options.config);
300
+ }
217
301
  const injected = await page
218
302
  .evaluate(() => {
219
- // @ts-ignore
220
- return (typeof window.WAPI !== 'undefined' &&
303
+ // wapi.js defines WAPI and Store even when wa-js is missing
304
+ return (typeof window.WPP !== 'undefined' &&
305
+ typeof window.WAPI !== 'undefined' &&
221
306
  typeof window.Store !== 'undefined');
222
307
  })
223
308
  .catch(() => false);
224
- if (injected) {
225
- return;
309
+ // Stop between steps so a superseded injection does not keep writing
310
+ if (!injected) {
311
+ signal?.throwIfAborted();
312
+ await page.addScriptTag({
313
+ path: require.resolve('@wppconnect/wa-js'),
314
+ });
315
+ signal?.throwIfAborted();
316
+ await page.evaluate(() => {
317
+ WPP.chat.defaultSendMessageOptions.createChat = true;
318
+ WPP.conn.setKeepAlive(true);
319
+ });
320
+ signal?.throwIfAborted();
321
+ await page.addScriptTag({
322
+ path: require.resolve(path.join(__dirname, '../../dist/lib/wapi', 'wapi.js')),
323
+ });
324
+ signal?.throwIfAborted();
325
+ await onLoadingScreen(page, onLoadingScreenCallBack);
226
326
  }
227
- await page.addScriptTag({
228
- path: require.resolve('@wppconnect/wa-js'),
229
- });
230
- await page.evaluate(() => {
231
- WPP.chat.defaultSendMessageOptions.createChat = true;
232
- WPP.conn.setKeepAlive(true);
233
- });
234
- await page.addScriptTag({
235
- path: require.resolve(path.join(__dirname, '../../dist/lib/wapi', 'wapi.js')),
236
- });
237
- await onLoadingScreen(page, onLoadingScreenCallBack);
238
327
  // Make sure WAPI is initialized
239
- await page.waitForFunction(() => {
240
- return (typeof window.WAPI !== 'undefined' &&
241
- typeof window.Store !== 'undefined' &&
242
- window.WPP.isReady);
243
- });
328
+ await waitForWppReady(page, options);
244
329
  }
245
330
  /**
246
331
  * Initializes browser, will try to use chrome as default
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from './api/model';
3
3
  export * from './api/model/enum';
4
4
  export { Whatsapp } from './api/whatsapp';
5
5
  export { CreateConfig } from './config/create-config';
6
+ export { InjectionTimeoutError } from './controllers/browser';
6
7
  export { create } from './controllers/initializer';
7
8
  export { defaultLogger } from './utils/logger';
8
9
  export * as tokenStore from './token-store';
package/dist/index.js CHANGED
@@ -36,11 +36,13 @@ var __importStar = (this && this.__importStar) || (function () {
36
36
  };
37
37
  })();
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.tokenStore = exports.defaultLogger = exports.create = exports.Whatsapp = void 0;
39
+ exports.tokenStore = exports.defaultLogger = exports.create = exports.InjectionTimeoutError = exports.Whatsapp = void 0;
40
40
  __exportStar(require("./api/model"), exports);
41
41
  __exportStar(require("./api/model/enum"), exports);
42
42
  var whatsapp_1 = require("./api/whatsapp");
43
43
  Object.defineProperty(exports, "Whatsapp", { enumerable: true, get: function () { return whatsapp_1.Whatsapp; } });
44
+ var browser_1 = require("./controllers/browser");
45
+ Object.defineProperty(exports, "InjectionTimeoutError", { enumerable: true, get: function () { return browser_1.InjectionTimeoutError; } });
44
46
  var initializer_1 = require("./controllers/initializer");
45
47
  Object.defineProperty(exports, "create", { enumerable: true, get: function () { return initializer_1.create; } });
46
48
  var logger_1 = require("./utils/logger");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wppconnect-team/wppconnect",
3
- "version": "2.3.3",
3
+ "version": "2.3.5",
4
4
  "description": "WPPConnect is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node, which can be used to support the creation of any interaction, such as customer service, media sending, intelligence recognition based on phrases artificial and many other things, use your imagination... 😀🤔💭",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,9 +8,9 @@
8
8
  "build:client": "tsc",
9
9
  "build:wapi": "cd src/lib/wapi/ && webpack",
10
10
  "build": "npm run build:wapi && npm run build:client",
11
- "changelog:last": "conventional-changelog -p angular -r 2",
12
- "changelog:preview": "conventional-changelog -p angular -u",
13
- "changelog:update": "conventional-changelog -p angular -i CHANGELOG.md -s",
11
+ "changelog:last": "conventional-changelog -n ./changelog.config.cjs -r 2",
12
+ "changelog:preview": "conventional-changelog -n ./changelog.config.cjs -u",
13
+ "changelog:update": "conventional-changelog -n ./changelog.config.cjs -i CHANGELOG.md -s",
14
14
  "clean": "shx rm -rf session dist",
15
15
  "example": "node ./examples/basic/index.js",
16
16
  "commit": "cz",
@@ -56,12 +56,12 @@
56
56
  "homepage": "https://github.com/wppconnect-team/wppconnect#readme",
57
57
  "devDependencies": {
58
58
  "@babel/core": "^7.29.7",
59
- "@babel/eslint-parser": "^7.29.7",
59
+ "@babel/eslint-parser": "^7.29.9",
60
60
  "@babel/eslint-plugin": "^7.29.7",
61
61
  "@babel/preset-env": "^7.29.7",
62
- "@commitlint/cli": "^21.2.2",
63
- "@commitlint/config-conventional": "^21.2.2",
64
- "@commitlint/cz-commitlint": "^21.2.2",
62
+ "@commitlint/cli": "^21.2.3",
63
+ "@commitlint/config-conventional": "^21.2.3",
64
+ "@commitlint/cz-commitlint": "^21.2.3",
65
65
  "@eslint/js": "^10.0.1",
66
66
  "@tony.ganchev/eslint-plugin-header": "^3.4.4",
67
67
  "@types/atob": "^2.1.4",
@@ -73,28 +73,28 @@
73
73
  "@types/ws": "^8.18.1",
74
74
  "babel-loader": "^10.1.1",
75
75
  "commitizen": "^4.3.2",
76
- "concurrently": "^10.0.5",
76
+ "concurrently": "^10.0.6",
77
77
  "conventional-changelog-cli": "^5.0.0",
78
- "eslint": "10.10.0",
78
+ "eslint": "10.12.0",
79
79
  "eslint-config-prettier": "^10.1.8",
80
80
  "eslint-plugin-prettier": "^5.5.6",
81
- "globals": "^17.12.0",
81
+ "globals": "^17.13.0",
82
82
  "husky": "^9.1.7",
83
- "mocha": "^11.8.0",
83
+ "mocha": "^12.0.3",
84
84
  "prettier": "^2.8.8",
85
85
  "pretty-quick": "^4.2.2",
86
86
  "regenerator-runtime": "^0.14.1",
87
- "release-it": "^21.0.2",
87
+ "release-it": "^21.1.1",
88
88
  "shx": "^0.4.0",
89
89
  "ts-node": "^10.9.2",
90
90
  "typedoc": "^0.28.20",
91
91
  "typescript": "^5.9.3",
92
- "typescript-eslint": "^8.69.0",
92
+ "typescript-eslint": "^8.71.2",
93
93
  "webpack": "^5.110.3",
94
94
  "webpack-cli": "^6.0.1"
95
95
  },
96
96
  "dependencies": {
97
- "@wppconnect/wa-js": "^4.6.0",
97
+ "@wppconnect/wa-js": "^4.7.1",
98
98
  "@wppconnect/wa-version": "^1.5.4472",
99
99
  "atob": "^2.1.2",
100
100
  "axios": "^1.20.0",
@@ -116,17 +116,17 @@
116
116
  "reflect-metadata": "^0.2.1",
117
117
  "rimraf": "^3.0.2",
118
118
  "sanitize-filename": "^1.6.4",
119
- "sharp": "0.35.4",
119
+ "sharp": "0.35.5",
120
120
  "tmp": "^0.2.7",
121
121
  "tree-kill": "^1.2.2",
122
122
  "winston": "^3.19.0",
123
123
  "ws": "^8.21.3"
124
124
  },
125
125
  "overrides": {
126
- "serialize-javascript": "7.1.1"
126
+ "serialize-javascript": "7.1.2"
127
127
  },
128
128
  "optionalDependencies": {
129
- "@img/sharp-win32-x64": "^0.35.4",
129
+ "@img/sharp-win32-x64": "^0.35.5",
130
130
  "fsevents": "^2.3.3"
131
131
  },
132
132
  "directories": {