For the complete documentation index, see llms.txt. Every page is also served as Markdown at its URL followed by .md.

standards
Set up the clientData model

Set up the client

Install @standards/client, create one server-side client, and know what it covers before you write your first object.


@standards/client is one package. It carries the schema builders, bundle, createStandards and the error classes. You declare your objects in TypeScript, sync them to a workspace with bundles.sync, read and write typed records with db.<object>, upload files with files and documents, and read AI usage with usage. Nothing else is required: no runtime, no framework adapter.

pnpm add @standards/client

The package runs on Node 22 or newer, and on edge runtimes: bundle does nothing at import, and hashing uses Web Crypto.

Create the client

import { createStandards } from "@standards/client";

export const standards = createStandards();

Called without an argument, createStandards reads STANDARDS_API_URL and STANDARDS_API_KEY from process.env, the same two variables the CLI reads. Pass any option explicitly and it wins over its variable; the rest still come from the environment:

export const standards = createStandards({
  baseUrl: "https://api.standards.new/v1", // wins over STANDARDS_API_URL
  // apiKey still comes from STANDARDS_API_KEY
});

Pass your source as schema to get one typed query per object. The key is the camelCase of the object name:

import { createStandards } from "@standards/client";
import { statusSource } from "./schema";

const db = createStandards({
  baseUrl: "https://api.standards.new/v1",
  apiKey: process.env.STANDARDS_API_KEY!,
  schema: statusSource,
});

await db.checks.fetch();

createStandards takes six options and nothing else.

OptionRequiredDefaultEffect
baseUrlyes, unless STANDARDS_API_URL is setSTANDARDS_API_URLThe API root, /v1 included. A dedicated instance uses its own hostname.
apiKeyyes, unless STANDARDS_API_KEY is setSTANDARDS_API_KEYSent as Authorization: Bearer. bundles.sync needs a key whose role grants architect:update.
bundlesnononeThe bundles you declare with bundle(name, label). Exposes db.<camelCaseName> for each of its objects, typed from the builders.
tenantIdnononeSent as X-Tenant-ID on every request.
timeoutMsno30_000Bounds each request until its response headers arrive; reading the body is not timed.
transportnononeCalls go through this transport instead of an API key's HTTP connection: the in-process one in a server that embeds Standards. With it, baseUrl, apiKey, tenantId and timeoutMs are refused with StandardsConfigurationError, and export() needs an HTTP transport.

An empty variable counts as unset. When a value is in neither place, createStandards throws StandardsConfigurationError before sending anything, and the message names the variable: STANDARDS_API_URL first, then STANDARDS_API_KEY. The variables are read when you call createStandards, never at import, and only when a process global exists, so importing the package in a runtime without one does not throw.

There is no fetch override, no custom headers option and no retry. Retries, if you need them, live in your code.

The ready instance

standards is a client already made: import it and call it.

import { standards } from "@standards/client";
import type { status } from "./schema";

declare module "@standards/client" {
  interface Register {
    bundle: typeof status;
  }
}

await standards.checks.all();

Its transport is chosen on first use. In a server that embeds Standards (a licensed backend host, which registers itself at boot), each call runs in that process, and its objects are the host's bundles. Anywhere else it calls the API over HTTP with STANDARDS_API_URL and STANDARDS_API_KEY, and with neither a host nor the variables it throws StandardsConfigurationError naming the variable to set. Over HTTP it reaches the contract and from(objectName): pass bundles to createStandards for typed objects there. The Register declaration types it, with no generic to repeat; createStandards stays for several clients or another workspace.

Who acts

Over HTTP, every call acts as the API key's actor. In process, the place the code runs says who acts:

The code runs in…It acts as
An authenticated requestThe request's user or API key
A trigger fired by a writeThe write's author
A taskThe actor who enqueued it
A cron, a task no one enqueued, boot, a scriptThe workspace's system actor
A public route (a webhook)The workspace's system actor
A request whose context was lost (a guard, a detached callback)Refused: ActorContextLostError, code ACTOR_CONTEXT_LOST

