nanoeffects 0.4.0 → 0.6.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/README.md +4 -1
- package/dist/{action-creator-D48fp13T.d.ts → action-creator-c292nK7v.d.ts} +130 -34
- package/dist/actions.d.ts +54 -5
- package/dist/actions.js +1 -1
- package/dist/{bus-Cho463Sq.js → bus-BAs9x7IQ.js} +1 -1
- package/dist/{context-DlA80GOA.js → context-CK0ZomWt.js} +1 -1
- package/dist/context-plugin-1pYmSQEG.d.ts +34 -0
- package/dist/dev.d.ts +2 -2
- package/dist/effects.d.ts +27 -129
- package/dist/effects.js +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/{module-DVX8aYlq.d.ts → module-BlF2KSgy.d.ts} +34 -5
- package/dist/notrace/{action-creator-D48fp13T.d.ts → action-creator-DKG_sIia.d.ts} +130 -34
- package/dist/notrace/actions.d.ts +96 -7
- package/dist/notrace/actions.js +1 -1
- package/dist/notrace/{bus-B12SvxLv.js → bus-Bdk0YyFQ.js} +1 -1
- package/dist/notrace/{context-yAWj0BFZ.js → context-CctVmHLC.js} +1 -1
- package/dist/notrace/context-plugin-Dt1IgVo8.d.ts +34 -0
- package/dist/notrace/{delay-Cgvn16oY.js → delay-B_W1tnkS.js} +1 -1
- package/dist/notrace/effects.d.ts +27 -129
- package/dist/notrace/effects.js +1 -1
- package/dist/notrace/index.d.ts +3 -2
- package/dist/notrace/index.js +1 -1
- package/dist/notrace/plugin-B0AXKusc.d.ts +207 -0
- package/dist/notrace/policies.d.ts +1 -1
- package/dist/notrace/policies.js +1 -1
- package/dist/notrace/redux.d.ts +18 -20
- package/dist/notrace/redux.js +1 -1
- package/dist/observable.d.ts +1 -1
- package/dist/plugin-CCYlC0XS.d.ts +207 -0
- package/dist/policies.d.ts +1 -1
- package/dist/policies.js +1 -1
- package/dist/react.d.ts +50 -0
- package/dist/react.js +1 -0
- package/dist/redux.d.ts +18 -20
- package/dist/redux.js +1 -1
- package/dist/scope-key-B7l7mUS5.js +1 -0
- package/dist/scope.d.ts +58 -0
- package/dist/scope.js +1 -0
- package/dist/trace.d.ts +1 -1
- package/dist/types-mLaAx-EZ.d.ts +15 -0
- package/docs/README.md +7 -1
- package/docs/actions.md +25 -1
- package/docs/context.md +26 -2
- package/docs/effects.md +83 -5
- package/docs/guide.md +24 -0
- package/docs/migrating-from-effector.md +293 -0
- package/docs/migrating-from-rxjs.md +127 -0
- package/docs/migrating-from-saga.md +93 -0
- package/docs/observable.md +1 -0
- package/docs/package.md +13 -2
- package/docs/policies.md +1 -0
- package/docs/react.md +157 -0
- package/docs/scope.md +226 -0
- package/docs/stores.md +429 -40
- package/docs/typescript.md +153 -0
- package/llms-full.txt +2925 -0
- package/llms.txt +49 -0
- package/package.json +44 -6
package/dist/effects.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./onAbort-BgMfspK4.js";import{a as n,i as r,o as i,t as a}from"./context-
|
|
1
|
+
import{n as e,t}from"./onAbort-BgMfspK4.js";import{a as n,i as r,o as i,t as a}from"./context-CK0ZomWt.js";import{n as o,r as s,t as c}from"./delay-CIHnOh_L.js";const l=(e,n)=>n?.signal?new Promise((r,i)=>{let a=t(n,i);e.then(r,i).finally(a)}):e,u=async(e,n,o,s)=>{n?.signal?.throwIfAborted();let{ctx:c,unlink:u}=r(n??{}),d=a(c,e);i(c,e,`start`),t(c,()=>d(`cancel`));try{let e=await l(o(c),n);return d(`done`),s?.(!1),e}catch(e){throw d(`error`,e),s?.(!0),e}finally{u()}},d=async(e,t)=>{let{ctx:i,unlink:a}=r(e);try{return await n(i,`run`,()=>t(i))}finally{a()}},f=e=>e,p=(e,t)=>n=>e(t,f(n)),m=e=>Array.isArray(e)?Array(e.length):{},h=(e,t)=>{let i=Object.entries(t).map(([t,i])=>{let a=r(e),o={signal:a.ctx.signal,abort:a.ctx.abort},s=()=>i(o);return{key:t,task:new Promise(e=>e(n(a.ctx,`run`,s))).finally(a.unlink),cancel:a.ctx.abort}});return{tasks:i.map(({key:e,task:t})=>[e,t]),cancelAll:()=>{for(let e of i)e.cancel()}}},g=(e,t,n,r,i)=>{let a=()=>{};return u(e,t,async e=>{let t=h(e,n);return a=t.cancelAll,r(t.tasks)},e=>{(e||i===`end`)&&a()})};function _(e,t){return g(`all`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>e)),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const v=e=>e.then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}));function y(e,t){return g(`allSettled`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>v(e))),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const b=e=>e>0?e:0,x=(e={})=>{let t=b(e.base??100),n=e.factor??2,r=b(e.max??1/0),i=e.jitter??!1;return e=>{let a=b(Math.min(r,t*n**(e-1)));return i?Math.random()*a||0:a}},S=(n,r)=>n.signal.aborted?Promise.reject(n.signal.reason):new Promise((i,a)=>{let o=[],s=`pending`,c=t=>{try{t()}catch(t){e(`cancel cleanup failed`,t)}},l=t(n,e=>{s=`cancelled`;for(let e of o.reverse())c(e);a(e)}),u=e=>(...t)=>{s===`pending`&&(s=`settled`,l(),o.length=0,e(...t))},d=e=>{s===`pending`?o.push(e):s===`cancelled`&&c(e)};try{r({resolve:u(i),reject:u(a),onCancel:d})}catch(e){u(a)(e)}}),C=e=>t=>{let n=t.addContext,r=Object.entries(e);return t.addContext=e=>{n?.(e);for(let[t,n]of r)Object.assign(e,{[t]:(...t)=>n(e,...t)})},t},w=(e,n,r,i)=>{if(e.signal.aborted)return Promise.resolve();let a=i.leading??!1,c=i.waitForFn??!1;return u(`poll`,e,e=>new Promise((i,l)=>{let u=0,f=null,p=()=>{f!==null&&(o(f),f=null)},m=e=>{try{f=s(h,typeof r==`function`?r(e):r)}catch(e){p(),l(e)}},h=()=>{f=null,c||m(u+1),g()},g=()=>{let t=u++;d(e,e=>n(e,t)).then(()=>{c&&!e.signal.aborted&&m(u)},e=>{p(),l(e)})};t(e,p),a?(g(),c||m(u)):m(0)})).catch(t=>{if(!e.signal.aborted)throw t})};function T(e,t,n,r={}){if(typeof e!=`object`){let r=t,i=n??{};return(t,n)=>w(n,p(r,t),e,i)}let i=t;return w(e,(e,t)=>i(t),n,r)}function E(e,t){let n=m(t);return Object.keys(t).length===0?Promise.resolve(n):g(`race`,e,t,async e=>{let[t,r]=await Promise.race(e.map(([e,t])=>t.then(t=>[e,t])));return n[t]=r,n},`end`)}const D=(e,t,n)=>typeof e==`function`?e(t,n):e,O=e=>({times:e.times??3,delay:e.delay??0,shouldRetry:e.shouldRetry??(()=>!0)}),k=(e,t,n)=>u(`retry`,e,async e=>{let{times:r,delay:i,shouldRetry:a}=O(n);for(let n=1;;n++)try{return await d(e,e=>t(e,n))}catch(t){if(e.signal.throwIfAborted(),!(n<r)||!a(t,n))throw t;let o=D(i,n,t);o>0&&await c(e,o)}});function A(e,t,n={}){if(typeof e==`function`){let n=e;return(e,r)=>k(r,p(n,e),t??{})}let r=t;return k(e,(e,t)=>r(t),n)}function j(e,n,r={}){return u(`take`,e,i=>new Promise((a,o)=>{let{predicate:s}=r,c=[],l=()=>{for(let e of c)e()},u=e=>{l(),o(e)};c.push(e.on(n,e=>{(!s||s(e))&&(l(),a(e))})),c.push(t(i,u)),c.push(t({signal:r.signal},u))}))}const M=(e,t,i)=>u(`timeout`,e,async e=>{let a=r(e),c=s(()=>a.ctx.abort(new DOMException(`Timed out after ${t}ms`,`TimeoutError`)),t);try{return await l(Promise.resolve(n(a.ctx,`run`,()=>i(a.ctx))),a.ctx)}finally{o(c),a.unlink()}});function N(e,t,n){if(typeof e==`number`){let n=t;return(t,r)=>M(r,e,p(n,t))}let r=t,i=n;return M(e,r,e=>i({signal:e.signal,abort:e.abort}))}export{_ as all,y as allSettled,x as backoff,S as cancellable,c as delay,C as effectsPlugin,t as onAbort,T as poll,E as race,A as retry,j as take,N as timeout};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
|
|
1
|
+
import { A as HandlerRef, B as EventMap, C as Emit, D as EventPayload, E as EventLike, F as commandCall, G as Trace, H as PayloadOf, I as createBus, J as UnsubscribeCallback, K as TraceEvent, L as Tracer, M as On, N as WithContext, O as EventsOf, P as WithType, R as anyEventType, S as ContextOption, T as EventKey, U as Phase, V as Keys, W as Task, _ as Command, b as Context, g as BusOptions, h as Bus, i as WithPayload, j as Off, k as Handler, m as AnyEvent, p as Action, q as TraceLogger, v as CommandCall, w as Emittable, x as ContextOf, y as Commands, z as EffectName } from "./action-creator-c292nK7v.js";
|
|
2
|
+
import { n as NoClash, r as contextPlugin, t as ContextTask } from "./context-plugin-1pYmSQEG.js";
|
|
3
|
+
export { type Action, type AnyEvent, type Bus, type BusOptions, type Command, type CommandCall, type Commands, type Context, type ContextOf, type ContextOption, type ContextTask, type EffectName, type Emit, type Emittable, type EventKey, type EventLike, type EventMap, type EventPayload, type EventsOf, type Handler, type HandlerRef, type Keys, type NoClash, type Off, type On, type PayloadOf, type Phase, type Task, type Trace, type TraceEvent, type TraceLogger, type Tracer, type UnsubscribeCallback, type WithContext, type WithPayload, type WithType, anyEventType, commandCall, contextPlugin, createBus };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{i as e,n as t,t as n}from"./bus-BAs9x7IQ.js";const r=e=>typeof e==`function`,i=e=>({type:Reflect.get(e,`type`),payload:Reflect.get(e,`payload`)}),a=e=>t=>{let n=t.addContext;return t.addContext=t=>{n?.(t);let a=r(e)?e(i(t)):e;for(let[e,n]of Object.entries(a))e in t||Reflect.set(t,e,n)},t};export{e as anyEventType,n as commandCall,a as contextPlugin,t as createBus};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as EventMap, H as PayloadOf, J as UnsubscribeCallback, W as Task, _ as Command, b as Context, c as WithScope, h as Bus, o as Scope, v as CommandCall } from "./action-creator-c292nK7v.js";
|
|
2
|
+
import { n as Scoped, t as FieldsOfScope } from "./types-mLaAx-EZ.js";
|
|
2
3
|
//#region src/actions/command.d.ts
|
|
3
4
|
/** What `createCommand` returns: a command that also tells whether an action is of its type. */
|
|
4
5
|
type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
@@ -12,6 +13,10 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
12
13
|
payload: P;
|
|
13
14
|
};
|
|
14
15
|
};
|
|
16
|
+
/** `Made`, called so that its calls carry the scope fields `F`; `Made` itself when there are none. */
|
|
17
|
+
type CarryingCalls<Made, P, R, F> = [unknown] extends [F] ? Made : ((payload: P) => CommandCall<P, R> & WithScope<F>) & Made & WithScope<F>;
|
|
18
|
+
/** A command made with a scope: its calls carry the fields of that scope, for the checker. */
|
|
19
|
+
type ScopedCommand<P, R, T extends string, F> = ((payload: P) => CommandCall<P, R> & WithScope<F>) & MadeCommand<P, R, T> & WithScope<F>;
|
|
15
20
|
/**
|
|
16
21
|
* Creates a command: a typed request for a result. Calling it builds
|
|
17
22
|
* `{ type, payload }` like `createAction`. `bus.emit(command(payload))` (or
|
|
@@ -28,6 +33,11 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
28
33
|
* `command.match(action)` tells whether an action has the type of the command,
|
|
29
34
|
* as it does for an action creator.
|
|
30
35
|
*
|
|
36
|
+
* A scope as the third argument, `{ cache, effects: { race } }`, puts those fields on
|
|
37
|
+
* the context of the handler and of the listeners of the command; the handler
|
|
38
|
+
* sees them typed. It works on a bus that uses `scopePlugin` from
|
|
39
|
+
* `nanoeffects/scope` and is ignored on any other.
|
|
40
|
+
*
|
|
31
41
|
* @example
|
|
32
42
|
* ```ts
|
|
33
43
|
* const getUser = createCommand("user/get", (id: string, { signal }) =>
|
|
@@ -42,7 +52,8 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
42
52
|
* commands.handle(getUser, async () => fakeUser); // in a test
|
|
43
53
|
* ```
|
|
44
54
|
*/
|
|
45
|
-
declare
|
|
55
|
+
declare function createCommand<P = void, R = void, T extends string = string, E extends EventMap = EventMap>(type: T, handler?: Task<P, E, R>): MadeCommand<P, R, T>;
|
|
56
|
+
declare function createCommand<P, R, T extends string, S extends Scope = Record<never, never>>(type: T, handler: Task<P, Scoped<EventMap, S>, R>, scope: S): ScopedCommand<P, R, T, FieldsOfScope<EventMap, S>>;
|
|
46
57
|
/** A command (or its type) with the handler to bind to it; `bindHandler` makes one. */
|
|
47
58
|
type Binding<E extends EventMap = EventMap> = readonly [Command<never, unknown> | string, Task<never, E, unknown>];
|
|
48
59
|
/**
|
|
@@ -104,7 +115,10 @@ type ModuleContext<E extends EventMap = EventMap> = Context<E> & {
|
|
|
104
115
|
* returned function undoes just this call, e.g. for what was added later from
|
|
105
116
|
* a listener.
|
|
106
117
|
*/
|
|
107
|
-
use(...items: Array<Module<E> |
|
|
118
|
+
use(...items: Array<Module<E> | {
|
|
119
|
+
readonly type: string;
|
|
120
|
+
(payload: never): unknown;
|
|
121
|
+
}>): UnsubscribeCallback;
|
|
108
122
|
/**
|
|
109
123
|
* Starts a background task that lives as long as the module: it is aborted
|
|
110
124
|
* on unmount, and an error of it is left unhandled, as in any handler.
|
|
@@ -114,6 +128,8 @@ type ModuleContext<E extends EventMap = EventMap> = Context<E> & {
|
|
|
114
128
|
type Module<E extends EventMap = EventMap> = {
|
|
115
129
|
readonly name: string;
|
|
116
130
|
readonly setup: (m: ModuleContext<E>) => void;
|
|
131
|
+
/** Fields for everything the module owns; see `scopePlugin`. */
|
|
132
|
+
readonly scope?: Scope;
|
|
117
133
|
};
|
|
118
134
|
/**
|
|
119
135
|
* Describes one domain of an app: the commands it handles, the events it
|
|
@@ -134,7 +150,8 @@ type Module<E extends EventMap = EventMap> = {
|
|
|
134
150
|
* });
|
|
135
151
|
* ```
|
|
136
152
|
*/
|
|
137
|
-
declare
|
|
153
|
+
declare function createModule<E extends EventMap = EventMap>(name: string, setup: (m: ModuleContext<E>) => void): Module<E>;
|
|
154
|
+
declare function createModule<E extends EventMap, S extends Scope = Record<never, never>>(name: string, setup: (m: ModuleContext<Scoped<E, S>>) => void, scope: S): Module<E>;
|
|
138
155
|
type Registry<E extends EventMap> = ReturnType<ReturnType<typeof commandsPlugin<E>>>;
|
|
139
156
|
/** What `modulePlugin` returns. */
|
|
140
157
|
type ModuleApi<E extends EventMap = EventMap> = {
|
|
@@ -146,6 +163,13 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
146
163
|
isMounted(module: Module<E>): boolean;
|
|
147
164
|
/** Unmounts every module; a disposed app cannot mount modules. */
|
|
148
165
|
dispose(): void;
|
|
166
|
+
/**
|
|
167
|
+
* `createModule` with the event map of this bus: the module sees the context
|
|
168
|
+
* fields of the bus without a type argument. It returns a plain module, not
|
|
169
|
+
* mounted, with no link to this bus.
|
|
170
|
+
*/
|
|
171
|
+
createModule(name: string, setup: (m: ModuleContext<E>) => void): Module<E>;
|
|
172
|
+
createModule<S extends Scope = Record<never, never>>(name: string, setup: (m: ModuleContext<Scoped<E, S>>) => void, scope: S): Module<E>;
|
|
149
173
|
};
|
|
150
174
|
/**
|
|
151
175
|
* The plugin that assembles an app from modules: `bus.use(modulePlugin(modules))`
|
|
@@ -171,6 +195,11 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
171
195
|
* const unmount = app.mount(orderModule); // later, e.g. after a lazy import
|
|
172
196
|
* unmount(); // or app.unmount(orderModule)
|
|
173
197
|
*
|
|
198
|
+
* // a module made from the app has the context fields of the bus, typed
|
|
199
|
+
* const userModule = app.createModule("user", (m) => {
|
|
200
|
+
* m.on("loaded", (user, { store }) => store.put(user));
|
|
201
|
+
* });
|
|
202
|
+
*
|
|
174
203
|
* bus.emit(getUser, "1");
|
|
175
204
|
* app.commands.handle(getUser, fakeUser); // in a test
|
|
176
205
|
* app.dispose();
|
|
@@ -178,4 +207,4 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
178
207
|
*/
|
|
179
208
|
declare const modulePlugin: <E extends EventMap>(modules?: readonly Module<E>[]) => (bus: Bus<E>) => ModuleApi<E>;
|
|
180
209
|
//#endregion
|
|
181
|
-
export { modulePlugin as a,
|
|
210
|
+
export { modulePlugin as a, MadeCommand as c, createCommand as d, createModule as i, bindHandler as l, ModuleApi as n, Binding as o, ModuleContext as r, CarryingCalls as s, Module as t, commandsPlugin as u };
|
|
@@ -1,3 +1,29 @@
|
|
|
1
|
+
//#region src/core/types.d.ts
|
|
2
|
+
type PayloadOf<P> = undefined extends P ? [payload?: P] : [payload: P];
|
|
3
|
+
type EventMap = Record<string, unknown>;
|
|
4
|
+
type Keys<E> = keyof E & string;
|
|
5
|
+
type Task<P, E extends EventMap, R = unknown> = (payload: P, ctx: Context<E>) => R;
|
|
6
|
+
type EffectName = "every" | "latest" | "leading" | "debounce" | "throttle" | "run" | "all" | "race" | "retry" | "timeout" | "poll" | "take" | "queue" | "allSettled" | "command";
|
|
7
|
+
type Phase = "start" | "done" | "error" | "cancel" | "drop";
|
|
8
|
+
type TraceEvent<E = Record<string, unknown>> = { [K in Keys<E>]: {
|
|
9
|
+
id: number;
|
|
10
|
+
parent?: number;
|
|
11
|
+
type: K;
|
|
12
|
+
effect: EffectName;
|
|
13
|
+
phase: Phase;
|
|
14
|
+
payload: E[K];
|
|
15
|
+
error?: unknown;
|
|
16
|
+
}; }[Keys<E>];
|
|
17
|
+
/**
|
|
18
|
+
* The contract of every trace logger: receives each task phase of a bus.
|
|
19
|
+
* Adapters in `nanoeffects/trace` are factories that return one; pass it
|
|
20
|
+
* through `createTracer` to `createBus({ trace })`.
|
|
21
|
+
*/
|
|
22
|
+
type TraceLogger<E = Record<string, unknown>> = (event: TraceEvent<E>) => void;
|
|
23
|
+
/** One logger or several; a throwing logger never breaks the task or the others. */
|
|
24
|
+
type Trace<E = Record<string, unknown>> = TraceLogger<E> | readonly TraceLogger<E>[];
|
|
25
|
+
type UnsubscribeCallback = () => void;
|
|
26
|
+
//#endregion
|
|
1
27
|
//#region src/core/store.d.ts
|
|
2
28
|
declare const anyEventType = "*";
|
|
3
29
|
//#endregion
|
|
@@ -83,14 +109,21 @@ type Emit<E extends EventMap> = {
|
|
|
83
109
|
<K extends EventKey<E>>(event: K, ...payload: PayloadOf<E[K]>): void;
|
|
84
110
|
/** Before Handler: a command is callable too, and must return its result type. */
|
|
85
111
|
<P, R>(command: Command<P, R>, ...payload: PayloadOf<P>): R;
|
|
86
|
-
|
|
112
|
+
/** A scope as the second argument replaces context fields for the tasks of this emit; see `scopePlugin`. */
|
|
113
|
+
<P, R, F>(call: CommandCall<P, R> & WithScope<F>, scope?: EmitScope<E, F>): R;
|
|
114
|
+
<P, R>(call: CommandCall<P, R>, scope?: EmitScope<E>): R;
|
|
87
115
|
<K extends EventKey<E>, R>(event: Handler<E, R, K>, ...payload: PayloadOf<E[K]>): R;
|
|
88
|
-
(event: EventLike<E>): void;
|
|
116
|
+
<F>(event: EventLike<E> & WithScope<F>, scope?: EmitScope<E, F>): void;
|
|
117
|
+
(event: EventLike<E>, scope?: EmitScope<E>): void;
|
|
89
118
|
};
|
|
90
119
|
type On<E extends EventMap> = {
|
|
91
120
|
(event: AnyEvent, fn: Task<EventPayload<E>, E>): UnsubscribeCallback;
|
|
92
121
|
<K extends EventKey<E>>(event: K, fn: Task<E[K], E>): UnsubscribeCallback;
|
|
93
122
|
/** An action creator without a payload type: the payload comes from the event map. */
|
|
123
|
+
/** The creators and commands that carry a scope come first: the handler sees their fields. */
|
|
124
|
+
<K extends EventKey<E>, F>(creator: FreeActionCreator<K, F> & WithScope<F>, fn: Task<E[K], WithFields<E, F>>): UnsubscribeCallback;
|
|
125
|
+
<P, F>(creator: ActionCreator<P, string, PayloadOf<P>, F> & WithScope<F>, fn: Task<P, WithFields<E, F>>): UnsubscribeCallback;
|
|
126
|
+
<P, F>(command: Command<P, unknown> & WithScope<F>, fn: Task<P, WithFields<E, F>>): UnsubscribeCallback;
|
|
94
127
|
<K extends EventKey<E>>(creator: FreeActionCreator<K>, fn: Task<E[K], E>): UnsubscribeCallback;
|
|
95
128
|
/** An action creator: the payload comes from it, so an event map is not needed. */
|
|
96
129
|
<P>(creator: ActionCreator<P>, fn: Task<P, E>): UnsubscribeCallback;
|
|
@@ -157,6 +190,18 @@ type Context<E extends EventMap> = EventLike<E> & ContextOf<E> & {
|
|
|
157
190
|
/** Child task: aborted with the parent; errors propagate to the parent. */
|
|
158
191
|
run<P, R>(fn: Task<P, E, R>, ...args: PayloadOf<P>): Promise<Awaited<R>>;
|
|
159
192
|
};
|
|
193
|
+
/**
|
|
194
|
+
* The event map of a bus, with the context fields that plugins added. Use it to
|
|
195
|
+
* name the types of a bus in other files: `type AppEvents = EventsOf<typeof bus>`.
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* ```ts
|
|
199
|
+
* const bus = createBus<Events>().use(effectsPlugin({ race }));
|
|
200
|
+
* type AppEvents = EventsOf<typeof bus>;
|
|
201
|
+
* type AppContext = Context<AppEvents>; // has `race`
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
type EventsOf<B> = B extends Bus<infer E extends EventMap> ? E : never;
|
|
160
205
|
interface Bus<E extends EventMap> {
|
|
161
206
|
on: On<E>;
|
|
162
207
|
/**
|
|
@@ -173,10 +218,16 @@ interface Bus<E extends EventMap> {
|
|
|
173
218
|
*/
|
|
174
219
|
use<R>(plugin: (bus: Bus<E>) => R): R;
|
|
175
220
|
/** `BusOptions.context` and `.trace`, and `commands`, for what makes tasks of its own, like `modulePlugin`. */
|
|
176
|
-
readonly
|
|
221
|
+
readonly ctx?: ContextOption<E> | undefined;
|
|
177
222
|
/** What runs the commands; `commandsPlugin` and `modulePlugin` set it. Without one a command runs its own handler. */
|
|
178
223
|
commands?: Commands | undefined;
|
|
179
224
|
readonly trace?: Tracer | undefined;
|
|
225
|
+
/** Called with every new task context to add fields to it, for what needs the task, like `effectsPlugin`. Chain to the previous one. */
|
|
226
|
+
addContext?: ((ctx: object) => void) | undefined;
|
|
227
|
+
/** Puts the fields of a module's scope on the context of one of its tasks; `scopePlugin` sets it. Without it a module's scope is ignored. */
|
|
228
|
+
applyScope?: ((ctx: object, scope: Scope) => void) | undefined;
|
|
229
|
+
/** Wraps a handler so it runs with the fields of a module's scope; `scopePlugin` sets it. */
|
|
230
|
+
fitScope?: ((scope: Scope, fn: (payload: never, ctx: never) => unknown) => unknown) | undefined;
|
|
180
231
|
}
|
|
181
232
|
type BusOptions<E extends EventMap> = {
|
|
182
233
|
/** Tracing of every task phase; make it with `createTracer` from `nanoeffects/trace`. */
|
|
@@ -214,31 +265,76 @@ type BusOptions<E extends EventMap> = {
|
|
|
214
265
|
};
|
|
215
266
|
declare const createBus: <Events extends EventMap>(options?: BusOptions<Events>) => Bus<Events>;
|
|
216
267
|
//#endregion
|
|
217
|
-
//#region src/core/types.d.ts
|
|
218
|
-
|
|
219
|
-
type
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
type
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
type: K;
|
|
228
|
-
effect: EffectName;
|
|
229
|
-
phase: Phase;
|
|
230
|
-
payload: E[K];
|
|
231
|
-
error?: unknown;
|
|
232
|
-
}; }[Keys<E>];
|
|
268
|
+
//#region src/core/effect-types.d.ts
|
|
269
|
+
/** What an effect needs of the task it runs for: its signal. A task context fits, and so does `{ signal }`. */
|
|
270
|
+
type Signaled = {
|
|
271
|
+
signal: AbortSignal;
|
|
272
|
+
};
|
|
273
|
+
/** An effect: a function whose first parameter takes `{ signal }`, like `retry(ctx, fn)`. */
|
|
274
|
+
type SignalFirst = (ctx: Signaled, ...args: never[]) => unknown;
|
|
275
|
+
/** The effects of a scope or of `effectsPlugin`, by the name they get on the context. */
|
|
276
|
+
type Effects = Record<string, SignalFirst>;
|
|
277
|
+
declare const bound: unique symbol;
|
|
233
278
|
/**
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
279
|
+
* An effect that says what it looks like once it is bound to a task (without
|
|
280
|
+
* the `ctx` parameter). A plain effect has its first parameter removed, which
|
|
281
|
+
* erases its generics; this type keeps them, because `F` is carried as it is.
|
|
282
|
+
* It changes the checker only: the function is the same at run time.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* ```ts
|
|
286
|
+
* type First = <T>(items: T[]) => T; // how a handler calls it
|
|
287
|
+
* const first: Effect<First> = (ctx, items) => items[0];
|
|
288
|
+
* ```
|
|
237
289
|
*/
|
|
238
|
-
type
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
290
|
+
type Effect<F extends (...args: never[]) => unknown> = ((ctx: Signaled, ...args: Parameters<F>) => ReturnType<F>) & {
|
|
291
|
+
readonly [bound]?: F;
|
|
292
|
+
};
|
|
293
|
+
/** The bound form of a plain effect: the first parameter is gone, and so are its generics. */
|
|
294
|
+
type Strip<F> = F extends ((ctx: never, ...args: infer A) => infer R) ? (...args: A) => R : never;
|
|
295
|
+
/** The bound type an `Effect<F>` carries, or `Strip` of a plain function. */
|
|
296
|
+
type BoundForm<F> = typeof bound extends keyof F ? NonNullable<F[typeof bound & keyof F]> : Strip<F>;
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/core/scope-types.d.ts
|
|
299
|
+
declare const scopeFields: unique symbol;
|
|
300
|
+
/** What an action creator, a command or a call knows of the scope it was made with: its fields, for the checker. */
|
|
301
|
+
type WithScope<F> = {
|
|
302
|
+
readonly [scopeFields]: F;
|
|
303
|
+
};
|
|
304
|
+
/** `X`, marked with the scope fields `F` it carries; `X` itself when there are none, so unscoped types stay as they were. */
|
|
305
|
+
type Carrying<X, F> = X & ([unknown] extends [F] ? unknown : WithScope<F>);
|
|
306
|
+
/**
|
|
307
|
+
* What a task gets on top of the context of its bus, for one place: every key
|
|
308
|
+
* is a context value and goes on `ctx` as it is, except `effects`, whose
|
|
309
|
+
* functions (each takes `{ signal }` first) are bound to the task. Made work by
|
|
310
|
+
* `scopePlugin` from `nanoeffects/scope`; without it a scope is ignored.
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* ```ts
|
|
314
|
+
* const scope = { cache, effects: { race } }; // ctx.cache, and ctx.race bound to the task
|
|
315
|
+
* ```
|
|
316
|
+
*/
|
|
317
|
+
type Scope = {
|
|
318
|
+
readonly effects?: Effects;
|
|
319
|
+
readonly [field: string]: unknown;
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* What a call may replace of what it already has: the fields of the bus and
|
|
323
|
+
* those of its own scope, and its effects. The types must match the ones they
|
|
324
|
+
* replace; a field that neither declares has no type to check against, so it is
|
|
325
|
+
* an error.
|
|
326
|
+
*/
|
|
327
|
+
type EmitScope<E extends EventMap, F = unknown> = ([unknown] extends [ContextOf<E> & F] ? unknown : Partial<ContextOf<E> & F>) & {
|
|
328
|
+
effects?: Partial<Effects>;
|
|
329
|
+
};
|
|
330
|
+
/** `A` with the fields of `B` replacing those of the same name, not intersected with them. */
|
|
331
|
+
type Merge<A, B> = Omit<A, keyof B> & B;
|
|
332
|
+
/**
|
|
333
|
+
* The event map `E` with the fields `F` of a scope on top of its context
|
|
334
|
+
* fields; `E` itself when there are none. A field of the scope replaces the
|
|
335
|
+
* one of the bus in the type too.
|
|
336
|
+
*/
|
|
337
|
+
type WithFields<E extends EventMap, F> = [unknown] extends [F] ? E : Omit<E, keyof WithContext<object>> & WithContext<Merge<ContextOf<E>, F>>;
|
|
242
338
|
//#endregion
|
|
243
339
|
//#region src/core/action-creator.d.ts
|
|
244
340
|
type WithPayload<E extends EventMap, K extends Keys<E>> = undefined extends E[K] ? {
|
|
@@ -257,15 +353,15 @@ type Free = typeof free;
|
|
|
257
353
|
* it is given, and the bus checks it against its event map, so
|
|
258
354
|
* `createAction("user/loaded")` needs no generics and keeps its literal type.
|
|
259
355
|
*/
|
|
260
|
-
interface FreeActionCreator<T extends string> {
|
|
261
|
-
(): {
|
|
356
|
+
interface FreeActionCreator<T extends string, F = unknown> {
|
|
357
|
+
(): Carrying<{
|
|
262
358
|
type: T;
|
|
263
359
|
payload: undefined;
|
|
264
|
-
}
|
|
265
|
-
<P>(payload: P): {
|
|
360
|
+
}, F>;
|
|
361
|
+
<P>(payload: P): Carrying<{
|
|
266
362
|
type: T;
|
|
267
363
|
payload: P;
|
|
268
|
-
}
|
|
364
|
+
}, F>;
|
|
269
365
|
readonly type: T;
|
|
270
366
|
/** Tells whether an action is one of this creator. */
|
|
271
367
|
match(action: {
|
|
@@ -281,8 +377,8 @@ interface FreeActionCreator<T extends string> {
|
|
|
281
377
|
* Makes actions of one type. It also works as the event of that type:
|
|
282
378
|
* `bus.on(creator, fn)` and `bus.emit(creator(payload))`.
|
|
283
379
|
*/
|
|
284
|
-
interface ActionCreator<P = void, T extends string = string, A extends unknown[] = PayloadOf<P
|
|
285
|
-
(...args: A): Made<P, T>;
|
|
380
|
+
interface ActionCreator<P = void, T extends string = string, A extends unknown[] = PayloadOf<P>, F = unknown> {
|
|
381
|
+
(...args: A): Carrying<Made<P, T>, F>;
|
|
286
382
|
readonly type: T;
|
|
287
383
|
/** Tells whether an action is one of this creator, and narrows its type. */
|
|
288
384
|
match(action: {
|
|
@@ -292,4 +388,4 @@ interface ActionCreator<P = void, T extends string = string, A extends unknown[]
|
|
|
292
388
|
toString(): T;
|
|
293
389
|
}
|
|
294
390
|
//#endregion
|
|
295
|
-
export {
|
|
391
|
+
export { On as A, PayloadOf as B, EventKey as C, Handler as D, EventsOf as E, Tracer as F, TraceLogger as G, Task as H, anyEventType as I, UnsubscribeCallback as K, EffectName as L, WithType as M, commandCall as N, HandlerRef as O, createBus as P, EventMap as R, Emittable as S, EventPayload as T, Trace as U, Phase as V, TraceEvent as W, Commands as _, Scope as a, ContextOption as b, BoundForm as c, Action as d, AnyEvent as f, CommandCall as g, Command as h, WithPayload as i, WithContext as j, Off as k, Effect as l, BusOptions as m, Free as n, WithFields as o, Bus as p, FreeActionCreator as r, WithScope as s, ActionCreator as t, Effects as u, Context as v, EventLike as w, Emit as x, ContextOf as y, Keys as z };
|
|
@@ -1,5 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as PayloadOf, C as EventKey, H as Task, K as UnsubscribeCallback, R as EventMap, a as Scope, g as CommandCall, h as Command, n as Free, o as WithFields, p as Bus, r as FreeActionCreator, s as WithScope, t as ActionCreator, u as Effects, v as Context } from "./action-creator-DKG_sIia.js";
|
|
2
|
+
import { t as BoundOf } from "./plugin-B0AXKusc.js";
|
|
3
|
+
//#region src/scope/types.d.ts
|
|
4
|
+
type BoundEffects<E extends EventMap, S extends Scope> = S extends {
|
|
5
|
+
effects: infer H extends Effects;
|
|
6
|
+
} ? BoundOf<H, E> : unknown;
|
|
7
|
+
/** The fields a scope gives a task: its values as they are and its `effects` bound; `unknown` for an empty scope. */
|
|
8
|
+
type FieldsOfScope<E extends EventMap, S extends Scope> = [keyof S] extends [never] ? unknown : Omit<S, "effects"> & BoundEffects<E, S>;
|
|
9
|
+
/**
|
|
10
|
+
* The event map `E` with the fields of a scope on top of its context fields.
|
|
11
|
+
* A field the scope sets replaces the one of the bus in the type too.
|
|
12
|
+
*/
|
|
13
|
+
type Scoped<E extends EventMap, S extends Scope> = WithFields<E, FieldsOfScope<E, S>>;
|
|
14
|
+
//#endregion
|
|
2
15
|
//#region src/actions/action.d.ts
|
|
16
|
+
type ScopedCreator<P, T extends string, F> = [P] extends [Free] ? FreeActionCreator<T, F> & WithScope<F> : ActionCreator<P, T, PayloadOf<P>, F> & WithScope<F>;
|
|
3
17
|
/**
|
|
4
18
|
* Creates an action creator, as in Redux Toolkit.
|
|
5
19
|
*
|
|
@@ -12,6 +26,9 @@ import { S as Context, _ as Bus, c as PayloadOf, m as UnsubscribeCallback, n as
|
|
|
12
26
|
* generic: `createAction<User, "user/loaded">("user/loaded")`.
|
|
13
27
|
* - With `prepare` the arguments of the creator can differ from the payload,
|
|
14
28
|
* and both types are inferred.
|
|
29
|
+
* - A scope as the last argument, `{ cache, effects: { race } }`, gives the
|
|
30
|
+
* listeners of its calls those context fields; it works on a bus that uses `scopePlugin`
|
|
31
|
+
* from `nanoeffects/scope` and is ignored on any other.
|
|
15
32
|
*
|
|
16
33
|
* @example
|
|
17
34
|
* ```ts
|
|
@@ -32,6 +49,10 @@ export declare function createAction<P = Free, T extends string = string>(type:
|
|
|
32
49
|
export declare function createAction<A extends unknown[], P, T extends string = string>(type: T, prepare: (...args: A) => {
|
|
33
50
|
payload: P;
|
|
34
51
|
}): ActionCreator<P, T, A>;
|
|
52
|
+
export declare function createAction<P = Free, T extends string = string, S extends Scope = Record<never, never>>(type: T, scope: S): ScopedCreator<P, T, FieldsOfScope<EventMap, S>>;
|
|
53
|
+
export declare function createAction<A extends unknown[], P, T extends string, S extends Scope>(type: T, prepare: (...args: A) => {
|
|
54
|
+
payload: P;
|
|
55
|
+
}, scope: S): ActionCreator<P, T, A, FieldsOfScope<EventMap, S>> & WithScope<FieldsOfScope<EventMap, S>>;
|
|
35
56
|
//#endregion
|
|
36
57
|
//#region src/actions/command.d.ts
|
|
37
58
|
/** What `createCommand` returns: a command that also tells whether an action is of its type. */
|
|
@@ -46,6 +67,10 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
46
67
|
payload: P;
|
|
47
68
|
};
|
|
48
69
|
};
|
|
70
|
+
/** `Made`, called so that its calls carry the scope fields `F`; `Made` itself when there are none. */
|
|
71
|
+
type CarryingCalls<Made, P, R, F> = [unknown] extends [F] ? Made : ((payload: P) => CommandCall<P, R> & WithScope<F>) & Made & WithScope<F>;
|
|
72
|
+
/** A command made with a scope: its calls carry the fields of that scope, for the checker. */
|
|
73
|
+
type ScopedCommand<P, R, T extends string, F> = ((payload: P) => CommandCall<P, R> & WithScope<F>) & MadeCommand<P, R, T> & WithScope<F>;
|
|
49
74
|
/**
|
|
50
75
|
* Creates a command: a typed request for a result. Calling it builds
|
|
51
76
|
* `{ type, payload }` like `createAction`. `bus.emit(command(payload))` (or
|
|
@@ -62,6 +87,11 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
62
87
|
* `command.match(action)` tells whether an action has the type of the command,
|
|
63
88
|
* as it does for an action creator.
|
|
64
89
|
*
|
|
90
|
+
* A scope as the third argument, `{ cache, effects: { race } }`, puts those fields on
|
|
91
|
+
* the context of the handler and of the listeners of the command; the handler
|
|
92
|
+
* sees them typed. It works on a bus that uses `scopePlugin` from
|
|
93
|
+
* `nanoeffects/scope` and is ignored on any other.
|
|
94
|
+
*
|
|
65
95
|
* @example
|
|
66
96
|
* ```ts
|
|
67
97
|
* const getUser = createCommand("user/get", (id: string, { signal }) =>
|
|
@@ -76,7 +106,8 @@ type MadeCommand<P, R, T extends string> = Command<P, R> & {
|
|
|
76
106
|
* commands.handle(getUser, async () => fakeUser); // in a test
|
|
77
107
|
* ```
|
|
78
108
|
*/
|
|
79
|
-
export declare
|
|
109
|
+
export declare function createCommand<P = void, R = void, T extends string = string, E extends EventMap = EventMap>(type: T, handler?: Task<P, E, R>): MadeCommand<P, R, T>;
|
|
110
|
+
export declare function createCommand<P, R, T extends string, S extends Scope = Record<never, never>>(type: T, handler: Task<P, Scoped<EventMap, S>, R>, scope: S): ScopedCommand<P, R, T, FieldsOfScope<EventMap, S>>;
|
|
80
111
|
/** A command (or its type) with the handler to bind to it; `bindHandler` makes one. */
|
|
81
112
|
type Binding<E extends EventMap = EventMap> = readonly [Command<never, unknown> | string, Task<never, E, unknown>];
|
|
82
113
|
/**
|
|
@@ -118,6 +149,41 @@ export declare const commandsPlugin: <E extends EventMap>(bindings?: readonly Bi
|
|
|
118
149
|
};
|
|
119
150
|
};
|
|
120
151
|
//#endregion
|
|
152
|
+
//#region src/actions/emitter.d.ts
|
|
153
|
+
/** What `emitterPlugin` adds to the bus. */
|
|
154
|
+
type EmitterApi<E extends EventMap> = {
|
|
155
|
+
/**
|
|
156
|
+
* Turns an action creator into a function that emits its action on this
|
|
157
|
+
* bus, to pass as a callback. The function takes what the creator takes.
|
|
158
|
+
*/
|
|
159
|
+
emitter: {
|
|
160
|
+
/** A creator without a payload type: the payload comes from the event map. */
|
|
161
|
+
<K extends EventKey<E>>(creator: FreeActionCreator<K>): (...payload: PayloadOf<E[K]>) => void;
|
|
162
|
+
<P, T extends string, A extends unknown[]>(creator: ActionCreator<P, T, A>): (...args: A) => void;
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Adds `bus.emitter(creator)`: a function that emits the action of `creator`
|
|
167
|
+
* on this bus. Use it where something wants a callback, such as the
|
|
168
|
+
* subscription of a state manager, instead of `(value) => bus.emit(creator(value))`.
|
|
169
|
+
* The creator stays a plain `createAction`, so `bus.emit(creator(value))` and
|
|
170
|
+
* `bus.on(creator, …)` work as before. Returns the same bus.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts
|
|
174
|
+
* import { createBus } from "nanoeffects";
|
|
175
|
+
* import { createAction, emitterPlugin } from "nanoeffects/actions";
|
|
176
|
+
*
|
|
177
|
+
* const bus = createBus().use(emitterPlugin());
|
|
178
|
+
* const nameChanged = createAction<string>("name/changed");
|
|
179
|
+
* const emitNameChanged = bus.emitter(nameChanged);
|
|
180
|
+
*
|
|
181
|
+
* // nanostores: the store calls it with the new value
|
|
182
|
+
* $name.listen(emitNameChanged);
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
export declare const emitterPlugin: () => <E extends EventMap>(bus: Bus<E>) => Bus<E> & EmitterApi<E>;
|
|
186
|
+
//#endregion
|
|
121
187
|
//#region src/actions/job.d.ts
|
|
122
188
|
type Creator = {
|
|
123
189
|
(...args: never[]): {
|
|
@@ -142,6 +208,9 @@ type Job<P, R, T extends string, S extends Outcome, F extends Outcome> = MadeCom
|
|
|
142
208
|
* effect. It returns the command, with the two actions on it: `job.success` and
|
|
143
209
|
* `job.fail`.
|
|
144
210
|
*
|
|
211
|
+
* A scope as the last argument, `{ cache, effects: { race } }`, gives the handler
|
|
212
|
+
* and the listeners of the outcome those context fields; see `scopePlugin`.
|
|
213
|
+
*
|
|
145
214
|
* `success` and `fail` are a type string, from which the job makes an action
|
|
146
215
|
* creator with `createAction`, or an action creator that exists already, which
|
|
147
216
|
* is used and returned as it is. A missing one is made with the type
|
|
@@ -166,12 +235,14 @@ type Job<P, R, T extends string, S extends Outcome, F extends Outcome> = MadeCom
|
|
|
166
235
|
* bus.emit(loadUser("1")); // loadUser.success(user) or loadUser.fail(error) comes later
|
|
167
236
|
* ```
|
|
168
237
|
*/
|
|
169
|
-
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail
|
|
238
|
+
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail`, X extends Scope = Record<never, never>>(type: T, handler?: Task<P, Scoped<E, X>, R>, outcomes?: {
|
|
170
239
|
/** Gets the result when the handler succeeds: a type to make an action creator of, or an action creator. */
|
|
171
240
|
success?: S;
|
|
172
241
|
/** Gets the error when the handler fails: a type to make an action creator of, or an action creator. */
|
|
173
242
|
fail?: F;
|
|
174
|
-
}
|
|
243
|
+
},
|
|
244
|
+
/** Context values and `effects` for the handler and for the listeners of the outcome; see `scopePlugin`. */
|
|
245
|
+
scope?: X) => CarryingCalls<Job<P, R, T, S, F>, P, Promise<Awaited<R> | undefined>, FieldsOfScope<E, X>>;
|
|
175
246
|
//#endregion
|
|
176
247
|
//#region src/actions/module.d.ts
|
|
177
248
|
/**
|
|
@@ -193,7 +264,10 @@ type ModuleContext<E extends EventMap = EventMap> = Context<E> & {
|
|
|
193
264
|
* returned function undoes just this call, e.g. for what was added later from
|
|
194
265
|
* a listener.
|
|
195
266
|
*/
|
|
196
|
-
use(...items: Array<Module<E> |
|
|
267
|
+
use(...items: Array<Module<E> | {
|
|
268
|
+
readonly type: string;
|
|
269
|
+
(payload: never): unknown;
|
|
270
|
+
}>): UnsubscribeCallback;
|
|
197
271
|
/**
|
|
198
272
|
* Starts a background task that lives as long as the module: it is aborted
|
|
199
273
|
* on unmount, and an error of it is left unhandled, as in any handler.
|
|
@@ -203,6 +277,8 @@ type ModuleContext<E extends EventMap = EventMap> = Context<E> & {
|
|
|
203
277
|
type Module<E extends EventMap = EventMap> = {
|
|
204
278
|
readonly name: string;
|
|
205
279
|
readonly setup: (m: ModuleContext<E>) => void;
|
|
280
|
+
/** Fields for everything the module owns; see `scopePlugin`. */
|
|
281
|
+
readonly scope?: Scope;
|
|
206
282
|
};
|
|
207
283
|
/**
|
|
208
284
|
* Describes one domain of an app: the commands it handles, the events it
|
|
@@ -223,7 +299,8 @@ type Module<E extends EventMap = EventMap> = {
|
|
|
223
299
|
* });
|
|
224
300
|
* ```
|
|
225
301
|
*/
|
|
226
|
-
export declare
|
|
302
|
+
export declare function createModule<E extends EventMap = EventMap>(name: string, setup: (m: ModuleContext<E>) => void): Module<E>;
|
|
303
|
+
export declare function createModule<E extends EventMap, S extends Scope = Record<never, never>>(name: string, setup: (m: ModuleContext<Scoped<E, S>>) => void, scope: S): Module<E>;
|
|
227
304
|
type Registry<E extends EventMap> = ReturnType<ReturnType<typeof commandsPlugin<E>>>;
|
|
228
305
|
/** What `modulePlugin` returns. */
|
|
229
306
|
type ModuleApi<E extends EventMap = EventMap> = {
|
|
@@ -235,6 +312,13 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
235
312
|
isMounted(module: Module<E>): boolean;
|
|
236
313
|
/** Unmounts every module; a disposed app cannot mount modules. */
|
|
237
314
|
dispose(): void;
|
|
315
|
+
/**
|
|
316
|
+
* `createModule` with the event map of this bus: the module sees the context
|
|
317
|
+
* fields of the bus without a type argument. It returns a plain module, not
|
|
318
|
+
* mounted, with no link to this bus.
|
|
319
|
+
*/
|
|
320
|
+
createModule(name: string, setup: (m: ModuleContext<E>) => void): Module<E>;
|
|
321
|
+
createModule<S extends Scope = Record<never, never>>(name: string, setup: (m: ModuleContext<Scoped<E, S>>) => void, scope: S): Module<E>;
|
|
238
322
|
};
|
|
239
323
|
/**
|
|
240
324
|
* The plugin that assembles an app from modules: `bus.use(modulePlugin(modules))`
|
|
@@ -260,6 +344,11 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
260
344
|
* const unmount = app.mount(orderModule); // later, e.g. after a lazy import
|
|
261
345
|
* unmount(); // or app.unmount(orderModule)
|
|
262
346
|
*
|
|
347
|
+
* // a module made from the app has the context fields of the bus, typed
|
|
348
|
+
* const userModule = app.createModule("user", (m) => {
|
|
349
|
+
* m.on("loaded", (user, { store }) => store.put(user));
|
|
350
|
+
* });
|
|
351
|
+
*
|
|
263
352
|
* bus.emit(getUser, "1");
|
|
264
353
|
* app.commands.handle(getUser, fakeUser); // in a test
|
|
265
354
|
* app.dispose();
|
|
@@ -267,4 +356,4 @@ type ModuleApi<E extends EventMap = EventMap> = {
|
|
|
267
356
|
*/
|
|
268
357
|
export declare const modulePlugin: <E extends EventMap>(modules?: readonly Module<E>[]) => (bus: Bus<E>) => ModuleApi<E>;
|
|
269
358
|
//#endregion
|
|
270
|
-
export type { ActionCreator, Binding, FreeActionCreator, Job, Module, ModuleApi, ModuleContext };
|
|
359
|
+
export type { ActionCreator, Binding, EmitterApi, FreeActionCreator, Job, Module, ModuleApi, ModuleContext };
|
package/dist/notrace/actions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,s as n}from"./context-
|
|
1
|
+
import{i as e,n as t,s as n}from"./context-CctVmHLC.js";import{a as r,r as i}from"./bus-Bdk0YyFQ.js";const a=Symbol.for(`nanoeffects.scope`),o=(e,t)=>(t&&Object.defineProperty(e,a,{value:t}),e);function s(e,t,n){let r=typeof t==`function`?t:void 0,i=typeof t==`function`?n:t;return Object.assign(o((...t)=>o({type:e,payload:r?r(...t).payload:t[0]},i),i),{type:e,match:t=>t.type===e,toString:()=>e})}var c=class extends Error{};function l(e,t,n){let r=t=>t.type===e;function a(r,a){if(typeof a==`object`){if(!t)throw new c(`No handler for command "${e}"`);return t(r,a)}return o(i(l,e,r),n)}let s=Object.assign(a,{type:e,match:r}),l=o(s,n);return l}const u=(e,t)=>[e,t],d=(e=[])=>t=>{let n=/* @__PURE__ */ new Map,i=(e,t)=>{let r={fn:t};return n.set(e,[...n.get(e)??[],r]),()=>{let t=(n.get(e)??[]).filter(e=>e!==r);t.length>0?n.set(e,t):n.delete(e)}};function a(e,t){if(t)return i(r(e),t);let n=e.map(([e,t])=>i(r(e),t));return()=>{for(let e of n)e()}}a(e);let o={run:(e,t,r)=>{let i=(n.get(e.type)??[]).at(-1)?.fn,a=i&&e.wrap?e.wrap(i):i??e;return Reflect.apply(a,null,[t,r])},handle:a};return t.commands=o,o},f=()=>e=>{function t(t){return(...n)=>{let r=t(...n);e.emit(r)}}return Object.assign(e,{emitter:t})},p=e=>typeof e==`string`?s(e):e,m=(e,t,n,r)=>{let i=e.emit;i(Reflect.apply(t,null,[n]),r)},h=e=>{try{return Promise.resolve(e())}catch(e){if(e instanceof c)throw e;return Promise.reject(e)}},g=(e,t,n={},r)=>{let a=l(e,t),s=p(n.success??`${e}/success`),c=p(n.fail??`${e}/fail`),u=(e,t,n)=>{let i=n;return h(()=>Reflect.apply(e,null,[t,n])).then(e=>(m(i,s,e,r),e),e=>{m(i,c,e,r)})},d=e=>(t,n)=>u(e,t,n);function f(t,n){return typeof n==`object`?u(a,t,n):o(i(_,e,t),r)}let g=Object.assign(f,{type:e,match:a.match,wrap:d,success:s,fail:c}),_=o(g,r);return _};function _(e,t,n){return n?{name:e,setup:t,scope:n}:{name:e,setup:t}}const v=(e,t)=>n=>t&&typeof n==`function`?e.fitScope?.(t,n)??n:n,y=(e,t,n)=>{n&&e.applyScope?.(t,n)},b=(e,t,n)=>Array.isArray(t)?[t.map(([t,n])=>[t,e(n)]),n]:[t,e(n)],x=(e,t)=>{let n=e.on;return(...e)=>{let[r,i]=e;return Reflect.apply(n,null,[r,t(i)])}},S=e=>(t,...n)=>{e.run(t,...n).catch(t=>{if(!e.signal.aborted)throw t})},C=(r=[])=>i=>{let a=i.commands??d()(i),o={handle:(...e)=>{if(!a.handle)throw Error("modulePlugin: the `commands` of the bus is not a registry from `commandsPlugin()`");return Reflect.apply(a.handle,null,e)}},s=t({event:{type:`app`,payload:void 0},bus:i,tracer:i.trace}),c=t=>{let r=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;return{mount:s=>{let l=r.get(s);if(l)return l;let u=a.get(s.name);u&&r.get(u)?.();let d=e(t,s.name),f=d.ctx,p=c(f),m=()=>{r.delete(s),a.get(s.name)===s&&a.delete(s.name),f.abort(),d.unlink()};r.set(s,m),a.set(s.name,s);let h=s.scope,g=v(i,h),_=(e,t)=>{let r=Reflect.apply(o.handle,null,b(g,e,t));return n(f,r),r},C=(...e)=>{let t=e.map(e=>typeof e==`function`?_(e,e):p.mount(e));return()=>{for(let e of t)e()}},w=S(f),T=x(f,g);try{y(i,f,h),s.setup(Object.assign(f,{handle:_,use:C,spawn:w,on:T}))}catch(e){throw m(),e}return m},unmount:e=>r.get(e)?.(),isMounted:e=>r.has(e)}},l=c(s.ctx);for(let e of r)l.mount(e);return{commands:a,mount:e=>(s.ctx.signal.throwIfAborted(),l.mount(e)),unmount:l.unmount,isMounted:l.isMounted,dispose:()=>s.ctx.abort(),createModule:_}};export{u as bindHandler,d as commandsPlugin,s as createAction,l as createCommand,g as createJob,_ as createModule,f as emitterPlugin,C as modulePlugin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,c as t,n,r}from"./context-
|
|
1
|
+
import{a as e,c as t,n,r}from"./context-CctVmHLC.js";import{n as i}from"./promise-CSLpzwSR.js";const a=e=>typeof e==`string`?e:e.type,o=(e,t)=>typeof e==`object`?e.payload:t,s=`*`,c=()=>{let e={},t={},n=n=>(t[n]=void 0,e[n]??=/* @__PURE__ */ new Map,e[n]),r=(e,t)=>{let r=n(e),i=r.get(t)??0;i>1?r.set(t,i-1):t?r.delete(t):r.clear()};return{get:n=>(t[n]??=[...e[n]??[]].flatMap(([e,t])=>Array(t).fill(e)),t[n]),add:(e,t)=>{let i=n(e);return i.set(t,(i.get(t)??0)+1),()=>{r(e,t)}},remove:r,clear:()=>{for(let t of Reflect.ownKeys(e))delete e[t];for(let e of Reflect.ownKeys(t))delete t[e]}}},l=Symbol(`nanoeffects.commandCall`),u=(e,t,n)=>{let r={type:t,payload:n};return Object.defineProperty(r,l,{value:e,enumerable:!1}),r},d=e=>{if(typeof e==`function`)return e;if(typeof e==`object`&&e&&l in e)return e[l]},f=(e,t,n)=>Reflect.apply(e,null,[t,n]),p=(s={})=>{let l=c(),u=(e,t)=>l.add(a(e),t),p=(e,t)=>{let n=u(e,(e,r)=>(n(),t(e,r)));return n},m=(e,t)=>{e===void 0?l.clear():l.remove(a(e),t)},h=(e,a)=>{let{onError:o}=s,{ctx:c}=n({event:a,bus:g,tracer:s.trace,parent:{ref:r()}});if(!o){e(a.payload,c);return}let l=e=>{try{o(e,a)}catch(e){t(`onError failed`,e)}};try{let t=e(a.payload,c);i(t)&&Promise.resolve(t).catch(l)}catch(e){l(e)}},g={on:u,once:p,off:m,emit:(t,i)=>{let c=a(t),u=o(t,i),p={type:c,payload:u},m=d(t),_=[...l.get(c),...l.get(`*`)];_.length===0&&!m&&s.onUnhandled?.(p);for(let e of _)h(e,p);if(m){let{ctx:t}=n({event:p,bus:g,tracer:s.trace,parent:{ref:r()}}),i=g.commands?.run??f;return e(t,`command`,()=>i(m,u,t))}},use:e=>e(g),ctx:s.context,trace:s.trace};return g};export{a,s as i,p as n,u as r,l as t};
|
|
@@ -1 +1 @@
|
|
|
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))}};let o;const s=()=>o,c=()=>{},l=(e,t,n,r)=>{},u=(e,t)=>c,d=(e,t,n)=>n(),f=(e,t)=>typeof e==`function`?e(t):e,p=e=>e,m=({event:e,bus:t,tracer:n,parent:r})=>{let{controller:s,unlink:l}=a(r?.signal),{signal:u}=s,h=(...e)=>{if(u.aborted)return;let n=t?.emit,r=o;o=void 0;try{return n?.(...e)}finally{o=r}},g=(...e)=>{if(u.aborted)return c;let n=t?.on,r=n?.(...e);if(!r)return c;let a=i({signal:u},r);return()=>{a(),r()}},_=async(r,...i)=>{u.throwIfAborted();let a=i[0],o=m({event:{type:e.type,payload:a},bus:t,tracer:n,parent:{signal:u,ref:void 0}});try{return await d(o.ctx,`run`,()=>r(a,o.ctx))}finally{o.unlink()}}
|
|
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))}};let o;const s=()=>o,c=()=>{},l=(e,t,n,r)=>{},u=(e,t)=>c,d=(e,t,n)=>n(),f=(e,t)=>typeof e==`function`?e(t):e,p=e=>e,m=({event:e,bus:t,tracer:n,parent:r})=>{let{controller:s,unlink:l}=a(r?.signal),{signal:u}=s,h=(...e)=>{if(u.aborted)return;let n=t?.emit,r=o;o=void 0;try{return n?.(...e)}finally{o=r}},g=(...e)=>{if(u.aborted)return c;let n=t?.on,r=n?.(...e);if(!r)return c;let a=i({signal:u},r);return()=>{a(),r()}},_=async(r,...i)=>{u.throwIfAborted();let a=i[0],o=m({event:{type:e.type,payload:a},bus:t,tracer:n,parent:{signal:u,ref:void 0}});try{return await d(o.ctx,`run`,()=>r(a,o.ctx))}finally{o.unlink()}},v=p({...f(t?.ctx,e),type:e.type,payload:e.payload,signal:u,abort:e=>s.abort(e),emit:h,on:g,off:t?.off??c,run:_});return t?.addContext?.(v),{ctx:v,unlink:l}},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{d as a,e as c,h as i,m as n,l as o,s as r,i as s,u as t};
|