@browserless.io/cli 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,149 +1,167 @@
1
1
  # Changelog
2
2
 
3
- ## [0.6.0](https://github.com/browserless/browserless-cli/compare/v0.5.2...v0.6.0) (2026-11-05)
3
+ ## 0.7.0 (2026-11-20)
4
4
 
5
5
 
6
6
  ### Features
7
7
 
8
- * AUTO-691 record failure category, code and HTTP status in CLI telemetry ([#145](https://github.com/browserless/browserless-cli/issues/145)) ([90e8459](https://github.com/browserless/browserless-cli/commit/90e8459415783cd1bb927e92b251f8a41e5b35d9))
8
+ * use saved cloud profiles for agent sign-in with `agent --cloud-profile <name>`; the agent no longer asks for a username and password
9
9
 
10
- ## [0.5.2](https://github.com/browserless/browserless-cli/compare/v0.5.1...v0.5.2) (2026-10-30)
10
+ ## 0.6.1 (2026-11-13)
11
11
 
12
12
 
13
13
  ### Bug Fixes
14
14
 
15
- * PLT-1989 reject authenticated API redirects ([#142](https://github.com/browserless/browserless-cli/issues/142)) ([211decc](https://github.com/browserless/browserless-cli/commit/211decc03f01896a8881c031f14a3ed56e4b6279))
16
- * PLT-1990 isolate capture smoke state and replay ([#143](https://github.com/browserless/browserless-cli/issues/143)) ([6c4f352](https://github.com/browserless/browserless-cli/commit/6c4f3520ee46213159001a528b5126fd12d88ccc))
15
+ * bound decoded API responses and body deadlines
16
+ * capture over a private pipe instead of a local debugging port, and stop the headless browser and delete the temporary profile copy when a capture is interrupted
17
+ * escape remote agent terminal output
18
+ * escape terminal controls in error and profile displays
19
+ * pin custom browser registration paths
17
20
 
18
- ## [0.5.1](https://github.com/browserless/browserless-cli/compare/v0.5.0...v0.5.1) (2026-10-22)
21
+ ## 0.6.0 (2026-11-05)
22
+
23
+
24
+ ### Features
25
+
26
+ * record failure category, code and HTTP status in CLI telemetry
27
+
28
+ ## 0.5.2 (2026-10-30)
29
+
30
+
31
+ ### Bug Fixes
32
+
33
+ * reject authenticated API redirects
34
+ * isolate capture smoke state and replay
35
+
36
+ ## 0.5.1 (2026-10-22)
19
37
 
20
38
 
21
39
  ### Bug Fixes
22
40
 
23
- * AUTO-640 detect the Windows cookie-file lock during profile capture ([#134](https://github.com/browserless/browserless-cli/issues/134)) ([3a2ca62](https://github.com/browserless/browserless-cli/commit/3a2ca628558976e3444362d368bab2b27dc8ff8d))
41
+ * detect the Windows cookie-file lock during profile capture
24
42
 
25
- ## [0.5.0](https://github.com/browserless/browserless-cli/compare/v0.4.2...v0.5.0) (2026-10-16)
43
+ ## 0.5.0 (2026-10-16)
26
44
 
27
45
 
28
46
  ### Features
29
47
 
30
- * AUTO-303 add profile terms command ([#130](https://github.com/browserless/browserless-cli/issues/130)) ([3472d1f](https://github.com/browserless/browserless-cli/commit/3472d1fd8dcb23f59f3c0d4501399d9cc49ff0dc))
48
+ * add profile terms command
31
49
 
32
- ## [0.4.2](https://github.com/browserless/browserless-cli/compare/v0.4.1...v0.4.2) (2026-10-13)
50
+ ## 0.4.2 (2026-10-13)
33
51
 
34
52
 
35
53
  ### Bug Fixes
36
54
 
37
- * PLT-1314 enforce secure server URLs before sending tokens ([#120](https://github.com/browserless/browserless-cli/issues/120)) ([de84550](https://github.com/browserless/browserless-cli/commit/de8455044faa84d99627475db49eb76a7feadfc1))
55
+ * enforce secure server URLs before sending tokens
38
56
 
39
- ## [0.4.1](https://github.com/browserless/browserless-cli/compare/v0.4.0...v0.4.1) (2026-10-06)
57
+ ## 0.4.1 (2026-10-06)
40
58
 
41
59
 
42
60
  ### Bug Fixes
43
61
 
44
- * PLT-1315 restrict telemetry to trusted API hosts ([#119](https://github.com/browserless/browserless-cli/issues/119)) ([c67453c](https://github.com/browserless/browserless-cli/commit/c67453c272feb00f890013e3d334f7c8a226a35d))
62
+ * restrict telemetry to trusted API hosts
45
63
 
46
- ## [0.4.0](https://github.com/browserless/browserless-cli/compare/v0.3.0...v0.4.0) (2026-09-22)
64
+ ## 0.4.0 (2026-09-22)
47
65
 
48
66
 
49
67
  ### Features
50
68
 
51
- * AUTO-419 track CLI profile setup attempts ([#100](https://github.com/browserless/browserless-cli/issues/100)) ([93f5f5f](https://github.com/browserless/browserless-cli/commit/93f5f5fc033dbe98788f614082e997bd31a7129c))
69
+ * track CLI profile setup attempts
52
70
 
53
- ## [0.3.0](https://github.com/browserless/browserless-cli/compare/v0.2.0...v0.3.0) (2026-08-04)
71
+ ## 0.3.0 (2026-08-04)
54
72
 
55
73
 
56
74
  ### Features
57
75
 
58
- * Profile refresh replays the capture settings a profile was created with — no flags needed ([#58](https://github.com/browserless/browserless-cli/issues/58)) ([94fe959](https://github.com/browserless/browserless-cli/commit/94fe959620909e9f7e9bfe533dd0c94c1560c712))
76
+ * Profile refresh replays the capture settings a profile was created with — no flags needed
59
77
 
60
- ## [0.2.0](https://github.com/browserless/browserless-cli/compare/v0.1.0...v0.2.0) (2026-06-18)
78
+ ## 0.2.0 (2026-06-18)
61
79
 
62
80
 
63
81
  ### Features
64
82
 
65
- * add usage telemetry ([#19](https://github.com/browserless/browserless-cli/issues/19)) ([bdaa5dd](https://github.com/browserless/browserless-cli/commit/bdaa5dd01a8c6712dcf345edae1c41a228e05097))
83
+ * add usage telemetry
66
84
 
67
- ## [0.1.0](https://github.com/browserless/browserless-cli/compare/v0.0.3...v0.1.0) (2026-06-05)
85
+ ## 0.1.0 (2026-06-05)
68
86
 
69
87
 
70
88
  ### Features
71
89
 
72
- * Interactive agent chat via `browserless agent` ([c453dba](https://github.com/browserless/browserless-cli/commit/c453dbad50aa3283f9f8340bf32ed51d185ff132))
90
+ * Interactive agent chat via `browserless agent`
73
91
 
74
- ## [0.0.3](https://github.com/browserless/browserless-cli/compare/v0.0.2...v0.0.3) (2026-06-05)
92
+ ## 0.0.3 (2026-06-05)
75
93
 
76
94
 
77
95
  ### Bug Fixes
78
96
 
79
- * **capture:** connect to the browser CDP endpoint, not a default page target ([417cb12](https://github.com/browserless/browserless-cli/commit/417cb122743bfcfdd91ebbd4d010c7558f02138c))
80
- * **capture:** retry the default-target CDP connect on "No inspectable targets" ([b834311](https://github.com/browserless/browserless-cli/commit/b8343118a801938e09ff4a5e67957762317a08b1))
81
- * **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets") ([69c2e96](https://github.com/browserless/browserless-cli/commit/69c2e961e6f70fba5fd40a6ea64e3aba9f323047))
82
- * **cli:** set process.exitCode instead of process.exit() on error path ([2a6042a](https://github.com/browserless/browserless-cli/commit/2a6042a52fbdbedfcb56086566a6f0a4bdb09ea0))
83
- * **cli:** windows/macos flaky tests ([559a10d](https://github.com/browserless/browserless-cli/commit/559a10d729251cca0ba1e891bffe13b8caf7b186))
97
+ * **capture:** connect to the browser CDP endpoint, not a default page target
98
+ * **capture:** retry the default-target CDP connect on "No inspectable targets"
99
+ * **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets")
100
+ * **cli:** set process.exitCode instead of process.exit() on error path
101
+ * **cli:** windows/macos flaky tests
84
102
 
85
- ## [0.0.2](https://github.com/browserless/browserless-cli/compare/v0.0.1...v0.0.2) (2026-05-27)
103
+ ## 0.0.2 (2026-05-27)
86
104
 
87
105
 
88
106
  ### Features
89
107
 
90
- * --region sfo|lon|ams shortcut + region config key ([c921251](https://github.com/browserless/browserless-cli/commit/c921251664c89bb0e66c2549767d37ae2f011734))
91
- * Add the Browserless CLI for authenticated profile management ([d2ccbbe](https://github.com/browserless/browserless-cli/commit/d2ccbbe33204f74e188a1a4bb7a999e40a7034d7))
92
- * **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt ([f83c2a9](https://github.com/browserless/browserless-cli/commit/f83c2a99d086f9ab4c267f254a42c1154de7b9d4))
93
- * **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions ([0ad3a97](https://github.com/browserless/browserless-cli/commit/0ad3a9731c6133dcd68356c33b4ce40b0d01c4d0))
94
- * **ci:** cli-smoke integration test invokes every command on every OS via stub server ([c5fb558](https://github.com/browserless/browserless-cli/commit/c5fb5581bc4255b5b118e13cc543d4a115e5ebd5))
95
- * **disclaimer:** include privacy-policy link in liability disclaimer text ([3be0c1c](https://github.com/browserless/browserless-cli/commit/3be0c1cf5c0c4c3d43b2ef70e37bbe2c533bb005))
96
- * **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it ([645a2f0](https://github.com/browserless/browserless-cli/commit/645a2f0b2466b8da172e226b39a7188052124804))
97
- * **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup ([5374585](https://github.com/browserless/browserless-cli/commit/5374585462a9652b818ffabf4281a412a34df65c))
98
- * **sources:** surface broken custom-browser registrations in sources list ([fb06afe](https://github.com/browserless/browserless-cli/commit/fb06afe7ee3982404fada378904f7ddd9fb0ee4a))
108
+ * --region sfo|lon|ams shortcut + region config key
109
+ * Add the Browserless CLI for authenticated profile management
110
+ * **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt
111
+ * **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions
112
+ * **ci:** cli-smoke integration test invokes every command on every OS via stub server
113
+ * **disclaimer:** include privacy-policy link in liability disclaimer text
114
+ * **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it
115
+ * **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup
116
+ * **sources:** surface broken custom-browser registrations in sources list
99
117
 
100
118
 
101
119
  ### Bug Fixes
102
120
 
103
- * address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests) ([d3f5e7e](https://github.com/browserless/browserless-cli/commit/d3f5e7e2ed59e8482453cf562c803a6e6850f354))
104
- * **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/) ([710b011](https://github.com/browserless/browserless-cli/commit/710b01104cf7185ae90ba53cfbb629e2e1a6a177))
105
- * **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery ([55df91b](https://github.com/browserless/browserless-cli/commit/55df91b3a5b209754cd5a04b5efcaee6254367e5))
106
- * **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium ([f98c8c2](https://github.com/browserless/browserless-cli/commit/f98c8c2737958c51051dd02e60ed81fac5e198f9))
107
- * **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins ([8157a4d](https://github.com/browserless/browserless-cli/commit/8157a4df2618c3aa370fed431f66b4df256ad71e))
108
- * **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge ([393c813](https://github.com/browserless/browserless-cli/commit/393c8134bb9e30f0d940979dc89683e4f335de66))
109
- * **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed ([2de326e](https://github.com/browserless/browserless-cli/commit/2de326ed30813e07cf9022b13162e11508a0b80e))
110
- * **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself ([a968526](https://github.com/browserless/browserless-cli/commit/a96852623552246a8bc95009bb1c5b297dd18533))
111
- * **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture ([53644e9](https://github.com/browserless/browserless-cli/commit/53644e91ff477fce02bf6a21b28c3ebfb5965ee9))
112
- * **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI ([7d2e9b4](https://github.com/browserless/browserless-cli/commit/7d2e9b41adf609d1ff4af02675399cce80f96486))
113
- * **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI ([0755b50](https://github.com/browserless/browserless-cli/commit/0755b50b54445cfa84d6ede21f227d815377dce0))
114
- * **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows) ([ab8faae](https://github.com/browserless/browserless-cli/commit/ab8faaecfc35ffc8a9f61363680c327221956088))
115
- * **capture:** surface browser stderr in CDP-timeout error for diagnostics ([de047c7](https://github.com/browserless/browserless-cli/commit/de047c776588368c4e458a7789e0ff1ce7c9c300))
116
- * **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T ([8d30d38](https://github.com/browserless/browserless-cli/commit/8d30d38d5aff8a9a3ea27f8ecb46d58cb9769dfd))
117
- * **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount ([ed28db0](https://github.com/browserless/browserless-cli/commit/ed28db0d8bf994c0ead7110645521468cd92e3ef))
118
- * **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI ([87a0a9b](https://github.com/browserless/browserless-cli/commit/87a0a9b59ac951e625c4915209b5047285d6974e))
119
- * **ci:** apt options go after apt-get, not after sudo ([bdcc69e](https://github.com/browserless/browserless-cli/commit/bdcc69e07566a2ed06e143cdbb276557eb9ecec0))
120
- * **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source ([d59e289](https://github.com/browserless/browserless-cli/commit/d59e2897957528a06a6f4c1c24e508bc85420b5a))
121
- * **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it) ([0431920](https://github.com/browserless/browserless-cli/commit/0431920fb5747b3161352803bb0c4d1073f62042))
122
- * **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT ([61f976d](https://github.com/browserless/browserless-cli/commit/61f976df8d2d511d7a9b7d5d88568a05fd2e3bc9))
123
- * **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot) ([dd9d146](https://github.com/browserless/browserless-cli/commit/dd9d1467f2f39d5bab6caae96e7cb1619fb8fffd))
124
- * **ci:** restore apt-get update before gnome-keyring install — cached lists go stale ([a0c3845](https://github.com/browserless/browserless-cli/commit/a0c3845b6bbf014bbacb1558c08767620212718a))
125
- * **ci:** same Chrome seed fix for linux smoke ([7955e33](https://github.com/browserless/browserless-cli/commit/7955e33bb8fb85a54e792748f5b0659490688e88))
126
- * **ci:** seed Chrome user-data-dir directly instead of racing first-run boot ([fbdd633](https://github.com/browserless/browserless-cli/commit/fbdd633ce39e8123933a34735e1354f350521d6b))
127
- * **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces ([d416399](https://github.com/browserless/browserless-cli/commit/d416399a132280eb635ed2699b270e418027a686))
128
- * **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture) ([baa5433](https://github.com/browserless/browserless-cli/commit/baa54339f8e246bda210d6bea351114e77fc13d5))
129
- * **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting ([efcdd7d](https://github.com/browserless/browserless-cli/commit/efcdd7d63d90ad56d82ae9a5df4201be8a1f7490))
130
- * **commands:** add missing region?: string to upload/refresh Options interfaces ([dbd984e](https://github.com/browserless/browserless-cli/commit/dbd984e510d8ed18b0b331dd55dcf3cb079950f1))
131
- * **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir ([eb00c03](https://github.com/browserless/browserless-cli/commit/eb00c035a6e09e5ef2afcef694583c3fb1f24285))
132
- * **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains ([94ac479](https://github.com/browserless/browserless-cli/commit/94ac479497d0f9e5cb87a77af6b2aebbc2c65845))
133
- * **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames) ([c122331](https://github.com/browserless/browserless-cli/commit/c12233125e32ab8e6dd14876fceddbb8c40c2cad))
134
- * **lock:** Windows lockfile is an empty marker — presence = locked (no PID) ([0093d88](https://github.com/browserless/browserless-cli/commit/0093d88b108a481419acfb1d763374c8b1b6d562))
135
- * **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs ([c1ac1a5](https://github.com/browserless/browserless-cli/commit/c1ac1a54d91abb5019e9fc24b8a1fe3636353bdb))
136
- * **sh:** drop duplicate Linux pattern in verify-chrome.sh case ([ea2ded6](https://github.com/browserless/browserless-cli/commit/ea2ded65dc24cc81c840fcec827d47bf7f43f820))
137
- * **sources:** validate --path and --user-data-dir at sources add time ([9909bbb](https://github.com/browserless/browserless-cli/commit/9909bbb7bb41cb6dbdb0c94db733fd7fd38a735a))
138
- * **test:** bound chrome.exe warmup to 30s so it can't hang CI ([899b3b6](https://github.com/browserless/browserless-cli/commit/899b3b61460916f9f745253e464505f66fa12db0))
139
- * **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation) ([1a43a46](https://github.com/browserless/browserless-cli/commit/1a43a46659ce3f34ce97152919615a97bd452ec4))
140
- * **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals) ([c42dffd](https://github.com/browserless/browserless-cli/commit/c42dffd1f4f5e328632e7c5e6f9dc61f58ce26a8))
141
- * **trim-state:** don't treat unparseable origins as protected by --keep-domain ([9eeb46f](https://github.com/browserless/browserless-cli/commit/9eeb46fbbb7a5550d321df687cf8fda9da1eca04))
121
+ * address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests)
122
+ * **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/)
123
+ * **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery
124
+ * **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium
125
+ * **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins
126
+ * **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge
127
+ * **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed
128
+ * **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself
129
+ * **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture
130
+ * **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI
131
+ * **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI
132
+ * **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows)
133
+ * **capture:** surface browser stderr in CDP-timeout error for diagnostics
134
+ * **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T
135
+ * **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount
136
+ * **capture:** unref child + close stdio after kill — unblock Node exit when browser doesn't reap fast; bypass .cmd shim on Windows when detached so CTRL_BREAK_EVENT targets the CLI
137
+ * **ci:** apt options go after apt-get, not after sudo
138
+ * **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source
139
+ * **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it)
140
+ * **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT
141
+ * **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot)
142
+ * **ci:** restore apt-get update before gnome-keyring install — cached lists go stale
143
+ * **ci:** same Chrome seed fix for linux smoke
144
+ * **ci:** seed Chrome user-data-dir directly instead of racing first-run boot
145
+ * **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces
146
+ * **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture)
147
+ * **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting
148
+ * **commands:** add missing region?: string to upload/refresh Options interfaces
149
+ * **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir
150
+ * **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains
151
+ * **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames)
152
+ * **lock:** Windows lockfile is an empty marker — presence = locked (no PID)
153
+ * **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs
154
+ * **sh:** drop duplicate Linux pattern in verify-chrome.sh case
155
+ * **sources:** validate --path and --user-data-dir at sources add time
156
+ * **test:** bound chrome.exe warmup to 30s so it can't hang CI
157
+ * **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation)
158
+ * **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals)
159
+ * **trim-state:** don't treat unparseable origins as protected by --keep-domain
142
160
 
143
161
 
144
162
  ### Reverts
145
163
 
146
- * drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario ([caf828b](https://github.com/browserless/browserless-cli/commit/caf828b5020e36dbd2b4232a94bb7e7d5cccee9a))
164
+ * drop Windows orphan-cleanup hacks — Chrome utility processes self-exit within ~30s; not worth the test/CLI complexity for an external-force-kill-only scenario
147
165
 
148
166
  ## Changelog
149
167
 
package/README.md CHANGED
@@ -52,12 +52,15 @@
52
52
  - [Privacy & Domain Filtering](#-privacy--domain-filtering)
53
53
  - [Managing Artifact Size](#-managing-artifact-size)
54
54
  - [Custom Chromium Browsers](#-custom-chromium-browsers)
55
+ - [Hosted Agent](#-hosted-agent)
55
56
  - [Shared Flags](#-shared-flags)
56
57
  - [Configuration](#-configuration)
57
58
  - [Environment Variables](#-environment-variables)
58
59
  - [Usage Analytics](#-usage-analytics)
59
60
  - [Exit Codes](#-exit-codes)
60
61
  - [Why use the CLI?](#-why-use-the-cli)
62
+ - [Contributing](#-contributing)
63
+ - [Security](#-security)
61
64
  - [Licensing](#-licensing)
62
65
 
63
66
  ## 🚀 Get Started in Seconds!
@@ -73,10 +76,12 @@ Requires Node.js ≥ 24.
73
76
  ### Step 2: Log in
74
77
 
75
78
  ```bash
76
- # Pass your API token as a positional arg, or pipe it via stdin to keep
77
- # it out of shell history.
78
- browserless auth login <your-token>
79
+ # Recommended: pipe the token via stdin (or paste it at the prompt)
79
80
  echo $TOKEN | browserless auth login
81
+
82
+ # Also works, but a token passed as an argument is visible to other local
83
+ # users in the process list and lands in your shell history
84
+ browserless auth login <your-token>
80
85
  ```
81
86
 
82
87
  Tokens are stored in your **OS keychain** when available (Keychain on
@@ -286,16 +291,52 @@ If the binary or `user-data-dir` later goes missing, `profile sources
286
291
  list` flags the entry under "Registered custom browsers with missing
287
292
  paths" so you can clean it up with `profile sources rm`.
288
293
 
294
+ ## 🤖 Hosted Agent
295
+
296
+ `browserless agent` opens an interactive chat with the Browserless hosted
297
+ agent. The model runs on Browserless and drives a cloud browser for you; the
298
+ terminal shows its replies and each browser action as it happens.
299
+
300
+ ```bash
301
+ # Start a chat, optionally with the first task
302
+ browserless agent "find the opening hours of the Louvre"
303
+
304
+ # Scripts: stdout carries only the final result as JSON (progress goes to stderr)
305
+ browserless agent "find the opening hours of the Louvre" --json
306
+
307
+ # Save a signed-in local browser once, then use its cloud profile
308
+ browserless profile upload --browser chrome --profile Personal --name github
309
+ browserless agent --cloud-profile github "star browserless/browserless on GitHub"
310
+ ```
311
+
312
+ - Follow-up messages continue the same session. Ctrl-C stops the current
313
+ turn; press it again (or send an empty line) to exit.
314
+ - When the agent pauses for input — for example a one-time code — the CLI
315
+ prompts you for it.
316
+ - For signed-in tasks, upload a signed-in browser with
317
+ `browserless profile upload --name <name> --browser <browser> --profile <local-profile>` and pass that cloud name with
318
+ `browserless agent --cloud-profile <name>`. The CLI validates the name and
319
+ checks that it exists before starting the agent. Run `browserless profile list`
320
+ to see your cloud profiles. A login-looking first message without the flag
321
+ prints a tip instead of asking for credentials. The agent is instructed never
322
+ to ask for passwords or other secrets and to stop when sign-in is needed.
323
+ If the saved profile is no longer signed in, update it with
324
+ `browserless profile refresh --name <name>`.
325
+ - Prompts you type are kept in `~/.browserless/agent_history` (mode 0600,
326
+ last 200) so the up arrow recalls them across sessions; one-time codes
327
+ are never written there. `--no-history` turns the
328
+ file off.
329
+
289
330
  ## ⚙️ Shared Flags
290
331
 
291
332
  Every command that hits the cloud API accepts:
292
333
 
293
- | Flag | Effect |
294
- | ----------------- | --------------------------------------------------------------- |
295
- | `--token <tok>` | Override token resolution (flag > env > keychain > config file) |
296
- | `--server <url>` | Override the configured server URL |
297
- | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
298
- | `--json` | Emit the server response as JSON (script-friendly) |
334
+ | Flag | Effect |
335
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
336
+ | `--token <tok>` | Override token resolution (flag > env > keychain > config file). Visible in the process list; prefer `BROWSERLESS_TOKEN` for scripts |
337
+ | `--server <url>` | Override the configured server URL |
338
+ | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
339
+ | `--json` | Emit the server response as JSON (script-friendly) |
299
340
 
300
341
  Capture commands (`upload`, `refresh`, `inspect`) also accept:
301
342
 
@@ -372,6 +413,13 @@ authenticated with your token and targeted a Browserless cloud region:
372
413
  - the production region (`sfo` / `lon` / `ams`) — never a raw server URL
373
414
  - a random per-install id (`cli_device_id`), stored in
374
415
  `~/.browserless/telemetry-device-id`
416
+ - for `profile upload` / `profile refresh`, a few setup-progress events
417
+ (`Profile Setup Method Selected`, `Profile Setup Started`,
418
+ `Profile Setup Ready`, `Profile Save Submitted`, and
419
+ `Profile Setup Failed` with a short reason code) that share a random
420
+ `attempt_id`. Pass `--attempt-id <UUID>` to keep your own id across
421
+ retries; the same id is sent to the Browserless server with the upload as
422
+ the `x-browserless-attempt-id` header
375
423
 
376
424
  **What's never in the analytics data:** your API token, profile names,
377
425
  captured URLs or domains, cookies, or any captured auth state. The token is
@@ -422,16 +470,30 @@ touched; sensitive domains never leave your machine.
422
470
  Once uploaded, any Browserless cloud session can attach the profile
423
471
  via `?profile=<name>` and start _already authenticated_.
424
472
 
425
- ## 📜 Licensing
473
+ ## 🤝 Contributing
474
+
475
+ Pull requests are welcome. [AGENTS.md](AGENTS.md) is the contributor guide —
476
+ architecture, local setup, testing patterns and conventions (coding agents
477
+ read the same file). Before opening a PR:
478
+
479
+ ```bash
480
+ npm run build && npm run lint && npm test
481
+ ```
482
+
483
+ PR titles follow [Conventional Commits](https://www.conventionalcommits.org/)
484
+ and become the changelog entry.
485
+
486
+ ## 🔒 Security
426
487
 
427
- Distributed as part of the Browserless platform. The `LICENSE` file
428
- ships in the package; see [browserless.io](https://browserless.io) for
429
- full terms.
488
+ Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md).
489
+ Don't open a public issue for a security problem.
490
+
491
+ ## 📜 Licensing
430
492
 
431
- If you're building a commercial application on Browserless, a
432
- [commercial license](https://www.browserless.io/contact) covers
433
- priority support, on-premise deployment, source modification, and
434
- the admin UI in addition to keeping your software proprietary.
493
+ The Browserless CLI is open source under the [MIT License](LICENSE).
494
+ Using it with the hosted Browserless service is also covered by your
495
+ Browserless account terms and the
496
+ [privacy policy](https://www.browserless.io/privacy-policy).
435
497
 
436
498
  <div align="center">
437
499
 
@@ -1 +1 @@
1
- var p=Object.defineProperty;var c=(i,e)=>p(i,"name",{value:e,configurable:!0});import{EventEmitter as f}from"node:events";import m from"ws";import{ApiError as d,PreconditionError as w}from"../errors.js";const u=new Set([1e3,1001,1005]),g=c((i,e)=>{const r=i.replace(/^http/i,"ws").replace(/\/+$/,""),s=new URL(`${r}/chromium/cli`);return s.searchParams.set("token",e),s.toString()},"buildCliWsUrl");class $ extends f{static{c(this,"AgentClient")}ws=null;server;token;WebSocketImpl;constructor(e){super(),this.server=e.server,this.token=e.token,this.WebSocketImpl=e.WebSocketImpl??m}connect(){const e=g(this.server,this.token);return new Promise((r,s)=>{const n=new this.WebSocketImpl(e);let l=!1;const h=c(t=>{if(!l)if(l=!0,t){try{n.terminate()}catch{}s(t)}else this.ws=n,r()},"settle");n.once("open",()=>h()),n.once("unexpected-response",(t,a)=>{const o=a.statusCode??0;h(this.mapUpgradeError(o,a.statusMessage??""))}),n.on("error",t=>{if(!l){h(new d(`WebSocket connection failed: ${t.message}`,0,void 0,"websocket-failed"));return}this.emit("agent_error",{code:"ws-error",message:t.message,retryable:!1})}),n.on("message",t=>this.handleMessage(t)),n.on("close",(t,a)=>{const o=a?.toString("utf8")??"";if(!u.has(t)){this.emit("agent_error",{code:`ws-closed-${t}`,message:`WebSocket closed abnormally (code ${t}${o?`: ${o}`:""})`,retryable:!1});return}this.emit("close",{code:t,reason:o})})})}start(e){this.sendFrame({type:"start",prompt:e})}send(e){this.sendFrame({type:"send",prompt:e})}stop(){this.sendFrame({type:"stop"})}close(){this.ws&&this.ws.readyState===m.OPEN&&this.ws.close()}sendFrame(e){if(!this.ws||this.ws.readyState!==m.OPEN)throw new d("Cannot send a frame: WebSocket is not open.",0,void 0,"websocket-not-open");this.ws.send(JSON.stringify(e))}handleMessage(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}typeof r.type=="string"&&this.emit(r.type==="error"?"agent_error":r.type,r)}mapUpgradeError(e,r){const s=r?` \u2014 ${r}`:"";return e===401||e===403?new w(`Authentication failed (HTTP ${e}${s}). Check your token and server.`,"invalid-token"):new d(`Server rejected the agent connection (HTTP ${e}${s}).`,e)}}export{$ as AgentClient,g as buildCliWsUrl};
1
+ var p=Object.defineProperty;var c=(i,e)=>p(i,"name",{value:e,configurable:!0});import{EventEmitter as f}from"node:events";import h from"ws";import{ApiError as d,PreconditionError as w}from"../errors.js";import{terminalSafe as u}from"../utils/terminal.js";const S=new Set([1e3,1001,1005]),g=c((i,e)=>{const r=i.replace(/^http/i,"ws").replace(/\/+$/,""),s=new URL(`${r}/chromium/cli`);return s.searchParams.set("token",e),s.toString()},"buildCliWsUrl");class W extends f{static{c(this,"AgentClient")}ws=null;server;token;WebSocketImpl;constructor(e){super(),this.server=e.server,this.token=e.token,this.WebSocketImpl=e.WebSocketImpl??h}connect(){const e=g(this.server,this.token);return new Promise((r,s)=>{const n=new this.WebSocketImpl(e);let l=!1;const m=c(t=>{if(!l)if(l=!0,t){try{n.terminate()}catch{}s(t)}else this.ws=n,r()},"settle");n.once("open",()=>m()),n.once("unexpected-response",(t,a)=>{const o=a.statusCode??0;m(this.mapUpgradeError(o,a.statusMessage??""))}),n.on("error",t=>{if(!l){m(new d(`WebSocket connection failed: ${t.message}`,0,void 0,"websocket-failed"));return}this.emit("agent_error",{code:"ws-error",message:t.message,retryable:!1})}),n.on("message",t=>this.handleMessage(t)),n.on("close",(t,a)=>{const o=a?.toString("utf8")??"";if(!S.has(t)){this.emit("agent_error",{code:`ws-closed-${t}`,message:`WebSocket closed abnormally (code ${t}${o?`: ${o}`:""})`,retryable:!1});return}this.emit("close",{code:t,reason:o})})})}start(e){this.sendFrame({type:"start",prompt:e})}send(e){this.sendFrame({type:"send",prompt:e})}stop(){this.sendFrame({type:"stop"})}close(){this.ws&&this.ws.readyState===h.OPEN&&this.ws.close()}sendFrame(e){if(!this.ws||this.ws.readyState!==h.OPEN)throw new d("Cannot send a frame: WebSocket is not open.",0,void 0,"websocket-not-open");this.ws.send(JSON.stringify(e))}handleMessage(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}typeof r.type=="string"&&this.emit(r.type==="error"?"agent_error":r.type,r)}mapUpgradeError(e,r){const s=r?` \u2014 ${u(r)}`:"";return e===401||e===403?new w(`Authentication failed (HTTP ${e}${s}). Check your token and server.`,"invalid-token"):new d(`Server rejected the agent connection (HTTP ${e}${s}).`,e)}}export{W as AgentClient,g as buildCliWsUrl};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var c=(e,t)=>l(e,"name",{value:t,configurable:!0});import{ApiError as f}from"../errors.js";const $=3e4,w=c(e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?e.toLowerCase():void 0,"profileAttemptId"),p=c((e,t,a,r)=>{const s=e.endsWith("/")?e:`${e}/`,m=t.replace(/^\/+/,""),o=new URL(m,s);if(o.searchParams.set("token",a),r)for(const[u,h]of Object.entries(r))h!==void 0&&o.searchParams.set(u,String(h));return o},"buildUrl"),y=c((e,t,a)=>{if(!a)return`HTTP ${e} ${t}`;try{const s=JSON.parse(a);if(s?.message&&typeof s.message=="string")return s.message}catch{}const r=a.trim();return r.length>200?`HTTP ${e} ${t}: ${r.slice(0,200)}\u2026`:`HTTP ${e} ${t}: ${r}`},"messageFromBody"),T=c(async(e,t)=>{const a=p(e.server,t.path,e.token,t.query),r={method:t.method,redirect:"error"};let s;t.rawBody!==void 0?s=t.rawBody:t.body!==void 0&&(s=JSON.stringify(t.body)),s!==void 0&&(r.body=s,r.headers={"Content-Type":"application/json"});const m=w(t.attemptId);m&&(r.headers={...r.headers,"x-browserless-attempt-id":m});const o=t.timeoutMs??$,u=new AbortController,h=setTimeout(()=>u.abort(),o);r.signal=u.signal;let n;try{n=await fetch(a,r)}catch(i){throw i?.name==="AbortError"?new f(`Request to ${e.server}${t.path} timed out after ${o}ms`,0,void 0,"request-timeout"):new f(`Failed to reach ${e.server}: ${i?.message??i}`,0,void 0,"network-unreachable")}finally{clearTimeout(h)}let d;try{d=await n.text()}catch(i){throw i?.name==="AbortError"?new f(`Request to ${e.server}${t.path} timed out after ${o}ms`,0,void 0,"request-timeout"):new f(`Failed to read response from ${e.server}${t.path}: ${i?.message??i}`,0,void 0,"response-read-failed")}if(!n.ok)throw new f(y(n.status,n.statusText,d),n.status,d);if(!(n.status===204||!d))try{return JSON.parse(d)}catch{throw new f(`Server returned non-JSON response: ${d}`,n.status,d,"invalid-response")}},"apiFetch");export{T as apiFetch,w as profileAttemptId};
1
+ var p=Object.defineProperty;var u=(e,t)=>p(e,"name",{value:t,configurable:!0});import{ApiError as c}from"../errors.js";import{terminalSafe as i}from"../utils/terminal.js";const b=3e4,$=10*1024*1024,g=u(e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)?e.toLowerCase():void 0,"profileAttemptId"),T=u((e,t,d,r)=>{const n=e.endsWith("/")?e:`${e}/`,h=t.replace(/^\/+/,""),f=new URL(h,n);if(f.searchParams.set("token",d),r)for(const[m,l]of Object.entries(r))l!==void 0&&f.searchParams.set(m,String(l));return f},"buildUrl"),S=u((e,t,d)=>{if(!d)return`HTTP ${e} ${i(t)}`;try{const n=JSON.parse(d);if(n?.message&&typeof n.message=="string")return i(n.message)}catch{}const r=d.trim();return r.length>200?`HTTP ${e} ${i(t)}: ${i(r.slice(0,200))}\u2026`:`HTTP ${e} ${i(t)}: ${i(r)}`},"messageFromBody"),A=u(async(e,t)=>{const d=T(e.server,t.path,e.token,t.query),r={method:t.method,redirect:"error"};let n;t.rawBody!==void 0?n=t.rawBody:t.body!==void 0&&(n=JSON.stringify(t.body)),n!==void 0&&(r.body=n,r.headers={"Content-Type":"application/json"});const h=g(t.attemptId);h&&(r.headers={...r.headers,"x-browserless-attempt-id":h});const f=t.timeoutMs??b,m=new AbortController,l=setTimeout(()=>m.abort(),f);r.signal=m.signal;let s,a="";try{s=await fetch(d,r);const o=new TextDecoder;let w=0;if(s.body){for await(const y of s.body){if(w+=y.byteLength,w>$)throw m.abort(),new c(`Response exceeds the ${$}-byte decoded body limit`,0,void 0,"response-too-large");a+=o.decode(y,{stream:!0})}a+=o.decode()}}catch(o){throw o instanceof c?o:o?.name==="AbortError"?new c(`Request to ${e.server}${t.path} timed out after ${f}ms`,0,void 0,"request-timeout"):new c(s?`Failed to read response from ${e.server}${t.path}: ${o?.message??o}`:`Failed to reach ${e.server}: ${o?.message??o}`,0,void 0,s?"response-read-failed":"network-unreachable")}finally{clearTimeout(l)}if(!s.ok)throw new c(S(s.status,s.statusText,a),s.status,a);if(!(s.status===204||!a))try{return JSON.parse(a)}catch{throw new c(`Server returned non-JSON response: ${i(a)}`,s.status,a,"invalid-response")}},"apiFetch");export{A as apiFetch,g as profileAttemptId};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var t=(o,e)=>f(o,"name",{value:e,configurable:!0});import{apiFetch as n}from"./client.js";const l=t(async(o,e={})=>n(o,{method:"GET",path:"/profiles",query:{...e.limit!==void 0?{limit:e.limit}:{},...e.offset!==void 0?{offset:e.offset}:{}}}),"listProfiles"),r=t(async(o,e)=>n(o,{method:"GET",path:`/profile/${encodeURIComponent(e)}`}),"getProfile"),c=t(async(o,e,i)=>n(o,{method:"PUT",path:`/profile/${encodeURIComponent(e)}`,body:{name:i}}),"renameProfile"),m=t(async(o,e)=>n(o,{method:"DELETE",path:`/profile/${encodeURIComponent(e)}`}),"deleteProfile");export{m as deleteProfile,r as getProfile,l as listProfiles,c as renameProfile};
1
+ var n=Object.defineProperty;var t=(o,e)=>n(o,"name",{value:e,configurable:!0});import{apiFetch as i}from"./client.js";import{UsageError as f}from"../errors.js";import{terminalSafe as s}from"../utils/terminal.js";const a=t(o=>{if(!o||o.length>255||!/^[^\s/?#]+$/.test(o)||o==="."||o==="..")throw new f(`"${s(o)}" is not a valid cloud profile name: use 1-255 characters with no whitespace, "/", "?" or "#".`,"invalid-cloud-profile-name");return o},"assertCloudProfileName"),m=t(async(o,e={})=>i(o,{method:"GET",path:"/profiles",query:{...e.limit!==void 0?{limit:e.limit}:{},...e.offset!==void 0?{offset:e.offset}:{}}}),"listProfiles"),r=t(o=>{if(o==="."||o==="..")throw new f(`"${o}" is not a valid profile name.`);return`/profile/${encodeURIComponent(o)}`},"profilePath"),u=t(async(o,e)=>i(o,{method:"GET",path:r(e)}),"getProfile"),P=t(async(o,e,l)=>i(o,{method:"PUT",path:r(e),body:{name:l}}),"renameProfile"),w=t(async(o,e)=>i(o,{method:"DELETE",path:r(e)}),"deleteProfile");export{a as assertCloudProfileName,w as deleteProfile,u as getProfile,m as listProfiles,P as renameProfile};
@@ -1,4 +1,4 @@
1
- var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as n,stdout as s}from"node:process";import{readConfig as m,updateConfig as c}from"../config/store.js";import{DEFAULT_TERMS_TTL_DAYS as f}from"../config/schema.js";import{PreconditionError as p}from"../errors.js";const w=`
1
+ var d=Object.defineProperty;var o=(t,e)=>d(t,"name",{value:e,configurable:!0});import u from"node:readline/promises";import{stdin as s,stdout as n}from"node:process";import{readConfig as m,updateConfig as c}from"../config/store.js";import{DEFAULT_TERMS_TTL_DAYS as f}from"../config/schema.js";import{PreconditionError as l}from"../errors.js";const h=`
2
2
  Heads up \u2014 uploading a profile sends authentication state to Browserless:
3
3
 
4
4
  \u2022 Cookies, localStorage and IndexedDB from the browser profile you select
@@ -7,10 +7,14 @@ Heads up \u2014 uploading a profile sends authentication state to Browserless:
7
7
  \u2022 Only upload profiles you have authority to share. Cookies for banking,
8
8
  healthcare, employer-SSO or other sensitive sites should be added to the
9
9
  domain exclusion list (\`browserless profile exclude add <domain>\`).
10
+ \u2022 Each cloud profile keeps the exclusion list it was captured with, and a
11
+ later \`profile refresh\` reuses it. To apply a domain you excluded
12
+ since, refresh with \`--exclude-domain <domain>\`: that replaces the
13
+ stored list with this machine's list plus the domain.
10
14
  \u2022 Your local browser profile is never modified \u2014 the CLI runs against a
11
15
  temporary copy and cleans it up after capture.
12
16
 
13
17
  By continuing you confirm you understand the above and accept responsibility
14
18
  for the contents of the upload. Privacy policy: https://www.browserless.io/privacy-policy
15
- `,l="I accept",y=o(()=>!!process.env.CI,"isCi"),h=o((t,e)=>{if(!t||e<=0)return!1;const r=Date.parse(t);if(!Number.isFinite(r))return!1;const a=Date.now()-r;return a>=0&&a<e*24*60*60*1e3},"isWithinTtl"),S=o(async t=>{s.write(t);const e=u.createInterface({input:n,output:s});try{return await e.question(`
16
- Type "${l}" to continue: `)}finally{e.close()}},"defaultPrompt"),R=o(async(t,e={})=>{const r=await m(),a=t.ttlDaysOverride??r.terms_ttl_days??f;if(h(r.accepted_terms_at,a))return;if(t.acceptViaFlag||process.env.BROWSERLESS_ACCEPT_TERMS==="1"){await c(i=>{i.accepted_terms_at=new Date().toISOString()});return}if(!(e.isInteractive??(n.isTTY&&!y())))throw new p("Liability disclaimer must be acknowledged before uploading. Re-run with `--accept-terms` or set BROWSERLESS_ACCEPT_TERMS=1 in non-interactive environments.","terms-not-accepted");if((await(e.prompt??S)(w)).trim()!==l)throw new p("Disclaimer not accepted \u2014 aborting.","terms-not-accepted");await c(i=>{i.accepted_terms_at=new Date().toISOString()})},"ensureTermsAccepted");export{w as DISCLAIMER_TEXT,R as ensureTermsAccepted,y as isCi};
19
+ `,p="I accept",w=o(()=>!!process.env.CI,"isCi"),y=o((t,e)=>{if(!t||e<=0)return!1;const r=Date.parse(t);if(!Number.isFinite(r))return!1;const i=Date.now()-r;return i>=0&&i<e*24*60*60*1e3},"isWithinTtl"),S=o(async t=>{n.write(t);const e=u.createInterface({input:s,output:n});try{return await e.question(`
20
+ Type "${p}" to continue: `)}finally{e.close()}},"defaultPrompt"),x=o(async(t,e={})=>{const r=await m(),i=t.ttlDaysOverride??r.terms_ttl_days??f;if(y(r.accepted_terms_at,i))return;if(t.acceptViaFlag||process.env.BROWSERLESS_ACCEPT_TERMS==="1"){await c(a=>{a.accepted_terms_at=new Date().toISOString()});return}if(!(e.isInteractive??(s.isTTY&&!w())))throw new l("Liability disclaimer must be acknowledged before uploading. Re-run with `--accept-terms` or set BROWSERLESS_ACCEPT_TERMS=1 in non-interactive environments.","terms-not-accepted");if((await(e.prompt??S)(h)).trim()!==p)throw new l("Disclaimer not accepted \u2014 aborting.","terms-not-accepted");await c(a=>{a.accepted_terms_at=new Date().toISOString()})},"ensureTermsAccepted");export{h as DISCLAIMER_TEXT,x as ensureTermsAccepted,w as isCi};
@@ -1,5 +1,5 @@
1
- var N=Object.defineProperty;var n=(e,r)=>N(e,"name",{value:r,configurable:!0});import h from"node:fs/promises";import m from"node:path";import{spawn as g}from"node:child_process";import{BUILT_IN_BROWSERS as y}from"./registry.js";import{readCustomBrowsers as p}from"./custom.js";import{UsageError as w}from"../errors.js";import{pathExists as c}from"../utils/fs.js";const b=n(e=>new Promise(r=>{const t=g("which",[e],{stdio:["ignore","pipe","ignore"]});let s="";t.stdout?.on("data",o=>{s+=o.toString()}),t.on("error",()=>r(null)),t.on("exit",o=>r(o===0&&s.trim()?s.trim():null))}),"whichOnPath"),k=n(async e=>{for(const r of e)if(await c(r))return r;return null},"firstExistingPath"),C=n(async e=>{const r=await k(e);if(r)return r;if(process.platform==="linux")for(const t of e){const s=m.basename(t);if(!s)continue;const o=await b(s);if(o)return o}return null},"firstExistingBinary"),B=n(async e=>{const r=m.join(e,"Local State");try{const t=await h.readFile(r,"utf-8"),o=JSON.parse(t)?.profile?.info_cache??{};return Object.fromEntries(Object.entries(o).map(([i,l])=>[i,l?.name??i]))}catch{return{}}},"readProfileDisplayNames"),$=n(async e=>await c(m.join(e,"Preferences"))||await c(m.join(e,"Cookies"))||await c(m.join(e,"Network","Cookies")),"looksLikeProfile"),P=n(async(e,r,t,s)=>{const o=await B(e);let i;try{i=await h.readdir(e,{withFileTypes:!0})}catch{return[]}const l=i.filter(a=>a.isDirectory()).filter(a=>a.name==="Default"||/^Profile \d+$/.test(a.name));return(await Promise.all(l.map(async a=>{const f=m.join(e,a.name);return await $(f)?{browserKey:t,browserDisplayName:s,profileDirName:a.name,profileDisplayName:o[a.name]??a.name,userDataDir:e,profilePath:f,binaryPath:r}:null}))).filter(a=>a!==null)},"profilesUnder"),L=n(async e=>{const r=e.userDataDirByPlatform[process.platform],t=e.binaryPathByPlatform[process.platform]??[];if(!r||t.length===0)return[];const s=Array.isArray(r)?r:[r],o=await C(t);if(!o)return[];for(const i of s){if(!await c(i))continue;const l=await P(i,o,e.key,e.displayName);if(l.length>0)return l}return[]},"discoverBuiltIn"),x=n(async e=>await c(e.userDataDir)?await c(e.binaryPath)?P(e.userDataDir,e.binaryPath,e.name,e.name):[]:[],"discoverCustom"),j=n(async()=>{const[e,r]=await Promise.all([Promise.all(y.map(L)),p().then(t=>Promise.all(t.map(x)))]);return[...e.flat(),...r.flat()]},"discoverProfiles"),T=n(async()=>{const e=await p();return(await Promise.all(e.map(async t=>{const[s,o]=await Promise.all([c(t.binaryPath),c(t.userDataDir)]);return s&&o?null:{name:t.name,binaryPath:t.binaryPath,userDataDir:t.userDataDir,missingBinary:!s,missingUserDataDir:!o}}))).filter(t=>t!==null)},"findBrokenCustomSources"),D=n((e,r)=>{const t=e.trim().toLowerCase();return r.browserKey.toLowerCase()===t||r.browserDisplayName.toLowerCase()===t},"matchesBrowser"),E=n((e,r)=>{const t=e.trim().toLowerCase();return r.profileDirName.toLowerCase()===t||r.profileDisplayName.toLowerCase()===t},"matchesProfile"),O=n((e,r,t,s)=>{const o=e.trim().toLowerCase();if(!t.some(a=>a.key.toLowerCase()===o||a.displayName.toLowerCase()===o))throw new w(`Unknown browser "${e}". Run \`browserless profile sources list\` to see detected browsers, or register a custom one with \`profile sources add\`.`,"unknown-browser");const l=s.filter(a=>D(e,a)&&E(r,a));if(l.length===1)return l[0];if(l.length===0){const a=s.filter(u=>D(e,u));if(a.length===0)throw new w(`Browser "${e}" is registered but has no detected profiles on this machine.`,"browser-has-no-profiles");const f=a.map(u=>` - ${u.profileDisplayName} (${u.profileDirName})`).join(`
2
- `);throw new w(`No profile named "${r}" under ${e}. Available profiles:
3
- ${f}`,"local-profile-not-found")}const d=l.map(a=>` - ${a.profileDisplayName} (dir: ${a.profileDirName}) under ${a.browserDisplayName}`).join(`
4
- `);throw new w(`Profile "${r}" matches multiple entries \u2014 disambiguate by passing the directory name to --profile:
5
- ${d}`,"local-profile-ambiguous")},"resolveProfileFromCandidates"),J=n(async(e,r)=>{const t=await p(),s=[...y.map(i=>({key:i.key,displayName:i.displayName})),...t.map(i=>({key:i.name,displayName:i.name}))],o=await j();return O(e,r,s,o)},"resolveProfile");export{j as discoverProfiles,T as findBrokenCustomSources,J as resolveProfile,O as resolveProfileFromCandidates,b as whichOnPath};
1
+ var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import y from"node:fs/promises";import f from"node:path";import{spawn as N}from"node:child_process";import{BUILT_IN_BROWSERS as P}from"./registry.js";import{readCustomBrowsers as d}from"./custom.js";import{PreconditionError as C,UsageError as p}from"../errors.js";import{pathExists as m}from"../utils/fs.js";import{terminalSafe as c}from"../utils/terminal.js";const k=n(e=>new Promise(r=>{const t=N("which",[e],{stdio:["ignore","pipe","ignore"]});let i="";t.stdout?.on("data",o=>{i+=o.toString()}),t.on("error",()=>r(null)),t.on("exit",o=>r(o===0&&i.trim()?i.trim():null))}),"whichOnPath"),$=n(async e=>{for(const r of e)if(await m(r))return r;return null},"firstExistingPath"),B=n(async e=>{const r=await $(e);if(r)return r;if(process.platform==="linux")for(const t of e){const i=f.basename(t);if(!i)continue;const o=await k(i);if(o)return o}return null},"firstExistingBinary"),L=n(async e=>{const r=f.join(e,"Local State");try{const t=await y.readFile(r,"utf-8"),o=JSON.parse(t)?.profile?.info_cache??{};return Object.fromEntries(Object.entries(o).map(([s,l])=>[s,l?.name??s]))}catch{return{}}},"readProfileDisplayNames"),x=n(async e=>await m(f.join(e,"Preferences"))||await m(f.join(e,"Cookies"))||await m(f.join(e,"Network","Cookies")),"looksLikeProfile"),D=n(async(e,r,t,i)=>{const o=await L(e);let s;try{s=await y.readdir(e,{withFileTypes:!0})}catch{return[]}const l=s.filter(a=>a.isDirectory()).filter(a=>a.name==="Default"||/^Profile \d+$/.test(a.name));return(await Promise.all(l.map(async a=>{const u=f.join(e,a.name);return await x(u)?{browserKey:t,browserDisplayName:i,profileDirName:a.name,profileDisplayName:o[a.name]??a.name,userDataDir:e,profilePath:u,binaryPath:r}:null}))).filter(a=>a!==null)},"profilesUnder"),j=n(async e=>{const r=e.userDataDirByPlatform[process.platform],t=e.binaryPathByPlatform[process.platform]??[];if(!r||t.length===0)return[];const i=Array.isArray(r)?r:[r],o=await B(t);if(!o)return[];for(const s of i){if(!await m(s))continue;const l=await D(s,o,e.key,e.displayName);if(l.length>0)return l}return[]},"discoverBuiltIn"),v=n(async e=>{if(!f.isAbsolute(e.binaryPath)||!f.isAbsolute(e.userDataDir))throw new C(`Custom browser "${e.name}" has relative paths. Remove it with \`profile sources rm <name>\` and re-register it with \`profile sources add\` from its original directory.`,"invalid-custom-browsers-file");return await m(e.userDataDir)?await m(e.binaryPath)?D(e.userDataDir,e.binaryPath,e.name,e.name):[]:[]},"discoverCustom"),E=n(async()=>{const[e,r]=await Promise.all([Promise.all(P.map(j)),d().then(t=>Promise.all(t.map(v)))]);return[...e.flat(),...r.flat()]},"discoverProfiles"),q=n(async()=>{const e=await d();return(await Promise.all(e.map(async t=>{const[i,o]=await Promise.all([m(t.binaryPath),m(t.userDataDir)]);return i&&o?null:{name:t.name,binaryPath:t.binaryPath,userDataDir:t.userDataDir,missingBinary:!i,missingUserDataDir:!o}}))).filter(t=>t!==null)},"findBrokenCustomSources"),b=n((e,r)=>{const t=e.trim().toLowerCase();return r.browserKey.toLowerCase()===t||r.browserDisplayName.toLowerCase()===t},"matchesBrowser"),S=n((e,r)=>{const t=e.trim().toLowerCase();return r.profileDirName.toLowerCase()===t||r.profileDisplayName.toLowerCase()===t},"matchesProfile"),O=n((e,r,t,i)=>{const o=e.trim().toLowerCase();if(!t.some(a=>a.key.toLowerCase()===o||a.displayName.toLowerCase()===o))throw new p(`Unknown browser "${c(e)}". Run \`browserless profile sources list\` to see detected browsers, or register a custom one with \`profile sources add\`.`,"unknown-browser");const l=i.filter(a=>b(e,a)&&S(r,a));if(l.length===1)return l[0];if(l.length===0){const a=i.filter(w=>b(e,w));if(a.length===0)throw new p(`Browser "${c(e)}" is registered but has no detected profiles on this machine.`,"browser-has-no-profiles");const u=a.map(w=>` - ${c(w.profileDisplayName)} (${c(w.profileDirName)})`).join(`
2
+ `);throw new p(`No profile named "${c(r)}" under ${c(e)}. Available profiles:
3
+ ${u}`,"local-profile-not-found")}const h=l.map(a=>` - ${c(a.profileDisplayName)} (dir: ${c(a.profileDirName)}) under ${c(a.browserDisplayName)}`).join(`
4
+ `);throw new p(`Profile "${c(r)}" matches multiple entries \u2014 disambiguate by passing the directory name to --profile:
5
+ ${h}`,"local-profile-ambiguous")},"resolveProfileFromCandidates"),z=n(async(e,r)=>{const t=await d(),i=[...P.map(s=>({key:s.key,displayName:s.displayName})),...t.map(s=>({key:s.name,displayName:s.name}))],o=await E();return O(e,r,i,o)},"resolveProfile");export{E as discoverProfiles,q as findBrokenCustomSources,z as resolveProfile,O as resolveProfileFromCandidates,k as whichOnPath};
@@ -0,0 +1 @@
1
+ var C=Object.defineProperty;var o=(f,c)=>C(f,"name",{value:c,configurable:!0});const l="CDP pipe closed",D=o((f,c)=>{let P=1,i=null;const a=new Map,d=new Map,w=new Set;let m=[];const $=o((r,e)=>`${r??""}\0${e}`,"key"),g=o(r=>{if(!i){i=r;for(const{reject:e}of a.values())e(r);a.clear();for(const e of w)e(r);w.clear(),d.clear()}},"fail"),S=o(r=>{let e;try{e=JSON.parse(r)}catch{return}if(typeof e?.id=="number"){const n=a.get(e.id);if(!n)return;a.delete(e.id),e.error?n.reject(new Error(`${n.method}: ${e.error.message??"protocol error"}`)):n.resolve(e.result??{});return}if(typeof e?.method=="string"){const n=d.get($(e.sessionId,e.method));for(const t of[...n??[]])t(e.params)}},"dispatch");c.on("data",r=>{let e=0,n=r.indexOf(0);for(;n!==-1;){m.push(r.subarray(e,n));const t=Buffer.concat(m).toString("utf8");m=[],S(t),e=n+1,n=r.indexOf(0,e)}e<r.length&&m.push(r.subarray(e))}),c.on("end",()=>g(new Error(l))),c.on("close",()=>g(new Error(l))),c.on("error",r=>g(new Error(`${l}: ${r.message}`))),f.on("error",r=>g(new Error(`${l}: ${r.message}`)));const h=o((r,e={},n)=>{if(i)return Promise.reject(i);const t=P++;return new Promise((s,p)=>{a.set(t,{method:r,resolve:s,reject:p});const O=n?{id:t,method:r,params:e,sessionId:n}:{id:t,method:r,params:e};f.write(`${JSON.stringify(O)}\0`,u=>{!u||!a.has(t)||(a.delete(t),p(new Error(`${l}: ${u.message}`)))})})},"send"),y=o((r,e,n)=>{if(i)return()=>{};const t=$(r,e),s=d.get(t)??new Set;return s.add(n),d.set(t,s),()=>{s.delete(n),s.size===0&&d.get(t)===s&&d.delete(t)}},"on"),x=o((r,e)=>new Promise((n,t)=>{if(i){t(i);return}w.add(t);const s=y(r,e,p=>{s(),w.delete(t),n(p)})}),"once"),E=o(r=>({send:o((e,n)=>h(e,n,r),"send"),on:o((e,n)=>y(r,e,n),"on"),once:o(e=>x(r,e),"once")}),"sessionFor");return{...E(void 0),session:o(r=>E(r),"session"),close:o(()=>{g(new Error(l)),f.destroy(),c.destroy()},"close")}},"connectCdpPipe");export{l as CDP_PIPE_CLOSED,D as connectCdpPipe};
@@ -1,4 +1,4 @@
1
- var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});import b from"node:fs/promises";import x from"node:path";import y from"chrome-remote-interface";import{CaptureError as S}from"../errors.js";import{errMessage as A}from"../utils/errors.js";import{applyExclusions as I,originAllowedBy as E,originMatchesAny as P}from"./exclusion.js";const v=50,D=5,$=1e3,R=3,j=15e3,q=d((e,t,s)=>{let r;return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),new Promise((n,a)=>{r=setTimeout(()=>a(new Error(`${s} timed out after ${t}ms`)),t)})])},"withTimeout"),M=d(e=>/ECONNREFUSED|EPIPE|socket hang up/i.test(e),"isTransportDeadError"),k=d(e=>{const t=e.startsWith(".")?e.slice(1):e;return!!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t===""||t.includes(":"))},"isPrivateCookieDomain"),N=d(e=>{try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?!0:k(t.hostname)}catch{return!0}},"isPrivateOrigin"),O=new Set(["ntp.msn.com"]),C=d(e=>{try{return O.has(new URL(e).hostname)}catch{return!1}},"isVendorNtpOrigin"),L=d(async e=>{const t=x.join(e,"Local Storage","leveldb");let s;try{s=await b.readdir(t)}catch{return[]}const r=new Set;let n=0;const a=10*1024*1024,c=/https?:\/\/[a-zA-Z0-9.-]+(?::\d+)?/g;for(const i of s)if(!(!i.endsWith(".log")&&!i.endsWith(".ldb"))){if(n>=a)break;try{const l=await b.readFile(x.join(t,i));n+=l.byteLength;const p=l.toString("latin1");for(const f of p.matchAll(c))try{const u=new URL(f[0]);(u.protocol==="https:"||u.protocol==="http:")&&!k(u.hostname)&&!O.has(u.hostname)&&r.add(u.origin)}catch{}}catch{}}return[...r]},"enumerateLocalStorageOrigins"),F=d(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:typeof e.expires=="number"?e.expires:-1,size:e.size,httpOnly:!!e.httpOnly,secure:!!e.secure,session:!!e.session,...e.sameSite?{sameSite:e.sameSite}:{},...e.sourceScheme?{sourceScheme:e.sourceScheme}:{},...e.sourcePort?{sourcePort:e.sourcePort}:{}}),"cookieFromCdp"),H=d(async e=>{const t=await y({port:e});try{const{cookies:s}=await t.Storage.getCookies({});return s.filter(r=>!k(r.domain)).map(F)}finally{await t.close()}},"captureCookies"),U=Buffer.from("<html></html>").toString("base64"),X=d(async e=>{const t=await y({port:e.port});let s;try{s=(await t.Target.createTarget({url:"about:blank"})).targetId}finally{await t.close()}if(!s)return null;const r=await y({port:e.port,target:s});try{await r.Page.enable(),await r.Network.enable(),await r.Fetch.enable({patterns:[{urlPattern:"*"}]});const n=new Set([`${e.origin}/`]);r.on("Fetch.requestPaused",p=>{const{requestId:f,request:u}=p;n.has(u.url)?(n.delete(u.url),r.send("Fetch.fulfillRequest",{requestId:f,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/html"}],body:U}).catch(()=>{})):r.send("Fetch.failRequest",{requestId:f,errorReason:"BlockedByClient"}).catch(()=>{})}),await r.Page.navigate({url:`${e.origin}/`}),await r.Page.loadEventFired().catch(()=>{});const a=await r.Runtime.evaluate({expression:`
1
+ var I=Object.defineProperty;var u=(e,t)=>I(e,"name",{value:t,configurable:!0});import x from"node:fs/promises";import E from"node:path";import{CaptureError as w}from"../errors.js";import{errMessage as T}from"../utils/errors.js";import{applyExclusions as A,originAllowedBy as P,originMatchesAny as R}from"./exclusion.js";const v=50,D=5,$=1e3,O=3,M=15e3,N=u((e,t,n)=>{let s;return Promise.race([e.finally(()=>{s&&clearTimeout(s)}),new Promise((c,r)=>{s=setTimeout(()=>r(new Error(`${n} timed out after ${t}ms`)),t)})])},"withTimeout"),j=u(e=>/CDP pipe closed|ECONNREFUSED|EPIPE|socket hang up/i.test(e),"isTransportDeadError"),b=u(e=>{const t=e.startsWith(".")?e.slice(1):e;return!!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t===""||t.includes(":"))},"isPrivateCookieDomain"),_=u(e=>{try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?!0:b(t.hostname)}catch{return!0}},"isPrivateOrigin"),C=new Set(["ntp.msn.com"]),B=u(e=>{try{return C.has(new URL(e).hostname)}catch{return!1}},"isVendorNtpOrigin"),q=u(async e=>{const t=E.join(e,"Local Storage","leveldb");let n;try{n=await x.readdir(t)}catch{return[]}const s=new Set;let c=0;const r=10*1024*1024,i=/https?:\/\/[a-zA-Z0-9.-]+(?::\d+)?/g;for(const a of n)if(!(!a.endsWith(".log")&&!a.endsWith(".ldb"))){if(c>=r)break;try{const d=await x.readFile(E.join(t,a));c+=d.byteLength;const p=d.toString("latin1");for(const f of p.matchAll(i))try{const l=new URL(f[0]);(l.protocol==="https:"||l.protocol==="http:")&&!b(l.hostname)&&!C.has(l.hostname)&&s.add(l.origin)}catch{}}catch{}}return[...s]},"enumerateLocalStorageOrigins"),F=u(e=>({name:e.name,value:e.value,domain:e.domain,path:e.path,expires:typeof e.expires=="number"?e.expires:-1,size:e.size,httpOnly:!!e.httpOnly,secure:!!e.secure,session:!!e.session,...e.sameSite?{sameSite:e.sameSite}:{},...e.sourceScheme?{sourceScheme:e.sourceScheme}:{},...e.sourcePort?{sourcePort:e.sourcePort}:{}}),"cookieFromCdp"),L=3e4,U=u(async e=>{const{cookies:t}=await N(e.send("Storage.getCookies"),L,"Storage.getCookies").catch(n=>{throw new w(`Reading cookies from the headless browser failed: ${T(n)}`,"cdp-timeout")});return t.filter(n=>!b(n.domain)).map(F)},"captureCookies"),H=Buffer.from("<html></html>").toString("base64"),X=u(async e=>{const{cdp:t}=e,{targetId:n}=await t.send("Target.createTarget",{url:"about:blank"});if(!n)return null;let s,c=u(()=>{},"stopIntercepting");try{({sessionId:s}=await t.send("Target.attachToTarget",{targetId:n,flatten:!0}));const r=t.session(s);await r.send("Page.enable"),await r.send("Network.enable"),await r.send("Fetch.enable",{patterns:[{urlPattern:"*"}]});const i=new Set([`${e.origin}/`]);c=r.on("Fetch.requestPaused",S=>{const{requestId:y,request:o}=S;i.has(o.url)?(i.delete(o.url),r.send("Fetch.fulfillRequest",{requestId:y,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/html"}],body:H}).catch(()=>{})):r.send("Fetch.failRequest",{requestId:y,errorReason:"BlockedByClient"}).catch(()=>{})});const a=r.once("Page.loadEventFired").catch(()=>{});await r.send("Page.navigate",{url:`${e.origin}/`}),await a;const d=await r.send("Runtime.evaluate",{expression:`
2
2
  (() => {
3
3
  const out = {};
4
4
  for (let i = 0; i < localStorage.length; i++) {
@@ -7,7 +7,7 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
7
7
  }
8
8
  return JSON.stringify(out);
9
9
  })()
10
- `,returnByValue:!0,awaitPromise:!1}),c=a?.result?.value?JSON.parse(a.result.value):{},i=await r.Runtime.evaluate({expression:`
10
+ `,returnByValue:!0,awaitPromise:!1}),p=d?.result?.value?JSON.parse(d.result.value):{},f=await r.send("Runtime.evaluate",{expression:`
11
11
  (async (MAX_DBS, MAX_ENTRIES) => {
12
12
  if (typeof indexedDB.databases !== 'function') return [];
13
13
  const dbInfos = await indexedDB.databases();
@@ -59,4 +59,4 @@ var _=Object.defineProperty;var d=(e,t)=>_(e,"name",{value:t,configurable:!0});i
59
59
  }
60
60
  return JSON.stringify(out);
61
61
  })(${D}, ${$})
62
- `,returnByValue:!0,awaitPromise:!0}),l=i?.result?.value?JSON.parse(i.result.value):[];return Object.keys(c).length===0&&l.length===0?null:{origin:e.origin,localStorage:c,...l.length>0?{indexedDBs:l}:{}}}finally{await r.send("Fetch.disable").catch(()=>{}),await r.send("Network.disable").catch(()=>{}),await r.close().catch(()=>{});const n=await y({port:e.port});try{await n.Target.closeTarget({targetId:s})}catch{}finally{await n.close()}}},"captureOrigin"),W=d(async(e,t,s,r,n=[])=>{const a=[],c=[];let i=!1,l=0,p=0,f=0,u=0;const T=e.filter(o=>!N(o)).filter(o=>!C(o)).filter(o=>!P(o,t)).filter(o=>n.length===0||E(o,n)).length,B=Math.min(T,v);for(const o of e){if(u>=v){i=!0;break}if(!N(o)&&!C(o)){if(P(o,t)){l++;continue}if(n.length>0&&!E(o,n)){p++;continue}u++,r?.({attempted:u,total:B,origin:o});try{const m=await s(o);m&&a.push(m),f=0}catch(m){const h=A(m);if(M(h)){if(f++,f>=R)throw new S(`Headless browser appears to have crashed mid-capture \u2014 ${R} consecutive transport errors on the CDP port. Last failure on "${o}": ${h}. Retry the capture; if it persists, try a smaller profile or a different --password-store value.`,"browser-crashed-during-capture")}else f=0;let w="unknown";const g=h.toLowerCase();g.includes("timeout")||g.includes("timed out")?w="navigation-timeout":(g.includes("websocket")||g.includes("not connected")||g.includes("connection closed"))&&(w="cdp-disconnected"),c.push({origin:o,error:h,kind:w})}}}if(a.length===0&&c.length>0){const o=c.slice(0,3).map(h=>`${h.origin}: ${h.error}`).join("; "),m=c.length>3?` (+${c.length-3} more)`:"";throw new S(`All ${c.length} attempted origin(s) failed to capture; nothing usable was produced. Sample: ${o}${m}`,"all-origins-failed")}return{origins:a,failedOrigins:c,capHit:i,originCountSkippedByExclusion:l,originCountSkippedByOnlyDomain:p}},"runOriginCaptureLoop"),Y=d(async(e,t,s=[],r,n=[])=>{const a=await H(t),c=await L(e.profilePath),i=await W(c,s,p=>q(X({port:t,origin:p}),j,`per-origin capture of ${p}`),r,n),l=I({cookies:a,origins:i.origins},s);return{state:l.state,capHit:i.capHit,cookieCountTotal:a.length,cookieCountExcluded:a.length-l.state.cookies.length,originCountSkippedByExclusion:i.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:i.originCountSkippedByOnlyDomain,failedOrigins:i.failedOrigins}},"captureViaCdp");export{S as CaptureError,Y as captureViaCdp,F as cookieFromCdp,L as enumerateLocalStorageOrigins,k as isPrivateCookieDomain,N as isPrivateOrigin,M as isTransportDeadError,C as isVendorNtpOrigin,W as runOriginCaptureLoop,q as withTimeout};
62
+ `,returnByValue:!0,awaitPromise:!0}),l=f?.result?.value?JSON.parse(f.result.value):[];return Object.keys(p).length===0&&l.length===0?null:{origin:e.origin,localStorage:p,...l.length>0?{indexedDBs:l}:{}}}finally{if(c(),s){const r=t.session(s);await r.send("Fetch.disable").catch(()=>{}),await r.send("Network.disable").catch(()=>{}),await t.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{})}await t.send("Target.closeTarget",{targetId:n}).catch(()=>{})}},"captureOrigin"),W=u(async(e,t,n,s,c=[])=>{const r=[],i=[];let a=!1,d=0,p=0,f=0,l=0;const S=e.filter(o=>!_(o)).filter(o=>!B(o)).filter(o=>!R(o,t)).filter(o=>c.length===0||P(o,c)).length,y=Math.min(S,v);for(const o of e){if(l>=v){a=!0;break}if(!_(o)&&!B(o)){if(R(o,t)){d++;continue}if(c.length>0&&!P(o,c)){p++;continue}l++,s?.({attempted:l,total:y,origin:o});try{const g=await n(o);g&&r.push(g),f=0}catch(g){const h=T(g);if(j(h)){if(f++,f>=O)throw new w(`Headless browser appears to have crashed mid-capture \u2014 ${O} consecutive transport errors on the CDP connection. Last failure on "${o}": ${h}. Retry the capture; if it persists, try a smaller profile or a different --password-store value.`,"browser-crashed-during-capture")}else f=0;let k="unknown";const m=h.toLowerCase();m.includes("timeout")||m.includes("timed out")?k="navigation-timeout":(m.includes("websocket")||m.includes("not connected")||m.includes("connection closed")||m.includes("pipe closed"))&&(k="cdp-disconnected"),i.push({origin:o,error:h,kind:k})}}}if(r.length===0&&i.length>0){const o=i.slice(0,3).map(h=>`${h.origin}: ${h.error}`).join("; "),g=i.length>3?` (+${i.length-3} more)`:"";throw new w(`All ${i.length} attempted origin(s) failed to capture; nothing usable was produced. Sample: ${o}${g}`,"all-origins-failed")}return{origins:r,failedOrigins:i,capHit:a,originCountSkippedByExclusion:d,originCountSkippedByOnlyDomain:p}},"runOriginCaptureLoop"),Q=u(async(e,t,n=[],s,c=[])=>{const r=await U(t),i=await q(e.profilePath),a=await W(i,n,p=>N(X({cdp:t,origin:p}),M,`per-origin capture of ${p}`),s,c),d=A({cookies:r,origins:a.origins},n);return{state:d.state,capHit:a.capHit,cookieCountTotal:r.length,cookieCountExcluded:r.length-d.state.cookies.length,originCountSkippedByExclusion:a.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:a.originCountSkippedByOnlyDomain,failedOrigins:a.failedOrigins}},"captureViaCdp");export{L as COOKIE_READ_TIMEOUT_MS,w as CaptureError,Q as captureViaCdp,F as cookieFromCdp,q as enumerateLocalStorageOrigins,b as isPrivateCookieDomain,_ as isPrivateOrigin,j as isTransportDeadError,B as isVendorNtpOrigin,W as runOriginCaptureLoop,N as withTimeout};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var i=(e,r)=>u(e,"name",{value:r,configurable:!0});import d from"node:fs/promises";import{killBrowser as f}from"./launch.js";const p=i((e,r,n=f,c=()=>{})=>{let o;return()=>o??=(async()=>{c();const t=await r()?.catch(()=>{});t&&await n(t.child);const a=e();a&&await d.rm(a,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}).catch(()=>{})})()},"createCaptureCleanup");export{p as createCaptureCleanup};