LumiBaseDocs

LumiBase JavaScript SDK

Package: @lumibase/sdk

A composable, typed REST client for LumiBase, plus realtime subscriptions and TypeScript type generation.

Installation

bash
npm install @lumibase/sdk
# or
pnpm add @lumibase/sdk

The shape of this SDK

Two things to know before the examples, because they differ from most CMS clients:

  1. The client is a transport, not a façade. createLumiClient gives you rawRequest, request, and with. Operations are separate command functions you pass to request — a command is a function that takes the client and returns a promise. This keeps the bundle tree-shakeable: you import only the commands you use.
  2. There is no login(). The client takes a token you already hold. Obtain it through your auth flow (Logto, or dev:<logtoId> in dev mode) and pass it in. The client can silently refresh it if you also supply a refreshToken.

A convenience plugin, legacyRest(), bundles the whole REST surface into grouped namespaces if you would rather not import commands individually.

Quick start

typescript
import { createLumiClient, readItems } from '@lumibase/sdk'

const client = createLumiClient({
  url: 'https://api.mysite.lumibase.dev',
  siteId: 'site_abc123',
  token: process.env.LUMIBASE_TOKEN!,
})

// Commands are curried: build one, hand it to request().
const articles = await client.request(
  readItems('articles', {
    filter: { status: { _eq: 'published' } },
    sort: ['-created_at'],
    limit: 10,
  }),
)

Client configuration

createLumiClient(opts: LumiClientOptions) (packages/sdk/src/client.ts):

OptionTypeRequiredDescription
urlstringYesAPI base URL, e.g. https://api.lumibase.dev
tokenstringYesBearer token (Logto access token, or dev:<logtoId> in dev mode)
siteIdstringYesActive tenant id; sent as X-Lumi-Site
fetchertypeof fetchNoOverride fetch (Node/Workers polyfills); defaults to globalThis.fetch
headersRecord<string, string>NoExtra headers on every request
onUnauthorized() => voidNoFires once on a 401, before the LumiError throws — clear the stale token and route to login. With auto-refresh on, it fires only after a refresh attempt also fails
refreshTokenstringNoRotating refresh token. A 401 then triggers one POST /api/v1/auth/refresh and retries the original request once
onTokensRefreshed(tokens) => voidNoCalled after a successful silent refresh with the rotated pair, so the host can persist them — the old refresh token is now revoked

The returned LumiClient:

MemberDescription
rawRequest<T>(path, init?)One HTTP call; returns { data, meta? }
request<Output>(command)Runs a command function against this client
with(plugin)Returns the client extended by a plugin's members
url, token, siteId, fetcherThe resolved configuration

Refresh is single-flight: a burst of parallel 401s triggers one refresh, not one per request.


Grouped namespaces via legacyRest()

legacyRest() is a plugin. Attach it with with() and you get the REST surface as namespaces — convenient for application code and for Studio:

typescript
import { createLumiClient, legacyRest } from '@lumibase/sdk'

const client = createLumiClient({ url, siteId, token }).with(legacyRest())

await client.schema.collections.list()
await client.items('articles').list({ limit: 20 })
await client.me.getPreferences()

Namespaces exposed: schema (collections, fields, relations), items, roles, policies, access, apiKeys, shares, me, permissions, presets, translations, tm, settings, uploads, site, domains, users, teams, folders, files, webhooks, activity, extensions, deployments, realtime.


Items

The item envelope

An item is not a flat record. Field values live under data; workflow and scheduling columns sit beside it:

typescript
{ data: { title: 'Hello' }, status: 'draft', sort: 1, publishAt: null, unpublishAt: null }

List

typescript
const res = await client.items('articles').list({
  fields: ['id', 'title', 'status'],
  filter: { status: { _eq: 'published' } },
  sort: ['-published_at'],
  limit: 20,
  offset: 0,
  status: 'published',
})

Supported list params are fields, filter, sort, limit, offset, and status. Note there is no page param — paginate with limit/offset — and no aggregate/groupBy on this endpoint. Full-text search is the separate search command.

Detail

typescript
const article = await client.items('articles').detail('art_abc123', ['id', 'title', 'content'])

Create

typescript
const created = await client.items('articles').create({
  data: { title: 'New Article', author: 'usr_abc123' },
  status: 'draft',
})

Update (patch) and replace

typescript
await client.items('articles').patch('art_abc123', {
  data: { title: 'Updated title' },
  status: 'published',
  publishAt: new Date().toISOString(),
})

// PUT — replaces `data` wholesale
await client.items('articles').replace('art_abc123', { data: { title: 'Only field left' } })

Delete and bulk

typescript
await client.items('articles').delete('art_abc123')

// op is 'create' | 'update' | 'delete'; see docs/en/features/data-import.md
await client.items('articles').bulk('create', [{ title: 'A' }, { title: 'B' }])

Export

