gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2f391aa92f391aa9Log: HM50 startedmre2f391aa9/plugins/web/WebFramework.hl

270.0 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 2f391aa9Log: HM50 startedmre
  • 4b59c03dHM50 mission: doc pathmre
  • ed526d67HM50 missionmre
  • 2f986ca3Log: RT50 passmre
  • 1c4715a4RT50 mission: day50 repro retestmre
  • 57d1c0dcLog: day50 retest requestmre
  • 60b1f419Log: Anton #336 result, wake checkmre
  • 919a18aalog: scratchmre
  • 6b504440status tidymre
  • 9332bd10log: DP70 livemre
  • be11daa0DP70 brief fixmre
  • 886a7028DP70 brief, HM67 mergedmre
  • b41cdd6dMerge hm67-searchids: packed search IDsmre
  • 385904eaReport HM67 matched heap measurements and gate proofmre
  • e5c9b659Pack retained search IDs into UTF-8 bytesmre
  • 62a5f6c7HM67 brief, HM66 mergedmre
  • b32b8440Merge hm66-catalogindex: packed catalog indexmre
  • 2db0f7adReport HM66 heap measurements and validationmre
  • 6ce15623Pack catalog lists and membership maps in UTF-8 bytesmre
  • 71134e21HM66 briefmre