Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@brandingbrand/cargo-hold

Package Overview
Dependencies
Maintainers
101
Versions
84
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@brandingbrand/cargo-hold - npm Package Compare versions

Comparing version 11.66.0 to 11.67.0

src/lib/action-bus/init.action.d.ts

9

CHANGELOG.md

@@ -5,2 +5,11 @@ # Changelog

# [11.67.0](https://github.com/brandingbrand/shipyard/compare/v11.66.0...v11.67.0) (2022-08-02)
### Features
* **cargo-hold:** devtools support ([7a4def7](https://github.com/brandingbrand/shipyard/commit/7a4def7e2803f766ce3f9354a91f014173ac8436))
# [11.66.0](https://github.com/brandingbrand/shipyard/compare/v11.65.0...v11.66.0) (2022-07-15)

@@ -7,0 +16,0 @@

541

index-esm.js

@@ -1,3 +0,3 @@

import { filter, scan, shareReplay, switchMap as switchMap$1, withLatestFrom as withLatestFrom$1, map as map$1, mergeMap as mergeMap$1 } from 'rxjs/operators';
import { Subscription, Subject, filter as filter$1, withLatestFrom, map, switchMap, from, mergeMap, of, merge, ReplaySubject, BehaviorSubject } from 'rxjs';
import { filter, scan, shareReplay, map as map$1, switchMap as switchMap$1, withLatestFrom as withLatestFrom$1, mergeMap as mergeMap$1 } from 'rxjs/operators';
import { Subject, Subscription, filter as filter$1, withLatestFrom, map, switchMap, from, mergeMap, of, merge, BehaviorSubject, ReplaySubject } from 'rxjs';
import { pipe, branchObject, branch } from '@brandingbrand/standard-compose';

@@ -34,5 +34,11 @@ import { ok, fail, isOk } from '@brandingbrand/standard-result';

class ActionBus {
get action$() {
return this._action$.asObservable();
/**
* Action buses provide a way to subscribe to actions dispatched anywhere.
*/ class ActionBus {
/**
* Getter for observable actions
*
* @return Action observable
*/ get action$() {
return this.internalAction$.asObservable();
}

@@ -43,3 +49,3 @@ registerHandler(guardOrActionHandler, handler) {

const actionHandler = createHandler(guard, handler);
const subscription = actionHandler(this._action$);
const subscription = actionHandler(this.internalAction$);
this.subscriptions.add(subscription);

@@ -49,3 +55,3 @@ return subscription;

const actionHandler = guardOrActionHandler;
const subscription = actionHandler(this._action$);
const subscription = actionHandler(this.internalAction$);
this.subscriptions.add(subscription);

@@ -55,10 +61,17 @@ return subscription;

constructor(){
this.internalAction$ = new Subject();
this.subscriptions = new Subscription();
this._action$ = new Subject();
this.dispatch = (action)=>{
this._action$.next(action);
/**
* Dispatches an action into the action bus
*
* @param action The action to dispatch
*/ this.dispatch = (action)=>{
this.internalAction$.next(action);
};
this.dispose = ()=>{
/**
* Releases all subscriptions before destroying the action bus
*
*/ this.dispose = ()=>{
this.subscriptions.unsubscribe();
this._action$.complete();
this.internalAction$.complete();
};

@@ -68,2 +81,6 @@ }

const InitAction = createActionCreator({
actionKey: '@brandingbrand/cargo-hold/init'
});
function _defineProperty$6(obj, key, value) {

@@ -97,5 +114,3 @@ if (key in obj) {

}
/**
*
*/ function asyncBuilder() {
function asyncBuilder() {
return {};

@@ -172,3 +187,8 @@ }

}
const buildInitActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns an init action creator.
*
* @param builder
* @return
*/ const buildInitActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:init',

@@ -178,3 +198,8 @@ callback: (idlePayload)=>idlePayload

;
const buildLoadingActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a loading action creator.
*
* @param builder
* @return
*/ const buildLoadingActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
actionKey: builder.actionKey,

@@ -185,3 +210,8 @@ subtype: 'async:load',

;
const buildLoadingMoreActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a loading more action creator.
*
* @param builder
* @return
*/ const buildLoadingMoreActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:load-more',

@@ -191,3 +221,8 @@ callback: (loadingPayload)=>loadingPayload

;
const buildSucceedActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a success action creator.
*
* @param builder
* @return
*/ const buildSucceedActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:succeed',

@@ -197,3 +232,8 @@ callback: (succeedPayload)=>succeedPayload

;
const buildFailActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a failure action creator.
*
* @param builder
* @return
*/ const buildFailActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:fail',

@@ -203,3 +243,8 @@ callback: (failure)=>failure

;
const buildRevertActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a revert action creator.
*
* @param builder
* @return
*/ const buildRevertActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:revert',

@@ -209,3 +254,8 @@ callback: (revertPayload)=>revertPayload

;
const buildActionCreators = (builder)=>pipe(builder, branchObject({
/**
* Builds a full suite of async action creators.
*
* @param builder
* @return
*/ const buildActionCreators = (builder)=>pipe(builder, branchObject({
init: buildInitActionCreator,

@@ -220,13 +270,24 @@ load: buildLoadingActionCreator,

const buildAsyncEffect = (builder)=>(action$, state$)=>{
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure.
*
* @param builder
* @return The async effect
*/ const buildAsyncEffect = (builder)=>(action$, state$)=>{
// load$ gets triggered by the triggerActionFilter, runs the prediction if given, and emits
// loading or loadingMore actions
const load$ = action$.pipe(// these typeguards don't have perfect Typescript defs
filter$1(builder.triggerActionFilter), withLatestFrom(state$), map(([action, state])=>{
const newSuccessPayload = builder.prediction ? builder.prediction(action.payload)(state.payload) : state.payload;
if (builder.enableLoadMore && (state.status === 'success' || state.status === 'loading-more')) {
return buildLoadingMoreActionCreator(builder).create(newSuccessPayload);
const predictedPayload = builder.prediction ? builder.prediction(action.payload)(state.payload) : state.payload;
if (builder.enableLoadMore === true && (state.status === 'success' || state.status === 'loading-more')) {
return buildLoadingMoreActionCreator(builder).create(predictedPayload);
}
return buildLoadingActionCreator(builder).create(newSuccessPayload);
return buildLoadingActionCreator(builder).create(predictedPayload);
}));
const callbackAction$ = action$.pipe(// these typeguards don't have perfect Typescript defs
filter$1(builder.triggerActionFilter), // grab state to get back to if we have optimistic updates on and we fail
// callbackAction$ is also triggered by the triggerActionFilter, whose payload serves as the
// argument for the callback. It runs the callback, judges success vs failure, and emits the
// appropriate action accordingly. If it was a failure, also emits a revert if we had a prediction.
const callbackAction$ = action$.pipe(filter$1(builder.triggerActionFilter), // grab state to get back to if we have optimistic updates on and we fail
withLatestFrom(state$), switchMap(([action, stateAtStart])=>from(// take advantage of the flattening of Promises - wrap it in a promise regardless

@@ -240,4 +301,2 @@ new Promise((resolve, reject)=>{

}).then(ok).catch(fail)).pipe(// grab latest state for mapOnSuccess etc functions to use
// type coercion because "run the lens if we have one, and if we don't we'll assume the raw
// value is right" is not a simple Typescript concept.
withLatestFrom(state$), mergeMap(([wrappedResult, stateAtReturn])=>{

@@ -247,4 +306,4 @@ if (isOk(wrappedResult)) {

// Type coercion is due to Typescript not following unions quite right
const newState = builder.mapOnSuccess ? builder.mapOnSuccess(result)(stateAtReturn.payload) : result;
return of(buildSucceedActionCreator(builder).create(newState));
const mappedNewState = builder.mapOnSuccess ? builder.mapOnSuccess(result)(stateAtReturn.payload) : result;
return of(buildSucceedActionCreator(builder).create(mappedNewState));
}

@@ -259,9 +318,23 @@ const result = wrappedResult.failure;

;
const buildAsyncEffectWithLens = (builder)=>(action$, state$)=>buildAsyncEffect(builder)(action$, state$.pipe(map(builder.lens.get)))
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure. This runs inside a lens, so
* as to operate on a larger data structure.
*
* @param builder
* @return The async effect
*/ const buildAsyncEffectWithLens = (builder)=>(action$, state$)=>// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any is of limited scope and not worth specifying
buildAsyncEffect(builder)(action$, state$.pipe(map(builder.lens.get)))
;
/**
* If we input a lens it outputs a lens that goes from the outer structure of the input
* lens to the async state's payload. If we do not input a lens it outputs a lens that goes
* from the async state to its payload.
*
* @param builder
*/ function buildPayloadLens(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- we're using overloads
function buildPayloadLens(builder) {
const innerPayloadLens = createLensCreator().fromPath('payload');

@@ -274,12 +347,28 @@ if (builder.lens) {

const combineEffects = (...effects)=>(action$, state$)=>merge(...effects.map((effect)=>effect(action$, state$)
/**
* Combines multiple effects into one, merging all of their observables.
*
* @param effects The effects to combine.
* @return The combined effect.
*/ const combineEffects = (...effects)=>(action$, state$)=>merge(...effects.map((effect)=>effect(action$, state$)
))
;
const combineActionReducers = (...reducers)=>(action)=>(state)=>reducers.reduce((currentState, reducer)=>reducer(action)(currentState)
/**
* Combines action reducers by calling each of them in succession
*
* @param reducers Reducers to combine
* @return Action reducer that combines all effects
*/ const combineActionReducers = (...reducers)=>(action)=>(state)=>reducers.reduce((currentState, reducer)=>reducer(action)(currentState)
, state)
;
const on = (filter, reducer)=>(action)=>{
/**
* Makes it easier to build reducers by filtering actions first, narrowing their type.
* If the type matches it then calls the given reducer
*
* @param filter A function that filters the action down to the desired actions.
* @param reducer A reducer that operates on the desired action.
* @return A reducer that operates on any action.
*/ const on = (filter, reducer)=>(action)=>{
if (filter(action)) {
// sorry for coercion. TS can't detect the typeguard logic through the ActionOf<> type.
return reducer(action);

@@ -291,17 +380,64 @@ }

;
const requireSource = (...sources)=>(action)=>sources.length === 0 || sources.includes(action.source)
/**
* Filters actions based on the desired source. Actions that do no have a source will fail
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source: false if otherwise.
* @deprecated
*/ const requireSource = (...sources)=>(action)=>sources.length === 0 || sources.includes(action.source)
;
const optionalSource = (...sources)=>(action)=>sources.length === 0 || !action.source || sources.includes(action.source)
/**
* Filters actions based on the desired source. Actions that do no have a source will pass
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source or no source: false if otherwise.
* @deprecated
*/ const optionalSource = (...sources)=>(action)=>sources.length === 0 || !action.source || sources.includes(action.source)
;
const isType = (...actionTypes)=>(action)=>actionTypes.includes(action.type)
/**
* Filters actions by the desired type
*
* @param actionTypes The desired action types.
* @return True if the type is one of the desired action types: false if otherwise.
*/ const isType = (...actionTypes)=>(action)=>actionTypes.includes(action.type)
;
const isSubtype = (...actionSubtypes)=>(action)=>actionSubtypes.includes(action.subtype)
/**
* Filters actions by the desired subtype
*
* @param actionSubtypes The desired action subtypes.
* @return True if the subtype is one of the desired action types: false if otherwise.
*/ const isSubtype = (...actionSubtypes)=>(action)=>actionSubtypes.includes(action.subtype)
;
const matches = (specifier, extraSources)=>(inputAction)=>specifier.type === inputAction.type && specifier.subtype === inputAction.subtype && (extraSources === undefined || requireSource(specifier.source, ...extraSources)(inputAction)) && equal(specifier.filterMetadata, inputAction.filterMetadata)
/**
* Type guard that tells you whether an action matches a given action specifier.
*
* @param specifier Action specifier to match
* @param extraSources Possible extra values of the source field that are allowed. (Deprecated)
* @return True if the action matches the specifier: false if not.
*/ const matches = (specifier, extraSources)=>(inputAction)=>specifier.type === inputAction.type && specifier.subtype === inputAction.subtype && (extraSources === undefined || requireSource(specifier.source, ...extraSources)(inputAction)) && equal(specifier.filterMetadata, inputAction.filterMetadata)
;
const and = (outerTypeguard, innerTypeguard)=>(action)=>outerTypeguard(action) && innerTypeguard(action)
/**
* Combines two type guards such that an action must comply with both.
*
* @param outerTypeguard First type guard to be called.
* @param innerTypeguard Second type guard to be called if the outer returns true.
* @return True if the action matches both specifiers: false if not.
*/ const and = (outerTypeguard, innerTypeguard)=>(action)=>outerTypeguard(action) && innerTypeguard(action)
;
const or = (typeguardA, typeguardB)=>(action)=>typeguardA(action) || typeguardB(action)
/**
* Combines two type guards such that an action must comply with either.
*
* @param typeguardA First type guard to be called.
* @param typeguardB Second type guard to be called if the first returns false.
* @return True if the action matches either specifiers: false if not.
*/ const or = (typeguardA, typeguardB)=>(action)=>typeguardA(action) || typeguardB(action)
;
const composeStateReducers = (outerReducer)=>(innerReducer)=>(state)=>outerReducer(innerReducer(state))
/**
* Combines two state reducers calling the inner and then the outer.
*
* @param outerReducer The state reducer
* @return A function that takes another reducer and returns the combined state reducer.
*/ const composeStateReducers = (outerReducer)=>(innerReducer)=>(state)=>outerReducer(innerReducer(state))
;

@@ -316,2 +452,6 @@

const UpdateReducersAction = createActionCreator({
actionKey: '@brandingbrand/cargo-hold/update-reducers'
});
/**

@@ -322,19 +462,43 @@ * `Store` provides the state container and facilitates effects & reducers upon state.

*/ class Store extends ActionBus {
get state() {
/**
* Synchronous getter for current state. Use `state$` when possible.
*
* @return Current state
*/ get state() {
return this.subject$.value;
}
get state$() {
/**
* Getter for the state observable
*
* @return The state observable
*/ get state$() {
return this.subject$.asObservable();
}
get reducer$() {
// Concatenates the reducers into an observable array.
return this.internalReducer$.asObservable().pipe(accumulateToArray(), map$1((reducers)=>combineActionReducers(...reducers)
));
}
/**
* Registers a new effect to the store.
*
* @param effect The effect to register.
* @return A subscription. Unsubscribe to the subscription to stop the effect from listening
*/ get reducedAction$() {
return this.internalReducedAction$.asObservable();
}
constructor(initialState){
super();
this.reducer$ = new ReplaySubject(Number.POSITIVE_INFINITY);
this.reducedAction$ = new Subject();
this.initialState = initialState;
this.subject$ = new BehaviorSubject(this.initialState);
this.internalReducedAction$ = new Subject();
this.internalReducer$ = new ReplaySubject(Number.POSITIVE_INFINITY);
this.registerReducer = (reducer)=>{
this.reducer$.next(reducer);
this.internalReducer$.next(reducer);
this.dispatch(UpdateReducersAction.create());
};
this.registerEffect = (effect)=>{
const subscription = effect(this.reducedAction$, this.state$).subscribe({
const subscription = effect(this.internalReducedAction$, this.state$).subscribe({
next: (value)=>{
this._action$.next(value);
this.dispatch(value);
}

@@ -345,11 +509,8 @@ });

};
const allReducers$ = this.reducer$.pipe(accumulateToArray());
this.subject$ = new BehaviorSubject(initialState);
const reducerSubscription = allReducers$.pipe(switchMap$1((reducers)=>this._action$.pipe(scan((currentState, action)=>reducers.reduce((state, reducer)=>reducer(action)(state)
, currentState)
, initialState), withLatestFrom$1(this._action$))
const reducerSubscription = this.reducer$.pipe(switchMap$1((reducer)=>this.action$.pipe(scan((state, action)=>reducer(action)(state)
, initialState), withLatestFrom$1(this.action$))
)).subscribe({
next: ([state, action])=>{
this.subject$.next(state);
this.reducedAction$.next(action);
this.internalReducedAction$.next(action);
},

@@ -422,13 +583,46 @@ complete: ()=>{

}
const buildInitStateReducer = (_builder)=>(payload)=>()=>createIdleState(payload)
/**
* Given a payload it will return a state reducer that gives us an idle state of that payload.
*
* @param _builder
* @return
*/ const buildInitStateReducer = (_builder)=>(payload)=>()=>createIdleState(payload)
;
const buildLoadingStateReducer = (_builder)=>(payload)=>()=>createLoadingState(payload)
/**
* Given a payload it will return a state reducer that gives us a loading state of that payload.
*
* @param _builder
* @return
*/ const buildLoadingStateReducer = (_builder)=>(payload)=>()=>createLoadingState(payload)
;
const buildLoadingMoreStateReducer = (_builder)=>(payload)=>()=>createLoadingMoreState(payload)
/**
* Given a payload it will return a state reducer that gives us a loading more state
* of that payload.
*
* @param _builder
* @return
*/ const buildLoadingMoreStateReducer = (_builder)=>(payload)=>()=>createLoadingMoreState(payload)
;
const buildSuccessStateReducer = (_builder)=>(payload)=>()=>createSuccessState(payload)
/**
* Given a payload it will return a state reducer that gives us a success state of that payload.
*
* @param _builder
* @return
*/ const buildSuccessStateReducer = (_builder)=>(payload)=>()=>createSuccessState(payload)
;
const buildFailureStateReducer = (_builder)=>(failure)=>(state)=>createFailureState(state.payload, failure)
/**
* Given a failure it will return a state reducer that gives us a failure state.
*
* @param _builder
* @return
*/ const buildFailureStateReducer = (_builder)=>(failure)=>(state)=>createFailureState(state.payload, failure)
;
const buildRevertStateReducer = (_builder)=>(payload)=>(state)=>_objectSpread$4({}, state, {
/**
* Given a payload it will return a state reducer that reverts to the given payload but leaving
* the status the same.
*
* @param _builder
* @return
*/ const buildRevertStateReducer = (_builder)=>(payload)=>(state)=>// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- fixes a nuanced type issue.
_objectSpread$4({}, state, {
payload

@@ -440,52 +634,107 @@ })

;
const buildInitActionReducer = (builder)=>pipe(builder, branch(buildInitActionCreator, buildInitStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in an idle state.
*
* @param builder A builder with an action key and an idle type.
* @return
*/ const buildInitActionReducer = (builder)=>pipe(builder, // buildInitActionCreator will take WithMetadata and do the right thing.
branch(buildInitActionCreator, buildInitStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildLoadingActionReducer = (builder)=>pipe(builder, branch(buildLoadingActionCreator, buildLoadingStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), // slight coercion necessary as TS isn't picking up the union quite properly
(action)=>stateReducerCreator(action.payload)
/**
* Given a builder this makes an action reducer that results in a loading state.
*
* @param builder A builder with an action key and a loading type.
* @return
*/ const buildLoadingActionReducer = (builder)=>pipe(builder, branch(buildLoadingActionCreator, buildLoadingStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
)
)
;
const buildLoadingMoreActionReducer = (builder)=>pipe(builder, branch(buildLoadingMoreActionCreator, buildLoadingMoreStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in a loading more state.
*
* @param builder A builder with an action key and a loading more type.
* @return
*/ const buildLoadingMoreActionReducer = (builder)=>pipe(builder, branch(buildLoadingMoreActionCreator, buildLoadingMoreStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildSuccessActionReducer = (builder)=>pipe(builder, branch(buildSucceedActionCreator, buildSuccessStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in a success state.
*
* @param builder A builder with an action key and a success type.
* @return
*/ const buildSuccessActionReducer = (builder)=>pipe(builder, branch(buildSucceedActionCreator, buildSuccessStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildFailureActionReducer = (builder)=>pipe(builder, branch(buildFailActionCreator, buildFailureStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>(state)=>stateReducerCreator(action.payload)(state)
/**
* Given a builder this makes an action reducer that results in a failure state.
*
* @param builder A builder with an action key and payload types.
* @return
*/ const buildFailureActionReducer = (builder)=>pipe(builder, branch(buildFailActionCreator, buildFailureStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>(state)=>stateReducerCreator(action.payload)(state)
)
)
;
const buildRevertActionReducer = (builder)=>pipe(builder, branch(buildRevertActionCreator, buildRevertStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
/**
* Given a builder this makes an action reducer that results in a reverted payload.
*
* @param builder A builder with an action key and payload types.
* @return
*/ const buildRevertActionReducer = (builder)=>pipe(builder, branch(buildRevertActionCreator, buildRevertStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
)
)
;
const buildCombinedReducers = (builder)=>pipe(builder, branch(buildInitActionReducer, buildLoadingActionReducer, buildLoadingMoreActionReducer, buildSuccessActionReducer, buildFailureActionReducer, buildRevertActionReducer), (actionReducers)=>combineActionReducers(...actionReducers)
/**
* Given a builder it makes an action reducer that looks for all of the async actions
* and performs the appropriate state change.
*
* @param builder A builder with an action key an payload types.
* @return
*/ const buildCombinedReducers = (builder)=>pipe(builder, branch(buildInitActionReducer, buildLoadingActionReducer, buildLoadingMoreActionReducer, buildSuccessActionReducer, buildFailureActionReducer, buildRevertActionReducer), (actionReducers)=>combineActionReducers(...actionReducers)
)
;
const buildCombinedLensedReducers = (builder)=>(action)=>withLens(builder.lens)(buildCombinedReducers(builder)(action))
/**
* Returns an action reducer from buildCombinedReducers, but run in a lens so that it handles
* a larger data structure.
*
* @param builder
* @return
*/ const buildCombinedLensedReducers = (builder)=>(action)=>withLens(builder.lens)(buildCombinedReducers(builder)(action))
;
/**
* Takes a builder and returns a selector that selects the payload.
*
* @param builder
*/ function buildSelectPayload(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectPayload(builder) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return buildPayloadLens(builder).get;
}
/**
* Takes a builder and returns a selector that selects the status.
*
* @param builder
*/ function buildSelectStatus(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectStatus(builder) {
const statusLens = createLensCreator().fromPath('status');
if (builder.lens) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return statusLens.withOuterLens(builder.lens).get;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return statusLens.get;
}
/**
* Takes a builder and returns a selector that selects the failure data if available.
*
* @param builder
*/ function buildSelectFailure(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectFailure(builder) {
const failureLens = createLensCreator().fromPath('failure');
if (builder.lens) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return -- the any is limited in scope and not worth it to describe.
return failureLens.withOuterLens(// this coercion is fine; the lens just gets 'failure' from it so if it's not a failure,

@@ -495,2 +744,3 @@ // it'll return undefined, which is what we want.

}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return failureLens.get;

@@ -828,3 +1078,9 @@ }

;
const makeSetMany = (deps)=>(items)=>withLens(deps.lens)((state)=>{
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* overriding existing ids that collide.
*
* @param deps
* @return
*/ const makeSetMany = (deps)=>(items)=>withLens(deps.lens)((state)=>{
const entities = _objectSpread$1({}, state.entities, fromEntityArray(deps)(items));

@@ -838,7 +1094,19 @@ const ids = mergeIdLists(...state.ids, ...items.map(deps.idSelector));

;
const makeSetOne = (deps)=>(item)=>makeSetMany(deps)([
/**
* Takes an item and makes a reducer that adds that item to an existing state, overriding
* the existing id if it exists.
*
* @param deps
* @return
*/ const makeSetOne = (deps)=>(item)=>makeSetMany(deps)([
item
])
;
const makeAddMany = (deps)=>(items)=>(structure)=>{
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* preserving existing ids.
*
* @param deps
* @return
*/ const makeAddMany = (deps)=>(items)=>(structure)=>{
const state = deps.lens.get(structure);

@@ -855,11 +1123,32 @@ const newIds = items.map(deps.idSelector).filter((val)=>!state.ids.includes(val)

;
const makeAddOne = (deps)=>(item)=>makeAddMany(deps)([
/**
* Takes an item and makes a reducer that adds that item to an existing state, preserving
* the existing id if it exists.
*
* @param deps
* @return
*/ const makeAddOne = (deps)=>(item)=>makeAddMany(deps)([
item
])
;
const makeSetAll = (deps)=>(items)=>(structure)=>makeSetMany(deps)(items)(deps.lens.set(makeCreateState(deps)([]))(structure))
/**
* Takes an array of items and replaces the existing state with the incoming state.
*
* @param deps
* @return
*/ const makeSetAll = (deps)=>(items)=>(structure)=>makeSetMany(deps)(items)(deps.lens.set(makeCreateState(deps)([]))(structure))
;
const makeRemoveAll = (deps)=>()=>(structure)=>deps.lens.set(makeCreateState(deps)([]))(structure)
/**
* Removes all entities and state ids.
*
* @param deps
* @return
*/ const makeRemoveAll = (deps)=>()=>(structure)=>deps.lens.set(makeCreateState(deps)([]))(structure)
;
const makeRemoveMany = (deps)=>(ids)=>withLens(deps.lens)((state)=>{
/**
* Takes an array of entity ids and returns a reducer that removes those ids if they exist.
*
* @param deps
* @return
*/ const makeRemoveMany = (deps)=>(ids)=>withLens(deps.lens)((state)=>{
const newIds = state.ids.filter((id)=>!ids.includes(id)

@@ -880,7 +1169,17 @@ );

;
const makeRemoveOne = (deps)=>(id)=>makeRemoveMany(deps)([
/**
* Takes an entity id, returns a reducer that removes it if it exists.
*
* @param deps
* @return
*/ const makeRemoveOne = (deps)=>(id)=>makeRemoveMany(deps)([
id
])
;
const makeReducers = (deps)=>({
/**
* Returns a full suite of reducers applying the given dependencies.
*
* @param deps
* @return
*/ const makeReducers = (deps)=>({
addMany: makeAddMany(deps),

@@ -897,3 +1196,9 @@ addOne: makeAddOne(deps),

const makeSelectAll = (lens)=>(structure)=>{
/**
* Take all of the entities in an entity state from a given lens and returns
* an array of the entities.
*
* @param lens
* @return
*/ const makeSelectAll = (lens)=>(structure)=>{
const state = lens.get(structure);

@@ -911,3 +1216,8 @@ // TODO @grayontheweb 04-01-2022 this pattern is repeated with minor

;
const makeSelectByIds = (lens)=>(ids)=>(structure)=>{
/**
* Select the given Ids from the entity state from a give lens and returns an array of them.
*
* @param lens
* @return
*/ const makeSelectByIds = (lens)=>(ids)=>(structure)=>{
const state = lens.get(structure);

@@ -923,3 +1233,9 @@ return ids.reduce((acc, id)=>{

;
const makeSelectById = (lens)=>(id)=>(structure)=>{
/**
* Select the given Id from the entity state from a give lens and returns either the entity
* or undefined.
*
* @param lens
* @return
*/ const makeSelectById = (lens)=>(id)=>(structure)=>{
const state = lens.get(structure);

@@ -929,9 +1245,19 @@ return id in state.entities ? state.entities[id] : undefined;

;
const makeSelectByIndex = (lens)=>(index)=>(structure)=>{
/**
* Given an index it will select the Nth value if it exists.
*
* @param lens
* @return
*/ const makeSelectByIndex = (lens)=>(index)=>(structure)=>{
const state = lens.get(structure);
const id = state.ids[index];
return id ? state.entities[id] : undefined;
return id !== undefined ? state.entities[id] : undefined;
}
;
const makeSelectByIndices = (lens)=>(indices)=>(structure)=>{
/**
* Given multiple indices it will select the Nth values if they exist.
*
* @param lens
* @return
*/ const makeSelectByIndices = (lens)=>(indices)=>(structure)=>{
const state = lens.get(structure);

@@ -941,3 +1267,3 @@ return indices.reduce((acc, index)=>{

const entity = id ? state.entities[id] : undefined;
return entity && entity in state.entities ? [
return entity !== undefined && entity in state.entities ? [
...acc,

@@ -949,3 +1275,8 @@ entity

;
const getSelectors = (lens)=>({
/**
* Returns the full suite of selectors given the lens.
*
* @param lens
* @return
*/ const getSelectors = (lens)=>({
selectAll: makeSelectAll(lens),

@@ -989,3 +1320,8 @@ selectByIds: makeSelectByIds(lens),

;
const createEntityAdaptor = (options)=>{
/**
* Creates an entity adapter.
*
* @param options Options to create the entity adapter.
* @return
*/ const createEntityAdaptor = (options)=>{
const isSorted = Boolean(options.comparer);

@@ -1023,3 +1359,5 @@ var _lens;

};
const EMPTY_ENTITY_STATE = {
/**
* A constant that is a good initial state for any entity state.
*/ const EMPTY_ENTITY_STATE = {
entities: {},

@@ -1029,3 +1367,8 @@ ids: []

const getDefaultedEntity = (id)=>(state)=>{
/**
* Returns the entity for a given id, if no id is provided it returns the first entity.
*
* @param id Optional entity id.
* @return Entity represented by the id, or the first entity.
*/ const getDefaultedEntity = (id)=>(state)=>{
const defaultedId = id !== null && id !== void 0 ? id : state.ids[0];

@@ -1039,2 +1382,2 @@ if (defaultedId === undefined) {

export { ActionBus, EMPTY_ENTITY_STATE, Store, and, asyncBuilder, asyncBuilderWithStructureLens, buildActionCreators, buildAsyncEffect, buildAsyncEffectWithLens, buildCombinedLensedReducers, buildCombinedReducers, buildFailActionCreator, buildFailureActionReducer, buildFailureStateReducer, buildInitActionCreator, buildInitActionReducer, buildInitStateReducer, buildLoadingActionCreator, buildLoadingActionReducer, buildLoadingMoreActionCreator, buildLoadingMoreActionReducer, buildLoadingMoreStateReducer, buildLoadingStateReducer, buildPayloadLens, buildRevertActionCreator, buildRevertActionReducer, buildRevertStateReducer, buildSelectFailure, buildSelectPayload, buildSelectStatus, buildSucceedActionCreator, buildSuccessActionReducer, buildSuccessStateReducer, combineActionReducers, combineEffects, composeStateReducers, createActionCreator, createAsyncActionCreators, createAsyncAdaptor, createCombinedReducer, createEntityAdaptor, createFailureState, createHandler, createIdleState, createLensedReducers, createLoadingMoreState, createLoadingState, createReducers, createSelectors, createSuccessState, defaultIdSelector, fromEntityArray, getDefaultedEntity, getSelectors, isSubtype, isType, makeAddMany, makeAddOne, makeAsyncEffect, makeCreateState, makeReducers, makeRemoveAll, makeRemoveMany, makeRemoveOne, makeSelectAll, makeSelectById, makeSelectByIds, makeSelectByIndex, makeSelectByIndices, makeSelectFailure, makeSelectPayload, makeSelectStatus, makeSetAll, makeSetMany, makeSetOne, matches, notOfType, ofType, on, optionalSource, or, requireSource, sortIfNeeded, withActionKey, withAsyncCallback, withEnableLoadingMore, withMapOnFailure, withMapOnSuccess, withMetadata, withOptimisticUpdate, withStructureLens, withTriggerActionFilter };
export { ActionBus, EMPTY_ENTITY_STATE, InitAction, Store, UpdateReducersAction, and, asyncBuilder, asyncBuilderWithStructureLens, buildActionCreators, buildAsyncEffect, buildAsyncEffectWithLens, buildCombinedLensedReducers, buildCombinedReducers, buildFailActionCreator, buildFailureActionReducer, buildFailureStateReducer, buildInitActionCreator, buildInitActionReducer, buildInitStateReducer, buildLoadingActionCreator, buildLoadingActionReducer, buildLoadingMoreActionCreator, buildLoadingMoreActionReducer, buildLoadingMoreStateReducer, buildLoadingStateReducer, buildPayloadLens, buildRevertActionCreator, buildRevertActionReducer, buildRevertStateReducer, buildSelectFailure, buildSelectPayload, buildSelectStatus, buildSucceedActionCreator, buildSuccessActionReducer, buildSuccessStateReducer, combineActionReducers, combineEffects, composeStateReducers, createActionCreator, createAsyncActionCreators, createAsyncAdaptor, createCombinedReducer, createEntityAdaptor, createFailureState, createHandler, createIdleState, createLensedReducers, createLoadingMoreState, createLoadingState, createReducers, createSelectors, createSuccessState, defaultIdSelector, fromEntityArray, getDefaultedEntity, getSelectors, isSubtype, isType, makeAddMany, makeAddOne, makeAsyncEffect, makeCreateState, makeReducers, makeRemoveAll, makeRemoveMany, makeRemoveOne, makeSelectAll, makeSelectById, makeSelectByIds, makeSelectByIndex, makeSelectByIndices, makeSelectFailure, makeSelectPayload, makeSelectStatus, makeSetAll, makeSetMany, makeSetOne, matches, notOfType, ofType, on, optionalSource, or, requireSource, sortIfNeeded, withActionKey, withAsyncCallback, withEnableLoadingMore, withMapOnFailure, withMapOnSuccess, withMetadata, withOptimisticUpdate, withStructureLens, withTriggerActionFilter };

@@ -42,5 +42,11 @@ 'use strict';

class ActionBus {
get action$() {
return this._action$.asObservable();
/**
* Action buses provide a way to subscribe to actions dispatched anywhere.
*/ class ActionBus {
/**
* Getter for observable actions
*
* @return Action observable
*/ get action$() {
return this.internalAction$.asObservable();
}

@@ -51,3 +57,3 @@ registerHandler(guardOrActionHandler, handler) {

const actionHandler = createHandler(guard, handler);
const subscription = actionHandler(this._action$);
const subscription = actionHandler(this.internalAction$);
this.subscriptions.add(subscription);

@@ -57,3 +63,3 @@ return subscription;

const actionHandler = guardOrActionHandler;
const subscription = actionHandler(this._action$);
const subscription = actionHandler(this.internalAction$);
this.subscriptions.add(subscription);

@@ -63,10 +69,17 @@ return subscription;

constructor(){
this.internalAction$ = new rxjs.Subject();
this.subscriptions = new rxjs.Subscription();
this._action$ = new rxjs.Subject();
this.dispatch = (action)=>{
this._action$.next(action);
/**
* Dispatches an action into the action bus
*
* @param action The action to dispatch
*/ this.dispatch = (action)=>{
this.internalAction$.next(action);
};
this.dispose = ()=>{
/**
* Releases all subscriptions before destroying the action bus
*
*/ this.dispose = ()=>{
this.subscriptions.unsubscribe();
this._action$.complete();
this.internalAction$.complete();
};

@@ -76,2 +89,6 @@ }

const InitAction = createActionCreator({
actionKey: '@brandingbrand/cargo-hold/init'
});
function _defineProperty$6(obj, key, value) {

@@ -105,5 +122,3 @@ if (key in obj) {

}
/**
*
*/ function asyncBuilder() {
function asyncBuilder() {
return {};

@@ -180,3 +195,8 @@ }

}
const buildInitActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns an init action creator.
*
* @param builder
* @return
*/ const buildInitActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:init',

@@ -186,3 +206,8 @@ callback: (idlePayload)=>idlePayload

;
const buildLoadingActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a loading action creator.
*
* @param builder
* @return
*/ const buildLoadingActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
actionKey: builder.actionKey,

@@ -193,3 +218,8 @@ subtype: 'async:load',

;
const buildLoadingMoreActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a loading more action creator.
*
* @param builder
* @return
*/ const buildLoadingMoreActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:load-more',

@@ -199,3 +229,8 @@ callback: (loadingPayload)=>loadingPayload

;
const buildSucceedActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a success action creator.
*
* @param builder
* @return
*/ const buildSucceedActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:succeed',

@@ -205,3 +240,8 @@ callback: (succeedPayload)=>succeedPayload

;
const buildFailActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a failure action creator.
*
* @param builder
* @return
*/ const buildFailActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:fail',

@@ -211,3 +251,8 @@ callback: (failure)=>failure

;
const buildRevertActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
/**
* Takes a builder and returns a revert action creator.
*
* @param builder
* @return
*/ const buildRevertActionCreator = (builder)=>createActionCreator(_objectSpread$5({}, builder, {
subtype: 'async:revert',

@@ -217,3 +262,8 @@ callback: (revertPayload)=>revertPayload

;
const buildActionCreators = (builder)=>standardCompose.pipe(builder, standardCompose.branchObject({
/**
* Builds a full suite of async action creators.
*
* @param builder
* @return
*/ const buildActionCreators = (builder)=>standardCompose.pipe(builder, standardCompose.branchObject({
init: buildInitActionCreator,

@@ -228,13 +278,24 @@ load: buildLoadingActionCreator,

const buildAsyncEffect = (builder)=>(action$, state$)=>{
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure.
*
* @param builder
* @return The async effect
*/ const buildAsyncEffect = (builder)=>(action$, state$)=>{
// load$ gets triggered by the triggerActionFilter, runs the prediction if given, and emits
// loading or loadingMore actions
const load$ = action$.pipe(// these typeguards don't have perfect Typescript defs
rxjs.filter(builder.triggerActionFilter), rxjs.withLatestFrom(state$), rxjs.map(([action, state])=>{
const newSuccessPayload = builder.prediction ? builder.prediction(action.payload)(state.payload) : state.payload;
if (builder.enableLoadMore && (state.status === 'success' || state.status === 'loading-more')) {
return buildLoadingMoreActionCreator(builder).create(newSuccessPayload);
const predictedPayload = builder.prediction ? builder.prediction(action.payload)(state.payload) : state.payload;
if (builder.enableLoadMore === true && (state.status === 'success' || state.status === 'loading-more')) {
return buildLoadingMoreActionCreator(builder).create(predictedPayload);
}
return buildLoadingActionCreator(builder).create(newSuccessPayload);
return buildLoadingActionCreator(builder).create(predictedPayload);
}));
const callbackAction$ = action$.pipe(// these typeguards don't have perfect Typescript defs
rxjs.filter(builder.triggerActionFilter), // grab state to get back to if we have optimistic updates on and we fail
// callbackAction$ is also triggered by the triggerActionFilter, whose payload serves as the
// argument for the callback. It runs the callback, judges success vs failure, and emits the
// appropriate action accordingly. If it was a failure, also emits a revert if we had a prediction.
const callbackAction$ = action$.pipe(rxjs.filter(builder.triggerActionFilter), // grab state to get back to if we have optimistic updates on and we fail
rxjs.withLatestFrom(state$), rxjs.switchMap(([action, stateAtStart])=>rxjs.from(// take advantage of the flattening of Promises - wrap it in a promise regardless

@@ -248,4 +309,2 @@ new Promise((resolve, reject)=>{

}).then(standardResult.ok).catch(standardResult.fail)).pipe(// grab latest state for mapOnSuccess etc functions to use
// type coercion because "run the lens if we have one, and if we don't we'll assume the raw
// value is right" is not a simple Typescript concept.
rxjs.withLatestFrom(state$), rxjs.mergeMap(([wrappedResult, stateAtReturn])=>{

@@ -255,4 +314,4 @@ if (standardResult.isOk(wrappedResult)) {

// Type coercion is due to Typescript not following unions quite right
const newState = builder.mapOnSuccess ? builder.mapOnSuccess(result)(stateAtReturn.payload) : result;
return rxjs.of(buildSucceedActionCreator(builder).create(newState));
const mappedNewState = builder.mapOnSuccess ? builder.mapOnSuccess(result)(stateAtReturn.payload) : result;
return rxjs.of(buildSucceedActionCreator(builder).create(mappedNewState));
}

@@ -267,9 +326,23 @@ const result = wrappedResult.failure;

;
const buildAsyncEffectWithLens = (builder)=>(action$, state$)=>buildAsyncEffect(builder)(action$, state$.pipe(rxjs.map(builder.lens.get)))
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure. This runs inside a lens, so
* as to operate on a larger data structure.
*
* @param builder
* @return The async effect
*/ const buildAsyncEffectWithLens = (builder)=>(action$, state$)=>// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any is of limited scope and not worth specifying
buildAsyncEffect(builder)(action$, state$.pipe(rxjs.map(builder.lens.get)))
;
/**
* If we input a lens it outputs a lens that goes from the outer structure of the input
* lens to the async state's payload. If we do not input a lens it outputs a lens that goes
* from the async state to its payload.
*
* @param builder
*/ function buildPayloadLens(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- we're using overloads
function buildPayloadLens(builder) {
const innerPayloadLens = standardLens.createLensCreator().fromPath('payload');

@@ -282,12 +355,28 @@ if (builder.lens) {

const combineEffects = (...effects)=>(action$, state$)=>rxjs.merge(...effects.map((effect)=>effect(action$, state$)
/**
* Combines multiple effects into one, merging all of their observables.
*
* @param effects The effects to combine.
* @return The combined effect.
*/ const combineEffects = (...effects)=>(action$, state$)=>rxjs.merge(...effects.map((effect)=>effect(action$, state$)
))
;
const combineActionReducers = (...reducers)=>(action)=>(state)=>reducers.reduce((currentState, reducer)=>reducer(action)(currentState)
/**
* Combines action reducers by calling each of them in succession
*
* @param reducers Reducers to combine
* @return Action reducer that combines all effects
*/ const combineActionReducers = (...reducers)=>(action)=>(state)=>reducers.reduce((currentState, reducer)=>reducer(action)(currentState)
, state)
;
const on = (filter, reducer)=>(action)=>{
/**
* Makes it easier to build reducers by filtering actions first, narrowing their type.
* If the type matches it then calls the given reducer
*
* @param filter A function that filters the action down to the desired actions.
* @param reducer A reducer that operates on the desired action.
* @return A reducer that operates on any action.
*/ const on = (filter, reducer)=>(action)=>{
if (filter(action)) {
// sorry for coercion. TS can't detect the typeguard logic through the ActionOf<> type.
return reducer(action);

@@ -299,17 +388,64 @@ }

;
const requireSource = (...sources)=>(action)=>sources.length === 0 || sources.includes(action.source)
/**
* Filters actions based on the desired source. Actions that do no have a source will fail
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source: false if otherwise.
* @deprecated
*/ const requireSource = (...sources)=>(action)=>sources.length === 0 || sources.includes(action.source)
;
const optionalSource = (...sources)=>(action)=>sources.length === 0 || !action.source || sources.includes(action.source)
/**
* Filters actions based on the desired source. Actions that do no have a source will pass
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source or no source: false if otherwise.
* @deprecated
*/ const optionalSource = (...sources)=>(action)=>sources.length === 0 || !action.source || sources.includes(action.source)
;
const isType = (...actionTypes)=>(action)=>actionTypes.includes(action.type)
/**
* Filters actions by the desired type
*
* @param actionTypes The desired action types.
* @return True if the type is one of the desired action types: false if otherwise.
*/ const isType = (...actionTypes)=>(action)=>actionTypes.includes(action.type)
;
const isSubtype = (...actionSubtypes)=>(action)=>actionSubtypes.includes(action.subtype)
/**
* Filters actions by the desired subtype
*
* @param actionSubtypes The desired action subtypes.
* @return True if the subtype is one of the desired action types: false if otherwise.
*/ const isSubtype = (...actionSubtypes)=>(action)=>actionSubtypes.includes(action.subtype)
;
const matches = (specifier, extraSources)=>(inputAction)=>specifier.type === inputAction.type && specifier.subtype === inputAction.subtype && (extraSources === undefined || requireSource(specifier.source, ...extraSources)(inputAction)) && equal__default["default"](specifier.filterMetadata, inputAction.filterMetadata)
/**
* Type guard that tells you whether an action matches a given action specifier.
*
* @param specifier Action specifier to match
* @param extraSources Possible extra values of the source field that are allowed. (Deprecated)
* @return True if the action matches the specifier: false if not.
*/ const matches = (specifier, extraSources)=>(inputAction)=>specifier.type === inputAction.type && specifier.subtype === inputAction.subtype && (extraSources === undefined || requireSource(specifier.source, ...extraSources)(inputAction)) && equal__default["default"](specifier.filterMetadata, inputAction.filterMetadata)
;
const and = (outerTypeguard, innerTypeguard)=>(action)=>outerTypeguard(action) && innerTypeguard(action)
/**
* Combines two type guards such that an action must comply with both.
*
* @param outerTypeguard First type guard to be called.
* @param innerTypeguard Second type guard to be called if the outer returns true.
* @return True if the action matches both specifiers: false if not.
*/ const and = (outerTypeguard, innerTypeguard)=>(action)=>outerTypeguard(action) && innerTypeguard(action)
;
const or = (typeguardA, typeguardB)=>(action)=>typeguardA(action) || typeguardB(action)
/**
* Combines two type guards such that an action must comply with either.
*
* @param typeguardA First type guard to be called.
* @param typeguardB Second type guard to be called if the first returns false.
* @return True if the action matches either specifiers: false if not.
*/ const or = (typeguardA, typeguardB)=>(action)=>typeguardA(action) || typeguardB(action)
;
const composeStateReducers = (outerReducer)=>(innerReducer)=>(state)=>outerReducer(innerReducer(state))
/**
* Combines two state reducers calling the inner and then the outer.
*
* @param outerReducer The state reducer
* @return A function that takes another reducer and returns the combined state reducer.
*/ const composeStateReducers = (outerReducer)=>(innerReducer)=>(state)=>outerReducer(innerReducer(state))
;

@@ -324,2 +460,6 @@

const UpdateReducersAction = createActionCreator({
actionKey: '@brandingbrand/cargo-hold/update-reducers'
});
/**

@@ -330,19 +470,43 @@ * `Store` provides the state container and facilitates effects & reducers upon state.

*/ class Store extends ActionBus {
get state() {
/**
* Synchronous getter for current state. Use `state$` when possible.
*
* @return Current state
*/ get state() {
return this.subject$.value;
}
get state$() {
/**
* Getter for the state observable
*
* @return The state observable
*/ get state$() {
return this.subject$.asObservable();
}
get reducer$() {
// Concatenates the reducers into an observable array.
return this.internalReducer$.asObservable().pipe(accumulateToArray(), operators.map((reducers)=>combineActionReducers(...reducers)
));
}
/**
* Registers a new effect to the store.
*
* @param effect The effect to register.
* @return A subscription. Unsubscribe to the subscription to stop the effect from listening
*/ get reducedAction$() {
return this.internalReducedAction$.asObservable();
}
constructor(initialState){
super();
this.reducer$ = new rxjs.ReplaySubject(Number.POSITIVE_INFINITY);
this.reducedAction$ = new rxjs.Subject();
this.initialState = initialState;
this.subject$ = new rxjs.BehaviorSubject(this.initialState);
this.internalReducedAction$ = new rxjs.Subject();
this.internalReducer$ = new rxjs.ReplaySubject(Number.POSITIVE_INFINITY);
this.registerReducer = (reducer)=>{
this.reducer$.next(reducer);
this.internalReducer$.next(reducer);
this.dispatch(UpdateReducersAction.create());
};
this.registerEffect = (effect)=>{
const subscription = effect(this.reducedAction$, this.state$).subscribe({
const subscription = effect(this.internalReducedAction$, this.state$).subscribe({
next: (value)=>{
this._action$.next(value);
this.dispatch(value);
}

@@ -353,11 +517,8 @@ });

};
const allReducers$ = this.reducer$.pipe(accumulateToArray());
this.subject$ = new rxjs.BehaviorSubject(initialState);
const reducerSubscription = allReducers$.pipe(operators.switchMap((reducers)=>this._action$.pipe(operators.scan((currentState, action)=>reducers.reduce((state, reducer)=>reducer(action)(state)
, currentState)
, initialState), operators.withLatestFrom(this._action$))
const reducerSubscription = this.reducer$.pipe(operators.switchMap((reducer)=>this.action$.pipe(operators.scan((state, action)=>reducer(action)(state)
, initialState), operators.withLatestFrom(this.action$))
)).subscribe({
next: ([state, action])=>{
this.subject$.next(state);
this.reducedAction$.next(action);
this.internalReducedAction$.next(action);
},

@@ -430,13 +591,46 @@ complete: ()=>{

}
const buildInitStateReducer = (_builder)=>(payload)=>()=>createIdleState(payload)
/**
* Given a payload it will return a state reducer that gives us an idle state of that payload.
*
* @param _builder
* @return
*/ const buildInitStateReducer = (_builder)=>(payload)=>()=>createIdleState(payload)
;
const buildLoadingStateReducer = (_builder)=>(payload)=>()=>createLoadingState(payload)
/**
* Given a payload it will return a state reducer that gives us a loading state of that payload.
*
* @param _builder
* @return
*/ const buildLoadingStateReducer = (_builder)=>(payload)=>()=>createLoadingState(payload)
;
const buildLoadingMoreStateReducer = (_builder)=>(payload)=>()=>createLoadingMoreState(payload)
/**
* Given a payload it will return a state reducer that gives us a loading more state
* of that payload.
*
* @param _builder
* @return
*/ const buildLoadingMoreStateReducer = (_builder)=>(payload)=>()=>createLoadingMoreState(payload)
;
const buildSuccessStateReducer = (_builder)=>(payload)=>()=>createSuccessState(payload)
/**
* Given a payload it will return a state reducer that gives us a success state of that payload.
*
* @param _builder
* @return
*/ const buildSuccessStateReducer = (_builder)=>(payload)=>()=>createSuccessState(payload)
;
const buildFailureStateReducer = (_builder)=>(failure)=>(state)=>createFailureState(state.payload, failure)
/**
* Given a failure it will return a state reducer that gives us a failure state.
*
* @param _builder
* @return
*/ const buildFailureStateReducer = (_builder)=>(failure)=>(state)=>createFailureState(state.payload, failure)
;
const buildRevertStateReducer = (_builder)=>(payload)=>(state)=>_objectSpread$4({}, state, {
/**
* Given a payload it will return a state reducer that reverts to the given payload but leaving
* the status the same.
*
* @param _builder
* @return
*/ const buildRevertStateReducer = (_builder)=>(payload)=>(state)=>// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- fixes a nuanced type issue.
_objectSpread$4({}, state, {
payload

@@ -448,52 +642,107 @@ })

;
const buildInitActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildInitActionCreator, buildInitStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in an idle state.
*
* @param builder A builder with an action key and an idle type.
* @return
*/ const buildInitActionReducer = (builder)=>standardCompose.pipe(builder, // buildInitActionCreator will take WithMetadata and do the right thing.
standardCompose.branch(buildInitActionCreator, buildInitStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildLoadingActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildLoadingActionCreator, buildLoadingStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), // slight coercion necessary as TS isn't picking up the union quite properly
(action)=>stateReducerCreator(action.payload)
/**
* Given a builder this makes an action reducer that results in a loading state.
*
* @param builder A builder with an action key and a loading type.
* @return
*/ const buildLoadingActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildLoadingActionCreator, buildLoadingStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
)
)
;
const buildLoadingMoreActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildLoadingMoreActionCreator, buildLoadingMoreStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in a loading more state.
*
* @param builder A builder with an action key and a loading more type.
* @return
*/ const buildLoadingMoreActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildLoadingMoreActionCreator, buildLoadingMoreStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildSuccessActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildSucceedActionCreator, buildSuccessStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
/**
* Given a builder this makes an action reducer that results in a success state.
*
* @param builder A builder with an action key and a success type.
* @return
*/ const buildSuccessActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildSucceedActionCreator, buildSuccessStateReducer), ([actionCreator, stateReducerCreator])=>makeActionReducer(actionCreator, stateReducerCreator)
)
;
const buildFailureActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildFailActionCreator, buildFailureStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>(state)=>stateReducerCreator(action.payload)(state)
/**
* Given a builder this makes an action reducer that results in a failure state.
*
* @param builder A builder with an action key and payload types.
* @return
*/ const buildFailureActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildFailActionCreator, buildFailureStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>(state)=>stateReducerCreator(action.payload)(state)
)
)
;
const buildRevertActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildRevertActionCreator, buildRevertStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
/**
* Given a builder this makes an action reducer that results in a reverted payload.
*
* @param builder A builder with an action key and payload types.
* @return
*/ const buildRevertActionReducer = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildRevertActionCreator, buildRevertStateReducer), ([actionCreator, stateReducerCreator])=>on(matches(actionCreator), (action)=>stateReducerCreator(action.payload)
)
)
;
const buildCombinedReducers = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildInitActionReducer, buildLoadingActionReducer, buildLoadingMoreActionReducer, buildSuccessActionReducer, buildFailureActionReducer, buildRevertActionReducer), (actionReducers)=>combineActionReducers(...actionReducers)
/**
* Given a builder it makes an action reducer that looks for all of the async actions
* and performs the appropriate state change.
*
* @param builder A builder with an action key an payload types.
* @return
*/ const buildCombinedReducers = (builder)=>standardCompose.pipe(builder, standardCompose.branch(buildInitActionReducer, buildLoadingActionReducer, buildLoadingMoreActionReducer, buildSuccessActionReducer, buildFailureActionReducer, buildRevertActionReducer), (actionReducers)=>combineActionReducers(...actionReducers)
)
;
const buildCombinedLensedReducers = (builder)=>(action)=>standardLens.withLens(builder.lens)(buildCombinedReducers(builder)(action))
/**
* Returns an action reducer from buildCombinedReducers, but run in a lens so that it handles
* a larger data structure.
*
* @param builder
* @return
*/ const buildCombinedLensedReducers = (builder)=>(action)=>standardLens.withLens(builder.lens)(buildCombinedReducers(builder)(action))
;
/**
* Takes a builder and returns a selector that selects the payload.
*
* @param builder
*/ function buildSelectPayload(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectPayload(builder) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return buildPayloadLens(builder).get;
}
/**
* Takes a builder and returns a selector that selects the status.
*
* @param builder
*/ function buildSelectStatus(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectStatus(builder) {
const statusLens = standardLens.createLensCreator().fromPath('status');
if (builder.lens) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return statusLens.withOuterLens(builder.lens).get;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return statusLens.get;
}
/**
* Takes a builder and returns a selector that selects the failure data if available.
*
* @param builder
*/ function buildSelectFailure(builder) {
* @return
*/ // eslint-disable-next-line prefer-arrow/prefer-arrow-functions -- cant use arrow functions for overloading.
function buildSelectFailure(builder) {
const failureLens = standardLens.createLensCreator().fromPath('failure');
if (builder.lens) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return -- the any is limited in scope and not worth it to describe.
return failureLens.withOuterLens(// this coercion is fine; the lens just gets 'failure' from it so if it's not a failure,

@@ -503,2 +752,3 @@ // it'll return undefined, which is what we want.

}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any -- the any is limited in scope and not worth it to describe.
return failureLens.get;

@@ -836,3 +1086,9 @@ }

;
const makeSetMany = (deps)=>(items)=>standardLens.withLens(deps.lens)((state)=>{
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* overriding existing ids that collide.
*
* @param deps
* @return
*/ const makeSetMany = (deps)=>(items)=>standardLens.withLens(deps.lens)((state)=>{
const entities = _objectSpread$1({}, state.entities, fromEntityArray(deps)(items));

@@ -846,7 +1102,19 @@ const ids = mergeIdLists(...state.ids, ...items.map(deps.idSelector));

;
const makeSetOne = (deps)=>(item)=>makeSetMany(deps)([
/**
* Takes an item and makes a reducer that adds that item to an existing state, overriding
* the existing id if it exists.
*
* @param deps
* @return
*/ const makeSetOne = (deps)=>(item)=>makeSetMany(deps)([
item
])
;
const makeAddMany = (deps)=>(items)=>(structure)=>{
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* preserving existing ids.
*
* @param deps
* @return
*/ const makeAddMany = (deps)=>(items)=>(structure)=>{
const state = deps.lens.get(structure);

@@ -863,11 +1131,32 @@ const newIds = items.map(deps.idSelector).filter((val)=>!state.ids.includes(val)

;
const makeAddOne = (deps)=>(item)=>makeAddMany(deps)([
/**
* Takes an item and makes a reducer that adds that item to an existing state, preserving
* the existing id if it exists.
*
* @param deps
* @return
*/ const makeAddOne = (deps)=>(item)=>makeAddMany(deps)([
item
])
;
const makeSetAll = (deps)=>(items)=>(structure)=>makeSetMany(deps)(items)(deps.lens.set(makeCreateState(deps)([]))(structure))
/**
* Takes an array of items and replaces the existing state with the incoming state.
*
* @param deps
* @return
*/ const makeSetAll = (deps)=>(items)=>(structure)=>makeSetMany(deps)(items)(deps.lens.set(makeCreateState(deps)([]))(structure))
;
const makeRemoveAll = (deps)=>()=>(structure)=>deps.lens.set(makeCreateState(deps)([]))(structure)
/**
* Removes all entities and state ids.
*
* @param deps
* @return
*/ const makeRemoveAll = (deps)=>()=>(structure)=>deps.lens.set(makeCreateState(deps)([]))(structure)
;
const makeRemoveMany = (deps)=>(ids)=>standardLens.withLens(deps.lens)((state)=>{
/**
* Takes an array of entity ids and returns a reducer that removes those ids if they exist.
*
* @param deps
* @return
*/ const makeRemoveMany = (deps)=>(ids)=>standardLens.withLens(deps.lens)((state)=>{
const newIds = state.ids.filter((id)=>!ids.includes(id)

@@ -888,7 +1177,17 @@ );

;
const makeRemoveOne = (deps)=>(id)=>makeRemoveMany(deps)([
/**
* Takes an entity id, returns a reducer that removes it if it exists.
*
* @param deps
* @return
*/ const makeRemoveOne = (deps)=>(id)=>makeRemoveMany(deps)([
id
])
;
const makeReducers = (deps)=>({
/**
* Returns a full suite of reducers applying the given dependencies.
*
* @param deps
* @return
*/ const makeReducers = (deps)=>({
addMany: makeAddMany(deps),

@@ -905,3 +1204,9 @@ addOne: makeAddOne(deps),

const makeSelectAll = (lens)=>(structure)=>{
/**
* Take all of the entities in an entity state from a given lens and returns
* an array of the entities.
*
* @param lens
* @return
*/ const makeSelectAll = (lens)=>(structure)=>{
const state = lens.get(structure);

@@ -919,3 +1224,8 @@ // TODO @grayontheweb 04-01-2022 this pattern is repeated with minor

;
const makeSelectByIds = (lens)=>(ids)=>(structure)=>{
/**
* Select the given Ids from the entity state from a give lens and returns an array of them.
*
* @param lens
* @return
*/ const makeSelectByIds = (lens)=>(ids)=>(structure)=>{
const state = lens.get(structure);

@@ -931,3 +1241,9 @@ return ids.reduce((acc, id)=>{

;
const makeSelectById = (lens)=>(id)=>(structure)=>{
/**
* Select the given Id from the entity state from a give lens and returns either the entity
* or undefined.
*
* @param lens
* @return
*/ const makeSelectById = (lens)=>(id)=>(structure)=>{
const state = lens.get(structure);

@@ -937,9 +1253,19 @@ return id in state.entities ? state.entities[id] : undefined;

;
const makeSelectByIndex = (lens)=>(index)=>(structure)=>{
/**
* Given an index it will select the Nth value if it exists.
*
* @param lens
* @return
*/ const makeSelectByIndex = (lens)=>(index)=>(structure)=>{
const state = lens.get(structure);
const id = state.ids[index];
return id ? state.entities[id] : undefined;
return id !== undefined ? state.entities[id] : undefined;
}
;
const makeSelectByIndices = (lens)=>(indices)=>(structure)=>{
/**
* Given multiple indices it will select the Nth values if they exist.
*
* @param lens
* @return
*/ const makeSelectByIndices = (lens)=>(indices)=>(structure)=>{
const state = lens.get(structure);

@@ -949,3 +1275,3 @@ return indices.reduce((acc, index)=>{

const entity = id ? state.entities[id] : undefined;
return entity && entity in state.entities ? [
return entity !== undefined && entity in state.entities ? [
...acc,

@@ -957,3 +1283,8 @@ entity

;
const getSelectors = (lens)=>({
/**
* Returns the full suite of selectors given the lens.
*
* @param lens
* @return
*/ const getSelectors = (lens)=>({
selectAll: makeSelectAll(lens),

@@ -997,3 +1328,8 @@ selectByIds: makeSelectByIds(lens),

;
const createEntityAdaptor = (options)=>{
/**
* Creates an entity adapter.
*
* @param options Options to create the entity adapter.
* @return
*/ const createEntityAdaptor = (options)=>{
const isSorted = Boolean(options.comparer);

@@ -1031,3 +1367,5 @@ var _lens;

};
const EMPTY_ENTITY_STATE = {
/**
* A constant that is a good initial state for any entity state.
*/ const EMPTY_ENTITY_STATE = {
entities: {},

@@ -1037,3 +1375,8 @@ ids: []

const getDefaultedEntity = (id)=>(state)=>{
/**
* Returns the entity for a given id, if no id is provided it returns the first entity.
*
* @param id Optional entity id.
* @return Entity represented by the id, or the first entity.
*/ const getDefaultedEntity = (id)=>(state)=>{
const defaultedId = id !== null && id !== void 0 ? id : state.ids[0];

@@ -1049,3 +1392,5 @@ if (defaultedId === undefined) {

exports.EMPTY_ENTITY_STATE = EMPTY_ENTITY_STATE;
exports.InitAction = InitAction;
exports.Store = Store;
exports.UpdateReducersAction = UpdateReducersAction;
exports.and = and;

@@ -1052,0 +1397,0 @@ exports.asyncBuilder = asyncBuilder;

10

package.json
{
"name": "@brandingbrand/cargo-hold",
"version": "11.66.0",
"version": "11.67.0",
"license": "MIT",

@@ -10,6 +10,6 @@ "typings": "./src/index.d.ts",

"rxjs": "^7.5.2",
"@brandingbrand/standard-compose": "11.66.0",
"@brandingbrand/standard-result": "11.66.0",
"@brandingbrand/types-utility": "11.66.0",
"@brandingbrand/standard-lens": "11.66.0",
"@brandingbrand/standard-compose": "11.67.0",
"@brandingbrand/standard-result": "11.67.0",
"@brandingbrand/types-utility": "11.67.0",
"@brandingbrand/standard-lens": "11.67.0",
"fast-deep-equal": "^3.1.3"

@@ -16,0 +16,0 @@ },

import type { Observable } from 'rxjs';
import { Subject, Subscription } from 'rxjs';
import { Subscription } from 'rxjs';
import type { PAYLOAD } from '../internal/tokens';
import type { TypeGuard } from './action';
import type { Action, ActionHandler, AnyAction, AnyActionHandler, AnyActionSpecifier, Dispatch } from './action-bus.types';
import type { Action, ActionHandler, AnyAction, AnyActionHandler, Dispatch } from './action-bus.types';
/**
* Action buses provide a way to subscribe to actions dispatched anywhere.
*/
export declare class ActionBus {
private readonly internalAction$;
protected readonly subscriptions: Subscription;
protected readonly _action$: Subject<AnyAction<unknown>>;
constructor();
/**
* Getter for observable actions
*
* @return Action observable
*/
get action$(): Observable<AnyAction>;
/**
* Dispatches an action into the action bus
*
* @param action The action to dispatch
*/
dispatch: Dispatch;
/**
* Registers a handler to this action bus
*
* @param handler handler that gets registered
*/
registerHandler(handler: AnyActionHandler): Subscription;
registerHandler<Specifier extends AnyActionSpecifier>(guard: TypeGuard<AnyActionSpecifier, Specifier>, handler: ActionHandler<Action<Specifier['type'], NonNullable<Specifier[typeof PAYLOAD]>, Specifier['subtype']>>): Subscription;
/**
* Registers a handler to this action bus
*
* @param guard type guard to filter actions
* @param handler handler that gets registered
*/
registerHandler<ActionType extends AnyAction>(guard: TypeGuard<AnyAction, ActionType>, handler: ActionHandler<Action<ActionType['type'], NonNullable<ActionType[typeof PAYLOAD]>, ActionType['subtype']>>): Subscription;
/**
* Releases all subscriptions before destroying the action bus
*
*/
dispose: () => void;
}

@@ -14,4 +14,4 @@ import type { Observable } from 'rxjs';

export declare const createActionCreator: <ActionKey extends string, Subtype extends string | undefined, Payload, Params extends unknown[] = []>(options: CreateActionOptions<ActionKey, Subtype, Payload, Params>) => ActionCreator<ActionKey, Subtype, Payload, Params>;
export declare const createHandler: <Specifier extends AnyActionSpecifier>(guard: TypeGuard<AnyActionSpecifier, Specifier>, handler: ActionHandler<Action<Specifier["type"], NonNullable<Specifier[typeof PAYLOAD]>, Specifier["subtype"]>>) => (action$: Observable<AnyAction>) => import("rxjs").Subscription;
export declare const createHandler: <ActionType extends AnyAction<unknown>>(guard: TypeGuard<AnyAction<unknown>, ActionType>, handler: ActionHandler<Action<ActionType["type"], NonNullable<ActionType[typeof PAYLOAD]>, ActionType["subtype"]>>) => (action$: Observable<AnyAction>) => import("rxjs").Subscription;
export declare const ofType: <ActionType extends AnyActionSpecifier>(...selectActions: NonEmptyArray<ActionType>) => import("rxjs").OperatorFunction<AnyAction<unknown>, Action<ActionType["type"], NonNullable<ActionType[typeof PAYLOAD]>, ActionType["subtype"]>>;
export declare const notOfType: (...selectActions: NonEmptyArray<AnyActionSpecifier>) => import("rxjs").MonoTypeOperatorFunction<AnyAction<unknown>>;
export * from './action';
export * from './action-bus';
export * from './action-bus.types';
export * from './init.action';

@@ -0,15 +1,58 @@

import { ActionCreator } from '../../action-bus';
import type { WithActionKey, WithFailureType, WithIdleType, WithMetadata, WithPayloadTypes, WithSuccessType } from './async.builder.types';
export declare const buildInitActionCreator: <ActionKey extends string, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithIdleType<IdleType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:init", IdleType, [idlePayload: IdleType]>;
export declare const buildLoadingActionCreator: <ActionKey extends string, SuccessType, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithIdleType<IdleType> & WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:load", SuccessType | IdleType, [loadingPayload: SuccessType | IdleType]>;
export declare const buildLoadingMoreActionCreator: <ActionKey extends string, SuccessType, MetadataType extends Record<string, unknown> | undefined>(builder: WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:load-more", SuccessType, [loadingPayload: SuccessType]>;
export declare const buildSucceedActionCreator: <ActionKey extends string, SuccessType, MetadataType extends Record<string, unknown> | undefined>(builder: WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:succeed", SuccessType, [succeedPayload: SuccessType]>;
export declare const buildFailActionCreator: <ActionKey extends string, FailureType, MetadataType extends Record<string, unknown> | undefined>(builder: WithFailureType<FailureType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:fail", FailureType, [failure: FailureType]>;
export declare const buildRevertActionCreator: <ActionKey extends string, SuccessType, FailureType, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithActionKey<ActionKey> & WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => import("../../action-bus").ActionCreator<ActionKey, "async:revert", SuccessType | IdleType, [revertPayload: SuccessType | IdleType]>;
/**
* Takes a builder and returns an init action creator.
*
* @param builder
* @return
*/
export declare const buildInitActionCreator: <ActionKey extends string, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithIdleType<IdleType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:init", IdleType, [IdleType]>;
/**
* Takes a builder and returns a loading action creator.
*
* @param builder
* @return
*/
export declare const buildLoadingActionCreator: <ActionKey extends string, SuccessType, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithIdleType<IdleType> & WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:load", SuccessType | IdleType, [SuccessType | IdleType]>;
/**
* Takes a builder and returns a loading more action creator.
*
* @param builder
* @return
*/
export declare const buildLoadingMoreActionCreator: <ActionKey extends string, SuccessType, MetadataType extends Record<string, unknown> | undefined>(builder: WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:load-more", SuccessType, [SuccessType]>;
/**
* Takes a builder and returns a success action creator.
*
* @param builder
* @return
*/
export declare const buildSucceedActionCreator: <ActionKey extends string, SuccessType, MetadataType extends Record<string, unknown> | undefined>(builder: WithSuccessType<SuccessType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:succeed", SuccessType, [SuccessType]>;
/**
* Takes a builder and returns a failure action creator.
*
* @param builder
* @return
*/
export declare const buildFailActionCreator: <ActionKey extends string, FailureType, MetadataType extends Record<string, unknown> | undefined>(builder: WithFailureType<FailureType> & WithActionKey<ActionKey> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:fail", FailureType, [FailureType]>;
/**
* Takes a builder and returns a revert action creator.
*
* @param builder
* @return
*/
export declare const buildRevertActionCreator: <ActionKey extends string, SuccessType, FailureType, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithActionKey<ActionKey> & WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => ActionCreator<ActionKey, "async:revert", SuccessType | IdleType, [revertPayload: SuccessType | IdleType]>;
/**
* Builds a full suite of async action creators.
*
* @param builder
* @return
*/
export declare const buildActionCreators: <ActionKey extends string, SuccessType, FailureType, IdleType, MetadataType extends Record<string, unknown> | undefined>(builder: WithActionKey<ActionKey> & WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType> & (MetadataType extends Record<string, unknown> ? WithMetadata<MetadataType> : {})) => {
init: import("../../action-bus").ActionCreator<string, "async:init", IdleType, [idlePayload: IdleType]>;
load: import("../../action-bus").ActionCreator<string, "async:load", unknown, [loadingPayload: unknown]>;
loadMore: import("../../action-bus").ActionCreator<string, "async:load-more", SuccessType, [loadingPayload: SuccessType]>;
succeed: import("../../action-bus").ActionCreator<string, "async:succeed", SuccessType, [succeedPayload: SuccessType]>;
fail: import("../../action-bus").ActionCreator<string, "async:fail", FailureType, [failure: FailureType]>;
revert: import("../../action-bus").ActionCreator<ActionKey, "async:revert", unknown, [revertPayload: unknown]>;
init: ActionCreator<string, "async:init", IdleType, [IdleType]>;
load: ActionCreator<string, "async:load", unknown, [unknown]>;
loadMore: ActionCreator<string, "async:load-more", SuccessType, [SuccessType]>;
succeed: ActionCreator<string, "async:succeed", SuccessType, [SuccessType]>;
fail: ActionCreator<string, "async:fail", FailureType, [FailureType]>;
revert: ActionCreator<ActionKey, "async:revert", unknown, [revertPayload: unknown]>;
};
import type { IPathLens } from '@brandingbrand/standard-lens';
import type { MaybePromise } from '@brandingbrand/types-utility';
import type { ActionSpecifier, AnyActionSpecifier, TypeGuard } from '../..';
import type { AnyAction, TypeGuard } from '../../action-bus';
import type { AsyncBuilder, WithActionKey, WithAsyncCallback, WithEnableLoadingMore, WithFailureType, WithIdleType, WithLensInstance, WithMapOnFailure, WithMapOnSuccess, WithMetadata, WithOptimisticUpdate, WithPayloadTypes, WithSuccessType, WithTriggerActionFilter } from './async.builder.types';

@@ -13,3 +13,3 @@ import type { AsyncState } from './async.types';

export declare const withMetadata: <MetadataType extends Record<string, unknown>>(metadata: MetadataType) => <BuilderType extends AsyncBuilder>(builder: BuilderType) => BuilderType & WithMetadata<MetadataType>;
export declare const withTriggerActionFilter: <Specifier extends ActionSpecifier<string, any, unknown>>(triggerActionFilter: TypeGuard<AnyActionSpecifier, Specifier>) => <BuilderType extends AsyncBuilder>(builder: BuilderType) => BuilderType & WithTriggerActionFilter<Specifier>;
export declare const withTriggerActionFilter: <DesiredActionType extends AnyAction<unknown>>(triggerActionFilter: TypeGuard<AnyAction<unknown>, DesiredActionType>) => <BuilderType extends AsyncBuilder>(builder: BuilderType) => BuilderType & WithTriggerActionFilter<DesiredActionType>;
export declare const withAsyncCallback: <Input, CallbackResult>(callback: (input: Input) => MaybePromise<CallbackResult>) => <BuilderType extends AsyncBuilder>(builder: BuilderType) => BuilderType & WithAsyncCallback<Input, CallbackResult>;

@@ -16,0 +16,0 @@ export declare const withMapOnSuccess: <Input, PayloadType, StateType = PayloadType>(mapOnSuccess: (input: Input) => (oldPayload: StateType) => PayloadType) => <BuilderType extends AsyncBuilder>(builder: BuilderType) => BuilderType & WithMapOnSuccess<Input, StateType, PayloadType>;

@@ -1,7 +0,24 @@

import type { ActionSpecifier, AnyActionSpecifier } from '../../action-bus';
import type { AnyAction } from '../../action-bus';
import type { Effect } from '../../store';
import type { WithActionKey, WithAsyncCallback, WithEnableLoadingMore, WithLensInstance, WithMapOnFailure, WithMapOnSuccess, WithOptimisticUpdate, WithPayloadTypes, WithTriggerActionFilter } from './async.builder.types';
import type { AsyncState } from './async.types';
export declare type AsyncEffectDeps<ActionKey extends string, SuccessType, FailureType, IdleType, TriggerSpecifier extends AnyActionSpecifier, CallbackResult> = WithPayloadTypes<SuccessType, FailureType, IdleType> & WithActionKey<ActionKey> & WithTriggerActionFilter<TriggerSpecifier> & Partial<WithEnableLoadingMore> & Partial<WithMapOnFailure<unknown, FailureType>> & Partial<WithOptimisticUpdate<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload> ? Payload : never, SuccessType | IdleType, SuccessType>> & (CallbackResult extends SuccessType ? WithAsyncCallback<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload> ? Payload : never, SuccessType> & Partial<WithMapOnSuccess<CallbackResult, SuccessType>> : WithAsyncCallback<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload> ? Payload : never, CallbackResult> & WithMapOnSuccess<CallbackResult, SuccessType | IdleType, SuccessType>);
export declare const buildAsyncEffect: <ActionKey extends string, SuccessType, FailureType, IdleType, TriggerSpecifier extends AnyActionSpecifier, CallbackResult>(builder: AsyncEffectDeps<ActionKey, SuccessType, FailureType, IdleType, TriggerSpecifier, CallbackResult>) => Effect<AsyncState<SuccessType, FailureType, IdleType>>;
export declare const buildAsyncEffectWithLens: <ActionKey extends string, SuccessType, FailureType, IdleType, TriggerSpecifier extends AnyActionSpecifier, CallbackResult, OuterStructureType>(builder: import("./async.builder.types").WithFailureType<FailureType> & import("./async.builder.types").WithIdleType<IdleType> & import("./async.builder.types").WithSuccessType<SuccessType> & WithActionKey<ActionKey> & WithTriggerActionFilter<TriggerSpecifier> & Partial<WithEnableLoadingMore> & Partial<WithMapOnFailure<unknown, FailureType, FailureType>> & Partial<WithOptimisticUpdate<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload> ? Payload : never, SuccessType | IdleType, SuccessType>> & (CallbackResult extends SuccessType ? WithAsyncCallback<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload_1> ? Payload_1 : never, SuccessType> & Partial<WithMapOnSuccess<CallbackResult, SuccessType, SuccessType>> : WithAsyncCallback<TriggerSpecifier extends ActionSpecifier<string, any, infer Payload_2> ? Payload_2 : never, CallbackResult> & WithMapOnSuccess<CallbackResult, SuccessType | IdleType, SuccessType>) & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>) => Effect<OuterStructureType>;
export declare type AsyncEffectDeps<ActionKeyType extends string, SuccessType, FailureType, IdleType, TriggerActionType extends AnyAction, CallbackResultType> = Partial<WithEnableLoadingMore> & Partial<WithMapOnFailure<unknown, FailureType>> & Partial<WithOptimisticUpdate<TriggerActionType['payload'], IdleType | SuccessType, SuccessType>> & WithActionKey<ActionKeyType> & WithPayloadTypes<SuccessType, FailureType, IdleType> & WithTriggerActionFilter<TriggerActionType> & (CallbackResultType extends SuccessType ? Partial<WithMapOnSuccess<CallbackResultType, SuccessType>> & WithAsyncCallback<TriggerActionType['payload'], SuccessType> : WithAsyncCallback<TriggerActionType['payload'], CallbackResultType> & WithMapOnSuccess<CallbackResultType, IdleType | SuccessType, SuccessType>);
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure.
*
* @param builder
* @return The async effect
*/
export declare const buildAsyncEffect: <ActionKeyType extends string, SuccessType, FailureType, IdleType, TriggerActionType extends AnyAction<unknown>, CallbackResultType>(builder: AsyncEffectDeps<ActionKeyType, SuccessType, FailureType, IdleType, TriggerActionType, CallbackResultType>) => Effect<AsyncState<SuccessType, FailureType, IdleType>>;
/**
* Given a correctly-typed builder object, construct an Effect that will be triggered by the
* triggering action, instigate loading states, run optimistic predictions, and end with success or
* failure. Also reverts optimistic predictions if necessary on failure. This runs inside a lens, so
* as to operate on a larger data structure.
*
* @param builder
* @return The async effect
*/
export declare const buildAsyncEffectWithLens: <ActionKeyType extends string, SuccessType, FailureType, IdleType, ActionTriggerType extends AnyAction<unknown>, CallbackResultType, OuterStructureType>(builder: Partial<WithEnableLoadingMore> & Partial<WithMapOnFailure<unknown, FailureType, FailureType>> & Partial<WithOptimisticUpdate<ActionTriggerType["payload"], SuccessType | IdleType, SuccessType>> & WithActionKey<ActionKeyType> & import("./async.builder.types").WithFailureType<FailureType> & import("./async.builder.types").WithIdleType<IdleType> & import("./async.builder.types").WithSuccessType<SuccessType> & WithTriggerActionFilter<ActionTriggerType> & (CallbackResultType extends SuccessType ? Partial<WithMapOnSuccess<CallbackResultType, SuccessType, SuccessType>> & WithAsyncCallback<ActionTriggerType["payload"], SuccessType> : WithAsyncCallback<ActionTriggerType["payload"], CallbackResultType> & WithMapOnSuccess<CallbackResultType, SuccessType | IdleType, SuccessType>) & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>) => Effect<OuterStructureType>;
import type { IPathLens } from '@brandingbrand/standard-lens';
import type { WithLensInstance, WithPayloadTypes } from './async.builder.types';
import type { AsyncState } from './async.types';
/**
* Builds a lens that goes from an async state to its payload.
*
* @param builder
*/
export declare function buildPayloadLens<SuccessType, FailureType, IdleType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>>): IPathLens<AsyncState<SuccessType, FailureType, IdleType>, IdleType | SuccessType>;
/**
* Builds a lens that goes from the outer structure to the payload of an async state.
*
* @param builder
*/
export declare function buildPayloadLens<SuccessType, FailureType, IdleType, OuterStructureType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>> & WithLensInstance<SuccessType, FailureType, IdleType, OuterStructureType>): IPathLens<OuterStructureType, IdleType | SuccessType>;
import type { AnyActionReducer, StateReducer } from '../../store';
import type { WithActionKey, WithIdleType, WithLensInstance, WithPayloadTypes, WithSuccessType } from './async.builder.types';
import type { AsyncIdleState, AsyncLoadingMoreState, AsyncLoadingState, AsyncState, AsyncSuccessState } from './async.types';
/**
* Given a payload it will return a state reducer that gives us an idle state of that payload.
*
* @param _builder
* @return
*/
export declare const buildInitStateReducer: <IdleType>(_builder: WithIdleType<IdleType>) => (payload: IdleType) => () => AsyncIdleState<IdleType>;
/**
* Given a payload it will return a state reducer that gives us a loading state of that payload.
*
* @param _builder
* @return
*/
export declare const buildLoadingStateReducer: <SuccessType, IdleType>(_builder: WithIdleType<IdleType> & WithSuccessType<SuccessType>) => (payload: SuccessType | IdleType) => () => AsyncLoadingState<SuccessType | IdleType>;
/**
* Given a payload it will return a state reducer that gives us a loading more state
* of that payload.
*
* @param _builder
* @return
*/
export declare const buildLoadingMoreStateReducer: <SuccessType>(_builder: WithSuccessType<SuccessType>) => (payload: SuccessType) => () => AsyncLoadingMoreState<SuccessType>;
/**
* Given a payload it will return a state reducer that gives us a success state of that payload.
*
* @param _builder
* @return
*/
export declare const buildSuccessStateReducer: <SuccessType>(_builder: WithSuccessType<SuccessType>) => (payload: SuccessType) => () => AsyncSuccessState<SuccessType>;
/**
* Given a failure it will return a state reducer that gives us a failure state.
*
* @param _builder
* @return
*/
export declare const buildFailureStateReducer: <SuccessType, FailureType, IdleType>(_builder: WithPayloadTypes<SuccessType, FailureType, IdleType>) => (failure: FailureType) => (state: AsyncState<SuccessType, FailureType, IdleType>) => import("./async.types").AsyncFailureState<SuccessType | IdleType, FailureType>;
/**
* Given a payload it will return a state reducer that reverts to the given payload but leaving
* the status the same.
*
* @param _builder
* @return
*/
export declare const buildRevertStateReducer: <SuccessType, FailureType, IdleType>(_builder: WithPayloadTypes<SuccessType, FailureType, IdleType>) => (payload: SuccessType | IdleType) => StateReducer<AsyncState<SuccessType, FailureType, IdleType>>;
export declare const buildInitActionReducer: <ActionKey extends string, IdleType>(builder: WithActionKey<ActionKey> & WithIdleType<IdleType>) => AnyActionReducer<AsyncIdleState<IdleType>>;
export declare const buildLoadingActionReducer: <ActionKey extends string, SuccessType, IdleType>(builder: WithActionKey<ActionKey> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncLoadingState<SuccessType | IdleType>>;
export declare const buildLoadingMoreActionReducer: <ActionKey extends string, SuccessType>(builder: WithActionKey<ActionKey> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncLoadingMoreState<SuccessType>>;
export declare const buildSuccessActionReducer: <ActionKey extends string, SuccessType>(builder: WithActionKey<ActionKey> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncSuccessState<SuccessType>>;
export declare const buildFailureActionReducer: <ActionKey extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKey> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
export declare const buildRevertActionReducer: <ActionKey extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKey> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
export declare const buildCombinedReducers: <ActionKey extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKey> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
export declare const buildCombinedLensedReducers: <ActionKey extends string, SuccessType, FailureType, IdleType, OuterStructureType>(builder: WithActionKey<ActionKey> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<OuterStructureType>;
/**
* Given a builder this makes an action reducer that results in an idle state.
*
* @param builder A builder with an action key and an idle type.
* @return
*/
export declare const buildInitActionReducer: <ActionKeyType extends string, IdleType>(builder: WithActionKey<ActionKeyType> & WithIdleType<IdleType>) => AnyActionReducer<AsyncIdleState<IdleType>>;
/**
* Given a builder this makes an action reducer that results in a loading state.
*
* @param builder A builder with an action key and a loading type.
* @return
*/
export declare const buildLoadingActionReducer: <ActionKeyType extends string, SuccessType, IdleType>(builder: WithActionKey<ActionKeyType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncLoadingState<SuccessType | IdleType>>;
/**
* Given a builder this makes an action reducer that results in a loading more state.
*
* @param builder A builder with an action key and a loading more type.
* @return
*/
export declare const buildLoadingMoreActionReducer: <ActionKeyType extends string, SuccessType>(builder: WithActionKey<ActionKeyType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncLoadingMoreState<SuccessType>>;
/**
* Given a builder this makes an action reducer that results in a success state.
*
* @param builder A builder with an action key and a success type.
* @return
*/
export declare const buildSuccessActionReducer: <ActionKeyType extends string, SuccessType>(builder: WithActionKey<ActionKeyType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncSuccessState<SuccessType>>;
/**
* Given a builder this makes an action reducer that results in a failure state.
*
* @param builder A builder with an action key and payload types.
* @return
*/
export declare const buildFailureActionReducer: <ActionKeyType extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKeyType> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
/**
* Given a builder this makes an action reducer that results in a reverted payload.
*
* @param builder A builder with an action key and payload types.
* @return
*/
export declare const buildRevertActionReducer: <ActionKeyType extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKeyType> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
/**
* Given a builder it makes an action reducer that looks for all of the async actions
* and performs the appropriate state change.
*
* @param builder A builder with an action key an payload types.
* @return
*/
export declare const buildCombinedReducers: <ActionKeyType extends string, SuccessType, FailureType, IdleType>(builder: WithActionKey<ActionKeyType> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<AsyncState<SuccessType, FailureType, IdleType>>;
/**
* Returns an action reducer from buildCombinedReducers, but run in a lens so that it handles
* a larger data structure.
*
* @param builder
* @return
*/
export declare const buildCombinedLensedReducers: <ActionKeyType extends string, SuccessType, FailureType, IdleType, OuterStructureType>(builder: WithActionKey<ActionKeyType> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType> & import("./async.builder.types").WithFailureType<FailureType> & WithIdleType<IdleType> & WithSuccessType<SuccessType>) => AnyActionReducer<OuterStructureType>;

@@ -1,8 +0,40 @@

import type { WithLensInstance, WithPayloadTypes } from './async.builder.types';
import type { WithIdleType, WithLensInstance, WithPayloadTypes, WithSuccessType } from './async.builder.types';
import type { AsyncState, AsyncStatus } from './async.types';
/**
* Takes a builder and returns a selector that selects the payload.
*
* @param builder
*/
export declare function buildSelectPayload<SuccessType, FailureType, IdleType, OuterStructureType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>): (input: OuterStructureType) => IdleType | SuccessType;
export declare function buildSelectPayload<SuccessType, FailureType, IdleType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>>): (input: AsyncState<SuccessType, FailureType, IdleType>) => IdleType | SuccessType;
/**
* Takes a builder and returns a selector that selects the payload.
*
* @param builder
*/
export declare function buildSelectPayload<SuccessType, IdleType>(builder: WithIdleType<IdleType> & WithSuccessType<SuccessType>): (input: AsyncState<SuccessType, unknown, IdleType>) => IdleType | SuccessType;
/**
* Takes a builder and returns a selector that selects the status.
*
* @param builder
*/
export declare function buildSelectStatus<SuccessType, FailureType, IdleType, OuterStructureType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>): (input: OuterStructureType) => AsyncStatus;
/**
* Takes a builder and returns a selector that selects the status.
*
* @param builder
*/
export declare function buildSelectStatus<SuccessType, FailureType, IdleType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>>): (input: AsyncState<SuccessType, FailureType, IdleType>) => AsyncStatus;
export declare function buildSelectFailure<SuccessType, FailureType, IdleType, OuterStructureType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>): (input: AsyncState<SuccessType, FailureType, IdleType>) => FailureType | undefined;
/**
* Takes a builder and returns a selector that selects the failure data if available.
*
* @param builder
* @return
*/
export declare function buildSelectFailure<SuccessType, FailureType, IdleType, OuterStructureType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>> & WithLensInstance<IdleType, SuccessType, FailureType, OuterStructureType>): (input: OuterStructureType) => FailureType | undefined;
/**
* Takes a builder and returns a selector that selects the failure data if available.
*
* @param builder
* @return
*/
export declare function buildSelectFailure<SuccessType, FailureType, IdleType>(builder: Partial<WithPayloadTypes<SuccessType, FailureType, IdleType>>): (input: AsyncState<SuccessType, FailureType, IdleType>) => FailureType | undefined;
import type { IPathLens } from '@brandingbrand/standard-lens';
import type { MaybePromise } from '@brandingbrand/types-utility';
import type { ActionSpecifier, AnyActionSpecifier, TypeGuard } from '../../action-bus';
import type { AnyAction, TypeGuard } from '../../action-bus';
import type { AsyncState } from './async.types';

@@ -22,22 +22,22 @@ declare const IDLE_SYMBOL: unique symbol;

};
export declare type WithActionKey<ActionKey extends string> = {
actionKey: ActionKey;
export declare type WithActionKey<ActionKeyType extends string> = {
actionKey: ActionKeyType;
};
export declare type WithMetadata<Metadata extends Record<string, unknown>> = {
metadata: Metadata;
export declare type WithMetadata<MetadataType extends Record<string, unknown>> = {
metadata: MetadataType;
};
export declare type WithTriggerActionFilter<Specifier extends ActionSpecifier<string, any, unknown>> = {
triggerActionFilter: TypeGuard<AnyActionSpecifier, Specifier>;
export declare type WithTriggerActionFilter<ActionType extends AnyAction> = {
triggerActionFilter: TypeGuard<AnyAction, ActionType>;
};
export declare type WithAsyncCallback<Input, Output> = {
callback: (input: Input) => MaybePromise<Output>;
export declare type WithAsyncCallback<InputType, OutputType> = {
callback: (input: InputType) => MaybePromise<OutputType>;
};
export declare type WithMapOnSuccess<Input, State, OutputState = State> = {
mapOnSuccess: (input: Input) => (state: State) => OutputState;
export declare type WithMapOnSuccess<InputType, StateType, OutputStateType = StateType> = {
mapOnSuccess: (input: InputType) => (state: StateType) => OutputStateType;
};
export declare type WithMapOnFailure<Input, FailureType, Output = FailureType> = {
mapOnFailure: (input: Input) => (oldFailure?: FailureType | undefined) => Output;
export declare type WithMapOnFailure<InputType, FailureType, OutputType = FailureType> = {
mapOnFailure: (input: InputType) => (oldFailure?: FailureType | undefined) => OutputType;
};
export declare type WithOptimisticUpdate<Input, State, OutputState = State> = {
prediction: (input: Input) => (state: State) => OutputState;
export declare type WithOptimisticUpdate<InputType, StateType, OutputStateType = StateType> = {
prediction: (input: InputType) => (state: StateType) => OutputStateType;
};

@@ -44,0 +44,0 @@ export declare type WithEnableLoadingMore = {

import type { AsyncFailureState, AsyncIdleState, AsyncLoadingMoreState, AsyncLoadingState, AsyncSuccessState } from './async.types';
export declare const createIdleState: <IdleType>(payload: IdleType) => AsyncIdleState<IdleType>;
export declare const createLoadingState: <Payload>(payload: Payload) => AsyncLoadingState<Payload>;
export declare const createLoadingMoreState: <Payload>(payload: Payload) => AsyncLoadingMoreState<Payload>;
export declare const createSuccessState: <Payload>(payload: Payload) => AsyncSuccessState<Payload>;
export declare const createFailureState: <Payload, FailureType, EmptyPayload = Payload>(payload: Payload | EmptyPayload, failure: FailureType) => AsyncFailureState<Payload | EmptyPayload, FailureType>;
export declare const createLoadingState: <PayloadType>(payload: PayloadType) => AsyncLoadingState<PayloadType>;
export declare const createLoadingMoreState: <PayloadType>(payload: PayloadType) => AsyncLoadingMoreState<PayloadType>;
export declare const createSuccessState: <PayloadType>(payload: PayloadType) => AsyncSuccessState<PayloadType>;
export declare const createFailureState: <PayloadType, FailureType, EmptyPayloadType = PayloadType>(payload: PayloadType | EmptyPayloadType, failure: FailureType) => AsyncFailureState<PayloadType | EmptyPayloadType, FailureType>;

@@ -1,3 +0,3 @@

interface BaseAsyncState<Status extends string, T> {
status: Status;
interface BaseAsyncState<StatusType extends string, T> {
status: StatusType;
payload: T;

@@ -4,0 +4,0 @@ }

@@ -1,2 +0,2 @@

import type { ActionSpecifier, AnyAction } from '../../../action-bus';
import type { ActionSpecifier } from '../../../action-bus';
import type { Effect } from '../../../store';

@@ -15,2 +15,2 @@ import type { AsyncState } from '../async.types';

*/
export declare const makeAsyncEffect: <AsyncActionKey extends string, Payload, FailPayload, EmptyPayload = Payload>(asyncActionCreators: AsyncActionCreators<AsyncActionKey, Payload, FailPayload, EmptyPayload>) => <DesiredActionSpecifier extends ActionSpecifier<string, string | undefined, Params> | AnyAction<Params>, Params extends unknown[], CallbackResult, FailedCallbackResult>(effectOptions: import("../../../internal/types").OptionalIfExtends<import("../../../internal/types").OptionalIfExtends<import("./async.types").BaseCreateAsyncEffectOptions<DesiredActionSpecifier, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>, FailPayload, FailedCallbackResult, "mapOnFail">, Payload | EmptyPayload, CallbackResult, "mapOnSuccess">) => Effect<AsyncState<Payload, FailPayload, EmptyPayload>>;
export declare const makeAsyncEffect: <AsyncActionKey extends string, Payload, FailPayload, EmptyPayload = Payload>(asyncActionCreators: AsyncActionCreators<AsyncActionKey, Payload, FailPayload, EmptyPayload>) => <DesiredActionType extends ActionSpecifier<string, string | undefined, Params>, Params extends unknown[], CallbackResult, FailedCallbackResult>(effectOptions: import("../../../internal/types").OptionalIfExtends<import("../../../internal/types").OptionalIfExtends<import("./async.types").BaseCreateAsyncEffectOptions<DesiredActionType, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>, FailPayload, FailedCallbackResult, "mapOnFail">, Payload | EmptyPayload, CallbackResult, "mapOnSuccess">) => Effect<AsyncState<Payload, FailPayload, EmptyPayload>>;
import type { ILens } from '@brandingbrand/standard-lens';
import type { ActionSpecifier, AnyAction, AnyActionSpecifier, TypeGuard } from '../../../action-bus';
import type { ActionOf, ActionSpecifier, AnyAction, TypeGuard } from '../../../action-bus';
import type { OptionalIfExtends } from '../../../internal/types';

@@ -21,5 +21,5 @@ import type { AnyActionReducer, Effect, StateReducer } from '../../../store';

}
export interface BaseCreateAsyncEffectOptions<DesiredActionSpecifier extends ActionSpecifier<string, string | undefined, Params> | AnyAction<Params>, Params extends unknown[], CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload = Payload> {
export interface BaseCreateAsyncEffectOptions<DesiredActionType extends ActionSpecifier<string, string | undefined, Params>, Params extends unknown[], CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload = Payload> {
loadingMore?: boolean;
when: TypeGuard<AnyActionSpecifier, DesiredActionSpecifier>;
when: TypeGuard<AnyAction, ActionOf<DesiredActionType>>;
do: (...params: Params) => Promise<CallbackResult>;

@@ -30,3 +30,3 @@ mapOnSuccess: (result: CallbackResult) => (currentPayload: EmptyPayload | Payload) => Payload;

}
export declare type CreateAsyncEffectOptions<DesiredActionSpecifier extends ActionSpecifier<string, string | undefined, Params> | AnyAction<Params>, Params extends unknown[], CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload = Payload> = OptionalIfExtends<OptionalIfExtends<BaseCreateAsyncEffectOptions<DesiredActionSpecifier, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>, FailPayload, FailedCallbackResult, 'mapOnFail'>, EmptyPayload | Payload, CallbackResult, 'mapOnSuccess'>;
export declare type CreateAsyncEffectOptions<DesiredActionType extends ActionSpecifier<string, string | undefined, Params>, Params extends unknown[], CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload = Payload> = OptionalIfExtends<OptionalIfExtends<BaseCreateAsyncEffectOptions<DesiredActionType, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>, FailPayload, FailedCallbackResult, 'mapOnFail'>, EmptyPayload | Payload, CallbackResult, 'mapOnSuccess'>;
export interface AsyncAdaptor<ActionKey extends string, Payload, FailPayload, Structure, EmptyPayload = Payload> {

@@ -41,3 +41,3 @@ createState: (initialPayload: EmptyPayload | Payload) => AsyncState<Payload, FailPayload, EmptyPayload>;

withLens: <OuterStructure>(lens: ILens<OuterStructure, Structure>) => AsyncAdaptor<ActionKey, Payload, FailPayload, OuterStructure, EmptyPayload>;
createEffect: <DesiredActionSpecifier extends ActionSpecifier<string, string | undefined, Params> | AnyAction<Params>, Params extends unknown[], CallbackResult = Payload, FailedCallbackResult = FailPayload>(effectOptions: CreateAsyncEffectOptions<DesiredActionSpecifier, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>) => Effect<Structure>;
createEffect: <DesiredActionSpecifier extends AnyAction<Params>, Params extends unknown[], CallbackResult = Payload, FailedCallbackResult = FailPayload>(effectOptions: CreateAsyncEffectOptions<DesiredActionSpecifier, Params, CallbackResult, Payload, FailedCallbackResult, FailPayload, EmptyPayload>) => Effect<Structure>;
}

@@ -7,7 +7,26 @@ import type { ILens } from '@brandingbrand/standard-lens';

export interface CreateEntityAdaptorOptions<T, Structure> {
/**
* A function that can get an entityId out of the entity
*/
idSelector: IdSelector<T>;
/**
* An optional comparison function that compares two entities for order. If this is not defined
* order is not guaranteed
*/
comparer?: Comparer<T>;
/**
* Optional lens that allows the adaptor to operate on larger data structures.
*/
lens?: ILens<Structure, EntityState<T>>;
}
export declare const createEntityAdaptor: <T, Structure>(options: CreateEntityAdaptorOptions<T, Structure>) => EntityAdaptor<T, Structure>;
/**
* Creates an entity adapter.
*
* @param options Options to create the entity adapter.
* @return
*/
export declare const createEntityAdaptor: <T, StructureType>(options: CreateEntityAdaptorOptions<T, StructureType>) => EntityAdaptor<T, StructureType>;
/**
* A constant that is a good initial state for any entity state.
*/
export declare const EMPTY_ENTITY_STATE: EntityState<never>;
import type { StateReducer } from '../store/store.types';
import type { EntityId, EntityReducers, EntityState } from './entity.types';
import type { EntityAdaptorDeps } from './entity.types.internal';
export declare const sortIfNeeded: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (items: Record<string | number, T>, idList?: EntityId[] | undefined) => EntityId[];
export declare const fromEntityArray: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (items: T[]) => Record<string | number, T>;
export declare const makeCreateState: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (initialEntities: T[]) => EntityState<T>;
export declare const makeSetMany: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (items: T[]) => StateReducer<Structure>;
export declare const makeSetOne: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (item: T) => StateReducer<Structure>;
export declare const makeAddMany: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (items: T[]) => StateReducer<Structure>;
export declare const makeAddOne: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (item: T) => StateReducer<Structure>;
export declare const makeSetAll: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (items: T[]) => StateReducer<Structure>;
export declare const makeRemoveAll: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => () => StateReducer<Structure>;
export declare const makeRemoveMany: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (ids: EntityId[]) => StateReducer<Structure>;
export declare const makeRemoveOne: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => (id: EntityId) => StateReducer<Structure>;
export declare const sortIfNeeded: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (items: Record<string | number, T>, idList?: EntityId[] | undefined) => EntityId[];
export declare const fromEntityArray: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (items: T[]) => Record<string | number, T>;
export declare const makeCreateState: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (initialEntities: T[]) => EntityState<T>;
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* overriding existing ids that collide.
*
* @param deps
* @return
*/
export declare const makeSetMany: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (items: T[]) => StateReducer<StructureType>;
/**
* Takes an item and makes a reducer that adds that item to an existing state, overriding
* the existing id if it exists.
*
* @param deps
* @return
*/
export declare const makeSetOne: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (item: T) => StateReducer<StructureType>;
/**
* Take an array of items and make a reducer that adds those items to an existing state,
* preserving existing ids.
*
* @param deps
* @return
*/
export declare const makeAddMany: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (items: T[]) => StateReducer<StructureType>;
/**
* Takes an item and makes a reducer that adds that item to an existing state, preserving
* the existing id if it exists.
*
* @param deps
* @return
*/
export declare const makeAddOne: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (item: T) => StateReducer<StructureType>;
/**
* Takes an array of items and replaces the existing state with the incoming state.
*
* @param deps
* @return
*/
export declare const makeSetAll: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (items: T[]) => StateReducer<StructureType>;
/**
* Removes all entities and state ids.
*
* @param deps
* @return
*/
export declare const makeRemoveAll: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => () => StateReducer<StructureType>;
/**
* Takes an array of entity ids and returns a reducer that removes those ids if they exist.
*
* @param deps
* @return
*/
export declare const makeRemoveMany: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (ids: EntityId[]) => StateReducer<StructureType>;
/**
* Takes an entity id, returns a reducer that removes it if it exists.
*
* @param deps
* @return
*/
export declare const makeRemoveOne: <T, StructureType = EntityState<T>>(deps: EntityAdaptorDeps<T, StructureType>) => (id: EntityId) => StateReducer<StructureType>;
/**
* Returns a full suite of reducers applying the given dependencies.
*
* @param deps
* @return
*/
export declare const makeReducers: <T, Structure = EntityState<T>>(deps: EntityAdaptorDeps<T, Structure>) => EntityReducers<T, Structure>;
import type { ILens } from '@brandingbrand/standard-lens';
import type { EntityId, EntityState } from './entity.types';
export declare const makeSelectAll: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => (structure: Structure) => T[];
export declare const makeSelectByIds: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => (ids: EntityId[]) => (structure: Structure) => T[];
export declare const makeSelectById: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => (id: EntityId) => (structure: Structure) => T | undefined;
export declare const makeSelectByIndex: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => (index: number) => (structure: Structure) => T | undefined;
export declare const makeSelectByIndices: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => (indices: number[]) => (structure: Structure) => T[];
export declare const getSelectors: <T, Structure>(lens: ILens<Structure, EntityState<T>>) => {
selectAll: (structure: Structure) => T[];
selectByIds: (ids: EntityId[]) => (structure: Structure) => T[];
selectById: (id: EntityId) => (structure: Structure) => T | undefined;
selectByIndex: (index: number) => (structure: Structure) => T | undefined;
selectByIndices: (indices: number[]) => (structure: Structure) => T[];
};
import type { EntityId, EntitySelectors, EntityState } from './entity.types';
/**
* Take all of the entities in an entity state from a given lens and returns
* an array of the entities.
*
* @param lens
* @return
*/
export declare const makeSelectAll: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => (structure: StructureType) => T[];
/**
* Select the given Ids from the entity state from a give lens and returns an array of them.
*
* @param lens
* @return
*/
export declare const makeSelectByIds: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => (ids: EntityId[]) => (structure: StructureType) => T[];
/**
* Select the given Id from the entity state from a give lens and returns either the entity
* or undefined.
*
* @param lens
* @return
*/
export declare const makeSelectById: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => (id: EntityId) => (structure: StructureType) => T | undefined;
/**
* Given an index it will select the Nth value if it exists.
*
* @param lens
* @return
*/
export declare const makeSelectByIndex: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => (index: number) => (structure: StructureType) => T | undefined;
/**
* Given multiple indices it will select the Nth values if they exist.
*
* @param lens
* @return
*/
export declare const makeSelectByIndices: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => (indices: number[]) => (structure: StructureType) => T[];
/**
* Returns the full suite of selectors given the lens.
*
* @param lens
* @return
*/
export declare const getSelectors: <T, StructureType>(lens: ILens<StructureType, EntityState<T>>) => EntitySelectors<T, StructureType>;
import type { EntityId, EntityState } from './entity.types';
/**
* Returns the entity for a given id, if no id is provided it returns the first entity.
*
* @param id Optional entity id.
* @return Entity represented by the id, or the first entity.
*/
export declare const getDefaultedEntity: (id?: EntityId | undefined) => <EntityType>(state: EntityState<EntityType>) => EntityType | undefined;
import type { Effect } from './store.types';
/**
* Combines multiple effects into one, merging all of their observables.
*
* @param effects The effects to combine.
* @return The combined effect.
*/
export declare const combineEffects: <State>(...effects: Effect<State>[]) => Effect<State>;

@@ -5,1 +5,2 @@ export * from './effect';

export * from './store.types';
export * from './update-reducers.action';
import type { ActionOf, ActionSpecifier, AnyAction, AnyActionSpecifier, TypeGuard } from '../action-bus';
import type { NonEmptyArray } from '../internal/util/functional/non-empty-array.types';
import type { ActionReducer, AnyActionReducer, SourcesList, StateReducer } from './store.types';
export declare const combineActionReducers: <State extends {}>(...reducers: AnyActionReducer<State>[]) => AnyActionReducer<State>;
export declare const on: <State, DesiredActionSpecifier extends ActionSpecifier<string, any, unknown>>(filter: TypeGuard<AnyActionSpecifier, DesiredActionSpecifier>, reducer: ActionReducer<State, ActionOf<DesiredActionSpecifier>>) => AnyActionReducer<State>;
export declare const requireSource: (...sources: Array<string | symbol | undefined>) => <ActionType extends ActionSpecifier<string, any, unknown>>(action: ActionType) => action is ActionType;
export declare const optionalSource: (...sources: Array<string | symbol | undefined>) => <ActionType extends ActionSpecifier<string, any, unknown>>(action: ActionType) => action is ActionType;
export declare const isType: <ActionType extends ActionSpecifier<string, any, unknown>>(...actionTypes: NonEmptyArray<ActionType["type"]>) => (action: ActionSpecifier<string, any, unknown>) => action is ActionType;
/**
* Combines action reducers by calling each of them in succession
*
* @param reducers Reducers to combine
* @return Action reducer that combines all effects
*/
export declare const combineActionReducers: <StateType extends {}>(...reducers: AnyActionReducer<StateType>[]) => AnyActionReducer<StateType>;
/**
* Makes it easier to build reducers by filtering actions first, narrowing their type.
* If the type matches it then calls the given reducer
*
* @param filter A function that filters the action down to the desired actions.
* @param reducer A reducer that operates on the desired action.
* @return A reducer that operates on any action.
*/
export declare const on: <StateType, DesiredActionType extends AnyAction<unknown>>(filter: TypeGuard<AnyAction<unknown>, DesiredActionType>, reducer: ActionReducer<StateType, DesiredActionType>) => AnyActionReducer<StateType>;
/**
* Filters actions based on the desired source. Actions that do no have a source will fail
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source: false if otherwise.
* @deprecated
*/
export declare const requireSource: (...sources: Array<string | symbol | undefined>) => <ActionType extends AnyAction<unknown>>(action: ActionType) => action is ActionType;
/**
* Filters actions based on the desired source. Actions that do no have a source will pass
* this filter.
*
* @param sources The list of acceptable sources that you want to filter for.
* @return True if the action has an acceptable source or no source: false if otherwise.
* @deprecated
*/
export declare const optionalSource: (...sources: Array<string | symbol | undefined>) => <ActionType extends AnyAction<unknown>>(action: ActionType) => action is ActionType;
/**
* Filters actions by the desired type
*
* @param actionTypes The desired action types.
* @return True if the type is one of the desired action types: false if otherwise.
*/
export declare const isType: <ActionType extends AnyAction<unknown>>(...actionTypes: NonEmptyArray<ActionType["type"]>) => (action: ActionSpecifier<string, any, unknown>) => action is ActionType;
/**
* Filters actions by the desired subtype
*
* @param actionSubtypes The desired action subtypes.
* @return True if the subtype is one of the desired action types: false if otherwise.
*/
export declare const isSubtype: <ActionType extends AnyAction<unknown>>(...actionSubtypes: NonEmptyArray<ActionType["subtype"]>) => (action: AnyAction) => action is ActionType;
export declare const matches: <DesiredActionSpecifier extends AnyActionSpecifier>(specifier: DesiredActionSpecifier, extraSources?: SourcesList | undefined) => TypeGuard<AnyActionSpecifier, DesiredActionSpecifier>;
export declare const and: <RefinedActionType extends ActionType, ActionType extends OuterActionType, OuterActionType extends AnyActionSpecifier = AnyActionSpecifier>(outerTypeguard: TypeGuard<OuterActionType, ActionType>, innerTypeguard: TypeGuard<ActionType, RefinedActionType>) => TypeGuard<OuterActionType, RefinedActionType>;
export declare const or: <ActionTypeA extends OuterActionType, ActionTypeB extends OuterActionType, OuterActionType extends AnyActionSpecifier = AnyActionSpecifier>(typeguardA: TypeGuard<OuterActionType, ActionTypeA>, typeguardB: TypeGuard<OuterActionType, ActionTypeB>) => TypeGuard<OuterActionType, ActionTypeA | ActionTypeB>;
/**
* Type guard that tells you whether an action matches a given action specifier.
*
* @param specifier Action specifier to match
* @param extraSources Possible extra values of the source field that are allowed. (Deprecated)
* @return True if the action matches the specifier: false if not.
*/
export declare const matches: <DesiredActionSpecifierType extends AnyActionSpecifier>(specifier: DesiredActionSpecifierType, extraSources?: SourcesList | undefined) => TypeGuard<AnyAction<unknown>, ActionOf<DesiredActionSpecifierType>>;
/**
* Combines two type guards such that an action must comply with both.
*
* @param outerTypeguard First type guard to be called.
* @param innerTypeguard Second type guard to be called if the outer returns true.
* @return True if the action matches both specifiers: false if not.
*/
export declare const and: <RefinedActionType extends ActionType, ActionType extends OuterActionType, OuterActionType extends AnyAction<unknown> = AnyAction<unknown>>(outerTypeguard: TypeGuard<OuterActionType, ActionType>, innerTypeguard: TypeGuard<ActionType, RefinedActionType>) => TypeGuard<OuterActionType, RefinedActionType>;
/**
* Combines two type guards such that an action must comply with either.
*
* @param typeguardA First type guard to be called.
* @param typeguardB Second type guard to be called if the first returns false.
* @return True if the action matches either specifiers: false if not.
*/
export declare const or: <ActionTypeA extends OuterActionType, ActionTypeB extends OuterActionType, OuterActionType extends AnyAction<unknown> = AnyAction<unknown>>(typeguardA: TypeGuard<OuterActionType, ActionTypeA>, typeguardB: TypeGuard<OuterActionType, ActionTypeB>) => TypeGuard<OuterActionType, ActionTypeA | ActionTypeB>;
/**
* Combines two state reducers calling the inner and then the outer.
*
* @param outerReducer The state reducer
* @return A function that takes another reducer and returns the combined state reducer.
*/
export declare const composeStateReducers: <T>(outerReducer: StateReducer<T>) => (innerReducer: StateReducer<T>) => StateReducer<T>;
import type { Observable, Subscription } from 'rxjs';
import type { AnyAction } from '../action-bus';
import { ActionBus } from '../action-bus';

@@ -9,11 +10,42 @@ import type { AnyActionReducer, Effect, IStore } from './store.types';

*/
export declare class Store<State> extends ActionBus implements IStore<State> {
constructor(initialState: State);
export declare class Store<StateType> extends ActionBus implements IStore<StateType> {
readonly initialState: StateType;
constructor(initialState: StateType);
/**
* Current state subject at any given time.
*/
private readonly subject$;
private readonly reducer$;
private readonly reducedAction$;
get state(): State;
get state$(): Observable<State>;
registerReducer: (reducer: AnyActionReducer<State>) => void;
registerEffect: (effect: Effect<State>) => Subscription;
/**
* A clone of the action$ that emits only once the state has been updated.
* Used for effects to guarantee the order of operations.
*/
private readonly internalReducedAction$;
private readonly internalReducer$;
/**
* Registers a new reducer to the store.
*
* @param reducer The reducer that gets registered to the store.
*/
registerReducer: (reducer: AnyActionReducer<StateType>) => void;
registerEffect: (effect: Effect<StateType>) => Subscription;
/**
* Synchronous getter for current state. Use `state$` when possible.
*
* @return Current state
*/
get state(): StateType;
/**
* Getter for the state observable
*
* @return The state observable
*/
get state$(): Observable<StateType>;
get reducer$(): Observable<AnyActionReducer<StateType>>;
/**
* Registers a new effect to the store.
*
* @param effect The effect to register.
* @return A subscription. Unsubscribe to the subscription to stop the effect from listening
*/
get reducedAction$(): Observable<AnyAction>;
}

@@ -18,3 +18,3 @@ import type { Observable, Subscription } from 'rxjs';

*/
export declare type AnyActionReducer<State> = (action: AnyAction) => StateReducer<State>;
export declare type AnyActionReducer<State = any> = (action: AnyAction) => StateReducer<State>;
/**

@@ -54,2 +54,3 @@ * An Effect is a function that takes an action observable and state observable, returning an

export interface IStore<State = any> extends ActionBus {
readonly initialState: State;
/**

@@ -73,2 +74,7 @@ * A snapshot of the most recent update to state. This value is not reactive so do not try to key

/**
* An observable of the combined reducer of
* all registered reducers
*/
readonly reducer$: Observable<AnyActionReducer<State>>;
/**
* Dispatch actions in order to trigger effects and/or reducers.

@@ -75,0 +81,0 @@ *

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc