jukebox
All repositories: gitoria
13.4 KB
// The framework's SERVICE WORKER (COMPONENTS §10, D38) — the offline shell. It exists// only for an app that declares `offline = [ … ]`: hl:web compiles this file like// client.hl, serves it at /__hl/web/worker.js, and registers the entry script// /__hl/sw.js, which imports it and constructs it ONCE with the table below.//// WHAT IS KEPT IS THE APP'S DECISION (D38). `precache` holds the shared shell —// the runtime, the client half, the stylesheet, every page module, the web app// manifest and its icons — plus the DOCUMENT of each param-free route whose// component the allow-list names. `routes` is the client's route table with// `keep` on the rows the allow-list names, so a param-bearing page (`/notes/:id`)// is kept when it is VISITED, and only then. Every other page is unavailable// offline, and says so.//// THREE RULES, the ones the old hl:web ran (mission 101):// · a NAVIGATION is network-first. The network is the truth while it answers,// and a fresh document for a kept page replaces the cached one on the way past;// the cache is what an outage falls back to.// · a precached asset is cache-first. Its url carries the build's hash, so a hit// cannot be stale.// · everything else goes to the network untouched: the emit channel, a function// route, an app's own file. The socket never reaches a worker at all.//// WHY THE ENTRY SCRIPT IS NOT THIS FILE. A worker must add its listeners while its// script is first evaluated, and a `fetch` listener must hand `respondWith` its// promise before the listener returns. Every call in this language is awaited, so// neither can be written here; /__hl/sw.js does exactly those two things and calls// the methods below for everything else (WebFramework.hl, `workerEntry`).import HlwRouter from './router.hl'cfgText = '' // the table, as JSON text (the one construction argument)cfg = JSON.parse(cfgText)router = new HlwRouter(routes = cfg.routes)// INSTALL: the shell into this build's cache, one url at a time — a single failed// url must not throw the whole install away and leave the app with no shellinstall() {let cache = globalThis.caches.open(cfg.cache)for (url of cfg.precache) {// a data-free page is fetched as nobody: its document carries no user's state (#120)let creds = cfg.dataFree.includes(url) ? 'omit' : 'same-origin'let r = globalThis.__hlAttempt(() => { return fetch(url, { cache = 'reload' credentials = creds }) })if (r.ok && r.value.ok) { cache.put(url, r.value) }}globalThis.skipWaiting()return null}// ACTIVATE: the cache name carries the build's hash, so every other hl cache is an// older deploy's. This worker then controls the pages that are already open.activate() {for (name of globalThis.caches.keys()) {if (name != cfg.cache && name.startsWith('hl-shell-')) { globalThis.caches.delete(name) }}globalThis.clients.claim()return null}// FETCH: what answers this request. Never null — the entry script hands the answer to// `respondWith` unread.answer(req) {if (cfg.shell == false) { return fetch(req) }if (req.method != 'GET') { return fetch(req) }let url = new URL(req.url)if (url.origin != globalThis.location.origin) { return fetch(req) }if (req.mode == 'navigate') { return navigation(req, url) }if (cfg.precache.includes(url.pathname + url.search)) { return cacheFirst(req, url.pathname + url.search) }return fetch(req)}// may the document at this path be kept? Only if the route that answers it is a page// the allow-list names — the whole of D38 in one predicatekept(path) {let m = router.match(path)return m != null && m.route.keep == true}// HOW LONG A NAVIGATION WAITS FOR THE NETWORK when a kept copy of the page exists (#340), in ms.// A silent connection (no answer, no refusal) would otherwise show nothing at all. After this the// copy is served and the fetch goes on in the background; if it succeeds it refreshes the copy// (the page already shown stays). A page with no copy, or not kept, waits for the network.navWait = HlwRouter.navigationWaitnavigation(req, url) {path = url.pathname + url.searchlet copy = nullif (kept(url.pathname)) {copy = globalThis.caches.match(path, { cacheName = cfg.cache })if (copy == null) { copy = standIn(url.pathname) }}let r = nullif (copy != null) {r = globalThis.__hlWithin(() => { return fetch(req) }, navWait, (late) => {if (late.ok && late.value.ok && !cfg.dataFree.includes(url.pathname)) { keep(path, late.value.clone()) }return null})if (r.late == true) { return marked(copy) }} else {r = globalThis.__hlAttempt(() => { return fetch(req) })}if (r.ok) {// a data-free page's copy is the anonymous one made at install, never the live renderif (r.value.ok && kept(url.pathname) && !cfg.dataFree.includes(url.pathname)) { keep(url.pathname + url.search, r.value.clone()) }return r.value}let hit = globalThis.caches.match(url.pathname + url.search, { cacheName = cfg.cache })if (hit != null) { return marked(hit) }// A PAGE OF A KEPT COMPONENT THAT WAS NEVER LOADED AS A DOCUMENT (#124): any kept document// of the same component stands in — the page boots it with this url's parameterslet like = standIn(url.pathname)if (like != null) { return marked(like) }// THE APP'S OWN FALLBACK (#120): a data-free page, kept once, instead of the bare noticeif (cfg.fallback != null) {let fb = globalThis.caches.match(cfg.fallback, { cacheName = cfg.cache })if (fb != null) { return fb }}standby = noticeShell(url.pathname)if (standby != null) { return standby }return unavailable(url.pathname)}// A KEPT DOCUMENT LENDS ITS SHELL (#350), never its page. The client claims the// shell against this document, whose page markup is already replaced by the notice.// It never constructs the donor page or opens the state store. The cached copy stays intact.noticeShell(String path) {cache = globalThis.caches.open(cfg.cache)tag = 'id="hl-seed">'for (req of cache.keys()) {if (kept(new URL(req.url).pathname)) {res = cache.match(req)text = res.text()at = text.indexOf(tag)if (at >= 0) {start = at + tag.lengthend = text.indexOf('</script>', start)if (end > start) {seed = JSON.tryParse(text.slice(start, end))if (seed != null && seed.shell != null && seed.page != null) {// A path can contain '<'; it must remain JSON inside a script element.value = JSON.stringify(path).replaceAll('<', '\u003c')taggedHtml = text.slice(0, start + 1) + '"offlineNotice":' + value + ',' + text.slice(start + 1)body = noticeDocument(taggedHtml, seed, path)if (body == null) { continue }H = globalThis.HeadersR = globalThis.Responseheaders = new H(res.headers)headers.delete('content-length')headers.delete('content-encoding')return new R(body, { status = 503 headers = headers })}}}}}return null}// The labelled page region is unambiguous even when the shell has its own if/for// regions or several parent levels. Replace it before sending any HTML to the tab.noticeDocument(String html, Hybrid seed, String path) {open = '<!--[hl:page-->'close = '<!--]hl:page-->'start = html.indexOf(open)if (start < 0) { return null }end = html.indexOf(close, start + open.length)if (end < 0) { return null }body = html.slice(0, start + open.length) + noticeMarkup(path) + html.slice(end)// seed.head holds appHead(), not headOf(): the donor's __title is not used.title = seed.head != null && seed.head.title != null ? seed.head.title : ''tag = '<title>' + noticeEscape(title) + '</title>'titleStart = body.indexOf('<title>')titleEnd = body.indexOf('</title>', titleStart)if (titleStart >= 0 && titleEnd >= 0) {return body.slice(0, titleStart) + tag + body.slice(titleEnd + 8)}return body.replace('</head>', tag + '</head>')}noticeEscape(String text) {return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')}// The shell notice keeps the text of the original shell-less response.noticeMarkup(String path) {return '<main data-hl-offline="1" role="status"><h1>Unavailable offline</h1><p><code>' + noticeEscape(path) + '</code> is not one of the pages this app carries offline.</p><p><a href="/">Back to the start</a></p></main>'}// A DOCUMENT FROM THE CACHE SAYS SO (#342). It is as old as its visit, so the page must catch up when its// first socket opens: `"cached":true` goes first into the seed, and the client's first hello asks as a// reconnect does (`again`), which the server answers with the #143 resync. A document the network// rendered is never marked, so it never resyncs. The stored copy stays as it was.marked(res) {R = globalThis.ResponseH = globalThis.Headerstag = 'id="hl-seed">{'text = res.text()h = new H(res.headers)h.delete('content-length')h.delete('content-encoding')let out = textif (text.includes(tag) && !text.includes(tag + '}')) { out = text.replace(tag, tag + '"cached":true,') }return new R(out, { status = res.status statusText = res.statusText headers = h })}// a kept document of the route's own component: this route's first, else another route'sstandIn(path) {let m = router.match(path)if (m == null || m.route.keep != true) { return null }let cache = globalThis.caches.open(cfg.cache)let other = nullfor (req of cache.keys()) {let o = router.match(new URL(req.url).pathname)if (o != null && o.route.keep == true && o.route.page == m.route.page) {if (o.index == m.index) { return cache.match(req) }if (other == null) { other = req }}}return other != null ? cache.match(other) : null}keep(key, res) {let cache = globalThis.caches.open(cfg.cache)cache.put(key, res)return null}// CACHE-FIRST for the shell. A miss still asks the network, so a worker installed// before an asset existed is not a permanent failure.cacheFirst(req, key) {let hit = globalThis.caches.match(key, { cacheName = cfg.cache })if (hit != null) { return hit }let r = globalThis.__hlAttempt(() => { return fetch(req) })if (r.ok) {if (r.value.ok) { keep(key, r.value.clone()) }return r.value}let R = globalThis.Responsereturn new R('', { status = 503 statusText = 'Offline' })}// A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side// navigation was never a document request, so the client asks for it to be kept —// fetched here as the document it would be, if it is a page the allow-list names.message(data) {if (data != null && data.t == 'forget') { return forget(data.path) }if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })if (r.ok && r.value.ok) { keep(data.path, r.value) }return null}// THE USER CHANGED (#125): every kept document is another user's, so they all go; the// page that stands is fetched again as the new session sees itforget(path) {let cache = globalThis.caches.open(cfg.cache)for (req of cache.keys()) {let u = new URL(req.url)if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }}if (path != null && kept(path) && !cfg.dataFree.includes(path)) {let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })if (r.ok && r.value.ok) { keep(path, r.value) }}return null}// A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at// the path the notification carriesclicked(n) {n.close()let path = n.data != null && n.data.path != null ? n.data.path : '/'for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {if (c.focus != null) { return c.focus() }}return globalThis.clients.openWindow(path)}// A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a// notification by this worker, whether or not any page is open. `url` is where a click goes (the// path rides in the notification's data, `clicked` reads it); a payload that is not JSON is// shown as the body of a notification titled with the page's origin host.pushed(text) {let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }let title = p.title != null ? p.title : globalThis.location.hostlet opts = { data = { path = p.url != null ? p.url : '/' }; }if (p.body != null) { opts.body = p.body }if (p.tag != null) { opts.tag = p.tag }if (p.icon != null) { opts.icon = p.icon }return globalThis.registration.showNotification(title, opts)}// A page this app does not carry offline. A DOCUMENT, so the tab shows something and// no navigation fails inside the browser; 503, so a probe can tell it from a page.unavailable(path) {let esc = path.replaceAll('&', '&').replaceAll('<', '<')let body = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Offline</title><link rel="stylesheet" href="' + cfg.css + '"></head><body><main data-hl-offline="1"><h1>Unavailable offline</h1><p><code>' + esc + '</code> is not one of the pages this app carries offline.</p><p><a href="/">Back to the start</a></p></main></body></html>'let R = globalThis.Responsereturn new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })}
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre