@browserless.io/cli 0.6.0 → 0.6.1

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,160 @@
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.6.1 (2026-11-13)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bound decoded API responses and body deadlines
9
+ * 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
10
+ * escape remote agent terminal output
11
+ * escape terminal controls in error and profile displays
12
+ * pin custom browser registration paths
13
+
14
+ ## 0.6.0 (2026-11-05)
4
15
 
5
16
 
6
17
  ### Features
7
18
 
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))
19
+ * record failure category, code and HTTP status in CLI telemetry
9
20
 
10
- ## [0.5.2](https://github.com/browserless/browserless-cli/compare/v0.5.1...v0.5.2) (2026-10-30)
21
+ ## 0.5.2 (2026-10-30)
11
22
 
12
23
 
13
24
  ### Bug Fixes
14
25
 
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))
26
+ * reject authenticated API redirects
27
+ * isolate capture smoke state and replay
17
28
 
18
- ## [0.5.1](https://github.com/browserless/browserless-cli/compare/v0.5.0...v0.5.1) (2026-10-22)
29
+ ## 0.5.1 (2026-10-22)
19
30
 
20
31
 
21
32
  ### Bug Fixes
22
33
 
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))
34
+ * detect the Windows cookie-file lock during profile capture
24
35
 
25
- ## [0.5.0](https://github.com/browserless/browserless-cli/compare/v0.4.2...v0.5.0) (2026-10-16)
36
+ ## 0.5.0 (2026-10-16)
26
37
 
27
38
 
28
39
  ### Features
29
40
 
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))
41
+ * add profile terms command
31
42
 
32
- ## [0.4.2](https://github.com/browserless/browserless-cli/compare/v0.4.1...v0.4.2) (2026-10-13)
43
+ ## 0.4.2 (2026-10-13)
33
44
 
34
45
 
35
46
  ### Bug Fixes
36
47
 
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))
48
+ * enforce secure server URLs before sending tokens
38
49
 
39
- ## [0.4.1](https://github.com/browserless/browserless-cli/compare/v0.4.0...v0.4.1) (2026-10-06)
50
+ ## 0.4.1 (2026-10-06)
40
51
 
41
52
 
42
53
  ### Bug Fixes
43
54
 
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))
55
+ * restrict telemetry to trusted API hosts
45
56
 
46
- ## [0.4.0](https://github.com/browserless/browserless-cli/compare/v0.3.0...v0.4.0) (2026-09-22)
57
+ ## 0.4.0 (2026-09-22)
47
58
 
48
59
 
49
60
  ### Features
50
61
 
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))
62
+ * track CLI profile setup attempts
52
63
 
53
- ## [0.3.0](https://github.com/browserless/browserless-cli/compare/v0.2.0...v0.3.0) (2026-08-04)
64
+ ## 0.3.0 (2026-08-04)
54
65
 
55
66
 
56
67
  ### Features
57
68
 
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))
69
+ * Profile refresh replays the capture settings a profile was created with — no flags needed
59
70
 
60
- ## [0.2.0](https://github.com/browserless/browserless-cli/compare/v0.1.0...v0.2.0) (2026-06-18)
71
+ ## 0.2.0 (2026-06-18)
61
72
 
62
73
 
63
74
  ### Features
64
75
 
65
- * add usage telemetry ([#19](https://github.com/browserless/browserless-cli/issues/19)) ([bdaa5dd](https://github.com/browserless/browserless-cli/commit/bdaa5dd01a8c6712dcf345edae1c41a228e05097))
76
+ * add usage telemetry
66
77
 
67
- ## [0.1.0](https://github.com/browserless/browserless-cli/compare/v0.0.3...v0.1.0) (2026-06-05)
78
+ ## 0.1.0 (2026-06-05)
68
79
 
69
80
 
70
81
  ### Features
71
82
 
72
- * Interactive agent chat via `browserless agent` ([c453dba](https://github.com/browserless/browserless-cli/commit/c453dbad50aa3283f9f8340bf32ed51d185ff132))
83
+ * Interactive agent chat via `browserless agent`
73
84
 
74
- ## [0.0.3](https://github.com/browserless/browserless-cli/compare/v0.0.2...v0.0.3) (2026-06-05)
85
+ ## 0.0.3 (2026-06-05)
75
86
 
76
87
 
77
88
  ### Bug Fixes
78
89
 
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))
90
+ * **capture:** connect to the browser CDP endpoint, not a default page target
91
+ * **capture:** retry the default-target CDP connect on "No inspectable targets"
92
+ * **capture:** wait for an inspectable target before connecting (fixes "No inspectable targets")
93
+ * **cli:** set process.exitCode instead of process.exit() on error path
94
+ * **cli:** windows/macos flaky tests
84
95
 
85
- ## [0.0.2](https://github.com/browserless/browserless-cli/compare/v0.0.1...v0.0.2) (2026-05-27)
96
+ ## 0.0.2 (2026-05-27)
86
97
 
87
98
 
88
99
  ### Features
89
100
 
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))
101
+ * --region sfo|lon|ams shortcut + region config key
102
+ * Add the Browserless CLI for authenticated profile management
103
+ * **capture:** live progress events, skip vendor NTP origins, cap loop on attempts, + --auto-fit/--keep-domain/--only-domain for artifact size mgmt
104
+ * **capture:** skip sensitive profile files from temp copy + CI smoke that catches future Chrome additions
105
+ * **ci:** cli-smoke integration test invokes every command on every OS via stub server
106
+ * **disclaimer:** include privacy-policy link in liability disclaimer text
107
+ * **registry:** discover Snap-installed Chromium on Linux + CI matrix axis for it
108
+ * **scripts:** add npm run dev (build + npm link) for one-shot local-dev setup
109
+ * **sources:** surface broken custom-browser registrations in sources list
99
110
 
100
111
 
101
112
  ### Bug Fixes
102
113
 
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))
114
+ * address review findings — surface silent fallbacks, narrow types, add coverage (+57 tests)
115
+ * **api:** preserve path prefix on configured server URL (self-hosted-behind-/browserless/)
116
+ * **browsers:** swallow fs.readdir EACCES/EIO so one bad source doesn't abort discovery
117
+ * **browsers:** try every candidate user-data-dir so Snap chromium isn't masked by a stale ~/.config/chromium
118
+ * **capture:** apply --only-domain pre-navigation so the per-run origin cap isn't burned on non-matching origins
119
+ * **capture:** fail fast on all-invalid --only-domain so pre/post filters can't silently diverge
120
+ * **capture:** fail-fast on consecutive transport-dead CDP errors + throw on all-origins-failed
121
+ * **capture:** filter Windows process sweep to chrome family binary — was killing PowerShell itself
122
+ * **capture:** per-origin 15 s timeout so a single hung CDP tab can't lock the whole capture
123
+ * **capture:** richer CDP-timeout diagnostics (pid/exit/args) + spec slop for CI
124
+ * **capture:** run Windows process sweep detached + fire-and-forget — synchronous PowerShell call was crashing the CLI
125
+ * **capture:** spawnSync taskkill on Windows + poll for orphan reap in test (Chrome tree teardown is slower on Windows)
126
+ * **capture:** surface browser stderr in CDP-timeout error for diagnostics
127
+ * **capture:** sweep Chrome processes by user-data-dir on Windows — renderers/utilities use CREATE_BREAKAWAY_FROM_JOB and survive taskkill /T
128
+ * **capture:** tally origin drops from both pre-nav skip and post-capture filter so a future post-capture filter can't silently undercount
129
+ * **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
130
+ * **ci:** apt options go after apt-get, not after sudo
131
+ * **ci:** avoid $HOME override in capture smoke — add BROWSERLESS_CONFIG_DIR + custom browser source
132
+ * **ci:** BROWSERLESS_DISABLE_KEYCHAIN escape hatch + drop whitespace-arg test (Windows cmd trims it)
133
+ * **ci:** drop flaky windows-kill dep; use inline PowerShell P/Invoke for CTRL_BREAK_EVENT
134
+ * **ci:** make CDP-wait timeout configurable; bump to 60s in capture smoke (macOS cold-boot)
135
+ * **ci:** restore apt-get update before gnome-keyring install — cached lists go stale
136
+ * **ci:** same Chrome seed fix for linux smoke
137
+ * **ci:** seed Chrome user-data-dir directly instead of racing first-run boot
138
+ * **ci:** spawn browserless.cmd directly on Windows — shell:true splits args with spaces
139
+ * **ci:** split discovery smoke — chromium uses lookup-only mode (registry hit only); inspect mode kept for brave/edge (full capture)
140
+ * **ci:** Windows arg quoting — shell:true with manual cmd-metachar quoting
141
+ * **commands:** add missing region?: string to upload/refresh Options interfaces
142
+ * **discover:** don't apply which-fallback to user-data-dir lookup — would return a binary path as a directory and crash readdir
143
+ * **exclusion:** punycode-normalize bare hostnames so Unicode patterns match IDN cookie domains
144
+ * **lock:** check 'lockfile' on Windows, 'SingletonLock' on POSIX (Chrome uses different filenames)
145
+ * **lock:** Windows lockfile is an empty marker — presence = locked (no PID)
146
+ * **registry:** discover Brave at per-user install path on Windows (%LOCALAPPDATA%) — default for choco / non-admin installs
147
+ * **sh:** drop duplicate Linux pattern in verify-chrome.sh case
148
+ * **sources:** validate --path and --user-data-dir at sources add time
149
+ * **test:** bound chrome.exe warmup to 30s so it can't hang CI
150
+ * **test:** poll lstatSync for SingletonLock + skip Windows orphan-check (documented limitation)
151
+ * **test:** skip SIGTERM-trap killBrowser test on Windows (no real signals)
152
+ * **trim-state:** don't treat unparseable origins as protected by --keep-domain
142
153
 
143
154
 
144
155
  ### Reverts
145
156
 
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))
157
+ * 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
158
 
148
159
  ## Changelog
149
160
 
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,43 @@ 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
+
308
+ - Follow-up messages continue the same session. Ctrl-C stops the current
309
+ turn; press it again (or send an empty line) to exit.
310
+ - When the agent pauses for input — for example a one-time code — the CLI
311
+ prompts you for it.
312
+ - If your first message asks the agent to log in somewhere, the CLI asks
313
+ for a username and password (the password is masked) and sends them to
314
+ the hosted agent together with your task. Leave the prompts blank to
315
+ skip.
316
+ - Prompts you type are kept in `~/.browserless/agent_history` (mode 0600,
317
+ last 200) so the up arrow recalls them across sessions; usernames,
318
+ passwords and codes are never written there. `--no-history` turns the
319
+ file off.
320
+
289
321
  ## ⚙️ Shared Flags
290
322
 
291
323
  Every command that hits the cloud API accepts:
292
324
 
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) |
325
+ | Flag | Effect |
326
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
327
+ | `--token <tok>` | Override token resolution (flag > env > keychain > config file). Visible in the process list; prefer `BROWSERLESS_TOKEN` for scripts |
328
+ | `--server <url>` | Override the configured server URL |
329
+ | `--region <code>` | `sfo` / `lon` / `ams` — shorthand for `--server` |
330
+ | `--json` | Emit the server response as JSON (script-friendly) |
299
331
 
300
332
  Capture commands (`upload`, `refresh`, `inspect`) also accept:
301
333
 
@@ -372,6 +404,13 @@ authenticated with your token and targeted a Browserless cloud region:
372
404
  - the production region (`sfo` / `lon` / `ams`) — never a raw server URL
373
405
  - a random per-install id (`cli_device_id`), stored in
374
406
  `~/.browserless/telemetry-device-id`
407
+ - for `profile upload` / `profile refresh`, a few setup-progress events
408
+ (`Profile Setup Method Selected`, `Profile Setup Started`,
409
+ `Profile Setup Ready`, `Profile Save Submitted`, and
410
+ `Profile Setup Failed` with a short reason code) that share a random
411
+ `attempt_id`. Pass `--attempt-id <UUID>` to keep your own id across
412
+ retries; the same id is sent to the Browserless server with the upload as
413
+ the `x-browserless-attempt-id` header
375
414
 
376
415
  **What's never in the analytics data:** your API token, profile names,
377
416
  captured URLs or domains, cookies, or any captured auth state. The token is
@@ -422,16 +461,30 @@ touched; sensitive domains never leave your machine.
422
461
  Once uploaded, any Browserless cloud session can attach the profile
423
462
  via `?profile=<name>` and start _already authenticated_.
424
463
 
