Conventions
Conventions minimize decision-making and improve consistency.
This page and the guides it links to explain Evolu's coding conventions.
The repository's AGENTS.md is a selective summary for routine agent work,
with additional repository workflow instructions. Keep shared rules consistent;
not every convention needs a summary there. Agents should read only the relevant
documentation section when clarification is needed or when reviewing or changing
a convention.
Imports and exports
Use named exports and named imports.
Use a default export only when a framework or tool API requires one. Namespace imports are allowed for third-party namespace APIs.
import { ok, trySync } from "@evolu/common";
export { ok, trySync };
Avoid namespaces. Use unique names because Evolu re-exports everything through a single index.ts.
// Use: export each unique name.
export const emptyArray: ReadonlyArray<never> = [];
export const emptyRecord: Readonly<Record<string, never>> = {};
// Avoid: a namespace-like object hides the names from the shared index.
export const Empty = { array: emptyArray, record: emptyRecord };
Naming conventions
- Types — PascalCase:
Eq,Order,Result,Millis - Type instances — type prefix + TypeSuffix:
eqString,eqNumber,orderString,orderBigInt - Operations — verb + TypeSuffix:
mapArray,filterSet,sortArray,addToSet - Conversions —
xToY(often symmetric pairs):ownerIdToOwnerIdBytes/ownerIdBytesToOwnerId,durationToMillis - Factories —
createX:createTime,createStore,createRun - Library-exported test helpers —
testX:testCreateDeps,testCreateRun,testCreateTime,testSetupSqlite - Empty constants —
emptyX:emptyArray,emptySet,emptyRecord - Predicates —
isX:isNonEmptyArray,isBetween,isBetweenBigInt - Accessors — position +
InX:firstInArray,lastInArray,firstInSet - Indexed collections — value +
By+ key (vByK):rowsByQuery,messagesByOwnerId,usersById - Dependencies —
XDep:TimeDep,RandomDep,ConsoleDep - Domain errors — interface
XError; omitErrorfrom the discriminant only when the remaining name clearly describes a failure:UserNotFoundErrorextendsTyped<"UserNotFound">, whileTimeoutErrorkeeps"TimeoutError"
Reusable test setup helpers should be named after what they set up: use setupFoo
for local helpers and helpers shared from test-only files such as _deps.ts.
Use the test prefix only for test helpers exported from library modules.
Consistent prefixes enable discoverability—type map and autocomplete shows mapArray, mapSet, mapObject, mapSchedule without importing first.
Use globalThis for globals whose names overlap local APIs, such as
globalThis.Worker. Variable shadowing is allowed.
Order (top-down readability)
Many developers naturally write code bottom-up, starting with small helpers and building up to the public API. However, Evolu optimizes for reading, not writing, because source code is read far more often than it is written. By presenting the public API first—interfaces and types—followed by implementation and implementation details, the developer-facing contract is immediately clear.
Think of it like painting—from the whole to the detail. The painter never starts with details, but with the overall composition, then gradually refines.
Group declarations by feature. Finish each feature before starting the next; do not collect all exported declarations at the top of the module. Within a feature, put the public contract and its supporting types before the implementation. Shared helpers and private implementation types follow the implementation.
import { assertEqual } from "@evolu/common";
// Public interface first: the contract developers rely on.
interface Foo {
readonly bar: Bar;
}
// Supporting types next: details of the contract.
interface Bar {
readonly name: string;
}
// Implementation after: how the contract is fulfilled.
const foo: Foo = { bar: { name: "Evolu" } };
// Shared helpers and private implementation types follow, if needed.
assertEqual(foo.bar.name, "Evolu");
Error types are part of the public contract, just like success types. Place both before the implementation so readers can understand the possible outcomes before reading how the function works.
import {
assertErr,
assertOk,
err,
ok,
type Result,
type Typed,
} from "@evolu/common";
interface User {
readonly id: string;
}
interface UserNotFoundError extends Typed<"UserNotFound"> {}
const getUser = (id: string): Result<User, UserNotFoundError> =>
id === "user-1" ? ok({ id }) : err({ type: "UserNotFound" });
assertOk(getUser("user-1"), { id: "user-1" });
assertErr(getUser("user-2"), { type: "UserNotFound" });
Keep an inferred output interface immediately after its Evolu Type value, as shown under Interface over type.
Place orchestration before the lower-level operations it calls. There is one
runtime constraint: a const helper must be initialized before a module
initializer calls it, including through another function. Otherwise module
evaluation can fail before initialization is complete.
Do not extract a helper used only once; inline it. Keeping the operation in place lets the reader follow the code without jumping to another declaration. Meaningful local constants can explain intermediate values within that flow.
Immutability
Immutable data makes reference equality useful for detecting changes. When a reference stays the same, consumers can skip work because its contents have not changed. A new reference may contain equal data. Preserving the original reference for unchanged data can avoid unnecessary rendering and recomputation.
import { assertEqual, assertSame, assertTrue } from "@evolu/common";
// Mutable: the same reference now holds different content.
const mutableItems = [1, 2, 3];
const previousItems = mutableItems;
mutableItems.push(4);
assertSame(mutableItems, previousItems);
assertEqual(mutableItems, [1, 2, 3, 4]);
// Immutable: a new reference signals the change.
const items = [1, 2, 3];
const nextItems = [...items, 4];
assertTrue(items !== nextItems);
assertEqual(items, [1, 2, 3]);
assertEqual(nextItems, [1, 2, 3, 4]);
Mutation causes unintended side effects, makes code harder to predict, and complicates debugging. Evolu public functions do not mutate application data passed to them. Low-level APIs may mutate explicitly mutable values, such as buffers, when mutation is part of their contract. Prefer immutable update patterns for application data.
Local mutation is allowed as an implementation detail when useful for performance. A function may mutate a value it exclusively owns while constructing its result, but mutation must stop before returning it as immutable data. Explicitly mutable APIs may retain mutable state as part of their contract. Use readonly types to describe immutable APIs, but do not mistake them for runtime immutability or an ownership system.
Readonly types
Use readonly types for collections and prefix interface properties with readonly:
ReadonlyArray<T>andNonEmptyReadonlyArray<T>for arraysReadonlySet<T>for setsReadonlyRecord<K, V>for recordsReadonlyMap<K, V>for maps
import { assertEqual, assertTrue } from "@evolu/common";
// Use ReadonlyArray for immutable arrays.
const values: ReadonlyArray<string> = ["a", "b", "c"];
// Use readonly for interface properties.
interface Example {
readonly id: number;
readonly items: ReadonlyArray<string>;
readonly tags: ReadonlySet<string>;
}
const example: Example = { id: 1, items: values, tags: new Set(["a"]) };
assertEqual(example.items, ["a", "b", "c"]);
assertTrue(example.tags.has("a"));
// @ts-expect-error Index signature in type 'readonly string[]' only permits reading.
values[0] = "d";
// @ts-expect-error Cannot assign to 'id' because it is a read-only property.
example.id = 2;
Readonly in TypeScript is only a static constraint. It prevents direct mutation through that particular type, but it does not freeze the value or prove the value is actually immutable. A mutable alias can still change it, and TypeScript can allow a readonly object to be passed to a function accepting a mutable type.
import { assertEqual } from "@evolu/common";
const mutable = [1, 2, 3];
const items: ReadonlyArray<number> = mutable;
mutable.push(4);
assertEqual(items, [1, 2, 3, 4]);
const mutateRecord = (value: Record<string, number>): void => {
value.count = 1;
};
const record: Readonly<Record<string, number>> = {};
// TypeScript accepts the readonly record for the mutable parameter.
mutateRecord(record);
assertEqual(record, { count: 1 });
Treat readonly types as a contract for APIs that already maintain immutability. Do not cast mutable values to readonly just to satisfy the type checker. A value may be built through local mutation and then returned as readonly, provided that it is not mutated after leaving the constructing function.
Evolu also provides helpers in the Array and Object modules that do not mutate and preserve readonly types.
Interface over type
Use interface over type because interfaces retain their names in error
messages and tooltips, while type aliases can be expanded into their underlying
types.
Use type only when necessary:
- Union types:
type Status = "pending" | "done" - Mapped types, tuples, or type utilities
- Intersections that compose dependencies, such as
ConsoleDep & TimeDep
Use
interfaceuntil you need to use features fromtype.
Evolu Type objects
For Evolu Type objects created with object() or typed(), use an interface with InferType. TypeScript displays the interface name instead of expanding all properties.
import {
Number,
String,
assertOk,
object,
type InferType,
} from "@evolu/common";
const User = object({ name: String, age: Number });
interface User extends InferType<typeof User> {}
const user: User = { name: "Ada", age: 36 };
assertOk(User.fromUnknown(user), user);
Avoid the type alias type User = typeof User.Output because TypeScript expands
all properties of a type alias in tooltips and error messages.
Arrow functions
Use arrow functions instead of the function keyword.
import { assertEqual } from "@evolu/common";
interface User {
readonly name: string;
}
const createUser = (name: string): User => ({ name });
assertEqual(createUser("Ada"), { name: "Ada" });
Do not write function createUser(name: string): User { ... }. The shared lint
configuration reserves function declarations for overloads.
Why arrow functions?
- Consistency - Functions and readonly function-valued interface properties use the same concise syntax
- No dynamic
this- Arrow functions retain their lexicalthiswhen passed around as values - Conciseness - Callbacks, small functions, and currying need little syntax
Exception: function overloads. While overloading with arrow functions is possible (using a type with multiple call signatures), it can be hard to type properly because the implementation must satisfy all overloads at once, which TypeScript often can't verify without assertions. Use the function keyword instead:
import {
assertEqual,
assertType,
type NonEmptyReadonlyArray,
} from "@evolu/common";
function mapArray<T, U>(
array: NonEmptyReadonlyArray<T>,
mapper: (item: T) => U,
): NonEmptyReadonlyArray<U>;
function mapArray<T, U>(
array: ReadonlyArray<T>,
mapper: (item: T) => U,
): ReadonlyArray<U>;
function mapArray<T, U>(
array: ReadonlyArray<T>,
mapper: (item: T) => U,
): ReadonlyArray<U> {
return array.map(mapper);
}
const nonEmpty: NonEmptyReadonlyArray<number> = [1, 2];
const doubled = mapArray(nonEmpty, (value) => value * 2);
assertType<typeof doubled, NonEmptyReadonlyArray<number>>();
assertEqual(doubled, [2, 4]);
In interfaces too. Use readonly function-valued properties rather than
method shorthand such as bar(value: string): void. This keeps contracts
consistent with our arrow-function implementations.
import { assertEqual } from "@evolu/common";
interface Foo {
readonly bar: (value: string) => void;
readonly baz: () => number;
}
const values: Array<string> = [];
const foo: Foo = {
bar: (value) => {
values.push(value);
},
baz: () => values.length,
};
foo.bar("a");
assertEqual(foo.baz(), 1);
Function options
For functions with optional configuration, inline single-use, non-exported
options types without readonly. Use a named interface with readonly
properties when the options type is exported or used by more than one function.
Destructure options in the parameter list.
Inline types when options are single-use and not exported:
import { assertEqual } from "@evolu/common";
const formatName = (
name: string,
{
trim = true,
}: {
// Whether surrounding whitespace is removed.
trim?: boolean;
} = {},
): string => (trim ? name.trim() : name);
assertEqual(formatName(" Ada "), "Ada");
assertEqual(formatName(" Ada ", { trim: false }), " Ada ");
Named interfaces when options are exported or reused:
import { assertEqual, durationToMillis, type Duration } from "@evolu/common";
export interface BackoffOptions {
readonly maxAttempts?: number;
readonly delay?: Duration;
readonly backoff?: "linear" | "exponential";
}
export const backoffDelays = ({
maxAttempts = 3,
delay = "1s",
backoff = "exponential",
}: BackoffOptions = {}): ReadonlyArray<number> => {
const base = durationToMillis(delay);
const delays: Array<number> = [];
for (let attempt = 0; attempt < maxAttempts; attempt++) {
delays.push(
backoff === "linear" ? base * (attempt + 1) : base * 2 ** attempt,
);
}
return delays;
};
assertEqual(backoffDelays(), [1000, 2000, 4000]);
assertEqual(backoffDelays({ backoff: "linear", maxAttempts: 2 }), [1000, 2000]);
React components
Type React components as FC<Props>. Keep props inline, without readonly, and
destructure them in the parameter, also for exported components. Destructuring
leaves the props object unreachable, so readonly would add nothing. Declare
children as ReactNode, required unless the component works without it.
PropsWithChildren would make it optional.
import { assertEqual } from "@evolu/common";
import type { FC, ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
export const Section: FC<{ title: string; children: ReactNode }> = ({
title,
children,
}) => (
<section>
<h2>{title}</h2>
{children}
</section>
);
assertEqual(
renderToStaticMarkup(<Section title="Todos">Buy milk</Section>),
"<section><h2>Todos</h2>Buy milk</section>",
);
// @ts-expect-error Section requires children.
const _empty = <Section title="Todos" />;
A component that only forwards its props, such as an icon that spreads them
onto <svg>, takes props whole. A value typed as FC cannot be generic, so
a generic component annotates its parameter instead.
Switch exhaustiveness
In a side-effecting switch over a union, call exhaustiveCheck in default.
This makes missing cases fail at compile time. Its throw runs only on a branch
the type rules out, so it costs nothing for valid values and turns an
impossible case into a loud failure instead of a silent no-op.
For value-producing switches, return from every case and omit default so TypeScript enforces
exhaustiveness through the return type.
import { assertEqual, exhaustiveCheck } from "@evolu/common";
type Message =
| { readonly type: "Create" }
| { readonly type: "Update" }
| { readonly type: "Delete" };
const handledTypes: Array<string> = [];
// Side-effecting switch: exhaustiveCheck guards the default branch.
const handleMessage = (message: Message): void => {
switch (message.type) {
case "Create":
handledTypes.push("created");
break;
case "Update":
handledTypes.push("updated");
break;
case "Delete":
handledTypes.push("deleted");
break;
default:
exhaustiveCheck(message);
}
};
// Value-producing switch: every case returns, so no default is needed.
const messageToVerb = (message: Message): string => {
switch (message.type) {
case "Create":
return "create";
case "Update":
return "update";
case "Delete":
return "delete";
}
};
handleMessage({ type: "Create" });
assertEqual(handledTypes, ["created"]);
assertEqual(messageToVerb({ type: "Delete" }), "delete");
Avoid getters and setters
Avoid JavaScript getters and setters. Use simple readonly properties for stable values and explicit methods for values that may change.
Getters break the readonly contract. In Evolu, readonly properties signal stable values you can safely cache or pass around. A getter disguised as a readonly property violates this expectation—it looks stable but might return different values on each access.
Setters hide mutation and conflict with readonly. Evolu uses readonly properties everywhere for immutability. Setters are incompatible with this approach and make mutation invisible—obj.value = x looks like simple assignment but executes arbitrary code.
Use explicit methods instead. When a value can change or requires computation, use a method like getValue(). The parentheses signal "this might change or compute something" and make the behavior obvious at the call site. A readonly property like readonly id: string communicates stability—you can safely cache, memoize, or pass the value around knowing it won't change behind your back.
import { assertEqual } from "@evolu/common";
interface Counter {
// Stable: safe to cache.
readonly id: string;
// Changes over time: an explicit function signals it.
readonly getValue: () => number;
readonly increment: () => void;
}
const createCounter = (id: string): Counter => {
let value = 0;
return {
id,
getValue: () => value,
increment: () => {
value++;
},
};
};
const counter = createCounter("clicks");
const cachedValue = counter.getValue();
counter.increment();
assertEqual(counter.id, "clicks");
assertEqual(cachedValue, 0);
assertEqual(counter.getValue(), 1);
Avoid readonly value: number backed by a getter. It looks stable, but its
value can change on every access.
Functions over classes
Use interfaces with factory functions instead of classes. This keeps the public API separate from the implementation so the interface can describe the whole contract without mixing in state and method bodies.
Name factories createX. Inside a factory, declare items in this order:
- Derived constants and assertions.
- Mutable variables.
DisposableStack,AsyncDisposableStack, and other owned resources.- Listeners and timers.
- Local functions.
- The returned API.
The initialization constraint also applies here: initialize a const helper
before any setup code calls it synchronously.
Evolu favors composition over class inheritance. When inheritance is useful, an interface can extend multiple interfaces, which is more flexible than a class hierarchy.
Classes also bring this binding, constructor semantics, and visibility rules
that do not add much value in this codebase.
The same applies to domain objects. Evolu does not model domain entities as
classes with methods. We model them as plain data described by interfaces.
When a domain object is a tagged union member, extend
Typed<T>. When it needs
runtime validation or transport as JSON, define it with
typed(...) or
object(...).
For behavior, prefer plain functions that take the previous state and return the next state instead of mutating an instance.
import {
NonEmptyTrimmedString100,
assertFalse,
assertTrue,
createIdFromString,
id,
type Typed,
} from "@evolu/common";
const TodoId = id("Todo");
type TodoId = typeof TodoId.Output;
interface Todo extends Typed<"Todo"> {
readonly id: TodoId;
readonly title: NonEmptyTrimmedString100;
readonly isCompleted: boolean;
}
const completeTodo = (todo: Todo): Todo => ({
...todo,
isCompleted: true,
});
const todo: Todo = {
type: "Todo",
id: TodoId.orThrow(createIdFromString("todo")),
title: NonEmptyTrimmedString100.orThrow("Buy milk"),
isCompleted: false,
};
const completedTodo = completeTodo(todo);
assertFalse(todo.isCompleted);
assertTrue(completedTodo.isCompleted);
import {
Boolean,
NonEmptyTrimmedString100,
assertEqual,
assertOk,
createIdFromString,
id,
typed,
type InferType,
} from "@evolu/common";
const Todo = typed("Todo", {
id: id("Todo"),
title: NonEmptyTrimmedString100,
isCompleted: Boolean,
});
interface Todo extends InferType<typeof Todo> {}
const result = Todo.fromUnknown({
type: "Todo",
id: createIdFromString("todo"),
title: "Buy milk",
isCompleted: false,
});
assertOk(result);
const todo: Todo = result.value;
assertEqual(todo.title, "Buy milk");
import { assertEqual } from "@evolu/common";
// Use an interface with a factory function.
interface Counter {
readonly getValue: () => number;
readonly increment: () => void;
}
const createCounter = (step = 1): Counter => {
// Mutable variables stay private to the factory.
let value = 0;
// The returned API is the only way to observe or change them.
return {
getValue: () => value,
increment: () => {
value += step;
},
};
};
const counter = createCounter(2);
counter.increment();
assertEqual(counter.getValue(), 2);
Avoid a class Counter with a public value field and an increment()
method. The class exposes its state and mixes the contract with the
implementation.
Make invalid states unrepresentable
When an object's fields constrain each other, model it as a union of Typed
variants, each holding only the fields valid for it. With independent booleans
and nullable or optional fields, every combination type-checks, so each reader
has to learn which ones can happen, and a test fixture or example can build one
that never does. With a union, consumers switch on
type and access only the fields of the matched variant.
Do not store a value derivable from sibling fields, such as a status beside the data it summarizes. Derive it with a function, so it cannot disagree with its source.
Both rules apply to public outputs, such as snapshots, not only to internal state. When internal state is already a union, publish the union rather than flattening it into booleans at the API boundary.
import { assertEqual, Millis, type Typed } from "@evolu/common";
type Upload = PendingUpload | CompleteUpload | FailedUpload;
interface PendingUpload extends Typed<"Pending"> {}
interface CompleteUpload extends Typed<"Complete"> {
readonly completedAt: Millis;
}
interface FailedUpload extends Typed<"Failed"> {
readonly error: UploadError;
}
interface UploadError extends Typed<"UploadError"> {
readonly reason: string;
}
// Derived from the uploads rather than stored beside them.
const uploadsToUploadError = (
uploads: ReadonlyArray<Upload>,
): UploadError | null =>
uploads.find((upload) => upload.type === "Failed")?.error ?? null;
const error: UploadError = { type: "UploadError", reason: "Quota exceeded" };
const uploads: ReadonlyArray<Upload> = [
{ type: "Complete", completedAt: Millis.orThrow(1000) },
{ type: "Failed", error },
{ type: "Pending" },
];
assertEqual(uploadsToUploadError(uploads), error);
assertEqual(uploadsToUploadError([{ type: "Pending" }]), null);
// @ts-expect-error A complete upload requires its completion time.
const _incomplete: Upload = { type: "Complete" };
const _completeWithError: Upload = {
type: "Complete",
completedAt: Millis.orThrow(1000),
// @ts-expect-error A complete upload has no error.
error,
};
Avoid an interface Upload with independent isComplete, completedAt, and
error fields. It accepts a complete upload with an error or without its
completion time.
Apply the same rules to lifecycles spread across callbacks or collections. Keep transition checks and updates with the code that owns the state, and change the phase and its data together. For example, an owner registration can wait for its turn, acquire transports, or be active. Only the active variant stores the transport lease.
An event can arrive after its operation has been replaced. Cancel delivery when possible or check the operation's identity before applying the event. For example, a database worker reply must match the current dispatch attempt before it can remove the request from the queue.
A boolean or nullable value suffices when it represents the whole state. A batch that is either empty or has a nonempty queue can use the queue's presence to decide whether to schedule a flush.
Disposing
Create disposable objects with
disposable. It
adds the appropriate disposal method and guards the object's functions against
use after disposal.
When the object owns cleanup resources, register them in a DisposableStack or
AsyncDisposableStack and pass the stack to disposable. The helper moves the
stack into the returned object. Omit the stack when disposal only needs to make
the object unusable.
For full disposal patterns, anti-patterns, and move() examples, see
Resource management.
Branded types
Validate external input with Evolu Types. A cast or assertion does not replace
decoding untrusted data. Construct Types with factories such as createType, brand,
array, and object.
Use Brand to give
otherwise identical values distinct meaning at the type level. Branding lets us
separate domain concepts without changing the runtime representation. For
example, PositiveInt is still a number at runtime, but it is not
interchangeable with an arbitrary number in the type system.
import { type Brand } from "@evolu/common";
type UserId = number & Brand<"UserId">;
type TrimmedName = string & Brand<"TrimmedName">;
const describeUser = (_id: UserId, _name: TrimmedName): void => {};
// @ts-expect-error A plain number and string are not assignable to the branded UserId and TrimmedName parameters.
describeUser(1, "Ada");
Prefer Evolu Type brands over raw primitives when the value has domain
meaning. Do not create bare brands that application code must apply with
plain as casts. Define a validated Type with brand(...)
so the constraint is enforced and the branded value can only be obtained
through validation. A value that only library code produces, such as
PerformanceTime or RandomNumber from a dependency, a wasm pointer, or bytes
a decoder reads at a length it checked, may be a bare Brand intersection cast
where it is produced; test doubles of such a dependency cast the same way.
Once a value has a brand, trust it. Do not check at runtime what its type
already proves: a function with a NonNegativeInt parameter does not test that
the value is a non-negative integer, and a function with a JsonValue
parameter does not search it for NaN. A value that breaks its type got there
through a wrong cast, and that cast is the bug. Runtime checks belong to
external or unbranded input, such as decoded bytes or an ArrayLike length, to
relations a brand cannot express, such as an index below a length, and to
internal invariants. When code itself proves a brand's constraint, such as the
difference of two NonNegativeInt values after checking their order, or bytes
of the length a decoder just read, cast the result instead of validating it
again.
Evolu Type's typed boundaries are the exception: from, to, orThrow,
and orNull assert the whole value their parameter type promises, brands
included, because TypeScript cannot prove structural invariants such as
data-only properties, dense arrays, or the absence of excess keys, and one
check covers both. See "Why can a typed operation throw?" in the
Type FAQ.
A public function also keeps a cheap check where a wrongly typed value would
otherwise hang, spin, or silently break a limit. A failure that throws is easy
to find, but one that waits forever is not. For example, each checks that its
array is non-empty, because with no Tasks it would wait until aborted.
Opaque types
Opaque types are the standalone-brand case: a Brand with no base type. Use
them when callers should not inspect or construct values directly and can only
pass them back to the API that created them.
import { assertEqual, type Brand } from "@evolu/common";
// Opaque type: standalone brand with no exposed representation.
type TimeoutId = Brand<"TimeoutId">;
interface Timer {
readonly setTimeout: (fn: () => void, ms: number) => TimeoutId;
readonly clearTimeout: (id: TimeoutId) => void;
}
// Only the creating API knows the representation behind the brand.
const timer: Timer = {
setTimeout: (fn) => {
fn();
const handle: unknown = 1;
return handle as TimeoutId;
},
clearTimeout: () => {},
};
let calls = 0;
const timeoutId = timer.setTimeout(() => {
calls++;
}, 0);
timer.clearTimeout(timeoutId);
assertEqual(calls, 1);
// @ts-expect-error A number is not a TimeoutId.
timer.clearTimeout(1);
Opaque types are useful for:
- Platform abstraction - Hide platform-specific details (e.g.,
NativeMessagePortwraps browser/Node MessagePort) - Handle types - IDs that should only be passed back to the creating API (e.g., timeout IDs, file handles)
- Type safety - Prevent accidental misuse by making internal structure inaccessible
Symbol identity
Symbols used as keys in exported types must retain their unique identity in
emitted declarations. globalThis.Symbol() can infer symbol instead of
unique symbol, causing computed properties to disappear from emitted
declarations and erase type distinctions. Follow the explicit unique-symbol
declaration pattern in the repository's Type.ts and verify the emitted
declarations.
Define shared symbol keys at module scope so objects and the code reading them
use the same runtime key. Creating a key with Symbol() inside a function gives
each call a different symbol, but TypeScript associates its unique type with
the declaration. It can therefore accept an object from another call and allow
reading a required property that is actually missing at runtime. Sharing one
module-level key prevents this separate mismatch.
Runtime-only symbols used as sentinels or identity tokens do not need unique types.
Composition without pipe
Evolu doesn't provide a pipe helper. Instead, compose functions directly:
import {
assertType,
exponential,
jitter,
maxDelay,
take,
type Millis,
type Schedule,
} from "@evolu/common";
// AWS SDK for Java 2.1 ordinary-failure retry timing.
const retryStrategyAws = jitter("100%")(
maxDelay("20s")(take(2)(exponential("50ms"))),
);
assertType<typeof retryStrategyAws, Schedule<Millis>>();
If nested composition gets too deep, split into meaningful named parts:
import {
assertType,
exponential,
jitter,
maxDelay,
take,
type Millis,
type Schedule,
} from "@evolu/common";
// Split long compositions into named intermediate values.
const limitedExponential = take(2)(exponential("50ms"));
const cappedBackoff = maxDelay("20s")(limitedExponential);
const retryStrategyAws = jitter("100%")(cappedBackoff);
assertType<typeof retryStrategyAws, Schedule<Millis>>();
Evolu favors imperative code and direct composition over pipes. Use meaningful local constants when nesting becomes hard to read; keep single-use operations inline.
Result and errors
Fallible public APIs return Result<T, E> for typed domain errors. Represent
domain errors as exact plain objects, not Error instances. Name their
interfaces XError. Omit the Error suffix from the discriminant only when
the remaining name already clearly describes a failure, as in
UserNotFoundError extends Typed<"UserNotFound">. Keep it for names such as
TimeoutError, RetryError, and AbortError.
Use trySync and tryAsync to convert thrown or rejected values into a Result.
Use getOrThrow and Type .orThrow for module initialization, startup and
configuration loading, test fixtures, or internal invariants. Do not use them
to process user input.
See the Result module for composition and error-handling examples.
Avoid meaningless ok values
Don't use ok("done") or ok("success") — the ok() itself already communicates success. Use ok() for Result<void, E> or return a meaningful value.
import {
assertErr,
assertOk,
err,
ok,
type Result,
type Typed,
} from "@evolu/common";
interface User {
readonly id: string;
}
interface SaveError extends Typed<"SaveError"> {}
// Good: ok() means success, no redundant string needed.
const save = (_user: User): Result<void, SaveError> => ok();
interface ParseError extends Typed<"ParseError"> {}
// Good: return a meaningful value.
const parse = (input: string): Result<User, ParseError> =>
input === "" ? err({ type: "ParseError" }) : ok({ id: input });
assertOk(save({ id: "user-1" }), undefined);
assertOk(parse("user-1"), { id: "user-1" });
assertErr(parse(""), { type: "ParseError" });
Avoid ok("done") and ok("success"); the strings add no information.
Testing
Every feature addition and bug fix includes a test that fails without the change. Create fresh dependencies in each test. Cover the changed behavior, including relevant branches and failure paths. Report pre-existing coverage gaps without adding unrelated tests solely to reach 100% coverage of an entire source file.
Use assertType for compile-time contracts and @ts-expect-error for rejected
programs. Every @ts-expect-error must describe the specific expected rejection.
If an Evolu API supplies a CompileTimeError message, copy it verbatim;
otherwise, state the rejected TypeScript contract precisely.
See Testing for test doubles, fresh dependency setup, deterministic Tasks, and test helper naming.
Dependency injection and Tasks
Synchronous functions with injected dependencies accept one deps object.
Describe each dependency and its XDep wrapper with interfaces. Wrappers give
dependencies distinct property names, preventing clashes when combining them.
Dependency interfaces do not use generic parameters and expose domain errors,
not implementation-specific errors.
Use type aliases for intersections that compose dependencies. Sort dependencies
alphabetically and put Partial dependencies last. A caller may pass more
dependencies than a function requires, but a function must not require
dependencies it does not use.
Shared modules do not export dependency instances. Create and wire them in the composition root, where module-level instances are allowed.
Tasks declare dependencies in Task<T, E, D> and read them through run.deps.
Call Tasks with run(task), never task(run). Return, handle, or translate an
Err before accessing the result's value. An object exposing multiple
asynchronous operations creates one internal Run that every asynchronous
method uses.
See Dependency injection for synchronous examples and the Task module for asynchronous composition.
Timestamps and elapsed time
Time exposes two clocks, and they are not interchangeable.
Time.now is Unix epoch time. Use it for a moment that is recorded, displayed,
or compared across devices, such as the close time in a status snapshot.
Time.performance.now measures elapsed time and is unaffected by system clock
adjustments. Use it for durations that drive behavior: how long a connection has
been open, how long since the last attempt, whether a deadline has passed.
Subtracting two Time.now readings is a bug even though it compiles. A clock
correction changes the result, so an NTP sync after a device wakes can make a
one-millisecond interval look like an hour, or hide an hour of silence behind a
negative value. Neither failure reproduces on a developer machine.
A deadline that must count time the device spent suspended is the exception.
Depending on the platform, the monotonic clock can stop while the system sleeps,
so a duration measured across sleep reports less than the time that passed. A
delay that has to expire on schedule regardless of sleep therefore keeps an
absolute Time.now deadline and accepts that a clock correction can shorten or
lengthen it. createTime splits long timeouts this way, and its documentation
states the trade-off. Choose the wall clock deliberately for such a deadline,
never by reaching for the nearest now.
Store a moment a duration is measured from as PerformanceTime rather than
Millis, so the two clocks cannot be mixed by accident. The brands are
distinct, so assigning one where the other belongs fails to compile, which is
the only reliable guard. Subtraction erases the brand, so take the difference
with performanceDurationBetween, which returns a PerformanceDuration and
asserts the readings are ordered. Code that must tolerate an unordered reading,
such as a schedule that keeps stepping rather than throwing, clamps the
difference itself instead.
Documentation
JSDoc should explain behavior and intent without repeating TypeScript parameter
or return types. Do not use @param, @return, or @example. Put examples
under a ### Example Markdown heading. Use {@link} on the first mention of
an exported symbol. Avoid pipe characters in the first sentence because TypeDoc
inserts that sentence into Markdown tables. Do not make alignment-only JSDoc
edits.
Code that works around a bug in a browser, runtime, or dependency explains it in
a // comment at the workaround, not in public JSDoc. Describe the behavior it
handles and link the upstream issue, such as a WebKit, Chromium, or Mozilla bug,
so a maintainer knows why the code exists and can check whether it is still
needed.
Executable examples
Write every TypeScript code fence as a standalone, deterministic example that
testJSDocExamples can lint, compile, and run. Explicitly import dependencies
and assertions. Prefix intentionally unused declarations with _; the harness
rejects both unprefixed unused declarations and used underscore-prefixed
declarations.
Use a ts fence, or a tsx fence for JSX, which the harness transforms before
running it. The harness rejects other spellings, such as typescript.
On a documentation page, an example that continues an earlier one can hide the
setup it needs, such as the schema the page already defined, between
// ---cut-start--- and // ---cut-end--- lines. The harness compiles and runs
them, but the website, its copy button, and its Markdown for LLMs leave them
out. Hide only what the page already shows or names, keep the visible imports,
and hide an assertion only when it would distract from what the example
teaches. JSDoc examples hide nothing, because editors show them as written. A
Svelte component goes in a svelte fence, which the harness skips, because
Node.js cannot run it.
Prove the documented contract with assertions instead of describing expected
output only in comments. Use assertType for static contracts, assertEqual
for Data comparisons, assertSame for SameValue or reference identity,
assertTrue or assertFalse for predicates, assert with a descriptive message
for invariants and narrowing, and assertOk or assertErr for Results.
After changing examples or exported APIs, run pnpm test:jsdoc, which checks
the configured sources, and for a changed file outside them also run
pnpm test:jsdoc <changed-file>. The configured sources are every changeset,
every handwritten documentation page and blog post, and the JSDoc of every
package except @evolu/svelte, whose examples need the Svelte compiler. In
Node.js, the examples run Evolu's workers in-process over in-memory SQLite and
cannot reach relays.
API reference organization
Use TypeDoc's generated declaration-kind groups for simple modules. If a module
uses custom @group tags, assign every exported declaration to a semantic
group. Do not mix custom groups with generated groups such as Functions,
Interfaces, and Type Aliases.
Name custom groups by their purpose within the module, using short contextual
names such as Creation, Guards, Model, or Pull, and define their order
explicitly. Keep module prose before generated API groups, with FAQ last when
present. Put API-specific guidance and examples on the relevant declarations.
Do not use @groupDescription or custom renderer logic to reposition module
prose.
TypeDoc warnings fail CI. Resolve every warning emitted by pnpm build:docs.
Decision records
Record a decision that no single code site owns, such as why sync uses
WebSocket and not WebTransport, or why the relay's Docker image installs the
published npm package instead of a bundle, as an architecture decision record
(ADR) in docs/adr,
whose README explains what an ADR is. Write one only when the decision is hard
to reverse, surprising without context, and the result of a real trade-off. The
reason for one piece of code stays in a // comment at that code, such as why
an oversized mutation throws, and behavior and constraints stay in module JSDoc,
such as how Evolu handles clock drift.
Copy docs/adr/template.md to a file named with a short slug of the title, and
state the decision in the title. Keep the record to one or two pages and link
module docs, issues, and measurements instead of restating them. Before
proposing a design, check docs/adr for an ADR that already proposes or
rejects it.
A new ADR is Proposed, so contributors and agents can read the design before it is decided. It does not bind and is revised until a maintainer accepts or rejects it. Its date is the day it was proposed until a maintainer accepts or rejects it, and then the day of that decision. A rejected ADR stays, so the idea is not proposed again.
Do not rewrite an accepted or rejected ADR beyond fixing typos and links. When a
decision changes, propose a new ADR. When a maintainer accepts it, change the
old one's status to Superseded by with a link to the new one and move the
code's pointers to the new one. An accepted ADR binds, so a change that
conflicts with one needs an accepted superseding ADR first.
Code that a decision governs points to its accepted ADR with a comment naming
the path, such as // See docs/adr/sync-uses-websocket-not-webtransport.md.
scripts/adr.test.mts checks the file names and the template, that every link
and reference to an ADR resolves, and that code points only to accepted ADRs.
Documentation, such as a blog post, may link an ADR of any status.
Supported tool versions
Evolu supports the current major version of each tool it works with, such as Vite, Next.js, React, Svelte, Vue, Expo, React Native, Electron, TypeScript and Node.js, as the examples use them. Code, tests and reviews target those versions: don't add workarounds or tests for older ones, and don't report review findings that affect only older versions. Browsers are different: Evolu supports the current releases of Chromium, Firefox and WebKit, and works around their bugs.
Versioning
Published packages follow semantic versioning. Fixes are patch releases, additions are minor, and breaking changes are major. Semver tells whether an upgrade within a version range can break a working install. It says nothing about how hard the break is to fix.
So renaming or removing an exported runtime symbol of a stable API, such as a function or constant, is never a patch, however simple the migration. A library compiled against the old name breaks at runtime for its users, and JavaScript users get no compiler error. Dependency update tools also commonly merge patch releases automatically.
Add the new name in a minor release and keep the old one as an alias marked
@deprecated that names its replacement. Rename an exported type the same way
and keep the old name as a @deprecated type alias, because the declarations
of libraries compiled against it still name it. Remove deprecated aliases
together in an occasional major release. Libraries that declare Evolu packages
as peer dependencies then rarely have to move their ranges.
Local-first APIs, including their platform and framework integrations, and APIs
marked @experimental are not stable yet. Incompatible changes to them, renames
and removals included, are patch releases. Additions are minor. Their changesets
document the migration impact.
@evolu/sqlite-wasm is the exception to semantic versioning. Like SQLite's own
npm package, it is versioned <SQLite version>-build<n>, and any build may
change its API. scripts/version-sqlite-wasm.mts replaces the version its
changeset bump computes, so the bump type only selects the heading of its
release notes. Its README describes the scheme for users.