nanoeffects 0.14.0 → 0.16.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.
Files changed (50) hide show
  1. package/dist/{notrace/action-creator-Ls3Gy3jk.d.ts → action-creator-HFA_LZOH.d.ts} +2 -2
  2. package/dist/actions.d.ts +3 -3
  3. package/dist/actions.js +1 -1
  4. package/dist/bus-duCCrqrr.js +1 -0
  5. package/dist/{notrace/context-types-DQYBFJG4.d.ts → context-types-BNcs43eY.d.ts} +1 -1
  6. package/dist/context.d.ts +2 -2
  7. package/dist/dev.d.ts +2 -2
  8. package/dist/effects.d.ts +2 -2
  9. package/dist/index.d.ts +2 -3
  10. package/dist/index.js +1 -1
  11. package/dist/match.d.ts +1 -1
  12. package/dist/{module-COv9ZSzS.d.ts → module-DTf73Wdq.d.ts} +2 -2
  13. package/dist/{action-creator-CQlFgQm4.d.ts → notrace/action-creator-CbFf398i.d.ts} +2 -24
  14. package/dist/notrace/actions.d.ts +2 -2
  15. package/dist/notrace/actions.js +1 -1
  16. package/dist/notrace/bus-BkUtjPHp.js +1 -0
  17. package/dist/notrace/effects.d.ts +2 -2
  18. package/dist/notrace/index.d.ts +2 -3
  19. package/dist/notrace/index.js +1 -1
  20. package/dist/{plugin-15-kkZp0.d.ts → notrace/plugin-C5vIjxhR.d.ts} +8 -2
  21. package/dist/notrace/policies.d.ts +1 -1
  22. package/dist/notrace/redux.d.ts +1 -1
  23. package/dist/observable.d.ts +30 -1
  24. package/dist/observable.js +1 -1
  25. package/dist/oop.d.ts +49 -1
  26. package/dist/oop.js +1 -1
  27. package/dist/{notrace/plugin-W4pZY7mM.d.ts → plugin-Sy8z9IId.d.ts} +2 -2
  28. package/dist/policies.d.ts +2 -2
  29. package/dist/react.d.ts +2 -2
  30. package/dist/redux.d.ts +1 -1
  31. package/dist/scope.d.ts +2 -2
  32. package/dist/signal.d.ts +1 -1
  33. package/dist/signal.js +1 -1
  34. package/dist/trace.d.ts +2 -2
  35. package/dist/{types-C7ukMwE-.d.ts → types-DaZT158m.d.ts} +2 -2
  36. package/dist/{with-policy-_zP3OKGy.d.ts → with-policy-C_mX7S54.d.ts} +1 -1
  37. package/docs/cancel-stale-requests.md +6 -2
  38. package/docs/debounce-and-abort.md +1 -3
  39. package/docs/effects.md +10 -3
  40. package/docs/observable.md +50 -0
  41. package/docs/oop.md +126 -4
  42. package/docs/package.md +2 -2
  43. package/docs/plugins.md +8 -2
  44. package/docs/tracing.md +32 -8
  45. package/llms-full.txt +235 -24
  46. package/llms.txt +2 -2
  47. package/package.json +2 -2
  48. package/dist/bus-Cdw5ajKF.js +0 -1
  49. package/dist/context-types-qXxr_Grf.d.ts +0 -14
  50. package/dist/notrace/bus-G2AdGObY.js +0 -1
@@ -70,6 +70,56 @@ bus.on(queryChanged, (query) => console.log("search for", query));
70
70
 
71
71
  The Observable can come from anywhere, not only from `createObserve`. `subscription.unsubscribe()` stops it; the bus does not know about it. Pass the callback to `subscribe` as it is, and do not call `bus.emitter(...)` inside the operators on every value.
72
72
 