as overrides it, in process only (over HTTP it is absent from the type, and the ready instance refuses it with StandardsConfigurationError):

await standards.as("system").checks.all();
await standards.as(managerId).checks.all();

as(actorId) returns the same client acting as that actor, with that actor's permissions and visibility; as("system") acts as the workspace's system actor. Actor ids are UUIDs, so "system" never collides with one. When an actor was acting, it is recorded as the one who triggered the call. as is a reserved key: no object may be named as.

The client is server-only. When a window global exists and an apiKey is set, createStandards throws StandardsConfigurationError before sending anything. In that context the environment is never read either: a call without an explicit baseUrl throws, even if STANDARDS_API_URL and STANDARDS_API_KEY are set. Keep the key in Route Handlers, Server Components, scripts and cron jobs.

The surface

ExportWhat it does
createStandards(config?)Returns every operation group of the API at the root, plus from and contract. Missing options come from STANDARDS_API_URL / STANDARDS_API_KEY. With bundles, it also exposes one typed query per object (see below).
standards.bundles.sync(bundle, { resolutions? })GET the bundle's summary, PUT it when the hash, label or description differs, with the renames and retypes it resolves. Never throws for "nothing to do". Given { name, bundle } (an artifact you built), it is the API's own call.
standards.<camelCaseName>With createStandards({ …, bundles: [bundle] }): a typed RecordsQuery per declared object (standards.dailyStats for daily-stats): filters, sorts, fetch, all, single, get, create, update, delete. An object named like an operation group takes its place at the root.
standards.from("name")The same query, untyped, for an object your code does not declare.
standards.<group>.<verb>(input)Every operation of the HTTP API, typed from the contract (standards.decisions.list({}), standards.users.get({ id }), standards.files.upload({ files }), standards.records.update({ objectName, id, values })), on the same connection. Answers are the API's own shapes (a record keeps its values bag).
standards.contract.<group>.<verb>(input)The same operations under their own names only: the way to a group one of your objects hides, since the object wins at the root. A group Standards adds later never changes what your code reads.
bundle(name, label)Declares a bundle of objects, views, pages and agents with .add() and keeps the builders for inference. Does no work at import: build() validates and hashes it on first sync.
object, text, number, date, select, status, relation, document, …The builders. listView, detailView, group and content declare views.
RecordInput, RecordUpdate, ExtractRecord, RecordMetadata, …The inference helpers.
StandardsRequestError, StandardsAuthError, BundleConflictError, BundleValidationError, StandardsConfigurationErrorThe error classes. Builders throw ValidationError and DuplicateError.
createTransport, createRecordsQueryThe lower layer, for raw calls and tests. A record's date attributes are decoded from its object's definition by recordValuesCodec (@standards/schema).

Files and documents

Files go through the operations of the HTTP API, standards.files and standards.documents. An upload takes a File (or a Blob with a name): the bytes, a filename and a MIME type. The server compares the MIME type, the extension and the file signature, so all three are sent. The client builds the multipart request and sends the same auth headers as every other call.

Publish a public file

import { readFile } from "node:fs/promises";
import { standards } from "./client";

const bytes = await readFile("./logo.png");
const [logo] = await standards.files.upload({
  files: [new File([bytes], "logo.png", { type: "image/png" })],
  public: true,
});

logo.publicUrl; // `{publicFilesUrl}/{id}`, readable without signing in

files.upload answers one entry per file sent. A public link is permanent and anyone who has it can open the file. It carries no credential. See Public files.

Attach a private file to a record

const { document, file } = await standards.records.attachDocument({
  objectName: "brand-assets",
  id: asset.id,
  attributeName: "original",
  files: new File([bytes], "original.png", { type: "image/png" }),
});

// Later, add a file to the same document:
await standards.records.attachDocument({
  objectName: "brand-assets",
  id: asset.id,
  attributeName: "original",
  documentId: document.id,
  files: new File([variant], "[email protected]", { type: "image/png" }),
});

