Skip to content
DocspackagesDocumentation

@lunora/client

Framework-agnostic browser/edge client.

PackagesClient

@lunora/client is the framework-agnostic SDK. React, Vue, Solid and Svelte adapters wrap it. You only depend on it directly when writing a custom adapter or driving Lunora from a Node/Bun script.

import { LunoraClient } from "lunorash/client";

import { api } from "@/lunora/_generated/api";

const client = new LunoraClient({ url: "https://app.example.workers.dev" });

const messages = await client.query(api.messages.list, { channelId: "general" });
await client.mutation(api.messages.send, { channelId: "general", text: "hi" });

// Live subscription — returns an unsubscribe function.
const unsubscribe = client.subscribe(api.messages.list, { channelId: "general" }, (next) => {
    console.log("new value", next);
});

Wire protocol

  • Queries / mutations / actions: POST /_lunora/rpc, JSON body { functionPath, args, shardKey? }. Response: { result } or { error }.
  • Subscriptions: single multiplexed WebSocket at /_lunora/ws. The client sends connect / subscribe / shape_subscribe / unsubscribe / stream / whisper frames; the server pushes ack, data, delta, resume, settled, chunk, error, complete and whisper frames back, each tagged with the originating subscription id. The normative frame table is protocol/README.md §5.

Supported value types

The wire is JSON, but a tagged codec carries the value kinds JSON can't, so args and results round-trip losslessly across RPC, streams, whispers, and batches:

  • bigint, ArrayBuffer + typed-array views (v.bytes()), Date, NaN/±Infinity, and undefined in array positions.
  • Map, Set, URL, and Error (including its cause chain), reachable via a v.any() field, whisper data, an action's return, or a LunoraError's data.

A pure-JSON payload encodes byte-identically, so this is transparent and back-compatible. A value a stable form can't represent is rejected at the send site (never silently corrupted): a RegExp, Headers, or any class instance throws a TypeError, and anything nested deeper than 64 levels throws a RangeError. An over-long bigint (more than 1024 digits) is rejected with a RangeError on both the encode and decode sides, so the sender sees it at the call site.

Cache-keyed args included. A subscription / useQuery / shape arg doubles as the reactive cache key: it is keyed on its wire form (stableWireKey), so bigint, bytes, Date, Map, Set, and URL args subscribe, dedup, and re-execute with their real values, and two subscriptions whose args differ only by such a value get distinct keys. Two caveats: Map/Set args key by insertion order (two equal Maps built in different orders open separate subscriptions, so prefer plain objects), and a URL arg is best passed as url.href (the server stores each subscription in its socket attachment, and a failure there surfaces as a structured SUBSCRIPTION_PERSIST_FAILED error). Values the wire refuses (RegExp, class instances, …) still fail loud with a TypeError at the call site, and over-deep nesting with a RangeError.

Reconnect & bookmarks

Reconnect uses exponential backoff with equal jitter (reconnect option): the delay doubles per attempt from initialDelayMs (default 250 ms) up to maxDelayMs (default 30 s), and each attempt then picks uniformly from [delay/2, delay] (jitter, on by default). The client keeps a per-session monotonic bookmark in BookmarkStorage (in-memory by default), sent on the x-d1-bookmark request header of each HTTP RPC and refreshed from the response, so D1 reads are read-your-writes consistent across replicas. When a durable queryCache is configured, a re-subscribe also carries the last sinceSeq / sinceEpoch cursor so the server can resume from where the cache left off instead of re-sending a full snapshot.

Offline queue

Mutations issued while disconnected land in OfflineQueue, a bounded FIFO (default maxItems: 1000, oldest rejected with OFFLINE_QUEUE_OVERFLOW on overflow). They replay in submission order once the socket reconnects. Each mutation carries a stable idempotency id, so a write that committed before the client lost the ack is deduplicated by the server on replay rather than applied twice. On reconnect the replay coalesces the queued writes for a shard into batched round trips (one /_lunora/rpc-batch request per chunk of up to 500 writes, split smaller when a body would exceed 1 MiB) instead of one request per write: a flaky reconnect with a full outbox flushes in a handful of round trips, not hundreds. In a browser that has indexedDB, the queue persists to IndexedDB by default. Pass persistence: false to keep it in memory, or pass an adapter to choose the store:

import { LunoraClient, createIndexedDbPersistence, createAsyncStoragePersistence } from "lunorash/client";

// Browser:
new LunoraClient({ url, persistence: createIndexedDbPersistence() });

// React Native / Expo (any async key/value store):
import AsyncStorage from "@react-native-async-storage/async-storage";
new LunoraClient({ url, persistence: createAsyncStoragePersistence({ storage: AsyncStorage }) });

A queued write that is replayed after a reload (or evicted on overflow, or discarded on an identity change) has no live mutation() Promise left to reject, so its rolled-back optimistic row would vanish silently. Subscribe to onMutationSettled for a durable, per-write terminal verdict (committed / rejected, with hadAwaiter: false for those orphaned replays) and surface the rejection in your UI:

client.onMutationSettled((event) => {
    if (event.status === "rejected") {
        toast.error(`Couldn't save your change (${event.code ?? "error"}).`);
    }
});

See Offline-first for the full reads + writes story.

Optimistic updates

client.mutation(fn, args, { optimisticUpdate }) patches subscribed queries immediately, then reconciles them gaplessly: each patch is recorded as a rebaseable layer, so an unrelated server delta that lands while the write is still pending is re-folded under it (your change never flickers away and back), and the layer is dropped the moment a server frame whose cursor reaches the write's committed cursor arrives. The server echoes that cursor on the mutation response, so the drop is keyed on confirmed server state, not RPC-response timing (which races the WebSocket broadcast). A coded rejection rolls every layer of the batch back atomically.

The callback receives an OptimisticLocalStore over the live cache plus the mutation's args, and names the queries it patches — which it has to: a write and the queries it affects are different functions, and no client can infer which ones a messages:send changes.

await client.mutation(
    api.messages.send,
    { channelId, text },
    {
        optimisticUpdate: (store, args) => {
            const current = store.getQuery(api.messages.list, { channelId: args.channelId }) ?? [];

            store.setQuery(api.messages.list, { channelId: args.channelId }, [...current, draft]);
        },
    },
);

getAllQueries(fn) patches every subscribed variant of a query (all channels, all filters) when you don't want to enumerate their args.

There is also a per-call optimistic: (current) => next shortcut, and its targeting rule is narrow enough to be worth stating: it patches the subscription registered under the mutation's own reference and args, and silently finds nothing otherwise. That makes it the shorthand for a query and a mutation that share a path (a counter, a document by id) — for anything else, including the send/list shape above, use optimisticUpdate. See Offline-first for the full reconciliation model.

Actions

client.action(fn, args, { shardKey }) invokes an action over the same POST /_lunora/rpc transport as a query or mutation, and resolves with the server value (rejects on failure). It takes no optimistic options: an optimistic update patches the subscription cache on the assumption a write will land, and an action is not a write — it runs in the Worker, may call a third party, and has no declared effect on any query.

const result = await client.action(api.commands.run, { command: "lunora", args: ["verify"] });

The shared call runner

createCallRunner(invoke, sinks) is the half of an adapter's write primitive that isn't framework-specific — it backs both the mutate of useMutation/createMutation/mutation and the call of useAction/createAction/action, in every adapter. It ref-counts overlapping invocations into sinks.setPending (so the flag clears only once the last settles), normalizes a thrown non-Error, and routes success/failure to setResult / setError before re-throwing the same instance.

data and error track the latest invocation rather than the last to settle: each call takes a monotonic token and writes the value sinks only while it is still the most recent one, so a double-click whose first call resolves after the second cannot leave the UI showing the first one's result — or an error for a call that succeeded.

invoke is a pre-bound thunk, which is what lets one runner serve both procedure kinds: the runner forwards options without ever inspecting them, so the option type is inferred from the closure. What keeps optimisticUpdate off an action is the adapter's exported handle type, not this runner.

