browser-use-sdk 0.1.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.
Files changed (370) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +201 -0
  3. package/README.md +358 -0
  4. package/api-promise.d.mts +2 -0
  5. package/api-promise.d.mts.map +1 -0
  6. package/api-promise.d.ts +2 -0
  7. package/api-promise.d.ts.map +1 -0
  8. package/api-promise.js +6 -0
  9. package/api-promise.js.map +1 -0
  10. package/api-promise.mjs +2 -0
  11. package/api-promise.mjs.map +1 -0
  12. package/client.d.mts +189 -0
  13. package/client.d.mts.map +1 -0
  14. package/client.d.ts +189 -0
  15. package/client.d.ts.map +1 -0
  16. package/client.js +470 -0
  17. package/client.js.map +1 -0
  18. package/client.mjs +466 -0
  19. package/client.mjs.map +1 -0
  20. package/core/api-promise.d.mts +46 -0
  21. package/core/api-promise.d.mts.map +1 -0
  22. package/core/api-promise.d.ts +46 -0
  23. package/core/api-promise.d.ts.map +1 -0
  24. package/core/api-promise.js +74 -0
  25. package/core/api-promise.js.map +1 -0
  26. package/core/api-promise.mjs +70 -0
  27. package/core/api-promise.mjs.map +1 -0
  28. package/core/error.d.mts +46 -0
  29. package/core/error.d.mts.map +1 -0
  30. package/core/error.d.ts +46 -0
  31. package/core/error.d.ts.map +1 -0
  32. package/core/error.js +113 -0
  33. package/core/error.js.map +1 -0
  34. package/core/error.mjs +97 -0
  35. package/core/error.mjs.map +1 -0
  36. package/core/resource.d.mts +6 -0
  37. package/core/resource.d.mts.map +1 -0
  38. package/core/resource.d.ts +6 -0
  39. package/core/resource.d.ts.map +1 -0
  40. package/core/resource.js +11 -0
  41. package/core/resource.js.map +1 -0
  42. package/core/resource.mjs +7 -0
  43. package/core/resource.mjs.map +1 -0
  44. package/core/uploads.d.mts +3 -0
  45. package/core/uploads.d.mts.map +1 -0
  46. package/core/uploads.d.ts +3 -0
  47. package/core/uploads.d.ts.map +1 -0
  48. package/core/uploads.js +6 -0
  49. package/core/uploads.js.map +1 -0
  50. package/core/uploads.mjs +2 -0
  51. package/core/uploads.mjs.map +1 -0
  52. package/error.d.mts +2 -0
  53. package/error.d.mts.map +1 -0
  54. package/error.d.ts +2 -0
  55. package/error.d.ts.map +1 -0
  56. package/error.js +6 -0
  57. package/error.js.map +1 -0
  58. package/error.mjs +2 -0
  59. package/error.mjs.map +1 -0
  60. package/index.d.mts +6 -0
  61. package/index.d.mts.map +1 -0
  62. package/index.d.ts +6 -0
  63. package/index.d.ts.map +1 -0
  64. package/index.js +30 -0
  65. package/index.js.map +1 -0
  66. package/index.mjs +7 -0
  67. package/index.mjs.map +1 -0
  68. package/internal/builtin-types.d.mts +73 -0
  69. package/internal/builtin-types.d.mts.map +1 -0
  70. package/internal/builtin-types.d.ts +73 -0
  71. package/internal/builtin-types.d.ts.map +1 -0
  72. package/internal/builtin-types.js +4 -0
  73. package/internal/builtin-types.js.map +1 -0
  74. package/internal/builtin-types.mjs +3 -0
  75. package/internal/builtin-types.mjs.map +1 -0
  76. package/internal/detect-platform.d.mts +15 -0
  77. package/internal/detect-platform.d.mts.map +1 -0
  78. package/internal/detect-platform.d.ts +15 -0
  79. package/internal/detect-platform.d.ts.map +1 -0
  80. package/internal/detect-platform.js +162 -0
  81. package/internal/detect-platform.js.map +1 -0
  82. package/internal/detect-platform.mjs +157 -0
  83. package/internal/detect-platform.mjs.map +1 -0
  84. package/internal/errors.d.mts +3 -0
  85. package/internal/errors.d.mts.map +1 -0
  86. package/internal/errors.d.ts +3 -0
  87. package/internal/errors.d.ts.map +1 -0
  88. package/internal/errors.js +41 -0
  89. package/internal/errors.js.map +1 -0
  90. package/internal/errors.mjs +36 -0
  91. package/internal/errors.mjs.map +1 -0
  92. package/internal/headers.d.mts +20 -0
  93. package/internal/headers.d.mts.map +1 -0
  94. package/internal/headers.d.ts +20 -0
  95. package/internal/headers.d.ts.map +1 -0
  96. package/internal/headers.js +79 -0
  97. package/internal/headers.js.map +1 -0
  98. package/internal/headers.mjs +74 -0
  99. package/internal/headers.mjs.map +1 -0
  100. package/internal/parse.d.mts +12 -0
  101. package/internal/parse.d.mts.map +1 -0
  102. package/internal/parse.d.ts +12 -0
  103. package/internal/parse.d.ts.map +1 -0
  104. package/internal/parse.js +35 -0
  105. package/internal/parse.js.map +1 -0
  106. package/internal/parse.mjs +32 -0
  107. package/internal/parse.mjs.map +1 -0
  108. package/internal/request-options.d.mts +75 -0
  109. package/internal/request-options.d.mts.map +1 -0
  110. package/internal/request-options.d.ts +75 -0
  111. package/internal/request-options.d.ts.map +1 -0
  112. package/internal/request-options.js +14 -0
  113. package/internal/request-options.js.map +1 -0
  114. package/internal/request-options.mjs +10 -0
  115. package/internal/request-options.mjs.map +1 -0
  116. package/internal/shim-types.d.mts +17 -0
  117. package/internal/shim-types.d.mts.map +1 -0
  118. package/internal/shim-types.d.ts +17 -0
  119. package/internal/shim-types.d.ts.map +1 -0
  120. package/internal/shim-types.js +4 -0
  121. package/internal/shim-types.js.map +1 -0
  122. package/internal/shim-types.mjs +3 -0
  123. package/internal/shim-types.mjs.map +1 -0
  124. package/internal/shims.d.mts +20 -0
  125. package/internal/shims.d.mts.map +1 -0
  126. package/internal/shims.d.ts +20 -0
  127. package/internal/shims.d.ts.map +1 -0
  128. package/internal/shims.js +92 -0
  129. package/internal/shims.js.map +1 -0
  130. package/internal/shims.mjs +85 -0
  131. package/internal/shims.mjs.map +1 -0
  132. package/internal/to-file.d.mts +45 -0
  133. package/internal/to-file.d.mts.map +1 -0
  134. package/internal/to-file.d.ts +45 -0
  135. package/internal/to-file.d.ts.map +1 -0
  136. package/internal/to-file.js +91 -0
  137. package/internal/to-file.js.map +1 -0
  138. package/internal/to-file.mjs +88 -0
  139. package/internal/to-file.mjs.map +1 -0
  140. package/internal/tslib.js +81 -0
  141. package/internal/tslib.mjs +17 -0
  142. package/internal/types.d.mts +69 -0
  143. package/internal/types.d.mts.map +1 -0
  144. package/internal/types.d.ts +69 -0
  145. package/internal/types.d.ts.map +1 -0
  146. package/internal/types.js +4 -0
  147. package/internal/types.js.map +1 -0
  148. package/internal/types.mjs +3 -0
  149. package/internal/types.mjs.map +1 -0
  150. package/internal/uploads.d.mts +42 -0
  151. package/internal/uploads.d.mts.map +1 -0
  152. package/internal/uploads.d.ts +42 -0
  153. package/internal/uploads.d.ts.map +1 -0
  154. package/internal/uploads.js +141 -0
  155. package/internal/uploads.js.map +1 -0
  156. package/internal/uploads.mjs +131 -0
  157. package/internal/uploads.mjs.map +1 -0
  158. package/internal/utils/base64.d.mts +3 -0
  159. package/internal/utils/base64.d.mts.map +1 -0
  160. package/internal/utils/base64.d.ts +3 -0
  161. package/internal/utils/base64.d.ts.map +1 -0
  162. package/internal/utils/base64.js +38 -0
  163. package/internal/utils/base64.js.map +1 -0
  164. package/internal/utils/base64.mjs +33 -0
  165. package/internal/utils/base64.mjs.map +1 -0
  166. package/internal/utils/bytes.d.mts +4 -0
  167. package/internal/utils/bytes.d.mts.map +1 -0
  168. package/internal/utils/bytes.d.ts +4 -0
  169. package/internal/utils/bytes.d.ts.map +1 -0
  170. package/internal/utils/bytes.js +31 -0
  171. package/internal/utils/bytes.js.map +1 -0
  172. package/internal/utils/bytes.mjs +26 -0
  173. package/internal/utils/bytes.mjs.map +1 -0
  174. package/internal/utils/env.d.mts +9 -0
  175. package/internal/utils/env.d.mts.map +1 -0
  176. package/internal/utils/env.d.ts +9 -0
  177. package/internal/utils/env.d.ts.map +1 -0
  178. package/internal/utils/env.js +22 -0
  179. package/internal/utils/env.js.map +1 -0
  180. package/internal/utils/env.mjs +18 -0
  181. package/internal/utils/env.mjs.map +1 -0
  182. package/internal/utils/log.d.mts +37 -0
  183. package/internal/utils/log.d.mts.map +1 -0
  184. package/internal/utils/log.d.ts +37 -0
  185. package/internal/utils/log.d.ts.map +1 -0
  186. package/internal/utils/log.js +86 -0
  187. package/internal/utils/log.js.map +1 -0
  188. package/internal/utils/log.mjs +80 -0
  189. package/internal/utils/log.mjs.map +1 -0
  190. package/internal/utils/path.d.mts +15 -0
  191. package/internal/utils/path.d.mts.map +1 -0
  192. package/internal/utils/path.d.ts +15 -0
  193. package/internal/utils/path.d.ts.map +1 -0
  194. package/internal/utils/path.js +79 -0
  195. package/internal/utils/path.js.map +1 -0
  196. package/internal/utils/path.mjs +74 -0
  197. package/internal/utils/path.mjs.map +1 -0
  198. package/internal/utils/sleep.d.mts +2 -0
  199. package/internal/utils/sleep.d.mts.map +1 -0
  200. package/internal/utils/sleep.d.ts +2 -0
  201. package/internal/utils/sleep.d.ts.map +1 -0
  202. package/internal/utils/sleep.js +7 -0
  203. package/internal/utils/sleep.js.map +1 -0
  204. package/internal/utils/sleep.mjs +3 -0
  205. package/internal/utils/sleep.mjs.map +1 -0
  206. package/internal/utils/uuid.d.mts +5 -0
  207. package/internal/utils/uuid.d.mts.map +1 -0
  208. package/internal/utils/uuid.d.ts +5 -0
  209. package/internal/utils/uuid.d.ts.map +1 -0
  210. package/internal/utils/uuid.js +19 -0
  211. package/internal/utils/uuid.js.map +1 -0
  212. package/internal/utils/uuid.mjs +15 -0
  213. package/internal/utils/uuid.mjs.map +1 -0
  214. package/internal/utils/values.d.mts +18 -0
  215. package/internal/utils/values.d.mts.map +1 -0
  216. package/internal/utils/values.d.ts +18 -0
  217. package/internal/utils/values.d.ts.map +1 -0
  218. package/internal/utils/values.js +112 -0
  219. package/internal/utils/values.js.map +1 -0
  220. package/internal/utils/values.mjs +94 -0
  221. package/internal/utils/values.mjs.map +1 -0
  222. package/internal/utils.d.mts +7 -0
  223. package/internal/utils.d.mts.map +1 -0
  224. package/internal/utils.d.ts +7 -0
  225. package/internal/utils.d.ts.map +1 -0
  226. package/internal/utils.js +11 -0
  227. package/internal/utils.js.map +1 -0
  228. package/internal/utils.mjs +8 -0
  229. package/internal/utils.mjs.map +1 -0
  230. package/package.json +138 -0
  231. package/resource.d.mts +2 -0
  232. package/resource.d.mts.map +1 -0
  233. package/resource.d.ts +2 -0
  234. package/resource.d.ts.map +1 -0
  235. package/resource.js +6 -0
  236. package/resource.js.map +1 -0
  237. package/resource.mjs +2 -0
  238. package/resource.mjs.map +1 -0
  239. package/resources/agent-profiles.d.mts +94 -0
  240. package/resources/agent-profiles.d.mts.map +1 -0
  241. package/resources/agent-profiles.d.ts +94 -0
  242. package/resources/agent-profiles.d.ts.map +1 -0
  243. package/resources/agent-profiles.js +40 -0
  244. package/resources/agent-profiles.js.map +1 -0
  245. package/resources/agent-profiles.mjs +36 -0
  246. package/resources/agent-profiles.mjs.map +1 -0
  247. package/resources/browser-profiles.d.mts +98 -0
  248. package/resources/browser-profiles.d.mts.map +1 -0
  249. package/resources/browser-profiles.d.ts +98 -0
  250. package/resources/browser-profiles.d.ts.map +1 -0
  251. package/resources/browser-profiles.js +40 -0
  252. package/resources/browser-profiles.js.map +1 -0
  253. package/resources/browser-profiles.mjs +36 -0
  254. package/resources/browser-profiles.mjs.map +1 -0
  255. package/resources/index.d.mts +5 -0
  256. package/resources/index.d.mts.map +1 -0
  257. package/resources/index.d.ts +5 -0
  258. package/resources/index.d.ts.map +1 -0
  259. package/resources/index.js +13 -0
  260. package/resources/index.js.map +1 -0
  261. package/resources/index.mjs +6 -0
  262. package/resources/index.mjs.map +1 -0
  263. package/resources/sessions/index.d.mts +3 -0
  264. package/resources/sessions/index.d.mts.map +1 -0
  265. package/resources/sessions/index.d.ts +3 -0
  266. package/resources/sessions/index.d.ts.map +1 -0
  267. package/resources/sessions/index.js +9 -0
  268. package/resources/sessions/index.js.map +1 -0
  269. package/resources/sessions/index.mjs +4 -0
  270. package/resources/sessions/index.mjs.map +1 -0
  271. package/resources/sessions/public-share.d.mts +36 -0
  272. package/resources/sessions/public-share.d.mts.map +1 -0
  273. package/resources/sessions/public-share.d.ts +36 -0
  274. package/resources/sessions/public-share.d.ts.map +1 -0
  275. package/resources/sessions/public-share.js +28 -0
  276. package/resources/sessions/public-share.js.map +1 -0
  277. package/resources/sessions/public-share.mjs +24 -0
  278. package/resources/sessions/public-share.mjs.map +1 -0
  279. package/resources/sessions/sessions.d.mts +97 -0
  280. package/resources/sessions/sessions.d.mts.map +1 -0
  281. package/resources/sessions/sessions.d.ts +97 -0
  282. package/resources/sessions/sessions.d.ts.map +1 -0
  283. package/resources/sessions/sessions.js +36 -0
  284. package/resources/sessions/sessions.js.map +1 -0
  285. package/resources/sessions/sessions.mjs +31 -0
  286. package/resources/sessions/sessions.mjs.map +1 -0
  287. package/resources/sessions.d.mts +2 -0
  288. package/resources/sessions.d.mts.map +1 -0
  289. package/resources/sessions.d.ts +2 -0
  290. package/resources/sessions.d.ts.map +1 -0
  291. package/resources/sessions.js +6 -0
  292. package/resources/sessions.js.map +1 -0
  293. package/resources/sessions.mjs +3 -0
  294. package/resources/sessions.mjs.map +1 -0
  295. package/resources/tasks.d.mts +246 -0
  296. package/resources/tasks.d.mts.map +1 -0
  297. package/resources/tasks.d.ts +246 -0
  298. package/resources/tasks.d.ts.map +1 -0
  299. package/resources/tasks.js +47 -0
  300. package/resources/tasks.js.map +1 -0
  301. package/resources/tasks.mjs +43 -0
  302. package/resources/tasks.mjs.map +1 -0
  303. package/resources.d.mts +2 -0
  304. package/resources.d.mts.map +1 -0
  305. package/resources.d.ts +2 -0
  306. package/resources.d.ts.map +1 -0
  307. package/resources.js +5 -0
  308. package/resources.js.map +1 -0
  309. package/resources.mjs +2 -0
  310. package/resources.mjs.map +1 -0
  311. package/src/api-promise.ts +2 -0
  312. package/src/client.ts +817 -0
  313. package/src/core/README.md +3 -0
  314. package/src/core/api-promise.ts +92 -0
  315. package/src/core/error.ts +130 -0
  316. package/src/core/resource.ts +11 -0
  317. package/src/core/uploads.ts +2 -0
  318. package/src/error.ts +2 -0
  319. package/src/index.ts +22 -0
  320. package/src/internal/README.md +3 -0
  321. package/src/internal/builtin-types.ts +93 -0
  322. package/src/internal/detect-platform.ts +196 -0
  323. package/src/internal/errors.ts +33 -0
  324. package/src/internal/headers.ts +97 -0
  325. package/src/internal/parse.ts +50 -0
  326. package/src/internal/request-options.ts +91 -0
  327. package/src/internal/shim-types.ts +26 -0
  328. package/src/internal/shims.ts +107 -0
  329. package/src/internal/to-file.ts +154 -0
  330. package/src/internal/types.ts +95 -0
  331. package/src/internal/uploads.ts +187 -0
  332. package/src/internal/utils/base64.ts +40 -0
  333. package/src/internal/utils/bytes.ts +32 -0
  334. package/src/internal/utils/env.ts +18 -0
  335. package/src/internal/utils/log.ts +127 -0
  336. package/src/internal/utils/path.ts +88 -0
  337. package/src/internal/utils/sleep.ts +3 -0
  338. package/src/internal/utils/uuid.ts +17 -0
  339. package/src/internal/utils/values.ts +105 -0
  340. package/src/internal/utils.ts +8 -0
  341. package/src/lib/.keep +4 -0
  342. package/src/resource.ts +2 -0
  343. package/src/resources/agent-profiles.ts +163 -0
  344. package/src/resources/browser-profiles.ts +172 -0
  345. package/src/resources/index.ts +45 -0
  346. package/src/resources/sessions/index.ts +12 -0
  347. package/src/resources/sessions/public-share.ts +53 -0
  348. package/src/resources/sessions/sessions.ts +150 -0
  349. package/src/resources/sessions.ts +3 -0
  350. package/src/resources/tasks.ts +352 -0
  351. package/src/resources.ts +1 -0
  352. package/src/tsconfig.json +11 -0
  353. package/src/uploads.ts +2 -0
  354. package/src/version.ts +1 -0
  355. package/uploads.d.mts +2 -0
  356. package/uploads.d.mts.map +1 -0
  357. package/uploads.d.ts +2 -0
  358. package/uploads.d.ts.map +1 -0
  359. package/uploads.js +6 -0
  360. package/uploads.js.map +1 -0
  361. package/uploads.mjs +2 -0
  362. package/uploads.mjs.map +1 -0
  363. package/version.d.mts +2 -0
  364. package/version.d.mts.map +1 -0
  365. package/version.d.ts +2 -0
  366. package/version.d.ts.map +1 -0
  367. package/version.js +5 -0
  368. package/version.js.map +1 -0
  369. package/version.mjs +2 -0
  370. package/version.mjs.map +1 -0
