@stratware/swrules
v0.1.1
Published
Firebase security rules generator and validator for people by Stratware
Maintainers
Readme
firerules
Purpose
firerules is a small JavaScript builder for generating Firebase Firestore security rules programmatically. It lets you define rules in a structured way and emits a valid Firestore rules file as a string.
How it works
Call the exported firerules function with a define callback.
The callback receives an object containing match and helpers, which you use to declare match blocks and allow rules.
firerules returns an object with a build() method that produces the complete Firestore rules text.
Minimal usage
import { firerules } from './index.js';
const rules = firerules(({ match, helpers }) => {
match('/posts/{postId}', ({ allow }) => {
allow('read').when(helpers.authenticated);
allow(['create', 'update']).when(helpers.owner('ownerId'));
});
});
console.log(rules.build());API summary
firerules(define)Main entry point. Callsdefinewith{ match, helpers }.match(path, buildCallback)Declares a Firestorematchblock.pathmust follow the builder’s Firestore-style pattern (leading slash, path segments with alphanumerics, underscores, hyphens, and{vars}).buildCallbackreceives an object exposingallow.allow(ops)Declares anallowrule inside a match block.opsmay be a single operation or an array of operations. Chain.when(condition),.if(condition), or.then(condition)to attach the rule condition. These methods are aliases with identical behavior.helpersA collection of predefined helper expressions that can be passed to.when(),.if(), or.then().build()Returns the final Firestore rules string, including:rules_versionservice cloud.firestore- Generated helper functions
- All declared match blocks and rules
Built-in helpers
Authentication and identity
authenticated,uid,admin,denyAllOperation state
creating,updating,deletingOwnership
owner(field),ownerOnCreate(field)Field immutability and change control
immutable(fields[]),changedOnly(fields[]),unchanged(fields[])Field presence constraints
fieldsOnly(fields[]),fieldsAtLeast(fields[])Size limits
maxArray(field, size),maxString(field, size)Composition and utilities
pathVarEquals(varName, expr),and(...),or(...),not(cond)
Important details
Valid operations are:
read,get,list,create,update,delete,write. Thewriteoperation expands tocreate,update, anddelete.Helper expressions are de-duplicated. Identical expressions are emitted once as generated Firestore functions:
function f_xxx() { return <expr>; }The builder logs warnings when:
- A very large number of match blocks is produced
- The generated rules text exceeds approximately 200 KB
