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.
- webcompy_cli/__init__.py +20 -0
- webcompy_cli/_argparser.py +232 -0
- webcompy_cli/_browser_probes.py +648 -0
- webcompy_cli/_browser_test_harness.py +554 -0
- webcompy_cli/_build.py +425 -0
- webcompy_cli/_console_types.py +15 -0
- webcompy_cli/_dependency_resolver.py +301 -0
- webcompy_cli/_dualrun_pytest_plugin.py +130 -0
- webcompy_cli/_exception.py +9 -0
- webcompy_cli/_generate.py +224 -0
- webcompy_cli/_init_project.py +54 -0
- webcompy_cli/_inspect.py +741 -0
- webcompy_cli/_inspect_pyexec.py +244 -0
- webcompy_cli/_lock.py +82 -0
- webcompy_cli/_lockfile.py +396 -0
- webcompy_cli/_lockfile_sync.py +343 -0
- webcompy_cli/_output.py +150 -0
- webcompy_cli/_prebuild.py +661 -0
- webcompy_cli/_pwa.py +474 -0
- webcompy_cli/_pyodide_downloader.py +113 -0
- webcompy_cli/_pyodide_lock.py +74 -0
- webcompy_cli/_runtime_downloader.py +222 -0
- webcompy_cli/_server.py +568 -0
- webcompy_cli/_static_files.py +27 -0
- webcompy_cli/_utils.py +72 -0
- webcompy_cli/_version_sweep.py +213 -0
- webcompy_cli/_wheel_builder.py +509 -0
- webcompy_cli/config/__init__.py +23 -0
- webcompy_cli/config/_build_config.py +168 -0
- webcompy_cli/config/_pwa_config.py +203 -0
- webcompy_cli/config/_server_config.py +53 -0
- webcompy_cli/py.typed +0 -0
- webcompy_cli/template_data/app/__init__.py +0 -0
- webcompy_cli/template_data/app/app.py +22 -0
- webcompy_cli/template_data/app/components/__init__.py +0 -0
- webcompy_cli/template_data/app/components/fizzbuzz.py +117 -0
- webcompy_cli/template_data/app/components/home.py +15 -0
- webcompy_cli/template_data/app/components/input.py +34 -0
- webcompy_cli/template_data/app/components/navigation.py +36 -0
- webcompy_cli/template_data/app/components/not_found.py +22 -0
- webcompy_cli/template_data/app/components/root.py +16 -0
- webcompy_cli/template_data/app/router.py +17 -0
- webcompy_cli/template_data/webcompy_config.py +12 -0
- webcompy_cli-0.0.14.dist-info/METADATA +53 -0
- webcompy_cli-0.0.14.dist-info/RECORD +47 -0
- webcompy_cli-0.0.14.dist-info/WHEEL +4 -0
- webcompy_cli-0.0.14.dist-info/licenses/LICENSE +21 -0
webcompy_cli/_pwa.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"""Build-time Progressive Web App generation: manifest serialization, precache enumeration, and worker emission.
|
|
2
|
+
|
|
3
|
+
The framework owns the Service Worker implementation as a vanilla JS
|
|
4
|
+
template embedded in this module; the effective PWA configuration is
|
|
5
|
+
serialized into it at build time so the worker operates offline from its
|
|
6
|
+
first install without fetching any runtime configuration.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import pathlib
|
|
14
|
+
import sys
|
|
15
|
+
from dataclasses import asdict
|
|
16
|
+
from typing import TYPE_CHECKING
|
|
17
|
+
|
|
18
|
+
from webcompy.exception import WebComPyException
|
|
19
|
+
from webcompy_server._html import PYSCRIPT_VERSION, get_runtime_asset_prefix
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from webcompy_cli._build import BuildArtifacts
|
|
23
|
+
from webcompy_cli.config._pwa_config import PWAConfig
|
|
24
|
+
|
|
25
|
+
MANIFEST_FILENAME = "manifest.webmanifest"
|
|
26
|
+
SW_FILENAME = "sw.js"
|
|
27
|
+
PWA_OUTPUT_NAMES = frozenset({MANIFEST_FILENAME, SW_FILENAME})
|
|
28
|
+
MANIFEST_MEDIA_TYPE = "application/manifest+json"
|
|
29
|
+
SW_MEDIA_TYPE = "application/javascript"
|
|
30
|
+
RUNTIME_ASSET_PREFIX = f"{get_runtime_asset_prefix(PYSCRIPT_VERSION)}/"
|
|
31
|
+
|
|
32
|
+
_DEFAULT_OFFLINE_HTML = (
|
|
33
|
+
'<!doctype html><html><head><meta charset="utf-8">'
|
|
34
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">'
|
|
35
|
+
"<title>Offline</title>"
|
|
36
|
+
"<style>body{font-family:system-ui,sans-serif;text-align:center;padding:15vmin 24px;color:#333}</style>"
|
|
37
|
+
"</head><body><main><h1>You're offline</h1>"
|
|
38
|
+
"<p>This page is not available without a network connection.</p>"
|
|
39
|
+
"</main></body></html>"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
_SW_TEMPLATE = """const CONFIG = __WC_PWA_CONFIG__;
|
|
43
|
+
const PREFIX = "webcompy-pwa-";
|
|
44
|
+
const PRECACHE_NAME = PREFIX + "v-" + CONFIG.version;
|
|
45
|
+
const SCOPE_PATH = self.location.pathname.replace(/[^/]*$/, "");
|
|
46
|
+
const cachedAt = new Map();
|
|
47
|
+
|
|
48
|
+
function resolveUrl(url) {
|
|
49
|
+
return new URL(url, self.location.href);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function scopeRelative(pathname) {
|
|
53
|
+
return pathname.indexOf(SCOPE_PATH) === 0 ? "/" + pathname.slice(SCOPE_PATH.length) : pathname;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function ruleCacheName(index) {
|
|
57
|
+
return PREFIX + "r" + index + "-" + CONFIG.version;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function globToRegex(glob) {
|
|
61
|
+
var source = "";
|
|
62
|
+
for (var i = 0; i < glob.length; i++) {
|
|
63
|
+
var char = glob[i];
|
|
64
|
+
if (char === "*") {
|
|
65
|
+
if (glob[i + 1] === "*") {
|
|
66
|
+
source += ".*";
|
|
67
|
+
i++;
|
|
68
|
+
} else {
|
|
69
|
+
source += "[^/]*";
|
|
70
|
+
}
|
|
71
|
+
} else if ("\\\\.[]{}()+-?^$|".indexOf(char) !== -1) {
|
|
72
|
+
source += "\\\\" + char;
|
|
73
|
+
} else {
|
|
74
|
+
source += char;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return new RegExp("^" + source + "$");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function matchRule(url) {
|
|
81
|
+
var rules = CONFIG.runtime || [];
|
|
82
|
+
var pathname = scopeRelative(url.pathname);
|
|
83
|
+
for (var i = 0; i < rules.length; i++) {
|
|
84
|
+
var pattern = rules[i].pattern;
|
|
85
|
+
var matched = pattern.indexOf("*") !== -1
|
|
86
|
+
? globToRegex(pattern).test(pathname)
|
|
87
|
+
: pathname.indexOf(pattern) === 0;
|
|
88
|
+
if (matched) {
|
|
89
|
+
var rule = {};
|
|
90
|
+
for (var key in rules[i]) rule[key] = rules[i][key];
|
|
91
|
+
rule.cacheName = ruleCacheName(i);
|
|
92
|
+
return rule;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isFresh(request, rule) {
|
|
99
|
+
if (!rule.maxAge) return true;
|
|
100
|
+
var stored = cachedAt.get(request.url);
|
|
101
|
+
if (stored === undefined) return true;
|
|
102
|
+
return Date.now() - stored <= rule.maxAge * 1000;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function trimCache(cache, rule) {
|
|
106
|
+
if (!rule.maxEntries) return;
|
|
107
|
+
var keys = await cache.keys();
|
|
108
|
+
if (keys.length <= rule.maxEntries) return;
|
|
109
|
+
var excess = keys.slice(0, keys.length - rule.maxEntries);
|
|
110
|
+
for (var entry of excess) {
|
|
111
|
+
cachedAt.delete(entry.url);
|
|
112
|
+
await cache.delete(entry);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function store(cache, request, response, rule) {
|
|
117
|
+
if (response && response.ok) {
|
|
118
|
+
await cache.put(request, response.clone());
|
|
119
|
+
cachedAt.set(request.url, Date.now());
|
|
120
|
+
await trimCache(cache, rule);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function cacheFirst(request, rule) {
|
|
125
|
+
var cache = await caches.open(rule.cacheName);
|
|
126
|
+
var hit = await cache.match(request);
|
|
127
|
+
if (hit && isFresh(request, rule)) return hit;
|
|
128
|
+
try {
|
|
129
|
+
var fresh = await fetch(request);
|
|
130
|
+
await store(cache, request, fresh, rule);
|
|
131
|
+
return fresh;
|
|
132
|
+
} catch (err) {
|
|
133
|
+
if (hit) return hit;
|
|
134
|
+
throw err;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function networkFirst(request, rule) {
|
|
139
|
+
var cache = await caches.open(rule.cacheName);
|
|
140
|
+
try {
|
|
141
|
+
var fresh = await fetch(request);
|
|
142
|
+
await store(cache, request, fresh, rule);
|
|
143
|
+
return fresh;
|
|
144
|
+
} catch (err) {
|
|
145
|
+
var hit = await cache.match(request);
|
|
146
|
+
if (hit) return hit;
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function staleWhileRevalidate(request, rule) {
|
|
152
|
+
var cache = await caches.open(rule.cacheName);
|
|
153
|
+
var hit = await cache.match(request);
|
|
154
|
+
var update = fetch(request)
|
|
155
|
+
.then(function (fresh) {
|
|
156
|
+
return store(cache, request, fresh, rule).then(function () {
|
|
157
|
+
return fresh;
|
|
158
|
+
});
|
|
159
|
+
})
|
|
160
|
+
.catch(function () {
|
|
161
|
+
return null;
|
|
162
|
+
});
|
|
163
|
+
if (hit && isFresh(request, rule)) return hit;
|
|
164
|
+
var fresh = await update;
|
|
165
|
+
if (fresh) return fresh;
|
|
166
|
+
if (hit) return hit;
|
|
167
|
+
return fetch(request);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function hasFileExtension(pathname) {
|
|
171
|
+
return pathname.lastIndexOf(".") > pathname.lastIndexOf("/");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function navigationMatch(request) {
|
|
175
|
+
var hit = await caches.match(request, { ignoreSearch: true });
|
|
176
|
+
if (hit) return hit;
|
|
177
|
+
var pathname = new URL(request.url).pathname;
|
|
178
|
+
if (hasFileExtension(pathname)) return undefined;
|
|
179
|
+
return caches.match(pathname.replace(/\\/?$/, "/index.html"));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function offlineResponse() {
|
|
183
|
+
if (CONFIG.fallback) {
|
|
184
|
+
var hit = await caches.match(CONFIG.fallback);
|
|
185
|
+
if (hit) return hit;
|
|
186
|
+
}
|
|
187
|
+
return new Response(CONFIG.offlineHtml, {
|
|
188
|
+
status: 200,
|
|
189
|
+
headers: {
|
|
190
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
191
|
+
"X-WebComPy-Offline": "fallback",
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function handleRequest(request, url) {
|
|
197
|
+
if (request.mode === "navigate") {
|
|
198
|
+
var cached = await navigationMatch(request);
|
|
199
|
+
if (cached) return cached;
|
|
200
|
+
try {
|
|
201
|
+
return await fetch(request);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
return offlineResponse();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
var rule = matchRule(url);
|
|
207
|
+
if (!rule) return fetch(request);
|
|
208
|
+
if (rule.strategy === "network-first") return networkFirst(request, rule);
|
|
209
|
+
if (rule.strategy === "stale-while-revalidate") return staleWhileRevalidate(request, rule);
|
|
210
|
+
return cacheFirst(request, rule);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function precacheEntry(cache, entry) {
|
|
214
|
+
var target = resolveUrl(entry);
|
|
215
|
+
var init = target.origin === self.location.origin ? undefined : { mode: "no-cors" };
|
|
216
|
+
var response = await fetch(new Request(target.href, init));
|
|
217
|
+
if (response.ok || response.type === "opaque") {
|
|
218
|
+
await cache.put(target.href, response);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
throw new Error("HTTP " + response.status);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function installPrecache() {
|
|
225
|
+
var cache = await caches.open(PRECACHE_NAME);
|
|
226
|
+
var entries = (CONFIG.precache || []).map(function (entry) {
|
|
227
|
+
return precacheEntry(cache, entry).catch(function (err) {
|
|
228
|
+
console.warn("[webcompy-pwa] precache failed:", entry, err);
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
await Promise.all(entries);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
self.addEventListener("install", function (event) {
|
|
235
|
+
event.waitUntil(installPrecache().then(function () {
|
|
236
|
+
return self.skipWaiting();
|
|
237
|
+
}));
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
self.addEventListener("activate", function (event) {
|
|
241
|
+
var keep = [PRECACHE_NAME];
|
|
242
|
+
var rules = CONFIG.runtime || [];
|
|
243
|
+
for (var i = 0; i < rules.length; i++) keep.push(ruleCacheName(i));
|
|
244
|
+
event.waitUntil(
|
|
245
|
+
caches.keys().then(function (names) {
|
|
246
|
+
return Promise.all(names.filter(function (name) {
|
|
247
|
+
return name.indexOf(PREFIX) === 0 && keep.indexOf(name) === -1;
|
|
248
|
+
}).map(function (name) {
|
|
249
|
+
return caches.delete(name);
|
|
250
|
+
}));
|
|
251
|
+
}).then(function () {
|
|
252
|
+
return self.clients.claim();
|
|
253
|
+
})
|
|
254
|
+
);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
self.addEventListener("fetch", function (event) {
|
|
258
|
+
var request = event.request;
|
|
259
|
+
if (request.method !== "GET") return;
|
|
260
|
+
var url = new URL(request.url);
|
|
261
|
+
if (url.origin !== self.location.origin) return;
|
|
262
|
+
event.respondWith(handleRequest(request, url));
|
|
263
|
+
});"""
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def serialize_manifest(pwa: PWAConfig, base_url: str) -> str:
|
|
267
|
+
"""Serialize the PWA manifest configuration to Web App Manifest JSON.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
pwa: PWA configuration whose ``manifest`` is serialized.
|
|
271
|
+
base_url: Application base URL (normalized with surrounding
|
|
272
|
+
slashes) used for ``start_url`` and ``scope`` defaults.
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
The ``manifest.webmanifest`` document as a JSON string.
|
|
276
|
+
|
|
277
|
+
Raises:
|
|
278
|
+
WebComPyException: If no manifest is configured.
|
|
279
|
+
|
|
280
|
+
"""
|
|
281
|
+
manifest = pwa.manifest
|
|
282
|
+
if manifest is None:
|
|
283
|
+
raise WebComPyException("serialize_manifest requires PWAConfig.manifest to be set")
|
|
284
|
+
data: dict = {
|
|
285
|
+
"name": manifest.name,
|
|
286
|
+
"start_url": base_url if manifest.start_url is None else manifest.start_url,
|
|
287
|
+
"scope": base_url if manifest.scope is None else manifest.scope,
|
|
288
|
+
"display": manifest.display,
|
|
289
|
+
}
|
|
290
|
+
if manifest.short_name is not None:
|
|
291
|
+
data["short_name"] = manifest.short_name
|
|
292
|
+
if manifest.theme_color is not None:
|
|
293
|
+
data["theme_color"] = manifest.theme_color
|
|
294
|
+
if manifest.background_color is not None:
|
|
295
|
+
data["background_color"] = manifest.background_color
|
|
296
|
+
if manifest.icons:
|
|
297
|
+
data["icons"] = [
|
|
298
|
+
{key: value for key, value in asdict(icon).items() if value is not None} for icon in manifest.icons
|
|
299
|
+
]
|
|
300
|
+
return json.dumps(data, ensure_ascii=False, indent=2) + "\n"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def runtime_entry_urls(cdn_lockfile_url: str | None) -> list[str]:
|
|
304
|
+
"""List the known CDN entry URLs of the Python runtime for precaching.
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
cdn_lockfile_url: URL of the Pyodide lock file when the runtime is
|
|
308
|
+
served from a CDN, or ``None`` when unavailable.
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
Absolute URLs of the PyScript core files and the lock file.
|
|
312
|
+
|
|
313
|
+
"""
|
|
314
|
+
from webcompy_server._html import PYSCRIPT_BASE_URL
|
|
315
|
+
|
|
316
|
+
urls = [f"{PYSCRIPT_BASE_URL}/core.js", f"{PYSCRIPT_BASE_URL}/core.css"]
|
|
317
|
+
if cdn_lockfile_url:
|
|
318
|
+
urls.append(cdn_lockfile_url)
|
|
319
|
+
return urls
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _clean_page_url(rel: str) -> str | None:
|
|
323
|
+
if rel == "index.html":
|
|
324
|
+
return "./"
|
|
325
|
+
if rel.endswith("/index.html"):
|
|
326
|
+
return rel[: -len("index.html")]
|
|
327
|
+
return None
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def build_precache_entries(
|
|
331
|
+
pwa: PWAConfig,
|
|
332
|
+
*,
|
|
333
|
+
dist_dir: pathlib.Path | None = None,
|
|
334
|
+
runtime_asset_files: dict[str, pathlib.Path] | None = None,
|
|
335
|
+
cdn_runtime_urls: list[str] | None = None,
|
|
336
|
+
) -> list[str]:
|
|
337
|
+
"""Resolve the precache URL list for a PWA-enabled build or server start.
|
|
338
|
+
|
|
339
|
+
With ``precache="none"`` the output directory is not enumerated and no
|
|
340
|
+
build output is included; only a configured ``fallback_path`` remains
|
|
341
|
+
in the manifest so an overridden offline page is still served offline.
|
|
342
|
+
With ``"auto"`` and a ``dist_dir``, build output is enumerated as
|
|
343
|
+
scope-relative paths, each generated page additionally contributes its
|
|
344
|
+
clean URL, and the PWA output files are excluded.
|
|
345
|
+
Runtime files are excluded regardless of serving mode unless
|
|
346
|
+
``precache_runtime`` is enabled, in which case the included set is
|
|
347
|
+
extended with the local runtime URLs and/or the given CDN runtime
|
|
348
|
+
entry URLs and a size warning is logged to stderr.
|
|
349
|
+
|
|
350
|
+
Args:
|
|
351
|
+
pwa: Validated PWA configuration.
|
|
352
|
+
dist_dir: SSG output directory to enumerate, or ``None`` for
|
|
353
|
+
dynamic server mode (no pages to precache).
|
|
354
|
+
runtime_asset_files: Mapping of runtime asset paths (relative to
|
|
355
|
+
the versioned ``_webcompy-assets/{PYSCRIPT_VERSION}/`` prefix) to on-disk source paths, for
|
|
356
|
+
local runtime serving.
|
|
357
|
+
cdn_runtime_urls: Absolute CDN entry URLs for runtime precaching
|
|
358
|
+
when the runtime is served from a CDN.
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
Sorted precache entries (scope-relative paths and absolute URLs).
|
|
362
|
+
|
|
363
|
+
"""
|
|
364
|
+
if pwa.precache == "none":
|
|
365
|
+
return [pwa.fallback_path] if pwa.fallback_path is not None else []
|
|
366
|
+
|
|
367
|
+
runtime_rels = frozenset(f"{RUNTIME_ASSET_PREFIX}{rel}" for rel in runtime_asset_files or {})
|
|
368
|
+
entries: set[str] = set()
|
|
369
|
+
|
|
370
|
+
if dist_dir is not None:
|
|
371
|
+
for path in dist_dir.rglob("*"):
|
|
372
|
+
if not path.is_file():
|
|
373
|
+
continue
|
|
374
|
+
rel = path.relative_to(dist_dir).as_posix()
|
|
375
|
+
if rel in PWA_OUTPUT_NAMES or (rel in runtime_rels and not pwa.precache_runtime):
|
|
376
|
+
continue
|
|
377
|
+
entries.add(rel)
|
|
378
|
+
clean = _clean_page_url(rel)
|
|
379
|
+
if clean is not None:
|
|
380
|
+
entries.add(clean)
|
|
381
|
+
|
|
382
|
+
if pwa.precache_runtime:
|
|
383
|
+
entries.update(runtime_rels)
|
|
384
|
+
if cdn_runtime_urls:
|
|
385
|
+
entries.update(cdn_runtime_urls)
|
|
386
|
+
if runtime_asset_files:
|
|
387
|
+
total = sum(p.stat().st_size for p in runtime_asset_files.values() if p.is_file())
|
|
388
|
+
print(
|
|
389
|
+
f"Warning: precache_runtime enabled: the Python runtime "
|
|
390
|
+
f"({total / 1_000_000:.1f} MB) will be precached to device storage.",
|
|
391
|
+
file=sys.stderr,
|
|
392
|
+
flush=True,
|
|
393
|
+
)
|
|
394
|
+
elif cdn_runtime_urls:
|
|
395
|
+
print(
|
|
396
|
+
"Warning: precache_runtime enabled with a CDN runtime: only runtime "
|
|
397
|
+
"entry files are precached; offline startup is not guaranteed.",
|
|
398
|
+
file=sys.stderr,
|
|
399
|
+
flush=True,
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
if pwa.fallback_path is not None:
|
|
403
|
+
entries.add(pwa.fallback_path)
|
|
404
|
+
|
|
405
|
+
return sorted(entries)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def precache_entries_for_artifacts(
|
|
409
|
+
pwa: PWAConfig, artifacts: BuildArtifacts, *, dist_dir: pathlib.Path | None = None
|
|
410
|
+
) -> list[str]:
|
|
411
|
+
"""Derive precache entries from resolved build artifacts.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
pwa: Validated PWA configuration.
|
|
415
|
+
artifacts: Resolved build artifacts describing runtime serving.
|
|
416
|
+
dist_dir: SSG output directory to enumerate, or ``None`` for
|
|
417
|
+
dynamic server mode.
|
|
418
|
+
|
|
419
|
+
Returns:
|
|
420
|
+
Sorted precache entries.
|
|
421
|
+
|
|
422
|
+
"""
|
|
423
|
+
runtime_asset_files = artifacts.runtime_asset_files
|
|
424
|
+
cdn_runtime_urls = None
|
|
425
|
+
if pwa.precache_runtime and not runtime_asset_files:
|
|
426
|
+
cdn_runtime_urls = runtime_entry_urls(artifacts.lockfile_url)
|
|
427
|
+
return build_precache_entries(
|
|
428
|
+
pwa,
|
|
429
|
+
dist_dir=dist_dir,
|
|
430
|
+
runtime_asset_files=runtime_asset_files,
|
|
431
|
+
cdn_runtime_urls=cdn_runtime_urls,
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _normalize_pattern(pattern: str) -> str:
|
|
436
|
+
if pattern.startswith("/"):
|
|
437
|
+
return pattern
|
|
438
|
+
return "/" + pattern
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def generate_sw(pwa: PWAConfig, app_version: str, precache_entries: list[str]) -> str:
|
|
442
|
+
"""Generate the framework-owned Service Worker with the build config embedded.
|
|
443
|
+
|
|
444
|
+
Runtime rule patterns are normalized to start with a slash so patterns
|
|
445
|
+
written without the leading slash match the scope-relative request
|
|
446
|
+
paths the worker compares against.
|
|
447
|
+
|
|
448
|
+
Args:
|
|
449
|
+
pwa: Validated PWA configuration.
|
|
450
|
+
app_version: Application build version embedded in cache names.
|
|
451
|
+
precache_entries: Precache manifest entries.
|
|
452
|
+
|
|
453
|
+
Returns:
|
|
454
|
+
The complete ``sw.js`` source with the serialized configuration.
|
|
455
|
+
|
|
456
|
+
"""
|
|
457
|
+
rules: list[dict] = []
|
|
458
|
+
for rule in pwa.runtime:
|
|
459
|
+
entry: dict = {"pattern": _normalize_pattern(rule.pattern), "strategy": rule.strategy}
|
|
460
|
+
if rule.max_entries is not None:
|
|
461
|
+
entry["maxEntries"] = rule.max_entries
|
|
462
|
+
if rule.max_age is not None:
|
|
463
|
+
entry["maxAge"] = rule.max_age
|
|
464
|
+
rules.append(entry)
|
|
465
|
+
config: dict = {
|
|
466
|
+
"precache": precache_entries,
|
|
467
|
+
"runtime": rules,
|
|
468
|
+
"fallback": pwa.fallback_path,
|
|
469
|
+
"offlineHtml": _DEFAULT_OFFLINE_HTML,
|
|
470
|
+
}
|
|
471
|
+
digest = hashlib.sha256(json.dumps(config, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()[:12]
|
|
472
|
+
config["version"] = f"{app_version}-{digest}"
|
|
473
|
+
payload = json.dumps(config, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
|
|
474
|
+
return _SW_TEMPLATE.replace("__WC_PWA_CONFIG__", payload)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Download helpers for Pyodide wheels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import pathlib
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
import zipfile
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from webcompy_cli._lockfile import Lockfile
|
|
14
|
+
|
|
15
|
+
PYODIDE_CDN_URL_TEMPLATE = "https://cdn.jsdelivr.net/pyodide/v{version}/full/{file_name}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PyodideDownloadError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _sha256_of_file(path: pathlib.Path) -> str:
|
|
23
|
+
h = hashlib.sha256()
|
|
24
|
+
with open(path, "rb") as f:
|
|
25
|
+
while True:
|
|
26
|
+
chunk = f.read(65536)
|
|
27
|
+
if not chunk:
|
|
28
|
+
break
|
|
29
|
+
h.update(chunk)
|
|
30
|
+
return h.hexdigest()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def download_pyodide_wheel(
|
|
34
|
+
file_name: str,
|
|
35
|
+
pyodide_version: str,
|
|
36
|
+
expected_sha256: str,
|
|
37
|
+
modules_dir: pathlib.Path,
|
|
38
|
+
) -> pathlib.Path:
|
|
39
|
+
cache_dir = modules_dir / "pyodide-packages" / pyodide_version
|
|
40
|
+
cached_path = cache_dir / file_name
|
|
41
|
+
|
|
42
|
+
if cached_path.is_file():
|
|
43
|
+
actual_sha256 = _sha256_of_file(cached_path)
|
|
44
|
+
if actual_sha256 == expected_sha256:
|
|
45
|
+
return cached_path
|
|
46
|
+
cached_path.unlink()
|
|
47
|
+
|
|
48
|
+
url = PYODIDE_CDN_URL_TEMPLATE.format(version=pyodide_version, file_name=file_name)
|
|
49
|
+
try:
|
|
50
|
+
req = urllib.request.Request(url, headers={"User-Agent": "WebComPy/0.1"})
|
|
51
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
52
|
+
data = resp.read()
|
|
53
|
+
except (urllib.error.URLError, OSError, TimeoutError) as e:
|
|
54
|
+
raise PyodideDownloadError(
|
|
55
|
+
f"Failed to download {file_name} from Pyodide CDN: {e}. Ensure you have network access."
|
|
56
|
+
) from e
|
|
57
|
+
|
|
58
|
+
actual_sha256 = hashlib.sha256(data).hexdigest()
|
|
59
|
+
if actual_sha256 != expected_sha256:
|
|
60
|
+
raise PyodideDownloadError(
|
|
61
|
+
f"SHA256 verification failed for {file_name}. "
|
|
62
|
+
f"Expected: {expected_sha256}, got: {actual_sha256}. "
|
|
63
|
+
f"The download may be corrupted or the lock file may be outdated."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
cached_path.write_bytes(data)
|
|
68
|
+
return cached_path
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def download_wasm_wheels(
|
|
72
|
+
lockfile: Lockfile,
|
|
73
|
+
modules_dir: pathlib.Path,
|
|
74
|
+
) -> dict[str, pathlib.Path]:
|
|
75
|
+
results: dict[str, pathlib.Path] = {}
|
|
76
|
+
for name, entry in lockfile.wasm_packages.items():
|
|
77
|
+
if entry.file_name and entry.sha256:
|
|
78
|
+
wheel_path = download_pyodide_wheel(
|
|
79
|
+
entry.file_name,
|
|
80
|
+
lockfile.pyodide_version,
|
|
81
|
+
entry.sha256,
|
|
82
|
+
modules_dir,
|
|
83
|
+
)
|
|
84
|
+
results[name] = wheel_path
|
|
85
|
+
return results
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def extract_wheel(
|
|
89
|
+
wheel_path: pathlib.Path,
|
|
90
|
+
dest: pathlib.Path,
|
|
91
|
+
) -> list[tuple[str, pathlib.Path]]:
|
|
92
|
+
with zipfile.ZipFile(wheel_path, "r") as zf:
|
|
93
|
+
zf.extractall(dest)
|
|
94
|
+
|
|
95
|
+
result: list[tuple[str, pathlib.Path]] = []
|
|
96
|
+
for dist_info in sorted(dest.glob("*.dist-info")):
|
|
97
|
+
top_level_path = dist_info / "top_level.txt"
|
|
98
|
+
if top_level_path.exists():
|
|
99
|
+
for line in top_level_path.read_text(encoding="utf-8").strip().splitlines():
|
|
100
|
+
pkg_name = line.strip()
|
|
101
|
+
if pkg_name:
|
|
102
|
+
pkg_dir = dest / pkg_name
|
|
103
|
+
if pkg_dir.is_dir():
|
|
104
|
+
result.append((pkg_name, pkg_dir))
|
|
105
|
+
elif (dest / f"{pkg_name}.py").is_file():
|
|
106
|
+
result.append((pkg_name, dest))
|
|
107
|
+
else:
|
|
108
|
+
pkg_name = dist_info.name.split("-")[0]
|
|
109
|
+
pkg_dir = dest / pkg_name
|
|
110
|
+
if pkg_dir.is_dir():
|
|
111
|
+
result.append((pkg_name, pkg_dir))
|
|
112
|
+
|
|
113
|
+
return result
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Fetch and cache the Pyodide lock file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import pathlib
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
|
|
10
|
+
PYODIDE_LOCK_URL_TEMPLATE = "https://cdn.jsdelivr.net/pyodide/v{version}/full/pyodide-lock.json"
|
|
11
|
+
PYSCRIPT_RELEASE_URL_TEMPLATE = "https://pyscript.net/releases/{pyscript_version}/{filename}"
|
|
12
|
+
PYODIDE_RUNTIME_URL_TEMPLATE = "https://cdn.jsdelivr.net/pyodide/v{pyodide_version}/full/{filename}"
|
|
13
|
+
|
|
14
|
+
PYSCRIPT_TO_PYODIDE: dict[str, str] = {
|
|
15
|
+
"2026.3.1": "0.29.3",
|
|
16
|
+
"2026.7.3": "314.0.3",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PyodideLockFetchError(Exception):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_pyodide_version(pyscript_version: str) -> str:
|
|
25
|
+
if pyscript_version not in PYSCRIPT_TO_PYODIDE:
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"Unknown PyScript version '{pyscript_version}'. "
|
|
28
|
+
f"Known versions: {', '.join(sorted(PYSCRIPT_TO_PYODIDE))}. "
|
|
29
|
+
f"Update the PYSCRIPT_TO_PYODIDE mapping in webcompy_cli/_pyodide_lock.py."
|
|
30
|
+
)
|
|
31
|
+
return PYSCRIPT_TO_PYODIDE[pyscript_version]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _load_cached(cached_path: pathlib.Path) -> dict | None:
|
|
35
|
+
if not cached_path.is_file():
|
|
36
|
+
return None
|
|
37
|
+
try:
|
|
38
|
+
return json.loads(cached_path.read_text(encoding="utf-8"))
|
|
39
|
+
except (json.JSONDecodeError, OSError):
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def fetch_pyodide_lock(pyodide_version: str, modules_dir: pathlib.Path) -> dict:
|
|
44
|
+
cache_dir = modules_dir / "pyodide-lock"
|
|
45
|
+
cached_path = cache_dir / f"pyodide-lock-{pyodide_version}.json"
|
|
46
|
+
|
|
47
|
+
cached = _load_cached(cached_path)
|
|
48
|
+
if cached is not None:
|
|
49
|
+
return cached
|
|
50
|
+
|
|
51
|
+
url = PYODIDE_LOCK_URL_TEMPLATE.format(version=pyodide_version)
|
|
52
|
+
fetch_error: Exception | None = None
|
|
53
|
+
try:
|
|
54
|
+
req = urllib.request.Request(url, headers={"User-Agent": "WebComPy/0.1"})
|
|
55
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
56
|
+
data = resp.read()
|
|
57
|
+
lock_data = json.loads(data)
|
|
58
|
+
except (urllib.error.URLError, OSError, json.JSONDecodeError, TimeoutError) as e:
|
|
59
|
+
fetch_error = e
|
|
60
|
+
lock_data = None
|
|
61
|
+
|
|
62
|
+
if lock_data is not None:
|
|
63
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
cached_path.write_text(json.dumps(lock_data, indent=2), encoding="utf-8")
|
|
65
|
+
return lock_data
|
|
66
|
+
|
|
67
|
+
if fetch_error is not None:
|
|
68
|
+
raise PyodideLockFetchError(
|
|
69
|
+
f"Failed to fetch Pyodide lock for version {pyodide_version}: {fetch_error}. "
|
|
70
|
+
f"Ensure you have network access, or run 'webcompy lock' in an environment with internet access."
|
|
71
|
+
)
|
|
72
|
+
raise PyodideLockFetchError(
|
|
73
|
+
f"Failed to parse Pyodide lock for version {pyodide_version}. The CDN may have returned invalid data."
|
|
74
|
+
)
|