Pyric
Navigate

API reference

pyric/firestore

174 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

AbstractUserDataWriter

Constructors

Constructor
new AbstractUserDataWriter(): AbstractUserDataWriter;
Returns

AbstractUserDataWriter


AggregateField

Constructors

Constructor
new AggregateField(): AggregateField;
Returns

AggregateField

Properties

PropertyModifierType
field?readonlystring
kindreadonlyAggregateFieldType

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


AggregateQuerySnapshot

Type Parameters

Type ParameterDefault type
T extends Record<string, number | null>Record<string, number | null>

Constructors

Constructor
new AggregateQuerySnapshot<T>(): AggregateQuerySnapshot<T>;
Returns

AggregateQuerySnapshot<T>

Methods

data()
data(): T;
Returns

T

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


Bytes

Methods

isEqual()
isEqual(other: Bytes): boolean;
Parameters
ParameterType
otherBytes
Returns

boolean

toBase64()
toBase64(): string;
Returns

string

toJSON()
toJSON(): object;
Returns

object

toString()
toString(): string;
Returns

string

toUint8Array()
toUint8Array(): Uint8Array;
Returns

Uint8Array

fromBase64String()
static fromBase64String(base64: string): Bytes;
Parameters
ParameterType
base64string
Returns

Bytes

fromJSON()
static fromJSON(json: object): Bytes;
Parameters
ParameterType
jsonobject
Returns

Bytes

fromUint8Array()
static fromUint8Array(array: Uint8Array): Bytes;
Parameters
ParameterType
arrayUint8Array
Returns

Bytes


CollectionReference

Type Parameters

Type ParameterDefault type
_TDocumentData

Constructors

Constructor
new CollectionReference<_T>(): CollectionReference<_T>;
Returns

CollectionReference<_T>

Properties

PropertyModifierType
idreadonlystring
pathreadonlystring

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


DocumentReference

Type Parameters

Type ParameterDefault type
_TDocumentData

Constructors

Constructor
new DocumentReference<_T>(): DocumentReference<_T>;
Returns

DocumentReference<_T>

Properties

PropertyModifierType
idreadonlystring
pathreadonlystring

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


DocumentSnapshot

Extended by

Type Parameters

Type ParameterDefault type
TDocumentData

Constructors

Constructor
new DocumentSnapshot<T>(): DocumentSnapshot<T>;
Returns

DocumentSnapshot<T>

Properties

PropertyModifierType
existsreadonlyboolean | () => boolean
idreadonlystring
metadatareadonlySnapshotMetadata
refreadonlyDocumentReference<T>

Methods

data()
data(): T;
Returns

T

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


FieldPath

Constructors

Constructor
new FieldPath(...fieldNames: string[]): FieldPath;
Parameters
ParameterType
fieldNamesstring[]
Returns

FieldPath

Methods

isEqual()
isEqual(other: FieldPath): boolean;
Parameters
ParameterType
otherFieldPath
Returns

boolean


FieldValue

Constructors

Constructor
new FieldValue(): FieldValue;
Returns

FieldValue

Methods

arrayRemove()
static arrayRemove(...values: unknown[]): FieldValueSentinel;
Parameters
ParameterType
valuesunknown[]
Returns

FieldValueSentinel

arrayUnion()
static arrayUnion(...values: unknown[]): FieldValueSentinel;
Parameters
ParameterType
valuesunknown[]
Returns

FieldValueSentinel

delete()
static delete(): FieldValueSentinel;
Returns

FieldValueSentinel

increment()
static increment(n: number): FieldValueSentinel;
Parameters
ParameterType
nnumber
Returns

FieldValueSentinel

serverTimestamp()
static serverTimestamp(): FieldValueSentinel;
Returns

FieldValueSentinel


Firestore

Constructors

Constructor
new Firestore(): Firestore;
Returns

Firestore

Properties

PropertyModifierType
[TARGET_SYMBOL]readonlyTarget
app?readonlyFirebaseApp

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


FirestoreError

Extends

  • Error

Constructors

Constructor
new FirestoreError(code: string, message: string): FirestoreError;
Parameters
ParameterType
codestring
messagestring
Returns

FirestoreError

Overrides
Error.constructor

Properties

PropertyModifierType
codereadonlystring

GeoPoint

Constructors

Constructor
new GeoPoint(lat: number, lng: number): GeoPoint;
Parameters
ParameterType
latnumber
lngnumber
Returns

GeoPoint

Accessors

latitude
Get Signature
get latitude(): number;
Returns

number

longitude
Get Signature
get longitude(): number;
Returns

number

Methods

isEqual()
isEqual(other: GeoPoint): boolean;
Parameters
ParameterType
otherGeoPoint
Returns

boolean

toJSON()
toJSON(): {
  latitude: number;
  longitude: number;
  type: string;
};
Returns
{
  latitude: number;
  longitude: number;
  type: string;
}
latitude
latitude: number;
longitude
longitude: number;
type
type: string;

fromJSON()
static fromJSON(json: object): GeoPoint;
Parameters
ParameterType
jsonobject
Returns

GeoPoint


LoadBundleTask

Implements

Constructors

Constructor
new LoadBundleTask(promise: Promise<LoadBundleTaskProgress>): LoadBundleTask;
Parameters
ParameterType
promisePromise<LoadBundleTaskProgress>
Returns

LoadBundleTask

Methods

catch()
catch<TResult>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<LoadBundleTaskProgress | TResult>;
Type Parameters
Type ParameterDefault type
TResultnever
Parameters
ParameterType
onrejected?(reason: any) => TResult | PromiseLike<TResult>
Returns

Promise<LoadBundleTaskProgress | TResult>

onProgress()
onProgress(
   _next?: (progress: LoadBundleTaskProgress) => void,
   _error?: (err: Error) => void,
   _complete?: () => void): void;
Parameters
ParameterType
_next?(progress: LoadBundleTaskProgress) => void
_error?(err: Error) => void
_complete?() => void
Returns

void

