Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

Extensions

Extend a client with calls, units, arguments, rules, defaults, methods and computed fields, each part paying only for itself

$extends() returns an immutable derived client. The base client is unchanged, and the derived client carries one ordered extension chain and its own operation scope.

import { around, extension } from "viborm";

const timing = extension(
  "timing",
  around(() => async (run) => {
    const startedAt = performance.now();
    const value = await run();
    recordDuration(performance.now() - startedAt);
    return value;
  })
);

const measured = client.$extends(timing);

An extension is always applied the same way: client.$extends(extension), where extension is a value built by extension(name, ...parts) or returned by an official extension, such as client.$extends(permissions({...})). $extends() takes no object literal and no function of the client.

The parts

An extension has one name and up to eight parts, each built by a function imported from viborm. Each part brings into your bundle the code that runs it, and nothing else:

Part Boundary Authority
call A logical model or raw call, before validation Patch the arguments with a synchronous shallow patch, or refuse the call
around The prepared call Wrap execution; a read outside an array can answer without it
unit A real unit of work: operation, statement, batch, transaction, savepoint, connection Observe its end; a declared part may rewrite a statement
args A call’s arguments Declare an argument; only the declaring extension’s parts and the chain’s rules read its value
rule The rows every call of the client reads and writes Filters, write judgements, gated fields and kept rows, per model, in the ORM’s own where and data
defaults What a call gets when it says nothing Default order, default data and default omission, per model; the caller can override them
methods, modelMethods The derived client, its model delegates Add typed $-prefixed client methods; add model methods
fields The rows an operation returns Fields computed from each row’s needs, selectable and omittable by name
disclosure The errors a call throws Whether they may carry SQL, parameters, provider details and the call site

Inside the parts, words imported from viborm carry the rest, each with its own code: target(...) and the sets reads, writes, deletes, selecting, models say which calls a call or an around concerns; watch, settled, again, via, key, codec and database serve the moments of a call; oneOf, accepts and bound declare an argument; arg, now, row, exists, when, unless, provided, nothing, only, check, gate, facts, keep, lazy and within write rules; omitted writes a default omission; text, parameters, driver, failure, statement, statements, run, work, note, notes and the others read and emit units, and disclosed presents a failure. See Create an extension.

These are one extension language, not one universal hook. A first moment is synchronous and runs before validation. A second moment is asynchronous and the child it runs is authoritative. A unit wraps physical work, and a rewrite is trusted low-level SQL. Methods change the static surface. Rules and defaults are plain data: the engine applies them at every place they concern, so an extension declares what it wants instead of rewriting queries.

Official extensions

Official extensions are built from the same public parts and applied in one step, client.$extends(softDelete(config)). All seven import only names any author can import: the instrumentation presents a failure through disclosed, as any logging extension does:

Operation lifecycle

Calling a model method still creates a lazy operation. Its parts start only when that operation is awaited or admitted to an array transaction. A methods factory runs when the client $extends() returns is built, and in every other view when what it returns is first read:

unit `operation` begins                                     [unit]
  extension arguments taken out of the arguments, validated  [args]
  first moments, in chain order                             [call]
  default omission                                          [defaults]
  computed fields planned                                   [fields]
  validation and preparation
  second moments, nested, the first applied outermost       [around]
    { inner: true } parts (the official cache), closest to the core
      planning and compilation
      for each logical statement
        rewrites, in chain order                            [unit, rewrites]
        rendering, parameter snapshot, connection
        unit `statement` begins, one per physical send      [unit]
          driver
      result read
  computed fields attached (computed when first read)
unit `operation` ends

Rules and defaults are not a moment: the engine applies them wherever a model appears in the query.

Array transactions add one outer batch unit. Every member completes its first moments and reaches run() in its second before provider work begins. Fallback execution then runs members in order inside the real transaction or savepoint; a native batch uses one provider submission while retaining one logical operation per member and one statement unit for the submission.

A rewrite receives safe model statements and tagged/fragment raw Sql. It excludes verbatim $queryRawUnsafe and $executeRawUnsafe text, whose physical execution is still a statement unit.

Continuation authority

For writes and raw queries, a matched around must call run() exactly once. Reads outside an array may deliberately return without it. Once run() starts, the child’s result or error is authoritative: returning a fabricated value does not replace a failure, and a child that fails fails the call with its own error, whatever the handler throws after. There is no aggregated error.

In $transaction([...]), all matched second moments must reach run() before any provider work. A refusal, double call, late detached call, or rejected handler aborts admission and submits nothing.

Observation

A unit part wraps a real unit of work and reads its end:

import { extension, unit } from "viborm";

const audit = extension(
  "audit",
  unit(async (u, next) => {
    const end = await next();
    record({ kind: u.kind, model: u.model, operation: u.operation, end });
    return end;
  })
);

Units are operation, statement, batch, transaction, savepoint, connection, and the kinds extensions emit with work (the official cache emits cache): a kind is an open string. The end has the status, duration, and commit certainty where there is a commit; it never carries the application result.

Facts are read on demand, through words imported from viborm: text(u), parameters(u), driver(u), failure(u) and the others in Create an extension. A fact no word reads is never produced.

A unit handler runs in the call: VibORM awaits it, and what it throws fails the call. An observer that must never affect the application contains its own failures, as the official instrumentation() does.

Authorization boundary

Calls, rules and defaults are useful policy foundations, but a root filter is not complete authorization. Nested reads and writes, relation membership, field use, raw SQL, and statement rewrites need one graph-wide semantic policy owner. viborm/permissions is that owner: one predicate per model and action, judged in the statement at every scope; raw SQL and statement rewrites still see every row. Omission is presentation control, not authorization: query-level and default omission can be overridden, and even model .omit() does not replace database authorization. A rule, and the soft-delete extension built on one, decides which rows are visible, not who may see them: any caller can pass another value of an argument unless it is a bound one, and raw SQL ignores them. A tenant filter keeps a call inside the tenant it names; your server, not the caller, must choose that tenant.

Was this page helpful?