qat

Backend contracts

The backend already describes itself: an OpenAPI document, its auth scopes, its validation rules. Qat reads that description once, at build time, and the app is typed and checked against it:

From the backend In the app Checked by
OpenAPI operations api.orders.create(…), typed params, responses and errors TypeScript; qatjs check --api-drift
A request body's schema form(api.orders.create): fields, required, length, pattern QX-FORM-UNKNOWN-FIELD, QX-FORM-SCHEMA-DRIFT
Permissions (policy.json or the OAuth scopes) can('orders.place') QX-POLICY-UNKNOWN; qatjs check --policy
Message catalogs (locales/*.json) t('checkout.title') QX-I18N-MISSING-KEY, QX-I18N-DEFAULT-DRIFT
Your error tracker onError(sentry(…)), onError(otel(…)) the .qx line in every stack

Every example on this page is type-checked inside examples/shop, against the client it generates (packages/toolchain/test/docs-backend.test.ts).

A typed client: qatjs api

shell1 line
qatjs api openapi.json --out src/contract

qatjs api reads an OpenAPI document — a file or a URL, OpenAPI 3.x or Swagger 2.0, JSON or YAML — and writes src/contract/index.ts: one namespace per tag, one function per operation, fetch only. It records the source in package.json#qat.api, so qatjs api alone regenerates:

JSON1 line
{ "qat": { "api": { "source": "openapi.json", "out": "src/contract", "validate": true } } }

A document behind auth: the token is used for the request and never written anywhere.

shell1 line
qatjs api https://api.example.com/openapi.json --header "Authorization: Bearer $QAT_API_TOKEN"

In a load, pass the load's signal on: leaving the page aborts the request. The compiler keys the load by operation and params (['reviews.list', { id }]), so two components asking for the same reviews share one request.

.qx12 lines, 1 reactive nameOpen in the playground
import { api } from '../contract/index.ts'

export default function Reviews({ id }: { id: string }) {
  let reviews = load(({ signal }) => api.reviews.list({ id }, { signal }))
  return (
    <ul class="reviews">
      {for (const r of reviews.data ?? [])}
        <li key={r.text}>{r.text}</li>
      {/for}
    </ul>
  )
}
reviews load

Where requests go, and with what headers, is set once:

TypeScript4 lines
import { configure } from './contract/index.ts'

const token = () => sessionStorage.getItem('token') ?? ''
configure({ base: '/api', headers: () => ({ authorization: `Bearer ${token()}` }) })

A response outside 2xx throws ApiError, its status and body typed by the responses the operation declares:

TypeScript11 lines
import { api, ApiError } from './contract/index.ts'

export async function place(email: string, name: string, zip: string) {
  try {
    return await api.orders.create({ body: { email, name, zip, items: [] } })
  } catch (e) {
    // a 422 here is a ValidationProblem: its `errors` map, field → messages
    if (e instanceof ApiError && e.status === 422) return { invalid: e.body.errors }
    throw e
  }
}

Drift. When the backend changes, qatjs check --api-drift compares the source with the client that was generated from it: one QX-API-DRIFT per changed operation, naming the components that call it. It is the only check that fetches.

shell1 line
qatjs check --api-drift

Validate. With "validate": true (or qatjs api --validate), each response in qatjs dev is checked against its schema; a mismatch is a QX-API-CONTRACT warning in the console and the devtools. A build carries none of that code.

Forms from the contract

form(api.orders.create) takes its fields from the operation's request body: type, required, minLength/maxLength, min/max, pattern, enum. A field the contract does not have is an error in qatjs check (QX-FORM-UNKNOWN-FIELD, from the program graph: the dev overlay does not show it); when the contract changes under a form, QX-FORM-SCHEMA-DRIFT says which field moved. Messages are yours; a 422 from the backend lands on its field.

.qx20 linesOpen in the playground
import { form } from '@qatjs/form'
import { api } from '../contract/index.ts'

export default function Signup() {
  let f = form(api.orders.create, {
    messages: { email: { valueMissing: 'Enter your email', typeMismatch: 'That is not an email address' }, zip: 'A ZIP code is 5 digits' },
  })
  const send = async (body) => {
    await api.orders.create({ body: { ...body, items: [] } })
  }
  return (
    <form novalidate on:submit={f.submit(send)}>
      <input ref={f.field('email')} />
      <input ref={f.field('name')} />
      <input ref={f.field('zip')} />
      {if (f.errors.zip)}<p class="error">{f.errors.zip}</p>{/if}
      <button disabled={f.submitting}>Send</button>
    </form>
  )
}

A Standard Schema validator — zod, valibot, arktype — refines the contract, or stands alone:

.qx16 linesOpen in the playground
import { z } from 'zod'
import { form } from '@qatjs/form'

const schema = z.object({ email: z.email(), age: z.number().min(18) })

export default function Join() {
  let f = form({ schema })
  return (
    <form novalidate on:submit={f.submit((v) => console.log(v.email))}>
      <input ref={f.field('email')} />
      <input type="number" ref={f.field('age')} />
      {if (f.errors.age)}<p class="error">{f.errors.age}</p>{/if}
      <button>Join</button>
    </form>
  )
}

Permissions: @qatjs/policy

policy.json declares what can be asked; who may do it is the app's to answer.

JSON4 lines
{
  "permissions": { "orders.place": "Place an order", "reports.view": "See the sales reports" },
  "roles": { "customer": ["orders.place"], "admin": ["*"] }
}

Without a policy.json, the permissions are the OAuth scopes of the OpenAPI security schemes (qat api writes them). qatjs check and qatjs dev write policy.d.ts, so can() takes only declared names, and a typo is QX-POLICY-UNKNOWN with the nearest name as its fix.

The resolver is any function: a role table, a token's scopes, an answer from the server kept in a signal. One that reads signals makes everything that asks reactive.

TypeScript5 lines, 1 reactive name
import { signal } from '@qatjs/core'
import { providePolicy } from '@qatjs/policy'

export const scopes = signal<string[]>([])
providePolicy((p) => scopes().includes(p))
scopes state
.qx10 linesOpen in the playground
import { can } from '@qatjs/policy'

export default function Orders() {
  return (
    <section>
      {if (can('orders.place'))}<a href="/checkout">Checkout</a>{/if}
      {if (can('reports.view'))}<a href="/reports">Reports</a>{/if}
    </section>
  )
}

Route guards ask the same way: guard(() => can('reports.view'), page('./pages/reports.qx'), { redirect: '/' }). The audit reads the program graph — per route what it requires and what its components ask for, which roles reach it, and the declared permissions nothing uses:

shell1 line
qatjs check --policy

Messages: @qatjs/core/i18n

locales/<locale>.json per language, flat or nested; ICU plural and select, compiled at build so the runtime (757 B) has no parser. t() is typed from the catalogs: its keys, and each message's params.

JSON4 lines
{
  "cart": { "items": "{count, plural, =0 {Your cart is empty} one {# item} other {# items}}" },
  "checkout": { "heading": "Checkout" }
}
.qx13 linesOpen in the playground
import { t, locale, setLocale } from '@qatjs/core/i18n'

export default function Header() {
  return (
    <header>
      <h1>{t('checkout.heading', 'Checkout')}</h1>
      <select value={locale()} on:change={(e) => setLocale(e.currentTarget.value)}>
        <option value="en">English</option>
        <option value="az">Azərbaycanca</option>
      </select>
    </header>
  )
}

A message's params come after the key, or after the default text: t('cart.items', { count }), t('cart.items', 'Your cart', { count }). setLocale(l) returns a promise, settled once that locale's messages are in. The chosen locale is not kept: a reload starts from <html lang> again, so store the choice yourself (a persisted store) and call setLocale with it at startup. setLocale also sets <html lang> and its dir (rtl for Arabic, Hebrew, Persian, Urdu and the other languages written from the right); en_US is read as en-US, and a name that is no locale rejects with a RangeError.

Besides plural, selectordinal and select, a message formats numbers and dates with the platform's Intl: {n, number}, {n, number, integer}, {n, number, percent}, {n, number, ::currency/AZN}, {n, number, ::compact-short}; {d, date} and {d, time} with short, medium (the default), long or full. A date is a Date, its milliseconds or its ISO text; one that is not there yet is no text. A message ICU cannot read, a style not in this list, or a value that is not a text is QX-I18N-SYNTAX in qatjs check, an error at its line of the catalog; a file of locales/ not named as a locale is (az_AZ.json) is QX-I18N-LOCALE-NAME.

A key a locale lacks is QX-I18N-MISSING-KEY, naming the locale; prose in JSX that is not a t() call is QX-I18N-BARE-TEXT (mark an element i18n-ignore to say it is not prose). It checks text children only: the text of aria-label, placeholder, title and alt is not checked, so give those t() too. The second argument, the default text, is written in the source locale — index.html's <html lang> — and never reaches the output; qatjs i18n extract writes it into the source catalog and TODO into the others. A message still TODO is QX-I18N-UNTRANSLATED in qatjs check, a warning at its line (lint key i18n-untranslated). QX-I18N-DEFAULT-DRIFT says when the default and the catalog diverge (--defaults makes the catalog follow the code):

shell1 line
qatjs i18n extract

In the editor, each t('key') shows the source locale's text after it, and the hover shows every locale's text linked to its line; in qatjs dev --devtools, the Aa button names the key of any text on the page.

Errors to your tracker

What no {try} catches goes to onError. The adapters send it with every frame at its .qx line — qatjs dev has the source maps inline, a build has them with qatjs compress --sourcemap. With report: true and @qatjs/devtools in the page, the devtools' report() (snapshot, action log, recent errors) goes with it. It is off by default: the report is the page's state, and Sentry is a third party.

TypeScript7 lines
import { onError } from '@qatjs/core'
import { sentry } from '@qatjs/report-sentry'
import { otel } from '@qatjs/report-otel'

const toSentry = sentry({ dsn: 'https://public@o1.ingest.example.io/42', release: '1.4.0' })
const toOtel = otel({ endpoint: 'https://collector.example.com/v1/logs', service: 'shop' })
onError((e) => (toSentry(e), toOtel(e)))

@qatjs/report-sentry posts to Sentry's envelope endpoint (no SDK; 1.15 kB). @qatjs/report-otel sends an OTLP/HTTP log record with the semantic conventions' exception.* attributes, or, given the app's own tracer, an exception span:

TypeScript5 lines
import { onError } from '@qatjs/core'
import { otel, type Tracer } from '@qatjs/report-otel'

declare const tracer: Tracer // e.g. trace.getTracer('shop') from @opentelemetry/api
onError(otel({ tracer }))

Both resolve stacks with @qatjs/stack, which any other tracker can use the same way: await resolve(error) gives { type, message, frames: [{ fn, file: '/src/pages/checkout.qx', line, col, mapped, app }], cause? }.