JavaScript and TypeScript SDK
Use the JavaScript and TypeScript SDK to moderate content and manage assets from your server, and to upload from browsers and apps. The server client needs Node.js 22 or later, Bun, Deno or Cloudflare Workers; the app client runs in browsers and React Native. The SDK reference lists every option, method and error code.
Install
npm install calmlensThe same package is also published as @calmlens/sdk, at the same version. These docs import from calmlens; if you install @calmlens/sdk, import from @calmlens/sdk/server, @calmlens/sdk/app and so on instead.
See Versioning and support for what each version change means and where to find the changelog.
The package has two clients:
| Import | Client | Use it |
|---|---|---|
calmlens/server | CalmLensServerClient | On your server, with your API key. Every method, upload tokens and webhook verification. |
calmlens/app | CalmLensAppClient | In browsers and React Native apps, through an upload preset. Uploads only. |
SDK methods take a single options object. CalmLensServerClient refuses to start in a web page or app, where anyone could read the API key.
Moderate content
assets.create() queues processing and returns at once; assets.classify() and text.classify() wait for the decision. Audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.
Create an API key and copy your project ID as described in Authentication.
import { CalmLensServerClient } from "calmlens/server";
const client = new CalmLensServerClient({
apiKey: process.env.CALMLENS_API_KEY!,
projectId: process.env.CALMLENS_PROJECT_ID!,
});
// Text: waits for the decision.
const comment = await client.text.classify({
text: "Great photo!",
externalId: "comment-42",
});
console.log(comment.classification.moderation.status); // "allowed", "limited", "age-restricted", "blocked" or "purged"
// assets.create() queues any upload; resolve it with a webhook or assets.retrieve().
const image = await client.assets.create({
name: "hero.jpg",
content: { data: file, type: "image/jpeg" },
externalId: "post-7",
});
console.log(image.classification.status); // "processing"
// Once an image is allowed, build its URL for an <img>: a public asset needs no API key or signature.
const src = client.cdn.getAssetUrl({ assetId: image.id, resource: "rendered" });The examples use top-level await, which needs an ES module: "type": "module" in package.json, or an .mts file.
See How CalmLens works for what each classification.moderation.status means. Treat a status you don't recognise as not allowed.
Text moderation
text.classify() checks comments, captions, bios and messages. It takes the text, an optional name (text by default), and the same externalId, metadata, tags, folderId and processingOptions as assets.create(). The text is classified as a plaintext-document asset and, by default, not retained afterwards.
const result = await client.text.classify({
text: message.body,
externalId: `message-${message.id}`,
metadata: [{ id: "channel", value: message.channelId }],
});To queue text instead of waiting, call assets.create() with content: { plainText, type: "text/plain" }.
Classification results
All eight parent categories are present in a completed report. Narrow on a category's status before accessing its score; not-evaluated is an explicit unknown result rather than a zero score. Qualifier detail such as graphic violence is nested below its parent.
const violence = comment.classification.moderation.raw?.categories.violence;
if (violence?.status === "evaluated" || violence?.status === "partial") {
console.log(violence.score);
}
const graphicViolence = violence?.qualifiers?.["violence-graphic"];See Reading classification results for the complete schema, evaluation coverage and OCR merge behaviour, and Policies and actions for actions.
Uploads
Binary payloads accept base64, uint8Array, buffer, or data. data supports Blob, File, Response, and ReadableStream. Streamed multipart parts must provide an exact sizeInBytes. In Node.js, openAsBlob(path) from node:fs uploads a file from disk without reading it into memory. Binary uploads have no deadline unless you set uploadTimeoutMs.
For a multipart upload, split the original bytes before base64-encoding each part. Parts are sequential, begin at 1, and only the final part may be smaller than 5 MiB. When you know the file's size, pass totalSizeInBytes next to part when you start the upload with assets.create or assets.classify.
CalmLens saves whether a multipart upload waits for the decision when it starts and applies that when the final part arrives, so later parts can be sent by another process. Pass wait to assets.uploadPart to override it.
Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.
Metadata is a list of {id, value} items, such as metadata: [{ id: "campaign.id", value: "launch-2026" }]. The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.
Upload presets
Pass uploadPresetId to assets.create and assets.classify to apply an upload preset's folder, visibility, file types and size limit. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.uploadTokens.sign({ uploadPresetId }). Signing happens locally with your API key and makes no request.
Browser client
Configure the app client once before using browser upload examples. Presets open to anyone with the preset ID need only uploadPresetId; presets requiring tokens also need a function that fetches a fresh token from your server.
import { CalmLensAppClient } from "calmlens/app";
const client = new CalmLensAppClient({
uploadPresetId: "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P",
token: () => fetchTokenFromYourServer(),
});See the quick start for choosing an upload flow.
Upload widget and asset component
calmlens/react, calmlens/react-native, calmlens/vue, calmlens/svelte and calmlens/elements (custom elements for plain HTML and other libraries) provide a ready-made uploader built on the app client and CalmLensAsset, which shows any asset from its asset URL. See Widgets.
CDN methods
Fetch retained content directly from your backend with client.cdn.serve():
const response = await client.cdn.serve({
assetId,
resource: "original",
});The response contains raw content bytes, not the asset report. Non-2xx responses are returned rather than thrown, so check the status before using the body. For text assets (such as comments sent with text.classify), decode the body as text; for binary content, use the response stream or arrayBuffer(). cdn.serve() returns as soon as headers arrive, so the body streams and long downloads are not cut off by timeoutMs.
The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL on your server with client.cdn.signAssetUrl() (see Signed asset URLs).
Upload with processingOptions: { keepContentAfterProcessing: true } to retain content. The CDN delivers by the current classification.moderation.status, and still requires available content and authorised access. See Delivery eligibility.
client.cdn.getAssetUrl() only builds the URL. Name the asset by assetId or externalId (the ID it was uploaded with). Without resource it returns the asset URL, which every resource is a path beneath; with one, that resource's URL: rendered (the displayable file), preview, original (the uploaded file as it is), placeholder (a small blurred PNG served publicly whatever the asset's visibility or moderation status, except once the asset is purged or its content removed), hls, embed or info. Only rendered and preview take lens and transform. cdn.serve() takes the same options and fetches rendered unless you pass a resource.
client.cdn.signAssetUrl({ assetId, expiresIn?, original? }) signs a private asset's URL and returns { url, expiresAt }. Every resource is a path beneath it; /original only when signed with original: true. The grant binds the project, the asset, original access and the expiry: a resource, lens, transform or viewerClaims you pass is appended as getAssetUrl appends it. client.cdn.getAssetInfo(url) reads an asset URL's display info from its info resource.
viewerClaims: { ageConfirmed: true } lets an age-restricted asset load from its URL, for viewers your app allows; without it, the CDN refuses the asset with 403 viewer/age-confirmation-required, even with a signed URL or your API key. Claims are unsigned, so add them to public and signed URLs alike. In browsers, CalmLensAppClient's cdn.getAssetUrl builds the same public URLs from a projectId, with no API key or request.
Methods
See the SDK reference for each method's options and errors.
| Method | Purpose |
|---|---|
text.classify({ text, ...options }) | Classify text and wait for the decision. |
assets.create(options) | Upload content and queue processing. |
assets.classify(options) | Upload content and wait for the decision where supported. |
assets.uploadPart({ assetId, part, wait? }) | Send the next part of a multipart upload. |
assets.retrieve({ assetId }) | Fetch one asset. |
assets.waitForDecision({ assetId, timeoutMs?, signal? }) | Retrieve an asset until its classification.status is completed or failed. Rejects with sdk/timeout after timeoutMs (default 60000). |
assets.listTimeline({ assetId, cursor?, pageSize? }) / assets.iterateTimeline({ assetId }) | Page through an audio or video asset's findings timeline Preview, in time order. |
assets.list(options) / assets.iterate(options) | List one page of assets, or iterate over every matching asset. |
assets.search({ query, ...options }) | Search assets by keyword or meaning; see Asset search. |
assets.listChildren({ assetId }) / assets.iterateChildren({ assetId }) | List an asset's extracted children. |
assets.update({ assetId, ...changes }) | Update asset fields. |
assets.move({ assetId, folderId }) | Move an asset to a folder, or to the project root with null. |
assets.retry({ assetId }) | Retry an eligible processing failure. |
assets.decide({ assetId, decision, note, confirmPurge? }) | Record a reviewer's decision (allowed, limited, age-restricted, blocked or purged) with a required note. An asset pending moderation can only be blocked or purged, and purging needs confirmPurge: true; see POST /. |
assets.explain({ assetId, rerun? }) | Complete the policy evidence behind a decision (moderation.explanationComplete becomes true; every action stays as decided). With rerun: true, moderate the asset again with the current policy. |
assets.removeContent({ assetId }) | Remove stored content and keep the asset record and report. |
assets.delete({ assetId }) | Delete the asset record and its content. |
assets.batch({ assetIds, operation }) | Delete up to 500 assets ("delete") or remove their stored content ("remove-content") in one queued request; see POST /. |
folders.list(), folders.iterate(), folders.retrieve(), folders.create(), folders.update(), folders.move(), folders.delete() | Manage folders. folders.list() returns a page of root folders by name by default; pass nextCursor as cursor for the next page. Only empty folders can be deleted. |
hashLists.list(), hashLists.iterate(), hashLists.retrieve(), hashLists.create(), hashLists.update(), hashLists.delete() | Manage hash lists that image uploads are compared with. |
hashLists.listEntries(), hashLists.iterateEntries(), hashLists.addEntry(), hashLists.removeEntry() | Manage the hashes in a hash list. |
policies.list(), policies.iterate(), policies.retrieve(), policies.create(), policies.update(), policies.reset(), policies.upgrade(), policies.setAutomaticUpdates(), policies.delete(), policies.retrieveAssigned(), policies.assign() | Manage the organisation's moderation policies, and read or choose the one the project uses; see Policies. |
events.list(options) / events.pages(options) | Read one page of the project event feed, or follow its cursor page by page. |
ensureLens(options) / ensureLenses({ lenses }) | Create or update lenses by identifier. |
lenses.list(), lenses.iterate(), lenses.create(), lenses.retrieve(), lenses.update(), lenses.delete() | Manage the project's lenses by ID; see Lenses. |
cdn.getAssetUrl(options) / cdn.serve(options) | Build a CDN URL, or fetch content. |
cdn.signAssetUrl({ assetId, ...options }) | Sign a private asset's URL. |
cdn.getAssetInfo(url) | Read an asset URL's display info. |
uploadTokens.sign({ uploadPresetId, externalId?, expiresIn? }) | Sign an upload token locally, without a request. |
// Create a folder hierarchy
const marketing = await client.folders.create({ name: "Marketing" });
const launch = await client.folders.create({ name: "Launch", parentId: marketing.id });
// Move an asset into a folder or back to root
await client.assets.move({ assetId: asset.id, folderId: launch.id });
await client.assets.move({ assetId: asset.id, folderId: null });
// Reorganise or delete folders
await client.folders.move({ folderId: launch.id, parentId: null });
await client.folders.update({ folderId: launch.id, name: "Public Launch" });
await client.folders.delete({ folderId: launch.id });Pagination
Every list returns a cursor page: items, hasMore and nextCursor. Pass nextCursor as cursor, with the same filters, to fetch the next page, and set its size with pageSize. Each list has an iterator that fetches pages as you go and yields the items: assets.iterate, assets.iterateChildren, assets.iterateTimeline, folders.iterate, hashLists.iterate, hashLists.iterateEntries, policies.iterate and lenses.iterate. events.pages yields the feed page by page. Use events.pages to read pending events and save the cursor. See Reading the feed for cursor semantics and Feed and webhook shape for response shapes:
let { nextCursor: cursor } = await client.events.list(); // no events yet: a cursor for now
// later, and on every poll: pages() follows the cursor until no more events are waiting
for await (const page of client.events.pages({ cursor, pageSize: 100 })) {
for (const event of page.items) console.log(event.type, event.facts);
cursor = page.nextCursor;
}Errors and retries
Every failure is a CalmLensError with a stable code, plus status, requestId (the X-Request-Id header), headers and retryAfter when the API responded. CALMLENS_ERROR_CODES lists the codes, error.isNotFound() and error.isRetryable() classify errors, and CalmLensError.isCalmLensError(error) works across copies of the SDK.
| Failure | What the SDK does | What you do |
|---|---|---|
Network failure (sdk/transport-error) or timeout (sdk/timeout) | Retries reads and uploads (assets.create, assets.classify, text.classify, assets.uploadPart) up to maxRetries times (default 2; 0 turns retries off), waiting from 0.5 seconds, doubling up to 8 seconds, with jitter | Once retries run out, retry later: isRetryable() is true, including for waitForDecision's timeout |
429, 500, 502, 503, 504 or 409 idempotency/request-in-progress | Retries the same requests, waiting for Retry-After when the API sends one | A Retry-After over 60 seconds is thrown to you instead: wait, then retry |
Cancellation through your signal (sdk/cancelled) | Stops at once; never retried | Nothing; isRetryable() is false |
Failure of another write, such as assets.update or assets.delete | Not retried | Retry only when repeating the change is safe |
Upload from a ReadableStream or Response | Sent once, because the body can't be replayed | Upload again with a new stream |
| Upload retried from another process | Each call sends a new Idempotency-Key, reused for its own retries | Pass your own idempotencyKey to assets.create, assets.classify, text.classify or assets.uploadPart |
| Redirect | Not followed, so your API key never reaches another origin; throws sdk/http-error | Check baseUrl and cdnBaseUrl |
| Invalid arguments or client options | Throws sdk/invalid-argument or sdk/invalid-config before sending anything | Fix the call or the configuration |
cdn.serve() failure | Retries the same failures. Once retries run out, returns the last error response instead of throwing; a network failure or timeout still throws | Check the response status |
| Option | Default | Limits |
|---|---|---|
timeoutMs | 120 seconds | Each attempt of an API call, including text uploads; cdn.serve() only until headers arrive |
uploadTimeoutMs | None | Each attempt of a binary upload, so large files are not cut off |
maxResponseBytes | 32 MiB | The API response body the client reads |
Webhooks
Verify the exact raw request body, then parse it, with parseWebhookEvent({ payload, headers, secret }). Pass the body as a string, Uint8Array, Buffer or ArrayBuffer, never parsed JSON: a body that was parsed and serialised again rarely has the same bytes, so the signature would not match.
import { CalmLensError, isTestWebhookEvent, parseWebhookEvent } from "calmlens/server";
export async function POST(request: Request): Promise<Response> {
let event;
try {
event = await parseWebhookEvent({
payload: await request.text(),
headers: request.headers,
secret: process.env.CALMLENS_WEBHOOK_SECRET!,
});
} catch (error) {
const forged = error instanceof CalmLensError && error.code === "sdk/invalid-webhook-signature";
return new Response(null, { status: forged ? 401 : 400 });
}
if (!isTestWebhookEvent(event)) {
// Queue the work, keyed by event.id, then respond quickly.
}
return new Response(null, { status: 204 });
}Pass the raw body your framework received:
| Framework | Raw body | Headers |
|---|---|---|
| Fetch API (Next.js route handlers, Workers, Bun, Deno) | await request.text() | request.headers |
| Hono | await c.req.text() | c.req.raw.headers |
| Express | req.body, with express.raw({ type: "application/json" }) on the route | req.headers |
parseWebhookEvent reads the x-calmlens-signature and x-calmlens-timestamp headers by name in any case, joining a repeated header with ,, or takes them as signature and timestamp. Deliveries timestamped more than 5 minutes from the current time are rejected; toleranceSeconds changes that. It throws sdk/invalid-webhook-signature for a missing, wrong or stale signature, and sdk/invalid-webhook-payload for a verified body that isn't a CalmLens event. verifyWebhookSignature takes the same options and returns a boolean instead.
Event types and fields added after your SDK version are returned as they are, so keep a default branch when you switch on event.type. getEventFact(event, key) from calmlens/server returns one fact's value, or undefined when the event doesn't carry it, and getEventFacts(event) returns every fact's value by key, such as { "flagged-categories": ["hate"] }; a key repeated in the event keeps its first value. isTestWebhookEvent(event) is true for a test send from the portal or the CLI. Deliveries also carry x-calmlens-delivery (WEBHOOK_DELIVERY_HEADER), which stays the same across a delivery's retries; a redelivery gets a new one, so deduplicate on the event id. See Webhooks.
Command-line tool
See Local development to install the CLI, forward signed events and trigger test uploads.
Testing
Use MockCalmLensServerClient and MockCalmLensAppClient from calmlens/testing for offline tests. See JavaScript testing.