qat

Shipping: qatjs compress, qatjs preview

shell2 lines
qatjs compress
qatjs preview --port 4180

qatjs compress builds dist/ with Rolldown, from the same compiler output qatjs dev serves:

  • Each route loads exactly what it needs (route sets): every page(), layout() and remote() is its own chunk, and every other module goes where the routes that use it are — no route downloads code it does not run.
  • What nothing has opened yet loads when it opens (on first render): a component that renders only inside a closed {if} is a chunk of its own, with its CSS.
  • Chunks are addressed by their content through the import map (below): a chunk imports ./tabs.js, the page's import map points that at tabs-Ab3dE9xY.js, so editing one component changes one file, and the browser keeps the rest. Minified, with manifest.json listing every chunk's file, imports and CSS, and <link rel="modulepreload"> for every chunk the first page needs.
  • CSS: each component's <style> is extracted. The CSS of the modules the entry imports statically is inlined into index.html; a lazy chunk loads its own file next to it — in a routed app every page() is one, so its CSS is a file and index.html has no <style>. Stylesheets linked from index.html are hashed. All of it through Lightning CSS for your browserslist.
  • Dev code is gone: the HMR client, the hot wrappers and every import.meta.env.DEV branch (the router's dev hooks among them) are 0 B of dist/; env values are inlined.
  • Assets imported from JS (import logo from './logo.svg') are copied with a hash; public/ is copied as it is.

On examples/shop (qatjs compress examples/shop, then report.json): 25 chunks, 11.41 kB gzip of JavaScript in the entry's set, 13.4–17.9 kB per route; a second build with nothing changed takes 0.15 s. Every build also writes report.json and proof.json (below).

shell1 line
qatjs compress --analyze

prints each chunk's gzip size, then every route's set, then each chunk with the rule that placed each of its modules:

15 lines
route sets (each route loads exactly these chunks)
route                          gzip       chunks
/                               12.16 kB  7: head, home, main, qat, routes, shell, tabs
/products/:id                   13.94 kB  10: catalog, detail, head, load, main, qat, routes, shell, tabs, view
/checkout                       11.92 kB  7: checkout, form, head, main, qat, routes, shell

chunks, and the rule that placed each module (entry · split · own · merged · route-set · package)
home                             1.17 kB  split
    merged    src/components/likes.qx  → into src/pages/home.qx
    split     src/pages/home.qx
form                             1.13 kB  route-set
    route-set @qatjs/form/dist/chunk-5W73D4DT.js
qat                              7.17 kB  package
    package   9 modules of qat, @qatjs/router, @qatjs/store
…

On first render

There is no lazy() to write: compress finds what to load late from the program graph (10b B1, D284). A component is loaded the first time it renders — its module and its CSS a chunk of their own, not in the page's first load — when every place that renders it is closed:

  • inside an {if}'s first branch whose condition is a state that starts falsy (false, null, 0, '', nothing) and is written only in handlers or effects — closed at setup and on the server: a dialog's body, a popover's panel, a picker's calendar;
  • or inside a component that only such places render (the whole program is read, so a component rendered open anywhere else is not deferred).
.qx14 lines, 2 reactive namesOpen in the playground
import { Calendar } from './ui/calendar/calendar.qx'

export default function Pick() {
  let open = state(false)
  let day = state('2026-10-23')
  return (
    <div>
      <button on:click={() => (open = !open)}>Choose date</button>
      {if (open)}
        <Calendar bind:value={day} />
      {/if}
    </div>
  )
}
open stateday state

(The calendar's module and its stylesheet load on the first click.)

The tag compiles to a getter over a loader (import() once, the module held in a signal): until the module is here the branch shows nothing, then the component, its props live, its events through. The server compiles with the same plan, so what it writes is what the browser resumes. lazy stays a reserved word. What --analyze lists as split includes these chunks.

Build-time values: static()

static(() => …) runs at build, not in the browser (10b B2, D287): qatjs compress (and qatjs dev) runs the function in Node with the file's imports, and writes its result where the call was, as a literal. The function and what only it imports are not in the output.

.qx13 linesOpen in the playground
import { routes } from './routes.js'
import { buildMenu } from './menu.js'

export default function Nav() {
  const menu = static(() => buildMenu(routes))
  return (
    <nav>
      {for (const m of menu)}
        <a key={m.href} href={m.href}>{m.label}</a>
      {/for}
    </nav>
  )
}
  • What it may return: JSON, a Map, a Set, a Date, a typed array — anything a literal can write. A function, a class's instance or a cycle is QX-STATIC-VALUE, naming where it is (the result.items[2]).
  • What it may read: its imports and its own locals. A browser-only global (window, fetch, localStorage, …) is QX-STATIC-RUNTIME; a value of the file (a state, a local) is QX-STATIC-FREE.
  • It is stopped after 5 s. Its result is kept by the hash of what ran (the function and everything it imports), so unchanged code does not run again.
  • A string, number, boolean or null folds the {if} or {switch} it decides: only the chosen branch is in the output. A const holding any result is static where it is read: no effect.
  • In qatjs dev it runs when its file changes (not when only what it imports does).
  • Compiled without the toolchain (a test, the playground), static(f) is f(): the same value, at run time. static is a reserved word in .qx (.tsx has no static(): its name cannot be an identifier there).

A build profile: --profile

qatjs dev --count adds up what the app's own sessions did: route visits and transitions (by pattern), how many of each component's elements were rendered and how many were ever in view. It writes them, counters only, to qat.profile.json in the app (profile/v1; ignored by git). qat compress --profile qat.profile.json reads it, and dist/report.json lists what the build decided and why (decisions):

  • from the program graph, with or without a profile: the props that never change (static-props), the components loaded on first render (deferred), the route data the seed leaves out (seed-omit);
  • from the profile: the likely next route (prefetch, where most navigations from a route go), the components rarely seen (lazy-visible, below the fold), the routes visited back and forth (merge). These are proposed, not applied: each says why. No route's initial chunk set grows from a profile.

qatjs check --suggest (with --profile, or the app's qat.profile.json) lists them with fix-its, and the states nothing writes. Qat never sends data to Qat. Any endpoint is the project's own; production collection is opt-in, identifier-free, counters only. A build profile (qatjs dev --count, qatjs compress --profile) is a file of the project's: nothing reads it but its own toolchain.

Exact route sets

A module's route set is the set of split points (entries, page(), layout(), remote(), and the components loaded on first render) whose static imports reach it. A split point every importer of which already holds a module statically does not count for it: that module is loaded first. compress places every module by one of six rules, in this order, and --analyze names the one it used:

rule what goes there
entry index.html's module script (or a federation expose): its own chunk
split a page()/layout()/remote() target, or a component loaded on first render: its own chunk
package a package's modules of one route set are one unit (qat and @qatjs/* count as one package)
own a module (or unit) of 3 kB or more, minified: its own chunk
merged under 3 kB: merged into its most common requester among the modules of the same route set
route-set under 3 kB with no requester of its set: one chunk per route set

A module the entry loads is loaded on every route, so it counts once (with the entry). So does what a layout loads, for the pages under it: a page is never shown without its layouts, so a module a layout holds is of the layout's set whichever of its pages use it too — one chunk, not one for each group of pages that happens to share it. And a layout around every route of the table is loaded whatever the route, as the entry is: what it holds goes with the entry's (its @qatjs/* modules into the one qat chunk). The route table says which pages are under which layouts; a page that something else imports as well (lazy()) is not assumed to come with its layout, and a build with server-rendered routes does not use the rule (a resumed page loads its handlers alone). Merging never adds a module to a route that does not need it (only requesters with the same set qualify), modules of one import cycle stay together, and no merge creates a cycle between chunks. The result is checked: the build compares Rolldown's chunks with the plan, and the shop's and the scale app's Playwright suites check every route against the network — each opened directly loads exactly its set, nothing else, every chunk of it preloaded, none fetched twice.

Content addressing

Chunks import each other by stable names (import "./tabs.js"), and index.html's import map maps each stable URL to the file named by the hash of that chunk's bytes:

HTML1 line
<script type="importmap">{"imports":{"/assets/tabs.js":"/assets/tabs-Ab3dE9xY.js",…},"integrity":{…}}</script>

A chunk's bytes therefore never contain another chunk's hash: a change to one module re-addresses the one chunk that holds it, its importers keep their names, and a returning visitor downloads that chunk again and nothing else (the scale app: 0.11 % of its JavaScript after editing a leaf component, against 99.4 % before — scale). When a route's page is imported, its whole set is preloaded at once: import("./p1.js") is compiled to __qatP([0,3],()=>import("./p1.js")), which adds a <link rel="modulepreload"> (with the file's integrity) for each chunk of the set not loaded yet. A federated app keeps hashed file names in its chunks' imports (its import map is built at boot, and a remote's chunks load from another origin).

Incremental builds

compress keeps a cache in node_modules/.qat/compress/ (one file): each module's compile result and the runtime facts read from it, keyed by its source and the compiler's version and build. A second build compiles only the modules whose source changed, skips the scan pass when the app uses the same runtime units as last time (it checks that after the build, and builds again if not), and writes only the files whose bytes changed — unchanged chunks keep their names. What the build no longer produces is removed from dist/.

shell1 line
qatjs compress --no-cache

is a full build (it writes the cache again).

The cache is safe to delete at any time, and a damaged one is ignored: the next build is a clean one, with the same output (tested).

The report and the regression gate

Every build writes dist/report.json ($schema: https://qat.dev/schema/report/v1.json): per route, its chunk set, its gzip size and budget, the runtime units its modules use (core trimming), its dependencies (name@version), its i18n keys (literal t('…') calls of an imported t) and the env names it reads; per chunk, its file, sizes and rule; per module, its chunk and rule.

shell2 lines
qatjs compress --compare dist/report.json --fail-on size,deps,budget
qatjs compare dist/report.json dist/report.json --markdown

After a build, compress prints what changed against --compare (by default the last build's report): size deltas per route, the runtime units a change brings in (“this change brings portal into 12 routes, +80 B each”), new dependencies, budgets crossed, i18n keys lost. --fail-on makes the exit code 1 when a route grew (size), a dependency is new (deps) or a route is over its budget (budget). qatjs compare diffs two existing reports (--markdown for a pull-request comment). node_modules/@qatjs/toolchain/templates/github/qat-report.yml is a GitHub Action that builds a pull request's base and head and posts that diff as one comment, updated on each push.

Deterministic, provable output

The same source and the same toolchain write the same bytes, in any directory and on Linux or macOS: no timestamps, file and module order fixed, hashes made from content only, every path in the output relative to the app (scripts/ci/deterministic.mjs builds an app twice in two fresh directories and diffs; CI runs it on both systems and diffs them too).

dist/proof.json ($schema: https://qat.dev/schema/proof/v1.json) records the source commit, the toolchain and compiler versions, the lockfile's SHA-256 and every output file's hash:

shell1 line
qatjs verify dist/proof.json

checks every file of the build against the proof. With a project key (ed25519: openssl genpkey -algorithm ed25519 -out release.pem, and its public half), qatjs compress --sign release.pem signs the proof and qatjs verify dist/proof.json --key release.pub.pem checks that signature too.

A changed, added or missing file fails the check; with --key, so does a proof signed by another key, or not signed.

The production size while you work

qatjs dev shows, in a corner of the page, what the current route costs in production — “this route: 13.9 kB in production, budget 15.0 kB, 10 chunks” — and __qat.explain().production has the details (each chunk, its size and rule). It is computed from the compiler's module graph with the same plan as compress, without bundling: the app's modules are compiled and measured as compress would ship them, packages as the last qatjs compress shipped them. It updates after each navigation and each hot update.

Streaming output (deferred)

compress --stream (writing each route's chunks as soon as they are final, for adapters that upload route by route) is not built. The adapter interface, createHandler({ app, template, … }), serves a finished dist/; nothing consumes a partial one, and chunk names are only final once every chunk is hashed. It waits for an adapter that uploads as it goes.

shell2 lines
qatjs compress --sourcemap
qatjs compress --sourcemap hidden

write source maps (.map next to each file, pointing at your .qx sources); hidden leaves the //# sourceMappingURL comment out, for an error tracker that has the maps but users do not.

shell1 line
qatjs compress --out build --mode staging

builds into build/ with .env.staging.

Serving from a subdirectory: --base

shell1 line
qatjs compress --base /shop/

builds an app served at https://example.com/shop/. The same setting can live in package.json, as "qat": { "base": "/shop/" }; the flag wins. Everything the build writes is then under the base:

  • index.html: the entry script, its modulepreloads, the stylesheets, the import map (the integrity of each lazy chunk), the federation boot's shared imports, and src/hrefs that name a file of public/ by its root-absolute URL (/icon.svg → /shop/icon.svg);
  • CSS: url(/…) naming a file of public/ (a url() relative to its own file — in a sheet or in a component's <style> — names a file of the app: emitted into assets/ under its content's hash, like an image a module imports, with or without a base);
  • the router: the route table is prefixed when compress compiles it. / matches /shop/ (and /shop), to.products.list() is /shop/products, and redirect('/cart') written in the route table goes to /shop/cart, as does a guard's redirect (default: the base). The router ships no base code. A path outside the base is the '*' route;
  • --pwa: the worker is /shop/sw.js with the scope /shop/, and the manifest's start_url and scope are the base;
  • server-rendered routes: the server matches below the base, serves dist/ there and prerenders 'static' pages at their URLs under it;
  • import.meta.env.BASE_URL: the base (/ in qatjs dev and without --base), for URLs the build cannot see: fetch(import.meta.env.BASE_URL + 'hours.json').

Chunks already import each other by relative URLs, so they are the same with any base. What is not rewritten is a path you write yourself in a component: <a href="/products">, navigate('/done') or fetch('/data.json'). Use to.* for routes and BASE_URL for files, and qatjs dev (which serves at /) and the build agree.

--base ./ writes relative URLs (./assets/main-x.js), for a page served from a directory whose path is not known at build time, such as the official js-framework-benchmark, which serves each app at /frameworks/keyed/<name>/dist/. The router then reads its prefix in the browser, from the URL of the chunk that holds the route table. A relative page only works at its own directory: a deep link such as /shop/products/3 would load ./assets/… from /shop/products/. An app with routes uses an absolute base, and server-rendered routes require one.

qatjs preview serves a build under its base (read from dist/index.html): / redirects to the base, and anything else outside it is a 404.

Sets of modules: import.meta.glob

JavaScript3 lines
const pages = import.meta.glob('./pages/*.qx')                                        // lazy
const icons = import.meta.glob('./icons/*.qx', { eager: true, import: 'default' })   // eager
const posts = import.meta.glob('./posts/*.md', { query: '?raw', import: 'default' }) // text

A pattern (relative to the file, or /src/… from the project; **, {a,b}, ! to leave files out, an array for several) becomes plain imports when the module is transformed, the same in qatjs dev and qatjs compress:

options each value in dist/
none () => import('./pages/a.qx') a chunk per file, loaded when called
{ eager: true } the module (a static import) in the importer's chunk
{ import: 'default' } (or any export) that export, lazily or eagerly as above
{ query: '?raw' } the file's text ({ default: text }, or the text with import: 'default') inlined

Keys are the patterns' own form, sorted. The arguments must be literals (QX-GLOB says where otherwise). In qatjs dev, adding or removing a matching file re-runs the module that globs it.

The results are typed: qatjs dev, qatjs check and qatjs compress write glob.d.ts next to env.d.ts, with the files each literal pattern matches, so pages['./pages/a.qx'] is that module's type and a key no file has is an error. An app that never calls import.meta.glob gets no file.

Workers

JavaScript1 line
const worker = new Worker(new URL('./workers/search.ts', import.meta.url), { type: 'module' })

is the one way to write a worker, the one the browser understands with no build at all.

  • qatjs dev serves the worker's modules marked ?worker. A worker has no import map, so its bare imports (import { signal } from '@qatjs/core') are resolved on the server.
  • qatjs compress builds each worker as its own entry: one file with everything it imports (a worker is its own realm and shares no chunk with the page), minified, hashed (assets/search-<hash>.js), and the URL in the importing chunk rewritten to it. Without { type: 'module' } it is a classic worker, built as an IIFE.
  • SRI and CSP: manifest.json lists the worker with its format and sha384, which is also in the import map's integrity (browsers take no integrity for a worker script), and csp.json gets worker-src 'self'. SharedWorker works the same way.

A worker started by a server-rendered route (in mount, which runs in the browser only) works the same: the server renders the page, the resumed page starts the worker (server rendering).

Server-rendered routes

When a route's page() sets a mode other than 'client', compress also writes dist/server/: entry.mjs (a (request) => Promise<Response> handler, and a server when run with node dist/server/entry.mjs), the pages of 'static' routes rendered at build, and their 'static' load values. The browser build resumes those pages instead of rendering them, and qatjs preview serves the build through entry.mjs; qatjs preview --target edge serves an edge adapter's build (edge or edge-cloudflare) through dist/server/fetch.mjs and names the routes it leaves to the browser (QX-EDGE-NO-ALS, QX-EDGE-NO-EVAL, edge). See server rendering.

The core, trimmed to the app

The runtime core is a set of units — the {for} reconciler, {if}/{switch}, the delegated event table, each binder, SVG templates, transition: leave hooks, {try} routing — and qatjs compress ships only the ones your app uses. The compiled modules are standard ESM calling the public runtime API, so a first pass reads every call (.qx, .tsx, plain .js/.ts and packages alike) with the arguments that pick an algorithm: on:'s event type and modifiers, a {for}'s key and index, an <svg> template, render(…, { onError }). The build then takes the core from qat/dist/units/ with the units it does not need folded away. Nothing is configured, and nothing changes in the compiled code: an algorithm the app uses is the same code as in the full core. Anything the reader cannot follow — import * as q from '@qatjs/core', a runtime function passed around as a value, an event type that is not a literal — keeps everything it could reach. The dom renderer used directly keeps the unit of the method called (dom.setStyle(…): style); as a value, the units its methods belong to; a renderer made from it ({ ...dom, … }) none. A build that resumes makes its renderer so: it is trimmed like any other. qatjs dev always loads the full core.

A new app (qatjs init, then qatjs compress) ships 2.29 kB of core; the shop 3.75 kB; the full core is 4.06 kB. --analyze lists every unit, kept or removed, and why — the syntax, file and line that needed it (examples/shop, qatjs compress examples/shop --analyze):

13 lines
core units — core 3.75 kB gzip (the full core: 4.06 kB)
  kept     core              every app: signals, effects, ownership, components, templates, `{expr}` content, render()
  removed  svg               nothing uses an SVG template (`<svg>` root)
  kept     attr              aria-label={…} at src/components/tabs.qx:48:28 (+86 more)
  kept     class             class:selected at src/components/tabs.qx:66:7 (+2 more)
  kept     events.delegated  on:click at src/components/likes.qx:23:15 (+19 more) — table: click, input, keydown
  kept     events.direct     on:change at src/layouts/shell.qx:22:79 (+4 more)
  kept     list              `list` used as a value at @qatjs/ui/components/virtual/virtual.ts:60:3 (+11 more)
  removed  selector          nothing uses `selector()`
  removed  transition        nothing uses `transition:`
  removed  boundary          nothing uses `{try}…{catch}` or `render(…, { onError })`
  removed  deep.collections  nothing uses deep `state(new Map)` / `state(new Set)`
  …

The same, as data, is dist/core.json. qatjs compress --full-core ships the whole core. In a federation the shell's core serves its remotes too, so it keeps the union of every party's units (each qat.json declares its uses): see federation.

Security: SRI, a CSP, the audit

Every build also writes:

  • integrity (SRI) on each script, stylesheet and module preload index.html references (sha384). The chunks loaded later, the lazy routes, are listed in an import map's integrity section, so a changed file is refused wherever it comes from. A federated shell builds its import map at boot, so there only the page's own references are covered.
  • dist/csp.json: a strict Content-Security-Policy for this build — 'self', the hashes of each inline script (the env bootstrap, the federation boot, the import map) and inline style (the CSS the entry imports statically, when there is any), object-src 'none', no unsafe-inline, no unsafe-eval — as policy, ready for a header, and as directives. Filling #qat-env at deploy time changes no hash: it is JSON, not script. For servers that send a nonce per response, nonce.policy uses __QAT_CSP_NONCE__, which every inline script and style in index.html carries: replace it in both. Add your API's origin to connect-src.
  • dist/audit.json: every package in the bundle, its version, license and chunks.

The shop's browser suite runs the build under its own csp.json policy with no violation, and checks that a tampered chunk does not run.

Offline and installable: --pwa

shell1 line
qatjs compress --pwa

adds three files to dist/, each built from what compress already knows. There is still no config:

  • sw.js, a service worker that knows your routes:

    request strategy
    install precaches the shell (index.html), the offline page, the manifest and its icons, and the entry route's set: every chunk and stylesheet / needs (the same files as its route budget)
    a navigation network first. Offline, a route whose whole set is cached (precached, or visited before) gets the shell and the router renders it; any other URL gets the offline page
    /assets/… (hashed) cache first; a miss is fetched with the file's SRI hash, so the cache never keeps a file the page would refuse
    a load's GET fresh within the load's stale from the cache (no request); after that, the network, with the cache as the offline answer. A response the server marks cache-control: no-store is never kept
    anything else not touched (POSTs, other origins, plain fetch outside a load)

    @qatjs/load marks each request's signal with its stale. While the worker controls the page, the page's fetch carries that value to the worker in an x-qat-stale header, and the worker removes the header before the request leaves. A new build gets a new worker. The first worker takes over at once. A later one waits until the pages of the old build are closed, so a running page never loses its chunks. The cache of loads (qat-data) is the browser profile's, not a user's: when someone signs out, caches.delete('qat-data').

  • app.webmanifest, from index.html: <title>, <meta name="description">, <meta name="theme-color">, <meta name="application-name"> (the short name), <html lang>, and the <link rel="icon">s. If the page links its own manifest, that one is precached and none is generated.

  • offline.html: your own offline.html next to index.html, or a plain page with your title and stylesheets.

index.html gains <link rel="manifest"> and one inline script, which registers the worker. Both go through the same steps as the rest of the page: the script gets its hash in csp.json and the nonce placeholder, and every script and stylesheet keeps its SRI. The offline page has no inline script or style, so the same policy covers it. Without --pwa, the build is byte for byte what it was.

The worker also replays the queue of offline forms on Background Sync.

Route budgets

JavaScript5 lines
import { page, router } from '@qatjs/router'

export default router({
  '/products/:id': page('./pages/products/detail.qx', { budget: '30kb' }),
})

A route's budget (gzip: '30kb', '1.5 kB', or bytes) is checked by qatjs compress against the route's initial JavaScript. That covers the entry's chunks plus the route's layouts and page, with everything they import statically: what the browser loads to show it. Over the budget, the build fails, naming the route, the sizes and the files. --analyze shows every route:

3 lines
route                          initial JS   budget
/                                12.88 kB   —
/products/:id                    13.88 kB   30.00 kB ok

Build and field side by side: qatjs budget

qatjs budget puts each route's build numbers beside what visitors measured with @qatjs/vitals: p75 LCP, INP and CLS over a window.

shell2 lines
qatjs compress
qatjs budget --endpoint vitals.ndjson --window 28d --fail-on both
6 lines
route          build kB  limit  p75 LCP  p75 INP  p75 CLS  target                 status
/                  8.37      —   1.81 s    96 ms     0.02  2.50 s · 200 ms · 0.1  ok
/products/:id      9.10  30.00   2.90 s   120 ms     0.02  2.50 s · 200 ms · 0.1  over: LCP
/checkout          7.00      —        —        —        —  2.50 s · 200 ms · 0.1  —

field: 412 visits in the last 28 days from vitals.ndjson
  • build kB is the route's initial chunk set, read from dist/graph.json (the route's chunk edges, what those chunks import, and the entry's chunks), each chunk's size from dist/report.json: the same set the budget above checks. limit is its page(…, { budget }).
  • The field columns are the p75 of each metric over the window's rows for the route's pattern that have that metric. --endpoint is a URL that answers GET with the stored rows (NDJSON or a JSON array; ?since=<ms> is added) — the endpoint in vitals.md does — or a local file of them (vitals.ndjson). --window takes 28d (the default), 12h, 2w or milliseconds.
  • Without the flags, the endpoint and window are package.json#qat.vitals = { endpoint, window } (vitals.md): a path such as /vitals (read from qat.site's origin), a file, or a URL on the site's origin. Another origin is the warning QX-VITALS-FOREIGN-ENDPOINT and is not read. qatjs dev --devtools reads the same key for the Routes tab.
  • target defaults to the "good" thresholds (LCP 2.5 s, INP 200 ms, CLS 0.1); --target LCP=2000,INP=150 changes any of them.
  • Missing field data is — and never fails: no --endpoint, an endpoint that cannot be read (a warning says why), a route nobody visited, a metric a browser did not report.
  • --fail-on build exits 1 when a route is over its limit, --fail-on field when a p75 is over its target, --fail-on both on either. Without it, qatjs budget only reports. A build it cannot read (no dist/graph.json: run qatjs compress first) exits 2.
  • --json prints the table (schema budget v1). The same object comes from budgetTable() in @qatjs/graph/budget, which the devtools Routes panel calls with what it fetched:
JavaScript4 lines
import { budgetTable, budgetText } from '@qatjs/graph/budget'

const table = budgetTable({ graph, report, rows, window: 28 * 86_400_000 })
console.log(budgetText(table))

qatjs preview serves dist/ as it would be deployed: hashed files cached forever, a directory's own index.html (a prerendered page: dist/guide/index.html for /guide), index.html for any other path (the router takes it from there), gzip for text and .wasm when the browser accepts it, and CORS headers (a federation remote's files load from other origins).

qatjs federate is qatjs compress for an app with qat.federate.js: exposes as entries, the shared packages built once, and qat.json — see federation.

Deploying: keep the earlier builds

A deploy never breaks a session that is open. qatjs compress writes dist/versions.json: this build, then the earlier builds, newest first, up to package.json#qat.retain (3). Their chunks stay in dist/assets/, so a page opened on an earlier build still loads its own lazy chunks. Deploy dist/ as it is: what it lists, it holds.

Retention needs the last deploy's dist/ to build into. A CI job that builds from an empty directory keeps nothing, so restore the deployed assets/ and versions.json first (from the host, an artifact or a cache). qatjs preview says when no earlier build is kept, or when one it lists lost chunks: QX-DEPLOY-NO-RETENTION.

The page can tell its user. With @qatjs/core/version imported, the build names itself in the page (<meta name="qat-version">). At each navigation, and when the tab comes back, the page reads versions.json; a newer build sets outdated:

// update-bar.qx
import { outdated } from '@qatjs/core/version'

export default function UpdateBar() {
  return <div>{if (outdated())}<p role="status">A new version is available. <a href="">Reload</a></p>{/if}</div>
}

Nothing reloads by itself. A navigation to a path only the newer build has a route for loads that build, as a full navigation. Every other navigation stays in the running build.

Switching in place: @qatjs/core/version/live

With import '@qatjs/core/version/live', or a store with version: (see state.md), the build is a live build, and a newer deploy is switched into the open page in place when that is provably safe. Each component sits behind a wrapper and each state is kept by name, as in qatjs dev's HMR. The build also writes, for each build it keeps, its changed chunks again under assets/live/<id>/, with their imports pointing at the files themselves: the page's import map cannot change.

When outdated turns, the switch is decided from versions.json. It goes ahead only if:

  • every running component in a changed module keeps its state: the same state, derived, load, form and prop names, kinds and types;
  • the runtime and the route table are the same;
  • every qatjs api operation the page calls is in the newer build unchanged (an added one is fine);
  • every changed module is a component's or a store's.

It waits for a quiet moment (no request in flight, no focused input, no running animation), then imports the changed chunks and re-creates their mounted components, which keep their state. Changed stores take the running state, migrated; a changed stylesheet's link moves to the newer file.

When a check fails, the page keeps its build, and its next navigation is a full one: that loads the newer build, so a checkout open during a contract change places its order on the build it started with. __qat.explain('version') says where the switch stands and why.

A page rendered on the server switches the same way. Its components claimed the server's HTML, and a switch re-creates a changed one in place, like any other component. A re-created component's load starts with the data the running one had: its function runs with an aborted signal, for what it reads, and makes no request when it passes that signal on. One more check applies: each changed module's markup (its templates) must be the same. A component still waiting to claim the server's HTML, and the newer server's next pages, need the markup the page was rendered with. A changed template keeps the running build, and the next navigation loads the newer one.

Settings in package.json#qat

There is no config file. Behaviour lives in code (router, page, load, federate), one-off choices are flags, and the few project settings are keys of package.json#qat:

key what read by
adapter "node" (default), "edge", "edge-cloudflare" or "static": the deploy target (server.md) compress
api { source, out }: the API contract the typed client was generated from, and where it is (backend.md); written by qatjs api api, dev, compress, check
base the subdirectory the app is served from ("/shop/"); --base wins compress
plugins Vite and Rollup plugins: a package or ./path, with its options (dev.md) dev, compress
lint rule levels ({ "a11y-name": "off" }) check, dev, the editor
site the site's URL ("https://shop.example/"): sitemap.xml, and the app's own origin; --site wins compress --static, budget, check
retain how many earlier builds a deploy keeps, their chunks and their entries in versions.json (3; 0 keeps none) compress
vitals { endpoint, window }: where the field vitals rows are (vitals.md); the app's own server only (QX-VITALS-FOREIGN-ENDPOINT); --endpoint/--window win budget, dev --devtools, check

Machine-readable files

Every JSON file and --json output Qat writes starts with its schema and version:

JSON1 line
{ "$schema": "https://qat.dev/schema/csp/v1.json", "version": 1, "policy": "default-src 'self'; …" }
File or output Written by Schema
qat.json qatjs federate, qatjs dev qat
dist/env.json, csp.json, audit.json, core.json, manifest.json qatjs compress env, csp, audit, core, manifest
dist/report.json, dist/proof.json qatjs compress report, proof
dist/server/routes.json, dist/server/cache.json qatjs compress (server routes) routes, cache
dist/static.json qatjs compress --static static
dist/graph.json, dist/graph/**/*.json, .qat/graph.json qatjs compress, qatjs dev (graph.md) graph (v2: the slices' index maps chunk → part)
GET /__qat/fragment a federation remote's server fragment
qatjs check --json, check --unused --json, explain --json, env --json the CLI check, unused, explain, variables
qatjs migrate --config … --json the CLI migrate-config
qatjs budget --json, budgetTable() the CLI, @qatjs/graph/budget budget
upgrade-ledger.json (in @qatjs/toolchain) each release that changes an API; read by qatjs upgrade upgrade-ledger
dist/custom-elements.json (--lib) qatjs compress --lib the standard Custom Elements Manifest (its own $schema and schemaVersion)
the @qatjs/vitals beacon the browser vitals

The schemas ship in @qatjs/schemas (@qatjs/schemas/schemas/<name>/v<n>.json). Read a file through readManifest: it takes any version ever written, including the unversioned files from before schemas (v0), and returns the current shape, validated. A file from a newer Qat is refused.

JavaScript4 lines
import { readManifest, validate } from '@qatjs/schemas'

const remote = readManifest(await (await fetch('https://pay.example/qat.json')).json(), 'qat')
validate(JSON.parse(readFileSync('dist/csp.json', 'utf8'))) // [] when valid

qatjs check --json was a bare array until 0.9.0-rc.1. --json=0 still prints that array until 0.10.0 (the first entry of the upgrade ledger); readManifest(json, 'check') reads both.

qat.json and proof.json may be signed (ed25519): qatjs federate --sign key.pem adds a signature over the file's canonical JSON. qatjs verify dist/qat.json --key public.pem checks the schema and that signature. Make a key with openssl genpkey -algorithm ed25519 -out key.pem and its public half with openssl pkey -in key.pem -pubout -out public.pem.

Audience builds

One app, a build per audience: a route that only some users may see can be left out of the others' builds entirely, instead of being hidden behind a guard.

JavaScript11 lines
// routes.js
import { layout, page, router } from '@qatjs/router'

export default router({
  '/': layout('./layouts/shell.qx', {
    '/': page('./pages/home.qx'),
    '/reports': page('./pages/reports.qx', { audience: ['officer', 'admin'] }),
    '/admin': page('./pages/admin.qx', { audience: ['admin'] }),
  }),
  '*': page('./pages/404.qx'),
})
shell2 lines
cd ../bundle-cases
qatjs compress --audience officer --audience admin

writes dist/officer/ and dist/admin/, one build each (the example is examples/bundle-cases):

  • Absent, not hidden. A page whose audience does not name the build's audience is cut from the route table before anything is compiled. Nothing only it reaches is ever imported: its components, stores, styles and t() keys, its path and its to helper, and the runtime units only it used (core trimming reads the same graph). In dist/officer/ above, a grep for anything of /admin (or for the name admin) finds nothing; the audience lists themselves are dropped from every build. A page without audience is in every build; a layout goes when all its pages do. audience is read at build time: write it as a list of string literals on page() (QX-AUDIENCE-VALUE otherwise).
  • Links are checked. A link (<a href>, navigate(), to.…()) from code a build ships to a route that build does not have is QX-AUDIENCE-LINK: it fails qatjs compress --audience for that build, and qatjs check reports it for every audience the tables name, at the link. Show the link from code only that route's audience reaches (the admin layout, not the shell), or add the audience to the route. It is suppressed like a lint (// qat-ignore QX-AUDIENCE-LINK).
  • Each build is complete: its own index.html with SRI, csp.json, audit.json (only the packages that build ships) and audience.json: the routes it has and how many were removed.
  • --audience names one of the audiences the tables name; anything else is an error listing them. Without --audience, qatjs compress builds every route, as before.

Only page(…, { audience }) removes code from a build. can() of @qatjs/policy decides in the browser what a user sees; it removes nothing, so a route every audience's table lists ships to every audience.

Locale-split messages

With a locales/ folder at the app root (locales/en.json, locales/az.json, … flat keys or nested objects), qatjs compress splits the dictionaries by chunk instead of shipping one per locale. Every call of an imported t with a literal key (t('cart.title')) is a request for that key; a template key takes its static prefix (t(`nav.${k}`) asks for every nav.* key); any other argument asks for every key, and that chunk gets the whole dictionary (i18n.json says why).

  • Each chunk that asks for keys gets one file per locale, assets/i18n/<chunk>.<locale>-<hash>.json ({ "$schema", "version": 1, "locale", "messages" }) with only its keys, and registers them first thing when it runs: await (globalThis.__qat_i18n ||= []).push([import.meta.url, { en: [url, integrity], … }]).
  • A helper (@qatjs/core/i18n, or your own on the same protocol, as examples/bundle-cases/src/i18n.js) takes the entries registered before it loaded, then answers each push with a fetch of the active locale's file (with its SRI hash), so a route's chunk runs once its messages are in. A locale change fetches that locale's file of every chunk loaded so far, and nothing more. In qatjs dev there are no chunks: the helper reads locales/<locale>.json whole.
  • dist/i18n.json lists each chunk's files and, per route and locale, every file the route loads, for a server that picks the locale from Accept-Language and preloads them; and the keys a locale lacks. The example's Playwright suite checks that a route fetches only its own files for the active locale and that a switch fetches the others.

Semantic shaking: qat.shake.json

Tree shaking removes unused exports. A library can go further — drop the features its callers never select — when it declares how in a qat.shake.json next to its package.json. The compiler tells qatjs compress which functions of which packages are called, with which constant arguments; nothing is guessed about a package without the file.

shell1 line
qatjs compress

With the example's date formatter (vendor/tiny-date), an app that only calls format(d, 'yyyy-MM-dd') ships none of its month and day names, and one that also calls format(d, 'd MMMM yyyy', 'az') ships the English and Azerbaijani names, not the German ones. dist/shake.json lists every flag, kept or dropped, with the calls that decided it. The library's side:

JSON14 lines
{
  "$schema": "https://qat.dev/schema/shake/v1.json",
  "version": 1,
  "flags": {
    "__TINY_DATE_NAMES__": "month and day names (MMMM, MMM, EEEE, EEE)",
    "__TINY_DATE_AZ__": "the az names"
  },
  "calls": {
    "format": [
      { "arg": 1, "match": "MMM|EEE", "keep": ["__TINY_DATE_NAMES__"] },
      { "arg": 2, "equals": "az", "keep": ["__TINY_DATE_AZ__"] }
    ]
  }
}
  • flags are identifiers the library's own modules read as booleans, written to run unbuilt too: const AZ = typeof __TINY_DATE_AZ__ === 'undefined' || __TINY_DATE_AZ__. In the library's files (only there), compress replaces each with true or false, and the minifier removes what a false gates, its imports included.
  • calls describe the exports of the package's main entry. A rule keeps its flags when the export is called and argument arg (0-based) is not a constant, or is a constant that equals (a string or a list) or matches (a regular expression); a rule without arg keeps them whenever the export is called. A missing argument is undefined, which selects nothing.
  • What the reader cannot follow keeps everything it could reach: the export passed as a value (dates.map(format)), a spread call, the namespace used as an object, a re-export, require() or import() of the package, an import of a subpath.
  • An invalid file is an error naming it; a package without one is left as it is.

No first-party package ships a qat.shake.json: @qatjs/core/i18n carries no rules per locale (plural and number rules are the browser's Intl; its dictionaries are split by chunk, above), and @qatjs/ui is copied into the app (qatjs add), so its components are the app's own code, which the minifier already shakes.

Libraries: --lib

shell3 lines
cd ../lib-elements
qatjs compress --lib
cd ../shop

builds a package of components for other apps, from src/index.ts (or .js):

  • dist/index.js: ESM, with the package's dependencies and peerDependencies left as imports (qat is the app's), source maps, and each component's <style> registering itself: there is no stylesheet to link.
  • dist/index.d.ts: the declarations of every source (dist/types/), components typed with their props and events.
  • dist/custom-elements.json: the standard Custom Elements Manifest, one entry per define('tag', Component) call: the attributes and properties from the component's props (types, defaults and doc comments from its signature; an array or object prop is a property only), and the events from its emits<…>(), each a CustomEvent with its detail type. Editors, Storybook and documentation tools read it.
TypeScript7 lines
// counter.qx
/** A counter that starts at `count` and moves by `step`. */
export default function Counter({ count = 0, step = 1 }: { count?: number; step?: number }) {
  let emit = emits<{ change: [value: number] }>()
  …
}
define('qat-counter', Counter)

Any app then uses the elements: in React 19, <qat-counter count={n} onchange={(e) => setN(e.detail)} /> sets the props as properties and listens to the event (examples/lib-react uses examples/lib-elements this way, with a Playwright test). Point package.json at the outputs: "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } } and "customElements": "dist/custom-elements.json" (compress says when they are missing).