@ilha/model 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Ryuz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # `@ilha/model`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Elm-style Model, `update`, commands, and subscriptions for [Ilha](https://github.com/ilhajs/ilha) islands. One state tree per island, every change through a single `update` function.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ bun add @ilha/model
11
+ ```
12
+
13
+ ---
14
+
15
+ ## Usage
16
+
17
+ ```tsx
18
+ import { defineApp } from "@ilha/model";
19
+ import type { Dispatch } from "@ilha/model";
20
+ import { Data } from "effect";
21
+
22
+ type Message = Data.TaggedEnum<{
23
+ Decrement: {};
24
+ Increment: {};
25
+ }>;
26
+ const Message = Data.taggedEnum<Message>();
27
+
28
+ interface Model {
29
+ readonly count: number;
30
+ }
31
+
32
+ const app = defineApp({
33
+ init: () => ({ model: { count: 0 } }),
34
+ update: (model: Model, message: Message) =>
35
+ Message.$match(message, {
36
+ Decrement: () => ({ model: { count: model.count - 1 } }),
37
+ Increment: () => ({ model: { count: model.count + 1 } }),
38
+ }),
39
+ view: (model: Model, dispatch: Dispatch<Message>) => (
40
+ <div>
41
+ <p>{model.count}</p>
42
+ <button type="button" onclick={() => dispatch(Message.Decrement())}>
43
+ -
44
+ </button>
45
+ <button type="button" onclick={() => dispatch(Message.Increment())}>
46
+ +
47
+ </button>
48
+ </div>
49
+ ),
50
+ });
51
+
52
+ export const Counter = app.component;
53
+ ```
54
+
55
+ Mount it like any Ilha component: `mount(host, Counter)` or `await renderToString(Counter)`.
56
+
57
+ Test commands without rendering with `@ilha/model/test`: `runCommands` collects what commands resolve to, and `simulate` runs the loop on input messages.
58
+
59
+ See [Elm architecture](https://ilha.build/guide/ui/model) for commands, subscriptions, submodels, and testing.
package/dist/app.d.ts ADDED
@@ -0,0 +1,125 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Layer from "effect/Layer";
3
+ import type { AtomRegistry } from "effect/reactivity/AtomRegistry";
4
+ import type * as Schema from "effect/Schema";
5
+ import * as Stream from "effect/Stream";
6
+ import type { Component, View } from "ilha";
7
+ /** Send a message into the app loop. */
8
+ export type Dispatch<Message> = (message: Message) => void;
9
+ /**
10
+ * One-shot work returned from `init` or `update`. Resolve with a follow-up
11
+ * message or with nothing. The `never` error channel forces every expected
12
+ * failure into a message; defects are logged and the island keeps running.
13
+ */
14
+ export type Cmd<Message, R = never> = Effect.Effect<Message | void, never, R | AtomRegistry>;
15
+ /**
16
+ * What `init` and `update` return: the next model plus optional one-shot
17
+ * work. Several commands run concurrently with each other.
18
+ */
19
+ export interface UpdateResult<Model, Message, R = never> {
20
+ readonly model: Model;
21
+ readonly cmd?: Cmd<Message, R> | readonly Cmd<Message, R>[] | undefined;
22
+ }
23
+ /**
24
+ * Ongoing work whose lifetime follows `deps(model)`. Build entries with
25
+ * {@link subscription} so each one keeps its own `Deps` type.
26
+ */
27
+ export interface Subscription<Model, Message, Deps, R = never> {
28
+ /** Values controlling the lifetime; the stream restarts when they change. */
29
+ readonly deps: (model: Model) => Deps;
30
+ /** Stream of messages for the current deps. Restarted when deps change. */
31
+ readonly stream: (deps: Deps) => Stream.Stream<Message, never, R | AtomRegistry>;
32
+ }
33
+ /**
34
+ * Name one subscription. Each entry infers its own `Deps` from its `deps`
35
+ * function, so `stream` receives the exact type its deps return. Annotate
36
+ * the model parameter; everything else infers.
37
+ */
38
+ export declare const subscription: <Model, Message, Deps, R = never>(sub: Subscription<Model, Message, Deps, R>) => Subscription<Model, Message, Deps, R>;
39
+ /**
40
+ * Options for {@link defineApp}. `Message` is inferred from `update`'s
41
+ * message parameter only; every other position checks against it, so a
42
+ * command that resolves to one variant never narrows the app's message
43
+ * type.
44
+ */
45
+ export interface AppOptions<Model, Message, R = never, E = never> {
46
+ /** Component name shown in `ilha/debug` trees. Default `"ModelApp"`. */
47
+ readonly name?: string | undefined;
48
+ /**
49
+ * Build the first model, plus an optional start-up command. Must be pure.
50
+ * Runs once per instance; the command runs once per client mount, never
51
+ * during server rendering.
52
+ */
53
+ readonly init: () => UpdateResult<Model, NoInfer<Message>, R>;
54
+ /** The only place state changes. Must be pure. */
55
+ readonly update: (model: Model, message: Message) => UpdateResult<Model, NoInfer<Message>, R>;
56
+ /** Render the model. Must be pure; report facts with `dispatch`. */
57
+ readonly view: (model: Model, dispatch: Dispatch<NoInfer<Message>>) => View;
58
+ /** Ongoing work gated by slices of the model. */
59
+ readonly subscriptions?: readonly Subscription<Model, NoInfer<Message>, any, R>[] | undefined;
60
+ /** Services available to commands and subscriptions. */
61
+ readonly layer?: Layer.Layer<R, E> | undefined;
62
+ /**
63
+ * Codec for the model snapshot. Without it the model must be JSON-safe;
64
+ * with it, values like `Date` survive server rendering into hydration.
65
+ */
66
+ readonly schema?: Schema.ConstraintCodec<Model, unknown> | undefined;
67
+ }
68
+ /** An Elm-style app: mount `component` like any Ilha component. */
69
+ export interface ModelApp<Model, Message, R = never, E = never> {
70
+ readonly component: Component;
71
+ readonly options: AppOptions<Model, Message, R, E>;
72
+ }
73
+ /**
74
+ * Latest-wins command: starting one interrupts the running command with the
75
+ * same key, so only the latest result dispatches. Different keys run
76
+ * independently. Keys are per app instance: two mounted instances never
77
+ * share them.
78
+ */
79
+ export declare const keyed: <Message, R>(key: string, cmd: Cmd<Message, R>) => Cmd<Message, R>;
80
+ /** Services an effect still requires. */
81
+ type EffectNeeds<T> = T extends Effect.Effect<unknown, unknown, infer R> ? R : never;
82
+ /** Services one command, or one command list, still requires. */
83
+ type CmdNeeds<T> = T extends readonly (infer Each)[] ? EffectNeeds<Each> : EffectNeeds<T>;
84
+ /** Services an `init` or `update` result still requires. */
85
+ type UpdateNeeds<T> = T extends {
86
+ cmd?: infer C;
87
+ } ? CmdNeeds<Exclude<C, undefined>> : never;
88
+ /** Services one subscription entry still requires. */
89
+ type SubNeeds<T> = T extends {
90
+ stream: (...args: never[]) => Stream.Stream<unknown, unknown, infer R>;
91
+ } ? R : never;
92
+ /** Every service the app's commands and subscriptions still require. */
93
+ type OptionsNeeds<O> = (O extends {
94
+ init: (...args: never[]) => infer Ret;
95
+ } ? UpdateNeeds<Ret> : never) | (O extends {
96
+ update: (...args: never[]) => infer Ret;
97
+ } ? UpdateNeeds<Ret> : never) | (O extends {
98
+ subscriptions?: infer S;
99
+ } ? S extends readonly (infer Each)[] ? SubNeeds<Each> : never : never);
100
+ /**
101
+ * Reject commands and subscriptions that need services outside the layer.
102
+ * The runtime always provides `AtomRegistry`; anything else must come from
103
+ * `layer`. Evaluated after `O` and `L` are fixed, so inference never sees
104
+ * the layer's services through this check.
105
+ */
106
+ type CheckServices<O, L extends Layer.Any> = OptionsNeeds<O> extends infer Needs ? [Needs] extends [Layer.Success<L> | AtomRegistry] ? unknown : {
107
+ "services missing from layer": Exclude<Needs, Layer.Success<L> | AtomRegistry>;
108
+ } : never;
109
+ /**
110
+ * What `defineApp` infers `Model` and `Message` from. Command and stream
111
+ * requirements stay permissive here so inference never forces the layer
112
+ * type early; `CheckServices` validates coverage after, and the layer
113
+ * itself is captured by `{ layer?: L }`.
114
+ */
115
+ type LooseOptions<Model, Message> = Omit<AppOptions<Model, Message, any, any>, "layer">;
116
+ /**
117
+ * Define an Elm-style app. One atom holds the whole model; `dispatch` runs
118
+ * `update` and rerenders; commands run concurrently inside the app runtime;
119
+ * each subscription restarts only when its own deps change and stops on
120
+ * unmount.
121
+ */
122
+ export declare const defineApp: <Model, Message, L extends Layer.Any = Layer.Layer<never, never>, O extends LooseOptions<Model, Message> = LooseOptions<Model, Message>>(options: LooseOptions<Model, Message> & O & {
123
+ layer?: L | undefined;
124
+ } & CheckServices<O, L>) => ModelApp<Model, Message, Layer.Success<L>, Layer.Error<L>>;
125
+ export {};
@@ -0,0 +1,6 @@
1
+ export type { AppOptions, Cmd, Dispatch, ModelApp, Subscription, UpdateResult, } from "./app";
2
+ export { defineApp, keyed, subscription } from "./app";
3
+ export type { DispatchRecord, ModelRecorder } from "./log";
4
+ export { attachModelRecorder } from "./log";
5
+ export type { FoldChildOptions, Step } from "./submodel";
6
+ export { combine, foldChild } from "./submodel";
package/dist/index.js ADDED
@@ -0,0 +1,198 @@
1
+ import { a as runCommand, i as reportCause, r as eachCmd, t as KeyedScope } from "./internal-kl_qCyzu.js";
2
+ import * as Cause from "effect/Cause";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Equal from "effect/Equal";
5
+ import * as Exit from "effect/Exit";
6
+ import * as Fiber from "effect/Fiber";
7
+ import * as FiberMap from "effect/FiberMap";
8
+ import * as Layer from "effect/Layer";
9
+ import * as Queue from "effect/Queue";
10
+ import * as Atom from "effect/reactivity/Atom";
11
+ import * as Scope from "effect/Scope";
12
+ import * as Stream from "effect/Stream";
13
+ import { atom, untrack, watch } from "ilha";
14
+
15
+ // src/log.ts
16
+ /** Attached recorders; `dispatch` builds a record only while non-empty. */
17
+ const recorders = /* @__PURE__ */ new Set();
18
+ /**
19
+ * Hand every `dispatch` of every model island to `recorder` until the
20
+ * returned detach runs. The devtools page script attaches one for you.
21
+ * Detached, `dispatch` pays one size check: no record, no allocation. A
22
+ * recorder that throws is logged and never breaks `dispatch`.
23
+ */
24
+ const attachModelRecorder = (recorder) => {
25
+ const entry = { recorder };
26
+ recorders.add(entry);
27
+ return () => {
28
+ recorders.delete(entry);
29
+ };
30
+ };
31
+ /** Whether any recorder is attached. Internal: `dispatch` checks it first. */
32
+ const isRecording = () => recorders.size > 0;
33
+ /** Deliver one dispatch to every recorder. Internal: `dispatch` calls it. */
34
+ const recordDispatch = (record) => {
35
+ for (const { recorder } of recorders) try {
36
+ recorder(record);
37
+ } catch (error) {
38
+ Effect.runSync(Effect.logError("@ilha/model recorder failed", error));
39
+ }
40
+ };
41
+
42
+ // src/app.ts
43
+ /**
44
+ * Name one subscription. Each entry infers its own `Deps` from its `deps`
45
+ * function, so `stream` receives the exact type its deps return. Annotate
46
+ * the model parameter; everything else infers.
47
+ */
48
+ const subscription = (sub) => sub;
49
+ /**
50
+ * Latest-wins command: starting one interrupts the running command with the
51
+ * same key, so only the latest result dispatches. Different keys run
52
+ * independently. Keys are per app instance: two mounted instances never
53
+ * share them.
54
+ */
55
+ const keyed = (key, cmd) => Effect.flatMap(Effect.serviceOption(KeyedScope), (scope) => scope._tag === "None" ? cmd : Effect.flatMap(FiberMap.run(scope.value, key, cmd), (fiber) => Fiber.join(fiber)));
56
+ const makeInstanceCells = () => {
57
+ const keyedScope = Effect.runSync(Scope.make());
58
+ return {
59
+ alive: true,
60
+ keyedMap: Effect.runSync(Effect.provideService(FiberMap.make(), Scope.Scope, keyedScope)),
61
+ keyedScope,
62
+ queue: Effect.runSync(Queue.unbounded()),
63
+ started: false
64
+ };
65
+ };
66
+ /**
67
+ * Log a defect and end the stream quietly. Interruption passes through so
68
+ * restarts and unmount stay silent.
69
+ */
70
+ const quietOnDefect = (cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.unwrap(Effect.as(Effect.logError(Cause.pretty(cause)), Stream.empty));
71
+ /**
72
+ * One subscription's restartable stream: the model feeds `deps`, equal deps
73
+ * keep the stream alive, changed deps restart it. A defect in the stream for
74
+ * the current deps is logged and silences only that stream, so the next
75
+ * deps change starts a fresh one. A defect in `deps` itself is logged and
76
+ * ends the subscription.
77
+ */
78
+ const watchOne = (stateAtom, sub) => Atom.toStream(stateAtom).pipe(Stream.map((model) => sub.deps(model)), Stream.changesWith(Equal.equals), Stream.switchMap((deps) => Stream.suspend(() => sub.stream(deps)).pipe(Stream.catchCause(quietOnDefect))), Stream.catchCause(quietOnDefect));
79
+ /**
80
+ * Merge every subscription into one stream, built once per app instance.
81
+ * Each entry restarts only on its own deps; entries never disturb each
82
+ * other.
83
+ */
84
+ const mergeSubscriptions = (stateAtom, subscriptions) => Stream.mergeAll(subscriptions.map((sub) => watchOne(stateAtom, sub)), { concurrency: "unbounded" });
85
+ /**
86
+ * Define an Elm-style app. One atom holds the whole model; `dispatch` runs
87
+ * `update` and rerenders; commands run concurrently inside the app runtime;
88
+ * each subscription restarts only when its own deps change and stops on
89
+ * unmount.
90
+ */
91
+ const defineApp = (options) => {
92
+ const { init, update, view } = options;
93
+ const subscriptions = options.subscriptions ?? [];
94
+ const provided = options.layer ?? Layer.empty;
95
+ const runtime = Atom.runtime(provided);
96
+ const component = () => {
97
+ const initResult = atom.lazy(() => init(), { snapshot: false });
98
+ const state = atom.lazy(() => untrack(() => initResult()).model, { schema: options.schema });
99
+ const cells = atom.lazy(() => makeInstanceCells(), { snapshot: false });
100
+ const merged = atom.lazy(() => ({ stream: mergeSubscriptions(state.atom, subscriptions) }), { snapshot: false });
101
+ const isAlive = () => {
102
+ try {
103
+ return untrack(() => cells()).alive;
104
+ } catch {
105
+ return false;
106
+ }
107
+ };
108
+ const dispatch = (message) => {
109
+ if (!isAlive()) return;
110
+ const before = untrack(() => state());
111
+ const result = update(before, message);
112
+ state.set(result.model);
113
+ let started = 0;
114
+ if (result.cmd !== void 0) {
115
+ const { queue } = untrack(() => cells());
116
+ const cmds = eachCmd(result.cmd);
117
+ for (const cmd of cmds) Queue.offerUnsafe(queue, cmd);
118
+ started = cmds.length;
119
+ }
120
+ if (isRecording()) recordDispatch({
121
+ after: result.model,
122
+ before,
123
+ commands: started,
124
+ instance: state.atom,
125
+ message
126
+ });
127
+ };
128
+ const { keyedMap } = untrack(() => cells());
129
+ const runOne = (cmd) => runCommand(cmd, (message) => Effect.sync(() => dispatch(message)), keyedMap);
130
+ const runner = atom(Atom.fn((queue, get) => Effect.flatMap(get.result(runtime), (services) => Effect.provideContext(Effect.forever(Effect.flatMap(Queue.take(queue), (cmd) => Effect.forkChild(runOne(cmd)))), services))));
131
+ const runnerFailure = atom(runner.atom.pipe(Atom.map((result) => result._tag === "Failure" && !Cause.hasInterruptsOnly(result.cause) ? Cause.pretty(result.cause) : "")));
132
+ runner();
133
+ watch(runnerFailure, (failure) => {
134
+ if (failure !== "") Effect.runSync(Effect.logError(failure));
135
+ });
136
+ watch.once(({ ssr }) => {
137
+ const helpers = untrack(() => cells());
138
+ if (!ssr && !helpers.started) {
139
+ helpers.started = true;
140
+ const begin = untrack(() => initResult()).cmd;
141
+ if (begin !== void 0) for (const cmd of eachCmd(begin)) Queue.offerUnsafe(helpers.queue, cmd);
142
+ if (subscriptions.length > 0) Queue.offerUnsafe(helpers.queue, Stream.runForEach(untrack(() => merged()).stream, (message) => Effect.catchCause(Effect.sync(() => dispatch(message)), reportCause)));
143
+ runner.set(helpers.queue);
144
+ }
145
+ return () => {
146
+ helpers.alive = false;
147
+ Effect.runFork(Scope.close(helpers.keyedScope, Exit.void));
148
+ };
149
+ });
150
+ return view(state(), dispatch);
151
+ };
152
+ Object.defineProperty(component, "name", { value: options.name ?? "ModelApp" });
153
+ return {
154
+ component,
155
+ options
156
+ };
157
+ };
158
+
159
+ // src/submodel.ts
160
+ /**
161
+ * Run steps in order, threading each model into the next. The steps run in
162
+ * order, but the commands from all steps run concurrently, like any command
163
+ * list.
164
+ */
165
+ const combine = (model, steps) => {
166
+ let current = model;
167
+ const cmds = [];
168
+ for (const step of steps) {
169
+ const result = step(current);
170
+ current = result.model;
171
+ if (result.cmd !== void 0) cmds.push(...eachCmd(result.cmd));
172
+ }
173
+ if (cmds.length === 0) return { model: current };
174
+ return {
175
+ cmd: cmds.length === 1 ? cmds[0] : cmds,
176
+ model: current
177
+ };
178
+ };
179
+ /**
180
+ * Embed a child update in a parent. Runs the child, writes its model back,
181
+ * and lifts its commands so results arrive wrapped for the parent.
182
+ */
183
+ const foldChild = (options) => {
184
+ const { read, toParentMessage, update, write } = options;
185
+ return (model, message) => {
186
+ const child = read(model);
187
+ if (child === void 0) return { model };
188
+ const result = update(child, message);
189
+ const next = write(model, result.model);
190
+ if (result.cmd === void 0) return { model: next };
191
+ return {
192
+ cmd: eachCmd(result.cmd).map((cmd) => cmd.pipe(Effect.map((out) => out === void 0 ? void 0 : toParentMessage(out)))),
193
+ model: next
194
+ };
195
+ };
196
+ };
197
+
198
+ export { attachModelRecorder, combine, defineApp, foldChild, keyed, subscription };
@@ -0,0 +1,45 @@
1
+ import * as Cause from "effect/Cause";
2
+ import * as Effect from "effect/Effect";
3
+ import * as Fiber from "effect/Fiber";
4
+ import * as Context from "effect/Context";
5
+ import * as Ref from "effect/Ref";
6
+
7
+ // src/internal.ts
8
+ /**
9
+ * Split one or many commands. Internal: shared by the runtime, `submodel`,
10
+ * and the test helpers, not part of the package surface. `Effect.isEffect`
11
+ * narrows the union where `Array.isArray` cannot, so no assertion is needed.
12
+ */
13
+ const eachCmd = (cmd) => Effect.isEffect(cmd) ? [cmd] : cmd;
14
+ /**
15
+ * Per-instance keyed-command scope. The runner provides it around every
16
+ * command; `keyed` reads it back without adding a service requirement.
17
+ */
18
+ const KeyedScope = Context.Service("ilha/model/KeyedScope");
19
+ /**
20
+ * Report an unexpected cause through the Effect logger. Interruption
21
+ * (unmount, keyed supersede, subscription restart) is silent; anything else
22
+ * is a defect worth logging.
23
+ */
24
+ const reportCause = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logError(Cause.pretty(cause));
25
+ /**
26
+ * Run one command, delivering its message when it resolves to one. Shared
27
+ * by the app runtime and the test helpers: a `void` result delivers
28
+ * nothing, defects are logged, and interruption stays silent.
29
+ */
30
+ const runCommand = (cmd, deliver, keyedMap) => Effect.provideService(Effect.catchCause(cmd.pipe(Effect.flatMap((out) => out === void 0 ? Effect.void : deliver(out))), reportCause), KeyedScope, keyedMap);
31
+ /**
32
+ * Run commands concurrently like the app runtime, collecting delivered
33
+ * messages in completion order. Commands fork in array order and each
34
+ * `keyed` registration is synchronous, so same-key commands supersede
35
+ * deterministically with the latest winning.
36
+ */
37
+ const drainCommands = (cmds, keyedMap) => Effect.gen(function* drain() {
38
+ const outbox = yield* Ref.make([]);
39
+ const fibers = [];
40
+ for (const cmd of cmds) fibers.push(yield* Effect.forkChild(runCommand(cmd, (message) => Ref.update(outbox, (seen) => [...seen, message]), keyedMap)));
41
+ for (const fiber of fibers) yield* Fiber.join(fiber);
42
+ return yield* Ref.get(outbox);
43
+ });
44
+
45
+ export { runCommand as a, reportCause as i, drainCommands as n, eachCmd as r, KeyedScope as t };
@@ -0,0 +1,36 @@
1
+ import * as Cause from "effect/Cause";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import type * as FiberMap from "effect/FiberMap";
5
+ import type { AtomRegistry } from "effect/reactivity/AtomRegistry";
6
+ import type { Cmd } from "./app";
7
+ /**
8
+ * Split one or many commands. Internal: shared by the runtime, `submodel`,
9
+ * and the test helpers, not part of the package surface. `Effect.isEffect`
10
+ * narrows the union where `Array.isArray` cannot, so no assertion is needed.
11
+ */
12
+ export declare const eachCmd: <Message, R>(cmd: Cmd<Message, R> | readonly Cmd<Message, R>[]) => readonly Cmd<Message, R>[];
13
+ /**
14
+ * Per-instance keyed-command scope. The runner provides it around every
15
+ * command; `keyed` reads it back without adding a service requirement.
16
+ */
17
+ export declare const KeyedScope: Context.Service<FiberMap.FiberMap<string, unknown, unknown>, FiberMap.FiberMap<string, unknown, unknown>>;
18
+ /**
19
+ * Report an unexpected cause through the Effect logger. Interruption
20
+ * (unmount, keyed supersede, subscription restart) is silent; anything else
21
+ * is a defect worth logging.
22
+ */
23
+ export declare const reportCause: (cause: Cause.Cause<never>) => Effect.Effect<void>;
24
+ /**
25
+ * Run one command, delivering its message when it resolves to one. Shared
26
+ * by the app runtime and the test helpers: a `void` result delivers
27
+ * nothing, defects are logged, and interruption stays silent.
28
+ */
29
+ export declare const runCommand: <Message, R>(cmd: Cmd<Message, R>, deliver: (message: Message) => Effect.Effect<void>, keyedMap: FiberMap.FiberMap<string, unknown, unknown>) => Effect.Effect<void, never, R | AtomRegistry>;
30
+ /**
31
+ * Run commands concurrently like the app runtime, collecting delivered
32
+ * messages in completion order. Commands fork in array order and each
33
+ * `keyed` registration is synchronous, so same-key commands supersede
34
+ * deterministically with the latest winning.
35
+ */
36
+ export declare const drainCommands: <Message, R>(cmds: readonly Cmd<Message, R>[], keyedMap: FiberMap.FiberMap<string, unknown, unknown>) => Effect.Effect<readonly Message[], never, R | AtomRegistry>;
package/dist/log.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * One dispatch as an attached recorder sees it: raw values, nothing copied
3
+ * or summarized. Summarizing, diffing, and buffering belong to the
4
+ * recorder, so apps never ship that code.
5
+ */
6
+ export interface DispatchRecord {
7
+ /**
8
+ * The island instance's model atom. Join it against `atomsOf(id)` from
9
+ * `ilha/debug` to find which island dispatched.
10
+ */
11
+ readonly instance: object;
12
+ /** The dispatched message. */
13
+ readonly message: unknown;
14
+ /** The model `update` received. */
15
+ readonly before: unknown;
16
+ /** The model `update` returned. */
17
+ readonly after: unknown;
18
+ /** How many commands the message started. */
19
+ readonly commands: number;
20
+ }
21
+ /** Receives every dispatch while attached. */
22
+ export type ModelRecorder = (record: DispatchRecord) => void;
23
+ /**
24
+ * Hand every `dispatch` of every model island to `recorder` until the
25
+ * returned detach runs. The devtools page script attaches one for you.
26
+ * Detached, `dispatch` pays one size check: no record, no allocation. A
27
+ * recorder that throws is logged and never breaks `dispatch`.
28
+ */
29
+ export declare const attachModelRecorder: (recorder: ModelRecorder) => (() => void);
30
+ /** Whether any recorder is attached. Internal: `dispatch` checks it first. */
31
+ export declare const isRecording: () => boolean;
32
+ /** Deliver one dispatch to every recorder. Internal: `dispatch` calls it. */
33
+ export declare const recordDispatch: (record: DispatchRecord) => void;
@@ -0,0 +1,28 @@
1
+ import type { UpdateResult } from "./app";
2
+ /**
3
+ * One transform over a model, used with {@link combine}. A child fold
4
+ * returns a step; inline lambdas receive the model the previous step wrote.
5
+ */
6
+ export type Step<Model, Message, R = never> = (model: Model) => UpdateResult<Model, Message, R>;
7
+ /**
8
+ * Run steps in order, threading each model into the next. The steps run in
9
+ * order, but the commands from all steps run concurrently, like any command
10
+ * list.
11
+ */
12
+ export declare const combine: <Model, Message, R = never>(model: Model, steps: readonly Step<Model, Message, R>[]) => UpdateResult<Model, Message, R>;
13
+ /** Options for {@link foldChild}. */
14
+ export interface FoldChildOptions<ParentModel, ParentMessage, ChildModel, ChildMessage, R = never> {
15
+ /** The child's own update. The parent never touches the child model. */
16
+ readonly update: (model: ChildModel, message: ChildMessage) => UpdateResult<ChildModel, ChildMessage, R>;
17
+ /** Read the child slice. `undefined` leaves the parent unchanged. */
18
+ readonly read: (model: ParentModel) => ChildModel | undefined;
19
+ /** Write the child slice back. */
20
+ readonly write: (model: ParentModel, child: ChildModel) => ParentModel;
21
+ /** Lift child messages, usually into a `Got*` wrapper. */
22
+ readonly toParentMessage: (message: ChildMessage) => ParentMessage;
23
+ }
24
+ /**
25
+ * Embed a child update in a parent. Runs the child, writes its model back,
26
+ * and lifts its commands so results arrive wrapped for the parent.
27
+ */
28
+ export declare const foldChild: <ParentModel, ParentMessage, ChildModel, ChildMessage, R = never>(options: FoldChildOptions<ParentModel, ParentMessage, ChildModel, ChildMessage, R>) => ((model: ParentModel, message: ChildMessage) => UpdateResult<ParentModel, ParentMessage, R>);
package/dist/test.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as Layer from "effect/Layer";
3
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
+ import type { Cmd, ModelApp, UpdateResult } from "./app";
5
+ /**
6
+ * Message a command resolves to, excluding `void` results that deliver
7
+ * nothing.
8
+ */
9
+ type CommandMessage<T> = T extends Effect.Effect<infer M, never, unknown> ? Exclude<M, void> : never;
10
+ /**
11
+ * Services a command still requires, excluding the `AtomRegistry` the
12
+ * helpers provide themselves.
13
+ */
14
+ type CommandServices<T> = T extends Effect.Effect<unknown, never, infer R> ? Exclude<R, AtomRegistry.AtomRegistry> : never;
15
+ /**
16
+ * Run one command without rendering and collect the message it resolves
17
+ * to. Commands run with the app runtime's semantics: `keyed` supersedes
18
+ * per key with the latest winning, defects are logged and dropped, and
19
+ * `void` results produce no message. Provide services with
20
+ * `Effect.provide` and time with `TestClock` from `effect/testing`.
21
+ */
22
+ export declare function runCommands<Message, R>(input: Cmd<Message, R>): Effect.Effect<readonly Exclude<Message, void>[], never, Exclude<R, AtomRegistry.AtomRegistry>>;
23
+ /**
24
+ * Run several commands concurrently, collecting their messages in
25
+ * completion order.
26
+ */
27
+ export declare function runCommands<const Cmds extends readonly Cmd<unknown, unknown>[]>(input: Cmds): Effect.Effect<readonly CommandMessage<Cmds[number]>[], never, CommandServices<Cmds[number]>>;
28
+ /** Run the command of an update result, collecting its messages. */
29
+ export declare function runCommands<Model, Message, R>(input: UpdateResult<Model, Message, R>): Effect.Effect<readonly Exclude<Message, void>[], never, Exclude<R, AtomRegistry.AtomRegistry>>;
30
+ /** Result of {@link simulate}: the final model and every message seen. */
31
+ export interface SimulateResult<Model, Message> {
32
+ /** Model after init and every message ran to quiet. */
33
+ readonly model: Model;
34
+ /** Every message `update` saw, in the order it saw them. */
35
+ readonly messages: readonly Message[];
36
+ }
37
+ /** Options for {@link simulate}. */
38
+ export interface SimulateOptions<R, E2 = never> {
39
+ /**
40
+ * Replace the app's layer for this run, for example with test doubles.
41
+ * Must provide the same services the app needs. Defaults to the app's
42
+ * own layer.
43
+ */
44
+ readonly layer?: Layer.Layer<R, E2> | undefined;
45
+ }
46
+ /**
47
+ * Run an app's loop without rendering: init and its command first, then
48
+ * each input message through `update`, running every resulting command and
49
+ * feeding produced messages back through `update` until quiet. Takes the
50
+ * `ModelApp` from `defineApp` so the layer travels with `init` and
51
+ * `update`. Subscriptions never run here; test them through `update` with
52
+ * the messages their streams would emit. Commands that sleep run on the
53
+ * ambient clock, so `TestClock` from `effect/testing` controls them.
54
+ */
55
+ export declare const simulate: <Model, Message, R, E, E2 = never>(app: ModelApp<Model, Message, R, E>, inputs: readonly NoInfer<Message>[], options?: SimulateOptions<NoInfer<R>, E2> | undefined) => Effect.Effect<SimulateResult<Model, Message>, E | E2>;
56
+ export {};
package/dist/test.js ADDED
@@ -0,0 +1,54 @@
1
+ import { n as drainCommands, r as eachCmd } from "./internal-kl_qCyzu.js";
2
+ import * as Effect from "effect/Effect";
3
+ import * as FiberMap from "effect/FiberMap";
4
+ import * as Layer from "effect/Layer";
5
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
+
7
+ // src/test.ts
8
+ /**
9
+ * Normalize the `runCommands` input to a command list. Update results
10
+ * without a command run nothing.
11
+ */
12
+ const toCmds = (input) => {
13
+ if (Effect.isEffect(input)) return [input];
14
+ if ("model" in input) return input.cmd === void 0 ? [] : eachCmd(input.cmd);
15
+ return input;
16
+ };
17
+ function runCommands(input) {
18
+ return Effect.scoped(Effect.flatMap(FiberMap.make(), (keyedMap) => Effect.provide(drainCommands(toCmds(input), keyedMap), AtomRegistry.layer)));
19
+ }
20
+ /**
21
+ * Run an app's loop without rendering: init and its command first, then
22
+ * each input message through `update`, running every resulting command and
23
+ * feeding produced messages back through `update` until quiet. Takes the
24
+ * `ModelApp` from `defineApp` so the layer travels with `init` and
25
+ * `update`. Subscriptions never run here; test them through `update` with
26
+ * the messages their streams would emit. Commands that sleep run on the
27
+ * ambient clock, so `TestClock` from `effect/testing` controls them.
28
+ */
29
+ const simulate = (app, inputs, options) => Effect.scoped(Effect.flatMap(FiberMap.make(), (keyedMap) => {
30
+ const provided = options?.layer ?? app.options.layer ?? Layer.empty;
31
+ const drain = (cmd) => cmd === void 0 ? Effect.succeed([]) : drainCommands(eachCmd(cmd), keyedMap);
32
+ return Effect.provide(Effect.gen(function* runLoop() {
33
+ const begun = app.options.init();
34
+ const first = yield* drain(begun.cmd);
35
+ let { model } = begun;
36
+ const queue = [...first, ...inputs];
37
+ const seen = [];
38
+ while (true) {
39
+ const message = queue.shift();
40
+ if (message === void 0) break;
41
+ seen.push(message);
42
+ const { cmd: command, model: next } = app.options.update(model, message);
43
+ model = next;
44
+ const produced = yield* drain(command);
45
+ queue.push(...produced);
46
+ }
47
+ return {
48
+ messages: seen,
49
+ model
50
+ };
51
+ }), Layer.merge(provided, AtomRegistry.layer));
52
+ }));
53
+
54
+ export { runCommands, simulate };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@ilha/model",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Elm-style Model, update, commands, and subscriptions for Ilha islands",
5
+ "keywords": [
6
+ "effect",
7
+ "elm-architecture",
8
+ "frontend",
9
+ "hydration",
10
+ "ilha",
11
+ "island-architecture",
12
+ "islands",
13
+ "ssr"
14
+ ],
15
+ "homepage": "https://github.com/ilhajs/ilha/tree/main/packages/model#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/ilhajs/ilha/issues"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Ryuz <ryuzer@proton.me>",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/ilhajs/ilha.git"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "main": "./dist/index.js",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ },
38
+ "./test": {
39
+ "types": "./dist/test.d.ts",
40
+ "import": "./dist/test.js"
41
+ }
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "build": "tsdown && tsc -p tsconfig.build.json",
48
+ "cleanup": "rimraf dist node_modules",
49
+ "test": "bun test",
50
+ "typecheck": "tsc -p tsconfig.json --noEmit"
51
+ },
52
+ "devDependencies": {
53
+ "@types/bun": "^1.4.4",
54
+ "effect": "^4.1.0",
55
+ "ilha": "^0.16.3"
56
+ },
57
+ "peerDependencies": {
58
+ "effect": "^4.1.0",
59
+ "ilha": ">=0.16.3"
60
+ }
61
+ }