then()
then<TResult1, TResult2>(onfulfilled?: (value: LoadBundleTaskProgress) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>;

Attaches callbacks for the resolution and/or rejection of the Promise.

Type Parameters
Type ParameterDefault type
TResult1LoadBundleTaskProgress
TResult2never
Parameters
ParameterTypeDescription
onfulfilled?(value: LoadBundleTaskProgress) => TResult1 | PromiseLike<TResult1>The callback to execute when the Promise is resolved.
onrejected?(reason: any) => TResult2 | PromiseLike<TResult2>The callback to execute when the Promise is rejected.
Returns

Promise<TResult1 | TResult2>

A Promise for the completion of which ever callback is executed.

Implementation of
PromiseLike.then

PersistentCacheIndexManager

Constructors

Constructor
new PersistentCacheIndexManager(_db: Firestore): PersistentCacheIndexManager;
Parameters
ParameterType
_dbFirestore
Returns

PersistentCacheIndexManager

Methods

deleteAllIndexes()
deleteAllIndexes(): Promise<void>;
Returns

Promise<void>

disableIndexAutoCreation()
disableIndexAutoCreation(): Promise<void>;
Returns

Promise<void>

enableIndexAutoCreation()
enableIndexAutoCreation(): Promise<void>;
Returns

Promise<void>


Query

Type Parameters

Type ParameterDefault type
_TDocumentData

Constructors

Constructor
new Query<_T>(): Query<_T>;
Returns

Query<_T>

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


QueryCompositeFilterConstraint

Extends

Constructors

Constructor
new QueryCompositeFilterConstraint(): QueryCompositeFilterConstraint;
Returns

QueryCompositeFilterConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


QueryConstraint

Extended by

Constructors

Constructor
new QueryConstraint(): QueryConstraint;
Returns

QueryConstraint

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


QueryDocumentSnapshot

Extends

Type Parameters

Type ParameterDefault type
TDocumentData

Constructors

Constructor
new QueryDocumentSnapshot<T>(): QueryDocumentSnapshot<T>;
Returns

QueryDocumentSnapshot<T>

Inherited from

DocumentSnapshot.constructor

Properties

PropertyModifierType
existsreadonlyboolean | () => boolean
idreadonlystring
metadatareadonlySnapshotMetadata
refreadonlyDocumentReference<T>

Methods

data()
data(): T;
Returns

T

Overrides

DocumentSnapshot.data

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Inherited from

DocumentSnapshot.[hasInstance]


QueryEndAtConstraint

Extends

Constructors

Constructor
new QueryEndAtConstraint(): QueryEndAtConstraint;
Returns

QueryEndAtConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


QueryFieldFilterConstraint

Extends

Constructors

Constructor
new QueryFieldFilterConstraint(): QueryFieldFilterConstraint;
Returns

QueryFieldFilterConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


QueryLimitConstraint

Extends

Constructors

Constructor
new QueryLimitConstraint(): QueryLimitConstraint;
Returns

QueryLimitConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


QueryOrderByConstraint

Extends

Constructors

Constructor
new QueryOrderByConstraint(): QueryOrderByConstraint;
Returns

QueryOrderByConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


QuerySnapshot

Type Parameters

Type ParameterDefault type
TDocumentData

Constructors

Constructor
new QuerySnapshot<T>(): QuerySnapshot<T>;
Returns

QuerySnapshot<T>

Properties

PropertyModifierType
docsreadonlyreadonly QueryDocumentSnapshot<T>[]
emptyreadonlyboolean
metadatareadonlySnapshotMetadata
sizereadonlynumber

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


QueryStartAtConstraint

Extends

Constructors

Constructor
new QueryStartAtConstraint(): QueryStartAtConstraint;
Returns

QueryStartAtConstraint

Inherited from

QueryConstraint.constructor

Properties

PropertyModifierType
type?readonlystring

Methods

applySandbox()
applySandbox(q: Query): Query;
Parameters
ParameterType
qQuery
Returns

Query

Inherited from

QueryConstraint.applySandbox

prepareSandbox()?
optional prepareSandbox(owner: object): QueryConstraint;
Parameters
ParameterType
ownerobject
Returns

QueryConstraint

Inherited from

QueryConstraint.prepareSandbox

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Overrides

QueryConstraint.[hasInstance]


SandboxError

Sandbox-layer error. Catch with instanceof SandboxError and switch on code. denialContext is populated for permission-denied only (and only after Slice 4 wires it through).

Two construction forms are supported:

  • Positional: new SandboxError(code, message, denialContext?) — the original signature, kept for backward compatibility with existing internal call sites.
  • Options bag: new SandboxError({ code, message, remediation? }) — used when attaching remediation guidance.

Extends

  • Error

Constructors

Constructor
new SandboxError(
   code: SandboxErrorCode,
   message: string,
   denialContext?: DenialContext): SandboxError;
Parameters
ParameterType
codeSandboxErrorCode
messagestring
denialContext?DenialContext
Returns

SandboxError

Overrides
Error.constructor
Constructor
new SandboxError(options: SandboxErrorOptions): SandboxError;
Parameters
ParameterType
optionsSandboxErrorOptions
Returns

SandboxError

Overrides
Error.constructor

Properties

PropertyModifierType
codereadonlySandboxErrorCode
denialContext?readonlyDenialContext
remediation?readonlystring

SnapshotMetadata

Constructors

Constructor
new SnapshotMetadata(): SnapshotMetadata;
Returns

SnapshotMetadata

Properties

PropertyModifierType
fromCachereadonlyboolean
hasPendingWritesreadonlyboolean

Methods

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


Timestamp

Constructors

Constructor
new Timestamp(seconds: number, nanoseconds: number): Timestamp;
Parameters
ParameterType
secondsnumber
nanosecondsnumber
Returns

Timestamp

Properties

PropertyModifierType
nanosecondsreadonlynumber
secondsreadonlynumber

Methods

isEqual()
isEqual(other: Timestamp): boolean;

FS-B12 — value equality, mirroring fb.Timestamp.isEqual.

Parameters
ParameterType
otherTimestamp
Returns

boolean

toDate()
toDate(): Date;
Returns

Date

toJSON()
toJSON(): {
  nanoseconds: number;
  seconds: number;
  type: string;
};

FS-B12 — JSON form, mirroring fb.Timestamp.toJSON.

Returns
{
  nanoseconds: number;
  seconds: number;
  type: string;
}
nanoseconds
nanoseconds: number;
seconds
seconds: number;
type
type: string;

toMillis()
toMillis(): number;
Returns

number

toString()
toString(): string;

FS-B12 — textual form, mirroring fb.Timestamp.toString.

Returns

string

valueOf()
valueOf(): string;

FS-B12 — primitive coercion for </<=/>=/> comparisons, mirroring fb.Timestamp.valueOf: a zero-padded <seconds>.<nanoseconds> string (seconds offset by MIN_SECONDS so it stays non-negative and lexically ordered).

Returns

string

fromDate()
static fromDate(d: Date): Timestamp;
Parameters
ParameterType
dDate
Returns

Timestamp

fromMillis()
static fromMillis(ms: number): Timestamp;
Parameters
ParameterType
msnumber
Returns

Timestamp

now()
static now(): Timestamp;
Returns

Timestamp


Transaction

Extends

Constructors

Constructor
new Transaction(): Transaction;
Returns

Transaction

Inherited from
ChainTransaction.constructor

Methods

delete()
delete(ref: DocumentReference): Transaction;
Parameters
ParameterType
refDocumentReference
Returns

Transaction

Inherited from

Transaction.delete

get()
Call Signature
get(ref: DocumentReference): Promise<AdminDocumentSnapshot>;
Parameters
ParameterType
refDocumentReference
Returns

Promise<AdminDocumentSnapshot>

Inherited from

Transaction.get

Call Signature
get(query: Query): Promise<AdminQuerySnapshot>;
Parameters
ParameterType
queryQuery
Returns

Promise<AdminQuerySnapshot>

Inherited from

Transaction.get

set()
set(ref: DocumentReference, data: DocumentData): Transaction;
Parameters
ParameterType
refDocumentReference
dataDocumentData
Returns

Transaction

Inherited from

Transaction.set

update()
update(ref: DocumentReference, data: DocumentData): Transaction;
Parameters
ParameterType
refDocumentReference
dataDocumentData
Returns

Transaction

Inherited from

Transaction.update

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean


VectorValue

Methods

isEqual()
isEqual(other: VectorValue): boolean;
Parameters
ParameterType
otherVectorValue
Returns

boolean

toArray()
toArray(): number[];
Returns

number[]

toJSON()
toJSON(): object;
Returns

object

create()
static create(values: number[]): VectorValue;
Parameters
ParameterType
valuesnumber[]
Returns

VectorValue

fromJSON()
static fromJSON(json: object): VectorValue;
Parameters
ParameterType
jsonobject
Returns

VectorValue


WriteBatch

Extends

Constructors

Constructor
new WriteBatch(): WriteBatch;
Returns

WriteBatch

Inherited from
ChainWriteBatch.constructor

Methods

commit()
commit(opts?: OperationOptions): Promise<void>;
Parameters
ParameterType
opts?OperationOptions
Returns

Promise<void>

Inherited from

WriteBatch.commit

delete()
delete(ref: DocumentReference): WriteBatch;
Parameters
ParameterType
refDocumentReference
Returns

WriteBatch

Inherited from

WriteBatch.delete

set()
set(ref: DocumentReference, data: DocumentData): WriteBatch;
Parameters
ParameterType
refDocumentReference
dataDocumentData
Returns

WriteBatch

Inherited from

WriteBatch.set

update()
update(ref: DocumentReference, data: DocumentData): WriteBatch;
Parameters
ParameterType
refDocumentReference
dataDocumentData
Returns

WriteBatch

Inherited from

WriteBatch.update

[hasInstance]()
static hasInstance: boolean;
Parameters
ParameterType
instanceunknown
Returns

boolean

Interfaces

DocumentChange

Type Parameters

Type ParameterDefault type
TDocumentData

Properties

PropertyModifierType
docreadonlyQueryDocumentSnapshot<T>
newIndexreadonlynumber
oldIndexreadonlynumber
typereadonlyDocumentChangeType

EmulatorMockTokenOptions

Properties

PropertyType
mockUserToken?string | Record<string, unknown>

ExperimentalLongPollingOptions

Properties

PropertyType
forceLongPolling?boolean

FirestoreDataConverter

Pair of translators between the consumer’s app model and the underlying Firestore representation. Mirrors firebase/firestore’s FirestoreDataConverter shape.

  • toFirestore(model) runs on every write (setDoc, addDoc) through a converted ref. Returns the DocumentData to send.
  • fromFirestore(snapshot) runs on every read (getDoc, getDocs, snapshot listener callback) through a converted ref. Receives the raw snapshot, returns the typed model.

Type Parameters

Type ParameterDefault type
AppModelType-
DbModelType extends DocumentDataDocumentData

Methods

fromFirestore()
fromFirestore(snapshot: QueryDocumentSnapshot<DbModelType>): AppModelType;
Parameters
ParameterType
snapshotQueryDocumentSnapshot<DbModelType>
Returns

AppModelType

toFirestore()
toFirestore(modelObject: AppModelType): DbModelType;
Parameters
ParameterType
modelObjectAppModelType
Returns

DbModelType


FirestoreDataToolDeps

Methods

resolveDb()
resolveDb(as?: As): Firestore | Promise<Firestore>;

Resolver returning a Firestore handle. Called per-dispatch with the op’s as value: 'admin' (or undefined) → an admin-bypass Firestore; { uid, claims? } → a rules-enforcing Firestore acting as that user.

The host decides the posture; the tool layer does NOT enforce it. A sandbox resolver may default to admin (rules bypass is the point of seeding), but a resolver wired to a real backend should require an explicit identity or confirm-gate admin writes (see the bridge’s prod confirm-policy).

Parameters
ParameterType
as?As
Returns

Firestore | Promise<Firestore>


FirestoreInspectToolDeps

Methods

resolveSandbox()
resolveSandbox():
  | LocalSandbox
| Promise<LocalSandbox>;

Resolve the sandbox whose Firestore state should be inspected.

Returns

| LocalSandbox | Promise<LocalSandbox>


FirestoreSettings

Client-cache/network settings initializeFirestore accepts but no-ops on sandbox targets — see the tier-1 section rationale above.

Properties

PropertyType
cacheSizeBytes?number
experimentalAutoDetectLongPolling?boolean
experimentalForceLongPolling?boolean
host?string
ignoreUndefinedProperties?boolean
localCache?LocalCache
ssl?boolean

Index

Properties

PropertyType
collectionGroupstring
fields?IndexField[]

IndexConfiguration

Properties

PropertyType
fieldOverrides?unknown[]
indexes?Index[]

IndexField

Properties

PropertyType
arrayConfig?"contains"
fieldPathstring
order?"ascending" | "descending"

LintResult

Properties

PropertyTypeDescription
metricsRulesMetrics-
parseError?ParseErrorStructured parse failure when the source did not parse. When defined, metrics (except sourceSize) and warnings carry no signal — budget checks were skipped. Callers should branch on parseError before interpreting warnings or metrics. Why this isn’t a new severity value: a parse failure means “this isn’t a rule yet” rather than “this rule will fail at runtime”, which is a categorically different question from anything warnings answers. Adding a new severity would force every consumer to handle a third branch they don’t care about; a separate field lets old code keep working and gives new code a clean signal to check.
warningsLintWarning[]-

LoadBundleTaskProgress

Properties

PropertyModifierType
bytesLoadedreadonlynumber
documentsLoadedreadonlynumber
taskStatereadonlyTaskState
totalBytesreadonlynumber
totalDocumentsreadonlynumber

LocalCache

Opaque local-cache config token accepted by initializeFirestore’s settings.localCache. Inert — see the tier-1 section rationale above.

Properties

PropertyModifierType
[LOCAL_CACHE_SYMBOL]readonly"persistent" | "memory"
garbageCollector?readonlyMemoryGarbageCollector
tabManager?readonlyPersistentTabManager

MemoryCacheSettings

Properties

PropertyType
garbageCollector?MemoryGarbageCollector

MemoryGarbageCollector

Opaque garbage-collector config token. Inert for the same reason — there is no memory cache tier with GC pressure to tune.

Properties

PropertyModifierType
[GC_SYMBOL]readonly"eager" | "lru"

PersistenceSettings

Properties

PropertyType
forceOwnership?boolean

PersistentCacheSettings

Properties

PropertyType
cacheSizeBytes?number
tabManager?PersistentTabManager

PersistentSingleTabManagerSettings

Properties

PropertyType
forceOwnership?boolean

PersistentTabManager

Opaque tab-manager config token. Inert — persistence is always on, and the SharedWorker/pyric dev path already is the one shared store every tab talks to, so there is no separate multi-tab mode to opt into. Carries the requested kind only for debugging.

Properties

PropertyModifierType
[TAB_MANAGER_SYMBOL]readonly"single" | "multiple"

Sandbox

A Firebase sandbox — an isolated environment with one auth identity.

Created via initializeSandbox(config). Use fork({ auth }) to derive a new sandbox with a different identity that shares the underlying environment (rules, data, state). Fork is the only identity-switching mechanism — there are no per-op auth overrides and no in-place mutation.

Extended by

Properties

PropertyModifierTypeDescription
adminreadonlySandboxAdminAdmin-plane access (rule-bypass reads). Identity-agnostic by design — admin reads aren’t gated on auth, so they live on the sandbox, not on a context. See SandboxAdmin.
currentUserpublic{ token?: Record<string, unknown>; uid: string; }Current authenticated user across the sandbox. Mutated by pyric/auth’s signInAnonymously / signInWithEmailAndPassword / signOut / sandbox.setUser. Read per-call by service factories (e.g. a future getFirestore(sandbox) overload) so they see auth state changes without re-binding handles. Defaults to null (anonymous / signed out). Independent of withAuth({uid})withAuth still produces a frozen SandboxContext that carries its own identity for the runner’s test code (the existing pattern: explicit identity per service call). currentUser exists for the pyric/auth mirror, where consumer app code drives identity through a stateful Auth handle rather than naming it per call.
currentUser.token?publicRecord<string, unknown>-
currentUser.uidpublicstring-

Methods

clearPersistence()
clearPersistence(): Promise<void>;

Wipe the persisted blob for this sandbox’s key. In-memory state is left intact — call reset() if you want both. Useful for “sign out and forget” flows.

No-op when persistence is not enabled.

Returns

Promise<void>

dispose()
dispose(): void;

Tear down listener registries on this sandbox’s environment without replacing it. Use this when you’re about to discard the sandbox itself (e.g. runner.reseed() builds a fresh sandbox rather than calling reset()) and want to drop callback references on the outgoing instance defensively. Idempotent. Does not touch data.

Returns

void

enablePersistence()
enablePersistence(options: SandboxPersistenceOptions): Promise<void>;

Persist the sandbox’s data to a backend and restore it on next enablePersistence call. The default 'indexedDB' backend turns the sandbox into the host page’s local Firestore — writes flush automatically and a fresh initializeSandbox() rehydrates from the prior session.

Restoration happens before the promise resolves; awaiting this call is sufficient to guarantee in-memory state matches the persisted blob.

Idempotent across the same key — calling twice in one process is a no-op on the second call. Different keys are rejected as an error (a sandbox can persist to at most one backend at a time).

Listener semantics: every write event the sandbox emits triggers a debounced flush (default 250ms). Browser hosts additionally flush on beforeunload so a page navigation doesn’t lose the tail of the debounce window.

See SandboxPersistenceOptions for backend selection and tuning.

Parameters
ParameterType
optionsSandboxPersistenceOptions
Returns

Promise<void>

enableTabSync()
enableTabSync(options?: TabSyncOptions): () => void;

Enable cross-tab realtime sync via BroadcastChannel. A write in this tab will propagate to every OTHER tab of the same origin that also called enableTabSync, causing their onSnapshot listeners to re-evaluate — restoring production’s cross-client realtime behavior.

Opt-in, OFF by default. Firestore only (RTDB is a follow-on).

Returns a disable function. Calling it removes the onEvent subscription, the channel message listener, and closes the channel (when it was created internally). After disable, no further propagation occurs in either direction.

Multi-writer note: concurrent writes from two tabs to the same doc produce last-write-wins divergence — there is no conflict resolution. The intended model is one active writer (one user, one tab) with observers in other tabs; this covers the overwhelming majority of local development scenarios.

Parameters
ParameterType
options?TabSyncOptions
Returns
(): void;
Returns

void

See

TabSyncOptions for channel injection (tests) and originId.

Example
// In every tab that should participate in realtime:
const sandbox = initializeSandbox();
const disableSync = sandbox.enableTabSync();
// Later, to stop syncing:
disableSync();

flush()
flush(): Promise<void>;

Force a snapshot to the configured persistence backend right now. Useful before a manual navigation, or in tests that need deterministic ordering against the debounce window. Resolves once the write hits the backend.

Throws if persistence is not enabled.

Returns

Promise<void>

history()
history(): SandboxEvent[];

Every SandboxEvent this sandbox has emitted since init or the last reset(). Returns a defensive copy.

Use this for replay: hand the array to replay(events, rules) from pyric/sandbox and the engine re-issues every captured write against a fresh sandbox.

Unlike onEvent (live stream from the moment of subscribe), history() returns every event the sandbox has seen — useful for consumers that attach late (e.g., loading a saved session before subscribing) or that need a snapshot at a particular moment.

reset() and dispose() each append a closing session_boundary event; reset() then clears the history. Consumers that took a snapshot before reset retain the boundary in their copy.

Returns

SandboxEvent[]

loadSnapshot()
loadSnapshot(data: SandboxSnapshot): void;

CLOBBER-restore the sandbox’s entire state from a prior snapshot: reset() (clears firestore + the signed-in session), then rebuild firestore from data and restore each registered service. This is a TOTAL replace — documents absent from data do NOT survive — and is the counterpart to snapshot. It is what makes “transfer (clobber) one instance’s data into another” and named-branch switching possible.

Fires a session_boundary (reset phase), re-evaluates live listeners against the loaded state, and the next persistence flush writes the loaded state. Services present in data but not currently registered are skipped (a snapshot taken via snapshot always includes every registered service, so this only affects cross-instance imports from a sandbox that had a service this one lacks).

Parameters
ParameterType
dataSandboxSnapshot
Returns

void

onCurrentUserChanged()
onCurrentUserChanged(cb: (user: {
  token?: Record<string, unknown>;
  uid: string;
}) => void): () => void;

Subscribe to currentUser changes. Fires on every mutation — sign-in, sign-out, user swap. Does NOT fire on subscribe.

Survives reset() and dispose() only as a no-op: a disposed sandbox emits nothing further; a reset sandbox clears currentUser to null (and fires the change) before swapping the env.

Returns an unsubscribe function. Listener errors are swallowed — subscribers are observational, the sandbox does not propagate their errors.

Parameters
ParameterType
cb(user: { token?: Record<string, unknown>; uid: string; }) => void
Returns
(): void;
Returns

void

onEvent()
onEvent(cb: (event: SandboxEvent) => void): () => void;

Subscribe to every event the sandbox emits — see SandboxEvent for the discriminated-union shape. One subscription covers request/denial/snapshot-error/listener-lifecycle/session-boundary; filter on event.kind to recover individual streams.

Replaces the prior three-channel surface (onRequest / onDenial / onSnapshotError) — see issue #307. Filter cookbook:

  • All denials: event.kind === 'request' && event.result === 'deny'
  • Stream errors: event.kind === 'listener_errored'
  • Per-op traffic: event.kind === 'request'

Survives sandbox.reset() — the subscription is held on the sandbox, not on the underlying environment. A session_boundary event with phase: 'reset' fires before the env swap so consumers can segment their stream.

Returns an unsubscribe function. Listener errors are swallowed so a faulty subscriber can’t change rule semantics or hide other events. Both synchronous throws and rejected Promises from async callbacks are silently discarded — subscribers are observational, the sandbox doesn’t await them and doesn’t propagate their errors.

Parameters
ParameterType
cb(event: SandboxEvent) => void
Returns
(): void;
Returns

void

registerPersistableService()
registerPersistableService(name: string, hooks: PersistableService): () => void;

Register a service (auth, storage, …) as a persistence participant. The sandbox calls hooks.snapshot() on every flush and hooks.restore(data) on restore. If hooks.subscribe is provided, the persistence controller subscribes and schedules a debounced flush on each change — so auth-user edits flush promptly, not only on the next Firestore write.

Returns an unregister function — call it if the service is torn down before the sandbox is disposed (uncommon in practice; the sandbox’s dispose() clears the registry anyway).

Throws failed-precondition when a service with the same name is already registered — the auth package registers 'auth' once when getAuth(sandbox) first creates a backend, so accidental double- registration is a caller bug, not a no-op.

Advanced / internal API. Service packages (auth, storage) call this when they first attach to a sandbox. Consumer app code should not need to call this directly.

Parameters
ParameterType
namestring
hooksPersistableService
Returns
(): void;
Returns

void

reset()
reset(): void;

Reset the underlying environment to a fresh state — wipes data, rules, and any service-specific configuration.

Snapshot listeners attached to the OLD environment are dropped at the swap — they can’t survive because their target docs have been wiped. onEvent subscribers DO survive — the registry lives on the sandbox, and a session_boundary event with phase: 'reset' fires before the swap so subscribers know the rollover happened. Existing SandboxContexts continue to work — their sandbox reference is stable; subsequent operations resolve to the new env.

Returns

void

resetAll()
resetAll(): Promise<{
  errors: string[];
}>;

Reset the WHOLE sandbox: reset (Firestore env + signed-in session), then clear every registered persistable service that provides a PersistableService.reset hook — auth users, the RTDB tree, storage objects. This is the one sandbox-owned “wipe everything” path: because it iterates the service registry, a new service that registers with a reset hook is cleared automatically, and a consumer (Pyric Studio’s reset) cannot forget one.

Service resets may be async (storage clears IndexedDB stores); the returned promise resolves when every service has finished clearing. A service whose reset throws is isolated (others still clear) and REPORTED in the returned errors (as name: message) — a reset that leaves data behind must never look successful to the caller.

Returns

Promise<{ errors: string[]; }>

runWithProvenance()?
optional runWithProvenance<T>(provenance: EventProvenance, fn: () => T): T;

Run fn with ambient EventProvenance defaults: every event emitted SYNCHRONOUSLY during fn that doesn’t already carry a provenance field (on the event itself or via an explicit per-emit override) is stamped with these values instead of the global defaults. This is the mechanical “who issued this op” seam the serve worker uses to tag Studio-issued ops (actor: { kind: 'studio' }) and to stamp the auth lens an op ran under (authLens) — declared by the caller that issues the op, never inferred from the op’s shape.

SYNCHRONOUS WINDOW: the ambient values apply only until fn returns (for an async fn, its synchronous prefix — which covers the local environment’s rules eval + event emission, since those run before the op’s promise is handed back). Work an op DEFERS (snapshot-listener deliveries and re-evals drain on a microtask, off-stack) is intentionally OUTSIDE the window: a listener re-eval belongs to the listener’s owner, not to whoever’s write triggered it. Nested calls stack — the innermost window wins per field, and each window restores the previous one on exit (including on throw).

OPTIONAL because remote sandbox proxies can’t provide an ambient emit window (events are emitted in the worker they front). Callers spell sandbox.runWithProvenance?.(prov, fn) ?? fn().

Type Parameters
Type Parameter
T
Parameters
ParameterType
provenanceEventProvenance
fn() => T
Returns

T

snapshot()
snapshot(): SandboxSnapshot;

Capture a snapshot of every service’s state. For v1 with only Firestore, the return value carries a firestore key mapping doc paths to data. Future services will add their own keys.

Returns

SandboxSnapshot

withAuth()
withAuth(auth: {
  token?: Record<string, unknown>;
  uid: string;
}): SandboxContext;

Derive a context bound to this sandbox under the given auth identity. Operations through services attached to the returned context evaluate rules under that identity. Many contexts can coexist for one sandbox; data is shared.

null is anonymous; an AuthState object names the user (and optional custom claims). Passing undefined is a deliberate error — say withAuth(null) for anonymous so the call site is unambiguous.

Parameters
ParameterType
auth{ token?: Record<string, unknown>; uid: string; }
auth.token?Record<string, unknown>
auth.uidstring
Returns

SandboxContext

Example
const sandbox = initializeSandbox();
const dbAlice = getFirestore(sandbox.withAuth({ uid: 'alice' }));
const dbAnon  = getFirestore(sandbox.withAuth(null));

SandboxContext

Identity-bearing handle on a Sandbox. A (sandbox, auth, operationContext) tuple — cheap to create, immutable, freely shareable. Service factories require a SandboxContext; bare Sandbox is a type error so every call site states identity explicitly.

Constructed via Sandbox.withAuth(auth) or chained via SandboxContext.withAuth(auth). The concrete class is exported from pyric/sandbox for instanceof routing in service factories; consumers don’t construct it directly.

Properties

PropertyModifierTypeDescription
authreadonly{ token?: Record<string, unknown>; uid: string; }The identity rules evaluate under for operations through this context.
auth.token?publicRecord<string, unknown>-
auth.uidpublicstring-
operationContextreadonlyOperationContextImmutable provenance bound to every operation issued through this handle.
sandboxreadonlySandboxThe data foundation this context operates against.

Methods

withAuth()
withAuth(auth: {
  token?: Record<string, unknown>;
  uid: string;
}): SandboxContext;

Derive a sibling context on the same sandbox with different auth. Replaces auth and its lens while preserving the operation source and optional plan identity.

Parameters
ParameterType
auth{ token?: Record<string, unknown>; uid: string; }
auth.token?Record<string, unknown>
auth.uidstring
Returns

SandboxContext


SetOptions

Modular Web-SDK-shaped SetOptions. Either flag controls how data combines with the existing document; passing nothing replaces the existing doc entirely (Firestore default).

  • { merge: true } — shallow-merge every top-level field in data into the existing document, preserving fields not in data. Equivalent to firebase/firestore’s setDoc(ref, data, { merge: true }).
  • { mergeFields: [...] } — project data to just the listed top-level fields, then merge. Other fields in data are ignored; other fields in the existing doc are preserved.

merge and mergeFields are mutually exclusive; passing both is a programming error (mergeFields wins on the sandbox path, matching the JS SDK’s effective behavior).

Properties

PropertyType
merge?boolean
mergeFields?readonly string[]

SnapshotListenOptions

Properties

PropertyType
includeMetadataChanges?boolean

SnapshotObserver

Type Parameters

Type Parameter
T

Properties

PropertyType
complete?() => void
error?(error: unknown) => void
next?(snapshot: T) => void

SnapshotOptions

Properties

PropertyModifierType
serverTimestamps?readonly"estimate" | "previous" | "none"

TransactionOptions

Options accepted by the modular Web-SDK-shaped runTransaction.

Properties

PropertyType
maxAttempts?number

UserAuth

Properties

PropertyType
claims?Record<string, unknown>
uidstring

Type Aliases

AddPrefixToKeys

type AddPrefixToKeys<Prefix, T> = { [K in keyof T as `${Prefix}.${string & K}`]: T[K] };

Type Parameters

Type Parameter
Prefix extends string
T extends Record<string, unknown>

AggregateFieldType

type AggregateFieldType = "count" | "sum" | "average";

Aggregate-field descriptor returned by count() / sum(field) / average(field).


AggregateSpec

type AggregateSpec = Record<string, AggregateField>;

Spec passed to getAggregateFromServer(query, spec).


AggregateSpecData

type AggregateSpecData<T> = Record<string, unknown>;

Type Parameters

Type Parameter
T

AggregateType

type AggregateType = "count" | "sum" | "average";

AppFirestore

type AppFirestore = Firestore & {
  app: FirebaseApp;
};

Firestore handle returned by Firebase-shaped app overloads.

Type Declaration

app
readonly app: FirebaseApp;

As

type As = "admin" | UserAuth;

Who a data-plane op runs as. The default (omitted, or the literal 'admin') is an ADMIN write that BYPASSES rules — the right mode for sandbox seeding. A { uid, claims? } runs as that user with rules ENFORCED. The point of the explicit literal: bypass is NAMED (as:'admin'), not the silent consequence of omitting an auth field, and acting-as-a-user is named too.


AuthState

type AuthState =
  | {
  token?: Record<string, unknown>;
  uid: string;
}
  | null;

A signed-in identity for sandbox operations. null is anonymous.

token is the Firebase Auth token claims map (custom claims plus standard ones). It surfaces the same way it does in production rules via request.auth.token.*. Omit it for plain UID-only auth.

Renamed from AuthContext (pre-multi-context) so the data type doesn’t visually collide with SandboxContext (the identity-bearing handle). They sit at different layers — payload vs. handle — and the names should reflect that.


ChildUpdateFields

type ChildUpdateFields<T> = Record<string, unknown>;

Type Parameters

Type Parameter
T

DocumentChangeType

type DocumentChangeType = "added" | "removed" | "modified";

DocumentData

type DocumentData = Record<string, unknown>;

FieldValueSentinel

type FieldValueSentinel =
  | {
}
  | {
  value: number;
}
  | {
  values: unknown[];
}
  | {
  values: unknown[];
}
  | {
};

FirestoreErrorCode

type FirestoreErrorCode =
  | "cancelled"
  | "unknown"
  | "invalid-argument"
  | "deadline-exceeded"
  | "not-found"
  | "already-exists"
  | "permission-denied"
  | "resource-exhausted"
  | "failed-precondition"
  | "aborted"
  | "out-of-range"
  | "unimplemented"
  | "internal"
  | "unavailable"
  | "data-loss"
  | "unauthenticated";

FirestoreLocalCache

type FirestoreLocalCache = LocalCache;

ListenSource

type ListenSource = "default" | "cache";

LogLevel

type LogLevel = "debug" | "verbose" | "info" | "warn" | "error" | "silent";

Mirrors firebase/firestore’s LogLevel union.


MemoryEagerGarbageCollector

type MemoryEagerGarbageCollector = MemoryGarbageCollector & {
  [GC_SYMBOL]: "eager";
};

Type Declaration

[GC_SYMBOL]
readonly [GC_SYMBOL]: "eager";

MemoryLocalCache

type MemoryLocalCache = LocalCache & {
  [LOCAL_CACHE_SYMBOL]: "memory";
};

Type Declaration

[LOCAL_CACHE_SYMBOL]
readonly [LOCAL_CACHE_SYMBOL]: "memory";

MemoryLruGarbageCollector

type MemoryLruGarbageCollector = MemoryGarbageCollector & {
  [GC_SYMBOL]: "lru";
};

Type Declaration

[GC_SYMBOL]
readonly [GC_SYMBOL]: "lru";

NestedUpdateFields

type NestedUpdateFields<T> = Record<string, unknown>;

Type Parameters

Type Parameter
T

OrderByDirection

type OrderByDirection = "asc" | "desc";

OrderDirection

type OrderDirection = QueryOrderDirection;

PartialWithFieldValue

type PartialWithFieldValue<T> = Partial<T> | Record<string, unknown>;

Type Parameters

Type Parameter
T

PersistentLocalCache

type PersistentLocalCache = LocalCache & {
  [LOCAL_CACHE_SYMBOL]: "persistent";
};

Type Declaration

[LOCAL_CACHE_SYMBOL]
readonly [LOCAL_CACHE_SYMBOL]: "persistent";

PersistentMultipleTabManager

type PersistentMultipleTabManager = PersistentTabManager & {
  [TAB_MANAGER_SYMBOL]: "multiple";
};

Type Declaration

[TAB_MANAGER_SYMBOL]
readonly [TAB_MANAGER_SYMBOL]: "multiple";

PersistentSingleTabManager

type PersistentSingleTabManager = PersistentTabManager & {
  [TAB_MANAGER_SYMBOL]: "single";
};

Type Declaration

[TAB_MANAGER_SYMBOL]
readonly [TAB_MANAGER_SYMBOL]: "single";

Primitive

type Primitive = string | number | boolean | bigint | symbol | undefined | null;

QueryConstraintType

type QueryConstraintType =
  | "where"
  | "orderBy"
  | "limit"
  | "limitToLast"
  | "startAt"
  | "startAfter"
  | "endAt"
  | "endBefore"
  | "or"
  | "and";

QueryFilterConstraint

type QueryFilterConstraint = any;

QueryNonFilterConstraint

type QueryNonFilterConstraint = any;

TaskState

type TaskState = "Error" | "Running" | "Success";

UnionToIntersection

type UnionToIntersection<U> = U extends any ? (k: U) => void : never extends (k: infer I) => void ? I : never;

Type Parameters

Type Parameter
U

Unsubscribe()

type Unsubscribe = () => void;

Returns

void


UpdateData

type UpdateData<T> = { [path in string]: unknown };

Type Parameters

Type Parameter
T

WhereFilterOp

type WhereFilterOp = QueryWhereFilterOp;

WithFieldValue

type WithFieldValue<T> = T | Record<string, unknown>;

Type Parameters

Type Parameter
T

Variables

CACHE_SIZE_UNLIMITED

const CACHE_SIZE_UNLIMITED: -1 = -1;

TARGET_SYMBOL

const TARGET_SYMBOL: unique symbol;

Hidden property on every Firestore handle. Discriminates the sandbox backend so free functions can recover their owner.

Functions

actingAs()

function actingAs(sandbox: Sandbox, identity: {
  token?: Record<string, unknown>;
  uid: string;
}): Firestore;

A Firestore handle scoped to a specific identity, for multi-user testing.

actingAs(sandbox, { uid }) returns a Firestore whose ops evaluate security rules as that user (request.auth.uid === uid; custom claims via token); actingAs(sandbox, null) is the anonymous (signed-out) path. Multiple identities over ONE sandbox share the same store, so a write by one is delivered to another’s onSnapshot: the basis for multi-user sync testing.

Parameters

ParameterType
sandboxSandbox
identity{ token?: Record<string, unknown>; uid: string; }
identity.token?Record<string, unknown>
identity.uidstring

Returns

Firestore

Example

import { initializeSandbox } from 'pyric/sandbox';
import { actingAs, doc, setDoc, onSnapshot } from 'pyric/firestore';
const sandbox = initializeSandbox();
const alice = actingAs(sandbox, { uid: 'alice' });
const bob   = actingAs(sandbox, { uid: 'bob', token: { role: 'member' } });
onSnapshot(doc(bob, 'rooms/r1'), () => {
  // fires when alice writes (same store; rules evaluated as bob)
});
await setDoc(doc(alice, 'rooms/r1'), { owner: 'alice' });

Thin sugar over getFirestore(sandbox.withAuth(identity)); the value is a named, discoverable seam for multi-user scenarios. See the design rationale.


addDoc()

function addDoc<T>(coll: CollectionReference<T>, data: T): Promise<DocumentReference<T>>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
collCollectionReference<T>
dataT

Returns

Promise<DocumentReference<T>>


aggregateFieldEqual()

function aggregateFieldEqual(a: any, b: any): boolean;

Parameters

ParameterType
aany
bany

Returns

boolean


aggregateQuerySnapshotEqual()

function aggregateQuerySnapshotEqual(a: any, b: any): boolean;

Parameters

ParameterType
aany
bany

Returns

boolean


and()

function and(...filters: QueryConstraint[]): QueryConstraint;

AND composite. Same shape as or() but every inner constraint must match. Useful inside an or() to combine constraints that would otherwise be at the top level.

Parameters

ParameterType
filtersQueryConstraint[]

Returns

QueryConstraint


arrayRemove()

function arrayRemove(...values: unknown[]): FieldValueSentinel;

Parameters

ParameterType
valuesunknown[]

Returns

FieldValueSentinel


arrayUnion()

function arrayUnion(...values: unknown[]): FieldValueSentinel;

Parameters

ParameterType
valuesunknown[]

Returns

FieldValueSentinel


average()

function average(field: string): AggregateField;

Factory: average-of-field aggregate.

Parameters

ParameterType
fieldstring

Returns

AggregateField


clearIndexedDbPersistence()

function clearIndexedDbPersistence(db: Firestore): Promise<void>;

Sandbox: actually clears the sandbox’s persisted store via Sandbox.clearPersistence() — the honest mapping, not a no-op. This wipes the persisted blob (IndexedDB, or whatever backend enablePersistence was configured with) while leaving in-memory state untouched, matching clearPersistence’s own contract. It is ALREADY a no-op when persistence was never enabled, so callers that invoke this defensively at startup are safe either way.

getFirestore(ctx) (frozen SandboxContext) targets don’t carry a live Sandbox handle with a clearPersistence method reachable the same way as a sandbox/sandbox-live target’s .sandbox field — both variants do, in fact, so this always has a sandbox to call into.

The real SDK requires this before Firestore starts; the sandbox’s mapped clearPersistence() has no such restriction.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


collection()

function collection(parent:
  | Firestore
  | DocumentReference<DocumentData>, ...pathSegments: string[]): CollectionReference;

Parameters

ParameterType
parent| Firestore | DocumentReference<DocumentData>
pathSegmentsstring[]

Returns

CollectionReference


collectionGroup()

function collectionGroup(db: Firestore, collectionId: string): Query;

Cross-collection query — scans every document under every collection whose final segment matches collectionId. Mirrors firebase/firestore’s collectionGroup(db, id) shape.

Returned Query accepts the same where / orderBy / limit constraints as any other query.

Parameters

ParameterType
dbFirestore
collectionIdstring

Returns

Query


connectFirestoreEmulator()

function connectFirestoreEmulator(
   db: Firestore,
   host: string,
   port: number,
   options?: {
  mockUserToken?:   | string
     | {
   [claim: string]: unknown;
     firebase?: {
        identities?: Record<string, string[]>;
        sign_in_provider?: string;
     };
     sub?: string;
     user_id?: string;
   };
}): void;

No-op in the sandbox mirror because the sandbox already runs locally.

The option shape remains source-compatible with Firebase so canonical initialization code can call it unconditionally.

Parameters

ParameterType
dbFirestore
hoststring
portnumber
options?{ mockUserToken?: | string | { [claim: string]: unknown; firebase?: { identities?: Record<string, string[]>; sign_in_provider?: string; }; sub?: string; user_id?: string; }; }
options.mockUserToken?| string | { [claim: string]: unknown; firebase?: { identities?: Record<string, string[]>; sign_in_provider?: string; }; sub?: string; user_id?: string; }

Returns

void


count()

function count(): AggregateField;

Factory: count() aggregate.

Returns

AggregateField


createFirestoreDataTools()

function createFirestoreDataTools(deps: FirestoreDataToolDeps): ToolHandler<unknown, unknown>[];

Modular Web-SDK-shaped Firestore data tools — get, list, create, update, delete. Each tool’s auth arg is forwarded to the resolver; omitted = admin mode, supplied = user mode.

Parameters

ParameterType
depsFirestoreDataToolDeps

Returns

ToolHandler<unknown, unknown>[]


createFirestoreInspectTools()

function createFirestoreInspectTools(deps: FirestoreInspectToolDeps): ToolHandler<unknown, unknown>[];

sandbox_inspect — the missing-tool tax this entire library used to charge agents. Without it, debugging “why aren’t my rules working?” took 51 tool calls + 72k tokens of grepping node_modules (recorded in CLAUDE_DEBUG_SESSION.md). With it, the same diagnosis is one tool call:

{ rules: { source, sizeBytes, isEmpty, lint: { errors, warnings, findings } }, documents: { totalCount, byCollection }, events: { totalCount, recentDenials, recentRequests } }

Returns a snapshot of sandbox state — current rules, lint summary, document census by collection, and the most-recent denials + requests from sandbox.history(). Everything an agent needs to localize a sandbox bug in one round-trip.

Sandbox-only. resolveSandbox must return the owning Sandbox.

Parameters

ParameterType
depsFirestoreInspectToolDeps

Returns

ToolHandler<unknown, unknown>[]


deleteAllPersistentCacheIndexes()

function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): Promise<void>;

Parameters

ParameterType
indexManagerPersistentCacheIndexManager

Returns

Promise<void>


deleteDoc()

function deleteDoc(ref: DocumentReference): Promise<void>;

Parameters

ParameterType
refDocumentReference

Returns

Promise<void>


deleteField()

function deleteField(): FieldValueSentinel;

Returns

FieldValueSentinel


disableNetwork()

function disableNetwork(db: Firestore): Promise<void>;

Sandbox: no-op success. There is no network in the sandbox — every op is a local call into the in-memory/IndexedDB-backed store — so there is nothing to disable. This deliberately does NOT simulate an offline mode: queued writes still commit immediately rather than queuing, because the sandbox cannot honestly deliver “queued until reconnected” when there is no connection to lose in the first place. App code that calls this to prep for flaky connectivity will not crash, but it also will not observe write-queuing behavior.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


disablePersistentCacheIndexAutoCreation()

function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): Promise<void>;

Parameters

ParameterType
indexManagerPersistentCacheIndexManager

Returns

Promise<void>


doc()

function doc<T>(parent:
  | Firestore
| CollectionReference<T>, ...pathSegments: string[]): DocumentReference<T>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
parent| Firestore | CollectionReference<T>
pathSegmentsstring[]

Returns

DocumentReference<T>