import { createCallRunner } from "@lunora/client";

const call = createCallRunner((args, options) => client.action(api.commands.run, args, options), {
    setError: (error) => {
        /* your framework's error sink */
    },
    setPending: (pending) => {
        /* your framework's pending sink */
    },
    setResult: (result) => {
        /* your framework's value sink */
    },
});

The adapters that use it agree on one lifecycle contract: a success clears error, a failure leaves the previous data in place (a transient error does not blank the view), and reset() clears both without cancelling an in-flight call — a call that settles after a reset repopulates.

React's useMutation is the exception. It is TanStack Query's useMutation with a ref-counted pending on top, not this runner, so data and error follow TanStack's reducer: data is cleared when a call starts and when one fails. A component that renders the previous data as a fallback during a retry keeps it on Vue/Solid/Svelte and blanks on React — hold the last value yourself if you need it on both. useAction and every other adapter's mutation/action handle are runner-backed and follow the contract above.

You only reach for it when writing a custom adapter; app code uses the adapter primitive for its framework.

Shape subscriptions

subscribeShape is the local-first sync engine's parallel to subscribe: it replicates a partial view of a table (a shape) over the poke diff protocol instead of re-running a query:

const unsubscribe = client.subscribeShape({ name: "messagesByChannel", args: { channelId: "general" } }, (rows) => console.log("current shape rows", rows), {
    onError: (e) => console.error(e),
});

You send the shape name + validated args (never a where the client could forge); the server seeds the current membership as an insert-poke and streams live membership diffs, materializing the rowset into callback on each applied poke. Unlike subscribe, shape subscriptions are not deduped by (name, args): the server resolves each under the socket's verified identity, so every call gets its own view. Pass { shardKey } to route a sharded shape to its DO.

Most apps don't call this directly; @lunora/db's lunoraCollectionOptions({ shape }) wires it into a TanStack DB collection.

Auth

client.setAuthToken(jwt) stamps an Authorization: Bearer <jwt> header on every HTTP RPC and clears the in-memory offline queue's writes from the previous identity. It does not touch the WebSocket: a socket keeps the session credential it connected with, which is sent in its connect frame, not the URL. To rotate live WS auth call client.setWsToken(token), which closes the open shard sockets so they reconnect with the new credential.

getCurrentUser() resolves the signed-in user from better-auth's get-session route (returns null when signed out), and onAuthTokenChange fires whenever the bearer changes. The @lunora/client/auth subpath wraps these into a shared per-client identity store (single in-flight fetch, fan-out to every mounted hook) that the framework adapters consume.

Auth status

The store resolves to one of four states, exposed as status by every adapter's auth primitive (useAuth, createAuth, auth). Branch on status, never on whether user is null — user is null both when signed out and when a held credential's identity has not resolved (or could not be reached), and gating on it renders a sign-in form to a signed-in user.

StatusMeaningGate
loadingthe first identity resolve is in flightloading
authenticatedthe server returned a userauthenticated
unauthenticatedthe server answered that there is no sessionsigned out
unreachablea credential is held but the identity endpoint could not be reachedauthenticated

unreachable counts as authenticated because the credential is what authorizes requests; a failed identity round-trip is a fact about the network, not about the session. A cookie session carries no bearer token at all, so the first resolve always asks the server — a null token is not an answer.

SSR preloading

@lunora/client/ssr runs a query once on the server and captures the result in a serializable Preloaded token. Embed the token in the rendered HTML and hand it to usePreloadedQuery on the client: the first render shows the server value with no loading flash, then a live subscription takes over. The SSR client only needs a fetch that can reach the worker, and no in-process Durable Object access.

import { createServerClient, preloadQuery, serializePreloaded } from "lunorash/client/ssr";

import { api } from "@/lunora/_generated/api";

const client = createServerClient({ url: "https://app.example.workers.dev" });
const preloaded = await preloadQuery(client, api.messages.list, { channelId: "general" });

