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,301 @@
1
+ """Classification of application dependencies for browser deployment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.metadata
6
+ import importlib.util
7
+ import pathlib
8
+ from dataclasses import dataclass
9
+ from enum import Enum
10
+ from typing import Literal
11
+
12
+
13
+ class PackageKind(Enum):
14
+ WASM = "wasm"
15
+ CDN_PURE_PYTHON = "cdn_pure_python"
16
+ LOCAL_PURE_PYTHON = "local_pure_python"
17
+
18
+
19
+ @dataclass
20
+ class ClassifiedDependency:
21
+ name: str
22
+ version: str
23
+ source: Literal["explicit", "transitive"]
24
+ kind: PackageKind
25
+ pyodide_file_name: str | None = None
26
+ pyodide_sha256: str | None = None
27
+ pkg_dir: pathlib.Path | None = None
28
+
29
+
30
+ def _is_pure_python_package(pkg_dir: pathlib.Path) -> bool:
31
+ for _root, _dirs, files in pkg_dir.walk():
32
+ for f in files:
33
+ if f.endswith((".so", ".pyd", ".dylib")):
34
+ return False
35
+ return True
36
+
37
+
38
+ def _classify_from_pyodide_lock(pkg_name: str, pyodide_lock: dict) -> PackageKind | None:
39
+ packages = pyodide_lock.get("packages", {})
40
+ pkg_info = packages.get(pkg_name)
41
+ if pkg_info is None:
42
+ return None
43
+ file_name = pkg_info.get("file_name", "")
44
+ if "wasm32" in file_name:
45
+ return PackageKind.WASM
46
+ return PackageKind.CDN_PURE_PYTHON
47
+
48
+
49
+ def _find_package_dir(package_name: str) -> pathlib.Path | None:
50
+ normalized = package_name.replace("-", "_").replace(".", "_")
51
+ spec = importlib.util.find_spec(normalized)
52
+ if spec is None:
53
+ spec = importlib.util.find_spec(package_name)
54
+ if spec is None:
55
+ return None
56
+ if spec.origin is None:
57
+ if spec.submodule_search_locations:
58
+ for loc in spec.submodule_search_locations:
59
+ p = pathlib.Path(loc)
60
+ if p.is_dir():
61
+ return p
62
+ return None
63
+ origin = pathlib.Path(spec.origin)
64
+ if origin.is_file() and origin.name == "__init__.py":
65
+ return origin.parent
66
+ if origin.is_file():
67
+ return origin.parent
68
+ return None
69
+
70
+
71
+ def _get_package_version(package_name: str) -> str | None:
72
+ normalized = package_name.replace("-", "_")
73
+ try:
74
+ return importlib.metadata.version(normalized)
75
+ except importlib.metadata.PackageNotFoundError:
76
+ pass
77
+ try:
78
+ return importlib.metadata.version(package_name)
79
+ except importlib.metadata.PackageNotFoundError:
80
+ return None
81
+
82
+
83
+ def _resolve_transitive_deps_via_pyodide_lock(
84
+ package_name: str,
85
+ pyodide_lock: dict,
86
+ visited: set[str] | None = None,
87
+ ) -> set[str]:
88
+ if visited is None:
89
+ visited = set()
90
+ if package_name in visited:
91
+ return set()
92
+ visited.add(package_name)
93
+ packages = pyodide_lock.get("packages", {})
94
+ pkg_info = packages.get(package_name)
95
+ if pkg_info is None:
96
+ return set()
97
+ result: set[str] = set()
98
+ for dep in pkg_info.get("depends", []):
99
+ dep_name = dep.split("[")[0].split(";")[0].strip()
100
+ if dep_name and dep_name in packages:
101
+ result.add(dep_name)
102
+ result |= _resolve_transitive_deps_via_pyodide_lock(dep_name, pyodide_lock, visited)
103
+ return result
104
+
105
+
106
+ def _get_pyodide_sha256(pkg_name: str, pyodide_lock: dict) -> str | None:
107
+ packages = pyodide_lock.get("packages", {})
108
+ pkg_info = packages.get(pkg_name)
109
+ if pkg_info is None:
110
+ return None
111
+ return pkg_info.get("sha256")
112
+
113
+
114
+ def _resolve_transitive_deps_local(package_name: str) -> set[str]:
115
+ try:
116
+ reqs = importlib.metadata.requires(package_name)
117
+ except importlib.metadata.PackageNotFoundError:
118
+ try:
119
+ reqs = importlib.metadata.requires(package_name.replace("-", "_"))
120
+ except importlib.metadata.PackageNotFoundError:
121
+ return set()
122
+ if reqs is None:
123
+ return set()
124
+ result: set[str] = set()
125
+ for req_str in reqs:
126
+ dep_part = req_str.split(";")[0].strip()
127
+ marker_part = req_str.split(";")[1].strip() if ";" in req_str else ""
128
+ if marker_part:
129
+ try:
130
+ from packaging.markers import Marker
131
+
132
+ if not Marker(marker_part).evaluate():
133
+ continue
134
+ except Exception:
135
+ continue
136
+ dep_name = dep_part.split(">")[0].split("<")[0].split("=")[0].split("!")[0].split("~")[0].strip()
137
+ dep_name = dep_name.split("[")[0].strip()
138
+ if dep_name and dep_name[0].isalpha():
139
+ result.add(dep_name)
140
+ return result
141
+
142
+
143
+ def classify_dependencies(
144
+ dependencies: list[str],
145
+ pyodide_lock: dict,
146
+ ) -> tuple[list[ClassifiedDependency], list[str], list[str]]:
147
+ classified: list[ClassifiedDependency] = []
148
+ errors: list[str] = []
149
+ warnings: list[str] = []
150
+ seen: dict[str, ClassifiedDependency] = {}
151
+
152
+ for dep_name in dependencies:
153
+ norm_name = dep_name.replace("-", "_")
154
+ if norm_name in seen:
155
+ continue
156
+ pkg_info = pyodide_lock.get("packages", {}).get(dep_name)
157
+ if pkg_info is not None:
158
+ kind = _classify_from_pyodide_lock(dep_name, pyodide_lock)
159
+ version = pkg_info.get("version", "0.0.0")
160
+ file_name = pkg_info.get("file_name", "")
161
+ sha256 = _get_pyodide_sha256(dep_name, pyodide_lock)
162
+ if kind == PackageKind.WASM:
163
+ classified_dep = ClassifiedDependency(
164
+ name=dep_name,
165
+ version=version,
166
+ source="explicit",
167
+ kind=PackageKind.WASM,
168
+ pyodide_file_name=file_name,
169
+ pyodide_sha256=sha256,
170
+ pkg_dir=None,
171
+ )
172
+ else:
173
+ assert kind is not None
174
+ pkg_dir = _find_package_dir(dep_name)
175
+ classified_dep = ClassifiedDependency(
176
+ name=dep_name,
177
+ version=version,
178
+ source="explicit",
179
+ kind=kind,
180
+ pyodide_file_name=file_name,
181
+ pyodide_sha256=sha256,
182
+ pkg_dir=pkg_dir,
183
+ )
184
+ classified.append(classified_dep)
185
+ seen[norm_name] = classified_dep
186
+ else:
187
+ pkg_dir = _find_package_dir(dep_name)
188
+ if pkg_dir is None:
189
+ errors.append(
190
+ f"Package '{dep_name}' not found locally and not in Pyodide CDN. "
191
+ f"Install it locally or add it to WebComPyBuildConfig.dependencies."
192
+ )
193
+ continue
194
+ if not _is_pure_python_package(pkg_dir):
195
+ errors.append(
196
+ f"Package '{dep_name}' is a C extension and is not available in Pyodide. "
197
+ f"Consider using a pure-Python alternative."
198
+ )
199
+ continue
200
+ version = _get_package_version(dep_name) or "0.0.0"
201
+ classified_dep = ClassifiedDependency(
202
+ name=dep_name,
203
+ version=version,
204
+ source="explicit",
205
+ kind=PackageKind.LOCAL_PURE_PYTHON,
206
+ pyodide_file_name=None,
207
+ pyodide_sha256=None,
208
+ pkg_dir=pkg_dir,
209
+ )
210
+ classified.append(classified_dep)
211
+ seen[norm_name] = classified_dep
212
+
213
+ _resolve_all_transitives(classified, seen, pyodide_lock, errors, warnings)
214
+
215
+ return classified, errors, warnings
216
+
217
+
218
+ def _resolve_all_transitives(
219
+ classified: list[ClassifiedDependency],
220
+ seen: dict[str, ClassifiedDependency],
221
+ pyodide_lock: dict,
222
+ errors: list[str],
223
+ warnings: list[str],
224
+ ) -> None:
225
+ all_deps_to_process = list(classified)
226
+ visited_for_transitive: set[str] = {d.name.replace("-", "_") for d in classified}
227
+
228
+ while all_deps_to_process:
229
+ dep = all_deps_to_process.pop(0)
230
+ dep_name = dep.name
231
+
232
+ transitive_names = list(_resolve_transitive_deps_via_pyodide_lock(dep_name, pyodide_lock))
233
+
234
+ if dep.kind == PackageKind.LOCAL_PURE_PYTHON and dep.pkg_dir is not None:
235
+ local_transitives = _resolve_transitive_deps_local(dep_name)
236
+ for lt in local_transitives:
237
+ if lt not in transitive_names:
238
+ transitive_names.append(lt)
239
+
240
+ for trans_name in transitive_names:
241
+ trans_norm = trans_name.replace("-", "_")
242
+ if trans_norm in seen:
243
+ continue
244
+ if trans_norm in visited_for_transitive:
245
+ continue
246
+ visited_for_transitive.add(trans_norm)
247
+
248
+ pkg_info = pyodide_lock.get("packages", {}).get(trans_name)
249
+ if pkg_info is not None:
250
+ kind = _classify_from_pyodide_lock(trans_name, pyodide_lock)
251
+ version = pkg_info.get("version", "0.0.0")
252
+ file_name = pkg_info.get("file_name", "")
253
+ sha256 = _get_pyodide_sha256(trans_name, pyodide_lock)
254
+ if kind == PackageKind.WASM:
255
+ classified_dep = ClassifiedDependency(
256
+ name=trans_name,
257
+ version=version,
258
+ source="transitive",
259
+ kind=PackageKind.WASM,
260
+ pyodide_file_name=file_name,
261
+ pyodide_sha256=sha256,
262
+ pkg_dir=None,
263
+ )
264
+ else:
265
+ assert kind is not None
266
+ pkg_dir = _find_package_dir(trans_name)
267
+ classified_dep = ClassifiedDependency(
268
+ name=trans_name,
269
+ version=version,
270
+ source="transitive",
271
+ kind=kind,
272
+ pyodide_file_name=file_name,
273
+ pyodide_sha256=sha256,
274
+ pkg_dir=pkg_dir,
275
+ )
276
+ classified.append(classified_dep)
277
+ seen[trans_norm] = classified_dep
278
+ all_deps_to_process.append(classified_dep)
279
+ else:
280
+ pkg_dir = _find_package_dir(trans_name)
281
+ if pkg_dir is None:
282
+ warnings.append(
283
+ f"Transitive dependency '{trans_name}' not found locally "
284
+ f"and not in Pyodide CDN. Consider adding it to WebComPyBuildConfig.dependencies."
285
+ )
286
+ continue
287
+ if not _is_pure_python_package(pkg_dir):
288
+ continue
289
+ version = _get_package_version(trans_name) or "0.0.0"
290
+ classified_dep = ClassifiedDependency(
291
+ name=trans_name,
292
+ version=version,
293
+ source="transitive",
294
+ kind=PackageKind.LOCAL_PURE_PYTHON,
295
+ pyodide_file_name=None,
296
+ pyodide_sha256=None,
297
+ pkg_dir=pkg_dir,
298
+ )
299
+ classified.append(classified_dep)
300
+ seen[trans_norm] = classified_dep
301
+ all_deps_to_process.append(classified_dep)
@@ -0,0 +1,130 @@
1
+ """Pytest plugin recording per-test outcomes for the dual-run sweep.
2
+
3
+ Loaded in the CPython-side subprocess via
4
+ ``pytest -p webcompy_cli._dualrun_pytest_plugin``. When the environment
5
+ variable ``WEBCOMPY_DUALRUN_REPORT`` points at a file path, the plugin writes
6
+ a JSON report of ``{nodeid: outcome}`` plus a nodeid-to-parametrize-index map
7
+ at session finish; without the variable it stays inert so ordinary runs are
8
+ unaffected.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ from typing import Any
17
+
18
+ _DISPLAY_SUFFIX_RE = re.compile(r"\[[^\[\]]*\]$")
19
+ _OUTCOME_PRECEDENCE = {"failed": 3, "skipped": 2, "passed": 1}
20
+
21
+ _OUTCOMES: dict[str, str] = {}
22
+ _PARAM_INDICES: dict[str, int] = {}
23
+
24
+
25
+ def _parametrize_index_of(item: Any) -> int | None:
26
+ """Derive the machine parametrize index for one collected item.
27
+
28
+ Mirrors the browser-tier conftest algorithm: match the item's resolved
29
+ callspec params against the declared values list of its single
30
+ ``@pytest.mark.parametrize`` mark.
31
+
32
+ Args:
33
+ item: A collected pytest item.
34
+
35
+ Returns:
36
+ The zero-based index within the declared values, or ``None`` when the
37
+ item is not parametrized or the values cannot be matched uniquely.
38
+
39
+ """
40
+ callspec = getattr(item, "callspec", None)
41
+ if callspec is None:
42
+ return None
43
+ marks = [mark for mark in getattr(item.function, "pytestmark", []) if mark.name == "parametrize"]
44
+ if not marks:
45
+ return None
46
+ raw_names, values = marks[0].args
47
+ names = (
48
+ [name.strip() for name in raw_names.split(",")] if isinstance(raw_names, str) else [str(n) for n in raw_names]
49
+ )
50
+ actual = tuple(callspec.params[name] for name in names)
51
+ matches: list[int] = []
52
+ for index, value in enumerate(values):
53
+ candidate = (value,) if len(names) == 1 else tuple(value)
54
+ expected = (actual[0],) if len(names) == 1 else actual
55
+ if candidate == expected:
56
+ matches.append(index)
57
+ return matches[0] if len(matches) == 1 else None
58
+
59
+
60
+ def pytest_configure(config: Any) -> None:
61
+ """Reset per-run recording state.
62
+
63
+ Args:
64
+ config: The pytest config object starting the session.
65
+
66
+ Returns:
67
+ ``None``.
68
+
69
+ """
70
+ _OUTCOMES.clear()
71
+ _PARAM_INDICES.clear()
72
+
73
+
74
+ def pytest_collection_finish(session: Any) -> None:
75
+ """Record every collected item's node id and parametrize index.
76
+
77
+ Args:
78
+ session: The pytest session that finished collection.
79
+
80
+ Returns:
81
+ ``None``.
82
+
83
+ """
84
+ for item in session.items:
85
+ index = _parametrize_index_of(item)
86
+ if index is not None:
87
+ match = _DISPLAY_SUFFIX_RE.search(item.nodeid)
88
+ stripped = item.nodeid[: match.start()] if match else item.nodeid
89
+ _PARAM_INDICES[stripped] = index
90
+
91
+
92
+ def pytest_runtest_logreport(report: Any) -> None:
93
+ """Merge one phase's report into the node-id outcome map.
94
+
95
+ Outcomes across setup/call/teardown merge with precedence
96
+ failed > skipped > passed so a teardown failure after a passing call is
97
+ still surfaced.
98
+
99
+ Args:
100
+ report: The phase report emitted by pytest.
101
+
102
+ Returns:
103
+ ``None``.
104
+
105
+ """
106
+ existing = _OUTCOMES.get(report.nodeid)
107
+ if existing is None or _OUTCOME_PRECEDENCE.get(report.outcome, 0) > _OUTCOME_PRECEDENCE.get(existing, 0):
108
+ _OUTCOMES[report.nodeid] = report.outcome
109
+
110
+
111
+ def pytest_sessionfinish(session: Any, exitstatus: int) -> None:
112
+ """Write the recorded outcomes and indices when a report path is set.
113
+
114
+ Args:
115
+ session: The finishing pytest session.
116
+ exitstatus: Pytest's internal exit status code (unused).
117
+
118
+ Returns:
119
+ ``None``.
120
+
121
+ """
122
+ target = os.environ.get("WEBCOMPY_DUALRUN_REPORT")
123
+ if not target:
124
+ return
125
+ payload = {
126
+ "outcomes": dict(_OUTCOMES),
127
+ "param_indices": dict(_PARAM_INDICES),
128
+ }
129
+ with open(target, "w", encoding="utf-8") as handle:
130
+ json.dump(payload, handle, ensure_ascii=False, sort_keys=True)
@@ -0,0 +1,9 @@
1
+ """CLI-specific exception type."""
2
+
3
+ from webcompy.exception import WebComPyException
4
+
5
+
6
+ class WebComPyCliException(WebComPyException):
7
+ """Exception raised for CLI errors."""
8
+
9
+ pass
@@ -0,0 +1,224 @@
1
+ """Static site generation via the ASGI transport."""
2
+
3
+ import os
4
+ import pathlib
5
+ import shutil
6
+ import sys
7
+ from typing import Any, cast
8
+
9
+ import httpx
10
+
11
+ from webcompy.app._app import WebComPyApp
12
+ from webcompy.exception import WebComPyException
13
+ from webcompy.router import LazyComponentGenerator
14
+ from webcompy_cli._argparser import get_params
15
+ from webcompy_cli._output import copy_static_files, materialize_build_assets, write_pwa_outputs
16
+ from webcompy_cli._server import create_asgi_app
17
+ from webcompy_cli._static_files import get_static_files
18
+ from webcompy_cli._utils import discover_config
19
+ from webcompy_cli.config._build_config import WebComPyBuildConfig
20
+
21
+
22
+ async def generate_static_site(app: WebComPyApp | None = None):
23
+ """Generate static HTML files for the application.
24
+
25
+ Builds the wheel and assets, copies static and resource files, and
26
+ fetches each route via the ASGI app to write ``index.html`` files
27
+ into the distribution directory.
28
+
29
+ See https://webcompy.net/llms.txt for LLM-readable SSG CLI docs.
30
+
31
+ Args:
32
+ app: Application instance to generate. When ``None``, the
33
+ configuration is discovered via ``discover_config`` and CLI
34
+ flags override the build options.
35
+
36
+ Raises:
37
+ WebComPyException: If fetching a registered virtual static route
38
+ fails with a non-200 HTTP status.
39
+
40
+ """
41
+ _, args = get_params()
42
+ if app is None:
43
+ build_config = discover_config(args.get("config"))
44
+ app = build_config.app
45
+ else:
46
+ import types as _types
47
+
48
+ app_module = None
49
+ for mod in sys.modules.values():
50
+ if isinstance(mod, _types.ModuleType) and mod.__name__ == app.__class__.__module__:
51
+ continue
52
+ if isinstance(mod, _types.ModuleType) and hasattr(mod, "app") and mod.app is app:
53
+ app_module = mod
54
+ break
55
+ if app_module is None:
56
+ from pathlib import Path as _Path
57
+
58
+ app_module = _types.ModuleType("_webcompy_app")
59
+ app_module.__file__ = str(_Path.cwd())
60
+ cast("Any", app_module).app = app
61
+ build_config = WebComPyBuildConfig(app_module)
62
+
63
+ serve_all_deps = args.get("serve_all_deps")
64
+ if serve_all_deps is not None:
65
+ build_config.serve_all_deps = serve_all_deps
66
+ wasm_serving = args.get("wasm_serving")
67
+ if wasm_serving is not None:
68
+ build_config.wasm_serving = wasm_serving
69
+ build_config._explicit_wasm_serving = wasm_serving
70
+ runtime_serving = args.get("runtime_serving")
71
+ if runtime_serving is not None:
72
+ build_config.runtime_serving = runtime_serving
73
+ build_config._explicit_runtime_serving = runtime_serving
74
+ standalone = args.get("standalone")
75
+ if standalone is not None:
76
+ build_config.standalone = standalone
77
+ wheel_mode = args.get("wheel_mode")
78
+ if wheel_mode is not None:
79
+ build_config.wheel_mode = wheel_mode
80
+ build_config.resolve_standalone()
81
+
82
+ assert app is not None
83
+
84
+ from webcompy.di._keys import ERROR_POLICY_KEY
85
+
86
+ app.provide(ERROR_POLICY_KEY, "ssg")
87
+
88
+ if args.get("dist") is not None:
89
+ dist_dir = pathlib.Path(args["dist"]).absolute()
90
+ else:
91
+ dist_dir = (build_config.app_package_path / build_config.dist).absolute()
92
+ if dist_dir.exists():
93
+ shutil.rmtree(dist_dir)
94
+ os.mkdir(dist_dir)
95
+
96
+ static_files_dir = (build_config.app_package_path / build_config.static_files_dir).absolute()
97
+ copy_static_files(
98
+ static_files_dir,
99
+ dist_dir,
100
+ relative_paths=get_static_files(static_files_dir),
101
+ verbose=True,
102
+ )
103
+
104
+ serving = create_asgi_app(app, build_config, mode="prod")
105
+ artifacts = serving.artifacts
106
+ assert artifacts is not None
107
+
108
+ app._ssg_full_text_resources = _collect_full_text_resources(app, build_config, artifacts)
109
+
110
+ materialize_build_assets(artifacts, build_config.app_package_path, dist_dir, verbose=True)
111
+
112
+ base_url_path = app.config.base_url.strip("/")
113
+ url_prefix = f"/{base_url_path}" if base_url_path else ""
114
+
115
+ try:
116
+ if app.router_mode == "history" and app.routes:
117
+ router = app.router
118
+ if router is not None and getattr(router, "preload_lazy_routes", None) is not None:
119
+ router.preload_lazy_routes(force=True)
120
+ else:
121
+ for _, _, _, _, page in app.routes:
122
+ component = page["component"]
123
+ if isinstance(component, LazyComponentGenerator):
124
+ component._preload()
125
+
126
+ async with httpx.AsyncClient(
127
+ transport=httpx.ASGITransport(app=serving.asgi),
128
+ base_url="http://test",
129
+ ) as client:
130
+ if app.router_mode == "history" and app.routes:
131
+ route_variants = app.router.__route_variants__ if app.router is not None else None
132
+ for i, (p, _, _, _, _) in enumerate(app.routes):
133
+ variants = route_variants[i] if route_variants is not None else None
134
+ paths = {p} if variants is None else {p.format(**params) for params in variants}
135
+ for path in paths:
136
+ response = await client.get(f"{url_prefix}/{path}")
137
+ if not (path_dir := dist_dir / path).exists():
138
+ os.makedirs(path_dir)
139
+ html_path = path_dir / "index.html"
140
+ html_path.open("w", encoding="utf8").write(response.text)
141
+ print(html_path)
142
+ response = await client.get(
143
+ f"{url_prefix}/_webcompy_404",
144
+ headers={"Accept": "text/html"},
145
+ )
146
+ html_path = dist_dir / "404.html"
147
+ html_path.open("w", encoding="utf8").write(response.text)
148
+ print(html_path)
149
+ else:
150
+ response = await client.get(f"{url_prefix}/")
151
+ html_path = dist_dir / "index.html"
152
+ html_path.open("w", encoding="utf8").write(response.text)
153
+ print(html_path)
154
+
155
+ for rel_path in getattr(serving, "static_route_paths", ()):
156
+ response = await client.get(f"{url_prefix}/{rel_path}")
157
+ if response.status_code != 200:
158
+ raise WebComPyException(
159
+ f"Failed to export virtual static route '/{rel_path}': HTTP {response.status_code}"
160
+ )
161
+ dst = dist_dir / rel_path
162
+ dst.parent.mkdir(parents=True, exist_ok=True)
163
+ dst.write_bytes(response.content)
164
+ print(dst)
165
+ finally:
166
+ app._ssg_full_text_resources = None
167
+
168
+ if build_config.pwa.enabled:
169
+ write_pwa_outputs(build_config, app, artifacts, dist_dir, precache_dir=dist_dir, verbose=True)
170
+
171
+ print("done")
172
+
173
+
174
+ _TEXT_RESOURCE_EXTENSIONS: frozenset[str] = frozenset(
175
+ {
176
+ ".md",
177
+ ".markdown",
178
+ ".txt",
179
+ ".json",
180
+ ".csv",
181
+ ".yaml",
182
+ ".yml",
183
+ ".toml",
184
+ ".svg",
185
+ ".html",
186
+ ".xml",
187
+ }
188
+ )
189
+
190
+ _TEXT_RESOURCE_MAX_BYTES = 256 * 1024
191
+ _TEXT_RESOURCE_MAX_TOTAL_BYTES = 1024 * 1024
192
+
193
+
194
+ def _collect_full_text_resources(
195
+ app: WebComPyApp, build_config: WebComPyBuildConfig, artifacts: Any
196
+ ) -> dict[str, bytes] | None:
197
+ if build_config.resource_transfer != "all-text":
198
+ return None
199
+ if not artifacts.resource_allow_list:
200
+ return None
201
+ from pathlib import PurePosixPath
202
+
203
+ full: dict[str, bytes] = {}
204
+ for rel_path in sorted(artifacts.resource_allow_list):
205
+ if PurePosixPath(rel_path).suffix.lower() not in _TEXT_RESOURCE_EXTENSIONS:
206
+ continue
207
+ data = (build_config.app_package_path / rel_path).read_bytes()
208
+ if len(data) > _TEXT_RESOURCE_MAX_BYTES:
209
+ print(
210
+ f"Warning: text resource {rel_path} ({len(data)} bytes) exceeds "
211
+ f"{_TEXT_RESOURCE_MAX_BYTES} bytes; it will be embedded in every generated page.",
212
+ file=sys.stderr,
213
+ flush=True,
214
+ )
215
+ full[rel_path] = data
216
+ total = sum(len(data) for data in full.values())
217
+ if total > _TEXT_RESOURCE_MAX_TOTAL_BYTES:
218
+ print(
219
+ f"Warning: total text resources ({total} bytes) exceed {_TEXT_RESOURCE_MAX_TOTAL_BYTES} bytes; "
220
+ "every generated page embeds the full set.",
221
+ file=sys.stderr,
222
+ flush=True,
223
+ )
224
+ return full