documentId()

function documentId(): FieldPath;

Returns

FieldPath


documentSnapshotFromJSON()

function documentSnapshotFromJSON(db: Firestore, json: string): DocumentSnapshot;

Parameters

ParameterType
dbFirestore
jsonstring

Returns

DocumentSnapshot


enableIndexedDbPersistence()

function enableIndexedDbPersistence(db: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;

Enables the persistence lifecycle before first use. As in the browser SDK, initialization after another Firestore operation rejects with failed-precondition.

Parameters

ParameterType
dbFirestore
persistenceSettings?PersistenceSettings

Returns

Promise<void>


enableMultiTabIndexedDbPersistence()

function enableMultiTabIndexedDbPersistence(db: Firestore): Promise<void>;

Sandbox: no-op success, same rationale as enableIndexedDbPersistence. Multi-tab coordination is meaningless here too: the sandbox’s SharedWorker path already IS the single shared store every tab talks to, so there’s no separate “multi-tab” mode to opt into.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


enableNetwork()

function enableNetwork(db: Firestore): Promise<void>;

Sandbox: no-op success, symmetric with disableNetwork — since network was never disabled locally, there is nothing to re-enable.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


enablePersistentCacheIndexAutoCreation()

function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): Promise<void>;

Parameters

ParameterType
indexManagerPersistentCacheIndexManager

