Skip to content
undertext developers
Skip to Content
undertext developers

Node SDK

The @undertext/sdk package for calling the Undertext API from your server, with typed methods for every endpoint.

@undertext/sdk wraps the REST API for Node.js servers. Every method maps to one endpoint, takes the same fields and returns the same objects, so the REST reference describes the SDK too. Use the client only on your server: it holds your secret key. Its roles and people work in your pages too.

Install

npm install @undertext/sdk

It needs Node.js 20 or later and has no dependencies.

Create a client

undertext.ts
import Undertext from "@undertext/sdk";

export const undertext = new Undertext(process.env.UNDERTEXT_SECRET_KEY);

The key decides the platform: everything the client does is on the platform it belongs to. undertext.platform.retrieve() says which.

The second argument takes options:

OptionDefaultWhat it does
maxRetries2How many times a request answered with 429 or 5xx is tried again.
baseUrlhttps://api.undertext.sh/v1Where requests go. Change it only for a proxy, or an Undertext you run yourself.
const undertext = new Undertext(process.env.UNDERTEXT_SECRET_KEY, { maxRetries: 4 });

Field names

The SDK uses the API's own field names, in snake_case, in both directions. What you send to undertext.documents.update is the body of PATCH /v1/documents/:id, and what comes back is the document object as the REST reference shows it.

await undertext.documents.update("doc_8Hq2Lm4R", { link_access: "suggest" });

Methods

Each resource is a property of the client. Path parameters come first, then the body or query as one object.

Users

See Users.

MethodEndpoint
undertext.users.upsert(externalId, params)PUT /v1/users/external/:external_id
undertext.users.retrieve(userId)GET /v1/users/:user_id
undertext.users.retrieveByExternalId(externalId)GET /v1/users/external/:external_id
undertext.users.update(userId, params)PATCH /v1/users/:user_id
undertext.users.delete(userId)DELETE /v1/users/:user_id
undertext.users.merge(userId, { into })POST /v1/users/:user_id/merge
undertext.users.listDocuments(userId, { limit?, ids? })GET /v1/users/:user_id/documents
undertext.users.listTrash(userId)GET /v1/users/:user_id/documents?trashed=true
undertext.users.emptyTrash(userId)DELETE /v1/users/:user_id/trash
undertext.users.deleteFromTrash(userId, documentId)DELETE /v1/users/:user_id/trash/:document_id
undertext.users.listAgents(userId, { document? })GET /v1/users/:user_id/agents
undertext.users.endSessions(userId, { group? })DELETE /v1/users/:user_id/sessions
undertext.users.retrieveCheckins(userId)GET /v1/users/:user_id/checkins
undertext.documents.retrieveCheckins(documentId, userId)GET /v1/documents/:document_id/checkins/:user_id
undertext.documents.updateCheckins(documentId, userId, { enabled })PUT /v1/documents/:document_id/checkins/:user_id

Documents

See Documents.

MethodEndpoint
undertext.documents.create(params)POST /v1/documents
undertext.documents.retrieve(documentId)GET /v1/documents/:id
undertext.documents.update(documentId, params)PATCH /v1/documents/:id
undertext.documents.trash(documentId, { user? })POST /v1/documents/:id/trash
undertext.documents.restore(documentId, { user? })POST /v1/documents/:id/restore
undertext.documents.delete(documentId)DELETE /v1/documents/:id
undertext.documents.export(documentId, { format })GET /v1/documents/:id/export
undertext.documents.provenance(documentId)GET /v1/documents/:id/provenance

export resolves to the Markdown as a string.

Members

See Members.

MethodEndpoint
undertext.members.list(documentId)GET /v1/documents/:id/members
undertext.members.put(documentId, userId, { role })PUT /v1/documents/:id/members/:user_id
undertext.members.delete(documentId, userId)DELETE /v1/documents/:id/members/:user_id

Sessions

See Sessions.

