Command unstable
Commands are the side effects a component asks the runtime to run.
update and init return Commands as data. The runtime runs each one and
feeds its result back to the instance as a message, so update stays pure
and a story test can read what was issued without running anything. A
Command with nothing to tell the component ends with Component.noop, or
is piped through Command.asNoop, and sends nothing. A Command.Service
that omits success, or declares success: Component.Noop, is always
silent, whatever its body returns.
Both constructors take a name and options. args defaults to none:
Command.make(name, { args }, body)for Commands that need nothing beyond the framework services. Issue one withRollDie.make({ sides: 6 }). Its body can't fail.Command.Service<Self>()(key, { args, success, error, invalidates })for Commands that reach other services. Attach the implementation withtoLayer(a function, or an Effect that builds one and captures its dependencies), so a component only requires the Command service. Issue withDeleteTodo.make({ id }); fake withDeleteTodo.toLayer(fn).
A Command.Service declares what it does to the query cache:
invalidates, optimistic and writes are optional. Omitting
invalidates means the run invalidates nothing.
When one component consumes a Command's result, the usual case for an
app's own Commands, the body returns that component's message and handles
a typed failure with Effect.match. A body that leaves a typed error
gives an Unmatched Command, which $.run rejects.
Command.match, Command.map and Command.asNoop are for a Command that
can't know its caller's messages: one from a library, such as
Router.replace, or one that several components issue.
In a Story or Scene, resolve takes what the body returns: the
message in the first case, and the Command's own value in the second, where
fail takes its typed error and the mapping runs in the test.
A Command starts once the update that issued it is applied, Subscription
changes included, and before whoever sent the message gets control back.
For a DOM event, that is still inside the event's listener. The body runs
in that task until its first wait, so a call that needs the event's user
activation, such as a clipboard write, goes before anything the body waits
for. init's Commands start after the render that mounts the instance.
The Commands of one update start in order. A body that ends without
waiting has its message handled before the next Command starts, and a chain
of such Commands yields after a hundred runs. Commands that need the
rendered DOM, such as HtmlCommand.focus, wait for the render to commit
instead.
Example Copying a link while the click still has user activation
import { Command, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ Copied: {}, FailedCopy: {} })
const CopyLink = Command.make( "CopyLink", { args: { url: Schema.String } }, // `writeText` runs as the body starts, inside the click's listener. The // body's first wait is for the Promise it returns. ({ url }) => Effect.tryPromise(() => navigator.clipboard.writeText(url)).pipe( Effect.match({ onSuccess: () => Message.Copied(), onFailure: () => Message.FailedCopy() }) ))
// `update` answers a click with `$.run(CopyLink.make({ url }))`.Example A Command service with a captured dependency
import { Command, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"import { KeyValueStore } from "effect/persistence"
const Message = UiSchema.TaggedEnum({ ClickedDelete: {}, SucceededDeleteTodo: {}, FailedDeleteTodo: {} })
class DeleteTodo extends Command.Service<DeleteTodo>()("todos/DeleteTodo", { args: { id: Schema.String }, success: Message}) { static readonly layer = this.toLayer(Effect.gen(function*() { const kv = yield* KeyValueStore.KeyValueStore return ({ id }) => kv.remove(`todo/${id}`).pipe( Effect.match({ onSuccess: () => Message.SucceededDeleteTodo(), onFailure: () => Message.FailedDeleteTodo() }) ) }))}
// `update` issues `DeleteTodo.make({ id })`, and the component requires `DeleteTodo`.// The live wiring provides `DeleteTodo.layer`, which requires `KeyValueStore`.Accessors
Constructors
Issues a Command that interrupts the running and queued runs of another one.
When to use
Use to handle a user-driven cancel, such as a "Cancel upload" button, from
update.
Details
It produces no message. An interrupted run dispatches nothing and is logged
as CommandInterrupted when its fiber exits. Until then it holds its group:
a queue or switch run issued after the interrupt starts once the
interrupted run's cleanup has finished. With a pick of the Command's group
fields, only the runs of that group are interrupted. Without one, every run
of the Command the instance has is.
Signature
declare function interrupt<Args, G extends string>(definition: Definition<Args, any, boolean, any, G>, ...group: GroupArg<Args, G>): InterruptExample Cancelling an upload
import { Command } from "effect/ui"import { Effect, Schema } from "effect"
const UploadFile = Command.make("UploadFile", { args: { name: Schema.String }, group: ["name"]}, ({ name }) => Effect.succeed(`https://cdn/${name}`))
// In `update`: `$.run(Command.interrupt(UploadFile, { name: "photo.png" }))`const cancel = Command.interrupt(UploadFile, { name: "photo.png" })Defines a Command that needs nothing beyond the framework services.
When to use
Use to wrap an Effect that only needs the runtime's own services (Scope, a
host's refs) or none at all, such as a random roll or focusing an element.
Anything that reaches another service is a Service.
Details
Takes an optional args Schema and returns a definition whose make
method takes the args struct and issues a Command. Story tests can inspect
its args without running the Effect. The body can't fail. Its requirements may only
be framework services, which are removed from R. A body that requires
anything else doesn't compile. The error names those services and points to
Command.Service. With stream: true the body returns a Stream
instead. A make Command declares nothing about the query cache.
Gotchas
Effect.tryPromise(() => fetch(...)) compiles with R = never, but a
Command written that way can't be faked. Put I/O behind a Service.
Signature
declare const make: { <Name extends string, In extends ArgsInput = {}, Msg = never, R extends FrameworkService = never, G extends never = never>(name: Name, options: Options<In, G> & NoInfer<Given<"args", In, {}>> & { readonly stream?: false; }, run: (args: View<ArgsFields<In>>) => Effect<Msg, never, R>): Factory<View<ArgsFields<In>, "Type", TypeOptionalKeys<ArgsFields<In>>, TypeMutableKeys<ArgsFields<In>>>, Msg, false, G>; <Name extends string, In extends ArgsInput = {}, Msg = never, R extends FrameworkService = never, G extends never = never>(name: Name, options: Options<In, G> & NoInfer<Given<"args", In, {}>> & { readonly stream: true; }, run: (args: View<ArgsFields<In>>) => Stream<Msg, never, R>): Factory<View<ArgsFields<In>, "Type", TypeOptionalKeys<ArgsFields<In>>, TypeMutableKeys<ArgsFields<In>>>, Msg, true, G>; <In extends ArgsInput = {}, R = never>(name: string, options: Options<In, GroupField<In>>, run: (args: View<ArgsFields<In>>) => Effect<unknown, unknown, R> | Stream<unknown, unknown, R> & UnsupportedServices<R>): any;}Example A Command that only needs the runtime
import { Command, UiSchema } from "effect/ui"import { Effect, Random, Schema } from "effect"
const DieMessage = UiSchema.TaggedEnum({ ClickedRoll: {}, CompletedRollDie: { n: Schema.Number } })
const RollDie = Command.make("RollDie", { args: { sides: Schema.Number } }, ({ sides }) => Random.nextIntBetween(1, sides).pipe(Effect.map((n) => DieMessage.CompletedRollDie({ n }))))
// In a component: `$.run(RollDie.make({ sides: 6 }))`, pending in a story as { name: "RollDie", args: { sides: 6 } }Defines a Command whose implementation is a service.
When to use
Use when a Command needs a non-framework service, such as a store or HTTP client, including mutations of data a query reads.
Details
Takes a key (the Command's name in logs and stories) and options, all
optional: args (none by default), success and error (Schema.Never
by default). Set success to the Message Schema of the component that
consumes the result. Without it, or with success: Component.Noop, every
run is silent and the body may return anything, with no
Effect.as(Component.noop). Attach the body
with toLayer, passing a function or an Effect that runs once per Layer
build to capture its dependencies; components then require only this class,
and tests can fake it with X.toLayer(fn).
The body may use framework services on each call without them appearing in
the Layer's requirements. When one component consumes the result, the body
returns that component's message and handles a typed failure with
Effect.match. A library or shared Command returns its own result
instead, and the issue site maps it: Command.match when error isn't
Schema.Never, since make then issues an Unmatched Command, and
Command.map or Command.asNoop when it can't fail.
The options declare what a run does to the query cache, from the args:
invalidates (optional), optimistic patches, live from issue, and
writes of the success. The runtime applies them when the run's fiber
exits, before its message is sent.
To invalidate queries using reactivityKeys, wrap the handler's mutation
with Reactivity.mutation(keys) so keys publish only on success. Pick
either Reactivity.mutation or invalidates per query to avoid redundant
refetches.
Every run is owned by the instance that issued it and ends with it,
whatever its kind or mode. A save that must outlive a page is issued by a
component that outlives it, such as the layout, so its result and its
failure reach an update.
Signature
declare const Service: <Self>() => { <Key extends string>(key: Key, options?: undefined): Service<Self, Key, {}, NoopSchema, false, Never, never>; <Key extends string, In extends ArgsInput = {}, Success extends Top = NoopSchema, Error extends Top = Never, G extends never = never>(key: Key, options: Options<In, Success, Error, G> & NoInfer<ServiceGiven<In, Success, Error>> & { readonly stream?: false; }): Service<Self, Key, View<ArgsFields<In>, "Type", TypeOptionalKeys<ArgsFields<In>>, TypeMutableKeys<ArgsFields<In>>>, Success, false, Error, G>; <Key extends string, In extends ArgsInput = {}, Success extends Top = NoopSchema, Error extends Top = Never, G extends never = never>(key: Key, options: Options<In, Success, Error, G> & NoInfer<ServiceGiven<In, Success, Error>> & { readonly stream: true; readonly writes?: undefined; }): Service<Self, Key, View<ArgsFields<In>, "Type", TypeOptionalKeys<ArgsFields<In>>, TypeMutableKeys<ArgsFields<In>>>, Success, true, Error, G>;}Example Defining, issuing and faking a Command service
import { Command, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"import { KeyValueStore } from "effect/persistence"
const Message = UiSchema.TaggedEnum({ ClickedSave: {}, SucceededSaveTodo: {}, FailedSaveTodo: { reason: Schema.String }})
class SaveTodo extends Command.Service<SaveTodo>()("todos/SaveTodo", { args: { id: Schema.String, title: Schema.String }, success: Message, mode: "queue", group: ["id"]}) { static readonly layer = this.toLayer(Effect.gen(function*() { const kv = yield* KeyValueStore.KeyValueStore return ({ id, title }) => kv.set(`todo/${id}`, title).pipe( Effect.match({ onSuccess: () => Message.SucceededSaveTodo(), onFailure: (e) => Message.FailedSaveTodo({ reason: e.message }) }) ) }))}
// Issue: `$.run` takes the Command as isconst command = SaveTodo.make({ id: "1", title: "Buy milk" })// Live: provide `SaveTodo.layer`, which requires `KeyValueStore`// Test: a fake that needs nothingconst Fake = SaveTodo.toLayer(() => Effect.succeed(Message.SucceededSaveTodo()))Guards
Returns true if u is a Command.
Signature
declare function isCommand(u: unknown): u is Command<unknown, unknown>isDefinition
unstableReturns true if u is a Command definition: a factory from make or a
Service class.
Signature
declare function isDefinition(u: unknown): u is AnyisUnmatched
unstableReturns true if u is a Command issued by a Service whose body can
fail, before match.
Signature
declare function isUnmatched(u: unknown): u is Unmatched<unknown, unknown, unknown, Kind>Mapping
afterRefetch
unstableHolds a Command's success message until the entries its run invalidated
have refetched, or until budget runs out.
When to use
Use when update needs the refetched data with the success: a "save, then
show the saved row" flow whose refetch would otherwise land a render after
the message.
Details
It applies to an issued or unmatched Effect-kind Service Command, on
either side of match and map. A Stream Command or a make Command
doesn't compile. A second application replaces the first.
- The wait covers entries invalidated by the run that have a watcher,
from any instance, when success applies the invalidation. It excludes
entries stored fresh by the run's
writesand open streams it only patched. A watcher that comes later doesn't join. - An entry's wait ends when it has no refetch in flight and none owed, whether the refetch succeeds, fails or dies. The wait ends on the slowest entry, and the budget is the upper bound.
budgetis aDuration.Input:"Infinity"waits with no bound, zero doesn't wait, and a bare number is milliseconds. The clock is the EffectClock, started when invalidation is applied. A run cut by the budget, byswitchor byCommand.interruptdelivers its success at once, and its refetches run on.- A typed failure is delivered at once. An interrupt before the body succeeds sends nothing. If the issuing instance closes during the wait, the message is dropped.
h.isRunningstays true through the wait. Underqueuethe next run starts when the body exits, and messages keep issue order.- Each awaited entry emits when it settles, so its query's result is written before the success, in one render, for the last entry to settle. Two entries settling apart can briefly show a patched row next to the refetched one.
Signature
declare const afterRefetch: { (budget: Input): <C extends Awaitable>(self: C & AwaitsRefetch<C>) => C; <C extends Awaitable>(self: C & AwaitsRefetch<C>, budget: Input): C;}Example Waiting for a rename's refetch
import { Command, UiSchema } from "effect/ui"import { Schema } from "effect"
const Message = UiSchema.TaggedEnum({ CompletedRenameUser: {} })
class RenameUser extends Command.Service<RenameUser>()("RenameUser", { args: { id: Schema.String, name: Schema.String }, success: Schema.Void}) {}
const rename = RenameUser.make({ id: "1", name: "Ada" }).pipe( Command.map(() => Message.CompletedRenameUser()), Command.afterRefetch("5 seconds"))Replaces each message a Command produces with the supplied value.
When to use
Use when the component needs a fixed message rather than the Command's
result: command.pipe(Command.as(message)) is shorthand for
command.pipe(Command.map(() => message)).
Details
Keeps the original name, args, options, source type and requirements, just
like map. Stream Commands emit the same supplied value for each element.
Apply match first to a Command whose body can fail. After match, both
mapped channels are replaced. The data-first form leaves an Interrupt
unchanged; the pipeable form only accepts issued Commands.
Gotchas
For a union with different source types or requirements, use the data-first
form, Command.as(input, message), to preserve each branch's types.
See
- map
Signature
declare const as: { <B>(message: B): <A, R, Source, K extends Kind, SourceE>(self: Issued<A, R, Source, K, SourceE>) => K extends Kind ? Issued<B, R, Source, K, SourceE> : never; <C extends Command<any, any>, B>(self: C, message: B): Mapped<C, B>;}Makes a Command send nothing when it finishes.
When to use
Use when a Command's result doesn't matter to the component, such as a
navigation or a focus, instead of adding a no-op variant to its Message. It's shorthand for Command.as(Component.noop).
A Command.Service that never reports anything omits success instead.
Details
Every result is replaced with Component.noop, so the run ends with no
message and CommandEnded records it as silent. A Stream Command's
elements are all silenced. It keeps the name, args, options, source type
and requirements, like as, and leaves an Interrupt unchanged.
Gotchas
It takes issued Commands only, never an Unmatched one, so a typed failure
can't be dropped by accident. After match it silences both channels: to
keep the failure message, write
match({ onSuccess: () => Component.noop, onFailure }). On a navigation
Command it also hides a "blocked" outcome.
See
- as
Signature
declare function asNoop<C extends Command<any, any>>(self: C): Mapped<C, Noop>Example Tracking an event without a message
import { Command } from "effect/ui"import { Effect, Schema } from "effect"
const Track = Command.make("Track", { args: { event: Schema.String } }, () => Effect.succeed(200))
const track = Track.make({ event: "opened" }).pipe(Command.asNoop)Maps the message a Command produces.
When to use
Use when issuing a Command that can't know its caller's messages, such as
Router.replace or a shared UploadFile Command that returns a URL. A
Command whose body can fail takes match instead.
Details
The name, args and options are kept, so the log and story tests still see
the original Command, and a story's resolve step still takes the
definition's own success (the Source type parameter). The data-first form
returns an Interrupt unchanged; the pipeable form only takes issued
Commands.
The mapping's second argument is the run's SpanContext, for a later
Command that continues its trace through withParentSpan.
Gotchas
The pipeable form infers one Source and one R for its input, so it maps
one Command, or a union whose branches share them, and keeps them exact.
For a union of Commands with different sources or requirements, use the
data-first form, Command.map(input, f), which keeps each branch's own.
Signature
declare const map: { <A, B>(f: (a: A, span: { readonly sampled: boolean; readonly spanId: string; readonly traceId: string; }) => B): <R, Source, K extends Kind, SourceE>(self: Issued<A, R, Source, K, SourceE>) => K extends Kind ? Issued<B, R, Source, K, SourceE> : never; <C extends Command<any, any>, B>(self: C, f: (a: Message<C>, span: { readonly sampled: boolean; readonly spanId: string; readonly traceId: string; }) => B): Mapped<C, B>;}Example Mapping a shared Command into a component's message
import { Command, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"
const Message = UiSchema.TaggedEnum({ CompletedUploadFile: { url: Schema.String } })
const UploadFile = Command.make("UploadFile", { args: { name: Schema.String } }, ({ name }) => Effect.succeed(`https://cdn/${name}`))
const upload = UploadFile.make({ name: "photo.png" }).pipe( Command.map((url) => Message.CompletedUploadFile({ url })))Maps both channels of a Command whose body can fail to messages.
When to use
Use when issuing a library or shared Command.Service whose body has a
typed error: $.run rejects the Unmatched Command its make returns.
A Command that one component consumes handles the error in its body
instead.
Details
onSuccess maps the body's success, or each element of a Stream Command,
and onFailure the typed failure, which ends a Stream Command. A defect or
an interrupt isn't mapped. A Command whose body can't fail takes map, and
match on it doesn't compile. Both mappings get the run's SpanContext
as their second argument, as with map.
In a Story or Scene the mapping runs in the test: resolve takes the
body's success and fail its typed error. A Stream Command takes next
for each element and end when it completes.
Signature
declare const match: { <A, E, B, C>(options: { readonly onFailure: (e: E, span: SpanContext) => C; readonly onSuccess: (a: A, span: SpanContext) => B; }): <R, K extends Kind>(self: Unmatched<A, E, R, K>) => Issued<B | C, R, A, K, E>; <A, E, R, K extends Kind, B, C>(self: Unmatched<A, E, R, K>, options: { readonly onFailure: (e: E, span: SpanContext) => C; readonly onSuccess: (a: A, span: SpanContext) => B; }): Issued<B | C, R, A, K, E>;}Example Mapping a shared Command that can fail
import { Command, UiSchema } from "effect/ui"import { Effect, Schema } from "effect"
class SaveFailed extends Schema.TaggedError<SaveFailed>()("SaveFailed", { reason: Schema.String }) {}
const Message = UiSchema.TaggedEnum({ SucceededSaveTodo: {}, FailedSaveTodo: { reason: Schema.String } })
class SaveTodo extends Command.Service<SaveTodo>()("todos/SaveTodo", { args: { title: Schema.String }, success: Schema.Void, error: SaveFailed}) { static readonly layer = this.toLayer(({ title }) => title === "" ? Effect.fail(new SaveFailed({ reason: "empty" })) : Effect.void )}
const saveTodo = (title: string) => SaveTodo.make({ title }).pipe(Command.match({ onSuccess: () => Message.SucceededSaveTodo(), onFailure: (error) => Message.FailedSaveTodo({ reason: error.reason }) }))skipOnRestore
unstableMarks a Command to be skipped in the init result when an instance restores
saved history state, including on Back, forward or reload. Fresh mounts and
hydration from server state still run it.
When to use
Use when an init Command starts work already recorded in the restored
Model, such as starting a checkout.
Details
Accepts issued and unmatched Commands; match and map preserve the marker.
An instance with restore: false, no saved state or state that fails to decode
still runs the Command. Story tests can inspect its skipOnRestore field.
Signature
declare function skipOnRestore<C extends Awaitable>(self: C): CExample Starting a checkout once per visit
import { Command } from "effect/ui"import { Effect, Schema } from "effect"
const StartCheckout = Command.make("StartCheckout", { args: { cart: Schema.String } }, () => Effect.void)
// In `init`: `$.set(model).run(start)`const start = StartCheckout.make({ cart: "c1" }).pipe(Command.skipOnRestore)start.skipOnRestore // => truewithParentSpan
unstableRuns a Command as a child of an earlier span context, continuing its trace without keeping any span or fiber open across the gap.
When to use
Use when one user workflow spans several Commands separated by user
interaction, such as a preflight check followed by a confirmation click.
Store the first run's SpanContext (from the second argument of map or
match) in the Model, then pass it to the follow-up Command.
Details
Works on issued and unmatched Commands of both "Effect" and "Stream"
kinds, on either side of match and map. Passing null, undefined
or the all-zero span a mapping gets outside any trace is a no-op. Sets
parentSpan on the issued Command, so a Story test can assert it.
Signature
declare const withParentSpan: { (span: { readonly sampled: boolean; readonly spanId: string; readonly traceId: string; } | null | undefined): <C extends Awaitable>(self: C) => C; <C extends Awaitable>(self: C, span: { readonly sampled: boolean; readonly spanId: string; readonly traceId: string; } | null | undefined): C;}Example Continuing a preflight trace after confirmation
import { Command } from "effect/ui"import { Effect, Schema } from "effect"
const Release = Command.make("Release", { args: { id: Schema.String } }, () => Effect.void)
const parent: Command.SpanContext = { traceId: "00000000000000000000000000000001", spanId: "0000000000000001", sampled: true}
const command = Release.make({ id: "1" }).pipe(Command.withParentSpan(parent))command.parentSpan // => parentModels
What args accepts: a fields record or a Schema.Struct.
Signature
type ArgsInput = Schema.Struct.Fields | Schema.Struct<Schema.Struct.Fields>What update returns inside a step and a story test sees as pending.
Details
Msg is the message the Command produces, which $.run checks against the
component's message type. R is what the Command requires: the Service
for a service Command, never for one made with make. A Command whose
result is never (Effect.never, Effect.die, Stream.never) produces
no message, so any component can run it.
Signature
type Command<Msg, R = never> = Issued<Msg, R, never, "Effect"> | Issued<Msg, R, never, "Stream"> | InterruptThe data every issued Command carries, matched or not.
Signature
interface Data extends Declared { readonly args: unknown; readonly groupKey: string | undefined; readonly mode: Mode; readonly name: string; readonly parentSpan: { readonly sampled: boolean; readonly spanId: string; readonly traceId: string; } | undefined; readonly skipOnRestore?: true;}What a Command declares about the query cache, computed from its args when
it's issued. A story test reads these off the issued Command without a
cache. make Commands declare nothing.
Signature
interface Declared { readonly afterRefetch: Duration | undefined; readonly invalidates: readonly Array<Target>; readonly optimistic: readonly Array<Patch<Any>>; readonly writes: (success: any) => readonly Array<Write<Any>> | undefined;}What make and Service have in common: the data about a Command that's
known before it's issued.
Details
Args is the decoded args struct a Command is issued with, A the
body's success, IsStream whether it was declared with stream: true,
E the body's typed failure and G its group fields. Story steps
such as resolve take a definition and are typed by it.
Signature
interface Definition<in Args, out A, out IsStream extends boolean, out E = never, out G extends string = never> { readonly "~effect/ui/Command/Definition": Variance<Args, A, IsStream, E, G>; readonly group: readonly Array<G>; readonly mode: Mode; readonly stream: IsStream;}What Command.make returns: a definition whose make issues the Command
from its args struct.
Signature
interface Factory<in out Args, in out Msg, out IsStream extends boolean = false, out G extends string = never> extends Definition<Args, Msg, IsStream, never, G> { readonly args: Top; readonly name: string; make(...args: MakeArgs<Args>): IsStream extends true ? Issued<Msg, never, Msg, "Stream", never> : Issued<Msg, never, Msg, "Effect", never>;}The union of the registered framework services.
Signature
type FrameworkService = FrameworkServices[keyof FrameworkServices]The services every mounted app is guaranteed to have, which a Command may use without them appearing in its component's requirements.
Details
Host packages widen this interface by module augmentation. The runtime
provides these services when a Command runs, so they're removed from R.
The core lists Scope, Renderer.Refs and the query cache, and host
packages add their host marker.
Signature
interface FrameworkServices { readonly Cache: Cache; readonly HtmlHost: Host; readonly Refs: Refs; readonly Scope: Scope;}Example Registering a host's framework service
declare module "effect/ui/Command" { interface FrameworkServices { readonly MyHost: MyHost }}
declare class MyHost { readonly _: unique symbol}A Command that interrupts the running and queued runs of another Command.
Details
It produces no message. With a group key, only the runs of that group are interrupted.
Signature
interface Interrupt extends Pipeable { readonly _tag: "Interrupt"; readonly "~effect/ui/Command": Variance<never, unknown>; readonly groupKey: string | undefined; readonly name: string;}An issued Command: what a definition's make returns, or what match makes
of an Unmatched one.
Details
Msg is the message it produces and R what it requires. Source is
the success of the Command's definition before any map, and SourceE
its typed failure before match; they're what a story's resolve and
fail steps take. K is the kind, which decides whether effect or
stream holds the work; the other field is undefined: "Effect" for a
Command whose result is one message, "Stream" for one declared with
stream: true. Narrow a Command on _tag before reading the work.
One interface for both kinds, rather than two, is what lets
command.pipe(Command.map((result) => ...)) infer result.
Signature
interface Issued<out Msg, out R, in Source, out K extends Kind, in SourceE = never> extends Proto<Msg, Source, SourceE> { readonly _tag: K; readonly effect: K extends "Effect" ? Effect<Msg, never, R> : undefined; readonly stream: K extends "Stream" ? Stream<Msg, never, R> : undefined;}The kind of an issued Command: "Effect" for one message, "Stream" for a
Stream of them.
Signature
type Kind = "Effect" | "Stream"How runs of one Command relate to each other when a new one is issued while an earlier one is still running.
Details
Runs are grouped by instance, Command name and the group key. Within a
group, concurrent runs everything at once, switch interrupts the earlier
runs and starts the new one once their fibers have exited, cleanup
included, and queue starts it once the earlier runs have ended. A cut run
delivers nothing.
A run is over when its fiber exits. One that was interrupted, by switch,
Command.interrupt or its instance going, still holds its group and counts
for h.isRunning until then, so a run queued behind it never overlaps its
cleanup.
There is no mode that ignores a new run while one is going: update would
still apply the Model change it issued the run with. Keep what update
needs to know in the Model, such as a Submitting state, and issue nothing
while it holds.
Signature
type Mode = "concurrent" | "switch" | "queue"The options shared by make and Service.
Details
args: a fields record or aSchema.Struct, none when omitted. The body gets one decoded struct. The log encodes a run's args through it, redactingSchema.Redactedfields.stream: truedeclares a Stream Command, so a story test knows the kind without building a Layer.modedefaults to"concurrent".grouplists args fields whose values split runs into groups, so runs of different groups don't interfere. The group key is the canonical JSON of those fields, encoded. Without it, all runs of a Command in one instance are one group.
Signature
interface Options<In extends ArgsInput, G extends string> { readonly args?: In; readonly group?: readonly Array<G>; readonly mode?: Mode; readonly stream?: boolean;}The shared fields of an issued Command.
Signature
interface Proto<out Msg, in Source = Msg, in SourceE = never> extends Pipeable, Data { readonly "~effect/ui/Command": Variance<Msg, Source, SourceE>;}A Command service class, as returned by Service.
Details
A Context.Service holding the Command's implementation. Attach one with
toLayer (or fake with X.toLayer(fn)), and issue Commands with make.
Signature
interface Service<in out Self, in out Key extends string, in out Args, in out Success extends Schema.Top, out IsStream extends boolean, in out Error extends Schema.Top = Schema.Never, out G extends string = never> extends ServiceClass<Self, Key, Service.Implementation<Args, BodyResult<Success>, IsStream, Error["Type"]>>, Definition<Args, Success["Type"], IsStream, Error["Type"], G> { constructor(_: never); readonly args: Top; readonly error: Error; readonly success: Success; make(...args: MakeArgs<Args>): [Error["Type"]] extends [never] ? IsStream extends true ? Issued<Success["Type"], Self, Success["Type"], "Stream", never> : Issued<Success["Type"], Self, Success["Type"], "Effect", never> : Unmatched<Success["Type"], Error["Type"], Self, IsStream extends true ? "Stream" : "Effect">; toLayer<LE = never, LR = never>(build: Implementation<Args, BodyResult<Success>, IsStream, Error["Type"]> | Effect<Implementation<Args, BodyResult<Success>, IsStream, Error["Type"]>, LE, LR>): Layer<Self, LE, Exclude<LR, Scope>>;}SpanContext
unstableThe coordinates of a Command run's trace span: enough to continue the same
trace in a later Command with Command.withParentSpan, without holding
any span or fiber open in between.
Details
Plain data backed by a Schema, so a component can store it in its Model
or pass it in a message. sampled travels with the ids so a child of an
unsampled root stays unsampled. Tracer.Span and Tracer.ExternalSpan
match this shape as well.
Signature
declare const SpanContext: Struct<{ readonly sampled: Boolean; readonly spanId: String; readonly traceId: String;}>A Command run's span coordinates.
Signature
type SpanContext = typeof SpanContext.TypeWhat a Service whose body can fail issues: a Command whose success A
and typed failure E haven't been mapped to messages yet.
Details
It isn't a Command, so $.run and Command.map reject it until
match maps both channels. It already carries the Command's data: its
name, args and what it declares about the cache.
Signature
interface Unmatched<out A, out E, out R, out K extends Kind> extends Pipeable, Data { readonly _tag: K; readonly "~effect/ui/Command/Unmatched": { readonly _A: Covariant<A>; readonly _E: Covariant<E>; readonly _R: Covariant<R>; }; readonly effect: K extends "Effect" ? Effect<A, E, R> : undefined; readonly stream: K extends "Stream" ? Stream<A, E, R> : undefined;}Phantom variance for a Command's message type and the success and failure of its definition.
Signature
interface Variance<out Msg, in Source, in SourceE = never> { readonly _Msg: Covariant<Msg>; readonly _Source: Contravariant<Source>; readonly _SourceE: Contravariant<SourceE>;}Other
Definition
unstableHelper types for Definition.
Signature
declare class InterruptedByRemount extends Readonly<{ readonly commands: readonly Array<{ readonly command: string; readonly path: string; }>; readonly message: string; readonly path: string; readonly remountedAt: string;}> & { readonly _tag: "InterruptedByRemount";} & Pipeable { constructor(args: { readonly commands: readonly Array<{ readonly command: string; readonly path: string; }>; readonly message: string; readonly path: string; readonly remountedAt: string; });}Helper types for Service.
Problems
CleanupFailed
unstableA run that was stopped died before its fiber exited, such as in an
Effect.onInterrupt cleanup or an uninterruptible part of its body.
Details
A stopped run delivers nothing, so the defect can't reach update, and it
doesn't fail the instance or the run that replaced it. It's reported every
time, and the log has the run's CommandInterrupted entry.
Signature
declare class CleanupFailed extends Readonly<{ readonly cause: Cause<unknown>; readonly command: string; readonly message: string; readonly path: string;}> & { readonly _tag: "CleanupFailed";} & Pipeable { constructor(args: { readonly cause: Cause<unknown>; readonly command: string; readonly message: string; readonly path: string; });}ServerCommandIssued
unstableA server-side update issued a Command. No Command runs on the server, so
it was dropped, and the log has a CommandDropped entry with reason
"server" for the same path. It is reported every time.
Details
Data the server renders comes from a query: a query fetched by the
server's per-request cache. init's Commands are dropped silently, since
the client runs them when it adopts the Model.
Signature
declare class ServerCommandIssued extends Readonly<{ readonly command: string; readonly message: string; readonly path: string;}> & { readonly _tag: "ServerCommandIssued";} & Pipeable { constructor(args: { readonly command: string; readonly message: string; readonly path: string; });}Type Ids
DefinitionTypeId
unstableIdentifies a Command definition: a factory from make or a Service class.
Signature
declare const DefinitionTypeId: "~effect/ui/Command/Definition"Identifies a Command definition: a factory from make or a Service class.
Signature
type DefinitionTypeId = typeof DefinitionTypeIdIdentifies a Command value.
Signature
declare const TypeId: "~effect/ui/Command"Identifies a Command value.
Signature
type TypeId = typeof TypeIdUnmatchedTypeId
unstableIdentifies a Command issued by a Service whose body can fail, before
match has mapped its two channels to messages.
Signature
declare const UnmatchedTypeId: "~effect/ui/Command/Unmatched"Identifies an unmatched Command.
Signature
type UnmatchedTypeId = typeof UnmatchedTypeIdUtility Types
The fields of an args input.
Signature
type ArgsFields<In> = In extends Schema.Struct<infer Fields> ? Fields : In extends Schema.Struct.Fields ? In : neverThe decoded args struct of an args input: what the body, invalidates,
optimistic and writes get.
Signature
type ArgsOf<In> = Schema.Struct<ArgsFields<In>>["Type"]Passes when C is an issued or unmatched Effect-kind Service Command,
and otherwise says why Command.afterRefetch doesn't take it.
Signature
type AwaitsRefetch<C> = C extends Unmatched<infer _A, infer _E, infer R, infer K> ? AwaitsRefetchOf<R, K> : C extends Issued<infer _Msg, infer R, infer _S, infer K, infer _SE> ? AwaitsRefetchOf<R, K> : neverWhat fails a Command in a story: the definition's own typed failure, for a
definition or an issued Command, before match.
Signature
type Failure<C> = C extends Proto<infer _Msg, infer _Source, infer SourceE> ? SourceE : C extends Unmatched<infer _A, infer E, infer _R, infer _K> ? E : C extends Definition<infer _Args, infer _A, infer _S, infer E, infer _G> ? E : neverThe optional group argument of Command.interrupt and h.isRunning: the
group fields of the Command's args, or none for a Command without a
group.
Signature
type GroupArg<Args, G extends string> = [G] extends [never] ? [] : [group?: Pick<Args, G & keyof Args>]The args fields a group may name: those whose encoded form is JSON.
Signature
type GroupField<In> = { [K in keyof ArgsFields<In>]: ArgsFields<In>[K] extends { readonly Encoded: infer E;} ? [E] extends [Json] ? K : never : never }[keyof ArgsFields<In>] & stringThe arguments of make: optional when every field of the args is.
Signature
type MakeArgs<Args> = {} extends Args ? [args?: Args] : [args: Args]C with its message mapped to B. An Interrupt stays an Interrupt, and
a Command whose kind is "Effect" | "Stream" becomes a union of the two kinds,
so it still fits Command<B>.
Signature
type Mapped<C, B> = C extends Issued<infer _Msg, infer R, infer Source, infer K, infer SourceE> ? K extends Kind ? Issued<B, R, Source, K, SourceE> : never : C extends Interrupt ? Interrupt : neverThe message type of a Command, or of a union of them.
Signature
type Message<C> = C extends Proto<infer Msg, infer _Source, infer _SourceE> ? Msg : C extends Definition<infer _Args, infer Msg, infer _S, infer _E, infer _G> ? Msg : neverThe requirements of a Command, or of a union of them.
Signature
type Requirements<C> = C extends Issued<infer _Msg, infer R, infer _S, infer _K, infer _SE> ? R : neverWhat resolves a Command in a story: the definition's own success, for a
definition or an issued Command, before any map or match.
Signature
type Result<C> = C extends Proto<infer _Msg, infer Source, infer _SourceE> ? Source : C extends Unmatched<infer A, infer _E, infer _R, infer _K> ? A : C extends Definition<infer _Args, infer A, infer _S, infer _E, infer _G> ? A : never