pyunbrowser 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ # Rust build artifacts
2
+ /target
3
+ **/*.rs.bk
4
+
5
+ # Editor / OS
6
+ .DS_Store
7
+ *.swp
8
+ *.swo
9
+ .idea/
10
+ .vscode/
11
+
12
+ # Local-only artifacts
13
+ *.log
14
+ /tmp/
15
+
16
+ # Secrets — never commit. .env* covers .env, .env.local, .env.production, etc.
17
+ .env
18
+ .env.*
19
+ !.env.example
20
+
21
+ # Python package build artifacts (the binary lands in _bin/ at CI time
22
+ # only — we never want it in git; the .gitkeep placeholder is preserved)
23
+ /python/dist/
24
+ /python/build/
25
+ /python/*.egg-info/
26
+ /python/unbrowser/__pycache__/
27
+ /python/unbrowser/_bin/*
28
+ !/python/unbrowser/_bin/.gitkeep
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyunbrowser
3
+ Version: 0.0.1
4
+ Summary: Web access for LLM agents. One static binary. No Chrome.
5
+ Project-URL: Homepage, https://github.com/protostatis/unbrowser
6
+ Project-URL: Repository, https://github.com/protostatis/unbrowser
7
+ Project-URL: Issues, https://github.com/protostatis/unbrowser/issues
8
+ Author: protostatis
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agent,automation,browser,headless,llm,scraping
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Rust
23
+ Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # unbrowser
29
+
30
+ **Web access for LLM agents. One static binary. No Chrome.**
31
+
32
+ Single-file native headless browser optimized for LLM agents. Runs JavaScript via QuickJS, returns a low-token page summary on every navigate, and gives you stable element refs for click/type/submit. Tens of MB RAM per session, no Chrome dependency.
33
+
34
+ ```bash
35
+ pip install unbrowser
36
+ ```
37
+
38
+ The wheel ships the native binary for your platform — there's nothing else to install.
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ from unbrowser import Client
44
+
45
+ with Client() as ub:
46
+ r = ub.navigate("https://news.ycombinator.com")
47
+ for s in ub.query(".titleline > a")[:3]:
48
+ print(s["text"], s["attrs"]["href"])
49
+ ```
50
+
51
+ ## Why
52
+
53
+ | | curl | This | Playwright / headless Chrome |
54
+ |---|---|---|---|
55
+ | Static / SSR pages | ✅ but token-heavy | ✅ low-token BlockMap | overkill |
56
+ | SPA-shell sites (with `exec_scripts`) | ❌ | ⚠️ partial | ✅ |
57
+ | Bot-walled (cookie handoff) | ❌ | ✅ | ✅ |
58
+ | Run in Lambda / Workers / edge | ✅ | ✅ | ❌ Chrome too big |
59
+ | Per-page cost at 100K/day | ~free | ~free | $$$ |
60
+ | LLM-shaped output | DIY parse | ✅ inline BlockMap | DIY parse |
61
+
62
+ ## What it does
63
+
64
+ - **`navigate(url)`** — fetch, parse, return `{status, url, bytes, headers, blockmap, challenge}`. With `exec_scripts=True`, runs page JS in QuickJS (bounded by a 30s watchdog so it can't wedge).
65
+ - **`query(selector)`** — CSS query → `[{ref, tag, attrs, text}]`. Refs are stable handles for click/type/submit.
66
+ - **`extract()`** — auto-strategy structured data: tries JSON-LD → `__NEXT_DATA__` → Nuxt → OpenGraph → microdata → text fallback, returns highest-confidence hit.
67
+ - **`click(ref)` / `type(ref, text)` / `submit(ref)`** — interaction. POST and GET forms supported. Checkboxes/radios tracked.
68
+ - **`cookies_set(...)`** — paste cookies from a real Chrome session to bypass bot detection (Cloudflare, PerimeterX, Datadome). Solve once, replay forever.
69
+
70
+ Full RPC reference, BlockMap shape, challenge detection, profile system, and architecture: [github.com/protostatis/unbrowser](https://github.com/protostatis/unbrowser).
71
+
72
+ ## Honest limits
73
+
74
+ - Heavy framework SPAs (Ember/React) often don't auto-mount inside QuickJS even with `exec_scripts=True` — the watchdog ensures it returns, check `density.likely_js_filled` to decide whether to escalate.
75
+ - No screenshots (out of scope by design).
76
+ - Hardest-tier anti-bot (FingerprintJS Pro, Kasada, advanced Akamai BMP) needs the cookie handoff path. The binary detects and labels the challenge for you.
77
+
78
+ ## License
79
+
80
+ Apache-2.0.
@@ -0,0 +1,53 @@
1
+ # unbrowser
2
+
3
+ **Web access for LLM agents. One static binary. No Chrome.**
4
+
5
+ Single-file native headless browser optimized for LLM agents. Runs JavaScript via QuickJS, returns a low-token page summary on every navigate, and gives you stable element refs for click/type/submit. Tens of MB RAM per session, no Chrome dependency.
6
+
7
+ ```bash
8
+ pip install unbrowser
9
+ ```
10
+
11
+ The wheel ships the native binary for your platform — there's nothing else to install.
12
+
13
+ ## Quick start
14
+
15
+ ```python
16
+ from unbrowser import Client
17
+
18
+ with Client() as ub:
19
+ r = ub.navigate("https://news.ycombinator.com")
20
+ for s in ub.query(".titleline > a")[:3]:
21
+ print(s["text"], s["attrs"]["href"])
22
+ ```
23
+
24
+ ## Why
25
+
26
+ | | curl | This | Playwright / headless Chrome |
27
+ |---|---|---|---|
28
+ | Static / SSR pages | ✅ but token-heavy | ✅ low-token BlockMap | overkill |
29
+ | SPA-shell sites (with `exec_scripts`) | ❌ | ⚠️ partial | ✅ |
30
+ | Bot-walled (cookie handoff) | ❌ | ✅ | ✅ |
31
+ | Run in Lambda / Workers / edge | ✅ | ✅ | ❌ Chrome too big |
32
+ | Per-page cost at 100K/day | ~free | ~free | $$$ |
33
+ | LLM-shaped output | DIY parse | ✅ inline BlockMap | DIY parse |
34
+
35
+ ## What it does
36
+
37
+ - **`navigate(url)`** — fetch, parse, return `{status, url, bytes, headers, blockmap, challenge}`. With `exec_scripts=True`, runs page JS in QuickJS (bounded by a 30s watchdog so it can't wedge).
38
+ - **`query(selector)`** — CSS query → `[{ref, tag, attrs, text}]`. Refs are stable handles for click/type/submit.
39
+ - **`extract()`** — auto-strategy structured data: tries JSON-LD → `__NEXT_DATA__` → Nuxt → OpenGraph → microdata → text fallback, returns highest-confidence hit.
40
+ - **`click(ref)` / `type(ref, text)` / `submit(ref)`** — interaction. POST and GET forms supported. Checkboxes/radios tracked.
41
+ - **`cookies_set(...)`** — paste cookies from a real Chrome session to bypass bot detection (Cloudflare, PerimeterX, Datadome). Solve once, replay forever.
42
+
43
+ Full RPC reference, BlockMap shape, challenge detection, profile system, and architecture: [github.com/protostatis/unbrowser](https://github.com/protostatis/unbrowser).
44
+
45
+ ## Honest limits
46
+
47
+ - Heavy framework SPAs (Ember/React) often don't auto-mount inside QuickJS even with `exec_scripts=True` — the watchdog ensures it returns, check `density.likely_js_filled` to decide whether to escalate.
48
+ - No screenshots (out of scope by design).
49
+ - Hardest-tier anti-bot (FingerprintJS Pro, Kasada, advanced Akamai BMP) needs the cookie handoff path. The binary detects and labels the challenge for you.
50
+
51
+ ## License
52
+
53
+ Apache-2.0.
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ # Distribution name `pyunbrowser` (not `unbrowser`) because PyPI's name
7
+ # moderation blocked `unbrowser` on typosquat-prevention grounds (it's too
8
+ # close to `browser`). The `py-` prefix is the established PyPI workaround
9
+ # (cf. python-dateutil → `from dateutil import ...`); the import name and
10
+ # binary stay `unbrowser` everywhere else.
11
+ name = "pyunbrowser"
12
+ version = "0.0.1"
13
+ description = "Web access for LLM agents. One static binary. No Chrome."
14
+ readme = "README.md"
15
+ license = { text = "Apache-2.0" }
16
+ requires-python = ">=3.10"
17
+ authors = [{ name = "protostatis" }]
18
+ keywords = ["browser", "scraping", "llm", "agent", "headless", "automation"]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Developers",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Operating System :: MacOS",
24
+ "Operating System :: POSIX :: Linux",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ "Programming Language :: Rust",
31
+ "Topic :: Internet :: WWW/HTTP :: Browsers",
32
+ "Topic :: Software Development :: Libraries",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/protostatis/unbrowser"
37
+ Repository = "https://github.com/protostatis/unbrowser"
38
+ Issues = "https://github.com/protostatis/unbrowser/issues"
39
+
40
+ # The wheel ships the platform-specific native binary inside unbrowser/_bin/.
41
+ # CI builds the binary first (cargo build --release for each target), copies
42
+ # it into unbrowser/_bin/, then runs `python -m build --wheel` to produce a
43
+ # platform-tagged wheel. The sdist intentionally excludes _bin/ — a source
44
+ # distribution should be platform-neutral.
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["unbrowser"]
47
+ # pure-python = false flips the wheel from py3-none-any to a platform-tagged
48
+ # wheel based on the host (macosx_*, linux_*, etc.). CI cross-compiles by
49
+ # post-processing the wheel name via `wheel tags --platform <target>`.
50
+ pure-python = false
51
+ # Even though _bin/* is gitignored (binary is a build artifact, never in git),
52
+ # hatchling's package auto-discovery picks up the binary if it's physically
53
+ # present at build time — exactly what we want. CI drops the per-platform
54
+ # binary into _bin/ before running `python -m build --wheel`. Sdist build
55
+ # explicitly excludes _bin/ (see [tool.hatch.build.targets.sdist] below)
56
+ # because a source distribution must be platform-neutral.
57
+ # Suppress hatchling's "did you mean to mark this as platform-specific?"
58
+ # nag — yes, we did, deliberately, for the bundled binary.
59
+ [tool.hatch.metadata]
60
+ allow-direct-references = true
61
+
62
+ [tool.hatch.build.targets.sdist]
63
+ include = ["unbrowser/", "README.md", "LICENSE"]
64
+ exclude = ["unbrowser/_bin/"]
@@ -0,0 +1,333 @@
1
+ """unbrowser — Python client for the unbrowser binary.
2
+
3
+ `pip install unbrowser` ships the native binary inside the wheel for your
4
+ platform — there's nothing else to install. Use it like:
5
+
6
+ from unbrowser import Client
7
+
8
+ with Client() as ub:
9
+ r = ub.navigate("https://news.ycombinator.com")
10
+ for s in ub.query(".titleline > a")[:3]:
11
+ print(s["text"], s["attrs"]["href"])
12
+
13
+ For the `extract` / auto-strategy command, watchdog-bounded `exec_scripts`,
14
+ the cookie handoff for bot-walled sites, and the BlockMap shape: see the
15
+ project README at https://github.com/protostatis/unbrowser.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import atexit
21
+ import json
22
+ import os
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import Any
28
+ from urllib.parse import quote_plus, urljoin, urlparse
29
+
30
+ __version__ = "0.0.1"
31
+
32
+ __all__ = ["Client", "UnbrowserError", "find_binary", "navigate", "__version__"]
33
+
34
+
35
+ class UnbrowserError(Exception):
36
+ """Raised when the binary returns a JSON-RPC error or can't be spawned."""
37
+
38
+
39
+ def find_binary() -> str:
40
+ """Resolve the unbrowser binary path.
41
+
42
+ Resolution order, most-explicit first:
43
+
44
+ 1. ``UNBROWSER_BIN`` env var (overrides everything; right escape hatch
45
+ for testing a one-off build or vendored copy).
46
+ 2. Bundled binary inside this package (the wheel ships one for your
47
+ platform — this is what end users hit).
48
+ 3. ``unbrowser`` on ``$PATH`` (covers ``cargo install`` / ``brew install``
49
+ users who didn't install the wheel).
50
+ 4. The local debug build at ``target/debug/unbrowser`` relative to the
51
+ repo root (developer convenience — only fires when running from a
52
+ checkout without an installed wheel).
53
+
54
+ Raises UnbrowserError with a helpful message if none of the above resolve.
55
+ """
56
+ env = os.environ.get("UNBROWSER_BIN")
57
+ if env:
58
+ if not Path(env).is_file():
59
+ raise UnbrowserError(
60
+ f"UNBROWSER_BIN points to {env!r}, which doesn't exist"
61
+ )
62
+ return env
63
+
64
+ bundled = Path(__file__).parent / "_bin" / _binary_name()
65
+ if bundled.is_file():
66
+ return str(bundled)
67
+
68
+ on_path = shutil.which("unbrowser")
69
+ if on_path:
70
+ return on_path
71
+
72
+ # Dev fallback: target/debug/unbrowser two dirs up from this file
73
+ # (python/unbrowser/__init__.py -> python/unbrowser -> python -> repo root).
74
+ dev = Path(__file__).resolve().parents[2] / "target" / "debug" / "unbrowser"
75
+ if dev.is_file():
76
+ return str(dev)
77
+
78
+ raise UnbrowserError(
79
+ "Could not locate the unbrowser binary. Tried: $UNBROWSER_BIN, "
80
+ "package-bundled binary, $PATH, target/debug/unbrowser. "
81
+ "Install via `pip install unbrowser` (ships the binary), "
82
+ "`cargo install unbrowser`, or `brew install unbrowser`."
83
+ )
84
+
85
+
86
+ def _binary_name() -> str:
87
+ return "unbrowser.exe" if sys.platform == "win32" else "unbrowser"
88
+
89
+
90
+ class Client:
91
+ """Synchronous JSON-RPC client for the unbrowser binary.
92
+
93
+ One subprocess per Client. The session (cookies, last_url, last_body)
94
+ persists across calls until close().
95
+ """
96
+
97
+ def __init__(self, binary: str | None = None):
98
+ self._proc = subprocess.Popen(
99
+ [binary or find_binary()],
100
+ stdin=subprocess.PIPE,
101
+ stdout=subprocess.PIPE,
102
+ stderr=subprocess.DEVNULL,
103
+ text=True,
104
+ bufsize=1,
105
+ )
106
+ self._next_id = 0
107
+ self._closed = False
108
+ # Track the last successful navigate URL Python-side so make_absolute_url
109
+ # can resolve relative hrefs without round-tripping to the binary. Updated
110
+ # after every successful navigate / submit / click-with-follow.
111
+ self._last_url: str | None = None
112
+ # Belt-and-braces orphan prevention: if the interpreter exits before
113
+ # __exit__ runs (unhandled exception, sys.exit, heredoc-wrapped
114
+ # invocation killed mid-flight), atexit reaps the subprocess. The
115
+ # binary's own watchdog bounds JS execution; this covers the
116
+ # subprocess-lifecycle layer.
117
+ atexit.register(self._reap)
118
+
119
+ # ---- core RPC --------------------------------------------------------
120
+
121
+ def call(self, method: str, **params) -> Any:
122
+ """Send one JSON-RPC request, return the result. Raises UnbrowserError on RPC error."""
123
+ self._next_id += 1
124
+ req = {"id": self._next_id, "method": method, "params": params}
125
+ assert self._proc.stdin is not None and self._proc.stdout is not None
126
+ self._proc.stdin.write(json.dumps(req) + "\n")
127
+ self._proc.stdin.flush()
128
+ line = self._proc.stdout.readline()
129
+ if not line:
130
+ raise UnbrowserError(f"binary closed stdout while waiting for {method}")
131
+ resp = json.loads(line)
132
+ if "error" in resp:
133
+ raise UnbrowserError(f"{method}: {resp['error']}")
134
+ return resp.get("result")
135
+
136
+ # ---- typed wrappers (don't add behavior; just discoverability) -------
137
+
138
+ def navigate(self, url: str, exec_scripts: bool = False) -> dict:
139
+ r = self.call("navigate", url=url, exec_scripts=exec_scripts)
140
+ if isinstance(r, dict) and r.get("url"):
141
+ self._last_url = r["url"]
142
+ return r
143
+
144
+ def query(self, selector: str) -> list[dict]:
145
+ return self.call("query", selector=selector)
146
+
147
+ def text(self, selector: str = "body") -> str | None:
148
+ return self.call("text", selector=selector)
149
+
150
+ def text_main(self) -> str | None:
151
+ """textContent of the main content area (excludes header/nav/footer/aside)."""
152
+ return self.call("text_main")
153
+
154
+ def query_text(self, text: str, selector: str | None = None,
155
+ exact: bool = False, limit: int = 20) -> list[dict]:
156
+ """Find elements by visible text content (chrome-stripped, deepest match).
157
+
158
+ Use when CSS selectors are unstable (React-rendered pages) but the
159
+ visible label is reliable, e.g. r.query_text('Sign in')[0].
160
+ """
161
+ params: dict = {"text": text, "exact": exact, "limit": limit}
162
+ if selector is not None:
163
+ params["selector"] = selector
164
+ return self.call("query_text", **params)
165
+
166
+ def click(self, ref: str) -> dict:
167
+ r = self.call("click", ref=ref)
168
+ # click on <a href> auto-follows and returns navigate-shape result;
169
+ # update last_url so make_absolute_url stays accurate.
170
+ if isinstance(r, dict) and r.get("url"):
171
+ self._last_url = r["url"]
172
+ return r
173
+
174
+ def type(self, ref: str, text: str) -> dict:
175
+ return self.call("type", ref=ref, text=text)
176
+
177
+ def submit(self, ref: str) -> dict:
178
+ r = self.call("submit", ref=ref)
179
+ if isinstance(r, dict) and r.get("url"):
180
+ self._last_url = r["url"]
181
+ return r
182
+
183
+ def search(self, query: str, engine: str = "ddg") -> dict:
184
+ """Search via the named engine; return the navigate result.
185
+
186
+ Engines:
187
+ ddg — DuckDuckGo HTML (default; reliable, returns SSR'd results
188
+ that the cheap path can extract directly via query()).
189
+ bing — Bing search (also works without exec_scripts).
190
+
191
+ Google is intentionally NOT supported via the cheap path — Google's
192
+ search page returns ~no useful HTML without JS, so it would silently
193
+ fail. Use the cookie-handoff escalation path or one of the supported
194
+ engines instead.
195
+
196
+ Use after navigate(), or as the first call: it kicks off its own
197
+ navigate. The returned dict is the same shape as Client.navigate.
198
+ """
199
+ if engine == "ddg":
200
+ url = "https://duckduckgo.com/html/?q=" + quote_plus(query)
201
+ elif engine == "bing":
202
+ url = "https://www.bing.com/search?q=" + quote_plus(query)
203
+ else:
204
+ raise UnbrowserError(
205
+ f"unknown search engine '{engine}'. Supported: ddg, bing. "
206
+ "Google is intentionally unsupported via the cheap path."
207
+ )
208
+ return self.navigate(url)
209
+
210
+ def make_absolute_url(self, href: str) -> str:
211
+ """Resolve a relative href against the current page URL.
212
+
213
+ Use after navigate to expand `<a href="/foo">` or `href="../bar"`
214
+ into a full URL. If `href` is already absolute (has scheme + host),
215
+ it's returned unchanged — preventing the double-prefix class of bug
216
+ you get from naive ``current_url + href`` concatenation.
217
+
218
+ Raises UnbrowserError if no page has been navigated yet.
219
+ """
220
+ if not href:
221
+ raise UnbrowserError("empty href")
222
+ parsed = urlparse(href)
223
+ if parsed.scheme and parsed.netloc:
224
+ return href
225
+ if not self._last_url:
226
+ raise UnbrowserError("no current page — call navigate first")
227
+ return urljoin(self._last_url, href)
228
+
229
+ def blockmap(self) -> dict:
230
+ return self.call("blockmap")
231
+
232
+ def extract(self, strategy: str | None = None) -> dict:
233
+ """Auto-strategy structured-data extraction.
234
+
235
+ Tries JSON-LD → __NEXT_DATA__ → Nuxt → OpenGraph/meta → microdata →
236
+ text_main fallback, returns the highest-confidence hit as
237
+ {strategy, confidence, data, tried}. Pass strategy='json_ld' (etc.)
238
+ to force a specific extractor.
239
+ """
240
+ if strategy is None:
241
+ return self.call("extract")
242
+ return self.call("extract", strategy=strategy)
243
+
244
+ def settle(self, max_ms: int = 2000, max_iters: int = 50) -> dict:
245
+ """Drain the JS event loop: microtasks + setTimeout/setInterval.
246
+
247
+ Returns when queue empty, max_ms elapses, or max_iters hit. Result:
248
+ {iters, elapsed_ms, microtasks_run, timers_fired, pending_timers,
249
+ pending_microtasks, timed_out}.
250
+ """
251
+ return self.call("settle", max_ms=max_ms, max_iters=max_iters)
252
+
253
+ def body(self) -> str:
254
+ return self.call("body")
255
+
256
+ def eval(self, code: str) -> Any:
257
+ """Run arbitrary JS in the session.
258
+
259
+ Returns the JS expression's result already JSON-decoded into a Python
260
+ value (dict / list / str / int / float / bool / None). DO NOT call
261
+ json.loads() on the return value — the wrapper already did. The Rust
262
+ side runs JSON.stringify on the JS value, the JSON-RPC framing parses
263
+ it once, and the result is the Python equivalent.
264
+
265
+ Errors surface the real JS exception name + message
266
+ (`TypeError: cannot read property 'foo' of null` etc.) so iteration
267
+ is fast.
268
+ """
269
+ return self.call("eval", code=code)
270
+
271
+ def cookies_set(self, cookies: list[dict], url: str | None = None) -> dict:
272
+ if url is None:
273
+ return self.call("cookies_set", cookies=cookies)
274
+ return self.call("cookies_set", cookies=cookies, url=url)
275
+
276
+ def cookies_get(self) -> list[dict]:
277
+ return self.call("cookies_get")
278
+
279
+ def cookies_clear(self) -> dict:
280
+ return self.call("cookies_clear")
281
+
282
+ def close(self) -> None:
283
+ if self._closed:
284
+ return
285
+ self._closed = True
286
+ try:
287
+ self.call("close")
288
+ except (UnbrowserError, BrokenPipeError, OSError):
289
+ pass
290
+ self._reap()
291
+
292
+ def _reap(self) -> None:
293
+ # Idempotent: stdin EOF first (binary's reader returns None and the
294
+ # RPC loop exits cleanly), then escalate via terminate → kill if it
295
+ # doesn't respond. Always wait() at the end so we don't leave a
296
+ # zombie. Called from both close() and atexit.
297
+ if self._proc.poll() is not None:
298
+ return
299
+ try:
300
+ if self._proc.stdin and not self._proc.stdin.closed:
301
+ self._proc.stdin.close()
302
+ except (BrokenPipeError, OSError):
303
+ pass
304
+ try:
305
+ self._proc.wait(timeout=2)
306
+ return
307
+ except subprocess.TimeoutExpired:
308
+ pass
309
+ self._proc.terminate()
310
+ try:
311
+ self._proc.wait(timeout=2)
312
+ return
313
+ except subprocess.TimeoutExpired:
314
+ pass
315
+ self._proc.kill()
316
+ try:
317
+ self._proc.wait(timeout=2)
318
+ except subprocess.TimeoutExpired:
319
+ pass
320
+
321
+ # ---- context manager -------------------------------------------------
322
+
323
+ def __enter__(self) -> "Client":
324
+ return self
325
+
326
+ def __exit__(self, *exc) -> None:
327
+ self.close()
328
+
329
+
330
+ def navigate(url: str) -> dict:
331
+ """One-shot: fetch a URL and return the navigate result. Closes immediately."""
332
+ with Client() as ub:
333
+ return ub.navigate(url)