Functions Engine
TypeScript triggers on collection and auth events. Implemented in Milestone 5.
Location
src/core/functions/
types.ts—FunctionContext,FunctionsEngine,RegisteredTriggertriggers.ts—onCreate,onUpdate,onDelete,onLogin,onRegister(exported asbakend/functions)trigger-registry.ts— per-discovery trigger registration stackdiscover.ts— scansfunctions/**/*.ts, resolvesbakend/functionsimportscreate-functions-engine.ts— loads triggers, subscribes to Event Bus, emits lifecycle eventswatch.ts—fs.watchdebounced reload for hot reload
Trigger API
import { onCreate, onUpdate, onDelete } from "bakend/functions";
onCreate("posts", async ({ record, db, logger, event }) => {});
| Helper | Event type |
|---|---|
onCreate(collection, fn) | {collection}.created |
onUpdate(collection, fn) | {collection}.updated |
onDelete(collection, fn) | {collection}.deleted |
onLogin(collection, fn) | auth.login |
onRegister(collection, fn) | auth.register |
Discovery
- Path:
{projectRoot}/functions/(sibling tobakend.json) - Missing directory is skipped (no error)
bakend/functionsimports are rewritten to the runtime triggers module before import- Transformed modules cached under
functions/.bakend-cache/
Engine API
const functions = createFunctionsEngine({
eventBus, db, logger,
functionsDir: join(projectDir, "functions"),
watch: false,
});
await functions.load();
functions.list(); // RegisteredTrigger[]
functions.reload(); // re-discover and re-subscribe
functions.shutdown();
Wired into start() via StartResult.functions.
Lifecycle Events
Emitted by the functions engine (source: functions):
function.startedfunction.completedfunction.failed
Hot Reload
bak dev— starts withwatch: truebak start --watch— same behavior via flag- Uses
fs.watchwith 100ms debounce
Rules
- Functions subscribe via Event Bus only (never called from record-store directly)
- Handler errors never crash the process
- Same-process execution in M5 (no worker sandbox)
onLogin/onRegisterfire onauth.login/auth.registerevents (Milestone 7)auth.useris populated in function context for auth eventsstorage.get(id)/storage.delete(id)available in function context (Milestone 8)
Deferred
- HTTP functions, scheduled functions, secrets
- Worker sandbox isolation
bak functionsCLI management- Dashboard functions viewer