@mayurajs/browser-browser-use 0.0.0-stage → 1.2.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.
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +37 -2
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +85 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -4
- package/src/index.ts +91 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Mayura
|
|
2
|
+
Copyright 2026 The Mayura Authors
|
|
3
|
+
|
|
4
|
+
This product includes software developed by the Mayura contributors.
|
|
5
|
+
|
|
6
|
+
Third-party dependencies retain their own copyright and license terms. Exact
|
|
7
|
+
resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
|
|
8
|
+
artifact and dependency qualification procedures.
|
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/browser-browser-use
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Browser Use Cloud](https://docs.browser-use.com/cloud/browser/quickstart) browsers for `mayura/browser`: hosted
|
|
4
|
+
Chromium, created over Browser Use's browsers API (v2) and driven over CDP, from any runtime, with no dependency. This
|
|
5
|
+
is Browser Use's browser infrastructure, not its agent: Mayura's own agent drives the browser.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install mayura @mayurajs/browser-browser-use
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createBrowsers } from 'mayura/browser';
|
|
13
|
+
import { browserUseBrowsers } from '@mayurajs/browser-browser-use';
|
|
14
|
+
|
|
15
|
+
const browsers = createBrowsers(browserUseBrowsers({ apiKey }), {
|
|
16
|
+
maxBrowsers: 2, maxLifetimeMs: 30 * 60_000,
|
|
17
|
+
origins: ['https://example.com'],
|
|
18
|
+
});
|
|
19
|
+
const browser = await browsers.open();
|
|
20
|
+
await browser.goto('https://example.com/');
|
|
21
|
+
await browser.release();
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
- Each browser is created when opened and stopped when released. **A Browser Use browser outlives its connection**:
|
|
25
|
+
only stopping ends it, so one not released runs until its lifetime, given to Browser Use as its timeout (whole
|
|
26
|
+
minutes, up to 4 hours). Browser Use charges for that timeout up front and refunds what a stop leaves unused. A
|
|
27
|
+
browser that already stopped counts as released.
|
|
28
|
+
- **No proxy and no captcha solving**, though Browser Use's own defaults are a US proxy and captcha solving on; ask for
|
|
29
|
+
them with `proxyCountryCode` and `solveCaptchas`. Recording is off. Labels become metadata (at most 10).
|
|
30
|
+
- There is no live view unless `liveView: true`: whoever has Browser Use's live link may be able to use the browser,
|
|
31
|
+
not only watch it.
|
|
32
|
+
- Treat the CDP URL as a secret, as Browser Use does not say what it carries: Mayura never logs it.
|
|
33
|
+
- Origins are enforced inside the browser, by intercepting its requests over CDP; a live check against Browser Use
|
|
34
|
+
confirmed it on October 6, 2026. Should a connection ever not allow that, opening a browser fails rather than
|
|
35
|
+
running unchecked.
|
|
36
|
+
- Options: `apiKey`, `liveView`, `proxyCountryCode`, `solveCaptchas`, `maxLifetimeMs` (4 hours), `fetch`, `baseUrl`.
|
|
37
|
+
|
|
38
|
+
See the [browser guide](https://mayurajs.com/docs/guides/browsers/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type BrowserProvider } from 'mayura/browser';
|
|
2
|
+
export interface BrowserUseBrowserOptions {
|
|
3
|
+
/** A Browser Use Cloud API key. Nothing is read from the environment. */
|
|
4
|
+
readonly apiKey: string;
|
|
5
|
+
/**
|
|
6
|
+
* Give each browser Browser Use's live view (`liveViewUrl`); off by default, as whoever has the link may be able to
|
|
7
|
+
* use the browser, not only watch it.
|
|
8
|
+
*/
|
|
9
|
+
readonly liveView?: boolean;
|
|
10
|
+
/** Route browsing through Browser Use's proxy in this country, such as `us`; no proxy by default (Browser Use's own default is `us`). */
|
|
11
|
+
readonly proxyCountryCode?: string;
|
|
12
|
+
/** Let Browser Use solve captchas; off here, though Browser Use's own default is on. */
|
|
13
|
+
readonly solveCaptchas?: boolean;
|
|
14
|
+
/** The longest lifetime; Browser Use's 4 hours by default. */
|
|
15
|
+
readonly maxLifetimeMs?: number;
|
|
16
|
+
/** For tests and proxies: the fetch to use. */
|
|
17
|
+
readonly fetch?: typeof fetch;
|
|
18
|
+
/** The API's address; `https://api.browser-use.com` by default. */
|
|
19
|
+
readonly baseUrl?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Browsers from Browser Use Cloud: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser
|
|
23
|
+
* is created when opened and stopped when released; Browser Use stops it at its lifetime too. A Browser Use browser
|
|
24
|
+
* outlives its connection: only stopping ends it. Give the result to `createBrowsers` from `mayura/browser`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function browserUseBrowsers(options: BrowserUseBrowserOptions): BrowserProvider;
|
|
27
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAEgB,KAAK,eAAe,EAC1C,MAAM,gBAAgB,CAAC;AAExB,MAAM,WAAW,wBAAwB;IACvC,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAC5B,yIAAyI;IACzI,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,wFAAwF;IACxF,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;IACjC,8DAA8D;IAC9D,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,+CAA+C;IAC/C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAC9B,mEAAmE;IACnE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAKD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,wBAAwB,GAAG,eAAe,CAwDrF"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import { BrowserError, browserHttpFailure, browserResponseFailure, resolveCdpUrl, } from 'mayura/browser';
|
|
3
|
+
/** A CDP URL over TLS, or plain only on this machine (a local proxy or a test). */
|
|
4
|
+
const secureEndpoint = /^(?:wss|https):\/\/|^(?:ws|http):\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/]/u;
|
|
5
|
+
/**
|
|
6
|
+
* Browsers from Browser Use Cloud: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser
|
|
7
|
+
* is created when opened and stopped when released; Browser Use stops it at its lifetime too. A Browser Use browser
|
|
8
|
+
* outlives its connection: only stopping ends it. Give the result to `createBrowsers` from `mayura/browser`.
|
|
9
|
+
*/
|
|
10
|
+
export function browserUseBrowsers(options) {
|
|
11
|
+
if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey))
|
|
12
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): apiKey must be a Browser Use API key.');
|
|
13
|
+
for (const flag of ['liveView', 'solveCaptchas']) {
|
|
14
|
+
if (options[flag] !== undefined && typeof options[flag] !== 'boolean')
|
|
15
|
+
throw new MayuraError('INVALID_CONFIG', `browserUseBrowsers(): ${flag} must be a boolean.`);
|
|
16
|
+
}
|
|
17
|
+
if (options.proxyCountryCode !== undefined && (typeof options.proxyCountryCode !== 'string' || !/^[a-z]{2}$/u.test(options.proxyCountryCode))) {
|
|
18
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): proxyCountryCode is a two-letter country code, such as us.');
|
|
19
|
+
}
|
|
20
|
+
const maxLifetimeMs = options.maxLifetimeMs ?? 14_400_000;
|
|
21
|
+
if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000 || maxLifetimeMs > 14_400_000)
|
|
22
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): maxLifetimeMs is 1 minute to 4 hours.');
|
|
23
|
+
if (options.fetch !== undefined && typeof options.fetch !== 'function')
|
|
24
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): fetch must be a function.');
|
|
25
|
+
const base = (() => {
|
|
26
|
+
try {
|
|
27
|
+
const url = new URL(options.baseUrl ?? 'https://api.browser-use.com');
|
|
28
|
+
if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost')
|
|
29
|
+
throw new Error();
|
|
30
|
+
return url.origin;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): baseUrl must be an https URL.');
|
|
34
|
+
}
|
|
35
|
+
})();
|
|
36
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
37
|
+
const liveView = options.liveView ?? false;
|
|
38
|
+
const headers = (json = false) => ({ 'x-browser-use-api-key': options.apiKey, ...(json ? { 'content-type': 'application/json' } : {}) });
|
|
39
|
+
const create = async (spec, { signal }) => {
|
|
40
|
+
if (Object.keys(spec.labels).length > 10)
|
|
41
|
+
throw new MayuraError('INVALID_INPUT', 'Browser Use takes at most 10 labels.');
|
|
42
|
+
const created = await fetcher(`${base}/api/v2/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
|
|
43
|
+
// Browser Use stops the browser at its timeout, should a stop never come: whole minutes, 1 to 240 as the
|
|
44
|
+
// lifetime is at most 4 hours.
|
|
45
|
+
timeout: Math.ceil(spec.lifetimeMs / 60_000),
|
|
46
|
+
browserScreenWidth: Math.max(320, spec.viewport.width), browserScreenHeight: Math.max(320, spec.viewport.height),
|
|
47
|
+
// Browser Use proxies through the US unless told otherwise.
|
|
48
|
+
proxyCountryCode: options.proxyCountryCode ?? null,
|
|
49
|
+
solveCaptchas: options.solveCaptchas ?? false, enableRecording: false,
|
|
50
|
+
...(Object.keys(spec.labels).length ? { metadata: { ...spec.labels } } : {}),
|
|
51
|
+
}) });
|
|
52
|
+
if (!created.ok)
|
|
53
|
+
throw browserResponseFailure(created);
|
|
54
|
+
const browser = await created.json().catch(() => undefined);
|
|
55
|
+
if (typeof browser?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(browser.id) || typeof browser.cdpUrl !== 'string' || !secureEndpoint.test(browser.cdpUrl)) {
|
|
56
|
+
throw new BrowserError('invalid_response');
|
|
57
|
+
}
|
|
58
|
+
const id = browser.id;
|
|
59
|
+
const release = async ({ signal: callSignal }) => {
|
|
60
|
+
const reply = await fetcher(`${base}/api/v2/browsers/${id}`, { method: 'PATCH', signal: callSignal, headers: headers(true), body: JSON.stringify({ action: 'stop' }) });
|
|
61
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
62
|
+
if (reply.ok)
|
|
63
|
+
return;
|
|
64
|
+
// A browser that already stopped may not be stoppable: ask how it is before calling that a failure.
|
|
65
|
+
const state = await fetcher(`${base}/api/v2/browsers/${id}`, { signal: callSignal, headers: headers() });
|
|
66
|
+
const status = state.ok ? (await state.json().catch(() => undefined))?.status : (void state.body?.cancel().catch(() => undefined), undefined);
|
|
67
|
+
if (state.status === 404 || status === 'stopped')
|
|
68
|
+
return;
|
|
69
|
+
throw browserHttpFailure(reply.status);
|
|
70
|
+
};
|
|
71
|
+
// Without liveView, createBrowsers shows no live view. The CDP URL is a WebSocket, or the browser's http(s)
|
|
72
|
+
// address, asked for its WebSocket.
|
|
73
|
+
let url;
|
|
74
|
+
try {
|
|
75
|
+
url = /^wss?:/u.test(browser.cdpUrl) ? browser.cdpUrl : await resolveCdpUrl(browser.cdpUrl, { signal, fetch: fetcher });
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
await release({ signal: AbortSignal.timeout(30_000) }).catch(() => undefined);
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
return { id, cdp: { url }, ...(typeof browser.liveUrl === 'string' ? { liveViewUrl: browser.liveUrl } : {}), release };
|
|
82
|
+
};
|
|
83
|
+
return Object.freeze({ id: 'browser-use', features: Object.freeze({ liveView }), maxLifetimeMs, create });
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EACL,YAAY,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,aAAa,GAExE,MAAM,gBAAgB,CAAC;AAsBxB,mFAAmF;AACnF,MAAM,cAAc,GAAG,8EAA8E,CAAC;AAEtG;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAiC;IAClE,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAE,6DAA6D,CAAC,CAAC;IACtM,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,EAAE,eAAe,CAAU,EAAE,CAAC;QAC1D,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,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,GAAG,CAAC,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;IACzH,CAAC,CAAC;IAEF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC,CAAC;AAC5G,CAAC","sourcesContent":["import { MayuraError } from 'mayura';\nimport {\n BrowserError, browserHttpFailure, browserResponseFailure, resolveCdpUrl,\n type BrowserBackend, type BrowserProvider, type ProviderBrowserSpec,\n} from 'mayura/browser';\n\nexport interface BrowserUseBrowserOptions {\n /** A Browser Use Cloud API key. Nothing is read from the environment. */\n readonly apiKey: string;\n /**\n * Give each browser Browser Use's live view (`liveViewUrl`); off by default, as whoever has the link may be able to\n * use the browser, not only watch it.\n */\n readonly liveView?: boolean;\n /** Route browsing through Browser Use's proxy in this country, such as `us`; no proxy by default (Browser Use's own default is `us`). */\n readonly proxyCountryCode?: string;\n /** Let Browser Use solve captchas; off here, though Browser Use's own default is on. */\n readonly solveCaptchas?: boolean;\n /** The longest lifetime; Browser Use's 4 hours by default. */\n readonly maxLifetimeMs?: number;\n /** For tests and proxies: the fetch to use. */\n readonly fetch?: typeof fetch;\n /** The API's address; `https://api.browser-use.com` by default. */\n readonly baseUrl?: string;\n}\n\n/** A CDP URL over TLS, or plain only on this machine (a local proxy or a test). */\nconst secureEndpoint = /^(?:wss|https):\\/\\/|^(?:ws|http):\\/\\/(?:127\\.0\\.0\\.1|localhost|\\[::1\\])[:/]/u;\n\n/**\n * Browsers from Browser Use Cloud: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser\n * is created when opened and stopped when released; Browser Use stops it at its lifetime too. A Browser Use browser\n * outlives its connection: only stopping ends it. Give the result to `createBrowsers` from `mayura/browser`.\n */\nexport function browserUseBrowsers(options: BrowserUseBrowserOptions): BrowserProvider {\n if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): apiKey must be a Browser Use API key.');\n for (const flag of ['liveView', 'solveCaptchas'] as const) {\n if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `browserUseBrowsers(): ${flag} must be a boolean.`);\n }\n if (options.proxyCountryCode !== undefined && (typeof options.proxyCountryCode !== 'string' || !/^[a-z]{2}$/u.test(options.proxyCountryCode))) {\n throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): proxyCountryCode is a two-letter country code, such as us.');\n }\n const maxLifetimeMs = options.maxLifetimeMs ?? 14_400_000;\n if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000 || maxLifetimeMs > 14_400_000) throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): maxLifetimeMs is 1 minute to 4 hours.');\n if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): fetch must be a function.');\n const base = (() => {\n try { const url = new URL(options.baseUrl ?? 'https://api.browser-use.com'); if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') throw new Error(); return url.origin; }\n catch { throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): baseUrl must be an https URL.'); }\n })();\n const fetcher = options.fetch ?? globalThis.fetch;\n const liveView = options.liveView ?? false;\n const headers = (json = false) => ({ 'x-browser-use-api-key': options.apiKey, ...(json ? { 'content-type': 'application/json' } : {}) });\n\n const create = async (spec: ProviderBrowserSpec, { signal }: { readonly signal: AbortSignal }): Promise<BrowserBackend> => {\n if (Object.keys(spec.labels).length > 10) throw new MayuraError('INVALID_INPUT', 'Browser Use takes at most 10 labels.');\n const created = await fetcher(`${base}/api/v2/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({\n // Browser Use stops the browser at its timeout, should a stop never come: whole minutes, 1 to 240 as the\n // lifetime is at most 4 hours.\n timeout: Math.ceil(spec.lifetimeMs / 60_000),\n browserScreenWidth: Math.max(320, spec.viewport.width), browserScreenHeight: Math.max(320, spec.viewport.height),\n // Browser Use proxies through the US unless told otherwise.\n proxyCountryCode: options.proxyCountryCode ?? null,\n solveCaptchas: options.solveCaptchas ?? false, enableRecording: false,\n ...(Object.keys(spec.labels).length ? { metadata: { ...spec.labels } } : {}),\n }) });\n if (!created.ok) throw browserResponseFailure(created);\n const browser = await created.json().catch(() => undefined) as { id?: unknown; cdpUrl?: unknown; liveUrl?: unknown } | undefined;\n if (typeof browser?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(browser.id) || typeof browser.cdpUrl !== 'string' || !secureEndpoint.test(browser.cdpUrl)) {\n throw new BrowserError('invalid_response');\n }\n const id = browser.id;\n const release = async ({ signal: callSignal }: { readonly signal: AbortSignal }) => {\n const reply = await fetcher(`${base}/api/v2/browsers/${id}`, { method: 'PATCH', signal: callSignal, headers: headers(true), body: JSON.stringify({ action: 'stop' }) });\n void reply.body?.cancel().catch(() => undefined);\n if (reply.ok) return;\n // A browser that already stopped may not be stoppable: ask how it is before calling that a failure.\n const state = await fetcher(`${base}/api/v2/browsers/${id}`, { signal: callSignal, headers: headers() });\n const status = state.ok ? (await state.json().catch(() => undefined) as { status?: unknown } | undefined)?.status : (void state.body?.cancel().catch(() => undefined), undefined);\n if (state.status === 404 || status === 'stopped') return;\n throw browserHttpFailure(reply.status);\n };\n // Without liveView, createBrowsers shows no live view. The CDP URL is a WebSocket, or the browser's http(s)\n // address, asked for its WebSocket.\n let url: string;\n try { url = /^wss?:/u.test(browser.cdpUrl) ? browser.cdpUrl : await resolveCdpUrl(browser.cdpUrl, { signal, fetch: fetcher }); }\n catch (error) { await release({ signal: AbortSignal.timeout(30_000) }).catch(() => undefined); throw error; }\n return { id, cdp: { url }, ...(typeof browser.liveUrl === 'string' ? { liveViewUrl: browser.liveUrl } : {}), release };\n };\n\n return Object.freeze({ id: 'browser-use', features: Object.freeze({ liveView }), maxLifetimeMs, create });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/browser-browser-use",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Browser Use cloud browsers for mayura/browser, over its browsers API.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Aryabh",
|
|
7
|
+
"email": "dev@rokad.co"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/KartikeyAI/mayura.git",
|
|
13
|
+
"directory": "extensions/browser-browser-use"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/KartikeyAI/mayura#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/KartikeyAI/mayura/issues"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.12.0 <23 || >=24.14.1 <25"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src/**/*.ts",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"NOTICE"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"mayura": "^1.2.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { MayuraError } from 'mayura';
|
|
2
|
+
import {
|
|
3
|
+
BrowserError, browserHttpFailure, browserResponseFailure, resolveCdpUrl,
|
|
4
|
+
type BrowserBackend, type BrowserProvider, type ProviderBrowserSpec,
|
|
5
|
+
} from 'mayura/browser';
|
|
6
|
+
|
|
7
|
+
export interface BrowserUseBrowserOptions {
|
|
8
|
+
/** A Browser Use Cloud API key. Nothing is read from the environment. */
|
|
9
|
+
readonly apiKey: string;
|
|
10
|
+
/**
|
|
11
|
+
* Give each browser Browser Use's live view (`liveViewUrl`); off by default, as whoever has the link may be able to
|
|
12
|
+
* use the browser, not only watch it.
|
|
13
|
+
*/
|
|
14
|
+
readonly liveView?: boolean;
|
|
15
|
+
/** Route browsing through Browser Use's proxy in this country, such as `us`; no proxy by default (Browser Use's own default is `us`). */
|
|
16
|
+
readonly proxyCountryCode?: string;
|
|
17
|
+
/** Let Browser Use solve captchas; off here, though Browser Use's own default is on. */
|
|
18
|
+
readonly solveCaptchas?: boolean;
|
|
19
|
+
/** The longest lifetime; Browser Use's 4 hours by default. */
|
|
20
|
+
readonly maxLifetimeMs?: number;
|
|
21
|
+
/** For tests and proxies: the fetch to use. */
|
|
22
|
+
readonly fetch?: typeof fetch;
|
|
23
|
+
/** The API's address; `https://api.browser-use.com` by default. */
|
|
24
|
+
readonly baseUrl?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A CDP URL over TLS, or plain only on this machine (a local proxy or a test). */
|
|
28
|
+
const secureEndpoint = /^(?:wss|https):\/\/|^(?:ws|http):\/\/(?:127\.0\.0\.1|localhost|\[::1\])[:/]/u;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Browsers from Browser Use Cloud: hosted Chromium, driven over CDP from any runtime, with no dependency. Each browser
|
|
32
|
+
* is created when opened and stopped when released; Browser Use stops it at its lifetime too. A Browser Use browser
|
|
33
|
+
* outlives its connection: only stopping ends it. Give the result to `createBrowsers` from `mayura/browser`.
|
|
34
|
+
*/
|
|
35
|
+
export function browserUseBrowsers(options: BrowserUseBrowserOptions): BrowserProvider {
|
|
36
|
+
if (!options || typeof options.apiKey !== 'string' || !/^[!-~]{8,512}$/u.test(options.apiKey)) throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): apiKey must be a Browser Use API key.');
|
|
37
|
+
for (const flag of ['liveView', 'solveCaptchas'] as const) {
|
|
38
|
+
if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new MayuraError('INVALID_CONFIG', `browserUseBrowsers(): ${flag} must be a boolean.`);
|
|
39
|
+
}
|
|
40
|
+
if (options.proxyCountryCode !== undefined && (typeof options.proxyCountryCode !== 'string' || !/^[a-z]{2}$/u.test(options.proxyCountryCode))) {
|
|
41
|
+
throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): proxyCountryCode is a two-letter country code, such as us.');
|
|
42
|
+
}
|
|
43
|
+
const maxLifetimeMs = options.maxLifetimeMs ?? 14_400_000;
|
|
44
|
+
if (!Number.isSafeInteger(maxLifetimeMs) || maxLifetimeMs < 60_000 || maxLifetimeMs > 14_400_000) throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): maxLifetimeMs is 1 minute to 4 hours.');
|
|
45
|
+
if (options.fetch !== undefined && typeof options.fetch !== 'function') throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): fetch must be a function.');
|
|
46
|
+
const base = (() => {
|
|
47
|
+
try { const url = new URL(options.baseUrl ?? 'https://api.browser-use.com'); if (url.protocol !== 'https:' && url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') throw new Error(); return url.origin; }
|
|
48
|
+
catch { throw new MayuraError('INVALID_CONFIG', 'browserUseBrowsers(): baseUrl must be an https URL.'); }
|
|
49
|
+
})();
|
|
50
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
51
|
+
const liveView = options.liveView ?? false;
|
|
52
|
+
const headers = (json = false) => ({ 'x-browser-use-api-key': options.apiKey, ...(json ? { 'content-type': 'application/json' } : {}) });
|
|
53
|
+
|
|
54
|
+
const create = async (spec: ProviderBrowserSpec, { signal }: { readonly signal: AbortSignal }): Promise<BrowserBackend> => {
|
|
55
|
+
if (Object.keys(spec.labels).length > 10) throw new MayuraError('INVALID_INPUT', 'Browser Use takes at most 10 labels.');
|
|
56
|
+
const created = await fetcher(`${base}/api/v2/browsers`, { method: 'POST', signal, headers: headers(true), body: JSON.stringify({
|
|
57
|
+
// Browser Use stops the browser at its timeout, should a stop never come: whole minutes, 1 to 240 as the
|
|
58
|
+
// lifetime is at most 4 hours.
|
|
59
|
+
timeout: Math.ceil(spec.lifetimeMs / 60_000),
|
|
60
|
+
browserScreenWidth: Math.max(320, spec.viewport.width), browserScreenHeight: Math.max(320, spec.viewport.height),
|
|
61
|
+
// Browser Use proxies through the US unless told otherwise.
|
|
62
|
+
proxyCountryCode: options.proxyCountryCode ?? null,
|
|
63
|
+
solveCaptchas: options.solveCaptchas ?? false, enableRecording: false,
|
|
64
|
+
...(Object.keys(spec.labels).length ? { metadata: { ...spec.labels } } : {}),
|
|
65
|
+
}) });
|
|
66
|
+
if (!created.ok) throw browserResponseFailure(created);
|
|
67
|
+
const browser = await created.json().catch(() => undefined) as { id?: unknown; cdpUrl?: unknown; liveUrl?: unknown } | undefined;
|
|
68
|
+
if (typeof browser?.id !== 'string' || !/^[A-Za-z0-9-]{1,128}$/u.test(browser.id) || typeof browser.cdpUrl !== 'string' || !secureEndpoint.test(browser.cdpUrl)) {
|
|
69
|
+
throw new BrowserError('invalid_response');
|
|
70
|
+
}
|
|
71
|
+
const id = browser.id;
|
|
72
|
+
const release = async ({ signal: callSignal }: { readonly signal: AbortSignal }) => {
|
|
73
|
+
const reply = await fetcher(`${base}/api/v2/browsers/${id}`, { method: 'PATCH', signal: callSignal, headers: headers(true), body: JSON.stringify({ action: 'stop' }) });
|
|
74
|
+
void reply.body?.cancel().catch(() => undefined);
|
|
75
|
+
if (reply.ok) return;
|
|
76
|
+
// A browser that already stopped may not be stoppable: ask how it is before calling that a failure.
|
|
77
|
+
const state = await fetcher(`${base}/api/v2/browsers/${id}`, { signal: callSignal, headers: headers() });
|
|
78
|
+
const status = state.ok ? (await state.json().catch(() => undefined) as { status?: unknown } | undefined)?.status : (void state.body?.cancel().catch(() => undefined), undefined);
|
|
79
|
+
if (state.status === 404 || status === 'stopped') return;
|
|
80
|
+
throw browserHttpFailure(reply.status);
|
|
81
|
+
};
|
|
82
|
+
// Without liveView, createBrowsers shows no live view. The CDP URL is a WebSocket, or the browser's http(s)
|
|
83
|
+
// address, asked for its WebSocket.
|
|
84
|
+
let url: string;
|
|
85
|
+
try { url = /^wss?:/u.test(browser.cdpUrl) ? browser.cdpUrl : await resolveCdpUrl(browser.cdpUrl, { signal, fetch: fetcher }); }
|
|
86
|
+
catch (error) { await release({ signal: AbortSignal.timeout(30_000) }).catch(() => undefined); throw error; }
|
|
87
|
+
return { id, cdp: { url }, ...(typeof browser.liveUrl === 'string' ? { liveViewUrl: browser.liveUrl } : {}), release };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
return Object.freeze({ id: 'browser-use', features: Object.freeze({ liveView }), maxLifetimeMs, create });
|
|
91
|
+
}
|