Server functions

Code in a project's *.server.ts files runs on the app's backend, never on the device: the app imports a server function and awaits it like any async function, and a channel sends the server's messages to the apps that listen. Call your own server code here; keep records in the database; accounts and sign-in are Sign-in; files users upload are Stored files; a real-time game between players is Net; any other web server is fetch / WebSocket.

  • call my own server code from the app and get the result back
  • show data from the server on a screen, with loading and error states (resource)
  • run a server call from a button and dim the button while it runs (action)
  • refuse a call with a status and a message the app can show (ApiError, RpcError)
  • push live updates from the server to every app that listens (channel)
  • keep a screen in step with the server's data — a room, a game, an order — without polling (computed)
  • know who has a room open right now, and who dropped out, without heartbeats (watchers, members)
  • show "no connection" while the app cannot reach its server, and hide it when it can again (online)
  • send each user only their own updates, or a chat room's messages to that room (groupBy)
  • know who is calling: the device, the address and the headers of a call (request)
  • tell one device from another without sign-in (request.session)
  • keep two calls for one room from interleaving: a seat limit, a vote counted once (ordered)
  • run and test the backend on my machine (lecodes dev, lecodes test)
  • play my multiplayer app on the phone with headless players beside me (lecodes dev --bots)

Platforms: iOS, Android, desktop, the web and the web player; on desktop a channel reaches only a backend on your machine. Every call needs a build that carries a backend — see Where the backend runs.

At a glance

TypeScript
// dice.server.ts — runs on the app backend. Every exported ASYNC function is an endpoint; a function that is
// not async is a helper of the server, for server files only (the app's import of it is refused).
export async function roll(sides: number, count = 1) {
  if (!Number.isInteger(sides) || sides < 2) throw new ApiError(400, "sides must be a whole number, 2 or more")
  const dice = Array.from({ length: count }, () => 1 + Math.floor(Math.random() * sides))
  return { dice, total: dice.reduce((a, b) => a + b, 0) }
}
TypeScript
// main.ts — the app
import { roll } from "./dice.server"

const result = UIText("Tap to roll").style({ fontSize: 28, color: "white" })

const rollTwo = async () => {
  try {
    const r = await roll(6, 2)               // a call to the app backend, typed by the server function
    result.text = `${r.dice.join(" + ")} = ${r.total}`
  } catch (e) {
    if (!(e instanceof RpcError)) throw e
    result.text = `failed (${e.status}): ${e.message}`
  }
}

UIScreen(
  UIColumn(
    result,
    UIButton(UIText("Roll").style({ fontSize: 22, color: "white" }))
      .style({ bgColor: "#4f7cff", borderRadius: 12, px: 32, py: 14 })
      .named("roll")
      .onClick(rollTwo),
  ).style({ gap: 24, alignItems: "center" }),
).style({ bgColor: "#1e2230", alignItems: "center", justifyContent: "center" }).open()

The call reaches the backend the build carries. In le.codes' preview, the published app, lecodes dev, lecodes desktop run and lecodes render / lecodes test it shows the dice. A build with no backend (lecodes compile, web build, app sync, app build desktop) shows failed (0): … — see Where the backend runs.

Show server data on a screen: resource

To show what the server answers — a list, a profile, today's menu — wrap the call in resource: one reactive value that is loading, ready with the data, or failed. No try around the call, no flags by hand.

TypeScript
// menu.server.ts
export type Dish = { name: string, price: number }

export async function todaysMenu(): Promise<Dish[]> {
  return [{ name: "Soup", price: 4 }, { name: "Pasta", price: 9 }]
}
TypeScript
// main.ts
import { todaysMenu } from "./menu.server"

const menu = resource(() => todaysMenu())        // asked now, and again on menu.reload()

UIScreen(
  UIColumn(() => {
    const m = menu.value                         // the screen follows it: loading → ready or failed
    if (m.state === "loading") return [UIText("Loading…")]
    if (m.state === "failed") return [
      UIText(m.offline ? "No connection" : m.message),
      UIButton(UIText("Try again")).named("retry").onClick(() => menu.reload()),
    ]
    return m.data.map((dish) => UIText(`${dish.name} — ${dish.price} €`))
  }).style({ gap: 12, padding: 24 }),
).open()
TypeScript
resource<T>(load: () => Promise<T>, { initial?: T }): { value: Loaded<T>, peek(), reload() }
type Loaded<T> = { state: "loading" } | { state: "ready", data: T } | { state: "failed", message, offline }
dataOf(loaded, otherwise)       // the data once there, `otherwise` until then
failureOf(loaded)               // { message, offline } or null
  • A resource asks at once, again when a signal load read changes (listMessages(room.value) follows the room) and on reload(). An answer that arrives after a newer request is dropped. While asked again, what is shown stays.
  • initial is for rows the bundle carries: the data is ready from the start, the server's answer replaces it, and a failure then leaves it — what is shown is real.
  • For a binding that needs one state only: UIColumn(() => dataOf(menu.value, []).map(Row)), UIText(() => failureOf(menu.value)?.message ?? "").
  • A failure's message is the server's ApiError text, in the words the server chose. offline means the request never reached a server (no network, or no backend in this build) — say that in your own words, the message is the transport's note.
  • For state that changes while the screen shows it, a server computed gives the same resource kept fresh: roomView.resource(code) — every value the server sends, not one.

Run a call from a button: action

For what the person does on the server — place an order, send a message — wrap the call in action: the call resolves to the server's answer or to null, busy is true while it runs, and error says why the last call failed.

TypeScript
// orders.server.ts
export async function placeOrder(dish: string, count: number) {
  if (count < 1) throw new ApiError(400, "Order at least one")
  return { number: 1 + Math.floor(Math.random() * 1000), dish, count }
}
TypeScript
// main.ts
import { placeOrder } from "./orders.server"

const order = action((dish: string, count: number) => placeOrder(dish, count))
const status = UIText("")

const orderButton = (label: string, count: number) =>
  UIButton(UIText(label)).named(`order${count}`)
    .style({ opacity: () => order.busy.value ? 0.5 : 1 })     // dimmed while the call runs
    .onClick(async () => {
      const placed = await order("Soup", count)               // null: it failed, or a call was running
      if (placed) status.text = `Order #${placed.number} placed`
      else if (order.error.value) status.text = order.error.value.offline ? "No connection" : order.error.value.message
    })

UIScreen(
  UIColumn(orderButton("Order a soup", 1), orderButton("Order no soup", 0), status).style({ gap: 12, padding: 24 }),
).open()
TypeScript
action<A, R>(run: (...args: A) => Promise<R>): ((...args: A) => Promise<R | null>) & { busy, error }
type Failure = { message: string, offline: boolean }
  • A call made while one runs is ignored: it resolves to null.
  • error is cleared as a call starts. busy and error are computed signals: read .value in a binding and the screen follows them — UIText(() => order.error.value?.message ?? "") shows the refusal and clears it at the next call, nothing to write by hand.
  • An endpoint that answers nothing (Promise<void>) resolves to undefined when it went through and to null when it did not, so if (!result) cannot tell them apart. Read error after the call: await remove(id); if (remove.error.peek()) … — or bind it as above and check nothing. Don't make the endpoint answer { ok: true } for the app's sake: null is also what an ignored call resolves to, and only error tells a failure from that.
  • No try around an action. It never throws: the failure is in error. A call whose failure the code handles by itself — a background save with its own retry, a sign-out that goes through whatever the server says — is a plain call of the endpoint with catch, not an action. An action is for what the person does, with the busy and error the screen shows for it.
  • One action per surface, not per endpoint. busy and error are the state of the place that shows them — a form, a dialog, a sheet — so the action is that place's, whatever endpoints it calls: a dialog that may rename or delete is one action over a command, and its error is the dialog's. Two actions on one screen are right when they run at the same time and show their state in two places (a chat's send and its upload). Two actions with one busy and one error line are one action.
  • After a write, ask again for what the screen shows: if (placed) menu.reload().
TypeScript
type Command = { kind: "rename", title: string } | { kind: "delete" }

const dialog = action(async (cmd: Command) => {        // the dialog's action: one busy, one error
  if (cmd.kind === "rename") await renameBoard(boardId, cmd.title)
  else await deleteBoard(boardId)
})

UIColumn(
  UIText(() => dialog.error.value?.message ?? ""),      // the dialog's error line
  UIButton(UIText(() => dialog.busy.value ? "Saving…" : "Rename")).named("rename")
    .onClick(async () => { await dialog({ kind: "rename", title: field.value }); if (!dialog.error.peek()) close() }),
  UIButton(UIText("Delete")).named("delete")
    .onClick(async () => { await dialog({ kind: "delete" }); if (!dialog.error.peek()) close() }),
)

Write an endpoint: export async function

A server function the app can call is an export async function of a *.server.ts file.

  • A file whose name ends in .server.ts (or .server.js) is server code. It never reaches the app bundle.
  • Its exports are sorted by how they are written:
    • endpoint: export async function f, export const f = async (…) => …, or export { f } of a local async function;
    • channel: export const c = channel<Message>()… (see Live updates from the server);
    • server-only: anything else — a constant, a class, a database handle (see Server-only exports).
  • export default in a server file is a compile error: default exports are not endpoints — use named exports.
  • A server file may import shared files and other server files. A *.server.ts is never the entry.
  • An endpoint's id is <file>#<export>, for example dice.server.ts#roll. It appears in error messages and in request.id.

In app code, an imported endpoint keeps the server function's parameter types, and every call returns a promise.

Note

an endpoint is async. A plain export function add(a: number, b: number) would be imported with the type number while its call is a promise, so it doesn't compile: an endpoint is called over the network, so in the app its result is a promise — declare it async. (A function that hands a promise or a query back as it is — () => db.auth.user() — passes.)

Arguments and results: what crosses the wire

  • Arguments travel positionally as JSON.
    • The server checks them against the endpoint's TypeScript parameter types before the function runs. A mismatch is a 400 that names the path: sides: expected number, got string, v.n: expected number, got string.
    • Optional and defaulted parameters may be left off the end.
    • Extra arguments and unknown object keys are ignored.
    • any / unknown accept anything.
  • undefined at the end of the arguments is the same as leaving them off: roll(6, undefined) is roll(6). An undefined BEFORE another argument arrives as null, which fails a parameter whose type has no null (count: expected number, got null) — type such a parameter number | null.
  • A parameter of type File is an upload: the app passes a picked file or a photo, and the call carries its bytes — see Stored files.
  • Every other parameter type must be JSON. Functions, Date, Map / Set, recursive types and generic parameters fail the le.codes build and lecodes dev with endpoint args must be JSON-serializable: …. lecodes compile does not run this check.
  • The result is serialized as JSON and not validated:
    • undefined (a void endpoint) resolves to null;
    • a Date arrives as its ISO string;
    • undefined properties disappear.

Errors: ApiError on the server, RpcError in the app

To refuse a call, throw ApiError(status, message) in the endpoint: the app's call rejects with an RpcError of that status and message. The At a glance pair shows both ends; an action or a resource keeps the failure for you.

TypeScript
throw new ApiError(status: number, message = "")     // server code: the app's call rejects with this status + message
err instanceof RpcError                               // app code: every failed call
err.status: number                                    // the HTTP-like status, 0 = the request never reached a server
err.message: string
status when message
yours the endpoint threw ApiError(status, message) yours
400 an argument failed the type check <param path>: expected …, got …
409 / 404 the database refused a write: a taken unique value, a relation to no row, a delete restrict forbids (409); a row that is gone (404) the database's words
500 the endpoint threw anything else Internal error — the real error goes to the server's log
504 the call ran past the backend's 30 s cap Endpoint timed out after 30000 ms
429 the device called this endpoint too often — see The limits Too many calls
0 this build has no backend, the request failed (no network), or a server-only export was used Endpoint <id>: … / <id> is server-only — …
other the response was not the backend's (a proxy's 502, …) Endpoint <id>: unexpected response (HTTP n)

Who is calling: request

To know who is calling an endpoint — its address, its headers — read the server global request. For the signed-in user, use db.auth (Sign-in).

TypeScript
// whoami.server.ts
export async function whoami() {
  return { endpoint: request.id, ip: request.ip ?? null, agent: request.headers["user-agent"] ?? null, device: request.session }
}
  • request.id is the endpoint id, or the channel id inside a channel's authorize / groupBy.
  • request.ip is the caller's address.
  • request.session is the calling device: a number that is the same in every call and channel hook of one installation of the app, and differs between devices. It needs no sign-in. With sign-in (withAuth) it is db.auth.sessionId, the same through sign-in and sign-out.
    • It is not a secret: store it in a row, show it to other players. Knowing a device's number does not let a call act as that device.
    • The app keeps it in its storage: a reinstall, or clearing the app's data, gives a new one. The tabs of one browser profile share their storage, so they are one device.
  • request.headers holds an endpoint call's HTTP headers, with lower-case names. Inside a channel's hooks it holds only authorization (the session), if there is one.
  • Outside a call (module load, a timer that fires after the response), id, ip and session are undefined and headers is {}.

Calls that must not interleave: ordered

The calls of an endpoint run at the same time, and every await lets another call in. Two join calls for one room can both count seven players and both sit down: nine at a table for eight. Wrap the read, the check and the write in ordered(key, fn): the calls with one key run one after another, each once the previous one has finished; calls with other keys don't wait.

TypeScript
// rooms.server.ts
const Player = model({ room: t.string(), device: t.int(), name: t.string() })
const db = defineDb({ Player })
const SEATS = 8

export async function join(room: string, name: string) {
  const device = request.session!                          // set in every call
  return ordered(room, async () => {                       // one join of this room at a time
    const players = await db.player.where({ room }).select({ device: true })
    if (players.some((p) => p.device === device)) return   // already seated
    if (players.length >= SEATS) throw new ApiError(409, "The room is full")
    await db.player.insert({ room, device, name })
  })
}
TypeScript
ordered(key: string | number, fn: () => T | Promise<T>): Promise<T>   // fn's result, once every earlier call of key is done
  • The key is yours: a room's code, a user's id. 42 and "42" are two keys.
  • ordered returns or throws what fn does. A call that fails does not hold up the next one.
  • The queue is in the server's memory; the data stays in the database. It holds on le.codes and under lecodes dev alike: one worker serves a project, and after a deploy the new worker takes its first call once the old one's calls have finished.

Two rules:

  • Keep the body short. Every other call with the key waits for it, and a call has 30 s. Read, check, write; a fetch to another server or long work goes before or after ordered.
  • No ordered of a key inside its own body. It would wait for itself, so it rejects: ordered("ABCD") inside its own body would wait for itself — call that code directly. Another key inside is fine; nest keys in the same order everywhere, or two calls that took them in opposite orders wait for each other until the 30 s cap.

Live updates from the server: channels

To push news from the server to the apps — a new post, a chat message, an order that changed — export a channel: the server publishes, every app that subscribed gets the message. An endpoint is a call from the app to the server; a channel is the other direction, typed by the same export.

TypeScript
// posts.server.ts
export type Post = { author: string, text: string }

export const postsChannel = channel<Post>()        // every app that subscribed hears every post

export async function sendPost(author: string, text: string) {
  const post = { author, text }
  postsChannel.publish(post)                        // to the apps subscribed right now
  return post
}
TypeScript
// main.ts
import { postsChannel, sendPost, type Post } from "./posts.server"

const feed = signal<Post[]>([])
let posts: ChannelSubscription | null = null

UIScreen(
  UIColumn(() => feed.value.map((p) => UIText(`${p.author}: ${p.text}`))).style({ gap: 8 }),
  UIButton(UIText("Post")).named("post").onClick(() => sendPost("Ann", "Hello, everyone")),
).style({ gap: 16, padding: 24 })
  .onOpen(() => {
    posts = postsChannel.subscribe((post) => { feed.value = [post, ...feed.value] })
  })
  .onClose(() => posts?.close())                    // the screen went away: stop listening
  .open()
TypeScript
channel<Message>()                         // server: export it from a *.server.ts
  .authorize(() => void)                   // who may listen
  .groupBy((...args) => string | number)   // which group a subscriber is in
ch.publish(message)                        // server: to every subscriber
ch.publish(group, message)                 // server: a channel with groupBy — to that group
ch.members([group]): Promise<number[]>     // server: who is subscribed now — see Who is here
ch.subscribe([...args,] handler, { reconnect?, error? }): ChannelSubscription   // app: { close() }
  • Name a channel somethingChannel: in the app it sits next to the data it carries.
  • A channel is server → app only. The app talks back through endpoints (sendPost above); publish in app code is a compile error.
  • A channel carries one type of message. Two kinds of news are two channels (or one message type that is a union).
  • A subscription lives until close(). Keep what subscribe answers as a ChannelSubscription.
  • publish from a channel that isn't exported throws.
Note

on the desktop host a channel reaches only a backend on your machine (lecodes dev, desktop run). A le.codes backend is https, so its socket is wss://, which the desktop host does not open: the subscription keeps retrying and no message arrives. Endpoint calls work there.

Each user's own updates, or one room's: groupBy

To send a message to some subscribers only — one chat room, one user's devices — give the channel a groupBy: it runs on the server for each subscription and answers the group that subscriber is in; publish(group, message) reaches that group.

TypeScript
// chat.server.ts
export type Message = { room: string, text: string }
const ROOMS = ["general", "random"]

export const chatChannel = channel<Message>()
  .groupBy(async (room: string) => {               // what the app passes to subscribe, checked as a string
    if (!ROOMS.includes(room)) throw new ApiError(404, "No such room")
    return room                                     // this subscriber's group
  })

export async function say(room: string, text: string) {
  if (!ROOMS.includes(room)) throw new ApiError(404, "No such room")
  chatChannel.publish(room, { room, text })         // only that room's subscribers get it
}
TypeScript
// main.ts
import { chatChannel, say } from "./chat.server"

const lines = signal<string[]>([])

const room = chatChannel.subscribe("general", (m) => { lines.value = [...lines.value, m.text] }, {
  error: (e) => { lines.value = [...lines.value, `refused (${e.status}): ${e.message}`] },
  reconnect: () => { lines.value = [...lines.value, "(reconnected — messages may have been missed)"] },
})

UIScreen(
  UIColumn(() => lines.value.map((t) => UIText(t))).style({ gap: 8 }),
  UIButton(UIText("Say hello")).named("say").onClick(() => say("general", "hello, room")),
).style({ gap: 16, padding: 24 }).open()

For "each their own", take nothing from the app and answer the caller's id — nobody can ask for someone else's:

TypeScript
// notices.server.ts
const User = model({ name: t.string().default("") })
const db = defineDb({ User }).withAuth({ model: "User" })

export type Notice = { text: string }

export const noticesChannel = channel<Notice>()     // each user hears only their own
  .groupBy(async () => (await db.auth.requireUser().select({ id: true })).id)   // a guest is refused (401)

export async function remindMe(text: string) {      // to every device the caller is signed in on
  const me = await db.auth.requireUser().select({ id: true })
  noticesChannel.publish(me.id, { text })
}
TypeScript
// main.ts
import { noticesChannel } from "./notices.server"

