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,568 @@
1
+ """ASGI application factory and development server runner."""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import mimetypes
7
+ import os
8
+ import sys
9
+ from functools import partial
10
+ from importlib import import_module
11
+ from pathlib import Path
12
+ from typing import Any, Literal, cast
13
+
14
+ import aiofiles
15
+ import uvicorn
16
+ from sse_starlette.sse import EventSourceResponse
17
+ from starlette.exceptions import HTTPException
18
+ from starlette.requests import Request
19
+ from starlette.responses import FileResponse, Response
20
+ from starlette.routing import BaseRoute, Route
21
+ from starlette.types import ASGIApp
22
+
23
+ from webcompy.app._app import WebComPyApp
24
+ from webcompy.exception import WebComPyException
25
+ from webcompy_cli._argparser import get_params
26
+ from webcompy_cli._build import BuildArtifacts, resolve_build_artifacts
27
+ from webcompy_cli._exception import WebComPyCliException
28
+ from webcompy_cli._pwa import (
29
+ MANIFEST_FILENAME,
30
+ MANIFEST_MEDIA_TYPE,
31
+ PWA_OUTPUT_NAMES,
32
+ SW_FILENAME,
33
+ SW_MEDIA_TYPE,
34
+ generate_sw,
35
+ precache_entries_for_artifacts,
36
+ serialize_manifest,
37
+ )
38
+ from webcompy_cli._static_files import get_static_files
39
+ from webcompy_cli._utils import discover_config
40
+ from webcompy_cli.config._build_config import WebComPyBuildConfig
41
+ from webcompy_server._asgi import (
42
+ WEBCOMPY_PREBUILT_DIR_ENV,
43
+ _assemble_ssr_asgi,
44
+ _build_dynamic_static_routes,
45
+ _build_prebuilt_serving_components,
46
+ _resolve_mounts,
47
+ _resolve_static_routes,
48
+ )
49
+ from webcompy_server._html import PYSCRIPT_VERSION, generate_html, get_runtime_asset_prefix
50
+ from webcompy_server._prebuild import load_prebuild_manifest
51
+
52
+ _DEV_SERVER_ARGS_ENV = "_WEBCOMPY_DEV_SERVER_ARGS"
53
+ _logger = logging.getLogger(__name__)
54
+
55
+
56
+ class _ServingApp:
57
+ asgi: ASGIApp
58
+ html_generator: partial[Any]
59
+ hash_cache: list[str]
60
+ artifacts: BuildArtifacts | None
61
+ static_route_paths: tuple[str, ...]
62
+ needs_hash_prerender: bool
63
+
64
+ def __init__(
65
+ self,
66
+ asgi: ASGIApp,
67
+ html_generator: partial[Any],
68
+ hash_cache: list[str],
69
+ artifacts: BuildArtifacts | None = None,
70
+ static_route_paths: tuple[str, ...] = (),
71
+ needs_hash_prerender: bool = True,
72
+ ) -> None:
73
+ self.asgi = asgi
74
+ self.html_generator = html_generator
75
+ self.hash_cache = hash_cache
76
+ self.artifacts = artifacts
77
+ self.static_route_paths = static_route_paths
78
+ self.needs_hash_prerender = needs_hash_prerender
79
+
80
+
81
+ def create_asgi_app(
82
+ app: WebComPyApp,
83
+ build_config: WebComPyBuildConfig,
84
+ *,
85
+ mode: Literal["prod", "dev"] = "prod",
86
+ prebuilt_dir: str | Path | None = None,
87
+ serve_assets: bool = True,
88
+ ) -> _ServingApp:
89
+ """Create the ASGI application for serving the WebComPy app.
90
+
91
+ When ``prebuilt_dir`` is omitted, resolves build artifacts, wires static,
92
+ asset, and resource routes, and mounts the HTML and optional RPC and
93
+ dev-reload routes. When ``prebuilt_dir`` is given, loads
94
+ ``PrebuildManifest`` without running ``resolve_build_artifacts()``.
95
+
96
+ See https://webcompy.net/llms.txt for LLM-readable server CLI docs.
97
+
98
+ Args:
99
+ app: Application instance to serve.
100
+ build_config: Build configuration controlling artifact resolution.
101
+ mode: Serving mode, ``"prod"`` or ``"dev"``.
102
+ prebuilt_dir: Optional directory containing prebuilt artifacts. When
103
+ provided, ``mode="dev"`` is rejected, build-time artifact
104
+ resolution is skipped, and ``build_config.static_routes`` is not
105
+ re-evaluated because materialized static routes are served from the
106
+ prebuilt ``public/`` directory (use
107
+ ``webcompy_server.create_prebuilt_asgi_app(..., static_routes=...)``
108
+ when runtime static-route overrides are needed).
109
+ serve_assets: Whether asset and prebuilt static routes should be
110
+ served by the ASGI application.
111
+
112
+ Returns:
113
+ A ``_ServingApp`` wrapping the ASGI app and its serving metadata.
114
+
115
+ Raises:
116
+ WebComPyException: If ``prebuilt_dir`` is combined with ``mode="dev"``,
117
+ or if manifest/mount/route validation fails.
118
+
119
+ """
120
+ if prebuilt_dir is not None:
121
+ if mode == "dev":
122
+ raise WebComPyException("Cannot use mode='dev' with prebuilt_dir; prebuilt artifacts require mode='prod'.")
123
+ build_config.server.dev = False
124
+ manifest = load_prebuild_manifest(prebuilt_dir)
125
+ asgi, html_generator, hash_cache, static_route_paths, needs_hash_prerender = _build_prebuilt_serving_components(
126
+ app,
127
+ manifest,
128
+ mounts=build_config.server.mounts,
129
+ static_routes=None,
130
+ serve_assets=serve_assets,
131
+ )
132
+ return _ServingApp(
133
+ asgi=asgi,
134
+ html_generator=html_generator,
135
+ hash_cache=hash_cache,
136
+ artifacts=None,
137
+ static_route_paths=static_route_paths,
138
+ needs_hash_prerender=needs_hash_prerender,
139
+ )
140
+
141
+ build_config.server.dev = mode == "dev"
142
+ artifacts = resolve_build_artifacts(app, build_config, dev_mode=build_config.server.dev)
143
+
144
+ base_url = app.config.base_url
145
+
146
+ async def send_app_package_file(request: Request):
147
+ filename: str = request.path_params.get("filename", "") # type: ignore
148
+ if artifacts.app_package_files and filename in artifacts.app_package_files:
149
+ content, media_type = artifacts.app_package_files[filename]
150
+ headers: dict[str, str] = {}
151
+ if artifacts.dev_mode:
152
+ if artifacts.fw_wheel_filename and filename == artifacts.fw_wheel_filename:
153
+ headers["Cache-Control"] = "max-age=86400, must-revalidate"
154
+ else:
155
+ headers["Cache-Control"] = "no-cache"
156
+ else:
157
+ headers["Cache-Control"] = "public, max-age=31536000, immutable"
158
+ return Response(content, media_type=media_type, headers=headers)
159
+ else:
160
+ raise HTTPException(404)
161
+
162
+ app_package_files_route = Route(
163
+ "/_webcompy-app-package/{filename:path}",
164
+ send_app_package_file,
165
+ )
166
+
167
+ wasm_asset_routes: list[Route] = []
168
+ wasm_asset_files = artifacts.wasm_asset_files
169
+ if wasm_asset_files is not None: # wasm_asset_files is set only when wasm_serving == "local"
170
+
171
+ async def send_wasm_asset(request: Request):
172
+ filename: str = request.path_params.get("filename", "") # type: ignore
173
+ if filename in wasm_asset_files:
174
+ asset_path = wasm_asset_files[filename]
175
+ headers = {
176
+ "Cache-Control": (
177
+ "max-age=86400, must-revalidate"
178
+ if artifacts.dev_mode
179
+ else "public, max-age=31536000, immutable"
180
+ )
181
+ }
182
+ return FileResponse(asset_path, media_type="application/octet-stream", headers=headers)
183
+ else:
184
+ raise HTTPException(404)
185
+
186
+ wasm_asset_routes.append(Route("/_webcompy-assets/packages/{filename:path}", send_wasm_asset))
187
+
188
+ runtime_asset_routes: list[Route] = []
189
+ runtime_asset_files = artifacts.runtime_asset_files
190
+ if runtime_asset_files is not None: # runtime_asset_files is set only when runtime_serving == "local"
191
+
192
+ async def send_runtime_asset(request: Request):
193
+ filename: str = request.path_params.get("filename", "") # type: ignore
194
+ if filename in runtime_asset_files:
195
+ asset_path = runtime_asset_files[filename]
196
+ media_type = mimetypes.guess_type(str(asset_path))[0] or "application/octet-stream"
197
+ headers = {
198
+ "Cache-Control": (
199
+ "max-age=86400, must-revalidate"
200
+ if artifacts.dev_mode
201
+ else "public, max-age=31536000, immutable"
202
+ )
203
+ }
204
+ return FileResponse(asset_path, media_type=media_type, headers=headers)
205
+ else:
206
+ raise HTTPException(404)
207
+
208
+ runtime_prefix = get_runtime_asset_prefix(PYSCRIPT_VERSION)
209
+ runtime_asset_routes.append(Route(f"/{runtime_prefix}/{{filename:path}}", send_runtime_asset))
210
+
211
+ static_file_routes: list[Route] = []
212
+ static_files_dir = (build_config.app_package_path / build_config.static_files_dir).absolute()
213
+ static_relative_paths = get_static_files(static_files_dir)
214
+ static_url_prefix = "/" + base_url.strip("/") if base_url.strip("/") else ""
215
+ for relative_path in static_relative_paths:
216
+ static_file = static_files_dir / relative_path
217
+ if (media_type := mimetypes.guess_type(str(static_file))[0]) is None:
218
+ media_type = "application/octet-stream"
219
+
220
+ async def send_file(request: Request, _static_file=static_file, _media_type=media_type):
221
+ async with aiofiles.open(_static_file, "rb") as f:
222
+ content = await f.read()
223
+ return Response(content, media_type=_media_type)
224
+
225
+ static_file_routes.append(Route("/" + relative_path, send_file))
226
+ if static_url_prefix:
227
+ static_file_routes.append(Route(static_url_prefix + "/" + relative_path, send_file))
228
+
229
+ resource_routes: list[Route] = []
230
+ resource_allow_list = artifacts.resource_allow_list
231
+ if resource_allow_list is not None:
232
+ base_url_stripped = "/" + app.config.base_url.strip("/") if app.config.base_url.strip("/") else ""
233
+
234
+ async def send_resource(request: Request):
235
+ path: str = request.path_params.get("path", "") # type: ignore
236
+ if path not in resource_allow_list: # type: ignore[operator]
237
+ raise HTTPException(404)
238
+ try:
239
+ resolved = (build_config.app_package_path / path).resolve()
240
+ resolved.relative_to(build_config.app_package_path.resolve())
241
+ except (ValueError, OSError):
242
+ raise HTTPException(403) from None
243
+ media_type = mimetypes.guess_type(str(resolved))[0] or "application/octet-stream"
244
+ headers: dict[str, str] = {}
245
+ if artifacts.dev_mode:
246
+ headers["Cache-Control"] = "no-cache, must-revalidate"
247
+ elif request.query_params.get("v", "").strip():
248
+ headers["Cache-Control"] = "public, max-age=31536000, immutable"
249
+ else:
250
+ headers["Cache-Control"] = "public, max-age=3600"
251
+ return FileResponse(resolved, media_type=media_type, headers=headers)
252
+
253
+ resource_routes.append(Route(base_url_stripped + "/_webcompy-resource/{path:path}", send_resource))
254
+ if base_url_stripped:
255
+ resource_routes.append(Route("/_webcompy-resource/{path:path}", send_resource))
256
+
257
+ from webcompy.ui._styles import get_styles_file
258
+
259
+ async def send_framework_ui_css(request: Request):
260
+ filename: str = request.path_params.get("filename", "") # type: ignore
261
+ if "/" in filename or "\\" in filename or filename.startswith("."):
262
+ raise HTTPException(404)
263
+ if filename == "index.css" and not artifacts.dev_mode and artifacts.framework_ui_index_css is not None:
264
+ content: bytes | None = artifacts.framework_ui_index_css
265
+ else:
266
+ content = get_styles_file(filename)
267
+ if content is None:
268
+ raise HTTPException(404)
269
+ headers = {
270
+ "Cache-Control": (
271
+ "no-cache, must-revalidate" if artifacts.dev_mode else "public, max-age=0, must-revalidate"
272
+ )
273
+ }
274
+ return Response(content, media_type="text/css", headers=headers)
275
+
276
+ framework_ui_routes: list[Route] = [
277
+ Route("/_webcompy-ui/{filename:path}", send_framework_ui_css),
278
+ ]
279
+
280
+ pwa_enabled = build_config.pwa.enabled
281
+ pwa_routes: list[Route] = []
282
+ if pwa_enabled:
283
+ manifest_content = serialize_manifest(build_config.pwa, base_url).encode("utf-8")
284
+ precache = precache_entries_for_artifacts(build_config.pwa, artifacts)
285
+ sw_content = generate_sw(build_config.pwa, artifacts.app_version, precache).encode("utf-8")
286
+ base_url_prefix = "/" + base_url.strip("/") if base_url.strip("/") else ""
287
+
288
+ async def send_manifest(request: Request):
289
+ return Response(manifest_content, media_type=MANIFEST_MEDIA_TYPE)
290
+
291
+ async def send_service_worker(request: Request):
292
+ return Response(sw_content, media_type=SW_MEDIA_TYPE, headers={"Cache-Control": "no-cache"})
293
+
294
+ pwa_routes.append(Route(f"/{MANIFEST_FILENAME}", send_manifest))
295
+ pwa_routes.append(Route(f"/{SW_FILENAME}", send_service_worker))
296
+ if base_url_prefix:
297
+ pwa_routes.append(Route(f"{base_url_prefix}/{MANIFEST_FILENAME}", send_manifest))
298
+ pwa_routes.append(Route(f"{base_url_prefix}/{SW_FILENAME}", send_service_worker))
299
+ collisions = sorted(PWA_OUTPUT_NAMES.intersection(static_relative_paths))
300
+ if collisions:
301
+ print(
302
+ f"Warning: static files {collisions} are shadowed by framework-generated PWA files",
303
+ file=sys.stderr,
304
+ flush=True,
305
+ )
306
+
307
+ html_generator = partial(
308
+ generate_html,
309
+ app_package_name=build_config.app_package_path.name,
310
+ dev_mode=artifacts.dev_mode,
311
+ prerender=True,
312
+ wheel_filename=artifacts.wheel_filename,
313
+ pyodide_package_names=artifacts.pyodide_package_names,
314
+ wasm_local_urls=artifacts.wasm_local_urls,
315
+ lockfile_url=artifacts.lockfile_url,
316
+ runtime_serving=artifacts.runtime_serving,
317
+ extra_wheel_filenames=artifacts.extra_wheel_filenames,
318
+ app_package_path=build_config.app_package_path,
319
+ pwa_enabled=pwa_enabled,
320
+ asset_hashes=None if artifacts.dev_mode else artifacts.asset_hashes,
321
+ resource_version=None if artifacts.dev_mode else artifacts.resource_version,
322
+ )
323
+
324
+ # Mutable cache for hash-mode pre-rendered HTML
325
+ _hash_cache: list[str] = []
326
+
327
+ if build_config.server.dev:
328
+
329
+ async def loop():
330
+ while True:
331
+ await asyncio.sleep(60)
332
+ yield None
333
+
334
+ async def sse(_: Request):
335
+ return EventSourceResponse(loop())
336
+
337
+ dev_routes: list[BaseRoute] = [Route("/_webcompy_reload", endpoint=sse)]
338
+ else:
339
+ dev_routes = []
340
+
341
+ mount_entries = _resolve_mounts(app, build_config.server.mounts)
342
+
343
+ virtual_static_entries = _resolve_static_routes(
344
+ app,
345
+ build_config.static_routes,
346
+ static_relative_paths,
347
+ pwa_enabled=pwa_enabled,
348
+ mount_prefixes=tuple(prefix for prefix, _ in mount_entries),
349
+ )
350
+ virtual_static_routes = _build_dynamic_static_routes(
351
+ virtual_static_entries,
352
+ base_url_prefix=static_url_prefix,
353
+ dev_mode=artifacts.dev_mode,
354
+ )
355
+
356
+ asset_routes: list[BaseRoute] = (
357
+ [
358
+ app_package_files_route,
359
+ *wasm_asset_routes,
360
+ *runtime_asset_routes,
361
+ *framework_ui_routes,
362
+ *resource_routes,
363
+ *pwa_routes,
364
+ *static_file_routes,
365
+ ]
366
+ if serve_assets
367
+ else []
368
+ )
369
+
370
+ asgi = _assemble_ssr_asgi(
371
+ app,
372
+ html_generator=html_generator,
373
+ hash_cache=_hash_cache,
374
+ dev_routes=dev_routes,
375
+ asset_routes=asset_routes,
376
+ virtual_static_routes=virtual_static_routes,
377
+ mount_entries=mount_entries,
378
+ ssr_enabled=True,
379
+ serve_prerendered=False,
380
+ include_html_catchall=True,
381
+ configure_fetch=True,
382
+ )
383
+
384
+ return _ServingApp(
385
+ asgi=asgi,
386
+ html_generator=html_generator,
387
+ hash_cache=_hash_cache,
388
+ artifacts=artifacts,
389
+ static_route_paths=tuple(rel_path for rel_path, _ in virtual_static_entries),
390
+ )
391
+
392
+
393
+ async def _pre_render_hash_mode_html(
394
+ app: WebComPyApp,
395
+ html_generator: partial,
396
+ hash_cache: list[str],
397
+ ) -> None:
398
+ ctx = app.create_render_context("/")
399
+ try:
400
+ html = await html_generator(ctx)
401
+ hash_cache.append(html)
402
+ finally:
403
+ ctx.dispose()
404
+
405
+
406
+ def _apply_cli_overrides(build_config: WebComPyBuildConfig, args: dict[str, Any]) -> None:
407
+ serve_all_deps = args.get("serve_all_deps")
408
+ if serve_all_deps is not None:
409
+ build_config.serve_all_deps = serve_all_deps
410
+ wasm_serving = args.get("wasm_serving")
411
+ if wasm_serving is not None:
412
+ build_config.wasm_serving = wasm_serving
413
+ build_config._explicit_wasm_serving = wasm_serving
414
+ runtime_serving = args.get("runtime_serving")
415
+ if runtime_serving is not None:
416
+ build_config.runtime_serving = runtime_serving
417
+ build_config._explicit_runtime_serving = runtime_serving
418
+ standalone = args.get("standalone")
419
+ if standalone is not None:
420
+ build_config.standalone = standalone
421
+ wheel_mode = args.get("wheel_mode")
422
+ if wheel_mode is not None:
423
+ build_config.wheel_mode = wheel_mode
424
+ build_config.resolve_standalone()
425
+
426
+
427
+ def _create_dev_asgi_app() -> ASGIApp:
428
+ raw = os.environ.get(_DEV_SERVER_ARGS_ENV)
429
+ if not raw:
430
+ raise WebComPyException(f"Missing {_DEV_SERVER_ARGS_ENV} environment variable for dev server factory")
431
+ payload: dict[str, Any] = json.loads(raw)
432
+ app_module_name = payload.get("app_module")
433
+ if app_module_name:
434
+ mod = import_module(app_module_name)
435
+ build_config = WebComPyBuildConfig(mod)
436
+ else:
437
+ build_config = discover_config(payload.get("config"))
438
+ app = build_config.app
439
+ _apply_cli_overrides(build_config, payload)
440
+ assert app is not None
441
+ serving = create_asgi_app(app, build_config, mode="dev")
442
+ if app.router_mode != "history":
443
+ asyncio.run(_pre_render_hash_mode_html(app, serving.html_generator, serving.hash_cache))
444
+ return serving.asgi
445
+
446
+
447
+ def run_server(app: WebComPyApp | None = None):
448
+ """Run the development or production ASGI server.
449
+
450
+ Args:
451
+ app: Application instance to serve. When ``None``, the
452
+ configuration is discovered via ``discover_config`` and CLI
453
+ flags override the build and server options.
454
+
455
+ Raises:
456
+ WebComPyCliException: When ``--prebuilt`` is combined with ``--dev`` or
457
+ build-time override CLI flags.
458
+
459
+ """
460
+ _, args = get_params()
461
+ app_was_none = app is None
462
+ importable_app_module: str | None = None
463
+ if app is None:
464
+ build_config = discover_config(args.get("config"))
465
+ app = build_config.app
466
+ else:
467
+ import types as _types
468
+
469
+ app_module = None
470
+ for mod in sys.modules.values():
471
+ if isinstance(mod, _types.ModuleType) and mod.__name__ == app.__class__.__module__:
472
+ continue
473
+ if isinstance(mod, _types.ModuleType) and hasattr(mod, "app") and mod.app is app:
474
+ app_module = mod
475
+ break
476
+ if app_module is None:
477
+ from pathlib import Path as _Path
478
+
479
+ app_module = _types.ModuleType("_webcompy_app")
480
+ app_module.__file__ = str(_Path.cwd())
481
+ cast("Any", app_module).app = app
482
+ elif app_module.__name__ != "__main__":
483
+ importable_app_module = app_module.__name__
484
+ build_config = WebComPyBuildConfig(app_module)
485
+
486
+ prebuilt_arg = args.get("prebuilt")
487
+ if prebuilt_arg is not None:
488
+ incompatible: list[tuple[str, bool]] = [
489
+ ("--dev", bool(args.get("dev"))),
490
+ ("--serve-all-deps / --no-serve-all-deps", args.get("serve_all_deps") is not None),
491
+ ("--wasm-serving", args.get("wasm_serving") is not None),
492
+ ("--runtime-serving", args.get("runtime_serving") is not None),
493
+ ("--standalone / --no-standalone", args.get("standalone") is not None),
494
+ ("--wheel-mode", args.get("wheel_mode") is not None),
495
+ ]
496
+ for flag_name, is_set in incompatible:
497
+ if is_set:
498
+ raise WebComPyCliException(f"Cannot combine --prebuilt with {flag_name}.")
499
+
500
+ if isinstance(prebuilt_arg, str) and prebuilt_arg.strip():
501
+ raw_path = Path(prebuilt_arg.strip())
502
+ resolved_prebuilt = raw_path.resolve() if raw_path.is_absolute() else (Path.cwd() / raw_path).resolve()
503
+ elif env_dir := os.environ.get(WEBCOMPY_PREBUILT_DIR_ENV, "").strip():
504
+ resolved_prebuilt = Path(env_dir).resolve()
505
+ else:
506
+ resolved_prebuilt = (build_config.app_package_path / build_config.prebuild_dir).resolve()
507
+
508
+ port = args.get("port") or build_config.server.port
509
+ assert app is not None
510
+ serve_assets = not bool(args.get("no_serve_assets"))
511
+ serving = create_asgi_app(
512
+ app,
513
+ build_config,
514
+ mode="prod",
515
+ prebuilt_dir=resolved_prebuilt,
516
+ serve_assets=serve_assets,
517
+ )
518
+ if app.router_mode != "history" and getattr(serving, "needs_hash_prerender", True):
519
+ asyncio.run(_pre_render_hash_mode_html(app, serving.html_generator, serving.hash_cache))
520
+ uvicorn.run(serving.asgi, host="0.0.0.0", port=port, reload=False)
521
+ else:
522
+ _apply_cli_overrides(build_config, args)
523
+
524
+ port = args.get("port") or build_config.server.port
525
+ assert app is not None
526
+ is_dev = bool(args.get("dev") or build_config.server.dev)
527
+
528
+ if is_dev and (app_was_none or importable_app_module is not None):
529
+ payload = {
530
+ "config": args.get("config") if app_was_none else None,
531
+ "app_module": importable_app_module,
532
+ "serve_all_deps": args.get("serve_all_deps"),
533
+ "wasm_serving": args.get("wasm_serving"),
534
+ "runtime_serving": args.get("runtime_serving"),
535
+ "standalone": args.get("standalone"),
536
+ "wheel_mode": args.get("wheel_mode"),
537
+ }
538
+ prev_env = os.environ.get(_DEV_SERVER_ARGS_ENV)
539
+ os.environ[_DEV_SERVER_ARGS_ENV] = json.dumps(payload)
540
+ try:
541
+ uvicorn.run(
542
+ "webcompy_cli._server:_create_dev_asgi_app",
543
+ host="0.0.0.0",
544
+ port=port,
545
+ reload=True,
546
+ reload_dirs=[str(build_config.app_package_path)],
547
+ app_dir=os.getcwd(),
548
+ factory=True,
549
+ )
550
+ finally:
551
+ if prev_env is None:
552
+ os.environ.pop(_DEV_SERVER_ARGS_ENV, None)
553
+ else:
554
+ os.environ[_DEV_SERVER_ARGS_ENV] = prev_env
555
+ else:
556
+ if is_dev:
557
+ _logger.warning(
558
+ "File-watch reload is unavailable when passing a non-importable WebComPyApp directly to run_server(); "
559
+ "starting dev server with reload=False."
560
+ )
561
+
562
+ mode: Literal["prod", "dev"] = "dev" if is_dev else "prod"
563
+ serving = create_asgi_app(app, build_config, mode=mode)
564
+
565
+ if app.router_mode != "history" and getattr(serving, "needs_hash_prerender", True):
566
+ asyncio.run(_pre_render_hash_mode_html(app, serving.html_generator, serving.hash_cache))
567
+
568
+ uvicorn.run(serving.asgi, host="0.0.0.0", port=port, reload=False)
@@ -0,0 +1,27 @@
1
+ """Static file discovery for the development server."""
2
+
3
+ import os
4
+ import pathlib
5
+ from functools import partial
6
+ from re import compile as re_compile
7
+ from re import escape as re_escape
8
+
9
+ from webcompy_cli._exception import WebComPyCliException
10
+
11
+
12
+ def _list_up_files(target: pathlib.Path) -> list[pathlib.Path]:
13
+ if target.is_dir():
14
+ return [f for d in sorted(target.iterdir(), key=lambda p: p.name) for f in _list_up_files(d)]
15
+ return [target]
16
+
17
+
18
+ def get_static_files(static_file_dir: pathlib.Path):
19
+ static_file_dir = static_file_dir.absolute()
20
+ if not static_file_dir.exists():
21
+ raise WebComPyCliException(f"Static File dir '{static_file_dir}' does not exist")
22
+ elif not static_file_dir.is_dir():
23
+ raise WebComPyCliException(
24
+ f"'{static_file_dir}' is not directory",
25
+ )
26
+ get_relative_path = partial(re_compile("^" + re_escape(str(static_file_dir) + os.sep)).sub, "")
27
+ return tuple(sorted(get_relative_path(str(p)).replace("\\", "/") for p in _list_up_files(static_file_dir)))
webcompy_cli/_utils.py ADDED
@@ -0,0 +1,72 @@
1
+ """Shared utilities for config discovery and runtime directories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pathlib
6
+ from importlib import import_module
7
+
8
+ from webcompy_cli._exception import WebComPyCliException
9
+ from webcompy_cli.config._build_config import WebComPyBuildConfig
10
+
11
+
12
+ def discover_config(module_path: str | None = None) -> WebComPyBuildConfig:
13
+ """Discover and return the build configuration.
14
+
15
+ Args:
16
+ module_path: Dotted import path of the config module. When
17
+ ``None``, ``webcompy_config`` is imported.
18
+
19
+ Returns:
20
+ The ``WebComPyBuildConfig`` instance found in the module.
21
+
22
+ Raises:
23
+ WebComPyCliException: If the module cannot be imported, or the
24
+ ``config`` attribute is missing or has the wrong type.
25
+
26
+ """
27
+ if module_path:
28
+ try:
29
+ config_module = import_module(module_path)
30
+ except ModuleNotFoundError:
31
+ raise WebComPyCliException(
32
+ f"No python module named '{module_path}'",
33
+ ) from None
34
+ else:
35
+ try:
36
+ config_module = import_module("webcompy_config")
37
+ except ModuleNotFoundError:
38
+ raise WebComPyCliException(
39
+ "No python module named 'webcompy_config'. Provide --config flag or create webcompy_config.py.",
40
+ ) from None
41
+ config = getattr(config_module, "config", None)
42
+ if config is None:
43
+ raise WebComPyCliException(
44
+ "No 'config' attribute in config module. "
45
+ "Define 'config = WebComPyBuildConfig(app_module, ...)' in the config file.",
46
+ )
47
+ if not isinstance(config, WebComPyBuildConfig):
48
+ raise WebComPyCliException(
49
+ "'config' is not a WebComPyBuildConfig instance",
50
+ )
51
+ return config
52
+
53
+
54
+ def get_webcompy_packge_dir(path: pathlib.Path | None = None) -> pathlib.Path:
55
+ import webcompy
56
+
57
+ p = webcompy.__file__
58
+ assert p is not None
59
+ return pathlib.Path(p).parent
60
+
61
+
62
+ def ensure_webcompy_modules_dir(modules_dir: pathlib.Path) -> None:
63
+ modules_dir.mkdir(parents=True, exist_ok=True)
64
+ gitignore = modules_dir / ".gitignore"
65
+ if not gitignore.exists():
66
+ gitignore.write_text("*\n", encoding="utf-8")
67
+
68
+
69
+ def generate_app_version(app_version: str | None = None) -> str:
70
+ if app_version is not None:
71
+ return app_version
72
+ return "0.0.0"