package/src/client.ts ADDED
@@ -0,0 +1,817 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types';
4
+ import type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types';
5
+ import { uuid4 } from './internal/utils/uuid';
6
+ import { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values';
7
+ import { sleep } from './internal/utils/sleep';
8
+ export type { Logger, LogLevel } from './internal/utils/log';
9
+ import { castToError, isAbortError } from './internal/errors';
10
+ import type { APIResponseProps } from './internal/parse';
11
+ import { getPlatformHeaders } from './internal/detect-platform';
12
+ import * as Shims from './internal/shims';
13
+ import * as Opts from './internal/request-options';
14
+ import { VERSION } from './version';
15
+ import * as Errors from './core/error';
16
+ import * as Uploads from './core/uploads';
17
+ import * as API from './resources/index';
18
+ import { APIPromise } from './core/api-promise';
19
+ import {
20
+ AgentProfileCreateParams,
21
+ AgentProfileDeleteResponse,
22
+ AgentProfileListParams,
23
+ AgentProfileListResponse,
24
+ AgentProfileUpdateParams,
25
+ AgentProfileView,
26
+ AgentProfiles,
27
+ } from './resources/agent-profiles';
28
+ import {
29
+ BrowserProfileCreateParams,
30
+ BrowserProfileDeleteResponse,
31
+ BrowserProfileListParams,
32
+ BrowserProfileListResponse,
33
+ BrowserProfileUpdateParams,
34
+ BrowserProfileView,
35
+ BrowserProfiles,
36
+ ProxyCountryCode,
37
+ } from './resources/browser-profiles';
38
+ import {
39
+ LlmModel,
40
+ TaskCreateParams,
41
+ TaskListParams,
42
+ TaskListResponse,
43
+ TaskRetrieveLogsResponse,
44
+ TaskRetrieveOutputFileParams,
45
+ TaskRetrieveOutputFileResponse,
46
+ TaskRetrieveParams,
47
+ TaskRetrieveResponse,
48
+ TaskStatus,
49
+ TaskUpdateParams,
50
+ TaskView,
51
+ Tasks,
52
+ } from './resources/tasks';
53
+ import {
54
+ SessionListParams,
55
+ SessionListResponse,
56
+ SessionRetrieveParams,
57
+ SessionStatus,
58
+ SessionUpdateParams,
59
+ SessionView,
60
+ Sessions,
61
+ } from './resources/sessions/sessions';
62
+ import { type Fetch } from './internal/builtin-types';
63
+ import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers';
64
+ import { FinalRequestOptions, RequestOptions } from './internal/request-options';
65
+ import { readEnv } from './internal/utils/env';
66
+ import {
67
+ type LogLevel,
68
+ type Logger,
69
+ formatRequestDetails,
70
+ loggerFor,
71
+ parseLogLevel,
72
+ } from './internal/utils/log';
73
+ import { isEmptyObj } from './internal/utils/values';
74
+
75
+ export interface ClientOptions {
76
+ /**
77
+ * Defaults to process.env['BROWSER_USE_API_KEY'].
78
+ */
79
+ apiKey?: string | undefined;
80
+
81
+ /**
82
+ * Override the default base URL for the API, e.g., "https://api.example.com/v2/"
83
+ *
84
+ * Defaults to process.env['BROWSER_USE_BASE_URL'].
85
+ */
86
+ baseURL?: string | null | undefined;
87
+
88
+ /**
89
+ * The maximum amount of time (in milliseconds) that the client should wait for a response
90
+ * from the server before timing out a single request.
91
+ *
92
+ * Note that request timeouts are retried by default, so in a worst-case scenario you may wait
93
+ * much longer than this timeout before the promise succeeds or fails.
94
+ *
95
+ * @unit milliseconds
96
+ */
97
+ timeout?: number | undefined;
98
+ /**
99
+ * Additional `RequestInit` options to be passed to `fetch` calls.
100
+ * Properties will be overridden by per-request `fetchOptions`.
101
+ */
102
+ fetchOptions?: MergedRequestInit | undefined;
103
+
104
+ /**
105
+ * Specify a custom `fetch` function implementation.
106
+ *
107
+ * If not provided, we expect that `fetch` is defined globally.
108
+ */
109
+ fetch?: Fetch | undefined;
110
+
111
+ /**
112
+ * The maximum number of times that the client will retry a request in case of a
113
+ * temporary failure, like a network error or a 5XX error from the server.
114
+ *
115
+ * @default 2
116
+ */
117
+ maxRetries?: number | undefined;
118
+
119
+ /**
120
+ * Default headers to include with every request to the API.
121
+ *
122
+ * These can be removed in individual requests by explicitly setting the
123
+ * header to `null` in request options.
124
+ */
125
+ defaultHeaders?: HeadersLike | undefined;
126
+
127
+ /**
128
+ * Default query parameters to include with every request to the API.
129
+ *
130
+ * These can be removed in individual requests by explicitly setting the
131
+ * param to `undefined` in request options.
132
+ */
133
+ defaultQuery?: Record<string, string | undefined> | undefined;
134
+
135
+ /**
136
+ * Set the log level.
137
+ *
138
+ * Defaults to process.env['BROWSER_USE_LOG'] or 'warn' if it isn't set.
139
+ */
140
+ logLevel?: LogLevel | undefined;
141
+
142
+ /**
143
+ * Set the logger.
144
+ *
145
+ * Defaults to globalThis.console.
146
+ */
147
+ logger?: Logger | undefined;
148
+ }
149
+
150
+ /**
151
+ * API Client for interfacing with the Browser Use API.
152
+ */
153
+ export class BrowserUse {
154
+ apiKey: string;
155
+
156
+ baseURL: string;
157
+ maxRetries: number;
158
+ timeout: number;
159
+ logger: Logger | undefined;
160
+ logLevel: LogLevel | undefined;
161
+ fetchOptions: MergedRequestInit | undefined;
162
+
163
+ private fetch: Fetch;
164
+ #encoder: Opts.RequestEncoder;
165
+ protected idempotencyHeader?: string;
166
+ private _options: ClientOptions;
167
+
168
+ /**
169
+ * API Client for interfacing with the Browser Use API.
170
+ *
171
+ * @param {string | undefined} [opts.apiKey=process.env['BROWSER_USE_API_KEY'] ?? undefined]
172
+ * @param {string} [opts.baseURL=process.env['BROWSER_USE_BASE_URL'] ?? https://api.browser-use.com/api/v2] - Override the default base URL for the API.
173
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
174
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
175
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
176
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
177
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
178
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
179
+ */
180
+ constructor({
181
+ baseURL = readEnv('BROWSER_USE_BASE_URL'),
182
+ apiKey = readEnv('BROWSER_USE_API_KEY'),
183
+ ...opts
184
+ }: ClientOptions = {}) {
185
+ if (apiKey === undefined) {
186
+ throw new Errors.BrowserUseError(
187
+ "The BROWSER_USE_API_KEY environment variable is missing or empty; either provide it, or instantiate the BrowserUse client with an apiKey option, like new BrowserUse({ apiKey: 'My API Key' }).",
188
+ );
189
+ }
190
+
191
+ const options: ClientOptions = {
192
+ apiKey,
193
+ ...opts,
194
+ baseURL: baseURL || `https://api.browser-use.com/api/v2`,
195
+ };
196
+
197
+ this.baseURL = options.baseURL!;
198
+ this.timeout = options.timeout ?? BrowserUse.DEFAULT_TIMEOUT /* 1 minute */;
199
+ this.logger = options.logger ?? console;
200
+ const defaultLogLevel = 'warn';
201
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
202
+ this.logLevel = defaultLogLevel;
203
+ this.logLevel =
204
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
205
+ parseLogLevel(readEnv('BROWSER_USE_LOG'), "process.env['BROWSER_USE_LOG']", this) ??
206
+ defaultLogLevel;
207
+ this.fetchOptions = options.fetchOptions;
208
+ this.maxRetries = options.maxRetries ?? 2;
209
+ this.fetch = options.fetch ?? Shims.getDefaultFetch();
210
+ this.#encoder = Opts.FallbackEncoder;
211
+
212
+ this._options = options;
213
+
214
+ this.apiKey = apiKey;
215
+ }
216
+
217
+ /**
218
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
219
+ */
220
+ withOptions(options: Partial<ClientOptions>): this {
221
+ const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
222
+ ...this._options,
223
+ baseURL: this.baseURL,
224
+ maxRetries: this.maxRetries,
225
+ timeout: this.timeout,
226
+ logger: this.logger,
227
+ logLevel: this.logLevel,
228
+ fetch: this.fetch,
229
+ fetchOptions: this.fetchOptions,
230
+ apiKey: this.apiKey,
231
+ ...options,
232
+ });
233
+ return client;
234
+ }
235
+
236
+ /**
237
+ * Check whether the base URL is set to its default.
238
+ */
239
+ #baseURLOverridden(): boolean {
240
+ return this.baseURL !== 'https://api.browser-use.com/api/v2';
241
+ }
242
+
243
+ protected defaultQuery(): Record<string, string | undefined> | undefined {
244
+ return this._options.defaultQuery;
245
+ }
246
+
247
+ protected validateHeaders({ values, nulls }: NullableHeaders) {
248
+ return;
249
+ }
250
+
251
+ protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
252
+ return buildHeaders([{ 'X-Browser-Use-API-Key': this.apiKey }]);
253
+ }
254
+
255
+ /**
256
+ * Basic re-implementation of `qs.stringify` for primitive types.
257
+ */
258
+ protected stringifyQuery(query: Record<string, unknown>): string {
259
+ return Object.entries(query)
260
+ .filter(([_, value]) => typeof value !== 'undefined')
261
+ .map(([key, value]) => {
262
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
263
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
264
+ }
265
+ if (value === null) {
266
+ return `${encodeURIComponent(key)}=`;
267
+ }
268
+ throw new Errors.BrowserUseError(
269
+ `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,
270
+ );
271
+ })
272
+ .join('&');
273
+ }
274
+
275
+ private getUserAgent(): string {
276
+ return `${this.constructor.name}/JS ${VERSION}`;
277
+ }
278
+
279
+ protected defaultIdempotencyKey(): string {
280
+ return `stainless-node-retry-${uuid4()}`;
281
+ }
282
+
283
+ protected makeStatusError(
284
+ status: number,
285
+ error: Object,
286
+ message: string | undefined,
287
+ headers: Headers,
288
+ ): Errors.APIError {
289
+ return Errors.APIError.generate(status, error, message, headers);
290
+ }
291
+
292
+ buildURL(
293
+ path: string,
294
+ query: Record<string, unknown> | null | undefined,
295
+ defaultBaseURL?: string | undefined,
296
+ ): string {
297
+ const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL;
298
+ const url =
299
+ isAbsoluteURL(path) ?
300
+ new URL(path)
301
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
302
+
303
+ const defaultQuery = this.defaultQuery();
304
+ if (!isEmptyObj(defaultQuery)) {
305
+ query = { ...defaultQuery, ...query };
306
+ }
307
+
308
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
309
+ url.search = this.stringifyQuery(query as Record<string, unknown>);
310
+ }
311
+
312
+ return url.toString();
313
+ }
314
+
315
+ /**
316
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
317
+ */
318
+ protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}
319
+
320
+ /**
321
+ * Used as a callback for mutating the given `RequestInit` object.
322
+ *
323
+ * This is useful for cases where you want to add certain headers based off of
324
+ * the request properties, e.g. `method` or `url`.
325
+ */
326
+ protected async prepareRequest(
327
+ request: RequestInit,
328
+ { url, options }: { url: string; options: FinalRequestOptions },
329
+ ): Promise<void> {}
330
+
331
+ get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
332
+ return this.methodRequest('get', path, opts);
333
+ }
334
+
335
+ post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
336
+ return this.methodRequest('post', path, opts);
337
+ }
338
+
339
+ patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
340
+ return this.methodRequest('patch', path, opts);
341
+ }
342
+
343
+ put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
344
+ return this.methodRequest('put', path, opts);
345
+ }
346
+
347
+ delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
348
+ return this.methodRequest('delete', path, opts);
349
+ }
350
+
351
+ private methodRequest<Rsp>(
352
+ method: HTTPMethod,
353
+ path: string,
354
+ opts?: PromiseOrValue<RequestOptions>,
355
+ ): APIPromise<Rsp> {
356
+ return this.request(
357
+ Promise.resolve(opts).then((opts) => {
358
+ return { method, path, ...opts };
359
+ }),
360
+ );
361
+ }
362
+
363
+ request<Rsp>(
364
+ options: PromiseOrValue<FinalRequestOptions>,
365
+ remainingRetries: number | null = null,
366
+ ): APIPromise<Rsp> {
367
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
368
+ }
369
+
370
+ private async makeRequest(
371
+ optionsInput: PromiseOrValue<FinalRequestOptions>,
372
+ retriesRemaining: number | null,
373
+ retryOfRequestLogID: string | undefined,
374
+ ): Promise<APIResponseProps> {
375
+ const options = await optionsInput;
376
+ const maxRetries = options.maxRetries ?? this.maxRetries;
377
+ if (retriesRemaining == null) {
378
+ retriesRemaining = maxRetries;
379
+ }
380
+
381
+ await this.prepareOptions(options);
382
+
383
+ const { req, url, timeout } = await this.buildRequest(options, {
384
+ retryCount: maxRetries - retriesRemaining,
385
+ });
386
+
387
+ await this.prepareRequest(req, { url, options });
388
+
389
+ /** Not an API request ID, just for correlating local log entries. */
390
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
391
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
392
+ const startTime = Date.now();
393
+
394
+ loggerFor(this).debug(
395
+ `[${requestLogID}] sending request`,
396
+ formatRequestDetails({
397
+ retryOfRequestLogID,
398
+ method: options.method,
399
+ url,
400
+ options,
401
+ headers: req.headers,
402
+ }),
403
+ );
404
+
405
+ if (options.signal?.aborted) {
406
+ throw new Errors.APIUserAbortError();
407
+ }
408
+
409
+ const controller = new AbortController();
410
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
411
+ const headersTime = Date.now();
412
+
413
+ if (response instanceof Error) {
414
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
415
+ if (options.signal?.aborted) {
416
+ throw new Errors.APIUserAbortError();
417
+ }
418
+ // detect native connection timeout errors
419
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
420
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
421
+ // others do not provide enough information to distinguish timeouts from other connection errors
422
+ const isTimeout =
423
+ isAbortError(response) ||
424
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
425
+ if (retriesRemaining) {
426
+ loggerFor(this).info(
427
+ `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`,
428
+ );
429
+ loggerFor(this).debug(
430
+ `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`,
431
+ formatRequestDetails({
432
+ retryOfRequestLogID,
433
+ url,
434
+ durationMs: headersTime - startTime,
435
+ message: response.message,
436
+ }),
437
+ );
438
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
439
+ }
440
+ loggerFor(this).info(
441
+ `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`,
442
+ );
443
+ loggerFor(this).debug(
444
+ `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`,
445
+ formatRequestDetails({
446
+ retryOfRequestLogID,
447
+ url,
448
+ durationMs: headersTime - startTime,
449
+ message: response.message,
450
+ }),
451
+ );
452
+ if (isTimeout) {
453
+ throw new Errors.APIConnectionTimeoutError();
454
+ }
455
+ throw new Errors.APIConnectionError({ cause: response });
456
+ }
457
+
458
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${
459
+ response.ok ? 'succeeded' : 'failed'
460
+ } with status ${response.status} in ${headersTime - startTime}ms`;
461
+
462
+ if (!response.ok) {
463
+ const shouldRetry = await this.shouldRetry(response);
464
+ if (retriesRemaining && shouldRetry) {
465
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
466
+
467
+ // We don't need the body of this response.
468
+ await Shims.CancelReadableStream(response.body);
469
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
470
+ loggerFor(this).debug(
471
+ `[${requestLogID}] response error (${retryMessage})`,
472
+ formatRequestDetails({
473
+ retryOfRequestLogID,
474
+ url: response.url,
475
+ status: response.status,
476
+ headers: response.headers,
477
+ durationMs: headersTime - startTime,
478
+ }),
479
+ );
480
+ return this.retryRequest(
481
+ options,
482
+ retriesRemaining,
483
+ retryOfRequestLogID ?? requestLogID,
484
+ response.headers,
485
+ );
486
+ }
487
+
488
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
489
+
490
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
491
+
492
+ const errText = await response.text().catch((err: any) => castToError(err).message);
493
+ const errJSON = safeJSON(errText);
494
+ const errMessage = errJSON ? undefined : errText;
495
+
496
+ loggerFor(this).debug(
497
+ `[${requestLogID}] response error (${retryMessage})`,
498
+ formatRequestDetails({
499
+ retryOfRequestLogID,
500
+ url: response.url,
501
+ status: response.status,
502
+ headers: response.headers,
503
+ message: errMessage,
504
+ durationMs: Date.now() - startTime,
505
+ }),
506
+ );
507
+
508
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
509
+ throw err;
510
+ }
511
+
512
+ loggerFor(this).info(responseInfo);
513
+ loggerFor(this).debug(
514
+ `[${requestLogID}] response start`,
515
+ formatRequestDetails({
516
+ retryOfRequestLogID,
517
+ url: response.url,
518
+ status: response.status,
519
+ headers: response.headers,
520
+ durationMs: headersTime - startTime,
521
+ }),
522
+ );
523
+
524
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
525
+ }
526
+
527
+ async fetchWithTimeout(
528
+ url: RequestInfo,
529
+ init: RequestInit | undefined,
530
+ ms: number,
531
+ controller: AbortController,
532
+ ): Promise<Response> {
533
+ const { signal, method, ...options } = init || {};
534
+ if (signal) signal.addEventListener('abort', () => controller.abort());
535
+
536
+ const timeout = setTimeout(() => controller.abort(), ms);
537
+
538
+ const isReadableBody =
539
+ ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) ||
540
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
541
+
542
+ const fetchOptions: RequestInit = {
543
+ signal: controller.signal as any,
544
+ ...(isReadableBody ? { duplex: 'half' } : {}),
545
+ method: 'GET',
546
+ ...options,
547
+ };
548
+ if (method) {
549
+ // Custom methods like 'patch' need to be uppercased
550
+ // See https://github.com/nodejs/undici/issues/2294
551
+ fetchOptions.method = method.toUpperCase();
552
+ }
553
+
554
+ try {
555
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
556
+ return await this.fetch.call(undefined, url, fetchOptions);
557
+ } finally {
558
+ clearTimeout(timeout);
559
+ }
560
+ }
561
+
562
+ private async shouldRetry(response: Response): Promise<boolean> {
563
+ // Note this is not a standard header.
564
+ const shouldRetryHeader = response.headers.get('x-should-retry');
565
+
566
+ // If the server explicitly says whether or not to retry, obey.
567
+ if (shouldRetryHeader === 'true') return true;
568
+ if (shouldRetryHeader === 'false') return false;
569
+
570
+ // Retry on request timeouts.
571
+ if (response.status === 408) return true;
572
+
573
+ // Retry on lock timeouts.
574
+ if (response.status === 409) return true;
575
+
576
+ // Retry on rate limits.
577
+ if (response.status === 429) return true;
578
+
579
+ // Retry internal errors.
580
+ if (response.status >= 500) return true;
581
+
582
+ return false;
583
+ }
584
+
585
+ private async retryRequest(
586
+ options: FinalRequestOptions,
587
+ retriesRemaining: number,
588
+ requestLogID: string,
589
+ responseHeaders?: Headers | undefined,
590
+ ): Promise<APIResponseProps> {
591
+ let timeoutMillis: number | undefined;
592
+
593
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
594
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
595
+ if (retryAfterMillisHeader) {
596
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
597
+ if (!Number.isNaN(timeoutMs)) {
598
+ timeoutMillis = timeoutMs;
599
+ }
600
+ }
601
+
602
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
603
+ const retryAfterHeader = responseHeaders?.get('retry-after');
604
+ if (retryAfterHeader && !timeoutMillis) {
605
+ const timeoutSeconds = parseFloat(retryAfterHeader);
606
+ if (!Number.isNaN(timeoutSeconds)) {
607
+ timeoutMillis = timeoutSeconds * 1000;
608
+ } else {
609
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
610
+ }
611
+ }
612
+
613
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
614
+ // just do what it says, but otherwise calculate a default
615
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
616
+ const maxRetries = options.maxRetries ?? this.maxRetries;
617
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
618
+ }
619
+ await sleep(timeoutMillis);
620
+
621
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
622
+ }
623
+
624
+ private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
625
+ const initialRetryDelay = 0.5;
626
+ const maxRetryDelay = 8.0;
627
+
628
+ const numRetries = maxRetries - retriesRemaining;
629
+
630
+ // Apply exponential backoff, but not more than the max.
631
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
632
+
633
+ // Apply some jitter, take up to at most 25 percent of the retry time.
634
+ const jitter = 1 - Math.random() * 0.25;
635
+
636
+ return sleepSeconds * jitter * 1000;
637
+ }
638
+
639
+ async buildRequest(
640
+ inputOptions: FinalRequestOptions,
641
+ { retryCount = 0 }: { retryCount?: number } = {},
642
+ ): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
643
+ const options = { ...inputOptions };
644
+ const { method, path, query, defaultBaseURL } = options;
645
+
646
+ const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
647
+ if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
648
+ options.timeout = options.timeout ?? this.timeout;
649
+ const { bodyHeaders, body } = this.buildBody({ options });
650
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
651
+
652
+ const req: FinalizedRequestInit = {
653
+ method,
654
+ headers: reqHeaders,
655
+ ...(options.signal && { signal: options.signal }),
656
+ ...((globalThis as any).ReadableStream &&
657
+ body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }),
658
+ ...(body && { body }),
659
+ ...((this.fetchOptions as any) ?? {}),
660
+ ...((options.fetchOptions as any) ?? {}),
661
+ };
662
+
663
+ return { req, url, timeout: options.timeout };
664
+ }
665
+
666
+ private async buildHeaders({
667
+ options,
668
+ method,
669
+ bodyHeaders,
670
+ retryCount,
671
+ }: {
672
+ options: FinalRequestOptions;
673
+ method: HTTPMethod;
674
+ bodyHeaders: HeadersLike;
675
+ retryCount: number;
676
+ }): Promise<Headers> {
677
+ let idempotencyHeaders: HeadersLike = {};
678
+ if (this.idempotencyHeader && method !== 'get') {
679
+ if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
680
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
681
+ }
682
+
683
+ const headers = buildHeaders([
684
+ idempotencyHeaders,
685
+ {
686
+ Accept: 'application/json',
687
+ 'User-Agent': this.getUserAgent(),
688
+ 'X-Stainless-Retry-Count': String(retryCount),
689
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
690
+ ...getPlatformHeaders(),
691
+ },
692
+ await this.authHeaders(options),
693
+ this._options.defaultHeaders,
694
+ bodyHeaders,
695
+ options.headers,
696
+ ]);
697
+
698
+ this.validateHeaders(headers);
699
+
700
+ return headers.values;
701
+ }
702
+
703
+ private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): {
704
+ bodyHeaders: HeadersLike;
705
+ body: BodyInit | undefined;
706
+ } {
707
+ if (!body) {
708
+ return { bodyHeaders: undefined, body: undefined };
709
+ }
710
+ const headers = buildHeaders([rawHeaders]);
711
+ if (
712
+ // Pass raw type verbatim
713
+ ArrayBuffer.isView(body) ||
714
+ body instanceof ArrayBuffer ||
715
+ body instanceof DataView ||
716
+ (typeof body === 'string' &&
717
+ // Preserve legacy string encoding behavior for now
718
+ headers.values.has('content-type')) ||
719
+ // `Blob` is superset of `File`
720
+ body instanceof Blob ||
721
+ // `FormData` -> `multipart/form-data`
722
+ body instanceof FormData ||
723
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
724
+ body instanceof URLSearchParams ||
725
+ // Send chunked stream (each chunk has own `length`)
726
+ ((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream)
727
+ ) {
728
+ return { bodyHeaders: undefined, body: body as BodyInit };
729
+ } else if (
730
+ typeof body === 'object' &&
731
+ (Symbol.asyncIterator in body ||
732
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))
733
+ ) {
734
+ return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable<Uint8Array>) };
735
+ } else {
736
+ return this.#encoder({ body, headers });
737
+ }
738
+ }
739
+
740
+ static BrowserUse = this;
741
+ static DEFAULT_TIMEOUT = 60000; // 1 minute
742
+
743
+ static BrowserUseError = Errors.BrowserUseError;
744
+ static APIError = Errors.APIError;
745
+ static APIConnectionError = Errors.APIConnectionError;
746
+ static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
747
+ static APIUserAbortError = Errors.APIUserAbortError;
748
+ static NotFoundError = Errors.NotFoundError;
749
+ static ConflictError = Errors.ConflictError;
750
+ static RateLimitError = Errors.RateLimitError;
751
+ static BadRequestError = Errors.BadRequestError;
752
+ static AuthenticationError = Errors.AuthenticationError;
753
+ static InternalServerError = Errors.InternalServerError;
754
+ static PermissionDeniedError = Errors.PermissionDeniedError;
755
+ static UnprocessableEntityError = Errors.UnprocessableEntityError;
756
+
757
+ static toFile = Uploads.toFile;
758
+
759
+ tasks: API.Tasks = new API.Tasks(this);
760
+ sessions: API.Sessions = new API.Sessions(this);
761
+ browserProfiles: API.BrowserProfiles = new API.BrowserProfiles(this);
762
+ agentProfiles: API.AgentProfiles = new API.AgentProfiles(this);
763
+ }
764
+ BrowserUse.Tasks = Tasks;
765
+ BrowserUse.Sessions = Sessions;
766
+ BrowserUse.BrowserProfiles = BrowserProfiles;
767
+ BrowserUse.AgentProfiles = AgentProfiles;
768
+ export declare namespace BrowserUse {
769
+ export type RequestOptions = Opts.RequestOptions;
770
+
771
+ export {
772
+ Tasks as Tasks,
773
+ type LlmModel as LlmModel,
774
+ type TaskStatus as TaskStatus,
775
+ type TaskView as TaskView,
776
+ type TaskRetrieveResponse as TaskRetrieveResponse,
777
+ type TaskListResponse as TaskListResponse,
778
+ type TaskRetrieveLogsResponse as TaskRetrieveLogsResponse,
779
+ type TaskRetrieveOutputFileResponse as TaskRetrieveOutputFileResponse,
780
+ type TaskCreateParams as TaskCreateParams,
781
+ type TaskRetrieveParams as TaskRetrieveParams,
782
+ type TaskUpdateParams as TaskUpdateParams,
783
+ type TaskListParams as TaskListParams,
784
+ type TaskRetrieveOutputFileParams as TaskRetrieveOutputFileParams,
785
+ };
786
+
787
+ export {
788
+ Sessions as Sessions,
789
+ type SessionStatus as SessionStatus,
790
+ type SessionView as SessionView,
791
+ type SessionListResponse as SessionListResponse,
792
+ type SessionRetrieveParams as SessionRetrieveParams,
793
+ type SessionUpdateParams as SessionUpdateParams,
794
+ type SessionListParams as SessionListParams,
795
+ };
796
+
797
+ export {
798
+ BrowserProfiles as BrowserProfiles,
799
+ type BrowserProfileView as BrowserProfileView,
800
+ type ProxyCountryCode as ProxyCountryCode,
801
+ type BrowserProfileListResponse as BrowserProfileListResponse,
802
+ type BrowserProfileDeleteResponse as BrowserProfileDeleteResponse,
803
+ type BrowserProfileCreateParams as BrowserProfileCreateParams,
804
+ type BrowserProfileUpdateParams as BrowserProfileUpdateParams,
805
+ type BrowserProfileListParams as BrowserProfileListParams,
806
+ };
807
+
808
+ export {
809
+ AgentProfiles as AgentProfiles,
810
+ type AgentProfileView as AgentProfileView,
811
+ type AgentProfileListResponse as AgentProfileListResponse,
812
+ type AgentProfileDeleteResponse as AgentProfileDeleteResponse,
813
+ type AgentProfileCreateParams as AgentProfileCreateParams,
814
+ type AgentProfileUpdateParams as AgentProfileUpdateParams,
815
+ type AgentProfileListParams as AgentProfileListParams,
816
+ };
817
+ }