gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit536d7c58536d7c58Merge branch 'playing-row' into mainJukebox536d7c58/plugins/web/README.md

60.3 KB

  1. # hl:web — the web framework
  2. `hl:web` serves an app's pages from the server and keeps them live in the browser. It is written
  3. in Hybriel: `WebFramework.hl` is the server half, `client.hl` the browser half, and `compile.hl`
  4. turns each component's View into that component's own code. `offline.hl` holds the optional
  5. browser state and durable queue. The model behind it (components,
  6. Views, realms, the boundary) is in [COMPONENTS.md](../../COMPONENTS.md). This page lists the rules
  7. an app is held to. Each rule is a located refusal at boot unless it says otherwise.
  8. ## Starting an app
  9. ```hybriel
  10. import WebFramework from 'hl:web'
  11. import Home from './components/home.hl'
  12. import Styles from './styles.hl'
  13. routes = [ { pattern = "/" component = Home } ]
  14. server = new WebFramework(routes = routes, styles = Styles, port = 8080)
  15. ```
  16. Settings may be passed as named arguments. Most of them may instead be members of the file that
  17. runs the `new`:
  18. | setting | default | meaning |
  19. |---|---|---|
  20. | `routes` | `[]` | the route table (below); pass it as an argument |
  21. | `styles` | none | the app's styles file: the imported class, or a path string. It must be in the project graph |
  22. | `port` | 8080 | the port to listen on |
  23. | `host` | `HL_HOST`/`HOST`, else 0.0.0.0 | the interface to bind |
  24. | `audience` | `{}` | per outward event, who receives it (see Events) |
  25. | `coalesce` | `{}` | server face name → milliseconds without a newer call before sending; e.g. `coalesce = { saveDraft = 600 }` (see drafts below). Unknown faces and non-number delays are refused at boot |
  26. | `minify` | false | one-line HTML and compact modules; a compact module carries no position tables — the framework answers them at the module's url with `sites=1` in the query, and the browser fetches them once when a fault is reported (mission 505) |
  27. | `watchMode` | true | a saved `.hl` file re-analyses the app and reloads every open tab |
  28. | `sessionDir` | `<app>/.sessions` | where sessions are stored; `false` keeps them in memory |
  29. | `sessionMaxAge`, `sessionIdle`, `sweepInterval` | 14 days, 15 min, 5 min | the session clocks, in seconds |
  30. | `sessionCookie` | `hlsid` | the cookie's name: letters, digits, `-` and `_` |
  31. | `sessionSecure` | null | the cookie's `Secure` flag: null = set when the request came over https (this server speaks TLS, or `X-Forwarded-Proto: https`), true always, false never |
  32. | `sessionAnonMax` | 10000 | the most sessions nobody logged in to; the oldest go first |
  33. | `sessionAnonKeep` | 1 day | seconds any session without a login stays valid, with or without app data; cold reads reject expired sessions and the sliced store pass removes their files, while logged-in sessions use `sessionMaxAge` |
  34. | `lang` | none | the default `<html lang>` on served documents; a page's or shell's `$lang` overrides it |
  35. | `appTitle`, `appDescription`, `appImage`, `appFavicon`, `meta` | none | the head every page gets unless it declares its own |
  36. | `links` | none | a list of hybrids, one `<link>` each in every page's head (`{ rel = 'preconnect' href = '…' }`) |
  37. | `appIcons`, `appShortName`, `appThemeColor`, `appBackgroundColor`, `appTouchIcon`, `appManifest` | none | make the app installable: a web app manifest, linked from every head (see Offline and installable) |
  38. | `offline` | none | the pages kept offline: a service worker, their state in IndexedDB, a queue for their emits |
  39. | `pushKey` | none | the app's VAPID public key (base64url): serves the service worker with Web Push, and enables `subscribePush()` (see Web Push) |
  40. | `pushPrivateKey`, `pushSubject` | none | the VAPID private key (base64url, the 32-byte scalar of `pushKey`) and a `mailto:`/`https://` contact: enable `sendPush()` (see Web Push). A key that is not `pushKey`'s other half is refused at boot |
  41. | `pingEvery`, `pongWithin` | 25, 10 | the dead-socket clock, in seconds: the browser pings every `pingEvery`, and a pong missing after `pongWithin` closes the socket and reconnects |
  42. | `uploadMax` | 64 MiB | the largest file an emit may carry, in bytes (see Files in an emit) |
  43. | `uploadSessionMax`, `uploadHeldMax`, `emitMax` | 256 MiB, 1 GiB, 16 MiB | the bytes announced by one session's unfinished uploads, by all sessions', and the largest `POST /__hl/emit` body (413 past them). An accepted upload start makes a session when the visitor has none |
  44. | `pageHeaders` | none | headers added to EVERY answer, over the safe defaults (see Security headers) |
  45. | `trustedOrigins` | none | origins besides the request's own host allowed to emit, upload and open the socket |
  46. | `pushKept`, `pushKeptBytes`, `tabKept` | 10000, 1 MiB, 600 | the push log per tab (see Events): the pushes kept for a socket that comes back, their bytes, and the seconds a tab without a socket is kept |
  47. An app runs on one web framework. If its files reach two packages that hold a `WebFramework.hl`
  48. (for example an old vendored copy beside this one), it is refused at boot, naming the import row
  49. of each.
  50. ## Routes
  51. A page may declare the framework-reserved root member `$status = missing ? 404 : 200` after its `missing` member. The server reads it only for a document answer, from the matched page after construction; absent/null (or a parent that closes its slot) keeps 200. It must be an integer Number from 100 to 599; an invalid value causes a clear server error naming the component and `$status`. The old `__status` is still accepted during migration; `$status` wins when both are declared. Client navigation stays in-shell and constructs no server page. The member follows ordinary browser state rules; there is no extra status channel. An offline cached document keeps its cached status.
  52. After a successful login face returns, use `navigate(path, replace = true)` to replace the current login entry so Back reaches the page before it (#379; case `9379`).
  53. Import `{ navigate }` from `'hl:web'` and call `navigate(path)` to add a history entry, or `navigate(path, replace = true)` to replace the current entry. Both apply the matched route in the browser. A URL of another origin loads as a document, replacing the current history entry when `replace = true`. When the page component and its parent chain stay the same, its instance and DOM stand: typed text and open edits survive, while changed route parameters (including removed parameters, which become null), their client derivations and server values update in place. Navigation constructs no page on the server.
  54. Fragment links (#347) keep their fragment in the address. Same-page fragment links use the
  55. browser's native scroll and history without a page request. Cross-page links and
  56. `navigate('/page#section')` scroll to the element with that id after the page stands,
  57. including Back/Forward restores. The fragment never crosses to the server.
  58. Each entry has a `pattern` (`/posts/:id`, `/assets/*`) and one kind:
  59. | kind | answers with |
  60. |---|---|
  61. | `component = Home` or `"./components/home.hl"` | the page, rendered on the server; the component must be imported by the app, and must declare a View |
  62. | `function = (route, req, server) => { … }` | what the function returns (a Hybrid becomes JSON); `req.session` is the cookie's session, or null; `server` is the running WebFramework instance |
  63. | `direct = "text"` | that text |
  64. | `file = "./x"` | one file |
  65. | `directory = "./assets"` | the files under a directory |
  66. | `socket = Device` | one server instance per WebSocket connection; see below |
  67. A function route may be imported from a separate file. Its third argument is the running
  68. framework, so it can read settings such as `server.appTitle` or call `server.page(…)`.
  69. Declare the third parameter as `&server` to write through it to the running instance.
  70. Existing handlers that declare only `(route, req)` keep working.
  71. `server.page(…)` includes the rendered component’s Style, its composed children and parent
  72. layouts when the component is imported anywhere in the project graph; no component route
  73. entry is required. It serves the page without the JSON seed or browser bootstrap when the
  74. whole chain can be proven to need no browser code: no handlers of any kind, faces, emits,
  75. member writes or bound inputs. Plain native POST forms and simple read-only server-rendered
  76. members qualify. CSS and head metadata stay; links and forms then work natively, with no
  77. framework JavaScript fetches, hydration, socket or client navigation.
  78. The check includes parent layouts and composed children, including untaken branches. When
  79. unsure it keeps the scripts: callable members, unfamiliar syntax/imports, inheritance, cycles
  80. and component argument bindings retain the browser client. An app declaring `offline` or
  81. `pushKey` retains scripts for these renders too. This is automatic, with no new option;
  82. ordinary `component = …` route pages keep their existing client behaviour.
  83. A component route may also declare `redirect = (route, req) => { … }` (proposal #241,
  84. branch W284, pending creator acceptance). Return a non-empty URL String for a permanent
  85. `301` with `Location`, or `null` to render normally. The callback runs on the server before
  86. component construction; the route remains a component page in the browser table. There is
  87. no status option in this proposal: existing route rows have no redirect-status convention.
  88. ```hybriel
  89. { pattern = "/" component = Home redirect = (route, req) => { if (req.headers['host'] == 'old.example') { return 'https://new.example/repo' } return null } }
  90. ```
  91. Client navigation, including Back/Forward, asks the same callback through the existing
  92. `page` crossing, before deriving destination values. It uses a logical GET request with
  93. `path`, decoded `query`, `session`, null `body`, and the carrier's lowercase headers (the
  94. socket upgrade or POST fallback; cookie and authorization headers are omitted). Document
  95. requests use their ordinary request object. Keep the callback a decision without writes;
  96. use host, path, query or session for rules shared by both request paths. A redirect answer
  97. loads the destination as a document using `location.replace`, including another origin.
  98. A null answer continues normal in-page navigation without loading a document. The callback
  99. itself never travels to the browser.
  100. A named group (`:id`) reaches the component as a construction argument of the same name: declare
  101. `id = null` at its root. A named wildcard does the same with the rest of the path:
  102. `/code/*path` gives `path = 'src/lib/util.hl'` for `/code/src/lib/util.hl`, on the first load and
  103. on a navigation. A bare `*` has no name a member could take; it is what a `directory` route
  104. serves from.
  105. The request itself reaches a component the same way, and only one that declares the member
  106. (COMPONENTS.md): `session = null` gets the session, `host = null` the host without its port,
  107. `headers = null` the request's headers as a hash with lowercase names —
  108. `headers['accept-language']`. On a client navigation they are the headers of the request the
  109. navigation crossed on, so they are still the browser's own: the socket's upgrade request, or the
  110. `POST /__hl/emit` under the fallback. `cookie`, `authorization` and `proxy-authorization` are left
  111. out, because a member is state and state reaches page script.
  112. Socket routes (#353) accept an application WebSocket on the main port:
  113. `{ pattern = '/__hc/device-channel' socket = Device }`. Import Device as a
  114. server class that inherits `Socket` from `hl:web/socket`. Each connection gets
  115. one instance, with `on connect(Hybrid req)` receiving the raw `path` (including
  116. query), lowercase `headers` (including Authorization), and cookie `session` or
  117. null. Returning false closes with 1008 immediately after the handshake. Handle
  118. `on message(String data)` and `on close()`; inherited `send(String data)` and
  119. `close()` act on that connection. http1 delivers binary payloads as Strings;
  120. `send(data, binary = true)` sends a binary frame. Messages bypass the boundary protocol and
  121. socket routes are omitted from the client route table. Combining `socket` with
  122. `component` or `function` is a located build error.
  123. ```hl
  124. import Socket from 'hl:web/socket'
  125. inherit Socket
  126. on connect(Hybrid req) { return req.headers['authorization'] == 'Bearer secret' }
  127. on message(String data) { send(data) }
  128. on close() { echo('connection closed') }
  129. ```
  130. ## Persistent pages
  131. A page that declares `persistent = true` is kept by its ADDRESS
  132. (pathname + search), with no count cap. When the user leaves it (inside the same shell levels), its DOM is detached and kept
  133. with its live instances; a later visit to the same address by a link click, `navigate()`, Back or Forward attaches the same
  134. nodes again, scrolled where it was left, with typed text and open edits, and asks the server for nothing. A page without the
  135. flag behaves as before (Back and Forward keep the last five pages left; a link builds fresh).
  136. A page built locally while disconnected that still lacks its first server answer is an exception:
  137. restoring it starts that values crossing again, keeping the same instance, nodes and drafts (#437). While detached it processes no
  138. push: the pushes the tab receives that its components listen to are queued for it, in order, within 1 MiB (the default
  139. `pushKeptBytes`), and run before it is shown, so it comes back with them applied. The copy is dropped and the page built fresh
  140. (one server crossing) when the queue overflowed, when the socket resynced (`resumed` with `how = 'resynced'`) or the session
  141. changed while it was away. An optional `persistFor = <seconds>` drops a copy not shown for longer than that; the check runs
  142. at each navigation (there is no timer), so a stale copy only waits in memory until the next navigation or visit. Without it a
  143. persistent page never expires.
  144. ```hl
  145. parent './shell.hl'
  146. persistent = true // keep this chat's DOM and state per address
  147. persistFor = 3600 // optional: rebuild it when it was not shown for an hour
  148. Hybrid msgs = []
  149. on client msg(String room, String text) { if (room == id) { msgs.push(text) } }
  150. ```
  151. ## Components
  152. A View `if` takes a member, a field path or a `for` row variable, a comparison of one with a literal (`==` `!=` `<` `<=` `>` `>=` against a string, number, boolean or `null`: `if (x != '')`, `if (row.state == 'open')`, `if (count > 3)`), or a `!` of one; it repaints when the member changes, and the server render agrees (#287; case `9287`). Anything else is refused at build: derive `showRows = rows.length > 0` or `enabled = a && !b` at the root and use `if (showRows)` / `if (enabled)`; field paths such as `if (flags.enabled)` also update live (#379; case `9379`).
  153. A component is a `.hl` file with a `View`. Its root members are its state, and are constructed on
  154. the server for each request.
  155. **A View attribute is a literal, a member or a field path.** `href = "/"`, `href = url` and
  156. `href = p.url` are allowed. `href = '/posts/' + id` is refused at its line: declare
  157. `postUrl = '/posts/' + id` at the file's root and write `href = postUrl`. The same holds for a
  158. value bound on a component reference (`Card { title = t }`) and for the condition of an `if` in a
  159. View, which may also be a `for` row variable.
  160. **`follow = flag` keeps a scroll container at its end** (#396; case `9396`). `div { follow = tailing style = 'overflow-y: auto; overflow-anchor: none; height: 20em' for (r of rows) { … } }`: `follow` is a literal or a member (a flag). After a patch that adds or grows content inside the container, the framework scrolls it to its end only if it stood at its end (within 4 px) before the patch; a user who scrolled up stays where they are. What grows later inside it (an image that loads, wrapping text of a child that stood there at the last patch) keeps it at the end the same way. A member that becomes false turns it off. It needs no handler, timer or observer in the app and renders no HTML attribute. Give the container `overflow-anchor: none`: the browser's own scroll anchoring otherwise moves a container that is not following when rows are inserted above its anchor. `overflow-anchor: auto` is supported too: a paused reader keeps their place through the browser's anchoring, while follow still keeps a following container at its end (case `9396.1`).
  161. `scrollTop = member` and `scrollLeft = member` (#445) set a container's position after the patch that writes that member, including another write of the same value. They accept a literal or field path too, render no HTML attribute, and apply non-zero initial values on mount/hydration. User scrolling never writes the member; unrelated member writes preserve it. A virtual-list can declare `scroll = 0`, bind `div { scrollTop = scroll … }`, and reset with `set resetKey(Number v) { scroll = 0 }`: every changed reset key resets the container, even after an earlier reset already stored 0. Scroll position bindings on elements inside `for` rows are currently unsupported.
  162. **`dialog { modal = flag }` opens the dialog as a browser modal; `popoverOpen = flag` shows a popover** (#329, #389; cases `9329`, `9389`). `modal` (on a `dialog`) and `popoverOpen` (on an element with the HTML `popover` attribute) take a literal or a member (a flag). True calls `showModal()` (`showPopover()`), false calls `close()` (`hidePopover()`); it works at first load (a flag true at render opens after the page is claimed), after a navigation and by a handler's write. Escape, a form `method = 'dialog'` close or any other native close of the dialog, and a light dismiss of the popover (a click outside, Escape), write the member back to false, so a text bound to the member agrees with the screen. `open` keeps its present meaning (a non-modal dialog). Neither name renders an HTML attribute.
  163. **An attribute name that is not an identifier is quoted.** `"aria-hidden" = "true"` and
  164. `"data-page" = it.target` render as written and bind like any attribute, in a `for` row too. A
  165. camelCase name is not rewritten (`ariaHidden` renders as `ariaHidden`). `data-page = it.target`
  166. unquoted is refused at its line, naming the quoted form.
  167. **A bound attribute in a `for` row follows the row** on every update of the list: a new list, a
  168. `push`, an `upsert` and a write into a row's record (`items[0].title = …`) repaint it, as they
  169. repaint the row's text and class.
  170. Keyed row updates keep an independent snapshot of what was painted (#210). After the
  171. initial snapshot, a change updates its changed fields; unchanged text is retained without
  172. JSON serialisation. The compiled View supplies field read paths, so unrelated element,
  173. text-leaf and nested-region reads skip painting (#355). Reads of a whole record overlap
  174. all its fields. Insertions, removals and replacements still use the keyed row reconciliation.
  175. **The tree carries the elements the HTML parser implies.** `table { tr { td { … } } }` is rendered
  176. as `table > tbody > tr > td`, because that is the tree the browser builds from the HTML, and the
  177. page is continued from the tree the browser built. The pairs are listed in `view.hl`
  178. (`impliedElements`): `tr`, `td` and `th` under `table` get a `tbody`, `td` and `th` under `tbody`,
  179. `thead` or `tfoot` get a `tr`, and `col` gets a `colgroup`. Consecutive children that need the same
  180. container share one.
  181. **Build warnings (#348).** An `a` without `href`, and a click handler on a
  182. non-interactive element, each produce a located warning on stderr once per site
  183. per build; boot continues. Use `a { href = url }` for navigation and
  184. `button { type = "button" }` for actions. Buttons, anchors with href, input,
  185. select, textarea, summary, label, option and details accept click handlers.
  186. A literal role of button/link/tab/menuitem/checkbox/switch together with tabindex
  187. also qualifies. Elements with `contenteditable` are text-editing surfaces: their
  188. click places the caret, so they do not produce the click warning. A tabindex
  189. alone does not qualify. Composed components are checked at their own elements.
  190. The other rules:
  191. - A View reads names the file declares and `$parent` host reads. Other undeclared names are refused.
  192. - `parent './main.hl'` wraps a page in a shell. The shell declares `slot = null` and places
  193. `slot` in its View exactly once. A component that is filled (`Card { p { … } }`) must declare a
  194. slot too.
  195. - **`$parent` is the page or component whose View placed this one** (hybriel#63). In a handler,
  196. `$parent.save(x)` calls a method of that host and `$parent.title` reads one of its members; writing
  197. through it is refused when the file is built. In the browser, hl:web hands the component the live
  198. host instance (never a copy) when it builds it: when the page is hydrated, when a row or an `if`
  199. arm adds a component later, and after a client-side navigation. A page's `$parent` is its
  200. wrapping layout (`parent './main.hl'`), whose `slot` holds it (hybriel#361). A layout with
  201. its own `parent` reaches that parent the same way. Navigation and kept-page restoration
  202. use the current live layout instance. A top shell or standalone page has no host, so
  203. `$parent` there keeps the "'$parent' has no owner" error. Server construction also passes
  204. the host as `hlLoad`'s third argument. Reads `$parent.x` and `$parent.x.y` are also
  205. allowed in View text, attributes, `if` conditions and `for` sources under the usual
  206. member rules, and in member initializers (including derived expressions). They follow
  207. host writes locally and take the current value on arrival and kept-page return
  208. (#441, decision 2026-11-24). Calls work in handlers and, as before, lexical initializers; dependencies inside
  209. host methods are not tracked here. View calls and writes remain refused.
  210. There is no cross-file emit.
  211. - `body { … }` is allowed only as the root of a View, and a page wrapped by a parent cannot have
  212. one: the shell owns the body. A standalone page and a shell both use the existing
  213. document body: its root attributes and Style classes apply there, and its children
  214. render inside it. Client navigation updates that body in place and clears the prior
  215. root's attributes. A bound `class` and Style references share one class attribute.
  216. - A View cannot render itself, directly or through other components.
  217. - A Style rule cannot be written on a component reference. Write it on an element inside that
  218. component.
  219. - A page's head comes from its members `$title`, `$description`, `$image`, `$favicon` and
  220. `$meta`, and falls back to the app's `appTitle`, `appDescription`, `appImage`, `appFavicon` and
  221. `meta`. `$lang` (page, shell or layout; the page's wins) sets `<html lang>` over the `lang` option. A handler that writes one of them updates the document. The old `__title` … `__meta` and `__lang` are still accepted; when both are declared the `$` one wins. A page needs no `import 'hl:web'` for these.
  222. A member used as an element's `class` can select `Style.rule` values; its initializer must name every rule it can hold (a rule named only in a handler remains unused), and each element applies the usual kebab-case and tag-prefix rules when the member changes (#448): write `active` in the handler so `look` recomputes.
  223. ```hybriel
  224. Boolean active = false
  225. look = active ? Style.buttonOnLook : Style.offLook
  226. Style {
  227. buttonOnLook { color = 'green' }
  228. offLook { color = 'red' }
  229. }
  230. View { button { type = 'button' class = look 'Toggle' on click() { active = !active } } }
  231. ```
  232. A plain `Style.notice` emits `.notice`, which loses to an older app `p.notice`; remove or rename the older app rule so the component's Style owns its look (F14), or, if that rule must stay, use a literal View id and its component `Style { '#strong' = { … } }` rule to win by specificity (#379; case `9379`).
  233. In a component, `import { colorText } from '../shared/tokens.hl'` and `Style { p { color = colorText } }` use a shared static token declared with `var()` and imported by the app's styles file; CSS emits `var(--color-text)` and the Style-only token import stays out of the browser module (core fix `6aeb0a48`, #239). Direct component imports of `var` from `'hl:web/css'` are still refused by the core; use token members ([repro](../../missions/web/repros/W327-style-tokens/)).
  234. A View may reference a nested Style rule with `Style.name` when the name is unique
  235. within its component's Style. The class follows the ordinary tag-prefix rule, and
  236. the CSS retains the enclosing descendant selector. Repeated names are ambiguous
  237. (including a top-level and nested pair); the error locates the reference and both
  238. rule declarations. Rename one rule to make the reference unique. A rule repeated
  239. under `@media`, `@supports` or `@container` at the same nesting path restyles
  240. the same rule and does not make the reference ambiguous.
  241. A parameter the parent binds (`Child { resetKey = token }`) goes through the setter the child declares for it
  242. (`set resetKey(Number v) { … }`), at the mount and on every change of the host's value; without a setter it is the plain
  243. member write. See COMPONENTS.md, "A bound parameter goes through the child's setter".
  244. ## Events
  245. `on name(…)` handlers and `emit` statements cross between the browser and the server over a
  246. WebSocket on the app's own port. `POST /__hl/emit` is the fallback for a peer without a socket.
  247. A handler that takes `session` as its last parameter gets the connection's session from the
  248. server, never from the peer. A handler may end its parameters with `request` (after `session`):
  249. `on server login(user, session, request)` gets `{ ip, headers, userAgent, https }` of the carrier, read-only —
  250. `ip` is `X-Client-IP`, else the first `X-Forwarded-For` hop, else the peer address (a WebSocket's upgrade carries none yet).
  251. Trust the proxy headers only behind a proxy that sets them.
  252. The store pass queues filenames only; memory still grows with store size because `hl:fs listDir` buffers the directory.
  253. SESSIONS ARE LAZY: a visitor gets a session (id, file, cookie) only when something is stored in it — a login,
  254. `session.data`, an accepted upload start — so cookie-less requests cost nothing. Existing cookies (same name) and
  255. session files keep working unchanged; logins never expire. Over a socket the ack carries a one-time token the page
  256. trades for the cookie at `POST /__hl/adopt`.
  257. THE COOKIE IS RE-ISSUED (W138). Every HTTP answer that resolves a signed-in session (a page, a function route, a
  258. POST emit, an upload start) sends the session's `Set-Cookie` again when the cookie was never issued with the app's
  259. current attributes (name, `Domain`, `Path`, `Secure`, `SameSite`: a short signature is kept in the session file) or
  260. was last issued more than 24 hours ago. So an old host-only login moves onto the app's `sessionDomain` on its next
  261. visit, and a login with `sessionMaxAge` of 99 years stays inside Chrome's 400-day cap on a cookie's lifetime.
  262. Anonymous sessions are not refreshed, and a socket cannot set a cookie, so sockets are left alone.
  263. An outward event reaches the tab that caused it. To send it to other connections, give it an
  264. `audience` entry: a function of the event's arguments and the receiving connection's session that
  265. answers true or false.
  266. **No push is lost across a socket gap** (ticket #143). A push goes to the tab, not to its
  267. socket: the server numbers every push to a tab and keeps the last `pushKept` of them (at most
  268. `pushKeptBytes`), also while the tab has no socket. The bytes bound is the one that governs: a
  269. busy server pushes hundreds of small frames in a few seconds, and a count bound below the bytes one
  270. turns a short gap into a resync (#160). A tab whose socket comes back (a phone
  271. that slept, a network switch, a socket the ping gave up on) names the last push it got in
  272. its `hello` and is sent the rest again, in order, each once. A gap longer than that log, a
  273. tab gone longer than `tabKept` seconds, or a server that restarted is told `resynced`, and nothing more
  274. (hybriel#401): the page keeps its values, the server derives none again. The one resync that carries values is the
  275. first build of a destination the browser built offline (its hello says `refresh`). Then
  276. every mounted component that declares `on client reconnected(r)` gets
  277. `r = { how, missed, build, stale }`: `how` is `'replayed'` (nothing was lost; `missed` pushes came again)
  278. or `'resynced'` (the log did not cover the gap: a member only a push handler builds up may lack what was pushed
  279. meanwhile — ask the server for it here, or reload when `r.stale`). `build` is the server's build and `stale` is true when it is not
  280. the build this page was rendered by — the server restarted onto changed sources (ticket #152;
  281. in every mode, `watchMode` additionally reloads the tab itself). It fires once per reopened
  282. socket, never on the first. A late first server answer for a locally built page also raises `reconnected` once after its values are applied, with `how = 'resynced'`, `missed = 0`, and the answer's `build` and `stale`; construction does not run again.
  283. **A component mounted** (#236). `on mount()` runs once per instance, in the browser, after its elements stand
  284. and its handlers are attached: after the document's first claim, after an in-shell navigation built it, for a
  285. kid minted later (a row added). A kid runs before the component that placed it. A page kept for Back/Forward
  286. does not run it again when it comes back (it did not mount again); a page built afresh is a new instance and
  287. runs it once. The server never runs it, and a write in it repaints like any handler's. Case `9236`.
  288. ```hybriel
  289. count = 0
  290. View { input { id = 'name' name = 'name' } p { count } }
  291. on mount() {
  292. count = count + 1
  293. document.querySelector('#name').focus()
  294. }
  295. ```
  296. **A page shown again** (#174). Every mounted component that declares `on client shown(r)` gets
  297. `r = { persisted }` when the browser shows the page: on `pageshow` (`persisted` is true for a restore
  298. from the back/forward cache, false for the first show) and when `visibilitychange` makes the tab
  299. visible (`persisted` false; turning hidden does not call it). An app re-plans here, without waiting
  300. for the user's first touch.
  301. ```hybriel
  302. on client reconnected(r) {
  303. if (r.stale) { location.reload() }
  304. if (r.how == 'resynced') { refresh() }
  305. }
  306. ```
  307. **An element seen** (#412). An element handler `on seen() { … }`, on any element, on a component placement (`Msg { m = row on seen() { … } }`: it watches the placement's root
  308. element, #422) and in a `for` row, runs
  309. ONCE per element: when the element is at least partly in the viewport while the tab is visible
  310. (`document.visibilityState`). An element that came into view while the tab was hidden fires when the tab becomes
  311. visible. The page has one `IntersectionObserver` for all of them; an element is let go after it fired and when it
  312. leaves the DOM unseen. The handler is an ordinary one: its writes repaint, its emits go out as usual (one each, no
  313. batching). Measured at 2000 rows: see the #412 case.
  314. ```hybriel
  315. rows = [{ @id = 'a' id = 'a' } { @id = 'b' id = 'b' }]
  316. View { for (row of rows) { article { row.id on seen() { emit server markRead(row.id) } } } }
  317. ```
  318. **Window, viewport and document events (#430, #431).** A component handles the events of the browser's own objects with
  319. the language's qualified `on`, whose qualifiers `window`, `viewport` (`window.visualViewport`) and `document` are reserved
  320. browser targets (SPEC.md "Reserved browser targets"): `on window.beforeinstallprompt(Hybrid e)`, `on window.appinstalled(Hybrid e)`,
  321. `on viewport.resize(Hybrid e)`, `on document.paste(Hybrid e)`, `on document.drop(Hybrid e)`; any event name of the object works.
  322. On the server the handler is inert. The listener is attached when the component mounts and a handler runs only while its mount
  323. stands: a destroyed component does not hear, and a persistent page (#411) kept away is detached and hears nothing until it is
  324. put back (no push and no window event reaches a page that is not on the document). The handler starts INSIDE the DOM event, before
  325. any await, so `e.clipboardData` and `e.dataTransfer` are still readable (Firefox empties them after the event); do the reading
  326. first. A member write repaints like any handler's. A `beforeinstallprompt` that fired before any component listened is kept
  327. (the same event object, so `e.prompt()` works) and handed once to the first component that listens when it mounts. A component
  328. that listens to `document.drop` makes the framework cancel `dragover`, or the browser would open the dropped file. A member,
  329. import or local named `window`, `document` or `viewport` cannot be such a qualifier (a located compile error).
  330. ```hybriel
  331. canInstall = false
  332. keyboard = 0
  333. pastedText = ''
  334. on window.beforeinstallprompt(Hybrid e) { e.preventDefault() canInstall = true }
  335. on viewport.resize(Hybrid e) { keyboard = window.innerHeight - window.visualViewport.height }
  336. on document.paste(Hybrid e) { pastedText = e.clipboardData.getData('text/plain') }
  337. ```
  338. A value-form emit (`answer = emit server ask()`) waits for one answer, so it has one answerer.
  339. If two files in the target realm answer the event, it is refused.
  340. DOM handlers received during the initial claim run after claim finishes; native defaults remain enabled except submit, so a deferred handler's `preventDefault()` is too late to cancel that original event.
  341. **A write anywhere repaints what it wrote** (tickets #98, #99), from the compiler's write
  342. sets, never by watching the members:
  343. - A listener repaints what its handler writes when the handler is done. A handler still
  344. waiting after the task that started it (a network answer, `new Promise(…)`) has its
  345. write set painted at the next animation frame too, so what it wrote before
  346. the wait shows while it waits, even when timers are throttled.
  347. - A function made inside a component — an `XMLHttpRequest`'s `onload` or `onprogress`, a
  348. timer, a Promise's executor, a `then` — is compiled so that every return of it is
  349. announced with the site it was made at. What it writes (a member, a push into one, a
  350. field inside one, and what the methods it calls and the events it emits write) is
  351. repainted at the next animation frame. A function that writes no member
  352. repaints nothing.
  353. - A repaint the listener already made before that frame is not made twice.
  354. - Late paints also schedule a zero-delay timer: it and the animation frame race,
  355. and only the first drains the pending writes. A hidden tab therefore paints
  356. without waiting to become visible; throttled timers still allow the frame to
  357. paint a visible tab (#378).
  358. **A component's init runs once** (hybriel#401). Its server member initializers — the data received and put into the
  359. view — run when the component is built: a document load, an in-shell navigation to the page (also to the same page with
  360. another route parameter), a component the browser builds later (its `values` ask), and the first build of an offline-built
  361. destination. They never run again: not after a face that takes `session`, not on a replayed or plain resync, not when a kept
  362. page returns. After the build a value changes only by a handler's write, a face's own write (the numbered `sync` below) or
  363. a push (`emit client`). A sign-in face that other mounted components must show therefore writes the member it owns or
  364. pushes `emit client signedIn(...)` to the session's tabs, which the shell handles with `on client signedIn(...)`. The
  365. components do not read `session`; the server functions their initializers call do (the core part of #401 is pending).
  366. A REST face that moved the session sets `ack.sessionNews`, so the browser reconnects its socket to follow the cookie.
  367. Reconnect resyncs and navigation answers still carry the tab's `route` (`path`, `params`, `pattern`, `query`) as a
  368. document load does (#400); no page is constructed or rendered.
  369. Navigation answers keep the host's values for binding. A child's server value equal to a directly bound argument
  370. is copied from that argument when the browser constructs the child (#413); a differing value still travels in full.
  371. This copies the evaluated value without running its initializer again. Row and fill bindings keep their server values.
  372. A server face's own writes (its declared members) travel as a separate numbered push `{ t: 'sync', n, sync: { <file>: { member: value } } }`
  373. to the emitting tab only, sent before the face's outward `emit client` frames and before the ack (COMPONENTS §10).
  374. - A member that calls an imported class, directly or through a local
  375. method or static, is computed on the server only, once at the build, and never re-derived in the browser.
  376. - Such a member is already up to date when the handler continues, so a client handler that
  377. appends the face's returned row to a list derived from `session` shows it twice. Assign
  378. from what the sync brought, or leave the list to the sync.
  379. - A member derived from `session` that needs a server-only resource (a database) must reach
  380. it through an imported class or a static of one; a plain copy (`me = session.user.id`) is
  381. derived everywhere.
  382. ### Waiting marks: the progress bar and the waiting button (#434, #435)
  383. Two marks, set by the framework from the
  384. moment a crossing is open, and a default look that appears only after 300 ms (a CSS transition delay, no timer
  385. per button), so a fast action shows nothing:
  386. - `<html data-hl-busy>` stands while a navigation (the span that marks the slot `aria-busy`) or any emit
  387. answer of the page is open. The default stylesheet draws a thin indeterminate bar on `html::after` (fixed,
  388. top, 3 px, `currentColor`, no percentages). Restyle it in the app's Style / styles file with the rule
  389. `'html[data-hl-busy]::after' { background = 'rgb(200, 0, 0)' height = '5px' }`; switch it off with
  390. `'html::after' { display = 'none' }`. The framework rules are all inside `:where()`, so the app's rule wins
  391. whatever its order.
  392. - A DOM handler on a button (`on click`, or any event on `button`, `input[type=button|submit|reset]`,
  393. `[role=button]`) or a form's `on submit` (then the submit button) that runs `emit server …` marks that
  394. button `aria-busy="true"` and `data-hl-waiting` until the answer arrives, fails, or the emit is queued
  395. (a queued offline emit ends the mark when it is queued, not when it is replayed). The emits the handler
  396. makes before it ends belong to the button while no network wait has intervened. Default look: opacity .6
  397. and `cursor: progress`, after 300 ms. Nothing is disabled and nothing blocks a second click. Restyle with
  398. `'button[aria-busy="true"]' { opacity = '0.4' }`, undo with `{ opacity = '1' cursor = 'auto' }`, and
  399. opt a single button (or form) out with the attribute `data-hl-quiet`: it is never marked.
  400. Handler code before its first crossing still runs synchronously inside DOM event dispatch, including `preventDefault()` and immediate reads after a click.
  401. No page crossing, no server build and no data are added: both marks are attributes the browser sets and removes.
  402. ### Files in an emit
  403. A browser `File` (an input's `ev.target.files[0]`, a dropped file) or a list of them
  404. (`ev.target.files`) may be an argument of an `emit server …`. It never rides the socket:
  405. the first File-bearing emit loads `/__hl/uploads.js?v=<build>` once, then the upload provider sends each file to `/__hl/upload` as its own HTTP
  406. requests, with the page's session cookie, in parts of 1 MiB. The face gets the file in its
  407. place as `{ bytes, name, type, size }` (`bytes` a `Bytes`), or a list of those for a list:
  408. ```hybriel
  409. input { type = 'file' on change(ev) { emit send(ev) } }
  410. on send(ev) { saved = emit server saveFile(ev.target.files[0]) }
  411. on server saveFile(file) {
  412. writeFile('uploads/' + file.name, file.bytes)
  413. return file.size
  414. }
  415. ```
  416. - **Progress.** While a file is sent, every mounted component that declares
  417. `on client uploadProgress(p)` gets `p = { event, index, name, sent, size }`: the emit's
  418. event, the file's position among the emit's files, its name, the bytes sent so far and
  419. its size.
  420. - **A dropped connection.** A part that did not come back is asked for again: the client
  421. waits (250 ms, doubling up to 4 s), asks the server how much of the file it has, and goes
  422. on from there. After 8 drops in a row it gives up.
  423. - **A failed upload ends the emit.** A file the server refuses (bigger than `uploadMax`, an
  424. upload of another session) or a connection that stays down ends the emit with that error
  425. instead of sending it — except a queueable emit in an offline app, which is queued with its
  426. files when the connection is what failed (COMPONENTS §10): it gets the failed ack a failing face sends
  427. (`{ t: 'ack', i, ok: false, error }`), so a value-form emit answers null and the error is
  428. logged. The face does not run.
  429. - An upload belongs to the session that started it, and one emit takes it. An upload that
  430. nothing takes within an hour is dropped. The parts are held in the server's memory until
  431. the emit takes them.
  432. ## Offline and installable
  433. Browser `online`/`offline` events alone update `__hlOnline` and do not fire `on client reachability(r)`; socket/probe changes do, with `{ reach, was }` (for example `'down'`/`'up'` on socket loss), and online can prompt a reconnect (#379; case `9379`).
  434. The full model is [COMPONENTS.md §10](../../COMPONENTS.md). An app writes no JavaScript for any
  435. of it. Declaring `offline` (including `offline = []`) loads `/__hl/offline.js?v=<build>`
  436. before components are constructed and includes it in the worker precache. Apps without
  437. that declaration load the base client alone until an emit carries a File. Offline apps also precache the upload provider so queued Files can replay without a new module download.
  438. ```hybriel
  439. appTitle = "Hybriel Notes"
  440. appIcons = [ { src = "/static/icon-192.png" sizes = "192x192" } { src = "/static/icon-512.png" sizes = "512x512" } ]
  441. offline = [ NoteList, NoteEditor ]
  442. ```
  443. - `appIcons` (or `appManifest`, or `offline`) serves `/__hl/manifest.webmanifest` and links it,
  444. with an apple-touch-icon, from every page's head. `appManifest`'s entries are written over the
  445. generated manifest.
  446. - `offline` lists pages: route components, as classes or path strings. Anything else is refused
  447. at its line. The framework generates the service worker and registers it. The shell and the
  448. listed pages' documents are cached, and a real document load or start is network-first. When the network gives no answer for 1.5 s and a kept copy exists, the copy is served and the fetch refreshes it in the background. A document served from the cache is marked in its seed, and its first socket resyncs the page and shell (#143); a network-rendered document does not. What the server last
  449. said about a listed page is kept in IndexedDB and shown over an older cached document.
  450. State is written through at once on every application, but only the members whose value
  451. changed are written (#419): an unchanged member is neither serialized nor put, and its stored
  452. time stays the older one. A tab guards later writes with the newest time it wrote or confirmed
  453. per member (told to other tabs over a BroadcastChannel), so a late older answer cannot replace
  454. a newer value. Each member is its own IndexedDB record (`component|path|member`, D27), so a
  455. changed member is the only thing written; a combined record of an older install is read as before,
  456. copied member by member into per-member records on first use (a newer stored member wins) and then dropped.
  457. statement-form `emit server …` from a listed page that does not reach the server is queued and
  458. replayed in order when the socket reopens. Each queued emit carries a stable id, and the
  459. server runs it once: a replay whose ack was lost is answered again without running the handler
  460. (the last 200 ids per session are kept). A socket that goes silent without closing is noticed
  461. by the ping and reopened. A queued emit keeps its files: IndexedDB holds them with the entry,
  462. and they go up on the replay under the emit's id, once (COMPONENTS §10). A queueable emit on an
  463. open socket is written to the queue first and sent after, and leaves it on its ack, so an app
  464. killed while its connection stalls still has it; the replay sends it under the same id. A page that
  465. declares `__hlQueued = 0` /
  466. `__hlQueue = []` shows the queue. A page that declares `__hlOnline = true` has it follow the browser's
  467. connection (`navigator.onLine`, and the online/offline events), so a View can say "you are offline".
  468. `__hlReach = 'connecting'` follows whether the server answers (`'up'`, `'down'`), `on client reachability(r)` runs on a change,
  469. and `takeBack(q)` (an import from hl:web) takes a waiting emit back (a `__hlQueue` row's `q`); see COMPONENTS §10.
  470. - A kept page whose navigation request has not answered after 1.5 seconds is built locally
  471. in the existing document (#420), using the same cached modules and state as a known-down
  472. navigation. Its request stays in flight and its late answer refreshes that instance and
  473. its children once; it does not navigate again or reset client drafts. Navigating elsewhere
  474. discards the old answer. Non-kept pages continue waiting. This timeout does not declare
  475. reachability down; it uses the worker's shared network-first window.
  476. - When reachability is `down`, a link or `navigate()` to a component declared in `offline`
  477. completes locally in the existing document (#377), with new parameters and route/query state.
  478. It uses the exact address's kept server data and component-wide server values. Client members
  479. get fresh initial values as online; no draft is copied from the origin into the destination.
  480. Back restores the origin's draft where the online history cache retains that page (a standing
  481. shell); shell-less pages are constructed fresh as online. A route-dependent server-read
  482. member is null until reconnect when no value is kept for that address. Reconnect requests a full
  483. values resync and patches the current page without a document load or server page construction.
  484. [COMPONENTS §10](../../COMPONENTS.md#10--offline-and-an-installable-app-current-hlweb) details the state rules.
  485. Online navigation and non-kept destinations keep #346's waiting carrier: document, draft and
  486. timers stay; the slot carries `aria-busy="true"` and `data-navigating` until recovery. The page
  487. request waits separately from the durable app-emit queue. Cached documents still serve real
  488. document loads or starts, with the bounded wait and cached-start resync described above.
  489. - `offlineFallback = Start` (a route component, class or path string, answered by a route with no
  490. parameter; needs `offline`) names a DATA-FREE page: the worker keeps its document once, fetched without
  491. credentials, and shows it for any page it has nothing for while the network is down. Without it, a kept
  492. document with a shell supplies the layout and app title; the framework puts an "Unavailable offline"
  493. status notice in its page slot before first paint, without constructing the donor page. Links in this notice navigate in-shell (#423, R67): kept pages build locally; navigation to a non-kept destination waits for
  494. the server (#346). When no kept document has a shell, the bare 503 notice remains. A page (kept or the fallback) that declares `__hlDataFree = true` is kept
  495. the same way — its document is the anonymous one, and the browser keeps neither its state nor a queue for it.
  496. - `offlineFiles = ['/md-editor.js', '/vendor/lib.js']` (needs `offline`) lists the app's OWN file-route urls the
  497. worker precaches at install and serves cache-first offline (ticket #170). Exactly the urls listed: a
  498. directory route is never kept as a tree, list each file you need. Not set: no extra file is kept.
  499. - Kept state is per component for a member no route parameter feeds (the same list at every url of
  500. the page), per url for the rest. A param page that was never loaded as a document is answered offline
  501. with a kept document of the same component, booted with the url's parameters. The shell, its
  502. parent levels and the components composed into them are kept by the same rules (per member, with
  503. the server's time, laid over a cached document only when newer), under keys that are never a page's.
  504. So are the components composed into the page itself, at any depth (#343), under `@page|…` keys.
  505. - An app that registered its own `/sw.js` before moving to `offline`: hl:web does not register while a
  506. worker controls the page (COMPONENTS §10).
  507. - What is kept belongs to the last user who was logged in. An expired or fresh anonymous session
  508. changes nothing: that user's queue is held, and replays when the same user logs in again (the server
  509. refuses a replay made for another user). Another user logging in forgets the copy (state, queue and the
  510. worker's documents); an entry from before users were kept is dropped unsent. A
  511. face that logs the session out forgets the copy by itself (the ack says whose session it is now);
  512. an app with its own logout calls `forgetOffline()` from `hl:web`.
  513. - In any app, an emit in flight when its socket closes is sent again with its id over the POST
  514. fallback or the next socket, and answered there (ticket #107). A page being left
  515. (`beforeunload`, `pagehide`) reopens nothing and posts nothing.
  516. - **A failed answer after a give-up means "not run".** An emit that waits for a socket that stays closed
  517. ends, at the give-up (`window.__hlGiveUp`, 120 s), with the failed answer (`null` for a value-form emit).
  518. The POST carrying it is aborted then, and the frame carries `by`, the give-up horizon in the *server's* clock
  519. (the time the server last told the page, in the clock frame after a hello or in a pong, plus the duration the page measured since, plus
  520. the give-up; client and server clocks are never compared). A frame that reaches the server after `by` (a proxy
  521. held it) is refused and run by no face, so the app that was told "failed" is never contradicted. The horizon is
  522. early by at most one message latency, which can only refuse an emit the page was about to give up anyway.
  523. - `import { notify, notifyAt, notifyIn, cancelNotify } from 'hl:web'` shows a notification now, or schedules one.
  524. For `notifyAt` / `notifyIn`, `options.tag` replaces any pending notice with the same tag.
  525. `cancelNotify(tag)` cancels it and returns true if one was pending, otherwise false.
  526. Pending notices are tab-scoped and survive in-shell navigation; untagged notices cannot be cancelled.
  527. A closed app cannot be woken at a set time without a server push.
  528. Drafts that must survive reopening: keep them on the server ([recipe #383](../../COMPONENTS.md)), case `9383`; browser-only drafts are #367. To send after typing pauses, declare `coalesce = { saveDraft = 600 }` in the manifest or WebFramework arguments, and keep writing the member and emitting `saveDraft(id, draft)` on input. The browser holds the newest payload per face and first argument, then sends after 600 ms without another call. A form submit (before its handler’s emits), in-shell navigation, `pagehide` and becoming hidden flush held calls in order. Submit waits for the flushed calls’ answers before its handler runs; navigation and page-hide handling start them without waiting for their answers. Calls use the normal durable queue offline; value-form queue rules are unchanged. Every superseded value-form caller gets the answer of the final call for its key. Busy marks start at send, and unlisted faces keep sending every call. Case `9444`.
  529. **`$notifyPermission`** (#443). Declare `$notifyPermission = ''` to follow this browser's notification state: `'unsupported'`, `'default'`, `'granted'` or `'denied'`. It updates at boot, after navigation and permission requests through `notify*()` / `subscribePush()`, and on permission changes where the Permissions API supports them, throughout shell, layouts, page and composed children. It is never kept or sent; server rendering leaves the declared initial value. For example, `if ($notifyPermission == 'default') { button { type = 'button' 'Enable notifications' on click() { subscribePush() } } }` shows a settings button only before a choice, and `if ($notifyPermission == 'denied') { p { 'Notifications are blocked in browser settings.' } }` explains a refusal (import `subscribePush` from `hl:web`).
  530. ## Web Push
  531. A reminder for a closed app is a server push the service worker shows. This is the browser half
  532. (ticket #173); the server's VAPID signature and payload encryption are `hl:crypto`'s.
  533. - `pushKey = '<base64url VAPID public key>'` (a `WebFramework` argument or a manifest member) serves
  534. the service worker — also in an app with no `offline` (it then keeps nothing and answers every fetch
  535. from the network) — and tells the page the key.
  536. - The worker handles `push`: the payload is JSON text `{ "title", "body", "url", "tag", "icon" }`, shown
  537. with `registration.showNotification` (a payload that is not JSON becomes the body, titled with the
  538. host). On `notificationclick` it focuses an open window of the app, else opens `url` (default `/`).
  539. - `import { subscribePush } from 'hl:web'`: in a handler, asks for notification permission (on first
  540. use), registers the worker if the page has none, calls `pushManager.subscribe({ userVisibleOnly:
  541. true, applicationServerKey: pushKey })` and answers `{ endpoint, expirationTime, keys = { p256dh, auth } }`,
  542. or `null` (no push support, permission refused, no `pushKey`, subscribe failed — said in the console).
  543. The app hands it on with its own emit:
  544. ```
  545. import { subscribePush } from 'hl:web'
  546. View { button { "Turn on notifications" on click(e) { let s = subscribePush() emit server savePush(s) } } }
  547. on server savePush(s) { /* store s.endpoint, s.keys.p256dh, s.keys.auth for this user and device */ }
  548. ```
  549. ### Sending a push (the server half)
  550. - `pushKey`, `pushPrivateKey` and `pushSubject` together enable `import { sendPush } from 'hl:web'`, called in an `on server`
  551. handler or a route function (in a component's browser build the name binds to a refusal, like any server-only name).
  552. - `sendPush(subscription, payload, opts)`: `subscription` is what `subscribePush()` gave (`endpoint`, `keys.p256dh`,
  553. `keys.auth`), as the app stored it; `payload` a String or Bytes up to 3993 bytes (the worker shows JSON text
  554. `{ title, body, url, tag, icon }`); `opts` = `{ ttl` (seconds, default 86400), `urgency` (`'very-low'`, `'low'`, `'normal'`,
  555. `'high'`), `topic` (up to 32 URL-safe characters) `}`. It signs a VAPID JWT (ES256, `aud` the endpoint's origin, 12 h), encrypts
  556. the payload (RFC 8291 aes128gcm, one record) and POSTs it with hl:fetch.
  557. - It answers `{ ok, status, gone, error }`: `ok` is a 2xx (201 = accepted); `gone` is a 404/410, the subscription is dead and
  558. the app drops it; `status` 0 with `error` is a malformed subscription, or a push service that cannot be reached (the latter
  559. only where the caller has an `on Error(e)` handler — without one hl:fetch faults the call, as it does everywhere).
  560. - A call blocks its handler until the push service answers (15 s at most). A missing setting is a located error.
  561. ## What it serves
  562. | url | what |
  563. |---|---|
  564. | `/<file key>` (e.g. `/components/home.hl`) | a component's browser module |
  565. | `/__hl/modules/<sha256>.hl` | a module imported from above the project folder; its opaque key is `__hl/modules/<sha256>.hl` in seeds, component tables and transport frames |
  566. | `/__hl/hl-runtime.js` | the runtime every module imports |
  567. | `/__hl/web/client.js` | this package's browser half (other packages' halves are at `/__hl/<name>/client.js`) |
  568. | `/__hl/offline.js` | the optional browser state and durable queue, for an app declaring `offline` |
  569. | `/__hl/app.css` | the one stylesheet, built from the styles file and every component's `Style` |
  570. | `/__hl/emit` | the POST fallback for emits |
  571. | `/__hl/up` | an empty `204`: the probe a tab makes once a second while its socket waits to reconnect, so it is back within about a second of a restarted server (ticket #153; the backoff between socket attempts stops at 4 s) |
  572. | `/__hl/manifest.webmanifest` | the web app manifest, for an installable app |
  573. | `/__hl/sw.js`, `/__hl/web/worker.js` | the service worker's entry script and its compiled module, for an app with `offline` or `pushKey` |
  574. | `/__hl/upload` | a file of an emit, in parts (`POST` `{ name, type, size, q, n }` → `{ id, have }`, or `{ handled }` when the session handled emit `q` already; `POST ?id=&at=` one part → `{ have }`; `GET ?id=` → `{ have }`) |
  575. The page loads the modules and the stylesheet as `<url>?v=<hash>`, where the hash covers everything the build serves. A url with the current hash is sent with `Cache-Control: public, max-age=31536000, immutable`, and any other url with `no-cache`. A deploy therefore changes every url, and a tab that navigates into a newer build loads that page as a full document.
  576. An app's own `file` and `directory` routes keep the same url across deploys, so they answer with an `ETag` of the content and `Cache-Control: no-cache` (a route's own `Cache-Control` header replaces that). A request whose `If-None-Match` names the current tag gets a `304` with no body.
  577. ## Cloned row templates: measured, not adopted (ticket #68)
  578. Svelte clones one hoisted `<template>` per row or branch shape; hl:web builds a browser-created row element by element. Measured with `tests/browser/bench-web-rows.mjs` (headless Chrome, a clean page before every run, best of 5, ms, master c183052c):
  579. | case | ms |
  580. |---|---|
  581. | replace 1000 rows (li, 3 elements, an `if` inside) | 338 |
  582. | append 10 x 100 rows (same row) | 780 |
  583. | deep row, 20 elements x 300 rows | 7.5 |
  584. | shallow row, 2 elements x 1000 rows | 14 |
  585. | toggle an `if` branch 1000 times | 45 |
  586. DOM creation is not where the time goes: the CPU profile (`HL_BENCH_PROF=<case>`) puts `createElement`, `setAttribute` and `appendChild` together under 3% of the cheap cases and the dearer cases are bound by something else. A 20-element row costs 25 us per row in total, a 2-element row 14 us; cloning could not make either 1.2x faster, and the machinery that wires sites, events and marks onto a clone is the same code the walk runs today (a claim walk over the clone), so nothing is saved there either. No prototype was built: the bound from the profile is under 1.03x.
  587. What the profile does show: the 3-element row with an `if` costs 340 us, and 115 ms of its 340 is `rehome` -> `sitesOnto`, which scans the mount's WHOLE `m.sites` for every row built and copies each site it reads (value semantics), so a build of n rows is O(n x sites). The append case is worse (780 ms) for the same reason plus `updateRow` on the rows that stay. That is the cost to attack, not element creation.
  588. ### The fix that followed (ticket #68, second step)
  589. `sitesOnto` now reads `m.sites` from the end, stops at the first site older than the walk's, and writes `el` in place instead of copying each site. `rebindRow` decides once per row body whether it composes a child (nothing to take again if not) instead of copying the seed's tree for every row that stays, and `rowPaint` reads its paint entry in place (`paintEntry`) instead of copying the compiled table. Same bench, old (c183052c) vs new, best of 5, ms:
  590. | case | old | new | ratio |
  591. |---|---|---|---|
  592. | replace 1000 rows | 342.0 | 20.0 | 17.1x |
  593. | append 10 x 100 rows | 782.3 | 92.6 | 8.5x |
  594. | deep row 20 el x 300 | 8.4 | 7.6 | 1.1x |
  595. | shallow row 2 el x 1000 | 18.2 | 13.1 | 1.4x |
  596. | toggle if-branch x 1000 | 48.8 | 40.2 | 1.2x (noise: 0.98x to 1.2x across runs) |
  597. Typing in a routger chat (a copy of the app, 30 keystrokes, main-thread time) is unchanged at about 1.5 ms per key: a keystroke builds no rows. Gates: `HL_WEB_STRICT=1` framework browser test 398 ok, `tests/core-ast/web-tickets.mjs` 205 ok.
  598. ## Session rotation (W120)
  599. `session.rotate()` in a face that logs a session in (the handler takes `session`) mints a new session id when it returns,
  600. moves user/data/handled to it and deletes the old id (a planted cookie is anonymous). The REST carrier answers with
  601. `Set-Cookie`; over the socket the server pushes `{ t: 'rotate', token }` and the client POSTs `/__hl/rotate` (Origin-checked,
  602. one-shot token + the current cookie), whose answer sets the cookie. All live tabs of the session follow. See COMPONENTS.md.
  603. ## Security headers and cross-site requests
  604. Every answer carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`,
  605. `X-Frame-Options: SAMEORIGIN` and `Content-Security-Policy: frame-ancestors 'self'` — pages, the 404, `/__hl/*`
  606. and the app's own routes. A header a route sets itself is left alone. The app adds or replaces any of them
  607. (and a script CSP, which is not a default because it would break apps) with `pageHeaders`; `null` removes one:
  608. ```hybriel
  609. pageHeaders = { 'Content-Security-Policy' = "default-src 'self'" 'X-Frame-Options' = null }
  610. ```
  611. `POST /__hl/emit`, `/__hl/upload` and the WebSocket upgrade refuse a cross-site caller: `Sec-Fetch-Site: cross-site`,
  612. or an `Origin` that is not the request's `Host` (or `X-Forwarded-Host`) nor listed in `trustedOrigins`. The first two
  613. answer 403; a socket is closed straight after its handshake. A request with no `Origin` (curl, another server) passes.
  614. **Behind a proxy on a non-443 port** (W123): nginx's `proxy_set_header Host $host;` drops the port while the browser's
  615. `Origin` keeps it (`https://h:8443` vs `Host: h`). A `Host` (or `X-Forwarded-Host`) WITHOUT a port is compared with the
  616. Origin by hostname only (cookies are not port-scoped); with a port it must match exactly, and an `X-Forwarded-Port`
  617. completes a portless one. Prefer `proxy_set_header Host $http_host;` (keeps the port), or send `X-Forwarded-Host` /
  618. `X-Forwarded-Port`; otherwise list the origin in `trustedOrigins`. A refused socket or emit logs one console warning
  619. naming Origin vs Host, and the client backs off (the reconnect delay resets only when the server answers a frame).

Branches

Latest commits

  • 536d7c58Merge branch 'playing-row' into mainJukebox
  • 05c3578c|||PR Keep each playing row bound to the shell song on day76mre
  • eaa7e6d6Vendor Hybriel day76 for live parent member readsmre
  • 0923398bMerge branch 'records-1124d' into mainJukebox
  • 78f0cc86|||PR records 2026-11-24: inbox-thread rule, "Not playing" confirmed and closedmre
  • c1b153c4Merge branch 'records-1124c' into mainJukebox
  • d7b5e780|||PR Records 2026-11-24 (2): live day72, PR #19 merge, #10 newsmre
  • 43b564dbMerge branch 'records-1124b' into mainJukebox
  • fa86b08c|||PR Records 2026-11-24: LOG, STATUS, missions 020-023mre
  • 0a2ae3daMerge remote-tracking branch 'origin/records-1123' into records-1124mre
  • 9a48cfcaMerge branch 'vendor-theme' into mainJukebox
  • 170d3735Merge branch 'code-order-2' into mainJukebox
  • 3f1918a7|||PR Re-sync layouts theme 4099e64 with Segoe UI firstmre
  • 2e7f6a43Vendor virtual-list 489afcf from components.hybrielmre
  • 0ba85799Merge branch 'reset-classes' into mainJukebox
  • 502eeed5jukebox#20: vendor virtual-list initial resetKey baseline fixmre
  • 6d5ce287|||PR jukebox#9 Centralize songs table reads and writes in db.hlmre
  • dcca21abjukebox#8 Move copies and queue logic into their topicsmre
  • 3b76651cjukebox#20: update virtual-list README pin and resetKey optionsmre
  • bc09e1e8|||PR jukebox#20: reset virtual lists through resetKey (partial validation)mre