// Embed `serializePreloaded(preloaded)` in HTML; rehydrate with usePreloadedQuery on the client.

API

LunoraClientOptions

Type: interface. The options object for new LunoraClient(). url is the only required field. These fields set the defaults the client uses:

  • reconnect: backoff for the WebSocket. Default: a 250 ms initial delay that doubles up to 30 s, with equal jitter.
  • persistence: the store for the offline queue. Default: IndexedDB when indexedDB exists and no outbox is set, otherwise in memory. false turns persistence off.
  • queryCache: the read cache. Default: IndexedDB when indexedDB exists, otherwise none. false turns the cache off.
  • offlineQueue: queue limits. maxItems defaults to 1000.
  • connectTimeoutMs: Default: 10 000 ms.
  • rpcTimeoutMs: Default: 30 000 ms.
  • heartbeatIntervalMs: Default: 30 000 ms.

createInMemoryPersistence()

Type: () => PersistenceAdapter. Keeps the offline queue in memory. It does not survive a reload. Use it in tests, during SSR, or where no durable store is wanted.

createInMemoryQueryCache(options?)

Type: (options?: { maxEntries?: number }) => QueryCacheAdapter. An in-memory read cache, capped at maxEntries rows. It does not survive a reload.

createIndexedDbQueryCache(options?)

Type: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter. A durable read cache stored in the lunora-query-cache IndexedDB database. It throws when no IDBFactory exists, so use createInMemoryQueryCache outside a browser.

subscribeLiveTopic(options)

Type: (options: SubscribeLiveTopicOptions) => () => void. Follows a live topic on the connection shared by a URL. It returns an unsubscribe function. The last unsubscribe closes the connection.

httpStream(route, args?, options?)

Type: (route, args?, options?) => StreamIterable. Reads a streaming HTTP route as an async iterable. The iterable ends when the server sends event: complete. An event: error frame, or a transport failure, rejects the next next() call. Call .cancel(), or abort options.signal, to stop the fetch.

getIdentityStore(client)

Type: (client: LunoraClient) => IdentityStore. Returns the identity store that @lunora/client/auth uses for one client. The store is created on first access and reused for that client, so each client makes one identity request.

createUpload(options)

Type: (options: CreateUploadOptions) => UploadAdapter. Creates an upload adapter for an RLS-gated endpoint. TUS is the default protocol, and it resumes after a pause or a dropped connection. Import it from @lunora/client/upload.

lunoraQueryOptions(client, function_, args, options?)

Type: (client: LunoraClient, function_: FunctionReference, args, options?) => LunoraQueryOptions. TanStack Query options for a one-shot fetch. staleTime is infinite, so TanStack never refetches on its own, and no WebSocket opens. Import it from @lunora/client/query.

LunoraAdminClient

Type: class, extends LunoraClient. Adds admin operations such as setDeploymentPause, listScheduledJobs, schedulerStatus and listWorkflowInstances. Import it from @lunora/client/admin.

createServiceClient(binding)

Type: (binding: ServiceBindingLike) => LunoraServiceClient. Calls another Worker through a service binding, for example env.BACKEND. Import it from @lunora/client/service.

getServerSession(request, auth)

Type: <Result>(request: HeadersSource, auth: AuthLike<Result>) => Promise<NonNullable<Result> | null>. Reads the signed-in session on the server. Forward the session's token to createServerClient so the server-side load runs as the same user. Import it from @lunora/client/ssr.

isUnauthorizedError(error)

Type: (error: unknown) => error is Error & { code: "UNAUTHORIZED" }. True when a rejection is an authentication failure (HTTP 401), such as a missing or invalid identity.

isForbiddenError(error)

Type: (error: unknown) => error is Error & { code: "FORBIDDEN" }. True when a rejection is an RLS or policy denial (HTTP 403). The caller is authenticated but not allowed to read or write that row.

LunoraClientError

Type: type. The error that client calls reject with. It extends Error with optional code, data, docsUrl, headers, hint and why fields. Branch on code, or use the is*Error guards above.