Classes
RtdbExpressionSyntaxError
Why canonicalRtdbExpression could not read its input.
Extends
Error
Constructors
Constructor
new RtdbExpressionSyntaxError(raw: string, message: string): RtdbExpressionSyntaxError;
Parameters
| Parameter | Type |
|---|---|
raw | string |
message | string |
Returns
Overrides
Error.constructor
Properties
RulesAssertionError
Thrown by assertCase / a runner case’s run() when the simulated
decision did not match the case’s expectation. The message is the
rendered trace from explainCase, so a test runner surfaces the “why”
without extra wiring.
Extends
Error
Constructors
Constructor
new RulesAssertionError(message: string): RulesAssertionError;
Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
Overrides
Error.constructor
RulesCompileError
Thrown by firestoreRules(source) / rtdbRules(...) when the source
cannot compile. Carries the compile-blocking issues on .issues so a
caller can surface them without re-parsing.
Extends
Error
Constructors
Constructor
new RulesCompileError(message: string, issues: RuleIssue[]): RulesCompileError;
Parameters
| Parameter | Type |
|---|---|
message | string |
issues | RuleIssue[] |
Returns
Overrides
Error.constructor
Properties
| Property | Modifier | Type |
|---|---|---|
issues | readonly | RuleIssue[] |
RulesUnsupportedError
Thrown by assertCase / a runner case’s run() when the simulator
abstained — it hit a feature it does not implement, so neither a pass nor
a genuine failure can be asserted. Distinct from
RulesAssertionError so a runner can choose to skip rather than
fail on a known simulator gap.
Extends
Error
Constructors
Constructor
new RulesUnsupportedError(message: string): RulesUnsupportedError;
Parameters
| Parameter | Type |
|---|---|
message | string |
Returns
Overrides
Error.constructor
Interfaces
CaseResult
The outcome of running one Firestore case through simulate. Never a
thrown error — a denied or abstained case is data, not an exception.
Properties
| Property | Type | Description |
|---|---|---|
case | FirestoreCase | The case that produced this result. |
decision | "UNSUPPORTED" | "ALLOW" | "DENY" | The engine’s absolute verdict, independent of expectation. |
description | string | - |
evaluatedExpressions | number | Expressions the request evaluated, in the unit of production’s per-request limit of 1000, across every allow rule and match block it reached. 1000 - evaluatedExpressions is the request’s margin. See TestResult.evaluatedExpressions for the unit. |
expectation | "ALLOW" | "DENY" | - |
notes | string[] | Top-level diagnostic strings. |
passed | boolean | true when decision matched expectation. |
pathResolution? | PathResolutionTrace | Which match blocks the resolver considered and where each fell apart. |
queryProof? | ListQueryProofReport | Static list-query proof verdict for list cases, separate from per-document decision (#371). |
resourceLimit? | RulesResourceLimit | The per-request limit that stopped the request, when one did. A request past 1000 expressions is DENY with kind: 'expressions' and production’s message. |
trace | RuleEvaluation[] | Per-rule evaluation entries in source order. |
unsupported | boolean | true when the simulator abstained on a feature it does not implement — neither a pass nor a genuine failure. |
DiffRtdbRulesOptions
Properties
| Property | Type | Description |
|---|---|---|
ignoreEquivalent? | boolean | Treat two .read, .write or .validate expressions as the same rule when their canonicalRtdbExpression texts are equal: spellings that cannot change any decision, such as === for == or child('a/' + $id) for child('a').child($id). A changed entry still reports both expressions as written. An expression that does not parse is compared as written. Default false: expressions compare as text. |
EvaluatedRuleInfo
The DECIDING rule’s source position + sub-expression trace, projected from a
TestResult — for BOTH verdicts: the allow rule that granted an
ALLOW, or the rule responsible for a DENY. Additive companion to
renderLegacyDebugMessages: that flattens the per-rule trace to
strings (dropping line and expressionTrace); this preserves the
structured detail a UI needs to point at the exact source line and step
through the evaluation (“show the work”). Position/trace fields are optional
so a partial trace projects honestly.
Properties
| Property | Type | Description |
|---|---|---|
citation? | string | - |
col? | number | - |
column? | number | - |
expression? | string | Pretty-printed condition text of the deciding rule. |
expressionTrace? | ExprTraceEntry[] | Per-sub-expression evaluation trace of the deciding rule. |
file? | string | - |
line? | number | 1-indexed source line of the deciding allow rule. |
verdict | "allow" | "deny" | The verdict the deciding rule produced for the op. |
Explanation
The structured account of why one Firestore case resolved as it did.
Properties
| Property | Type | Description |
|---|---|---|
deciding? | EvaluatedRuleInfo | The deciding allow rule (line, condition text, sub-expression trace), when one was evaluated. Absent on default-deny / abstain. |
decision | "UNSUPPORTED" | "ALLOW" | "DENY" | - |
evaluatedExpressions | number | Expressions the request evaluated; see CaseResult.evaluatedExpressions. |
expectation | "ALLOW" | "DENY" | - |
notes | string[] | - |
passed | boolean | - |
pathResolution? | PathResolutionTrace | - |
queryProof? | ListQueryProofReport | Static list-query proof verdict for list cases, separate from per-document decision (#371). |
resourceLimit? | RulesResourceLimit | The per-request limit that stopped the request, when one did. |
trace | RuleEvaluation[] | - |
unsupported | boolean | - |
ExprTraceEntry
One entry in a per-rule expression trace, emitted in evaluation order.
Properties
FirestoreCase
One Firestore rules case: a single request plus the outcome it should
produce. Structurally identical to the engine’s TestCase — re-exported
here under the public name so callers never reach into the engine seam.
Properties
FirestoreRuleset
Methods
explain()
explain(oneCase: FirestoreCase): Explanation;
The structured account of why one case resolved as it did.
Parameters
| Parameter | Type |
|---|---|
oneCase | FirestoreCase |
Returns
lint()
lint(): RuleIssue[];
Structural, security, and budget findings on the compiled ruleset. No parse errors — the source already compiled.
Returns
simulate()
simulate(cases: FirestoreCase[]): SimulationSummary;
Run every case. Never throws on a rule outcome: a denied or abstained case is reported in the returned summary.
Parameters
| Parameter | Type |
|---|---|
cases | FirestoreCase[] |
Returns
toJSON()
toJSON(): FirestoreRules;
The parsed ruleset as plain data (the AST).
Returns
FirestoreRules
ListQueryProofReport
Separate static list-query proof verdict reported alongside per-document
evaluation on TestResult / CaseResult / Explanation (#371).
Properties
| Property | Type | Description |
|---|---|---|
failures | QueryProofFailure[] | Rules rejected by static query proof, in source order. |
kind | | "provable" | "no-rule" | "unsupported-predicate" | "unsupported-path" | "constraints-not-satisfied" | Specific proof classification ('provable', 'no-rule', or the primary failure kind). |
provable | boolean | True when the rules can statically prove every document the query could return is readable. |
reason? | string | Human-readable explanation when verdict === 'UNPROVABLE'. |
remediation? | string | Narrowing where(...) remediation when verdict === 'UNPROVABLE' and equalities can discharge the rule. |
residual? | QueryProofResidual | Structured account of missing/mismatched where(...) equalities when verdict === 'UNPROVABLE'. |
rule? | EvaluatedRuleInfo | Source location and expression of the primary unprovable rule when verdict === 'UNPROVABLE'. |
verdict | "PROVABLE" | "UNPROVABLE" | "NO_RULE" | Static list-query proof verdict, separate from per-document decision. |
PathDef
Definition of rules for a single database path.
Properties
| Property | Type | Description |
|---|---|---|
children? | Record<string, PathDef> | - |
fieldConstraints? | Record<string, Expr[]> | - |
indexOn? | string[] | Fields to emit under .indexOn for the container node. May be declared directly on a container path (e.g. "/jobs") or on a $wildcard child path (e.g. "/jobs/$jobId"), which lifts .indexOn onto its parent. |
read? | string | boolean | An expression, or a boolean as database.rules.json spells it: false denies, true allows. |
schema? | ZodObject<any> | - |
validate? | string | boolean | - |
write? | string | boolean | - |
PathResolutionEntry
One match block the simulator considered while resolving the
request path. Together, PathResolutionTrace.attempts forms a
complete picture of “what did the resolver try, and where did
each attempt fall apart?” — useful for the agent when a request
lands in the default-deny path because no block matched.
Recorded only by the local simulator; the production Test API client doesn’t expose path-resolution internals.
Properties
PathResolutionTrace
Properties
| Property | Type | Description |
|---|---|---|
attempts | PathResolutionEntry[] | One entry per match block the resolver considered, in the order it tried them. attempts[i].matched: true marks a block that fully resolved; one or more per trace, since overlapping blocks all match and OR-combine. |
requestPath | string | The request path that was resolved, verbatim from TestCase.path. |
QueryProofFailure
Local proof evidence. These categories do not claim a Firebase decision.
Properties
| Property | Type | Description |
|---|---|---|
kind | | "unsupported-predicate" | "unsupported-path" | "constraints-not-satisfied" | - |
predicate? | { citation?: string; col?: number; column?: number; expression?: string; file?: string; line?: number; } | Location of the rejected predicate, which may be inside a helper. |
predicate.citation? | string | - |
predicate.col? | number | - |
predicate.column? | number | - |
predicate.expression? | string | - |
predicate.file? | string | - |
predicate.line? | number | - |
reason | string | - |
residual | QueryProofResidual | - |
rule? | { citation?: string; col?: number; column?: number; expression?: string; file?: string; line?: number; } | - |
rule.citation? | string | - |
rule.col? | number | - |
rule.column? | number | - |
rule.expression? | string | - |
rule.file? | string | - |
rule.line? | number | - |
QueryProofResidual
Structured account of why a doc-dependent query is unprovable. Empty missing
and mismatched with outOfScope set means the rule’s doc-dependence is a
shape equality analysis cannot discharge, so no query constraint could prove it.
Properties
QueryRepro
Ready-to-run repro for a rejected list query (#371).
Properties
RtdbCase
One Realtime Database rules case. expectation is required so a simulate
run can partition cases into passed/failed the same way Firestore does —
the RTDB simulator otherwise returns only a raw allow/deny with no notion
of an expectation.
Properties
| Property | Type | Description |
|---|---|---|
auth? | | string | { tenant?: string; token?: Record<string, unknown>; uid: string; } | Auth context; a bare uid string, a full identity, or null. |
data? | | Record<string, unknown> | RtdbInstancesData | Existing data the rules read: the instance’s tree, or one tree per instance as { instances: { "<name>": tree } }. The per-instance form applies when the case names an instance or the ruleset holds rules per instance (rtdbRules.fromFirebaseJson); otherwise an object whose one key is instances is a tree with an /instances child, as before. |
description? | string | Human-readable description of what this case verifies. |
expectation | "ALLOW" | "DENY" | Expected outcome. |
instance? | string | The database instance the request goes to, by name, such as "demo-app-shard-1". Omit it for the default instance. A rule’s root and data read only this instance’s tree. |
newData? | unknown | Proposed write value (newData), for write/validate cases. Any JSON value: a scalar such as 5 or true is a scalar write. For an update case it is the patch, an object keyed by paths relative to path, such as { "rooms/r1/title": "x", "rooms/r2/title": "y" }. Its keys are checked as the SDK checks update() keys: an invalid key, or a key that is an ancestor or duplicate of another, makes the case UNSUPPORTED. |
now? | number | The instant now reports in this case, in epoch milliseconds. A caller hosting a sandbox passes its sandbox clock so a now-gated rule moves with the sandbox rather than the wall clock. Omit to evaluate at the real current instant. |
operation | "read" | "write" | "update" | "validate" | RTDB rule kind under test. update is a multi-path update(): every path in newData is written together and each is judged against the tree the whole update produces. |
path | string | Absolute, root-relative tree path, e.g. "/users/alice". A path the SDK refuses, one holding ., #, $, [ or ], is UNSUPPORTED. |
query? | RtdbCaseQuery | The query a read case carries, so query.* rule expressions evaluate. Omit it to simulate a plain read of path. |
updates? | { path: string; value: unknown; }[] | For a 'write' or 'validate' case, the full set of paths written together in one atomic multi-path update(), so path’s rules evaluate against the shared post-write tree projection. It lists path, with newData as its value when the case gives newData, and no path in it is an ancestor or duplicate of another; a case that breaks either is UNSUPPORTED. |
RtdbCaseQuery
The query a Realtime Database read carries, in the members rules read as
query.*. At most one orderBy* member and at most one limit may be set,
as in the SDK.
Properties
RtdbCaseResult
The outcome of running one RTDB case through simulate.
Properties
| Property | Type | Description |
|---|---|---|
case | RtdbCase | - |
decision | "UNSUPPORTED" | "ALLOW" | "DENY" | - |
description? | string | - |
expectation | "ALLOW" | "DENY" | - |
instance? | string | The database instance the case ran on: the one it named, or the default instance of a ruleset that holds rules per instance. Absent when neither applies. |
matchedPath | string | The tree path whose rule decided the request. |
matchedRule | string | The expression of the rule that decided, such as auth != null. Empty when no rule on the path decided, as for a request denied by default or one the engine could not evaluate. |
passed | boolean | - |
reason | string | Engine-provided reason string. |
trace | { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[] | Every .read, .write and .validate rule the engine evaluated, in evaluation order. Empty when no rule of the operation’s kind exists on the path, or when the engine could not evaluate the case. |
unsupported | boolean | - |
RtdbCoverageOptions
Properties
RtdbCoverageSummary
Properties
| Property | Type | Description |
|---|---|---|
files | RtdbFileCoverage[] | - |
missingIndexes | { file?: string; index: string; path: string; }[] | Queries that needed an index no loaded node declares, with the rules file when the summary covers several files. |
rules | RtdbRuleCoverage[] | - |
uncovered | string[] | "<path> .<kind>" for each node never evaluated, in tree order; "<file> <path> .<kind>" when the summary covers several files. |
RtdbExplanation
Properties
| Property | Type | Description |
|---|---|---|
decision | "UNSUPPORTED" | "ALLOW" | "DENY" | - |
expectation | "ALLOW" | "DENY" | - |
instance? | string | See RtdbCaseResult.instance. |
matchedPath | string | - |
matchedRule | string | - |
passed | boolean | - |
reason | string | - |
trace | { conditionText: string; instance?: string; kind: "read" | "write" | "validate"; message?: string; path: string; pathVariableBindings: Record<string, string>; verdict: "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY"; }[] | See RtdbCaseResult.trace. |
unsupported | boolean | - |
RtdbFileCoverage
Properties
| Property | Type | Description |
|---|---|---|
byKind | Record<RtdbCoverageKind, { covered: number; total: number; unsupported: number; }> | - |
covered | number | Nodes with at least one evaluation. |
file | string | The rules file the nodes came from, or null when none was named. |
neverEvaluated | number | - |
total | number | - |
unsupported | number | Nodes the simulator could not evaluate, every time it reached them. covered + neverEvaluated + unsupported is total. |
RtdbFirebaseJsonOptions
Reads the Realtime Database rules a project’s firebase.json deploys to
each instance, for rtdbRules.fromFirebaseJson.
BROWSER-CLEAN: no static node imports. pyric/rules is reachable from
browser graphs, so node:fs and node:path are acquired lazily through
process.getBuiltinModule; in a browser the loader throws saying it needs
a file system.
Properties
RtdbRuleChange
One rule expression that differs. deployed is absent for added and
local is absent for removed: the change is what deploying the local
ruleset would do to the deployed one.
Properties
| Property | Type |
|---|---|
change | "added" | "removed" | "changed" |
deployed? | string |
kind | RtdbRuleKind |
local? | string |
path | string |
RtdbRuleCoverage
Properties
| Property | Type | Description |
|---|---|---|
allow | number | - |
deny | number | - |
error | number | - |
evaluated | number | Evaluations that produced a verdict: allow + deny + error. |
expression | string | The rule expression, or the declared index list for indexOn. |
file? | string | The rules file holding the node, when the summary covers several files. |
kind | RtdbCoverageKind | - |
line? | number | 1-indexed line in the rules file, when a line lookup was supplied. |
path | string | The rule node’s path, such as /rooms/$roomId. |
status | RtdbCoverageStatus | - |
unsupported | number | - |
RtdbRulesCheckResult
Properties
| Property | Type |
|---|---|
errors | RtdbRulesFinding[] |
ok | boolean |
warnings | RtdbRulesFinding[] |
RtdbRulesConstructor()
rtdbRules: call it with one ruleset, or call rtdbRules.fromFirebaseJson
for the rules a project’s firebase.json deploys to each database
instance.
RtdbRulesConstructor(input: string | RtdbRulesInput): RtdbRuleset;
Build a deep handle on a Realtime Database ruleset from the text of a
database.rules.json file, a definition, a compiled document, or compiled
{ rules } JSON.
Parameters
| Parameter | Type |
|---|---|
input | string | RtdbRulesInput |
Returns
Throws
when rules text is not JSON (after comments
and trailing commas) or has no top-level rules object.
Methods
fromFirebaseJson()
fromFirebaseJson(firebaseJsonPath: string, options?: RtdbFirebaseJsonOptions): RtdbRuleset;
Build a handle on the Realtime Database rules a project’s firebase.json
deploys, one ruleset per database instance, as firebase deploy resolves
them: a single database object deploys to the default instance, and each
entry of a database array deploys to its instance, or to the instances
.firebaserc maps its target to. Each rules file is read as
rtdbRules reads rules text, comments and trailing commas included.
A case runs on the instance it names, or on the default instance
<projectId>-default-rtdb, which <projectId> also names; the project
id is options.projectId, else projects.default in the .firebaserc
beside firebase.json. A case that
names an instance firebase.json deploys no rules to is UNSUPPORTED, with
a reason naming the instances it does.
Node-only: it reads files.
Parameters
| Parameter | Type |
|---|---|
firebaseJsonPath | string |
options? | RtdbFirebaseJsonOptions |
Returns
Throws
when a rules file is not rules text.
Throws
when a file cannot be read, firebase.json deploys no
Realtime Database rules, or a deploy target maps to no instance.
RtdbRulesDefinition
Properties
| Property | Type |
|---|---|
paths | | Record<string, PathDef> | (ctx: RulesetContext) => void |
RtdbRulesDocument
The authored RTDB rules artifact defineRtdbRules returns.
Deliberately INERT on the public surface: it exposes no methods. It is a
value you author and hand to rtdbRules(), which is the one analysis
surface (lint / simulate / explain / toJSON). The brand is
type-level only; nothing exists at runtime.
Properties
RtdbRuleset
Methods
coverage()
coverage(results: readonly RtdbCaseResult[], options?: RtdbCoverageOptions): RtdbCoverageSummary;
Which .read, .write, .validate and .indexOn nodes the given case
results evaluated, and which they never reached. simulate returns this
for its own cases; call it to merge several runs or to attach a file name
and line numbers. A ruleset from rtdbRules.fromFirebaseJson
reports each rules file under the name firebase.json gives it, with
lines located in its text, and takes no options.
Parameters
| Parameter | Type |
|---|---|
results | readonly RtdbCaseResult[] |
options? | RtdbCoverageOptions |
Returns
explain()
explain(oneCase: RtdbCase): RtdbExplanation;
The structured account of why one case resolved as it did.
Parameters
| Parameter | Type |
|---|---|
oneCase | RtdbCase |
Returns
lint()
lint(): RuleIssue[];
Structural findings on the compiled ruleset (from check()). On a
ruleset from rtdbRules.fromFirebaseJson, each rules file’s
findings, once per file, with its file.
Returns
simulate()
simulate(cases: RtdbCase[]): RtdbSimulationSummary;
Run every case. Never throws on a rule outcome.
Parameters
| Parameter | Type |
|---|---|
cases | RtdbCase[] |
Returns
toJSON()
toJSON(): RtdbRulesJson;
The compiled rules.json. On a ruleset from
rtdbRules.fromFirebaseJson, the default instance’s rules; it
throws when firebase.json deploys none to the default instance.
Returns
RtdbRulesFinding
Properties
| Property | Type |
|---|---|
code | string |
message | string |
path | string |
rule | RtdbRulesFindingRule |
RtdbSimulationSummary
Properties
| Property | Type | Description |
|---|---|---|
cases | RtdbCaseResult[] | - |
coverage | RtdbCoverageSummary | Which rule nodes the cases evaluated, and which they never reached. |
failed | number | - |
passed | number | - |
unsupported | number | - |
RuleEvaluation
Per-rule evaluation entry produced by the local simulator. Each entry
corresponds to one allow declaration the simulator evaluated, in
source order.
Populated only by the internal simulator (which has the parsed
AST in hand); the production Test API client (TestFirestoreRulesHandler)
returns an empty trace and surfaces the wire text on TestResult.notes.
Properties
| Property | Type | Description |
|---|---|---|
citation? | string | - |
col? | number | - |
column? | number | - |
conditionText? | string | Pretty-printed condition expression. Use this verbatim in agent-facing summaries — derived from the AST via printExpression, so it survives comment removal and whitespace re-flow in the source. |
evaluatedExpressions? | number | Expressions the request had evaluated when this rule’s evaluation ended, counting every earlier rule and match block (see TestResult.evaluatedExpressions for the unit). Populated by the local simulator; absent on production Test API results. |
expressionTrace? | ExprTraceEntry[] | Per-sub-expression evaluation trace for this rule’s condition. Flat, in evaluation order; reconstruct the tree via the parent index on each entry. Populated by the local simulator when the caller enables tracing — currently always on for the simulator so agents can see why a rule’s condition resolved as it did (which disjunct was true, which let binding the value flowed through, which method call threw). Absent on entries that came from the production Test API client (no AST visibility). |
file? | string | - |
line? | number | 1-indexed source line of the allow keyword. Populated when the rule’s loc was set by the parser. |
matchPath? | string | Source-rendered path of the match block this rule belongs to, e.g. '/docs/{docId}' or '/{document=**}'. Populated when the request path matches MORE THAN ONE overlapping match block: allows OR-combine across every matching block (production semantics — there is no first-match-wins), so a DENY trace can carry entries from several blocks. This field keeps them unambiguous — which block did this rule live in. Absent for the common single-block case. |
message? | string | Human-readable diagnostic — populated for UNSUPPORTED (which sim surface is missing) and ERROR (which runtime error caused the rule to abort). |
operations | ("read" | "write" | "delete" | "get" | "list" | "create" | "update")[] | Operations declared on the allow rule (read, write, get, …). |
ruleIndex | number | Position of the allow declaration within its match block, 0-indexed in source order. |
verdict | "ERROR" | "UNSUPPORTED" | "ALLOW" | "DENY" | Outcome for this single rule. The TestResult’s overall decision is derived from the trace under OR semantics (any 'ALLOW' ⇒ ALLOW, else any 'UNSUPPORTED' ⇒ UNSUPPORTED, else DENY). |
RuleIssue
Properties
| Property | Type | Description |
|---|---|---|
code | string | Stable machine code, e.g. 'PARSE_ERROR', 'SEC-4', 'GET_BUDGET'. |
file? | string | The Realtime Database rules file the issue is in, as firebase.json names it, for a ruleset read with rtdbRules.fromFirebaseJson. |
fix? | string | Suggested remediation, verbatim, when the producing stage offers one. |
line? | number | 1-indexed source line, when known. |
message | string | Human-readable description. |
origin | RuleIssueOrigin | - |
path? | string | Rules path the issue applies to, when known (e.g. '/users/{uid}'). |
rule? | ".read" | ".write" | ".validate" | The Realtime Database rule at path the issue applies to. Absent for Firestore issues and for an RTDB issue about the whole ruleset. |
severity | RuleIssueSeverity | - |
RulesetContext
Context passed to the callback overload of ruleset().
Properties
| Property | Type |
|---|---|
path | (path: string, def: PathDef) => void |
RulesResourceLimit
A per-request rules limit the local simulator enforces.
expressions: 1000 evaluated expressions (see TestResult.evaluatedExpressions).messageis production’s own: “Unable to evaluate the expression as the maximum of 1000 expressions to evaluate has been reached.”document-lookups: 10 distinct get(), exists(), getAfter() and existsAfter() document accesses.
line and column place an expressions limit where production reports
it: the 1-based line and column, in the evaluated source, of the
expression the request was evaluating when the budget ran out.
Properties
| Property | Type |
|---|---|
column? | number |
kind | "expressions" | "document-lookups" |
limit | number |
line? | number |
message | string |
SchemaRulesResult
Properties
ShapeOptions
Properties
ShapeResult
Properties
| Property | Type |
|---|---|
children | Record<string, PathDef> |
validate? | string |
SimulationSummary
Aggregate of a simulate(cases) run. Counts partition the cases:
passed + failed + unsupported === cases.length.
Properties
| Property | Type |
|---|---|
cases | CaseResult[] |
failed | number |
passed | number |
unsupported | number |
Type Aliases
Expr
type Expr = string;
Type alias for RTDB rule expression strings.
FieldRule
type FieldRule = "string" | "number" | "boolean" | Expr | PathDef;
A field’s rule in shape: a type name, an expression for its .validate, or a full path definition.
FirestoreMethod
type FirestoreMethod = typeof FIRESTORE_METHODS[number];
ListQuery
type ListQuery = z.infer<typeof ListQuerySchema>;
ListQueryWhereConstraint
type ListQueryWhereConstraint = z.infer<typeof ListQueryWhereConstraintSchema>;
RtdbCoverageKind
type RtdbCoverageKind = "read" | "write" | "validate" | "indexOn";
RtdbCoverageStatus
type RtdbCoverageStatus = "allow" | "deny" | "error" | "mixed" | "unsupported" | "never-evaluated";
allow,deny,error: every evaluation of the node had that outcome.mixed: the node had more than one of those outcomes.unsupported: the node’s expression could not be evaluated, every time.never-evaluated: no request in the run reached the node.
RtdbInstancesData
type RtdbInstancesData = {
instances: Record<string, Record<string, unknown>>;
};
A case’s data as one tree per database instance, keyed by instance name.
Properties
RtdbRuleEvaluation
type RtdbRuleEvaluation = z.infer<typeof RtdbRuleEvaluationSchema>;
RtdbRuleKind
type RtdbRuleKind = ".read" | ".write" | ".validate" | ".indexOn";
RtdbRulesFindingRule
type RtdbRulesFindingRule = ".read" | ".write" | ".validate" | "ruleset";
RtdbRulesJson
type RtdbRulesJson = {
rules: Record<string, unknown>;
};
Properties
RtdbRulesSimulationAuth
type RtdbRulesSimulationAuth =
| string
| {
tenant?: string;
token?: Record<string, unknown>;
uid: string;
}
| null;
RtdbRulesSimulationInput
type RtdbRulesSimulationInput = Omit<SimulationInput, "auth" | "mockData"> & {
auth?: RtdbRulesSimulationAuth;
data?: Record<string, unknown>;
mockData?: Record<string, unknown>;
};
Type Declaration
auth?
optional auth: RtdbRulesSimulationAuth;
data?
optional data: Record<string, unknown>;
mockData?
optional mockData: Record<string, unknown>;
RtdbStdlib
type RtdbStdlib = typeof rtdbStdlib;
RuleIssueOrigin
type RuleIssueOrigin = "parse" | "validate" | "lint";
The stage that produced the issue.
parse— the source did not parse, or broke a production compile limit; nothing downstream ran.validate— a structural/security finding on a parsed ruleset.lint— a budget/quality/hallucination warning.
RuleIssueSeverity
type RuleIssueSeverity = "error" | "warning" | "info";
Ordered by decreasing urgency. info is advisory.
Segment
type Segment =
| string
| {
$: string;
};
A path segment: string for literal, { $: name } for path variable.
Variables
allow()
const allow: () => Expr;
Always allow (true). Readable alias for always().
Returns
always()
const always: () => Expr;
Always allow (true).
Returns
AUTH_UID
const AUTH_UID: Segment;
auth.uid as a comparison value (unquoted in expressions)
authenticated()
const authenticated: () => Expr;
Returns
dataExists()
const dataExists: (path?: string) => Expr;
Check if data exists at current node or a child path
Parameters
| Parameter | Type |
|---|---|
path? | string |
Returns
dataParentVal()
const dataParentVal: (depth: number, field: string) => Expr;
Navigate up from data snapshot, then read a child field’s value
Parameters
| Parameter | Type |
|---|---|
depth | number |
field | string |
Returns
dataVal()
const dataVal: (path?: string) => Expr;
Read data value at current node or a child path (pre-write state)
Parameters
| Parameter | Type |
|---|---|
path? | string |
Returns
deny()
const deny: () => Expr;
Always deny (false).
Returns
eq()
const eq: (left: Expr, right: CompareValue) => Expr;
Equality: left == right (right is a literal value or runtime ref)
Parameters
| Parameter | Type |
|---|---|
left | Expr |
right | CompareValue |
Returns
expr()
const expr: (raw: string) => Expr;
Create an Expr from a raw expression string.
Parameters
| Parameter | Type |
|---|---|
raw | string |
Returns
fieldEnum()
const fieldEnum: (field: string, values: string[]) => Expr;
Field must be one of the allowed string values
Parameters
| Parameter | Type |
|---|---|
field | string |
values | string[] |
Returns
fieldIsBoolean()
const fieldIsBoolean: (field: string) => Expr;
Field must be a boolean
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
fieldIsNumber()
const fieldIsNumber: (field: string) => Expr;
Field must be a number
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
fieldIsString()
const fieldIsString: (field: string) => Expr;
Field must be a string
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
fieldOwnerOnly()
const fieldOwnerOnly: (field: string) => Expr;
Only the field owner (auth.uid == data.child(field).val()) can access
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
gt()
const gt: (left: Expr, right: number) => Expr;
Greater than: left > right
Parameters
| Parameter | Type |
|---|---|
left | Expr |
right | number |
Returns
hasChild()
const hasChild: (field: string) => Expr;
Incoming data must have a specific child field
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
hasChildren()
const hasChildren: () => Expr;
Incoming data must be an object with at least one child
Returns
hasRole()
const hasRole: (segments: Segment[], role: string) => Expr;
Cross-path role check via root lookup
Parameters
| Parameter | Type |
|---|---|
segments | Segment[] |
role | string |
Returns
immutable()
const immutable: (field: string) => Expr;
Field can be set on creation but never changed after
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
immutableSelf()
const immutableSelf: () => Expr;
This node’s own value can be set on creation but never changed
Returns
isNew()
const isNew: () => Expr;
Data at this path doesn’t exist yet (creation check)
Returns
lte()
const lte: (left: Expr, right: number) => Expr;
Less than or equal: left <= right
Parameters
| Parameter | Type |
|---|---|
left | Expr |
right | number |
Returns
neq()
const neq: (left: Expr, right: CompareValue) => Expr;
Inequality: left != right
Parameters
| Parameter | Type |
|---|---|
left | Expr |
right | CompareValue |
Returns
newDataExists()
const newDataExists: (path?: string) => Expr;
Check if incoming data exists at current node or a child path
Parameters
| Parameter | Type |
|---|---|
path? | string |
Returns
newDataIs()
const newDataIs: (type: "String" | "Number" | "Boolean") => Expr;
Check incoming data type at current node
Parameters
| Parameter | Type |
|---|---|
type | "String" | "Number" | "Boolean" |
Returns
newDataParentExists()
const newDataParentExists: (depth: number, field: string) => Expr;
Navigate up from newData snapshot, then check if a child field exists
Parameters
| Parameter | Type |
|---|---|
depth | number |
field | string |
Returns
newDataParentVal()
const newDataParentVal: (depth: number, field: string) => Expr;
Navigate up from newData snapshot, then read a child field’s value
Parameters
| Parameter | Type |
|---|---|
depth | number |
field | string |
Returns
newDataVal()
const newDataVal: (path?: string) => Expr;
Read incoming data value at current node or a child path (post-write state)
Parameters
| Parameter | Type |
|---|---|
path? | string |
Returns
ownerOrNew()
const ownerOrNew: (field: string) => Expr;
Anyone authenticated can create; only the field owner can edit
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
ownField()
const ownField: (field: string) => Expr;
Field-based ownership: auth.uid matches a value stored in a data field
Parameters
| Parameter | Type |
|---|---|
field | string |
Returns
pathOwnerOnly()
const pathOwnerOnly: (pathVar: string) => Expr;
Only the path owner (auth.uid == $pathVar) can access
Parameters
| Parameter | Type |
|---|---|
pathVar | string |
Returns
ref()
const ref: (expression: string) => Segment;
Wrap a runtime rule expression so comparisons emit it unquoted
Parameters
| Parameter | Type |
|---|---|
expression | string |
Returns
required()
const required: (...fields: string[]) => Expr;
All specified fields must be present in the incoming data. Single keys are
checked together with newData.hasChildren([...]); a nested path such as
‘puck/x’ is checked with newData.hasChild('puck/x'), joined with &&.
Every segment of every field must be a valid RTDB key.
Parameters
| Parameter | Type |
|---|---|
…fields | string[] |
Returns
rootEquals()
const rootEquals: (segments: Segment[], value: string) => Expr;
Check if a path’s value equals a specific string (via root)
Parameters
| Parameter | Type |
|---|---|
segments | Segment[] |
value | string |
Returns
rootExists()
const rootExists: (segments: Segment[]) => Expr;
Check if a path exists in the database (via root)
Parameters
| Parameter | Type |
|---|---|
segments | Segment[] |
Returns
rtdbRules
const rtdbRules: RtdbRulesConstructor;
Build a deep handle on a Realtime Database ruleset from the text of a
database.rules.json file, a definition, a compiled document, or compiled
{ rules } JSON.
Throws
when rules text is not JSON (after comments
and trailing commas) or has no top-level rules object.
rtdbStdlib
const rtdbStdlib: Readonly<{
auth: typeof auth;
collections: typeof collections;
counters: typeof counters;
lifecycle: typeof lifecycle;
lobby: typeof lobby;
membership: typeof membership;
presence: typeof presence;
results: typeof results;
timing: typeof timing;
turns: typeof turns;
validation: typeof validation;
}>;
transition()
const transition: (field: string, allowed: [string, string][]) => Expr;
State machine: only allowed transitions on a field
Parameters
| Parameter | Type |
|---|---|
field | string |
allowed | [string, string][] |
Returns
Functions
all()
function all(...exprs: string[]): string;
All conditions must be true (AND). An operand is parenthesized only when
it holds a top-level || or ternary, which binds looser than &&.
Empty and whitespace-only operands are dropped; with none left it throws, since an empty
conjunction would allow everything. Use always for that.
Parameters
| Parameter | Type |
|---|---|
…exprs | string[] |
Returns
string
any()
function any(...exprs: string[]): string;
At least one condition must be true (OR). An operand with a top-level &&
is parenthesized for the reader, and one with a ternary for the parser.
Empty and whitespace-only operands are dropped; with none left it throws, since an empty
disjunction would deny everything. Use deny for that.
Parameters
| Parameter | Type |
|---|---|
…exprs | string[] |
Returns
string
assertCase()
Call Signature
function assertCase(result: RtdbCaseResult | CaseResult): void;
Throw when a case result did not pass. A simulator abstention throws
RulesUnsupportedError; a genuine expectation mismatch throws
RulesAssertionError. Both carry the explainCase trace as
their message. Returns void on a passing result.
Parameters
| Parameter | Type |
|---|---|
result | RtdbCaseResult | CaseResult |
Returns
void
Call Signature
function assertCase(ruleset: FirestoreRuleset, oneCase: FirestoreCase): void;
Simulate one case against a ruleset and throw on a miss — the runner
form: for (const c of cases) test(c.description, () => assertCase(ruleset, c)).
Parameters
| Parameter | Type |
|---|---|
ruleset | FirestoreRuleset |
oneCase | FirestoreCase |
Returns
void
Call Signature
function assertCase(ruleset: RtdbRuleset, oneCase: RtdbCase): void;
Throw when a case result did not pass. A simulator abstention throws
RulesUnsupportedError; a genuine expectation mismatch throws
RulesAssertionError. Both carry the explainCase trace as
their message. Returns void on a passing result.
Parameters
| Parameter | Type |
|---|---|
ruleset | RtdbRuleset |
oneCase | RtdbCase |
Returns
void
Call Signature
function assertCase(source: string, oneCase: FirestoreCase): void;
Convenience: compile Firestore source and assert one case against it.
Parameters
| Parameter | Type |
|---|---|
source | string |
oneCase | FirestoreCase |
Returns
void
bytes()
function bytes(input: string | Uint8Array<ArrayBufferLike>): Bytes;
A bytes value.
- string → UTF-8 encoded
- Uint8Array → used verbatim
Parameters
| Parameter | Type |
|---|---|
input | string | Uint8Array<ArrayBufferLike> |
Returns
Bytes
canonicalRtdbExpression()
function canonicalRtdbExpression(raw: string): string;
Canonical text of an RTDB rule expression: two expressions with equal canonical texts evaluate identically for every request. Deterministic and idempotent. Throws RtdbExpressionSyntaxError for text that is not a rule expression.
Parameters
| Parameter | Type |
|---|---|
raw | string |
Returns
string
defineRtdbRules()
function defineRtdbRules(definition: RtdbRulesDefinition): RtdbRulesDocument;
Parameters
| Parameter | Type |
|---|---|
definition | RtdbRulesDefinition |
Returns
diffRtdbRules()
function diffRtdbRules(
deployed: Record<string, unknown>,
local: Record<string, unknown>,
options?: DiffRtdbRulesOptions): RtdbRuleChange[];
Node-level diff of two rules trees, ordered by path then rule kind.
Parameters
| Parameter | Type |
|---|---|
deployed | Record<string, unknown> |
local | Record<string, unknown> |
options? | DiffRtdbRulesOptions |
Returns
duration()
function duration(value: number, unit?: string): Duration;
A duration value. unit is one of the Firestore duration units
('w' | 'd' | 'h' | 'm' | 's' | 'ms' | 'ns'); defaults to seconds.
Parameters
| Parameter | Type |
|---|---|
value | number |
unit? | string |
Returns
Duration
explainCase()
function explainCase(result: RtdbCaseResult | CaseResult): string;
Render a case result as a human-readable trace. The single sanctioned
trace renderer — used as the message of the error assertCase throws, and
available directly for logging a result without asserting.
Parameters
| Parameter | Type |
|---|---|
result | RtdbCaseResult | CaseResult |
Returns
string
firestoreRules()
function firestoreRules(source: string): FirestoreRuleset;
Compile Firestore rules source into a deep, safe-by-default handle.
Parameters
| Parameter | Type |
|---|---|
source | string |
Returns
Throws
when the source does not parse, names a
service other than cloud.firestore, declares one service twice, or breaks one of production’s
compile limits. The thrown error carries the
compile-blocking issues on .issues.
flip()
function flip(marks: string[]): string;
Turn flip: validates a turn field alternates between marks. First mark is the initial value on creation. Supports 2+ players with circular rotation.
Parameters
| Parameter | Type | Description |
|---|---|---|
marks | string[] | ordered list of marks (e.g., [“X”, “O”]) |
Returns
string
isMember()
function isMember(listName: string, pathVarName: string): string;
Cross-path membership check: root.child(list).child($var).child(auth.uid).exists()
Parameters
| Parameter | Type |
|---|---|
listName | string |
pathVarName | string |
Returns
string
latlng()
function latlng(lat: number, lng: number): LatLng;
A latlng geographic point.
Parameters
| Parameter | Type |
|---|---|
lat | number |
lng | number |
Returns
LatLng
Throws
for a latitude outside -90 to 90 or a longitude outside -180 to 180.
lint()
function lint(source: string): RuleIssue[];
Lint Firestore rules source. Accepts anything — including empty or syntactically broken source — and always returns an issue list.
Parameters
| Parameter | Type |
|---|---|
source | string |
Returns
lit()
function lit(value: Literal): string;
A rules literal: a single-quoted string with \ and ' escaped, a finite
number, a boolean, or null. Every builder writes its literals through this,
so compiled rules use one quote style.
The quote and backslash escapes match Pyric’s rules simulator. A string with a newline or another control character is refused: Pyric does not model escapes for those, and production behavior for them is not captured.
Parameters
| Parameter | Type |
|---|---|
value | Literal |
Returns
string
not()
function not(e: string): string;
Negate a condition. A member chain such as data.child('a').exists() needs no parentheses.
Parameters
| Parameter | Type |
|---|---|
e | string |
Returns
string
ownPath()
function ownPath(pathVar: string): string;
Path-based ownership: auth.uid matches a URL path variable
Parameters
| Parameter | Type |
|---|---|
pathVar | string |
Returns
string
reference()
function reference(path: string): Reference;
A reference to a document, by its path (e.g. "users/alice").
Parameters
| Parameter | Type |
|---|---|
path | string |
Returns
Reference
renderRtdbCoverage()
function renderRtdbCoverage(summary: RtdbCoverageSummary): string;
One line per rule node, then the per-file totals and the nodes never evaluated.
Parameters
| Parameter | Type |
|---|---|
summary | RtdbCoverageSummary |
Returns
string
ruleset()
function ruleset(input:
| Record<string, PathDef>
| (ctx: RulesetContext) => void): RtdbNode;
Compile a declarative rules definition into an environment-independent tree.
Parameters
| Parameter | Type |
|---|---|
input | | Record<string, PathDef> | (ctx: RulesetContext) => void |
Returns
RtdbNode
schemaRules()
function schemaRules(schema: ZodObject<any>, fieldConstraints?: Record<string, Expr[]>): SchemaRulesResult;
Generate RTDB validate rules from a Zod object schema. Optional fieldConstraints are AND-composed with the schema type check.
Parameters
| Parameter | Type |
|---|---|
schema | ZodObject<any> |
fieldConstraints? | Record<string, Expr[]> |
Returns
serverTimestamp()
function serverTimestamp(): {
};
The server-timestamp sentinel — the case-data equivalent of
FieldValue.serverTimestamp() and serverTimestamp(). The simulator
resolves it to the request time (request.time in Firestore, now in
Realtime Database), so a rule comparing a timestamp field to the server
clock sees a match.
Returns
{
}
timestamp()
function timestamp(input:
| string
| number
| Date
| {
nanos?: number;
seconds: number;
}): Timestamp;
A Firestore timestamp value.
- number → milliseconds since the epoch
- string → ISO-8601 with
Zor an explicit offset - Date → its instant
- object → explicit
{ seconds, nanos }
Parameters
| Parameter | Type |
|---|---|
input | | string | number | Date | { nanos?: number; seconds: number; } |
Returns
Timestamp
Throws
for an input that names no instant, such as 'nope',
an ISO string without an offset, an invalid Date, or NaN.
turnGuard()
function turnGuard(
turnField: string,
players: Record<string, string>,
statusField?: string,
playingValue?: string): string;
Turn enforcement: only the current turn’s player can write. Uses data (pre-write) for the turn check — NOT newData.
Parameters
| Parameter | Type | Description |
|---|---|---|
turnField | string | the field that stores whose turn it is (e.g., “currentTurn”) |
players | Record<string, string> | map of mark → player field (e.g., { X: “playerX”, O: “playerO” }) |
statusField? | string | optional field that must equal playingValue for moves to be allowed |
playingValue? | string | the value of statusField during active play (e.g., “playing”) |
Returns
string
vector()
function vector(values: readonly number[]): Vector;
A vector value from its numeric components.
Parameters
| Parameter | Type |
|---|---|
values | readonly number[] |
Returns
Vector
Throws
for a component that is not a finite number.
winCheckHelper()
function winCheckHelper(
mark: string,
lines: number[][],
boardPath?: string): string;
Win check helper: validates a boolean field against winning lines on a board. If true, at least one winning line must exist. If false, no winning line can exist. Uses the “client claims, rules verify” pattern.
Parameters
| Parameter | Type | Description |
|---|---|---|
mark | string | the player mark to check (e.g., “X”) |
lines | number[][] | array of winning line coordinates (e.g., [[0,1,2], [3,4,5], …]) |
boardPath? | string | the path to the board relative to the parent (default “board”) |
Returns
string