Classes
RtdbOnDisconnect
Constructors
Constructor
new RtdbOnDisconnect(_repo: RtdbRefHandle, _path?: string): RtdbOnDisconnect;
Parameters
| Parameter | Type |
|---|---|
_repo | RtdbRefHandle |
_path? | string |
Returns
Methods
cancel()
cancel(): Promise<void>;
Returns
Promise<void>
remove()
remove(): Promise<void>;
Returns
Promise<void>
set()
set(value: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
Returns
Promise<void>
setWithPriority()
setWithPriority(value: unknown, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
value | unknown |
priority | string | number |
Returns
Promise<void>
update()
update(values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
values | Record<string, unknown> |
Returns
Promise<void>
Interfaces
ClientAuth
Client-side Auth handle. Holds the port + a local currentUser mirror.
Returned by getAuth(db | workerUrl). Mirrors firebase/auth’s Auth.
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
currentUser | public | ClientUser | Local mirror of the worker’s currentUser, updated from the stream. |
port | readonly | ClientPort | - |
ClientDb
Opaque client-side Firestore handle. Holds the MessagePort to the worker.
Properties
ClientDocSnapshot
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
id | readonly | string | - |
path | readonly | string | - |
ref | readonly | DocRefHandle | Full port-carrying reference, usable by write APIs. |
Methods
data()
data(): Record<string, unknown>;
Returns
Record<string, unknown>
exists()
exists(): boolean;
Returns
boolean
ClientFirebaseStorage
Worker-backed Storage handle (carries the shared MessagePort).
Properties
ClientQuerySnapshot
Properties
| Property | Modifier | Type |
|---|---|---|
docs | readonly | ClientDocSnapshot[] |
empty | readonly | boolean |
size | readonly | number |
ClientRtdb
Properties
ClientSettableMetadata
Mirror of pyric/storage’s SettableMetadata (plain JSON on the wire).
Properties
| Property | Type |
|---|---|
cacheControl? | string |
contentDisposition? | string |
contentEncoding? | string |
contentLanguage? | string |
contentType? | string |
customMetadata? | { [key: string]: string; } |
ClientStorageReference
Worker-backed Storage reference (path + name; carries the port for ops).
Properties
| Property | Modifier | Type |
|---|---|---|
bucket | readonly | string |
fullPath | readonly | string |
name | readonly | string |
parent | readonly | ClientStorageReference |
port | readonly | ClientPort |
root | readonly | ClientStorageReference |
storage? | readonly | ClientFirebaseStorage |
Methods
toString()
toString(): string;
Returns
string
ClientTransaction
Client-side transaction handle.
Methods
delete()
delete(ref: DocRefHandle): void;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
void
get()
get(ref: DocRefHandle): Promise<ClientDocSnapshot>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
Promise<ClientDocSnapshot>
set()
set(
ref: DocRefHandle,
data: Record<string, unknown>,
options?: {
merge?: boolean;
mergeFields?: string[];
}): void;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
options? | { merge?: boolean; mergeFields?: string[]; } |
options.merge? | boolean |
options.mergeFields? | string[] |
Returns
void
update()
update(ref: DocRefHandle, data: Record<string, unknown>): void;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
void
ClientUploadTask
Extends
Promise<ClientUploadTaskSnapshot>
Properties
| Property | Modifier | Type |
|---|---|---|
snapshot | readonly | ClientUploadTaskSnapshot |
Methods
cancel()
cancel(): boolean;
Returns
boolean
on()
on(
event: string,
nextOrObserver?:
| (snapshot: ClientUploadTaskSnapshot) => unknown
| {
complete?: () => unknown;
error?: (error: Error) => unknown;
next?: (snapshot: ClientUploadTaskSnapshot) => unknown;
},
error?: (error: Error) => unknown,
complete?: () => unknown): () => void;
Parameters
| Parameter | Type |
|---|---|
event | string |
nextOrObserver? | | (snapshot: ClientUploadTaskSnapshot) => unknown | { complete?: () => unknown; error?: (error: Error) => unknown; next?: (snapshot: ClientUploadTaskSnapshot) => unknown; } |
error? | (error: Error) => unknown |
complete? | () => unknown |
Returns
(): void;
Returns
void
pause()
pause(): boolean;
Returns
boolean
resume()
resume(): boolean;
Returns
boolean
ClientUploadTaskSnapshot
Properties
| Property | Modifier | Type |
|---|---|---|
bytesTransferred | readonly | number |
metadata | readonly | FullMetadata |
ref | readonly | ClientStorageReference |
state | readonly | ClientTaskState |
task | readonly | ClientUploadTask |
totalBytes | readonly | number |
ClientUser
Client-side User — a snapshot of the worker’s User with token accessors
that RPC back to the worker. Mirrors firebase/auth’s User shape.
Properties
Methods
getIdToken()
getIdToken(forceRefresh?: boolean): Promise<string>;
Parameters
| Parameter | Type |
|---|---|
forceRefresh? | boolean |
Returns
Promise<string>
getIdTokenResult()
getIdTokenResult(forceRefresh?: boolean): Promise<SerializedIdTokenResult>;
Parameters
| Parameter | Type |
|---|---|
forceRefresh? | boolean |
Returns
Promise<SerializedIdTokenResult>
ClientUserCredential
Client-side UserCredential — mirrors firebase/auth.
Properties
| Property | Type |
|---|---|
operationType | "signIn" | "link" | "reauthenticate" |
providerId | string |
user | ClientUser |
ClientWriteBatch
Client-side write batch. Buffers set/update/delete calls and
sends them all to the worker on .commit().
Mirrors pyric/firestore’s writeBatch(db) shape:
const batch = writeBatch(db);
batch.set(ref, { … });
batch.delete(ref2);
await batch.commit();
Methods
commit()
commit(): Promise<void>;
Returns
Promise<void>
delete()
delete(ref: DocRefHandle): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
set()
set(
ref: DocRefHandle,
data: Record<string, unknown>,
options?: {
merge?: boolean;
mergeFields?: string[];
}): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
options? | { merge?: boolean; mergeFields?: string[]; } |
options.merge? | boolean |
options.mergeFields? | string[] |
Returns
update()
update(ref: DocRefHandle, data: Record<string, unknown>): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
CollRefHandle
Client-side collection reference.
Properties
| Property | Modifier | Type |
|---|---|---|
descriptor | readonly | CollRef |
id | readonly | string |
path | readonly | string |
port | readonly | ClientPort |
DisconnectClientOptions
Properties
| Property | Type | Description |
|---|---|---|
ackTimeoutMs? | number | Bound version-skew and worker-crash cases where no disconnect reply arrives. |
DocRefHandle
Client-side document reference — carries a DocRef descriptor + port.
Properties
| Property | Modifier | Type |
|---|---|---|
descriptor | readonly | DocRef |
id | readonly | string |
path | readonly | string |
port | readonly | ClientPort |
PresenceSession
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
clientId | readonly | string | Logical page id — Studio uses this to label “This page”. |
kind | readonly | PresenceClientKind | - |
Methods
stop()
stop(): void;
Stop heartbeats, listeners, and send a best-effort disconnect.
Returns
void
PresenceSnapshot
Authoritative presence snapshot owned by the SharedWorker host.
Properties
PyricRuntimeManifest
Browser-safe SharedWorker CLIENT surface (Pyric Studio data plane).
This barrel exports ONLY the leaf client + the wire-protocol types — the
pieces a browser app (the served page, or Pyric Studio’s Vite app) imports to
connect to the pyric-shared-worker over its MessagePort. It deliberately
does NOT re-export host.ts/entry.ts:
host.tsimports the fullpyric/firestore+pyric/authengine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.entry.tsreferencesSharedWorkerGlobalScopeand is esbuild-only.
client.ts imports only the value codec
(pyric/firestore/internal/value-codec, a leaf internal seam)
and type-only pyric/sandbox (erased at build), so this entry stays free of
the ~10 MB rules/sandbox engine — safe to import from any browser app.
Exposed by @pyric/cli’s ./serve/worker package export so Studio can
import { getFirestore, subscribeEvents, setLens } from '@pyric/cli/serve/worker' and reach the live SharedWorker backend.
Properties
QueryHandle
Client-side query.
Properties
ResolvedIdentity
A provider identity resolved IN-PAGE (by the ServeAuthHelper’s
popup/redirect picker) and handed to the worker for sign-in. Provider flows
(signInWithPopup/signInWithRedirect) can’t cross the worker port — the
AuthFlowResolver lives in-page — so the page resolves the picked identity
and bridges it here; the worker seeds it + restoreSessions it (no password
— provider users never sign in with one). See auth.acceptIdentity.
Properties
| Property | Modifier | Type |
|---|---|---|
customClaims | readonly | Record<string, unknown> |
displayName | readonly | string |
email | readonly | string |
providerId | readonly | string |
uid | readonly | string |
RtdbDataSnapshot
Properties
| Property | Modifier | Type |
|---|---|---|
key | readonly | string |
priority | readonly | string | number |
ref | readonly | RtdbRefHandle |
size | readonly | number |
Methods
child()
child(path: string): RtdbDataSnapshot;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
exists()
exists(): boolean;
Returns
boolean
exportVal()
exportVal(): unknown;
Returns
unknown
forEach()
forEach(cb: (child: RtdbDataSnapshot) => boolean | void): boolean;
Parameters
| Parameter | Type |
|---|---|
cb | (child: RtdbDataSnapshot) => boolean | void |
Returns
boolean
hasChild()
hasChild(path: string): boolean;
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
boolean
hasChildren()
hasChildren(): boolean;
Returns
boolean
toJSON()
toJSON(): unknown;
Returns
unknown
val()
val(): unknown;
Returns
unknown
RtdbRefHandle
Properties
| Property | Modifier | Type |
|---|---|---|
key | readonly | string |
parent | readonly | RtdbRefHandle |
path | readonly | string |
port | readonly | ClientPort |
root | readonly | RtdbRefHandle |
Methods
isEqual()
isEqual(other: RtdbRefHandle): boolean;
Parameters
| Parameter | Type |
|---|---|
other | RtdbRefHandle |
Returns
boolean
toJSON()
toJSON(): string;
Returns
string
toString()
toString(): string;
Returns
string
SerializedIdTokenResult
Wire form of getIdTokenResult().
Properties
| Property | Modifier | Type |
|---|---|---|
authTime | readonly | string |
claims | readonly | Record<string, unknown> |
expirationTime | readonly | string |
issuedAtTime | readonly | string |
signInProvider | readonly | string |
token | readonly | string |
SerializedUser
Wire representation of a signed-in User. The real pyric/auth User
carries methods (getIdToken, getIdTokenResult) that don’t survive
structured clone, so the worker flattens the fields the client mirror
needs into a plain object. Token accessors on the client re-RPC to the
worker (the worker holds the one real user).
null means “signed out” — there is no current user.
Properties
SerializedUserCredential
Wire form of a UserCredential returned by the sign-in/create ops.
Properties
| Property | Modifier | Type |
|---|---|---|
operationType | readonly | "signIn" | "link" | "reauthenticate" |
providerId | readonly | string |
user | readonly | SerializedUser |
WorkerReplacement
Methods
dispose()
dispose(): void;
Returns
void
request()
request(): Promise<void>;
Returns
Promise<void>
Type Aliases
AnyHandle
type AnyHandle =
| ClientDb
| DocRefHandle
| CollRefHandle
| QueryHandle;
Union of all client handles.
AuthPersistenceMode
type AuthPersistenceMode = "LOCAL" | "SESSION" | "NONE";
Persistence mode for the worker’s shared auth session.
Mirrors pyric/auth’s Persistence.type. 'NONE' (inMemoryPersistence)
disables the IndexedDB session record so a full close does NOT keep the
user signed in; 'LOCAL' and 'SESSION' both persist the session in
this single-backend model (see SESSION/LOCAL collapse note in host.ts).
PresenceClientKind
type PresenceClientKind = "app" | "studio";
Logical page kind for presence (#227).
PresenceVisibility
type PresenceVisibility = "visible" | "hidden";
Page Visibility API state carried on presence records.
Unsubscribe()
type Unsubscribe = () => void;
Unsubscribe function returned by every streaming subscription.
Returns
void
Variables
browserLocalPersistence
const browserLocalPersistence: {
type: "LOCAL";
};
Type Declaration
type
readonly type: "LOCAL";
browserSessionPersistence
const browserSessionPersistence: {
type: "SESSION";
};
Type Declaration
type
readonly type: "SESSION";
inMemoryPersistence
const inMemoryPersistence: {
type: "NONE";
};
Persistence markers — mirror firebase/auth / pyric/auth.
Type Declaration
type
readonly type: "NONE";
PRESENCE_HEARTBEAT_INTERVAL_MS
const PRESENCE_HEARTBEAT_INTERVAL_MS: 15000 = 15000;
Suggested client heartbeat interval.
PRESENCE_STALE_MS
const PRESENCE_STALE_MS: 90000 = 90000;
Lease TTL. Sized to tolerate one delayed background-tab heartbeat under typical timer throttling (~1/min) without falsely evicting a live page.
PYRIC_WORKER_GENERATION_KEY
const PYRIC_WORKER_GENERATION_KEY: "pyric:worker-generation" = "pyric:worker-generation";
PYRIC_WORKER_NAME
const PYRIC_WORKER_NAME: "pyric-shared-worker" = "pyric-shared-worker";
Browser-safe SharedWorker CLIENT surface (Pyric Studio data plane).
This barrel exports ONLY the leaf client + the wire-protocol types — the
pieces a browser app (the served page, or Pyric Studio’s Vite app) imports to
connect to the pyric-shared-worker over its MessagePort. It deliberately
does NOT re-export host.ts/entry.ts:
host.tsimports the fullpyric/firestore+pyric/authengine (it IS the backend) — node/engine-heavy, never wanted in a page bundle.entry.tsreferencesSharedWorkerGlobalScopeand is esbuild-only.
client.ts imports only the value codec
(pyric/firestore/internal/value-codec, a leaf internal seam)
and type-only pyric/sandbox (erased at build), so this entry stays free of
the ~10 MB rules/sandbox engine — safe to import from any browser app.
Exposed by @pyric/cli’s ./serve/worker package export so Studio can
import { getFirestore, subscribeEvents, setLens } from '@pyric/cli/serve/worker' and reach the live SharedWorker backend.
PYRIC_WORKER_URL
const PYRIC_WORKER_URL: "/__pyric/sdk/worker.js" = "/__pyric/sdk/worker.js";
Stable routes and identity used by the served runtime and its UI.
Functions
acceptProviderCredential()
function acceptProviderCredential(auth: ClientAuth, identity: ResolvedIdentity): Promise<ClientUserCredential>;
Bridge a provider identity resolved IN-PAGE to the worker (the provider
sign-in seam). The entry adapter’s worker-path signInWithPopup/
signInWithRedirect runs the in-page AuthFlowResolver (which can’t cross
the worker port), then calls this with the picked identity; the worker seeds
it + signs it in, returning a worker-backed credential. The mirror updates
eagerly (like the email/anon paths) so a synchronous auth.currentUser
read right after the await reflects the new user.
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
identity | ResolvedIdentity |
Returns
Promise<ClientUserCredential>
addDoc()
function addDoc(coll: CollRefHandle, data: Record<string, unknown>): Promise<DocRefHandle>;
Parameters
| Parameter | Type |
|---|---|
coll | CollRefHandle |
data | Record<string, unknown> |
Returns
Promise<DocRefHandle>
adminClearUsers()
function adminClearUsers(auth: ClientAuth): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<void>
adminCreateUser()
function adminCreateUser(auth: ClientAuth, request: CreateUserRequest): Promise<AuthUserRecord>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
request | CreateUserRequest |
Returns
Promise<AuthUserRecord>
adminDeleteDocument()
function adminDeleteDocument(db: ClientDb, path: string): Promise<boolean>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<boolean>
adminDeleteRtdbValue()
function adminDeleteRtdbValue(db: ClientDb | ClientRtdb, path: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
Returns
Promise<void>
adminDeleteUser()
function adminDeleteUser(auth: ClientAuth, uid: string): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
uid | string |
Returns
Promise<void>
adminGetDocument()
function adminGetDocument(db: ClientDb, path: string): Promise<Record<string, unknown>>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<Record<string, unknown>>
adminListDocuments()
function adminListDocuments(db: ClientDb, path: string): Promise<{
data: unknown;
path: string;
phantom?: boolean;
}[]>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
Returns
Promise<{
data: unknown;
path: string;
phantom?: boolean;
}[]>
adminReadRtdbState()
function adminReadRtdbState(db: ClientDb | ClientRtdb): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
Returns
Promise<unknown>
adminReadState()
function adminReadState(db: ClientDb, opts?: {
maxDepth?: number;
path?: string;
}): Promise<Record<string, unknown>>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
opts? | { maxDepth?: number; path?: string; } |
opts.maxDepth? | number |
opts.path? | string |
Returns
Promise<Record<string, unknown>>
adminSetDocument()
function adminSetDocument(
db: ClientDb,
path: string,
data: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
path | string |
data | unknown |
Returns
Promise<void>
adminSetRtdbValue()
function adminSetRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
value: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
value | unknown |
Returns
Promise<void>
adminSubscribeRtdbValue()
function adminSubscribeRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
next: (value: unknown) => void,
error?: (err: unknown) => void): Unsubscribe;
Subscribe with an explicit admin lens so Studio stays rules-independent.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
next | (value: unknown) => void |
error? | (err: unknown) => void |
Returns
adminUpdateRtdbValue()
function adminUpdateRtdbValue(
db: ClientDb | ClientRtdb,
path: string,
values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
path | string |
values | Record<string, unknown> |
Returns
Promise<void>
adminUpdateUser()
function adminUpdateUser(
auth: ClientAuth,
uid: string,
request: UpdateUserRequest): Promise<AuthUserRecord>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
uid | string |
request | UpdateUserRequest |
Returns
Promise<AuthUserRecord>
and()
function and(...filters: QueryConstraintHandle[]): QueryConstraintHandle;
AND composite filter — every operand must match. See or.
Parameters
| Parameter | Type |
|---|---|
…filters | QueryConstraintHandle[] |
Returns
QueryConstraintHandle
arrayRemove()
function arrayRemove(...values: unknown[]): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
SentinelMarker
arrayUnion()
function arrayUnion(...values: unknown[]): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
SentinelMarker
average()
function average(field: string): AggregateFieldDescriptor;
Factory: average-of-field aggregate. Empty input yields null.
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
AggregateFieldDescriptor
callTool()
function callTool(
db: ClientDb,
name: string,
args: Record<string, unknown>): Promise<{
data?: unknown;
ok: boolean;
summary: string;
}>;
Forward an agent tool-call to the worker so it executes against the SAME
sandbox the app + Studio use. The worker runs the canonical tool dispatcher
(buildSandboxDispatcher) and replies with the { ok, summary, data }
result. Used by the bridge peer on the worker path (connectBridgePeer in
entries/runtime.ts) so the agent shares the one authoritative sandbox.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
args | Record<string, unknown> |
Returns
Promise<{
data?: unknown;
ok: boolean;
summary: string;
}>
collection()
function collection(parent: ClientDb | DocRefHandle, ...pathSegments: string[]): CollRefHandle;
Build a collection reference. Mirrors pyric/firestore’s collection(db, path).
Parameters
| Parameter | Type |
|---|---|
parent | ClientDb | DocRefHandle |
…pathSegments | string[] |
Returns
collectionGroup()
function collectionGroup(db: ClientDb, collectionId: string): QueryHandle;
Build a collection-group query. Mirrors pyric/firestore’s collectionGroup(db, id).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
collectionId | string |
Returns
connectAuthEmulator()
function connectAuthEmulator(
_auth: ClientAuth,
_url: string,
_options?: {
disableWarnings?: boolean;
}): void;
Connect to the auth emulator. No-op shim over the worker: the worker’s sandbox IS the emulator-equivalent backend, so there’s nothing to point at. Present for surface parity so app code that calls it doesn’t break.
Parameters
| Parameter | Type |
|---|---|
_auth | ClientAuth |
_url | string |
_options? | { disableWarnings?: boolean; } |
_options.disableWarnings? | boolean |
Returns
void
count()
function count(): AggregateFieldDescriptor;
Factory: count() aggregate field. Mirrors pyric/firestore’s count().
Returns
AggregateFieldDescriptor
createUserWithEmailAndPassword()
function createUserWithEmailAndPassword(
auth: ClientAuth,
email: string,
password: string): Promise<ClientUserCredential>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
email | string |
password | string |
Returns
Promise<ClientUserCredential>
createWorkerReplacement()
function createWorkerReplacement(options: WorkerReplacementOptions): WorkerReplacement;
Coordinate one reload per page after the old SharedWorker announces retirement.
Parameters
| Parameter | Type |
|---|---|
options | WorkerReplacementOptions |
Returns
deleteDoc()
function deleteDoc(ref: DocRefHandle): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
Promise<void>
deleteField()
function deleteField(): SentinelMarker;
Returns
SentinelMarker
deleteObject()
function deleteObject(reference: ClientStorageReference): Promise<void>;
Delete the object at the reference’s path (idempotent — missing = no-op, matching the sandbox backend’s delete semantics).
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<void>
deleteWorkerBranch()
function deleteWorkerBranch(db: ClientDb, name: string): Promise<void>;
Phase 3: delete a named branch.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
Returns
Promise<void>
disconnectClient()
function disconnectClient(db: ClientDb, options?: DisconnectClientOptions): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
options? | DisconnectClientOptions |
Returns
Promise<void>
doc()
function doc(parent: ClientDb | CollRefHandle, ...pathSegments: string[]): DocRefHandle;
Build a document reference. Mirrors pyric/firestore’s doc(db, path).
WHY CLIENT-SIDE: Firebase’s doc() is synchronous and path-only — it
needs no data from the sandbox. We build a descriptor object here and
include the port so execution calls can route to the worker.
Parameters
| Parameter | Type |
|---|---|
parent | ClientDb | CollRefHandle |
…pathSegments | string[] |
Returns
endAt()
function endAt(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
endBefore()
function endBefore(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
eventHistory()
function eventHistory(db: ClientDb): Promise<readonly SandboxEvent[]>;
Fetch the worker sandbox’s event history as a one-shot snapshot (every event so far). Opens a transient stream sub, resolves with the initial history batch, and tears the sub down immediately — so it never holds a live subscription. Useful for a late, snapshot-only consumer.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<readonly SandboxEvent[]>
exportWorkerState()
function exportWorkerState(db: ClientDb): Promise<string>;
Phase 2 (transfer): export the FULL sandbox state as a portable bundle string (the chunk format the persist layer uses, so wrapper types round-trip). Save it to a file and importWorkerState it into another instance.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string>
getActiveRules()
function getActiveRules(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
service? | "firestore" | "database" |
Returns
Promise<unknown>
getAggregateFromServer()
function getAggregateFromServer<S>(source: CollRefHandle | QueryHandle, spec: S): Promise<{
data: { [K in string | number | symbol]: number };
}>;
Run a multi-field aggregate on the worker. Mirrors pyric/firestore’s
getAggregateFromServer(query, spec): spec entries are keyed by
caller-chosen aliases; .data() returns the numbers under the same keys
(average over no rows is null).
Type Parameters
| Type Parameter |
|---|
S extends AggregateSpecDescriptor |
Parameters
| Parameter | Type |
|---|---|
source | CollRefHandle | QueryHandle |
spec | S |
Returns
Promise<{
data: { [K in string | number | symbol]: number };
}>
getAuth()
function getAuth(source: string | ClientDb | URL, name?: string): ClientAuth;
Get the worker-backed Auth handle.
Mirrors pyric/auth’s getAuth(sandbox) / firebase/auth’s
getAuth(app) — but the input is either an existing ClientDb (reusing
its port, the common case in serve where Firestore + auth share one
worker) or a worker URL (standalone).
The returned handle seeds its currentUser mirror by opening an internal
authState subscription that keeps it live across tabs.
Parameters
| Parameter | Type |
|---|---|
source | string | ClientDb | URL |
name? | string |
Returns
getBlob()
function getBlob(reference: ClientStorageReference): Promise<Blob>;
Read an object’s bytes as a Blob (Pyric Studio inspector preview). MessagePort-only — a Blob cannot cross the JSON bridge relay.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<Blob>
getBytes()
function getBytes(reference: ClientStorageReference, maxDownloadSizeBytes?: number): Promise<ArrayBuffer>;
Read an object’s bytes (JSON-safe base64 op → ArrayBuffer). Mirrors
pyric/storage’s getBytes, including the optional client-side cap.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
maxDownloadSizeBytes? | number |
Returns
Promise<ArrayBuffer>
getCountFromServer()
function getCountFromServer(source: CollRefHandle | QueryHandle): Promise<{
data: {
count: number;
};
}>;
Parameters
| Parameter | Type |
|---|---|
source | CollRefHandle | QueryHandle |
Returns
Promise<{
data: {
count: number;
};
}>
getDoc()
function getDoc(ref: DocRefHandle): Promise<ClientDocSnapshot>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
Returns
Promise<ClientDocSnapshot>
getDocs()
function getDocs(source: CollRefHandle | QueryHandle): Promise<ClientQuerySnapshot>;
Parameters
| Parameter | Type |
|---|---|
source | CollRefHandle | QueryHandle |
Returns
Promise<ClientQuerySnapshot>
getDownloadURL()
function getDownloadURL(reference: ClientStorageReference): Promise<string>;
Return a page-owned URL for an object read through the SharedWorker.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<string>
getFirestore()
function getFirestore(
workerUrl: string | URL,
name?: string,
options?: SharedWorkerConnectionOptions): ClientDb;
Parameters
| Parameter | Type |
|---|---|
workerUrl | string | URL |
name? | string |
options? | SharedWorkerConnectionOptions |
Returns
getIdToken()
function getIdToken(user: ClientUser, forceRefresh?: boolean): Promise<string>;
Top-level mirror of firebase/auth’s getIdToken(user).
Parameters
| Parameter | Type |
|---|---|
user | ClientUser |
forceRefresh? | boolean |
Returns
Promise<string>
getIdTokenResult()
function getIdTokenResult(user: ClientUser, forceRefresh?: boolean): Promise<SerializedIdTokenResult>;
Top-level mirror of firebase/auth’s getIdTokenResult(user).
Parameters
| Parameter | Type |
|---|---|
user | ClientUser |
forceRefresh? | boolean |
Returns
Promise<SerializedIdTokenResult>
getLens()
function getLens(): AuthLens;
The active default lens (read-only view), for Studio UI to reflect state.
Returns
getMetadata()
function getMetadata(reference: ClientStorageReference): Promise<FullMetadata>;
Read an object’s metadata (Pyric Studio inspector).
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<FullMetadata>
getProviderConfig()
function getProviderConfig(auth: ClientAuth): Promise<{
enabled: boolean;
providerId: string;
}[]>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<{
enabled: boolean;
providerId: string;
}[]>
getRulesStatus()
function getRulesStatus(db: ClientDb | ClientRtdb, service?: "firestore" | "database"): Promise<unknown>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
service? | "firestore" | "database" |
Returns
Promise<unknown>
getSnapshot()
function getSnapshot(db: ClientDb): Promise<SandboxSnapshot>;
Export the current sandbox snapshot (Pyric Studio rules re-run). Studio forks it locally to test a denied op against edited rules or re-issue it as the attempting user, on a throwaway branch (no live mutation).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<SandboxSnapshot>
getStorage()
function getStorage(
source: string | ClientDb | URL,
name?: string,
bucketUrl?: string): ClientFirebaseStorage;
Get the worker-backed Storage handle. Like getAuth, accepts an existing
ClientDb (reusing its port) or a worker URL (standalone).
Parameters
| Parameter | Type |
|---|---|
source | string | ClientDb | URL |
name? | string |
bucketUrl? | string |
Returns
getWorkerInstanceId()
function getWorkerInstanceId(db: ClientDb): Promise<string>;
Ask the worker for its stable per-instance id (see host INSTANCE_ID_KEY).
Studio renders a human-friendly form so a user can tell which sandbox instance
they’re looking at — the same localhost:<port> in a different browser profile
is a SEPARATE sandbox (a separate SharedWorker + IndexedDB), and this is how
the two are told apart.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string>
getWorkerVersion()
function getWorkerVersion(db: ClientDb, options?: {
timeoutMs?: number;
}): Promise<string>;
Ask the worker for its baked build version (staleness guard). The page compares it to the served bundle version and warns when a still-running OLD worker is older than what’s served (a SharedWorker can’t hot-update).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
options? | { timeoutMs?: number; } |
options.timeoutMs? | number |
Returns
Promise<string>
importWorkerState()
function importWorkerState(db: ClientDb, bundle: string): Promise<void>;
Phase 2 (clobber): replace this sandbox’s ENTIRE state with bundle.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
bundle | string |
Returns
Promise<void>
increment()
function increment(n: number): SentinelMarker;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
SentinelMarker
limit()
function limit(n: number): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
QueryConstraintHandle
limitToLast()
function limitToLast(n: number): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
n | number |
Returns
QueryConstraintHandle
listAll()
function listAll(reference: ClientStorageReference): Promise<{
items: ClientStorageReference[];
prefixes: ClientStorageReference[];
}>;
Enumerate immediate child items + sub-prefixes under a ref (Pyric Studio
data browse). The host enforces read rules on the scanned prefix.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
Returns
Promise<{
items: ClientStorageReference[];
prefixes: ClientStorageReference[];
}>
listRootCollections()
function listRootCollections(db: ClientDb): Promise<string[]>;
Enumerate root collection ids (Pyric Studio data browse). The modular SDK has
no client listCollections, so the host scans the sandbox keyspace and
returns the ids. Lens is attached (via dataRpc) but the host enumeration is
lens-independent.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string[]>
listSubcollections()
function listSubcollections(db: ClientDb, docPath: string): Promise<string[]>;
Enumerate subcollection ids under a document path (Pyric Studio data browse).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
docPath | string |
Returns
Promise<string[]>
listUsers()
function listUsers(auth: ClientAuth): Promise<AuthUserRecord[]>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<AuthUserRecord[]>
listWorkerBranches()
function listWorkerBranches(db: ClientDb): Promise<string[]>;
Phase 3: list this instance’s saved branch names.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<string[]>
mintPresenceClientId()
function mintPresenceClientId(): string;
Mint a random client id (page-lifetime).
Returns
string
onAuthStateChanged()
function onAuthStateChanged(auth: ClientAuth, callback: (user: ClientUser) => void): Unsubscribe;
Subscribe to auth-state changes. Mirrors firebase/auth’s
onAuthStateChanged. Fires immediately with THIS PORT’s current session,
then on every change to it (#754: sessions are per-port — another tab’s
sign-in is a different user, not an update to this one). Updates the
handle’s currentUser mirror before invoking the callback.
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
callback | (user: ClientUser) => void |
Returns
onIdTokenChanged()
function onIdTokenChanged(auth: ClientAuth, callback: (user: ClientUser) => void): Unsubscribe;
Subscribe to ID-token changes. Mirrors firebase/auth’s
onIdTokenChanged — fires on THIS PORT’s identity transitions (per-port
sessions, #754).
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
callback | (user: ClientUser) => void |
Returns
onSnapshot()
function onSnapshot(
target:
| DocRefHandle
| CollRefHandle
| QueryHandle,
callback: (snap:
| ClientDocSnapshot
| ClientQuerySnapshot) => void,
errorCallback?: (err: unknown) => void): Unsubscribe;
Subscribe to a document or query. Mirrors pyric/firestore’s onSnapshot.
Returns an unsub function. Sends { t:'unsub', subId } to the worker
to deregister the listener on the worker side.
Parameters
| Parameter | Type |
|---|---|
target | | DocRefHandle | CollRefHandle | QueryHandle |
callback | (snap: | ClientDocSnapshot | ClientQuerySnapshot) => void |
errorCallback? | (err: unknown) => void |
Returns
onWorkerRuntimeReload()
function onWorkerRuntimeReload(listener: (epoch: string) => void): () => void;
Observe the worker’s all-pages reload signal.
Parameters
| Parameter | Type |
|---|---|
listener | (epoch: string) => void |
Returns
(): void;
Returns
void
or()
function or(...filters: QueryConstraintHandle[]): QueryConstraintHandle;
OR composite filter — at least one operand must match. Operands must be
filters (where(), or nested or()/and()). Mirrors pyric/firestore’s
or(...); the worker rebuilds it with the real modular factory.
Parameters
| Parameter | Type |
|---|---|
…filters | QueryConstraintHandle[] |
Returns
QueryConstraintHandle
orderBy()
function orderBy(field: string, direction?: "asc" | "desc"): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
field | string |
direction? | "asc" | "desc" |
Returns
QueryConstraintHandle
ownClientUntilPagehide()
function ownClientUntilPagehide(
client: ClientDb,
events?: PagehideEvents,
disconnectClientImpl?: Disconnect): {
disconnect: Promise<void>;
dispose: void;
};
Own a worker port until its page permanently leaves.
Parameters
| Parameter | Type |
|---|---|
client | ClientDb |
events? | PagehideEvents |
disconnectClientImpl? | Disconnect |
Returns
{
disconnect: Promise<void>;
dispose: void;
}
disconnect()
disconnect(): Promise<void>;
Returns
Promise<void>
dispose()
dispose(): void;
Returns
void
preflightWorkerEpochStorage()
function preflightWorkerEpochStorage(storage: EpochStorage): void;
Prove origin storage works without publishing a successor generation.
Parameters
| Parameter | Type |
|---|---|
storage | EpochStorage |
Returns
void
query()
function query(source: CollRefHandle | QueryHandle, ...constraints: QueryConstraintHandle[]): QueryHandle;
Apply query constraints to a source ref or query.
Mirrors pyric/firestore’s query(source, ...constraints).
Parameters
| Parameter | Type |
|---|---|
source | CollRefHandle | QueryHandle |
…constraints | QueryConstraintHandle[] |
Returns
readPyricRuntimeManifest()
function readPyricRuntimeManifest(documentLike?: RuntimeDocument): PyricRuntimeManifest;
Read the server-stamped worker epoch before application code starts.
Parameters
| Parameter | Type |
|---|---|
documentLike? | RuntimeDocument |
Returns
ref()
function ref(parent:
| ClientFirebaseStorage
| ClientStorageReference, path?: string): ClientStorageReference;
Build a Storage reference. Mirrors pyric/storage’s ref(storage, path?) /
ref(parentRef, path). Client-side path math; no RPC.
Parameters
| Parameter | Type |
|---|---|
parent | | ClientFirebaseStorage | ClientStorageReference |
path? | string |
Returns
relayWorkerOp()
function relayWorkerOp(db: ClientDb, op: WorkerOpPayload): Promise<unknown>;
Relay one raw worker-protocol op into the SharedWorker. op is the op
message minus t/id (the WorkerOpPayload wire shape); resolves with
the worker’s res.value, rejects with an Error carrying .code.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
op | WorkerOpPayload |
Returns
Promise<unknown>
relayWorkerSub()
function relayWorkerSub(
db: ClientDb,
sub: WorkerSubPayload,
onValue: (value: unknown) => void): () => void;
Relay a raw worker-protocol subscription into the SharedWorker. sub is
the sub message minus t/subId (the WorkerSubPayload wire shape).
onValue receives every snap value VERBATIM — including the worker host’s
{ __error: { code, message } } establishment-failure convention (listener
errors are re-wrapped into the same shape so the far side sees one form).
Returns the unsubscribe function.
The unified event stream (target: 'events') is NOT relayable yet — its
history batches aren’t coalescible, so it needs bounded backpressure first
(slice 2).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
sub | WorkerSubPayload |
onValue | (value: unknown) => void |
Returns
(): void;
Returns
void
rememberWorkerEpoch()
function rememberWorkerEpoch(epoch: string, storage: EpochStorage): void;
Persist the generation boundary before a page reloads.
Parameters
| Parameter | Type |
|---|---|
epoch | string |
storage | EpochStorage |
Returns
void
resetAll()
function resetAll(db: ClientDb): Promise<{
errors: string[];
}>;
Sandbox-owned full reset (issue #359): sandbox.resetAll() on the worker.
Clears the Firestore env, the signed-in session, and EVERY registered
persistable service — auth users, the RTDB tree, storage objects. Resolves
once the worker acks (all services finished clearing). This is the served
counterpart of calling sandbox.resetAll() on an in-process sandbox.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
Returns
Promise<{
errors: string[];
}>
retireWorkerRuntime()
function retireWorkerRuntime(
db: ClientDb,
targetEpoch: string,
options?: {
timeoutMs?: number;
}): Promise<void>;
Ask the current SharedWorker to drain accepted work and retire.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
targetEpoch | string |
options? | { timeoutMs?: number; } |
options.timeoutMs? | number |
Returns
Promise<void>
rtdbChild()
function rtdbChild(parent: RtdbRefHandle, path: string): RtdbRefHandle;
Parameters
| Parameter | Type |
|---|---|
parent | RtdbRefHandle |
path | string |
Returns
rtdbConnectDatabaseEmulator()
function rtdbConnectDatabaseEmulator(): void;
Returns
void
rtdbGet()
function rtdbGet(target: RtdbTarget): Promise<RtdbDataSnapshot>;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
Returns
Promise<RtdbDataSnapshot>
rtdbGetDatabase()
function rtdbGetDatabase(source?: string | ClientDb | URL, name?: string): ClientRtdb;
Parameters
| Parameter | Type |
|---|---|
source? | string | ClientDb | URL |
name? | string |
Returns
rtdbGoOffline()
function rtdbGoOffline(db: ClientRtdb): void;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
Returns
void
rtdbGoOnline()
function rtdbGoOnline(db: ClientRtdb): void;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
Returns
void
rtdbOff()
function rtdbOff(
target: RtdbTarget,
eventType?: RtdbEventType,
callback?: object): void;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
eventType? | RtdbEventType |
callback? | object |
Returns
void
rtdbOnChildAdded()
function rtdbOnChildAdded(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildChanged()
function rtdbOnChildChanged(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildMoved()
function rtdbOnChildMoved(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnChildRemoved()
function rtdbOnChildRemoved(
target: RtdbTarget,
next: ChildCallback,
cancel?: CancelOrOptions,
options?: ListenOptions,
identity?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | ChildCallback |
cancel? | CancelOrOptions |
options? | ListenOptions |
identity? | object |
Returns
rtdbOnDisconnect()
function rtdbOnDisconnect(ref: RtdbRefHandle): RtdbOnDisconnect;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
Returns
rtdbOnValue()
function rtdbOnValue(
target: RtdbTarget,
next: (snap: RtdbDataSnapshot) => void,
cancelCallbackOrOptions?:
| (err: unknown) => void
| {
onlyOnce?: boolean;
},
options?: {
onlyOnce?: boolean;
},
registryCallback?: object): Unsubscribe;
Parameters
| Parameter | Type |
|---|---|
target | RtdbTarget |
next | (snap: RtdbDataSnapshot) => void |
cancelCallbackOrOptions? | | (err: unknown) => void | { onlyOnce?: boolean; } |
options? | { onlyOnce?: boolean; } |
options.onlyOnce? | boolean |
registryCallback? | object |
Returns
rtdbPush()
function rtdbPush(ref: RtdbRefHandle, value?: unknown): RtdbRefHandle & PromiseLike<RtdbRefHandle>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value? | unknown |
Returns
RtdbRefHandle & PromiseLike<RtdbRefHandle>
rtdbRef()
function rtdbRef(db: ClientRtdb, path?: string): RtdbRefHandle;
Parameters
| Parameter | Type |
|---|---|
db | ClientRtdb |
path? | string |
Returns
rtdbRemove()
function rtdbRemove(ref: RtdbRefHandle): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
Returns
Promise<void>
rtdbRunTransaction()
function rtdbRunTransaction<T>(
ref: RtdbRefHandle,
transactionUpdate: (current: T) => T,
options?: RtdbTransactionOptions): Promise<RtdbTransactionResult>;
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
transactionUpdate | (current: T) => T |
options? | RtdbTransactionOptions |
Returns
Promise<RtdbTransactionResult>
rtdbServerTimestamp()
function rtdbServerTimestamp(): {
};
RTDB environment controls and server-value construction for served apps.
Returns
{
}
rtdbSet()
function rtdbSet(ref: RtdbRefHandle, value: unknown): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value | unknown |
Returns
Promise<void>
rtdbSetPriority()
function rtdbSetPriority(ref: RtdbRefHandle, priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
priority | string | number |
Returns
Promise<void>
rtdbSetWithPriority()
function rtdbSetWithPriority(
ref: RtdbRefHandle,
value: unknown,
priority: string | number): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
value | unknown |
priority | string | number |
Returns
Promise<void>
rtdbUpdate()
function rtdbUpdate(ref: RtdbRefHandle, values: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | RtdbRefHandle |
values | Record<string, unknown> |
Returns
Promise<void>
runTransaction()
function runTransaction<R>(db: ClientDb, updateFn: (txn: ClientTransaction) => R | Promise<R>): Promise<R>;
Run a transaction. Mirrors pyric/firestore’s runTransaction(db, fn).
MULTI-TAB CORRECTNESS — READ-SET VALIDATION + RETRY
A transaction spans two messages: the txn.get RPC (read) and the
txnCommit RPC (commit). Between those two messages another tab may
write to a doc the current tab read — a silent lost update without
validation. We fix this the standard way:
- Each
txn.get(ref)records{ path, data }in a per-attempt read-set (datais the rawSerializedDocDatathe worker returned, ornullif the doc was missing). txnCommitcarries bothreads(the read-set) andwrites.- The worker re-reads each doc inside a sandbox transaction, re-
serializes it the same way, and compares the JSON strings.
Any mismatch →
{ ok: false, error: { code: 'aborted' } }. - On
aborted, the client discards the result ofupdateFnand re-runs it with a fresh transaction object (fresh reads, empty write buffer). Up toTXN_MAX_ATTEMPTSattempts are made. - After the cap, throws an error with
.code === 'aborted'.
This matches real Firestore’s behaviour: the SDK retries updateFn
on conflict rather than surfacing the error immediately.
Type Parameters
| Type Parameter |
|---|
R |
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
updateFn | (txn: ClientTransaction) => R | Promise<R> |
Returns
Promise<R>
saveWorkerBranch()
function saveWorkerBranch(db: ClientDb, name: string): Promise<void>;
Phase 3: save the live sandbox as a named branch (a saved state bundle).
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
Returns
Promise<void>
serverTimestamp()
function serverTimestamp(): SentinelMarker;
Returns
SentinelMarker
setDatabaseRules()
function setDatabaseRules(db: ClientDb | ClientRtdb, source: unknown): Promise<{
messages: unknown[];
ok: boolean;
}>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb | ClientRtdb |
source | unknown |
Returns
Promise<{
messages: unknown[];
ok: boolean;
}>
setDoc()
function setDoc(
ref: DocRefHandle,
data: Record<string, unknown>,
options?: {
merge?: boolean;
mergeFields?: string[];
}): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
options? | { merge?: boolean; mergeFields?: string[]; } |
options.merge? | boolean |
options.mergeFields? | string[] |
Returns
Promise<void>
setFirestoreRules()
function setFirestoreRules(db: ClientDb, source: string): Promise<{
messages: unknown[];
ok: boolean;
warnings: unknown[];
}>;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
source | string |
Returns
Promise<{
messages: unknown[];
ok: boolean;
warnings: unknown[];
}>
setLens()
function setLens(lens: AuthLens): void;
Set the default auth lens applied to subsequent Firestore DATA ops from this
client (Pyric Studio). Pass { mode: 'as', uid } to read/write AS a user
(rules apply), { mode: 'admin' } for the admin lens, or
{ mode: 'app-session' } / undefined to revert to the app’s own session.
The lens is process-wide for this client module (one served page = one worker port), mirroring how Studio drives a single active identity at a time. Auth ops are unaffected — they always operate the real session.
Parameters
| Parameter | Type |
|---|---|
lens | AuthLens |
Returns
void
setOpIssuer()
function setOpIssuer(source: "studio"): void;
Declare who issues the ops this client module constructs. See _opIssuer.
Parameters
| Parameter | Type |
|---|---|
source | "studio" |
Returns
void
setPersistence()
function setPersistence(auth: ClientAuth, persistence: ClientPersistence): Promise<void>;
Record the session-persistence mode on the worker (surface parity). The effective persistence is CLIENT-side (#754): the entry adapter mirrors the mode into the page’s SessionStore, which decides where — or whether — this tab’s session uid is stored for reload restore.
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
persistence | ClientPersistence |
Returns
Promise<void>
setProviderConfig()
function setProviderConfig(
auth: ClientAuth,
providerId: string,
enabled: boolean): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
providerId | string |
enabled | boolean |
Returns
Promise<void>
setRules()
function setRules(db: ClientDb, source: string): Promise<{
warnings: unknown[];
}>;
Deploy new rules to the worker’s sandbox. Active onSnapshot listeners that were allowed by the old rules may start receiving error callbacks if the new rules deny them.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
source | string |
Returns
Promise<{
warnings: unknown[];
}>
signInAnonymously()
function signInAnonymously(auth: ClientAuth): Promise<ClientUserCredential>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<ClientUserCredential>
signInWithEmailAndPassword()
function signInWithEmailAndPassword(
auth: ClientAuth,
email: string,
password: string): Promise<ClientUserCredential>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
email | string |
password | string |
Returns
Promise<ClientUserCredential>
signOut()
function signOut(auth: ClientAuth): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
auth | ClientAuth |
Returns
Promise<void>
startAfter()
function startAfter(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
startAt()
function startAt(...values: unknown[]): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
…values | unknown[] |
Returns
QueryConstraintHandle
startPresence()
function startPresence(opts: StartPresenceOptions): PresenceSession;
Register this page with the worker and keep the lease alive until
PresenceSession.stop or pagehide.
Parameters
| Parameter | Type |
|---|---|
opts | StartPresenceOptions |
Returns
subscribeEvents()
function subscribeEvents(db: ClientDb, callback: (events: readonly SandboxEvent[]) => void): Unsubscribe;
Subscribe to the worker sandbox’s unified event stream. The callback fires
with each delivered BATCH of events — the FIRST call carries the initial
history() snapshot (possibly empty), each subsequent call carries one live
event. Returns an unsubscribe that deregisters on the worker.
This is the live counterpart to sandbox.onEvent + an initial history()
fold, collapsed into one subscription so a late subscriber never misses the
backlog.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
callback | (events: readonly SandboxEvent[]) => void |
Returns
subscribePresence()
function subscribePresence(db: ClientDb, callback: (snapshot: PresenceSnapshot) => void): Unsubscribe;
Subscribe to the worker’s authoritative presence snapshot. The callback fires immediately with the current snapshot, then on every change.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
callback | (snapshot: PresenceSnapshot) => void |
Returns
sum()
function sum(field: string): AggregateFieldDescriptor;
Factory: sum-of-field aggregate. Mirrors pyric/firestore’s sum().
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
AggregateFieldDescriptor
switchWorkerBranch()
function switchWorkerBranch(db: ClientDb, name: string): Promise<void>;
Phase 3 (clobber): switch the live sandbox to a named branch’s state.
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |
name | string |
Returns
Promise<void>
updateDoc()
function updateDoc(ref: DocRefHandle, data: Record<string, unknown>): Promise<void>;
Parameters
| Parameter | Type |
|---|---|
ref | DocRefHandle |
data | Record<string, unknown> |
Returns
Promise<void>
uploadBytes()
function uploadBytes(
reference: ClientStorageReference,
data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
metadata?: ClientSettableMetadata): Promise<{
metadata: FullMetadata;
ref: ClientStorageReference;
}>;
Upload bytes at the reference’s path (replaces existing content).
Mirrors pyric/storage’s uploadBytes result shape.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
data | ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob |
metadata? | ClientSettableMetadata |
Returns
Promise<{
metadata: FullMetadata;
ref: ClientStorageReference;
}>
uploadBytesResumable()
function uploadBytesResumable(
reference: ClientStorageReference,
data: ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob,
metadata?: ClientSettableMetadata): ClientUploadTask;
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
data | ArrayBuffer | Uint8Array<ArrayBufferLike> | Blob |
metadata? | ClientSettableMetadata |
Returns
uploadString()
function uploadString(
reference: ClientStorageReference,
value: string,
format?: StringFormat,
metadata?: ClientSettableMetadata): Promise<{
metadata: FullMetadata;
ref: ClientStorageReference;
}>;
Upload string payload at the reference’s path.
Mirrors pyric/storage’s uploadString result shape.
Parameters
| Parameter | Type |
|---|---|
reference | ClientStorageReference |
value | string |
format? | StringFormat |
metadata? | ClientSettableMetadata |
Returns
Promise<{
metadata: FullMetadata;
ref: ClientStorageReference;
}>
where()
function where(
field: string,
op: string,
value: unknown): QueryConstraintHandle;
Parameters
| Parameter | Type |
|---|---|
field | string |
op | string |
value | unknown |
Returns
QueryConstraintHandle
workerNameForEpoch()
function workerNameForEpoch(servedEpoch: string, storage: EpochStorage): string;
Select the origin’s active worker generation.
A browser that predates generation-aware workers has no stored epoch but may
still have the legacy pyric-shared-worker alive. Seed the first served
epoch before connecting so a new client never attaches to that incompatible
worker. Later releases keep using the stored generation until replacement
is explicitly committed.
Parameters
| Parameter | Type |
|---|---|
servedEpoch | string |
storage | EpochStorage |
Returns
string
writeBatch()
function writeBatch(db: ClientDb): ClientWriteBatch;
Parameters
| Parameter | Type |
|---|---|
db | ClientDb |