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,244 @@
1
+ """``webcompy inspect pyexec``: evaluate Python code in a harness PyScript interpreter.
2
+
3
+ Launches a single browser-harness session (the same boot path as the browser
4
+ test tier), evaluates the given code through the in-page ``evaluate``
5
+ gateway, and prints a structured JSON result. With ``--repl``, the session
6
+ stays alive and each stdin line is evaluated in turn, preserving interpreter
7
+ state. Evaluation is confined to the harness interpreter; it never targets a
8
+ production ``webcompy start`` server process.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import json
15
+ import queue
16
+ import signal
17
+ import sys
18
+ import threading
19
+ from argparse import Namespace
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING, Any
22
+
23
+ if TYPE_CHECKING:
24
+ from playwright.sync_api import Page
25
+
26
+ _READY_SENTINEL_SELECTOR = "html[data-webcompy-test-ready='1']"
27
+ _READY_TIMEOUT_SECONDS = 120.0
28
+ _DEFAULT_REPL_TIMEOUT_SECONDS = 300
29
+
30
+
31
+ class PyexecUsageError(SystemExit):
32
+ """Raised for invalid ``pyexec`` argument combinations (exit code 2)."""
33
+
34
+ def __init__(self, message: str) -> None:
35
+ super().__init__(2)
36
+ print(f"usage error: {message}", file=sys.stderr)
37
+
38
+
39
+ def register_pyexec_parser(subparsers: Any) -> None:
40
+ """Register the ``pyexec`` sub-subcommand on the ``inspect`` parser.
41
+
42
+ Args:
43
+ subparsers: The ``inspect`` command's subparsers action.
44
+
45
+ """
46
+ parser = subparsers.add_parser(
47
+ "pyexec",
48
+ help="Evaluate Python code inside a real PyScript interpreter",
49
+ description=(
50
+ "Evaluate Python code inside a real PyScript interpreter served by the "
51
+ "local browser test harness and print a structured JSON result."
52
+ ),
53
+ )
54
+ parser.add_argument("code", nargs="?", default=None, help="Python code to evaluate")
55
+ parser.add_argument("--file", default=None, help="Read the code from this file instead of CODE")
56
+ parser.add_argument(
57
+ "--repl",
58
+ action="store_true",
59
+ help="Keep the session alive; evaluate one stdin line per turn until EOF",
60
+ )
61
+ parser.add_argument(
62
+ "--repl-timeout",
63
+ type=int,
64
+ default=_DEFAULT_REPL_TIMEOUT_SECONDS,
65
+ help=f"REPL idle timeout in seconds (default: {_DEFAULT_REPL_TIMEOUT_SECONDS})",
66
+ )
67
+ parser.add_argument("--wait-for", dest="wait_for", default=None, help="CSS selector to wait for before evaluating")
68
+ parser.set_defaults(func=cmd_pyexec)
69
+
70
+
71
+ def resolve_code_source(args: Namespace) -> str | None:
72
+ """Resolve the code payload from CODE / --file for single-shot evaluation.
73
+
74
+ Args:
75
+ args: Parsed ``pyexec`` arguments.
76
+
77
+ Returns:
78
+ The code string to evaluate, or ``None`` in REPL mode.
79
+
80
+ Raises:
81
+ PyexecUsageError: On mutually exclusive or missing code sources, or
82
+ when ``--file`` does not exist.
83
+
84
+ """
85
+ if args.repl:
86
+ if args.code is not None or args.file is not None:
87
+ raise PyexecUsageError("--repl cannot be combined with CODE or --file")
88
+ return None
89
+ if args.code is not None and args.file is not None:
90
+ raise PyexecUsageError("CODE and --file are mutually exclusive")
91
+ if args.file is not None:
92
+ path = Path(args.file)
93
+ if not path.is_file():
94
+ raise PyexecUsageError(f"--file does not exist: {path}")
95
+ return path.read_text(encoding="utf-8")
96
+ if args.code is not None:
97
+ return args.code
98
+ raise PyexecUsageError("provide CODE, --file <path>, or --repl")
99
+
100
+
101
+ class _PyexecSession:
102
+ """One harness server plus one Playwright page bound to its lifetime."""
103
+
104
+ def __init__(self, wait_for: str | None = None) -> None:
105
+ from playwright.sync_api import sync_playwright
106
+
107
+ from webcompy_cli._browser_test_harness import create_harness_app, reserve_port, serve_harness
108
+
109
+ repo_root = Path.cwd()
110
+ cache_dir = repo_root / ".tmp" / "webcompy-browser-harness"
111
+ cache_dir.mkdir(parents=True, exist_ok=True)
112
+ port = reserve_port()
113
+ base_url = f"http://127.0.0.1:{port}/"
114
+ self._harness = create_harness_app(repo_root, cache_dir, base_url=base_url)
115
+ self._process = serve_harness(self._harness, port=port)
116
+ self._pw = sync_playwright().start()
117
+ self._browser = self._pw.chromium.launch(headless=True)
118
+ page = self._browser.new_page()
119
+ try:
120
+ page.goto(f"{base_url.rstrip('/')}/testharness", wait_until="domcontentloaded")
121
+ timeout_ms = int(_READY_TIMEOUT_SECONDS * 1000)
122
+ page.wait_for_selector(_READY_SENTINEL_SELECTOR, state="attached", timeout=timeout_ms)
123
+ except Exception as e:
124
+ self.close()
125
+ tail = "see harness console output above"
126
+ raise RuntimeError(
127
+ f"harness page did not become ready within {_READY_TIMEOUT_SECONDS:.0f}s ({tail})"
128
+ ) from e
129
+ if wait_for:
130
+ page.wait_for_selector(wait_for, timeout=30000)
131
+ self._page: Page = page
132
+
133
+ def evaluate(self, code: str) -> dict[str, Any]:
134
+ """Evaluate code through the in-page gateway and return its JSON payload.
135
+
136
+ Args:
137
+ code: Python source to evaluate.
138
+
139
+ Returns:
140
+ The parsed result payload with ``stdout``, ``stderr``,
141
+ ``result_repr``, ``console_error_delta``, ``exc_type``, and
142
+ ``traceback`` keys.
143
+
144
+ """
145
+ raw = self._page.evaluate("c => window.__webcompy_test__.evaluate(c)", code)
146
+ if isinstance(raw, (str, bytes)):
147
+ return json.loads(raw)
148
+ return raw
149
+
150
+ def close(self) -> None:
151
+ """Tear down the page, browser, Playwright driver, and harness server."""
152
+ from contextlib import suppress
153
+
154
+ with suppress(Exception):
155
+ self._page.close()
156
+ with suppress(Exception):
157
+ self._browser.close()
158
+ with suppress(Exception):
159
+ self._pw.stop()
160
+ with suppress(Exception):
161
+ from webcompy_cli._browser_test_harness import shutdown_harness
162
+
163
+ shutdown_harness(self._process)
164
+
165
+
166
+ def cmd_pyexec(args: Namespace) -> None:
167
+ """Run the ``pyexec`` subcommand (single-shot or REPL).
168
+
169
+ Args:
170
+ args: Parsed arguments carrying ``code``, ``file``, ``repl``,
171
+ ``repl_timeout``, and ``wait_for``.
172
+
173
+ """
174
+ from webcompy_cli._inspect import _check_playwright
175
+
176
+ _check_playwright()
177
+ code_source = resolve_code_source(args)
178
+
179
+ # Keep stdout clean: only JSON goes to stdout, harness logs go to stderr.
180
+ with contextlib.redirect_stdout(sys.stderr):
181
+ session = _PyexecSession(wait_for=args.wait_for)
182
+ try:
183
+ if args.repl:
184
+ sys.exit(_run_repl(session, args.repl_timeout))
185
+ print(json.dumps(session.evaluate(code_source or "")))
186
+ finally:
187
+ session.close()
188
+
189
+
190
+ def _run_repl(session: _PyexecSession, repl_timeout: int) -> int:
191
+ """Loop stdin lines through :meth:`_PyexecSession.evaluate`.
192
+
193
+ Each evaluated line prints one compact JSON object on its own line.
194
+ EOF (Ctrl-D) exits cleanly; SIGINT tears the session down; exceeding the
195
+ idle timeout exits with code 124.
196
+
197
+ Args:
198
+ session: The live harness session to evaluate against.
199
+ repl_timeout: Idle timeout in seconds between input lines.
200
+
201
+ Returns:
202
+ Process exit code: 0 on EOF, 130 on SIGINT, 124 on idle timeout.
203
+
204
+ """
205
+ lines: queue.Queue[str | None] = queue.Queue()
206
+
207
+ def read_stdin() -> None:
208
+ try:
209
+ for line in sys.stdin:
210
+ lines.put(line.rstrip("\n"))
211
+ finally:
212
+ lines.put(None)
213
+
214
+ reader = threading.Thread(target=read_stdin, daemon=True)
215
+ reader.start()
216
+
217
+ interrupted = False
218
+
219
+ def on_sigint(signum, frame):
220
+ nonlocal interrupted
221
+ interrupted = True
222
+ lines.put(None)
223
+
224
+ previous_sigint = signal.getsignal(signal.SIGINT)
225
+ signal.signal(signal.SIGINT, on_sigint)
226
+ exit_code = 0
227
+ try:
228
+ while True:
229
+ try:
230
+ line = lines.get(timeout=repl_timeout)
231
+ except queue.Empty:
232
+ print(json.dumps({"error": f"idle timeout after {repl_timeout}s"}), flush=True)
233
+ exit_code = 124
234
+ break
235
+ if line is None:
236
+ if interrupted:
237
+ exit_code = 130
238
+ break
239
+ if not line.strip():
240
+ continue
241
+ print(json.dumps(session.evaluate(line)), flush=True)
242
+ finally:
243
+ signal.signal(signal.SIGINT, previous_sigint)
244
+ return exit_code
webcompy_cli/_lock.py ADDED
@@ -0,0 +1,82 @@
1
+ """``webcompy lock`` command implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from webcompy_cli._argparser import get_params
8
+ from webcompy_cli._lockfile import LOCKFILE_NAME, resolve_lockfile
9
+ from webcompy_cli._lockfile_sync import (
10
+ discover_project_root,
11
+ discover_requirements_path,
12
+ export_requirements,
13
+ install_requirements,
14
+ record_requirements_path,
15
+ resolve_dependencies,
16
+ sync,
17
+ )
18
+ from webcompy_cli._utils import (
19
+ discover_config,
20
+ ensure_webcompy_modules_dir,
21
+ )
22
+ from webcompy_server._html import PYSCRIPT_VERSION
23
+
24
+
25
+ def lock_command() -> None:
26
+ _, args = get_params()
27
+ config = discover_config(args.get("config"))
28
+ resolve_dependencies(config)
29
+ assert config.dependencies is not None
30
+
31
+ export_flag = args.get("export", False)
32
+ sync_flag = args.get("sync", False)
33
+ install_flag = args.get("install", False)
34
+
35
+ if export_flag or sync_flag or install_flag:
36
+ lockfile_path = config.app_package_path / LOCKFILE_NAME
37
+
38
+ from webcompy_cli._lockfile import load_lockfile
39
+
40
+ lockfile = load_lockfile(lockfile_path)
41
+ if lockfile is None:
42
+ print("Error: Lock file not found. Run 'webcompy lock' first.", file=sys.stderr)
43
+ sys.exit(1)
44
+
45
+ requirements_path = discover_requirements_path(config.app_package_path, config.lockfile_sync_config)
46
+
47
+ if export_flag:
48
+ export_requirements(lockfile, requirements_path)
49
+ print(requirements_path)
50
+ if config.lockfile_sync_config is None or config.lockfile_sync_config.requirements_path is None:
51
+ record_requirements_path(config.app_package_path, requirements_path)
52
+ elif sync_flag:
53
+ project_root = discover_project_root(config.app_package_path)
54
+ report_lines = sync(
55
+ lockfile,
56
+ project_root,
57
+ config.lockfile_sync_config.sync_group if config.lockfile_sync_config else None,
58
+ )
59
+ for line in report_lines:
60
+ print(line)
61
+ elif install_flag:
62
+ install_requirements(lockfile, requirements_path)
63
+ else:
64
+ lockfile_path = config.app_package_path / LOCKFILE_NAME
65
+ modules_dir = config.app_package_path / ".webcompy_modules"
66
+ ensure_webcompy_modules_dir(modules_dir)
67
+ _lockfile, errors, warnings = resolve_lockfile(
68
+ config.dependencies,
69
+ PYSCRIPT_VERSION,
70
+ lockfile_path,
71
+ modules_dir,
72
+ wasm_serving=config.wasm_serving or "cdn",
73
+ runtime_serving=config.runtime_serving or "cdn",
74
+ standalone=config.standalone,
75
+ )
76
+ for warning in warnings:
77
+ print(f"Warning: {warning}", file=sys.stderr)
78
+ if errors:
79
+ for err in errors:
80
+ print(f"Error: {err}", file=sys.stderr)
81
+ sys.exit(1)
82
+ print(lockfile_path)