73
+ ## Read and write one event with a Subject
74
+
75
+ Problem: `createObserve` only reads. Code written for streams often also needs to push a value into the same event, and passing a bus and an event name around for that is clumsy.
76
+
77
+ `Subject` is one event of a bus as one object. `subscribe` listens, `next` emits. It has no `complete`, no `error` and no replay: an event of a bus does not end, and the bus keeps no values.
78
+
79
+ ```js
80
+ import { createBus } from "nanoeffects";
81
+ import { Subject } from "nanoeffects/observable";
82
+
83
+ const bus = createBus(); // the bus: events and handlers
84
+
85
+ const typed = new Subject(bus, "typed"); // Subject — the event "typed" as a stream you can also write to
86
+
87
+ const subscription = typed.subscribe((text) => console.log(text)); // like bus.on("typed", …)
88
+ typed.next("hello"); // like bus.emit("typed", "hello"): bus.on handlers and subscribers both run
89
+ subscription.unsubscribe(); // removes this subscription only
90
+ ```
91
+
92
+ - `next` works when you take it off the subject, so `input.addEventListener("input", (event) => typed.next(event.target.value))` and `store.subscribe(typed.next)` need no wrapper.
93
+ - A subscriber that is added later does not get a value emitted before. Add `startWith` or `shareReplay` in RxJS when it should.
94
+ - RxJS takes a `Subject` as it takes `createObserve`: `from(typed)`. It is not an RxJS `Subject` (no `error`, `complete` or `pipe`), so it does not fit where that type is wanted.
95
+
96
+ ### Extend it for a named stream
97
+
98
+ Problem: the event name is repeated wherever the stream is made. A subclass fixes it once.
99
+
100
+ ```js
101
+ import { createBus } from "nanoeffects";
102
+ import { Subject } from "nanoeffects/observable";
103
+
104
+ class TypedText extends Subject {
105
+ constructor(bus) {
106
+ super(bus, "typed"); // the event is fixed by the class
107
+ }
108
+
109
+ next(text) {
110
+ super.next(text.trim()); // a method of the subclass replaces the one of Subject
111
+ }
112
+ }
113
+
114
+ const bus = createBus(); // the bus: events and handlers
115
+ const typed = new TypedText(bus);
116
+ typed.next(" hello "); // emits "typed" with "hello"
117
+ ```
118
+
119
+ ### Use it inside a class with a bus
120
+
121
+ A class made with `extendBus` has its own `on` and `emit`. Pass `this` as the source and the subscription belongs to the instance, so `dispose()` ends it ([Classes with a bus](oop.md)).
122
+
73
123
  ## Do the work in a handler, not in `switchMap`
74
124
 
75
125
  An Observable is good for shaping values. A request is better in a handler with a policy, because the handler has a `signal` and the trace shows it. Split it: RxJS ends at the value, the bus starts the work.
package/docs/oop.md CHANGED
@@ -1,6 +1,11 @@
1
1
  # Use the bus from a class
2
2
 
3
- Use this page when **your domain logic lives in classes**: a service, a store or a controller that needs the bus inside its methods. A class made with `extendBus` has `on`, `emit` and the other methods of the bus, and remembers what each instance subscribed to, so `dispose()` ends it all.
3
+ Use this page when **your domain logic lives in classes**: a service, a store or a controller that needs the bus inside its methods. There are two ways to give a class the methods of a bus, and both remember what each instance subscribed to, so `dispose()` ends it all:
4
+
5
+ | You want | Use |
6
+ | -------- | --- |
7
+ | every `new Service()` to be an independent emitter | `extends Emitter` |
8
+ | the instances to share a bus, or to use plugins | `extends extendBus(bus)` |
4
9
 
5
10
  If your logic is plain functions, stay with [modules](actions.md#mount-domains-with-modules): a module is the same idea without a class.
6
11
 
@@ -8,7 +13,68 @@ If your logic is plain functions, stay with [modules](actions.md#mount-domains-w
8
13
 
9
14
  A class that listens to the bus keeps a reference to it, and keeps every unsubscribe function in a list to call when the object goes away. Forget one and the old object keeps handling events. `extendBus` does both for you.
10
15
 
11
- ## Give a class the methods of a bus
16
+ ## Make an independent emitter with `Emitter`
17
+
18
+ `Emitter` is a base class. Every instance of a class that extends it has a bus of its own: the events of one instance never reach another. It is the shape of Node's `EventEmitter`.
19
+
20
+ ```js
21
+ // video-service.js
22
+ import { Emitter } from "nanoeffects/oop";
23
+
24
+ // Emitter — a base class: each new VideoService() gets on, once, off, emit, dispose and its own bus
25
+ export class VideoService extends Emitter {
26
+ constructor() {
27
+ super();
28
+ // this.on — a subscription of this instance; dispose() removes it
29
+ this.on("played", () => console.log("playing"));
30
+ }
31
+ }
32
+ ```
33
+
34
+ ```js
35
+ import { VideoService } from "./video-service";
36
+
37
+ const first = new VideoService();
38
+ const second = new VideoService();
39
+ first.on("paused", () => console.log("first paused"));
40
+ second.emit("paused"); // nothing: the instances do not share a bus
41
+ first.emit("paused"); // logs "first paused"
42
+ first.dispose(); // its subscriptions are gone
43
+ ```
44
+
45
+ What you get:
46
+
47
+ - `on`, `once`, `off`, `emit`, `dispose` and `bus` (the bus of that instance). `instance[Symbol.dispose]()` does the same as `dispose()`, so `using video = new VideoService()` works where the runtime supports it.
48
+ - `@On` and `@Once` work on its methods (see below). They are subscribed when the base constructor runs, so before the fields of your subclass.
49
+ - `on`, `once`, `off` and `emit` are bound to the instance, so `const { emit } = video` works. A subclass replaces one with an arrow property (`emit = (…) => …`); TypeScript does not let it redeclare one as a method. `dispose` is a method and can be overridden as usual.
50
+ - No methods of plugins: the bus is made inside, so no plugin is on it. For plugins, or for a bus that several instances or classes share, use `extendBus` (next sections).
51
+ - For a stream of one event, see [`Subject`](observable.md#read-and-write-one-event-with-a-subject) and [Stream an event with a `Subject`](#stream-an-event-with-a-subject).
52
+
53
+ ### Type the events (optional)
54
+
55
+ `Emitter` takes the events of the class as a type parameter.
56
+
57
+ ```ts
58
+ // video-service.ts
59
+ import { Emitter } from "nanoeffects/oop";
60
+
61
+ // VideoEvents — checker only: the payload of each event of this class
62
+ type VideoEvents = { "video/time": number; "video/paused": void };
63
+
64
+ export class VideoService extends Emitter<VideoEvents> {
65
+ constructor() {
66
+ super();
67
+ // seconds is a number because "video/time" carries one
68
+ this.on("video/time", (seconds) => console.log(seconds));
69
+ }
70
+ }
71
+
72
+ const video = new VideoService();
73
+ video.emit("video/time", 12); // checked against VideoEvents
74
+ video.emit("video/paused"); // no payload
75
+ ```
76
+
77
+ ## Give a class the methods of a shared bus
12
78
 
13
79
  `extendBus(bus, Base)` returns a subclass of `Base`. Its instances have the methods of the bus, and the arguments of `new` go to the constructor of `Base`.
14
80
 
@@ -69,9 +135,33 @@ What you get:
69
135
  - `bus` is the bus, and `Class.bus` is the same one.
70
136
  - `this.on` works in the constructor of `Base`. The methods exist on the prototype of the subclass, which is the prototype of the instance already.
71
137
 
138
+ ### Extend the result with no class of your own
139
+
140
+ `extendBus(bus)` without a class returns a class with the methods of that bus and nothing else. Extend it as it is.
141
+
142
+ ```js
143
+ // service.js
144
+ import { createBus } from "nanoeffects";
145
+ import { extendBus } from "nanoeffects/oop";
146
+
147
+ const bus = createBus(); // the bus that the services share
148
+
149
+ // extendBus(bus) — a class with on, once, off, emit and dispose over this bus
150
+ export class AudioService extends extendBus(bus) {
151
+ constructor() {
152
+ super();
153
+ this.on("muted", () => console.log("muted")); // ends with dispose()
154
+ }
155
+ }
156
+
157
+ const audio = new AudioService();
158
+ bus.emit("muted"); // the instances share this bus: logs "muted"
159
+ audio.dispose();
160
+ ```
161
+
72
162
  ## Let the class make its bus
73
163
 
74
- Leave the bus out and the class gets its own, shared by all of its instances.
164
+ Leave the bus out and the class gets its own, shared by all of its instances. That is one bus for each class; `Emitter` makes one for each instance.
75
165
 
76
166
  ```js
77
167
  // notifier.js
@@ -113,6 +203,37 @@ stop(); // the function on returned still works, and does nothing now
113
203
 
114
204
  A subscription that you removed yourself (the function `on` returned, `this.off`, or a `once` that fired) is forgotten, so the instance holds nothing for it.
115
205
 
206
+ ## Stream an event with a `Subject`
207
+
208
+ Problem: a service hands one of its events to code written for streams, and the stream subscription should end with the service. `createObserve(this.bus)` would not: it subscribes through the bus, so `dispose()` does not know it.
209
+
210
+ Pass `this` to `Subject` as the source. The subject subscribes through `this.on`, so the subscription belongs to the instance ([Read and write one event with a Subject](observable.md#read-and-write-one-event-with-a-subject)).
211
+
212
+ ```js
213
+ // typing.js
214
+ import { createBus } from "nanoeffects";
215
+ import { Subject } from "nanoeffects/observable";
216
+ import { extendBus } from "nanoeffects/oop";
217
+
218
+ const bus = createBus(); // the bus: events and handlers
219
+
220
+ class TypingBase {
221
+ constructor() {
222
+ this.typed = new Subject(this, "typed"); // Subject — the event "typed" as a stream; this is the source
223
+ this.typed.subscribe((text) => console.log(text));
224
+ }
225
+ }
226
+
227
+ const Typing = extendBus(bus, TypingBase); // extendBus — a class with on, emit and dispose
228
+
229
+ const typing = new Typing();
230
+ typing.typed.next("a"); // logs "a"
231
+ typing.dispose(); // ends the subscription of the Subject too
232
+ typing.typed.next("b"); // nothing is logged
233
+ ```
234
+
235
+ In TypeScript, declare `on` and `emit` in the class (`declare on: BusMethods<typeof bus>["on"]`, see [Type the instances](#type-the-instances-optional)) so that `this` fits as the source.
236
+
116
237
  ## Keep a method of your own
117
238
 
118
239
  The class wins any clash of names. If `Base` has `emit`, `dispose`, `on` or `bus`, yours stays and the bus method is not added. A `Base` with its own `dispose` would never end the subscriptions, so call `disposeBus(this)` from there.
@@ -285,4 +406,5 @@ service.emit("order/placed", { id: "o1" }); // checked against Events
285
406
 
286
407
  - `this` is not bound in a handler that you pass by hand (see above).
287
408
  - The methods of a plugin used after `extendBus` are not on the class. Use the plugins first, then `extendBus`.
288
- - One bus for each instance, mixing the methods into an object that exists, and decorators for fields or parameters are not part of this entry.
409
+ - `Emitter` has no methods of plugins, because its bus is made inside. Use `extendBus(bus)` for them.
410
+ - Mixing the methods into an object that exists, and decorators for fields or parameters are not part of this entry.
package/docs/package.md CHANGED
@@ -11,10 +11,10 @@ Imports are split so you only load what you use. `createBus` stays small; the re
11
11
  | `nanoeffects/match` | `matchPlugin`: `on`, `once` and `off` that take a function which picks the events |
12
12
  | `nanoeffects/context` | `contextPlugin`: your own fields (a store, a client) on `ctx` of every task, typed from the value |
13
13
  | `nanoeffects/signal` | `signalPlugin`: `emit(call, { signal })` ties the tasks of an emit to an outside `AbortSignal` |
14
- | `nanoeffects/oop` | `extendBus`, `WithBus`, `On`, `Once`, `disposeBus`: the methods of a bus on a class, with the subscriptions of each instance ended by `dispose()` |
14
+ | `nanoeffects/oop` | `Emitter`, `extendBus`, `WithBus`, `On`, `Once`, `disposeBus`: the methods of a bus on a class, with the subscriptions of each instance ended by `dispose()` |
15
15
  | `nanoeffects/scope` | `scopePlugin`, `effect`: fields for one command, action, job, module or `emit` (the types `Scope`, `Effect`) |
16
16
  | `nanoeffects/redux` | `createEffectsMiddleware` |
17
- | `nanoeffects/observable` | `createObserve` |
17
+ | `nanoeffects/observable` | `createObserve`, `Subject` |
18
18
  | `nanoeffects/react` | `reactPlugin`: adds the `useEmitter` hook to a bus (needs React 18 or newer) |
19
19
  | `nanoeffects/dev` | `devPlugin` (no-op in production) |
20
20
  | `nanoeffects/trace` | `createTracer`, the loggers and `tracePlugin` (names for the trace) |
package/docs/plugins.md CHANGED
@@ -42,7 +42,9 @@ import { createBus } from "nanoeffects";
42
42
  import { delay, effectsPlugin, race } from "nanoeffects/effects";
43
43
 
44
44
  // effectsPlugin — race and delay are bound to the task of each handler
45
- const bus = createBus().use(effectsPlugin({ race, delay }));
45
+ const effects = effectsPlugin({ race, delay });
46
+
47
+ const bus = createBus().use(effects);
46
48
 
47
49
  bus.on("load", async (id, { race, delay }) => {
48
50
  const result = await race({
@@ -148,8 +150,12 @@ With a tracer on the bus, the plugin lets a trace say which subscription began a
148
150
  import { createBus } from "nanoeffects";
149
151
  import { consoleLogger, createTracer, tracePlugin } from "nanoeffects/trace";
150
152
 
153
+ // createTracer: sends each trace event to the logger; consoleLogger: prints one line each
154
+ const trace = createTracer(consoleLogger());
155
+
151
156
  // tracePlugin — names the roots, groups and listeners of the trace
152
- const bus = createBus({ trace: createTracer(consoleLogger()) }).use(tracePlugin());
157
+ const bus = createBus({ trace })
158
+ .use(tracePlugin());
153
159
 
154
160
  bus.on("name/changed", saveName, { traceId: "saveNotifier" }); // a listener you can find in the log
155
161
  ```
package/docs/tracing.md CHANGED
@@ -66,7 +66,10 @@ bus.on("load", async (id, ctx) => {
66
66
  import { createBus } from "nanoeffects";
67
67
  import { consoleLogger, createTracer, tracePlugin } from "nanoeffects/trace";
68
68
 
69
- export const bus = createBus({ trace: createTracer(consoleLogger()) })
69
+ // createTracer: sends each trace event to the logger; consoleLogger: prints one line each
70
+ const trace = createTracer(consoleLogger());
71
+
72
+ export const bus = createBus({ trace })
70
73
  .use(tracePlugin()); // tracePlugin: reports each emit as an event
71
74
  ```
72
75
 
@@ -95,7 +98,9 @@ import { createAction, emitterPlugin } from "nanoeffects/actions";
95
98
  import { consoleLogger, createTracer, tracePlugin } from "nanoeffects/trace";
96
99
 
97
100
  // createTracer: reports every task phase to the console
98
- const bus = createBus({ trace: createTracer(consoleLogger()) })
101
+ const trace = createTracer(consoleLogger());
102
+
103
+ const bus = createBus({ trace })
99
104
  .use(tracePlugin()) // tracePlugin: makes the root task that traceId names
100
105
  .use(emitterPlugin());
101
106
 
@@ -136,8 +141,12 @@ import { createBus } from "nanoeffects";
136
141
  import { createCommand } from "nanoeffects/actions";
137
142
  import { consoleLogger, createTracer, tracePlugin } from "nanoeffects/trace";
138
143
 
144
+ // createTracer: sends each trace event to the logger; consoleLogger: prints one line each
145
+ const trace = createTracer(consoleLogger());
146
+
139
147
  // tracePlugin: reads traceGroupId from the scope of a call
140
- const bus = createBus({ trace: createTracer(consoleLogger()) }).use(tracePlugin());
148
+ const bus = createBus({ trace })
149
+ .use(tracePlugin());
141
150
 
142
151
  // the scope names the flow; traceGroupId is for the tracer, not a field of ctx
143
152
  const pay = createCommand("checkout/pay", async () => {}, {
@@ -163,7 +172,11 @@ Give the listener a `traceId` when you register it. The plugin makes each call o
163
172
  import { createBus } from "nanoeffects";
164
173
  import { consoleLogger, createTracer, tracePlugin } from "nanoeffects/trace";
165
174
 
166
- const bus = createBus({ trace: createTracer(consoleLogger()) }).use(tracePlugin());
175
+ // createTracer: sends each trace event to the logger; consoleLogger: prints one line each
176
+ const trace = createTracer(consoleLogger());
177
+
178
+ const bus = createBus({ trace })
179
+ .use(tracePlugin());
167
180
 
168
181
  // traceId: the name of this listener in the trace
169
182
  bus.on("name/changed", saveName, { traceId: "saveNotifier" });
@@ -270,7 +283,10 @@ export const bus = createBus({ trace: createTracer(logger) })
270
283
  import { reduxDevtools } from "nanoeffects/trace";
271
284
 
272
285
  // debugging a race: which calls did a policy cancel or drop?
273
- reduxDevtools({ name: "app", policies: ["cancel", "drop"] });
286
+ reduxDevtools({
287
+ name: "app",
288
+ policies: ["cancel", "drop"],
289
+ });
274
290
 
275
291
  // every stage of every policy, one function for the choice
276
292
  reduxDevtools({
@@ -279,10 +295,18 @@ reduxDevtools({
279
295
  });
280
296
 
281
297
  // the old log: every stage, and the effects below the handlers
282
- reduxDevtools({ name: "app", policies: true, depth: 1, payload: "all" });
298
+ reduxDevtools({
299
+ name: "app",
300
+ policies: true,
301
+ depth: 1,
302
+ payload: "all",
303
+ });
283
304
 
284
305
  // keep the payloads out of the extension
285
- reduxDevtools({ name: "app", payload: "none" });
306
+ reduxDevtools({
307
+ name: "app",
308
+ payload: "none",
309
+ });
286
310
  ```
287
311
 
288
312
  With two quick `search` emits and a `latest` handler, the default list is `search`, `search`. With `policies: true` it adds the `latest` stages of each call, for example `search/latest/cancel` for the first one.
@@ -290,7 +314,7 @@ With two quick `search` emits and a `latest` handler, the default list is `searc
290
314
  ### Write your own logger
291
315
 
292
316
  ```ts
293
- import type { TraceLogger } from "nanoeffects";
317
+ import type { TraceLogger } from "nanoeffects/trace";
294
318
 
295
319
  const errorsOnly = (): TraceLogger => (event) => {
296
320
  if (event.phase === "error") {