Returns

Promise<void>


endAt()

Call Signature

function endAt(snapshot: DocumentSnapshot): QueryConstraint;

End the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included.

Parameters
ParameterType
snapshotDocumentSnapshot
Returns

QueryConstraint

Call Signature

function endAt(...values: unknown[]): QueryConstraint;

End the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included.

Parameters
ParameterType
valuesunknown[]
Returns

QueryConstraint


endBefore()

Call Signature

function endBefore(snapshot: DocumentSnapshot): QueryConstraint;

Same as endAt, but EXCLUDES the document at the cursor — the result ends at the prior ordered position.

Parameters
ParameterType
snapshotDocumentSnapshot
Returns

QueryConstraint

Call Signature

function endBefore(...values: unknown[]): QueryConstraint;

Same as endAt, but EXCLUDES the document at the cursor — the result ends at the prior ordered position.

Parameters
ParameterType
valuesunknown[]
Returns

QueryConstraint


ensureFirestoreConfigured()

function ensureFirestoreConfigured(db: Firestore): void;

Parameters

ParameterType
dbFirestore

Returns

void


executeWrite()

function executeWrite<T>(db: Firestore, action: (batch: WriteBatch) => Promise<T>): Promise<T>;

Type Parameters

Type Parameter
T

Parameters

