import { T as TellAnswer } from '../loop-CKqoteig.js'; import { Scope, Effect, Schema, ManagedRuntime } from 'effect'; import { b as Cmd$1, c as Sub, M as Machine$1, u as CmdInput, a as CmdDef, f as TaggedError, A as AnyCmdDef, k as Settled, C as CmdOf } from '../core-sEWVgnpI.js'; import { c as EffectRun, d as InterpretOption, E as EffectInterpret, S as SubscribeOption, a as EffectSubscribe } from '../run-DhgptktR.js'; export { C as CellErrors, e as EffectBootingRun, f as EffectBootingRuntime, g as EffectInterpretCell, h as EffectRunOptions, i as EffectRunner, j as EffectRuntime, I as InterpretServices, k as Stopped, l as StoreFailed, m as SubFailed, b as SubscribeServices, r as run } from '../run-DhgptktR.js'; import { e as MachineTypes, f as RunOptions, H as HandlerFamily, g as RunHandle } from '../runtime-types-f231H8Gq.js'; import '@standard-schema/spec'; import 'effect/Cause'; import 'effect/Types'; /** * Helpers for running child machines under a parent on the Effect engine * (#556, ruling R1.1 of #554). * * tea still runs one machine per `run` and keeps no table of runs (#312). A * host that builds a tree of runs keeps its own table, ids and Msg names, and * hands the steps that race to these functions: `spawn` starts a child and * enrols it as one step, `stop` stops one child, and `tell` puts a Msg on a * run's line without waiting for it. */ /** * Put `msg` on a run's line and answer at once. The answer means queued, not * handled: the receiver's step has not run yet, and any result comes back later * as its own Msg. So two machines can tell each other from their Cmd handlers * and neither stops. `machine` is the machine `runtime` runs. * * The answer is `"queued"`, `"stopped"` for a run that is stopping or has * stopped, or `"no_cell"` when its current State has no cell for the Msg. Msgs * already in line have not folded yet, so a Msg that only a queued one makes * acceptable answers `"no_cell"`. * * `runtime` is what `ready` succeeded with, or a spread of it. Those carry the * run's line, and the type asks for it, so an `EffectRuntime` built by hand is a * compile error. So is the handle `run` yielded, with a store or without one: wait * for `ready`. * * `tell` carries no failure in its type. A hand-built object cast past the type * has no line to put a Msg on, and `tell` dies with a defect there. * * What happens after `"queued"` is the receiver's. Two `tell`s from one sender * fold in the order they were sent. A failed save or a cell's failure goes to * the receiver's `onError`, never back to the sender. A Msg whose cell is gone * by its turn is dropped without a word, and a `stop()` that gives up drops * what is still in line and counts it, per Msg type, in its * `DrainTimeoutNotice`. * * Two hand-written waiting `runtime.dispatch(...)` calls into each other, one * from each machine's Cmd handler, still stop both machines: `dispatch` waits, * and tea has no lock-up detector. Use `tell` there. * * ```ts * const answer = yield* tell(parent, parentRun, { _tag: "child_stopped", id }); * ``` */ declare const tell: (machine: Machine$1, runtime: EffectRun, msg: NoInfer) => Effect.Effect; /** * The host's own steps of a {@link spawn}. The host owns the table of * children, their ids and the parent's Msg names; `spawn` owns the order the * steps run in and keeps an interrupt from landing between them. */ interface SpawnSteps { /** * Start the child and return what the host keeps for it. It runs with the * child's scope provided, so a `run(machine, opts)` in it belongs to that * scope, and so does anything else it acquires. `scope` is the same scope, * for a host that keeps it to stop the child with `stop`. A failure * closes the child's scope, which runs `remove` and `notify`. */ readonly start: (scope: Scope.Closeable) => Effect.Effect; /** Add the started child to the host's table. */ readonly enrol: (child: A) => Effect.Effect; /** * Take the child out of the host's table. It runs when the child's scope * closes, after its run has stopped, whether or not `enrol` ran, so it must * be safe on a child the table does not hold. */ readonly remove: Effect.Effect; /** * Say the child stopped, usually a {@link tell} to the parent. It runs * after `remove`, on a fiber of its own that the closing scope never waits * for, so even a step that does wait cannot hold the close. * * It cannot fail: nothing reads that fiber, so the step itself handles what * its notice can fail with. A `tell` has nothing to handle. Its argument is the * handle the parent's `ready` gave: a parent handle built by hand, or one straight * from `run`, does not compile. A defect in this step, such as a `tell` on a * hand-built object cast past that type, is not observed by `spawn` and ends the * fiber unseen. */ readonly notify: Effect.Effect; } /** * Start a child in a scope forked from `parentScope` and enrol it in the * host's table, as one uninterruptible step. Stop a child with `stop`, * or by closing its scope; closing `parentScope` stops every child spawned * under it. * * What it guarantees, with no guard in host code: * * - the table never holds a child whose scope has closed. The fork, the * removal finalizer, `start` and `enrol` all happen or none do, and a * child whose scope closed before `enrol` is removed again; * - closing a child never waits for the parent. `notify` runs on a detached * fiber, so a parent Cmd handler can stop a child; * - `remove` runs after the child's run has stopped. * * Nothing reads the fiber `notify` runs on, so `spawn` reports no failure of * it and `notify` is typed to have none. A `tell` carries no failure, and a * failed save of the parent reaches the parent's own `onError`. A defect in * `notify`, such as a `tell` on a handle cast past its type, ends that fiber * unseen. * * A child whose run fails stops the same way, with no host call: a Sub failure * the Sub did not map to a Msg, or a reducer throw under the default `stop` * strategy, closes the child's scope, so `remove` and `notify` run. * * `child.run.stop()` is not one of the two ways to stop a child. It stops the * run and leaves the scope open, so the entry stays in the table and the * parent is not told. * * ```ts * const child = yield* spawn(parentScope, { * start: (scope) => * Effect.map(run(worker, {}), (run) => ({ run, scope })), * enrol: (child) => Effect.sync(() => children.set(id, child)), * remove: Effect.sync(() => children.delete(id)), * notify: tell(parent, parentRun, { _tag: "child_stopped", id }), * }); * ``` */ declare const spawn: (parentScope: Scope.Scope, steps: SpawnSteps) => Effect.Effect>; /** * Stop one child that `spawn` started. `scope` is the child's scope, * the one its `start` was handed. * * It closes that scope, so the child's run stops, `remove` takes the entry * out of the host's table and `notify` tells the parent. It does not wait for * `notify`, so a parent Cmd handler can call it. Stopping a child that has * already stopped succeeds and sends no second notice. * * ```ts * yield* stop(child.scope); * ``` */ declare const stop: (scope: Scope.Closeable) => Effect.Effect; /** * The Effect entry's `Cmd`: the core's list helpers and `make` for plain * Effect schemas (#631). It is a function over the core `Cmd.define`, so the * def it returns is the same `CmdDef` a hand-wrapped call builds. */ /** * An Effect schema that checks a value and hands the same type on. Both sides * are one type, and decoding needs no service. * * tea types a handler's answer by the type the `ok` schema hands on, and checks * that answer by parsing it. A schema whose two sides differ — a * transformation like `Schema.FiniteFromString`, a brand — would refuse the * very value the handler's type asks for, so it does not compile here. Pass * `Schema.toType(schema)` to keep the checks and drop the translation. */ type CheckingSchema = Schema.Codec>; declare function make$1(name: Name, spec: { readonly input: CheckingSchema; readonly ok: CheckingSchema; readonly err: Tags; }): CmdDef>; /** * A Cmd value, as the core types it. Exported beside the `Cmd` helpers so an * Effect user reads both from this entry. */ type Cmd = Cmd$1; /** * The helpers for building Cmds on the Effect engine. `Cmd.none`, `Cmd.batch`, * `Cmd.when` and `Cmd.whenDefined` are the core's; `Cmd.make` is this * entry's own. */ declare const Cmd: { /** * Declare a typed Cmd constructor from plain Effect schemas. It returns what * the core `Cmd.define` returns, with each schema passed through * `Schema.toStandardSchemaV1` for you: * * const fetchUser = Cmd.make("fetch_user", { * input: Schema.Struct({ id: Schema.String }), * ok: Schema.Struct({ name: Schema.String }), * err: ["not_found"], * }); * * `input` and `ok` take a schema that checks and never translates: both of * its sides are one type and decoding needs no service. A transformation, a * brand or a schema that needs a service is a compile error. * * To keep the checks of a transformation or a brand, pass * `Schema.toType(schema)`. That is no way through for a schema that needs a * service: its check lives in the decode step, and `Schema.toType` drops that * step, so the Cmd would compile and never run the check. Run such a check in * the handler. * * A schema whose validation needs a Promise compiles, and is refused with * `AsyncSchemaError` when the Cmd settles, as the core's is. * * It takes Effect schemas only. A zod schema, or any other Standard Schema, * goes to `Cmd.define` from `@demlik/tea`. */ readonly make: typeof make$1; readonly none: readonly never[]; readonly batch: (...arrs: readonly (readonly C[])[]) => readonly C[]; readonly when: (cond: boolean, cmd: C) => readonly C[]; readonly whenDefined: (value: T | undefined, build: (value: T) => C) => readonly C[]; }; /** * `unknown` while no plain Msg tag is a settled Msg name of a listed Cmd, else * an object with one required key per colliding tag, so `msg: Schema.Schema` * is refused on its own line with each tag named in the diagnostic. */ type NoSettledTag = [ Extract["_tag"]> ] extends [never] ? unknown : { readonly [Tag in `msg tag "${Extract["_tag"]>}" is a settled Msg name of a listed Cmd`]: never; }; /** * The members of a tag union that are no one literal: `string` or a template * literal. `Record` has no required key for either, so the empty * object satisfies it, and it has one for every literal. */ type OpenTag = Tag extends string ? Record extends Record ? Tag : never : never; /** * `unknown` while every plain Msg tag is a literal, else one required key that * says so. One open member among literals is still found, since `OpenTag` * reads each member alone. */ type LiteralTags = [OpenTag] extends [never] ? unknown : { readonly "every msg tag must be a literal, not an open string": never; }; declare function make, Ctx = unknown>(spec: NoInfer, CmdOf, U, Ctx>, "cmds">> & { readonly model: Schema.Schema; readonly msg: Schema.Schema & NoSettledTag & LiteralTags; readonly cmds: readonly D[]; readonly types?: Pick, "sub" | "ctx">; }): Machine$1, CmdOf, U, Ctx> & { readonly model: Schema.Schema; readonly msg: Schema.Schema; }; /** A core tea machine, with the same init, update and engine contracts. */ type Machine = Machine$1; /** * Build a tea machine with readonly `model` and `msg` schema references for * explicit host decoding. Required `model` and `msg` Effect schemas supply the * model and plain message types. A required `cmds` list supplies command values * and their settled messages; use `[]` * for a machine without commands. No separate model, message or command type * declaration is needed. * * The optional `types` object accepts only `sub` and `ctx`, as phantom values * such as `{} as MySub`. The body follows `defineMachine`: `init` returns a * model and commands, and `update` is a reducer or transitions table. For a * tagged model, name `loaded` in `init` to keep literal return values narrow. * * The result exposes the same schema references as readonly `model` and `msg` * properties, typed as `Schema.Schema` and `Schema.Schema`. `msg` describes * plain messages only, without command-settlement messages. The result remains * a core tea `Machine` accepted by the engines and pure helpers. * * Two declarations are refused on the `msg` line, and the diagnostic names the * fault. A plain message whose tag is a settled message name of a listed * command (`fetch_file_ok` beside the command `fetch_file`) would put two * different messages in one update cell; the diagnostic names each such tag, * and the fix is to rename the message. A message whose tag is not a literal * (`Schema.String`, or a `Schema.TemplateLiteral`) would turn the update table * into one that accepts any cell name, so a misspelled cell compiles; the * diagnostic says every tag must be a literal, and the fix is to give the * message a `Schema.Literal` tag. * * The maker performs no decoding at construction, boot or dispatch. Hosts parse * external data explicitly. The exposed schema types track decoded values; * `Schema.toType(machine.model)` and `Schema.toType(machine.msg)` let a host * validate saved models and incoming messages already in those decoded shapes. * * @example * ```ts * import { Machine } from "@demlik/tea/effect"; * import { Schema } from "effect"; * * const counter = Machine.make({ * model: Schema.Struct({ count: Schema.Number }), * msg: Schema.Struct({ _tag: Schema.Literal("UserIncremented") }), * cmds: [], * init: (loaded) => [loaded ?? { count: 0 }, []], * update: { * UserIncremented: (state) => [{ count: state.count + 1 }, []], * }, * }); * * Schema.decodeUnknownSync(Schema.toType(counter.model))({ count: 2 }); * Schema.decodeUnknownSync(Schema.toType(counter.msg))({ * _tag: "UserIncremented", * }); * ``` */ declare const Machine: { readonly make: typeof make; }; /** * `runIn`: the Effect engine's `run`, as a host adapter takes it (#852). * * `useMachine` takes a `run` that hands back its handle at once. The Effect * engine's `run` is an `Effect` that needs a `Scope` and the services its * handlers read, so it does not fit. `runIn(runtime)` closes the gap and nothing * more: the services are the caller's `ManagedRuntime`, used as it is (ADR 0020), * and each call opens a `Scope` of its own to run in, which `stop()` closes (ADR * 0030). The lifecycle (one run per mount under Strict Mode, Subs paused on an * `` hide, the run stopped on a real unmount) stays `MountedRun`'s. * * A `ManagedRuntime` builds its Layer on first use, and an async Layer is not * built when `run` is called. So the handle is the run's whole surface from the * first instant: a Msg sent before the Layer is built waits and folds in order * once it is, and a Layer that fails to build ends the run before it began, * reaching `onError` once. */ /** * The Effect engine's handler tables for a runtime that provides `R`: `interpret` * cells that return an `Effect` and `subscribe` runners that return a `Stream`, * each reading no service outside `R` but the run's own `Scope.Scope`. * Requiredness is the engine's own: a machine with a Cmd needs `interpret`, one * with a Sub beyond `timer` needs `subscribe`. */ interface EffectHandlers extends HandlerFamily { readonly handlers: EffectHandlerTables; } /** The `interpret` and `subscribe` options of `run`, for a runtime providing `R`. */ type EffectHandlerTables = InterpretOption> & SubscribeOption>; /** * The `run` that {@link runIn} gives `useMachine`: any machine in, a handle out * at once, with the handlers typed by {@link EffectHandlers}. A cell that reads a * service the runtime does not provide does not compile. */ type BridgedRun = ((machine: Machine$1, opts: RunOptions>) => RunHandle) & { readonly "~demlik/tea/handlers"?: EffectHandlers; }; /** * Turn the caller's `ManagedRuntime` into the `run` that `useMachine` takes: * `useMachine(machine, { run: runIn(appRuntime), ctx, interpret })`. * * Every Cmd handler and Sub runner reads its services from `runtime`, which * `runIn` never builds on its own, caches or disposes: the caller owns it, and it * is still usable after the component is gone. * * The same function comes back for the same runtime every time, because * `useMachine` keys its run on it. Calling `runIn` in a render is safe. * * A run stops by closing the `Scope` it ran in: handler fibers are interrupted, * their finalizers run, and what a handler or runner acquired from `Scope.Scope` * is released. A Layer that fails to build, or a runtime already disposed, * reaches `onError` once under `phase: "boot"`. */ declare function runIn(runtime: ManagedRuntime.ManagedRuntime): BridgedRun; export { type BridgedRun, type CheckingSchema, Cmd, type EffectHandlerTables, type EffectHandlers, EffectInterpret, EffectRun, EffectSubscribe, Machine, type SpawnSteps, TellAnswer, runIn, spawn, stop, tell };