webcompy-cli 0.0.14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. webcompy_cli/__init__.py +20 -0
  2. webcompy_cli/_argparser.py +232 -0
  3. webcompy_cli/_browser_probes.py +648 -0
  4. webcompy_cli/_browser_test_harness.py +554 -0
  5. webcompy_cli/_build.py +425 -0
  6. webcompy_cli/_console_types.py +15 -0
  7. webcompy_cli/_dependency_resolver.py +301 -0
  8. webcompy_cli/_dualrun_pytest_plugin.py +130 -0
  9. webcompy_cli/_exception.py +9 -0
  10. webcompy_cli/_generate.py +224 -0
  11. webcompy_cli/_init_project.py +54 -0
  12. webcompy_cli/_inspect.py +741 -0
  13. webcompy_cli/_inspect_pyexec.py +244 -0
  14. webcompy_cli/_lock.py +82 -0
  15. webcompy_cli/_lockfile.py +396 -0
  16. webcompy_cli/_lockfile_sync.py +343 -0
  17. webcompy_cli/_output.py +150 -0
  18. webcompy_cli/_prebuild.py +661 -0
  19. webcompy_cli/_pwa.py +474 -0
  20. webcompy_cli/_pyodide_downloader.py +113 -0
  21. webcompy_cli/_pyodide_lock.py +74 -0
  22. webcompy_cli/_runtime_downloader.py +222 -0
  23. webcompy_cli/_server.py +568 -0
  24. webcompy_cli/_static_files.py +27 -0
  25. webcompy_cli/_utils.py +72 -0
  26. webcompy_cli/_version_sweep.py +213 -0
  27. webcompy_cli/_wheel_builder.py +509 -0
  28. webcompy_cli/config/__init__.py +23 -0
  29. webcompy_cli/config/_build_config.py +168 -0
  30. webcompy_cli/config/_pwa_config.py +203 -0
  31. webcompy_cli/config/_server_config.py +53 -0
  32. webcompy_cli/py.typed +0 -0
  33. webcompy_cli/template_data/app/__init__.py +0 -0
  34. webcompy_cli/template_data/app/app.py +22 -0
  35. webcompy_cli/template_data/app/components/__init__.py +0 -0
  36. webcompy_cli/template_data/app/components/fizzbuzz.py +117 -0
  37. webcompy_cli/template_data/app/components/home.py +15 -0
  38. webcompy_cli/template_data/app/components/input.py +34 -0
  39. webcompy_cli/template_data/app/components/navigation.py +36 -0
  40. webcompy_cli/template_data/app/components/not_found.py +22 -0
  41. webcompy_cli/template_data/app/components/root.py +16 -0
  42. webcompy_cli/template_data/app/router.py +17 -0
  43. webcompy_cli/template_data/webcompy_config.py +12 -0
  44. webcompy_cli-0.0.14.dist-info/METADATA +53 -0
  45. webcompy_cli-0.0.14.dist-info/RECORD +47 -0
  46. webcompy_cli-0.0.14.dist-info/WHEEL +4 -0
  47. webcompy_cli-0.0.14.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,554 @@
