Skip to content

Commit 0687dc7

Browse files
authored
Merge pull request #3 from lightpanda-io/docs-pages-snake-case
Publish pdoc reference to GitHub Pages, expose snake_case API only
2 parents 892c05d + ee7aa5d commit 0687dc7

8 files changed

Lines changed: 191 additions & 139 deletions

File tree

‎.github/workflows/docs.yml‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
name: docs
2+
3+
# Publish the pdoc API reference to GitHub Pages. Modeled on zignal's
4+
# documentation.yml, minus the Zig half: one job builds the docs, one deploys.
5+
#
6+
# The docs are generated from the bundled browser binary (the tool methods are
7+
# regenerated from its MCP schemas before pdoc runs), so this fetches the same
8+
# release asset the wheels workflow bundles. It runs on release so the
9+
# published reference matches the wheel on PyPI, or by hand for any browser
10+
# tag (nightly included) to preview.
11+
12+
on:
13+
release:
14+
types: [published]
15+
workflow_dispatch:
16+
inputs:
17+
release:
18+
description: "browser release tag to document (nightly or a version tag)"
19+
default: "nightly"
20+
21+
permissions:
22+
contents: read
23+
pages: write
24+
id-token: write
25+
26+
concurrency:
27+
group: pages
28+
cancel-in-progress: true
29+
30+
env:
31+
BROWSER_REPO: lightpanda-io/browser
32+
33+
jobs:
34+
build:
35+
runs-on: ubuntu-latest
36+
timeout-minutes: 15
37+
steps:
38+
- uses: actions/checkout@v4
39+
40+
- uses: astral-sh/setup-uv@v5
41+
42+
- name: Resolve browser release tag
43+
id: params
44+
run: |
45+
if [ "${{ github.event_name }}" = release ]; then
46+
echo "release_tag=${{ github.event.release.tag_name }}" >> "$GITHUB_OUTPUT"
47+
else
48+
echo "release_tag=${{ inputs.release }}" >> "$GITHUB_OUTPUT"
49+
fi
50+
cat "$GITHUB_OUTPUT"
51+
52+
- name: Download the release binary
53+
env:
54+
GH_TOKEN: ${{ github.token }}
55+
run: |
56+
gh release download "${{ steps.params.outputs.release_tag }}" -R "$BROWSER_REPO" \
57+
-p lightpanda-x86_64-linux -O lightpanda-bin
58+
chmod +x lightpanda-bin
59+
./lightpanda-bin version
60+
61+
- name: Set package version from tag
62+
if: steps.params.outputs.release_tag != 'nightly'
63+
run: |
64+
# Same rule as wheels.yml: package version == browser release tag.
65+
tag="${{ steps.params.outputs.release_tag }}"
66+
sed -i "s/^version = .*/version = \"${tag#v}\"/" pyproject.toml
67+
grep '^version' pyproject.toml
68+
69+
- name: Build docs
70+
env:
71+
LIGHTPANDA_BIN: ${{ github.workspace }}/lightpanda-bin
72+
run: uv run --group docs python scripts/build_docs.py
73+
74+
- uses: actions/upload-pages-artifact@v3
75+
with:
76+
path: docs
77+
78+
deploy:
79+
needs: build
80+
runs-on: ubuntu-latest
81+
timeout-minutes: 5
82+
environment:
83+
name: github-pages
84+
url: ${{ steps.deployment.outputs.page_url }}
85+
steps:
86+
- id: deployment
87+
uses: actions/deploy-pages@v4

‎README.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,11 @@ Every browser tool is a `Session` method, typed and documented in your IDE.
124124
The methods are not written by hand: they are generated from the bundled
125125
browser's MCP tool schemas (`scripts/generate_methods.py` →
126126
`lightpanda/_methods.py`), so signatures and docstrings come straight from the
127-
binary. Both camelCase (`waitForSelector`) and snake_case (`wait_for_selector`)
128-
names resolve to the same tool.
127+
binary, with tool and parameter names in snake_case (`waitForSelector` →
128+
`wait_for_selector`, `backendNodeId` → `backend_node_id`). `Session.call` is
129+
the escape hatch that takes the raw tool and parameter names as the MCP
130+
server declares them. The full API reference is published at
131+
[lightpanda.io/lightpanda-python](https://lightpanda.io/lightpanda-python/).
129132

130133
The bindings follow Lightpanda's development and the package version tracks
131134
browser releases — there is no backwards-compatibility guarantee: when the
@@ -198,3 +201,7 @@ maintainer approves the `pypi` environment deployment on the run page. A
198201
release can also be triggered by hand: create a GitHub release here whose tag
199202
matches a browser release tag, or use the `workflow_dispatch` path (any
200203
browser tag, publish to TestPyPI or PyPI) for dry runs.
204+
205+
The same release event runs `.github/workflows/docs.yml`, which regenerates
206+
the API reference from that browser release with pdoc and deploys it to GitHub
207+
Pages. It can also be dispatched by hand for any browser tag to preview.

‎lightpanda/_methods.py‎

Lines changed: 55 additions & 110 deletions
Large diffs are not rendered by default.

‎lightpanda/browser.py‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""Public API: Browser, Session, run_script.
22
33
Session tool methods are generated from the server's ``tools/list`` schemas —
4-
one method per browser tool, kwargs exactly the tool's schema properties.
5-
Both the original tool name (``waitForSelector``) and its snake_case form
6-
(``wait_for_selector``) resolve to the same method.
4+
one method per browser tool, with the tool name and its schema properties
5+
in snake_case (``waitForSelector`` → ``wait_for_selector``, ``backendNodeId``
6+
→ ``backend_node_id``). :meth:`Session.call` is the escape hatch that also
7+
accepts the raw tool and property names.
78
"""
89

910
from __future__ import annotations
@@ -83,10 +84,13 @@ def call(self, tool: str, **kwargs):
8384
name = self._snake_map.get(tool, tool)
8485
if name not in self._tools:
8586
raise ToolError(f"unknown tool {tool!r}")
86-
kwargs = {k: v for k, v in kwargs.items() if v is not None}
87+
# Params are sent under the schema's (camelCase) property names; the
88+
# generated methods take their snake_case forms, so map those back.
89+
properties = self._tools[name]["schema"].get("properties", {})
90+
snake_props = {_snake(prop): prop for prop in properties}
91+
kwargs = {snake_props.get(k, k): v for k, v in kwargs.items() if v is not None}
8792
# The server declares JSON-carrying params (e.g. extract's schema) as
8893
# strings; serialize dict/list values passed for any such param.
89-
properties = self._tools[name]["schema"].get("properties", {})
9094
for key, value in kwargs.items():
9195
if isinstance(value, (dict, list)) and properties.get(key, {}).get("type") == "string":
9296
kwargs[key] = json.dumps(value)
@@ -110,9 +114,9 @@ def call(self, tool: str, **kwargs):
110114
return text
111115

112116
def _resolve(self, attr: str) -> str | None:
113-
"""The tool name behind a public attribute (snake or camel), if any."""
114-
name = self._snake_map.get(attr, attr)
115-
return name if name in self._tools and name not in _SESSION_TOOLS else None
117+
"""The tool name behind a snake_case public attribute, if any."""
118+
name = self._snake_map.get(attr)
119+
return name if name is not None and name not in _SESSION_TOOLS else None
116120

117121
def __getattr__(self, attr: str):
118122
if self.__dict__.get("_tools") and (name := self._resolve(attr)):

‎scripts/build_docs.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Generate API documentation with pdoc (zignal's flow, adapted).
22
3-
Usage, from bindings/python (needs a lightpanda binary for regeneration):
3+
Usage (needs a lightpanda binary for regeneration):
44
uv run --group docs python scripts/build_docs.py
55
"""
66

‎scripts/generate_methods.py‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""Generate lightpanda/_methods.py from the binary's tools/list schemas.
22
3-
Emits one concrete, annotated, documented method per browser tool (snake_case,
4-
with the original tool name aliased), all forwarding to ``Session.call``.
5-
Being real code, the methods are visible to IDEs, type checkers, and pdoc
6-
alike. Run from bindings/python with a binary available:
3+
Emits one concrete, annotated, documented method per browser tool, with the
4+
tool name and its parameters in snake_case, all forwarding to ``Session.call``
5+
(which maps them back to the schema's names). Being real code, the methods are
6+
visible to IDEs, type checkers, and pdoc alike. Run with a binary available:
77
88
uv run --no-project python scripts/generate_methods.py
99
@@ -27,8 +27,9 @@
2727
"""Generated by scripts/generate_methods.py — do not edit.
2828
2929
One method per lightpanda browser tool, signatures derived from the tool
30-
JSON schemas. camelCase aliases mirror the underlying tool names.
31-
``AsyncSessionMethods`` is the same surface with ``async def`` signatures.
30+
JSON schemas, with tool and parameter names in snake_case (the schemas'
31+
camelCase names still work through ``Session.call``). ``AsyncSessionMethods``
32+
is the same surface with ``async def`` signatures.
3233
"""
3334
3435
from __future__ import annotations
@@ -53,23 +54,27 @@ def method_source(name: str, spec: dict, is_async: bool = False) -> str:
5354
schema = spec["schema"]
5455
properties = schema.get("properties", {})
5556
required = set(schema.get("required", []))
56-
for prop in properties:
57-
if keyword.iskeyword(prop) or not prop.isidentifier():
57+
args = {prop: _snake(prop) for prop in properties}
58+
for prop, arg in args.items():
59+
if keyword.iskeyword(arg) or not arg.isidentifier():
5860
raise SystemExit(f"tool {name}: property {prop!r} is not a valid Python parameter")
61+
if len(set(args.values())) != len(args):
62+
raise SystemExit(f"tool {name}: properties collide once in snake_case: {sorted(args)}")
5963

6064
params = ["self"]
6165
if properties:
6266
params.append("*")
6367
forwards = []
6468
for prop in sorted(properties, key=lambda p: p not in required):
69+
arg = args[prop]
6570
py_type = PY_TYPES.get(properties[prop].get("type", ""), "Any")
6671
if name == "extract" and prop == "schema":
6772
py_type = "str | dict | list"
6873
if prop in required:
69-
params.append(f"{prop}: {py_type}")
74+
params.append(f"{arg}: {py_type}")
7075
else:
71-
params.append(f"{prop}: {py_type} | None = None")
72-
forwards.append(f"{prop}={prop}")
76+
params.append(f"{arg}: {py_type} | None = None")
77+
forwards.append(f"{arg}={arg}")
7378

7479
snake = _snake(name)
7580
call_args = ", ".join([f'"{name}"'] + forwards)
@@ -78,9 +83,6 @@ def method_source(name: str, spec: dict, is_async: bool = False) -> str:
7883
lines = [f" {prefix} {snake}({', '.join(params)}) -> Any:"]
7984
lines.append(docstring(spec["description"]))
8085
lines.append(f" return {await_}self.call({call_args})")
81-
if snake != name:
82-
lines.append("")
83-
lines.append(f" {name} = {snake}")
8486
return "\n".join(lines)
8587

8688

‎tests/test_async.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@
99
from lightpanda import AsyncBrowser, LightpandaError, ToolError, run_script_async
1010

1111

12-
async def test_goto_markdown_and_alias(abrowser, fixture_url):
12+
async def test_goto_markdown_and_snake_case(abrowser, fixture_url):
1313
async with abrowser.session() as page:
1414
await page.goto(url=f"{fixture_url}/index.html")
1515
assert "Hello from the fixture" in await page.markdown()
16-
assert await page.get_url() == await page.getUrl()
16+
assert (await page.get_url()).endswith("/index.html")
17+
assert not hasattr(page, "getUrl")
18+
assert await page.tree(max_depth=1) == await page.call("tree", maxDepth=1)
1719

1820

1921
async def test_concurrent_sessions_are_isolated(abrowser, fixture_url):

‎tests/test_browser.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,15 @@ def test_screenshot_inline_returns_png_bytes(browser, fixture_url):
4242
assert png.startswith(b"\x89PNG\r\n\x1a\n")
4343

4444

45-
def test_snake_case_alias(browser, fixture_url):
45+
def test_snake_case_only(browser, fixture_url):
4646
with browser.new_session() as page:
4747
page.goto(url=f"{fixture_url}/index.html")
48-
assert page.get_url() == page.getUrl()
48+
assert page.get_url().endswith("/index.html")
49+
assert not hasattr(page, "getUrl")
50+
# Parameters are snake_case too; call() also takes the schema's names.
51+
shallow = page.tree(max_depth=1)
52+
assert shallow == page.call("tree", maxDepth=1)
53+
assert len(str(shallow)) < len(str(page.tree()))
4954

5055

5156
def test_sessions_are_isolated(browser, fixture_url):

0 commit comments

Comments
 (0)