MethodEndpoint
undertext.sessions.create({ user, document, via?, group? })POST /v1/sessions
undertext.sessions.create({ user, purpose: "presence", group? })POST /v1/sessions
undertext.sessions.create({ user, purpose: "seal", email?, group? })POST /v1/sessions

Agents

See Agents.

MethodEndpoint
undertext.agents.retrieve(agentId)GET /v1/agents/:agent_id
undertext.agents.update(agentId, { access })PATCH /v1/agents/:agent_id
undertext.agents.listDocuments(agentId)GET /v1/agents/:agent_id/documents
undertext.agents.putDocument(agentId, documentId, { role })PUT /v1/agents/:agent_id/documents/:document_id
undertext.agents.deleteDocument(agentId, documentId)DELETE /v1/agents/:agent_id/documents/:document_id
undertext.agents.revoke(agentId)DELETE /v1/agents/:agent_id

Agent requests

See Agent requests.

MethodEndpoint
undertext.agentRequests.retrieve(requestId)GET /v1/agent-requests/:id
undertext.agentRequests.approve(requestId, params)POST /v1/agent-requests/:id/approve
undertext.agentRequests.deny(requestId)POST /v1/agent-requests/:id/deny

Seals

See Seals.

MethodEndpoint
undertext.seals.create(documentId, { user })POST /v1/documents/:id/seals
undertext.seals.list(documentId)GET /v1/documents/:id/seals
undertext.seals.retrieve(code)GET /v1/seals/:code
undertext.seals.withdraw(code)DELETE /v1/seals/:code

Webhook endpoints

See Webhook endpoints.

MethodEndpoint
undertext.webhookEndpoints.create({ url, events })POST /v1/webhook-endpoints
undertext.webhookEndpoints.list()GET /v1/webhook-endpoints
undertext.webhookEndpoints.rollSecret(endpointId)POST /v1/webhook-endpoints/:id/roll-secret
undertext.webhookEndpoints.delete(endpointId)DELETE /v1/webhook-endpoints/:id

Platform

See Platform.

MethodEndpoint
undertext.platform.retrieve()GET /v1/platform
undertext.platform.update(params)PATCH /v1/platform
undertext.platform.verifyDomain()POST /v1/platform/verify-domain
undertext.platform.setTools({ url, secret, tools, instructions? })PUT /v1/platform/tools
undertext.platform.stats()GET /v1/platform/stats

Lists and paging

Methods that list things return a page you can either await or iterate. Awaiting it gives you one page, as the API returns it:

const page = await undertext.users.listDocuments("usr_5Kq2Lm8R", { limit: 20 });
page.data; // up to 20 documents, newest edited first
page.next; // a cursor, or null on the last page

Iterating it with for await fetches the following pages as you go, so you see every item once:

for await (const doc of undertext.users.listDocuments("usr_5Kq2Lm8R")) {
  console.log(doc.title);
}

Stop the loop with break whenever you have what you need; no further pages are fetched.

Errors

A request the API refuses throws an UndertextError. It carries the API's error fields and the HTTP status:

PropertyExampleWhat it is
type"permission"The kind of error, as listed in Errors.
code"no_access"A specific reason you can branch on.
message"usr_9Tb3Wc1X can't open doc_8Hq2Lm4R."A sentence for your logs, not for your users.
param"role"The field at fault, for invalid_request errors.
status403The HTTP status.
import Undertext, { UndertextError } from "@undertext/sdk";

try {
  const session = await undertext.sessions.create({ user: "usr_9Tb3Wc1X", document: "doc_8Hq2Lm4R" });
} catch (error) {
  if (error instanceof UndertextError && error.code === "no_access") {
    // Grace isn't a member, and the document's link access doesn't let Grace in.
  } else {
    throw error;
  }
}

Network failures throw the error fetch threw.

Retries

The client retries a request that was rate limited (429), and one other than a POST that failed on our side (500 and above), maxRetries times. It waits longer before each try, and as long as Retry-After asks when the API sends it. A POST that failed may have been carried out, so it isn't sent again: see Idempotency.

