@open-wa/driver-puppeteer 5.0.0-alpha.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,20 @@
1
+
2
+ > @open-wa/driver-puppeteer@5.0.0-alpha.0 build /Users/Mohammed/projects/tools/wa/packages/driver-puppeteer
3
+ > tsdown src/index.ts --format cjs
4
+
5
+ ℹ tsdown v0.21.7 powered by rolldown v1.0.0-rc.12
6
+ ℹ entry: src/index.ts
7
+ ℹ tsconfig: tsconfig.json
8
+ ℹ Build start
9
+ ℹ Cleaning 3 files
10
+ ℹ dist/index.cjs 13.63 kB │ gzip: 3.41 kB
11
+ ℹ 1 files, total: 13.63 kB
12
+ ℹ dist/index.d.cts.map 2.94 kB │ gzip: 0.92 kB
13
+ ℹ dist/index.d.cts 4.28 kB │ gzip: 1.24 kB
14
+ ℹ 2 files, total: 7.22 kB
15
+ [PLUGIN_TIMINGS] Warning: Your build spent significant time in plugins. Here is a breakdown:
16
+ - rolldown-plugin-dts:generate (54%)
17
+ - rolldown-plugin-dts:fake-js (21%)
18
+ See https://rolldown.rs/options/checks#plugintimings for more details.
19
+
20
+ ✔ Build complete in 3203ms
@@ -0,0 +1,6 @@
1
+
2
+ > @open-wa/driver-puppeteer@5.0.0-alpha.1 lint /Users/Mohammed/projects/tools/wa/packages/driver-puppeteer
3
+ > oxlint src
4
+
5
+ Found 0 warnings and 0 errors.
6
+ Finished in 265ms on 5 files with 93 rules using 8 threads.
@@ -0,0 +1,14 @@
1
+
2
+ > @open-wa/driver-puppeteer@5.0.0-alpha.0 test /Users/Mohammed/projects/tools/wa/packages/driver-puppeteer
3
+ > vitest run
4
+
5
+
6
+  RUN  v4.1.2 /Users/Mohammed/projects/tools/wa/packages/driver-puppeteer
7
+
8
+ ✓ src/__tests__/PuppeteerPage.test.ts (3 tests) 11ms
9
+
10
+  Test Files  1 passed (1)
11
+  Tests  3 passed (3)
12
+  Start at  15:25:43
13
+  Duration  1.12s (transform 233ms, setup 0ms, import 484ms, tests 11ms, environment 0ms)
14
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # @open-wa/driver-puppeteer
2
+
3
+ ## 6.0.0-alpha.2
4
+
5
+ ### Minor Changes
6
+
7
+ - Dry run minor bump
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies []:
12
+ - @open-wa/driver-interface@6.0.0-alpha.2
13
+
14
+ ## 5.0.1-alpha.2
15
+
16
+ ### Patch Changes
17
+
18
+ - Dry run patch bump
19
+
20
+ - Updated dependencies []:
21
+ - @open-wa/driver-interface@5.0.1-alpha.2
package/LICENSE.md ADDED
@@ -0,0 +1,67 @@
1
+ ### Copyright (c) 2020 Mohammed Shah
2
+
3
+ # Hippocratic + Do Not Harm (H-DNH) Version 1.1
4
+
5
+ ## Preamble
6
+
7
+ Most software today is developed with little to no thought of how it will be used, or the consequences for our society and planet.
8
+
9
+ As software developers, we engineer the infrastructure of the 21st century. We recognise that our infrastructure has great power to shape the world and the lives of those we share it with, and we choose to consciously take responsibility for the social and environmental impacts of what we build.
10
+
11
+ We envisage a world free from injustice, inequality, and the reckless destruction of lives and our planet. We reject slavery in all its forms, whether by force, indebtedness, or by algorithms that hack human vulnerabilities. We seek a world where humankind is at peace with our neighbours, nature, and ourselves. We want our work to enrich the physical, mental and spiritual wellbeing of all society.
12
+
13
+ We build software to further this vision of a just world, or at the very least, to not put that vision further from reach.
14
+
15
+ ## Terms
16
+
17
+ Licensor hereby grants permission by this license ("License"), free of charge, to any person or entity (the "Licensee") obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
18
+
19
+ 1. All redistribution of source code or binary form, including any modifications must be under these terms. You must inform recipients that the code is governed by these conditions, and how they can obtain a copy of this license. You may not attempt to alter the conditions of who may/may not use this software.
20
+
21
+ 2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
22
+
23
+ 3. This software must not be used by any organisation, website, product or service that:
24
+
25
+ a) lobbies for, promotes, or derives a majority of income from actions that support or contribute to:
26
+ * sex trafficking
27
+ * human trafficking
28
+ * slavery
29
+ * indentured servitude
30
+ * gambling
31
+ * tobacco
32
+ * adversely addictive behaviours
33
+ * nuclear energy
34
+ * warfare
35
+ * weapons manufacturing
36
+ * war crimes
37
+ * settler colonialism
38
+ * apartheid
39
+ * vaccine misinformation
40
+ * climate misinformation
41
+ * child endangerment
42
+ * violence (except when required to protect public safety)
43
+ * burning of forests
44
+ * deforestation
45
+ * hate speech or discrimination based on age, gender, gender identity, race, sexuality, religion, nationality
46
+
47
+ b) lobbies against, or derives a majority of income from actions that discourage or frustrate:
48
+ * peace
49
+ * access to the rights set out in the Universal Declaration of Human Rights and the Convention on the Rights of the Child
50
+ * peaceful assembly and association (including worker associations)
51
+ * a safe environment or action to curtail the use of fossil fuels or prevent climate change
52
+ * democratic processes
53
+
54
+
55
+ 4. Compliance with Human Rights Laws and Human Rights Principles:
56
+
57
+ a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
58
+
59
+ b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
60
+
61
+ c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles. 
62
+
63
+ 5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
64
+
65
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
66
+
67
+ This license is an extension of the Hippocratic License - an Ethical Source license (https://ethicalsource.dev) and the Do Not Harm License - (https://github.com/raisely/NoHarm)
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # @open-wa/driver-puppeteer
2
+
3
+ Puppeteer driver implementation for open-wa
4
+
5
+ Part of the [@open-wa v5 monorepo](https://github.com/open-wa/wa-automate-nodejs).
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @open-wa/driver-puppeteer
11
+ ```
12
+
13
+ ## Documentation
14
+
15
+ See the [docs site](https://docs.openwa.dev).
16
+
17
+ ## License
18
+
19
+ [H-DNH V1.0](https://github.com/open-wa/wa-automate-nodejs/blob/main/LICENSE.md) — Hippocratic + Do Not Harm
package/dist/index.cjs ADDED
@@ -0,0 +1,474 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/PuppeteerElementHandle.ts
3
+ var PuppeteerElementHandle = class {
4
+ constructor(element) {
5
+ this.element = element;
6
+ }
7
+ async click() {
8
+ await this.element.click();
9
+ }
10
+ async type(text) {
11
+ await this.element.type(text);
12
+ }
13
+ async getAttribute(name) {
14
+ return await this.element.evaluate((el, attr) => el.getAttribute(attr), name);
15
+ }
16
+ async textContent() {
17
+ return await this.element.evaluate((el) => el.textContent);
18
+ }
19
+ async dispose() {
20
+ await this.element.dispose();
21
+ }
22
+ unwrap() {
23
+ return this.element;
24
+ }
25
+ };
26
+ //#endregion
27
+ //#region src/PuppeteerPage.ts
28
+ var PuppeteerDisposableHandle = class {
29
+ constructor(disposer) {
30
+ this.disposer = disposer;
31
+ }
32
+ dispose() {
33
+ return this.disposer();
34
+ }
35
+ };
36
+ var PuppeteerFrame = class PuppeteerFrame {
37
+ constructor(frame, isMain) {
38
+ this.frame = frame;
39
+ this.isMain = isMain;
40
+ }
41
+ url() {
42
+ return this.frame.url();
43
+ }
44
+ name() {
45
+ return this.frame.name();
46
+ }
47
+ isMainFrame() {
48
+ return this.isMain;
49
+ }
50
+ parentFrame() {
51
+ const parent = this.frame.parentFrame();
52
+ return parent ? new PuppeteerFrame(parent, false) : null;
53
+ }
54
+ async content() {
55
+ return this.frame.content();
56
+ }
57
+ unwrap() {
58
+ return this.frame;
59
+ }
60
+ };
61
+ function normalizeSnippet(input) {
62
+ return input.replace(/\s+/g, " ").trim().slice(0, 160);
63
+ }
64
+ function enrichEvaluateError(kind, source, error) {
65
+ const normalized = error instanceof Error ? error : new Error(String(error));
66
+ const preview = normalizeSnippet(source);
67
+ const enriched = /* @__PURE__ */ new Error(`[puppeteer:${kind}] ${normalized.message} | scriptBytes=${source.length} | scriptPreview=${preview}`);
68
+ enriched.stack = normalized.stack ?? enriched.message;
69
+ throw enriched;
70
+ }
71
+ function enrichWaitError(kind, details, error) {
72
+ const normalized = error instanceof Error ? error : new Error(String(error));
73
+ const detailText = Object.entries(details).filter(([, value]) => typeof value !== "undefined").map(([key, value]) => `${key}=${typeof value === "string" ? value : JSON.stringify(value)}`).join(" | ");
74
+ const enriched = /* @__PURE__ */ new Error(`[puppeteer:${kind}] ${normalized.message}${detailText ? ` | ${detailText}` : ""}`);
75
+ enriched.stack = normalized.stack ?? enriched.message;
76
+ throw enriched;
77
+ }
78
+ var PuppeteerRequest = class {
79
+ constructor(request, page) {
80
+ this.request = request;
81
+ this.page = page;
82
+ }
83
+ url() {
84
+ return this.request.url();
85
+ }
86
+ method() {
87
+ return this.request.method();
88
+ }
89
+ headers() {
90
+ return this.request.headers();
91
+ }
92
+ resourceType() {
93
+ return this.request.resourceType?.() ?? null;
94
+ }
95
+ isNavigationRequest() {
96
+ return this.request.isNavigationRequest();
97
+ }
98
+ frame() {
99
+ const frame = this.request.frame();
100
+ return frame ? new PuppeteerFrame(frame, frame === this.page.mainFrame()) : null;
101
+ }
102
+ async abort(errorCode) {
103
+ await this.request.abort(errorCode);
104
+ }
105
+ async continue(overrides) {
106
+ await this.request.continue(overrides);
107
+ }
108
+ async respond(response) {
109
+ await this.request.respond({
110
+ ...response,
111
+ body: response.body instanceof Uint8Array ? Buffer.from(response.body) : response.body
112
+ });
113
+ }
114
+ unwrap() {
115
+ return this.request;
116
+ }
117
+ };
118
+ var PuppeteerConsoleMessage = class {
119
+ constructor(message) {
120
+ this.message = message;
121
+ }
122
+ type() {
123
+ return this.message.type();
124
+ }
125
+ text() {
126
+ return this.message.text();
127
+ }
128
+ location() {
129
+ const location = this.message.location();
130
+ return {
131
+ url: location.url,
132
+ lineNumber: location.lineNumber,
133
+ columnNumber: location.columnNumber
134
+ };
135
+ }
136
+ args() {
137
+ return this.message.args();
138
+ }
139
+ unwrap() {
140
+ return this.message;
141
+ }
142
+ };
143
+ var PuppeteerPage = class {
144
+ constructor(page, capabilities) {
145
+ this.page = page;
146
+ this.capabilities = capabilities;
147
+ this.name = "puppeteer";
148
+ this.listenerWrappers = /* @__PURE__ */ new Map();
149
+ }
150
+ async goto(url, options) {
151
+ await this.page.goto(url, {
152
+ waitUntil: options?.waitUntil,
153
+ timeout: options?.timeoutMs
154
+ });
155
+ }
156
+ url() {
157
+ return this.page.url();
158
+ }
159
+ async reload() {
160
+ await this.page.reload();
161
+ }
162
+ mainFrame() {
163
+ return new PuppeteerFrame(this.page.mainFrame(), true);
164
+ }
165
+ async evaluateOnNewDocument(fn, arg) {
166
+ await this.page.evaluateOnNewDocument(fn, arg);
167
+ }
168
+ async evaluate(fn, arg) {
169
+ try {
170
+ return await this.page.evaluate(fn, arg);
171
+ } catch (error) {
172
+ return enrichEvaluateError("evaluate", typeof fn === "function" ? fn.toString() : "[anonymous evaluate fn]", error);
173
+ }
174
+ }
175
+ async evaluateScript(script) {
176
+ try {
177
+ return await this.page.evaluate(script);
178
+ } catch (error) {
179
+ return enrichEvaluateError("evaluateScript", script, error);
180
+ }
181
+ }
182
+ async addInitScript(script) {
183
+ const registration = await this.page.evaluateOnNewDocument(script);
184
+ const identifier = this.getInitScriptIdentifier(registration);
185
+ let disposed = false;
186
+ return new PuppeteerDisposableHandle(async () => {
187
+ if (disposed) return;
188
+ disposed = true;
189
+ if (identifier && typeof this.page.removeScriptToEvaluateOnNewDocument === "function") await this.page.removeScriptToEvaluateOnNewDocument(identifier);
190
+ });
191
+ }
192
+ async setViewport(viewport) {
193
+ await this.page.setViewport(viewport);
194
+ }
195
+ async setUserAgent(ua) {
196
+ await this.page.setUserAgent(ua);
197
+ }
198
+ async setRequestInterception(enabled) {
199
+ this.require("requestInterception");
200
+ await this.page.setRequestInterception(enabled);
201
+ }
202
+ async waitForSelector(selector, options) {
203
+ try {
204
+ const element = await this.page.waitForSelector(selector, { timeout: options?.timeoutMs });
205
+ return element ? new PuppeteerElementHandle(element) : null;
206
+ } catch (error) {
207
+ return enrichWaitError("waitForSelector", {
208
+ selector,
209
+ timeoutMs: options?.timeoutMs
210
+ }, error);
211
+ }
212
+ }
213
+ async waitForFunction(fnOrScript, argOrOptions, maybeOptions) {
214
+ if (typeof fnOrScript === "string") {
215
+ const options = argOrOptions;
216
+ try {
217
+ await this.page.waitForFunction(fnOrScript, {
218
+ timeout: options?.timeoutMs,
219
+ polling: options?.polling
220
+ });
221
+ return;
222
+ } catch (error) {
223
+ return enrichWaitError("waitForFunction", {
224
+ timeoutMs: options?.timeoutMs,
225
+ polling: options?.polling,
226
+ scriptBytes: fnOrScript.length,
227
+ scriptPreview: normalizeSnippet(fnOrScript)
228
+ }, error);
229
+ }
230
+ }
231
+ const options = maybeOptions;
232
+ try {
233
+ await this.page.waitForFunction(fnOrScript, {
234
+ timeout: options?.timeoutMs,
235
+ polling: options?.polling
236
+ }, argOrOptions);
237
+ } catch (error) {
238
+ return enrichWaitError("waitForFunctionFn", {
239
+ timeoutMs: options?.timeoutMs,
240
+ polling: options?.polling,
241
+ fnPreview: normalizeSnippet(fnOrScript.toString()),
242
+ argPreview: typeof argOrOptions === "undefined" ? void 0 : normalizeSnippet(JSON.stringify(argOrOptions))
243
+ }, error);
244
+ }
245
+ }
246
+ async $(selector) {
247
+ const element = await this.page.$(selector);
248
+ return element ? new PuppeteerElementHandle(element) : null;
249
+ }
250
+ async $$(selector) {
251
+ return (await this.page.$$(selector)).map((el) => new PuppeteerElementHandle(el));
252
+ }
253
+ async click(selector) {
254
+ await this.page.click(selector);
255
+ }
256
+ async type(selector, text, options) {
257
+ await this.page.type(selector, text, { delay: options?.delayMs });
258
+ }
259
+ async screenshot(options) {
260
+ const buffer = await this.page.screenshot(options);
261
+ return new Uint8Array(buffer);
262
+ }
263
+ async exposeFunction(name, fn) {
264
+ await this.page.exposeFunction(name, fn);
265
+ }
266
+ on(event, handler) {
267
+ const wrapped = (...args) => {
268
+ const payload = this.wrapEventPayload(event, args);
269
+ if (event === "close") return handler();
270
+ return handler(payload);
271
+ };
272
+ this.getWrapperSet(event, handler).add(wrapped);
273
+ this.page.on(event, wrapped);
274
+ return new PuppeteerDisposableHandle(() => {
275
+ this.removeWrappedListener(event, handler, wrapped);
276
+ });
277
+ }
278
+ off(event, handler) {
279
+ const wrappers = this.listenerWrappers.get(event)?.get(handler);
280
+ if (!wrappers || wrappers.size === 0) {
281
+ this.page.off(event, handler);
282
+ return;
283
+ }
284
+ for (const wrapped of wrappers) this.page.off(event, wrapped);
285
+ this.listenerWrappers.get(event)?.delete(handler);
286
+ }
287
+ async close() {
288
+ await this.page.close();
289
+ }
290
+ isClosed() {
291
+ return this.page.isClosed();
292
+ }
293
+ has(cap) {
294
+ return this.capabilities[cap]?.supported === true;
295
+ }
296
+ require(cap) {
297
+ if (!this.has(cap)) {
298
+ const capability = this.capabilities[cap];
299
+ throw new Error(`Page does not support capability '${cap}'${capability?.reason ? `: ${capability.reason}` : ""}`);
300
+ }
301
+ }
302
+ async cdp() {
303
+ this.require("cdp");
304
+ return await this.page.createCDPSession();
305
+ }
306
+ async setBypassServiceWorker(bypass) {
307
+ this.require("serviceWorkerBypass");
308
+ await this.page.setBypassServiceWorker(bypass);
309
+ }
310
+ async pdf(options) {
311
+ this.require("pdf");
312
+ const buffer = await this.page.pdf(options);
313
+ return new Uint8Array(buffer);
314
+ }
315
+ async startTracing(options) {
316
+ this.require("tracing");
317
+ await this.page.tracing.start(options);
318
+ }
319
+ async stopTracing() {
320
+ this.require("tracing");
321
+ const buffer = await this.page.tracing.stop();
322
+ return buffer ? new Uint8Array(buffer) : new Uint8Array();
323
+ }
324
+ unwrap() {
325
+ return this.page;
326
+ }
327
+ getWrapperSet(event, handler) {
328
+ let wrappers = this.listenerWrappers.get(event);
329
+ if (!wrappers) {
330
+ wrappers = /* @__PURE__ */ new Map();
331
+ this.listenerWrappers.set(event, wrappers);
332
+ }
333
+ let handlerWrappers = wrappers.get(handler);
334
+ if (!handlerWrappers) {
335
+ handlerWrappers = /* @__PURE__ */ new Set();
336
+ wrappers.set(handler, handlerWrappers);
337
+ }
338
+ return handlerWrappers;
339
+ }
340
+ removeWrappedListener(event, handler, wrapped) {
341
+ this.page.off(event, wrapped);
342
+ const eventWrappers = this.listenerWrappers.get(event);
343
+ const handlerWrappers = eventWrappers?.get(handler);
344
+ if (!handlerWrappers) return;
345
+ handlerWrappers.delete(wrapped);
346
+ if (handlerWrappers.size === 0) eventWrappers?.delete(handler);
347
+ if (eventWrappers && eventWrappers.size === 0) this.listenerWrappers.delete(event);
348
+ }
349
+ getInitScriptIdentifier(registration) {
350
+ if (typeof registration === "string") return registration;
351
+ if (registration && typeof registration === "object") {
352
+ const candidate = registration.identifier ?? registration.id;
353
+ return typeof candidate === "string" ? candidate : void 0;
354
+ }
355
+ }
356
+ wrapEventPayload(event, args) {
357
+ const [payload] = args;
358
+ switch (event) {
359
+ case "request":
360
+ case "requestfailed":
361
+ case "requestfinished": return new PuppeteerRequest(payload, this.page);
362
+ case "framenavigated": return new PuppeteerFrame(payload, payload === this.page.mainFrame());
363
+ case "console": return new PuppeteerConsoleMessage(payload);
364
+ case "pageerror": return payload;
365
+ default: return payload;
366
+ }
367
+ }
368
+ };
369
+ //#endregion
370
+ //#region src/PuppeteerBrowser.ts
371
+ var PuppeteerBrowser = class {
372
+ constructor(browser, capabilities) {
373
+ this.browser = browser;
374
+ this.capabilities = capabilities;
375
+ this.name = "puppeteer";
376
+ }
377
+ async newPage(options) {
378
+ const page = await this.browser.newPage();
379
+ if (options?.clearFirstPage) {
380
+ const pages = await this.browser.pages();
381
+ if (pages.length > 0) await pages[0].close();
382
+ }
383
+ return new PuppeteerPage(page, this.capabilities);
384
+ }
385
+ async pages() {
386
+ return (await this.browser.pages()).map((p) => new PuppeteerPage(p, this.capabilities));
387
+ }
388
+ async close() {
389
+ await this.browser.close();
390
+ }
391
+ isConnected() {
392
+ return this.browser.isConnected();
393
+ }
394
+ async versionString() {
395
+ return await this.browser.version();
396
+ }
397
+ unwrap() {
398
+ return this.browser;
399
+ }
400
+ };
401
+ //#endregion
402
+ //#region src/PuppeteerDriver.ts
403
+ var PuppeteerDriver = class {
404
+ constructor() {
405
+ this.name = "puppeteer";
406
+ this.capabilities = {
407
+ cdp: { supported: true },
408
+ requestInterception: { supported: true },
409
+ serviceWorkerBypass: { supported: true },
410
+ stealth: {
411
+ supported: true,
412
+ notes: "Via puppeteer-extra plugins"
413
+ },
414
+ pdf: { supported: true },
415
+ tracing: {
416
+ supported: true,
417
+ notes: "Basic tracing support"
418
+ },
419
+ persistentContext: { supported: true },
420
+ browserExtensions: { supported: true },
421
+ exposeBinding: { supported: true }
422
+ };
423
+ }
424
+ async init(ctx) {
425
+ this.ctx = ctx;
426
+ const pExtra = await import("puppeteer-extra");
427
+ this.puppeteer = pExtra.default ?? pExtra;
428
+ try {
429
+ const { createRequire } = await import("node:module");
430
+ this.version = createRequire(__filename)("puppeteer/package.json").version;
431
+ } catch {}
432
+ this.ctx?.logger?.info("PuppeteerDriver initialized", { version: this.version });
433
+ }
434
+ async launch(options) {
435
+ if (!this.puppeteer) await this.init();
436
+ const browser = await this.puppeteer.launch({
437
+ headless: options?.headless ?? true,
438
+ executablePath: options?.executablePath,
439
+ args: options?.args || [],
440
+ defaultViewport: options?.defaultViewport,
441
+ userDataDir: options?.userDataDir,
442
+ timeout: options?.timeoutMs
443
+ });
444
+ try {
445
+ const browserVersion = await browser.version();
446
+ this.ctx?.logger?.info("Browser executable version", { version: browserVersion });
447
+ } catch {}
448
+ return new PuppeteerBrowser(browser, this.capabilities);
449
+ }
450
+ async connect(options) {
451
+ if (!this.puppeteer) await this.init();
452
+ return new PuppeteerBrowser(await this.puppeteer.connect({
453
+ browserWSEndpoint: options.wsEndpoint,
454
+ timeout: options?.timeoutMs
455
+ }), this.capabilities);
456
+ }
457
+ unwrap() {
458
+ return this.puppeteer;
459
+ }
460
+ has(cap) {
461
+ return this.capabilities[cap]?.supported === true;
462
+ }
463
+ require(cap) {
464
+ if (!this.has(cap)) {
465
+ const capability = this.capabilities[cap];
466
+ throw new Error(`Driver '${this.name}' does not support capability '${cap}'${capability?.reason ? `: ${capability.reason}` : ""}`);
467
+ }
468
+ }
469
+ };
470
+ //#endregion
471
+ exports.PuppeteerBrowser = PuppeteerBrowser;
472
+ exports.PuppeteerDriver = PuppeteerDriver;
473
+ exports.PuppeteerElementHandle = PuppeteerElementHandle;
474
+ exports.PuppeteerPage = PuppeteerPage;