SDK reference
The SDK is the JavaScript library your page uses to sign the user in and to read and write their data. Its package is @phibac/sdk. This page lists everything it exports, with each method's signature as written in the SDK's source, what it does, what it returns, when it fails and what it does offline. The guides show the same calls in complete apps: start with Build your first app.
Exports
The package exports two values and five types:
| Export | Kind | What it is |
|---|---|---|
connect |
function | Signs the user in and returns their Backend. |
PbError |
class | Every error the SDK gives your app. |
Backend |
type | The signed-in user's data, for your app. |
Collection |
type | One collection: create, read, change, delete and query its records. |
Query |
type | A query on a collection, built with where, orderBy and limit. |
PbRecord |
type | One record as your app gets it. |
QueuedOp |
type | A change waiting in the write queue, as onConflict reports it. |
import { connect, PbError, type Backend, type Collection, type Query, type PbRecord, type QueuedOp } from "@phibac/sdk";
// The types are TypeScript only; connect and PbError exist at run time.
const exported: [typeof connect, typeof PbError] = [connect, PbError];
type All = [Backend, Collection<{ text: string }>, Query<{ text: string }>, PbRecord<{ text: string }>, QueuedOp];
console.log(exported.length, {} as All | undefined);
A few words used on this page:
- Rejects with means the returned promise fails with a
PbErrorthat has thatcode. Throws means the call itself throws one, before returning anything. Every code is explained in Errors and how to fix them. - The browser's copy is the copy of the user's records the SDK keeps in the browser for your app, so reads are instant and work offline.
- The write queue is the list of changes made on this device that the server does not have yet. Offline writes and sync explains it.
connect
connect(opts: { app: string; baseUrl?: string; schemaMajors?: Record<string, number> }): Promise<Backend>
Signs the user in to your app, if they are not signed in already in this browser, and resolves with their Backend.
Options:
app(required): your app's ID, which starts withapp_.npx phibac initprints it and writes it intopb.config.ts.baseUrl: the server's address. The default ishttp://localhost:8787, the local servernpx phibac devruns; this server's address is https://phibac.com. A slash at the end is ignored.schemaMajors: for each collection, the major version your app writes, as{ "com.example.notes.note": 1 }. Pass theSCHEMA_MAJORSobject from the filenpx phibac generatewrites. Without it, a new record is written with the latest published major version (seebackend.collection()).
What it does:
- When no sign-in is stored in this browser for this app and server, it opens a sign-in popup on the server. There the user signs in if needed, with their passkey or their password, and approves your app the first time. The popup closes and the promise resolves. Sign users in shows it step by step.
- Browsers allow a popup only as a direct result of a click or key press.
connect()opens a blank window at once for that reason, before it knows whether a sign-in is stored, and closes it again when one is. Call it first in a click or key handler, before anyawait. - Called outside a click or key press, it does not try to open a window in browsers that report whether a click or key press is in progress, and other browsers usually block the window it tries to open. A stored sign-in still works; without one, when no window opened, it rejects with
popup_blocked. In a browser of the second kind where the user has allowed popups for your site, the window opens and sign-in goes ahead. - When a sign-in is stored, it needs no network and resolves at once, so your app can start offline.
Rejects with:
popup_blocked: no stored sign-in, and the browser did not open the popup.sign_in_cancelled: the user closed the popup before sign-in finished, including after it showed an error page (such as "This app is not registered.").access_denied: the user pressed Cancel on the page that asks to connect your app.network: the server could not be reached while signing in.- A server code from the last step of sign-in, such as
unauthorizedorapp_suspended.
Backend
export interface Backend {
collection<T>(name: string, opts?: { versions?: number[]; schemaMajor?: number }): Collection<T>;
files: { upload(blob: Blob, opts: { collection: string; rkey?: string }): Promise<string>; url(fileId: string): Promise<string>;
delete(fileId: string): Promise<void> };
onConflict(cb: (e: { op: QueuedOp; error: PbError; localData: unknown }) => void): () => void;
status(): { online: boolean; pending: number; problem?: PbError };
signOut(): Promise<void>;
}
The object connect() resolves with: one signed-in user's data, for your app, on one server. While it exists, the SDK sends the write queue whenever the device is online and keeps the collections your page subscribes to up to date. After signOut() it cannot be used.
backend.collection()
collection<T>(name: string, opts?: { versions?: number[]; schemaMajor?: number }): Collection<T>
Returns the Collection named name, such as "com.example.notes.note" or "sandbox.settings". T is the type of a record's data, usually a type from the file npx phibac generate writes. Nothing is sent to the server.
versions: the major versions your code reads. It is required for another app's collection: list the versions your code understands, such as{ versions: [1] }. Queries then return only records written with those versions, and the SDK leaves records of other versions out of the browser's copy. Without it, your app reads every version of its own collection.schemaMajor: the major version this handle writes. The default is the collection's entry inconnect({ schemaMajors }). When neither is given, a new record is written with the latest published major version and an update keeps the record's own version.
Throws unauthorized after signOut().
backend.files.upload()
upload(blob: Blob, opts: { collection: string; rkey?: string }): Promise<string>
Stores blob (a Blob, or a File from an <input type="file">) as a file of the collection opts.collection, and resolves with the file's ID, which starts with f_. Keep the ID in a fileRef field of a record. opts.rkey may name the record the file belongs to; when given, it must be a record key (a UUIDv7) and is stored with the file. The file's type is taken from blob.type, or application/octet-stream when that is empty.
The collection must be one your app owns or one of its own sandbox. collections. Uploads are never queued.
Rejects with:
network: the device is offline (checked before anything is sent), or the upload failed on the way.invalid_request:blobis not aBlob,rkeyis not a record key, or the type is not a plain media type such asimage/png(a type with parameters, such astext/plain;charset=utf-8, is refused).payload_too_large: the file is over 100 MB (see Limits).forbidden: the collection belongs to another app.not_found: the collection has no published schema.
backend.files.url()
url(fileId: string): Promise<string>
Resolves with an address the browser can load the file from, for example as an image's src. The address works for 5 minutes; call url() again each time you show the file in a new place. Your app can get the address of a file of its own collections, and of another app's collection once the user has allowed your app to read it.
Rejects with not_found (the ID is wrong, the upload did not finish or the file was deleted), consent_required (the file belongs to another app's collection your app may not read) and network (the server cannot be reached).
backend.files.delete()
delete(fileId: string): Promise<void>
Deletes the file at once and frees its storage. Only the app that owns the file's collection can delete it. It works also when the user's account is full or read-only. Records whose fields hold the file's ID are not changed: clear those fields yourself. File deletes are never queued.
Rejects with network (the device is offline, checked before anything is sent, or the server cannot be reached), forbidden (another app owns the file's collection) and not_found (the ID is wrong or the file is already deleted).
backend.onConflict()
onConflict(cb: (e: { op: QueuedOp; error: PbError; localData: unknown }) => void): () => void
Registers cb, which the SDK calls when the server refuses a queued change for good. Returns a function that unregisters it. Register it once, right after connect().
The server refuses a change for good when retrying can never help: record_deleted, forbidden, schema_violation, version_unsupported, not_found, invalid_request, payload_too_large and consent_required, and any code the SDK does not know. The SDK then drops the change from the queue, puts the record back as the server has it, and calls cb with:
op: the dropped change, aQueuedOp.error: why the server refused it, aPbError.localData: the record's data as your app had it with that change, ornull, so you can show it or save it again.
When a refused change was a create, the changes queued after it for the same record are dropped too, and cb is called once for each.
Other failures do not call cb: the change stays queued with every change after it, and the SDK tries again later, waiting longer after each failure, up to a fixed maximum, and at least as long as the server asks on rate_limited. These are network, internal, invalid_response, rate_limited, unauthorized, app_suspended and server errors. A refusal of a whole batch that no single change caused, such as forbidden because the page's origin is not registered, also keeps the queue.
backend.status()
status(): { online: boolean; pending: number; problem?: PbError }
Returns how things stand at the moment you call it. Call it again whenever your page shows its status; it does not notify you of changes.
online:truewhen the device says it is online and the last request reached the server.pending: how many changes are waiting in the write queue.problem: present while something the user must act on holds up the write queue or live updates:app_suspended,account_closed,consent_requiredfor a subscribed collection your app may not read, or an error that refused a whole batch, such asforbiddenfor an unregistered origin. It is cleared when the problem is gone.
backend.signOut()
signOut(): Promise<void>
Signs the user out of your app in this browser. It stops the write queue and live updates, deletes this user's copy of your app's data and the changes still waiting in the queue, and forgets the stored sign-in. Changes that were still pending are lost: check status().pending first and warn the user.
It does not sign the user out of the server itself, and it keeps the browser's key for the server and other apps' sign-ins. Afterwards the collection and file calls on this backend throw or reject with unauthorized; call connect() again from a click to sign in. Calling signOut() twice does nothing the second time.
Collection
export interface Collection<T> {
create(data: T): Promise<PbRecord<T>>; update(rkey: string, patch: Partial<T>): Promise<PbRecord<T>>;
delete(rkey: string): Promise<void>; get(rkey: string): Promise<PbRecord<T> | null>; list(): Promise<PbRecord<T>[]>;
where(field: string, op: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in", value: unknown): Query<T>;
orderBy(field: string, dir?: "asc" | "desc"): Query<T>;
subscribe(cb: (records: PbRecord<T>[]) => void): () => void;
requestAccess(): Promise<boolean>;
}
One collection of the user's data, from backend.collection(). Writes go to the browser's copy at once and into the write queue; reads come from the browser's copy. Your app can write only its own collections and its own sandbox. collections; another app's collection is read-only, even with the user's consent.
create()
create(data: T): Promise<PbRecord<T>>
Creates a record with the fields in data. The SDK makes the record's rkey (record key, a UUIDv7) on the device, saves the record in the browser's copy, queues the change and resolves at once with the new PbRecord, whose status is pending and rev is 0. It works offline.
Rejects with unauthorized after signOut(), and with invalid_request when data is not a plain object. The server checks the record when the change is sent; a refusal, such as schema_violation, arrives through onConflict.
update()
update(rkey: string, patch: Partial<T>): Promise<PbRecord<T>>
Changes the record rkey: each field in patch replaces that field, fields you leave out are kept, and a field set to null is removed. Resolves at once with the changed record, pending, and queues the change. The generated types do not allow null, so cast a patch that removes a field, as Read and write records shows.
When the record is not in the browser's copy yet, the SDK first asks the server for the collection's latest changes (when the device is online).
Rejects with unauthorized after signOut(), invalid_request when patch is not a plain object, not_found when there is no such record (offline, a record this browser has never seen counts as not found), and record_deleted when the record is deleted, including when that catch-up shows it was deleted elsewhere. When the SDK had to ask the server, any error from the server other than network, such as consent_required or unauthorized, also rejects the call; network does not, and the call goes on with the browser's copy. A refusal by the server arrives through onConflict.
delete()
delete(rkey: string): Promise<void>
Deletes the record rkey from the browser's copy at once and queues the change. A record this browser already knows is deleted is left as it is, with no error. As with update(), a record not in the browser's copy is looked up on the server first (when the device is online).
Rejects with unauthorized after signOut(), not_found when there is no such record, and record_deleted when the lookup on the server shows the record was deleted elsewhere. As with update(), a server error other than network during that lookup also rejects the call. A deleted record can be restored only by the user, from their account area, for 30 days.
get()
get(rkey: string): Promise<PbRecord<T> | null>
Resolves with the record rkey from the browser's copy, or null when the copy does not have it, it is deleted, or it was written with a major version outside versions. It never waits for the network. The first get() or list() of a collection in a session also starts bringing the browser's copy up to date in the background; subscribe to be called when that lands.
Rejects with unauthorized after signOut().
list()
list(): Promise<PbRecord<T>[]>
Resolves with every record of the collection in the browser's copy, oldest first (by createdAt, then rkey). There is no limit on the number. It never waits for the network and starts a background catch-up as get() does.
Rejects with unauthorized after signOut().
where()
where(field: string, op: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in", value: unknown): Query<T>
Starts a Query that keeps only records whose field compares to value with op. "in" keeps records whose field equals one of the values in a list, such as ["blue", "green"]. A Date value is sent as its date and time in ISO form. Only fields marked indexed, createdAt and updatedAt can be used.
Throws invalid_request for an operator not in the list. A field that is not indexed is refused when the query runs. See Query, sort and live updates.
orderBy()
orderBy(field: string, dir?: "asc" | "desc"): Query<T>
Starts a Query sorted by field, "asc" (the default, smallest first) or "desc". Only indexed fields, createdAt and updatedAt can be used. Without orderBy, queries are sorted by createdAt, oldest first.
subscribe()
subscribe(cb: (records: PbRecord<T>[]) => void): () => void
Calls cb with every record of the collection in the browser's copy, oldest first, now and again after every change to them: your own writes, results from the server, changes from other tabs, and live updates from other devices. While at least one subscription is open, the SDK keeps the collection up to date through a live connection to the server. There is no limit on the number of records. Returns a function that ends the subscription.
It works offline, on the browser's copy. Throws unauthorized after signOut(). When the collection belongs to another app that your app may not read, the SDK leaves it out of live updates, keeps them for your other collections, and status().problem holds consent_required.
requestAccess()
requestAccess(): Promise<boolean>
For another app's collection: opens a popup on the server that asks the user to let your app read the collection, and resolves true when they allow it, false when they deny or close the popup. Call it first in a click or key handler, before any await, as for connect(). After true, the SDK fetches the collection's records again from the start. The versions you gave to backend.collection() are sent with the request. A second call for the same collection while its popup is open returns the same promise.
It needs the network. Rejects with:
popup_blocked: the browser did not open the popup.invalid_request: a consent popup for another collection is still open; the collection is your app's own (it needs no consent); or it is asandbox.collection, which no other app can read.not_found: the collection has no published schema.version_unsupported:versionsnames a major version that was never published.network, andunauthorizedaftersignOut().
Query
export interface Query<T> { where: Collection<T>["where"]; orderBy: Collection<T>["orderBy"]; limit(n: number): Query<T>;
get(): Promise<PbRecord<T>[]>; subscribe(cb: (records: PbRecord<T>[]) => void): () => void }
A query on one collection, started with where() or orderBy() on a Collection. Each method returns a new query and leaves the one it was called on unchanged, so a query can be kept and reused.
query.where() and query.orderBy()
The same as on a collection. Every where() narrows the result (filters combine with AND only); two where() calls on one field give a range. A second orderBy() replaces the first, without an error. Query limits and workarounds lists what queries cannot do and what to do instead.
query.limit()
limit(n: number): Query<T>
Returns at most n records. Without limit(n), a query returns at most 500 records. Throws invalid_request when n is not a whole number of at least 1.
query.get()
get(): Promise<PbRecord<T>[]>
Runs the query. When the device is online, it runs on the server, asking for as many pages as it needs up to the limit, saves the records in the browser's copy, and adds this device's changes that are still queued. When the device is offline, or the server cannot be reached, it runs on the browser's copy with the same rules: records without the sort field come last, ties are sorted by rkey, and no operator, not even "!=", matches a record that lacks the field. Offline results include only records this browser has seen.
Rejects with unauthorized after signOut(), invalid_request (a field that is not indexed, a value that does not fit the field's type, too many "in" values, or no versions for another app's collection), consent_required (another app's collection your app may not read), version_unsupported and other server codes. It does not reject with network: it answers from the browser's copy instead.
query.subscribe()
subscribe(cb: (records: PbRecord<T>[]) => void): () => void
Calls cb with the query's result on the browser's copy, now and after every change to the collection, as a collection's subscribe() does, filtered and sorted, and cut at the query's limit (500 without limit(n)). Returns a function that ends the subscription. It works offline. Throws unauthorized after signOut().
PbRecord
export interface PbRecord<T> { id: string; collection: string; rkey: string; data: T; rev: number;
status: "pending" | "synced"; createdAt: string; updatedAt: string }
One record as your app gets it.
| Field | What it holds |
|---|---|
id |
The record's global ID, pb://<userId>/<collection>/<rkey>. A recordRef field holds this value. |
collection |
The collection's name. |
rkey |
The record's key within the collection, a UUIDv7 made on the device. |
data |
The record's fields. |
rev |
A number the server raises with every change to the record. A record not yet on the server has 0. |
status |
"pending" while a change to it is queued, "synced" once the server has its latest change. |
createdAt |
When it was created, as an RFC 3339 date and time. |
updatedAt |
When it was last changed, in the same form. |
Collections and records explains each part.
QueuedOp
export interface QueuedOp { opId: string; kind: "create" | "update" | "delete"; collection: string; rkey: string;
input: { schemaMajor?: number; baseRev?: number; data?: unknown } }
A change in the write queue, as onConflict reports it.
| Field | What it holds |
|---|---|
opId |
The change's own ID, a UUIDv7. The server applies a change with the same ID only once. |
kind |
"create", "update" or "delete". |
collection |
The collection's name. |
rkey |
The record's key. |
input.schemaMajor |
The major version the change writes, when your app chose one. |
input.baseRev |
For an update: the record's rev on the server when the change was made, when the browser knew it. |
input.data |
For a create, the record's fields; for an update, the fields it changes. |
PbError
export class PbError extends Error {
code: string;
hint: string;
extra: Record<string, unknown>;
constructor(code: string, message: string, hint = "", extra: Record<string, unknown> = {})
}
Every error the SDK throws, rejects with or reports is a PbError. Its name is "PbError", so e instanceof PbError tells it apart from other errors.
code: a short name. It is one of the server's codes, such asconsent_required, or one of the SDK's own:network,invalid_response,popup_blocked,sign_in_cancelled,access_deniedandaccount_closed. Decide what to do from the code, never from the message.message: what went wrong, in a sentence.hint: how to fix it.extra: every other detail the server sent, such asfieldsonschema_violation, plusretryAfter(in seconds) onrate_limitedandstatus(the HTTP status) when the server answered with an error that had no details.
You can construct one yourself, for example in tests: new PbError("network", "Offline."). Errors and how to fix them explains every code and what to do about it.
Example
Every call on this page, in one file:
import { connect, PbError, type PbRecord } from "@phibac/sdk";
interface Note {
text: string;
pinned?: boolean;
photo?: string;
}
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const fileInput = document.querySelector<HTMLInputElement>("#photo")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
signIn.addEventListener("click", async () => {
try {
const backend = await connect({ app: "app_...", baseUrl: "http://localhost:8787", schemaMajors: { "com.example.notes.note": 1 } });
const notes = backend.collection<Note>("com.example.notes.note");
const stopConflicts = backend.onConflict(({ op, error, localData }) => console.log(op.kind, error.code, localData));
const note = await notes.create({ text: "Buy milk" });
await notes.update(note.rkey, { pinned: true });
const same: PbRecord<Note> | null = await notes.get(note.rkey);
const all = await notes.list();
const pinned = await notes.where("pinned", "==", true).orderBy("createdAt", "desc").limit(20).get();
const stop = notes.where("pinned", "==", true).subscribe((records) => console.log(records.length));
const file = fileInput.files?.[0];
if (file) {
const fileId = await backend.files.upload(file, { collection: "com.example.notes.note", rkey: note.rkey });
await notes.update(note.rkey, { photo: fileId });
console.log(await backend.files.url(fileId));
}
const { online, pending, problem } = backend.status();
console.log(same?.status, all.length, pinned.length, online, pending, problem?.code);
await notes.delete(note.rkey);
stop();
stopConflicts();
await backend.signOut();
} catch (e) {
message.textContent = e instanceof PbError ? `${e.code}: ${e.message} ${e.hint}` : String(e);
}
});
Reading another app's collection with requestAccess() needs a click of its own; see Read another app's data.