One call is one POST /records/:object/:id/documents/attach. The server uploads the file, checks it against the attribute's accepts and maxFileSize, and creates the document or appends to documentId. If the attach fails, the server deletes the uploaded file. The route takes one file per request: to add more, call again with documentId. The file is always private. The attach takes bytes, never a file id, so a public upload can never be attached to a document. attributeName defaults to attachments. The result is { document, file, action }, where action is "created", "appended" or "linked-existing".

Every call takes options as its second argument. The client's timeoutMs (30 s by default) covers the whole upload, so raise it for large files: attachDocument({ … }, { timeoutMs: 300_000 }). A timed-out upload surfaces as StandardsRequestError with status 0, and the server may still have stored it. The attach is not idempotent, so before retrying a timed-out one, check with documents.files whether the file already landed.

Read a file back

const [original] = await standards.documents.files({ id: document.id });
const { url } = await standards.files.signedUrl({ id: original.id });
const response = await fetch(url);

signedUrl returns a new signed URL on every call. The URL expires, so request it right before you read the file and do not store it.

The server's refusals keep the classes the client already uses. A MIME type or size refusal is a StandardsRequestError with the server's status and code (for example 400 DOCUMENT_MIME_NOT_ACCEPTED). A key without the permission is a StandardsAuthError. A missing or invisible file or document is a StandardsRequestError with status: 404.

What the client does not cover

The typed client covers schema sync, records, files and documents. It does not cover global search, agents or forms. Which tool uploads is settled on Files and documents.

When you need one of them from Node, createTransport gives you the same authenticated fetch the client uses, without the typing:

import { createTransport } from "@standards/client";

const transport = createTransport({
  baseUrl: "https://api.standards.new/v1",
  apiKey: process.env.STANDARDS_API_KEY!,
});

const hits = await transport.get<{ data: unknown[] }>("/search", { q: "latency" });

The transport exposes get, post, patch, put, delete, getText and postMultipart. postMultipart(path, form, options?) takes an optional MultipartRequestOptions ({ timeoutMs }) that replaces the transport's timeout for that one request. It throws the same error classes as the client. Nothing on it revives dates or flattens values.

Keep three files under src/standards/, as the status page cookbook does.

src/standards/
  schema.ts        # the builders and the bundle
  client.ts        # createStandards, one instance per process
  sync-schema.ts   # a script: standards.bundles.sync(status)
// src/standards/schema.ts
import { bundle, date, number, object, relation, text } from "@standards/client";

export const service = object("services", "Service")
  .attribute(text("name", "Name").required())
  .attribute(text("url", "URL").url().required())
  .labelExpression("{{ name }}");

export const check = object("checks", "Check")
  .attribute(relation("service", "Service").to("services").required())
  .attribute(number("latencyMs", "Latency (ms)"))
  .attribute(date("checkedAt", "Checked at").includeTime().required())
  .labelExpression("{{ checkedAt }}");

export const status = bundle("status-site", "Status page").add(service, check);
// src/standards/client.ts
import { createStandards } from "@standards/client";
import { status } from "./schema";

let instance: ReturnType<typeof create> | null = null;

function create() {
  return createStandards({ bundles: [status] }); // STANDARDS_API_URL, STANDARDS_API_KEY
}

export function getStandards() {
  instance ??= create();
  return instance;
}
// src/standards/sync-schema.ts
import { getStandards } from "./client";
import { status } from "./schema";

const result = await getStandards().bundles.sync(status);
console.log(result.applied ? `applied ${result.hash}` : "already in sync");

Run the sync script from CI or by hand before the app starts. Sync is idempotent: an unchanged bundle costs one GET.

Testing without the network

db.<object> is createRecordsQuery(transport, builder) under the hood, and the transport argument only needs get, post, put and delete. export() also needs postRaw(path, body) returning a Response; without it, export() rejects with a StandardsConfigurationError. Hand it an in-memory object and every query stays typed:

import { createRecordsQuery } from "@standards/client";
import { service } from "./schema";

export const standards = {
  services: createRecordsQuery(memoryTransport, service),
};

Type your application against Pick<ReturnType<typeof getStandards>, "services"> and both the real client and the double satisfy it. The status page cookbook ships a working double that emulates filters, sorts and paging.

Next steps