@streamsy/views
Reference for every public export of @streamsy/views, including View, Relation, TypedExpression, ViewBackend, faults, and types.
import {
PlanChanged,
PlanCheckFailed,
View,
ViewBackend,
ViewDataFault,
ViewFault,
} from "@streamsy/views";
import type {
BooleanExpression,
CircuitBinding,
CircuitDeclaration,
CircuitError,
Input,
LiveReader,
LiveSnapshot,
ParameterExpressions,
Reference,
Relation,
RoutedView,
State,
TypedAggregateExpression,
TypedExpression,
} from "@streamsy/views";Install with bun add @streamsy/views @streamsy/projection @streamsy/core effect. All public APIs are exported from the package root. Views supports SQLite, Postgres, MySQL, and memory backends, plus scoped in-memory live snapshots.
Root exports
| Export | Kind | Purpose |
|---|---|---|
View | Namespace | Relation builders, routing, aggregates, expressions, circuit, live, and migrate |
ViewBackend | Service | Host-selected operator storage |
LiveReader | Type | Scoped reader returned by View.live's at(params) |
LiveSnapshot | Type | Committed rows and input offsets with initial catch-up status |
PlanChanged | Class (Schema.TaggedError) | Non-retryable fault (_tag: "ViewPlanChanged") when a namespace's plan hash changes |
ViewFault | Class (Schema.TaggedError) | Operational or setup fault (_tag: "ViewFault") |
ViewDataFault | Class (Schema.TaggedError) | Non-retryable row-level or maxAffectedKeys fault (_tag: "ViewDataFault") |
PlanCheckFailed | Class (Schema.TaggedError) | Compile-time plan check error (_tag: "PlanCheckFailed") with issues |
CircuitDeclaration | Type | Projection Declaration returned by View.circuit |
CircuitBinding | Type | Bound projection returned by declaration.at(params) |
CircuitError | Type | Union PlanChanged | ViewFault | ViewDataFault | ProjectionFault |
ParameterExpressions | Type | Map of JSON-valued binding parameters to TypedExpression values |
State | Type | Structural contract of a Streamsy.state class |
Input | Type | Existential input State class boundary used in Relation and View.circuit |
Relation | Type | Typed relation handle returned by View.from and relation operators |
RoutedView | Type | Routed circuit view returned by View.routed |
TypedExpression | Type | Typed expression node with fluent comparison, boolean, numeric, sort, optional, and field operations |
Reference | Type | Alias for TypedExpression<T> passed to operator callbacks |
BooleanExpression | Type | Alias for TypedExpression<boolean> |
TypedAggregateExpression | Type | Expression returned by the View aggregate functions |
View namespace
View exports these values and types:
| Member | Kind | Purpose |
|---|---|---|
View.from | Function | Start a Relation from a Streamsy.state class and collection name |
View.routed | Function | Attach explicit route expressions (and optional row selector) for a routed output |
View.circuit | Function | Compile views and generation-addressed outputs into a CircuitDeclaration |
View.live | Function | Compile named views for a scoped heap reader |
View.migrate | Function | Create operator tables on SQLite, Postgres, or MySQL |
View.count | Function | Count rows in a groupBy group |
View.sum | Function | Sum a numeric expression in a groupBy group |
View.min | Function | Minimum ordered (number | string) expression in a groupBy group |
View.max | Function | Maximum ordered (number | string) expression in a groupBy group |
View.list | Function | All values of an ordered expression in a groupBy group, with duplicates |
View.field | Function | Select a field whose name overlaps an expression method or member |
View.fn | Function | Declare a named, versioned, pure synchronous expression function |
View.literal | Function | Wrap a JSON value as a TypedExpression |
View.key | Function | Build a composite key expression or use View.key.asc() to sort by the relation key |
View.State | Type | Same as root State |
View.Input | Type | Same as root Input |
View.Relation | Type | Same as root Relation |
View.RoutedView | Type | Same as root RoutedView |
View.CircuitDeclaration | Type | Same as root CircuitDeclaration |
View.CircuitBinding | Type | Same as root CircuitBinding |
View.from
declare function from<
Codecs extends StreamRoute.ParamCodecs,
C extends StreamAddress.Collections,
R,
K extends keyof C & string,
>(state: State<Codecs, C, R>, collection: K): Relation<C[K]["schema"]["Type"], State<Codecs, C, R>>;
Creates a source relation for collection on state. Throws RangeError if collection is not declared on state.
View.routed
declare function routed<Row, Inputs extends Input, const By extends RouteFields>(
source: Relation<Row, Inputs>,
spec: { readonly by: (row: Reference<Row>) => By; readonly row?: never },
): RoutedView<Row, Inputs, By>;
declare function routed<
Row,
Inputs extends Input,
const By extends RouteFields,
Result extends JsonObject,
>(
source: Relation<Row, Inputs>,
spec: {
readonly by: (row: Reference<Row>) => By;
readonly row: (row: Reference<Row>) => TypedExpression<Result>;
},
): RoutedView<Result, Inputs, By>;Wraps a Relation for an output declared with Projection.perGeneration(StateClass, param, { routeBy: [...] }). by must return an expression (string, finite number, or boolean) for every parameter listed in routeBy with matching decoded types. Pass row when the emitted JSON object row is nested inside the relation row.
Passing a RoutedView to a non-routed circuit output or to View.live throws RangeError. See Route output rows.
View.circuit
// Single output form
declare function circuit<
C extends StreamRoute.ParamCodecs,
const V extends Views,
O extends Projection.PerGeneration<Input, string, string>,
HE = never,
HR = never,
>(definition: {
readonly id: string;
readonly generation?: number;
readonly params: C;
readonly retry?: CircuitDeclaration<C, { output: V }, { output: O }, HE, HR>["retry"];
readonly maxAffectedKeys?: number;
readonly wakeAt?: (unit: Unit<StreamRoute.Params<NoInfer<C>>>) => void | WakeAt;
readonly output: O;
readonly views: V | ((params: ParameterExpressions<NoInfer<C>>) => V);
}): CircuitDeclaration<C, { output: V }, { output: O }, HE, HR>;
// Multiple outputs form
declare function circuit<
C extends StreamRoute.ParamCodecs,
const V extends ViewMap,
const O extends Readonly<Record<string, Projection.PerGeneration<Input, string, string>>>,
HE = never,
HR = never,
>(definition: {
readonly id: string;
readonly generation?: number;
readonly params: C;
readonly retry?: CircuitDeclaration<C, V, O, HE, HR>["retry"];
readonly maxAffectedKeys?: number;
readonly wakeAt?: (unit: Unit<StreamRoute.Params<NoInfer<C>>>) => void | WakeAt;
readonly outputs: O;
readonly views: V | ((params: ParameterExpressions<NoInfer<C>>) => V);
}): CircuitDeclaration<C, V, O, HE, HR>;Compiles the declared views and returns a Declaration backed by Projection.process and a transactional cleanup commit.
Declaration-time checks:
- Throws
ViewFaultif any output is not wrapped inProjection.perGeneration. - Throws
RangeErrorfor missing circuit parameters, duplicate output State classes, missing or unknown output collections, emptyoutputs, mismatchedView.routedroute fields, an invalidmaxAffectedKeys, or a definedversionoption. - Throws
PlanCheckFailedif the compiled plan fails static validation.
View.live
View.live({ id, params, views, maxAffectedKeys?, retry? }) compiles named relations and returns a declaration with at(params). Pass a record of relations or a function from typed parameter expressions to that record. The declaration uses the same input parameter checks and affected-key limit as View.circuit. Routed relations throw RangeError. An invalid compiled plan throws PlanCheckFailed.
| Member | Result | Behavior |
|---|---|---|
at(params) | Effect of LiveReader<V>, with CircuitError | Opens a reader with a private heap host. Requires Scope and the input State services |
snapshot | Effect<LiveSnapshot<V>> | Reads the latest committed rows of all views, their input offsets, and catch-up status |
snapshots | Stream<LiveSnapshot<V>, CircuitError> | Starts with the latest snapshot and emits after commits and when initial catch-up succeeds. Slow subscribers can skip intermediate snapshots |
caughtUp | Effect<void, CircuitError> | Waits for the first snapshot that reaches the startup tails. Interrupts its caller if the reader ends without a fault before that |
Open a reader outside any transaction. A terminal startup or follower fault fails snapshots, including ViewDataFault from a bad input row and ProjectionFault with reason history-unavailable when required history is missing. A caughtUp wait that is still waiting for the first caught-up snapshot gets the same fault. Offsets are scoped to their input streams. A follower parked when an input closes without data can take up to 30 seconds to notice the close. See Read live snapshots.
View.migrate
declare const migrate: (
sql: SqlClient.SqlClient,
) => Effect.Effect<void, ViewFault | SqlError.SqlError>;
Creates streamsy_view_integrals, streamsy_view_arrangements, streamsy_view_accumulators, streamsy_view_key_owners, and streamsy_view_circuits if they do not exist. On Postgres and MySQL it also creates and checks streamsy_view_layout. An unsupported SQL dialect fails with ViewFault. See the migration rules for SQLite, Postgres, and MySQL.
Aggregates
declare const count: () => TypedAggregateExpression<number>;
declare const sum: (expression: TypedExpression<number>) => TypedAggregateExpression<number>;
declare const min: <T extends number | string>(
expression: TypedExpression<T>,
) => TypedAggregateExpression<T>;
declare const max: <T extends number | string>(
expression: TypedExpression<T>,
) => TypedAggregateExpression<T>;
declare const list: <T extends number | string>(
expression: TypedExpression<T>,
) => TypedAggregateExpression<readonly T[]>;
Used inside relation.groupBy(fields).aggregate(aggregates).
View.list returns values in ascending order, using numeric order for finite numbers and UTF-16 code-unit order for strings. Numbers precede strings, duplicates are kept, and absent operands are skipped. Empty groups have no output row. When a member changes the list, the aggregate emits the whole array. maxAffectedKeys does not bound group size.
Expression helpers
declare function field<T, K extends keyof Exclude<T, undefined> & string>(
expression: TypedExpression<T>,
name: K,
): TypedExpression<Exclude<T, undefined>[K] | Extract<T, undefined>>;
declare function fn<
Args extends readonly (JsonValue | undefined)[],
Result extends JsonValue | undefined,
>(
name: string,
version: number,
implementation: (...args: Args) => Result,
): (
...operands: { readonly [K in keyof Args]: TypedExpression<Args[K]> }
) => TypedExpression<Result>;
declare const literal: <T extends JsonValue>(value: T) => TypedExpression<T>;
declare const key: ((
...parts: readonly (
TypedExpression<boolean> | TypedExpression<number> | TypedExpression<string>
)[]
) => TypedExpression<readonly (boolean | number | string)[]>) & {
asc: () => SortTerm;
};
View.fn throws RangeError if name is blank or version is not a positive safe integer.
Relation
interface Relation<Row, Inputs extends Input = Input> {
readonly rowType?: Row;
readonly expression: RelationExpression<Row>;
readonly inputs: ReadonlyMap<string, { readonly state: Inputs; readonly collection: string }>;
readonly where: (predicate: (row: Reference<Row>) => BooleanExpression) => Relation<Row, Inputs>;
readonly select: <F extends Readonly<Record<string, Expression>>>(
fields: (row: Reference<Row>) => F,
) => Relation<Selected<F>, Inputs>;
readonly selectRow: <Result extends JsonObject>(
expression: (row: Reference<Row>) => TypedExpression<Result>,
) => Relation<Result, Inputs>;
readonly concat: <Other, OtherInputs extends Input>(
other: Relation<Other, OtherInputs>,
) => Relation<Row | Other, Inputs | OtherInputs>;
readonly closure: <Part extends JsonValue | undefined = undefined>(spec: {
readonly parent: (row: Reference<Row>) => ValueExpression<string | undefined>;
readonly part?: (row: Reference<Row>) => ValueExpression<Part>;
readonly maxDepth: number;
}) => Relation<
{
readonly node: string;
readonly ancestor: string;
readonly depth: number;
readonly path?: readonly Exclude<Part, undefined>[];
},
Inputs
>;
readonly join: <Right, Other extends Input, Alias extends string>(
other: Relation<Right, Other>,
spec: {
readonly as: Alias;
readonly on: (left: Reference<Row>, right: Reference<Right>) => BooleanExpression;
},
) => Relation<Row & Record<Alias, Right>, Inputs | Other>;
readonly leftJoin: <Right, Other extends Input, Alias extends string>(
other: Relation<Right, Other>,
spec: {
readonly as: Alias;
readonly on: (left: Reference<Row>, right: Reference<Right>) => BooleanExpression;
},
) => Relation<Row & Partial<Record<Alias, Right>>, Inputs | Other>;
readonly groupBy: <F extends Readonly<Record<string, Expression>>>(
fields: (row: Reference<Row>) => F,
) => {
readonly aggregate: <A extends Readonly<Record<string, TypedAggregateExpression<unknown>>>>(
aggregates: (row: Reference<Row>) => A,
) => Relation<Selected<F> & { readonly [K in keyof A]: AggregateValue<A[K]> }, Inputs>;
};
readonly top: (spec: {
readonly partitionBy?: (row: Reference<Row>) => Expression | readonly Expression[];
readonly by: (row: Reference<Row>) => readonly SortTerm[];
readonly limit: number;
}) => Relation<Row, Inputs>;
}selectRowprojects the whole row from one expression that returns a JSON object. It keeps the input relation key, asselectdoes. A circuit uses its output State collection's declared key when writing the row.concatpreserves all input values and prefixes each encoded relation key with its side as["l", encodedKey]or["r", encodedKey].closurefollows one parent per string relation key for at mostmaxDepthedges. A missing parent row is a final ancestor. Cycles stop before an ancestor repeats or the walk returns to its starting node. Each output key contains the encoded node and ancestor keys. Passpartto include the path values from the row below the ancestor down to the node. If any part on an emitted path is absent, the unit fails withViewDataFault. UseView.field(row, "path")to read the path. The selectors accept typed expressions, including optional parent values.
See Build relations for worked examples of every operator.
TypedExpression operations
Methods available on TypedExpression<T> depend on T:
| Group | Condition on T | Methods |
|---|---|---|
| Common | All types | eq(right), ne(right), in(...values) |
| Ordered | Exclude<T, undefined> is number | string | gt(right), gte(right), lt(right), lte(right) |
| Sort | Non-optional number | string | asc(), desc() |
| Boolean | Exclude<T, undefined> is boolean | and(...right), or(...right), not() |
| Number | Exclude<T, undefined> is number | add(right) |
| Optional | undefined is assignable to T | isPresent(), unwrap(), orElse(fallback) |
| Object fields | Exclude<T, undefined> is an object | Property access expr.prop for each field, propagating optionality; use View.field when a name overlaps a method |
ViewBackend
ViewBackend is an opaque Effect service. Supply it through a layer.
| Layer | Provides | Requires | Layer error |
|---|---|---|---|
ViewBackend.layerSql | ViewBackend | SqlClient.SqlClient | ViewFault for an unsupported dialect |
ViewBackend.layerMemory | ViewBackend | CommitBoundary | never |
layerSql uses the storage owner's SqlClient. Run View.migrate with that client before running the circuit. If the transaction for that client is absent, the fault message is The Views SQL client is outside the storage owner's transaction.
layerMemory requires an active memory owner transaction on the running fiber when the circuit uses the store. If the transaction is absent or belongs to another owner, the fault message is Views memory state requires the active memory owner transaction on this fiber.
For either transaction check, a circuit unit fails with a non-retryable ViewFault. During Projection.forget or Projection.retire, the same check fails cleanup with a ProjectionFault with phase checkpoint and reason unsupported-composition. The cleanup fault keeps the same message.
Faults
PlanChanged
interface PlanChanged {
readonly _tag: "ViewPlanChanged";
readonly namespace: string;
readonly stored: string;
readonly requested: string;
readonly [NonRetryable]: true;
}
ViewDataFault
interface ViewDataFault {
readonly _tag: "ViewDataFault";
readonly view: string;
readonly node: string;
readonly key: string | number | boolean | readonly (string | number | boolean)[] | null;
readonly reason: string;
readonly [NonRetryable]: true;
}
ViewFault
interface ViewFault {
readonly _tag: "ViewFault";
readonly message: string;
readonly cause?: unknown;
}
PlanCheckFailed
interface PlanCheckFailed {
readonly _tag: "PlanCheckFailed";
readonly issues: ReadonlyArray<{
readonly code:
| "invalid-expression-scope"
| "non-boolean-predicate"
| "join-alias-conflict"
| "join-condition-not-boolean"
| "aggregate-shape-mismatch"
| "undeclared-parameter"
| "invalid-top-limit"
| "invalid-closure-depth"
| "invalid-closure-key"
| "unstable-top-order"
| "unsupported-sql-plan";
readonly view: string;
readonly nodeId?: string;
readonly path: string;
readonly message: string;
}>;
}
Types
LiveReader and LiveSnapshot
interface LiveSnapshot<V> {
readonly rows: {
readonly [K in keyof V]: ReadonlyArray<V[K] extends Relation<infer Row> ? Row : never>;
};
readonly offsets: Readonly<Record<string, Offset>>;
readonly caughtUp: boolean;
}
interface LiveReader<V> {
readonly snapshot: Effect.Effect<LiveSnapshot<V>>;
readonly snapshots: Stream.Stream<LiveSnapshot<V>, CircuitError>;
readonly caughtUp: Effect.Effect<void, CircuitError>;
}
The snapshot and its rows are read-only. Use a State input's key to look up its committed offset. caughtUp records completion of the initial replay. Rows within each view are ordered by the encoded relation key. Select a key as a row field when the caller needs it.
CircuitError
type CircuitError = PlanChanged | ViewFault | ViewDataFault | ProjectionFault;
CircuitBinding and CircuitDeclaration
CircuitDeclaration<C, V, O, HE, HR> extends @streamsy/projection's Declaration<C, CircuitBinding<V, O>, HE, HR>. Calling declaration.at(params) returns a CircuitBinding<V, O> that Projection.pass, Projection.run, Projection.follow, and Projection.forget accept. Projection.attach, ProjectionWakeup.attach, and Projection.retire accept the CircuitDeclaration. The binding uses Commit.TransactionCommit<void | WakeAt, CheckpointStore | Transaction | ViewBackend>. Its handler requires ViewBackend and the output State services.
Faults and retry
Reference for ProjectionFault and ProjectionRetry in @streamsy/projection. A projection fails with a ProjectionFault that names where the run stopped and why.
SqlStorage
Reference for the SqlStorage namespace in @streamsy/storage. It keeps streams in a SQLite, Postgres, or MySQL database through an Effect SqlClient that you provide.