425
- ## 📜 Licensing
464
+ ## 🤝 Contributing
465
+
466
+ Pull requests are welcome. [AGENTS.md](AGENTS.md) is the contributor guide —
467
+ architecture, local setup, testing patterns and conventions (coding agents
468
+ read the same file). Before opening a PR:
469
+
470
+ ```bash
471
+ npm run build && npm run lint && npm test
472
+ ```
426
473
 
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.
474
+ PR titles follow [Conventional Commits](https://www.conventionalcommits.org/)
475
+ and become the changelog entry.
476
+
477
+ ## 🔒 Security
478
+
479
+ Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md).
480
+ Don't open a public issue for a security problem.
481
+
482
+ ## 📜 Licensing
430
483
 
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.
484
+ The Browserless CLI is open source under the [MIT License](LICENSE).
485
+ Using it with the hosted Browserless service is also covered by your
486
+ Browserless account terms and the
487
+ [privacy policy](https://www.browserless.io/privacy-policy).
435
488
 
436
489
  <div align="center">
437
490
 
@@ -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=(e,o)=>n(e,"name",{value:o,configurable:!0});import{apiFetch as i}from"./client.js";import{UsageError as l}from"../errors.js";const c=t(async(e,o={})=>i(e,{method:"GET",path:"/profiles",query:{...o.limit!==void 0?{limit:o.limit}:{},...o.offset!==void 0?{offset:o.offset}:{}}}),"listProfiles"),r=t(e=>{if(e==="."||e==="..")throw new l(`"${e}" is not a valid profile name.`);return`/profile/${encodeURIComponent(e)}`},"profilePath"),h=t(async(e,o)=>i(e,{method:"GET",path:r(o)}),"getProfile"),m=t(async(e,o,f)=>i(e,{method:"PUT",path:r(o),body:{name:f}}),"renameProfile"),a=t(async(e,o)=>i(e,{method:"DELETE",path:r(o)}),"deleteProfile");export{a as deleteProfile,h as getProfile,c as listProfiles,m 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};
@@ -1 +1 @@
1
- var S=Object.defineProperty;var c=(o,i)=>S(o,"name",{value:i,configurable:!0});import a from"node:fs/promises";import r from"node:path";import h from"node:os";import{CaptureError as l}from"../errors.js";import{COOKIE_DB_FILES as m,createLockGate as w,isWindowsLockError as p}from"./profile-lock.js";const g=new Set(["Cache","Code Cache","GPUCache","GraphiteDawnCache","ShaderCache","Service Worker","Crashpad","optimization_guide_model_store","Default Cache"]),k=new Set(["History","History-journal","History Provider Cache","Top Sites","Top Sites-journal","Visited Links","Favicons","Favicons-journal","Shortcuts","Shortcuts-journal","Network Action Predictor","Network Action Predictor-journal","Login Data","Login Data-journal","Login Data For Account","Login Data For Account-journal","Web Data","Web Data-journal","Account Web Data","Account Web Data-journal","Affiliation Database","Affiliation Database-journal","AutofillStrikeDatabase","AutofillAiModelCache","passkey_enclave_state","trusted_vault.pb","Bookmarks","Bookmarks.bak","BookmarkMergedSurfaceOrdering","DIPS","DIPS-shm","DIPS-wal","Trust Tokens","Trust Tokens-journal","BrowsingTopicsState","BrowsingTopicsSiteData","BrowsingTopicsSiteData-journal","Reporting and NEL","Reporting and NEL-journal","SCT Auditing Pending Reports","Extensions","Extension Cookies","Extension Cookies-journal","Extension Rules","Extension Scripts","Extension State","Local Extension Settings","Managed Extension Settings","Sync Extension Settings","Sessions","Sync Data","Sync App Settings","Web Applications","Platform Notifications","Download Service","chrome_cart_db","commerce_subscription_db","discount_infos_db","discounts_db","parcel_tracking_db","heavy_ad_intervention_opt_out.db","heavy_ad_intervention_opt_out.db-journal","Safe Browsing Cookies","Safe Browsing Cookies-journal"]),_=["SingletonLock","SingletonSocket","SingletonCookie"],v=c(async(o,i={interactive:!1})=>{const e=w(o,i),s=i.platform??process.platform;for(const u of m)await e.ensureReadable(r.join(o.profilePath,u));return e.retryOnLock(()=>D(o,s))},"buildTempUserDataDir"),D=c(async(o,i)=>{const e=await a.mkdtemp(r.join(h.tmpdir(),"browserless-cli-")),s=r.join(o.userDataDir,"Local State"),u=r.join(e,"Local State");try{await a.copyFile(s,u)}catch(t){const n=t?.code;if(n!=="ENOENT")throw await a.rm(e,{recursive:!0,force:!0}).catch(()=>{}),p(t,i)?t:new l(`Failed to copy ${s} (${n??"unknown error"}): ${t.message}`,"profile-copy-failed")}try{await a.writeFile(r.join(e,"First Run"),"")}catch(t){throw await a.rm(e,{recursive:!0,force:!0}).catch(()=>{}),new l(`Failed to write First Run marker in ${e}: ${t.message}`,"profile-copy-failed")}const d=r.join(e,o.profileDirName);try{await a.cp(o.profilePath,d,{recursive:!0,force:!0,filter:c(t=>{const n=r.relative(o.profilePath,t);if(!n)return!0;const f=n.split(r.sep)[0];return!(g.has(f)||k.has(f))},"filter")})}catch(t){throw await a.rm(e,{recursive:!0,force:!0}).catch(()=>{}),p(t,i)?t:new l(`Failed to copy profile from ${o.profilePath}: ${t?.message??t}`,"profile-copy-failed")}return await Promise.all(_.flatMap(t=>[a.unlink(r.join(e,t)).catch(()=>{}),a.unlink(r.join(d,t)).catch(()=>{})])),e},"copyOnce");export{v as buildTempUserDataDir};
1
+ var h=Object.defineProperty;var d=(o,i)=>h(o,"name",{value:i,configurable:!0});import r from"node:fs/promises";import a from"node:path";import m from"node:os";import{CaptureError as p}from"../errors.js";import{COOKIE_DB_FILES as _,createLockGate as D,isWindowsLockError as w}from"./profile-lock.js";const g=new Set(["Cache","Code Cache","GPUCache","GraphiteDawnCache","ShaderCache","Service Worker","Crashpad","optimization_guide_model_store","Default Cache"]),E=new Set(["History","History-journal","History Provider Cache","Top Sites","Top Sites-journal","Visited Links","Favicons","Favicons-journal","Shortcuts","Shortcuts-journal","Network Action Predictor","Network Action Predictor-journal","Login Data","Login Data-journal","Login Data For Account","Login Data For Account-journal","Web Data","Web Data-journal","Account Web Data","Account Web Data-journal","Affiliation Database","Affiliation Database-journal","AutofillStrikeDatabase","AutofillAiModelCache","passkey_enclave_state","trusted_vault.pb","Bookmarks","Bookmarks.bak","BookmarkMergedSurfaceOrdering","DIPS","DIPS-shm","DIPS-wal","Trust Tokens","Trust Tokens-journal","BrowsingTopicsState","BrowsingTopicsSiteData","BrowsingTopicsSiteData-journal","Reporting and NEL","Reporting and NEL-journal","SCT Auditing Pending Reports","Extensions","Extension Cookies","Extension Cookies-journal","Extension Rules","Extension Scripts","Extension State","Local Extension Settings","Managed Extension Settings","Sync Extension Settings","Sessions","Sync Data","Sync App Settings","Web Applications","Platform Notifications","Download Service","chrome_cart_db","commerce_subscription_db","discount_infos_db","discounts_db","parcel_tracking_db","heavy_ad_intervention_opt_out.db","heavy_ad_intervention_opt_out.db-journal","Safe Browsing Cookies","Safe Browsing Cookies-journal"]),k=["SingletonLock","SingletonSocket","SingletonCookie"],R=d(async(o,i={interactive:!1},l,s)=>{const e=D(o,i),n=i.platform??process.platform;for(const c of _)await e.ensureReadable(a.join(o.profilePath,c));return e.retryOnLock(()=>P(o,n,l,s))},"buildTempUserDataDir"),y="browserless-cli-",b=/^browserless-cli-[A-Za-z0-9]{6,}$/,j=3600*1e3,F=d(async({dir:o=m.tmpdir(),maxAgeMs:i=j,now:l=Date.now(),uid:s=process.getuid?.()}={})=>{const e=await r.readdir(o).catch(()=>[]);await Promise.all(e.filter(n=>b.test(n)).map(async n=>{const c=a.join(o,n),u=await r.lstat(c).catch(()=>null);!u?.isDirectory()||l-u.mtimeMs<i||s!==void 0&&u.uid!==s||await r.rm(c,{recursive:!0,force:!0}).catch(()=>{})}))},"sweepStaleTempDirs"),P=d(async(o,i,l,s)=>{const e=await r.mkdtemp(a.join(m.tmpdir(),y));l?.(e);const n=a.join(o.userDataDir,"Local State"),c=a.join(e,"Local State");try{await r.copyFile(n,c)}catch(t){const f=t?.code;if(f!=="ENOENT")throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),w(t,i)?t:new p(`Failed to copy ${n} (${f??"unknown error"}): ${t.message}`,"profile-copy-failed")}try{await r.writeFile(a.join(e,"First Run"),"")}catch(t){throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),new p(`Failed to write First Run marker in ${e}: ${t.message}`,"profile-copy-failed")}const u=a.join(e,o.profileDirName);try{await r.cp(o.profilePath,u,{recursive:!0,force:!0,filter:d(t=>{if(s?.aborted)return!1;const f=a.relative(o.profilePath,t);if(!f)return!0;const S=f.split(a.sep)[0];return!(g.has(S)||E.has(S))},"filter")})}catch(t){throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),w(t,i)?t:new p(`Failed to copy profile from ${o.profilePath}: ${t?.message??t}`,"profile-copy-failed")}if(s?.aborted)throw await r.rm(e,{recursive:!0,force:!0}).catch(()=>{}),new p("Profile copy interrupted before it finished","profile-copy-failed");return await Promise.all(k.flatMap(t=>[r.unlink(a.join(e,t)).catch(()=>{}),r.unlink(a.join(u,t)).catch(()=>{})])),e},"copyOnce");export{R as buildTempUserDataDir,F as sweepStaleTempDirs};
@@ -1 +1 @@
1
- var p=Object.defineProperty;var n=(i,t)=>p(i,"name",{value:t,configurable:!0});import g from"node:fs/promises";import{buildTempUserDataDir as m}from"./copy-profile.js";import{killBrowser as f,launchBrowser as D,pickFreePort as h,waitForDebuggerEndpoint as w}from"./launch.js";import{captureViaCdp as y}from"./cdp.js";const k=n(()=>process.hrtime.bigint(),"startTime"),C=n(i=>Number((process.hrtime.bigint()-i)/1000000n),"elapsedMs"),b=n(async i=>{const t=k(),o=i.onProgress;o?.({phase:"copying"});const c=await m(i.profile,{interactive:i.interactive??!1,onWait:n(r=>o?.({phase:"waiting-for-unlock",...r}),"onWait")}),a=await h();let s=null,l;try{o?.({phase:"launching"});const r=await D({profile:i.profile,userDataDir:c,port:a,passwordStoreOverride:i.passwordStoreOverride});s=r.child,l=r.passwordStoreDefaulted,o?.({phase:"waiting-for-debugger"}),await w(a,void 0,r.diagnostics),o?.({phase:"capturing-origins",attempted:0,total:0,origin:""});const e=await y(i.profile,a,i.excludedDomains??[],u=>o?.({phase:"capturing-origins",...u}),i.onlyDomains??[]);o?.({phase:"done"});const d=JSON.stringify(e.state);return{state:e.state,diagnostics:{cookieCountBeforeExclusion:e.cookieCountTotal,cookieCountExcluded:e.cookieCountExcluded,originCountBeforeExclusion:e.state.origins.length+e.originCountSkippedByExclusion+e.originCountSkippedByOnlyDomain,originCountExcluded:e.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:e.originCountSkippedByOnlyDomain,excludedDomains:i.excludedDomains??[],onlyDomains:i.onlyDomains??[],durationMs:C(t),failedOrigins:e.failedOrigins},capHit:e.capHit,passwordStoreDefaulted:l,serialized:d}}finally{s&&await f(s),await g.rm(c,{recursive:!0,force:!0}).catch(()=>{})}},"captureFromProfile");export{b as captureFromProfile};
1
+ var f=Object.defineProperty;var o=(e,s)=>f(e,"name",{value:s,configurable:!0});import{buildTempUserDataDir as w,sweepStaleTempDirs as y}from"./copy-profile.js";import{createCaptureCleanup as h}from"./cleanup.js";import{launchBrowserWithPipe as C,startAnsweringBrowser as D,waitForCdpPipe as b}from"./launch.js";import{captureViaCdp as x}from"./cdp.js";import{onInterrupt as B}from"../utils/interrupt.js";import{CaptureError as S}from"../errors.js";const k=o(()=>process.hrtime.bigint(),"startTime"),E=o(e=>Number((process.hrtime.bigint()-e)/1000000n),"elapsedMs"),M=o(async e=>{const s=k(),i=e.onProgress;await y();let n,p,d;const c=new AbortController,l=h(()=>n,()=>p,void 0,()=>c.abort()),u=B(l);try{i?.({phase:"copying"}),n=await w(e.profile,{interactive:e.interactive??!1,onWait:o(t=>i?.({phase:"waiting-for-unlock",...t}),"onWait")},t=>{n=t},c.signal);const g=n,a=await D(o(async()=>{if(c.signal.aborted)throw new S("Capture interrupted before the browser started","profile-copy-failed");i?.({phase:"launching"}),p=C({profile:e.profile,userDataDir:g,passwordStoreOverride:e.passwordStoreOverride});const t=await p;return i?.({phase:"waiting-for-debugger"}),t},"startBrowser"),{onRestart:o(()=>i?.({phase:"restarting-browser"}),"onRestart")});d=a.passwordStoreDefaulted,await b(a.cdp,void 0,a.diagnostics),i?.({phase:"capturing-origins",attempted:0,total:0,origin:""});const r=await x(e.profile,a.cdp,e.excludedDomains??[],t=>i?.({phase:"capturing-origins",...t}),e.onlyDomains??[]);i?.({phase:"done"});const m=JSON.stringify(r.state);return{state:r.state,diagnostics:{cookieCountBeforeExclusion:r.cookieCountTotal,cookieCountExcluded:r.cookieCountExcluded,originCountBeforeExclusion:r.state.origins.length+r.originCountSkippedByExclusion+r.originCountSkippedByOnlyDomain,originCountExcluded:r.originCountSkippedByExclusion,originCountSkippedByOnlyDomain:r.originCountSkippedByOnlyDomain,excludedDomains:e.excludedDomains??[],onlyDomains:e.onlyDomains??[],durationMs:E(s),failedOrigins:r.failedOrigins},capHit:r.capHit,passwordStoreDefaulted:d,serialized:m}}finally{await l(),u()}},"captureFromProfile");export{M as captureFromProfile};
@@ -1,7 +1,7 @@
1
- var w=Object.defineProperty;var a=(e,r)=>w(e,"name",{value:r,configurable:!0});import g from"node:net";import{spawn as b,spawnSync as m}from"node:child_process";import{resolveLinuxPasswordStore as C}from"../browsers/password-store.js";import{CaptureError as c}from"../errors.js";const y=a(e=>new Promise(r=>setTimeout(r,e)),"sleep"),D=a(()=>new Promise((e,r)=>{const t=g.createServer();t.unref(),t.on("error",r),t.listen(0,"127.0.0.1",()=>{const n=t.address();t.close(()=>{typeof n=="object"&&n?e(n.port):r(new Error("Could not pick a free port"))})})}),"pickFreePort"),B=a(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const n=Date.now()+r;let s,d="<not fetched>";for(;Date.now()<n;){try{if((await fetch(`http://127.0.0.1:${e}/json/version`)).ok){const o=await fetch(`http://127.0.0.1:${e}/json/list`);if(o.ok){const p=await o.json();if(Array.isArray(p)&&p.some(f=>typeof f?.webSocketDebuggerUrl=="string"))return;d=JSON.stringify(p)}}}catch(i){s=i}await y(150)}let l="";if(t){const i=t.getProcessState(),o=t.getStderr().trim();l=`
2
- Browser process: pid=${i.pid??"unspawned"} exitCode=${i.exitCode} signal=${i.signalCode}
3
- Launch command: ${i.spawnfile} ${i.spawnargs.slice(1).join(" ")}
4
- Last /json/list: ${d}`+(o?`
5
- Browser stderr (last ${Math.min(o.length,2e3)} chars):
6
- ${o.slice(-2e3)}`:`
7
- Browser stderr: <empty>`)}throw new c(`Browser CDP endpoint did not expose an inspectable target within ${r}ms (last error: ${String(s)})${l}`,"cdp-timeout")},"waitForDebuggerEndpoint"),k=["--disable-background-networking","--disable-component-update","--disable-sync","--disable-domain-reliability","--disable-datasaver-prompt","--no-pings","--no-service-autorun","--safebrowsing-disable-auto-update","--disable-external-intent-requests","--metrics-recording-only","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-back-forward-cache","--disable-ipc-flooding-protection","--disable-hang-monitor","--disable-popup-blocking","--disable-prompt-on-repost","--disable-search-engine-choice-screen","--disable-breakpad","--disable-client-side-phishing-detection","--disable-infobars","--disable-print-preview","--disable-desktop-notifications","--disable-speech-api","--disable-speech-synthesis-api","--suppress-message-center-popups","--noerrdialogs","--disable-blink-features=AutomationControlled","--disable-features="+["AcceptCHFrame","AutoExpandDetailsElement","AvoidUnnecessaryBeforeUnloadCheckSync","CertificateTransparencyComponentUpdater","DialMediaRouteProvider","GlobalMediaControls","HttpsUpgrades","ImprovedCookieControls","LazyFrameLoading","MediaRouter","PaintHolding","Translate","AutomationControlled","BackForwardCache","OptimizationHints","CalculateNativeWinOcclusion","AutofillServerCommunication","CrashReporting","OverscrollHistoryNavigation","InfiniteSessionRestore"].join(",")],P=a(async e=>{const r=e.headless??!0,t=[`--remote-debugging-port=${e.port}`,`--user-data-dir=${e.userDataDir}`,`--profile-directory=${e.profile.profileDirName}`,"--no-first-run","--no-default-browser-check"];r&&t.push("--headless=new","--disable-gpu",...k);let n=!1;if(process.platform==="linux"){const{store:o,defaulted:p}=await C(e.profile.userDataDir,e.passwordStoreOverride);t.push(`--password-store=${o}`),n=p}t.push("about:blank");const s=b(e.profile.binaryPath,t,{detached:!1,stdio:["ignore","pipe","pipe"]}),d=[];let l=0;const i=64*1024;return s.stdout?.on("data",()=>{}),s.stderr?.on("data",o=>{l>=i||(d.push(o),l+=o.length)}),{child:s,passwordStoreDefaulted:n,diagnostics:{getStderr:a(()=>Buffer.concat(d).toString("utf-8"),"getStderr"),getProcessState:a(()=>({pid:s.pid,exitCode:s.exitCode,signalCode:s.signalCode,spawnfile:s.spawnfile,spawnargs:s.spawnargs}),"getProcessState")}}},"launchBrowser"),A=a(async e=>{const r=await fetch(`http://127.0.0.1:${e}/json/version`);if(!r.ok)throw new c(`CDP /json/version returned ${r.status} ${r.statusText}`,"cdp-metadata-invalid");const t=await r.json();if(typeof t.webSocketDebuggerUrl!="string"||typeof t.Browser!="string")throw new c(`CDP /json/version returned an unexpected payload: ${JSON.stringify(t)}`,"cdp-metadata-invalid");return{Browser:t.Browser,webSocketDebuggerUrl:t.webSocketDebuggerUrl}},"fetchCdpMetadata"),u=a((e,r)=>new Promise(t=>{if(e.exitCode!==null||e.signalCode!==null){t();return}const n=setTimeout(t,r);e.once("exit",()=>{clearTimeout(n),t()})}),"waitExitOrTimeout"),T=a(async(e,r=2e3)=>{if(!(!e||e.killed)){if(process.platform==="win32"&&typeof e.pid=="number"){m("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}),await u(e,r);return}e.kill("SIGTERM"),await u(e,r),!e.killed&&e.exitCode===null&&(e.kill("SIGKILL"),await u(e,5e3)),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),e.unref()}},"killBrowser");export{A as fetchCdpMetadata,T as killBrowser,P as launchBrowser,D as pickFreePort,B as waitForDebuggerEndpoint};
1
+ var S=Object.defineProperty;var o=(e,r)=>S(e,"name",{value:r,configurable:!0});import y from"node:net";import k from"node:path";import{spawn as P,spawnSync as T}from"node:child_process";import{resolveLinuxPasswordStore as x}from"../browsers/password-store.js";import{CaptureError as c}from"../errors.js";import{CDP_PIPE_CLOSED as D,connectCdpPipe as $}from"./cdp-pipe.js";const w=o(e=>new Promise(r=>setTimeout(r,e)),"sleep"),W=o(()=>new Promise((e,r)=>{const t=y.createServer();t.unref(),t.on("error",r),t.listen(0,"127.0.0.1",()=>{const s=t.address();t.close(()=>{typeof s=="object"&&s?e(s.port):r(new Error("Could not pick a free port"))})})}),"pickFreePort"),F=o(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const s=Date.now()+r;let a,n="<not fetched>";for(;Date.now()<s;){try{if((await fetch(`http://127.0.0.1:${e}/json/version`)).ok){const i=await fetch(`http://127.0.0.1:${e}/json/list`);if(i.ok){const d=await i.json();if(Array.isArray(d)&&d.some(p=>typeof p?.webSocketDebuggerUrl=="string"))return;n=JSON.stringify(d)}}}catch(l){a=l}await w(150)}throw new c(`Browser CDP endpoint did not expose an inspectable target within ${r}ms (last error: ${String(a)})${g(t,`Last /json/list: ${n}`)}`,"cdp-timeout")},"waitForDebuggerEndpoint"),g=o((e,r)=>{if(!e)return"";const t=e.getProcessState(),s=e.getStderr().trim();return`
2
+ Browser process: pid=${t.pid??"unspawned"} exitCode=${t.exitCode} signal=${t.signalCode}
3
+ Launch command: ${t.spawnfile} ${t.spawnargs.slice(1).join(" ")}
4
+ ${r}`+(s?`
5
+ Browser stderr (last ${Math.min(s.length,2e3)} chars):
6
+ ${s.slice(-2e3)}`:`
7
+ Browser stderr: <empty>`)},"describeLaunch"),f=1e3,H=o(async(e,r=Number(process.env.BROWSERLESS_CDP_WAIT_MS)||15e3,t)=>{const s=Date.now()+r;let a,n="<not fetched>";for(;Date.now()<s;){let l;try{const{targetInfos:i}=await Promise.race([e.send("Target.getTargets"),new Promise((d,p)=>{l=setTimeout(()=>p(new Error("Target.getTargets did not answer")),Math.min(f,Math.max(s-Date.now(),0)))})]);if(i.some(d=>d.type==="page"))return;n=JSON.stringify(i)}catch(i){if(a=i,i instanceof Error&&i.message.startsWith(D))break}finally{clearTimeout(l)}await w(150)}throw new c(`Browser CDP pipe did not expose an inspectable target within ${r}ms (last error: ${String(a)})${g(t,`Last Target.getTargets: ${n}`)}`,"cdp-timeout")},"waitForCdpPipe"),v=["--disable-background-networking","--disable-component-update","--disable-sync","--disable-domain-reliability","--disable-datasaver-prompt","--no-pings","--no-service-autorun","--safebrowsing-disable-auto-update","--disable-external-intent-requests","--metrics-recording-only","--disable-background-timer-throttling","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-back-forward-cache","--disable-ipc-flooding-protection","--disable-hang-monitor","--disable-popup-blocking","--disable-prompt-on-repost","--disable-search-engine-choice-screen","--disable-breakpad","--disable-client-side-phishing-detection","--disable-infobars","--disable-print-preview","--disable-desktop-notifications","--disable-speech-api","--disable-speech-synthesis-api","--suppress-message-center-popups","--noerrdialogs","--disable-blink-features=AutomationControlled","--disable-features="+["AcceptCHFrame","AutoExpandDetailsElement","AvoidUnnecessaryBeforeUnloadCheckSync","CertificateTransparencyComponentUpdater","DialMediaRouteProvider","GlobalMediaControls","HttpsUpgrades","ImprovedCookieControls","LazyFrameLoading","MediaRouter","PaintHolding","Translate","AutomationControlled","BackForwardCache","OptimizationHints","CalculateNativeWinOcclusion","AutofillServerCommunication","CrashReporting","OverscrollHistoryNavigation","InfiniteSessionRestore"].join(",")],G=o(e=>m(e,{port:e.port}),"launchBrowser"),J=o(async e=>{const r=await m(e,{pipe:!0}),{stdio:t}=r.child;return{...r,cdp:$(t[3],t[4])}},"launchBrowserWithPipe"),m=o(async(e,r)=>{const t=e.headless??!0,s=["port"in r?`--remote-debugging-port=${r.port}`:"--remote-debugging-pipe",`--user-data-dir=${e.userDataDir}`,`--profile-directory=${e.profile.profileDirName}`,"--no-first-run","--no-default-browser-check"];t&&s.push("--headless=new","--disable-gpu",...v);let a=!1;if(process.platform==="linux"){const{store:p,defaulted:C}=await x(e.profile.userDataDir,e.passwordStoreOverride);s.push(`--password-store=${p}`),a=C}s.push("about:blank");const n=P(e.profile.binaryPath,s,{detached:!1,stdio:"port"in r?["ignore","pipe","pipe"]:["ignore","pipe","pipe","pipe","pipe"]}),l=[];let i=0;const d=64*1024;return n.stdout?.on("data",()=>{}),n.stderr?.on("data",p=>{i>=d||(l.push(p),i+=p.length)}),{child:n,passwordStoreDefaulted:a,diagnostics:{getStderr:o(()=>Buffer.concat(l).toString("utf-8"),"getStderr"),getProcessState:o(()=>({pid:n.pid,exitCode:n.exitCode,signalCode:n.signalCode,spawnfile:n.spawnfile,spawnargs:n.spawnargs}),"getProcessState")}}},"spawnBrowser"),z=o(async e=>{const r=await fetch(`http://127.0.0.1:${e}/json/version`);if(!r.ok)throw new c(`CDP /json/version returned ${r.status} ${r.statusText}`,"cdp-metadata-invalid");const t=await r.json();if(typeof t.webSocketDebuggerUrl!="string"||typeof t.Browser!="string")throw new c(`CDP /json/version returned an unexpected payload: ${JSON.stringify(t)}`,"cdp-metadata-invalid");return{Browser:t.Browser,webSocketDebuggerUrl:t.webSocketDebuggerUrl}},"fetchCdpMetadata"),u=o((e,r)=>new Promise(t=>{if(e.exitCode!==null||e.signalCode!==null){t();return}const s=setTimeout(t,r);e.once("exit",()=>{clearTimeout(s),t()})}),"waitExitOrTimeout"),E=o((e,r=process.env)=>k.win32.join(r.SystemRoot||"C:\\Windows","System32",e),"windowsSystemExe"),b=new WeakMap,_=o((e,r=2e3)=>{if(!e)return Promise.resolve();const t=b.get(e);if(t)return t;if(e.killed)return Promise.resolve();const s=B(e,r);return b.set(e,s),s},"killBrowser"),B=o(async(e,r)=>{if(process.platform==="win32"&&typeof e.pid=="number"){T(E("taskkill.exe"),["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}),await u(e,r),h(e);return}e.kill("SIGTERM"),await u(e,r),e.exitCode===null&&e.signalCode===null&&(e.kill("SIGKILL"),await u(e,5e3)),h(e),e.unref()},"stopBrowser"),h=o(e=>{for(const r of e.stdio)r?.destroy()},"closeStdio"),R=1e4,A=o(async(e,r)=>{const t=Date.now()+r;for(;Date.now()<t;){let s;const a=await Promise.race([e.send("Target.getTargets").then(()=>!0,()=>!0),new Promise(n=>{s=setTimeout(()=>n(!1),Math.min(f,Math.max(t-Date.now(),0)))})]);if(clearTimeout(s),a)return!0}return!1},"answersWithin"),q=o(async(e,r={})=>{const t=await e();return await A(t.cdp,r.silenceMs??R)||t.child.exitCode!==null||t.child.signalCode!==null?t:(r.onRestart?.(),t.cdp.close(),await(r.kill??_)(t.child),e())},"startAnsweringBrowser");export{R as CDP_SILENCE_RESTART_MS,z as fetchCdpMetadata,_ as killBrowser,G as launchBrowser,J as launchBrowserWithPipe,W as pickFreePort,q as startAnsweringBrowser,H as waitForCdpPipe,F as waitForDebuggerEndpoint,E as windowsSystemExe};
@@ -1,5 +1,5 @@
1
- var M=Object.defineProperty;var o=(e,n)=>M(e,"name",{value:n,configurable:!0});import y from"node:fs/promises";import l from"node:path";import{checkProfileLock as C}from"../browsers/lock.js";import{CaptureError as D}from"../errors.js";const b=12e4,R=1e3,x=1500,I=[l.join("Network","Cookies"),l.join("Network","Cookies-journal"),"Cookies","Cookies-journal"],p=o((e,n=process.platform)=>n==="win32"&&typeof e=="object"&&e!==null&&"code"in e&&(e.code==="EBUSY"||e.code==="EPERM"),"isWindowsLockError"),_=o(async e=>{try{return await((await y.stat(e)).isDirectory()?await y.opendir(e):await y.open(e,"r")).close(),null}catch(n){return n.code==="ENOENT"?null:n}},"probeReadable"),L=o((e,n,a,u=b)=>{const i=e.browserDisplayName,c=e.profileDisplayName,{relativePath:s,code:f,browserRunning:m}=n,h=l.win32.basename(e.binaryPath),w=Math.round(u/6e4);return a==="wait"?m?[`${i} is still running, so Windows keeps ${s} locked.`,`Quit ${i} completely now (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit). The capture continues automatically once it has closed \u2014 waiting up to ${w} minutes (Ctrl+C to cancel).`].join(`
2
- `):`${s} is locked by another program. Waiting up to ${w} minutes for it to be released (Ctrl+C to cancel).`:m?[`Can't capture ${i} / ${c}: ${s} is locked (${f}) because ${i} is still running.`,`On Windows, ${i} keeps its cookie database locked while it runs, including in the background after its last window is closed.`,`Quit ${i} completely (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit; end any leftover ${h} processes in Task Manager), then re-run this command.`,'To stop it running in the background, turn off "Continue running background apps" under Settings \u2192 System.'].join(`
3
- `):[`Can't capture ${i} / ${c}: ${s} is locked (${f}) by another program.`,`${i} is not running, but antivirus, backup or cloud-sync software can hold browser files open for a while. Wait a few seconds and re-run this command; if it keeps failing, restart Windows and try again.`].join(`
4
- `)},"formatProfileLockedMessage"),W=o((e,n)=>[`Can't capture ${e.browserDisplayName} / ${e.profileDisplayName}: Windows denied access to ${n} (EPERM).`,`Either your Windows account can't read this file, or another program is holding it (antivirus, backup or cloud-sync software, or ${e.browserDisplayName} itself if it is still running).`,`Quit ${e.browserDisplayName} completely, wait a few seconds and re-run this command. If it keeps failing, check that your Windows account can read the files in this browser profile.`].join(`
5
- `),"formatAccessDeniedMessage"),P=o((e,n)=>{const a=n.platform??process.platform,u=n.probe??_,i=n.isBrowserRunning??(async r=>(await C(r)).locked),c=n.sleep??(r=>new Promise(t=>setTimeout(t,r))),s=n.now??Date.now,f=n.timeoutMs??b,m=n.pollMs??R,h=n.retryDelayMs??x;let w,g=!1;const d=o(async(r,t)=>t==="EPERM"?new D(W(e,l.relative(e.userDataDir,r)),"profile-copy-failed"):new D(L(e,{relativePath:l.relative(e.userDataDir,r),browserRunning:await i(e.userDataDir),code:t},"fail"),"profile-file-locked"),"fileError"),k=o(async r=>{let t=await u(r);if(t?.code==="EPERM"&&(await c(h),t=await u(r),t?.code==="EPERM"))throw await d(r,t.code);return t},"probeWithPermissionRetry"),E=o(async r=>{if(a!=="win32")return;let t=await k(r);if(!p(t,a))return;const $=await i(e.userDataDir);if(!n.interactive){if($)throw await d(r,t.code);if(await c(h),t=await u(r),p(t,a))throw await d(r,t.code);return}for(w??=s()+f,g||(n.onWait?.({relativePath:l.relative(e.userDataDir,r),browserRunning:$,code:t.code}),g=!0);s()<w;)if(await c(m),t=await k(r),!p(t,a))return;throw await d(r,t.code)},"ensureReadable");return{ensureReadable:E,retryOnLock:o(async r=>{try{return await r()}catch(t){if(!p(t,a))throw t;await E(t.path??e.profilePath)}try{return await r()}catch(t){throw p(t,a)?await d(t.path??e.profilePath,t.code):t}},"retryOnLock")}},"createLockGate");export{I as COOKIE_DB_FILES,R as LOCK_POLL_MS,x as LOCK_RETRY_DELAY_MS,b as LOCK_WAIT_TIMEOUT_MS,P as createLockGate,W as formatAccessDeniedMessage,L as formatProfileLockedMessage,p as isWindowsLockError,_ as probeReadable};
1
+ var C=Object.defineProperty;var i=(e,n)=>C(e,"name",{value:n,configurable:!0});import g from"node:fs/promises";import l from"node:path";import{checkProfileLock as R}from"../browsers/lock.js";import{CaptureError as b}from"../errors.js";import{terminalSafe as a}from"../utils/terminal.js";const M=12e4,x=1e3,_=1500,B=[l.join("Network","Cookies"),l.join("Network","Cookies-journal"),"Cookies","Cookies-journal"],f=i((e,n=process.platform)=>n==="win32"&&typeof e=="object"&&e!==null&&"code"in e&&(e.code==="EBUSY"||e.code==="EPERM"),"isWindowsLockError"),L=i(async e=>{try{return await((await g.stat(e)).isDirectory()?await g.opendir(e):await g.open(e,"r")).close(),null}catch(n){return n.code==="ENOENT"?null:n}},"probeReadable"),W=i((e,n,s,w=M)=>{const o=a(e.browserDisplayName),u=a(e.profileDisplayName),c=a(n.relativePath),m=a(n.code),{browserRunning:h}=n,y=a(l.win32.basename(e.binaryPath)),d=Math.round(w/6e4);return s==="wait"?h?[`${o} is still running, so Windows keeps ${c} locked.`,`Quit ${o} completely now (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit). The capture continues automatically once it has closed \u2014 waiting up to ${d} minutes (Ctrl+C to cancel).`].join(`
2
+ `):`${c} is locked by another program. Waiting up to ${d} minutes for it to be released (Ctrl+C to cancel).`:h?[`Can't capture ${o} / ${u}: ${c} is locked (${m}) because ${o} is still running.`,`On Windows, ${o} keeps its cookie database locked while it runs, including in the background after its last window is closed.`,`Quit ${o} completely (menu \u2192 Exit, or right-click its icon in the taskbar notification area \u2192 Exit; end any leftover ${y} processes in Task Manager), then re-run this command.`,'To stop it running in the background, turn off "Continue running background apps" under Settings \u2192 System.'].join(`
3
+ `):[`Can't capture ${o} / ${u}: ${c} is locked (${m}) by another program.`,`${o} is not running, but antivirus, backup or cloud-sync software can hold browser files open for a while. Wait a few seconds and re-run this command; if it keeps failing, restart Windows and try again.`].join(`
4
+ `)},"formatProfileLockedMessage"),N=i((e,n)=>[`Can't capture ${a(e.browserDisplayName)} / ${a(e.profileDisplayName)}: Windows denied access to ${a(n)} (EPERM).`,`Either your Windows account can't read this file, or another program is holding it (antivirus, backup or cloud-sync software, or ${a(e.browserDisplayName)} itself if it is still running).`,`Quit ${a(e.browserDisplayName)} completely, wait a few seconds and re-run this command. If it keeps failing, check that your Windows account can read the files in this browser profile.`].join(`
5
+ `),"formatAccessDeniedMessage"),K=i((e,n)=>{const s=n.platform??process.platform,w=n.probe??L,o=n.isBrowserRunning??(async r=>(await R(r)).locked),u=n.sleep??(r=>new Promise(t=>setTimeout(t,r))),c=n.now??Date.now,m=n.timeoutMs??M,h=n.pollMs??x,y=n.retryDelayMs??_;let d,E=!1;const p=i(async(r,t)=>t==="EPERM"?new b(N(e,l.relative(e.userDataDir,r)),"profile-copy-failed"):new b(W(e,{relativePath:l.relative(e.userDataDir,r),browserRunning:await o(e.userDataDir),code:t},"fail"),"profile-file-locked"),"fileError"),k=i(async r=>{let t=await w(r);if(t?.code==="EPERM"&&(await u(y),t=await w(r),t?.code==="EPERM"))throw await p(r,t.code);return t},"probeWithPermissionRetry"),$=i(async r=>{if(s!=="win32")return;let t=await k(r);if(!f(t,s))return;const D=await o(e.userDataDir);if(!n.interactive){if(D)throw await p(r,t.code);if(await u(y),t=await w(r),f(t,s))throw await p(r,t.code);return}for(d??=c()+m,E||(n.onWait?.({relativePath:l.relative(e.userDataDir,r),browserRunning:D,code:t.code}),E=!0);c()<d;)if(await u(h),t=await k(r),!f(t,s))return;throw await p(r,t.code)},"ensureReadable");return{ensureReadable:$,retryOnLock:i(async r=>{try{return await r()}catch(t){if(!f(t,s))throw t;await $(t.path??e.profilePath)}try{return await r()}catch(t){throw f(t,s)?await p(t.path??e.profilePath,t.code):t}},"retryOnLock")}},"createLockGate");export{B as COOKIE_DB_FILES,x as LOCK_POLL_MS,_ as LOCK_RETRY_DELAY_MS,M as LOCK_WAIT_TIMEOUT_MS,K as createLockGate,N as formatAccessDeniedMessage,W as formatProfileLockedMessage,f as isWindowsLockError,L as probeReadable};
@@ -1,6 +1,8 @@
1
- var d=Object.defineProperty;var s=(t,e)=>d(t,"name",{value:e,configurable:!0});import{green as f,red as m}from"../utils/ansi.js";import{isAgentEndResult as p}from"../agent/types.js";const h=/\b(log[- _]?in|sign[- _]?in|sign[- _]?up|authenticate|log on)/i,b=s(t=>h.test(t),"hasLoginIntent"),k=s(t=>{if(!t)return;const e=t.trim();return e||void 0},"normalizeRationale"),A=s((t,e)=>{const n=[];return e.username&&n.push(`USERNAME=${e.username}`),e.password&&n.push(`PASSWORD=${e.password}`),n.length===0?t:`Credentials available for this task (do not echo back):
1
+ var d=Object.defineProperty;var s=(t,e)=>d(t,"name",{value:e,configurable:!0});import{green as m,red as p}from"../utils/ansi.js";import{isAgentEndResult as h}from"../agent/types.js";import{terminalSafe as g}from"../utils/terminal.js";const y=/\b(log[- _]?in|sign[- _]?in|sign[- _]?up|authenticate|log on)/i,A=s(t=>y.test(t),"hasLoginIntent"),R=s(t=>{if(typeof t!="string")return;const e=t.trim();return e||void 0},"normalizeRationale"),S=s((t,e)=>{const n=[];return e.username&&n.push(`USERNAME=${e.username}`),e.password&&n.push(`PASSWORD=${e.password}`),n.length===0?t:`Credentials available for this task (do not echo back):
2
2
  ${n.join(`
3
3
  `)}
4
4
 
5
- `+t},"withCredentials"),g=s((t,e)=>{const n=typeof t=="string"?t:t===null||typeof t!="object"?String(t):JSON.stringify(t);return n.length>e?`${n.slice(0,e-1)}\u2026`:n},"previewValue"),_=/^(pass(word|code)?|secret|token|auth(orization)?|cookie|credentials?|api[-_]?key|otp|mfa|text|value)$/i,R=s((t,e=60)=>{if(!t||typeof t!="object")return"";const n=t;if(Array.isArray(n.commands)){const o=n.commands;return`${o.length} cmds: ${o.map(i=>i.method??"?").join(" \u2192 ")}`.slice(0,e)}const r=Object.entries(n).filter(([,o])=>o!==void 0);if(r.length===0)return"";const l=[];let a=0;for(const[o,i]of r){const u=_.test(o)?"[REDACTED]":g(i,30),c=`${o}=${u}`;if(a+c.length+2>e)break;l.push(c),a+=c.length+2}return l.join(" ")},"summarizeParams"),j=s((t,e)=>{const n=e&&typeof e=="object"?e:{};if(t==="browserless_skill")return{method:"skill",params:{id:n.id}};if(t==="browserless_agent"){const r=n.commands;return Array.isArray(r)&&r.length>0?{method:"commands",params:{commands:r}}:{method:String(n.method??"agent"),params:n.params}}return{method:t??"?",params:e}},"unwrapToolCall"),S=s(t=>{if(!p(t.result))return"";const e=t.result,n=[`Result: ${e.success?f("success"):m("failed")}`];return typeof e.reason_code=="string"&&n.push(` reason_code: ${e.reason_code}`),typeof e.final_url=="string"&&n.push(` final_url: ${e.final_url}`),typeof e.evidence=="string"&&n.push(` evidence: ${e.evidence}`),n.join(`
6
- `)},"formatEndResult");export{S as formatEndResult,b as hasLoginIntent,k as normalizeRationale,R as summarizeParams,j as unwrapToolCall,A as withCredentials};
5
+ `+t},"withCredentials"),b=s((t,e)=>{const n=typeof t=="string"?t:t===null||typeof t!="object"?String(t):JSON.stringify(t),o=[...n];return o.length>e?`${o.slice(0,e-1).join("")}\u2026`:n},"previewValue"),_=/^(pass(word|code)?|secret|token|auth(orization)?|cookie|credentials?|api[-_]?key|otp|mfa|text|value)$/i,w=s((t,e=60)=>{if(!t||typeof t!="object")return"";const n=t;if(Array.isArray(n.commands)){const r=n.commands;return[...`${r.length} cmds: ${r.map(i=>i&&typeof i=="object"&&"method"in i&&typeof i.method=="string"?i.method:"?").join(" \u2192 ")}`].slice(0,e).join("")}const o=Object.entries(n).filter(([,r])=>r!==void 0);if(o.length===0)return"";const c=[];let l=0;for(const[r,a]of o){const i=_.test(r)?"[REDACTED]":b(a,30),u=`${r}=${i}`,f=[...u].length;if(l+f+2>e)break;c.push(u),l+=f+2}return c.join(" ")},"summarizeParams"),N=s((t,e)=>{const n=e&&typeof e=="object"?e:{};if(t==="browserless_skill")return{method:"skill",params:{id:n.id}};if(t==="browserless_agent"){const o=n.commands;return Array.isArray(o)&&o.length>0?{method:"commands",params:{commands:o}}:{method:typeof n.method=="string"?n.method:"agent",params:n.params}}return{method:typeof t=="string"?t:"?",params:e}},"unwrapToolCall"),x=s(t=>{if(!h(t.result))return"";const e=t.result,n=[`Result: ${e.success?m("success"):p("failed")}`];for(const o of["reason_code","final_url","evidence"])if(typeof e[o]=="string"){const c=` ${o}: `;n.push(c+g(e[o],{preserveLayout:o==="evidence"}).replaceAll(`
6
+ `,`
7
+ ${" ".repeat(c.length)}`))}return n.join(`
8
+ `)},"formatEndResult");export{x as formatEndResult,A as hasLoginIntent,R as normalizeRationale,w as summarizeParams,N as unwrapToolCall,S as withCredentials};
@@ -1,27 +1,8 @@
1
- var _=Object.defineProperty;var p=(t,e)=>_(t,"name",{value:e,configurable:!0});import{resolveProfile as v}from"../browsers/discover.js";import{captureFromProfile as C}from"../capture/index.js";import{applyOnlyFilter as F,mergeExclusionPatterns as B,normalizeExclusion as y}from"../capture/exclusion.js";import{readConfig as A}from"../config/store.js";import{ensureTermsAccepted as I,isCi as R}from"../auth/disclaimer.js";import{formatProfileLockedMessage as P}from"../capture/profile-lock.js";import{UsageError as T}from"../errors.js";import{version as L}from"../version.js";import{collectRepeated as b,parseNonNegativeInt as z}from"./client.js";import{formatBytes as u,measureOriginSizes as G,SERVER_ARTIFACT_CAP_BYTES as x,trimStateToFit as M}from"./trim-state.js";const j=p((t,e)=>t===!0&&!e,"captureIsInteractive"),H=p((t,e)=>{const o={copying:"copying profile data\u2026",launching:"launching headless browser\u2026","waiting-for-debugger":"waiting for browser to be ready\u2026"};let s="",d=0;return r=>{if(r.phase!=="done"){if(r.phase==="waiting-for-unlock"){P(t,r,"wait").split(`
2
- `).forEach(e);return}if(r.phase==="capturing-origins"){if(r.attempted===0){s!=="capturing-origins"&&(s="capturing-origins",e("capturing per-origin storage\u2026"));return}if(!(r.attempted===r.total)&&r.attempted-d<5)return;d=r.attempted;const i=r.origin.length>50?r.origin.slice(0,47)+"\u2026":r.origin;e(` ${r.attempted}/${r.total} ${i}`);return}r.phase!==s&&(s=r.phase,e(o[r.phase]??r.phase))}}},"createProgressRenderer"),ae=p((t,e={})=>{const l=e.sourceOptional?t.option.bind(t):t.requiredOption.bind(t),o=e.sourceOptional?". Optional here \u2014 read from the profile's stored settings when omitted":"";return l("--browser <key>",`Source browser key (chrome / brave / edge / ...) or display name${o}`),l("--profile <name>",`Source profile display name or directory (e.g. "Personal", "Default")${o}`),t.option("--exclude-domain <domain>","Append a domain to the exclusion list for this run (repeatable)",b).option("--no-default-excludes","Skip the persistent exclusion list for this run").option("--accept-terms","Pre-accept the liability disclaimer").option("--terms-ttl-days <n>","Override the disclaimer re-prompt TTL for this run").option("--password-store <store>","Linux only: --password-store value to pass through to the headless launch (basic / gnome-libsecret / kwallet5 / ...)").option("--auto-fit","If the captured artifact exceeds the 2 MB server cap, drop the heaviest origins (largest serialized contribution first) until it fits").option("--keep-domain <domain>","Domain that --auto-fit must never drop (suffix-match, same syntax as --exclude-domain; repeatable)",b).option("--only-domain <domain>","Capture only cookies / origins matching this domain \u2014 discard everything else (suffix-match; repeatable; applies after --exclude-domain)",b)},"addCaptureFlags"),U=p(t=>{if(t.length>0&&!t.some(e=>y(e)!==null))throw new T(`--only-domain: no valid domain pattern in ${JSON.stringify(t)}. Use a hostname like "example.com" or "*.example.com".`,"invalid-only-domain")},"validateOnlyDomain"),D=100,Y=253,O=255,N=8*1024,J=/[$`\\!\u0000-\u001f\u007f]/,K=/^[A-Za-z0-9*._-]+$/,$=p((t,e)=>{process.stderr.write(` \u2192 Not storing ${t} for refresh (${e}); a later flagless \`profile refresh\` of this profile will not replay it
3
- `)},"warnDropped"),X=p(t=>{const e=`they serialize past the server's ${N}-byte limit`;process.stderr.write(t==="upload"?` \u2192 Not storing any capture settings (${e}); a later flagless \`profile refresh\` of this profile will have nothing to replay
1
+ var v=Object.defineProperty;var l=(t,e)=>v(t,"name",{value:e,configurable:!0});import{resolveProfile as F}from"../browsers/discover.js";import{captureFromProfile as R}from"../capture/index.js";import{applyOnlyFilter as A,mergeExclusionPatterns as B,normalizeExclusion as x}from"../capture/exclusion.js";import{readConfig as I}from"../config/store.js";import{ensureTermsAccepted as P,isCi as L}from"../auth/disclaimer.js";import{formatProfileLockedMessage as z}from"../capture/profile-lock.js";import{CDP_SILENCE_RESTART_MS as M}from"../capture/launch.js";import{UsageError as N}from"../errors.js";import{version as G}from"../version.js";import{terminalSafe as E}from"../utils/terminal.js";import{collectRepeated as k,parseNonNegativeInt as j}from"./client.js";import{formatBytes as m,measureOriginSizes as H,SERVER_ARTIFACT_CAP_BYTES as D,trimStateToFit as U}from"./trim-state.js";const Y=l((t,e)=>t===!0&&!e,"captureIsInteractive"),K=l((t,e)=>{const o={copying:"copying profile data\u2026",launching:"launching headless browser\u2026","waiting-for-debugger":"waiting for browser to be ready\u2026","restarting-browser":`browser did not respond in ${M/1e3}s; restarting it\u2026`};let r="",d=0;return i=>{if(i.phase!=="done"){if(i.phase==="waiting-for-unlock"){z(t,i,"wait").split(`
2
+ `).forEach(e);return}if(i.phase==="capturing-origins"){if(i.attempted===0){r!=="capturing-origins"&&(r="capturing-origins",e("capturing per-origin storage\u2026"));return}if(!(i.attempted===i.total)&&i.attempted-d<5)return;d=i.attempted;const u=i.origin.length>50?i.origin.slice(0,47)+"\u2026":i.origin;e(` ${i.attempted}/${i.total} ${u}`);return}i.phase!==r&&(r=i.phase,e(o[i.phase]??i.phase))}}},"createProgressRenderer"),fe=l((t,e={})=>{const a=e.sourceOptional?t.option.bind(t):t.requiredOption.bind(t),o=e.sourceOptional?". Optional here \u2014 read from the profile's stored settings when omitted":"";return a("--browser <key>",`Source browser key (chrome / brave / edge / ...) or display name${o}`),a("--profile <name>",`Source profile display name or directory (e.g. "Personal", "Default")${o}`),t.option("--exclude-domain <domain>","Append a domain to the exclusion list for this run (repeatable)",k).option("--no-default-excludes","Skip the persistent exclusion list for this run").option("--accept-terms","Pre-accept the liability disclaimer").option("--terms-ttl-days <n>","Override the disclaimer re-prompt TTL for this run").option("--password-store <store>","Linux only: --password-store value to pass through to the headless launch (basic / gnome-libsecret / kwallet5 / ...)").option("--auto-fit","If the captured artifact exceeds the 2 MB server cap, drop the heaviest origins (largest serialized contribution first) until it fits").option("--keep-domain <domain>","Domain that --auto-fit must never drop (suffix-match, same syntax as --exclude-domain; repeatable)",k).option("--only-domain <domain>","Capture only cookies / origins matching this domain \u2014 discard everything else (suffix-match; repeatable; applies after --exclude-domain)",k)},"addCaptureFlags"),X=l(t=>{if(t.length>0&&!t.some(e=>x(e)!==null))throw new N(`--only-domain: no valid domain pattern in ${JSON.stringify(t)}. Use a hostname like "example.com" or "*.example.com".`,"invalid-only-domain")},"validateOnlyDomain"),$=100,q=253,_=255,C=8*1024,J=/[$`\\!\u0000-\u001f\u007f]/,V=/^[A-Za-z0-9*._-]+$/,S=l((t,e)=>{process.stderr.write(` \u2192 Not storing ${t} for refresh (${e}); a later flagless \`profile refresh\` of this profile will not replay it
3
+ `)},"warnDropped"),Z=l(t=>{const e=`they serialize past the server's ${C}-byte limit`;process.stderr.write(t==="upload"?` \u2192 Not storing any capture settings (${e}); a later flagless \`profile refresh\` of this profile will have nothing to replay
4
4
  `:` \u2192 Not updating the stored capture settings (${e}); whatever this profile already had is left as it was, so it no longer matches this run and a later flagless \`profile refresh\` will not reflect these filters. Shorten the domain lists to update them
5
- `)},"warnOverCap"),E=p((t,e)=>{const l=e?.trim();if(l){if(J.test(l)){$(`--${t}`,"it contains characters a shell would interpret");return}if(l.length>O){$(`--${t}`,`it exceeds ${O} characters`);return}return l}},"safeScalar"),k=p((t,e,l=!1)=>{const o=[...new Set((e??[]).map(d=>y(d)).filter(d=>d!==null))],s=o.filter(d=>d.length<=Y&&K.test(d));return s.length<o.length&&$(`${o.length-s.length} of ${o.length} --${t} patterns`,"the server only stores plain hostname patterns"),s.length?(s.length>D&&$(`${s.length-D} of ${s.length} --${t} patterns`,`the server stores at most ${D}`),s.slice(0,D)):l&&!(e??[]).length?[]:void 0},"safeDomains"),h=p((t,e)=>e===void 0?{}:{[t]:e},"withKey"),le={browser:"browser",profile:"profile",excludeDomains:"excludeDomain",onlyDomains:"onlyDomain",keepDomains:"keepDomain",autoFit:"autoFit",passwordStore:"passwordStore"},de=p((t,e,l)=>{const o={...h("browser",E("browser",t.browser)),...h("profile",E("profile",t.profile)),...h("excludeDomains",k("exclude-domain",e.excludedDomains,t.defaultExcludes===!1)),...h("onlyDomains",k("only-domain",t.onlyDomain)),...h("keepDomains",k("keep-domain",t.keepDomain)),...t.autoFit?{autoFit:!0}:{},...h("passwordStore",E("password-store",t.passwordStore)),cliVersion:L};if(Buffer.byteLength(JSON.stringify(o),"utf8")>N){X(l);return}return o},"buildCaptureSettings"),q=p(t=>{(t??[]).filter(e=>y(e)===null).forEach(e=>{process.stderr.write(` ! --exclude-domain ${JSON.stringify(e)} is not a usable domain pattern \u2014 nothing was excluded for it
6
- `)})},"warnUnusableExcludes"),pe=p((t,e)=>{if(!e)return t;const l=t.defaultExcludes===!1,o=(t.excludeDomain??[]).some(d=>y(d)!==null),s=!o&&e.excludeDomains!==void 0;return{...t,browser:t.browser??e.browser,profile:t.profile??e.profile,passwordStore:t.passwordStore??e.passwordStore,excludeDomain:o?t.excludeDomain:l?[]:e.excludeDomains,onlyDomain:t.onlyDomain??e.onlyDomains,keepDomain:t.keepDomain??e.keepDomains,autoFit:t.autoFit??e.autoFit,defaultExcludes:s?!1:t.defaultExcludes}},"mergeStoredSettings"),ce=p((t,e,l={})=>{if(!e)return;const o=p(i=>process.stderr.write(`${i}
7
- `),"w"),s=l.userOptedOut===!0;o("> Refreshing with these effective settings:"),t.browser&&o(` --browser ${t.browser}`),t.profile&&o(` --profile ${t.profile}`);const d=(t.excludeDomain??[]).filter(i=>y(i)!==null);d.length&&o(` --exclude-domain ${d.join(", ")}`),t.onlyDomain?.length&&(o(` --only-domain ${t.onlyDomain.join(", ")}`),o(" ! only these domains are captured \u2014 everything else in the saved"),o(" profile is replaced, not kept")),t.keepDomain?.length&&o(` --keep-domain ${t.keepDomain.join(", ")}`),t.autoFit&&o(" --auto-fit (only acts if the capture exceeds the 2 MB cap)"),t.passwordStore&&o(` --password-store ${t.passwordStore}`),s&&o(" --no-default-excludes");const r=s&&!d.length,f=e.excludeDomains?.length;r&&f&&(o(` ! --no-default-excludes drops the ${f} stored exclusion pattern(s) for this run,`),o(" and re-pass --exclude-domain if you want to keep them.")),r?(o(" ! Unless the settings exceed the 8 KB cap (reported after the capture), the"),o(" refreshed profile is stored with NO exclusion list, so later flagless refreshes"),o(" replay 'exclude nothing' and stop applying this machine's config.")):s?(o(" ! --no-default-excludes is in force: ONLY the --exclude-domain patterns above"),o(" are excluded, and this machine's own config is not applied.")):f===void 0&&(o(" (no stored exclusion list \u2014 this machine's own config applies)"),o(" This run stores the effective list on the profile, so later flagless refreshes"),o(" replay that snapshot instead of re-reading this config.")),o(" Pass --browser, --profile, --password-store or a domain flag to override."),s||(o(f===void 0?" --exclude-domain adds to this machine's config for this run; there is no stored list to replace.":" --exclude-domain replaces the stored list and re-applies this machine's config."),f&&o(" --no-default-excludes drops the stored list for good."))},"printEffectiveSettings"),fe=p(async t=>{const{flags:e,requiresDisclaimer:l}=t;if(!e.browser||!e.profile){const a=[e.browser?null:"--browser",e.profile?null:"--profile"].filter(Boolean);throw new T(`${a.join(" and ")} ${a.length>1?"are":"is"} required: this profile has no stored capture settings to read them from (it was not created by the CLI, or this server does not return them yet)`,"missing-capture-settings")}const o=await v(e.browser,e.profile);l&&await I({acceptViaFlag:!!e.acceptTerms,ttlDaysOverride:e.termsTtlDays!==void 0?z("--terms-ttl-days",e.termsTtlDays):void 0});const s=await A(),d=B(s.excluded_domains,e.excludeDomain,e.defaultExcludes===!1);U(e.onlyDomain??[]),q(e.excludeDomain),process.stderr.write(`> Capturing ${o.browserDisplayName} / ${o.profileDisplayName}
8
- `);const r=p(a=>{process.stderr.write(` ${a}
9
- `)},"writeLine"),f={profile:o,excludedDomains:d,onlyDomains:e.onlyDomain??[],passwordStoreOverride:e.passwordStore,interactive:j(process.stdin.isTTY,R()),onProgress:H(o,r)},i=await C(f);if(e.onlyDomain&&e.onlyDomain.length>0){const a=F(i.state,e.onlyDomain),m=i.state.cookies.length-a.state.cookies.length,n=i.diagnostics.originCountSkippedByOnlyDomain+a.originsDropped;(m>0||n>0)&&(i.state=a.state,i.serialized=JSON.stringify(a.state),process.stderr.write(` \u2192 --only-domain kept ${i.state.cookies.length} cookies / ${i.state.origins.length} origins; dropped ${m} cookies / ${n} origins not matching: ${e.onlyDomain.join(", ")}
10
- `))}const c=i.diagnostics,S=Buffer.byteLength(i.serialized,"utf-8");if(process.stderr.write(`> Captured ${c.cookieCountBeforeExclusion} cookies, ${c.originCountBeforeExclusion} origins in ${c.durationMs}ms (artifact: ${u(S)})
11
- `),c.cookieCountExcluded>0||c.originCountExcluded>0){const a=c.excludedDomains.length?c.excludedDomains.join(", "):"(none)";process.stderr.write(` \u2192 Excluded ${c.cookieCountExcluded} cookies / ${c.originCountExcluded} origins matching: ${a}
12
- `)}if(i.capHit&&process.stderr.write(` ! Hit the per-capture origin cap \u2014 some origins may be missing
13
- `),c.failedOrigins.length>0){process.stderr.write(` ! ${c.failedOrigins.length} origin(s) failed to capture \u2014 their localStorage / IndexedDB is missing from the upload:
14
- `);for(const a of c.failedOrigins)process.stderr.write(` - ${a.origin}: ${a.error}
15
- `)}if(i.passwordStoreDefaulted&&process.stderr.write(` ! Linux password-store could not be detected \u2014 defaulted to "basic". If decryption failed, re-run with --password-store=<your store>
16
- `),S>x){const a=G(i.state),g=10;process.stderr.write(` ! artifact size ${u(S)} exceeds the ${u(x)} server cap \u2014 heaviest origins:
17
- `);for(const{origin:m,bytes:n}of a.slice(0,g))process.stderr.write(` ${u(n).padStart(10)} ${m}
18
- `);if(a.length>g&&process.stderr.write(` \u2026 and ${a.length-g} more origins below ${u(a[g].bytes)}
19
- `),e.autoFit){const m=e.keepDomain??[],n=M(i.state,x,m);if(n.dropped.length===0&&n.finalBytes<=x)process.stderr.write(` ! --auto-fit had nothing to drop \u2014 artifact unchanged
20
- `);else{if(i.state=n.state,i.serialized=n.serialized,c.failedOrigins=[...c.failedOrigins,...n.dropped.map(w=>({origin:w,error:"dropped by --auto-fit to fit under the server cap",kind:"unknown"}))],n.dropped.length>0){process.stderr.write(` --auto-fit: dropped ${n.dropped.length} origin(s), now ${u(n.finalBytes)}:
21
- `);for(const w of n.dropped)process.stderr.write(` - ${w}
22
- `)}if(n.protectedFromDrop.length>0){process.stderr.write(` --auto-fit: ${n.protectedFromDrop.length} heavy origin(s) protected by --keep-domain:
23
- `);for(const w of n.protectedFromDrop)process.stderr.write(` - ${w}
24
- `)}n.finalBytes>x&&(n.protectedFromDrop.length>0?process.stderr.write(` ! Still ${u(n.finalBytes)} after the trim \u2014 the --keep-domain origins alone exceed the cap. Remove one or more --keep-domain entries, or accept the upload will be rejected.
25
- `):process.stderr.write(` ! Even after dropping every droppable origin the artifact is still over cap. The cookies alone may be too heavy.
26
- `))}}else process.stderr.write(` Re-run with --auto-fit to drop the heaviest origins automatically (combine with --keep-domain <domain> to protect specific sites; or --only-domain <domain> to capture just those), or pass --exclude-domain <host> for each you want removed.
27
- `)}return i},"runCapture");export{le as SETTINGS_REPLAY_SOURCE,ae as addCaptureFlags,de as buildCaptureSettings,j as captureIsInteractive,H as createProgressRenderer,pe as mergeStoredSettings,ce as printEffectiveSettings,fe as runCapture,U as validateOnlyDomain,q as warnUnusableExcludes};
5
+ `)},"warnOverCap"),T=l((t,e)=>{const a=e?.trim();if(a){if(J.test(a)){S(`--${t}`,"it contains characters a shell would interpret");return}if(a.length>_){S(`--${t}`,`it exceeds ${_} characters`);return}return a}},"safeScalar"),O=l((t,e,a=!1)=>{const o=[...new Set((e??[]).map(d=>x(d)).filter(d=>d!==null))],r=o.filter(d=>d.length<=q&&V.test(d));return r.length<o.length&&S(`${o.length-r.length} of ${o.length} --${t} patterns`,"the server only stores plain hostname patterns"),r.length?(r.length>$&&S(`${r.length-$} of ${r.length} --${t} patterns`,`the server stores at most ${$}`),r.slice(0,$)):a&&!(e??[]).length?[]:void 0},"safeDomains"),g=l((t,e)=>e===void 0?{}:{[t]:e},"withKey"),ue={browser:"browser",profile:"profile",excludeDomains:"excludeDomain",onlyDomains:"onlyDomain",keepDomains:"keepDomain",autoFit:"autoFit",passwordStore:"passwordStore"},me=l((t,e,a)=>{const o={...g("browser",T("browser",t.browser)),...g("profile",T("profile",t.profile)),...g("excludeDomains",O("exclude-domain",e.excludedDomains,t.defaultExcludes===!1)),...g("onlyDomains",O("only-domain",t.onlyDomain)),...g("keepDomains",O("keep-domain",t.keepDomain)),...t.autoFit?{autoFit:!0}:{},...g("passwordStore",T("password-store",t.passwordStore)),cliVersion:G};if(Buffer.byteLength(JSON.stringify(o),"utf8")>C){Z(a);return}return o},"buildCaptureSettings"),Q=l(t=>{(t??[]).filter(e=>x(e)===null).forEach(e=>{process.stderr.write(` ! --exclude-domain "${E(e)}" is not a usable domain pattern \u2014 nothing was excluded for it
6
+ `)})},"warnUnusableExcludes"),he=l((t,e)=>{if(!e)return t;const a=t.defaultExcludes===!1,o=(t.excludeDomain??[]).some(d=>x(d)!==null),r=!o&&e.excludeDomains!==void 0;return{...t,browser:t.browser??e.browser,profile:t.profile??e.profile,passwordStore:t.passwordStore??e.passwordStore,excludeDomain:o?t.excludeDomain:a?[]:e.excludeDomains,onlyDomain:t.onlyDomain??e.onlyDomains,keepDomain:t.keepDomain??e.keepDomains,autoFit:t.autoFit??e.autoFit,defaultExcludes:r?!1:t.defaultExcludes}},"mergeStoredSettings"),ge=l((t,e,a={})=>{if(!e)return;const o=l(u=>process.stderr.write(`${E(u)}
7
+ `),"w"),r=a.userOptedOut===!0;o("> Refreshing with these effective settings:"),t.browser&&o(` --browser ${t.browser}`),t.profile&&o(` --profile ${t.profile}`);const d=(t.excludeDomain??[]).filter(u=>x(u)!==null);d.length&&o(` --exclude-domain ${d.join(", ")}`),t.onlyDomain?.length&&(o(` --only-domain ${t.onlyDomain.join(", ")}`),o(" ! only these domains are captured \u2014 everything else in the saved"),o(" profile is replaced, not kept")),t.keepDomain?.length&&o(` --keep-domain ${t.keepDomain.join(", ")}`),t.autoFit&&o(" --auto-fit (only acts if the capture exceeds the 2 MB cap)"),t.passwordStore&&o(` --password-store ${t.passwordStore}`),r&&o(" --no-default-excludes");const i=r&&!d.length,f=e.excludeDomains?.length;i&&f&&(o(` ! --no-default-excludes drops the ${f} stored exclusion pattern(s) for this run,`),o(" and re-pass --exclude-domain if you want to keep them.")),i?(o(" ! Unless the settings exceed the 8 KB cap (reported after the capture), the"),o(" refreshed profile is stored with NO exclusion list, so later flagless refreshes"),o(" replay 'exclude nothing' and stop applying this machine's config.")):r?(o(" ! --no-default-excludes is in force: ONLY the --exclude-domain patterns above"),o(" are excluded, and this machine's own config is not applied.")):f===void 0&&(o(" (no stored exclusion list \u2014 this machine's own config applies)"),o(" This run stores the effective list on the profile, so later flagless refreshes"),o(" replay that snapshot instead of re-reading this config.")),o(" Pass --browser, --profile, --password-store or a domain flag to override."),r||(o(f===void 0?" --exclude-domain adds to this machine's config for this run; there is no stored list to replace.":" --exclude-domain replaces the stored list and re-applies this machine's config."),f&&o(" --no-default-excludes drops the stored list for good."))},"printEffectiveSettings"),ye=l(async t=>{const{flags:e,requiresDisclaimer:a}=t;if(!e.browser||!e.profile){const n=[e.browser?null:"--browser",e.profile?null:"--profile"].filter(Boolean);throw new N(`${n.join(" and ")} ${n.length>1?"are":"is"} required: this profile has no stored capture settings to read them from (it was not created by the CLI, or this server does not return them yet)`,"missing-capture-settings")}const o=await F(e.browser,e.profile);a&&await P({acceptViaFlag:!!e.acceptTerms,ttlDaysOverride:e.termsTtlDays!==void 0?j("--terms-ttl-days",e.termsTtlDays):void 0});const r=await I(),d=B(r.excluded_domains,e.excludeDomain,e.defaultExcludes===!1);X(e.onlyDomain??[]),Q(e.excludeDomain);const i=l(n=>process.stderr.write(`${E(n)}
8
+ `),"w");i(`> Capturing ${o.browserDisplayName} / ${o.profileDisplayName}`);const f=l(n=>{i(` ${n}`)},"writeLine"),u={profile:o,excludedDomains:d,onlyDomains:e.onlyDomain??[],passwordStoreOverride:e.passwordStore,interactive:Y(process.stdin.isTTY,L()),onProgress:K(o,f)},p=await R(u);if(e.onlyDomain&&e.onlyDomain.length>0){const n=A(p.state,e.onlyDomain),h=p.state.cookies.length-n.state.cookies.length,s=p.diagnostics.originCountSkippedByOnlyDomain+n.originsDropped;(h>0||s>0)&&(p.state=n.state,p.serialized=JSON.stringify(n.state),i(` \u2192 --only-domain kept ${p.state.cookies.length} cookies / ${p.state.origins.length} origins; dropped ${h} cookies / ${s} origins not matching: ${e.onlyDomain.join(", ")}`))}const c=p.diagnostics,b=Buffer.byteLength(p.serialized,"utf-8");if(i(`> Captured ${c.cookieCountBeforeExclusion} cookies, ${c.originCountBeforeExclusion} origins in ${c.durationMs}ms (artifact: ${m(b)})`),c.cookieCountExcluded>0||c.originCountExcluded>0){const n=c.excludedDomains.length?c.excludedDomains.join(", "):"(none)";i(` \u2192 Excluded ${c.cookieCountExcluded} cookies / ${c.originCountExcluded} origins matching: ${n}`)}if(p.capHit&&i(" ! Hit the per-capture origin cap \u2014 some origins may be missing"),c.failedOrigins.length>0){i(` ! ${c.failedOrigins.length} origin(s) failed to capture \u2014 their localStorage / IndexedDB is missing from the upload:`);for(const n of c.failedOrigins)i(` - ${n.origin}: ${n.error}`)}if(p.passwordStoreDefaulted&&i(' ! Linux password-store could not be detected \u2014 defaulted to "basic". If decryption failed, re-run with --password-store=<your store>'),b>D){const n=H(p.state),y=10;i(` ! artifact size ${m(b)} exceeds the ${m(D)} server cap \u2014 heaviest origins:`);for(const{origin:h,bytes:s}of n.slice(0,y))i(` ${m(s).padStart(10)} ${h}`);if(n.length>y&&i(` \u2026 and ${n.length-y} more origins below ${m(n[y].bytes)}`),e.autoFit){const h=e.keepDomain??[],s=U(p.state,D,h);if(s.dropped.length===0&&s.finalBytes<=D)i(" ! --auto-fit had nothing to drop \u2014 artifact unchanged");else{if(p.state=s.state,p.serialized=s.serialized,c.failedOrigins=[...c.failedOrigins,...s.dropped.map(w=>({origin:w,error:"dropped by --auto-fit to fit under the server cap",kind:"unknown"}))],s.dropped.length>0){i(` --auto-fit: dropped ${s.dropped.length} origin(s), now ${m(s.finalBytes)}:`);for(const w of s.dropped)i(` - ${w}`)}if(s.protectedFromDrop.length>0){i(` --auto-fit: ${s.protectedFromDrop.length} heavy origin(s) protected by --keep-domain:`);for(const w of s.protectedFromDrop)i(` - ${w}`)}s.finalBytes>D&&(s.protectedFromDrop.length>0?i(` ! Still ${m(s.finalBytes)} after the trim \u2014 the --keep-domain origins alone exceed the cap. Remove one or more --keep-domain entries, or accept the upload will be rejected.`):i(" ! Even after dropping every droppable origin the artifact is still over cap. The cookies alone may be too heavy."))}}else i(" Re-run with --auto-fit to drop the heaviest origins automatically (combine with --keep-domain <domain> to protect specific sites; or --only-domain <domain> to capture just those), or pass --exclude-domain <host> for each you want removed.")}return p},"runCapture");export{ue as SETTINGS_REPLAY_SOURCE,fe as addCaptureFlags,me as buildCaptureSettings,Y as captureIsInteractive,K as createProgressRenderer,he as mergeStoredSettings,ge as printEffectiveSettings,ye as runCapture,X as validateOnlyDomain,Q as warnUnusableExcludes};
@@ -1,2 +1,2 @@
1
- var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{resolveServer as l,resolveToken as a}from"../auth/store.js";import{UsageError as c}from"../errors.js";import{KNOWN_REGIONS as v}from"../regions.js";const m=o(async e=>{const r=await l({server:e.server,region:e.region}),{token:t,source:n}=await a({flag:e.token,server:r});return{server:r,token:t,source:n}},"buildClient"),k=o((e,r)=>[...r??[],e],"collectRepeated"),p=o(e=>e.option("--server <url>","Browserless server URL").option("--region <code>",`Browserless region (${v.join(" | ")}) \u2014 shorthand for --server`),"addServerOverrideFlags"),x=o(e=>p(e.option("--token <token>","API token (overrides env / keychain / file)")).option("--json","Emit the server response as JSON"),"addClientFlags"),I=o(e=>{process.stdout.write(JSON.stringify(e,null,2)+`
2
- `)},"printJson"),g=/^\d+$/,b=o((e,r,t=0)=>{const n=o(()=>{throw new c(`${e} must be a${t>0?" positive":" non-negative"} integer (got "${r}")`,"invalid-integer-flag")},"fail");g.test(r)||n();const s=Number(r);return(!Number.isFinite(s)||!Number.isInteger(s)||s<t)&&n(),s},"parseNonNegativeInt");export{x as addClientFlags,p as addServerOverrideFlags,m as buildClient,k as collectRepeated,b as parseNonNegativeInt,I as printJson};
1
+ var i=Object.defineProperty;var o=(e,r)=>i(e,"name",{value:r,configurable:!0});import{resolveServer as l,resolveToken as a}from"../auth/store.js";import{UsageError as c}from"../errors.js";import{KNOWN_REGIONS as p}from"../regions.js";const m=o(async e=>{const r=await l({server:e.server,region:e.region}),{token:t,source:n}=await a({flag:e.token,server:r});return{server:r,token:t,source:n}},"buildClient"),h=o((e,r)=>[...r??[],e],"collectRepeated"),v=o(e=>e.option("--server <url>","Browserless server URL").option("--region <code>",`Browserless region (${p.join(" | ")}) \u2014 shorthand for --server`),"addServerOverrideFlags"),E=o(e=>v(e.option("--token <token>","API token (overrides env / keychain / file). Visible to other local users in the process list \u2014 prefer BROWSERLESS_TOKEN or `auth login`")).option("--json","Emit the server response as JSON"),"addClientFlags"),S=o(e=>{process.stdout.write(JSON.stringify(e,null,2)+`
2
+ `)},"printJson"),g=/^\d+$/,k=o((e,r,t=0)=>{const n=o(()=>{throw new c(`${e} must be a${t>0?" positive":" non-negative"} integer (got "${r}")`,"invalid-integer-flag")},"fail");g.test(r)||n();const s=Number(r);return(!Number.isFinite(s)||!Number.isInteger(s)||s<t)&&n(),s},"parseNonNegativeInt");export{E as addClientFlags,v as addServerOverrideFlags,m as buildClient,h as collectRepeated,k as parseNonNegativeInt,S as printJson};
package/build/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var n=Object.defineProperty;var t=(e,s)=>n(e,"name",{value:s,configurable:!0});import{Command as m}from"commander";import{version as a}from"./version.js";import{registerProfile as c}from"./commands/profile/index.js";import{registerAuth as p}from"./commands/auth/index.js";import{registerConfig as f}from"./commands/config/index.js";import{registerAgent as g}from"./commands/agent/index.js";import{exitCodeFor as l,UserFacingError as d}from"./errors.js";import*as o from"./telemetry/index.js";const r=new m;r.name("browserless").description("Browserless CLI \u2014 manage profiles, sessions, and more.").version(a),c(r),p(r),f(r),g(r);const i=t(e=>e.name()==="terms"&&e.parent?.name()==="profile","isProfileTerms");r.hook("preAction",(e,s)=>{if(!i(s))try{o.begin(s)}catch{}}),r.hook("postAction",async(e,s)=>{if(!i(s))try{await o.complete({status:"ok",exitCode:0})}catch{}}),r.parseAsync(process.argv).catch(async e=>{e instanceof d?process.stderr.write(`${e.message}
3
- `):e instanceof Error?process.stderr.write(`${e.stack??e.message}
4
- `):process.stderr.write(`${String(e)}
5
- `),process.exitCode=l(e);try{await o.complete(o.errorResult(e,process.exitCode))}catch{}});
2
+ var m=Object.defineProperty;var i=(e,o)=>m(e,"name",{value:o,configurable:!0});import{Command as a}from"commander";import{version as p}from"./version.js";import{registerProfile as c}from"./commands/profile/index.js";import{registerAuth as f}from"./commands/auth/index.js";import{registerConfig as g}from"./commands/config/index.js";import{registerAgent as l}from"./commands/agent/index.js";import{exitCodeFor as u,UserFacingError as d}from"./errors.js";import*as s from"./telemetry/index.js";import{terminalSafe as t}from"./utils/terminal.js";const r=new a;r.name("browserless").description("Browserless CLI \u2014 manage profiles, sessions, and more.").version(p),c(r),f(r),g(r),l(r);const n=i(e=>e.name()==="terms"&&e.parent?.name()==="profile","isProfileTerms");r.hook("preAction",(e,o)=>{if(!n(o))try{s.begin(o)}catch{}}),r.hook("postAction",async(e,o)=>{if(!n(o))try{await s.complete({status:"ok",exitCode:0})}catch{}}),r.parseAsync(process.argv).catch(async e=>{e instanceof d?process.stderr.write(`${t(e.message,{preserveLayout:!0})}
3
+ `):e instanceof Error?process.stderr.write(`${t(e.stack??e.message,{preserveLayout:!0})}
4
+ `):process.stderr.write(`${t(e,{preserveLayout:!0})}
5
+ `),process.exitCode=u(e);try{await s.complete(s.errorResult(e,process.exitCode))}catch{}});
@@ -1,11 +1,14 @@
1
- var C=Object.defineProperty;var n=(e,l)=>C(e,"name",{value:l,configurable:!0});import{stdout as y,stderr as E}from"node:process";import{buildClient as S,printJson as $}from"../../cli-utils/client.js";import{buildPrompts as _}from"../../cli-utils/prompts.js";import{ApiError as T}from"../../errors.js";import{AgentClient as A}from"../../agent/ws-client.js";import{loadHistory as P,saveHistory as B}from"../../agent/history.js";import{normalizeRationale as I,formatEndResult as M,hasLoginIntent as R,summarizeParams as L,unwrapToolCall as j,withCredentials as v}from"../../cli-utils/agent-format.js";import{colorsFor as h}from"../../utils/ansi.js";import{Spinner as z}from"../../utils/spinner.js";const F={buildClient:S,makeClient:n(e=>new A(e),"makeClient")},b=n(e=>new Promise(l=>{const o=n(()=>{e.off("end",p),e.off("awaiting_input",s),e.off("agent_error",d),e.off("close",a)},"cleanup"),p=n(m=>{o(),l({kind:"end",payload:m})},"onEnd"),s=n(m=>{o(),l({kind:"awaiting_input",payload:m})},"onAwait"),d=n(m=>{o(),l({kind:"error",payload:m})},"onErr"),a=n(()=>{o(),l({kind:"closed"})},"onClose");e.once("end",p),e.once("awaiting_input",s),e.once("agent_error",d),e.once("close",a)}),"waitForTurnEnd"),G=n((e,l)=>{const o=l?E:y,p=h(o),s=new z({out:o}),d=new Map;let a="idle";const m=n(()=>{a==="status"&&(s.clear(),o.write(`
2
- `))},"ensureTextStart"),g=n(()=>{a==="text"&&o.write(`
3
- `),a==="status"&&s.clear()},"ensureLineEndedBeforeBlock");e.on("data",t=>{typeof t.text!="string"||t.text.length===0||(m(),a="text",o.write(t.text))});const k=n((t,r)=>{const c=t&&t!=="commands"?p.gray(t):"",i=r?p.dim(r):"";return[c,i].filter(Boolean).join(" ")},"formatTail"),f=n((t,r,u,c)=>{const i=k(u,c),w=r?`${r}: `:"";return`${t}${w}${i}`},"formatLine");return e.on("tool_call",t=>{a==="text"&&o.write(`
4
- `);const{method:r,params:u}=j(t.method,t.params),c=L(u),i=I(t.rationale);d.set(t.id??"",{rationale:i,summary:c,method:r}),a="status",s.set(f("",i,r,c))}),e.on("tool_result",t=>{const r=d.get(t.id??"")??{summary:"",method:"?"};d.delete(t.id??"");const u=t.ok?p.green("\u2713"):p.red("\u2717");s.done(f(`${u} `,r.rationale,r.method,r.summary)),a="idle"}),e.on("usage",()=>{}),{printEnd:n(t=>{if(g(),a="idle",l){$({type:"end",result:t.result??null});return}const r=M(t);o.write(r?`
5
- ${r}
1
+ var S=Object.defineProperty;var r=(e,c)=>S(e,"name",{value:c,configurable:!0});import{stdout as x,stderr as E}from"node:process";import{buildClient as _,printJson as A}from"../../cli-utils/client.js";import{buildPrompts as P}from"../../cli-utils/prompts.js";import{ApiError as T}from"../../errors.js";import{AgentClient as $}from"../../agent/ws-client.js";import{loadHistory as L,saveHistory as v}from"../../agent/history.js";import{normalizeRationale as I,formatEndResult as R,hasLoginIntent as B,summarizeParams as z,unwrapToolCall as F,withCredentials as G}from"../../cli-utils/agent-format.js";import{colorsFor as h}from"../../utils/ansi.js";import{Spinner as H}from"../../utils/spinner.js";import{terminalSafe as k}from"../../utils/terminal.js";const M={buildClient:_,makeClient:r(e=>new $(e),"makeClient")},b=r(e=>new Promise(c=>{const n=r(()=>{e.off("end",d),e.off("awaiting_input",o),e.off("agent_error",l),e.off("close",s)},"cleanup"),d=r(p=>{n(),c({kind:"end",payload:p})},"onEnd"),o=r(p=>{n(),c({kind:"awaiting_input",payload:p})},"onAwait"),l=r(p=>{n(),c({kind:"error",payload:p})},"onErr"),s=r(()=>{n(),c({kind:"closed"})},"onClose");e.once("end",d),e.once("awaiting_input",o),e.once("agent_error",l),e.once("close",s)}),"waitForTurnEnd"),j=r((e,c)=>{const n=c?E:x,d=h(n),o=new H({out:n}),l=new Map;let s="idle";const p=r(()=>{s==="status"&&(o.clear(),n.write(`
2
+ `))},"ensureTextStart"),g=r(()=>{s==="text"&&n.write(`
3
+ `),s==="status"&&o.clear()},"ensureLineEndedBeforeBlock");e.on("data",t=>{typeof t.text!="string"||t.text.length===0||(p(),s="text",n.write(k(t.text.replace(/\r$/,""),{preserveLayout:!0})))});const m=r(({rationale:t,method:a,summary:w})=>{const i=[];return t&&i.push({text:`${t}: `}),a&&a!=="commands"&&(i.push({text:a,style:d.gray}),w&&i.push({text:" "})),w&&i.push({text:w,style:d.dim}),i},"formatLine");return e.on("tool_call",t=>{s==="text"&&n.write(`
4
+ `);const{method:a,params:w}=F(t.method,t.params),i=I(t.rationale),u={rationale:i?k(i):void 0,summary:k(z(w)),method:k(a)};l.set(t.id??"",u),s="status",o.set(m(u))}),e.on("tool_result",t=>{const a=l.get(t.id??"")??{method:"?",summary:""};l.delete(t.id??""),s==="text"&&n.write(`
5
+ `),o.done([{text:t.ok?"\u2713":"\u2717",style:t.ok?d.green:d.red},{text:" "},...m(a)]),s="idle"}),e.on("usage",()=>{}),{printEnd:r(t=>{if(g(),s="idle",c){A({type:"end",result:t.result??null});return}const a=R(t);n.write(a?`
6
+ ${a}
6
7
  `:`
7
- `)},"printEnd"),clearStatus:n(()=>{g(),a="idle"},"clearStatus"),dispose:n(()=>s.clear(),"dispose")}},"createRenderer"),H=n((e,l)=>{let o=0;const p=n(()=>{if(o+=1,o===1){l(),process.stderr.write(h(process.stderr).gray(`
8
+ `)},"printEnd"),clearStatus:r(()=>{g(),s="idle"},"clearStatus"),dispose:r(()=>o.clear(),"dispose")}},"createRenderer"),D=r((e,c)=>{let n=0;const d=r(()=>{if(n+=1,n===1){c(),process.stderr.write(h(process.stderr).gray(`
8
9
  (stop sent \u2014 press Ctrl-C again to exit)
9
- `));try{e.stop()}catch{}}else process.exit(130)},"handler"),s=["SIGINT","SIGBREAK"];return s.forEach(d=>process.on(d,p)),()=>s.forEach(d=>process.off(d,p))},"installSigint"),Y=n(async(e,l,o=F)=>{const p=!!e.json,s=await o.buildClient(e),d=p?E:y;d.write(h(d).dim(`agent \u2192 ${s.server} (token from ${s.source})
10
- `));const a=e.history!==!1&&!l,m=a?await P().catch(()=>[]):[],k=l??_(m,a?u=>B(u):async()=>{},d),f=o.makeClient({server:s.server,token:s.token});await f.connect();const t=G(f,p),r=H(f,t.clearStatus);try{let u=!0;for(;;){let c;if(u&&e.prompt)c=e.prompt;else{try{c=await k.line("> ")}catch{break}if(c===""){if(u)continue;break}}if(u&&R(c))try{const w=await k.linePrivate("Username (blank to skip): "),x=w?await k.password("Password (blank to skip): "):"";c=v(c,{username:w,password:x})}catch{break}u?f.start(c):f.send(c),u=!1;let i=await b(f);for(;i.kind==="awaiting_input";){const w=await k.linePrivate("Enter code: ");if(!w){i={kind:"closed"};break}f.send(w),i=await b(f)}if(i.kind==="closed")break;if(i.kind==="error"){if(t.clearStatus(),process.stderr.write(`error: ${i.payload.message??i.payload.code??"unknown"}
11
- `),i.payload.retryable!==!0)throw new T("Agent session ended with an error.",0,void 0,"agent-session-error");continue}t.printEnd(i.payload)}}finally{r(),t.dispose(),f.close()}},"runAgentChat");export{Y as runAgentChat};
10
+ `));try{e.stop()}catch{}}else process.exit(130)},"handler"),o=["SIGINT","SIGBREAK"];return o.forEach(l=>process.on(l,d)),()=>o.forEach(l=>process.off(l,d))},"installSigint"),O=r(async(e,c,n=M)=>{const d=!!e.json,o=await n.buildClient(e),l=d?E:x;l.write(h(l).dim(`agent \u2192 ${o.server} (token from ${o.source})
11
+ `));const s=e.history!==!1&&!c,p=s?await L().catch(()=>[]):[],m=c??P(p,s?i=>v(i):async()=>{},l),t=n.makeClient({server:o.server,token:o.token});await t.connect();const a=j(t,d),w=D(t,a.clearStatus);try{let i=!0;for(;;){let u;if(i&&e.prompt)u=e.prompt;else{try{u=await m.line("> ")}catch{break}if(u===""){if(i)continue;break}}if(i&&B(u))try{const y=await m.linePrivate("Username (blank to skip): "),C=y?await m.password("Password (blank to skip): "):"";u=G(u,{username:y,password:C})}catch{break}i?t.start(u):t.send(u),i=!1;let f=await b(t);for(;f.kind==="awaiting_input";){const y=await m.linePrivate("Enter code: ");if(!y){f={kind:"closed"};break}t.send(y),f=await b(t)}if(f.kind==="closed")break;if(f.kind==="error"){if(a.clearStatus(),process.stderr.write(`error: ${k(f.payload.message||f.payload.code||"unknown",{preserveLayout:!0}).replaceAll(`
12
+ `,`
13
+ `)}
14
+ `),f.payload.retryable!==!0)throw new T("Agent session ended with an error.",0,void 0,"agent-session-error");continue}a.printEnd(f.payload)}}finally{w(),a.dispose(),t.close()}},"runAgentChat");export{O as runAgentChat};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var t=(o,e)=>c(o,"name",{value:e,configurable:!0});import{resolveServer as d,persistToken as f}from"../../auth/store.js";import{validateToken as m}from"../../api/auth.js";import{addServerOverrideFlags as k}from"../../cli-utils/client.js";import{PreconditionError as i}from"../../errors.js";import{recordToken as l}from"../../telemetry/token-cache.js";const v=t(async()=>{const o=[];for await(const e of process.stdin)o.push(Buffer.from(e));return Buffer.concat(o).toString("utf-8").trim()},"readFromStdin"),g=t(async(o,e)=>{const r=await d({server:e.server,region:e.region});let n=o?.trim();if(!n){if(process.stdin.isTTY)throw new i("Pass the token as an argument or pipe it via stdin: `echo $TOKEN | browserless auth login`","no-token");n=await v()}if(!n)throw new i("No token provided.","no-token");if(!await m({server:r,token:n}))throw new i(`Token rejected by ${r} \u2014 double-check it and retry.`,"invalid-token");l({token:n,server:r});const{mode:a,warning:s}=await f({server:r,token:n});console.log(a==="keychain"?`\u2713 Token saved to OS keychain for ${r}`:`\u2713 Token saved to ~/.browserless/config.json for ${r}`),s&&console.log(`! ${s}`)},"action"),$=t(o=>{const e=o.command("login [token]").description("Validate and persist an API token (reads from stdin if no argument is given)");k(e).action(g)},"registerAuthLogin");export{$ as registerAuthLogin};
1
+ var c=Object.defineProperty;var n=(o,e)=>c(o,"name",{value:e,configurable:!0});import{resolveServer as d,persistToken as f}from"../../auth/store.js";import{validateToken as l}from"../../api/auth.js";import{addServerOverrideFlags as m}from"../../cli-utils/client.js";import{PreconditionError as i}from"../../errors.js";import{recordToken as h}from"../../telemetry/token-cache.js";const k=n(async()=>{const o=[];for await(const e of process.stdin)o.push(Buffer.from(e));return Buffer.concat(o).toString("utf-8").trim()},"readFromStdin"),p=n(async(o,e)=>{const r=await d({server:e.server,region:e.region});let t=o?.trim();if(!t){if(process.stdin.isTTY)throw new i("Pass the token as an argument or pipe it via stdin: `echo $TOKEN | browserless auth login`","no-token");t=await k()}if(!t)throw new i("No token provided.","no-token");if(!await l({server:r,token:t}))throw new i(`Token rejected by ${r} \u2014 double-check it and retry.`,"invalid-token");h({token:t,server:r});const{mode:a,warning:s}=await f({server:r,token:t});console.log(a==="keychain"?`\u2713 Token saved to OS keychain for ${r}`:`\u2713 Token saved to ~/.browserless/config.json for ${r}`),s&&console.log(`! ${s}`)},"action"),$=n(o=>{const e=o.command("login [token]").description("Validate and persist an API token. Without an argument it is read from stdin \u2014 prefer that: an argument shows up in the process list for other local users and in shell history.");m(e).action(p)},"registerAuthLogin");export{$ as registerAuthLogin};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(o,e)=>l(o,"name",{value:e,configurable:!0});import{addClientFlags as r,buildClient as c,printJson as a}from"../../cli-utils/client.js";import{deleteProfile as s}from"../../api/profiles.js";const d=t(async(o,e)=>{const i=await c(e),n=await s(i,o);if(e.json){a(n);return}console.log(`\u2713 Deleted profile "${n.name}"`)},"action"),g=t(o=>{const e=o.command("delete <name>").description("Delete a cloud profile");r(e).action(d)},"registerDelete");export{g as registerDelete};
1
+ var r=Object.defineProperty;var t=(o,e)=>r(o,"name",{value:e,configurable:!0});import{addClientFlags as l,buildClient as a,printJson as c}from"../../cli-utils/client.js";import{deleteProfile as s}from"../../api/profiles.js";import{terminalSafe as m}from"../../utils/terminal.js";const d=t(async(o,e)=>{const i=await a(e),n=await s(i,o);if(e.json){c(n);return}console.log(`\u2713 Deleted profile "${m(n.name)}"`)},"action"),D=t(o=>{const e=o.command("delete <name>").description("Delete a cloud profile");l(e).action(d)},"registerDelete");export{D as registerDelete};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var i=(n,o)=>g(n,"name",{value:o,configurable:!0});import{addClientFlags as p,buildClient as h,parseNonNegativeInt as c,printJson as w}from"../../cli-utils/client.js";import{listProfiles as S}from"../../api/profiles.js";const A=i(async n=>{const o=await h(n),d=n.limit!==void 0?c("--limit",n.limit,1):void 0,m=n.offset!==void 0?c("--offset",n.offset):void 0,e=await S(o,{limit:d,offset:m});if(n.json){w(e);return}if(e.length===0){console.log("No profiles found.");return}const f=["NAME","COOKIES","ORIGINS","UPDATED","LAST USED"],a=e.map(t=>[t.name,String(t.cookieCount),String(t.originCount),t.updatedAt,t.lastUsedAt??"-"]),u=f.map((t,s)=>Math.max(t.length,...a.map(r=>r[s].length))),l=i(t=>console.log(t.map((s,r)=>s.padEnd(u[r])).join(" ")),"print");l(f);for(const t of a)l(t)},"action"),I=i(n=>{const o=n.command("list").description("List cloud profiles owned by the current token").option("--limit <n>","Maximum profiles to return").option("--offset <n>","Pagination offset");p(o).action(A)},"registerList");export{I as registerList};
1
+ var g=Object.defineProperty;var e=(n,o)=>g(n,"name",{value:o,configurable:!0});import{addClientFlags as p,buildClient as h,parseNonNegativeInt as c,printJson as S}from"../../cli-utils/client.js";import{listProfiles as w}from"../../api/profiles.js";import{terminalSafe as A}from"../../utils/terminal.js";const C=e(async n=>{const o=await h(n),d=n.limit!==void 0?c("--limit",n.limit,1):void 0,m=n.offset!==void 0?c("--offset",n.offset):void 0,s=await w(o,{limit:d,offset:m});if(n.json){S(s);return}if(s.length===0){console.log("No profiles found.");return}const f=["NAME","COOKIES","ORIGINS","UPDATED","LAST USED"],a=s.map(t=>[t.name,String(t.cookieCount),String(t.originCount),t.updatedAt,t.lastUsedAt??"-"].map(i=>A(i))),u=f.map((t,i)=>Math.max(t.length,...a.map(r=>r[i].length))),l=e(t=>console.log(t.map((i,r)=>i.padEnd(u[r])).join(" ")),"print");l(f);for(const t of a)l(t)},"action"),D=e(n=>{const o=n.command("list").description("List cloud profiles owned by the current token").option("--limit <n>","Maximum profiles to return").option("--offset <n>","Pagination offset");p(o).action(C)},"registerList");export{D as registerList};
@@ -1,2 +1,2 @@
1
- var c=Object.defineProperty;var a=(e,t)=>c(e,"name",{value:t,configurable:!0});import{addClientFlags as d,buildClient as f,printJson as m}from"../../cli-utils/client.js";import{addCaptureFlags as p,buildCaptureSettings as u,mergeStoredSettings as g,printEffectiveSettings as h,runCapture as C}from"../../cli-utils/capture-runner.js";import{getProfile as S}from"../../api/profiles.js";import{refreshProfile as w}from"../../api/refresh.js";import{withProfileSetup as $}from"../../telemetry/profile-setup.js";const x=a(e=>$(e.attemptId,"refresh",async t=>{const i=await f(e),s=await S(i,e.name),l=e.defaultExcludes===!1,o=g(e,s.captureSettings);h(o,s.captureSettings,{userOptedOut:l});const n=await C({flags:o,requiresDisclaimer:!0});t.ready(),process.stderr.write(`> Refreshing profile "${e.name}" on ${i.server}
2
- `),t.submit();const r=await w(i,{attemptId:t.attemptId,name:e.name,state:n.state,serialized:n.serialized,captureSettings:u(o,n.diagnostics,"refresh")});if(e.json){m(r);return}console.log(`\u2713 Profile "${r.name}" refreshed`),console.log(` id: ${r.id}`),console.log(` cookies: ${r.cookieCount}`),console.log(` origins: ${r.originCount}`),console.log(` updated: ${r.updatedAt}`)}),"action"),q=a(e=>{const t=e.command("refresh").description("Capture a local browser profile and replace an existing cloud profile in place").requiredOption("--name <name>","Name of the existing cloud profile to refresh").option("--attempt-id <UUID>","Optional setup correlation ID");p(d(t),{sourceOptional:!0}).action(x)},"registerRefresh");export{q as registerRefresh};
1
+ var d=Object.defineProperty;var s=(e,t)=>d(e,"name",{value:t,configurable:!0});import{addClientFlags as m,buildClient as f,printJson as p}from"../../cli-utils/client.js";import{addCaptureFlags as u,buildCaptureSettings as g,mergeStoredSettings as h,printEffectiveSettings as S,runCapture as C}from"../../cli-utils/capture-runner.js";import{getProfile as w}from"../../api/profiles.js";import{refreshProfile as $}from"../../api/refresh.js";import{withProfileSetup as x}from"../../telemetry/profile-setup.js";import{terminalSafe as i}from"../../utils/terminal.js";const I=s(e=>x(e.attemptId,"refresh",async t=>{const o=await f(e),l=await w(o,e.name),c=e.defaultExcludes===!1,n=h(e,l.captureSettings);S(n,l.captureSettings,{userOptedOut:c});const a=await C({flags:n,requiresDisclaimer:!0});t.ready(),process.stderr.write(`> Refreshing profile "${e.name}" on ${o.server}
2
+ `),t.submit();const r=await $(o,{attemptId:t.attemptId,name:e.name,state:a.state,serialized:a.serialized,captureSettings:g(n,a.diagnostics,"refresh")});if(e.json){p(r);return}console.log(`\u2713 Profile "${i(r.name)}" refreshed`),console.log(` id: ${i(r.id)}`),console.log(` cookies: ${i(r.cookieCount)}`),console.log(` origins: ${i(r.originCount)}`),console.log(` updated: ${i(r.updatedAt)}`)}),"action"),y=s(e=>{const t=e.command("refresh").description("Capture a local browser profile and replace an existing cloud profile in place").requiredOption("--name <name>","Name of the existing cloud profile to refresh").option("--attempt-id <UUID>","Optional setup correlation ID");u(m(t),{sourceOptional:!0}).action(I)},"registerRefresh");export{y as registerRefresh};
@@ -1 +1 @@
1
- var r=Object.defineProperty;var o=(n,e)=>r(n,"name",{value:e,configurable:!0});import{addClientFlags as c,buildClient as s,printJson as m}from"../../cli-utils/client.js";import{renameProfile as l}from"../../api/profiles.js";const d=o(async(n,e,t)=>{const a=await s(t),i=await l(a,n,e);if(t.json){m(i);return}console.log(`\u2713 Renamed "${n}" \u2192 "${i.name}"`)},"action"),u=o(n=>{const e=n.command("rename <old> <new>").description("Rename a cloud profile");c(e).action(d)},"registerRename");export{u as registerRename};
1
+ var m=Object.defineProperty;var o=(n,e)=>m(n,"name",{value:e,configurable:!0});import{addClientFlags as c,buildClient as s,printJson as l}from"../../cli-utils/client.js";import{renameProfile as d}from"../../api/profiles.js";import{terminalSafe as r}from"../../utils/terminal.js";const f=o(async(n,e,t)=>{const a=await s(t),i=await d(a,n,e);if(t.json){l(i);return}console.log(`\u2713 Renamed "${r(n)}" \u2192 "${r(i.name)}"`)},"action"),R=o(n=>{const e=n.command("rename <old> <new>").description("Rename a cloud profile");c(e).action(f)},"registerRename");export{R as registerRename};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(n,e)=>l(n,"name",{value:e,configurable:!0});import{addClientFlags as s,buildClient as c,printJson as a}from"../../cli-utils/client.js";import{getProfile as d}from"../../api/profiles.js";const r=t(async(n,e)=>{const i=await c(e),o=await d(i,n);if(e.json){a(o);return}console.log(`name: ${o.name}`),console.log(`id: ${o.id}`),console.log(`cookies: ${o.cookieCount}`),console.log(`origins: ${o.originCount}`),console.log(`created: ${o.createdAt}`),console.log(`updated: ${o.updatedAt}`),console.log(`last used: ${o.lastUsedAt??"-"}`)},"action"),u=t(n=>{const e=n.command("show <name>").description("Show a single cloud profile's metadata");s(e).action(r)},"registerShow");export{u as registerShow};
1
+ var s=Object.defineProperty;var i=(n,t)=>s(n,"name",{value:t,configurable:!0});import{addClientFlags as a,buildClient as c,printJson as r}from"../../cli-utils/client.js";import{getProfile as d}from"../../api/profiles.js";import{terminalSafe as e}from"../../utils/terminal.js";const m=i(async(n,t)=>{const l=await c(t),o=await d(l,n);if(t.json){r(o);return}console.log(`name: ${e(o.name)}`),console.log(`id: ${e(o.id)}`),console.log(`cookies: ${e(o.cookieCount)}`),console.log(`origins: ${e(o.originCount)}`),console.log(`created: ${e(o.createdAt)}`),console.log(`updated: ${e(o.updatedAt)}`),console.log(`last used: ${e(o.lastUsedAt??"-")}`)},"action"),$=i(n=>{const t=n.command("show <name>").description("Show a single cloud profile's metadata");a(t).action(m)},"registerShow");export{$ as registerShow};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var t=(r,e)=>o(r,"name",{value:e,configurable:!0});import n from"node:fs/promises";import{addCustomBrowser as s}from"../../../browsers/custom.js";import{findBuiltInByKeyOrName as d}from"../../../browsers/registry.js";import{UsageError as a}from"../../../errors.js";const m=t(async r=>{if(!r.name||!r.path||!r.userDataDir)throw new a("profile sources add requires --name, --path, and --user-data-dir");if(d(r.name))throw new a(`"${r.name}" collides with a built-in browser. Pick a different name (e.g. "${r.name}-custom").`);const[e,i]=await Promise.all([n.stat(r.path).catch(()=>null),n.stat(r.userDataDir).catch(()=>null)]);if(!e)throw new a(`--path does not exist: ${r.path}`);if(e.isDirectory())throw new a(`--path must point at a binary, not a directory: ${r.path}`);if(!i)throw new a(`--user-data-dir does not exist: ${r.userDataDir}`);if(!i.isDirectory())throw new a(`--user-data-dir must point at a directory: ${r.userDataDir}`);await s({name:r.name,binaryPath:r.path,userDataDir:r.userDataDir}),console.log(`\u2713 Registered custom browser "${r.name}"`)},"action"),D=t(r=>{r.command("add").description("Register a custom Chromium binary as a profile source").requiredOption("--name <name>","Identifier (also used as --browser key)").requiredOption("--path <path>","Path to the browser binary").requiredOption("--user-data-dir <dir>","Path to the browser's user-data-dir").action(m)},"registerSourcesAdd");export{D as registerSourcesAdd};
1
+ var m=Object.defineProperty;var t=(r,e)=>m(r,"name",{value:e,configurable:!0});import s from"node:fs/promises";import d from"node:path";import{addCustomBrowser as u}from"../../../browsers/custom.js";import{findBuiltInByKeyOrName as c}from"../../../browsers/registry.js";import{UsageError as a}from"../../../errors.js";const h=t(async r=>{if(!r.name||!r.path||!r.userDataDir)throw new a("profile sources add requires --name, --path, and --user-data-dir");if(c(r.name))throw new a(`"${r.name}" collides with a built-in browser. Pick a different name (e.g. "${r.name}-custom").`);const e=d.resolve(r.path),i=d.resolve(r.userDataDir),[o,n]=await Promise.all([s.stat(e).catch(()=>null),s.stat(i).catch(()=>null)]);if(!o)throw new a(`--path does not exist: ${r.path}`);if(o.isDirectory())throw new a(`--path must point at a binary, not a directory: ${r.path}`);if(!n)throw new a(`--user-data-dir does not exist: ${r.userDataDir}`);if(!n.isDirectory())throw new a(`--user-data-dir must point at a directory: ${r.userDataDir}`);await u({name:r.name,binaryPath:e,userDataDir:i}),console.log(`\u2713 Registered custom browser "${r.name}"`)},"action"),p=t(r=>{r.command("add").description("Register a custom Chromium binary as a profile source").requiredOption("--name <name>","Identifier (also used as --browser key)").requiredOption("--path <path>","Path to the browser binary").requiredOption("--user-data-dir <dir>","Path to the browser's user-data-dir").action(h)},"registerSourcesAdd");export{p as registerSourcesAdd};
@@ -1,2 +1,2 @@
1
- var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{addClientFlags as s,buildClient as d,printJson as c}from"../../cli-utils/client.js";import{addCaptureFlags as p,buildCaptureSettings as u,runCapture as m}from"../../cli-utils/capture-runner.js";import{uploadProfile as g}from"../../api/upload.js";import{withProfileSetup as f}from"../../telemetry/profile-setup.js";const C={runCapture:m},w=n((e,t)=>f(e.attemptId,"create",async a=>{const r=await d(e),i=await t.runCapture({flags:e,requiresDisclaimer:!0});a.ready(),process.stderr.write(`> Uploading to ${r.server}
2
- `),a.submit();const o=await g(r,{attemptId:a.attemptId,name:e.name,state:i.state,serialized:i.serialized,captureSettings:u(e,i.diagnostics,"upload")});if(e.json){c(o);return}console.log(`\u2713 Profile "${o.name}" uploaded`),console.log(` id: ${o.id}`),console.log(` cookies: ${o.cookieCount}`),console.log(` origins: ${o.originCount}`),console.log(` created: ${o.createdAt}`)}),"action"),P=n((e,t=C)=>{const a=e.command("upload").description("Capture a local browser profile and upload it as a new cloud profile").requiredOption("--name <name>","Name for the new cloud profile").option("--attempt-id <UUID>","Optional setup correlation ID");p(s(a)).action(r=>w(r,t))},"registerUpload");export{P as registerUpload};
1
+ var s=Object.defineProperty;var l=(e,t)=>s(e,"name",{value:t,configurable:!0});import{addClientFlags as d,buildClient as c,printJson as p}from"../../cli-utils/client.js";import{addCaptureFlags as m,buildCaptureSettings as u,runCapture as f}from"../../cli-utils/capture-runner.js";import{uploadProfile as g}from"../../api/upload.js";import{withProfileSetup as C}from"../../telemetry/profile-setup.js";import{terminalSafe as a}from"../../utils/terminal.js";const w={runCapture:f},$=l((e,t)=>C(e.attemptId,"create",async r=>{const i=await c(e),n=await t.runCapture({flags:e,requiresDisclaimer:!0});r.ready(),process.stderr.write(`> Uploading to ${i.server}
2
+ `),r.submit();const o=await g(i,{attemptId:r.attemptId,name:e.name,state:n.state,serialized:n.serialized,captureSettings:u(e,n.diagnostics,"upload")});if(e.json){p(o);return}console.log(`\u2713 Profile "${a(o.name)}" uploaded`),console.log(` id: ${a(o.id)}`),console.log(` cookies: ${a(o.cookieCount)}`),console.log(` origins: ${a(o.originCount)}`),console.log(` created: ${a(o.createdAt)}`)}),"action"),h=l((e,t=w)=>{const r=e.command("upload").description("Capture a local browser profile and upload it as a new cloud profile").requiredOption("--name <name>","Name for the new cloud profile").option("--attempt-id <UUID>","Optional setup correlation ID");m(d(r)).action(i=>$(i,t))},"registerUpload");export{h as registerUpload};
@@ -1 +1 @@
1
- var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});import{version as l}from"../version.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const h="https://api.browserless.io",u=o(()=>{const t=process.env.BROWSERLESS_API_URL?.trim()||h;return t.endsWith("/")?t.slice(0,-1):t},"apiBaseUrl"),m=o(t=>{try{const{protocol:e,hostname:s}=new URL(t);return e!=="http:"&&e!=="https:"?!1:p(s)||e==="https:"&&(s==="browserless.io"||s.endsWith(".browserless.io"))}catch{return!1}},"isTrustedApiBase"),f=2e3,b=`@browserless.io/cli/${l}`,A=o(async(t,e)=>{const s=e.timeoutMs??f,r=e.baseUrl??u();if(!m(r))return!1;const n=new AbortController,a=setTimeout(()=>n.abort(),s);try{const i=await fetch(`${r}/v2/cli/events`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":b,Authorization:`Bearer ${e.token}`},body:JSON.stringify({events:t}),signal:n.signal});return await i.text().catch(()=>{}),i.ok}catch{return!1}finally{clearTimeout(a)}},"postCliEvents");export{u as apiBaseUrl,m as isTrustedApiBase,A as postCliEvents};
1
+ var c=Object.defineProperty;var s=(t,e)=>c(t,"name",{value:e,configurable:!0});import{version as l}from"../version.js";import{isLoopbackHostname as p}from"../utils/loopback.js";const h="https://api.browserless.io",u=s(()=>{const t=process.env.BROWSERLESS_API_URL?.trim()||h;return t.endsWith("/")?t.slice(0,-1):t},"apiBaseUrl"),m=s(t=>{try{const{protocol:e,hostname:r}=new URL(t);return e!=="http:"&&e!=="https:"?!1:p(r)||e==="https:"&&(r==="browserless.io"||r.endsWith(".browserless.io"))}catch{return!1}},"isTrustedApiBase"),f=2e3,b=`@browserless.io/cli/${l}`,w=s(async(t,e)=>{const r=e.timeoutMs??f,o=e.baseUrl??u();if(!m(o))return!1;const n=new AbortController,a=setTimeout(()=>n.abort(),r);try{const i=await fetch(`${o}/v2/cli/events`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":b,Authorization:`Bearer ${e.token}`},body:JSON.stringify({events:t}),signal:n.signal,redirect:"error"});return await i.text().catch(()=>{}),i.ok}catch{return!1}finally{clearTimeout(a)}},"postCliEvents");export{u as apiBaseUrl,m as isTrustedApiBase,w as postCliEvents};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var o=(r,e)=>a(r,"name",{value:e,configurable:!0});const d={SIGINT:130,SIGTERM:143,SIGBREAK:130},i=o((r,{target:e=process,exit:I=o(n=>process.exit(n),"exit")}={})=>{let n;const E=Object.entries(d).map(([c,t])=>{const s=o(()=>{n??=r().catch(()=>{}),n.finally(()=>I(t))},"handler");return e.once(c,s),[c,s]});return()=>E.forEach(([c,t])=>e.off(c,t))},"onInterrupt");export{i as onInterrupt};
@@ -1,3 +1,3 @@
1
- var h=Object.defineProperty;var s=(i,t)=>h(i,"name",{value:t,configurable:!0});const e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],o=80,c=100,n=s((i,t)=>i.length<=t?i:`${i.slice(0,Math.max(0,t-1))}\u2026`,"clipToWidth");class l{static{s(this,"Spinner")}out;isTTY;intervalMs;timer=null;idx=0;text="";active=!1;constructor(t={}){this.out=t.out??process.stdout,this.isTTY=t.isTTY??!!this.out.isTTY,this.intervalMs=t.intervalMs??80}isActive(){return this.active}set(t){this.text=t,this.isTTY&&(this.active=!0,this.render(),this.intervalMs>0&&!this.timer&&(this.timer=setInterval(()=>this.render(),this.intervalMs),this.timer.unref?.()))}done(t){if(this.stopTimer(),!this.isTTY){this.out.write(`${t}
2
- `),this.active=!1;return}this.text=t,this.writeLine(t),this.out.write(`
3
- `),this.active=!1}clear(){if(this.stopTimer(),!this.isTTY){this.active=!1;return}this.active&&this.out.write("\r\x1B[K"),this.active=!1}render(){const t=e[this.idx%e.length];this.idx+=1,this.writeLine(`${t} ${this.text}`)}writeLine(t){const r=this.maxWidth();this.out.write(`\r\x1B[K${n(t,r)}`)}maxWidth(){const t=this.out.columns;return typeof t=="number"&&t>10?t-1:100}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}}export{l as Spinner};
1
+ var c=Object.defineProperty;var a=(h,t)=>c(h,"name",{value:t,configurable:!0});import u from"string-width";const l=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f=80,m=100,p=new Intl.Segmenter(void 0,{granularity:"grapheme"}),T=a((h,t)=>{let i=0,s="",o="";for(const{segment:e}of p.segment(h)){const n=e.replace(/[\ud800-\udfff]/gu,"\uFFFD"),r=u(n);if(i+r>t)return`${o}\u2026`;s+=n,i+=r,i<=t-1&&(o=s)}return s},"clipToWidth");class g{static{a(this,"Spinner")}out;isTTY;intervalMs;timer=null;idx=0;parts=[];active=!1;constructor(t={}){this.out=t.out??process.stdout,this.isTTY=t.isTTY??!!this.out.isTTY,this.intervalMs=t.intervalMs??f}isActive(){return this.active}set(t){this.parts=typeof t=="string"?[{text:t}]:t,this.isTTY&&(this.active=!0,this.render(),this.intervalMs>0&&!this.timer&&(this.timer=setInterval(()=>this.render(),this.intervalMs),this.timer.unref?.()))}done(t){if(this.stopTimer(),this.parts=typeof t=="string"?[{text:t}]:t,!this.isTTY){this.out.write(`${this.parts.map(({text:i})=>i).join("")}
2
+ `),this.active=!1;return}this.writeLine(this.parts),this.out.write(`
3
+ `),this.active=!1}clear(){if(this.stopTimer(),!this.isTTY){this.active=!1;return}this.active&&this.out.write("\r\x1B[K"),this.active=!1}render(){const t=l[this.idx%l.length];this.idx+=1,this.writeLine([{text:`${t} `},...this.parts])}writeLine(t){const i=T(t.map(({text:e})=>e).join(""),this.maxWidth());let s=0;const o=t.map(({text:e,style:n})=>{const r=i.slice(s,s+e.length);return s+=e.length,r&&n?n(r):r}).join("");this.out.write(`\r\x1B[K${o}`)}maxWidth(){const t=this.out.columns;return typeof t=="number"&&t>10?t-1:m}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}}export{g as Spinner};
@@ -0,0 +1,3 @@
1
+ var n=Object.defineProperty;var r=(u,t)=>n(u,"name",{value:t,configurable:!0});const o=r((u,t={})=>(t.preserveLayout?String(u).replace(/\r\n/g,`
2
+ `):String(u)).replace(/\u{1f3f4}[\u{e0020}-\u{e007e}]+\u{e007f}|[\x00-\x1f\x7f-\x9f\u00ad\u061c\u180e\u200b\u200e-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\u{e0000}-\u{e007f}]/gu,e=>{if(e.startsWith("\u{1F3F4}")||t.preserveLayout&&(e===`
3
+ `||e===" "))return e;const f=e.codePointAt(0);return f>65535?`\\u{${f.toString(16)}}`:`\\u${f.toString(16).padStart(4,"0")}`}),"terminalSafe");export{o as terminalSafe};
package/build/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.6.0";export{o as version};
1
+ const o="0.6.1";export{o as version};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@browserless.io/cli",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Browserless CLI — manage authentication profiles, sessions, and other Browserless features from your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,9 +45,9 @@
45
45
  "reporter": "spec"
46
46
  },
47
47
  "dependencies": {
48
- "chrome-remote-interface": "^0.34.0",
49
- "commander": "^15.0.0",
50
- "ws": "^8.22.1"
48
+ "commander": "^15.1.0",
49
+ "string-width": "^8.3.0",
50
+ "ws": "^8.22.2"
51
51
  },
52
52
  "optionalDependencies": {
53
53
  "@napi-rs/keyring": "^2.1.2"
@@ -61,6 +61,7 @@
61
61
  "@types/sinon": "^22.0.2",
62
62
  "@types/ws": "^8.18.2",
63
63
  "chai": "^6.3.0",
64
+ "chrome-remote-interface": "^0.34.0",
64
65
  "esbuild": "^0.28.2",
65
66
  "eslint": "^10.14.0",
66
67
  "globals": "^17.14.0",
@@ -70,7 +71,7 @@
70
71
  "prettier": "3.9.10",
71
72
  "sinon": "^22.1.0",
72
73
  "typescript": "^6.0.3",
73
- "typescript-eslint": "^8.72.1"
74
+ "typescript-eslint": "^8.72.2"
74
75
  },
75
76
  "overrides": {
76
77
  "mocha": {
@@ -87,5 +88,14 @@
87
88
  "trailingComma": "all",
88
89
  "singleQuote": true,
89
90
  "printWidth": 80
90
- }
91
+ },
92
+ "repository": {
93
+ "type": "git",
94
+ "url": "git+https://github.com/browserless/browserless-cli.git"
95
+ },
96
+ "homepage": "https://github.com/browserless/browserless-cli#readme",
97
+ "bugs": {
98
+ "url": "https://github.com/browserless/browserless-cli/issues"
99
+ },
100
+ "author": "browserless.io"
91
101
  }