Every id the client puts in a path is encoded as one segment, and an id of . or .. throws a TypeError: an id that came from your users can't name another endpoint.

Webhooks

undertext.webhooks.verify checks a delivery's signature and returns the event, or throws an Error. Give it the body exactly as it arrived, before any JSON parsing:

webhooks.ts
import express from "express";
import { undertext } from "./undertext";

const app = express();

app.post("/undertext/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  const event = undertext.webhooks.verify(req.body, req.get("Undertext-Signature") ?? "", process.env.UNDERTEXT_WEBHOOK_SECRET!);
  if (event.type === "mention.created") notifyMention(event.data);
  res.sendStatus(204);
});

It also refuses a delivery whose timestamp is more than five minutes from your clock. Webhook events lists every event and its payload.

Calls to your own agent tools are signed the same way. verifySignature(rawBody, header, secret) checks one and says whether it matched:

import { verifySignature } from "@undertext/sdk";

if (!verifySignature(rawBody, req.get("Undertext-Signature"), process.env.ACME_TOOLS_SECRET!)) return res.sendStatus(401);

Roles

@undertext/sdk/roles holds the roles and link access and how they rank, for your sharing screens and your own checks. It holds no key and needs nothing from Node, so your pages can import it too; the package's root exports the same names.

import { atLeast, LINK_ACCESS, ROLES, writes } from "@undertext/sdk/roles";

atLeast("editor", "suggester"); // true: an editor may do all a suggester may
writes("suggester"); // "suggest": a suggester changes the document only by suggesting
NameWhat it is
ROLESowner, editor, suggester and viewer, from the most a member may do to the least. Type Role.
LINK_ACCESSrestricted, view, suggest and edit: what a document's link gives anyone who opens it. Type LinkAccess.
AGENT_ROLESThe roles a person may give their agents: all but owner. Type AgentRole.
atLeast(role, needed)Whether role may do all that needed may. false for null, no role.
writes(role)How role changes a document: "edit", "suggest", or null for not at all.

Undertext decides what each person may do in a document; these only mirror its rules.

People

@undertext/sdk/people shows people and agents as the editor does, for your own lists: a bell, mentions, sharing. It also checks a person's name as Undertext takes it. Like the roles, it holds no key, so your pages can import it too; the package's root exports the same names.

import { colorOf, credit } from "@undertext/sdk/people";

const { author } = event.data.message; // { type: "agent", agent: "agt_…", user: "usr_…", name: "Codex" }
colorOf(author); // the agent's own colour
credit({ name: author.name, person: { name: "Ada" } }); // "Codex (Ada's agent)"
if (event.actor.type !== "platform") colorOf(event.actor); // an event's actor may be your platform itself
NameWhat it is
colorOf(actor)A person's colour, from { user }, or an agent's own, from { agent }: the shapes webhooks name people and agents by (not your platform, { type: "platform" }). A document shows someone in another colour when someone else there already has theirs.
COLORSThe colours colorOf picks from.
credit(actor)A name, and whose agent it is: "Codex (Ada's agent)". Takes { name, person? }.
whose(actor)"Ada's agent" for an agent with a person, or null.
NO_NAME"Someone": what anyone known by no name is called.
NAME_CHARS48: how long a person's name may be.
validName(name, clip?)A person's name as users.upsert takes it: trimmed and in NFC, or null when it's empty, longer than NAME_CHARS (48) or holds control or invisible characters. With clip, a long name is shortened instead.

TypeScript

The package ships its own types. Each object the API returns has a type of the same name:

import type { Agent, Document, Event, Member, Platform, Provenance, Role, Seal, Session, User } from "@undertext/sdk";

Event<T> is the webhook envelope, with data typed as T; pass the payload type of the events you handle:

const event = undertext.webhooks.verify<{ seal: Seal }>(rawBody, header, secret);
if (event.type === "seal.created") await saveSeal(event.data.seal.code, event.data.seal.url);

On this page