Skip to content

@flowcatalyst/api-runtime

@flowcatalyst/api-runtime is what a front end needs to talk to a service built on the application framework: a configured HTTP client, one error shape, the browser session and a router guard. It carries no components; those are in @flowcatalyst/ui, which depends on it.

The runtime assumes the SPA is served by the same service that exposes its API, authenticated by an HTTP-only session cookie (see Sessions and login and Static assets and the SPA). It never handles a token.

The package is private and unversioned (0.0.0); it is not on a registry and has no release tags. It ships TypeScript source, and an application links it by path from a checkout of the framework repository:

{
"dependencies": {
"@flowcatalyst/api-runtime": "link:../flowcatalyst-framework/ui/packages/api-runtime"
}
}

@flowcatalyst/ui and its peer dependencies are listed in the UI package page. Peer dependencies of the runtime itself are vue, vue-router and zod. Client generation uses @hey-api/openapi-ts, which your application installs as a development dependency. Use the versions in the framework workspace’s catalog (ui/pnpm-workspace.yaml).

Part Purpose
createApiRuntime One object created at start-up that configures your generated clients and owns the session.
configureClient Applies the runtime’s settings to a generated hey-api client.
ServiceError, toServiceError, fieldErrors, applyServiceError The framework’s error envelope as one typed value, and its field errors onto a form.
createBrowserSession, installSessionGuard The signed-in session, can(permission), sign-in and logout, and the router guard.
hasPermission, permissionMatches The platform’s permission-matching rule, for showing and hiding.
zodJitless Makes Zod work under a strict Content Security Policy.
exactOutput Bridges a validated form value to the generated request type.
@flowcatalyst/api-runtime/openapi-ts The shared client-generation config for your openapi.json.
getAuthSession, logout The generated client of the framework’s own /auth/session and /auth/logout.

@flowcatalyst/api-runtime must be the first import of the application’s entry file. Importing it runs zod-config.ts, which has to happen before any schema is built (see Strict CSP below).

main.ts
import { createApiRuntime, installSessionGuard } from "@flowcatalyst/api-runtime";
import { client } from "./api/client.gen";
import { createApp } from "vue";
import { flowcatalystUi } from "@flowcatalyst/ui";
import ui from "@nuxt/ui/vue-plugin";
const api = createApiRuntime({ clients: [client] }); // same origin, cookie only, 401 -> sign-in
installSessionGuard(router, api.session, { notPermitted: () => "/not-permitted" });
createApp(App).use(router).use(ui).use(flowcatalystUi, { api }).mount("#app");

createApiRuntime(options) accepts:

Option Default Meaning
clients none Your generated clients (client from each generated folder’s client.gen.ts). The framework’s own auth client is always configured.
navigate window.location.assign Full-page navigation, for sign-in and logout.
location window.location The current location.
focusTarget window Where focus is watched to refresh the session.
signedOutUrl none The signed-out page used after logout when the platform gives no end-session URL.
fetch global fetch Replaces fetch for the auth client (tests).

It returns { session, configure(client), onFailure(listener) }. configure applies the same settings to a client you create later. onFailure registers a listener for refused, failed and offline requests and returns the function that removes it.

configureClient sets baseUrl: "" (every call goes to the page’s own origin) and credentials: "same-origin" (the session cookie is the only credential). It deliberately sets no Authorization header and no CSRF token: the server’s CSRF check uses Fetch Metadata and the Origin header, which the browser sends by itself.

It watches responses without changing them:

  • a 401 starts the sign-in navigation (session.signIn());
  • a 403, a 5xx or a failed network call is reported to onFailure listeners as a RequestFailure of kind refused, failed or offline, with the HTTP status (0 when nothing arrived) and METHOD path (never the query string, which may hold search text);
  • the caller still receives { error, response } and decides what to do.

REQUEST_FAILURE_TEXT holds the default summary and detail text for each kind. The toast composable in @flowcatalyst/ui (useRequestFailureToasts) uses these.

api.session is a BrowserSession:

Member Meaning
current The last answer of GET /auth/session, or undefined before the first read
user The signed-in AuthSessionAuthenticated, or undefined
permissions The session’s permissions (empty when signed out)
start() Reads the session once (later calls share the read) and starts watching focus
refresh() Reads it again
can(required) True when a held permission grants required
signIn(returnTo?) Navigates to the sign-in URL, returning to returnTo (default: here)
logout() Posts /auth/logout and navigates to the end-session URL or signedOutUrl; rejects without navigating if the server refused
stop() Stops watching focus

