gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitcc1be2d6cc1be2d6Merge branch 'w62-pr-close' into mainGitoriacc1be2d6/plugins/web/WebFramework.hl

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

Only the first lines are shown.

Branches

Latest commits

  • cc1be2d6Merge branch 'w62-pr-close' into mainGitoria
  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre