gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2ed094412ed09441Use layouts theme 17e0f03 for W61 compatibilitymre2ed09441/plugins/web/WebFramework.hl

268.4 KB

  1. // The framework's server half — the SERVER REALM's entrypoint, and the EDGE
  2. // MODULE for the carriers the manifest declares.
  3. // Its jobs: answer a URL with the HTML of a constructed component (SSR), ship
  4. // the browser the client, the View tree and the state to continue from, carry
  5. // the boundary in both directions (a websocket on the same port, a POST for a
  6. // peer that has none), and run the server faces an inbound emit names.
  7. import { NativeWebSocketServer, Response, randomToken } from 'hl:http1'
  8. import HlwView from './view.hl'
  9. import HlwViewServer from './viewserver.hl'
  10. import HlwRouter from './router.hl'
  11. import HlwSessions from './sessions.hl'
  12. import HlwSession from './session.hl'
  13. // the Style walk — named Css here because `Style` is a well-known MEMBER name
  14. import HlwCss from './css.hl'
  15. import HlwCompile from './compile.hl'
  16. import { readFile, exists, watch } from 'hl:fs'
  17. import { file, env, setEnv, args } from 'hl:proc'
  18. import { now } from 'hl:time'
  19. import { sha256, base64urlDecode, base64urlEncode, p256PublicKey } from 'hl:crypto'
  20. // the statics of push.hl that server.hl (the app's import of sendPush) and the app use are named here: a package
  21. // file's statics are live only for the names the framework's own import selects
  22. import { configure as configurePush, sendPush as pushSender } from './push.hl'
  23. import { newline, tab } from './view.hl'
  24. Hybrid routes = [] // bound by `new WebFrameworkServer(routes = …)`
  25. // THE PROJECT'S STYLES FILE, declared by the app as a property of the framework:
  26. // `new WebFrameworkServer(…, styles = './styles.hl')`. A file of statics and one
  27. // `Style { }` root member (COMPONENTS §4) — the design tokens and the global
  28. // rules, under every component's own Style in the one stylesheet. null: none.
  29. styles = null // the app's styles file: the class it imported, or a path
  30. // WHO AN OUTWARD EVENT IS FOR (creator, 2026-09-12): per event, a function the app
  31. // declares — `audience = { postCreated = (p, session) => … }` — called for every
  32. // connection that has a listener for the event mounted, with the event's
  33. // arguments and that connection's session; a true answer sends the frame. An
  34. // event with no entry reaches the emitting connection only. Only the app knows
  35. // who is entitled; the face stays pure; the framework applies the answer.
  36. Hybrid audience = {}
  37. // THE SESSION STORE (the archive's manifest members, mission 252/255): nothing said →
  38. // `<project>/.sessions`; a path → that path; `false` → memory only. The three clocks
  39. // are seconds; null takes the layer's defaults (14 days valid, 15 min resident, sweep
  40. // every 5 min).
  41. // THE DEV WATCHER (the archive's `watch`): every save under the project arrives as an
  42. // event; a save that changes the analysis re-reads the graph, drops every cache and tells
  43. // every open tab to reload. Off by default — a deploy never re-analyses itself.
  44. Boolean minify = false // production: one-line HTML, compact JavaScript modules
  45. Boolean watchMode = true
  46. lastChange = 0 // epoch ms of the last save acted on (the debounce)
  47. String | Boolean sessionDir = null
  48. Number sessionMaxAge = null
  49. Number sessionIdle = null
  50. Number sweepInterval = null
  51. // THE SESSION COOKIE'S NAME (ticket #10). Cookies ignore the port, so two apps on one
  52. // host that both answered `hlsid` overwrote each other's sessions; an app names its own.
  53. // null: `hlsid`.
  54. String sessionCookie = null
  55. // THE COOKIE'S `Secure` FLAG (ticket #27): true when the app is reached over https —
  56. // behind a TLS proxy the server itself speaks plain http and cannot tell, so the app
  57. // says so. The browser then never sends the session over plain http. null (W124): `Secure` when THE REQUEST
  58. // came over https (X-Forwarded-Proto: https from the proxy); true: always; false: never.
  59. Boolean sessionSecure = null
  60. // THE MOST ANONYMOUS SESSIONS KEPT (W124): a visitor gets a session (and a file) only when something is stored
  61. // in it; the ones nobody logged in to are capped, the oldest evicted first.
  62. Number sessionAnonMax = 10000
  63. Number sessionAnonKeep = 86400
  64. // THE COOKIE'S `Domain` (ticket #44): 'example.org' shares one session with every
  65. // <sub>.example.org, which a host-only cookie cannot. null: host-only, no attribute.
  66. String sessionDomain = null
  67. \* THE PORT: the app's own `--port=N` argument (hybriel hands every argument
  68. after the entry to the program, creator ruling 2026-09-27), else the
  69. constructor's, else HL_PORT (hybriel resolves PORT and `.env` into it),
  70. else 8080. *\
  71. Number port = null
  72. // THE OFFLINE ALLOW-LIST (COMPONENTS §10, D38): the pages this app promises with the
  73. // network down, named as the route table names them — the imported class or a path
  74. // string. null: no service worker, no cache, no IndexedDB, nothing on the device.
  75. offline = null
  76. // THE OFFLINE FALLBACK PAGE (ticket #120): a data-free page — a route component with no
  77. // parameters, the class or its path string — the service worker keeps once, fetched with
  78. // NO credentials, and shows for any page it has nothing for while the network is down.
  79. // null: the "Unavailable offline" page, as before. Needs `offline`.
  80. offlineFallback = null
  81. // THE APP'S OWN FILES KEPT OFFLINE (ticket #170): a list of urls — each a path the app's
  82. // `file` routes answer (`/md-editor.js`, or one file under a directory route) — the worker
  83. // precaches at install and serves cache-first. Only the urls listed: a directory route is
  84. // never kept as a tree. Needs `offline`. null: none beyond the files a kept page's View
  85. // loads through a literal `<script src>` or `<link href>`.
  86. offlineFiles = null
  87. // WEB PUSH (ticket #173): the app's VAPID PUBLIC key, base64url (the 65-byte uncompressed P-256
  88. // point). Setting it serves the service worker — which then shows a pushed notification and
  89. // focuses the app on a click — and lets a component call `subscribePush()` (hl:web). null: no push.
  90. pushKey = null
  91. // …and the SERVER'S half: the VAPID PRIVATE key (base64url, the 32-byte P-256 scalar of `pushKey`) and the
  92. // contact `pushSubject` ('mailto:…' or 'https://…', the push service may write to it). Both set: the app can
  93. // `import { sendPush } from 'hl:web/push'` and send. A key that is not the private half of `pushKey` is refused at boot.
  94. pushPrivateKey = null
  95. pushSubject = null
  96. // THE DEAD-SOCKET CLOCK (COMPONENTS §10), in seconds. The browser pings every `pingEvery`,
  97. // and a socket whose pong has not come back within `pongWithin` is taken for dead: it is
  98. // closed, and the reconnect and the queue's replay start. A network that drops without a
  99. // close frame is noticed within pingEvery + pongWithin (35 s by default). null: 25 and 10.
  100. Number pingEvery = null
  101. Number pongWithin = null
  102. // AN UPLOAD THAT GOES SILENT — no progress, no answer — is read as dropped after this
  103. // many seconds (COMPONENTS §10, an emit's file). null: 15.
  104. Number uploadStall = null
  105. // THE LARGEST FILE AN EMIT MAY CARRY (ticket #94), in bytes: a bigger one is refused
  106. // at its first request, and the emit ends with that error. 1 GiB.
  107. Number uploadMax = 67108864
  108. // THE UPLOAD BUDGETS (W115): the bytes announced by the unfinished uploads of ONE session,
  109. // and of ALL sessions together (a part is held in memory until its emit claims it). 256 MiB, 1 GiB.
  110. Number uploadSessionMax = 268435456
  111. Number uploadHeldMax = 1073741824
  112. // THE LARGEST BODY `POST /__hl/emit` takes, in bytes (W115): a bigger one is answered 413. 16 MiB.
  113. // (hl:http1 reads a request's body whole before hl:web sees it, so this refuses the answer, not the read.)
  114. Number emitMax = 16777216
  115. // ONE PART OF AN UPLOAD, at most (the client half sends 1 MiB): 8 MiB.
  116. Number uploadPartMax = 8388608
  117. // THE HEADERS EVERY ANSWER CARRIES (W115, COMPONENTS §7): the safe defaults are nosniff,
  118. // Referrer-Policy strict-origin-when-cross-origin, X-Frame-Options SAMEORIGIN and a CSP of
  119. // `frame-ancestors 'self'`. `pageHeaders = { 'Content-Security-Policy' = "…" }` adds to or replaces
  120. // them on every answer (a header set to null is removed); a route's own header wins over both.
  121. Hybrid pageHeaders = {}
  122. // ORIGINS BESIDES THE REQUEST'S OWN HOST that may call `/__hl/emit`, `/__hl/upload` and open the
  123. // socket (W115): `['https://app.example.org']`. A request whose Origin is another is refused 403.
  124. trustedOrigins = []
  125. // THE PUSH LOG (ticket #143). A push is addressed to the TAB, not to its socket: each tab
  126. // keeps the last `pushKept` pushes it was sent (and no more than `pushKeptBytes` of them),
  127. // numbered, and a tab whose socket comes back gets what it missed again, in order. A tab
  128. // whose socket left is kept `tabKept` seconds, and pushed to and logged meanwhile; a gap
  129. // longer than the log (or a server restart) resyncs the tab's server-derived state instead.
  130. // THE BYTES BOUND IS THE ONE THAT GOVERNS (ticket #160): a push is small (a streamed delta is some
  131. // 150 bytes), and a count of 500 ran out within a 15-second gap on a server streaming several
  132. // chats to the tab while 1 MiB was far off. The count is the guard for the degenerate case only.
  133. Number pushKept = 10000
  134. Number pushKeptBytes = 1048576
  135. Number tabKept = 600
  136. // THE PUSHES SINCE A RENDER (W181): a page's tab does not exist until its first hello, so every fan-out push is also
  137. // kept here, numbered, for `recentKept` seconds (and within `pushKeptBytes`). The seed names the number the render stood at
  138. // (`pushed`), and the first hello is replayed what was sent since, exactly like a reconnect. Older than that, it is not.
  139. Number recentKept = 30
  140. recent = []
  141. recentBytes = 0
  142. pushCount = 0
  143. String host = null // the interface to bind; null → HL_HOST/HOST, the manifest's `host`, 0.0.0.0
  144. // THE ONE RUNTIME URL, and the reason it is a member and not a literal in two
  145. // places: a module's `import … from "./hl-runtime.js"` resolves against the
  146. // MODULE's own url, so a server answering modules at two directory depths hands
  147. // the browser two runtime urls — two ES-module instances, two `globalEvents`
  148. // buses, two `__hlRealm` variables, and a crossing emit announced on a bus the
  149. // edge module never taps. Every module this server compiles is handed this one
  150. // specifier (hlJs's third argument).
  151. // THE DIRECTORY THE FRAMEWORK ANSWERS FROM, and the reason it is its own member:
  152. // a package's browser half is served BESIDE THE RUNTIME, and the compiler derives
  153. // that url from the runtime's own (`js_module.zig browserHalfUrl`:
  154. // `<dirname(runtime)>/<pkg>/client.js`). Two sides deriving one url from one
  155. // directory is what keeps the module's `import` and this server's route table
  156. // from drifting apart.
  157. static halfDir = '/__hl'
  158. static runtimeUrl = halfDir + '/hl-runtime.js'
  159. clientUrl = halfUrl('web')
  160. styleUrl = halfDir + '/app.css'
  161. // THE BUILD'S VERSION IS IN EVERY URL THE BROWSER CACHES (after ticket #82): the
  162. // runtime, the package halves, the component modules and the stylesheet were served
  163. // at fixed urls, and a browser or Cloudflare kept the old client against a new
  164. // deploy's pages. Each is now asked for as `<url>?v=<hash>`, the hash of everything
  165. // this build serves, and answered with a year's `immutable` caching — a new build is
  166. // a new url. The modules are COMPILED against this mark and it is replaced with the
  167. // hash when they are served: the hash is of the compiled texts, so it cannot be in
  168. // them while they are compiled, and a binary's baked modules carry the mark too (the
  169. // one form both paths share). The route patterns stay the bare paths.
  170. static buildMark = '?v=__hlbuild__'
  171. static runtimeSpec = runtimeUrl + buildMark
  172. // the web app manifest and the service worker's entry script (COMPONENTS §10)
  173. static manifestUrl = halfDir + '/manifest.webmanifest'
  174. static workerUrl = halfDir + '/sw.js'
  175. // TEST-ONLY CONSTRUCTION COUNTER (mission 343, W133). Only with HL_WEB_COUNT=1: `construct` counts every server
  176. // construction by component file, and GET /__hl/constructs answers the counts. Without the flag nothing is
  177. // counted and the route does not exist.
  178. countConstructs = env('HL_WEB_COUNT') == '1'
  179. constructTotal = { n = 0 }
  180. constructByFile = {}
  181. // W159: the same switch also counts page builds (`mounts`), level renders (`renderOf`), documents and resyncs, as `calls`
  182. countCalls = {}
  183. tally(name) {
  184. if (countConstructs) { countCalls[name] = (countCalls[name] == null ? 0 : countCalls[name]) + 1 }
  185. return null
  186. }
  187. // THE FRAMEWORK'S OWN URLS ARE ROUTES (creator: "just use routes"), appended to
  188. // the app's table with `routes[] = …` — the append that takes on a caller's
  189. // pinned argument during construction, where `routes = routes + […]` is dropped.
  190. // Three of them here — the runtime, the REST carrier and the app's one
  191. // stylesheet — and then one per PACKAGE BROWSER HALF the app's graph holds,
  192. // appended below where the graph is known. There is no catch-all that compiles
  193. // any graph file a url names.
  194. routes[] = { pattern = runtimeUrl framework = true function = (route, req) => {
  195. return new Response(runtime, { headers = cached(req, 'text/javascript; charset=utf-8') })
  196. } }
  197. // THE REST CARRIER, the same emit/ack pair for a peer that cannot hold a socket
  198. // (SPEC: `POST /__hl/emit`).
  199. // ITS SESSION IS THE COOKIE'S (creator, 2026-09-14): this is an HTTP request like
  200. // the page request, so it resolves the SAME session the page route would for that
  201. // cookie — a `session.user` a face writes here is what the next document reads.
  202. // Before this the face was handed null and a login over the fallback was lost.
  203. // AN OUTWARD EMIT RAISED UNDER IT RIDES BACK IN THE ANSWER: there is no
  204. // connection to push to, so the frames a face raised for the CALLER are
  205. // collected while it runs and shipped in the ack as `emits`, which the client
  206. // half delivers before it resolves the emit. The audience fan-out to the other
  207. // connections of that user is the same walk it always was.
  208. routes[] = { pattern = '/__hl/emit' framework = true function = (route, req) => {
  209. if (req.method != 'POST') { return notFound(req.path) }
  210. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  211. if (req.body != null && req.body.length > emitMax) { return refused(413, 'the emit is longer than ' + emitMax + ' bytes (`emitMax`)') }
  212. // NO COOKIE, NO SESSION (W124): a face that stores something in the session it was handed makes one,
  213. // `inbound` leaves it in `postAdopted`, and the answer sets the cookie
  214. let s = sessions.resolve(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  215. let idBefore = s != null ? s.id : null
  216. // the session travels in a MEMBER, not an argument: a call argument is a copy,
  217. // an instance inside it included, and a copied session loses the face's write
  218. postSession = s
  219. postHost = hostOf(req.headers['host'])
  220. postHeaders = requestHeaders(req.headers)
  221. postReq = requestInfo(req.headers, req.remoteAddress, req.secure)
  222. postAdopted = null
  223. let res = new Response(inbound(null, JSON.parse(req.body)), { headers = { 'Content-Type' = 'application/json; charset=utf-8' } })
  224. // the session a face made (W124), or the one a face's `session.rotate()` moved to a new id (W120): this answer carries the cookie
  225. if (postAdopted != null) { res.headers['Set-Cookie'] = sessions.cookieHeader(postAdopted.id, isHttps(req.headers, req.secure)) } else if (s != null && s.id != idBefore) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id, isHttps(req.headers, req.secure)) }
  226. // W137: several cookies of the session's name: the answer re-issues the chosen one and expires the host-only stray
  227. let fx = sessions.repair(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], s, isHttps(req.headers, req.secure))
  228. for (k of fx.keys()) { if (res.headers[k] == null) { res.headers[k] = fx[k] } }
  229. postAdopted = null
  230. postReq = null
  231. return res
  232. } }
  233. // THE SOCKET CARRIER'S HALF OF `session.rotate()` (W120): a frame cannot set a cookie, so the server pushed the
  234. // tab `{ t: 'rotate', token }` and the client half POSTs it here. Origin-checked, authenticated twice — by the
  235. // token only that socket was given (one-shot) and by the cookie it still holds (the OLD id the rotation
  236. // recorded) — and the answer carries the Set-Cookie of the new id. A planted id has no token: nothing to claim.
  237. routes[] = { pattern = '/__hl/rotate' framework = true function = (route, req) => {
  238. if (req.method != 'POST') { return notFound(req.path) }
  239. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  240. let sent = req.body != null && req.body != '' ? JSON.parse(req.body) : null
  241. let token = sent != null ? sent.token : null
  242. let rec = token != null ? pendingRotate['r' + token] : null
  243. let cks = sessions.cookieValues(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  244. if (rec == null || !cks.includes(rec.old) || now() - rec.at > 300000) { return refused(403, 'no rotation to claim') }
  245. pendingRotate['r' + token] = null
  246. let res = new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' } })
  247. res.headers['Set-Cookie'] = sessions.cookieHeader(rec.id, isHttps(req.headers, req.secure))
  248. return res
  249. } }
  250. // A FILE IN AN EMIT TRAVELS OVER HTTP (ticket #94, creator 2026-09-25): the client half
  251. // sends each file of an `emit server …` here, in parts, before the emit itself; the emit's
  252. // frame then names the upload, and `inbound` hands the face the file in its place.
  253. // POST /__hl/upload { name, type, size, q, n } → { id, have } (an upload; see uploadRequest)
  254. // POST /__hl/upload?id=&at= one part, raw → { have } (appended when `at` is what arrived so far)
  255. // GET /__hl/upload?id= → { have } (after a dropped connection)
  256. // An upload belongs to the session of the cookie that started it, and only an emit
  257. // of that session can claim it. A part cut short by a dropped connection keeps what
  258. // arrived; the client asks for `have` and goes on from there.
  259. routes[] = { pattern = '/__hl/upload' framework = true function = (route, req) => {
  260. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  261. // W124: sessions are lazy (a page mints none), so the START of an upload is what makes one for a
  262. // visitor with no cookie; the answer sets it. A part or a question about `id` needs the session
  263. // that started it. The caps (uploadMax, uploadSessionMax, uploadHeldMax) still hold the memory.
  264. let s = sessions.resolve(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'])
  265. if (s == null && req.query != null && req.query.id != null) { return uploadAnswer(404, { error = 'no upload ' + req.query.id + ' in this session' }) }
  266. let made = s == null
  267. if (made) {
  268. if (req.method != 'POST') { return notFound(req.path) }
  269. s = sessions.fresh()
  270. }
  271. postAdopted = null
  272. let out = uploadRequest(&s, req)
  273. // a visitor whose start was refused (too big, bad body) keeps no session: `uploadRequest` adopts it
  274. // only when the upload is accepted
  275. if (postAdopted != null) { out.headers['Set-Cookie'] = sessions.cookieHeader(postAdopted.id, isHttps(req.headers, req.secure)) }
  276. // W137: several cookies of the session's name: re-issue the chosen session's id, expire the host-only stray
  277. let fx = made ? sessions.strays(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], isHttps(req.headers, req.secure)) : sessions.repair(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], s, isHttps(req.headers, req.secure))
  278. for (k of fx.keys()) { if (out.headers[k] == null) { out.headers[k] = fx[k] } }
  279. postAdopted = null
  280. return out
  281. } }
  282. // A SESSION MADE OVER THE SOCKET GETS ITS COOKIE HERE (W124): a socket cannot set one, so the ack of the
  283. // face that made the session carries a one-time token and the page POSTs it here; the answer sets the cookie.
  284. routes[] = { pattern = '/__hl/adopt' framework = true function = (route, req) => {
  285. if (req.method != 'POST') { return notFound(req.path) }
  286. if (crossSite(req.headers)) { return refused(403, 'cross-site request refused') }
  287. let t = req.query != null ? req.query.t : null
  288. let a = t != null ? adoptTokens[t] : null
  289. if (a == null || now() - a.at > 60000) { return refused(404, 'no such token') }
  290. adoptTokens[t] = null
  291. let res = new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' 'Set-Cookie' = sessions.cookieHeader(a.sid, isHttps(req.headers, req.secure)) } })
  292. // W137: the new cookie must be the only one of its name: a host-only stray is expired
  293. let fx = sessions.strays(req.headers['cookie'] != null ? req.headers['cookie'] : req.headers['Cookie'], isHttps(req.headers, req.secure))
  294. for (k of fx.keys()) { res.headers[k] = fx[k] }
  295. return res
  296. } }
  297. if (countConstructs) {
  298. routes[] = { pattern = '/__hl/constructs' framework = true function = (route, req) => {
  299. return new Response(JSON.stringify({ total = constructTotal.n; byFile = constructByFile; calls = countCalls; }), { headers = { 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' } })
  300. } }
  301. }
  302. // THE SERVER IS UP (ticket #153): an empty answer the client half asks for while its socket
  303. // waits to reconnect, so a tab is back within about a second of a restarted server listening
  304. routes[] = { pattern = '/__hl/up' framework = true function = (route, req) => {
  305. return new Response('', { status = 204 headers = { 'Cache-Control' = 'no-store' } })
  306. } }
  307. // THE APP'S ONE STYLESHEET — the `styles` file's rules and every mounted
  308. // component's `Style { }`, walked in style.hl and cached after the first ask.
  309. routes[] = { pattern = styleUrl framework = true function = (route, req) => {
  310. return new Response(stylesheet(), { headers = cached(req, 'text/css; charset=utf-8') })
  311. } }
  312. // THE COMPONENT MODULES ARE ROUTES TOO — the framework's, not the app's: one per
  313. // file a page route mounts and per wrapper above it (the graph's `parent`
  314. // chain), served at the file's own `.hl` url as the browser's projection. A
  315. // browser executes a module by its MIME type, so `text/javascript` at
  316. // `/components/home.hl` is a module, and the url is the path the author wrote.
  317. // Nothing else is served as a module: a file no page route reaches has no url.
  318. // THE LANGUAGE GRAPH, AND THE REALMS ARE THIS PACKAGE'S (creator, 2026-09-12: "the project.hl
  319. // defines no realms so the framework just fills them itself"). This file is the server
  320. // realm's entrypoint, client.hl beside it the browser's; the app reaches both by
  321. // importing hl:web, and the graph follows that reference into the package.
  322. graph = hlProject(
  323. realms = {
  324. server = { entrypoint = './WebFramework.hl' }
  325. client = { entrypoint = './client.hl' }
  326. }
  327. transports = [
  328. ['websocket' 'client' 'server']
  329. ['websocket' 'server' 'client']
  330. ['rest' 'client' 'server']
  331. ]
  332. )
  333. gen = graph.analysisGen // the syntax reflection's handle: the routes below read Views
  334. // TWO WEB FRAMEWORKS IN ONE APP IS NOT AN APP (creator, 15 Sep: project.hl switched
  335. // to the other framework the repo had then while styles.hl still said 'hl:web/css').
  336. // Both packages load, both `on server page` faces answer the same navigation, and
  337. // the second answers on a blank instance — a NotCallable deep inside the other framework's dispatch, which
  338. // says nothing about the two import rows that caused it. So it is refused HERE,
  339. // before anything is served, naming both rows.
  340. oneFrameworkOnly()
  341. // A VALUE-FORM EMIT HAS ONE ANSWERER (SPEC "An emit ANSWERS", ticket #20): checked here,
  342. // before anything is served, because the wire does not say which form an emit was
  343. oneAnswererEach()
  344. // THE APP'S SETTINGS come from the file that constructed this one when they were not
  345. // passed (the archive's `configure()`): `styles`, `audience`, `sessionDir`, the clocks,
  346. // `watchMode`, `minify`, `port`
  347. cfg = hlConstructor()
  348. if (cfg != null) {
  349. if (styles == null && cfg.styles != null) { styles = cfg.styles }
  350. if (cfg.audience != null && audience.keys().length == 0) { audience = cfg.audience }
  351. if (sessionDir == null && cfg.sessionDir != null) { sessionDir = cfg.sessionDir }
  352. if (sessionMaxAge == null && cfg.sessionMaxAge != null) { sessionMaxAge = cfg.sessionMaxAge }
  353. if (sessionIdle == null && cfg.sessionIdle != null) { sessionIdle = cfg.sessionIdle }
  354. if (sweepInterval == null && cfg.sweepInterval != null) { sweepInterval = cfg.sweepInterval }
  355. if (sessionCookie == null && cfg.sessionCookie != null) { sessionCookie = cfg.sessionCookie }
  356. if (sessionSecure == null && cfg.sessionSecure != null) { sessionSecure = cfg.sessionSecure }
  357. if (cfg.sessionAnonMax != null) { sessionAnonMax = cfg.sessionAnonMax }
  358. if (cfg.sessionAnonKeep != null) { sessionAnonKeep = cfg.sessionAnonKeep }
  359. if (sessionDomain == null && cfg.sessionDomain != null) { sessionDomain = cfg.sessionDomain }
  360. if (cfg.watchMode != null) { watchMode = cfg.watchMode }
  361. if (cfg.minify != null) { minify = cfg.minify }
  362. if (cfg.port != null) { port = cfg.port }
  363. if (offline == null && cfg.offline != null) { offline = cfg.offline }
  364. if (offlineFallback == null && cfg.offlineFallback != null) { offlineFallback = cfg.offlineFallback }
  365. if (offlineFiles == null && cfg.offlineFiles != null) { offlineFiles = cfg.offlineFiles }
  366. if (pushKey == null && cfg.pushKey != null) { pushKey = cfg.pushKey }
  367. if (pushPrivateKey == null && cfg.pushPrivateKey != null) { pushPrivateKey = cfg.pushPrivateKey }
  368. if (pushSubject == null && cfg.pushSubject != null) { pushSubject = cfg.pushSubject }
  369. if (pingEvery == null && cfg.pingEvery != null) { pingEvery = cfg.pingEvery }
  370. if (pongWithin == null && cfg.pongWithin != null) { pongWithin = cfg.pongWithin }
  371. if (uploadStall == null && cfg.uploadStall != null) { uploadStall = cfg.uploadStall }
  372. if (cfg.uploadMax != null) { uploadMax = cfg.uploadMax }
  373. if (cfg.uploadSessionMax != null) { uploadSessionMax = cfg.uploadSessionMax }
  374. if (cfg.uploadHeldMax != null) { uploadHeldMax = cfg.uploadHeldMax }
  375. if (cfg.emitMax != null) { emitMax = cfg.emitMax }
  376. if (cfg.pageHeaders != null && pageHeaders.keys().length == 0) { pageHeaders = cfg.pageHeaders }
  377. if (cfg.trustedOrigins != null && trustedOrigins.length == 0) { trustedOrigins = cfg.trustedOrigins }
  378. if (cfg.pushKept != null) { pushKept = cfg.pushKept }
  379. if (cfg.pushKeptBytes != null) { pushKeptBytes = cfg.pushKeptBytes }
  380. if (cfg.tabKept != null) { tabKept = cfg.tabKept }
  381. if (cfg.recentKept != null) { recentKept = cfg.recentKept }
  382. }
  383. // MISSION 511: `import { a, b } from './counter.hl'` of an app file (not a package's): the statics it takes live ONCE, in that
  384. // file's own module, which every importing module imports. A static function so the build and the boot agree.
  385. // The app's own entry (the manifest, which builds the server) is never one: it is no browser module.
  386. // MISSION 516: and not one the browser module leaves out: the graph says `unreadIn` for the realms whose module reads none of the
  387. // names (they are used only in a `Style {}` or in handlers of another realm), and that file is no module of the page then.
  388. static isBracedFileImport = (imp, entryKey, realm) => {
  389. if (imp.unreadIn != null && imp.unreadIn.includes(realm)) { return false }
  390. return imp.key != entryKey && imp.default == null && imp.key != null && !imp.key.startsWith('hl:') && imp.key.endsWith('.hl') && imp.names != null && imp.names.length > 0
  391. }
  392. served = {}
  393. mounted = []
  394. for (r of routes) { if (r.component != null) { mounted[] = keyOf(r.component) } }
  395. // A FUNCTION ROUTE MAY RENDER A COMPONENT (`server.page(...)`), and nothing in the route table names it: the framework
  396. // cannot read which one from a function body. So a component the app's entry file imports is part of the app, as a
  397. // route's component is (hybriel#249: its Style, its module and its children were left out).
  398. for (imp of graph.files[graph.manifest.file].imports) {
  399. if (imp.default != null && imp.key != null && graph.files[imp.key] != null && viewHandle(imp.key) != 0 && !mounted.includes(imp.key)) { mounted[] = imp.key }
  400. }
  401. for (k of mounted) {
  402. let key = k
  403. // a file the graph does not hold is refused at its route row, below (servedKeys
  404. // → routeComponentKey: this walk reads the evaluated table, which has no lines)
  405. if (graph.files[key] == null) { key = null }
  406. while (key != null) {
  407. serveComponent(key)
  408. let child = key
  409. key = graph.files[key].parent
  410. // A PARENT IS A COMPONENT (COMPONENTS §5): one without a View wraps nothing, and
  411. // every page under it answered a 500 while the boot said nothing (322 row 13)
  412. if (key != null && viewHandle(key) == 0) {
  413. hlError("hl:web: the `parent` clause of " + child + " names " + key + ", which declares no View: a parent is a component whose View places `slot` where the page renders")
  414. }
  415. }
  416. }
  417. // EVERY PACKAGE'S BROWSER HALF IS SERVED, BY ONE RULE. A package whose browser
  418. // side is written in this language ships it as `client.hl` beside its
  419. // plugin.json; the compiler compiles it like any other file and writes the
  420. // importing module `import { … } from "<halfDir>/<pkg>/client.js"`
  421. // (js_module.zig browserHalf / browserHalfUrl). Something has to answer that url,
  422. // and this is it — for EVERY such package the graph holds, because the rule
  423. // belongs to the language and not to one package. hl:web's own half is the first
  424. // case of it and no longer a hard-coded route of its own; hl:dnd is the second.
  425. //
  426. // The graph is the whole guard: a key is here only because the entry's closure
  427. // REACHED that package's half through an import, which is the same reason a
  428. // component has a module url. A package nothing imports is served nothing.
  429. for (gk of graph.files.keys()) {
  430. if (gk.startsWith('hl:') && gk.endsWith('/client.hl')) { serveHalf(gk) }
  431. }
  432. // ---- INSTALLABLE, AND OFFLINE (COMPONENTS §10, tickets #95–#97) ------------------
  433. // Two declarations in the app's manifest, and nothing written by hand in the app:
  434. // · `appIcons` (with `appTitle`, and optionally `appShortName`, `appThemeColor`,
  435. // `appBackgroundColor`, `appManifest`) makes the app INSTALLABLE — the web app
  436. // manifest below, linked from every page's head with its apple-touch-icon;
  437. // · `offline = [ … ]` makes the pages it names work OFFLINE — the service worker
  438. // (worker.hl) that keeps the shell and those pages, and in the client half the
  439. // IndexedDB copy of their state and the queue of the emits they make.
  440. // An app that declares neither is served nothing of either.
  441. offlineKeys = offlinePages()
  442. fallbackPattern = offlineFallbackPattern()
  443. dataFreeKeys = dataFreePages()
  444. queueEvents = offlineKeys != null ? queueable() : []
  445. if (installable()) {
  446. routes[] = { pattern = manifestUrl framework = true function = (route, req) => {
  447. return new Response(JSON.stringify(webManifest()), { headers = { 'Content-Type' = 'application/manifest+json; charset=utf-8' 'Cache-Control' = 'no-cache' } })
  448. } }
  449. }
  450. if (pushKey != null && hlTypeName(pushKey) != 'String') { refuseAtSetting('pushKey', 'hl:web: pushKey is the VAPID public key as a base64url string, and this one is a ' + hlTypeName(pushKey)) }
  451. if (pushPrivateKey != null || pushSubject != null) {
  452. if (pushKey == null || pushPrivateKey == null || pushSubject == null) { refuseAtSetting('pushPrivateKey', 'hl:web: sending a push needs pushKey, pushPrivateKey and pushSubject together') }
  453. if (hlTypeName(pushPrivateKey) != 'String' || hlTypeName(pushSubject) != 'String') { refuseAtSetting('pushPrivateKey', 'hl:web: pushPrivateKey is a base64url string and pushSubject a string (mailto:… or https://…)') }
  454. if (!pushSubject.startsWith('mailto:') && !pushSubject.startsWith('https://')) { refuseAtSetting('pushSubject', 'hl:web: pushSubject is a mailto: or https:// contact, and this one is ' + pushSubject) }
  455. let vapidPriv = base64urlDecode(pushPrivateKey)
  456. let vapidPub = vapidPriv != null && vapidPriv.length == 32 ? p256PublicKey(vapidPriv) : null
  457. if (vapidPub == null || base64urlEncode(vapidPub) != pushKey) { refuseAtSetting('pushPrivateKey', 'hl:web: pushPrivateKey is not the private half of pushKey (32 bytes, base64url)') }
  458. configurePush(pushKey, vapidPriv, pushSubject)
  459. }
  460. if (offlineKeys != null || pushKey != null) {
  461. // the ENTRY SCRIPT is served at the framework's directory, and its scope is the
  462. // whole app: `Service-Worker-Allowed` is what lets a script under /__hl/ say so
  463. routes[] = { pattern = workerUrl framework = true function = (route, req) => {
  464. return new Response(workerEntry(), { headers = { 'Content-Type' = 'text/javascript; charset=utf-8' 'Cache-Control' = 'no-cache' 'Service-Worker-Allowed' = '/' } })
  465. } }
  466. routes[] = { pattern = halfDir + '/web/worker.js' framework = true function = (route, req) => {
  467. return new Response(workerModule(), { headers = cached(req, 'text/javascript; charset=utf-8') })
  468. } }
  469. }
  470. // ---- WHAT THIS APP SERVES, OFF THE ANALYSIS ALONE (mission 315) ----------------
  471. // These four are STATIC, so they answer with no instance and without constructing
  472. // anything: the compiler evaluates `servedModulesOf(&graph)` at BUILD time to bake
  473. // each module's text, and this file's own root uses the very same functions at
  474. // boot. One definition, two callers — a second derivation would drift, and a
  475. // compiled binary would then serve text generated against different urls.
  476. //
  477. // The seed is the entry's route table AS WRITTEN, read through `hlSyntax`, not
  478. // the evaluated `routes` member: evaluating it means constructing the app, and
  479. // constructing this class binds a socket. The graph carries the entry's record
  480. // since 2026-09-16, which is what makes that readable at all.
  481. // A ROUTE'S COMPONENT IS A PAGE: a file without a View answered every request with a 500
  482. // ("declares no View", raised without a span) while the boot said nothing (mission 322
  483. // row 13). Refused at the row instead.
  484. static routePage = (gen, entryKey, valueNode, key) => {
  485. if (!hasViewMember(gen, key)) { hlSourceError(gen, entryKey, valueNode, key + " declares no View, so it is no page: a route's component is a file whose View renders") }
  486. return key
  487. }
  488. // The key a route row's `component` names: an imported class, or a path string.
  489. // Anything else is a located refusal AT THE ROW — never silently unserved.
  490. static routeComponentKey = (&graph, gen, entryKey, imports, valueNode) => {
  491. let v = hlSyntax(gen, entryKey, valueNode)
  492. if (v == null) { return null }
  493. if (v.tag == 'literal' && v.kind == 'string') {
  494. let t = v.text
  495. let k = t.startsWith('./') ? t.slice(2) : t
  496. // A PATH NO FILE OF THE APP IMPORTS IS NOT IN THE GRAPH: the analysis never read
  497. // it, so nothing can be served for it — refused here, at the row, instead of a
  498. // null deep in the framework once the server is already up (STATUS §2 item 0)
  499. if (graph.files[k] == null) { hlSourceError(gen, entryKey, valueNode, "the app never imports " + t + ", so the analysis never read it and the app would serve no module for it: import it in this file (`import Page from '" + t + "'`) and write `component = Page`") }
  500. return routePage(gen, entryKey, valueNode, k)
  501. }
  502. if (v.tag == 'identifier') {
  503. for (imp of imports) {
  504. if (imp.default == v.name && imp.key != null) { return routePage(gen, entryKey, valueNode, imp.key) }
  505. }
  506. }
  507. hlSourceError(gen, entryKey, valueNode, "a route's component must be an imported component class or a path string — this one the analysis cannot resolve to a file, so the app would serve no module for it")
  508. return null
  509. }
  510. // does the file at `key` declare a View? (a component, as opposed to a plain class)
  511. static hasViewMember = (gen, key) => {
  512. for (m of hlMembers(gen, key)) {
  513. if (m.name == 'View') { return true }
  514. }
  515. return false
  516. }
  517. // `key` and every component it composes, once each — the same walk
  518. // `serveComponent` performs, as a function of the graph.
  519. static collectServed = (&graph, gen, &out, key) => {
  520. if (key == null || graph.files[key] == null) { return null }
  521. for (k of out) { if (k == key) { return null } }
  522. out[] = key
  523. for (imp of graph.files[key].imports) {
  524. if (imp.default != null && imp.key != null && hasViewMember(gen, imp.key)) {
  525. collectServed(&graph, gen, &out, imp.key)
  526. }
  527. // MISSION 511: the same for a file imported by braces (its statics are shared through its module)
  528. if (isBracedFileImport(imp, graph.manifest.file, clientRealmOf(&graph)) && graph.files[imp.key] != null) {
  529. collectServed(&graph, gen, &out, imp.key)
  530. }
  531. }
  532. return null
  533. }
  534. // Every key this app answers a module for: each route's component and the wrapper
  535. // chain above it, the components those compose, and every package's browser half.
  536. static servedKeys = (&graph) => {
  537. let gen = graph.analysisGen
  538. let entryKey = graph.manifest.file
  539. let out = []
  540. if (entryKey != null && graph.files[entryKey] != null) {
  541. let imports = graph.files[entryKey].imports
  542. let routesNode = 0
  543. for (m of hlMembers(gen, entryKey)) {
  544. if (m.name == 'routes') { routesNode = m.node }
  545. }
  546. // the components the entry imports (a function route may render one: see `mounted` below), with their wrappers
  547. for (imp of imports) {
  548. if (imp.default != null && imp.key != null && graph.files[imp.key] != null && hasViewMember(gen, imp.key)) {
  549. let k = imp.key
  550. while (k != null) {
  551. collectServed(&graph, gen, &out, k)
  552. k = graph.files[k] != null ? graph.files[k].parent : null
  553. }
  554. }
  555. }
  556. if (routesNode != 0) {
  557. let arr = hlSyntax(gen, entryKey, routesNode)
  558. if (arr != null && arr.tag == 'array_expression') {
  559. for (e of arr.elements) {
  560. let row = hlSyntax(gen, entryKey, e)
  561. if (row != null && row.tag == 'object_expression') {
  562. for (pe of row.entries) {
  563. let prop = hlSyntax(gen, entryKey, pe)
  564. if (prop != null && prop.tag == 'object_property' && prop.key == 'component') {
  565. let key = routeComponentKey(&graph, gen, entryKey, imports, prop.value)
  566. // the wrapper chain above it, deepest last — a page is
  567. // served inside whatever wraps it
  568. let k = key
  569. while (k != null) {
  570. collectServed(&graph, gen, &out, k)
  571. k = graph.files[k] != null ? graph.files[k].parent : null
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. }
  579. }
  580. return out
  581. }
  582. // EVERY PACKAGE'S BROWSER HALF, BY ONE RULE — a package whose browser side is
  583. // written in this language ships it as `client.hl`, the compiler writes
  584. // `<halfDir>/<pkg>/client.js` into every importing module, and something has to
  585. // answer that url. The graph is the whole guard: a key is here only because the
  586. // entry's closure reached that package.
  587. //
  588. // SEPARATE FROM `servedKeys` ON PURPOSE: a half gets a ROUTE but is not a module
  589. // url of this app, so it is not in the map `hlJs` is handed. That asymmetry is
  590. // the existing `serveHalf`/`serveComponent` split, stated rather than inherited
  591. // by accident — measured 2026-09-16, when folding the two together made the
  592. // analysis set one key wider than the route walk's.
  593. static packageHalfKeys = (&graph) => {
  594. let out = []
  595. for (gk of graph.files.keys()) {
  596. if (gk.startsWith('hl:') && gk.endsWith('/client.hl')) { out[] = gk }
  597. }
  598. return out
  599. }
  600. // The browser realm's NAME, off the graph — the declared realm whose entrypoint
  601. // is this framework's client half. Static, so the compiler can ask it too.
  602. static clientRealmOf = (&graph) => {
  603. for (name of graph.realms.keys()) {
  604. if (graph.realms[name].entrypoint == 'hl:web/client.hl') { return name }
  605. }
  606. return null
  607. }
  608. // EVERY MODULE THIS APP SERVES, COMPILED — what a native binary answers `hlJs`
  609. // with (mission 315). The emitter needs the runtime specifier, the browser
  610. // realm and the served-url map; all three are functions of the analysis, so the
  611. // whole map is, and the COMPILER can build it without an instance.
  612. //
  613. // `minify` is NOT: it is an app setting bound at construction, and the analysis
  614. // cannot evaluate a construction. The value used is recorded beside each
  615. // module so a binary asked for a different one refuses at the call instead of
  616. // answering text generated the other way.
  617. // HOW THE APP ASKED FOR ITS MODULES. A build bakes ONE form of every module and
  618. // a binary answering the other form would be different bytes, so the build must
  619. // read the app's own answer — and the app writes it where it configures the
  620. // framework: `new WebFramework(… minify = true …)` in the manifest. The analysis
  621. // carries a construction's named arguments, so this is a READ of the same syntax
  622. // `servedKeys` reads for the routes, not a second declaration.
  623. //
  624. // A COMPUTED `minify` IS NOT READ HERE, and nothing is guessed from it: a build
  625. // cannot evaluate an expression the running app has not reached yet. Such an app
  626. // bakes the unminified form, exactly as every app did before this, and if it
  627. // then asks for the other form at run time the binary says so at the request —
  628. // "this binary carries the module compiled the other way", located, which is
  629. // the refusal that already exists and the one measured on the creator's social
  630. // app (2026-09-17). Writing the literal in the manifest is what removes it.
  631. static manifestMinify = (&graph) => {
  632. let gen = graph.analysisGen
  633. let key = graph.manifest.file
  634. if (key == null || graph.files[key] == null) { return false }
  635. for (m of hlMembers(gen, key)) {
  636. let s = hlSyntax(gen, key, m.node)
  637. if (s != null && s.tag == 'new_expression' && s.named != null) {
  638. for (h of s.named) {
  639. let p = hlSyntax(gen, key, h)
  640. if (p != null && p.tag == 'object_property' && p.key == 'minify') {
  641. let v = hlSyntax(gen, key, p.value)
  642. if (v != null && v.tag == 'literal' && v.kind == 'boolean') { return v.text == 'true' }
  643. }
  644. }
  645. }
  646. }
  647. return false
  648. }
  649. // THE PACKAGES WHOSE BROWSER HALF MAY BE ONE PLAIN `client.js`: each `hl:<pkg>` a served module (or a package's own
  650. // browser half) imports, that has no `client.hl` in the graph. Whether the package really has a `client.js` is
  651. // the compiler's to say (`hlJs('hl:<pkg>/client.js')` answers the empty text when it has none).
  652. static plainHalfPackages = (&graph) => {
  653. let out = []
  654. let keys = servedKeys(&graph)
  655. for (hk of packageHalfKeys(&graph)) { keys[] = hk }
  656. // the files those import, and theirs: a module reaches `hl:time` through a plain `.hl` file it imports (a static helper)
  657. let at = 0
  658. while (at < keys.length) {
  659. let k = keys[at]
  660. at = at + 1
  661. if (graph.files[k] != null) {
  662. for (imp of graph.files[k].imports) {
  663. if (imp.key != null && graph.files[imp.key] != null && !keys.includes(imp.key)) { keys[] = imp.key }
  664. if (imp.source.startsWith('hl:') && !imp.source.includes('/')) {
  665. let pkg = imp.source.slice(3, imp.source.length)
  666. if (graph.files['hl:' + pkg + '/client.hl'] == null && !out.includes(pkg)) { out[] = pkg }
  667. }
  668. }
  669. }
  670. }
  671. return out
  672. }
  673. // AND A PACKAGE WHOSE BROWSER HALF IS ONE PLAIN `client.js` (hl:time) THE SAME WAY (mission 509): the compiler
  674. // writes the same `import … from "<halfDir>/<pkg>/client.js"` for it, so the browser fetches it once and every
  675. // page module shares that one instance, instead of each module carrying a private copy of the half's text.
  676. plainHalves = {} // package name → the half's text, for the packages the served modules import
  677. for (pkg of plainHalfPackages(&graph)) { servePlainHalf(pkg) }
  678. static bakeModules = (graph) => {
  679. let realm = clientRealmOf(&graph)
  680. let served = servedModulesOf(&graph)
  681. let min = manifestMinify(&graph)
  682. let out = {}
  683. for (k of servedKeys(&graph)) {
  684. if (graph.files[k] != null) {
  685. let p = graph.files[k].path
  686. out[p] = {
  687. text = hlJs(p, min, runtimeSpec, realm, served)
  688. minify = min
  689. runtime = runtimeSpec
  690. realm = realm
  691. }
  692. }
  693. }
  694. // EVERY PACKAGE HALF TOO. The root walk above serves `<halfDir>/<pkg>/client.js`
  695. // for every `hl:<pkg>/client.hl` the graph holds, and a compiled binary answers
  696. // from BAKED text alone — so a bake that skipped them served the page and then
  697. // 404'd on the module the page imports, leaving the client half of the app
  698. // dead with nothing reported (measured on projects/framework, 2026-09-16).
  699. // Same rule, same list, one loop later: what the server routes, the build bakes.
  700. // AN OFFLINE APP'S SERVICE WORKER MODULE (COMPONENTS §10), under its own path
  701. if (manifestOffline(graph)) {
  702. let wp = workerPathOf(graph)
  703. out[wp] = {
  704. text = hlJs(wp, min, runtimeSpec, realm, served)
  705. minify = min
  706. runtime = runtimeSpec
  707. realm = realm
  708. }
  709. }
  710. // AND EACH PLAIN PACKAGE HALF (mission 509), under its pseudo path `hl:<pkg>/client.js`
  711. for (pkg of plainHalfPackages(&graph)) {
  712. let pp = 'hl:' + pkg + '/client.js'
  713. out[pp] = {
  714. text = hlJs(pp, min, runtimeSpec, realm, served)
  715. minify = min
  716. runtime = runtimeSpec
  717. realm = realm
  718. }
  719. }
  720. for (gk of graph.files.keys()) {
  721. if (gk.startsWith('hl:') && gk.endsWith('/client.hl') && graph.files[gk] != null) {
  722. let hp = graph.files[gk].path
  723. if (out[hp] == null) {
  724. out[hp] = {
  725. text = hlJs(hp, min, runtimeSpec, realm, served)
  726. minify = min
  727. runtime = runtimeSpec
  728. realm = realm
  729. }
  730. }
  731. }
  732. }
  733. return out
  734. }
  735. // file path → the url this server answers its module at. What `hlJs` is handed,
  736. // and what the compiler bakes against.
  737. static servedModulesOf = (&graph) => {
  738. let out = {}
  739. for (k of servedKeys(&graph)) {
  740. if (graph.files[k] != null) { out[graph.files[k].path] = '/' + k + buildMark }
  741. }
  742. return out
  743. }
  744. // ONE PACKAGE HALF'S ROUTE. It is a FUNCTION and not the body of the loop above
  745. // because the url's route closure must hold THIS key: a `let` in a loop body is
  746. // one binding the closures share, so every route built that way would serve the
  747. // last package's half (measured 2026-09-14 — both /__hl/web/client.js and
  748. // /__hl/dnd/client.js answered with hl:web's module). A parameter is a fresh
  749. // binding per call, which is the same reason serveComponent below is a function.
  750. serveHalf(key) {
  751. routes[] = { pattern = halfUrl(key.slice(3, key.length - 10)) framework = true function = (route, req) => { return serveHl('/' + key, req) } }
  752. return null
  753. }
  754. // ONE PLAIN PACKAGE HALF'S ROUTE (mission 509): the text comes from `hlJs` as `hl:<pkg>/client.js` (the compiler
  755. // reads it beside the package, a binary carries it baked); a package that has no such half answers the empty text
  756. // and gets no route. Cached by the build version exactly like the other halves (`cached`).
  757. servePlainHalf(pkg) {
  758. let text = hlJs('hl:' + pkg + '/client.js', minify, runtimeSpec, clientRealm(), servedModules())
  759. if (text == null || text == '') { return null }
  760. plainHalves[pkg] = text
  761. routes[] = { pattern = halfUrl(pkg) framework = true function = (route, req) => {
  762. return new Response(plainHalves[pkg], { headers = cached(req, 'text/javascript; charset=utf-8') })
  763. } }
  764. return null
  765. }
  766. // a mounted file's module route, and the routes of the components it composes
  767. // (an import with a View), recursively — off the graph, once each
  768. serveComponent(key) {
  769. if (served[key] != null) { return null }
  770. served[key] = true
  771. routes[] = { pattern = modulePath(key) framework = true function = (route, req) => { return serveHl(req.path, req) } }
  772. for (imp of graph.files[key].imports) {
  773. if (imp.default != null && imp.key != null && viewHandle(imp.key) != 0) { serveComponent(imp.key) }
  774. // MISSION 511: a file a served module imports statics from by braces is a module of its own too, so its statics exist once;
  775. // a braced import of a file outside the graph is skipped, as collectServed skips it, so it cannot crash the boot
  776. if (isBracedFileImport(imp, graph.manifest.file, clientRealm()) && graph.files[imp.key] != null) { serveComponent(imp.key) }
  777. }
  778. return null
  779. }
  780. // THE PROJECT DIRECTORY: this file lives in a package, so the app's directory is read
  781. // off a file that is the app's — the first route component's key against its path
  782. root = projectRoot()
  783. view = new HlwViewServer
  784. viewRead = new HlwView
  785. css = new HlwCss(minify = minify, view = view)
  786. compiler = new HlwCompile
  787. sessions = new HlwSessions(dir = sessionDirPath(), maxAge = sessionMaxAge != null ? sessionMaxAge : 1209600, idle = sessionIdle != null ? sessionIdle : 900, sweepEvery = sweepInterval != null ? sweepInterval : 300, cookie = cookieName(), secure = sessionSecure, anonMax = sessionAnonMax, anonKeep = sessionAnonKeep, domain = sessionDomain != null ? sessionDomain : '')
  788. sessions.open()
  789. // THE STYLES FILE IS NAMED AT BOOT, not at the first request for the stylesheet: a value
  790. // that names no file, or a file the graph does not hold, is the app's mistake and the
  791. // app does not start with it (ticket #12)
  792. if (styles != null) {
  793. if (hlTypeName(styles) != 'String' && hlTypeName(styles) != 'Class') { refuseAtSetting('styles', "hl:web: styles is the styles file — the class the app imported (`styles = Styles`) or a path string ('./styles.hl') — and this one is a " + hlTypeName(styles)) }
  794. if (graph.files[keyOf(styles)] == null) { refuseAtSetting('styles', "hl:web: styles names " + keyOf(styles) + ", which is not in the project graph — import it from the app's entry (`import Styles from './styles.hl'`) and write `styles = Styles`") }
  795. }
  796. // the whole tree, nothing excluded: dot directories (the session store) are skipped by
  797. // the walker's own rule, and a custom store inside the tree is the app's choice to pay for
  798. if (watchMode) { __native("eventloop.register", watch(root), "hlFileChanged") }
  799. sheetText = null // the stylesheet, walked once at the first request for it
  800. // hl:web's OWN urls (/__hl/*, /components/*.hl) win over the app's routes whatever the
  801. // app's table ends in (ticket #129: a last `/:slug/:n` answered /__hl/app.css with HTML):
  802. // the framework's routes first, the app's after them in their own order
  803. let ownFirst = []
  804. for (r of routes) { if (r.framework == true) { ownFirst[] = r } }
  805. for (r of routes) { if (r.framework != true) { ownFirst[] = r } }
  806. let oi = 0
  807. for (r of ownFirst) {
  808. routes[oi] = r
  809. oi = oi + 1
  810. }
  811. router = new HlwRouter(routes = routes)
  812. trees = {} // key → the View tree, built once
  813. preloaded = {} // key → true: the closure of the Views it reaches is loaded (preload)
  814. declared = {} // key → { member name → true } of its non-static members (declares)
  815. reach = {} // key → the component keys its View reaches, in the order preload walks them
  816. less = {} // key → { skipped, kids }: the server-only members the first load's seed leaves out (lessFor)
  817. needed = {} // key → { sites, names, reads }: the members only the server computes (serverNeeds)
  818. kidless = {} // key → 'yes' / 'no': does its View reference a component (holdsKids)
  819. fillsOf = {} // key → the named-region fills its View root writes (`side { … }`), lifted out of the tree
  820. slotAt = {} // key → where its View places its one `slot`
  821. styleNames = {} // key → the rule names of the file's Style, off the syntax
  822. styleRefs = {} // key → [{ tag rule }] the View wrote
  823. fillTags = {} // key → the element names (DOM tags) callers write into this component's slot (hybriel#270)
  824. styleTags = {} // key → the element names this file's View renders
  825. styleIds = {} // key → the literal `id` values this file's View writes (R3)
  826. staticHolders = {} // key → an instance of a file whose statics another file imports
  827. modules = {} // key → the browser module (JavaScript text), compiled once at boot
  828. buildHash = null // the hash of everything this build serves, in every cached url (build())
  829. workerCompiled = null // the service worker's module as compiled (offline apps only, workerText())
  830. shipped = {} // key → the module as served: its build marks replaced with the hash
  831. sitesOf = {} // key → the position tables cut out of a deploy build's module, as the JSON `?sites=1` answers
  832. servedUrls = null // file path → the url this server answers its module at, for hlJs
  833. // MISSION 505: the paint helpers every component module used to carry (compile.hl `paintHelpers`, 699 bytes in each of the 25
  834. // modules of the reference app's start page) ride once, at the end of the runtime text every module imports first
  835. runtime = hlJsRuntime() + newline + compiler.paintHelpers() // the runtime library every module imports as "./hl-runtime.js"
  836. peers = {} // connection key → the WsClient, while it is open
  837. peerSession = {} // connection key → its session, from the tab's `hello` (null = anonymous)
  838. peerHost = {} // connection key → the host its upgrade request named (null = none sent)
  839. peerHeaders = {} // connection key → its upgrade request's headers (requestHeaders)
  840. peerMounts = {} // connection key → the component keys the tab has mounted
  841. peerParams = {} // connection key → the route params the tab's shell and page were mounted with
  842. // A TAB OUTLIVES ITS SOCKET (ticket #143): 't' + the tab's id → { id, n, log, bytes, conn,
  843. // session, mounts, params, host, headers, left }. `n` counts the pushes sent to it, `log`
  844. // keeps the last of them as sent ([{ n, text }], bounded by pushKept/pushKeptBytes),
  845. // `conn` is its open socket's key or null, `left` when that socket went (tabKept)
  846. tabs = {}
  847. peerTab = {} // connection key → the id of the tab its `hello` named
  848. // SESSIONS (web/sessions.hl): named by the cookie, at the page request and at the
  849. // socket's handshake alike. Nothing about a session ever reaches page script.
  850. sending = null // the WsClient whose inbound emit is being handled — the peer
  851. // an outward emit reaches, and null under the POST fallback
  852. // THE POST FALLBACK'S PEER IS ITS OWN ANSWER. While a face dispatched over
  853. // `POST /__hl/emit` runs, or a socket face has a transient session (W214), `posting` is true. Every outward emit meant for the
  854. // CALLER is appended here instead of pushed; `inbound` ships the list in the ack.
  855. Boolean posting = false
  856. postEmits = []
  857. // …AND ITS TAB (#143): the tab a POST named (`tab` in its frame, of the same session) has
  858. // what is raised for it numbered and logged like a push, so the replay on its next socket
  859. // does not run it a second time
  860. postTab = null
  861. postSession = null // the cookie's session of the POST being dispatched
  862. pendingRotate = {} // 'r' + token → { old, id, at }: a socket-carrier rotation waiting for its browser's POST /__hl/rotate (W120)
  863. postAdopted = null // the session a POST's face (or an upload start) just made: its answer sets the cookie (W124)
  864. postReq = null // the request context of the POST being dispatched (requestInfo)
  865. faceReq = null // the request context of the carrier whose inbound emit is being dispatched
  866. peerReq = {} // connection key → its upgrade request's context (requestInfo)
  867. adoptTokens = {} // one-time token → { sid, at }: a socket cannot set a cookie, so the page asks for it (/__hl/adopt)
  868. postHost = null // the host of the POST being dispatched
  869. faceInst = null // the BLANK instance the running face writes on (step 2 of #201): read back as the tab's delta
  870. faceKey = null
  871. faceSent = {} // name -> JSON of what the delta already carried, so a later flush sends only the change
  872. faceHost = null // the host of the carrier whose inbound emit is being dispatched
  873. postHeaders = null // the headers of the POST being dispatched (requestHeaders)
  874. faceHeaders = null // the headers of the carrier whose inbound emit is being dispatched
  875. // EXACTLY ONCE (COMPONENTS §10): a queued emit carries a stable id `q`, and the ids handled
  876. // are kept per session, the last `handledKept` of them (Session.handled). A connection
  877. // with no session keeps its ids here, in one list under the same bound.
  878. Number handledKept = 200
  879. anonHandled = []
  880. // WHAT A KEPT ID WAS ANSWERED (ticket #107). An emit in flight when its socket closed
  881. // is sent again with its id, and its caller is still waiting — for a page, say. The
  882. // first delivery's ack went out on the dead socket, so the repeat is answered from
  883. // here: `answers[session id + ' ' + q]` is that ack as sent (its `i` replaced), or
  884. // `running` while the first delivery has not finished, which answers the repeat
  885. // `later` and the client asks again. In memory, the last `handledKept` of them: a
  886. // repeat comes seconds after the first try, and a restart loses nothing a live peer
  887. // still waits for but the ack, which is then plain `ok`, as before.
  888. answers = {}
  889. answerKeys = []
  890. uploads = {} // 'u' + upload id → { sid, name, type, size, have, parts, at, key }: a file on its way in (ticket #94)
  891. uploadKeys = {} // 'k' + session id + ' ' + q + ' ' + n → the upload id the n-th file of emit q went up under
  892. uploadParts = {} // 'u' + id + ':' + n → the n-th part as it arrived, a Bytes
  893. // ONE PORT, TWO CARRIERS. hl:http1's WebSocket engine answers the Upgrade
  894. // inline on the port this server already bound, so `websocket` and `rest` are
  895. // the same listener — which is why the manifest can declare both for the same
  896. // direction and this file needs no second server.
  897. // EVERY VIEW IS BUILT AT BOOT, not at the first request for its route: a View that
  898. // reads a name its file declares nowhere (checkRead) is the app's mistake, and the
  899. // app does not start with it — the port is bound on the line below this pass.
  900. // THE TWO DERIVATIONS MUST AGREE (mission 315). `served` is built above from the
  901. // EVALUATED route table; `servedKeys(&graph)` derives the same set from the
  902. // analysis alone, and the compiler bakes each module's text against the second.
  903. // If they ever disagree the binary would serve modules generated against urls
  904. // this server does not answer, so the disagreement is a refusal, here, at boot.
  905. analysedKeys = servedKeys(&graph)
  906. for (k of analysedKeys) {
  907. if (served[k] == null) {
  908. hlError('hl:web: the analysis says this app serves ' + k + ', the route walk did not — the two derivations of the served set disagree')
  909. }
  910. }
  911. for (k of served.keys()) {
  912. let seen = false
  913. for (a of analysedKeys) { if (a == k) { seen = true } }
  914. if (seen == false) {
  915. let why = ''
  916. for (imp of graph.files[k] != null ? [] : []) { why = why }
  917. hlError('hl:web: the route walk serves ' + k + ', the analysis did not — the two derivations of the served set disagree')
  918. }
  919. }
  920. routeNow = null
  921. anon = null
  922. for (k of served.keys()) { if (viewHandle(k) != 0) { tree(k) } }
  923. // the compiler reads a kid mount's View through this (a mount no longer carries a copy of it)
  924. compiler.treeOf = (key) => { return tree(key) }
  925. // A COMPONENT-REFERENCE CYCLE IS REFUSED HERE (COMPONENTS §12): a View that renders
  926. // itself, directly or through another, is a mount that never ends — it overflowed the
  927. // stack at the first request and the server died of a segfault with nothing said
  928. // (mission 322 row 1).
  929. acyclic = {}
  930. for (k of served.keys()) { if (viewHandle(k) != 0) { referenceCycle(k, [], []) } }
  931. // …and a page a shell wraps is placed at the shell's slot, inside its body: a page whose
  932. // root is `body` there emitted a second, nested <body> (mission 322 row 5)
  933. for (k of mounted) {
  934. if (graph.files[k] != null && graph.files[k].parent != null && viewHandle(k) != 0 && bodyRooted(k)) {
  935. hlError("hl:web: " + k + " is wrapped by " + graph.files[k].parent + " (its `parent` clause), but its View's root is `body { … }`, the page's body: the shell owns the body, so write the page's root as an element (`main { … }`, `section { … }`)")
  936. }
  937. }
  938. // THE SHEET IS WALKED AT BOOT, so the rules it drops are listed at boot (COMPONENTS §4,
  939. // css.hl's own header): walked at the first request for it, a dead rule was listed only
  940. // once some browser had asked, and a boot log said nothing (mission 322 row 11)
  941. stylesheet()
  942. // EVERY SERVED MODULE IS COMPILED AT BOOT: a free name in a View handler is a located
  943. // compile error (COMPONENTS §6b), and compiled at the first request for the module it
  944. // was a 500 behind a page that had already answered 200 (mission 322 row 14)
  945. for (k of served.keys()) { module(k) }
  946. // THE INTERFACE IS THE OPERATOR'S (ticket #24), on the ladder graph.zig's OperatorBind
  947. // states: the constructor's `host` > HL_HOST (the binary fills it from HOST) > the
  948. // manifest's > 0.0.0.0. Binding the default regardless put an app meant to sit behind
  949. // a proxy on every interface of the machine.
  950. if (host == null) { host = env('HL_HOST') }
  951. if (host == null && cfg != null && cfg.host != null) { host = cfg.host }
  952. if (host == null) { host = '0.0.0.0' }
  953. // A --PORT AFTER THE ENTRY OUTRANKS THE APP'S OWN PORT (creator ruling
  954. // 2026-09-27), but `port` ITSELF CANNOT SAY SO: the reference app passes an
  955. // explicit `port = …` to `new WebFramework(…)` (server.hl, computed from
  956. // HL_FW_PORT so a test run can sit beside a developer's own instance), which
  957. // PINS the member for the whole construction (SPEC.md "The file root is the
  958. // constructor" — "a root assignment to [a pinned] property… is a no-op").
  959. // `port = port_arg` below was exactly that no-op: `hybriel server.hl
  960. // --port=11499` still bound 44333, server.hl's own default, because this
  961. // line's write never landed. `boundPort`, a plain local nothing ever pins,
  962. // carries the actual ladder instead — CLI argument, else the (possibly
  963. // pinned) member, else HL_PORT, else 8080 — and IS what binds and what the
  964. // boot line names.
  965. warnRemovedCaches()
  966. let port_arg = portArgument()
  967. let boundPort = port_arg
  968. if (boundPort == null) { boundPort = port }
  969. if (boundPort == null && env('HL_PORT') != null) { boundPort = toNumber(env('HL_PORT')) }
  970. if (boundPort == null) { boundPort = 8080 }
  971. http = new NativeWebSocketServer(port = boundPort, host = host)
  972. echo 'framework listening on ' + boundPort
  973. module('web/client.hl')
  974. // ---- the browser's modules: compiled IN PROCESS, served from memory --------------
  975. // The JavaScript target is this binary's own function (hlJs), the same one `--js`
  976. // runs from the command line. No child process, no build directory.
  977. //
  978. // THE CLIENT is compiled at boot — every page needs it, and it carries the View
  979. // and the Router with it (one module, three classes). A COMPONENT is compiled ON
  980. // DEMAND, at the request for its own `.hl` url, and kept: a route nobody visits
  981. // costs nothing, and the browser asks for a component's module the first time it
  982. // mounts one.
  983. //
  984. // THE TABLE THE EMITTER WRITES IS DROPPED. `hlJs` puts each file's members,
  985. // handlers and methods — every node of every initializer, with the names it reads —
  986. // into the module, because the old hl:web's browser half reduces that table on every boot.
  987. // This framework asked the same questions at COMPILE time and wrote the answers into
  988. // the component's own statements, so the table is dead weight in the page: 58 KB of
  989. // syntax on the reference app's home page alone. What the framework SERVES is its own
  990. // text, so it leaves that statement out; the language is not asked to change, and
  991. // The old hl:web kept its table untouched.
  992. // THE TABLE STATEMENT'S NAME in this module: `hlTablesDef`, or in a compact module the
  993. // alias its import clause gives it (`hlTablesDef as _51`). Each statement stands at the
  994. // start of its own line, which is how it is found — an alias alone is a suffix of other
  995. // names (`$_51(` is a compiler temporary).
  996. tablesCall(text) {
  997. let alias = text.indexOf('hlTablesDef as ')
  998. if (alias < 0) { return newline + 'hlTablesDef(' }
  999. let first = alias + 15
  1000. let stop = first
  1001. while (stop < text.length && text[stop] != ',' && text[stop] != '}') { stop = stop + 1 }
  1002. return newline + text.slice(first, stop) + '('
  1003. }
  1004. // the `fns` of the file's own table — the first table statement the module carries is
  1005. // the file's; the ones after it are the classes it bundles
  1006. tableFns(text) {
  1007. let at = text.indexOf(tablesCall(text))
  1008. if (at < 0) { return [] }
  1009. let open = text.indexOf('{', at)
  1010. let end = text.indexOf(');', at)
  1011. if (open < 0 || end < 0) { return [] }
  1012. let t = JSON.parse(text.slice(open, end))
  1013. return t.fns == null ? [] : t.fns
  1014. }
  1015. withoutTables(text) {
  1016. // one per FILE the module carries — the client half bundles three classes. A compact
  1017. // module calls it by its alias, and was served with every table until ticket #98's
  1018. // follow-up: 50 KB and more of syntax on a minified app's page
  1019. let call = tablesCall(text)
  1020. let out = text
  1021. let at = out.indexOf(call)
  1022. while (at >= 0) {
  1023. let end = out.indexOf(');', at)
  1024. if (end < 0) { return out }
  1025. // the newline before it stays: it ends the statement above
  1026. out = out.slice(0, at + 1) + out.slice(end + 2)
  1027. at = out.indexOf(call)
  1028. }
  1029. return out
  1030. }
  1031. // THE APP RUNS ON ONE WEB FRAMEWORK. Which packages are frameworks is READ OFF THE
  1032. // GRAPH and not off a list this file keeps: a package the app's entry reached that
  1033. // holds a `WebFramework.hl` is one. hl:dnd, hl:http1 and every other package an app
  1034. // imports hold none and are untouched by this.
  1035. //
  1036. // The refusal names the ROW of each import, because the mistake IS an import line —
  1037. // a sub-file import (`'hl:web/css'`) counts as much as the package itself, which is
  1038. // exactly the case that made it: a lone braced import of a stylesheet helper puts the
  1039. // whole package into the graph, and with it a second navigation face.
  1040. oneFrameworkOnly() {
  1041. let frameworks = {}
  1042. for (gk of graph.files.keys()) {
  1043. if (gk.startsWith('hl:') && gk.endsWith('/WebFramework.hl')) { frameworks[gk.slice(0, gk.length - 16)] = true }
  1044. }
  1045. if (frameworks.keys().length < 2) { return null }
  1046. // the first row of the app's OWN files that reached each package
  1047. let sites = {}
  1048. for (k of graph.files.keys()) {
  1049. if (!k.startsWith('hl:')) {
  1050. for (imp of graph.files[k].imports) {
  1051. for (pkg of frameworks.keys()) {
  1052. if (sites[pkg] == null && (imp.source == pkg || imp.source.startsWith(pkg + '/'))) {
  1053. sites[pkg] = { key = k; node = imp.node; where = k + ':' + imp.line + ':' + imp.col + " imports '" + imp.source + "'" }
  1054. }
  1055. }
  1056. }
  1057. }
  1058. }
  1059. let said = ''
  1060. for (pkg of frameworks.keys()) {
  1061. if (said != '') { said = said + ', and ' }
  1062. if (sites[pkg] == null) { said = said + "'" + pkg + "' (reached through a package, not from a file of the app)" }
  1063. else { said = said + sites[pkg].where }
  1064. }
  1065. let msg = 'this app imports TWO web frameworks: ' + said + '. Both packages load, both answer a page navigation, and the second one answers on a blank instance. An app runs on ONE of them — switch EVERY hl: import in EVERY file of the app to the same package, a sub-file import like \'/css\' included. Switching one line is not switching the app.'
  1066. // THE CARET GOES ON ONE OF THE ROWS, and the sentence names them all: two
  1067. // import lines are equally the mistake, and a diagnostic can only underline one.
  1068. for (pkg of frameworks.keys()) {
  1069. if (sites[pkg] != null) { hlSourceError(gen, sites[pkg].key, sites[pkg].node, msg) }
  1070. }
  1071. hlError(msg)
  1072. return null
  1073. }
  1074. // ONE ANSWERER PER VALUE-FORM EMIT. SPEC: "if more than one class in the destination
  1075. // realm declares a non-tap handler for the event, the VALUE form is refused at the emit
  1076. // site naming both. As a statement it stays a broadcast and every handler still fires."
  1077. // The statement form is what `inbound` does — every face runs. The value form cannot be
  1078. // told apart on the wire, so every `x = emit server ev()` the app's files hold is read
  1079. // off the analysis here, and one whose event two files answer is refused at its site,
  1080. // naming both, before anything is served. Until ticket #20 both faces ran and the first
  1081. // answer was taken in silence.
  1082. oneAnswererEach() {
  1083. let realm = serverRealm()
  1084. for (k of graph.files.keys()) {
  1085. if (!k.startsWith('hl:')) {
  1086. for (e of hlEvents(gen, k).emits) {
  1087. if (e.value == true && e.realm == realm) {
  1088. let owners = facesOf(e.event)
  1089. if (owners.length > 1) {
  1090. let named = ''
  1091. for (o of owners) { named = named == '' ? o : named + ' and ' + o }
  1092. let msg = "hl:web: " + k + ':' + e.line + ':' + e.col + " — this emit waits for the answer of '" + e.event + "', and " + owners.length + " files answer it in the '" + realm + "' realm: " + named + ". A value-form emit has ONE answerer — rename the event in one of them, or emit it as a statement (a broadcast every handler receives)"
  1093. hlSourceError(gen, k, e.node, msg)
  1094. hlError(msg)
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. return null
  1101. }
  1102. // WHAT THIS SERVER SERVES AS A MODULE OF ITS OWN, by the file's path (mission 314
  1103. // rule 0). Handed to `hlJs`, it is what turns `import PostCard from './post_card.hl'`
  1104. // into an ES import of `/components/post_card.hl` instead of PostCard's whole class
  1105. // text copied into the importing module — EditHistory's class shipped three times on
  1106. // the social demo's home page before this. The urls are THIS file's (`moduleUrl`);
  1107. // the compiler invents none, and a file this server does not answer for is inlined
  1108. // exactly as it always was.
  1109. servedModules() {
  1110. if (servedUrls == null) {
  1111. let out = {}
  1112. for (k of served.keys()) { out[pathOf(k)] = modulePath(k) + buildMark }
  1113. servedUrls = out
  1114. }
  1115. return servedUrls
  1116. }
  1117. // A key the graph holds no file for is answered `null`, and the caller makes
  1118. // that a 404: a file the entry's closure never referenced is not part of this
  1119. // app, which is what keeps this from being a read of any path a url asks for.
  1120. module(key) {
  1121. if (modules[key] == null) {
  1122. let f = graph.files[key]
  1123. if (f == null) { return null }
  1124. // THE BROWSER GETS THE BROWSER'S PROJECTION, and nothing else. hlJs's
  1125. // fourth argument is the realm the module is produced for: a handler
  1126. // written `on server …` is not emitted at all, and a member whose
  1127. // initializer reaches a name the browser does not have is declared
  1128. // without one, for this server to lay over the instance with the state
  1129. // it already ships. The realm NAME comes off the manifest (clientRealm()
  1130. // above), never a literal — a project names its own realms.
  1131. let text = hlJs(f.path, minify, runtimeSpec, clientRealm(), servedModules())
  1132. // AND THE COMPILE STEP'S OWN OUTPUT BESIDE IT (mission 313): a component with a
  1133. // View carries, after its class, the paint statements this framework compiled
  1134. // from that View — one per bound spot, with its read written in (compile.hl).
  1135. // The browser calls them instead of walking the tree at paint time. Text
  1136. // produced here and served from memory like the module itself; nothing is
  1137. // written to disk and no JavaScript file lives under plugins/.
  1138. // THE FUNCTION VALUES' SITES are the one part of that table the browser still
  1139. // needs (tickets #98, #99): the compile step turns them into write sets
  1140. let fns = tableFns(text)
  1141. text = withoutTables(text)
  1142. if (viewHandle(key) != 0) {
  1143. let nodes = tree(key)
  1144. text = text + newline + compiler.module(gen, key, nodes, fns, fillsOf[key])
  1145. // THE COMPONENT'S BLUEPRINT COMES WITH ITS MODULE (W195): the structure the browser reads (`skeleton`), whether the
  1146. // component takes the route and which members the server computes. Not in the seed, so a page carries only the plans of
  1147. // components it uses. The elements, texts and attributes are not in it: the paint code above already holds them (W199).
  1148. let need = serverNeeds(key)
  1149. text = text + ';(globalThis.__hlB=globalThis.__hlB||{})[' + JSON.stringify(key) + ']=' + JSON.stringify({ view = skeleton(&nodes); route = declares(key, 'route'); srv = need.sites.length > 0 ? need.reads : null; ses = need.ses.length > 0; }) + ';' + newline
  1150. }
  1151. modules[key] = text
  1152. }
  1153. return modules[key]
  1154. }
  1155. // WHAT THE BROWSER READS OF A VIEW TREE besides the paint code (W199): the composed children with their bindings and fill (it
  1156. // mints and re-binds them), the `for`s (their site and the list they iterate, which decides whether a child is repainted or
  1157. // composed anew) and the `if`s that hold one of those. An element stands for nothing but the place of its children, so the
  1158. // elements go and their children move up; texts, attributes, handlers and styles are in the compiled paint code and not here.
  1159. skeleton(&nodes) {
  1160. let out = []
  1161. for (n of nodes) {
  1162. if (n.k == 'el') { for (c of skeleton(&n.children)) { out.push(c) } }
  1163. else if (n.k == 'component') { out.push({ k = 'component'; path = n.path; bindings = n.bindings; fill = skeleton(&n.fill); }) }
  1164. else if (n.k == 'for') { out.push({ k = 'for'; site = n.site; list = n.list; body = skeleton(&n.body); }) }
  1165. else if (n.k == 'if') {
  1166. let t = skeleton(&n.then)
  1167. let o = skeleton(&n.other)
  1168. if (t.length > 0 || o.length > 0) { out.push({ k = 'if'; site = n.site; then = t; other = o; }) }
  1169. }
  1170. }
  1171. return out
  1172. }
  1173. // the file the graph knows under this key — the graph carries every file's own path
  1174. pathOf(key) {
  1175. let f = graph.files[key]
  1176. if (f == null) { hlError('the graph holds no file ' + key + ' — nothing referenced it from the entry') }
  1177. return f.path
  1178. }
  1179. // THE BROWSER'S REALM, off the manifest: the realm whose declared entrypoint is
  1180. // this framework's client half. The framework's own two files ARE the two
  1181. // realms' entrypoints, so this is a lookup and never a guess.
  1182. clientRealm() {
  1183. for (name of graph.realms.keys()) {
  1184. if (graph.realms[name].entrypoint == 'hl:web/client.hl') { return name }
  1185. }
  1186. hlError('the manifest declares no realm whose entrypoint is ./client.hl — the browser half of this framework IS a realm, and a page cannot say which realm it is running in until the manifest names it')
  1187. }
  1188. // THIS realm, off the graph: the declared realm whose entrypoint REACHES this
  1189. // file (the app's entry imports it). A face names it, and so does the refusal
  1190. // when nothing answers.
  1191. serverRealm() {
  1192. let mine = graph.files['hl:web/WebFramework.hl'].realms
  1193. if (mine.length == 1) { return mine[0] }
  1194. hlError('the manifest declares no realm whose entrypoint reaches hl:web/WebFramework.hl — this file cannot dispatch a face without knowing which realm it is')
  1195. }
  1196. // the app's directory: a route component is the app's file, its key project-relative
  1197. projectRoot() {
  1198. for (r of routes) {
  1199. if (r.component != null) { return rootOf(keyOf(r.component)) }
  1200. }
  1201. // AN APP OF FUNCTION ROUTES ONLY (ticket #19) has no component to read it off, and
  1202. // needs no other: the manifest is the app's file too, and the graph knows its key
  1203. if (graph.manifest.file != null && graph.files[graph.manifest.file] != null) { return rootOf(graph.manifest.file) }
  1204. hlError('hl:web: the route table names no component and the graph names no manifest file, so the app\'s directory cannot be read off either')
  1205. }
  1206. // a project-relative key against its absolute path: what is left is the project's directory
  1207. rootOf(key) {
  1208. let path = pathOf(key)
  1209. // A COMPILED BINARY'S PATH IS ITS KEY (mission 318): it carries no
  1210. // build directory, so the file's path and its key are the same
  1211. // string and the root is the process's own directory. The
  1212. // interpreter's path is the script's absolute one, and the key is
  1213. // its tail — the root is what stands before it.
  1214. if (path == key) { return '.' }
  1215. return path.slice(0, path.length - key.length - 1)
  1216. }
  1217. // THE KEY OF A FILE THE APP NAMED — as the class it imported (`component = SortList`,
  1218. // `styles = Styles`: the import is the guarantee the graph reached it) or as a path
  1219. // ('./components/home.hl'). A class knows its file (`file(cls)`), and the graph knows
  1220. // the file's key.
  1221. keyOf(named) {
  1222. if (hlTypeName(named) == 'Class') {
  1223. let path = file(named)
  1224. for (k of graph.files.keys()) {
  1225. if (graph.files[k].path == path) { return k }
  1226. }
  1227. hlError('hl:web: the class at ' + path + ' is not in the project graph — import it from the app\'s entry')
  1228. }
  1229. // ANYTHING ELSE NAMES NO FILE (ticket #12): `styles = {}` booted and every request
  1230. // for the stylesheet was then a NotCallable on this line, with no line of the app's
  1231. if (hlTypeName(named) != 'String') { hlError("hl:web: a file the app names — a route's component, or `styles` — is the class it imported or a path string ('./styles.hl'), and this one is a " + hlTypeName(named)) }
  1232. if (named.startsWith('./')) { return named.slice(2) }
  1233. return named
  1234. }
  1235. // ---- the View tree: the member's syntax, reflected into plain hybrids ----------
  1236. viewHandle(key) {
  1237. for (m of hlMembers(gen, key)) {
  1238. if (m.name == 'View') { return m.node }
  1239. }
  1240. return 0
  1241. }
  1242. tree(key) {
  1243. treeLoad(key)
  1244. return trees[key]
  1245. }
  1246. // THE TREE IS BUILT ONCE PER KEY and read in place afterwards (`&trees[key]`): `tree(key)` hands out a COPY of the whole
  1247. // View tree on each call, and a mount, a render and a seed each asked for one (W116)
  1248. treeLoad(key) {
  1249. if (trees[key] != null) { return null }
  1250. let handle = viewHandle(key)
  1251. if (handle == 0) { hlError('component ' + key + ' declares no View') }
  1252. let v = hlSyntax(gen, key, handle)
  1253. let nodes = []
  1254. let fills = []
  1255. for (h of v.entries) {
  1256. let n = node(key, h, [], false, [])
  1257. // A NAMED REGION'S FILL (D-CHAIN addendum): `side { … }` at this View's root, where a level
  1258. // above declares `slot { name = 'side' … }`, is the content of THAT region and not of this
  1259. // page's own column: the region renders it, in this page's frame (compile.hl skips it here)
  1260. if (n != null && n.k == 'if' && n.regionfill != null) { fills.push({ name = n.regionfill; site = n.site; children = n.then; cond = null; }) }
  1261. // A CONDITIONAL FILL: `if (x) { side { … } }` at the View root fills while x holds (the default
  1262. // stands otherwise); the `if` itself stays in the page's tree (its branch holds the fill's
  1263. // components for the mounts, and the browser's `if` site is what hears x change)
  1264. else if (n != null && n.k == 'if' && n.region == null) {
  1265. for (c of n.then) {
  1266. if (c.k == 'if' && c.regionfill != null) { fills.push({ name = c.regionfill; site = c.site; children = c.then; cond = n.cond; }) }
  1267. }
  1268. }
  1269. if (n != null) { nodes.push(n) }
  1270. }
  1271. for (n of nodes) {
  1272. if (n.k == 'if' && n.regionfill == null && n.region == null) {
  1273. strayFill(key, n.then, true)
  1274. strayFill(key, n.other, false)
  1275. } else if (n.regionfill == null) { strayFill(key, [n], false) }
  1276. }
  1277. fillsOf[key] = fills
  1278. trees[key] = nodes
  1279. return null
  1280. }
  1281. // a fill standing anywhere but a View's root (or the root-level `if` that makes it conditional) is
  1282. // refused where it stands, rather than left to render nothing
  1283. strayFill(key, nodes, direct) {
  1284. for (n of nodes) {
  1285. if (n.k == 'if' && n.regionfill != null) {
  1286. if (!direct) { hlError('hl:web: ' + n.site + " — a region's fill (`" + n.regionfill + " { … }`) stands at a View's root or directly inside a root-level `if`; this one stands deeper (inside a nested `if`, an `else` or an element)") }
  1287. }
  1288. else if (n.k == 'if') { strayFill(key, n.then, false) strayFill(key, n.other, false) }
  1289. else if (n.k == 'el') { strayFill(key, n.children, false) }
  1290. else if (n.k == 'for') { strayFill(key, n.body, false) }
  1291. else if (n.k == 'component' && n.fill != null) { strayFill(key, n.fill, false) }
  1292. }
  1293. return null
  1294. }
  1295. // whether a node list holds a component anywhere (a region default that does is mounted late)
  1296. holdsComponent(nodes) {
  1297. for (n of nodes) {
  1298. if (n.k == 'component') { return true }
  1299. if (n.k == 'el' && holdsComponent(n.children)) { return true }
  1300. if (n.k == 'if' && (holdsComponent(n.then) || holdsComponent(n.other))) { return true }
  1301. if (n.k == 'for' && holdsComponent(n.body)) { return true }
  1302. }
  1303. return false
  1304. }
  1305. // the named regions the levels ABOVE this file declare (`slot { name = 'side' … }`)
  1306. regionsAbove(key) {
  1307. let out = []
  1308. let w = hlFile(gen, key).wrapper
  1309. let guard = 0
  1310. while (w != null && guard < 64) {
  1311. regionNamesIn(&out, tree(w))
  1312. w = hlFile(gen, w).wrapper
  1313. guard = guard + 1
  1314. }
  1315. return out
  1316. }
  1317. regionNamesIn(&out, nodes) {
  1318. for (n of nodes) {
  1319. if (n.k == 'if') {
  1320. if (n.region != null) { out.push(n.region) }
  1321. regionNamesIn(&out, n.then)
  1322. regionNamesIn(&out, n.other)
  1323. }
  1324. else if (n.k == 'el') { regionNamesIn(&out, n.children) }
  1325. else if (n.k == 'for') { regionNamesIn(&out, n.body) }
  1326. else if (n.k == 'component' && n.fill != null) { regionNamesIn(&out, n.fill) }
  1327. }
  1328. return null
  1329. }
  1330. // one entry of a hybrid literal → a tree node (null for an attribute: the
  1331. // element that owns it reads it)
  1332. node(key, handle, path, inFor, rows) {
  1333. let n = hlSyntax(gen, key, handle)
  1334. if (n == null) { return null }
  1335. if (n.tag == 'object_property') {
  1336. let v = hlSyntax(gen, key, n.value)
  1337. if (v.tag == 'object_expression') {
  1338. // A NAMED REGION: `slot { name = 'side' <default> }` is a region a lower level may fill
  1339. // (an `if` that always stands, carrying its name: the walkers already know the shape);
  1340. // `side { … }` at a View's root where a level above declares it is that region's fill
  1341. if (n.key == 'slot') {
  1342. let rname = regionName(key, v)
  1343. if (rname != null) {
  1344. let el = element(key, 'slot', v, path, inFor, rows)
  1345. let kids = []
  1346. for (c of el.children) { kids.push(c) }
  1347. return { k = 'if'; region = rname; deferred = holdsComponent(kids); cond = { k = 'text'; text = 'true'; kind = 'boolean'; }; then = kids; other = []; site = el.site; }
  1348. }
  1349. }
  1350. if (inFor && path.length == 0 && componentKeyOf(key, n.key) == null && regionsAbove(key).includes(n.key)) {
  1351. hlError('hl:web: ' + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a region's fill (`" + n.key + " { … }`) cannot stand inside a `for`: a fill stands at a View's root, or directly inside a root-level `if`")
  1352. }
  1353. if (path.length == 0 && !inFor && componentKeyOf(key, n.key) == null && regionsAbove(key).includes(n.key)) {
  1354. let el = element(key, n.key, v, path, inFor, rows)
  1355. // (an `if` that never renders in this column, so every walk of the tree that finds the
  1356. // components standing in it — mounts, seed, browser — sees them as it does an `if`'s)
  1357. return { k = 'if'; regionfill = n.key; cond = { k = 'text'; text = 'true'; kind = 'boolean'; }; then = el.children; other = []; site = el.site; }
  1358. }
  1359. let childKey = componentKeyOf(key, n.key)
  1360. if (childKey != null) { return component(key, n.key, childKey, v, v, path, inFor, rows) }
  1361. return element(key, n.key, v, path, inFor, rows)
  1362. }
  1363. return null
  1364. }
  1365. if (n.tag == 'literal') { return { k = 'text'; text = n.text; kind = n.kind; } }
  1366. if (n.tag == 'identifier') {
  1367. // A BARE CAPITALISED REFERENCE IS A COMPOSITION WITH AN EMPTY FILL (§12:
  1368. // "`Name { }` is the same reference as bare `Name`"). It is not a read, so it
  1369. // is answered before the read rules below refuse the name.
  1370. let bareKey = componentKeyOf(key, n.name)
  1371. if (bareKey != null) { return component(key, n.name, bareKey, null, n, path, inFor, rows) }
  1372. if (n.name == 'slot') { oneSlot(key, n) }
  1373. // AN IMPORTED STATIC IN A VIEW IS FOLDED (the archive did the same at build):
  1374. // `h1 { siteTitle }` with `import { siteTitle } from '../store.hl'` is not a
  1375. // member of this class, it is a constant of another file — read off that
  1376. // file's class once, here, and written into the tree as text
  1377. return nameRead(key, n.name, rows, n)
  1378. }
  1379. if (n.tag == 'view_for') {
  1380. // `for (row of list) { … }` — the list is a member (or a row field), the
  1381. // body's entries are rendered once per entry with `row` bound to it
  1382. let body = hlSyntax(gen, key, n.body)
  1383. let children = []
  1384. // THE ROW VARIABLE IS IN SCOPE INSIDE THE BODY, and nowhere else: the list is
  1385. // read in the scope that stands around the `for`
  1386. let list = ref(key, n.list, rows)
  1387. let inner = rows.slice(0)
  1388. inner.push(n.varName)
  1389. for (h of body.entries) {
  1390. let c = node(key, h, path, true, inner)
  1391. if (c != null) { children.push(c) }
  1392. }
  1393. // THE SITE, as every element node carries one: the id the module's tables
  1394. // file this `for`'s row under, so the browser reads what the list depends
  1395. // on from the compiler instead of guessing it off `list.name`.
  1396. return { k = 'for'; row = n.varName; list = list; body = children; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1397. }
  1398. if (n.tag == 'view_if') {
  1399. let then = []
  1400. let cons = hlSyntax(gen, key, n.consequent)
  1401. for (h of cons.entries) {
  1402. let c = node(key, h, path, inFor, rows)
  1403. if (c != null) { then.push(c) }
  1404. }
  1405. let other = []
  1406. let alt = hlSyntax(gen, key, n.alternate) // null when there is no else
  1407. if (alt != null) {
  1408. if (alt.tag == 'view_if') {
  1409. other.push(node(key, n.alternate, path, inFor, rows))
  1410. } else {
  1411. for (h of alt.entries) {
  1412. let c = node(key, h, path, inFor, rows)
  1413. if (c != null) { other.push(c) }
  1414. }
  1415. }
  1416. }
  1417. // A BRANCH CONDITION IS A READ (COMPONENTS: a member or a loop path).
  1418. // Anything else came back null here and the branch rendered nothing, on the
  1419. // server and after hydration, with no word said (ticket #17: `if (!flag)`).
  1420. let cond = ref(key, n.condition, rows)
  1421. if (cond == null) {
  1422. let c = hlSyntax(gen, key, n.condition)
  1423. hlError("hl:web: " + baseName(pathOf(key)) + ':' + c.line + ':' + c.col + " — a View `if` takes a member, a field path or a `for` row variable as its condition, and this one is an expression: declare it at the root of " + baseName(pathOf(key)) + " (`showIt = !flag`) and write `if (showIt)`")
  1424. }
  1425. return { k = 'if'; cond = cond; then = then; other = other; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1426. }
  1427. if (n.tag == 'member_expression') {
  1428. // `p.title` — a field path off a member or a row variable
  1429. let r = ref(key, handle, rows)
  1430. if (r != null) { return r }
  1431. }
  1432. if (n.tag == 'binary_expression' || n.tag == 'unary_expression' || n.tag == 'conditional_expression') {
  1433. // AN EXPRESSION IN A VIEW: its tree, and the names it reads (what repaints it)
  1434. let names = []
  1435. let x = exprTree(key, handle, rows, &names)
  1436. return { k = 'expr'; x = x; names = names; }
  1437. }
  1438. if (n.tag == 'on_statement') {
  1439. // a DOM event handled by the literal that carries it: the browser finds the
  1440. // literal in the instance's View by the path of keys and fires the event at it
  1441. // THE SITE IS THE HANDLER'S ID: the tables file this handler's write set
  1442. // under it, and the browser repaints exactly those members when it runs.
  1443. return { k = 'on'; event = n.event; site = baseName(pathOf(key)) + ':' + n.line + ':' + n.col; }
  1444. }
  1445. return { k = 'other'; tag = n.tag; }
  1446. }
  1447. // the literal name of a `slot { name = 'side' … }` region, null for anything else
  1448. regionName(key, v) {
  1449. for (h of v.entries) {
  1450. let e = hlSyntax(gen, key, h)
  1451. if (e.tag == 'object_property' && e.key == 'name') {
  1452. let val = hlSyntax(gen, key, e.value)
  1453. if (val.tag == 'literal' && val.kind == 'string') { return val.text }
  1454. }
  1455. }
  1456. return null
  1457. }
  1458. // A COMPONENT HAS EXACTLY ONE SLOT (COMPONENTS §2 table, §12): a second one rendered the
  1459. // child a second time, with no word said (mission 322 row 4)
  1460. oneSlot(key, n) {
  1461. let here = baseName(pathOf(key)) + ':' + n.line + ':' + n.col
  1462. if (slotAt[key] != null) {
  1463. hlError("hl:web: " + here + " — a second `slot` in this View (the first is at " + slotAt[key] + "): a component has exactly one slot, where the page it wraps or the fill it is given renders")
  1464. }
  1465. slotAt[key] = here
  1466. return null
  1467. }
  1468. isMember(key, name) {
  1469. for (m of hlMembers(gen, key)) { if (m.name == name) { return true } }
  1470. return false
  1471. }
  1472. // THE READ OF A BARE NAME IN A VIEW — wherever the name stands. A text child, an
  1473. // attribute's value and a reference-site binding are ONE lookup with ONE refusal:
  1474. //
  1475. // a `for` row variable standing around the read → read at render, from the row
  1476. // a member of this file → read at render, from the instance
  1477. // a name this file imports by BRACE → a STATIC of another file:
  1478. // constant-folded here, at build
  1479. // anything else → the located refusal (checkRead)
  1480. //
  1481. // An ATTRIBUTE used to skip the middle two and record every name as a member read,
  1482. // so `a { href = brandHref }` on a braced import asked the instance for a member it
  1483. // does not have and the renderer raised error.UndefinedProperty with view.hl's line
  1484. // and nothing of the app's — while the same name as a TEXT CHILD rendered fine
  1485. // (creator, routger migration W8). A read is a read; where it stands decides
  1486. // nothing about what it names.
  1487. nameRead(key, name, rows, at) {
  1488. if (rows != null && rows.includes(name)) { return { k = 'member'; name = name; } }
  1489. if (isMember(key, name)) { return { k = 'member'; name = name; } }
  1490. // A BRACED IMPORT FOLDS EVEN WHEN ITS VALUE IS NULL: the name resolved, so the
  1491. // read is answered here and never reaches the instance (a null static used to
  1492. // fall through to a member read and raise the same UndefinedProperty).
  1493. if (importsName(key, name)) {
  1494. let folded = importedStatic(key, name)
  1495. // THE VALUE AS WELL AS THE TEXT: an attribute and a text child want the text,
  1496. // and a reference binding wants the value the author's file declared (§12)
  1497. return { k = 'text'; text = folded == null ? '' : '' + folded; kind = 'folded'; value = folded; }
  1498. }
  1499. checkRead(key, name, rows, at)
  1500. return { k = 'member'; name = name; }
  1501. }
  1502. // A VIEW READS ONLY WHAT ITS FILE DECLARES. A name that is neither a member of
  1503. // this class, nor a static it imports by brace, nor a `for` row variable standing
  1504. // around this read, is a typo or a missing declaration — refused HERE, at the
  1505. // build of the tree (boot), naming the file and the line, instead of a 500 out of
  1506. // the renderer with the language's UndefinedProperty and no line of the app's.
  1507. checkRead(key, name, rows, n) {
  1508. if (rows != null && rows.includes(name)) { return null }
  1509. if (isMember(key, name)) { return null }
  1510. if (importsName(key, name)) { return null }
  1511. let hint = name == 'session' ? "`session = null` to receive the connection's session" : name == 'host' ? "`host = null` to receive the request's host" : name == 'headers' ? "`headers = null` to receive the request's headers" : name == 'route' ? "`route = null` to receive the matched route" : "`" + name + " = null`"
  1512. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — the View reads '" + name + "', which this file declares nowhere: declare it at the file's root (" + hint + "), or write the name it was meant to be")
  1513. }
  1514. // does this file import that name by brace from another file?
  1515. \* `--port=N` or `--port N` among the program's arguments, or null. *\
  1516. portArgument() {
  1517. let given = args()
  1518. let i = 0
  1519. while (i < given.length) {
  1520. let a = given[i]
  1521. let text = null
  1522. if (a.startsWith('--port=')) {
  1523. text = a.slice(7)
  1524. } else if (a == '--port' && i + 1 < given.length) {
  1525. text = given[i + 1]
  1526. }
  1527. if (text != null) {
  1528. let digits = text.length > 0 && text.length <= 5
  1529. let b = toBytes(text)
  1530. let k = 0
  1531. while (k < b.length) {
  1532. if (b[k] < 48 || b[k] > 57) { digits = false }
  1533. k = k + 1
  1534. }
  1535. if (!digits || toNumber(text) > 65535) {
  1536. hlError("hl:web: invalid --port value '" + text + "' — a port is a number 0-65535")
  1537. }
  1538. return toNumber(text)
  1539. }
  1540. i = i + 1
  1541. }
  1542. return null
  1543. }
  1544. importsName(key, name) {
  1545. for (imp of graph.files[key].imports) {
  1546. if (imp.key != null && memberOfImport(imp, name) != null) { return true }
  1547. }
  1548. return false
  1549. }
  1550. // the member of the imported file that the name `name` is bound to here, or null:
  1551. // the name itself, or what `import { a as name }` selected (#142)
  1552. memberOfImport(imp, name) {
  1553. if (imp.locals == null) { return imp.names.includes(name) ? name : null }
  1554. let i = 0
  1555. while (i < imp.locals.length) {
  1556. if (imp.locals[i] == name) { return imp.names[i] }
  1557. i = i + 1
  1558. }
  1559. return null
  1560. }
  1561. // the value of a static this file imports by brace from another .hl file, or null —
  1562. // read off an instance of that file (a class value takes no computed index, an
  1563. // instance does; the file is constructed once, its statics were evaluated at load)
  1564. importedStatic(key, name) {
  1565. for (imp of graph.files[key].imports) {
  1566. let member = imp.key != null ? memberOfImport(imp, name) : null
  1567. if (member != null) {
  1568. if (staticHolders[imp.key] == null) { staticHolders[imp.key] = construct(imp.key, constructionArgs(imp.key, {}, anonSession(), null, null)) }
  1569. return staticHolders[imp.key][member]
  1570. }
  1571. }
  1572. return null
  1573. }
  1574. // THE TREE OF A VIEW EXPRESSION: operators, literals and reads — evaluated by view.hl's
  1575. // `evalExpr`, with the language's own operators. `names` collects the members it reads.
  1576. exprTree(key, handle, rows, &names) {
  1577. let n = hlSyntax(gen, key, handle)
  1578. if (n.tag == 'literal') { return { k = 'text'; text = n.text; kind = n.kind; } }
  1579. if (n.tag == 'identifier') {
  1580. let r = nameRead(key, n.name, rows, n)
  1581. if (r.k == 'member' && !names.includes(r.name)) { names.push(r.name) }
  1582. return r
  1583. }
  1584. if (n.tag == 'member_expression' && !n.computed) {
  1585. let r = ref(key, handle, rows)
  1586. if (r != null) {
  1587. if (!names.includes(r.name)) { names.push(r.name) }
  1588. return r
  1589. }
  1590. }
  1591. if (n.tag == 'binary_expression') {
  1592. return { k = 'bin'; op = n.operator; l = exprTree(key, n.left, rows, &names); r = exprTree(key, n.right, rows, &names); }
  1593. }
  1594. if (n.tag == 'unary_expression') {
  1595. return { k = 'un'; op = n.operator; x = exprTree(key, n.operand, rows, &names); }
  1596. }
  1597. if (n.tag == 'conditional_expression') {
  1598. return { k = 'cond'; c = exprTree(key, n.condition, rows, &names); a = exprTree(key, n.consequent, rows, &names); b = exprTree(key, n.alternate, rows, &names); }
  1599. }
  1600. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a View expression holds names, literals, member paths and operators; a " + n.tag + " is none of those — declare it at the root of " + baseName(pathOf(key)) + " and write its name")
  1601. }
  1602. // a READ in the View: a member (`title`), or a field path (`p.title`) whose root
  1603. // is a member or a `for` row variable — the client decides which at render time
  1604. ref(key, handle, rows) {
  1605. let n = hlSyntax(gen, key, handle)
  1606. if (n.tag == 'identifier') { checkRead(key, n.name, rows, n) return { k = 'member'; name = n.name; } }
  1607. // A LIST WRITTEN IN PLACE (`for (n of [1, 2])`) is a literal, read as its value: the
  1608. // same folded 'text' node a folded static is, so every reader takes it the way it takes
  1609. // that one. Its entries are literals — anything else has no value before a read.
  1610. if (n.tag == 'array_expression') {
  1611. let items = []
  1612. for (e of n.elements) {
  1613. let el = hlSyntax(gen, key, e)
  1614. if (el == null || el.tag != 'literal') {
  1615. hlError("hl:web: " + baseName(pathOf(key)) + ':' + n.line + ':' + n.col + " — a list written in a View can hold literals only; declare it as a member to loop over anything else")
  1616. }
  1617. items.push(viewRead.literalValue(el.kind, el.text))
  1618. }
  1619. return { k = 'text'; text = ''; kind = 'folded'; value = items; }
  1620. }
  1621. if (n.tag == 'member_expression' && !n.computed) {
  1622. let obj = hlSyntax(gen, key, n.object)
  1623. let prop = hlSyntax(gen, key, n.property)
  1624. if (obj.tag == 'identifier') { checkRead(key, obj.name, rows, obj) return { k = 'field'; name = obj.name; path = [prop.name]; } }
  1625. let inner = ref(key, n.object, rows)
  1626. if (inner != null && inner.k == 'field') {
  1627. let path = inner.path.slice(0)
  1628. path.push(prop.name)
  1629. return { k = 'field'; name = inner.name; path = path; }
  1630. }
  1631. }
  1632. return null
  1633. }
  1634. // THE COMPOSED CHILD: an entry named after a class the file imports, whose file
  1635. // has a View. `Child { count = count on done(v) { … } }` — the entries are the
  1636. // BINDINGS (host values handed to the child's construction as named arguments)
  1637. // and the reference-site handlers. The graph says which name is which file.
  1638. componentKeyOf(key, name) {
  1639. for (imp of graph.files[key].imports) {
  1640. if (imp.default == name && imp.key != null && viewHandle(imp.key) != 0) { return imp.key }
  1641. }
  1642. return null
  1643. }
  1644. // THE REFERENCE'S SITE IS IN ITS PATH. A path of class names alone made two
  1645. // references of one class under one parent (`body/Card` twice) the SAME node key,
  1646. // so both collapsed onto one mount and one of the two fills was lost. A reference
  1647. // is a construction: each one is its own mount, so each one is its own path.
  1648. componentStep(cls, at) {
  1649. return cls + '@' + at.line + ':' + at.col
  1650. }
  1651. // is this entry a `Style.rule` reference? (the `Style` of THIS file, by name)
  1652. styleRef(key, e) {
  1653. let obj = hlSyntax(gen, key, e.object)
  1654. return obj.tag == 'identifier' && obj.name == 'Style'
  1655. }
  1656. // THE REFERENCE'S POSITIONAL SIGNATURE (§12: "a reference is a construction, so its
  1657. // POSITIONAL entries bind to the class's declared properties in declaration order —
  1658. // the same rule `new X(a, b)` follows").
  1659. //
  1660. // MEASURED, not guessed (2026-09-13, this worker): `new X(a, b, …)` fills the class's
  1661. // root PROPERTY DECLARATIONS in SOURCE ORDER, one slot each — `on` handlers and
  1662. // methods take no slot, and `hlMembers` returns exactly that list in exactly that
  1663. // order, so the tree builder reads the signature straight off it. Three of those
  1664. // declarations are not properties of the COMPOSITION and are left out here:
  1665. //
  1666. // `View` and `Style` — what the component renders and paints WITH, not what it is
  1667. // constructed from. The language does give them a slot (a
  1668. // bare `new` binds them), but §12 says `Card { "text" }` with
  1669. // no declared property takes its text as FILL, and a
  1670. // component always declares a View: counting it would make
  1671. // the positional-literal fill unreachable in every component
  1672. // there is.
  1673. // `slot` — the late-bound child, not state (§12); and with the fill
  1674. // rendered where the child places it the two readings emit
  1675. // the same HTML anyway.
  1676. // every `static` — a static belongs to the CLASS (§12 build-time constants), so
  1677. // a reference cannot seed one for every other reference.
  1678. //
  1679. // A NAMED assignment does NOT free its slot — measured: `new Q('n1', beta = 'B', 'n2')`
  1680. // puts 'n2' in the SECOND declaration and 'B' in beta. It is applied AFTER the
  1681. // positional ones and wins, which is why the positional bindings are emitted first
  1682. // below. (COMPONENTS.md:711 reads "a property the reference also assigns by name is
  1683. // not in the signature"; the interpreter says otherwise and the parenthetical in the
  1684. // same line — "named is applied after positional; the name wins, as in `new`" — is
  1685. // what this follows.)
  1686. positionalSignature(key) {
  1687. let out = []
  1688. for (m of hlMembers(gen, key)) {
  1689. if (!m.isStatic && m.name != 'View' && m.name != 'Style' && m.name != 'slot') { out.push(m.name) }
  1690. }
  1691. return out
  1692. }
  1693. component(key, cls, childKey, v, at, path, inFor, rows) {
  1694. let bindings = []
  1695. let positional = []
  1696. let ons = []
  1697. let fill = []
  1698. let here = path.slice(0)
  1699. here.push(componentStep(cls, at))
  1700. let sig = positionalSignature(childKey)
  1701. let taken = 0
  1702. if (v != null) {
  1703. for (h of v.entries) {
  1704. let e = hlSyntax(gen, key, h)
  1705. if (e.tag == 'object_property') {
  1706. let val = hlSyntax(gen, key, e.value)
  1707. // A BINDING NAMES A DECLARED MEMBER OF THE CHILD (COMPONENTS §12): the value
  1708. // otherwise went into the construction and nowhere, with no word said
  1709. // (mission 322 row 12). An element entry is the fill, not a binding.
  1710. if (val.tag != 'object_expression' && !isMember(childKey, e.key)) {
  1711. hlError("hl:web: " + baseName(pathOf(key)) + ':' + e.line + ':' + e.col + " — " + cls + " has no member '" + e.key + "' to bind: " + baseName(pathOf(childKey)) + " declares " + positionalSignature(childKey).join(', '))
  1712. }
  1713. // A LITERAL ON A REFERENCE KEEPS ITS TYPE (§12 "typed, not stringified"):
  1714. // the binding carries the literal's KIND, and `view.refValue` turns the
  1715. // pair into the value the child's member is given. Written as text alone,
  1716. // `Level2 { n = 1 }` handed the child the String "1" and `n * 97` refused
  1717. // (measured 2026-09-14, demo-nested wall 3).
  1718. if (val.tag == 'literal') { bindings.push({ name = e.key; text = val.text; kind = val.kind; }) }
  1719. else if (val.tag == 'identifier') {
  1720. // a binding is a read at the reference site, so it is the same lookup
  1721. let r = nameRead(key, val.name, rows, val)
  1722. // …and a folded static crosses as its VALUE, for the same reason
  1723. if (r.k == 'text') { bindings.push({ name = e.key; text = r.text; kind = 'folded'; value = r.value; }) }
  1724. else { bindings.push({ name = e.key; member = val.name; }) }
  1725. }
  1726. else if (val.tag == 'member_expression') { bindings.push({ name = e.key; ref = ref(key, e.value, rows); }) }
  1727. else {
  1728. // `Card { span { … } }` — an element entry is not a binding, it is the FILL
  1729. let c = node(key, h, here, inFor, rows)
  1730. // …and an EXPRESSION is neither, so it is refused rather than dropped:
  1731. // the same rule an attribute follows (mission 312 wall 4).
  1732. if (c == null) {
  1733. hlError("hl:web: " + baseName(pathOf(key)) + ':' + val.line + ':' + val.col + " — '" + e.key + "' is bound to an expression on the reference " + cls + ", and a binding is a literal, a member or a field path: declare the expression at the root of " + baseName(pathOf(key)) + " (`" + e.key + "Value = …`) and write `" + e.key + " = " + e.key + "Value`")
  1734. }
  1735. fill.push(c)
  1736. }
  1737. } else if (e.tag == 'on_statement') {
  1738. // A HANDLER WRITTEN ON A REFERENCE IS THE HOST'S, bound on the child's ROOT
  1739. // element. The reference is a literal of THIS file's View, so its behaviour
  1740. // is minted from THIS file's site and its body reaches this file through the
  1741. // owner rule — the same path an element's own handler takes. The child's own
  1742. // handler on that element is not replaced: both are listeners on one element
  1743. // and both run, the child's first, because it was bound when the child's tree
  1744. // was claimed. (Until 2026-09-13 the event was collected here and dropped: a
  1745. // reference with `on submit` never bound, and a form submitted natively.)
  1746. // …AND ITS SITE, because the tables file this handler's write set
  1747. // under it: the browser repaints exactly what it wrote (mission 309).
  1748. ons.push({ event = e.event; site = baseName(pathOf(key)) + ':' + e.line + ':' + e.col; })
  1749. } else if (e.tag == 'member_expression' && !e.computed && styleRef(key, e)) {
  1750. // a `Style.rule` written on a reference: the reference renders no element
  1751. // of its own, so there is nothing for the class to land on (§12)
  1752. hlError("hl:web: " + baseName(pathOf(key)) + ':' + at.line + ':' + at.col + " — a Style rule cannot be written on the component reference '" + cls + "': a reference renders no element of its own. Write the rule on an element inside " + baseName(pathOf(childKey)) + ", or name a '#" + cls + "' local rule in this file")
  1753. } else {
  1754. // AN ORDERED ENTRY. A literal or a read is the next declared property's
  1755. // value while the signature has room — `Button { "SD" }` is `Button
  1756. // { label = "SD" }` — and everything else, plus everything that EXCEEDS
  1757. // the signature, is the FILL: a fragment of THIS file's View, with its
  1758. // reads, its handlers and its `for` rows (§12 "host content").
  1759. let c = node(key, h, here, inFor, rows)
  1760. if (c != null) {
  1761. if (taken < sig.length && (c.k == 'text' || c.k == 'member' || c.k == 'field')) {
  1762. // the same rule as the named form above: a literal keeps its kind and a
  1763. // folded static crosses as its value
  1764. if (c.k == 'text') { positional.push({ name = sig[taken]; text = c.text; kind = c.kind; value = c.value; }) }
  1765. else if (c.k == 'member') { positional.push({ name = sig[taken]; member = c.name; }) }
  1766. else { positional.push({ name = sig[taken]; ref = c; }) }
  1767. taken = taken + 1
  1768. } else { fill.push(c) }
  1769. }
  1770. }
  1771. }
  1772. }
  1773. // THE NAMED ASSIGNMENTS COME LAST, so the name wins over the positional entry that
  1774. // landed on the same property (measured: that is what `new` does)
  1775. let allBindings = []
  1776. for (b of positional) { allBindings.push(b) }
  1777. for (b of bindings) { allBindings.push(b) }
  1778. bindings = allBindings
  1779. // FILLING WHAT PLACES NO SLOT IS A LOCATED ERROR (§12): the child would drop the
  1780. // content silently, which is exactly the bug this rule was written for.
  1781. if (fill.length > 0 && !isMember(childKey, 'slot')) {
  1782. hlError("hl:web: " + baseName(pathOf(key)) + ':' + at.line + ':' + at.col + " — " + cls + " is filled here, but " + baseName(pathOf(childKey)) + " declares no 'slot' to fill: declare `slot = null` there and place `slot` in its View, or write the content outside the reference")
  1783. }
  1784. if (fill.length > 0) {
  1785. if (fillTags[childKey] == null) { fillTags[childKey] = [] }
  1786. noteFillTags(childKey, fill)
  1787. }
  1788. let classes = []
  1789. if (styleRules(key).includes('#' + cls) && !viewIds(key).includes(view.kebab(cls))) {
  1790. classes.push(view.localClass(key))
  1791. for (t of rootTags(childKey)) { noteRef(key, t, '#' + cls) }
  1792. }
  1793. // THE NODE NAMES ITS CHILD, it does not carry it. What the browser needs to build
  1794. // a child the server never mounted — the module url and the View tree — stands
  1795. // ONCE in the component's own module (its blueprint, W195), keyed by this `key`.
  1796. // The node used to carry that pair itself, and only when it stood inside a `for`:
  1797. // a child deeper in a minted child's own tree therefore had nothing to build from
  1798. // and was silently missing after a push (a comment card's like button and its
  1799. // edit history, creator's social app, 2026-09-13).
  1800. // THE REFERENCE'S OWN SITE: `file:line:col` of the reference literal, the id the
  1801. // JavaScript target mints ITS behaviour class under — what a handler written on
  1802. // the reference is built from, in the host's frame (client.hl bindRefOns)
  1803. let site = baseName(pathOf(key)) + ':' + at.line + ':' + at.col
  1804. return { k = 'component'; cls = cls; key = childKey; path = here; bindings = bindings; ons = ons; classes = classes; row = inFor; fill = fill; site = site; }
  1805. }
  1806. // ---- Style, the View side (§4, as the archive did it) --------------------------
  1807. // The tree builder writes the class on the element and REPORTS what it wrote
  1808. // (`styleRefs[key]` = [{ tag rule }]) and the element names it rendered
  1809. // (`styleTags[key]`); web/style.hl spells the selectors from those. Three ways
  1810. // a rule reaches an element: `Style.rule` written on it (class = the tag-prefix
  1811. // strip of the rule name), a `#rule` local of this file matching the element by
  1812. // NAME (class = this file's four-character class; `#Child` matches a composed
  1813. // child's root elements), and — decided in style.hl, no class — a rule named
  1814. // like an element of this file's own View.
  1815. styleRules(key) {
  1816. if (styleNames[key] != null) { return styleNames[key] }
  1817. let names = []
  1818. for (m of hlMembers(gen, key)) {
  1819. if (m.name == 'Style') {
  1820. let v = hlSyntax(gen, key, m.node)
  1821. for (h of v.entries) {
  1822. let e = hlSyntax(gen, key, h)
  1823. if (e.tag == 'object_property' && !names.includes(e.key)) { names.push(e.key) }
  1824. }
  1825. }
  1826. }
  1827. styleNames[key] = names
  1828. return names
  1829. }
  1830. noteRef(key, tag, rule) {
  1831. if (styleRefs[key] == null) { styleRefs[key] = [] }
  1832. for (r of styleRefs[key]) { if (r.tag == tag && r.rule == rule) { return null } }
  1833. styleRefs[key].push({ tag = tag; rule = rule; })
  1834. return null
  1835. }
  1836. // the element names a caller writes into a component's slot, at any depth (hybriel#270): a nested
  1837. // Style rule of that component may reach them, they end up inside its elements
  1838. noteFillTags(childKey, nodes) {
  1839. for (n of nodes) {
  1840. if (n.k == 'el') {
  1841. if (!fillTags[childKey].includes(n.tag)) { fillTags[childKey].push(n.tag) }
  1842. noteFillTags(childKey, n.children)
  1843. } else if (n.k == 'if') { noteFillTags(childKey, n.then) noteFillTags(childKey, n.other) }
  1844. else if (n.k == 'for') { noteFillTags(childKey, n.body) }
  1845. else if (n.k == 'component' && n.fill != null) { noteFillTags(childKey, n.fill) }
  1846. }
  1847. return null
  1848. }
  1849. noteTag(key, tag) {
  1850. if (styleTags[key] == null) { styleTags[key] = [] }
  1851. if (!styleTags[key].includes(tag)) { styleTags[key].push(tag) }
  1852. return null
  1853. }
  1854. // `#name` IS AN ID WHEN THE VIEW HAS ONE (creator's ruling, ticket #51 / R3): a
  1855. // `#name` rule targets the element with `id = 'name'` if this file's View writes
  1856. // that id, and is the file-local class of the elements named `name` otherwise. The
  1857. // ids are read off the View's SYNTAX before the tree is built, because an element
  1858. // named `name` may stand before the element that carries the id. Only a literal id
  1859. // counts — a member-bound one has no value until render. A component reference's
  1860. // own `id = …` is a binding for the child, not an element of this View; its fill is.
  1861. viewIds(key) {
  1862. if (styleIds[key] != null) { return styleIds[key] }
  1863. let out = []
  1864. let handle = viewHandle(key)
  1865. if (handle != 0) { idsIn(key, hlSyntax(gen, key, handle), false, &out) }
  1866. styleIds[key] = out
  1867. return out
  1868. }
  1869. // AN ID IS KEBAB-CASE LIKE A CLASS (hybriel#256, R95): `id = 'addCode'` is written as
  1870. // id="add-code", and so are a `for` and a `#fragment` link that name an id this View
  1871. // defines, so `#addCode` in a Style, the id and the references to it all agree.
  1872. // viewIds holds the ids already kebab-cased; ONE function, view.kebab, spells them.
  1873. idText(key, name, text) {
  1874. if (name == 'id') { return view.kebab(text) }
  1875. if (name == 'for' && viewIds(key).includes(view.kebab(text))) { return view.kebab(text) }
  1876. if (name == 'href' && text.startsWith('#') && viewIds(key).includes(view.kebab(text.slice(1)))) { return '#' + view.kebab(text.slice(1)) }
  1877. return text
  1878. }
  1879. idsIn(key, block, isRef, &out) {
  1880. if (block == null || block.entries == null) { return null }
  1881. for (h of block.entries) {
  1882. let n = hlSyntax(gen, key, h)
  1883. if (n != null && n.tag == 'object_property') {
  1884. let v = hlSyntax(gen, key, n.value)
  1885. if (v.tag == 'object_expression') { idsIn(key, v, componentKeyOf(key, n.key) != null, &out) }
  1886. else if (!isRef && n.key == 'id' && v.tag == 'literal' && !out.includes(view.kebab(v.text))) { out.push(view.kebab(v.text)) }
  1887. } else if (n != null && n.tag == 'view_for') {
  1888. idsIn(key, hlSyntax(gen, key, n.body), false, &out)
  1889. } else if (n != null && n.tag == 'view_if') {
  1890. idsIn(key, hlSyntax(gen, key, n.consequent), false, &out)
  1891. let alt = hlSyntax(gen, key, n.alternate)
  1892. if (alt != null && alt.tag == 'view_if') { idsIn(key, { entries = [n.alternate] }, false, &out) }
  1893. else { idsIn(key, alt, false, &out) }
  1894. }
  1895. }
  1896. return null
  1897. }
  1898. // the root element tags of a component's tree (a composed child under `#Child`)
  1899. rootTags(key) {
  1900. let out = []
  1901. for (n of tree(key)) { if (n.k == 'el' && !out.includes(n.tag)) { out.push(n.tag) } }
  1902. return out
  1903. }
  1904. baseName(p) {
  1905. let i = p.lastIndexOf('/')
  1906. return i < 0 ? p : p.slice(i + 1)
  1907. }
  1908. element(key, tag, v, path, inFor, rows) {
  1909. let attrs = []
  1910. let children = []
  1911. let here = path.slice(0)
  1912. here.push(tag)
  1913. let domTag = view.domTag(tag)
  1914. // `body { }` IS THE PAGE'S BODY, and only as the View's root (COMPONENTS §6): below
  1915. // the root it rendered a second, nested <body> no browser keeps (mission 322 row 5)
  1916. if (domTag == 'body' && path.length > 0) {
  1917. hlError("hl:web: " + baseName(pathOf(key)) + ':' + v.line + ':' + v.col + " — a `body` element below the View's root: `body { … }` is the page's body and stands only as a View's root")
  1918. }
  1919. noteTag(key, tag)
  1920. let classes = []
  1921. for (h of v.entries) {
  1922. let e = hlSyntax(gen, key, h)
  1923. let styled = false
  1924. if (e.tag == 'member_expression' && !e.computed) {
  1925. let obj = hlSyntax(gen, key, e.object)
  1926. let prop = hlSyntax(gen, key, e.property)

Only the first lines are shown.

Branches

Latest commits

  • 2ed09441Use layouts theme 17e0f03 for W61 compatibilitymre
  • b8609a91Merge branch 'main' into w61-stylemre
  • 4639caf7Report W61 theme startup blocker and day39 Style probemre
  • 81f0a0bbREADME: two caches were restored by 90b4f72; log W62mre
  • 4a3f557eImport layouts theme ebd00b6 for W61 (startup blocked)mre
  • ab12a257Merge W62: #25 commit page measurements and proc repromre
  • 41323e49gitoria#25: measure commit request costs and reproduce blocking process waitsmre
  • 53ca42b2log: W60 merged, W61 W62 startedmre
  • 80870a33mission W61: style passmre
  • 560fd208Merge W60: helpers, bound forms, login in topics, two form fixes (gitoria#28 #32 #33)mre
  • ac5ba6a4log: W60, #25 measuredmre
  • 220f6342W60: record corrected form proof, full AE and remaining gapsmre
  • 7e31cac5gitoria#28: restrict reply form layout to reply formsmre
  • ae373cfdgitoria#28: keep each reply draft in its thread componentmre
  • eeeebd5agitoria: insert a newly created organization oncemre
  • 34d2d5cagitoria: clear the bound public-key textarea after creationmre
  • 119e54c0W60: restore conductor-owned tracking filesmre
  • 24b479e7W60: record final gates, Chrome failures and AE evidencemre
  • 5e11184cW60: record partial validation, framework gaps and cleanupmre
  • 20fe13fagitoria#33: centralize login and tickets connection statemre