typescript
// Streams CSV or JSON; see docs/en/features/data-export.md
const res = await client.items('articles').export({
  format: 'csv',
  fields: ['title', 'slug'],
  locales: ['en', 'vi'],
  relations: 'slug',
  filter: { status: { _eq: 'published' } },
})
const csv = await res.text()

Import

typescript
// Upload a CSV/JSON export as a background job; see docs/en/features/data-import.md
const { data: job } = await client.imports.create('articles', file, { mode: 'upsert' })
let current = job
while (!['succeeded', 'failed', 'cancelled', 'timed_out'].includes(current.status)) {
  await new Promise((r) => setTimeout(r, 2000))
  current = (await client.imports.get(job.id)).data
}
if (current.failedRows > 0) console.table((await client.imports.errors(job.id)).data.errors)

Revisions and pins

typescript
const revisions = await client.items('articles').listRevisions('art_abc123')
await client.items('articles').revertRevision('art_abc123', revisions.data[0].id)

// Law Zero pins — fields a human edit locked against agent writes
await client.items('articles').listPins('art_abc123')

Files

typescript
await client.files.list()
await client.files.create({ /* file metadata */ })
await client.files.update('fil_abc123', { title: 'My Image' })
await client.files.delete('fil_abc123')

Binary upload goes through the uploads namespace, which is the presigned flow — the CMS does not accept a file body on /files.

For a transform URL, use the mediaUrl command rather than building the query string yourself.


Agent Harness API

The governance lifecycle used by AI runs and generated app artifacts:

typescript
import {
  generateAgentApp,
  listAgentRuns,
  publishAgentArtifact,
  rollbackAgentArtifact,
} from '@lumibase/sdk/rest'

const result = await generateAgentApp({
  collections: ['products', 'orders', 'customers'],
  targetApp: 'storefront',
  approvalPolicy: 'before_commit',
  budget: { maxToolCalls: 20 },
})(client)

// result.artifacts contains page_spec, component_spec, seed_data, api_spec
const runs = await listAgentRuns()(client)
const published = await publishAgentArtifact(result.artifacts[0].id)(client)
await rollbackAgentArtifact(published.id, 'revert generated storefront')(client)

Publishing is idempotent. Schema and migration artifacts require a passing evaluation unless the caller supplies an override reason.

Other agent commands: createAgentGoal, listAgentGoals, retryAgentRun, listAgentTools, listAgentApprovals, decideAgentApproval, createAgentArtifact, listAgentArtifacts, evaluateAgentArtifact, readAgentMemoryContext, writeAgentMemory.


Decisions

decide calls POST /api/v1/ai/decisions: typed noul / choice / score questions answered with probabilities by TypeSafe Jev or the configured equivalent. Provider keys stay on the CMS; the client only sends its usual bearer and X-Lumi-Site headers, so never put a TypeSafe or OpenRouter key in browser code. Call decide and the review commands from Studio or from a server with a secret API key: a publishable API key (lbk_pub_…) or a frontend session gets 403 FORBIDDEN, even when its role grants ai:decide.

typescript
import { decide, LumiError } from '@lumibase/sdk'

const controller = new AbortController()
try {
  const result = await client.request(
    decide(
      {
        state: { title: 'Summer sale', body: 'Buy now!!!' },
        questions: {
          spam: {
            type: 'noul',
            instructions: 'Is this post spam?',
            criteria: { true: 'spam', false: 'legitimate' },
          },
          topic: {
            type: 'choice',
            instructions: 'Pick the topic',
            criteria: { promo: 'Promotion', news: null },
          },
        },
      },
      { signal: controller.signal },
    ),
  )
  result.answers.spam // { type: 'noul', noul: 0.12 }
} catch (err) {
  if (err instanceof LumiError && err.body.errors[0]?.code === 'DECISION_NOT_CONFIGURED') {
    // the CMS has no DECISION_PROVIDER set
  }
}

calibrated is false when the CMS answers with DECISION_PROVIDER=llm. Error codes are typed as DecisionErrorCode; see the API spec for limits and statuses.

Draft review

Draft review runs a versioned review profile, stored on the CMS, against a saved item or an unsaved draft. These commands call the /api/v1/ai/review-profiles and /api/v1/ai/reviews endpoints:

  • listReviewProfiles({ collection? }) and getReviewProfile(key, { version? }) read profiles. Profiles are created by admins.
  • reviewDraft(request) reviews an item (itemId) or a draft (snapshot).
  • getReview(id) and listReviews({ collection, itemId }) read runs, including stale and staleReason.
  • submitReviewFeedback(runId, { entries }) records accept, edit or reject for each question.
  • reviewContentHash(values) computes the sha256:<hex> content hash of a draft the way the CMS does. It uses WebCrypto and makes no request.

Every command accepts { signal } as its last argument. A review only suggests: none of these calls writes to the item.

typescript
import {
  decisionErrorCode,
  listReviewProfiles,
  LumiError,
  reviewContentHash,
  reviewDraft,
  submitReviewFeedback,
} from '@lumibase/sdk'

