Components on the server
The same markup and components write a server. A package with "rook": { "markup": "html" } in its package.json gets markup that is a string of HTML, of type Html, and components that answer requests. The root takes the Request of the web standard, and serve(App) of rooklang/server runs it on node:http; handler(App) is a function from Request to Response for Bun, Deno and Workers. This is experimental and may change before 1.0.
We finish the task board on the server: its page renders the current tasks as HTML, and an API route can return the same typed collection as JSON. The browser-only controls stay in the interactive board.
// The server renders the same task model as HTML or JSON; the package // has "rook": { "markup": "html" } in its package.json. import { reply, serve } from "rooklang/server" type Priority "low" | "normal" | "high" interface Task { id string title string done bool priority Priority } const TASKS Task[] = [ { id: "model", title: "Define the task model", done: true, priority: "normal" }, { id: "board", title: "Render the task board", done: false, priority: "high" }, ] async func loadTasks() Task[] { return TASKS } comp Layout(title string, children Content) { return <html lang="en"> <head><title>{title}</title></head> <body><main>{children}</main></body> </html> } comp TaskRows(tasks Task[]) { return <ul>{for task in tasks { <li> <label> <input type="checkbox" checked={task.done} /> {task.title} <small>{task.priority}</small> </label> </li> }}</ul> } comp TaskPage() { const tasks = await loadTasks() return <Layout title="Task board"> <h1>Task board</h1><TaskRows tasks={tasks} /> </Layout> } comp App(request Request) { const path = new URL(request.url).pathname if path == "/api/tasks" { return await loadTasks() } if path == "/" { return <TaskPage /> } return reply("Not found", { status: 404 }) } serve(App, { port: 3000 })
- Text and attributes are escaped; an
Htmlgoes in as it is, andhtml(text)marks a string you trust as HTML. Attributes are checked as in the browser, and<html>gets a doctype. What only a page has is an error:onClick,bind:,ref,state,mount. - A component is an async function: its body may
await, and a tag is its result, waited for. Components side by side in markup render at the same time. - A component returns any value; its type is inferred, or written after the properties:
comp PostList() Post[]. The answer is made from the value of the root: aResponseas it is,Htmlastext/html, a string as text,nullas 404, the rest as JSON.reply(value, { status, headers })gives a status and headers. - A
Responseamong the children of markup goes up: the render stops, and it is the answer to the request. The other components still end, so theirdeferruns.
Decorators are the middleware. Their bodies may wait too, and an early return is a guard: it answers instead of the component. A decorator applied to a component above is the context of the components below: they name it with needs and read its public members.
// A decorator of the server may wait, and an early return in its body // answers instead of the component: a guard import { reply, serve } from "rooklang/server" interface User { name string admin bool } async func userOf(request Request) ?User { const name = request.headers.get("x-user") return name == null ? null : { name: name, admin: name == "root" } } dec session(request Request) { public const path = new URL(request.url).pathname public const user = await userOf(request) } // needs session: @session is applied to a component above, App dec admin() needs session { if !(@session.user?.admin ?? false) { return reply("Forbidden", { status: 403 }) } } // Generic: gives what its children give, whatever it is comp Logger<T>(children Content<T>) T needs session { const started = Date.now() defer { console.log(`${@session.path}: ${Date.now() - started} ms`) } return await children() } comp Header() needs session { return <header>Signed in as {@session.user?.name ?? "guest"}</header> } @admin comp Dashboard() { return <main><Header /><p>3 new orders</p></main> } @session(request) comp App(request Request) { return <Logger><Dashboard /></Logger> } serve(App, { port: 3000 })
needs sessionis satisfied by@sessionon the component itself or on any component above it in the tree of the request; the nearest one is taken. Where a component is used by its name, the compiler checks that one is there.dec admin() needs sessiontakes@sessionfrom above, so@adminworks onDashboard, which does not apply@sessionitself.- The children are
Content<T>, a function that renders them when called:Loggerdecides when they run, and gives what they give. ItsTis inferred from the children of the tag, here theHtml | ResponseofDashboardwith its guard. - A wrapper,
return (page Html) => <main>{page}</main>, gets what the component gives, of any type, as in the browser. The server of this site uses one to log the status of every answer.
route("/orders/:id", Order) ties a path to a page: the parameters of the path are its properties, and the compiler checks one against the other. The router is a loop over the table.
// route() ties a path to a page: :id of the path is the property id, // and the compiler checks one against the other import { reply, route, Route, serve } from "rooklang/server" // A wrapper that takes Content gets the body to run: an error boundary dec fallback(message string) { return (page Content<Html | Response>) => { const value, err = try await page() if err != null { console.error(err) return <p class="error">{message}</p> } return value } } comp Home() { return <h1>Orders</h1> } @fallback("This order cannot be shown") comp Order(id string) { const n = Number(id) if Number.isNaN(n) { throw new Error(`not a number: ${id}`) } return <h1>Order #{n}</h1> } const ROUTES Route<Html | Response>[] = [ route("/", Home), route("/orders/:id", Order), // route("/orders/:number", Order) would be an error: // Order has no property "number" for ":number" ] comp App(request Request) { const path = new URL(request.url).pathname for each in ROUTES { const Page = each.match(path) if Page != null { return <Page /> } } return reply("Not Found", { status: 404 }) } serve(App, { port: 3000 })
- The path is a string literal. Each
:nameis a property of the page that takes a string, and each property the page needs is in the path, so a typo in either is an error.match(path)gives the page with them, ornull;Route<T>has theTthe page gives. - A wrapper that takes
Content<T>gets the body of the component instead of what it gave, and runs it itself: insidetry, it is an error boundary. AResponsefrom below still goes up throughtry.