const notices = noticesChannel.subscribe((n) => toast(n.text), {
  error: (e) => { if (e.status === 401) console.log("signed out: no notices until the next sign-in") },
})
  • groupBy(fn) runs on the server for each subscription, with request and db.auth as in an endpoint. What the app passes to subscribe before the handler is what fn receives.
    • Those arguments come from the app: they are checked against the parameter types like an endpoint's (400 on a mismatch), so each parameter needs a type. Check that the caller may be in the group they ask for, and throw if not.
    • A group's value is told to its subscriber. Don't put a secret in it.
  • authorize(fn) runs the same way and only decides who may listen. Throw (ApiError) to refuse. It goes before groupBy.
  • A refusal goes to the error handler: an RpcError with the thrown status. It can come more than once (once per session that is refused). Without an error handler it is logged to the console. Nothing is delivered while the subscription is refused.
  • Each time the session changes (a sign-in, a sign-out) the server is asked again for every subscription, and the hooks run for the new user: noticesChannel above switches to the new account, is refused after a sign-out, and comes back by itself after the next sign-in.

Missed messages and reconnects

A channel delivers what is published while the app listens; nothing is kept for later.

  • publish delivers at most once, to the apps subscribed at that moment. Nothing is stored.
  • One WebSocket per backend carries every channel of the app. It opens with the first subscription and closes a few seconds after the last close(). When it drops, the app reconnects with back-off (1, 2, 5, 10, then every 30 s), subscribes again and calls each reconnect. Messages sent while it was down are lost — read the state again in reconnect (a resource's reload()). Meanwhile online reads false.
  • A socket that can't connect keeps retrying and does not call error.
  • In a build with no backend, subscribe throws RpcError (status 0) at once.

computed: the server's computed

To show state that lives on the server and changes while the app shows it — a room's players, a game's phase, an order's status — export a computed: a server function the runtime keeps fresh. The app subscribes and gets the value at once, then again each time the data the function read changes. Nothing to poll, nothing to publish, nothing to read again after a reconnect.

TypeScript
// game.server.ts
const Room = model({ code: t.string().unique(), phase: t.string().default("lobby") })
const Player = model({ room: t.string(), name: t.string(), device: t.int() })
const db = defineDb({ Room, Player })

export type RoomView = { phase: string, players: string[], seated: boolean }

export const roomView = computed(async (code: string): Promise<RoomView | null> => {
  const room = await db.room.where({ code }).first()
  if (!room) return null
  const players = await db.player.where({ room: code }).select({ name: true, device: true })
  return {
    phase: room.phase,
    players: players.map((p) => p.name),
    seated: players.some((p) => p.device === request.session),   // each subscriber's own answer
  }
})

export async function join(code: string, name: string) {
  await db.player.insert({ room: code, name, device: request.session! })   // every subscriber of the room hears it
}
TypeScript
// main.ts
import { join, roomView, type RoomView } from "./game.server"

const room = roomView.resource("ABCD")             // Loaded<RoomView | null>: loading, then every value the server sends

UIScreen(
  UIColumn(() => {
    const r = room.value                             // the screen follows it, as a resource's
    if (r.state === "loading") return [UIText("Loading…")]
    if (r.state === "failed") return [UIText(r.offline ? "No connection" : r.message), UIButton(UIText("Try again")).named("retry").onClick(() => room.reload())]
    if (!r.data) return [UIText("No such room")]
    return [UIText(`${r.data.phase}: ${r.data.players.join(", ")}`), UIButton(UIText("Join")).named("join").onClick(() => join("ABCD", "Ann"))]
  }).style({ gap: 16, padding: 24 }),
).onOpen(() => room.reload())                        // shown again after it was covered: follow again
  .onClose(() => room.close())                       // covered, popped: stop following
  .open()
TypeScript
computed(async (...args) => value)                              // server: export it from a *.server.ts
view(...args): Promise<Value>                                   // one call, like an endpoint
view.resource(...args): Resource<Value> & { close() }           // app: the Loaded value a screen draws, kept fresh
view.subscribe([...args,] handler, { error? }): ChannelSubscription   // app: the same as a callback
view.watchers(...args): Promise<number[]>                       // server: who is subscribed now — see Who is here
  • view.resource(...args) is a resource the server keeps fresh: value is loading until the first value, then ready with each value as the server sends it. Draw it as any resource (dataOf, failureOf, the three states). It is failed when the server refused it (offline when the backend was never reached); a failure after a value leaves the value. close() ends it and reload() subscribes again (what is shown stays until the answer; one still loading is already asked, so it does nothing): onClose(() => room.close()) and onOpen(() => room.reload()), since a screen that is covered gets onClose and onOpen again when it is popped back to — nothing listens for a screen that is not shown. For a value a screen does not draw, subscribe gives the same as a callback.
  • handler is called with the current value as soon as the server answers, then each time the value changes. A value equal to the last one (as JSON) is not delivered.
  • The function runs on the server in the subscriber's request: request.session and db.auth are that subscriber's, so one export gives every player their own view. A function that reads neither runs once for all its subscribers — see One run for everyone, or one each.
  • What the app passes before the handler is the function's arguments. They are checked against the parameter types like an endpoint's (400 on a mismatch), so each parameter needs a type.
  • Called (await roomView(code)), it is an endpoint call. Another server function may call it too; its reads are then that function's own.
  • It rides the channels' socket. When the socket drops and comes back, the app subscribes again and the handler hears the current value if it differs from the last one; a deploy or a restart of the backend runs every subscription again the same way. There is no reconnect: nothing is missed.
  • error hears a refusal — the first run threw: an RpcError with its status, asked again when the session changes — and a later run that failed: the last value stands, and the next change of its data runs it again. Without error both are logged to the console.
  • Name it after what it shows: roomView, orderStatus.

Two rules:

  • It only reads. A write inside (insert, update, delete, …) fails the run with status 500: computed game.server.ts#roomView: Player.insert is a write — a computed only reads (it runs again whenever its data changes); write in an endpoint. Change data in endpoints; every computed that read it follows.
  • Its value follows from its data and its arguments alone — and from who is subscribed, when it reads watchers / members. It runs again whenever its data changes, at any moment. Math.random(), Date.now() or a counter inside give a new value at every run. A deadline is data: store when it ends (endsAt) and let the app count down to it — see A step that ends on time.

How it differs from the app's computed:

  • The app's computed(() => …) follows signals and is read with .value; the server's follows the database and is subscribed to.
  • The server's takes arguments, and its function is async: a call answers a promise.
  • It lives as long as its subscription: resource and subscribe answer { close() }. Close it when the screen goes.

A channel stays the tool for what is not state: a toast, a chat line, "the round is over" said once.

One run for everyone, or one each

How often a computed runs depends on what it read, and the runtime sees it by itself — there is nothing to declare. A run that read nothing of the request (no request.session, request.headers, request.ip, request.id, no db.auth) has a value that follows from its arguments and the data alone, the same for every subscriber with those arguments. So the subscribers of one export with one set of arguments share it: it runs once per change, and each of them gets that value. A run that read the request is its subscriber's own: it runs once per change for each subscriber. It is decided at every run, so a branch that starts reading request.session when the data changes makes the runs per subscriber from then on, and they are shared again when it stops. (Each subscription's first run is its own: it is the answer to that subscribe.)

roomView above reads request.session for seated, so every change of the room runs it once per player. Split such a view in two: the room's part, the same for everyone, and each player's own, which reads only that player's rows:

TypeScript
// game.server.ts
export const roomView = computed(async (code: string) => {   // shared: one run per change of the room
  const room = await db.room.where({ code }).first()
  if (!room) return null
  const players = await db.player.where({ room: code }).select({ name: true })
  return { phase: room.phase, players: players.map((p) => p.name) }
})

export const myView = computed(async (code: string) => {     // each player's own: it reads request.session
  const me = await db.player.where({ room: code, device: request.session! }).first()
  return { seated: me !== null, name: me?.name ?? null }
})
TypeScript
// main.ts — two subscriptions, one screen
const subs = [
  roomView.subscribe(code, (view) => { room.value = view }),
  myView.subscribe(code, (view) => { mine.value = view }),
]

A player joining runs roomView once for the whole room, and myView only for that player: the others' myView read rows the write did not touch.

The two values come on their own. A write that moves the room on runs both, and each is sent when its run ends, in either order: for a moment the app holds the room's new step and the player's part of the old one — last round's answer under the new picture. Put a marker of the step in both, read from the same row, and show the room only when the two agree. The marker must change at every step and at every game — a new game starts on the same phase and step as the last one did: { game, phase, step }.

TypeScript
// game.server.ts
const Room = model({ code: t.string().unique(), game: t.int().default(0), phase: t.string().default("lobby"), step: t.int().default(0) })
const Player = model({ room: t.string(), device: t.int(), name: t.string(), answer: t.string().optional() })
const db = defineDb({ Room, Player })

export type At = { game: number, phase: string, step: number }    // where the room is
export type Shared = At & { players: string[] }
export type Mine = At & { answer: string | null }

export const roomView = computed(async (code: string): Promise<Shared | null> => {
  const room = await db.room.where({ code }).first()
  if (!room) return null
  const players = await db.player.where({ room: code }).select({ name: true })
  return { game: room.game, phase: room.phase, step: room.step, players: players.map((p) => p.name) }
})

export const myView = computed(async (code: string): Promise<Mine | null> => {
  const room = await db.room.where({ code }).first()
  if (!room) return null
  const me = await db.player.where({ room: code, device: request.session! }).first()
  return { game: room.game, phase: room.phase, step: room.step, answer: me?.answer ?? null }
})
TypeScript
// main.ts — the room is shown when both speak of one step
import { myView, roomView, type At, type Mine, type Shared } from "./game.server"

const same = (a: At, b: At) => a.game === b.game && a.phase === b.phase && a.step === b.step
const room = signal<(Shared & Mine) | null>(null)
let shared: Shared | null = null, mine: Mine | null = null
const pair = () => {
  if (!shared || !mine || !same(shared, mine)) return   // one is a step ahead: wait for the other
  room.value = { ...shared, ...mine }
}
const subs = [
  roomView.subscribe("ABCD", (v) => { shared = v; pair() }),
  myView.subscribe("ABCD", (v) => { mine = v; pair() }),
]

A move of several rows: one $transaction

A computed runs again at the first commit that touches what it read; it does not wait for the endpoint to finish. An endpoint that ends a round in several writes — the phase, then each player's score — can be seen between two of them: the answer on screen with the old scores. ordered does not prevent it: it keeps the writers of a key apart, and a computed is not a writer. Put the writes that belong together in one db.$transaction([...]): it is one commit, and every subscriber sees all of it or none of it.

TypeScript
// game.server.ts
const Room = model({ code: t.string().unique(), phase: t.string().default("vote") })
const Player = model({ room: t.string(), score: t.int().default(0), right: t.bool().default(false) })
const db = defineDb({ Room, Player })

export async function endRound(code: string) {
  await ordered(code, async () => {
    const room = await db.room.where({ code }).first()
    if (!room || room.phase !== "vote") return
    const right = await db.player.where({ room: code, right: true }).select({ id: true })
    await db.$transaction([                        // one commit: no view shows "reveal" with the old scores
      db.room.update(room.id, { phase: "reveal" }),
      ...right.map((p) => db.player.update(p.id, { score: { $increment: 100 } })),
    ])
  })
}

A step that ends on time: the app calls at the deadline

The backend has no timer to end a step with: its worker stops when no call comes, and a setTimeout stops with it. A deadline is data — when the step ends, stored in its row — and moving on is a write, which a call makes. The apps make it: each counts down to the deadline and calls an endpoint when it comes. Every app calls; under ordered the first call moves the step on, and the others find it moved.

TypeScript
// game.server.ts
const Room = model({ code: t.string().unique(), phase: t.string().default("draw"), endsAt: t.date().optional() })
const db = defineDb({ Room })
const GRACE = 2000                                    // an answer sent as the time ran out still counts

export const roomView = computed(async (code: string) => await db.room.where({ code }).first())

export async function serverTime() { return Date.now() }   // the devices' clocks differ: count by the server's

export async function tick(code: string) {            // what the apps call at the deadline
  await ordered(code, async () => {
    const room = await db.room.where({ code }).first()
    if (!room || room.endsAt === null || Date.now() < room.endsAt + GRACE) return   // not over yet, or moved on
    await db.room.update(room.id, { phase: "vote", endsAt: Date.now() + 30_000 })
  })
}
TypeScript
// main.ts
import { roomView, serverTime, tick } from "./game.server"

let offset = 0                                        // the server's clock minus this device's, ms
const sent = Date.now()
serverTime().then((at) => { offset = at - (sent + Date.now()) / 2 })   // it answered halfway through the round trip

let wake = 0
const live = roomView.subscribe("ABCD", (r) => {
  clearTimeout(wake)
  if (r?.endsAt) wake = setTimeout(() => tick("ABCD"), Math.max(0, r.endsAt + 2000 + 200 - (Date.now() + offset)))
})
  • Ask the server's time once, when the room opens, not before every countdown.
  • A device whose clock runs a little ahead calls early and the step stays: while the room still shows that step, call again a little later.
  • The same endpoint moves a step that waits for nobody any more — see Who is here: a player who goes away is not a write.

Who is here: watchers and members

To know who has a room open right now — to grey out a player whose phone dropped, to pass the host on — ask who is subscribed. A subscription is presence: roomView.watchers(code) answers the sessions subscribed to roomView with those arguments, roomChannel.members(code) the sessions subscribed to that group of the channel. Nothing to write when a player connects, no heartbeat, no "last seen" column.

TypeScript
// game.server.ts
const Player = model({ room: t.string(), name: t.string(), device: t.int() })
const db = defineDb({ Player })

export type RoomView = { players: { name: string, away: boolean }[], host: string | null }

export const roomView = computed(async (code: string): Promise<RoomView> => {
  const here = await roomView.watchers(code)              // the devices that have this room open now
  const players = await db.player.where({ room: code }).select({ name: true, device: true })
  const host = players.find((p) => here.includes(p.device)) ?? players[0]   // computed, never stored
  return {
    players: players.map((p) => ({ name: p.name, away: !here.includes(p.device) })),
    host: host?.name ?? null,
  }
})

export async function join(code: string, name: string) {
  await db.player.insert({ room: code, name, device: request.session! })
}

export const roomChannel = channel<string>().groupBy((code: string) => code)

export async function say(code: string, text: string) {
  const listening = await roomChannel.members(code)       // in any endpoint
  if (listening.length < 2) throw new ApiError(409, "Nobody else is in the room")
  roomChannel.publish(code, text)
}
TypeScript
// main.ts — subscribing is being here
const live = roomView.subscribe(code, (view) => { room.value = view })
TypeScript
view.watchers(...args): Promise<number[]>   // server: the sessions subscribed to the computed with these arguments
ch.members(): Promise<number[]>             // server: the sessions subscribed to a channel without groups
ch.members(group): Promise<number[]>        // server: the sessions subscribed to that group
  • The answer is request.session numbers, each once: a device with two screens, or two sockets, on one room is one entry. Compare them with the request.session your rows store (device above).
  • watchers matches the arguments the app passed to subscribe as JSON: watchers("7") does not see subscribe(7, …). A trailing undefined is left out on both sides.
  • It is a read, not a hook. Nothing of yours runs when a device comes or goes — except a computed that read it: there watchers and members are inputs like its database reads, and a device that comes or goes runs it again (a value that did not change is not sent). An endpoint gets the answer of the moment it asks.
  • A player who goes away is not a write. A step that waits for everyone present ("on once all have voted") does not move on by itself when the only one not done goes away: no endpoint runs, and the computed only shows them away. The app moves it: when the room it shows has everyone not done away, it calls the endpoint that moves the step — the same one it calls at a deadline — which reads watchers and finds nobody left to wait for.
  • A subscriber is in its own first value: the player who just opened roomView sees themselves here.
  • A leave counts after 5 s. A subscription that ends — close(), a socket that drops — keeps its session listed for 5 s, and the session stays if one of its subscriptions to the same room comes back meanwhile: a phone switching from Wi-Fi to LTE does not flicker away. A device that comes counts at once.
  • Present means "subscribed now", not "signed in": a device that closed the screen or the app is not listed, whoever is signed in on it. A device that has no session yet is not listed either: without sign-in, a device gets its request.session with the first call or hook that reads it (join above).
  • Leaving a room is yours to write: an endpoint that deletes the player's row. Presence only says who is looking now; it stores nothing and calls nothing.
  • The list is kept in the backend's memory, beside the subscriptions: a deploy and a restart of the server code keep it.
  • In the app, watchers and members throw RpcError (status 0), as publish does: read them in a server function.
  • A computed that reads its own watchers needs its result type written (: Promise<RoomView> above): TypeScript cannot infer a value that is read from itself.

Is the backend reachable: online

To tell the player that the app cannot reach its server right now — a banner over the game, a note by the send button — read online, a global of the app: true while the app reaches its backend, false while it does not.

TypeScript
// main.ts
const noConnection = UIText("No connection — trying again…")
  .named("offline")
  .style({ display: () => (online.value ? "none" : "flex"), bgColor: "#b3261e", color: "#ffffff", padding: 8 })

UIScreen(UIColumn(noConnection, UIText("Room ABCD"))).open()
TypeScript
online.value: boolean     // app: does the app reach its backend now — followed in a binding, a computed, an effect
online.peek(): boolean    // the same, read without following it
  • It is true from the start, until the app learns otherwise.
  • It turns false when the channel socket drops or cannot connect while the app is subscribed (it keeps trying), and when a call fails without reaching the backend: an RpcError with status 0.
  • It turns true again when the socket opens, a message comes over it, or any call is answered — with an error too: a 404 or a 409 came from the backend.
  • It changes only when the app talks to its backend. A socket the app closes (its last subscription closed) changes nothing, and with nothing subscribed and no call made it keeps what it last learned. Calls are not held while it is false: each one tries, and one that is answered turns it true.
  • It is one value for the app: every channel and computed rides one socket per backend, and the calls go to the same backend. With several backends it is true while every one of them is reached.
  • The transport sets it; the app only reads it (online.value = … is a type error).
  • In a build with no backend nothing is reached and nothing is learned: it stays true, and every call fails with status 0 (Where the backend runs).

What it is not:

  • Not the device's network. device.online is the system's hint about the network; online is whether this app reaches its own backend. A phone on Wi-Fi can be out of its backend's reach (a captive portal, a server that is down), which the system does not know.
  • Not "the data is old". A computed subscribes again by itself when the socket is back and delivers the current value if it changed: there is nothing to read again on true. A channel's messages published meanwhile are lost — that is its reconnect.

Reach the user while the app is closed: push channels

A channel delivers to an app that is open. A push channel reaches the user's phone when it is not: the same shape — one export of a *.server.ts file, send(user, message) on the server, onTap / onMessage in the app — over the push notifications of iOS and Android (Push).