An authenticated answer carries principal (id, kind of USER or SERVICE, name?, email?), tier? (ANCHOR, PARTNER or CLIENT), client, clients, applications, roles, permissions, authTime, expiresAt, idleExpiresAt and csrf. An anonymous answer carries a loginUrl. signInUrl(loginUrl, returnTo) builds the URL with the return value percent-encoded.

A held permission grants a required one when both have the same number of :-separated segments and every held segment is * or equal to the required one. permissionMatches(held, required) and hasPermission(heldList, required) implement exactly that. In the browser the result only decides what is shown; every operation is checked again on the server. See Permissions and roles.

installSessionGuard(router, session, options) returns a function that removes it. Every route needs a signed-in session unless its meta says public: true. A route with meta.permission also needs that permission.

const routes = [
{ path: "/signed-out", component: SignedOut, meta: { public: true } },
{ path: "/orders", component: Orders, meta: { permission: "orders:order:view" } },
];
Option Meaning
notPermitted(to) Where a signed-in user without the permission goes. Without it the navigation is cancelled.
landing(to) Where an automatic landing (first page load, the page after sign-in) goes when it lacks the permission, so a user never meets a denial they did not cause.
onUnavailable(error) Called when the session could not be read at all (offline, 5xx); the navigation is cancelled.

Every failed call normalises to a ServiceError:

interface ServiceError {
status: number; // HTTP status, or 0 when no answer arrived
error: string; // envelope code, or NETWORK / HTTP_<status>
message: string;
details: Record<string, string>;
}

toServiceError(error, response) accepts what a generated SDK function returns as error. A body of the framework’s envelope shape ({ error, message, details? }, see Errors) keeps its code and message; anything else (a proxy’s HTML page, a network failure) gets a generic message and a NETWORK or HTTP_<status> code. ApiRequestError is a thrown ServiceError, used by the session read and logout. isErrorEnvelope(value) and isUnauthenticated(error) are the matching guards.

For a 400, fieldErrors(error) splits each detail ("<field path>": "<CODE>: <message>") into { name, code, message }. applyServiceError(form, error) puts them on a Nuxt UI UForm and returns the text for the form-level message: a field the form does not show is appended to that message instead of being lost.

Import the envelope type as ErrorEnvelope or ServiceError from this package. Do not import the generated Error, which shadows the global.

An application keeps a committed openapi.json of its own API and generates a client from it with the shared settings:

web/openapi-ts.config.ts
import { fwOpenApiConfig } from "@flowcatalyst/api-runtime/openapi-ts";
export default fwOpenApiConfig({ input: "openapi.json", output: "src/api" });
{
"scripts": {
"api:generate": "openapi-ts",
"api:drift": "openapi-ts && git diff --exit-code -- src/api && test -z \"$(git status --porcelain -- src/api)\""
}
}

Commit the generated folder and run api:drift in CI: a modified or new file fails it. The shared config adds two settings to the contract’s plugin list. It sets baseUrl: false on the fetch client, because a document without servers makes the generator write the input path as the base URL. And it replaces the Zod plugin’s handling of int64 and uint64, which would otherwise produce a BigInt that JSON.stringify cannot serialise, with a safe integer: values beyond 2^53 are refused in the browser (ids are strings for that reason). See Typed operations and OpenAPI for the contract the document follows.

A validated form value (Zod’s output) is not assignable to the generated request type under exactOptionalPropertyTypes, because Zod writes ?: T | undefined and the generator writes ?: T. Do not cast. Pass the value through exactOutput, which removes undefined-valued properties deeply and says so in the type:

const body: IngestionBody = exactOutput(zIngestionBody.parse(form));

The generated folder’s client/ and core/ subfolders need a separate TypeScript project because they break strict settings; the framework’s ui/README.md and ui/apps/gallery/tsconfig.generated.json show the layout, and @flowcatalyst/ui/tsconfig.generated-client.json is the preset to extend.

Zod 4 compiles object parsers with new Function when it can, and probes for that with new Function(""). Under the strict policy the framework serves (script-src without 'unsafe-eval') the probe is caught but still reported as a violation. zodJitless (run on import) sets Zod to jitless and replaces its developer-facing messages for email, URL and pattern failures with text a user can read next to a field. Because it must run before any schema exists, import @flowcatalyst/api-runtime (or @flowcatalyst/api-runtime/zod) before your router, pages or generated zod.gen.ts.

Create the runtime with injected navigate, location, focusTarget and fetch to test sign-in, logout and the guard without a browser. The package’s own tests use vitest (pnpm test in the framework’s ui/ directory); pnpm api:drift regenerates every client and fails on a change.