import WebSocket from 'ws'; import { c as Sub, D as Dispose } from '../core-sEWVgnpI.js'; import { M as Migrated, D as DeletableStore, F as FencedStore } from '../runtime-types-f231H8Gq.js'; import { F as FencedJournal, J as Journal } from '../index-_evnHmXt.js'; import '@standard-schema/spec'; /** * Why a writer could not take a lock: * * - `another-host`: the lock names another host, which may still be writing. * - `live-holder`: its process is alive on this machine, or its old-format id * names a live process here. * - `unwritten`: the lock is empty and too young to count as a crash. * - `unreadable`: its contents are not a lock this version can read. * - `contended`: no one holder was to blame; other writers kept taking it. */ type FileLockBlock = "another-host" | "live-holder" | "unwritten" | "unreadable" | "contended"; /** * A write gave up waiting for a lock file. `lockPath` names the file to clear * and `blockedBy` says why it could not be taken. The write did not happen. */ declare class FileLockTimeoutError extends Error { readonly lockPath: string; readonly waitedMs: number; readonly blockedBy: FileLockBlock; readonly name = "FileLockTimeoutError"; readonly _tag: "file_lock_timeout"; constructor(lockPath: string, waitedMs: number, blockedBy: FileLockBlock); } /** * @packageDocumentation * @demlik/tea/node — Node host adapter for `@demlik/tea`. * * Every host adapter ships two halves (mirrors `@demlik/tea/do`): * * 1. `fileStore(path, parse)` — a `Store` over a JSON file on disk. * Atomic save (temp + rename). Absent file → `load()` resolves `null` * (fresh boot). Structurally malformed JSON throws at `load()` (an infra * error), matching `doStore`; a shape mismatch is NOT a throw — the * substrate calls `migrate`, which returns `refuse(reason)`. Both make * `ready` reject with `StoreRefusedError`, and the file is left as is. * Use for resumable scripts / local repro of prod machines. Ephemeral * CLIs can skip persistence with `memoryStore` from `@demlik/tea/mem`. * * 2. `nodeSubscribe({ ws })` — the runners for the three node-native * Sub types this package owns, handed to `run` as its `subscribe`: * - `node_ws` — deps `{ key, url }`. Opens a `ws` WebSocket; routes * open/message/close/error into Msgs through the `ws` * handlers. Registers the live socket in * `ctx.wsRegistry` under `key` so a Cmd handler can * write to it (see `sendToWebSocket`). Cleanup closes * the socket for ANY non-CLOSED state. * - `node_timer` — deps `{ delayMs, msg, repeat? }`. setTimeout / * setInterval; cleanup clears it. * - `node_signal` — deps `{ signal, msg }`. A process signal * (SIGINT/SIGTERM/…) → Msg; cleanup detaches the * listener. * * Unlike tea-do — whose `alarm()` / `webSocketMessage()` are DO lifecycle * methods the handler can't observe from the outside, hence its registries — * a node process is continuously alive: each runner holds its resource in * closure and the returned cleanup closes it. The engine runs that cleanup the * instant the Sub's `deps` go null, and a changed `deps` value stops the old * runner before starting the new one — end-then-start choreography for free * (Rule 9, [invariant 4]). A lifecycle-bound resource (a socket, a timer) * becomes impossible to leak from a reducer cell, because no reducer cell owns * its teardown. * * `ctx.wsRegistry` is the one shared surface: `node_ws` populates it, keyed by * the Sub's `deps.key`; a Cmd interpreter reads it to write to the open * socket. Same shape as tea-do's `wsRegistry`. */ /** * Persist a machine's state to a JSON file — pass the `path` and a `parse` that * validates what comes back, get a `Store` you hand to `run` so the next run * resumes where this one stopped. * * `parse` is REQUIRED because the file is a real serialization boundary — the * bytes that come back through `JSON.parse` are structurally `unknown`, and the * caller (who owns `S`) is the only party that can validate the shape. * `parse` returns `S` for a shape it recognizes, `null` when nothing was saved * (the substrate boots `init` with `loaded = null`), and `refuse(reason)` for * saved bytes it cannot read (`ready` rejects with `StoreRefusedError`). * `parse` must NOT throw per the `Store.migrate` contract. * * Pass `{ fenced: true }` to get a `FencedStore` instead — see * {@link FileStoreOptions}. * * Either form is a `DeletableStore`: `delete()` removes the state file and * its `.fence` version stamp, so a host that forgets a run needs no * knowledge of the layout on disk. */ declare function fileStore(path: string, parse: (raw: unknown) => Migrated): DeletableStore; declare function fileStore(path: string, parse: (raw: unknown) => Migrated, options: FileStoreOptions & { readonly fenced: true; }): FencedStore & DeletableStore; declare function fileStore(path: string, parse: (raw: unknown) => Migrated, options?: FileStoreOptions): DeletableStore | (FencedStore & DeletableStore); /** Options for {@link fileStore}. */ interface FileStoreOptions { /** * Refuse a second live writer (#143). With `{ fenced: true }` the returned * store is a `FencedStore`: it carries a version stamp beside the state * file, and `run` compare-and-swaps against it on every save. A process that * boots reads the current version and takes the fence; the older live writer * that started from the same version is refused with a `StoreConflictError` * at its next save. Omit it and the store is exactly as it was — the last * writer wins, and single-writer is the caller's precondition to keep. * * A run on a fenced store must be given an `onError`, or it does not compile * (see `StoreAndOnError`). A lost fence can surface with no caller to reject * at, under `"stop-save"` or `"follow-up"`, and the default sink would rethrow * it and end the process. Treat a `StoreConflictError` there as this run having * moved to another process: stop that run, and leave the others alone. * * Each save and `delete()` takes a lock file, `.fence.lock`, and a * writer that dies holding it leaves it behind. The next write steals a lock * whose holder is proven gone: an empty one older than a short grace period, * one from an earlier boot of this machine, or one whose process is dead. * * Any other lock is waited on for up to 10 seconds, and then the write rejects * with a {@link FileLockTimeoutError} naming the file. That includes a lock * from another host, which is never stolen because that host may be live on a * shared volume. So a folder restored onto a new machine can need one clear * step: once the old machine is known to be gone, delete the file. Hosts are * told apart by `os.hostname()`, so give two live hosts on one volume two * names. */ readonly fenced?: true; } /** * Append opaque Unicode text in atomic batches under `dir`. * Stream file names encode UTF-8 bytes: a-z, 0-9, `-` and `_` stay literal; * every other byte is `%` plus two lowercase hex digits, followed by `.jsonl`. * Names remain distinct across case-insensitive and Unicode-normalizing volumes. * Each LF-terminated frame contains one array of opaque strings. * The driver never parses record bodies. * * The plain call takes no cross-process lock; one writer per stream is the * caller's precondition. Pass `{ fenced: true }` for `appendFenced`, which * compares the real head and appends under the existing `wx` stream lock. * A stale or ahead expectation refuses without writing; an unavailable lock * returns `journal_io` with `uncertain: false` and the lock's clear step. * Base `append` remains unconditional in either form. Reads refresh incrementally, * omit an incomplete tail without changing it, and the next append truncates * that tail before writing. Short writes are completed before acknowledgement. * Complete batches survive controlled process interruption; no fsync or * power-loss guarantee is made. * * The factory remains experimental on the stable `./node` subpath. * @experimental */ declare function fileJournal(dir: string, options: { readonly fenced: true; }): FencedJournal; declare function fileJournal(dir: string, options?: { readonly fenced?: false; }): Journal; /** * The `deps` of a `node_ws` Sub: which socket (`key`) and where it connects * (`url`). Both are plain data, so the engine derives the Sub's id from them — * the same `{ key, url }` across transitions is the same socket (kept open), * and a changed one closes it and opens a fresh one. * * `key` is the author's name for the socket: the Cmd side addresses it through * {@link sendToWebSocket} by that key, since the derived Sub id is not * something a Cmd handler can know. It must be unique among the machine's live * `node_ws` Subs. */ type NodeWsDeps = { readonly key: string; readonly url: string; }; /** * A node WebSocket sub. Its callbacks are not data, so they live on the runner * side — {@link NodeWsHandlers}, handed to {@link nodeSubscribe}. */ type NodeWsSub = Sub<"node_ws", NodeWsDeps>; /** * The `deps` of a `node_timer` Sub. One-shot `setTimeout` by default; * `repeat: true` → `setInterval`. */ type NodeTimerDeps = { readonly delayMs: number; readonly msg: M; readonly repeat?: boolean; }; /** * A node timer sub. Cleanup clears the timer — a timer keyed to a phase is * cancelled the moment the machine leaves that phase, and a changed * `delayMs` / `msg` / `repeat` is a new id, so the timer restarts. For a plain * one-shot, the engine's built-in `timer` Sub needs no runner at all. */ type NodeTimerSub = Sub<"node_timer", NodeTimerDeps>; /** The `deps` of a `node_signal` Sub: `signal` (SIGINT/SIGTERM/…) → `msg`. */ type NodeSignalDeps = { readonly signal: NodeJS.Signals; readonly msg: M; }; /** * A process-signal sub. Cleanup detaches the listener. Lets graceful shutdown * be a real machine transition rather than an out-of-band `process.on` that the * reducer can't see. */ type NodeSignalSub = Sub<"node_signal", NodeSignalDeps>; /** * The union of the Sub types the Node adapter ships runners for: WebSocket, * timer and process signal. */ type NodeSub = NodeWsSub | NodeTimerSub | NodeSignalSub; /** The live `node_ws` sockets, keyed by each Sub's `deps.key`. */ type NodeWsRegistry = Map; /** * The Ctx fields the `node_ws` runner depends on. A consumer's Ctx must extend * this so the runner can register the live socket and Cmd handlers can reach * it. * * Deliberately NOT parameterized by Msg: the registry holds raw `WebSocket`s, * and the Msg-typed callbacks live in the {@link NodeWsHandlers} handed to * `nodeSubscribe`. Trip-wire: if a future node Sub holds a Msg-typed callback * on ctx, this becomes `NodeSubscribeCtx`. */ interface NodeSubscribeCtx { wsRegistry: NodeWsRegistry; } /** * Write a frame to the `node_ws` socket whose `deps.key` is `key`. No-op * (returns `false`) when the socket is absent, not OPEN, or `send()` throws. * The Cmd-side companion to the `node_ws` Sub: the Sub owns the socket's * lifetime; this writes to it. * * The contract is a boolean no-op, never a throw: the socket can transition out * of OPEN between the `readyState` check and `send()` (or `ws` can throw on an * errored underlying connection), and a Cmd interpreter must not crash on that. */ declare function sendToWebSocket(ctx: NodeSubscribeCtx, key: string, data: string): boolean; /** * What a `node_ws` socket's events become. Functions cannot be `deps`, so they * live here, on the runner side; each receives the running Sub so one handler * table can branch on `sub.deps` (its `key` or `url`) when a machine runs more * than one socket. * * Only `onMessage` returns `M | null` (null drops the frame) because inbound * frames are the boundary that needs a parse-and-maybe-discard seam. `onOpen`/ * `onClose`/`onError` always dispatch — a spurious one is dropped in the reducer * (the cell ignores it), not here. An omitted one dispatches nothing. */ interface NodeWsHandlers { onMessage(data: string, sub: NodeWsSub): M | null; onOpen?(sub: NodeWsSub): M; onClose?(code: number, reason: string, sub: NodeWsSub): M; onError?(message: string, sub: NodeWsSub): M; } /** The options of {@link nodeSubscribe}: the `node_ws` handlers, when used. */ interface NodeSubscribeOpts { readonly ws: NodeWsHandlers; } /** The `node_timer` + `node_signal` runners — what every `nodeSubscribe` returns. */ interface NodeSubscribeBase { node_timer: (sub: NodeTimerSub, ctx: unknown, dispatch: (msg: M) => void) => Dispose; node_signal: (sub: NodeSignalSub, ctx: unknown, dispatch: (msg: M) => void) => Dispose; } /** The full runner table, with `node_ws` — `nodeSubscribe({ ws })`. */ interface NodeSubscribeWithWs extends NodeSubscribeBase { node_ws: (sub: NodeWsSub, ctx: Ctx, dispatch: (msg: M) => void) => Dispose; } /** * Build the `subscribe` runners for the node Sub types, to hand to `run`: * `run(machine, { subscribe: nodeSubscribe({ ws: { onMessage } }), ctx })`. * * `node_timer` and `node_signal` read everything off `sub.deps`, so they need * no options. `node_ws` needs its {@link NodeWsHandlers}; called without them, * the table has no `node_ws` runner, so a machine that declares `NodeWsSub` * fails to typecheck at `run` rather than opening a socket nobody listens to. * `Ctx` must extend {@link NodeSubscribeCtx} so the `node_ws` runner can * register its socket. */ declare function nodeSubscribe(): NodeSubscribeBase; declare function nodeSubscribe(opts: NodeSubscribeOpts): NodeSubscribeWithWs; export { type FileLockBlock, FileLockTimeoutError, type FileStoreOptions, type NodeSignalDeps, type NodeSignalSub, type NodeSub, type NodeSubscribeBase, type NodeSubscribeCtx, type NodeSubscribeOpts, type NodeSubscribeWithWs, type NodeTimerDeps, type NodeTimerSub, type NodeWsDeps, type NodeWsHandlers, type NodeWsRegistry, type NodeWsSub, fileJournal, fileStore, nodeSubscribe, sendToWebSocket };