# Zap Studio > Type-safe, framework-agnostic and composable TypeScript libraries for the web. # Getting Started Source: https://www.zapstudio.dev/docs Zap Studio is a set of small TypeScript packages for the code every app needs: HTTP calls, retries, permission checks, validation, logs, webhooks. Pick the one you need, install it, use it. No new runtime, no framework. This page takes about five minutes. At the end you will have a typed HTTP call that retries on failure. ## Before You Start You need Node.js 18, Bun 1.0, Deno 1.42, a current Cloudflare Workers release, or an evergreen browser. [Runtimes](/docs/runtimes) has the full matrix, including the four packages that ask for more. TypeScript 5 or later is recommended — the packages work in plain JavaScript, but the types are the point. ## Install Your First Package Start with [`fetch`](/docs/fetch). It makes an HTTP call and validates the response against a schema. ```bash npm npm install @zap-studio/fetch zod ``` ```bash yarn yarn add @zap-studio/fetch zod ``` ```bash pnpm pnpm add @zap-studio/fetch zod ``` ```bash bun bun add @zap-studio/fetch zod ``` ```bash deno deno add jsr:@zap-studio/fetch npm:zod ``` You also need a schema library that implements [Standard Schema](https://standardschema.dev) — Zod, Valibot, or ArkType. This page uses Zod. ## Make a Typed Call A **schema** describes the shape you expect back. You pass it to `api.get`, which validates the response at runtime and infers the type from it. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.email(), }); // `user` is typed from UserSchema — no manual annotations, no `as` casts const user = await api.get("https://jsonplaceholder.typicode.com/users/1", UserSchema); console.log(user.name); ``` Run it. You get: ```txt Leanne Graham ``` Change `name: z.string()` to `name: z.number()` and run it again. The call throws a `ValidationError` instead of handing you bad data. That is the whole idea: the response is checked before your code touches it. ## Add a Second Package Packages compose. Wrap the same call in a retry policy so a flaky network does not break it. ```bash npm npm install @zap-studio/retry ``` ```bash yarn yarn add @zap-studio/retry ``` ```bash pnpm pnpm add @zap-studio/retry ``` ```bash bun bun add @zap-studio/retry ``` ```bash deno deno add jsr:@zap-studio/retry ``` A **retry policy** decides how many attempts to make and how long to wait between them. `exponentialBackoff` doubles the delay after each failure, up to a cap. ```ts import { api } from "@zap-studio/fetch"; import { exponentialBackoff, runRetryPolicy } from "@zap-studio/retry"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.email(), }); const policy = exponentialBackoff({ maxAttempts: 3, // total attempts, including the first baseDelayMs: 100, // first retry waits 100 ms maxDelayMs: 2_000, // later retries never wait longer than 2 s }); const user = await runRetryPolicy(policy, () => api.get("https://jsonplaceholder.typicode.com/users/1", UserSchema), ); console.log(user.name); ``` Same output, three attempts instead of one. Point the URL at `https://jsonplaceholder.typicode.com/nope` and watch it try three times before it throws. ## Pick Your Package Fourteen packages, each one standalone. The **Packages** selector in the sidebar lists them all, with a one-line summary of each. ## Where to Go Next **[Composition](/docs/composition)** Stack several packages on one request: retries, caching, verified webhooks. **[Installation](/docs/installation)** npm and JSR, peer dependencies, subpath imports. **[Runtimes](/docs/runtimes)** Node, Bun, Deno, Workers and browser support, per package. **[Principles](/docs/principles)** The four rules every package follows — and where Zap Studio stops. Or go deeper on what you just built: [`fetch` Getting Started](/docs/fetch/getting-started) for error handling, POST/PUT/DELETE and configured clients, [`retry` Getting Started](/docs/retry/getting-started) for jitter, cancellation and result objects instead of throws. --- # cache Source: https://www.zapstudio.dev/docs/cache `cache` is a zero-dependency in-memory key-value cache with pluggable eviction policies, capacity limits, and optional TTL. ## Motivation A hand-rolled `Map`-based cache without a capacity limit is a memory leak waiting to happen — nothing ever gets removed. Reaching for a library instead usually means choosing between something that bakes in one eviction algorithm (LRU only, no LFU or FIFO) or a full-featured cache far bigger than a lean cache needs (cost-based sizing, stale-while-revalidate). `cache` keeps the core cache policy-agnostic: `createCache(capacity, options?)` handles storage, capacity, and TTL, while the eviction algorithm is a small object you pass in. Five are built in — `lru()`, `lfu()`, `mru()`, `mfu()`, and `fifo()` — and the `EvictionPolicy` interface is public, so you can write your own without forking the package. ## Features - **[Eviction policies](/docs/cache/eviction-policies)**: `lru()` (default), `lfu()`, `mru()`, `mfu()`, and `fifo()`, swappable via `createCache(capacity, { policy })`. - **[Capacity and eviction](/docs/cache/capacity-and-eviction)**: a count-based `capacity` evicts one entry — chosen by the configured policy — right before an insert that would exceed it. - **[TTL](/docs/cache/ttl)**: optional and lazy, checked on `get`/`has`/`peek`, no background sweep timer. A cache-wide default and a per-entry override. - **[`onEvict`](/docs/cache/on-evict)**: fires on capacity or TTL eviction — not on manual `delete()` or `clear()`. - **[`peek`](/docs/cache/peek)**: reads a value without affecting eviction order. - **[Custom policies](/docs/cache/custom-policies)**: `EvictionPolicy` is a public interface — implement your own algorithm (random replacement, ...) as a plain object, no subclassing. - **[Iteration](/docs/cache/iteration)**: `keys()`, `values()`, `entries()`, and `[Symbol.iterator]()` walk live entries in insertion order. - **Tree-shakeable** — every policy has its own subpath export (`@zap-studio/cache/lru`, `/lfu`, `/mru`, `/mfu`, `/fifo`); unused policies are dropped by any modern bundler. ## Quick Start ```ts import { createCache } from "@zap-studio/cache"; const cache = createCache(100); // lru() by default cache.set("a", 1); cache.get("a"); // 1 cache.has("a"); // true cache.size; // 1 ``` ## Runtime Support | Runtime | Minimum version | | ------------------ | --------------------------------------- | | Node.js | 18.0.0 | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Chrome/Edge 98, Firefox 97, Safari 15.4 | The package ships standard ESM only and uses no runtime-specific APIs. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/cache`). ## Learn More - [Getting Started](/docs/cache/getting-started) — install and build your first cache step by step - [Eviction Policies](/docs/cache/eviction-policies) — `lru()`, `lfu()`, `mru()`, `mfu()`, `fifo()` - [Capacity and Eviction](/docs/cache/capacity-and-eviction) - [TTL](/docs/cache/ttl) - [`onEvict`](/docs/cache/on-evict) - [`peek`](/docs/cache/peek) - [Custom Policies](/docs/cache/custom-policies) - [Iteration](/docs/cache/iteration) --- # Capacity and Eviction Source: https://www.zapstudio.dev/docs/cache/capacity-and-eviction `createCache(capacity, options?)` bounds the cache to `capacity` live entries. `capacity` must be a positive integer — a non-integer or non-positive value throws a `RangeError`. ```ts createCache(0); // throws RangeError createCache(1.5); // throws RangeError createCache(100); // ok ``` ## When Eviction Runs Eviction happens inside `set(...)`, only when **both** are true: - the key being set is new (not already in the cache), and - the cache is already at `capacity`. The configured [eviction policy](/docs/cache/eviction-policies) picks the victim key via `evict()`, and it is removed before the new entry is inserted. ```ts const cache = createCache(2); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // over capacity + new key -> evicts one entry first cache.size; // 2 ``` ## Updating an Existing Key Never Evicts A `set(...)` call for a key already present only updates its value — it never grows `size`, so it never triggers eviction, no matter how full the cache is. ```ts const cache = createCache(2); cache.set("a", 1); cache.set("b", 2); cache.set("a", 10); // "a" already exists — no eviction cache.size; // 2 cache.get("a"); // 10 cache.has("b"); // true ``` ## When the Policy Has Nothing to Evict If `evict()` returns `undefined` (an empty policy) or a key no longer present in the store, `createCache` inserts the new entry anyway without removing anything — `size` can then exceed `capacity`. This only happens with a hand-written [custom policy](/docs/cache/custom-policies); the built-in `lru()`, `lfu()`, `mru()`, `mfu()`, and `fifo()` always return a live key when the cache isn't empty. ## `capacity` and `size` Both are exposed as readonly properties on the returned `Cache`: ```ts const cache = createCache(3); cache.set("a", 1); cache.set("b", 2); cache.capacity; // 3 cache.size; // 2, live entries only — expired entries don't count ``` ## See Also - [Eviction Policies](/docs/cache/eviction-policies) — `lru()`, `lfu()`, `mru()`, `mfu()`, `fifo()` - [TTL](/docs/cache/ttl) — the other way entries leave the cache - [`onEvict`](/docs/cache/on-evict) — observe capacity and TTL evictions --- # Custom Policies Source: https://www.zapstudio.dev/docs/cache/custom-policies `EvictionPolicy` is the public interface `createCache(...)` consumes for eviction decisions. Implementations own all ordering/eviction state privately — the core cache never inspects it directly, only calls its hooks. Write one when the built-in [`lru()`, `lfu()`, `mru()`, `mfu()` and `fifo()`](/docs/cache/eviction-policies) don't match your eviction rules. ## Implement `EvictionPolicy` All five hooks are required — there are no optional members or defaults to fall back on. ```ts import type { EvictionPolicy } from "@zap-studio/cache/types"; interface EvictionPolicy { onGet: (key: K) => void; onSet: (key: K) => void; onDelete: (key: K) => void; evict: () => K | undefined; clear: () => void; } ``` | Hook | Called by the cache when... | | ---------- | ---------------------------------------------------------------------------------------------------------- | | `onGet` | a live (non-expired) read via `get(key)` succeeds. Not called for `peek(key)`. | | `onSet` | `set(key, value)` inserts or updates `key`. | | `onDelete` | `delete(key)` removes `key`. Not called for capacity or TTL evictions. | | `evict` | the cache needs a victim key on an over-capacity insert. Return `undefined` when there's nothing to evict. | | `clear` | `clear()` is called on the cache — reset all internal policy state. | ## Example: Random Replacement Evicts a uniformly random live key — cheap to implement, no per-access bookkeeping. ```ts import type { EvictionPolicy } from "@zap-studio/cache/types"; const random = (): EvictionPolicy => { const keys = new Set(); return { onGet: () => { // random replacement ignores access pattern }, onSet: (key) => { keys.add(key); }, onDelete: (key) => { keys.delete(key); }, evict: () => { const values = [...keys]; if (values.length === 0) return undefined; const victim = values[Math.floor(Math.random() * values.length)]; keys.delete(victim); return victim; }, clear: () => { keys.clear(); }, }; }; ``` ## Guidelines - `evict()` must remove its own bookkeeping for the returned key — the cache does not call `onDelete` for you after eviction. - Return `undefined` from `evict()` only when the policy has genuinely nothing to evict; returning a key not present in the cache is safe (the cache ignores it) but skips eviction that call. - Keep hooks side-effect free beyond internal bookkeeping — they run synchronously inside `get`/`set`/`delete`/`clear`. - Prefer O(1) or O(log n) operations in `onGet`/`onSet`/`evict` — they run on every cache access. ## See Also - [Eviction Policies](/docs/cache/eviction-policies) — the built-in `lru()`, `lfu()`, `mru()`, `mfu()`, `fifo()` for reference implementations - [Capacity and Eviction](/docs/cache/capacity-and-eviction) — when `evict()` is called --- # Eviction Policies Source: https://www.zapstudio.dev/docs/cache/eviction-policies `createCache(capacity, options?)` delegates the choice of victim key to an `EvictionPolicy` — a plain object implementing five hooks (`onGet`, `onSet`, `onDelete`, `evict`, `clear`). Five are built in, each from its own subpath so unused ones stay out of your bundle. ```ts import { createCache } from "@zap-studio/cache"; import { fifo } from "@zap-studio/cache/fifo"; import { lfu } from "@zap-studio/cache/lfu"; import { lru } from "@zap-studio/cache/lru"; import { mfu } from "@zap-studio/cache/mfu"; import { mru } from "@zap-studio/cache/mru"; const lruCache = createCache(100, { policy: lru() }); const lfuCache = createCache(100, { policy: lfu() }); const mruCache = createCache(100, { policy: mru() }); const mfuCache = createCache(100, { policy: mfu() }); const fifoCache = createCache(100, { policy: fifo() }); ``` ## `lru()` — Least Recently Used The default when `policy` is omitted. Both `get` and `set` count as use and move the key to the most-recently-used end. Implemented with a `Map`, whose keys iterate in insertion order — a delete-then-reinsert moves a key to the end in O(1), giving exact (not approximate) LRU ordering. ```ts const cache = createCache(2); // lru() by default cache.set("a", 1); cache.set("b", 2); cache.get("a"); // "a" is now most-recently-used cache.set("c", 3); // evicts "b", not "a" cache.has("a"); // true cache.has("b"); // false ``` ## `lfu()` — Least Frequently Used Evicts the key with the lowest access frequency, tracked with per-frequency bucket lists for O(1) `evict()`. Both `onGet` and a repeated `onSet` bump a key's frequency. Ties within the same frequency break by oldest insertion. ```ts import { lfu } from "@zap-studio/cache/lfu"; const cache = createCache(2, { policy: lfu() }); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // "a" now has frequency 2, "b" has frequency 1 cache.set("c", 3); // evicts "b" (lowest frequency) cache.has("a"); // true cache.has("b"); // false ``` ## `mru()` — Most Recently Used The inverse of `lru()`: evicts the most-recently-used key instead of the oldest. Useful when the entry you just touched is the least likely to be reused — for example, a one-pass scan over a large sequence, where each key is used once and never again. Implemented with a doubly-linked key list for O(1) touch and O(1) eviction, giving exact (not approximate) MRU ordering. ```ts import { mru } from "@zap-studio/cache/mru"; const cache = createCache(2, { policy: mru() }); cache.set("a", 1); cache.set("b", 2); // "b" is now most-recently-used cache.set("c", 3); // evicts "b", not "a" cache.has("a"); // true cache.has("b"); // false ``` ## `mfu()` — Most Frequently Used The inverse of `lfu()`: evicts the key with the highest access frequency instead of the lowest, tracked with the same per-frequency bucket lists for O(1) `evict()`. Ties within the same frequency break by oldest insertion. ```ts import { mfu } from "@zap-studio/cache/mfu"; const cache = createCache(2, { policy: mfu() }); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // "a" now has frequency 2, "b" has frequency 1 cache.set("c", 3); // evicts "a" (highest frequency) cache.has("a"); // false cache.has("b"); // true ``` ## `fifo()` — First In, First Out Evicts the oldest inserted key, regardless of access pattern. `get` never affects eviction order, and a repeated `set` on an already-tracked key does not move it. ```ts import { fifo } from "@zap-studio/cache/fifo"; const cache = createCache(2, { policy: fifo() }); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // ignored by fifo — does not save "a" cache.set("c", 3); // evicts "a" (oldest inserted) cache.has("a"); // false cache.has("b"); // true ``` ## See Also - [Capacity and Eviction](/docs/cache/capacity-and-eviction) — when eviction runs - [Custom Policies](/docs/cache/custom-policies) — implement `EvictionPolicy` yourself --- # Getting Started Source: https://www.zapstudio.dev/docs/cache/getting-started ## Installation ```bash npm npm install @zap-studio/cache ``` ```bash yarn yarn add @zap-studio/cache ``` ```bash pnpm pnpm add @zap-studio/cache ``` ```bash bun bun add @zap-studio/cache ``` ```bash deno deno add jsr:@zap-studio/cache ``` ## Create a Cache `createCache(capacity, options?)` returns a cache bounded to `capacity` live entries, using `lru()` by default. ```ts import { createCache } from "@zap-studio/cache"; const cache = createCache(100); ``` `capacity` must be a positive integer — `createCache` throws a `RangeError` otherwise. ## Set and Get Values ```ts cache.set("user:1", 42); cache.get("user:1"); // 42 cache.get("user:2"); // undefined cache.has("user:1"); // true ``` ## Let It Evict Once the cache is full, inserting a new key evicts one entry first — which one depends on the configured [eviction policy](/docs/cache/eviction-policies). ```ts const cache = createCache(2); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // evicts "a" (least recently used) cache.has("a"); // false ``` Updating an existing key never triggers eviction — only an insert that grows past `capacity` does. ## Pick an Eviction Policy Import a policy factory and pass it via `options.policy`: ```ts import { createCache } from "@zap-studio/cache"; import { fifo } from "@zap-studio/cache/fifo"; const cache = createCache(100, { policy: fifo() }); ``` See [Eviction Policies](/docs/cache/eviction-policies) for `lru()`, `lfu()`, `mru()`, `mfu()`, and `fifo()`. ## Add a TTL Pass `ttl` (in milliseconds) to expire entries automatically. TTL is lazy — checked on `get`/`has`/`peek`, no background timer. ```ts const cache = createCache(100, { ttl: 60_000 }); cache.set("session:1", { userId: 1 }); // expires in 60s ``` See [TTL](/docs/cache/ttl) for per-entry overrides. :::note Any function that returns a plain object implementing `EvictionPolicy` works as a `policy` — see [Custom Policies](/docs/cache/custom-policies) to write your own. ::: --- # Iteration Source: https://www.zapstudio.dev/docs/cache/iteration `Cache` exposes `keys()`, `values()`, `entries()`, and `[Symbol.iterator]()`. All four walk live (non-expired) entries in insertion order, and none of them notify the eviction policy — iterating never changes what gets evicted next. ```ts for (const [key, value] of cache) { console.log(key, value); } ``` ## `keys()`, `values()`, `entries()` Each returns an `IterableIterator` you can spread or loop over directly: ```ts const cache = createCache(3); cache.set("a", 1); cache.set("b", 2); [...cache.keys()]; // ["a", "b"] [...cache.values()]; // [1, 2] [...cache.entries()]; // [["a", 1], ["b", 2]] ``` ## `[Symbol.iterator]()` Makes `Cache` itself iterable, delegating to `entries()`: ```ts for (const [key, value] of cache) { console.log(key, value); } [...cache]; // [["a", 1], ["b", 2]] ``` ## Expired Entries Are Skipped Iteration checks TTL the same way `get`/`has`/`peek` do, but skips an expired entry instead of removing it from the store — no `onEvict` fires during iteration. ```ts const cache = createCache(3); cache.set("a", 1, { ttl: 100 }); cache.set("b", 2); // ... 101ms later ... [...cache.keys()]; // ["b"] — "a" is skipped, not removed ``` ## Insertion Order, Not Access Order Iteration order always follows insertion order, regardless of the configured eviction policy — even with `lru()`, `lfu()`, `mru()`, or `mfu()` active, `entries()` does not reorder itself by recency or frequency. Only `evict()` consults the policy's own internal order. ## See Also - [TTL](/docs/cache/ttl) — how expiry is determined - [Capacity and Eviction](/docs/cache/capacity-and-eviction) --- # onEvict Source: https://www.zapstudio.dev/docs/cache/on-evict `onEvict(key, value)` is an optional callback passed to `createCache(...)`. It fires whenever an entry is removed automatically — by capacity eviction or TTL expiry — and never for a removal you asked for explicitly. ```ts const cache = createCache(2, { onEvict: (key, value) => console.log("evicted", key, value), }); ``` ## When It Fires | Trigger | `onEvict` called? | | ------------------------------------------- | ------------------ | | Capacity eviction (`set` over capacity) | Yes | | TTL expiry discovered by `get`/`has`/`peek` | Yes | | Manual `delete(key)` | No | | `clear()` | No (not per entry) | ### Capacity Eviction ```ts const evicted: Array<[string, number]> = []; const cache = createCache(1, { onEvict: (key, value) => evicted.push([key, value]), }); cache.set("a", 1); cache.set("b", 2); // evicts "a" evicted; // [["a", 1]] ``` ### TTL Expiry Fires the first time an expired entry is discovered — via `get`, `has`, or `peek` — not at the moment it actually expires, since there is no background timer. ```ts const cache = createCache(2, { onEvict: (key, value) => console.log("expired", key, value), ttl: 100, }); cache.set("a", 1); // ... 101ms later ... cache.get("a"); // logs "expired a 1", then returns undefined ``` ### Not Called for `delete` or `clear` ```ts const onEvict = vi.fn(); const cache = createCache(2, { onEvict }); cache.set("a", 1); cache.delete("a"); // onEvict not called cache.clear(); // onEvict not called, even with more entries present ``` `delete` and `clear` are actions you took directly, not something the cache decided on its own — `onEvict` is reserved for evictions the cache initiates. ## See Also - [Capacity and Eviction](/docs/cache/capacity-and-eviction) - [TTL](/docs/cache/ttl) --- # peek Source: https://www.zapstudio.dev/docs/cache/peek `peek(key)` reads a value the same way `get(key)` does, but without notifying the eviction policy — so it never affects `lru()`/`mru()` recency or `lfu()`/`mfu()` frequency. It still respects TTL: an expired entry is removed and `undefined` is returned, same as `get`. ```ts cache.peek("a"); // same as get(), but no recency/frequency bump ``` ## Why It Exists Sometimes you need to look at a cached value without that look counting as "use" — for example, inspecting cache contents for metrics or debugging, or checking a value opportunistically without wanting it to outlive entries that are actually being used. ```ts const cache = createCache(2); // lru() by default cache.set("a", 1); cache.set("b", 2); cache.peek("a"); // does not mark "a" as recently used cache.set("c", 3); // evicts "a" anyway — peek didn't save it cache.has("a"); // false cache.has("b"); // true ``` Compare with `get`, which would have kept `"a"` alive by bumping its recency: ```ts const cache = createCache(2); cache.set("a", 1); cache.set("b", 2); cache.get("a"); // marks "a" as recently used cache.set("c", 3); // evicts "b" instead cache.has("a"); // true cache.has("b"); // false ``` ## Missing and Expired Keys `peek` returns `undefined` for a missing key, and also for an expired key — removing it from the store and firing [`onEvict`](/docs/cache/on-evict) if configured, exactly like `get` does. ```ts cache.peek("missing"); // undefined cache.set("a", 1, { ttl: 100 }); // ... 101ms later ... cache.peek("a"); // undefined — expired and removed, onEvict fires ``` ## See Also - [Eviction Policies](/docs/cache/eviction-policies) — what `get`/`set` bump that `peek` skips - [TTL](/docs/cache/ttl) --- # TTL Source: https://www.zapstudio.dev/docs/cache/ttl TTL (time-to-live) is optional and lazy — there is no background timer sweeping expired entries. Expiry is checked only when an entry is touched via `get`, `has`, or `peek`. An entry with no applicable `ttl` never expires. ## Cache-Wide Default Pass `ttl` (milliseconds) to `createCache(...)` to apply it to every entry that doesn't specify its own: ```ts const cache = createCache(100, { ttl: 60_000 }); // 60s default cache.set("a", 1); // expires in 60s ``` ## Per-Entry Override Pass `{ ttl }` as the third argument to `set(...)` to override the cache-wide default for that entry: ```ts const cache = createCache(100, { ttl: 60_000 }); cache.set("a", 1); // expires in 60s (cache-wide default) cache.set("b", 2, { ttl: 5_000 }); // expires in 5s, overriding the default ``` ## No Default, No Expiry Omitting `ttl` on both the cache and the entry means that entry never expires: ```ts const cache = createCache(100); // no ttl configured cache.set("a", 1); // never expires ``` ## How Expiry Is Checked Each entry stores an absolute `expiresAt` timestamp (`Date.now() + ttl` at the time of `set`). `get`, `has`, and `peek` compare it against the current time on every call: - **Expired**: the entry is removed from the store, [`onEvict`](/docs/cache/on-evict) fires if configured, and the call returns `undefined` (`get`/`peek`) or `false` (`has`). - **Live**: the call proceeds normally. ```ts const cache = createCache(2, { ttl: 100 }); cache.set("a", 1); // ... 101ms later ... cache.get("a"); // undefined — expired and removed cache.has("a"); // false ``` Because expiry is lazy, an expired entry that is never read stays in the underlying store (and counts toward nothing, since `size` only counts live entries) until the next touch or a capacity eviction reclaims the slot. ## Interaction with `size` `size` only counts live (non-expired) entries — an expired entry that hasn't been touched yet is not counted: ```ts const cache = createCache(2, { ttl: 100 }); cache.set("a", 1); // ... 101ms later, "a" still physically in the store ... cache.size; // 0 — expired entries don't count ``` ## Iteration Skips Expired Entries `keys()`, `values()`, `entries()`, and `[Symbol.iterator]()` all skip expired entries without removing them from the store or firing `onEvict` — see [Iteration](/docs/cache/iteration). ## See Also - [`onEvict`](/docs/cache/on-evict) — fires when a TTL expiry is discovered - [Capacity and Eviction](/docs/cache/capacity-and-eviction) — the other way entries leave the cache --- # Composition Source: https://www.zapstudio.dev/docs/composition Each package works alone. They also stack, because none of them owns the call stack: a policy, a cache and a router are values you pass around. These are the combinations worth knowing. ## Retry a Validated Call `fetch` validates the response, `retry` decides how often to try again. The retry policy wraps the call, so a schema failure and a network failure are both retried the same way. ```ts import { api } from "@zap-studio/fetch"; import { exponentialBackoff, runRetryPolicy } from "@zap-studio/retry"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const policy = exponentialBackoff({ maxAttempts: 3, baseDelayMs: 100, maxDelayMs: 2_000, }); const user = await runRetryPolicy(policy, () => api.get("https://api.example.com/users/1", UserSchema), ); ``` Retrying everything is rarely what you want: a `400` will fail the same way three times. A [custom policy](/docs/retry/custom-policies) decides per attempt — its `next` returns `shouldRetry: false` for an error that will not fix itself, so only transient failures cost you the extra attempts. ## Cache What You Just Fetched `cache` sits in front of the call. The typed result goes in, so what comes back out of the cache is typed too. ```ts import { createCache } from "@zap-studio/cache"; import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); type User = z.infer; const users = createCache(100, { ttl: 60_000 }); const getUser = async (id: string): Promise => { const hit = users.get(id); if (hit) { return hit; } const user = await api.get(`https://api.example.com/users/${id}`, UserSchema); users.set(id, user); return user; }; ``` TTL is lazy: an entry expires when it is next read, not on a timer, so this adds no background work. ## Verify, Route, Then Authorize a Webhook `webhooks` verifies the signature and validates the payload before your handler runs. `permit` decides whether this caller may act on the resource. `logger` records both. ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { allow, createPolicy, when } from "@zap-studio/permit"; import { createWebhookRouter } from "@zap-studio/webhooks"; import { z } from "zod"; const logger = new ConsoleLogger({ minLevel: "info" }); const policy = createPolicy<{ tenantId: string }>({ resources: { invoice: z.object({ id: z.string(), tenantId: z.string() }) }, actions: { invoice: ["read", "settle"] }, rules: { invoice: { read: allow(), settle: when((context, _action, invoice) => context.tenantId === invoice.tenantId), }, }, }); const router = createWebhookRouter({ prefix: "/webhooks", logger }); router.register("/invoices/paid", { schema: z.object({ id: z.string(), tenantId: z.string() }), handler: async ({ payload }) => { const allowed = await policy.can({ tenantId: payload.tenantId }, "invoice:settle", payload); if (!allowed) { logger.warn("rejected invoice", { id: payload.id }); return Response.json({ error: "forbidden" }, { status: 403 }); } return Response.json(`settled ${payload.id}`); }, }); export default { fetch: (request: Request) => router.handle(request) }; ``` Three checks run before your logic: the signature, the payload shape, then the permission. Each one fails on its own terms — `401`, `400`, `403` — instead of one handler guessing what went wrong. ## Validate the Environment, Then Build the Client `env` fails at startup when a variable is missing, so the client below never has to handle an undefined base URL. ```ts import { createEnvironment } from "@zap-studio/env"; import { createFetch } from "@zap-studio/fetch"; import { ConsoleLogger } from "@zap-studio/logger"; import { z } from "zod"; export const env = createEnvironment({ server: { API_URL: z.string().url(), API_TOKEN: z.string().min(1), }, runtimeEnvStrict: { API_URL: process.env.API_URL, API_TOKEN: process.env.API_TOKEN, }, }); export const { api } = createFetch({ baseURL: env.API_URL, headers: { Authorization: `Bearer ${env.API_TOKEN}` }, logger: new ConsoleLogger({ minLevel: "debug" }), }); ``` A missing `API_URL` now crashes the process on boot with the variable named, instead of sending a request to `undefined/users/1` in production. ## One Logger for All of Them `fetch`, `permit`, `retry` and `webhooks` each accept an optional `logger?: Logger`. Pass the same instance to all four and one request produces one ordered story: the outgoing call, the retry, the permission decision, the response. ```ts import { ConsoleLogger, jsonFormat } from "@zap-studio/logger"; export const logger = new ConsoleLogger({ minLevel: "info", format: jsonFormat }); ``` `Logger` is an interface, not a class you must use — any object with the six level methods works, so this can forward into the logging setup you already run. See [Observability](/docs/logger/opentelemetry) for the tracing side. ## Errors as Values Every recipe above throws on failure. If you would rather branch on a result, `monads` gives the same flows a `Result` shape, and `validation` gives one `ValidationError` shape whatever schema library produced the issue. ## Next **[Principles](/docs/principles)** Why the packages compose instead of integrating. **[Runtimes](/docs/runtimes)** What each package needs from its runtime. --- # env Source: https://www.zapstudio.dev/docs/env `env` checks an env object you already have (`process.env`, `import.meta.env`, dotenv output, or anything else) against a [Standard Schema](https://standardschema.dev/schema)-based `shared`/`server`/`client` shape. It does not read or parse files itself. It works the same way in Node, Deno, Bun, Cloudflare Workers, edge runtimes, and the browser, with any bundler or framework. It does not scan env vars itself. This is why it does not break the static `process.env`/`import.meta.env` replacement that bundlers use. But that replacement only works on a literal `process.env.X` line in your own code. For `client` vars, use [`runtimeEnvStrict`](/docs/env/advanced-options#runtimeenvstrict) and write each key on its own line. Do not pass the whole object instead. ## Motivation It uses the same `server`/`client`/`shared` split as [t3-env](https://env.t3.gg), the package most people use for this job today. A server secret cannot leak into a client bundle by accident. But t3-env still has real problems: its `extends` does a flat merge with no conflict check, so a key can silently get dropped or overwritten. Its presets do not cover Cloudflare Workers or Deno Deploy. And framework support needs its own packages, like `env-nextjs` and `env-nuxt`, tying the core package to one framework. [envin](https://envin.turbostarter.dev) already fixes some of this. It adds a CLI, better preset and `extends` support, and a live env preview. `env` goes further in two ways: its `extends` merges schemas at the key level and throws right away if two sources use the same key with two different schemas, and it ships presets for Cloudflare Workers and Deno Deploy, which neither t3-env nor envin do. Instead of a live preview through a dev server, `env` takes a simpler, static approach: [`generateEnvironmentExample`](/docs/env/generate-env-example) builds a `.env.example` file straight from your schema. No dev server needed, so it's safe to run in CI and commit. ## Features - **Full type safety** — the parsed env object is inferred from your schemas. - **Standard Schema support** — works with Zod, Valibot, ArkType, or any compatible library. - **[`server`/`client`/`shared` split](/docs/env/server-client-shared)** with `clientPrefix`, checked at both the type level and at runtime. - **[Schema composition](/docs/env/extends)** via `extends`, with reference-equality conflict detection. - **[Platform presets](/docs/env/presets)** for common hosting providers. - **[`.env.example` generation](/docs/env/generate-env-example)** via `generateEnvironmentExample(...)`. - **[Structured errors](/docs/env/errors)**: `EnvironmentError`, `EnvironmentValidationError`, and `EnvironmentAccessError`. - **[Optional OpenTelemetry support](/docs/env/opentelemetry)** through a single `env.validate` span — zero cost until an app registers an SDK. - **Tree-shakeable** — `createEnvironment`, `generateEnvironmentExample`, presets, and errors are plain functions and objects. ## Quick Start ```ts import { createEnvironment } from "@zap-studio/env"; import { z } from "zod"; export const env = createEnvironment({ server: { DATABASE_URL: z.string().url(), }, client: { NEXT_PUBLIC_API_URL: z.string().url(), }, clientPrefix: "NEXT_PUBLIC_", runtimeEnvStrict: { DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, }, }); env.DATABASE_URL; // server-only: throws if read from a client bundle env.NEXT_PUBLIC_API_URL; // readable everywhere ``` ## Learn More - [Getting Started](/docs/env/getting-started) — install and validate your first env schema - [`server`/`client`/`shared`](/docs/env/server-client-shared) — the split, `clientPrefix`, and the access guard - [`extends`](/docs/env/extends) — composing reusable schemas across packages - [Presets](/docs/env/presets) — env vars hosting platforms set automatically - [`generateEnvironmentExample`](/docs/env/generate-env-example) — schema-driven `.env.example` generation - [Errors](/docs/env/errors) — `EnvironmentError`, `EnvironmentValidationError`, `EnvironmentAccessError` - [Advanced Options](/docs/env/advanced-options) — `skipValidation`, `emptyStringAsUndefined`, `runtimeEnvStrict` - [OpenTelemetry](/docs/env/opentelemetry) — the `env.validate` span ## Runtime Support | Runtime | Minimum version | | ------------------ | ------------------------------------------------ | | Node.js | 18.0.0 | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Latest evergreen (Chrome, Edge, Firefox, Safari) | The package ships standard ESM only and uses no runtime-specific APIs. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/env`). --- # Advanced Options Source: https://www.zapstudio.dev/docs/env/advanced-options These `createEnvironment` options cover less common setups — partial build steps, blank env vars, and env objects that can't be spread from `process.env` directly. ## `skipValidation` Bypasses validation and parsing — the declared keys are read from `runtimeEnv` and returned as-is, unvalidated. `clientPrefix` checks, `extends` conflict checks, and the server-only access guard on the client still run: ```ts createEnvironment({ server: { DATABASE_URL: z.string().url() }, runtimeEnv: process.env, skipValidation: process.env["SKIP_ENV_VALIDATION"] === "true", }); ``` Useful for partial build steps — for example, a Docker build stage where not every var is available yet, but the build still needs to run without crashing on missing secrets. ## `emptyStringAsUndefined` Treats `""` as `undefined` for every declared key, before validation: ```ts createEnvironment({ server: { PORT: z.coerce.number().default(3000) }, runtimeEnv: process.env, emptyStringAsUndefined: true, }); ``` Some deployment tools set an env var to an empty string instead of leaving it unset. Without this option, `z.coerce.number()` would try to coerce `""`, which produces `NaN` rather than falling back to a schema default. ## `runtimeEnvStrict` Used instead of `runtimeEnv` when set. Its main job is `client` vars. A bundler (webpack, Next.js, Vite) only inlines a var into the browser bundle when it sees a literal `process.env.X` (or `import.meta.env.X`) line in your own code. `runtimeEnv: process.env` does not give it that — it is one runtime object, and the bundler cannot see inside it at build time. So the var never makes it into the client bundle. Instead, list each key on its own line: ```ts createEnvironment({ server: { DATABASE_URL: z.string().url() }, client: { NEXT_PUBLIC_API_URL: z.string().url() }, clientPrefix: "NEXT_PUBLIC_", runtimeEnvStrict: { DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, }, }); ``` TypeScript requires every declared `server`/`client`/`shared` key to be there, so you cannot miss one by accident. A schema with no `client` bucket has nothing for a bundler to inline. A plain `runtimeEnv: process.env` is fine there. `runtimeEnvStrict` is also useful when you can only build the object from several sources — for example, framework-injected values merged with `process.env`. Just keep every var a client bundle needs on its own literal line, not inside a spread: ```ts createEnvironment({ server: { DATABASE_URL: z.string().url() }, runtimeEnv: process.env, runtimeEnvStrict: { DATABASE_URL: process.env.DATABASE_URL, REQUEST_ID: frameworkInjectedVars.REQUEST_ID, }, }); ``` `runtimeEnv` is still required even when `runtimeEnvStrict` is set. This keeps the type of both options tied to a plain env object. ## See Also - [Getting Started](/docs/env/getting-started) — the core options - [Errors](/docs/env/errors) — what `EnvironmentValidationError` looks like when `skipValidation` is off --- # Errors Source: https://www.zapstudio.dev/docs/env/errors `env` throws three structured errors, each covering a different failure: a bad setup, a failed validation, and an out-of-bounds read. All three extend `Error`. ## `EnvironmentError` Thrown by `createEnvironment` and [`generateEnvironmentExample`](/docs/env/generate-env-example) when the schema itself is misconfigured — not a runtime validation failure: - a `client` key declared without a `clientPrefix` - a `client` key that doesn't start with the configured `clientPrefix` - a key declared by more than one composed [`extends`](/docs/env/extends) source with two different schemas ```ts import { EnvironmentError } from "@zap-studio/env/errors"; try { createEnvironment({ extends: [base, override], runtimeEnv: process.env }); } catch (error) { if (error instanceof EnvironmentError) { console.error(error.message); } } ``` ## `EnvironmentValidationError` Thrown by `createEnvironment` when one or more declared vars fail Standard Schema validation, and no [`onValidationError`](#custom-validation-handling) callback is provided. | Property | Type | Description | | ------------- | --------------------------------------------------- | ---------------------------------------------------- | | `invalidKeys` | `readonly string[]` | The keys that failed validation. Never their values. | | `issues` | `Record` | The full Standard Schema issues, per invalid key. | ```ts import { createEnvironment, EnvironmentValidationError } from "@zap-studio/env"; import { z } from "zod"; try { const env = createEnvironment({ server: { PORT: z.coerce.number() }, runtimeEnv: process.env, }); } catch (error) { if (error instanceof EnvironmentValidationError) { console.error("Invalid env vars:", error.invalidKeys); } } ``` Every key's issues are collected — the error is not thrown on the first invalid key, so `invalidKeys` and `issues` always report the full picture in one pass. ### Custom Validation Handling Pass `onValidationError` to run your own logic instead of throwing `EnvironmentValidationError` — for example, to format a startup error message. It receives the same per-key issues and must throw or otherwise never return: ```ts createEnvironment({ server: { PORT: z.coerce.number() }, runtimeEnv: process.env, onValidationError: (issues) => { console.error("Invalid environment variables:", Object.keys(issues).join(", ")); process.exit(1); }, }); ``` ## `EnvironmentAccessError` Thrown by the object `createEnvironment` returns when client-side code reads a `server`-only key, and no `onInvalidAccess` callback is provided. See [`server`/`client`/`shared`](/docs/env/server-client-shared#the-access-guard) for when this fires and how to override it with `onInvalidAccess`. | Property | Type | Description | | -------- | -------- | -------------------------------------- | | `key` | `string` | The server-only key that was accessed. | ```ts import { EnvironmentAccessError } from "@zap-studio/env"; try { env.DATABASE_URL; // server-only key, accessed from the browser } catch (error) { if (error instanceof EnvironmentAccessError) { console.error(error.message); } } ``` ## Subpath Import All three errors are also available from the dedicated `@zap-studio/env/errors` subpath, for consumers who prefer granular imports: ```ts import { EnvironmentAccessError, EnvironmentError, EnvironmentValidationError, } from "@zap-studio/env/errors"; ``` ## See Also - [`server`/`client`/`shared`](/docs/env/server-client-shared) — where `EnvironmentError` and `EnvironmentAccessError` come from - [`extends`](/docs/env/extends) — the conflict case that throws `EnvironmentError` - [Advanced Options](/docs/env/advanced-options) — `skipValidation` to bypass `EnvironmentValidationError` entirely --- # extends Source: https://www.zapstudio.dev/docs/env/extends `extends` reuses an `EnvironmentSchema` object — a plain object with the same `shared`/`server`/`client`/`clientPrefix` shape `createEnvironment` accepts, minus the runtime-specific options. This works like `tsconfig.json`'s `extends`, which reuses a base config. A shared package exports a plain object satisfying `EnvironmentSchema`: ```ts // packages/db/src/env-schema.ts import type { EnvironmentSchema } from "@zap-studio/env"; import { z } from "zod"; export const dbEnvironmentSchema = { server: { DATABASE_URL: z.string().url() }, } satisfies EnvironmentSchema; ``` An app composes it in via `extends`: ```ts // apps/api/src/env.ts import { createEnvironment } from "@zap-studio/env"; import { dbEnvironmentSchema } from "@your-org/db"; import { z } from "zod"; export const env = createEnvironment({ extends: [dbEnvironmentSchema], server: { PORT: z.coerce.number().default(3000) }, runtimeEnv: process.env, }); env.DATABASE_URL; // typed and validated, from dbEnvironmentSchema env.PORT; // typed and validated, from this call's own schema ``` `extends` accepts a list, composed in order — typically the `extends` entries followed by the call's own `shared`/`server`/`client`. ## Conflict Detection If two composed sources declare the same key with two different schemas, `createEnvironment` throws an [`EnvironmentError`](/docs/env/errors) right away, instead of silently letting one overwrite the other: ```ts createEnvironment({ extends: [{ server: { PORT: z.string() } }], server: { PORT: z.coerce.number() }, // ❌ EnvironmentError: "PORT" declared with two different schemas runtimeEnv: process.env, }); ``` There is one exception: when both sources use the **exact same schema object reference**. This can happen when two packages import one shared constant: ```ts import { PORT_SCHEMA } from "@your-org/shared-schemas"; const dbEnvironmentSchema = { server: { PORT: PORT_SCHEMA } } satisfies EnvironmentSchema; const cacheEnvironmentSchema = { server: { PORT: PORT_SCHEMA } } satisfies EnvironmentSchema; createEnvironment({ extends: [dbEnvironmentSchema, cacheEnvironmentSchema], // fine — same schema object, no conflict runtimeEnv: process.env, }); ``` Standard Schema has no generic introspection API, so structural schema-equivalence (two different `z.string()` calls that happen to produce the same rules) can't be reliably detected. Reference equality is the honest, buildable signal for "this is safe to merge." ## `clientPrefix` Per Source Each composed `EnvironmentSchema` carries its own `clientPrefix`, checked independently — see [`server`/`client`/`shared`](/docs/env/server-client-shared) for the full rule. ## `generateEnvironmentExample` Also Accepts `extends` `extends` works the same way for [`generateEnvironmentExample`](/docs/env/generate-env-example), so a generated `.env.example` includes every var from every composed source. ## See Also - [Presets](/docs/env/presets) — ready-made `EnvironmentSchema` objects for hosting platforms, composed the same way - [Errors](/docs/env/errors) — the exact `EnvironmentError` messages thrown on conflict --- # generateEnvironmentExample Source: https://www.zapstudio.dev/docs/env/generate-env-example `generateEnvironmentExample(...)` reads a schema and returns a `.env.example` file as a string. The schema has the same `shared`/`server`/`client`/`extends` shape as `createEnvironment`, minus the runtime-only options — no `runtimeEnv` is needed, since no real values are ever read. ```ts import { writeFileSync } from "node:fs"; import { generateEnvironmentExample } from "@zap-studio/env"; import { z } from "zod"; writeFileSync( ".env.example", generateEnvironmentExample({ server: { DATABASE_URL: z.string().url() }, client: { NEXT_PUBLIC_API_URL: z.string().url() }, clientPrefix: "NEXT_PUBLIC_", }), ); ``` ```ini # server, required DATABASE_URL= # client, required, prefix: NEXT_PUBLIC_ NEXT_PUBLIC_API_URL= ``` Because it never touches an actual environment, this is safe to run as a CI step and commit the result — your `.env.example` stays in sync with the schema without anyone maintaining it by hand. ## One Line Per Key Keys are sorted alphabetically, and each one gets a comment stating: - its bucket — `shared`, `server`, or `client` - whether it's `required` or `optional` - for `client` keys, the enforced `prefix` ## Required vs. Optional A key is marked `optional` when its schema accepts `undefined`. `generateEnvironmentExample` checks this by calling the schema with `undefined` and seeing whether that passes: - `z.string().optional()` — passes, marked `optional` - `z.string().default("x")` — passes (the default fills in), marked `optional` - `z.string()` — fails, marked `required` An async schema can't be checked this way synchronously, so it's conservatively reported as `required`. ## Composing With `extends` `extends` works the same way it does for `createEnvironment` — see [`extends`](/docs/env/extends) and [Presets](/docs/env/presets). A generated `.env.example` includes every var from every composed source: ```ts import { generateEnvironmentExample } from "@zap-studio/env"; import { vercel } from "@zap-studio/env/presets"; import { z } from "zod"; generateEnvironmentExample({ extends: [vercel], server: { DATABASE_URL: z.string().url() }, }); ``` ## Errors `generateEnvironmentExample` throws the same [`EnvironmentError`](/docs/env/errors) as `createEnvironment` for a bad setup: a missing `clientPrefix`, a `client` key that doesn't match it, or a conflicting `extends` key. ## See Also - [`server`/`client`/`shared`](/docs/env/server-client-shared) — what each bucket comment means - [`extends`](/docs/env/extends) — composing schemas before generating the file --- # Getting Started Source: https://www.zapstudio.dev/docs/env/getting-started This page walks you through installing `@zap-studio/env` and validating your first env object. For deeper details, check the other pages in this section. ## Install ```bash npm npm install @zap-studio/env ``` ```bash yarn yarn add @zap-studio/env ``` ```bash pnpm pnpm add @zap-studio/env ``` ```bash bun bun add @zap-studio/env ``` ```bash deno deno add jsr:@zap-studio/env ``` You also need a schema library that implements [Standard Schema](https://standardschema.dev/), such as Zod, Valibot, or ArkType. ## Define a Schema Split your vars into `server` (server-only) and `client` (readable everywhere, exposed to the browser). Use `shared` for vars that don't need the client/server split at all. ```ts import { z } from "zod"; const schema = { server: { DATABASE_URL: z.string().url(), }, client: { NEXT_PUBLIC_API_URL: z.string().url(), }, clientPrefix: "NEXT_PUBLIC_", }; ``` `clientPrefix` is required as soon as `client` is declared — see [`server`/`client`/`shared`](/docs/env/server-client-shared) for why. ## Validate Your Env Call `createEnvironment(...)` with the schema and the resolved env object to validate against. ```ts import { createEnvironment } from "@zap-studio/env"; import { z } from "zod"; export const env = createEnvironment({ server: { DATABASE_URL: z.string().url(), }, client: { NEXT_PUBLIC_API_URL: z.string().url(), }, clientPrefix: "NEXT_PUBLIC_", runtimeEnvStrict: { DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, }, }); ``` Each var is on its own line. Bundlers (webpack, Next.js, Vite) replace a literal `process.env.X` line at build time — they cannot do this with a spread of the whole object. This matters for `client` vars, since they must end up in the browser bundle. See [Advanced Options](/docs/env/advanced-options#runtimeenvstrict) for when `runtimeEnv: process.env` is fine instead. If any declared var fails validation, `createEnvironment` throws an [`EnvironmentValidationError`](/docs/env/errors) listing every invalid key. ## Read Values The returned `env` object is fully typed from your schemas. On the server, every declared var is readable. Off the server, reading a `server`-only key throws instead of silently returning `undefined`. ```ts env.DATABASE_URL; // string — throws if read from a client bundle env.NEXT_PUBLIC_API_URL; // string — readable everywhere ``` `isServer` defaults to `typeof window === "undefined"`. Set it yourself when that default is wrong, such as in some edge or SSR contexts — see [`server`/`client`/`shared`](/docs/env/server-client-shared). ## Next Steps - [`server`/`client`/`shared`](/docs/env/server-client-shared) — the full split, `clientPrefix`, and the access guard - [`extends`](/docs/env/extends) — reuse schemas across packages and apps - [Presets](/docs/env/presets) — type vars your hosting platform already sets - [`generateEnvironmentExample`](/docs/env/generate-env-example) — keep `.env.example` in sync with your schema --- # OpenTelemetry Source: https://www.zapstudio.dev/docs/env/opentelemetry `@opentelemetry/api` is a required peer dependency of `@zap-studio/env`. It's a tiny, side-effect-free package that's a no-op until an app registers a real SDK, so installing it costs nothing at runtime for consumers who never set one up. ```bash npm npm install @opentelemetry/api ``` ```bash yarn yarn add @opentelemetry/api ``` ```bash pnpm pnpm add @opentelemetry/api ``` ```bash bun bun add @opentelemetry/api ``` ```bash deno deno add npm:@opentelemetry/api ``` There's no option to configure — instrumentation is always on, and does nothing observable until your app registers an OpenTelemetry SDK: ```ts import { createEnvironment } from "@zap-studio/env"; import { z } from "zod"; // If your app has registered an OpenTelemetry SDK, this call now produces a // span. If not, it does nothing. No extra setup is needed either way. export const env = createEnvironment({ server: { PORT: z.coerce.number() }, runtimeEnv: process.env, }); ``` ## The `env.validate` Span Each `createEnvironment` validation pass gets an `INTERNAL` span named `env.validate`. On failure, the span carries the invalid key names — never their values — as the `env.invalid_keys` attribute, and is marked as an error, with the thrown error recorded via `recordException`. Validation itself runs once at startup, not per-request, so the span cost is negligible. ## Skipped Validation, No Span When [`skipValidation`](/docs/env/advanced-options#skipvalidation) is `true`, `createEnvironment` returns early before the `env.validate` span is created — there's nothing to trace, since no validation actually runs. ## Log Correlation Pair this with [`logger`](/docs/logger/opentelemetry): once a span is active, `ConsoleLogger` automatically stamps `trace_id`/`span_id` onto every log line, so anything you log around startup lines up with the `env.validate` span. ## See Also - [Errors](/docs/env/errors) — `EnvironmentValidationError`, whose `invalidKeys` end up on the span - [Advanced Options](/docs/env/advanced-options) — `skipValidation` and when the span is skipped --- # Presets Source: https://www.zapstudio.dev/docs/env/presets Presets cover env vars that a hosting platform sets on its own — deployment IDs, git metadata, region, and so on. Compose one into `createEnvironment` (or `generateEnvironmentExample`) via [`extends`](/docs/env/extends) to type and validate a platform's vars alongside your app's own: ```ts import { createEnvironment } from "@zap-studio/env"; import { vercel } from "@zap-studio/env/presets"; import { z } from "zod"; export const env = createEnvironment({ extends: [vercel], server: { DATABASE_URL: z.string().url() }, runtimeEnv: process.env, }); env.VERCEL_GIT_COMMIT_SHA; // string | undefined ``` ## Every Key Is Optional Every preset key is typed `string | undefined`. These vars are only present when the app is actually running on that platform, and this package never reads or parses files, so it can't detect the platform itself — you decide which presets apply, usually by knowing where the app deploys. ## Available Presets | Preset | Platform | Docs | | ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------- | | `vercel` | Vercel | [System environment variables](https://vercel.com/docs/environment-variables/system-environment-variables) | | `netlify` | Netlify | [Read-only build variables](https://docs.netlify.com/build/configure-builds/environment-variables/) | | `render` | Render | [Environment variables](https://render.com/docs/environment-variables) | | `railway` | Railway | [Variables reference](https://docs.railway.com/variables/reference) | | `fly` | Fly.io Machines | [Runtime environment](https://fly.io/docs/machines/runtime-environment/) | | `coolify` | Coolify | [Predefined variables](https://coolify.io/docs/knowledge-base/environment-variables) | | `cloudflare` | Cloudflare Pages | [Build configuration](https://developers.cloudflare.com/pages/configuration/build-configuration/) | | `denoDeploy` | Deno Deploy | [Env vars and contexts](https://docs.deno.com/deploy/reference/env_vars_and_contexts/) | All eight are available from `@zap-studio/env/presets` and can be imported individually — only the ones you import end up in your bundle. ```ts import { cloudflare, denoDeploy, netlify, vercel } from "@zap-studio/env/presets"; ``` ## Composing Multiple Presets Presets compose like any other `EnvironmentSchema` — pass more than one to `extends` if your app can run on more than one platform: ```ts createEnvironment({ extends: [vercel, cloudflare], runtimeEnv: process.env, }); ``` Presets never share keys with each other, so there's no conflict risk between them — see [`extends`](/docs/env/extends) for how conflicts are detected in general. ## See Also - [`extends`](/docs/env/extends) — how schema composition and conflict detection work - [Getting Started](/docs/env/getting-started) — your first schema, without presets --- # server / client / shared Source: https://www.zapstudio.dev/docs/env/server-client-shared Every schema — passed to `createEnvironment` or `generateEnvironmentExample` — can declare up to three buckets: | Bucket | Readable on server | Readable on client | Prefix required | | -------- | ------------------ | ------------------ | ------------------- | | `shared` | Yes | Yes | No | | `server` | Yes | No — throws | No | | `client` | Yes | Yes | Yes, `clientPrefix` | ```ts import { createEnvironment } from "@zap-studio/env"; import { z } from "zod"; export const env = createEnvironment({ shared: { NODE_ENV: z.enum(["development", "production", "test"]), }, server: { DATABASE_URL: z.string().url(), }, client: { NEXT_PUBLIC_API_URL: z.string().url(), }, clientPrefix: "NEXT_PUBLIC_", runtimeEnvStrict: { NODE_ENV: process.env.NODE_ENV, DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL, }, }); ``` `client` vars need `runtimeEnvStrict`, with each key on its own `process.env.X` line. See [Advanced Options](/docs/env/advanced-options#runtimeenvstrict) for why a plain `runtimeEnv: process.env` does not survive bundling. `shared` vars are validated once and carry no prefix requirement — use them for values that aren't secrets and don't need the client/server split at all, such as `NODE_ENV`. ## `clientPrefix` Is Required With `client` As soon as a schema declares any `client` key, `clientPrefix` becomes required. Every `client` key must start with it, checked both at the type level and at runtime: ```ts createEnvironment({ client: { API_URL: z.string().url() }, // ❌ type error: does not start with "NEXT_PUBLIC_" clientPrefix: "NEXT_PUBLIC_", runtimeEnv: process.env, }); ``` At runtime, a mismatched key or a missing `clientPrefix` throws an [`EnvironmentError`](/docs/env/errors) — this is a setup mistake, not a validation failure. ## The Access Guard Off the server — `isServer: false`, or the default `typeof window === "undefined"` check evaluating to `false` — the object `createEnvironment` returns is wrapped in a `Proxy`. Reading a `server`-only key through that proxy throws an [`EnvironmentAccessError`](/docs/env/errors) instead of silently returning the value (or `undefined`): ```ts // In a browser bundle, isServer defaults to false: env.DATABASE_URL; // throws EnvironmentAccessError env.NEXT_PUBLIC_API_URL; // fine — client and shared vars are always readable ``` This mirrors, at runtime, the same split that build-time tools (bundler dead-code elimination, `NEXT_PUBLIC_` inlining, and so on) already try to enforce — except it holds even when a bundler doesn't catch it. ## Detecting "Server" `isServer` defaults to `typeof window === "undefined"`. Override it for contexts where that default doesn't hold, such as some edge runtimes or custom SSR setups: ```ts createEnvironment({ server: { DATABASE_URL: z.string().url() }, runtimeEnv: process.env, isServer: process.env["RUNTIME"] === "edge-with-server-access", }); ``` ## Custom Access Handling Pass `onInvalidAccess` to run your own logic instead of throwing `EnvironmentAccessError` — for example, to log the offending key before crashing, or to integrate with an error-reporting service. It must throw or otherwise never return: ```ts createEnvironment({ server: { DATABASE_URL: z.string().url() }, runtimeEnv: process.env, onInvalidAccess: (key) => { reportError(`Server-only env var "${key}" was read from the client.`); throw new Error(`Blocked client access to "${key}".`); }, }); ``` See [Errors](/docs/env/errors) for the full error and callback reference. ## See Also - [`extends`](/docs/env/extends) — each composed source carries its own `clientPrefix` - [Errors](/docs/env/errors) — `EnvironmentError` and `EnvironmentAccessError` in detail --- # fetch Source: https://www.zapstudio.dev/docs/fetch `fetch` is a small fetch wrapper with [**Standard Schema**](https://standardschema.dev/schema) response validation. ## Motivation Raw `fetch` does not throw on HTTP errors like 404 or 500 — you must check `response.ok` yourself. And it does not check that the JSON body matches what your code expects. So most projects add the same pattern at every call site: check the status, parse the JSON, then validate it with `schema.parse(await res.json())`. It is easy to forget one of these steps somewhere, and that is how bad data or a network error goes unnoticed until it breaks something downstream. `fetch` makes this pattern the default, not something you write by hand. `api.get(url, UserSchema)` checks the response, validates the body, and throws a clear, typed error — `FetchError` for a bad HTTP status, `ValidationError` for a bad shape — so you always know what went wrong and where. It uses [Standard Schema](https://standardschema.dev/schema), so you are not locked into one validation library: start with Zod, move to Valibot later, and the call sites do not change. And because it only wraps the global `fetch` function, it is not a Node-only HTTP client — it runs the same way on Bun, Deno, Cloudflare Workers, and in the browser. ## Features - **Raw fetch mode** through `$fetch(input, options)` — behaves like native `fetch` and returns the `Response`. - **Validated fetch mode** through `$fetch(input, schema, options)` — parses and validates the JSON response. - **HTTP method helpers** through `api.get`, `api.post`, `api.put`, `api.patch`, and `api.delete`. - **Configured clients** through `createFetch(...)` with shared `baseURL`, headers, query params, and error defaults. - **JSON convenience** through the `json` option, which serializes the request body and sets `Content-Type`. - **Structured errors** with `FetchError` for HTTP failures and `ValidationError` for schema failures. - **Validator-agnostic** — works with any library that implements Standard Schema. - **[Optional logging](/docs/fetch/logging)** through `createFetch({ logger })` from [`logger`](/docs/logger) — omit it and there's zero logging overhead. - **[Native OpenTelemetry](/docs/fetch/opentelemetry)** — a `CLIENT` span per request with trace context injected into outgoing headers, no-op until an SDK is registered. - **Tree-shakeable** — every export is a standalone function with no shared internal state; unused exports are dropped by any modern bundler. ## Quick Start ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { createFetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.email(), }); const logger = new ConsoleLogger({ minLevel: "debug" }); const { api } = createFetch({ logger }); const user = await api.get("https://api.example.com/users/1", UserSchema); console.log(user.name); // typed as string, validated at runtime ``` ## Learn More - [Getting Started](/docs/fetch/getting-started) — install and make your first validated request. - [Raw Fetch Mode](/docs/fetch/raw-fetch-mode) — `$fetch` without a schema. - [Validated Fetch Mode](/docs/fetch/validated-fetch-mode) — `$fetch` with a schema. - [HTTP Method Helpers](/docs/fetch/api-methods) — `api.get`, `api.post`, and friends. - [Configured Clients](/docs/fetch/create-fetch) — shared defaults with `createFetch`. - [JSON Convenience](/docs/fetch/json-convenience) — the `json` request option. - [Structured Errors](/docs/fetch/errors) — `FetchError` and `ValidationError`. - [Validator-Agnostic](/docs/fetch/validation) — Standard Schema support. - [Logging](/docs/fetch/logging) — observe requests, responses, and validation failures. - [OpenTelemetry](/docs/fetch/opentelemetry) — native distributed tracing. ## Runtime Support | Runtime | Minimum version | | ------------------ | ------------------------------------------------ | | Node.js | 18.0.0 (ships native `fetch`) | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Latest evergreen (Chrome, Edge, Firefox, Safari) | The package relies on the global `fetch` API and ships standard ESM only. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/fetch`). --- # API Methods Source: https://www.zapstudio.dev/docs/fetch/api-methods `api.get`, `api.post`, `api.put`, `api.patch`, and `api.delete` are HTTP method helpers bound to `$fetch`. Use them when the HTTP method is known up front and the response should be validated. ```ts import { api } from "@zap-studio/fetch"; ``` ## Methods | Method | HTTP method | | ------------ | ----------- | | `api.get` | `GET` | | `api.post` | `POST` | | `api.put` | `PUT` | | `api.patch` | `PATCH` | | `api.delete` | `DELETE` | Each helper has the same overloads, options, and error behavior as [`$fetch`](/docs/fetch/validated-fetch-mode), but injects its HTTP method for you. The injected method always wins — a `method` passed in `options` is overridden. :::note The schema argument always validates the **response** body. It does not validate `json` or `body` request payloads. ::: ## Read Data ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.string(), name: z.string(), }); const user = await api.get("https://api.example.com/users/1", UserSchema); ``` ## Send JSON Use the `json` option for JSON request bodies. It is stringified with `JSON.stringify` and gets `Content-Type: application/json` when no content type is already set. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const CreateUserResponseSchema = z.object({ id: z.string(), name: z.string(), }); const user = await api.post("https://api.example.com/users", CreateUserResponseSchema, { json: { name: "Ada", }, }); ``` `CreateUserResponseSchema` validates the response from the server. The `json` object is only the outgoing request body. ## Use Native Body Use native `body` when sending `FormData`, `Blob`, `ReadableStream`, or an already-serialized payload. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const ProfileSchema = z.object({ id: z.string(), avatarUrl: z.string(), }); const avatarBytes = new Uint8Array([137, 80, 78, 71]); const avatar = new Blob([avatarBytes], { type: "image/png" }); const formData = new FormData(); formData.set("avatar", avatar, "avatar.png"); const profile = await api.patch("https://api.example.com/profile", ProfileSchema, { body: formData, }); ``` `body` and `json` cannot be used together — providing both throws a `TypeError`. ## Query Params `searchParams` accepts the same inputs as `new URLSearchParams(...)`. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserListSchema = z.array(z.object({ id: z.string(), name: z.string() })); const page = await api.get("https://api.example.com/users", UserListSchema, { searchParams: { page: "1", limit: "20", }, }); ``` ## Non-Throw Modes HTTP errors and validation issues throw by default. You can disable either behavior per request. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.string(), name: z.string() }); // Does not throw FetchError on non-2xx responses const user = await api.get("https://api.example.com/users/missing", UserSchema, { throwOnFetchError: false, }); // Returns a Standard Schema result object instead of throwing ValidationError const result = await api.get("https://api.example.com/users/1", UserSchema, { throwOnValidationError: false, }); if (result.issues) { console.error(result.issues); } else { console.log(result.value); } ``` See [Validation](/docs/fetch/validation) for details on the result object shape. ## Raw Responses The method helpers mirror the `$fetch` overloads, so calling one without a schema returns the native `Response`: ```ts import { api } from "@zap-studio/fetch"; const response = await api.delete("https://api.example.com/sessions/current"); console.log(response.status); ``` For clarity, prefer [`$fetch`](/docs/fetch/raw-fetch-mode) directly when raw response handling is the main goal. --- # createFetch Source: https://www.zapstudio.dev/docs/fetch/create-fetch `createFetch(...)` creates a fetch client with shared `baseURL`, headers, query params, and error defaults. It returns an independent `$fetch` function and `api` method set bound to those defaults. ## Basic Usage ```ts import { createFetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const { api, $fetch } = createFetch({ baseURL: "https://api.example.com", headers: { Authorization: `Bearer ${process.env.API_TOKEN}`, }, }); const user = await api.get("/users/1", UserSchema); const health = await $fetch("/health"); ``` The returned `$fetch` and `api` have the same overloads, options, and error behavior as the top-level exports. Each `createFetch` instance is independent. ## Options All options are optional; unset options fall back to the global defaults. | Option | Type | Default | Description | | ------------------------ | ---------------------- | ----------- | ------------------------------------------------------------------- | | `baseURL` | `string` | `""` | Base URL that relative request URLs are resolved against. | | `headers` | `HeadersInit` | `undefined` | Default headers merged into every request. Per-request headers win. | | `searchParams` | `URLSearchParams` init | `undefined` | Default query params applied to every request. | | `throwOnFetchError` | `boolean` | `true` | Default for throwing `FetchError` on non-2xx responses. | | `throwOnValidationError` | `boolean` | `true` | Default for throwing `ValidationError` on validation issues. | ## Base URL Relative URLs are resolved against `baseURL` using standard `URL` resolution. Absolute URLs keep their original origin. ```ts import { createFetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const StatusSchema = z.object({ ok: z.boolean() }); const { api } = createFetch({ baseURL: "https://api.example.com", }); await api.get("/users/1", UserSchema); await api.get("https://status.example.com/health", StatusSchema); ``` :::note Paths without a leading slash append to `baseURL`; paths with a leading slash resolve from the origin root instead. With `baseURL: "https://api.example.com/v1"`: - `"users"` → `https://api.example.com/v1/users` - `"/users"` → `https://api.example.com/users` ::: ## Headers Default headers are merged with per-request headers. Per-request headers win when the same header is set in both places. ```ts import { createFetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const defaultToken = process.env.API_TOKEN; const overrideToken = process.env.ADMIN_TOKEN; const { api } = createFetch({ baseURL: "https://api.example.com", headers: { Authorization: `Bearer ${defaultToken}`, }, }); await api.get("/users/1", UserSchema, { headers: { Authorization: `Bearer ${overrideToken}`, }, }); ``` ## Search Params Query params merge in this order, with later values winning for duplicate keys: 1. `createFetch({ searchParams })` defaults 2. query params already present in the request URL 3. per-request `searchParams` ```ts import { createFetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserListSchema = z.array(z.object({ id: z.number(), name: z.string() })); const { api } = createFetch({ baseURL: "https://api.example.com", searchParams: { locale: "en", page: "1", }, }); await api.get("/users?page=2", UserListSchema, { searchParams: { q: "ada", }, }); // Final URL: https://api.example.com/users?locale=en&page=2&q=ada ``` ## Default Throw Behavior Set throw behavior once for a client and override it per request when needed. ```ts import { createFetch } from "@zap-studio/fetch"; const { $fetch } = createFetch({ throwOnFetchError: false, }); const response = await $fetch("https://api.example.com/users/missing"); console.log(response.status); // e.g. 404, no FetchError thrown ``` :::warning[Type inference and throwOnValidationError] Return types are inferred from **per-call** options only — TypeScript cannot see client defaults. If you set `throwOnValidationError: false` as a client default, calls without the flag return the Standard Schema result object at runtime, but their inferred type is the validated data. To keep types and runtime in sync, pass `throwOnValidationError: false` explicitly at the call site: ```ts const result = await api.get("/users/1", UserSchema, { throwOnValidationError: false, }); if (result.issues) { console.error(result.issues); } ``` ::: --- # Error Handling Source: https://www.zapstudio.dev/docs/fetch/errors `fetch` throws `FetchError` for HTTP failures and `ValidationError` for schema failures. Platform and schema errors can still propagate from native `fetch`, body parsing, request construction, or the validator itself. | Error | Import path | Thrown when | | ----------------- | ------------ | -------------------------------------------------------------------------------------------------- | | `FetchError` | `fetch` | The response is not ok and `throwOnFetchError` is `true` (default). | | `ValidationError` | `validation` | A schema is provided, validation returns issues, and `throwOnValidationError` is `true` (default). | ```ts import { FetchError } from "@zap-studio/fetch"; import { ValidationError } from "@zap-studio/validation"; ``` ## FetchError Thrown for non-2xx responses before the body is parsed or validated. Its message has the form `HTTP : `. | Property | Type | Description | | ---------- | ---------- | ----------------------------------------------------------------- | | `status` | `number` | HTTP status code from the failing response. | | `response` | `Response` | Full response object for further inspection (headers, body, ...). | ```ts import { api, FetchError } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); try { await api.get("https://api.example.com/users/missing", UserSchema); } catch (error) { if (error instanceof FetchError) { console.error(error.status); console.error(await error.response.text()); } else { throw error; } } ``` Set `throwOnFetchError: false` to handle the response manually. ```ts import { $fetch } from "@zap-studio/fetch"; const response = await $fetch("https://api.example.com/users/missing", { throwOnFetchError: false, }); if (!response.ok) { console.error(response.status); } ``` :::note With `throwOnFetchError: false` and a schema provided, the error response body is still parsed and validated — which usually produces a `ValidationError` or `SyntaxError` for non-JSON error pages. Prefer schema-less `$fetch` when you need to inspect error responses. ::: ## ValidationError Thrown when the response body does not match the provided schema. Its message is a JSON string of the issues. | Property | Type | Description | | -------- | ----------------------------------- | ----------------------------------------- | | `issues` | `readonly StandardSchemaV1.Issue[]` | Validation issues reported by the schema. | ```ts import { api } from "@zap-studio/fetch"; import { ValidationError } from "@zap-studio/validation"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); try { await api.get("https://api.example.com/users/1", UserSchema); } catch (error) { if (error instanceof ValidationError) { console.error(error.issues); } else { throw error; } } ``` Set `throwOnValidationError: false` to receive the Standard Schema result object instead. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const result = await api.get("https://api.example.com/users/1", UserSchema, { throwOnValidationError: false, }); if (result.issues) { console.error(result.issues); } ``` See [Validation](/docs/fetch/validation) for the full validation flow. ## Other Throwable Errors Calls can also reject with: - `TypeError` — both `body` and `json` provided, invalid headers or search params, request construction failure, JSON request serialization failure, network failure, or a response body read failure. - `SyntaxError` — a schema is provided and `response.json()` cannot parse the body. - `DOMException` — the request or response body read is aborted (`AbortError`). - Any error thrown or rejected by the provided Standard Schema validator. ## Exhaustive Handling Catch package-specific errors first, then rethrow unknown failures. ```ts import { api, FetchError } from "@zap-studio/fetch"; import { ValidationError } from "@zap-studio/validation"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); async function loadUser(id: string) { try { const user = await api.get(`https://api.example.com/users/${id}`, UserSchema); return { ok: true as const, user }; } catch (error) { if (error instanceof FetchError) { return { ok: false as const, reason: "http", status: error.status }; } if (error instanceof ValidationError) { return { ok: false as const, reason: "validation", issues: error.issues }; } throw error; } } ``` --- # Getting Started Source: https://www.zapstudio.dev/docs/fetch/getting-started ## Installation ```bash npm npm install @zap-studio/fetch ``` ```bash yarn yarn add @zap-studio/fetch ``` ```bash pnpm pnpm add @zap-studio/fetch ``` ```bash bun bun add @zap-studio/fetch ``` ```bash deno deno add jsr:@zap-studio/fetch ``` You also need a schema library that implements [Standard Schema](https://standardschema.dev/schema), such as Zod, Valibot, or ArkType. The examples below use Zod. ## Make Your First Request Define a schema for the response shape, then pass it to `api.get`. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.email(), }); const user = await api.get("https://api.example.com/users/1", UserSchema); console.log(user.name); // typed as string, validated at runtime ``` The response is parsed and validated at runtime, and `user` is typed from `UserSchema` — no manual type annotations or `as` casts. ## Handle Errors `api.get` throws `FetchError` for non-2xx responses and `ValidationError` when the response doesn't match the schema. ```ts import { FetchError } from "@zap-studio/fetch"; import { ValidationError } from "@zap-studio/validation"; try { const user = await api.get("https://api.example.com/users/1", UserSchema); console.log(user); } catch (error) { if (error instanceof FetchError) console.error(error.status); if (error instanceof ValidationError) console.error(error.issues); } ``` :::note See [Structured Errors](/docs/fetch/errors) for the full error reference. ::: ## Next Steps - [Raw Fetch Mode](/docs/fetch/raw-fetch-mode) — skip validation, get the native `Response`. - [HTTP Method Helpers](/docs/fetch/api-methods) — `api.post`, `api.put`, `api.patch`, `api.delete`. - [Configured Clients](/docs/fetch/create-fetch) — share a `baseURL` and headers with `createFetch`. --- # JSON Convenience Source: https://www.zapstudio.dev/docs/fetch/json-convenience The `json` option serializes the request body and sets `Content-Type`. ```ts import { api } from "@zap-studio/fetch"; await api.post("/api/users", UserSchema, { json: { name: "Ada" }, }); ``` `UserSchema` still validates the response — the `json` value is only the outgoing request body and is not validated by the schema. ## What It Sets Providing `json` sets: - `body` to `JSON.stringify(json)` - `Content-Type` to `application/json`, when no content type is already set on `headers` ```ts import { $fetch } from "@zap-studio/fetch"; const user = await $fetch("https://api.example.com/users", UserSchema, { method: "POST", json: { name: "Ada" }, }); ``` ## Mutually Exclusive with `body` `json` and native `body` cannot be used together — providing both throws a `TypeError`. ```ts await $fetch("/api/upload", { method: "POST", body: formData, // use native `body` for FormData, Blob, ReadableStream, etc. }); ``` ## See Also - [Validated Fetch Mode](/docs/fetch/validated-fetch-mode) — how the response schema and `json` interact. - [HTTP Method Helpers](/docs/fetch/api-methods) — `api.post`, `api.put`, and `api.patch` examples. - [Overview](/docs/fetch) — package summary and quick start. --- # Logging Source: https://www.zapstudio.dev/docs/fetch/logging `createFetch(...)` accepts an optional `logger?: Logger` option from [`logger`](/docs/logger). Pass one to observe request internals; omit it and nothing is logged — zero overhead. ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { createFetch } from "@zap-studio/fetch"; const logger = new ConsoleLogger({ minLevel: "debug" }); const { api } = createFetch({ baseURL: "https://api.example.com", logger }); ``` ## What Gets Logged | Event | Level | Context | | ----------------------------- | ------- | ------------------------------ | | A request goes out | `debug` | `method`, `url` | | A 2xx response comes back | `debug` | `method`, `status`, `url` | | A non-2xx response comes back | `warn` | `method`, `status`, `url` | | Schema validation fails | `error` | `url`, and `error` or `issues` | A non-2xx response logs at `warn` instead of `debug` because it usually means something the caller should notice, even without `throwOnFetchError` turned on — without flooding `debug` output for every successful call. ## Bring Your Own Logger Any object implementing the `Logger` interface works, so you can forward these events into an existing logging setup instead of `ConsoleLogger`: ```ts import type { Logger } from "@zap-studio/logger"; const logger: Logger = { trace: (message, context) => myBackend.log("trace", message, context), debug: (message, context) => myBackend.log("debug", message, context), info: (message, context) => myBackend.log("info", message, context), warn: (message, context) => myBackend.log("warn", message, context), error: (message, context) => myBackend.log("error", message, context), fatal: (message, context) => myBackend.log("fatal", message, context), }; const { api } = createFetch({ logger }); ``` See [`logger`](/docs/logger) for the full `Logger` interface and `ConsoleLogger` options. --- # OpenTelemetry Source: https://www.zapstudio.dev/docs/fetch/opentelemetry `@opentelemetry/api` is a required peer dependency of `@zap-studio/fetch`. It's a tiny, side-effect-free package that's a no-op until an app registers a real SDK, so installing it costs nothing at runtime for consumers who never set one up — the same deal [`logger?`](/docs/fetch/logging) already gives. ```bash npm npm install @opentelemetry/api ``` ```bash yarn yarn add @opentelemetry/api ``` ```bash pnpm pnpm add @opentelemetry/api ``` ```bash bun bun add @opentelemetry/api ``` ```bash deno deno add npm:@opentelemetry/api ``` There's no option to configure — tracing is always on, and does nothing observable until your app registers an OpenTelemetry SDK (a Datadog agent, Honeycomb, Vercel OTel, a self-hosted collector, etc.): ```ts import { createFetch } from "@zap-studio/fetch"; const { api } = createFetch({ baseURL: "https://api.example.com" }); await api.get("/users/1", UserSchema); ``` ## What Gets Instrumented Every request produces a `CLIENT` span named after the HTTP method (e.g. `GET`), with: | Attribute | Value | | --------------------------- | ------------------------------ | | `http.request.method` | The HTTP method (e.g. `"GET"`) | | `url.full` | The resolved request URL | | `http.response.status_code` | Set once the response arrives | The span's trace context is injected into the outgoing request's headers (`traceparent`, and `tracestate` if your propagator uses it), so the call continues the caller's distributed trace instead of starting a new one. On failure — a non-2xx response, or a thrown error (network failure, aborted request, JSON parse failure, validation failure) — the span's status is set to `ERROR`. A thrown error is additionally recorded as a span exception via `recordException`. ## Edge Runtime Caveat Implicit context propagation — auto-linking the "active span" across `await` boundaries so your own spans nest correctly under the request span — depends on the host runtime supporting `AsyncLocalStorage`/`async_hooks`. Some edge runtimes don't support this reliably. Span creation and attribute-setting always work everywhere, regardless of this. Only the automatic parent/child linking across async boundaries can be affected on those runtimes. ## Log Correlation Pair this with [`logger`](/docs/logger/opentelemetry): once a span is active, `ConsoleLogger` automatically stamps `trace_id`/`span_id` onto every log line, so a request's spans and logs line up in whatever backend you send them to. --- # Raw Fetch Mode Source: https://www.zapstudio.dev/docs/fetch/raw-fetch-mode `$fetch(input, options)` behaves like native `fetch` and returns the `Response`. ```ts import { $fetch } from "@zap-studio/fetch"; const response = await $fetch("https://api.example.com/health"); console.log(response.status); console.log(response.headers.get("content-type")); ``` Use this mode for headers, status codes, streams, text, blobs, or any response that should not be parsed as JSON by the package. Non-2xx responses still throw a `FetchError` unless you set `throwOnFetchError: false`. ## Signature ```ts function $fetch(input: FetchInput, options?: ExtendedRequestInit): Promise; ``` - `input` — a `string`, `URL`, or `Request`, the same type as global `fetch`. Exported as `FetchInput`. - `options` — native `RequestInit` plus the extra options listed below. Exported as `ExtendedRequestInit`. When `input` is a `Request`, its headers are merged with per-request `headers` (per-request values win), and remaining options are applied on top: ```ts import { $fetch } from "@zap-studio/fetch"; const request = new Request("https://api.example.com/users/1", { headers: { Authorization: `Bearer ${process.env.API_TOKEN}`, }, }); const response = await $fetch(request); ``` ## Options | Option | Type | Default | Description | | ------------------- | ---------------------- | ----------- | ------------------------------------------------------ | | `searchParams` | `URLSearchParams` init | `undefined` | Per-request query params, merged into the request URL. | | `throwOnFetchError` | `boolean` | `true` | Throw a `FetchError` on non-2xx responses. | Every standard `RequestInit` option (`method`, `headers`, `body`, `signal`, ...) is also accepted. ## See Also - [Validated Fetch Mode](/docs/fetch/validated-fetch-mode) — parse and validate the JSON response instead. - [Structured Errors](/docs/fetch/errors) — `FetchError` details and catch patterns. - [Overview](/docs/fetch) — package summary and quick start. --- # Validated Fetch Mode Source: https://www.zapstudio.dev/docs/fetch/validated-fetch-mode `$fetch(input, schema, options)` parses and validates the JSON response. ```ts import { $fetch } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), }); const user = await $fetch("https://api.example.com/users/1", UserSchema); ``` The return type is inferred from the schema. The schema validates the response body only — never the request `json` or `body` options. ## Signature ```ts // Validated mode: resolves to data inferred from the schema function $fetch( input: FetchInput, schema: TSchema, options?: ExtendedRequestInit & { throwOnValidationError?: true }, ): Promise>; // Result mode: resolves to the Standard Schema result object function $fetch( input: FetchInput, schema: TSchema, options: ExtendedRequestInit & { throwOnValidationError: false }, ): Promise>>; ``` - `schema` — any object implementing Standard Schema (Zod, Valibot, ArkType, ...), exported as `StandardSchemaV1` from `validation`. ## Options | Option | Type | Default | Description | | ------------------------ | ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | | `searchParams` | `URLSearchParams` init | `undefined` | Per-request query params, merged into the request URL. | | `throwOnValidationError` | `boolean` | `true` | Throw a `ValidationError` when validation returns issues. When `false`, the Standard Schema result object is returned instead. | | `throwOnFetchError` | `boolean` | `true` | Throw a `FetchError` on non-2xx responses, before parsing or validation. | ## Non-Throw Validation Set `throwOnValidationError: false` to receive the raw Standard Schema result object instead of throwing. ```ts const result = await $fetch("https://api.example.com/users/1", UserSchema, { throwOnValidationError: false, }); if (result.issues) { console.error(result.issues); } else { console.log(result.value); } ``` ## See Also - [Raw Fetch Mode](/docs/fetch/raw-fetch-mode) — skip validation entirely. - [Validator-Agnostic](/docs/fetch/validation) — supported schema libraries and full validation flow. - [Structured Errors](/docs/fetch/errors) — `ValidationError` details and catch patterns. --- # Validation Source: https://www.zapstudio.dev/docs/fetch/validation Response validation works with any library that implements Standard Schema. `fetch` validates responses through [`validation`](/docs/validation), so any [Standard Schema](https://standardschema.dev/schema)-compatible validator can be used. :::note Schemas passed to `$fetch` or `api.*` validate **response bodies only**. They do not validate outgoing request `json` or `body` payloads. ::: ## Validation Flow When a schema is provided: 1. The HTTP request is executed. 2. If the response is not ok and `throwOnFetchError` is `true` (the default), a `FetchError` is thrown before any parsing. 3. The response body is read with `response.json()`. 4. The parsed value is validated against the provided Standard Schema. 5. The validated value is returned, or validation issues are surfaced. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const user = await api.get("https://api.example.com/users/1", UserSchema); ``` ## Supported Validators Any validator that implements Standard Schema works — the schema is passed straight through, so transforms, defaults, and refinements behave exactly as the library defines them. ```ts Zod import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string(), }); ``` ```ts Valibot import * as v from "valibot"; const UserSchema = v.object({ id: v.number(), name: v.string(), }); ``` ```ts ArkType import { type } from "arktype"; const UserSchema = type({ id: "number", name: "string", }); ``` ## Throwing Mode By default (`throwOnValidationError: true`), a `ValidationError` is thrown when the response does not match the schema. Import it from `validation`. ```ts import { api } from "@zap-studio/fetch"; import { ValidationError } from "@zap-studio/validation"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); try { const user = await api.get("https://api.example.com/users/1", UserSchema); console.log(user); } catch (error) { if (error instanceof ValidationError) { console.error(error.issues); } else { throw error; } } ``` `@zap-studio/validation` is a runtime dependency of `@zap-studio/fetch`, but install it explicitly if you import from it directly. ## Result Mode Set `throwOnValidationError: false` to receive the Standard Schema result object — `{ value }` on success, `{ issues }` on failure. ```ts import { api } from "@zap-studio/fetch"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const result = await api.get("https://api.example.com/users/1", UserSchema, { throwOnValidationError: false, }); if (result.issues) { console.error(result.issues); } else { console.log(result.value); } ``` ## Validating Request Bodies For request-body validation, validate the payload yourself before passing it to `json`. ```ts import { api } from "@zap-studio/fetch"; import { standardValidate } from "@zap-studio/validation"; import { z } from "zod"; const CreateUserInputSchema = z.object({ name: z.string() }); const UserSchema = z.object({ id: z.number(), name: z.string() }); const rawInput: unknown = { name: "Ada" }; const input = await standardValidate(rawInput, CreateUserInputSchema, { throwOnError: true, }); const user = await api.post("https://api.example.com/users", UserSchema, { json: input, }); ``` ## Standalone Validation For validation outside HTTP requests, use [`validation`](/docs/validation) directly. It also exports the `StandardSchemaV1` type when you need to type schema parameters yourself. ```ts import { standardValidate } from "@zap-studio/validation"; import type { StandardSchemaV1 } from "@zap-studio/validation"; import { z } from "zod"; const UserSchema = z.object({ id: z.number(), name: z.string() }); const input: unknown = { id: 1, name: "Ada" }; const user = await standardValidate(input, UserSchema, { throwOnError: true, }); ``` --- # Installation Source: https://www.zapstudio.dev/docs/installation Every package installs on its own. There is no meta-package, no shared runtime, and no setup step — install one, import it, use it. ## Install a Package Replace `fetch` with the package you want. ```bash npm npm install @zap-studio/fetch ``` ```bash yarn yarn add @zap-studio/fetch ``` ```bash pnpm pnpm add @zap-studio/fetch ``` ```bash bun bun add @zap-studio/fetch ``` ```bash deno deno add jsr:@zap-studio/fetch ``` npm, yarn, pnpm and bun install from npm. Deno installs from [JSR](https://jsr.io/@zap-studio), where every package is published in parallel under the same name and version. The two tooling packages are dev dependencies, since they only run at lint or format time: ```bash npm npm install --save-dev @zap-studio/oxlint oxlint ``` ```bash pnpm pnpm add -D @zap-studio/oxlint oxlint ``` ## Peer Dependencies A peer dependency is a package you install yourself, so you control its version. Most packages have none. | Package | Required peer | Optional peer | | -------------------------------------------------- | ---------------------------------------------- | -------------------- | | `env`, `logger` | `@opentelemetry/api` | — | | `fetch`, `permit`, `retry`, `webhooks` | `@opentelemetry/api` | `@zap-studio/logger` | | `oxfmt` | `oxfmt` | — | | `oxlint` | `oxlint`, `@oxlint/plugins`, `oxlint-tsgolint` | — | | `react-hooks` | `react` | — | | `cache`, `monads`, `store`, `validation`, `webmcp` | — | — | `@opentelemetry/api` is small and side-effect free. It stays a no-op until you register a real SDK, so installing it costs nothing until you want traces — see each package's OpenTelemetry page, such as [`fetch`](/docs/fetch/opentelemetry). A schema library is not a dependency of anything, but `env`, `fetch`, `permit`, `validation` and `webhooks` validate through [Standard Schema](https://standardschema.dev), so you install the one you like: Zod, Valibot or ArkType. ```bash npm install zod ``` ## Import What You Use Every package exports from its root, and most also expose one subpath per feature. Both forms give you the same function; the subpath is there when you want the smallest possible import graph. ```ts import { createCache } from "@zap-studio/cache"; import { lru } from "@zap-studio/cache/lru"; ``` `react-hooks` takes this the furthest: each of its 100+ hooks is its own module, so importing one never pulls in the rest. ```ts import { useIsMobile } from "@zap-studio/react-hooks/sensors/use-is-mobile"; ``` ## TypeScript TypeScript 5 or later is recommended. The packages run in plain JavaScript, but the types are the point — response shapes, permission checks and environment variables are all inferred from the schema you pass in. Every package ships standard ESM with its own type declarations. There is no CommonJS build, so a `require()` call will not resolve them. ## Next **[Runtimes](/docs/runtimes)** Minimum Node, Bun, Deno, Workers and browser versions, per package. **[Getting Started](/docs)** Make your first typed call in five minutes. --- # logger Source: https://www.zapstudio.dev/docs/logger `logger` gives `@zap-studio/*` packages (and your own code) an optional, pluggable way to emit logs — one interface, one console-backed implementation, with next to no dependency weight. ## Motivation Libraries like `winston` and `pino` are built for Node servers, with file transports and streams. They do not run well — or at all — on Cloudflare Workers or in the browser. This becomes a problem for small libraries that want to add logging: if a retry library or an HTTP client hard-depends on `winston`, every user of that library must install `winston`, even if they do not want logging, and even if their code runs somewhere `winston` does not. `logger` avoids this by shipping an interface, not an implementation. `Logger` is a small type with six methods (`trace`, `debug`, `info`, `warn`, `error`, `fatal`). Most `@zap-studio/*` packages that talk to the outside world — `fetch`, `permit`, `retry`, `webhooks` — accept an optional `logger: Logger`. Pass nothing, and there is no dependency and no runtime cost. Pass `ConsoleLogger`, and you get leveled, formatted output that works on Node, Bun, Deno, browsers, and Cloudflare Workers with no setup. Already use `pino`? It already exposes the same six methods, so it works as a `Logger` with no adapter code needed. ## Features - **One interface**: [`Logger`](/docs/logger/getting-started) — `trace`/`debug`/`info`/`warn`/`error`/`fatal`, each `(message: string, context?: Record) => void`. - **One implementation**: [`ConsoleLogger`](/docs/logger/getting-started), backed by the global `console` object, with a configurable `minLevel` to control verbosity. - **[Pluggable output formats](/docs/logger/formats)**: `classicFormat` (default), `jsonFormat`, `compactFormat`, `prettyFormat` — pass any function matching `LogFormatter`, no registration required. - **Minimal dependencies, tree-shakeable** — [`@opentelemetry/api`](/docs/logger/opentelemetry) is the only peer dependency, tiny and a no-op until you register an SDK; unused exports are dropped by any modern bundler. - **Optional by design** — other `@zap-studio/*` packages accept a `logger?: Logger` option; omit it and there's zero logging overhead. - **[Runtime-agnostic, zero config](/docs/logger/runtime-compatibility)** — works out of the box on Node.js, Bun, Deno, browsers, and Cloudflare Workers. - **[Automatic trace-log correlation](/docs/logger/opentelemetry)** — `ConsoleLogger` stamps the active span's `trace_id`/`span_id` onto every log call, no-op until an SDK is registered. ## Quick Start ```ts import { ConsoleLogger } from "@zap-studio/logger"; const logger = new ConsoleLogger({ minLevel: "debug" }); logger.debug("cache miss", { key: "user:42" }); logger.warn("retrying after failure", { attempt: 2 }); ``` ## Runtime Compatibility Works out of the box on Node.js, Bun, Deno, browsers, and Cloudflare Workers — no configuration needed. See [Runtime Compatibility](/docs/logger/runtime-compatibility) for how `prettyFormat`'s color detection adapts per runtime. ## Runtime Support | Runtime | Minimum version | | ------------------ | --------------------------------------- | | Node.js | 18.0.0 | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Chrome/Edge 98, Firefox 97, Safari 15.4 | Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/logger`). ## Learn More - [Getting Started](/docs/logger/getting-started) — install and use `ConsoleLogger`, and see how to implement `Logger` for a custom backend - [Output Formats](/docs/logger/formats) — `classicFormat`, `jsonFormat`, `compactFormat`, `prettyFormat`, and writing your own - [Runtime Compatibility](/docs/logger/runtime-compatibility) — how the package adapts automatically to each runtime - [OpenTelemetry](/docs/logger/opentelemetry) — automatic trace-log correlation --- # Output Formats Source: https://www.zapstudio.dev/docs/logger/formats `ConsoleLogger` accepts a `format?: LogFormatter` option, defaulting to `classicFormat` — today's `message` + `context` output. Built-in formatters are all exported from `logger` (and the dedicated `@zap-studio/logger/format` subpath). ```ts import { ConsoleLogger, jsonFormat } from "@zap-studio/logger"; const logger = new ConsoleLogger({ format: jsonFormat }); ``` ## classicFormat (default) The message, plus `context` as a second `console` argument when present. Leaves object inspection to the runtime console — collapsible in browser devtools, `util.inspect` in Node. ```ts logger.info("server started", { port: 3000 }); // console.info("server started", { port: 3000 }) ``` ## jsonFormat Single-line JSON, pino-compatible field names (`time` as epoch milliseconds, `level`, `msg`): ```ts logger.info("server started", { port: 3000 }); // {"port":3000,"time":1704067200000,"level":"info","msg":"server started"} ``` ## compactFormat Single-line `key=value` pairs (logfmt) — grep-friendly and still machine-parseable. Values containing whitespace, `"`, or `=` are quoted: ```ts logger.info("server started", { port: 3000 }); // port=3000 time=2024-01-01T00:00:00.000Z level=info msg="server started" ``` ## prettyFormat Colorized, human-friendly single-line output: a dim local clock time, a color-coded level label, then the message. `context`, when present, is still passed as a second argument for native object inspection instead of being hand-formatted: ```ts logger.info("server started", { port: 3000 }); // 12:34:56.789 INFO server started { port: 3000 } (colored) ``` Color is applied automatically per runtime, with no configuration needed — see [Runtime Compatibility](/docs/logger/runtime-compatibility) for exactly how it adapts on Node, Bun, Deno, browsers, and Cloudflare Workers. ## Field Merging (jsonFormat / compactFormat) `context` fields are flattened to the top level rather than nested under a `context` key, matching the pino/bunyan convention: ```ts logger.info("server started", { port: 3000 }); // jsonFormat: {"port":3000,"time":...,"level":"info","msg":"server started"} ``` A context field named `time`, `level`, or `msg` can never override the base field — the base fields are always applied last. `Error` and `bigint` context values are handled specially, since neither survives `JSON.stringify` on its own (`JSON.stringify(new Error("boom"))` is `"{}"`): ```ts logger.error("request failed", { error: new Error("boom") }); // jsonFormat: ...,"error":{"name":"Error","message":"boom","stack":"..."} // compactFormat: ... error="Error: boom" ``` ## Writing Your Own Any function matching `LogFormatter` works — no registration required: ```ts import type { LogFormatter, LogRecord } from "@zap-studio/logger"; const upperFormat: LogFormatter = (record: LogRecord) => [record.message.toUpperCase()]; const logger = new ConsoleLogger({ format: upperFormat }); ``` A `LogRecord` has `level`, `message`, `context` (`Record | undefined`), and `timestamp` (a `Date`, built fresh for each call that passes the `minLevel` filter). A `LogFormatter` returns the argument list `console[method](...)` gets called with — return one string for a single line, or more arguments (like `classicFormat` and `prettyFormat` do) to hand `context` off for native inspection. --- # Getting Started Source: https://www.zapstudio.dev/docs/logger/getting-started ## Installation ```bash npm npm install @zap-studio/logger ``` ```bash yarn yarn add @zap-studio/logger ``` ```bash pnpm pnpm add @zap-studio/logger ``` ```bash bun bun add @zap-studio/logger ``` ```bash deno deno add jsr:@zap-studio/logger ``` ## Use ConsoleLogger `ConsoleLogger` is the package's only built-in implementation. It logs to the global `console` object and filters calls below its `minLevel` (`"info"` by default). ```ts import { ConsoleLogger } from "@zap-studio/logger"; const logger = new ConsoleLogger(); // minLevel defaults to "info" logger.debug("this is filtered out by default"); logger.info("server started", { port: 3000 }); logger.error("request failed", { status: 500 }); ``` Lower `minLevel` to see more verbose output during development: ```ts const verboseLogger = new ConsoleLogger({ minLevel: "trace" }); ``` Raise it (or set it to `"none"`) to quiet a logger down in production: ```ts const quietLogger = new ConsoleLogger({ minLevel: "error" }); const silentLogger = new ConsoleLogger({ minLevel: "none" }); ``` `ConsoleLogger` also accepts a `format` option to switch between plain text, JSON, logfmt, or colorized output — see [Output Formats](/docs/logger/formats). ## Passing a Logger to Other Packages `retry`, `fetch`, `webhooks`, and `permit` all accept an optional `logger?: Logger` option. Passing nothing means no logging overhead at all — the package never calls into a logger it wasn't given. ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { exponentialBackoff, runRetryPolicy } from "@zap-studio/retry"; const logger = new ConsoleLogger({ minLevel: "debug" }); const policy = exponentialBackoff({ maxAttempts: 5, baseDelayMs: 100 }); await runRetryPolicy(policy, execute, { logger }); ``` ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { createWebhookRouter } from "@zap-studio/webhooks"; const logger = new ConsoleLogger({ minLevel: "debug" }); const router = createWebhookRouter({ prefix: "/webhooks", logger }); ``` Each package logs at a level that matches how noteworthy the event is — routine activity at `debug`, denials and failures at `warn`/`error`/`info` depending on the package. ## Implement a Custom Logger Any object matching the `Logger` shape works — no base class or subclassing required. This makes it straightforward to forward `@zap-studio/*` package logs into an existing logging backend (pino, a hosted log aggregator, etc.): ```ts import type { Logger } from "@zap-studio/logger"; const logger: Logger = { trace: (message, context) => myBackend.log("trace", message, context), debug: (message, context) => myBackend.log("debug", message, context), info: (message, context) => myBackend.log("info", message, context), warn: (message, context) => myBackend.log("warn", message, context), error: (message, context) => myBackend.log("error", message, context), fatal: (message, context) => myBackend.log("fatal", message, context), }; ``` --- # OpenTelemetry Source: https://www.zapstudio.dev/docs/logger/opentelemetry `@opentelemetry/api` is a required peer dependency of `@zap-studio/logger`. It's a tiny, side-effect-free package that's a no-op until an app registers a real SDK, so installing it costs nothing at runtime for consumers who never set one up. ```bash npm npm install @opentelemetry/api ``` ```bash yarn yarn add @opentelemetry/api ``` ```bash pnpm pnpm add @opentelemetry/api ``` ```bash bun bun add @opentelemetry/api ``` ```bash deno deno add npm:@opentelemetry/api ``` This is **not** a full bridge to the OTel Logs API — `Logger` already does that job well as its own abstraction, and duplicating it would be redundant. This is trace-log correlation: `ConsoleLogger` automatically stamps the active span's trace context onto every log call. ```ts import { ConsoleLogger } from "@zap-studio/logger"; const logger = new ConsoleLogger(); logger.info("checkpoint", { userId: "u1" }); ``` ## What Gets Added When a log call happens while a span is active, `trace_id` and `span_id` are merged into that call's context before formatting — so `jsonFormat`, `compactFormat`, and any custom formatter all see them like any other context field: ```json { "userId": "u1", "trace_id": "4bf92f...", "span_id": "00f067...", "level": "info", "msg": "checkpoint" } ``` If you pass an explicit `trace_id` or `span_id` in your own context, it wins — the active span's values only fill in what you didn't already provide. If no span is active (no OpenTelemetry SDK registered, or the log call happens outside any span), nothing is added — the log looks exactly like it did before this feature existed. ## Pairing With Other Packages [`fetch`](/docs/fetch/opentelemetry), [`webhooks`](/docs/webhooks/opentelemetry), and [`permit`](/docs/permit/opentelemetry) create spans; [`retry`](/docs/retry/opentelemetry) adds events to whichever span is already active. Pass a `ConsoleLogger` as those packages' `logger` option, and every log line they emit while a span is active carries that span's `trace_id`/`span_id` automatically — no extra wiring needed on top of what those packages' own [Logging](/docs/fetch/logging) pages already show. --- # Runtime Compatibility Source: https://www.zapstudio.dev/docs/logger/runtime-compatibility `logger` works out of the box on Node.js, Bun, Deno, browsers, and Cloudflare Workers — no configuration needed. `console` dispatch, level filtering, `classicFormat`, `jsonFormat`, and `compactFormat` have no runtime-specific code at all. The only per-runtime behavior is [`prettyFormat`](/docs/logger/formats)'s color detection: | Runtime | Colored? | | ------------------ | -------------------------------------------------------------------------------- | | Node / Bun / Deno | On a real TTY only, never when `NO_COLOR` is set | | Browsers | Always — devtools render ANSI fine | | Cloudflare Workers | Never — output may land in the dashboard's web log viewer, which can't render it | Node/Bun/Deno detection checks for a `process` global with `process.stdout.isTTY` and `process.env.NO_COLOR`. Cloudflare Workers is detected via `navigator.userAgent === "Cloudflare-Workers"`, [the runtime's own documented self-identification](https://developers.cloudflare.com/workers/runtime-apis/web-standards/#navigatoruseragent). Workers has no `process` global, and its output can land in `wrangler tail` (a real terminal, color-safe) or the dashboard's web log viewer (not color-safe), with no way to tell which from inside the Worker. Color stays off there to guarantee clean output either way. Anywhere else without a `process` global (browsers) colors unconditionally, on the assumption it's a devtools-like console. See [Runtime Support](/docs/logger#runtime-support) for minimum versions per runtime. --- # monads Source: https://www.zapstudio.dev/docs/monads `monads` provides `Result`, `ResultAsync`, and `Option` types with Rust-style functional combinators — an explicit, type-safe alternative to throw/catch and nullable checks. ## Motivation Hand-rolled `{ ok: boolean, ... }` result shapes and nullable checks are easy to write once and painful to keep consistent across a codebase. Libraries like [neverthrow](https://github.com/supermacro/neverthrow) and [Effect](https://effect.website/) solve this well, but pull in more surface (do-notation, a runtime, generators, `Either`, class-based fluent APIs) than most projects need. `monads` is deliberately small: `Result`, `ResultAsync`, and `Option`, as standalone, tree-shakeable functions composed with `pipe` — not class instances with chained methods. ## Features - **`Result`** — `ok`/`err` constructors, `isOk`/`isErr` guards, and `Result.map`/`Result.mapErr`/`Result.andThen`/`Result.unwrapOr`/`Result.unwrapOrElse`/`Result.unwrap`/`Result.match` combinators. - **`ResultAsync`** — a thenable wrapper around `Promise>`, awaitable directly, with chainable combinators for building async pipelines before the final `await`. - **`Option`** — `some`/`none` constructors, `isSome`/`isNone` guards, and the mirrored `Option` combinators. - **Bridges** — `fromThrowable`, `fromPromise`, `fromNullable`. - **`pipe`** — left-to-right composition for the standalone combinators above. - **Zero dependencies, tree-shakeable.** ## Quick Start ```ts import { err, ok, pipe, Result } from "@zap-studio/monads"; function parseAge(input: string): Result { const value = Number(input); return Number.isNaN(value) ? err("not a number") : ok(value); } const message = pipe( parseAge("42"), Result.map((age) => age + 1), Result.match({ ok: (age) => `Age next year: ${age}`, err: (reason) => `Invalid input: ${reason}`, }), ); ``` ## Learn More - [Getting Started](/docs/monads/getting-started) — install and use your first `Result` - [Result](/docs/monads/result) — `Result` constructors, guards, and combinators - [ResultAsync](/docs/monads/result-async) — chaining async operations that can fail - [Option](/docs/monads/option) — `Option` constructors, guards, and combinators - [Pipe](/docs/monads/pipe) — composing the standalone combinators ## Runtime Support | Runtime | Minimum version | | ------------------ | ------------------------------------------------ | | Node.js | 18.0.0 | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Latest evergreen (Chrome, Edge, Firefox, Safari) | The package ships standard ESM only and uses no runtime-specific APIs. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/monads`). --- # Getting Started Source: https://www.zapstudio.dev/docs/monads/getting-started This page walks you through installing `@zap-studio/monads` and using `Result` for a value that might fail. For deeper details, check the other pages in this section. ## Install ```bash npm npm install @zap-studio/monads ``` ```bash yarn yarn add @zap-studio/monads ``` ```bash pnpm pnpm add @zap-studio/monads ``` ```bash bun bun add @zap-studio/monads ``` ```bash deno deno add jsr:@zap-studio/monads ``` ## Write a Function That Returns a `Result` Instead of throwing, return `ok(value)` on success and `err(reason)` on failure: ```ts import { err, ok, Result } from "@zap-studio/monads"; function parseAge(input: string): Result { const value = Number(input); return Number.isNaN(value) ? err("not a number") : ok(value); } ``` ## Compose With `pipe` `Result`'s combinators are curried functions, not methods — compose them with `pipe`: ```ts import { pipe, Result } from "@zap-studio/monads"; const message = pipe( parseAge("42"), Result.map((age) => age + 1), Result.match({ ok: (age) => `Age next year: ${age}`, err: (reason) => `Invalid input: ${reason}`, }), ); ``` ## Extract the Value Use `Result.unwrapOr` for a default, `Result.unwrapOrElse` to compute a fallback from the error, or `Result.unwrap` to throw on `Err`: ```ts import { pipe, Result } from "@zap-studio/monads"; pipe(parseAge("not a number"), Result.unwrapOr(0)); // 0 ``` --- # Option Source: https://www.zapstudio.dev/docs/monads/option `Option` represents either a present value (`Some`) or its absence (`None`). It's an explicit alternative to `null`/`undefined` checks — absence is part of the type, and the compiler checks that both branches are handled. ```ts import type { Option } from "@zap-studio/monads"; ``` ## Constructors ```ts import { none, some } from "@zap-studio/monads"; some(42); // { some: true, value: 42 } none(); // { some: false } ``` ## Guards ```ts import { isNone, isSome, none, some } from "@zap-studio/monads"; isSome(some(1)); // true isNone(none()); // true ``` ## Bridging From Nullable Values ```ts import { fromNullable } from "@zap-studio/monads"; fromNullable([1, 2, 3].find((n) => n > 5)); // None fromNullable([1, 2, 3].find((n) => n > 1)); // Some(2) ``` ## Combinators All combinators live under the `Option` namespace to avoid colliding with `Result`'s combinators of the same name, and are curried — compose them with `pipe`. ```ts import { none, Option, pipe, some } from "@zap-studio/monads"; pipe( some(2), Option.map((n) => n * 2), ); // Some(4) const half = (n: number) => (n % 2 === 0 ? some(n / 2) : none()); pipe(some(4), Option.andThen(half)); // Some(2) pipe( none(), Option.orElse(() => some(0)), ); // Some(0) pipe( some(1), Option.orElse(() => some(0)), ); // Some(1), fallback not called pipe(none(), Option.unwrapOr(0)); // 0 pipe( none(), Option.unwrapOrElse(() => 99), ); // 99 pipe(some(42), Option.match({ some: (n) => `got ${n}`, none: () => "nothing" })); // "got 42" ``` `orElse` mirrors Rust's `Option::or_else`: it recovers a `None` into a fallback `Option` of the same type, and leaves a `Some` untouched without calling the fallback. ## Unwrapping `Option.unwrap` throws if the `Option` is `None`, mirroring Rust's `Option::unwrap`. ```ts import { none, Option } from "@zap-studio/monads"; Option.unwrap(none()); // throws Error("Called unwrap() on a None value") ``` Prefer `Option.match`, `Option.unwrapOr`, or `Option.unwrapOrElse` for control flow that shouldn't throw. --- # Pipe Source: https://www.zapstudio.dev/docs/monads/pipe `Result` and `Option` combinators are standalone, curried functions rather than methods — there's no `result.map().andThen()`. `pipe` is how you compose them, since TypeScript has no native pipe operator. ```ts import { pipe } from "@zap-studio/monads"; pipe(5); // 5, no functions applied pipe(5, (n) => n + 1); // 6 pipe( 5, (n) => n + 1, (n) => n * 2, ); // 12 ``` ## With `Result` ```ts import { err, ok, pipe, Result } from "@zap-studio/monads"; pipe( ok(2), Result.map((n) => n * 2), Result.andThen((n) => (n > 0 ? ok(n) : err("not positive"))), Result.unwrapOr(0), ); // 4 ``` ## With `Option` ```ts import { Option, pipe, some } from "@zap-studio/monads"; pipe( some(2), Option.map((n) => n * 2), Option.unwrapOr(0), ); // 4 ``` Each function in the chain receives the previous function's return value, left to right — `pipe(value, f, g, h)` is `h(g(f(value)))`. --- # Result Source: https://www.zapstudio.dev/docs/monads/result `Result` represents either success (`Ok`) or failure (`Err`). It's an explicit alternative to throw/catch — the possibility of failure is part of the function's return type, and the compiler checks that both branches are handled. ```ts import type { Result } from "@zap-studio/monads"; ``` ## Constructors ```ts import { err, ok } from "@zap-studio/monads"; ok(42); // { ok: true, value: 42 } err("not found"); // { ok: false, error: "not found" } ``` ## Guards ```ts import { err, isErr, isOk, ok } from "@zap-studio/monads"; isOk(ok(1)); // true isErr(err("x")); // true ``` ## Combinators All combinators live under the `Result` namespace to avoid colliding with `Option`'s combinators of the same name, and are curried — compose them with `pipe`. ```ts import { err, ok, pipe, Result } from "@zap-studio/monads"; pipe( ok(2), Result.map((n) => n * 2), ); // Ok(4) pipe( err("bad"), Result.mapErr((e) => e.toUpperCase()), ); // Err("BAD") pipe( ok("42"), Result.andThen((s) => (Number.isNaN(Number(s)) ? err("not a number") : ok(Number(s)))), ); // Ok(42) pipe( err("bad"), Result.orElse((e) => ok(e.length)), ); // Ok(3) pipe( ok(1), Result.orElse(() => ok(0)), ); // Ok(1), fallback not called pipe(err("bad"), Result.unwrapOr(0)); // 0 pipe( err("bad"), Result.unwrapOrElse((e) => e.length), ); // 3 pipe(ok(42), Result.match({ ok: (n) => `got ${n}`, err: (e) => `failed: ${e}` })); // "got 42" ``` `orElse` mirrors Rust's `Result::or_else`: it recovers an `Err` into a fallback `Result`, and leaves an `Ok` untouched without calling the fallback. ## Unwrapping `Result.unwrap` throws if the `Result` is `Err`, mirroring Rust's `Result::unwrap`. The original error is attached as `cause`. ```ts import { err, Result } from "@zap-studio/monads"; Result.unwrap(err("bad")); // throws Error("Called unwrap() on an Err value", { cause: "bad" }) ``` Prefer `Result.match`, `Result.unwrapOr`, or `Result.unwrapOrElse` for control flow that shouldn't throw. ## Wrapping Throwing Functions `fromThrowable` wraps a synchronous, potentially throwing function so it returns a `Result` instead: ```ts import { fromThrowable } from "@zap-studio/monads"; const safeParse = fromThrowable(JSON.parse, (error) => error instanceof Error ? error.message : "parse failed", ); safeParse('{"a":1}'); // Ok({ a: 1 }) safeParse("not json"); // Err("Unexpected token ...") ``` Called with just a function, `fromThrowable` uses the caught value as the `Err` error, typed as `unknown`: ```ts const safeParse = fromThrowable(JSON.parse); safeParse("not json"); // Err(SyntaxError: Unexpected token ...) ``` For asynchronous operations that can reject, see [ResultAsync](/docs/monads/result-async). --- # ResultAsync Source: https://www.zapstudio.dev/docs/monads/result-async `ResultAsync` wraps a `Promise>`. It's the one class in this package: it needs to be awaitable directly, and its combinators are instance methods so you can build an async chain before the final `await`. `Result` and `Option` stay plain discriminated unions with standalone functions — see [Result](/docs/monads/result) and [Option](/docs/monads/option). ## Creating a `ResultAsync` `fromPromise` wraps a rejecting `Promise`, mapping the rejection reason into your error type: ```ts import { fromPromise } from "@zap-studio/monads"; const user = fromPromise( fetch("/api/user").then((response) => response.json()), (error) => `request failed: ${String(error)}`, ); ``` ## Chaining ```ts import { err, fromPromise, ok } from "@zap-studio/monads"; const greeting = fromPromise( fetch("/api/user").then((response) => response.json()), (error) => `request failed: ${String(error)}`, ) .map((user) => user.name) .andThen((name) => (name.length > 0 ? ok(`Hello, ${name}`) : err("empty name"))); ``` `andThen`'s callback can return a `Result`, a `Promise`, or another `ResultAsync` — all three are awaited the same way. ## Recovering `orElse` is `andThen`'s counterpart for the failure side: it recovers an eventual `Err`, leaving an eventual `Ok` untouched. Its callback accepts the same three return shapes as `andThen`'s: ```ts const withFallback = fromPromise( fetch("/api/user").then((response) => response.json()), (error) => `request failed: ${String(error)}`, ).orElse((reason) => fromPromise( fetch("/api/user/default").then((response) => response.json()), () => reason, ), ); ``` ## Resolving `ResultAsync` is awaitable directly, resolving to the wrapped `Result`: ```ts const result = await user; // Result ``` Or fold it with `match`, which returns a `Promise` of the matched value: ```ts const message = await user.match({ ok: (u) => `Hello, ${u.name}`, err: (reason) => reason, }); ``` --- # oxfmt Source: https://www.zapstudio.dev/docs/oxfmt `oxfmt` is Zap Studio's [oxfmt](https://oxc.rs/docs/guide/usage/formatter.html) preset — sorted imports, sorted `package.json`, and an optional Tailwind CSS class-sorting extension. ## Motivation `oxfmt`'s `sortImports` option is powerful but unopinionated — it asks you to define your own group order, and most projects either skip it or improvise one per repo, so import order drifts between packages in the same monorepo and every PR review re-litigates it. `oxfmt` ships one decided order: type-only imports first, then builtin/external values, then internal types, then internal values, then parent/sibling/index imports grouped by type then value, then anything unmatched — with a blank line between each group. `package.json` is sorted the same way every time, keys and `scripts` alphabetically. Adopt the preset once and stop deciding it per project. ## Features - **[Sorted imports](/docs/oxfmt/presets)** — a fixed group order (type-only, then value builtin/external, internal types, internal values, parent/sibling/index, unknown) with a blank line between groups. - **Sorted `package.json`** — keys and `scripts` sorted alphabetically, every time. - **[Optional Tailwind CSS class sorting](/docs/oxfmt/presets)** — `sortTailwindcss: true` via the `tailwind` preset, for projects using Tailwind. - **Plain object, not a merge** — `oxfmt.config.ts` has no `extends`; override or add options with a spread. ## Quick Start ```ts // oxfmt.config.ts import { defineConfig } from "oxfmt"; import zapStudio from "@zap-studio/oxfmt/base"; export default defineConfig(zapStudio); ``` ## Learn More - [Getting Started](/docs/oxfmt/getting-started) — install and configure the preset - [Presets](/docs/oxfmt/presets) — the import group order, `package.json` sorting, and the Tailwind extension --- # Getting Started Source: https://www.zapstudio.dev/docs/oxfmt/getting-started ## Installation ```bash npm npm install --save-dev @zap-studio/oxfmt oxfmt ``` ```bash yarn yarn add -D @zap-studio/oxfmt oxfmt ``` ```bash pnpm pnpm add -D @zap-studio/oxfmt oxfmt ``` ```bash bun bun add -D @zap-studio/oxfmt oxfmt ``` ```bash deno deno add -D npm:@zap-studio/oxfmt npm:oxfmt ``` `oxfmt` is a peer dependency — install the version you want to run. ## Base Config ```ts // oxfmt.config.ts import { defineConfig } from "oxfmt"; import zapStudio from "@zap-studio/oxfmt/base"; export default defineConfig(zapStudio); ``` This sorts imports into groups and sorts `package.json` keys and `scripts` alphabetically. See [Presets](/docs/oxfmt/presets) for the exact group order. ## Tailwind CSS Projects Swap in the `tailwind` preset — it extends `base` with `sortTailwindcss: true`: ```ts import { defineConfig } from "oxfmt"; import zapStudio from "@zap-studio/oxfmt/tailwind"; export default defineConfig(zapStudio); ``` ## Override an Option Unlike `oxlint.config.ts`, oxfmt's config has no `extends` merge — the preset is a plain object, so override or add options with a spread: ```ts import { defineConfig } from "oxfmt"; import zapStudio from "@zap-studio/oxfmt/base"; export default defineConfig({ ...zapStudio, printWidth: 120, }); ``` --- # Presets Source: https://www.zapstudio.dev/docs/oxfmt/presets | Preset | Built on | Adds | | ---------------------------- | -------- | ---------------------------------------- | | `@zap-studio/oxfmt/base` | — | Sorted imports and sorted `package.json` | | `@zap-studio/oxfmt/tailwind` | `base` | `sortTailwindcss: true` | ## Sorted Imports `base` sets `sortImports.groups` to a fixed order, with `newlinesBetween: true` so each group is separated by a blank line: | Order | Group | | ----- | ---------------------------------------------- | | 1 | `type-import` | | 2 | `value-builtin`, `value-external` | | 3 | `type-internal` | | 4 | `value-internal` | | 5 | `type-parent`, `type-sibling`, `type-index` | | 6 | `value-parent`, `value-sibling`, `value-index` | | 7 | `unknown` | Type-only imports always sort ahead of value imports from the same source, and relative imports (`parent`/`sibling`/`index`) always sort after internal ones — the same shape whether it's a single package or a monorepo with path aliases. ### Group meanings | Group | Meaning | Example | | ---------------- | ------------------------------------------------- | ------------------------------------------ | | `type-import` | Any `import type` statement, regardless of source | `import type { User } from "./user"` | | `value-builtin` | Node.js built-in modules | `import fs from "node:fs"` | | `value-external` | Packages from `node_modules` | `import React from "react"` | | `type-internal` | Type-only import from an internal path alias | `import type { Config } from "@/config"` | | `value-internal` | Value import from an internal path alias | `import { db } from "@/lib/db"` | | `type-parent` | Type-only import from a parent directory (`../`) | `import type { Props } from "../types"` | | `type-sibling` | Type-only import from a sibling file (`./`) | `import type { Options } from "./options"` | | `type-index` | Type-only import from an index file | `import type { Foo } from "."` | | `value-parent` | Value import from a parent directory (`../`) | `import { helper } from "../utils"` | | `value-sibling` | Value import from a sibling file (`./`) | `import { Button } from "./Button"` | | `value-index` | Value import from an index file | `import { App } from "."` | | `unknown` | Anything oxfmt can't classify into the above | — | An internal path alias is any import resolved through `tsconfig`/`jsconfig` paths (like `@/*`) rather than a relative or package specifier. ### Before and after ```ts // Before import { Button } from "./Button"; import type { Config } from "@/config"; import fs from "node:fs"; import type { User } from "./user"; import { db } from "@/lib/db"; import React from "react"; // After import type { User } from "./user"; import fs from "node:fs"; import React from "react"; import type { Config } from "@/config"; import { db } from "@/lib/db"; import { Button } from "./Button"; ``` ## Sorted package.json `base` sets `sortPackageJson.sortScripts: true` — top-level keys and the `scripts` object are both sorted alphabetically, so `package.json` diffs stay small and reviewable regardless of the order fields were added in. ## Tailwind CSS `tailwind` extends `base` with `sortTailwindcss: true`, sorting class lists in template literals and JSX `className`/`class` attributes into Tailwind's recommended order. --- # oxlint Source: https://www.zapstudio.dev/docs/oxlint `oxlint` is Zap Studio's [oxlint](https://oxc.rs/docs/guide/usage/linter.html) preset — exclusive, single-owner rule sets built from vetted ESLint plugins, plus a bundled `anti-slop` plugin. ## Motivation `oxlint` runs zero-config out of the box, but that config only covers its own bundled rules. The moment a project needs React, Next.js, TanStack, or test-specific linting, that zero-config story ends — now it's on you to find the right plugins, wire them up, and decide which rules to turn on. `oxlint` picks up where zero-config leaves off: one preset per plugin or framework integration, each owning a disjoint slice of rules. Nothing cascades — `extends: [react]` gets you the `react` plugin's hooks rules and nothing else, not accessibility, not React-Doctor's broader catalog, not any particular framework. You list every preset you want. The one exception is `base`: JS/TS correctness and security rules that apply regardless of framework, bundled as a single preset since there's no meaningful way to want half of it. ## Features - **One preset, one owner** — no preset silently pulls another in, so two presets never fire the same check twice under different rule names. - **A preset per plugin and framework integration** — React, Next.js, React Router, TanStack, and more, composed explicitly instead of inherited through a chain. - **Bundled `anti-slop` plugin** — original rules for patterns that don't fit any upstream plugin. - **`extends` merges, it doesn't replace** — `rules` merge key-by-key and `plugins`/`jsPlugins` union, so overriding one rule in your own config doesn't require forking a preset. - **Cherry-pickable pieces** — every preset also exports its plugins and rules as plain values, for merging by hand instead of taking the default export. ## Quick Start ```ts // oxlint.config.ts import { defineConfig } from "oxlint"; import { base, react, reactA11y, reactDoctor } from "@zap-studio/oxlint"; export default defineConfig({ extends: [base, react, reactA11y, reactDoctor], }); ``` ## Learn More - [Getting Started](/docs/oxlint/getting-started) — install, pick a preset, and override a rule - [Presets](/docs/oxlint/presets) — what each preset adds and how they chain into each other - [Plugins](/docs/oxlint/plugins) — where every rule comes from, and where to read why one is off - [Anti-Slop Plugin](/docs/oxlint/anti-slop) — the bundled plugin with no upstream equivalent --- # Anti-Slop Plugin Source: https://www.zapstudio.dev/docs/oxlint/anti-slop `anti-slop` is bundled directly in `oxlint`, not wrapped from an upstream ESLint plugin. It's included in [`base`](/docs/oxlint/presets) — and therefore every preset built on it — and catches patterns that lose type evidence or swap a real implementation for something that only looks like one. ## Rules | Rule | Catches | | ------------------------------------------- | ------------------------------------------------------------------------------------------ | | `no-chained-type-assertions` | Nested type assertions, while still permitting chains made only of const assertions | | `no-conditional-empty-object-spread` | Conditional empty-object spreads that change omission semantics | | `no-known-value-widening` | Syntactic cases where a known value is explicitly widened and loses evidence | | `no-module-mocking` | Test-framework module mocking, in favor of real dependency seams | | `no-object-parameters` | The broad `object` type on function inputs, including local aliases to it | | `no-reflect-apply` | `Reflect.apply`, which bypasses ordinary typed function calls | | `no-reflect-get` | `Reflect.get`, which bypasses ordinary property access and useful type evidence | | `no-shape-in-symbol-names` | The case-insensitive substring "shape" in any JS/TS symbol name | | `no-unknown-parameters` | Unknown-typed inputs, except explicitly named error-cause enrichment | | `no-unknown-returns` | Function contracts that return `unknown` instead of a parsed domain type | | `no-unknown-type-aliases` | Named aliases that merely conceal TypeScript's `unknown` top type | | `no-unsafe-dictionary-type` | Object-dictionary contracts whose direct value type is an unsafe escape hatch | | `no-widen-then-assert` | Immutable local bindings that erase a known type, later asserted back to a narrower type | | `require-safety-comment-for-type-assertion` | Non-const type assertions missing a comment stating the invariant TypeScript can't express | ## License `anti-slop` ships under its own MIT license, bundled at [`src/anti-slop/LICENSE`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/anti-slop/LICENSE) inside the package. --- # Getting Started Source: https://www.zapstudio.dev/docs/oxlint/getting-started ## Installation ```bash npm npm install --save-dev @zap-studio/oxlint oxlint ``` ```bash yarn yarn add -D @zap-studio/oxlint oxlint ``` ```bash pnpm pnpm add -D @zap-studio/oxlint oxlint ``` ```bash bun bun add -D @zap-studio/oxlint oxlint ``` ```bash deno deno add -D npm:@zap-studio/oxlint npm:oxlint ``` `oxlint` is a peer dependency — install the version you want to run. If you use the `typeAware`/`typeCheck` options from `base` (on by default), also install `oxlint-tsgolint`. ## Extend a Preset Start with `base` — it's the one bundled preset, and the only one every project wants regardless of framework. Import it by name from the package root: ```ts import { defineConfig } from "oxlint"; import { base } from "@zap-studio/oxlint"; export default defineConfig({ extends: [base], }); ``` ## Combine Presets Every other preset owns one plugin or one framework integration's slice of rules, and none of them imply another — `extends` accepts an array, and you list every preset your project needs. A React project on Next.js adds `react` (hooks), `react-a11y` (accessibility), `react-doctor` (the rest of React-Doctor's framework-agnostic rules), a JSX runtime preset, and `nextjs`: ```ts import { defineConfig } from "oxlint"; import { base, react, reactA11y, reactDoctor, jsxRuntimeAutomatic, nextjs, } from "@zap-studio/oxlint"; export default defineConfig({ extends: [base, react, reactA11y, reactDoctor, jsxRuntimeAutomatic, nextjs], }); ``` This is more imports than one bundled preset would need — that's the tradeoff for never inheriting rules you didn't ask for. See [Presets](/docs/oxlint/presets) for the full list and what each one owns. Every preset is also reachable by its own subpath, e.g. `@zap-studio/oxlint/react`, if you'd rather import one preset per line instead of destructuring the root — both forms export the same value: ```ts import { defineConfig } from "oxlint"; import react from "@zap-studio/oxlint/react"; export default defineConfig({ extends: [react], }); ``` ## Override a Rule `extends` merges `rules` key-by-key and unions `plugins`/`jsPlugins`. Anything you set in your own `rules` after `extends` overrides the preset, so disabling or retuning a single rule doesn't require forking it: ```ts import { defineConfig } from "oxlint"; import { react } from "@zap-studio/oxlint"; export default defineConfig({ extends: [react], rules: { "sonarjs/cognitive-complexity": "off", }, }); ``` :::note Rule names from wrapped plugins are prefixed with the plugin's name (`sonarjs/...`, `regexp/...`, `github/...`, `e18e/...`, `react-doctor/...`), matching how they're registered as `jsPlugins`. ::: ## Cherry-Pick Pieces Every preset is already just `plugins`/`jsPlugins`/`rules` under the hood — each also exports those pieces by name, so you can merge them by hand instead of taking the default export, useful for overriding one rule out of a large preset like `react-doctor`: ```ts import { defineConfig } from "oxlint"; import { basePlugins, baseJsPlugins, baseRules } from "@zap-studio/oxlint/base"; import { reactDoctorJsPlugins, reactDoctorRulesFinal } from "@zap-studio/oxlint/react-doctor"; export default defineConfig({ plugins: basePlugins, jsPlugins: [...baseJsPlugins, ...reactDoctorJsPlugins], rules: { ...baseRules, ...reactDoctorRulesFinal, "react-doctor/no-barrel-import": "off" }, }); ``` --- # Plugins Source: https://www.zapstudio.dev/docs/oxlint/plugins Every rule in `oxlint` traces back to one of two places: a plugin **built into oxlint itself** (ported from an upstream ESLint plugin into Rust, and run natively), or an **external ESLint plugin** loaded through `jsPlugins` and run as real JS. This page lists both, with a link to the upstream source and a link to the file in this repo where the rule is turned on or off — every `"off"` entry carries a comment explaining why, so you never have to guess. ## Built into oxlint These run as native oxc rules, ported from the ESLint plugin named. Browse the full ported rule set on [oxc's rules reference](https://oxc.rs/docs/guide/usage/linter/rules.html); the upstream link is where the rule concept and original docs come from. | Plugin | Upstream | Used by | | ------------ | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `eslint` | [ESLint core rules](https://eslint.org/docs/latest/rules/) | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `typescript` | [typescript-eslint](https://typescript-eslint.io/rules/) | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `unicorn` | [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `oxc` | oxc-original — no upstream, native to the linter | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `import` | [eslint-plugin-import](https://github.com/import-js/eslint-plugin-import) | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `jsdoc` | [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc) | [`jsdoc`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/jsdoc.ts) | | `node` | [eslint-plugin-n](https://github.com/eslint-community/eslint-plugin-n) | [`node`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/node.ts) | | `promise` | [eslint-plugin-promise](https://github.com/eslint-community/eslint-plugin-promise) | [`base`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/base.ts) | | `react` | [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) | [`react`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react.ts), [`react-compiler`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react-compiler.ts), [`jsx-runtime-automatic`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/jsx-runtime-automatic.ts)/[`jsx-runtime-classic`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/jsx-runtime-classic.ts) | | `react-perf` | [eslint-plugin-react-perf](https://github.com/cvazac/eslint-plugin-react-perf) | [`react-perf`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react-perf.ts) | | `jsx-a11y` | [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y) | [`react-a11y`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react-a11y.ts) | | `vitest` | [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest) | [`vitest`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/vitest.ts) | None of these appear in `package.json` — oxlint ships its own port, so there's no npm dependency to install or version to track. ## External ESLint plugins These are real npm packages, loaded through `jsPlugins` and run as actual ESLint plugin JS (listed as `dependencies` in [`packages/oxlint/package.json`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/package.json)). Every upstream rule is covered — either `"error"` or explicitly `"off"` with a comment. | Plugin | Package | Upstream | Rule decisions in this repo | | ----------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `regexp` | `eslint-plugin-regexp` | [GitHub](https://github.com/ota-meshi/eslint-plugin-regexp) · [docs](https://ota-meshi.github.io/eslint-plugin-regexp/) | [`_rules-regexp.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-regexp.ts) | | `sonarjs` | `eslint-plugin-sonarjs` | [GitHub](https://github.com/SonarSource/SonarJS) · [rule docs](https://github.com/SonarSource/SonarJS/blob/master/packages/analysis/src/jsts/rules/README.md) | [`_rules-sonarjs.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-sonarjs.ts) | | `github` | `eslint-plugin-github` | [GitHub](https://github.com/github/eslint-plugin-github) | [`_rules-github.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-github.ts) (`base`); its 4 `a11y-*` rules with no jsx-a11y equivalent live in [`react-a11y.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react-a11y.ts) instead | | `e18e` | `@e18e/eslint-plugin` | [GitHub](https://github.com/e18e/eslint-plugin) | [`_rules-e18e.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-e18e.ts) | | `playwright` | `eslint-plugin-playwright` | [GitHub](https://github.com/mskelton/eslint-plugin-playwright) | [`playwright.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/playwright.ts), rules in [`_rules-playwright.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-playwright.ts) | | `react-doctor` | `oxlint-plugin-react-doctor` | [GitHub](https://github.com/millionco/react-doctor) (directory `packages/oxlint-plugin-react-doctor`) | [`react-doctor.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/react-doctor.ts) (framework-agnostic core, rules in [`_rules-react-doctor.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-react-doctor.ts)) and the per-framework leaves, each with its own `_rules-react-doctor-*.ts` | | `tanstack-query` | `@tanstack/eslint-plugin-query` | [Docs](https://tanstack.com/query/latest/docs/eslint/eslint-plugin-query) · [GitHub](https://github.com/TanStack/query) | [`tanstack-query.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/tanstack-query.ts), rules in [`_rules-tanstack-query.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-tanstack-query.ts) | | `tanstack-router` | `@tanstack/eslint-plugin-router` | [Docs](https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router) · [GitHub](https://github.com/TanStack/router) | [`tanstack-router.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/tanstack-router.ts), rules in [`_rules-tanstack-router.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-tanstack-router.ts) | | `stylex` | `@stylexjs/eslint-plugin` | [GitHub](https://github.com/facebook/stylex/tree/main/packages/eslint-plugin) | [`stylex.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/stylex.ts), rules in [`_rules-stylex.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-stylex.ts) | | `tailwindcss` | `eslint-plugin-tailwindcss` | [GitHub](https://github.com/francoismassart/eslint-plugin-tailwindcss) | [`tailwindcss.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/tailwindcss.ts), rules in [`_rules-tailwindcss.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-tailwindcss.ts) | | `testing-library` | `eslint-plugin-testing-library` | [GitHub](https://github.com/testing-library/eslint-plugin-testing-library) | [`testing-library.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/testing-library.ts), rules in [`_rules-testing-library.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-testing-library.ts) | | `jest-dom` | `eslint-plugin-jest-dom` | [GitHub](https://github.com/testing-library/eslint-plugin-jest-dom) | [`jest-dom.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/jest-dom.ts), rules in [`_rules-jest-dom.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-jest-dom.ts) | | `cypress` | `eslint-plugin-cypress` | [GitHub](https://github.com/cypress-io/eslint-plugin-cypress) | [`cypress.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/cypress.ts), rules in [`_rules-cypress.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-cypress.ts) | | `storybook` | `eslint-plugin-storybook` | [GitHub](https://github.com/storybookjs/eslint-plugin-storybook) | [`storybook.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/storybook.ts), rules in [`_rules-storybook.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-storybook.ts) | | `solid` | `eslint-plugin-solid` | [GitHub](https://github.com/solidjs-community/eslint-plugin-solid) | [`solid.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/solid.ts), rules in [`_rules-solid.ts`](https://github.com/zap-studio/monorepo/blob/main/packages/oxlint/src/_rules-solid.ts) | `react-doctor` is the one wrapped plugin that ships its own per-framework rule slices — [`presets`](/docs/oxlint/presets) explains how those slices map onto the framework and library leaf presets. Its framework-agnostic core used to duplicate roughly 90 rules already owned by `react`, `react-perf`, and `jsx-a11y`; those now live exclusively in the plugin that originates them, not in `react-doctor`. ## Original rules [`anti-slop`](/docs/oxlint/anti-slop) isn't wrapped from anything upstream — it's original to this repo. Its rules and their rationale live directly in [`src/anti-slop/rules`](https://github.com/zap-studio/monorepo/tree/main/packages/oxlint/src/anti-slop/rules). ## Checking why a rule is off Every `"off"` entry in this package sits next to a comment explaining the reason — a deprecation, a false-positive pattern, an option this repo's rule-map shape can't express. Open the file for the plugin in question (linked in the tables above) and search for the rule name; the comment sits directly above it. If a rule you'd expect isn't covered at all, it means the preset simply doesn't load that plugin — check [presets](/docs/oxlint/presets) for which plugins each preset pulls in. --- # Presets Source: https://www.zapstudio.dev/docs/oxlint/presets Every preset owns a disjoint slice of rules and stands alone — none of them `extends` another. `rules` merge key-by-key and `plugins`/`jsPlugins` union when you list several in your own `extends` array, so pick every preset your project needs; nothing comes along for free. The one exception is `base`. ## `base` Assumes no runtime, no framework, no UI library — JS/TS correctness and security rules any project wants, a Node CLI and a React app alike. The only bundled preset in the package, since there's no meaningful way to want half of it. | Preset | Adds | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `@zap-studio/oxlint/base` | `eslint`, `typescript`, `unicorn`, `oxc`, `import`, `promise`, plus `regexp`, `sonarjs`, `github`, `e18e`, and the bundled [`anti-slop`](/docs/oxlint/anti-slop) plugin | ## React Five independent presets. `react` alone gets hooks correctness only — accessibility, performance, and React-Doctor's broader catalog are each their own opt-in. | Preset | Owns | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `@zap-studio/oxlint/react` | the `react` plugin — `rules-of-hooks`, `exhaustive-deps` | | `@zap-studio/oxlint/react-a11y` | the `jsx-a11y` plugin, plus 4 accessibility checks from `eslint-plugin-github` with no jsx-a11y equivalent | | `@zap-studio/oxlint/react-perf` | the `react-perf` plugin — the 4 `jsx-no-new-*-as-prop` rules | | `@zap-studio/oxlint/react-doctor` | `oxlint-plugin-react-doctor`'s framework-agnostic rules — security, hydration, effect-timing, rendering correctness | | `@zap-studio/oxlint/react-compiler` | the `react/react-compiler` rule, for projects on the React Compiler | `react-doctor`'s rule catalog used to duplicate roughly 90 rules that `react`, `react-perf`, and `jsx-a11y` already cover under their own names — `button-has-type`, the entire `jsx-a11y` alt-text/aria/role catalog, all 4 `react-perf` prop-identity checks, and more. Those now live exclusively in the plugin they originate from; `react-doctor` only owns what's genuinely original to it. ### JSX runtime `react-in-jsx-scope` depends on which JSX transform a project uses, so it's a choice, not a default baked into `react`: | Preset | Sets | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | `@zap-studio/oxlint/jsx-runtime-automatic` | `react/react-in-jsx-scope: "off"` — for `jsx: "react-jsx"` (the default in modern React/Next.js/Vite/Preact/React Native setups) | | `@zap-studio/oxlint/jsx-runtime-classic` | `react/react-in-jsx-scope: "warn"` — for projects still on the classic transform | Pick exactly one. ## Framework & Library Leaves Each of these owns only its own slice of `oxlint-plugin-react-doctor`'s framework-specific rules — no `react`, `react-a11y`, `react-perf`, or `react-doctor` bundled in. Add those separately (you almost always want them, for anything that renders JSX). | Preset | Targets | | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@zap-studio/oxlint/nextjs` | Next.js — App Router, metadata, route handlers, `Image`/`Script`/`Head` | | `@zap-studio/oxlint/react-router` | React Router — loaders, actions, middleware, splat and nested routes | | `@zap-studio/oxlint/react-native` | React Native/Expo — lists, `Pressable`, Reanimated, deprecated modules | | `@zap-studio/oxlint/remotion` | Remotion — deterministic rendering, `delayRender`, CSS animation bans | | `@zap-studio/oxlint/preact` | Preact — API differences from React (`render` args, hooks import, `children`) | | `@zap-studio/oxlint/ink` | Ink — terminal rendering, raw mode, `Static`, focus handling | | `@zap-studio/oxlint/r3f` | React Three Fiber | | `@zap-studio/oxlint/three` | three.js | | `@zap-studio/oxlint/motion` | Motion (Framer Motion) — `AnimatePresence`, imperative animation, layout ids | | `@zap-studio/oxlint/redux` | Redux — `useSelector` derivation and return-value pitfalls | | `@zap-studio/oxlint/zustand` | Zustand — selector freshness, store mutation, whole-store destructuring | | `@zap-studio/oxlint/valtio` | Valtio — proxy reads and snapshots | | `@zap-studio/oxlint/mobx` | MobX — `observer`/`memo` interaction, `makeAutoObservable`, reaction disposal | | `@zap-studio/oxlint/jotai` | Jotai — derived atoms, `selectAtom` placement | | `@zap-studio/oxlint/styled-components` | styled-components — duplicate CSS properties, transient props | | `@zap-studio/oxlint/tanstack-query` | TanStack Query — `@tanstack/eslint-plugin-query` plus `react-doctor`'s 9 query-pattern rules (floating mutations, missing invalidation, unstable query clients) | | `@zap-studio/oxlint/tanstack-start` | TanStack Start — `react-doctor`'s 15 meta-framework rules (loaders, route property order, server functions, secrets in loaders) | | `@zap-studio/oxlint/tanstack-router` | TanStack Router — `@tanstack/eslint-plugin-router` | | `@zap-studio/oxlint/solid` | Solid — `eslint-plugin-solid`'s reactivity/JSX rules (props destructuring, `no-innerhtml`, `prefer-for`); not a react-doctor slice, Solid's reactivity model is its own | | `@zap-studio/oxlint/stylex` | StyleX — `@stylexjs/eslint-plugin`'s full rule set: valid/standard styles, unsafe shorthands, unused styles, conflicting props | | `@zap-studio/oxlint/tailwindcss` | Tailwind CSS v4 — `eslint-plugin-tailwindcss`'s contradicting/unnecessary-arbitrary-value and class-order rules | Preact and React Native are runtime-ambiguous — pair either with `jsx-runtime-automatic` or `jsx-runtime-classic` depending on the project's transform. Solid uses its own JSX transform (`babel-preset-solid`), not React's, so neither `jsx-runtime` preset applies to it. ## Opt-in Environment Presets Not every project runs in Node or wants JSDoc type-annotation rules enforced (redundant once a project is on TypeScript, which `base` already assumes) — kept separate from `base` for that reason: | Preset | Adds | | -------------------------- | ----------------------------------------------------------- | | `@zap-studio/oxlint/jsdoc` | the `jsdoc` plugin — for JS (or intentionally-untyped) code | | `@zap-studio/oxlint/node` | the `node` plugin — for code that actually runs under Node | ## Testing Split by test runner: | Preset | Adds | | ------------------------------------ | ----------------------------------------------------------------------------------------------------------- | | `@zap-studio/oxlint/vitest` | the `vitest` plugin | | `@zap-studio/oxlint/playwright` | `eslint-plugin-playwright` | | `@zap-studio/oxlint/cypress` | `eslint-plugin-cypress` | | `@zap-studio/oxlint/testing-library` | `eslint-plugin-testing-library`'s framework-agnostic DOM query/async rules | | `@zap-studio/oxlint/jest-dom` | `eslint-plugin-jest-dom` — its matcher rules work under both Jest and Vitest's jest-dom-compatible `expect` | ## Storybook | Preset | Adds | | ------------------------------ | ----------------------------------------------------------------------- | | `@zap-studio/oxlint/storybook` | `eslint-plugin-storybook`'s story-file correctness and CSF-format rules | ## Example: Next.js + TanStack, React Compiler on ```ts import { defineConfig } from "oxlint"; import { base, react, reactA11y, reactDoctor, reactCompiler, jsxRuntimeAutomatic, nextjs, tanstackQuery, vitest, } from "@zap-studio/oxlint"; export default defineConfig({ extends: [ base, react, reactA11y, reactDoctor, reactCompiler, jsxRuntimeAutomatic, nextjs, tanstackQuery, vitest, ], }); ``` Nine imports instead of one — the tradeoff for a preset stack that's exactly what the project uses, nothing implied. ## Where the Rules Come From Every plugin named in the tables above — built-in or external — traces back to an upstream project or, for `anti-slop`, this repo directly. See [Plugins](/docs/oxlint/plugins) for the source of each one and a link to the file where its rules are decided on or off. --- # permit Source: https://www.zapstudio.dev/docs/permit `permit` is a type-safe, declarative authorization library for TypeScript with [Standard Schema](https://standardschema.dev/) support. ## Motivation Authorization checks written by hand, like `if (user.role === "admin")`, spread through a codebase over time. After a while, nobody can answer "who is allowed to delete a post?" without searching the whole app. A framework like CASL solves the spreading problem, but it comes with its own vocabulary to learn (`subject`, `can`, `cannot`, `rules`), and its rules are not checked against your actual data shapes — you can write a rule that references a field your resource does not have, and it will only fail once that code runs. `permit` keeps all rules in one place, through `createPolicy(...)` with `allow()`, `deny()`, and `when(condition)` — one file answers "who can do what." And because resources come from your Standard Schema schemas, policy types are derived straight from your real data shapes. Reference a field that does not exist, and you get an error while writing the code, not a silent `undefined` in production. ## Features - **Full type safety** — actions, resources, and permissions are inferred from your schemas and `satisfies` declarations, from [Getting Started](/docs/permit/getting-started) onward. - **Standard Schema support** via `Resources` — works with Zod, Valibot, ArkType, or any compatible library. See [Standard Schema Support](/docs/permit/standard-schema). - **Declarative policies** through `createPolicy(...)` with `allow()`, `deny()`, and `when(condition)`. See [Declarative Policies](/docs/permit/declarative-policies). - **Role hierarchy support** via `hasRole(role, hierarchy?)`, with inheritance resolved by `collectInheritedRoles`. See [Role-Based Access Control](/docs/permit/roles). - **Composable conditions** via `and`, `or`, and `not`. See [Conditions](/docs/permit/conditions). - **Policy merging strategies** via `mergePoliciesAnd` and `mergePoliciesOr`. See [Merging Policies](/docs/permit/merging-policies). - **Structured errors** with `PolicyError` for invalid configuration or evaluation failures. See [Error Handling](/docs/permit/errors). - **[Optional logging](/docs/permit/logging)** through `createPolicy({ logger })` from [`logger`](/docs/logger) — omit it and there's zero added logging overhead. - **[Native OpenTelemetry](/docs/permit/opentelemetry)** — an `INTERNAL` span per check with the allow/deny decision as an attribute, plus a `permit.checks` counter, no-op until an SDK is registered. - **Tree-shakeable** — policies and conditions are plain functions; unused exports are dropped by any modern bundler. ## Quick Start ```ts import { z } from "zod"; import { ConsoleLogger } from "@zap-studio/logger"; import { createPolicy, allow, deny, when } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string() }), } satisfies Resources; const actions = { post: ["read", "write", "delete"], } as const satisfies Actions; type AppContext = { user: { id: string } }; const logger = new ConsoleLogger({ minLevel: "debug" }); const policy = createPolicy({ resources, actions, rules: { post: { read: allow(), write: when((ctx, action, resource) => ctx.user.id === resource.authorId), delete: deny(), }, }, logger, }); const ctx: AppContext = { user: { id: "user-1" } }; const post = { id: "1", authorId: "user-1" }; await policy.can(ctx, "post:write", post); // true, inferred as boolean ``` Continue with [Getting Started](/docs/permit/getting-started) for a full walkthrough of resources, actions, context, and checking permissions. ## Runtime Support | Runtime | Minimum version | | ------------------ | ------------------------------------------------ | | Node.js | 18.0.0 | | Bun | 1.0.0 | | Deno | 1.42 | | Cloudflare Workers | Any current release | | Browsers | Latest evergreen (Chrome, Edge, Firefox, Safari) | The package ships standard ESM only and uses no runtime-specific APIs. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/permit`). --- # Conditions Source: https://www.zapstudio.dev/docs/permit/conditions Conditions compose via `and`, `or`, and `not`. They are the building blocks for creating complex authorization rules — `permit` provides combinators to compose simple conditions into powerful, readable policies. ## Understanding Conditions A condition is a function that evaluates to `true` or `false`: ```ts type ConditionFn = ( context: TContext, action: TAction, resource: TResource, ) => boolean; ``` Conditions are used with `when()` to create policy rules: ```ts when((ctx, action, resource) => /* condition logic */) ``` ## Setup The examples on this page use these definitions: ```ts import { z } from "zod"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string(), status: z.enum(["draft", "published", "archived"]), reportedBy: z.array(z.string()), }), document: z.object({ id: z.string(), ownerId: z.string(), status: z.enum(["active", "archived"]), isLocked: z.boolean(), sharedWith: z.array(z.string()), }), } satisfies Resources; const actions = { post: ["edit", "like", "comment", "report"], document: ["read", "edit"], } as const satisfies Actions; type AppContext = { user: { id: string; role: "guest" | "user" | "admin" } | null; }; ``` ## Condition Combinators ### and() The `and()` combinator creates a condition that passes only when **all** conditions are true. It short-circuits on the first `false` value. ```ts import { and } from "@zap-studio/permit"; and(...conditions); ``` #### Example: Multiple Requirements ```ts import { createPolicy, when, and } from "@zap-studio/permit"; // User must be authenticated AND be the owner AND post must be published const canEditPublishedPost = and( (ctx) => ctx.user !== null, (ctx, _, post) => ctx.user?.id === post.authorId, (_, __, post) => post.status === "published", ); const policy = createPolicy({ resources, actions, rules: { post: { edit: when(canEditPublishedPost), }, }, }); ``` ### or() The `or()` combinator creates a condition that passes when **any** condition is true. It short-circuits on the first `true` value. ```ts import { or } from "@zap-studio/permit"; or(...conditions); ``` #### Example: Multiple Access Paths ```ts import { createPolicy, when, or } from "@zap-studio/permit"; // User can access if they're the owner OR an admin OR explicitly shared const canAccess = or( (ctx, _, doc) => ctx.user?.id === doc.ownerId, (ctx) => ctx.user?.role === "admin", (ctx, _, doc) => doc.sharedWith.includes(ctx.user?.id ?? ""), ); const policy = createPolicy({ resources, actions, rules: { document: { read: when(canAccess), }, }, }); ``` ### not() The `not()` combinator negates a condition. ```ts import { not } from "@zap-studio/permit"; not(condition); ``` #### Example: Exclusion Rules ```ts import { createPolicy, when, not, and } from "@zap-studio/permit"; // Cannot interact with your own content const isNotOwner = not((ctx, _, resource) => ctx.user?.id === resource.authorId); // Content is not archived const isNotArchived = not((_, __, resource) => resource.status === "archived"); const policy = createPolicy({ resources, actions, rules: { post: { // Can like any post except your own like: when(isNotOwner), // Can comment on posts that aren't archived comment: when(isNotArchived), // Can report posts that: you don't own AND aren't already reported by you report: when( and(isNotOwner, (ctx, _, post) => !post.reportedBy.includes(ctx.user?.id ?? "")), ), }, }, }); ``` ### has() The `has()` helper creates a condition that checks if a context property equals a specific value. It compares with strict equality (`===`). ```ts import { has } from "@zap-studio/permit"; has(key, value); ``` #### Example: Simple Property Checks ```ts import { z } from "zod"; import { createPolicy, when, has, or } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { settings: z.object({ id: z.string() }), billing: z.object({ id: z.string() }), export: z.object({ id: z.string() }), } satisfies Resources; const actions = { settings: ["read"], billing: ["read"], export: ["use"], } as const satisfies Actions; type AppContext = { role: "guest" | "user" | "admin"; isVerified: boolean; plan: "free" | "pro" | "enterprise"; }; const policy = createPolicy({ resources, actions, rules: { settings: { // Only admins can access settings read: when(has("role", "admin")), }, billing: { // Only verified users can access billing read: when(has("isVerified", true)), }, export: { // Pro or Enterprise users can export use: when(or(has("plan", "pro"), has("plan", "enterprise"))), }, }, }); ``` :::note `has()` only checks top-level context properties. For nested values like `ctx.user.role`, write the condition inline: `when((ctx) => ctx.user?.role === "admin")`. ::: ## Combining Combinators Combinators can be nested to create complex conditions: ```ts import { createPolicy, when, and, or, not } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { document: { // Can edit if: // (owner OR admin) AND (not archived) AND (not locked OR is admin) edit: when( and( or( (ctx, _, doc) => ctx.user?.id === doc.ownerId, (ctx) => ctx.user?.role === "admin", ), not((_, __, doc) => doc.status === "archived"), or( not((_, __, doc) => doc.isLocked), (ctx) => ctx.user?.role === "admin", ), ), ), }, }, }); ``` ## Extracting Reusable Conditions For cleaner code, extract conditions into named functions: ```ts import { createPolicy, when, and, or, not } from "@zap-studio/permit"; import type { ConditionFn } from "@zap-studio/permit"; type DocContext = { user: { id: string; role: string } | null; }; type Document = { ownerId: string; status: string; isLocked: boolean; }; // Reusable conditions const isOwner: ConditionFn = (ctx, _, doc) => ctx.user?.id === doc.ownerId; const isAdmin: ConditionFn = (ctx) => ctx.user?.role === "admin"; const isArchived: ConditionFn = (_, __, doc) => doc.status === "archived"; const isLocked: ConditionFn = (_, __, doc) => doc.isLocked; // Composed conditions const canEdit = and(or(isOwner, isAdmin), not(isArchived), or(not(isLocked), isAdmin)); // Use in policy const policy = createPolicy({ resources, actions, rules: { document: { edit: when(canEdit), }, }, }); ``` ## Best Practices 1. **Name your conditions** — Extract complex logic into well-named functions 2. **Keep conditions simple** — Each condition should check one thing 3. **Use short-circuit evaluation** — Put fast/common checks first in `and()`/`or()` 4. **Avoid side effects** — Conditions should be pure functions 5. **Document complex logic** — Add comments explaining business rules --- # Declarative Policies Source: https://www.zapstudio.dev/docs/permit/declarative-policies `createPolicy(...)` builds policies using `allow()`, `deny()`, and `when(condition)`. `permit` provides three rule builders for defining what's allowed. ## Understanding Rules Every rule returns a **decision**: either `"allow"` or `"deny"`. Rules receive three arguments: 1. **context** — The current user/request context 2. **action** — The action being performed (e.g., `"read"`, `"write"`) 3. **resource** — The resource being accessed (already validated against its schema) :::note Rules are optional per action. If an action has no rule, `policy.can()` returns `false` for it. If a rule throws, the error is caught, logged with `console.warn`, and the action is denied. ::: ## Setup The examples on this page use these definitions: ```ts import { z } from "zod"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string(), visibility: z.enum(["public", "private"]), }), } satisfies Resources; const actions = { post: ["read", "write", "delete"], } as const satisfies Actions; type AppContext = { user: { id: string; role: "guest" | "user" | "admin" } | null; }; ``` ## allow() The `allow()` function creates a rule that always permits the action, regardless of context or resource. ```ts import { allow } from "@zap-studio/permit"; ``` ### When to Use Use `allow()` for actions that should be available to everyone: - Public content (published blog posts, product listings) - Health check endpoints - Public API documentation ### Example: Public Content ```ts import { createPolicy, allow } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { // Anyone can read posts (refine this with conditions later) read: allow(), }, }, }); ``` ## deny() The `deny()` function creates a rule that always blocks the action. No context or resource can override this. ```ts import { deny } from "@zap-studio/permit"; ``` ### When to Use Use `deny()` for: - Temporarily disabled features - Actions reserved for future implementation - Hard blocks that should never be bypassed ### Example: Disabled Actions ```ts import { createPolicy, allow, deny, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { read: allow(), write: when((ctx, _, post) => ctx.user?.id === post.authorId), // Deleting posts is disabled for everyone delete: deny(), }, }, }); ``` ## when() The `when()` function creates a conditional rule. It takes a condition function and allows the action only if the condition returns `true`. ```ts import { when } from "@zap-studio/permit"; when((context, action, resource) => boolean); ``` ### Condition Function The condition function receives: | Parameter | Type | Description | | ---------- | ----------- | ---------------------------- | | `context` | `TContext` | Current user/request context | | `action` | `TAction` | The action being performed | | `resource` | `TResource` | The resource being accessed | It must return a `boolean`: - `true` → action is allowed - `false` → action is denied ### Example: Owner-Only Access ```ts import { createPolicy, allow, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { read: allow(), // Only the author can edit their post write: when((ctx, _, post) => ctx.user?.id === post.authorId), // Only the author can delete their post delete: when((ctx, _, post) => ctx.user?.id === post.authorId), }, }, }); ``` ## Using the Action Parameter The `action` parameter becomes useful when you create reusable condition functions that handle multiple actions differently. This lets you share logic across actions while still customizing behavior: ```ts import { createPolicy, when } from "@zap-studio/permit"; import type { ConditionFn } from "@zap-studio/permit"; type PostAction = "read" | "write" | "delete"; type Post = { id: string; authorId: string; visibility: "public" | "private" }; // Reusable condition that behaves differently based on action const canAccessPost: ConditionFn = (ctx, action, post) => { // Anyone can read public posts if (action === "read" && post.visibility === "public") { return true; } // For write/delete (or private reads), must be the author return ctx.user?.id === post.authorId; }; const policy = createPolicy({ resources, actions, rules: { post: { // Same function handles all three actions with different logic read: when(canAccessPost), write: when(canAccessPost), delete: when(canAccessPost), }, }, }); ``` This pattern is useful when actions share similar logic but need slight variations — you define the condition once and reuse it across multiple actions. ## Combining Rules Conditions can be composed with combinators. See [Conditions](/docs/permit/conditions) for details on `and()`, `or()`, `not()`, and `has()`. ## Best Practices 1. **Start restrictive** — Leave actions without a rule (or use `deny()`), then explicitly allow 2. **Keep conditions pure** — Don't perform side effects in condition functions 3. **Avoid async operations** — Conditions must be synchronous; fetch data before checking 4. **Use descriptive variable names** — `isOwner`, `isMember`, `hasAccess` 5. **Extract complex conditions** — Create reusable condition functions for clarity --- # Error Handling Source: https://www.zapstudio.dev/docs/permit/errors `PolicyError` signals invalid configuration or evaluation failures. `permit` keeps error handling minimal by design: permission checks resolve to `false` instead of throwing. This page covers the `PolicyError` class and when the library throws it. ## When permit Throws (and When It Doesn't) - `createPolicy()` **throws** a `PolicyError` at creation time if a resource key has no schema (`"Missing schema for resource: "`). - `policy.can()` **never throws**. Malformed permission strings, unlisted actions, resources that fail schema validation, missing rules, and rules that throw all resolve to `false`. Rule and validation errors are logged with `console.warn`. :::info Because `can()` fails closed, you decide how to surface denials — return a 403, throw your own `PolicyError`, or redirect. ::: ## PolicyError The `PolicyError` class is a custom error type for policy-related failures. The library uses it for configuration errors, and you can throw it yourself to distinguish authorization errors from other application errors. ```ts import { PolicyError } from "@zap-studio/permit"; ``` :::note `PolicyError` is exported from the package root, and also from the `@zap-studio/permit/errors` subpath for granular imports. ::: ### Constructor ```ts new PolicyError(message: string) ``` ### Properties | Property | Type | Description | | --------- | -------- | ----------------------- | | `name` | `string` | Always `"PolicyError"` | | `message` | `string` | Error description | | `stack` | `string` | Stack trace (inherited) | `PolicyError` extends `Error`, so `instanceof Error` checks also match it. ### Throwing Policy Errors ```ts import { PolicyError } from "@zap-studio/permit"; // Throw when an authorization check fails throw new PolicyError("User is not authorized to delete this resource"); // Throw for invalid policy configuration throw new PolicyError("Unknown resource type: 'invalid'"); // Throw for missing context throw new PolicyError("User context is required for this action"); ``` ### Catching Policy Errors ```ts import { PolicyError } from "@zap-studio/permit"; async function deletePost(postId: string, context: AppContext) { try { const post = await getPost(postId); if (!(await policy.can(context, "post:delete", post))) { throw new PolicyError("Not authorized to delete this post"); } await db.posts.delete(postId); return { success: true }; } catch (error) { if (error instanceof PolicyError) { // Handle authorization errors return { success: false, error: error.message, code: "FORBIDDEN" }; } // Re-throw unexpected errors throw error; } } ``` ## Best Practices 1. **Use `PolicyError` for authorization failures** — Makes it easy to distinguish from other errors 2. **Catch errors at boundaries** — Handle `PolicyError` in middleware or API handlers 3. **Include context in error messages** — "Not authorized to delete post-123" is better than "Forbidden" 4. **Log denied attempts** — Track authorization failures for security monitoring --- # Getting Started Source: https://www.zapstudio.dev/docs/permit/getting-started A policy is the core building block of `permit`. It defines what actions users can perform on your application's resources based on the current context. ## Installation ```bash npm npm install @zap-studio/permit ``` ```bash yarn yarn add @zap-studio/permit ``` ```bash pnpm pnpm add @zap-studio/permit ``` ```bash bun bun add @zap-studio/permit ``` ```bash deno deno add jsr:@zap-studio/permit ``` You also need a schema library that implements [Standard Schema](https://standardschema.dev/), such as Zod, Valibot, or ArkType. ## Understanding Policies Think of a policy as a rulebook that answers questions like: - "Can this user edit this blog post?" - "Can a guest view this private document?" - "Can an admin delete any comment?" A policy consists of three parts: 1. **Resources** — The things being protected (posts, comments, users) 2. **Actions** — What can be done with resources (read, write, delete) 3. **Rules** — The logic that determines if an action is allowed :::info Define resources and actions in a centralized location to ensure consistency and type safety across your application. ::: ## Defining Resources Resources are defined using [Standard Schema](https://standardschema.dev/), which means you can use Zod, Valibot, ArkType, or any compatible library. ```ts import { z } from "zod"; import type { Resources } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string(), title: z.string(), visibility: z.enum(["public", "private", "draft"]), createdAt: z.date(), }), comment: z.object({ id: z.string(), postId: z.string(), authorId: z.string(), content: z.string(), }), user: z.object({ id: z.string(), email: z.email(), role: z.enum(["guest", "user", "admin"]), }), } satisfies Resources; ``` See [Standard Schema Support](/docs/permit/standard-schema) for the same definition with Valibot and ArkType. :::warning Use `satisfies` to ensure type safety and consistency. Learn more about the [TypeScript `satisfies` operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator). ::: ## Defining Actions Actions specify what operations are allowed on each resource. Define them as readonly arrays: ```ts import type { Actions } from "@zap-studio/permit"; const actions = { post: ["read", "write", "delete", "publish"], comment: ["read", "write", "delete"], user: ["read", "update", "delete", "ban"], } as const satisfies Actions; ``` :::warning Use `as const` so TypeScript infers literal types for actions. This enables autocomplete and type checking when writing rules and permission strings. Learn more about [`const` assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions). ::: ## Understanding Context Context represents the runtime information available when checking permissions. This typically includes the current user, but can contain anything relevant to authorization: ```ts type AppContext = { user: { id: string; role: "guest" | "user" | "admin"; permissions: string[]; organizationId: string; } | null; request?: { ip: string; userAgent: string; }; timestamp: Date; }; ``` Context is passed to `policy.can()` at runtime and is available in all your rule functions. :::info Context is just a type — it can be anything relevant to your application's authorization needs. Include all the data your rules need so they never have to fetch anything. ::: ## Creating a Policy Use `createPolicy()` to combine your resources, actions, and rules into a policy. See [Declarative Policies](/docs/permit/declarative-policies) for the full reference on `allow()`, `deny()`, and `when()`. ```ts import { createPolicy, allow, deny, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { read: allow(), write: when((ctx, _action, post) => ctx.user?.id === post.authorId), delete: deny(), publish: when((ctx) => ctx.user?.role === "admin"), }, comment: { read: allow(), write: when((ctx) => ctx.user !== null), delete: when((ctx, _action, comment) => ctx.user?.id === comment.authorId), }, }, }); ``` :::note `createPolicy()` throws a [`PolicyError`](/docs/permit/errors) at creation time if a resource key is missing its schema. Rules for individual actions are optional — an action without a rule is always denied. ::: ## Checking Permissions The policy object provides a `can()` method. It takes the `context`, a `"resource:action"` permission string, and the `resource`, then returns a `Promise`: ```ts policy.can(context, permission, resource): Promise ``` ### Parameters | Parameter | Type | Description | | ------------ | ---------- | ---------------------------------------------------------------- | | `context` | `TContext` | The current context (user, request, etc.) | | `permission` | `string` | The permission to check (e.g., `"post:read"`, `"comment:write"`) | | `resource` | `object` | The actual resource being accessed | ### How can() Decides `can()` never throws — it resolves to `false` whenever a check fails: 1. **Parse the permission** — Malformed strings (missing or extra `:` segments) return `false`. 2. **Check the action** — Actions not listed for the resource in `actions` return `false`. 3. **Validate the resource** — The resource is validated against its Standard Schema; invalid resources return `false`. 4. **Evaluate the rule** — No rule defined for the action returns `false`. If the rule throws, the error is logged with `console.warn` and `can()` returns `false`. ## Real-World Example: E-commerce Store Here's a complete example for an e-commerce application: ```ts import { z } from "zod"; import { createPolicy, allow, when, or } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; // Define resources const resources = { product: z.object({ id: z.string(), sellerId: z.string(), price: z.number(), status: z.enum(["draft", "published", "archived"]), }), order: z.object({ id: z.string(), customerId: z.string(), sellerId: z.string(), status: z.enum(["pending", "paid", "shipped", "delivered"]), }), review: z.object({ id: z.string(), productId: z.string(), customerId: z.string(), rating: z.number().min(1).max(5), }), } satisfies Resources; const actions = { product: ["read", "create", "update", "delete", "publish"], order: ["read", "create", "update", "cancel"], review: ["read", "create", "update", "delete"], } as const satisfies Actions; type StoreContext = { user: { id: string; role: "customer" | "seller" | "admin"; } | null; }; const storePolicy = createPolicy({ resources, actions, rules: { product: { // Anyone can read published products read: when((_, __, product) => product.status === "published"), // Only sellers can create products create: when((ctx) => ctx.user?.role === "seller"), // Sellers can update their own products update: when( (ctx, _, product) => ctx.user?.role === "seller" && ctx.user.id === product.sellerId, ), // Only admins can delete products delete: when((ctx) => ctx.user?.role === "admin"), // Sellers can publish their own products publish: when( (ctx, _, product) => ctx.user?.role === "seller" && ctx.user.id === product.sellerId, ), }, order: { // Customers see their orders, sellers see orders for their products read: when( or( (ctx, _, order) => ctx.user?.id === order.customerId, (ctx, _, order) => ctx.user?.id === order.sellerId, ), ), // Only authenticated customers can create orders create: when((ctx) => ctx.user?.role === "customer"), // Sellers can update order status update: when((ctx, _, order) => ctx.user?.id === order.sellerId), // Customers can cancel pending orders cancel: when( (ctx, _, order) => ctx.user?.id === order.customerId && order.status === "pending", ), }, review: { // Anyone can read reviews read: allow(), // Customers can create reviews create: when((ctx) => ctx.user?.role === "customer"), // Customers can update their own reviews update: when((ctx, _, review) => ctx.user?.id === review.customerId), // Customers can delete their reviews, admins can delete any delete: when( or( (ctx, _, review) => ctx.user?.id === review.customerId, (ctx) => ctx.user?.role === "admin", ), ), }, }, }); // Usage const product = { id: "prod-1", sellerId: "seller-123", price: 99.99, status: "published" as const, }; const customerContext: StoreContext = { user: { id: "customer-456", role: "customer" }, }; console.log(await storePolicy.can(customerContext, "product:read", product)); // true console.log(await storePolicy.can(customerContext, "product:update", product)); // false ``` ## Best Practices 1. **Keep resources focused** — Each resource should represent a single domain entity 2. **Use descriptive action names** — "publish" is clearer than "update-status" 3. **Include all relevant data in context** — Don't fetch additional data inside rules 4. **Be explicit about what's allowed** — Actions without a rule are denied by default 5. **Test your policies** — Write unit tests for critical authorization rules --- # Logging Source: https://www.zapstudio.dev/docs/permit/logging `createPolicy(...)` accepts an optional `logger?: Logger` option from [`logger`](/docs/logger). Pass one to observe policy evaluation; omit it and only the pre-existing internal-error warnings still print, unchanged. ```ts import { ConsoleLogger } from "@zap-studio/logger"; import { createPolicy } from "@zap-studio/permit"; const logger = new ConsoleLogger({ minLevel: "debug" }); const policy = createPolicy({ resources, actions, rules, logger }); ``` ## What Gets Logged | Event | Level | Context | | ------------------------- | ------- | --------------------------------- | | A permission is allowed | `debug` | `action`, `resourceType` | | A permission is denied | `info` | `action`, `resourceType` | | Resource validation fails | `warn` | `resourceType`, `error` | | A policy function throws | `warn` | `action`, `resourceType`, `error` | Deny decisions log at `info` rather than `debug` — a denial is a meaningful authorization outcome worth seeing by default once a logger is attached, not just noise. The internal-error warnings (a policy function throwing, or resource validation failing) predate this option: without a logger they still print via `console.warn`, exactly as before; with one, they route through `logger.warn(...)` instead so they land wherever the rest of your logs go. ## Bring Your Own Logger Any object implementing the `Logger` interface works, so you can forward these events into an existing logging setup instead of `ConsoleLogger`: ```ts import type { Logger } from "@zap-studio/logger"; const logger: Logger = { trace: (message, context) => myBackend.log("trace", message, context), debug: (message, context) => myBackend.log("debug", message, context), info: (message, context) => myBackend.log("info", message, context), warn: (message, context) => myBackend.log("warn", message, context), error: (message, context) => myBackend.log("error", message, context), fatal: (message, context) => myBackend.log("fatal", message, context), }; const policy = createPolicy({ resources, actions, rules, logger }); ``` See [`logger`](/docs/logger) for the full `Logger` interface and `ConsoleLogger` options. --- # Merging Policies Source: https://www.zapstudio.dev/docs/permit/merging-policies `permit` merges policies via `mergePoliciesAnd` and `mergePoliciesOr`. As your application grows, you may want to organize authorization logic into separate policies. `permit` provides two merge strategies: AND and OR. ## Why Merge Policies? Merging policies is useful for: - **Separation of concerns** — Keep domain-specific rules in separate files - **Layered security** — Apply base rules that can be tightened or relaxed - **Feature flags** — Enable/disable features by adding or removing policies - **Multi-tenancy** — Combine organization policies with application policies :::note Merged policies evaluate in parallel and never short-circuit: every policy is invoked regardless of outcome. `mergePoliciesAnd()` requires all results to allow, `mergePoliciesOr()` requires at least one — but both wait for every policy's `can()` to settle first. ::: ## mergePoliciesAnd() — AND Strategy The `mergePoliciesAnd()` function combines policies using an AND strategy. An action is allowed only if **all** policies allow it. ```ts import { mergePoliciesAnd } from "@zap-studio/permit"; const mergedPolicy = mergePoliciesAnd(policy1, policy2, policy3); ``` Think of it as an AND operation: `policy1 AND policy2 AND policy3` ### Behavior | Policy 1 | Policy 2 | Result | | -------- | -------- | -------- | | allow | allow | allow | | allow | deny | **deny** | | deny | allow | **deny** | | deny | deny | deny | ### Example: Base + Restrictive Policy ```ts import { z } from "zod"; import { createPolicy, when, mergePoliciesAnd } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { document: z.object({ id: z.string(), ownerId: z.string(), classification: z.enum(["public", "internal", "confidential"]), }), } satisfies Resources; const actions = { document: ["read", "write", "delete"], } as const satisfies Actions; type AppContext = { user: { id: string; clearanceLevel: number } | null; }; // Base policy: standard access rules const basePolicy = createPolicy({ resources, actions, rules: { document: { read: when((ctx, _, doc) => doc.classification === "public" || ctx.user?.id === doc.ownerId), write: when((ctx, _, doc) => ctx.user?.id === doc.ownerId), delete: when((ctx, _, doc) => ctx.user?.id === doc.ownerId), }, }, }); // Security policy: additional clearance requirements const securityPolicy = createPolicy({ resources, actions, rules: { document: { read: when((ctx, _, doc) => { if (doc.classification === "confidential") { return (ctx.user?.clearanceLevel ?? 0) >= 3; } if (doc.classification === "internal") { return (ctx.user?.clearanceLevel ?? 0) >= 1; } return true; }), write: when((ctx, _, doc) => { if (doc.classification === "confidential") { return (ctx.user?.clearanceLevel ?? 0) >= 3; } return true; }), delete: when((ctx, _, doc) => { if (doc.classification === "confidential") { return (ctx.user?.clearanceLevel ?? 0) >= 4; } return true; }), }, }, }); // Merge: both policies must allow const policy = mergePoliciesAnd(basePolicy, securityPolicy); // Usage const confidentialDoc = { id: "doc-1", ownerId: "user-123", classification: "confidential" as const, }; // Owner with low clearance: base allows, security denies → DENIED const lowClearanceOwner: AppContext = { user: { id: "user-123", clearanceLevel: 1 }, }; console.log(await policy.can(lowClearanceOwner, "document:read", confidentialDoc)); // false // Owner with high clearance: both allow → ALLOWED const highClearanceOwner: AppContext = { user: { id: "user-123", clearanceLevel: 3 }, }; console.log(await policy.can(highClearanceOwner, "document:read", confidentialDoc)); // true ``` ## mergePoliciesOr() — OR Strategy The `mergePoliciesOr()` function combines policies using an OR strategy. An action is allowed if **any** policy allows it. ```ts import { mergePoliciesOr } from "@zap-studio/permit"; const mergedPolicy = mergePoliciesOr(policy1, policy2, policy3); ``` Think of it as an OR operation: `policy1 OR policy2 OR policy3` ### Behavior | Policy 1 | Policy 2 | Result | | -------- | -------- | --------- | | allow | allow | allow | | allow | deny | **allow** | | deny | allow | **allow** | | deny | deny | deny | ### Example: Multiple Access Paths ```ts import { z } from "zod"; import { createPolicy, when, mergePoliciesOr } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { file: z.object({ id: z.string(), ownerId: z.string(), isPublic: z.boolean(), sharedWith: z.array(z.string()), teamId: z.string().nullable(), }), } satisfies Resources; const actions = { file: ["read", "write", "delete"], } as const satisfies Actions; type FileContext = { user: { id: string; teamIds: string[] } | null; }; // Owner access policy const ownerPolicy = createPolicy({ resources, actions, rules: { file: { read: when((ctx, _, file) => ctx.user?.id === file.ownerId), write: when((ctx, _, file) => ctx.user?.id === file.ownerId), delete: when((ctx, _, file) => ctx.user?.id === file.ownerId), }, }, }); // Public access policy const publicPolicy = createPolicy({ resources, actions, rules: { file: { read: when((_, __, file) => file.isPublic), write: when(() => false), delete: when(() => false), }, }, }); // Shared access policy const sharedPolicy = createPolicy({ resources, actions, rules: { file: { read: when((ctx, _, file) => file.sharedWith.includes(ctx.user?.id ?? "")), write: when((ctx, _, file) => file.sharedWith.includes(ctx.user?.id ?? "")), delete: when(() => false), }, }, }); // Team access policy const teamPolicy = createPolicy({ resources, actions, rules: { file: { read: when( (ctx, _, file) => file.teamId !== null && (ctx.user?.teamIds.includes(file.teamId) ?? false), ), write: when( (ctx, _, file) => file.teamId !== null && (ctx.user?.teamIds.includes(file.teamId) ?? false), ), delete: when(() => false), }, }, }); // Any of these policies can grant access const filePolicy = mergePoliciesOr(ownerPolicy, publicPolicy, sharedPolicy, teamPolicy); // Usage const file = { id: "file-1", ownerId: "user-owner", isPublic: false, sharedWith: ["user-shared"], teamId: "team-1", }; const sharedUser: FileContext = { user: { id: "user-shared", teamIds: [] }, }; console.log(await filePolicy.can(sharedUser, "file:read", file)); // true (via sharedPolicy) console.log(await filePolicy.can(sharedUser, "file:write", file)); // true (via sharedPolicy) console.log(await filePolicy.can(sharedUser, "file:delete", file)); // false (no policy allows) ``` ## Combining Both Strategies You can combine `mergePoliciesAnd()` and `mergePoliciesOr()` for complex scenarios: ```ts import { mergePoliciesAnd, mergePoliciesOr } from "@zap-studio/permit"; // Access layer: multiple paths to access const accessPolicy = mergePoliciesOr(ownerPolicy, sharedPolicy, publicPolicy); // Security layer: must pass all security checks const securedPolicy = mergePoliciesAnd(auditPolicy, compliancePolicy, ratePolicy); // Final policy: must have access AND pass security const finalPolicy = mergePoliciesAnd(accessPolicy, securedPolicy); ``` ### Visualization ```text ┌─────────────┐ │ finalPolicy │ └──────┬──────┘ │ AND (mergePoliciesAnd) ┌─────────────┴─────────────┐ │ │ ┌──────┴──────┐ ┌──────┴───────┐ │accessPolicy │ │securedPolicy │ └──────┬──────┘ └──────┬───────┘ │ OR │ AND ┌───────┼───────┐ ┌───────┼───────┐ │ │ │ │ │ │ owner shared public audit compliance rate ``` ## Empty Policy Lists Merging zero policies always denies, with either strategy: ```ts const emptyAnd = mergePoliciesAnd(); // can() always resolves to false const emptyOr = mergePoliciesOr(); // can() always resolves to false ``` ## Best Practices 1. **Name policies descriptively** — `securityPolicy`, `ownerAccessPolicy`, `compliancePolicy` 2. **Keep policies focused** — Each policy should handle one concern 3. **Document why each policy is included** — Argument order has no effect on the result; explain each policy's role instead of relying on its position 4. **Test merged policies** — Ensure the combined behavior is correct 5. **Keep merged policies cheap** — Every policy runs on every check, even after another has already decided the outcome; avoid expensive work (I/O, heavy computation) inside a merged policy's rules --- # OpenTelemetry Source: https://www.zapstudio.dev/docs/permit/opentelemetry `@opentelemetry/api` is a required peer dependency of `@zap-studio/permit`. It's a tiny, side-effect-free package that's a no-op until an app registers a real SDK, so installing it costs nothing at runtime for consumers who never set one up — the same deal [`logger?`](/docs/permit/logging) already gives. ```bash npm npm install @opentelemetry/api ``` ```bash yarn yarn add @opentelemetry/api ``` ```bash pnpm pnpm add @opentelemetry/api ``` ```bash bun bun add @opentelemetry/api ``` ```bash deno deno add npm:@opentelemetry/api ``` There's no option to configure — tracing is always on, and does nothing observable until your app registers an OpenTelemetry SDK: ```ts import { createPolicy } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules }); await policy.can(ctx, "post:write", post); ``` ## What Gets Instrumented Every `can(...)` call produces an `INTERNAL` span named `permit.check {resourceType}:{action}` (e.g. `permit.check post:write`), with a `permit.decision` attribute set to `"allow"` or `"deny"` once the check resolves. A permission string that doesn't parse, an action that isn't allowed, or a resource that fails validation all resolve to `"deny"`, same as a rule explicitly denying. A `permit.checks` counter is incremented alongside every span, tagged with the same `permit.decision` value — the metric to graph "what's our deny rate" without needing a trace backend. ## Merged Policies `mergePoliciesAnd(...)` and `mergePoliciesOr(...)` get their own span around the composite check, in addition to the spans each underlying policy already produces for its own `can(...)` call — so a merged check shows up as one span with the aggregate decision, with each contributing policy's check nested inside it. ## Log Correlation Pair this with [`logger`](/docs/logger/opentelemetry): once a span is active, `ConsoleLogger` automatically stamps `trace_id`/`span_id` onto every log line, so the allow/deny logs from [the `logger` option](/docs/permit/logging) line up with the check spans. --- # Role-Based Access Control Source: https://www.zapstudio.dev/docs/permit/roles `permit` implements role checks via `hasRole(role, hierarchy?)`, with inheritance resolved by `collectInheritedRoles`. Role-Based Access Control (RBAC) is a common authorization pattern where permissions are assigned to roles, and users are assigned roles. ## Understanding RBAC In RBAC, instead of assigning permissions directly to users, you: 1. Define **roles** (e.g., "guest", "user", "admin") 2. Assign **permissions** to roles (e.g., admin can delete posts) 3. Assign **roles** to users (e.g., Alice is an admin) This simplifies permission management — when you need to change what admins can do, you update the role's permissions once instead of updating every admin user. ## Simple Role Checks The `hasRole()` function checks if the current user has a specific role: ```ts import { hasRole } from "@zap-studio/permit"; hasRole(role); hasRole(role, hierarchy); ``` :::note `hasRole()` returns a `ConditionFn` for use inside `when()` (or combinators like `or()`). It does not return a boolean directly. ::: ### Context Requirements Your context must include a top-level `role` property that can be: - A single role: `{ role: "admin" }` - An array of roles: `{ role: ["user", "moderator"] }` ### Example: Basic RBAC ```ts import { z } from "zod"; import { createPolicy, when, hasRole, or } from "@zap-studio/permit"; import type { Resources, Actions } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string(), status: z.enum(["draft", "published", "archived"]), }), user: z.object({ id: z.string(), email: z.string(), }), } satisfies Resources; const actions = { post: ["read", "write", "delete", "publish"], user: ["read", "update", "delete", "ban"], } as const satisfies Actions; type Role = "guest" | "user" | "moderator" | "admin"; type AppContext = { user: { id: string } | null; role: Role; }; const policy = createPolicy({ resources, actions, rules: { post: { // Guests can read published posts read: when((ctx, _, post) => post.status === "published" || ctx.role === "user"), // Users can write their own posts write: when((ctx, _, post) => ctx.role === "user" && ctx.user?.id === post.authorId), // Moderators and admins can delete any post delete: when(or(hasRole("moderator"), hasRole("admin"))), // Only admins can publish publish: when(hasRole("admin")), }, user: { // Users can read their own profile, admins can read any read: when(or((ctx, _, user) => ctx.user?.id === user.id, hasRole("admin"))), // Users can update their own profile update: when((ctx, _, user) => ctx.user?.id === user.id), // Only admins can delete users delete: when(hasRole("admin")), // Moderators and admins can ban users ban: when(or(hasRole("moderator"), hasRole("admin"))), }, }, }); ``` ## Role Hierarchies Often, higher-level roles inherit permissions from lower-level roles. For example, an admin should have all permissions that a user has, plus admin-specific ones. ### Defining a Role Hierarchy A role hierarchy maps each role to an array of roles it inherits from: ```ts import type { RoleHierarchy } from "@zap-studio/permit"; type Role = "guest" | "user" | "moderator" | "admin"; const roleHierarchy: RoleHierarchy = { guest: [], // No inherited roles user: ["guest"], // Users inherit guest permissions moderator: ["user"], // Moderators inherit user permissions admin: ["moderator"], // Admins inherit moderator permissions }; // Permission inheritance chain: // admin → moderator → user → guest ``` ### Using hasRole with Hierarchy Pass the hierarchy as the second argument to `hasRole()`: ```ts import { hasRole } from "@zap-studio/permit"; // Without hierarchy: only matches exact role hasRole("user"); // Only true if role === "user" // With hierarchy: matches role or any role that inherits from it hasRole("user", roleHierarchy); // True for "user", "moderator", or "admin" ``` ## Multiple Roles Users can have multiple roles. The context can include an array of roles: ```ts type AppContext = { user: { id: string } | null; role: Role[]; // Array of roles }; const context: AppContext = { user: { id: "user-1" }, role: ["user", "beta-tester"], // User has both roles }; ``` `hasRole()` checks if any of the user's roles match (or inherit from) the required role. ### Example: Multiple Roles ```ts import { z } from "zod"; import { createPolicy, when, hasRole, or } from "@zap-studio/permit"; import type { Resources, Actions, RoleHierarchy } from "@zap-studio/permit"; const resources = { betaFeature: z.object({ id: z.string(), name: z.string(), }), supportTicket: z.object({ id: z.string(), userId: z.string(), priority: z.enum(["low", "normal", "high", "urgent"]), }), } satisfies Resources; const actions = { betaFeature: ["access"], supportTicket: ["create", "escalate"], } as const satisfies Actions; type Role = "user" | "beta-tester" | "premium" | "support-agent" | "admin"; const roleHierarchy: RoleHierarchy = { user: [], "beta-tester": ["user"], premium: ["user"], "support-agent": ["user"], admin: ["premium", "support-agent"], // Admin inherits from multiple roles }; type MultiRoleContext = { user: { id: string } | null; role: Role[]; }; const multiRolePolicy = createPolicy({ resources, actions, rules: { betaFeature: { // Only beta testers can access beta features access: when(hasRole("beta-tester", roleHierarchy)), }, supportTicket: { // Any authenticated user can create tickets create: when(hasRole("user", roleHierarchy)), // Only premium users or support agents can escalate escalate: when( or(hasRole("premium", roleHierarchy), hasRole("support-agent", roleHierarchy)), ), }, }, }); // User with multiple roles const betaPremiumUser: MultiRoleContext = { user: { id: "u1" }, role: ["user", "beta-tester", "premium"], }; const ticket = { id: "t1", userId: "u1", priority: "normal" as const }; const feature = { id: "f1", name: "New Dashboard" }; console.log(await multiRolePolicy.can(betaPremiumUser, "betaFeature:access", feature)); // true (has beta-tester) console.log(await multiRolePolicy.can(betaPremiumUser, "supportTicket:escalate", ticket)); // true (has premium) ``` ## Collecting Inherited Roles The `collectInheritedRoles()` function returns the full set of roles a user has, including inherited ones. It handles repeated roles safely and returns a `Set`. ```ts import { collectInheritedRoles } from "@zap-studio/permit"; collectInheritedRoles(roles, hierarchy); ``` ### Example: Role Inspection ```ts import { collectInheritedRoles } from "@zap-studio/permit"; import type { RoleHierarchy } from "@zap-studio/permit"; type Role = "guest" | "user" | "moderator" | "admin" | "beta-tester"; const hierarchy: RoleHierarchy = { guest: [], user: ["guest"], moderator: ["user"], admin: ["moderator"], "beta-tester": [], }; // Get all roles for an admin const adminRoles = collectInheritedRoles(["admin"], hierarchy); console.log(adminRoles); // Set { "admin", "moderator", "user", "guest" } // Get all roles for a moderator const modRoles = collectInheritedRoles(["moderator"], hierarchy); console.log(modRoles); // Set { "moderator", "user", "guest" } // Multiple input roles const mixedRoles = collectInheritedRoles(["user", "beta-tester"], hierarchy); console.log(mixedRoles); // Set { "user", "guest", "beta-tester" } ``` ## Best Practices 1. **Keep hierarchies simple** — Deep hierarchies are hard to reason about 2. **Document role permissions** — Maintain a clear mapping of what each role can do 3. **Use meaningful role names** — "editor" is clearer than "level-3" 4. **Avoid circular dependencies** — Role A should not inherit from role B if B inherits from A 5. **Test edge cases** — Especially when users have multiple roles --- # Scaling Policies Source: https://www.zapstudio.dev/docs/permit/scaling-policies A policy with a handful of resources fits comfortably in one file. Once your app has a dozen resources — each with several actions and rules referencing different parts of your domain — that one `createPolicy()` call becomes hard to navigate and merge-conflict-prone to edit. Split it by domain instead. ## Split Rules Across Files, Keep One Policy The recommended pattern: each domain owns a file that exports its own `resources`, `actions`, and rules slice. A central file composes them into a single `resources`, a single `actions`, and a single `rules` object, then calls `createPolicy()` once. You still get one policy with one shared permission-string type — `"post:read"`, `"comment:write"`, and so on all type-check against the same `can()` — but no file holds more than one domain's worth of rules. Every domain file below imports one shared context type from `context.ts`: ```ts context.ts export type AppContext = { user: { id: string; role: "guest" | "user" | "admin" } | null; }; ``` ```ts policies/post.ts import { deny, when } from "@zap-studio/permit"; import type { ActionPolicyMap, Actions, Resources } from "@zap-studio/permit"; import { z } from "zod"; import type { AppContext } from "../context.js"; export const postResources = { post: z.object({ id: z.string(), authorId: z.string(), visibility: z.enum(["public", "private"]), }), } satisfies Resources; export const postActions = { post: ["read", "write", "delete"], } as const satisfies Actions; export const postRules: ActionPolicyMap< AppContext, (typeof postActions)["post"][number], z.infer > = { read: when((_, __, post) => post.visibility === "public"), write: when((ctx, _, post) => ctx.user?.id === post.authorId), delete: deny(), }; ``` ```ts policies/comment.ts import { allow, when } from "@zap-studio/permit"; import type { ActionPolicyMap, Actions, Resources } from "@zap-studio/permit"; import { z } from "zod"; import type { AppContext } from "../context.js"; export const commentResources = { comment: z.object({ id: z.string(), postId: z.string(), authorId: z.string(), }), } satisfies Resources; export const commentActions = { comment: ["read", "write"], } as const satisfies Actions; export const commentRules: ActionPolicyMap< AppContext, (typeof commentActions)["comment"][number], z.infer > = { read: allow(), write: when((ctx, _, comment) => ctx.user?.id === comment.authorId), }; ``` ```ts policies/index.ts import { createPolicy } from "@zap-studio/permit"; import type { Actions, Resources, Rules } from "@zap-studio/permit"; import type { AppContext } from "../context.js"; import { commentActions, commentResources, commentRules } from "./comment.js"; import { postActions, postResources, postRules } from "./post.js"; const resources = { ...postResources, ...commentResources, } satisfies Resources; const actions = { ...postActions, ...commentActions, } as const satisfies Actions; const rules: Rules = { post: postRules, comment: commentRules, }; export const policy = createPolicy({ resources, actions, rules, }); ``` ```ts usage import { policy } from "./policies/index.js"; await policy.can(ctx, "post:read", post); await policy.can(ctx, "comment:write", comment); ``` :::note `Rules` requires an entry for every key in `TResources`, so `policies/index.ts` is the one place that has to know about every domain — everything else about a domain's rules lives in that domain's own file. ::: Add a new domain by adding a file and one spread in each of the three objects in `policies/index.ts`. Nothing else changes. ## When to Merge Separate Policies Instead If your domains are independent enough that they're built and owned separately — different packages, different teams, policies that only come together at the edge of your app — build each as its own `createPolicy()` with its own narrower `resources` and `actions`, then combine them with [`mergePoliciesOr()`](/docs/permit/merging-policies#mergepoliciesor--or-strategy): ```ts policies/post.ts import { createPolicy, deny, when } from "@zap-studio/permit"; import type { Actions, Resources } from "@zap-studio/permit"; import { z } from "zod"; import type { AppContext } from "../context.js"; const postResources = { post: z.object({ id: z.string(), authorId: z.string(), visibility: z.enum(["public", "private"]), }), } satisfies Resources; const postActions = { post: ["read", "write", "delete"], } as const satisfies Actions; export const postPolicy = createPolicy({ resources: postResources, actions: postActions, rules: { post: { read: when((_, __, post) => post.visibility === "public"), write: when((ctx, _, post) => ctx.user?.id === post.authorId), delete: deny(), }, }, }); ``` ```ts usage import { mergePoliciesOr } from "@zap-studio/permit"; import { postPolicy } from "./policies/post.js"; import { commentPolicy } from "./policies/comment.js"; // built the same way const policy = mergePoliciesOr(postPolicy, commentPolicy); await policy.can(ctx, "post:read", post); // routed to postPolicy await policy.can(ctx, "comment:write", comment); // routed to commentPolicy ``` This works because a policy denies any permission for a resource type it doesn't define — `postPolicy` only knows about `"post"`, so it denies every `"comment:*"` check without commentPolicy's rules ever coming into play. With `mergePoliciesOr()`, each permission check is effectively routed to the one policy that owns that resource type. :::warning Don't reach for `mergePoliciesAnd()` to combine domain-split policies. It requires **every** merged policy to allow, and a policy that doesn't own a resource type always denies it — so anything outside the intersection of all domains would be denied by every check. `mergePoliciesAnd()` is for layering restrictions onto the _same_ resources (see [Merging Policies](/docs/permit/merging-policies)), not for splitting by domain. ::: ## Which Approach to Use | | Split rules, one policy | Separate policies, merged | | ------------------------------------------------------------------- | ------------------------------------ | ------------------------------------------------------ | | Permission strings | One shared type across all domains | Only valid within each domain's own policy | | Cross-domain rules (e.g. a comment rule that reads the parent post) | Straightforward — one `rules` object | Not possible — each policy only sees its own resources | | Ownership | One codebase, split by file | Can live in separate packages | | Composition | Compile-time, via object spread | Runtime, via `mergePoliciesOr()` | Default to splitting rules across files with one policy. Reach for merging separate policies only when domains are genuinely owned and shipped independently. ## Best Practices 1. **One file per domain** — a domain's `resources`, `actions`, and rules live together, next to the code that uses them 2. **Keep the composition file thin** — `policies/index.ts` should only spread and call `createPolicy()`, not contain any rule logic itself 3. **Name exports after the domain** — `postResources`, `postActions`, `postRules` scan easily across files 4. **Share the context type** — import one `AppContext` type everywhere instead of redefining it per domain 5. **Reach for `mergePoliciesOr()` only across real boundaries** — package, team, or deployment boundaries, not just "this file got long" --- # Standard Schema Support Source: https://www.zapstudio.dev/docs/permit/standard-schema `permit` works with Zod, Valibot, ArkType, or any compatible library. `permit` validates resources through the [Standard Schema](https://standardschema.dev/) specification instead of binding to one validation library. Define resources with the `Resources` type helper and any Standard Schema-compatible schema. ## Defining Resources ```ts Zod import { z } from "zod"; import type { Resources } from "@zap-studio/permit"; const resources = { post: z.object({ id: z.string(), authorId: z.string(), visibility: z.enum(["public", "private"]), }), } satisfies Resources; ``` ```ts Valibot import * as v from "valibot"; import type { Resources } from "@zap-studio/permit"; const resources = { post: v.object({ id: v.string(), authorId: v.string(), visibility: v.picklist(["public", "private"]), }), } satisfies Resources; ``` ```ts ArkType import { type } from "arktype"; import type { Resources } from "@zap-studio/permit"; const resources = { post: type({ id: "string", authorId: "string", visibility: "'public' | 'private'", }), } satisfies Resources; ``` :::warning Use `satisfies` to ensure type safety and consistency. Learn more about the [TypeScript `satisfies` operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator). ::: ## How Validation Runs Resources are validated against their schema whenever `policy.can()` evaluates a rule for that resource. Invalid resources resolve to `false` instead of throwing — see [Error Handling](/docs/permit/errors) for how `permit` surfaces failures. --- # Principles Source: https://www.zapstudio.dev/docs/principles Fourteen packages, one set of rules. This page says what those rules are, so you can predict how a package you have not read yet will behave. ## The Problem Most teams solve these problems by hand, per project — and the hard parts get skipped: - **Fragile by default.** Hand-rolled retries and webhook checks quietly skip the parts that matter: jitter, cancellation, constant-time signature comparison. - **Scattered, not audited.** Permission checks end up copy-pasted across the codebase instead of living in one place you can read in one sitting. - **Node-only, until it isn't.** Homegrown wrappers break the moment your code runs on an edge runtime or in the browser. ## What Every Package Guarantees - **Type safety.** Types come from your schema through [Standard Schema](https://standardschema.dev), not from hand-written annotations. No `as` casts to make a response fit. - **Framework-agnostic.** Built on standard runtime APIs — `fetch`, `Request`/`Response`, `AbortSignal`, `crypto.subtle`. No framework adapter, no plugin system, no global setup. - **Composable.** Each package does one thing and accepts the others as plain values: wrap a `fetch` call in a `retry` policy, validate a webhook payload with `validation`, pass a `logger` to any of them. - **Tree-shakeable.** Standalone functions with no shared state, one subpath per feature. What you do not import does not ship. ## What That Rules Out These follow from the four rules above, and they are choices, not omissions: - **No runtime of its own.** No effect system, no scheduler, no dependency injection container. Functions in, values out. - **No hidden state.** Nothing registers a global, patches a prototype, or reads an implicit context. A cache, a policy or a router is a value you created and can throw away. - **No required logging or tracing.** Both are optional parameters. Pass nothing and there is no dependency and no cost. - **No CommonJS.** Standard ESM only, so the tree-shaking guarantee holds. ## Compared to Effect If you know [Effect](https://effect.website): yes, there is overlap — typed errors, retries, schema validation. Effect is a full ecosystem built around its own runtime, and that investment pays off once you need that level of control. Zap Studio stays in plain TypeScript — no new runtime, no new mental model, small packages you adopt one at a time. Reach for it when you don't need everything Effect brings. ## Not For You If - You want one framework that owns your whole effect/error model — Effect is built for that. - You need every package to come from a single all-in-one SDK. - What you have today isn't costing you bugs. ## Next **[Composition](/docs/composition)** The composability rule, in working code. **[Getting Started](/docs)** Install one package and make a typed call. --- # react-hooks Source: https://www.zapstudio.dev/docs/react-hooks `react-hooks` is a collection of 100+ small, focused React hooks. Each hook ships as its own subpath export — importing one never pulls in unrelated hooks — with SSR-safe defaults and 100% test coverage. ## Motivation Reaching a browser API from React usually means hand-writing a `useEffect` — a resize listener, a `matchMedia` subscription, an `IntersectionObserver` — and each one carries the same two risks: forget the cleanup and you get a leaked listener that keeps firing after unmount, or forget to guard `window`/`document`/`navigator` and the same code throws on the server or hydrates to a value the client's first render did not have. `react-hooks` wraps these APIs — `IntersectionObserver`, `ResizeObserver`, the Battery/Geolocation/Share/Wake Lock APIs, `matchMedia`, and more — behind a small, correct React interface instead of code you write from scratch. Every hook is SSR- and hydration-safe: nothing touches `window`, `document`, or `navigator` outside an effect or a guarded check, so server renders never throw and hydration never mismatches. Every hook also ships as its own standalone, side-effect-free module — import it on its own and it tree-shakes cleanly. Public hooks never import each other; some share small internal helper modules, so pulling in `useIsMobile` never drags in unrelated hook code. ## Conventions - Every hook is available both from the top-level `.` barrel and from its own subpath (e.g. `@zap-studio/react-hooks/sensors/use-is-mobile`) — same function either way. - No hook file imports another hook file. ### Unstable vs. Experimental Two different name markers warn about two different kinds of risk: - **`Unstable`** — the hook reads a private API with no public type, not guaranteed to stay the same shape between React versions. Only `useUnstableFiber` and `useUnstableRenderReason` carry this marker, both in [Debug / Observability](/docs/react-hooks/debug): they walk react-dom's internal Fiber tree, the same private structure React DevTools itself reads. The risk is about **this package breaking on a React upgrade**, not about the browser. - **`Experimental`** — the hook wraps a browser Web API that MDN itself badges "Experimental," like the Idle Detection API or Web NFC. The hook's own code is stable; the risk is that **the browser API can change or ship in fewer browsers than you'd like**. Every `useExperimental*` hook still fails closed: `supported: false` (or the equivalent) wherever the underlying API doesn't exist, instead of throwing. A hook with neither marker is built entirely on public, standard APIs — safe to treat like any other hook in the package. ## Hooks by Category - [Sensors](/docs/react-hooks/sensors) — viewport, network, device, and permission state (`useMediaQuery`, `useOnlineStatus`, `useGeolocation`, `useBattery`, ...) - [DOM / Element Interaction](/docs/react-hooks/dom) — ref'd-element observers and browser chrome APIs (`useClickOutside`, `useIntersectionObserver`, `useFullscreen`, ...) - [Input](/docs/react-hooks/input) — keyboard, gamepad, and pointer input (`useKeyPress`, `useHotkeys`, `useGamepad`, ...) - [Media](/docs/react-hooks/media) — camera, microphone, and screen capture (`useCamera`, `useMediaRecorder`, `useSpeechRecognition`, ...) - [History & Navigation](/docs/react-hooks/navigation) — `popstate` and the Navigation API (`usePopState`, `useNavigation`, `useNavigationBlocker`, ...) - [Network](/docs/react-hooks/network) — WebSocket and Server-Sent Events (`useWebSocket`, `useEventSource`) - [PWA](/docs/react-hooks/pwa) — installability and service worker state (`useInstallPrompt`, `useServiceWorker`, ...) - [Commerce](/docs/react-hooks/commerce) — the Payment Request API (`usePaymentRequest`) - [Lifecycle](/docs/react-hooks/lifecycle) — mount/unmount, timers, and async helpers (`useMount`, `useInterval`, `useAsync`, ...) - [State](/docs/react-hooks/state) — local, persisted, and cross-tab state (`useLocalStorage`, `useIndexedDB`, `useBroadcastChannel`, ...) - [Debug / Observability](/docs/react-hooks/debug) — render diagnostics (`useRenderCount`, `useWhyDidYouUpdate`, `useUnstableFiber`, ...) ## Learn More - [Getting Started](/docs/react-hooks/getting-started) — install the package --- # Commerce Source: https://www.zapstudio.dev/docs/react-hooks/commerce A single hook wrapping the browser's native checkout UI. ## usePaymentRequest Wraps the [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API) — shows the browser/OS's native payment sheet for the given payment method data and details, resolving with the user's `PaymentResponse` once they authorize it. Callers are responsible for calling `response.complete("success" | "fail")` once their own backend confirms the charge — this hook only tracks whether the sheet itself completed or was cancelled/errored, not whether the charge succeeded. `supported: false` — the SSR-safe default — where the Payment Request API doesn't exist, and `pay()` then resolves `undefined` without throwing. [Support varies by browser and payment method](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API#browser_compatibility) — check `supported` before relying on it. ```tsx const { pay, status } = usePaymentRequest(); const response = await pay([{ supportedMethods: "basic-card" }], { total: { label: "Total", amount: { currency: "USD", value: "10.00" } }, }); await response?.complete("success"); ``` ## See Also - [Getting Started](/docs/react-hooks/getting-started) - [Overview](/docs/react-hooks) --- # Debug / Observability Source: https://www.zapstudio.dev/docs/react-hooks/debug Every hook in this category is a dev tool: it turns itself off in production builds, the same way React's own dev-only warnings do. Two of them — `useUnstableFiber` and `useUnstableRenderReason` — read react-dom's private, undocumented Fiber tree to do their job. That tree has no public type and isn't guaranteed to stay the same shape between React versions, so these two carry an `Unstable` marker in their own name. The risk travels with every import and autocomplete hit, not just a path a reader might skip. See [Unstable vs. Experimental](/docs/react-hooks#unstable-vs-experimental) for what that marker means package-wide. The rest of this page's hooks (`useRenderCount`, `useWhyDidYouUpdate`, `useIsFirstRender`, `useRenderDuration`, `useOwnerStack`) are built entirely on public React APIs (`useRef`, `useEffect`, ``, `captureOwnerStack`) — nothing private, so no `Unstable` marker. ## useRenderCount The render count for the calling component instance — `1` on mount, incrementing by one on every subsequent render. Always `0` in production builds. ```tsx const renderCount = useRenderCount(); console.log(`rendered ${renderCount} times`); ``` ## useWhyDidYouUpdate Logs which of `props`' keys changed to cause the current render — `console.log`s a `name`-labeled table of `{ from, to }` per changed key, or nothing when no key changed (a render caused by state/context rather than these particular props). Does nothing on the mount render, since there's no previous `props` to diff against, or in production builds. ```tsx function UserCard(props: { name: string; age: number }) { useWhyDidYouUpdate("UserCard", props); return
{props.name}
; } ``` ## useIsFirstRender `true` only on the mount render, `false` on every render after. Always `false` in production builds. ```tsx const isFirstRender = useIsFirstRender(); if (isFirstRender) console.log("mounted"); ``` ## useUnstableRenderReason Classifies why the ref'd component just re-rendered — `"mount"`, `"props"`, `"state"` (a `useState`/`useReducer` value changed), `"context"` (a read `useContext()` value changed), or `"parent"` (none of the above changed, so the parent re-rendered this component without a locally-observable cause). Computed in an effect, after commit, so `reason` updates one render behind the change that caused it. Call it as the first hook in the component — state detection skips this hook's own internal hooks by count when walking the Fiber hook list, so a stateful hook called before it would be miscounted as this hook's own. `options.maxWalk` caps how many Fiber ancestors, hooks, and context entries get walked while computing the reason. Defaults to 50. ```tsx const { ref, reason } = useUnstableRenderReason(); return
{reason}
; ``` ## useUnstableFiber Returns the nearest Fiber node for a ref'd DOM element, via react-dom's private `__reactFiber$` DOM pointer — walks up to the nearest function-component ancestor when found, else the host (DOM) fiber itself. No public API for this — it's the same private tree React DevTools itself walks. `fiber` is `null` until `ref` attaches to a mounted element, and stays `null` (rather than throwing) on an unrecognized internal shape or in production builds. `options.maxWalk` caps how many ancestors get walked while looking for a function component. Defaults to 50. ```tsx const { ref, fiber } = useUnstableFiber(); return
{typeof fiber?.type === "function" ? fiber.type.name : "?"}
; ``` ## useRenderDuration Wraps React's [``](https://react.dev/reference/react/Profiler) `onRender` timing as a hook — pass `onRender` to a `` wrapping the subtree to measure; `samples` accumulates each render's `{ id, phase, actualDuration, baseDuration, startTime, commitTime }`, capped at the last `limit` (default `20`). Records nothing in production builds. ```tsx const { onRender, last } = useRenderDuration(); return ( ); ``` ## useOwnerStack Wraps React 19's [`captureOwnerStack`](https://react.dev/reference/react/captureOwnerStack) debug API — call `captureOwnerStack()` during an event handler or effect to get the JSX "owner" stack (which component rendered which), the same trace React's own dev warnings use. `supported: false` where the export doesn't exist (React < 19, or a production build — React's own `captureOwnerStack` already returns `null` there, which this wrapper surfaces as `undefined`). ```tsx const { captureOwnerStack: capture, supported } = useOwnerStack(); const handleError = () => console.error(supported ? capture() : "unavailable"); ``` ## See Also - [Getting Started](/docs/react-hooks/getting-started) - [Overview](/docs/react-hooks) --- # DOM / Element Interaction Source: https://www.zapstudio.dev/docs/react-hooks/dom Hooks that observe a ref'd DOM element (visibility, size, mutations, hover, drag state) or reach into browser chrome (favicon, fullscreen, script loading, the clipboard-adjacent EyeDropper). Every hook here degrades to an inert, SSR-safe default when its underlying API is unsupported. ## useClickOutside Calls `onOutside` on a `mousedown`/`touchstart` whose target falls outside the ref'd element — the standard "close on outside click" pattern for dropdowns, popovers, and modals. Listens on the capture phase, so it still fires even if an inner handler calls `stopPropagation()`. ```tsx const ref = useClickOutside(() => setOpen(false)); return open ?
Menu
: null; ``` ## useHover Boolean hover state for a single ref'd element, via [`mouseenter`/`mouseleave`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event). ```tsx const { ref, hovered } = useHover(); return
{hovered ? "Hovering" : "Not hovering"}
; ``` ## useMousePosition Tracks the pointer's `clientX`/`clientY` (plus `pageX`/`pageY` and `screenX`/`screenY`) via window's [`mousemove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event) event. There's no synchronous read for pointer position, only the event, so this starts at all-`0` until the pointer first moves. ```tsx const { clientX, clientY } = useMousePosition(); ``` ## useIntersectionObserver Tracks whether the ref'd element is visible in the viewport (or a given `root`), via [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). `options` is passed straight through to the observer (`root`/`rootMargin`/`threshold`). Also exported as `useInView`, an alias for the same hook. ```tsx const { ref, inView } = useIntersectionObserver(); return
{inView ? "Visible" : "Off-screen"}
; ``` ## useResizeObserver Tracks the ref'd element's content-box size via [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver). ```tsx const { ref, size } = useResizeObserver(); return (
{size?.width}×{size?.height}
); ``` ## useEventListener Typed [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) wrapper with automatic cleanup — attaches `handler` for `type` on `target` (a `RefObject`, a DOM node, or `window`/`document`), and removes it on unmount or when the resolved element, `type`, or `options` change. Neither `handler` nor `options` needs to be memoized: the latest `handler` is always called without re-subscribing, and `options` is compared field by field, so an object literal written inline at the call site is free. The listener is attached in a layout effect ([`useIsomorphicLayoutEffect`](/docs/react-hooks/lifecycle#useisomorphiclayouteffect)), before the browser paints, so no event can slip through the gap a passive effect would leave open. When `target` is a ref, its `current` is re-read on every commit — a ref that is still `null` on the first render, or that later points at a different element, is picked up as soon as React commits the change. ```tsx const ref = useRef(null); useEventListener(ref, "scroll", (event) => console.log(event)); useEventListener(window, "resize", () => console.log("resized")); ``` ## useLockBodyScroll Locks `document.body`'s scroll while `locked` is `true` — the standard "no background scroll behind an open modal/drawer" pattern. Restores the body's previous inline `overflow` on unlock or unmount. ```tsx useLockBodyScroll(isModalOpen); ``` ## useFavicon Imperatively swaps the `` `href` — creates the tag if the document doesn't already have one, and restores the previous `href` on unmount. ```tsx useFavicon(hasUnread ? "/favicon-unread.svg" : "/favicon.svg"); ``` ## useScript Loads an external `