ParameterType
dbFirestore
action(batch: WriteBatch) => Promise<T>

Returns

Promise<T>


getAdminFirestore()

Call Signature

function getAdminFirestore(sandbox: Sandbox): Firestore;

Construct a rules-bypassing sandbox Firestore handle — the Pyric Studio admin lens (Gap #2). Every modular op issued against the returned handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/ count/writeBatch/runTransaction) SKIPS security-rule evaluation and is treated as ALLOW, while still going through the same store + emitting the same events + waking the same listeners. This is the modular sibling of the path-string sandbox.admin.* bypass; it reuses the underlying LocalEnvironment bypass execution path (the bypassRules op flag), not a parallel reimplementation.

Sandbox-only. There is no prod analog (you cannot bypass deployed security rules from a client), so this overload set accepts only a Sandbox, SandboxContext, or a privately-associated FirebaseApp. Admin ops are identity-agnostic (rules are off), so the handle is a FROZEN sandbox target: it does not track sandbox.currentUser.

Intended for Studio’s “edit anything as admin” surfaces (F2) and the serve worker’s { mode: 'admin' } auth lens. For rules-applied impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.

Parameters
ParameterType
sandboxSandbox
Returns

Firestore

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules

Call Signature

function getAdminFirestore(ctx: SandboxContext): Firestore;

Construct a rules-bypassing sandbox Firestore handle — the Pyric Studio admin lens (Gap #2). Every modular op issued against the returned handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/ count/writeBatch/runTransaction) SKIPS security-rule evaluation and is treated as ALLOW, while still going through the same store + emitting the same events + waking the same listeners. This is the modular sibling of the path-string sandbox.admin.* bypass; it reuses the underlying LocalEnvironment bypass execution path (the bypassRules op flag), not a parallel reimplementation.

Sandbox-only. There is no prod analog (you cannot bypass deployed security rules from a client), so this overload set accepts only a Sandbox, SandboxContext, or a privately-associated FirebaseApp. Admin ops are identity-agnostic (rules are off), so the handle is a FROZEN sandbox target: it does not track sandbox.currentUser.

Intended for Studio’s “edit anything as admin” surfaces (F2) and the serve worker’s { mode: 'admin' } auth lens. For rules-applied impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.

Parameters
ParameterType
ctxSandboxContext
Returns

Firestore

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules

Call Signature

function getAdminFirestore(app: FirebaseApp): Firestore;

Construct a rules-bypassing sandbox Firestore handle — the Pyric Studio admin lens (Gap #2). Every modular op issued against the returned handle (getDoc/getDocs/setDoc/updateDoc/deleteDoc/addDoc/ count/writeBatch/runTransaction) SKIPS security-rule evaluation and is treated as ALLOW, while still going through the same store + emitting the same events + waking the same listeners. This is the modular sibling of the path-string sandbox.admin.* bypass; it reuses the underlying LocalEnvironment bypass execution path (the bypassRules op flag), not a parallel reimplementation.

Sandbox-only. There is no prod analog (you cannot bypass deployed security rules from a client), so this overload set accepts only a Sandbox, SandboxContext, or a privately-associated FirebaseApp. Admin ops are identity-agnostic (rules are off), so the handle is a FROZEN sandbox target: it does not track sandbox.currentUser.

Intended for Studio’s “edit anything as admin” surfaces (F2) and the serve worker’s { mode: 'admin' } auth lens. For rules-applied impersonation (“act as this user”), use getFirestore(sandbox.withAuth({ uid })) instead.

Parameters
ParameterType
appFirebaseApp
Returns

Firestore

Example
import { initializeSandbox } from 'pyric/sandbox';
import { getAdminFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const adminDb = getAdminFirestore(sandbox);
await setDoc(doc(adminDb, 'locked/x'), { a: 1 }); // bypasses rules

getAggregateFromServer()

function getAggregateFromServer<S>(source:
  | Query<DocumentData>
| CollectionReference<DocumentData>, spec: S): Promise<AggregateQuerySnapshot<{ [K in string | number | symbol]: number }>>;

Run a multi-field aggregate against the query. Spec entries are keyed by caller-chosen aliases; the returned snapshot’s .data() uses the same keys.

The sandbox target dispatches straight into the chainable adapter.

Type Parameters

Type Parameter
S extends AggregateSpec

Parameters

ParameterType
source| Query<DocumentData> | CollectionReference<DocumentData>
specS

Returns

Promise<AggregateQuerySnapshot<{ [K in string | number | symbol]: number }>>


getCountFromServer()

function getCountFromServer(source:
  | Query<DocumentData>
  | CollectionReference<DocumentData>): Promise<AggregateQuerySnapshot<{
  count: number;
}>>;

Count documents matching the query. Returns a snapshot whose .data() yields { count: N } — same shape firebase/firestore’s getCountFromServer produces.

Parameters

Returns

Promise<AggregateQuerySnapshot<{ count: number; }>>


getDoc()

function getDoc<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocumentReference<T>

Returns

Promise<DocumentSnapshot<T>>


getDocFromCache()

function getDocFromCache<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;

Sandbox: delegates to getDoc. Real Firebase THROWS 'unavailable' here on a cache miss (nothing local matches the ref); pyric never misses — the local store always has whatever is there — so this never throws for that reason. Documented divergence, not a claim of parity.

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocumentReference<T>

Returns

Promise<DocumentSnapshot<T>>


getDocFromServer()

function getDocFromServer<T>(ref: DocumentReference<T>): Promise<DocumentSnapshot<T>>;

Sandbox: delegates to getDoc. The sandbox store IS the authoritative, always-fresh source — there is no separate server round-trip to force, so “from server” and the default read are the same honest thing.

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocumentReference<T>

Returns

Promise<DocumentSnapshot<T>>


getDocs()

function getDocs<T>(query: Query<T>): Promise<QuerySnapshot<T>>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
queryQuery<T>

Returns

Promise<QuerySnapshot<T>>


getDocsFromCache()

function getDocsFromCache<T>(query: Query<T>): Promise<QuerySnapshot<T>>;

Query-plural form of getDocFromCache — same cache-miss divergence.

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
queryQuery<T>

Returns

Promise<QuerySnapshot<T>>


getDocsFromServer()

function getDocsFromServer<T>(query: Query<T>): Promise<QuerySnapshot<T>>;

Query-plural form of getDocFromServer.

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
queryQuery<T>

Returns

Promise<QuerySnapshot<T>>


getFirestore()

Call Signature

function getFirestore(ctx: SandboxContext): Firestore;

Construct a Firestore handle. Three overloads dispatch by the input’s shape:

  • SandboxContext → sandbox-backed Firestore with a frozen identity (the ctx’s auth chosen at getFirestore time). Best for runner/test code that names identity explicitly per scenario.
  • Sandbox → sandbox-backed Firestore that reads sandbox.currentUser per-call. Best for app code that drives identity through pyric/auth — every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
ParameterType
ctxSandboxContext
Returns

Firestore

Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));

// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth);    // subsequent db ops use the new identity

// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);

Call Signature

function getFirestore(sandbox: Sandbox): Firestore;

Construct a Firestore handle. Three overloads dispatch by the input’s shape:

  • SandboxContext → sandbox-backed Firestore with a frozen identity (the ctx’s auth chosen at getFirestore time). Best for runner/test code that names identity explicitly per scenario.
  • Sandbox → sandbox-backed Firestore that reads sandbox.currentUser per-call. Best for app code that drives identity through pyric/auth — every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
ParameterType
sandboxSandbox
Returns

Firestore

Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));

// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth);    // subsequent db ops use the new identity

// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);

Call Signature

function getFirestore(app: FirebaseApp): AppFirestore;

Construct a Firestore handle. Three overloads dispatch by the input’s shape:

  • SandboxContext → sandbox-backed Firestore with a frozen identity (the ctx’s auth chosen at getFirestore time). Best for runner/test code that names identity explicitly per scenario.
  • Sandbox → sandbox-backed Firestore that reads sandbox.currentUser per-call. Best for app code that drives identity through pyric/auth — every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
ParameterType
appFirebaseApp
Returns

AppFirestore

Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));

// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth);    // subsequent db ops use the new identity

// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);

Call Signature

function getFirestore(): AppFirestore;

Construct a Firestore handle. Three overloads dispatch by the input’s shape:

  • SandboxContext → sandbox-backed Firestore with a frozen identity (the ctx’s auth chosen at getFirestore time). Best for runner/test code that names identity explicitly per scenario.
  • Sandbox → sandbox-backed Firestore that reads sandbox.currentUser per-call. Best for app code that drives identity through pyric/auth — every Firestore op evaluates rules under whatever user is currently signed in.
Returns

AppFirestore

Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));

// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth);    // subsequent db ops use the new identity

// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);

Call Signature

function getFirestore(target?:
  | FirebaseApp
  | Sandbox
  | SandboxContext): Firestore;

Construct a Firestore handle. Three overloads dispatch by the input’s shape:

  • SandboxContext → sandbox-backed Firestore with a frozen identity (the ctx’s auth chosen at getFirestore time). Best for runner/test code that names identity explicitly per scenario.
  • Sandbox → sandbox-backed Firestore that reads sandbox.currentUser per-call. Best for app code that drives identity through pyric/auth — every Firestore op evaluates rules under whatever user is currently signed in.
Parameters
ParameterType
target?| FirebaseApp | Sandbox | SandboxContext
Returns

Firestore

Example
// Sandbox, frozen identity (runner / explicit tests).
import { initializeSandbox } from 'pyric/sandbox';
import { getFirestore, doc, setDoc } from 'pyric/firestore';
const sandbox = initializeSandbox();
const db = getFirestore(sandbox.withAuth({ uid: 'alice' }));

// Sandbox, live identity (app code paired with pyric/auth).
import { initializeSandbox } from 'pyric/sandbox';
import { getAuth, signInAnonymously } from 'pyric/auth';
const sandbox = initializeSandbox();
const auth = getAuth(sandbox);
const db = getFirestore(sandbox); // reads sandbox.currentUser per op
await signInAnonymously(auth);    // subsequent db ops use the new identity

// Canonical imports are swapped to this mirror in a sandbox process.
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
const app = initializeApp({ projectId: 'demo-project' });
const db = getFirestore(app);

getPersistentCacheIndexManager()

function getPersistentCacheIndexManager(db: Firestore): PersistentCacheIndexManager;

Parameters

ParameterType
dbFirestore

Returns

PersistentCacheIndexManager


increment()

function increment(n: number): FieldValueSentinel;

Parameters

ParameterType
nnumber

Returns

FieldValueSentinel


initializeFirestore()

function initializeFirestore(
   app:
  | FirebaseApp
  | Sandbox
  | SandboxContext,
   _settings?: FirestoreSettings,
   _databaseId?: string): Firestore;

Delegates to getFirestore and returns the same handle. Accepts the settings argument (so the explicit-init pattern app code commonly writes — initializeFirestore(app, { localCache: persistentLocalCache(...) } ) — no longer crashes at import) but no-ops the cache/network settings: persistence is already the sandbox default, so there is nothing left to configure into existence.

Parameters

ParameterType
app| FirebaseApp | Sandbox | SandboxContext
_settings?FirestoreSettings
_databaseId?string

Returns

Firestore


limit()

function limit(n: number): QueryConstraint;

Parameters

ParameterType
nnumber

Returns

QueryConstraint


limitToLast()

function limitToLast(n: number): QueryConstraint;

Limit the query to the LAST n documents in the ordered result. Requires at least one orderBy on the query (production-aligned — the simulator throws at execute time without one).

Parameters

ParameterType
nnumber

Returns

QueryConstraint


loadBundle()

function loadBundle(db: Firestore, bundleData:
  | string
  | ArrayBuffer
  | ReadableStream<Uint8Array<ArrayBufferLike>>): LoadBundleTask;

Parameters

ParameterType
dbFirestore
bundleData| string | ArrayBuffer | ReadableStream<Uint8Array<ArrayBufferLike>>

Returns

LoadBundleTask


memoryEagerGarbageCollector()

function memoryEagerGarbageCollector(): MemoryGarbageCollector;

Inert config token accepted by memoryLocalCache’s garbageCollector.

Returns

MemoryGarbageCollector


memoryLocalCache()

function memoryLocalCache(settings?: {
  garbageCollector?: MemoryGarbageCollector;
}): LocalCache;

Inert config token — the memory-cache counterpart of persistentLocalCache.

Parameters

ParameterType
settings?{ garbageCollector?: MemoryGarbageCollector; }
settings.garbageCollector?MemoryGarbageCollector

Returns

LocalCache


memoryLruGarbageCollector()

function memoryLruGarbageCollector(_settings?: {
  cacheSizeBytes?: number;
}): MemoryGarbageCollector;

Inert config token accepted by memoryLocalCache’s garbageCollector.

Parameters

ParameterType
_settings?{ cacheSizeBytes?: number; }
_settings.cacheSizeBytes?number

Returns

MemoryGarbageCollector


namedQuery()

function namedQuery(db: Firestore, name: string): Promise<Query<DocumentData>>;

Parameters

ParameterType
dbFirestore
namestring

Returns

Promise<Query<DocumentData>>


onSnapshot()

Call Signature

function onSnapshot<T>(
   ref: T,
   observerOrNext:
  | SnapshotObserver<unknown>
  | (snap: unknown) => void,
   errorOrNothing?: (error: unknown) => void): Unsubscribe;
Type Parameters
Type Parameter
T extends | DocumentReference<DocumentData> | Query<DocumentData>
Parameters
ParameterType
refT
observerOrNext| SnapshotObserver<unknown> | (snap: unknown) => void
errorOrNothing?(error: unknown) => void
Returns

Unsubscribe

Call Signature

function onSnapshot<T>(
   ref: T,
   options: SnapshotListenOptions,
   observerOrNext:
  | SnapshotObserver<unknown>
  | (snap: unknown) => void,
   errorOrNothing?: (error: unknown) => void): Unsubscribe;
Type Parameters
Type Parameter
T extends | DocumentReference<DocumentData> | Query<DocumentData>
Parameters
ParameterType
refT
optionsSnapshotListenOptions
observerOrNext| SnapshotObserver<unknown> | (snap: unknown) => void
errorOrNothing?(error: unknown) => void
Returns

Unsubscribe


onSnapshotResume()

function onSnapshotResume(
   query: Query,
   snapshot: QuerySnapshot,
   observerOrNext: unknown,
   error?: unknown,
   complete?: unknown): Unsubscribe;

Parameters

ParameterType
queryQuery
snapshotQuerySnapshot
observerOrNextunknown
error?unknown
complete?unknown

