@ilha/model 0.1.1 → 0.2.0

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/dist/test.js CHANGED
@@ -1,54 +1,55 @@
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";
1
+ import { n as initDollar, o as updateDollar, r as isStepValue, t as createStep } from "./internal-DsyiAF5H.js";
2
+ import * as Schema from "effect/Schema";
6
3
 
7
4
  // 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
- }));
5
+ const Story = { make(component, ...args) {
6
+ const { definition } = component;
7
+ const impl = component.impl;
8
+ const decoded = Schema.decodeSync(definition.props)(args[0] ?? {});
9
+ let pending = [];
10
+ const emitted = [];
11
+ const commitInit = () => {
12
+ const out = impl.init(initDollar(decoded), decoded);
13
+ const step = isStepValue(out) ? out : createStep(out);
14
+ pending = step.commands.map(({ args: commandArgs, name }) => ({
15
+ args: commandArgs,
16
+ name
17
+ }));
18
+ for (const event of step.events) emitted.push(event);
19
+ return step.model;
20
+ };
21
+ let model = commitInit();
22
+ const send = (message) => {
23
+ const { _tag: tag } = message;
24
+ const handler = impl.update[tag];
25
+ if (handler === void 0) throw new Error(`${definition.name}: no update for "${tag}"`);
26
+ const out = handler(updateDollar(model, decoded), message);
27
+ const step = isStepValue(out) ? out : createStep(out);
28
+ const { model: next } = step;
29
+ model = next;
30
+ for (const { args: commandArgs, name } of step.commands) pending.push({
31
+ args: commandArgs,
32
+ name
33
+ });
34
+ for (const event of step.events) emitted.push(event);
35
+ };
36
+ return {
37
+ get commands() {
38
+ return [...pending];
39
+ },
40
+ get emitted() {
41
+ return [...emitted];
42
+ },
43
+ get model() {
44
+ return model;
45
+ },
46
+ resolve(command, message) {
47
+ const at = pending.findIndex((issue) => issue.name === command.name);
48
+ if (at !== -1) pending.splice(at, 1);
49
+ if (message !== void 0) send(message);
50
+ },
51
+ send
52
+ };
53
+ } };
53
54
 
54
- export { runCommands, simulate };
55
+ export { Story };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ilha/model",
3
- "version": "0.1.1",
4
- "description": "Elm-style Model, update, commands, and subscriptions for Ilha islands",
3
+ "version": "0.2.0",
4
+ "description": "Elm-style model components for Ilha islands: one atom per instance, commands, and subscriptions",
5
5
  "keywords": [
6
6
  "effect",
7
7
  "elm-architecture",
@@ -44,18 +44,18 @@
44
44
  "access": "public"
45
45
  },
46
46
  "scripts": {
47
- "build": "tsdown && tsc -p tsconfig.build.json",
47
+ "build": "tsdown",
48
48
  "cleanup": "rimraf dist node_modules",
49
49
  "test": "bun test",
50
50
  "typecheck": "tsc -p tsconfig.json --noEmit"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/bun": "^1.4.4",
54
- "effect": "^4.1.0",
55
- "ilha": "^0.16.3"
54
+ "effect": "^4.1.4",
55
+ "ilha": "^0.17.0"
56
56
  },
57
57
  "peerDependencies": {
58
- "effect": "^4.1.0",
58
+ "effect": "^4.1.4",
59
59
  "ilha": ">=0.16.3"
60
60
  }
61
61
  }
package/dist/app.d.ts DELETED
@@ -1,125 +0,0 @@
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 {};
@@ -1,45 +0,0 @@
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 };
@@ -1,36 +0,0 @@
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 DELETED
@@ -1,33 +0,0 @@
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;
@@ -1,28 +0,0 @@
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>);