TypeScript
export const orderShippedPushChannel = pushChannel<{ orderId: number }>()        // pushes.server.ts
await orderShippedPushChannel.send(order.owner, { title: "Order shipped", data: { orderId } })   // server
orderShippedPushChannel.onTap(({ data }) => Router.push(OrderScreen(data.orderId)))             // app

A user's devices are the ones they are signed in on; the permission is asked after the sign-in, by itself. send in the app is a compile error, like publish on a channel.

Server-only exports

An export that is neither an endpoint nor a channel (nor a push channel) stays on the server. In the app it becomes a placeholder, and any use of it throws RpcError with status 0 (dice.server.ts#PAGE is server-only — it can't be used in client code): reading a property, calling it, or converting it to a string or number. await on it does not throw. Keep constants the app needs in an ordinary file that both sides import.

Server code: its own globals, no app SDK

Code in a *.server.ts file has its own set of globals and runs on Bun, not in the app's runtime.

  • Server files get their own globals:
    • ApiError, channel, computed, request and ordered, documented on this page. computed is a global of the app too: in the app it follows signals, in a server file the database;
    • defineDb, model, t, ref — the database. Sign-in is not a global: it is db.auth of a database made with defineDb({...}).withAuth({ model: "User" }) — see Sign-in.
  • The app SDK is not there. Vec3, date, UIText, toast, Net and the rest are app globals. The editor's types know both sets in every file, so one used in a server file type-checks — and the build refuses it: blog.server.ts:25: toast is a global of the app — it does not exist in server code.
  • It works the other way round too: a server global in app code (new ApiError(…), model({…})) fails the build the same way. The app catches a server's error as RpcError.
  • A name your file declares itself (const t = …, a parameter request) is yours and is never refused. Types are not either: function f(at: Vec3) in a server file builds.
  • Server code runs on Bun, so JavaScript's standard globals are there (Date, JSON, crypto, timers, fetch).
    • That fetch is the standard one: its body reads return promises, so write await res.json().
    • The project's types describe the app SDK's fetch, whose res.json() is synchronous, so the missing await is not caught.
  • Module-level variables are not storage. Each project's server runs in a worker that is replaced on every deploy, stopped after 15 idle minutes and restarted when a call times out. Keep data in the database. A timer is not a scheduler either: it stops with the worker.
  • console.* output and unexpected errors (with their stack) go to the server's log. The app only sees Internal error.

Where the backend runs

An app reaches the backend whose URL its build carries; which backend that is depends on where the app was built.

On le.codes: the preview's backend and the published app's

  • A build on le.codes bakes the backend's URL into the stubs and deploys the server files with it. A project has two backends, each with its own database and stored files:
    • development — the editor's preview, the project link on a phone and the Data tab. Every compile of the project's current code deploys to it;
    • production — the published app: its web page, its shells' over-the-air updates, and the le.codes viewer app when it opens the published project. Only a publish (or a switch to an older release) deploys to it; its database holds what the app's users wrote.
  • A schema change that deletes data (a field or a model removed) waits for the author's confirmation: the editor asks, lecodes publish asks in the terminal (--allow-destructive applies it without asking).
  • A change the database can't take in place (a field that changes its type) is refused:
    • in the editor, until the development database is reset — its rows and files are deleted;
    • on a publish, outright: nothing changes, and the published app keeps its server and its data. The production database has no reset: change the models so the database can take the change instead (a new field under a new name — see Database).
  • A project whose database has sign-in (withAuth) also gets a device session. The transport stores its token per backend and sends it with every call and channel, and app code never handles it. A sign-in in the preview is not a sign-in in the published app.

On your machine: lecodes dev and lecodes web dev

The dev server runs the server files itself and the app it serves calls them — on a phone, in the desktop host and in the browser alike:

  • the database is a folder of the project, .lecodes/db; it stays between runs. Delete the folder to start empty;
  • saving a server file restarts the server with the new code before the app reloads. The data stays. A change of models the database can't take in place starts an empty database and moves the old one to .lecodes/db-old (its stored files to .lecodes/files-old);
  • console.* output and errors of server code print in the terminal as [server:log] …;
  • an email sign-in code is printed in the terminal instead of being mailed, and 000000 signs any email in with no code sent;
  • the first run of a project with models asks to install the database engine (marcidb-embedded), once;
  • server code runs on the runtime the CLI runs on (Node for the npm install), not on Bun: keep to the standard globals;
  • it is the project's one backend on this machine: the other commands talk to it while it runs (below). A lecodes web dev started beside it — or a second lecodes dev --port … — runs no backend of its own: its calls and sockets are forwarded to the first one's.

In local runs and tests: desktop run, render, call, test

One rule: while lecodes dev runs, the other commands talk to it. A project has one backend on your machine. While a lecodes dev of the project runs, render (headless, --desktop, --sim), desktop run, lecodes call and lecodes web dev use ITS backend over HTTP — its database, its data, the room you have open on the phone — instead of opening .lecodes/db (the database engine lets one process hold it). They find it through .lecodes/dev.json (the dev token and the port the dev server listens on); the command says so: The backend: the running lecodes dev's (port 4499). When no dev runs, each of them runs the server files itself for as long as it runs, on the same .lecodes/db (lecodes call: on the test database below). And:

  • the data stays: a render against the dev backend sees what you made on the phone. render --fresh empties the database first (the running dev's, else .lecodes/db) — a scripted scenario that wants a clean start says so;
  • the dev backend's clock is your devices': a render --script beside a running dev runs on real time — a wait waits, a clock step is refused;
  • test is the exception: it ALWAYS runs a backend of its own, on .lecodes/test-db, emptied before every case — a test never sees or changes the data of lecodes dev, running or not;
  • when the database is held but no dev answers where .lecodes/dev.json says (another desktop run, a dev that hangs), the command stops and says so — it never runs without its backend;
  • a step of a flow waits for the calls it started (5 s at most, 8 s when it draws pixels): after { "tap": "send" } the answer is in, no wait is needed. What the backend sends on its own — a channel's message, a computed's new value — is waited for by the expect that reads it: an expect waits until it holds (timeout, 5 s by default).

Testing a backend app: several clients, calls, one clock

Test an app with a backend against its real backend — not with fixtures. A flow runs several clients of the app at once, each with its own storage and session, against the one test backend:

JSON
{ "clients": { "ann": {}, "bob": {} },
  "steps": [
    { "client": "ann", "tap": "create", "expect": { "text": "Код комнаты" }, "save": { "code": "room-code" } },
    { "client": "bob", "type": "code", "text": "${code}" },
    { "client": "bob", "tap": "join", "expect": { "text": "2 из 8" } },
    { "client": "ann", "tap": "start" },
    { "clients": "*", "expect": { "node": "pad" } },
    { "clock": "+93s" },
    { "clients": "*", "expect": { "text": "Что это?" } },
    { "call": "game.server.ts#joinRoom", "as": "late", "args": ["${code}", "Ева"], "expect": { "error": { "status": 409 } } }
  ] }
  • Every step names its clients (client, clients, "*"); a step on several runs on them at once. What one client writes reaches the others the way it does on phones: a computed re-runs, its new value comes over each one's socket, and the expect that reads it waits for it.
  • A case has one clock. The apps' Date.now() and the server's move together: a wait moves both, { "clock": "+93s" } jumps both at once. A deadline the server stored is passed by a jump of its length — the apps' timers due meanwhile fire, they call tick, the server finds the step over. The server's clock also runs in real time between steps (it is ahead by the time the run itself takes): jump a deadline's length plus a margin, and let the next expect wait for the move.
  • call calls a function as a client — with that client's session, so request.session is that player — or as a name no client has: a device of its own, with no UI. "as": ["g1", "g2", …] calls once per name, all at once — a rush on ordered code: "expect": { "ok": 7, "error": { "status": 409, "count": 2 } }. A file of only call steps starts no app: a test of the server alone.
  • { "client": "bob", "offline": true } cuts bob's network (his calls fail with status 0, his socket drops, online turns false, the others see him leave after the grace); { "restart": "bob" } starts his app again on the same storage — his session token too, so he is the same device.
  • lecodes call game.server.ts#joinRoom '["1234", "Боб"]' --as bob calls one function from the terminal: of a running lecodes dev's backend, else of the test backend (its database is the tests', kept between calls); --reset empties the database it calls.
  • { "clients": "*", "close": true } ends the step's clients (their apps disposed, their sockets closed: the others see them leave after the grace); { "restart": "bob" } opens a closed one again.
  • Fixtures ("fixtures", a server function by its id: "game.server.ts#roomView") answer CALLS in a headless run, with the RPC envelope as the body ({ "json": { "ok": true, "result": … } }); a computed subscription goes over the socket to the real backend and can't be mocked. Keep them for apps whose backend is someone else's.

Playing with bots: lecodes dev --bots

A multiplayer app needs players. lecodes dev --bots tests/bots.flow.json adds them: the flow's clients join as headless players on the dev backend — the same backend as your phone, which stays a live player among them:

JSON
{ "vars": ["code"],
  "clients": { "bob": {}, "eve": {} },
  "steps": [
    { "clients": "*", "type": "code", "text": "${code}" },
    { "clients": "*", "tap": "join" },
    { "clients": "*", "expect": { "text": "Фаза 1" }, "timeout": 600000 },
    { "clients": "*", "tap": "submit-drawing" }
  ] }
TypeScript
lecodes dev --bots tests/bots.flow.json --var code=4821     # the room you made on the phone
  • --var code=4821 (several: --var a=1,b=2) sets ${code} before the flow runs; a flow lists the names it takes in "vars" — lecodes test does not run such a file, --bots refuses to start without them;
  • the flow runs on REAL time: nothing may move your phone's clock, so a clock step is refused, a wait waits, and every bot's clock follows the machine's. Wait for the human with an expect and a long timeout;
  • the bots start once the first compile is in, run the flow once, and stay in the game — subscribed, their timers alive — until Ctrl+C, unless the flow ends with { "clients": "*", "close": true };
  • every step is told in the terminal ([bots] ✓ …); a failing one is told with what the bot saw (its frame under the flow's .artifacts) and the next step runs — you are mid-game;
  • the bots run the app as it was when they started: a save reloads your phone, not them.

A room made on the phone before the bots exist: restart lecodes dev with --bots (the database and the phone's session stay), or start a second one beside it, lecodes dev --port 4500 --bots … — a second dev server of the project forwards to the first one's backend.

The limits

Every backend — on le.codes and under lecodes dev alike — limits how often one device knocks:

what per rate burst
calls of one endpoint device (its session token, or its address before it has one) 20 a second 40
subscriptions (channels and computeds) device 10 a second 20

Past the limit a call fails with RpcError status 429, Too many calls, and a subscription is refused with the same status. The limits are the same for every project for now. An app that stays under them does nothing; a loop that calls an endpoint every frame does not.

Builds with no backend: compile, web build, app sync, app build desktop

lecodes compile, lecodes web build, lecodes app sync (the app.js an iOS or Android shell carries) and lecodes app build desktop build the app with no backend URL:

  • the stubs are still generated and the app still builds;
  • every endpoint call rejects with RpcError status 0: Endpoint dice.server.ts#roll: the project has no deployed server (compile with serverUrl);
  • subscribe throws the same error;
  • a shell runs that bundle until its first over-the-air update — the published app's bundle, built with the production backend — is downloaded. The first launch of an installed build waits for it (a few seconds at most) and runs it at once; a later update runs from the next launch.

Calling server functions

Import a server function from its *.server.ts file and use the public API. Build tools prepare the connection to the server; there is no need to create transport helpers manually.

Pitfalls

TypeScript
export function add(a: number, b: number) { … }          // ✗ compile error: an endpoint is async
export async function add(a: number, b: number) { … }    // ✓

const n = add(1, 2)                 // ✗ a promise
const n = await add(1, 2)           // ✓

postsChannel.publish(post)          // ✗ in app code — compile error: the server publishes
await sendPost(author, text)        // ✓ an endpoint that publishes

setInterval(() => roomView(code).then(show), 2000)   // ✗ polling
roomView.subscribe(code, show)                       // ✓ the value when it changes

setInterval(() => ping(code), 2000)                  // ✗ a heartbeat, a seenAt column
const here = await roomView.watchers(code)           // ✓ server: who is subscribed now

if (e.status === 0) setTimeout(probe, 3000)          // ✗ calling now and then to learn the server is back
display: () => (online.value ? "none" : "flex")      // ✓ the transport says it: `online`

See also

  • Database — models and queries in server code
  • Sign-in — accounts, db.auth
  • Stored files — File parameters and t.file() fields
  • Multiplayer — real-time sessions between app instances
  • Network — fetch and WebSocket to other web servers
  • Storage — localStorage on the device