nanoeffects 0.22.0 → 0.23.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.
Files changed (42) hide show
  1. package/dist/actions.d.ts +2 -2
  2. package/dist/actions.js +1 -1
  3. package/dist/{bus-duCCrqrr.js → bus-hHp-T7JV.js} +1 -1
  4. package/dist/context-UcmrAIhP.js +1 -0
  5. package/dist/{notrace/delay-BosJKFjg.js → delay-mxZkTg17.js} +1 -1
  6. package/dist/dev.d.ts +1 -1
  7. package/dist/effects.d.ts +4 -4
  8. package/dist/effects.js +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/{module-1sUEXIcD.d.ts → module-D1VVKbE0.d.ts} +1 -1
  11. package/dist/notrace/actions.d.ts +1 -1
  12. package/dist/notrace/actions.js +1 -1
  13. package/dist/notrace/{bus-BkUtjPHp.js → bus-BdyvumpX.js} +1 -1
  14. package/dist/notrace/context-_HWcdjZf.js +1 -0
  15. package/dist/{delay-BnBdGPh7.js → notrace/delay-CqKplsaY.js} +1 -1
  16. package/dist/notrace/effects.d.ts +4 -4
  17. package/dist/notrace/effects.js +1 -1
  18. package/dist/notrace/index.js +1 -1
  19. package/dist/notrace/{plugin-ByDuI8Vq.d.ts → plugin-BEvYzo8Q.d.ts} +32 -26
  20. package/dist/notrace/policies.js +1 -1
  21. package/dist/oop.js +1 -1
  22. package/dist/{plugin-BiGv84Xu.d.ts → plugin-BZK83Z3N.d.ts} +32 -26
  23. package/dist/policies.js +1 -1
  24. package/dist/react.js +1 -1
  25. package/dist/scope.d.ts +1 -1
  26. package/dist/scope.js +1 -1
  27. package/dist/signal.js +1 -1
  28. package/dist/trace.js +1 -1
  29. package/dist/{types-DC-aLJit.d.ts → types-CBoV9m7W.d.ts} +1 -1
  30. package/dist/{with-policy-CW50Edgk.js → with-policy-D-SQRkPh.js} +1 -1
  31. package/docs/README.md +1 -0
  32. package/docs/actions.md +1 -1
  33. package/docs/chat-example.md +33 -27
  34. package/docs/effects.md +28 -4
  35. package/docs/migrating-from-rxjs.md +2 -2
  36. package/docs/server.md +202 -0
  37. package/docs/starter.md +1 -1
  38. package/llms-full.txt +271 -35
  39. package/llms.txt +2 -1
  40. package/package.json +7 -4
  41. package/dist/context-CJGW6OWj.js +0 -1
  42. package/dist/notrace/context-yYU3_9lq.js +0 -1
package/llms-full.txt CHANGED
@@ -603,7 +603,7 @@ npm create nanoeffects@latest my-app -- --template domains-ts
603
603
  | `src/domains/checkout/` | Placing an order: `checkout.ts` (a job), `checkout-handlers.ts` (`leading` and `retry`), `checkout-store.ts` (state written from the job's outcomes), `checkout-module.ts`. |
604
604
  | `src/ui/` | The components. None of them calls the fake server in `src/api.ts`. |
605
605
 
606
- For a bigger example with the same layout, a chat with four domains and mocks, see [Build a chat with domains, modules and a small server](chat-example.md).
606
+ For a bigger example, a chat in which parts react to each other, see [Build a chat with entities, features, modules and a small server](chat-example.md). It has more layers than `domains-ts`: when domains must react to each other, it keeps them from importing each other by splitting them into entities and features.
607
607
 
608
608
  The commands, jobs and modules themselves are explained in [Actions, commands, jobs and modules](actions.md). The template keeps found products in a Context provider with one `useEventState`, and the order state in a store of its own: `useEventState` is [not a store](react.md#show-the-last-value-of-an-event-as-state).
609
609
 
@@ -1745,7 +1745,8 @@ bus.on("load", async (id, { race, all, delay }) => {
1745
1745
  // race — same as race(ctx, …)
1746
1746
  const result = await race({
1747
1747
  data: ({ signal }) => fetchData(id, { signal }),
1748
- timeout: () => delay(5000), // delay — same as delay(ctx, 5000)
1748
+ // a starter gets its own child with the same bound effects, so delay(5000) stops with the race
1749
+ timeout: ({ delay }) => delay(5000),
1749
1750
  });
1750
1751
  if ("timeout" in result) throw new Error("timed out");
1751
1752
 
@@ -1847,8 +1848,8 @@ bus.on("login", async (user, ctx) => {
1847
1848
  console.log(stopped);
1848
1849
 
1849
1850
  // wait for a matching event, but not longer than 5 s
1850
- const id = await timeout(ctx, 5000, ({ signal }) =>
1851
- take(ctx, "saved", { signal, predicate: (savedId) => savedId === draft.id }),
1851
+ const id = await timeout(ctx, 5000, (child) =>
1852
+ take(child, "saved", { predicate: (savedId) => savedId === draft.id }),
1852
1853
  );
1853
1854
  });
1854
1855
  ```
@@ -1856,7 +1857,7 @@ bus.on("login", async (user, ctx) => {
1856
1857
  - Sees only events emitted after the call, takes one, and unsubscribes.
1857
1858
  - With an action creator the result has the payload type of the creator. A creator made without a payload type (`createAction("saved")`) takes it from the event map of the bus.
1858
1859
  - `options.predicate` skips payloads it rejects. In TypeScript, a type guard (`(payload): payload is Admin`) narrows the type of the result.
1859
- - `options.signal` stops the wait (how a `race` or `timeout` starter cancels it).
1860
+ - `options.signal` stops the wait. In a starter of `race`, `all` or `timeout` pass `child` as the first argument instead: it already carries the signal.
1860
1861
  - On abort of the task or of `options.signal`, unsubscribes and rejects with the abort reason.
1861
1862
 
1862
1863
  ## Run several starters together
@@ -1885,6 +1886,29 @@ bus.on("open", async (id, ctx) => {
1885
1886
 
1886
1887
  `race(ctx, effects)` settles with the first starter that finishes and cancels the others.
1887
1888
 
1889
+ ```js
1890
+ import { createBus } from "nanoeffects";
1891
+ import { delay, race, take } from "nanoeffects/effects";
1892
+
1893
+ const bus = createBus();
1894
+
1895
+ bus.on("save", async (draft, ctx) => {
1896
+ // race — the first starter to finish wins, the other is cancelled
1897
+ const result = await race(ctx, {
1898
+ waited: (child) => delay(child, 1000),
1899
+ cancelled: (child) => take(child, "cancel"),
1900
+ });
1901
+
1902
+ if ("waited" in result) {
1903
+ ctx.emit("saved", draft);
1904
+ }
1905
+ });
1906
+ ```
1907
+
1908
+ **A starter gets the context of its own child task.** Pass `child` as the first argument to any effect, as a handler passes `ctx`: when the race ends, `child` is aborted and stops exactly this effect. The outer `ctx` is only for `race` itself. Your own API takes the signal in its options: `({ signal }) => fetchUser(id, { signal })`. The same holds for `all`, `allSettled` and `timeout`.
1909
+
1910
+ If `ctx` is `{}` or a bare `{ signal }` (outside a task), `child` has only `signal` and `abort`, so it fits `delay` and `poll` but not `take`, which needs a bus.
1911
+
1888
1912
  ## Pass `ctx` outside a task
1889
1913
 
1890
1914
  Effects that wait inside a body take `ctx` first: `delay`, `all`, `allSettled`, `race`, `cancellable`, `onAbort`, `take`, and the `ctx` forms of `retry` / `timeout` / `poll`. Outside a task, pass `{}` or any object with a `signal`.
@@ -1942,7 +1966,7 @@ If you only need `on` / `emit` or policies, stay in the [Guide](guide.md) until
1942
1966
 
1943
1967
  Recipe without a UI framework: [`examples/modules.ts`](../examples/modules.ts).
1944
1968
 
1945
- A chat with four domains, jobs under policies and effects, and a stream tied to a module: [Build a chat with domains, modules and a small server](chat-example.md).
1969
+ A chat with two entities and three features, jobs under policies and effects, and a stream tied to a module: [Build a chat with entities, features, modules and a small server](chat-example.md).
1946
1970
 
1947
1971
  A whole project with two domains, a job and React as a thin layer: `npm create nanoeffects@latest my-app -- --template domains-ts` (see [Start a project from a template](starter.md#start-with-domains)).
1948
1972
 
@@ -3070,6 +3094,212 @@ Send it from the handler with `ctx.emit(userLoaded(user))`. Do not replace the c
3070
3094
 
3071
3095
  A whole small app, with a search, a filter, pages and a detail panel, is in the [Rick and Morty example](../examples/rickandmorty).
3072
3096
 
3097
+ ---
3098
+ Source: docs/server.md
3099
+
3100
+ # Stop work on a server when the client leaves
3101
+
3102
+ Read this page if you run a Node server (the examples use [Fastify](https://fastify.dev)) and want the work for a request, a socket or a queued job to stop when nobody needs it. It shows one pattern in three places: a request, a WebSocket and a worker.
3103
+
3104
+ You need Node 18 or newer, `fastify` and `nanoeffects`. `api` below is your own client for another service: replace it with your requests.
3105
+
3106
+ ## Why a server needs this
3107
+
3108
+ A browser tab that closes stops its own requests. A server does not: if a client leaves, the requests that the server made for it keep running, and so do their retries. On a busy server that is wasted work and a slower service for everyone else.
3109
+
3110
+ The fix is one `AbortController` for each unit of work that the client owns, and one rule: **when the client goes, abort the controller.** `signalPlugin` lets `bus.emit` take that signal, so `timeout`, `retry` and the request itself stop.
3111
+
3112
+ | Unit of work | Created when | Aborted when |
3113
+ | ------------ | ------------ | ------------ |
3114
+ | An HTTP request | the route starts | the connection closes before the answer |
3115
+ | A WebSocket | the socket connects | the socket closes |
3116
+ | A queued job | the job is accepted | the server shuts down |
3117
+
3118
+ ## Make the bus and the command
3119
+
3120
+ The bus and the command live in files that know nothing about HTTP, so the same command can run in a route, a test or a worker.
3121
+
3122
+ ```js
3123
+ // bus.js
3124
+ import { createBus } from "nanoeffects";
3125
+ import { signalPlugin } from "nanoeffects/signal";
3126
+
3127
+ // createBus — the bus the server shares
3128
+ // signalPlugin — lets emit take { signal }, so a closed connection can abort the work
3129
+ export const bus = createBus().use(signalPlugin());
3130
+ ```
3131
+
3132
+ The command loads a user. It tries the request up to three times, and gives up on each try after five seconds. `ctx.signal` is the signal of the task: it aborts when the controller of the request aborts.
3133
+
3134
+ ```js
3135
+ // user.js
3136
+ import { createCommand } from "nanoeffects/actions";
3137
+ import { retry, timeout } from "nanoeffects/effects";
3138
+
3139
+ // createCommand — a command with a handler: emit returns what the handler returns
3140
+ export const getUser = createCommand("user/get", async (id, ctx) => {
3141
+ // one try: the request, with the signal of timeout so it can stop it
3142
+ const load = ({ signal }) => api.getUser(id, { signal });
3143
+ // timeout — fail the try after 5 s
3144
+ const attempt = () => timeout(ctx, 5000, load);
3145
+ // retry — up to 3 tries, 500 ms apart
3146
+ return retry(ctx, attempt, { times: 3, delay: 500 });
3147
+ });
3148
+ ```
3149
+
3150
+ ## Stop the work of a request
3151
+
3152
+ <!-- docs-check: continue -->
3153
+
3154
+ Make a controller when the route starts. Listen to `close` of the **response** (`reply.raw`): it ends when the connection ends. `request.raw` also emits `close`, but it does so when the request body has been read, not when the client leaves, so it is the wrong event here.
3155
+
3156
+ ```js
3157
+ // server.js
3158
+ import Fastify from "fastify";
3159
+ import { bus } from "./bus";
3160
+ import { getUser } from "./user";
3161
+
3162
+ export const app = Fastify();
3163
+
3164
+ // the controllers of the requests that are still being answered, for the shutdown below
3165
+ export const inFlight = new Set();
3166
+
3167
+ app.get("/users/:id", async (request, reply) => {
3168
+ const controller = new AbortController();
3169
+ inFlight.add(controller);
3170
+
3171
+ // close on the response — the connection ended; if the answer was not finished, the client left
3172
+ reply.raw.on("close", () => {
3173
+ inFlight.delete(controller);
3174
+ if (!reply.raw.writableFinished) {
3175
+ controller.abort();
3176
+ }
3177
+ });
3178
+
3179
+ try {
3180
+ // emit with { signal } — aborting the controller aborts the command: timeout, retry and the request
3181
+ const call = getUser(request.params.id);
3182
+ return await bus.emit(call, { signal: controller.signal });
3183
+ } catch (error) {
3184
+ // nobody is left to answer when the client closed the connection
3185
+ if (reply.raw.destroyed) {
3186
+ return reply;
3187
+ }
3188
+ return reply.code(502).send({ error: String(error) });
3189
+ }
3190
+ });
3191
+ ```
3192
+
3193
+ After an abort the command rejects with the abort reason. The `catch` above ignores it when the connection is gone, because there is nobody to answer.
3194
+
3195
+ ## Stop the server
3196
+
3197
+ <!-- docs-check: continue -->
3198
+
3199
+ Keep the controllers of the requests in flight in a set. On SIGTERM (what a container sends) or SIGINT (Ctrl+C), abort them all, then close the app. A request that is aborted this way answers with an error, and `app.close()` waits for the connections to end.
3200
+
3201
+ ```js
3202
+ // shutdown.js
3203
+ import { app, inFlight } from "./server";
3204
+
3205
+ // SIGTERM is what a container sends, SIGINT is Ctrl+C
3206
+ for (const name of ["SIGTERM", "SIGINT"]) {
3207
+ process.on(name, async () => {
3208
+ for (const controller of inFlight) {
3209
+ controller.abort();
3210
+ }
3211
+ await app.close();
3212
+ process.exit(0);
3213
+ });
3214
+ }
3215
+ ```
3216
+
3217
+ The route above fills `inFlight` and empties it in the `close` listener. The [api-server example](../examples/api-server) does the same, with a limit of two seconds for the close.
3218
+
3219
+ ## Tie a WebSocket to its work
3220
+
3221
+ <!-- docs-check: continue -->
3222
+
3223
+ A socket lasts minutes and carries several tasks (a subscription, a heartbeat), so the controller belongs to the socket and every `emit` for it gets the same signal. Closing the socket stops all of them.
3224
+
3225
+ First the command. It sends a price now and then every second, until its task is aborted.
3226
+
3227
+ ```js
3228
+ // prices.js
3229
+ import { createCommand } from "nanoeffects/actions";
3230
+ import { poll } from "nanoeffects/effects";
3231
+ import { latest } from "nanoeffects/policies";
3232
+
3233
+ // createCommand — a command with a handler
3234
+ // latest — a new subscription stops the old one; key — but only the old one of the same socket
3235
+ export const watchPrices = createCommand(
3236
+ "prices/watch",
3237
+ latest(
3238
+ async (call, ctx) => {
3239
+ // poll — call the function now and every second, until the task is aborted
3240
+ await poll(ctx, () => call.send(`${call.symbol}: ${Math.random()}`), 1000, {
3241
+ leading: true,
3242
+ });
3243
+ },
3244
+ { key: (call) => call.socketId },
3245
+ ),
3246
+ );
3247
+ ```
3248
+
3249
+ Without the `key`, one policy serves the whole command, and a new subscription on one socket would stop the subscription on another.
3250
+
3251
+ Then the route. Each socket gets an id and a controller.
3252
+
3253
+ ```js
3254
+ // sockets.js
3255
+ import websocket from "@fastify/websocket";
3256
+ import Fastify from "fastify";
3257
+ import { bus } from "./bus";
3258
+ import { watchPrices } from "./prices";
3259
+
3260
+ const sockets = Fastify();
3261
+ sockets.register(websocket);
3262
+
3263
+ let lastSocketId = 0;
3264
+
3265
+ sockets.register(async (instance) => {
3266
+ instance.get("/prices", { websocket: true }, (socket) => {
3267
+ lastSocketId += 1;
3268
+ const socketId = lastSocketId;
3269
+ const controller = new AbortController();
3270
+ const { signal } = controller;
3271
+
3272
+ // close — the client left: stop everything started for this socket
3273
+ socket.on("close", () => controller.abort());
3274
+
3275
+ socket.on("message", (data) => {
3276
+ const send = (text) => socket.send(text);
3277
+ const call = watchPrices({ socketId, symbol: String(data), send });
3278
+ // emit with { signal } — the call stops when the socket closes
3279
+ bus.emit(call, { signal });
3280
+ });
3281
+ });
3282
+ });
3283
+ ```
3284
+
3285
+ The [ws-server example](../examples/ws-server) adds a close for a silent socket, made of `race`, `take` and `delay`.
3286
+
3287
+ ## Run a queue worker
3288
+
3289
+ A worker takes jobs from a client and answers at once, and the work goes on in the background. Use `createJob` with `queue` to limit how many run together, `retry` and `timeout` to give up, and the outcomes of the job (`pending`, `success`, `fail`, `cancel`) to count them. Give every `emit` of the job the same signal; aborting it at shutdown cancels the jobs that are left.
3290
+
3291
+ One detail matters: a call that is still waiting in the queue when the signal aborts never starts, and the job sends no outcome for it. Count such calls yourself if you need the totals to add up.
3292
+
3293
+ The [job-worker example](../examples/job-worker) has all of it: the counts, `GET /stats`, and a shutdown in three steps (stop taking jobs, wait, abort the rest).
3294
+
3295
+ ## Examples
3296
+
3297
+ | Folder | What it shows |
3298
+ | ------ | ------------- |
3299
+ | [`api-server`](../examples/api-server) | A Fastify server over PokeAPI: `timeout`, `retry`, `allSettled`, and the abort when the client leaves |
3300
+ | [`ws-server`](../examples/ws-server) | A WebSocket server: one controller for each socket, `latest` with a `key`, an idle close |
3301
+ | [`job-worker`](../examples/job-worker) | A queue worker: `queue`, `retry`, `timeout`, counts from the outcomes, a three-step shutdown |
3302
+
3073
3303
  ---
3074
3304
  Source: docs/react.md
3075
3305
 
@@ -3356,7 +3586,7 @@ export const Search = ({ wait }) => {
3356
3586
  ---
3357
3587
  Source: docs/chat-example.md
3358
3588
 
3359
- # Build a chat with domains, modules and a small server
3589
+ # Build a chat with entities, features, modules and a small server
3360
3590
 
3361
3591
  Use this page when your app has several features that react to each other and you want to see where each piece of logic goes. The example is a chat with rooms, a history that loads, messages that can fail to send, a search across all rooms, and new messages that arrive on their own. A small Fastify server in the example answers every request, and it misbehaves on a known schedule, so each problem on this page really happens.
3362
3592
 
@@ -3388,21 +3618,27 @@ Open the Network panel of the browser while you do this. A request that the page
3388
3618
 
3389
3619
  ## See how the files are split
3390
3620
 
3391
- Each domain is a folder. The components only emit events and read values; they never call the server.
3621
+ The code is in layers, and a file imports only from the layers below it. The components only emit events and read values; they never call the server.
3392
3622
 
3393
- | Path | Job |
3394
- | ---- | --- |
3395
- | `src/bus.ts` | Creates the bus. It imports no events and no domain. |
3396
- | `src/app.ts` | Mounts the four domains. |
3397
- | `src/api.ts` | The client of the server: one function per request. |
3398
- | `server/` | The Fastify server and the script that starts it with Vite. |
3399
- | `src/domains/rooms/` | The list of rooms and the selected room. |
3400
- | `src/domains/messages/` | The history of the open room and sending a message. |
3401
- | `src/domains/search/` | Searching every room and opening a result. |
3402
- | `src/domains/incoming/` | New messages, asked for at an interval. |
3403
- | `src/ui/` | The components. |
3623
+ | Path | Layer | Job |
3624
+ | ---- | ----- | --- |
3625
+ | `src/shared/bus.ts` | shared | Creates the bus. It imports no events, no entity and no feature. |
3626
+ | `src/shared/api.ts` | shared | The client of the server: one function per request. |
3627
+ | `src/entities/room/` | entity | The list of rooms and the selected room. |
3628
+ | `src/entities/message/` | entity | The history of the open room, sending a message, and a message that arrives. |
3629
+ | `src/features/show-history/` | feature | A selected room loads its history. |
3630
+ | `src/features/search-messages/` | feature | Searching every room and opening a result. |
3631
+ | `src/features/receive-messages/` | feature | New messages, asked for at an interval. |
3632
+ | `src/ui/`, `src/app.ts` | top | The components, and the file that mounts the modules. |
3633
+ | `server/` | | The Fastify server and the script that starts it with Vite. |
3634
+
3635
+ **The rule.** An entity is a thing with its own state and orders (a room, a message). It imports `shared` and nothing else. A feature is a scenario that connects things: it imports `shared` and entities, and never another feature. The top imports anything below. No two entities import each other and no two features import each other, and a test in the repository (`src/tests/architecture.test.ts`) fails when one does.
3636
+
3637
+ That rule is why `show-history` exists. Selecting a room must load its history, but `room` does not know `message` and `message` does not know `room`. The feature `show-history` is the one place that knows both: it listens to `rooms/selected` and starts the job `messages/loadHistory`. The same goes for a message that arrives: `receive-messages` emits `incoming/received`, an event that the `message` entity owns and listens to.
3638
+
3639
+ A folder has its events (`room.ts`, which imports no bus), its work (`room-handlers.ts`), the state it keeps (`room-store.ts`) and a module (`room-module.ts`) that wires them. Another layer reaches an entity through its events and commands, never through its handlers or its store. Events and commands both live in the events file. An event (`createAction`) says that something happened, and any feature may listen: `rooms/selected` is heard by two. A command (`createCommand`) is an order with exactly one handler, as `search/openResult` and `messages/mark` are. The handler is given to `createCommand`, so the command works wherever it is called and can return a result, and the module binds it with `module.use` for as long as it is mounted. A job is a command that also sends its outcomes, but its handler is bound in the module (`module.handle`): a job usually runs under a policy, and the type of its outcomes is exact only when the handler is not part of the type.
3404
3640
 
3405
- A domain folder has its events (`rooms.ts`, which imports no bus), its work (`rooms-handlers.ts`), the state it keeps (`rooms-store.ts`) and a module (`rooms-module.ts`) that wires them. A domain reacts to another domain by listening to its events, never by importing its handlers or its store. Events and commands both live in the events file. An event (`createAction`) says that something happened, and any domain may listen: `rooms/selected` is heard by three. A command (`createCommand`) is an order with exactly one handler, as `search/openResult` and `messages/mark` are. The handler is given to `createCommand`, so the command works wherever it is called and can return a result, and the module binds it with `module.use` for as long as it is mounted. A job is a command that also sends its outcomes, but its handler is bound in the module (`module.handle`): a job usually runs under a policy, and the type of its outcomes is exact only when the handler is not part of the type.
3641
+ The layers come from [Feature-Sliced Design](https://feature-sliced.design/), reduced to the three that an app of this size needs.
3406
3642
 
3407
3643
  ## Load a history that must not race
3408
3644
 
@@ -3413,7 +3649,7 @@ A domain folder has its events (`rooms.ts`, which imports no bus), its work (`ro
3413
3649
  A job sends `pending` when its handler starts and exactly one of `success`, `fail` and `cancel` when it ends. `latest` around the handler aborts the older load when a newer one starts, so only the newer result is delivered, and the older one sends `cancel`:
3414
3650
 
3415
3651
  ```js
3416
- // messages.js
3652
+ // message.js
3417
3653
  import { createJob } from "nanoeffects/actions";
3418
3654
 
3419
3655
  // createJob — a command that also sends pending, success, fail and cancel
@@ -3421,7 +3657,7 @@ export const loadHistory = createJob("messages/loadHistory");
3421
3657
  ```
3422
3658
 
3423
3659
  ```js
3424
- // messages-handlers.js
3660
+ // message-handlers.js
3425
3661
  import { latest } from "nanoeffects/policies";
3426
3662
 
3427
3663
  // latest — a load for a newer room aborts the older one, and its result is never delivered
@@ -3431,12 +3667,12 @@ export const fetchHistory = latest((roomId, { signal }) => api.loadHistory(roomI
3431
3667
  The module gives the job its work and keeps the state from the outcomes, so an aborted load clears the flag too (see [Show a loading state with a job](actions.md#show-a-loading-state-with-a-job)):
3432
3668
 
3433
3669
  ```js
3434
- // messages-module.js
3670
+ // message-module.js
3435
3671
  import { createModule } from "nanoeffects/actions";
3436
- import { loadHistory } from "./messages";
3437
- import { fetchHistory } from "./messages-handlers";
3672
+ import { loadHistory } from "./message";
3673
+ import { fetchHistory } from "./message-handlers";
3438
3674
 
3439
- export const messagesModule = createModule("messages", (module) => {
3675
+ export const messageModule = createModule("message", (module) => {
3440
3676
  // handle — this module does the work of loadHistory while it is mounted
3441
3677
  module.handle(loadHistory, fetchHistory);
3442
3678
  module.on(loadHistory.pending, () => console.log("show the spinner"));
@@ -3526,7 +3762,7 @@ export const runSearch = debounce(
3526
3762
 
3527
3763
  **Problem.** The reader opens a search result from another room. The message cannot be marked until that room's history has loaded, and the handler must not guess how long that takes.
3528
3764
 
3529
- **When.** A handler starts work in another domain and needs to continue after its outcome.
3765
+ **When.** A feature starts work in an entity and needs to continue after its outcome.
3530
3766
 
3531
3767
  `take` waits for the next event of a name. Start it before the emit that causes the event, so nothing is missed:
3532
3768
 
@@ -3534,7 +3770,7 @@ export const runSearch = debounce(
3534
3770
  import { createCommand } from "nanoeffects/actions";
3535
3771
  import { take } from "nanoeffects/effects";
3536
3772
 
3537
- // createCommand — an order for the messages domain, with the handler that does it
3773
+ // createCommand — an order for the message entity, with the handler that does it
3538
3774
  const markMessage = createCommand("messages/mark", (messageId) => console.log("mark", messageId));
3539
3775
 
3540
3776
  // the room that is open, kept from the rooms/selected event
@@ -3547,7 +3783,7 @@ export const goToResult = async (hit, ctx) => {
3547
3783
  ctx.emit("rooms/selected", hit.roomId);
3548
3784
  await loaded;
3549
3785
  }
3550
- // ctx.emit with a command — the messages domain marks the message
3786
+ // ctx.emit with a command — the message entity marks the message
3551
3787
  ctx.emit(markMessage(hit.id));
3552
3788
  };
3553
3789
  ```
@@ -3585,23 +3821,23 @@ const watchUpdates = async (_, ctx) => {
3585
3821
  await poll(ctx, check, 3000, { leading: true });
3586
3822
  };
3587
3823
 
3588
- export const incomingModule = createModule("incoming", (module) => {
3824
+ export const receiveMessagesModule = createModule("receive-messages", (module) => {
3589
3825
  // spawn — a background task that lives as long as this module
3590
3826
  module.spawn(watchUpdates);
3591
3827
  });
3592
3828
  ```
3593
3829
 
3594
- In the example a button calls `app.unmount(incomingModule)` and `app.mount(incomingModule)`, so you can watch the polling stop (the Network panel shows no more `updates` requests) and start.
3830
+ In the example a button calls `app.unmount(receiveMessagesModule)` and `app.mount(receiveMessagesModule)`, so you can watch the polling stop (the Network panel shows no more `updates` requests) and start.
3595
3831
 
3596
3832
  ## Know where each value lives
3597
3833
 
3598
- Each domain keeps its state in a [Zustand](https://zustand.docs.pmnd.rs/) store that the module writes and a component reads with `useStore`. Each store lists its mutations, such as `startLoading(roomId)` and `markFailed(localId)`, and a module calls them with the data of an event: `module.on(loadHistory.pending, startLoading)`. A mutation that sets plain values gives `set` an object, as in `set({ searching: true })`. The store of the messages uses the `immer` middleware, so a mutation that changes a list can change it in place, as in `state.messages.push(message)`, and the store still gives React a new object. Nothing else writes the state. The list of rooms is the exception: it is read with one `useEventState` in a provider at the root. `useEventState` is not a store: an event that came before the provider mounted is lost, and a second component gets its own copy. See [Show the last value of an event as state](react.md#show-the-last-value-of-an-event-as-state).
3834
+ Each entity and each feature that has state keeps it in a [Zustand](https://zustand.docs.pmnd.rs/) store that the module writes and a component reads with `useStore`. Each store lists its mutations, such as `startLoading(roomId)` and `markFailed(localId)`, and a module calls them with the data of an event: `module.on(loadHistory.pending, startLoading)`. A mutation that sets plain values gives `set` an object, as in `set({ searching: true })`. The store of the message entity uses the `immer` middleware, so a mutation that changes a list can change it in place, as in `state.messages.push(message)`, and the store still gives React a new object. Nothing else writes the state. The list of rooms is the exception: it is read with one `useEventState` in a provider at the root. `useEventState` is not a store: an event that came before the provider mounted is lost, and a second component gets its own copy. See [Show the last value of an event as state](react.md#show-the-last-value-of-an-event-as-state).
3599
3835
 
3600
3836
  ## Where to go next
3601
3837
 
3602
3838
  - The API of commands, jobs and modules: [Actions, commands, jobs and modules](actions.md).
3603
3839
  - Policies such as `latest` and `queue`: [Policies](policies.md). Effects such as `allSettled`, `take` and `poll`: [Effects](effects.md).
3604
- - A smaller project with two domains: [Start with domains](starter.md#start-with-domains).
3840
+ - A smaller project with two domains: [Start with domains](starter.md#start-with-domains). Its two domains do not talk to each other, so it needs no layers.
3605
3841
 
3606
3842
  ---
3607
3843
  Source: docs/vue.md
@@ -5364,9 +5600,9 @@ bus.on("watch", async (_, ctx) => {
5364
5600
 
5365
5601
  await race(ctx, {
5366
5602
  // poll: a check every 5 s; waitForFn: the next pause starts after the check ends
5367
- polling: ({ signal }) => poll({ signal }, checkStatus, 5000, { waitForFn: true }),
5603
+ polling: (child) => poll(child, checkStatus, 5000, { waitForFn: true }),
5368
5604
  // take: resolves at the next "leave", and race stops the polling
5369
- leave: ({ signal }) => take(ctx, "leave", { signal }),
5605
+ leave: (child) => take(child, "leave"),
5370
5606
  });
5371
5607
  });
5372
5608
 
package/llms.txt CHANGED
@@ -34,8 +34,9 @@ Rules that generated code often gets wrong:
34
34
  - [Actions, commands, jobs and modules](docs/actions.md): `createAction`, `createCommand`, `createJob`, `createModule`
35
35
  - [Connect Redux, Zustand, MobX, or Pinia](docs/stores.md): the Redux middleware and callbacks of other stores
36
36
  - [Use nanoeffects with React Query and SWR](docs/query-libraries.md): call a command from `queryFn` or the SWR fetcher; `signalPlugin` passes the abort of the library to the task
37
+ - [Stop work on a server when the client leaves](docs/server.md): one `AbortController` for each request or socket, `signalPlugin`, a clean shutdown, and a queue worker; Fastify examples
37
38
  - [Build a sign-up form in React](docs/react.md): a form with a username check, a submit that cannot fire twice, and retry; `useEventState` shows an event as state, `usePolicy` keeps a debounced handler between renders
38
- - [Build a chat with domains, modules and a small server](docs/chat-example.md): rooms, a history under `latest`, a send under `queue` and `retry`, a search with `allSettled` and `timeout`, new messages polled with `poll`
39
+ - [Build a chat with entities, features, modules and a small server](docs/chat-example.md): rooms, a history under `latest`, a send under `queue` and `retry`, a search with `allSettled` and `timeout`, new messages polled with `poll`
39
40
  - [Use nanoeffects in a Vue app](docs/vue.md): `vuePlugin` adds `watchEmitter` (a value of a component to the bus) and `useEventRef` (an event as a ref)
40
41
  - [Use nanoeffects in a Svelte app](docs/svelte.md): `sveltePlugin` adds `eventStore` (an event as a Svelte store)
41
42
  - [Context fields](docs/context.md): put a store or client on every task
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nanoeffects",
3
- "version": "0.22.0",
3
+ "version": "0.23.1",
4
4
  "description": "Cancel stale async work and fix race conditions in event handlers: a typed event bus where every handler is a task with an AbortSignal, plus latest, debounce, throttle, queue, retry, timeout and poll. About 1.4 kB gzip.",
5
5
  "keywords": [
6
6
  "event-bus",
@@ -167,14 +167,17 @@
167
167
  "@biomejs/biome": "2.5.15",
168
168
  "@commitlint/cli": "21.2.3",
169
169
  "@commitlint/config-conventional": "21.2.3",
170
+ "@fastify/websocket": "^11.3.4",
170
171
  "@reduxjs/toolkit": "^2.13.0",
171
172
  "@size-limit/esbuild": "^14.2.0",
172
173
  "@size-limit/file": "^14.2.0",
173
174
  "@tanstack/react-query": "^5.105.0",
174
175
  "@types/react": "^19.3.0",
175
176
  "@types/react-dom": "^19.3.0",
177
+ "@types/ws": "^8.18.2",
176
178
  "@vitejs/plugin-react": "^6.1.2",
177
179
  "archunit": "^2.5.4",
180
+ "fastify": "^5.12.7",
178
181
  "happy-dom": "^21.0.4",
179
182
  "immer": "^10.2.0",
180
183
  "jotai": "^3.0.1",
@@ -212,17 +215,17 @@
212
215
  {
213
216
  "name": "policies (all)",
214
217
  "path": "dist/policies.js",
215
- "limit": "2.65 kB"
218
+ "limit": "2.7 kB"
216
219
  },
217
220
  {
218
221
  "name": "effects (all)",
219
222
  "path": "dist/effects.js",
220
- "limit": "2.45 kB"
223
+ "limit": "2.5 kB"
221
224
  },
222
225
  {
223
226
  "name": "actions (all)",
224
227
  "path": "dist/actions.js",
225
- "limit": "3.02 kB"
228
+ "limit": "3.1 kB"
226
229
  },
227
230
  {
228
231
  "name": "match (plugin)",
@@ -1 +0,0 @@
1
- const e=(e,t)=>{globalThis.console?.error(`[nanoeffects] ${e}`,t)},t=()=>{},n=/* @__PURE__ */ new WeakMap,r=t=>{let r=n.get(t);if(r)return r;let i=/* @__PURE__ */ new Set;return n.set(t,i),t.addEventListener(`abort`,()=>{let n=[...i];i.clear();for(let{fn:r}of n)try{r(t.reason)}catch(t){e(`abort callback failed`,t)}},{once:!0}),i},i=(e,n)=>{let{signal:i}=e;if(!i)return t;if(i.aborted)return n(i.reason),t;let a=r(i),o={fn:n};return a.add(o),()=>{a.delete(o)}},a=e=>{let t=new AbortController;return{controller:t,unlink:i({signal:e},e=>t.abort(e))}},o=Symbol(),s=typeof __NANOEFFECTS_TRACE__>`u`||__NANOEFFECTS_TRACE__,c=/* @__PURE__ */ new WeakMap;let l;const u=()=>l,d=()=>{},f=(e,t,n,r)=>{let i=s&&c.get(e);i&&i.tracer.report(i.ref,t,n,r)},p=(e,t)=>{let n=s&&c.get(e);n&&n.tracer.rename?.(n.ref,t)},m=(e,t)=>{let n=s&&c.get(e);return n?n.tracer.settler(n.ref,t):d},h=(e,t,n)=>{let r=s&&c.get(e);return r?r.tracer.run(r.ref,t,e.signal,n):n()},g=(e,t)=>typeof e==`function`?e(t):e,_=({event:e,bus:t,tracer:n,parent:r})=>{let{controller:u,unlink:f}=a(r?.signal),{signal:p}=u,m=s&&n?{tracer:n,ref:n.task(e,r?.ref)}:void 0,v=(...e)=>{if(p.aborted&&!x[o])return;let n=t?.emit,r=l;l=m?.ref;try{return n?.(...e)}finally{l=r}},y=(...e)=>{if(p.aborted)return d;let n=t?.on,r=n?.(...e);if(!r)return d;let a=i({signal:p},r);return()=>{a(),r()}},b=async(r,...i)=>{p.throwIfAborted();let a=i[0],o=_({event:{type:e.type,payload:a},bus:t,tracer:n,parent:{signal:p,ref:m?.ref}});try{return await h(o.ctx,`run`,()=>r(a,o.ctx))}finally{o.unlink()}},x={...g(t?.ctx,e),type:e.type,payload:e.payload,signal:p,abort:e=>u.abort(e),emit:v,on:y,off:t?.off??d,run:b};return t?.addContext?.(x),m&&c.set(x,m),{ctx:x,unlink:f}},v=(e,t)=>{let n=s?c.get(e):void 0;return _({event:{type:t??e.type??``,payload:e.payload},bus:{emit:e.emit,on:e.on,off:e.off,ctx:e},tracer:n?.tracer,parent:{signal:e.signal,ref:n?.ref}})};export{p as a,s as c,e as d,v as i,o as l,_ as n,h as o,u as r,f as s,m as t,i as u};
@@ -1 +0,0 @@
1
- const e=(e,t)=>{globalThis.console?.error(`[nanoeffects] ${e}`,t)},t=()=>{},n=/* @__PURE__ */ new WeakMap,r=t=>{let r=n.get(t);if(r)return r;let i=/* @__PURE__ */ new Set;return n.set(t,i),t.addEventListener(`abort`,()=>{let n=[...i];i.clear();for(let{fn:r}of n)try{r(t.reason)}catch(t){e(`abort callback failed`,t)}},{once:!0}),i},i=(e,n)=>{let{signal:i}=e;if(!i)return t;if(i.aborted)return n(i.reason),t;let a=r(i),o={fn:n};return a.add(o),()=>{a.delete(o)}},a=e=>{let t=new AbortController;return{controller:t,unlink:i({signal:e},e=>t.abort(e))}},o=Symbol();let s;const c=()=>s,l=()=>{},u=(e,t,n,r)=>{},d=(e,t)=>l,f=(e,t,n)=>n(),p=(e,t)=>typeof e==`function`?e(t):e,m=({event:e,bus:t,tracer:n,parent:r})=>{let{controller:c,unlink:u}=a(r?.signal),{signal:d}=c,h=(...e)=>{if(d.aborted&&!v[o])return;let n=t?.emit,r=s;s=void 0;try{return n?.(...e)}finally{s=r}},g=(...e)=>{if(d.aborted)return l;let n=t?.on,r=n?.(...e);if(!r)return l;let a=i({signal:d},r);return()=>{a(),r()}},_=async(r,...i)=>{d.throwIfAborted();let a=i[0],o=m({event:{type:e.type,payload:a},bus:t,tracer:n,parent:{signal:d,ref:void 0}});try{return await f(o.ctx,`run`,()=>r(a,o.ctx))}finally{o.unlink()}},v={...p(t?.ctx,e),type:e.type,payload:e.payload,signal:d,abort:e=>c.abort(e),emit:h,on:g,off:t?.off??l,run:_};return t?.addContext?.(v),{ctx:v,unlink:u}},h=(e,t)=>m({event:{type:t??e.type??``,payload:e.payload},bus:{emit:e.emit,on:e.on,off:e.off,ctx:e},tracer:void 0,parent:{signal:e.signal,ref:void 0}});export{f as a,i as c,h as i,e as l,m as n,u as o,c as r,o as s,d as t};