gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5f95de055f95de05mission 012: re-vendor Hybriel ce6f2e0a (plugins), report: gate 478/2 on comments push redrawmre5f95de05/plugins/web/WebFramework.hl

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

Only the first lines are shown.

Branches

Latest commits

  • 5f95de05mission 012: re-vendor Hybriel ce6f2e0a (plugins), report: gate 478/2 on comments push redrawmre
  • 3794c591mission 011: report, LOG, STATUS, md-keys-run widths, cdp-blank helpermre
  • 77a93c16mission 011: gate hook for md-keys (480/0), flatten() runs one at a time (removeChild race), surface also built on first focus / pointer-down (background tab), md-bg test, README keysmre
  • 3c906718mission 011: md-editor key tests (real keys) and fixes: nested p/ul flatten, bare br, link change, Ctrl+E, code block exit (WIP)mre
  • 1442e583mission 010: report, LOG, STATUSmre
  • 6f27ad31md-editor: phone toolbar row contained (inline-size) so it never widens a grid parentmre
  • d702d76dmd-editor look: root class md-empty (a host .empty rule hit it), rows = surface height, one phone toolbar row with 44 px targets; comment form rows 3; gate 360/0mre
  • 15be2ac0comments: attach (FilesUpload pick), onPost(text, files), files per comment; md-editor files=off; README, gate fixmre
  • 1f8d79d6comments (mission 009 WIP, tickets#27): attachments — attach="true" puts the form in FilesUpload pick mode, onPost(text, files), files per comment (thumbnails open full size, file rows, no url = no link); MdEditor files="off"; demo with attachments; gate m009 checks (WIP: 356/1)mre
  • 13389d67mission 008: report, LOG, STATUSmre
  • ab47e4a2files-upload (mission 008, #18 for hycon#46): pick-first-send-later mode — host-owned list (files + onChange), slot for the host's input area, Ctrl+V paste (both modes), thumbnails, name+size rows, ✕ remove, maxSize per file, Camera on touch screens, 44 px targets; demo /files-upload/pick; gate 343/0 (19 new, 18 fail on the old code)mre
  • 172e66bemission brief 008mre
  • 9db927dfpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 00a95329components (mission 007): re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ git-ignored), gate 324/0 old and new, real-data copy unchanged, report 007, same-output.mjs ports overridablemre
  • fe50766bmission brief 007mre
  • 2dce51b8components (mission 006) 4/4: docs (README comments + gate 324, STATUS, LOG), report reports/006-comments.mdmre
  • 9ec7273ecomponents layouts#2 (mission 006) 3/4: comments — each text is MdEditor readonly directly in its row (hl:web builds a composed child anew when a bound value changes, so the keyed one-row list was not needed); demo 'bob edits his comment elsewhere (a push)' + gate check that a text the host changes from outside is drawn anew; theme radii (var(--radius-small/large) with 5px/10px fallbacks: layouts' check-theme 0 problems with comments.hl copied in); README 'How it is built'; gate 324/0 (34 comments checks)mre
  • fd57c18bcomponents layouts#2 (mission 006) 2/3: comments block (components/comments, demo /comments) — pure Hybriel: '1 comment' / 'n comments', avatar initial, bubble with name, time, 'edited' (<details> with the earlier versions), the text drawn by MdEditor readonly (one-row list keyed by id + text, so an edit redraws), like ♥ n (aria-pressed), Edit / Delete (asks first) only where author == user, the form below in MdEditor (Comment button or Ctrl+Enter; a fresh editor after a post). Host passes comments + user and hands onPost / onEdit / onDelete / onLike (hybriel#87); demo keeps a mock thread from lib/comments.hl in the page, switches alice / bob / nobody. Home entry, routes, map line, README; base-look gate covers comments; 33 gate checks with real clicks / keysmre
  • 850a376bcomponents (mission 006) 1/3: MdEditor readonly = "true" — the Markdown shown formatted and nothing else (no toolbar, link form, file rows, placeholder, source view or switch; article contenteditable false, tabindex -1, role document; no field background or focus ring); the mount only loads the value. For the comments block, which draws every comment with the editor's own renderermre
  • ee9f1b57mission brief w6mre