1
+ """Starlette harness server that boots a real PyScript runtime for browser tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html as html_module
6
+ import json
7
+ import mimetypes
8
+ import os
9
+ import socket
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from importlib import import_module
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Literal
17
+
18
+ import uvicorn
19
+ from starlette.applications import Starlette
20
+ from starlette.exceptions import HTTPException
21
+ from starlette.responses import FileResponse, JSONResponse, Response
22
+ from starlette.routing import Route
23
+
24
+ if TYPE_CHECKING:
25
+ from starlette.requests import Request
26
+
27
+ from webcompy_cli._pyodide_downloader import download_pyodide_wheel
28
+ from webcompy_cli._pyodide_lock import fetch_pyodide_lock, get_pyodide_version
29
+ from webcompy_cli._runtime_downloader import download_runtime_assets
30
+ from webcompy_cli._utils import get_webcompy_packge_dir
31
+ from webcompy_cli._wheel_builder import make_browser_webcompy_wheel, make_wheel
32
+ from webcompy_server._html import PYSCRIPT_VERSION, get_runtime_asset_prefix
33
+
34
+ SUPPLY_MODE_ENV_VAR = "WEBCOMPY_BROWSER_SOURCE"
35
+ BROWSER_TEST_DIR = "tests/browser"
36
+ _HARNESS_WHEEL_VERSION = "0+harness"
37
+ _HARNESS_PYODIDE_PACKAGES: tuple[str, ...] = ("micropip", "httpx", "starlette", "anyio")
38
+ _WC_SRC_MOUNT_ROOT = "/home/pyodide/_wc_src"
39
+ _TESTS_MOUNT_PARENT = "/home/pyodide"
40
+ _FRAMEWORK_TREES: dict[str, str] = {
41
+ "webcompy": "packages/webcompy/src/webcompy",
42
+ "webcompy_testing": "packages/webcompy-testing/src/webcompy_testing",
43
+ "webcompy_server": "packages/webcompy-server/src/webcompy_server",
44
+ }
45
+ _MOUNTED_TREE_BASES: dict[str, str] = {
46
+ "tests": "tests",
47
+ "webcompy": "packages/webcompy/src",
48
+ "webcompy_testing": "packages/webcompy-testing/src",
49
+ "webcompy_server": "packages/webcompy-server/src",
50
+ }
51
+ _BOOT_TIMEOUT_SECONDS = 30.0
52
+
53
+ ConsoleCollectorJS = (
54
+ "window.__webcompy_test_console__=[];"
55
+ "(function(){var b=window.__webcompy_test_console__,o=console.error;"
56
+ 'console.error=function(){b.push({type:"error",'
57
+ "text:Array.prototype.slice.call(arguments).map(String).join(' ')});"
58
+ "o.apply(console,arguments)};"
59
+ 'window.addEventListener("error",function(e){'
60
+ 'b.push({type:"error",text:"uncaught: "+e.message})});})();'
61
+ )
62
+
63
+
64
+ def resolve_supply_mode() -> Literal["wheel", "source"]:
65
+ """Return the framework supply mode selected by ``WEBCOMPY_BROWSER_SOURCE``."""
66
+ if os.environ.get(SUPPLY_MODE_ENV_VAR) == "1":
67
+ return "source"
68
+ return "wheel"
69
+
70
+
71
+ def discover_test_modules(repo_root: Path) -> list[Path]:
72
+ """Return sorted repo-relative paths of test modules under ``tests/browser``."""
73
+ base = repo_root / BROWSER_TEST_DIR
74
+ if not base.is_dir():
75
+ return []
76
+ return sorted(p.relative_to(repo_root) for p in base.rglob("test_*.py") if p.is_file())
77
+
78
+
79
+ def merge_test_relpaths(repo_root: Path, dual_test_relpaths: list[str] | None) -> list[str]:
80
+ """Merge dual-run module paths and their package markers into the mount set.
81
+
82
+ Each dual-run path is appended after the browser-tier inventory (which is
83
+ never removed), plus every existing ancestor ``__init__.py`` so dotted
84
+ imports such as ``tests.test_signal`` resolve on the Emscripten FS.
85
+
86
+ Args:
87
+ repo_root: Repository root used to probe ancestor ``__init__.py``
88
+ files.
89
+ dual_test_relpaths: Repo-relative eligible test module paths, or
90
+ ``None`` to return only the browser-tier inventory.
91
+
92
+ Returns:
93
+ Sorted, deduplicated repo-relative paths to mount and list in the
94
+ manifest.
95
+
96
+ """
97
+ merged: dict[str, None] = {p.as_posix(): None for p in discover_test_modules(repo_root)}
98
+ extras: set[str] = set()
99
+ for rel in dual_test_relpaths or []:
100
+ rel_posix = Path(rel).as_posix()
101
+ extras.add(rel_posix)
102
+ parts = Path(rel_posix).parts[:-1]
103
+ for depth in range(1, len(parts) + 1):
104
+ candidate = Path(*parts[:depth]) / "__init__.py"
105
+ if (repo_root / candidate).is_file():
106
+ extras.add(candidate.as_posix())
107
+ for extra in sorted(extras):
108
+ merged.setdefault(extra, None)
109
+ return sorted(merged)
110
+
111
+
112
+ def collect_framework_source_files(repo_root: Path) -> dict[str, list[str]]:
113
+ """Map each framework package name to sorted POSIX paths under its ``src`` root."""
114
+ result: dict[str, list[str]] = {}
115
+ for pkg_name, tree_rel in _FRAMEWORK_TREES.items():
116
+ src_root = (repo_root / tree_rel).parent
117
+ result[pkg_name] = [
118
+ p.relative_to(src_root).as_posix()
119
+ for p in sorted(src_root.rglob("*.py"))
120
+ if p.is_file() and "__pycache__" not in p.parts
121
+ ]
122
+ return result
123
+
124
+
125
+ def build_py_config(
126
+ *,
127
+ base_url: str,
128
+ supply_mode: Literal["wheel", "source"],
129
+ wheel_names: list[str],
130
+ test_relpaths: list[str],
131
+ framework_files: dict[str, list[str]] | None = None,
132
+ pyodide_package_names: tuple[str, ...] = _HARNESS_PYODIDE_PACKAGES,
133
+ pyscript_version: str = PYSCRIPT_VERSION,
134
+ ) -> dict:
135
+ """Generate the harness py-config dictionary with parity to ``webcompy_server._html``.
136
+
137
+ Args:
138
+ base_url: Base URL where the harness server is mounted.
139
+ supply_mode: Package delivery mode, ``"wheel"`` or ``"source"``.
140
+ wheel_names: Built framework wheel filenames for wheel supply mode.
141
+ test_relpaths: Relative paths of browser test modules to mount.
142
+ framework_files: Framework source file mapping required when
143
+ ``supply_mode`` is ``"source"``.
144
+ pyodide_package_names: Pre-resolved Pyodide CDN package names.
145
+ pyscript_version: Target PyScript version whose local runtime prefix is
146
+ emitted in ``interpreter`` and ``lockFileURL``.
147
+
148
+ Returns:
149
+ Dictionary suitable for JSON serialization in ``<script type="py" config>``.
150
+
151
+ Raises:
152
+ ValueError: If ``supply_mode`` is ``"source"`` and ``framework_files`` is ``None``.
153
+
154
+ """
155
+ if supply_mode == "source" and framework_files is None:
156
+ raise ValueError("supply_mode='source' requires the framework source inventory (framework_files)")
157
+ normalized = base_url.rstrip("/")
158
+ runtime_prefix = get_runtime_asset_prefix(pyscript_version)
159
+ config: dict = {"experimental_create_proxy": "auto"}
160
+ files: dict[str, str] = {}
161
+ for rel in test_relpaths:
162
+ files[f"{normalized}/_webcompy-test/files/{rel}"] = f"{_TESTS_MOUNT_PARENT}/{rel}"
163
+ wheel_urls = [f"{normalized}/_webcompy-test/wheels/{name}" for name in wheel_names]
164
+ if supply_mode == "wheel":
165
+ config["packages"] = [*pyodide_package_names, *wheel_urls]
166
+ elif framework_files is not None:
167
+ for pkg_name, rels in framework_files.items():
168
+ for rel in rels:
169
+ files[f"{normalized}/_webcompy-test/files/{pkg_name}/{rel}"] = f"{_WC_SRC_MOUNT_ROOT}/{rel}"
170
+ config["packages"] = list(pyodide_package_names)
171
+ if files:
172
+ config["files"] = files
173
+ config["interpreter"] = f"{normalized}/{runtime_prefix}/pyodide/pyodide.mjs"
174
+ config["lockFileURL"] = f"{normalized}/{runtime_prefix}/pyodide/pyodide-lock.json"
175
+ return config
176
+
177
+
178
+ def bootstrap_lines(supply_mode: Literal["wheel", "source"]) -> str:
179
+ """Return the inline ``<script type=\"py\">`` lines that boot the in-page runner."""
180
+ lines = ["import sys"]
181
+ if supply_mode == "source":
182
+ lines.append(f'sys.path.insert(0, "{_WC_SRC_MOUNT_ROOT}")')
183
+ lines.append(f'sys.path.insert(0, "{_TESTS_MOUNT_PARENT}")')
184
+ lines.append("from webcompy_testing.browser_runner import bootstrap")
185
+ lines.append("bootstrap()")
186
+ return "\n".join(lines)
187
+
188
+
189
+ def generate_harness_html(
190
+ py_config: dict,
191
+ *,
192
+ base_url: str,
193
+ source_mounted: bool,
194
+ pyscript_version: str = PYSCRIPT_VERSION,
195
+ ) -> str:
196
+ """Render the harness page that boots PyScript with the given py-config.
197
+
198
+ Args:
199
+ py_config: Harness configuration dictionary to embed on ``<script type="py">``.
200
+ base_url: Base URL where the harness server is mounted.
201
+ source_mounted: Whether framework packages are source-mounted rather than wheels.
202
+ pyscript_version: Target PyScript version whose local ``core.js`` and
203
+ ``core.css`` paths are referenced.
204
+
205
+ Returns:
206
+ Rendered HTML document string for ``/testharness``.
207
+
208
+ """
209
+ normalized = base_url.rstrip("/")
210
+ runtime_prefix = get_runtime_asset_prefix(pyscript_version)
211
+ config_attr = html_module.escape(json.dumps(py_config), quote=True)
212
+ bootstrap = bootstrap_lines("source" if source_mounted else "wheel")
213
+ return (
214
+ "<!doctype html>"
215
+ "<html>"
216
+ "<head>"
217
+ f'<link rel="stylesheet" href="{normalized}/{runtime_prefix}/core.css">'
218
+ f'<script type="module" src="{normalized}/{runtime_prefix}/core.js"></script>'
219
+ "</head>"
220
+ "<body>"
221
+ '<div id="webcompy-app"></div>'
222
+ f"<script>{ConsoleCollectorJS}</script>"
223
+ f'<script type="py" config="{config_attr}">\n{bootstrap}\n</script>'
224
+ "</body>"
225
+ "</html>"
226
+ )
227
+
228
+
229
+ def _asset_media_type(filename: str) -> str:
230
+ if filename.endswith((".js", ".mjs")):
231
+ return "text/javascript"
232
+ if filename.endswith(".css"):
233
+ return "text/css"
234
+ if filename.endswith(".json"):
235
+ return "application/json"
236
+ return mimetypes.guess_type(filename)[0] or "application/octet-stream"
237
+
238
+
239
+ def _build_harness_wheels() -> dict[str, bytes]:
240
+ """Build the three framework wheels and read their bytes into memory."""
241
+ testing_pkg = Path(import_module("webcompy_testing").__file__).parent # type: ignore[arg-type]
242
+ server_pkg = Path(import_module("webcompy_server").__file__).parent # type: ignore[arg-type]
243
+ wheels: dict[str, bytes] = {}
244
+ with tempfile.TemporaryDirectory() as tmp:
245
+ dest = Path(tmp)
246
+ built = [
247
+ make_browser_webcompy_wheel(get_webcompy_packge_dir(), dest, _HARNESS_WHEEL_VERSION),
248
+ make_wheel("webcompy_testing", testing_pkg, dest, _HARNESS_WHEEL_VERSION),
249
+ make_wheel("webcompy_server", server_pkg, dest, _HARNESS_WHEEL_VERSION),
250
+ ]
251
+ for wheel_path in built:
252
+ wheels[wheel_path.name] = wheel_path.read_bytes()
253
+ return wheels
254
+
255
+
256
+ def resolve_pyodide_package_closure(
257
+ pyodide_version: str,
258
+ cache_dir: Path,
259
+ *,
260
+ package_names: tuple[str, ...],
261
+ ) -> tuple[str, ...]:
262
+ """Expand seed package names to their transitive dependency closure per the lock."""
263
+ pyodide_lock = fetch_pyodide_lock(pyodide_version, cache_dir)
264
+ packages = pyodide_lock.get("packages", {})
265
+ pending = list(package_names)
266
+ seen: set[str] = set()
267
+ while pending:
268
+ name = pending.pop()
269
+ if name in seen:
270
+ continue
271
+ seen.add(name)
272
+ info = packages.get(name)
273
+ if info is None:
274
+ continue
275
+ pending.extend(info.get("depends", []))
276
+ return tuple(sorted(seen))
277
+
278
+
279
+ def _pure_python_installable(info: dict) -> bool:
280
+ """Whether micropip can install this lock entry by name (pure Python wheel)."""
281
+ file_name = info.get("file_name", "")
282
+ return file_name.endswith("py3-none-any.whl")
283
+
284
+
285
+ def _installable_pyodide_packages(
286
+ cache_dir: Path,
287
+ pyodide_version: str,
288
+ closure: tuple[str, ...],
289
+ ) -> tuple[str, ...]:
290
+ """Filter a package closure to entries installable by name via micropip."""
291
+ packages = fetch_pyodide_lock(pyodide_version, cache_dir).get("packages", {})
292
+ return tuple(
293
+ name for name in closure if (info := packages.get(name)) is not None and _pure_python_installable(info)
294
+ )
295
+
296
+
297
+ def report_uninstallable_packages(closure: tuple[str, ...], installable: tuple[str, ...]) -> None:
298
+ """Warn about lock packages skipped because they lack a pure-Python wheel.
299
+
300
+ Entries without a ``py3-none-any.whl`` cannot be installed by name via
301
+ micropip and are silently absent from the harness page; a warning makes
302
+ the resulting in-page ImportError diagnosable.
303
+ """
304
+ installable_set = set(installable)
305
+ for name in closure:
306
+ if name not in installable_set:
307
+ print(
308
+ f"Warning: pyodide package '{name}' has no pure-Python wheel in the "
309
+ "lock and will NOT be available inside the harness page.",
310
+ flush=True,
311
+ )
312
+
313
+
314
+ def _ensure_pyodide_package_files(
315
+ runtime_assets: dict[str, tuple[Path, str]],
316
+ pyodide_version: str,
317
+ cache_dir: Path,
318
+ *,
319
+ package_names: tuple[str, ...],
320
+ pyscript_version: str,
321
+ ) -> None:
322
+ """Fetch the Pyodide-distribution wheels needed by the harness page locally.
323
+
324
+ ``micropip`` installs URL packages, while the framework's import chain
325
+ (``webcompy_testing`` -> ``webcompy_server.ports`` -> ``httpx`` /
326
+ ``starlette``) needs its third-party imports present in the interpreter.
327
+ ``package_names`` must already be a resolved dependency closure.
328
+
329
+ Args:
330
+ runtime_assets: Asset map (filename -> (path, sha256)) to extend.
331
+ pyodide_version: Pyodide distribution version.
332
+ cache_dir: Runtime asset cache root.
333
+ package_names: Resolved pyodide dependency closure.
334
+ pyscript_version: PyScript version key selecting the cache directory.
335
+
336
+ """
337
+ packages = fetch_pyodide_lock(pyodide_version, cache_dir).get("packages", {})
338
+ dest_dir = cache_dir / "runtime-assets" / pyscript_version / "pyodide"
339
+ for name in package_names:
340
+ info = packages.get(name)
341
+ if info is None:
342
+ continue
343
+ file_name = info.get("file_name")
344
+ sha256 = info.get("sha256")
345
+ if not file_name or not sha256:
346
+ continue
347
+ rel_key = f"pyodide/{file_name}"
348
+ if rel_key in runtime_assets:
349
+ continue
350
+ try:
351
+ wheel_path = download_pyodide_wheel(file_name, pyodide_version, sha256, cache_dir)
352
+ except Exception as e:
353
+ print(f"Warning: failed to fetch pyodide package {name}: {e}", flush=True)
354
+ continue
355
+ dest_dir.mkdir(parents=True, exist_ok=True)
356
+ dest = dest_dir / file_name
357
+ if dest != wheel_path:
358
+ dest.write_bytes(wheel_path.read_bytes())
359
+ runtime_assets[rel_key] = (dest, sha256)
360
+
361
+
362
+ @dataclass
363
+ class HarnessServer:
364
+ """Harness Starlette application plus the metadata drivers need."""
365
+
366
+ asgi: Starlette
367
+ py_config: dict
368
+ manifest_modules: list[str]
369
+ supply_mode: Literal["wheel", "source"]
370
+ wheel_filenames: list[str] = field(default_factory=list)
371
+
372
+
373
+ def create_harness_app(
374
+ repo_root: Path,
375
+ cache_dir: Path,
376
+ *,
377
+ base_url: str,
378
+ supply_mode: Literal["wheel", "source"] | None = None,
379
+ dual_test_relpaths: list[str] | None = None,
380
+ pyscript_version: str | None = None,
381
+ ) -> HarnessServer:
382
+ """Assemble the harness application serving assets, files, config, manifest, and page.
383
+
384
+ Args:
385
+ repo_root: Repository root containing tests and framework sources.
386
+ cache_dir: Runtime asset cache root.
387
+ base_url: Base URL the harness page is served under.
388
+ supply_mode: Framework supply mode override (default resolved from
389
+ ``WEBCOMPY_BROWSER_SOURCE``).
390
+ dual_test_relpaths: Extra eligible test modules to mount and expose
391
+ via the manifest for the dual-run sweep.
392
+ pyscript_version: PyScript version to serve runtime assets for;
393
+ defaults to the pinned ``PYSCRIPT_VERSION``. Used by the
394
+ version-bump sweep to boot a candidate interpreter without
395
+ changing the pin.
396
+
397
+ Returns:
398
+ The assembled harness application plus driver-facing metadata.
399
+
400
+ """
401
+ mode = supply_mode or resolve_supply_mode()
402
+ version = pyscript_version or PYSCRIPT_VERSION
403
+ print(
404
+ f"[webcompy-browser-harness] preparing runtime assets ({mode} mode, pyscript {version})...",
405
+ flush=True,
406
+ )
407
+ pyodide_version = get_pyodide_version(version)
408
+ runtime_assets = download_runtime_assets(
409
+ pyodide_version,
410
+ version,
411
+ cache_dir,
412
+ )
413
+ package_closure = resolve_pyodide_package_closure(
414
+ pyodide_version,
415
+ cache_dir,
416
+ package_names=_HARNESS_PYODIDE_PACKAGES,
417
+ )
418
+ installable = _installable_pyodide_packages(cache_dir, pyodide_version, package_closure)
419
+ report_uninstallable_packages(package_closure, installable)
420
+ _ensure_pyodide_package_files(
421
+ runtime_assets,
422
+ pyodide_version,
423
+ cache_dir,
424
+ package_names=package_closure,
425
+ pyscript_version=version,
426
+ )
427
+ test_rels = merge_test_relpaths(repo_root, dual_test_relpaths)
428
+ manifest_modules = [rel[: -len(".py")].replace("/", ".") for rel in test_rels]
429
+
430
+ wheel_names: list[str] = []
431
+ framework_files: dict[str, list[str]] | None = None
432
+ wheel_bytes: dict[str, bytes] = {}
433
+ if mode == "wheel":
434
+ wheel_bytes = _build_harness_wheels()
435
+ wheel_names = sorted(wheel_bytes)
436
+ else:
437
+ framework_files = collect_framework_source_files(repo_root)
438
+
439
+ py_config = build_py_config(
440
+ base_url=base_url,
441
+ supply_mode=mode,
442
+ wheel_names=wheel_names,
443
+ test_relpaths=test_rels,
444
+ framework_files=framework_files,
445
+ pyodide_package_names=installable,
446
+ pyscript_version=version,
447
+ )
448
+ harness_html = generate_harness_html(
449
+ py_config,
450
+ base_url=base_url,
451
+ source_mounted=mode == "source",
452
+ pyscript_version=version,
453
+ )
454
+
455
+ async def send_runtime_asset(request: Request):
456
+ filename: str = request.path_params.get("filename", "") # type: ignore[assignment]
457
+ entry = runtime_assets.get(filename)
458
+ if entry is None:
459
+ raise HTTPException(404)
460
+ return FileResponse(entry[0], media_type=_asset_media_type(filename))
461
+
462
+ async def send_mounted_file(request: Request):
463
+ tree: str = request.path_params.get("tree", "") # type: ignore[assignment]
464
+ rel: str = request.path_params.get("path", "") # type: ignore[assignment]
465
+ tree_base = _MOUNTED_TREE_BASES.get(tree)
466
+ if tree_base is None or not rel:
467
+ raise HTTPException(404)
468
+ base_dir = (repo_root / tree_base).resolve()
469
+ target = (base_dir / rel).resolve()
470
+ try:
471
+ target.relative_to(base_dir)
472
+ except ValueError:
473
+ raise HTTPException(403) from None
474
+ if not target.is_file():
475
+ raise HTTPException(404)
476
+ return FileResponse(target, media_type=_asset_media_type(target.name))
477
+
478
+ async def send_wheel(request: Request):
479
+ filename: str = request.path_params.get("filename", "") # type: ignore[assignment]
480
+ content = wheel_bytes.get(filename)
481
+ if content is None:
482
+ raise HTTPException(404)
483
+ return Response(content, media_type="application/zip")
484
+
485
+ async def send_config(request: Request):
486
+ return JSONResponse(py_config)
487
+
488
+ async def send_manifest(request: Request):
489
+ return JSONResponse({"modules": manifest_modules})
490
+
491
+ async def send_testharness(request: Request):
492
+ return Response(harness_html, media_type="text/html")
493
+
494
+ runtime_prefix = get_runtime_asset_prefix(version)
495
+ routes = [
496
+ Route(f"/{runtime_prefix}/{{filename:path}}", send_runtime_asset),
497
+ Route("/_webcompy-test/files/{tree}/{path:path}", send_mounted_file),
498
+ Route("/_webcompy-test/wheels/{filename}", send_wheel),
499
+ Route("/_webcompy-test/config.json", send_config),
500
+ Route("/_webcompy-test/manifest.json", send_manifest),
501
+ Route("/testharness", send_testharness),
502
+ ]
503
+ return HarnessServer(
504
+ asgi=Starlette(routes=routes),
505
+ py_config=py_config,
506
+ manifest_modules=manifest_modules,
507
+ supply_mode=mode,
508
+ wheel_filenames=wheel_names,
509
+ )
510
+
511
+
512
+ @dataclass
513
+ class HarnessProcess:
514
+ """A running harness server bound to an ephemeral local port."""
515
+
516
+ server: uvicorn.Server
517
+ thread: threading.Thread
518
+ port: int
519
+
520
+
521
+ def reserve_port(host: str = "127.0.0.1") -> int:
522
+ """Reserve an ephemeral TCP port by binding and immediately releasing it."""
523
+ probe = socket.socket()
524
+ probe.bind((host, 0))
525
+ port = probe.getsockname()[1]
526
+ probe.close()
527
+ return port
528
+
529
+
530
+ def serve_harness(
531
+ harness: HarnessServer,
532
+ *,
533
+ host: str = "127.0.0.1",
534
+ port: int | None = None,
535
+ ) -> HarnessProcess:
536
+ """Run the harness ASGI app with uvicorn in a daemon thread."""
537
+ if port is None:
538
+ port = reserve_port(host)
539
+ config = uvicorn.Config(harness.asgi, host=host, port=port, log_level="warning", log_config=None)
540
+ server = uvicorn.Server(config)
541
+ thread = threading.Thread(target=server.run, daemon=True)
542
+ thread.start()
543
+ deadline = time.monotonic() + _BOOT_TIMEOUT_SECONDS
544
+ while not server.started:
545
+ if time.monotonic() > deadline:
546
+ raise RuntimeError("Harness server failed to start within the timeout.")
547
+ time.sleep(0.05)
548
+ return HarnessProcess(server=server, thread=thread, port=port)
549
+
550
+
551
+ def shutdown_harness(process: HarnessProcess) -> None:
552
+ """Stop the harness server thread."""
553
+ process.server.should_exit = True
554
+ process.thread.join(timeout=5)