const [profile] = await client.request(listReviewProfiles({ collection: 'posts' }))
const draft = { title: 'Summer sale', body: 'Buy now!!!' }
try {
  const hash = await reviewContentHash(draft) // 'sha256:<64 hex>', same as the CMS computes
  const run = await client.request(
    reviewDraft(
      {
        profile: profile.key,
        profileVersion: profile.version,
        collection: 'posts',
        snapshot: draft,
        // changes with the draft and the profile version; at most 116 chars
        idempotencyKey: `${profile.key}@${profile.version}:${hash.slice(7, 47)}`,
      },
      { signal: controller.signal },
    ),
  )
  run.status     // 'success' | 'abstained' ("not enough information") | …
  run.calibrated // false when the probabilities are self-reported by an LLM
  run.usage      // { inputTokens: 120, outputTokens: null } — null means unknown, not zero

  // Later, when the editor accepts: hash the draft as it is at that moment.
  await client.request(
    submitReviewFeedback(run.id, {
      entries: [{ questionKey: 'category', verdict: 'accept' }],
      contentHash: await reviewContentHash(currentDraft),
    }),
  )
} catch (err) {
  const code = decisionErrorCode(err) // typed DecisionErrorCode, or null
  if (code === 'DECISION_QUOTA_EXCEEDED') {
    console.warn(`retry in ${(err as LumiError).retryAfter}s`)
  } else if (code === 'REVIEW_STALE') {
    // the draft changed since the review: review the current draft (new hash, new key),
    // or send acknowledgeStale: true
  }
}

The CMS cannot re-read an unsaved draft. For a snapshot run it detects a changed draft only by comparing the contentHash you send on feedback with the hash it reviewed. Compute that value with reviewContentHash over the same fields you sent as snapshot, at the moment of the verdict. Sending run.contentHash back always matches, so it turns the check off. Item runs need no hash: the CMS re-reads the item and reports stale.

Sending the same idempotencyKey again returns the stored run without calling the provider a second time. The CMS looks the run up by site, caller and key only, and does not compare the content. A key that stays the same after the draft changes therefore returns the review of the old draft. Build the key from the content hash and the profile version, as above, and never use a fixed id. For an item run, also change the key once getReview reports stale. Keys are 8–128 characters. Errors use the same codes as decide. These include 403 DECISION_DISABLED, 504 DECISION_TIMEOUT, and 429 with retryAfter, plus the REVIEW_* codes: 409 REVIEW_STALE, 422 REVIEW_FIELD_NOT_ALLOWED, and 404 REVIEW_PROFILE_NOT_FOUND / REVIEW_RUN_NOT_FOUND. decisionErrorCode(err) returns null for an aborted request, a network failure, or a code this SDK version does not know. In those cases, read err.body. A complete example that compiles against the public entry is in packages/sdk/examples/draft-review.ts.


Change Feed

typescript
import { readCdcEvents, ackCdcSubscription } from '@lumibase/sdk'

let cursor: string | undefined
for (;;) {
  const { data, meta } = await client.request(readCdcEvents({ collections: ['posts'], cursor }))
  for (const event of data) await handle(event) // dedupe on event.id
  cursor = (meta as { nextCursor?: string }).nextCursor ?? cursor
  if (!(meta as { hasMore?: boolean }).hasMore) break
}
await client.request(ackCdcSubscription(subId, cursor!))

See Change Feed for the delivery semantics.


Realtime

Realtime is a RealtimeClient, created through the realtime namespace with a token for the WebSocket handshake:

typescript
const rt = client.realtime.create(process.env.LUMIBASE_TOKEN!, {
  userId: 'usr_abc123',
  initialBackoffMs: 500,
  maxBackoffMs: 30_000,
})

RealtimeClient and AudienceClient are also exported directly from @lumibase/sdk if you want to construct one without the plugin.


TypeScript types

The client is generic over your schema, so generated types flow into every call:

typescript
import { createLumiClient } from '@lumibase/sdk'
import type { Collections } from './lumibase-types'

const client = createLumiClient<Collections>({ url, siteId, token })

See the TypeGen reference for how to generate lumibase-types.ts.


Error handling

Every non-2xx response throws LumiError:

typescript
import { LumiError } from '@lumibase/sdk'

try {
  await client.items('articles').create({ data: { title: '' } })
} catch (error) {
  if (error instanceof LumiError) {
    console.error(error.status)            // 400
    console.error(error.body.errors[0].code)    // 'VALIDATION_FAILED'
    console.error(error.body.errors[0].message) // 'title is required'
    console.error(error.body.errors[0].path)    // optional field path
  }
}

A non-JSON or bodyless failure is still normalized into the same envelope, with code HTTP_ERROR.

error.retryAfter holds the Retry-After header in seconds, for example on a 429 site budget. It is null when the response did not send one.

Last modified: 15/11/2026