Returns

Unsubscribe


onSnapshotsInSync()

function onSnapshotsInSync(db: Firestore, observerOrCallback:
  | () => void
  | {
  complete?: () => void;
  error?: (error: unknown) => void;
  next?: () => void;
}): Unsubscribe;

Registers a service-scoped synchronization observer. It receives an initial signal and a batched signal after snapshot listeners deliver their latest local state, matching the production-observed callback ordering.

Parameters

ParameterType
dbFirestore
observerOrCallback| () => void | { complete?: () => void; error?: (error: unknown) => void; next?: () => void; }

Returns

Unsubscribe


or()

function or(...filters: QueryConstraint[]): QueryConstraint;

OR composite — at least one of the inner constraints must match. Each argument must itself be a filter constraint (where(), or nested or() / and()); passing orderBy() or limit() here is a type error at runtime.

Mirrors firebase/firestore’s or(...filters) shape.

Parameters

ParameterType
filtersQueryConstraint[]

Returns

QueryConstraint


orderBy()

function orderBy(field: string | FieldPath, direction?: QueryOrderDirection): QueryConstraint;

Parameters

ParameterType
fieldstring | FieldPath
direction?QueryOrderDirection

Returns

QueryConstraint


persistentLocalCache()

function persistentLocalCache(settings?: {
  cacheSizeBytes?: number;
  tabManager?: PersistentTabManager;
}): LocalCache;

Inert config token. Real Firebase uses this to select an on-disk, persistent IndexedDB cache tier; the sandbox has no separate cache tier — persistence is already the default — so this just returns a tagged token initializeFirestore can accept without crashing.

Parameters

ParameterType
settings?{ cacheSizeBytes?: number; tabManager?: PersistentTabManager; }
settings.cacheSizeBytes?number
settings.tabManager?PersistentTabManager

Returns

LocalCache


persistentMultipleTabManager()

function persistentMultipleTabManager(): PersistentTabManager;

Inert config token accepted by persistentLocalCache’s tabManager.

Returns

PersistentTabManager


persistentSingleTabManager()

function persistentSingleTabManager(_settings?: {
  forceOwnership?: boolean;
}): PersistentTabManager;

Inert config token accepted by persistentLocalCache’s tabManager.

Parameters

ParameterType
_settings?{ forceOwnership?: boolean; }
_settings.forceOwnership?boolean

Returns

PersistentTabManager


query()

function query<T>(source:
  | CollectionReference<T>
| Query<T>, ...constraints: QueryConstraint[]): Query<T>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
source| CollectionReference<T> | Query<T>
constraintsQueryConstraint[]

Returns

Query<T>


queryEqual()

function queryEqual(a: Query, b: Query): boolean;

Parameters

ParameterType
aQuery
bQuery

Returns

boolean


querySnapshotFromJSON()

function querySnapshotFromJSON(db: Firestore, json: string): QuerySnapshot;

Parameters

ParameterType
dbFirestore
jsonstring

Returns

QuerySnapshot


refEqual()

function refEqual(a: DocumentReference, b: DocumentReference): boolean;

Parameters

Returns

boolean


runTransaction()

function runTransaction<R>(
   db: Firestore,
   fn: (tx: Transaction) => R | Promise<R>,
options?: TransactionOptions): Promise<R>;

Type Parameters

Type Parameter
R

Parameters

ParameterType
dbFirestore
fn(tx: Transaction) => R | Promise<R>
options?TransactionOptions

Returns

Promise<R>


serverTimestamp()

function serverTimestamp(): FieldValueSentinel;

Returns

FieldValueSentinel


setDoc()

function setDoc<T>(
   ref: DocumentReference<T>,
   data: T,
options?: SetOptions): Promise<void>;

Type Parameters

Type ParameterDefault type
TDocumentData

Parameters

ParameterType
refDocumentReference<T>
dataT
options?SetOptions

Returns

Promise<void>


setIndexConfiguration()

function setIndexConfiguration(db: Firestore, configuration: string | IndexConfiguration): Promise<void>;

Parameters

ParameterType
dbFirestore
configurationstring | IndexConfiguration

Returns

Promise<void>


setLogLevel()

function setLogLevel(logLevel: LogLevel): void;

Accepted no-op: the sandbox has no modular-SDK-style logger to wire a level into (it uses host-level console logging directly, gated by pyric dev’s own flags, not this call). Exists purely so app code that calls this defensively at startup doesn’t crash on a missing export.

Parameters

ParameterType
logLevelLogLevel

Returns

void


snapshotEqual()

function snapshotEqual(a:
  | DocumentSnapshot<DocumentData>
  | QuerySnapshot<DocumentData>, b:
  | DocumentSnapshot<DocumentData>
  | QuerySnapshot<DocumentData>): boolean;

Parameters

Returns

boolean


startAfter()

Call Signature

function startAfter(snapshot: DocumentSnapshot): QueryConstraint;

Same as startAt, but EXCLUDES the document at the cursor — the result starts at the next ordered position.

Parameters
ParameterType
snapshotDocumentSnapshot
Returns

QueryConstraint

Call Signature

function startAfter(...values: unknown[]): QueryConstraint;

Same as startAt, but EXCLUDES the document at the cursor — the result starts at the next ordered position.

Parameters
ParameterType
valuesunknown[]
Returns

QueryConstraint


startAt()

Call Signature

function startAt(snapshot: DocumentSnapshot): QueryConstraint;

Start the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included in the result. Two overloads:

startAt(snapshot) — values come from snapshot.data() indexed by the query’s orderBy fields. startAt(...values) — explicit positional values (one per orderBy clause).

Parameters
ParameterType
snapshotDocumentSnapshot
Returns

QueryConstraint

Call Signature

function startAt(...values: unknown[]): QueryConstraint;

Start the query at the document whose ordered field values match the cursor. Inclusive — the document at the cursor IS included in the result. Two overloads:

startAt(snapshot) — values come from snapshot.data() indexed by the query’s orderBy fields. startAt(...values) — explicit positional values (one per orderBy clause).

Parameters
ParameterType
valuesunknown[]
Returns

QueryConstraint


sum()

function sum(field: string): AggregateField;

Factory: sum-of-field aggregate.

Parameters

ParameterType
fieldstring

Returns

AggregateField


terminate()

function terminate(db: Firestore): Promise<void>;

Terminates this Firestore service target only. Held references become unusable and owned listeners stop, while sibling Firestore handles and other services on the same Sandbox remain alive.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


updateDoc()

function updateDoc(ref: DocumentReference, data: DocumentData): Promise<void>;

updateDoc does NOT run the converter. Matches firebase/firestore’s Web SDK shape — partial updates can target any subset of fields, so a translator built around a full AppModelType would be a type-shape mismatch. Use the underlying DocumentData view (withConverter(ref, null)) for typed-and-untyped mixed access if you need both styles against the same path.

Parameters

ParameterType
refDocumentReference
dataDocumentData

Returns

Promise<void>


vector()

function vector(values?: number[]): VectorValue;

Parameters

ParameterType
values?number[]

Returns

VectorValue


waitForPendingWrites()

function waitForPendingWrites(db: Firestore): Promise<void>;

Resolves after writes that were issued while offline receive their modeled acknowledgement on reconnect.

Parameters

ParameterType
dbFirestore

Returns

Promise<void>


where()

function where(
   field: string | FieldPath,
   op: QueryWhereFilterOp,
   value: unknown): QueryConstraint;

Parameters

ParameterType
fieldstring | FieldPath
opQueryWhereFilterOp
valueunknown

Returns

QueryConstraint


withConverter()

Call Signature

function withConverter<AppModel, DbModel>(ref: DocumentReference<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): DocumentReference<AppModel>;
Type Parameters
Type ParameterDefault type
AppModel-
DbModel extends DocumentDataDocumentData
Parameters
ParameterType
refDocumentReference<DocumentData>
converterFirestoreDataConverter<AppModel, DbModel>
Returns

DocumentReference<AppModel>

Call Signature

function withConverter(ref: DocumentReference<unknown>, converter: null): DocumentReference<DocumentData>;
Parameters
ParameterType
refDocumentReference<unknown>
converternull
Returns

DocumentReference<DocumentData>

Call Signature

function withConverter<AppModel, DbModel>(ref: CollectionReference<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): CollectionReference<AppModel>;
Type Parameters
Type ParameterDefault type
AppModel-
DbModel extends DocumentDataDocumentData
Parameters
ParameterType
refCollectionReference<DocumentData>
converterFirestoreDataConverter<AppModel, DbModel>
Returns

CollectionReference<AppModel>

Call Signature

function withConverter(ref: CollectionReference<unknown>, converter: null): CollectionReference<DocumentData>;
Parameters
ParameterType
refCollectionReference<unknown>
converternull
Returns

CollectionReference<DocumentData>

Call Signature

function withConverter<AppModel, DbModel>(q: Query<DocumentData>, converter: FirestoreDataConverter<AppModel, DbModel>): Query<AppModel>;
Type Parameters
Type ParameterDefault type
AppModel-
DbModel extends DocumentDataDocumentData
Parameters
ParameterType
qQuery<DocumentData>
converterFirestoreDataConverter<AppModel, DbModel>
Returns

Query<AppModel>

Call Signature

function withConverter(q: Query<unknown>, converter: null): Query<DocumentData>;
Parameters
ParameterType
qQuery<unknown>
converternull
Returns

Query<DocumentData>


writeBatch()

function writeBatch(db: Firestore): WriteBatch;

Parameters

ParameterType
dbFirestore

Returns

WriteBatch