gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit84b574c484b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre84b574c4/plugins/web/WebFramework.hl

204.8 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 84b574c4notes mission 015: re-vendor plugins from hybriel f9614007 (incl. web, #117)mre
  • 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
  • fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
  • b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
  • 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
  • c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • 21c8f65dnotes mission 012: STATUSmre
  • 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
  • f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre