import { S as Subscriber, a as Subscription, O as Observable, r as rxSubscriber, A as AsyncAction, b as AsyncScheduler } from './scheduleArray-b9669898.js';
import { e as empty, N as Notification, o as of, d as delay } from './delay-d08c267f.js';
import { S as SimpleOuterSubscriber, a as SimpleInnerSubscriber, i as innerSubscribe, f as from, m as map, d as distinctUntilChanged, b as filter } from './filter-aeb65cac.js';

const ArgumentOutOfRangeErrorImpl = (() => {
    function ArgumentOutOfRangeErrorImpl() {
        Error.call(this);
        this.message = 'argument out of range';
        this.name = 'ArgumentOutOfRangeError';
        return this;
    }
    ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
    return ArgumentOutOfRangeErrorImpl;
})();
const ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;

function take(count) {
    return (source) => {
        if (count === 0) {
            return empty();
        }
        else {
            return source.lift(new TakeOperator(count));
        }
    };
}
class TakeOperator {
    constructor(total) {
        this.total = total;
        if (this.total < 0) {
            throw new ArgumentOutOfRangeError;
        }
    }
    call(subscriber, source) {
        return source.subscribe(new TakeSubscriber(subscriber, this.total));
    }
}
class TakeSubscriber extends Subscriber {
    constructor(destination, total) {
        super(destination);
        this.total = total;
        this.count = 0;
    }
    _next(value) {
        const total = this.total;
        const count = ++this.count;
        if (count <= total) {
            this.destination.next(value);
            if (count === total) {
                this.destination.complete();
                this.unsubscribe();
            }
        }
    }
}

const ObjectUnsubscribedErrorImpl = (() => {
    function ObjectUnsubscribedErrorImpl() {
        Error.call(this);
        this.message = 'object unsubscribed';
        this.name = 'ObjectUnsubscribedError';
        return this;
    }
    ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
    return ObjectUnsubscribedErrorImpl;
})();
const ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;

class SubjectSubscription extends Subscription {
    constructor(subject, subscriber) {
        super();
        this.subject = subject;
        this.subscriber = subscriber;
        this.closed = false;
    }
    unsubscribe() {
        if (this.closed) {
            return;
        }
        this.closed = true;
        const subject = this.subject;
        const observers = subject.observers;
        this.subject = null;
        if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
            return;
        }
        const subscriberIndex = observers.indexOf(this.subscriber);
        if (subscriberIndex !== -1) {
            observers.splice(subscriberIndex, 1);
        }
    }
}

class SubjectSubscriber extends Subscriber {
    constructor(destination) {
        super(destination);
        this.destination = destination;
    }
}
class Subject extends Observable {
    constructor() {
        super();
        this.observers = [];
        this.closed = false;
        this.isStopped = false;
        this.hasError = false;
        this.thrownError = null;
    }
    [rxSubscriber]() {
        return new SubjectSubscriber(this);
    }
    lift(operator) {
        const subject = new AnonymousSubject(this, this);
        subject.operator = operator;
        return subject;
    }
    next(value) {
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        if (!this.isStopped) {
            const { observers } = this;
            const len = observers.length;
            const copy = observers.slice();
            for (let i = 0; i < len; i++) {
                copy[i].next(value);
            }
        }
    }
    error(err) {
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        this.hasError = true;
        this.thrownError = err;
        this.isStopped = true;
        const { observers } = this;
        const len = observers.length;
        const copy = observers.slice();
        for (let i = 0; i < len; i++) {
            copy[i].error(err);
        }
        this.observers.length = 0;
    }
    complete() {
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        this.isStopped = true;
        const { observers } = this;
        const len = observers.length;
        const copy = observers.slice();
        for (let i = 0; i < len; i++) {
            copy[i].complete();
        }
        this.observers.length = 0;
    }
    unsubscribe() {
        this.isStopped = true;
        this.closed = true;
        this.observers = null;
    }
    _trySubscribe(subscriber) {
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        else {
            return super._trySubscribe(subscriber);
        }
    }
    _subscribe(subscriber) {
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        else if (this.hasError) {
            subscriber.error(this.thrownError);
            return Subscription.EMPTY;
        }
        else if (this.isStopped) {
            subscriber.complete();
            return Subscription.EMPTY;
        }
        else {
            this.observers.push(subscriber);
            return new SubjectSubscription(this, subscriber);
        }
    }
    asObservable() {
        const observable = new Observable();
        observable.source = this;
        return observable;
    }
}
Subject.create = (destination, source) => {
    return new AnonymousSubject(destination, source);
};
class AnonymousSubject extends Subject {
    constructor(destination, source) {
        super();
        this.destination = destination;
        this.source = source;
    }
    next(value) {
        const { destination } = this;
        if (destination && destination.next) {
            destination.next(value);
        }
    }
    error(err) {
        const { destination } = this;
        if (destination && destination.error) {
            this.destination.error(err);
        }
    }
    complete() {
        const { destination } = this;
        if (destination && destination.complete) {
            this.destination.complete();
        }
    }
    _subscribe(subscriber) {
        const { source } = this;
        if (source) {
            return this.source.subscribe(subscriber);
        }
        else {
            return Subscription.EMPTY;
        }
    }
}

class ObserveOnSubscriber extends Subscriber {
    constructor(destination, scheduler, delay = 0) {
        super(destination);
        this.scheduler = scheduler;
        this.delay = delay;
    }
    static dispatch(arg) {
        const { notification, destination } = arg;
        notification.observe(destination);
        this.unsubscribe();
    }
    scheduleMessage(notification) {
        const destination = this.destination;
        destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
    }
    _next(value) {
        this.scheduleMessage(Notification.createNext(value));
    }
    _error(err) {
        this.scheduleMessage(Notification.createError(err));
        this.unsubscribe();
    }
    _complete() {
        this.scheduleMessage(Notification.createComplete());
        this.unsubscribe();
    }
}
class ObserveOnMessage {
    constructor(notification, destination) {
        this.notification = notification;
        this.destination = destination;
    }
}

class BehaviorSubject extends Subject {
    constructor(_value) {
        super();
        this._value = _value;
    }
    get value() {
        return this.getValue();
    }
    _subscribe(subscriber) {
        const subscription = super._subscribe(subscriber);
        if (subscription && !subscription.closed) {
            subscriber.next(this._value);
        }
        return subscription;
    }
    getValue() {
        if (this.hasError) {
            throw this.thrownError;
        }
        else if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        else {
            return this._value;
        }
    }
    next(value) {
        super.next(this._value = value);
    }
}

class QueueAction extends AsyncAction {
    constructor(scheduler, work) {
        super(scheduler, work);
        this.scheduler = scheduler;
        this.work = work;
    }
    schedule(state, delay = 0) {
        if (delay > 0) {
            return super.schedule(state, delay);
        }
        this.delay = delay;
        this.state = state;
        this.scheduler.flush(this);
        return this;
    }
    execute(state, delay) {
        return (delay > 0 || this.closed) ?
            super.execute(state, delay) :
            this._execute(state, delay);
    }
    requestAsyncId(scheduler, id, delay = 0) {
        if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
            return super.requestAsyncId(scheduler, id, delay);
        }
        return scheduler.flush(this);
    }
}

class QueueScheduler extends AsyncScheduler {
}

const queueScheduler = new QueueScheduler(QueueAction);
const queue = queueScheduler;

class ReplaySubject extends Subject {
    constructor(bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, scheduler) {
        super();
        this.scheduler = scheduler;
        this._events = [];
        this._infiniteTimeWindow = false;
        this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
        this._windowTime = windowTime < 1 ? 1 : windowTime;
        if (windowTime === Number.POSITIVE_INFINITY) {
            this._infiniteTimeWindow = true;
            this.next = this.nextInfiniteTimeWindow;
        }
        else {
            this.next = this.nextTimeWindow;
        }
    }
    nextInfiniteTimeWindow(value) {
        if (!this.isStopped) {
            const _events = this._events;
            _events.push(value);
            if (_events.length > this._bufferSize) {
                _events.shift();
            }
        }
        super.next(value);
    }
    nextTimeWindow(value) {
        if (!this.isStopped) {
            this._events.push(new ReplayEvent(this._getNow(), value));
            this._trimBufferThenGetEvents();
        }
        super.next(value);
    }
    _subscribe(subscriber) {
        const _infiniteTimeWindow = this._infiniteTimeWindow;
        const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
        const scheduler = this.scheduler;
        const len = _events.length;
        let subscription;
        if (this.closed) {
            throw new ObjectUnsubscribedError();
        }
        else if (this.isStopped || this.hasError) {
            subscription = Subscription.EMPTY;
        }
        else {
            this.observers.push(subscriber);
            subscription = new SubjectSubscription(this, subscriber);
        }
        if (scheduler) {
            subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
        }
        if (_infiniteTimeWindow) {
            for (let i = 0; i < len && !subscriber.closed; i++) {
                subscriber.next(_events[i]);
            }
        }
        else {
            for (let i = 0; i < len && !subscriber.closed; i++) {
                subscriber.next(_events[i].value);
            }
        }
        if (this.hasError) {
            subscriber.error(this.thrownError);
        }
        else if (this.isStopped) {
            subscriber.complete();
        }
        return subscription;
    }
    _getNow() {
        return (this.scheduler || queue).now();
    }
    _trimBufferThenGetEvents() {
        const now = this._getNow();
        const _bufferSize = this._bufferSize;
        const _windowTime = this._windowTime;
        const _events = this._events;
        const eventsCount = _events.length;
        let spliceCount = 0;
        while (spliceCount < eventsCount) {
            if ((now - _events[spliceCount].time) < _windowTime) {
                break;
            }
            spliceCount++;
        }
        if (eventsCount > _bufferSize) {
            spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
        }
        if (spliceCount > 0) {
            _events.splice(0, spliceCount);
        }
        return _events;
    }
}
class ReplayEvent {
    constructor(time, value) {
        this.time = time;
        this.value = value;
    }
}

function skip(count) {
    return (source) => source.lift(new SkipOperator(count));
}
class SkipOperator {
    constructor(total) {
        this.total = total;
    }
    call(subscriber, source) {
        return source.subscribe(new SkipSubscriber(subscriber, this.total));
    }
}
class SkipSubscriber extends Subscriber {
    constructor(destination, total) {
        super(destination);
        this.total = total;
        this.count = 0;
    }
    _next(x) {
        if (++this.count > this.total) {
            this.destination.next(x);
        }
    }
}

function switchMap(project, resultSelector) {
    if (typeof resultSelector === 'function') {
        return (source) => source.pipe(switchMap((a, i) => from(project(a, i)).pipe(map((b, ii) => resultSelector(a, b, i, ii)))));
    }
    return (source) => source.lift(new SwitchMapOperator(project));
}
class SwitchMapOperator {
    constructor(project) {
        this.project = project;
    }
    call(subscriber, source) {
        return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
    }
}
class SwitchMapSubscriber extends SimpleOuterSubscriber {
    constructor(destination, project) {
        super(destination);
        this.project = project;
        this.index = 0;
    }
    _next(value) {
        let result;
        const index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (error) {
            this.destination.error(error);
            return;
        }
        this._innerSub(result);
    }
    _innerSub(result) {
        const innerSubscription = this.innerSubscription;
        if (innerSubscription) {
            innerSubscription.unsubscribe();
        }
        const innerSubscriber = new SimpleInnerSubscriber(this);
        const destination = this.destination;
        destination.add(innerSubscriber);
        this.innerSubscription = innerSubscribe(result, innerSubscriber);
        if (this.innerSubscription !== innerSubscriber) {
            destination.add(this.innerSubscription);
        }
    }
    _complete() {
        const { innerSubscription } = this;
        if (!innerSubscription || innerSubscription.closed) {
            super._complete();
        }
        this.unsubscribe();
    }
    _unsubscribe() {
        this.innerSubscription = undefined;
    }
    notifyComplete() {
        this.innerSubscription = undefined;
        if (this.isStopped) {
            super._complete();
        }
    }
    notifyNext(innerValue) {
        this.destination.next(innerValue);
    }
}

function isObservable(obj) {
    return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
}

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

const currentAction = {
    type: null,
    entityIds: null,
    skip: false,
    payload: null
};
let customActionActive = false;
function resetCustomAction() {
    customActionActive = false;
}
// public API for custom actions. Custom action always wins
function logAction(type, entityIds, payload) {
    setAction(type, entityIds, payload);
    customActionActive = true;
}
function setAction(type, entityIds, payload) {
    if (customActionActive === false) {
        currentAction.type = type;
        currentAction.entityIds = entityIds;
        currentAction.payload = payload;
    }
}
function action(action, entityIds) {
    return function (target, propertyKey, descriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = function (...args) {
            logAction(action, entityIds);
            return originalMethod.apply(this, args);
        };
        return descriptor;
    };
}

// @internal
function hasEntity(entities, id) {
    return entities.hasOwnProperty(id);
}

// @internal
function isArray(value) {
    return Array.isArray(value);
}

// @internal
function hasActiveState(state) {
    return state.hasOwnProperty('active');
}
// @internal
function isMultiActiveState(active) {
    return isArray(active);
}
// @internal
function resolveActiveEntity({ active, ids, entities }) {
    if (isMultiActiveState(active)) {
        return getExitingActives(active, ids);
    }
    if (hasEntity(entities, active) === false) {
        return null;
    }
    return active;
}
// @internal
function getExitingActives(currentActivesIds, newIds) {
    const filtered = currentActivesIds.filter(id => newIds.indexOf(id) > -1);
    /** Return the same reference if nothing has changed */
    if (filtered.length === currentActivesIds.length) {
        return currentActivesIds;
    }
    return filtered;
}

// @internal
function addEntities({ state, entities, idKey, options = {}, preAddEntity }) {
    let newEntities = {};
    let newIds = [];
    let hasNewEntities = false;
    for (const entity of entities) {
        if (hasEntity(state.entities, entity[idKey]) === false) {
            // evaluate the middleware first to support dynamic ids
            const current = preAddEntity(entity);
            const entityId = current[idKey];
            newEntities[entityId] = current;
            if (options.prepend)
                newIds.unshift(entityId);
            else
                newIds.push(entityId);
            hasNewEntities = true;
        }
    }
    return hasNewEntities
        ? {
            newState: Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, state.entities), newEntities), ids: options.prepend ? [...newIds, ...state.ids] : [...state.ids, ...newIds] }),
            newIds
        }
        : null;
}

// @internal
function isNil(v) {
    return v === null || v === undefined;
}

// @internal
function coerceArray(value) {
    if (isNil(value)) {
        return [];
    }
    return Array.isArray(value) ? value : [value];
}

const DEFAULT_ID_KEY = 'id';

// @internal
function isEmpty(arr) {
    if (isArray(arr)) {
        return arr.length === 0;
    }
    return false;
}

// @internal
function isFunction(value) {
    return typeof value === 'function';
}

// @internal
function isObject(value) {
    const type = typeof value;
    return value != null && (type == 'object' || type == 'function');
}

let CONFIG = {
    resettable: false,
    ttl: null,
    producerFn: undefined
};
// @internal
function getAkitaConfig() {
    return CONFIG;
}
function getGlobalProducerFn() {
    return CONFIG.producerFn;
}

// @internal
function isDefined(val) {
    return isNil(val) === false;
}

// @internal
const $$deleteStore = new Subject();
// @internal
const $$addStore = new ReplaySubject(50, 5000);
// @internal
const $$updateStore = new Subject();
// @internal
function dispatchDeleted(storeName) {
    $$deleteStore.next(storeName);
}
// @internal
function dispatchAdded(storeName) {
    $$addStore.next(storeName);
}
// @internal
function dispatchUpdate(storeName, action) {
    $$updateStore.next({ storeName, action });
}

const isBrowser = typeof window !== 'undefined';
const isNotBrowser = !isBrowser;
// export const isNativeScript = typeof global !== 'undefined' && (<any>global).__runtimeVersion !== 'undefined'; TODO is this used?
const hasLocalStorage = () => {
    try {
        return typeof localStorage !== 'undefined';
    }
    catch (_a) {
        return false;
    }
};
const hasSessionStorage = () => {
    try {
        return typeof sessionStorage !== 'undefined';
    }
    catch (_a) {
        return false;
    }
};

// @internal
const __stores__ = {};
// @internal
const __queries__ = {};
if (isBrowser) {
    window.$$stores = __stores__;
    window.$$queries = __queries__;
}

var Order;
(function (Order) {
    Order["ASC"] = "asc";
    Order["DESC"] = "desc";
})(Order || (Order = {}));

var EntityActions;
(function (EntityActions) {
    EntityActions["Set"] = "Set";
    EntityActions["Add"] = "Add";
    EntityActions["Update"] = "Update";
    EntityActions["Remove"] = "Remove";
})(EntityActions || (EntityActions = {}));

let __DEV__ = true;
function enableAkitaProdMode() {
    __DEV__ = false;
    if (isBrowser) {
        delete window.$$stores;
        delete window.$$queries;
    }
}
// @internal
function isDev() {
    return __DEV__;
}

// @internal
function getActiveEntities(idOrOptions, ids, currentActive) {
    let result;
    if (isArray(idOrOptions)) {
        result = idOrOptions;
    }
    else {
        if (isObject(idOrOptions)) {
            if (isNil(currentActive))
                return;
            idOrOptions = Object.assign({ wrap: true }, idOrOptions);
            const currentIdIndex = ids.indexOf(currentActive);
            if (idOrOptions.prev) {
                const isFirst = currentIdIndex === 0;
                if (isFirst && !idOrOptions.wrap)
                    return;
                result = isFirst ? ids[ids.length - 1] : ids[currentIdIndex - 1];
            }
            else if (idOrOptions.next) {
                const isLast = ids.length === currentIdIndex + 1;
                if (isLast && !idOrOptions.wrap)
                    return;
                result = isLast ? ids[0] : ids[currentIdIndex + 1];
            }
        }
        else {
            if (idOrOptions === currentActive)
                return;
            result = idOrOptions;
        }
    }
    return result;
}

// @internal
const getInitialEntitiesState = () => ({
    entities: {},
    ids: [],
    loading: true,
    error: null
});

// @internal
function isUndefined(value) {
    return value === undefined;
}

// @internal
function removeEntities({ state, ids }) {
    if (isNil(ids))
        return removeAllEntities(state);
    const entities = state.entities;
    let newEntities = {};
    for (const id of state.ids) {
        if (ids.includes(id) === false) {
            newEntities[id] = entities[id];
        }
    }
    const newState = Object.assign(Object.assign({}, state), { entities: newEntities, ids: state.ids.filter(current => ids.includes(current) === false) });
    if (hasActiveState(state)) {
        newState.active = resolveActiveEntity(newState);
    }
    return newState;
}
// @internal
function removeAllEntities(state) {
    return Object.assign(Object.assign({}, state), { entities: {}, ids: [], active: isMultiActiveState(state.active) ? [] : null });
}

// @internal
function toEntitiesObject(entities, idKey, preAddEntity) {
    const acc = {
        entities: {},
        ids: []
    };
    for (const entity of entities) {
        // evaluate the middleware first to support dynamic ids
        const current = preAddEntity(entity);
        acc.entities[current[idKey]] = current;
        acc.ids.push(current[idKey]);
    }
    return acc;
}

// @internal
function isEntityState(state) {
    return state.entities && state.ids;
}
// @internal
function applyMiddleware(entities, preAddEntity) {
    let mapped = {};
    for (const id of Object.keys(entities)) {
        mapped[id] = preAddEntity(entities[id]);
    }
    return mapped;
}
// @internal
function setEntities({ state, entities, idKey, preAddEntity, isNativePreAdd }) {
    let newEntities;
    let newIds;
    if (isArray(entities)) {
        const resolve = toEntitiesObject(entities, idKey, preAddEntity);
        newEntities = resolve.entities;
        newIds = resolve.ids;
    }
    else if (isEntityState(entities)) {
        newEntities = isNativePreAdd ? entities.entities : applyMiddleware(entities.entities, preAddEntity);
        newIds = entities.ids;
    }
    else {
        // it's an object
        newEntities = isNativePreAdd ? entities : applyMiddleware(entities, preAddEntity);
        newIds = Object.keys(newEntities).map(id => (isNaN(id) ? id : Number(id)));
    }
    const newState = Object.assign(Object.assign({}, state), { entities: newEntities, ids: newIds, loading: false });
    if (hasActiveState(state)) {
        newState.active = resolveActiveEntity(newState);
    }
    return newState;
}

// @internal
function deepFreeze(o) {
    Object.freeze(o);
    const oIsFunction = typeof o === 'function';
    const hasOwnProp = Object.prototype.hasOwnProperty;
    Object.getOwnPropertyNames(o).forEach(function (prop) {
        if (hasOwnProp.call(o, prop) &&
            (oIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true) &&
            o[prop] !== null &&
            (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
            !Object.isFrozen(o[prop])) {
            deepFreeze(o[prop]);
        }
    });
    return o;
}
// @internal
function assertStoreHasName(name, className) {
    if (!name) {
        console.error(`@StoreConfig({ name }) is missing in ${className}`);
    }
}

// @internal
function toBoolean(value) {
    return value != null && `${value}` !== 'false';
}

// @internal
function isPlainObject(value) {
    return toBoolean(value) && value.constructor.name === 'Object';
}

const configKey = 'akitaConfig';
function StoreConfig(metadata) {
    return function (constructor) {
        constructor[configKey] = { idKey: 'id' };
        for (let i = 0, keys = Object.keys(metadata); i < keys.length; i++) {
            const key = keys[i];
            /* name is preserved read only key */
            if (key === 'name') {
                constructor[configKey]['storeName'] = metadata[key];
            }
            else {
                constructor[configKey][key] = metadata[key];
            }
        }
    };
}

// @internal
const transactionFinished = new Subject();
// @internal
const transactionInProcess = new BehaviorSubject(false);
// @internal
const transactionManager = {
    activeTransactions: 0,
    batchTransaction: null
};
// @internal
function startBatch() {
    if (!isTransactionInProcess()) {
        transactionManager.batchTransaction = new Subject();
    }
    transactionManager.activeTransactions++;
    transactionInProcess.next(true);
}
// @internal
function endBatch() {
    if (--transactionManager.activeTransactions === 0) {
        transactionManager.batchTransaction.next(true);
        transactionManager.batchTransaction.complete();
        transactionInProcess.next(false);
        transactionFinished.next(true);
    }
}
// @internal
function isTransactionInProcess() {
    return transactionManager.activeTransactions > 0;
}
// @internal
function commit() {
    return transactionManager.batchTransaction ? transactionManager.batchTransaction.asObservable() : of(true);
}
/**
 *  A logical transaction.
 *  Use this transaction to optimize the dispatch of all the stores.
 *  The following code will update the store, BUT  emits only once
 *
 *  @example
 *  applyTransaction(() => {
 *    this.todosStore.add(new Todo(1, title));
 *    this.todosStore.add(new Todo(2, title));
 *  });
 *
 */
function applyTransaction(action, thisArg = undefined) {
    startBatch();
    try {
        return action.apply(thisArg);
    }
    finally {
        logAction('@Transaction');
        endBatch();
    }
}
/**
 *  A logical transaction.
 *  Use this transaction to optimize the dispatch of all the stores.
 *
 *  The following code will update the store, BUT  emits only once.
 *
 *  @example
 *  @transaction
 *  addTodos() {
 *    this.todosStore.add(new Todo(1, title));
 *    this.todosStore.add(new Todo(2, title));
 *  }
 *
 *
 */
function transaction() {
    return function (target, propertyKey, descriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = function (...args) {
            return applyTransaction(() => {
                return originalMethod.apply(this, args);
            }, this);
        };
        return descriptor;
    };
}

/**
 *
 * Store for managing any type of data
 *
 * @example
 *
 * export interface SessionState {
 *   token: string;
 *   userDetails: UserDetails
 * }
 *
 * export function createInitialState(): SessionState {
 *  return {
 *    token: '',
 *    userDetails: null
 *  };
 * }
 *
 * @StoreConfig({ name: 'session' })
 * export class SessionStore extends Store<SessionState> {
 *   constructor() {
 *    super(createInitialState());
 *   }
 * }
 */
class Store {
    constructor(initialState, options = {}) {
        this.options = options;
        this.inTransaction = false;
        this.cache = {
            active: new BehaviorSubject(false),
            ttl: null,
        };
        this.onInit(initialState);
    }
    /**
     *  Set the loading state
     *
     *  @example
     *
     *  store.setLoading(true)
     *
     */
    setLoading(loading = false) {
        if (loading !== this._value().loading) {
            isDev() && setAction('Set Loading');
            this._setState((state) => (Object.assign(Object.assign({}, state), { loading })));
        }
    }
    /**
     *
     * Set whether the data is cached
     *
     * @example
     *
     * store.setHasCache(true)
     * store.setHasCache(false)
     * store.setHasCache(true, { restartTTL: true })
     *
     */
    setHasCache(hasCache, options = { restartTTL: false }) {
        if (hasCache !== this.cache.active.value) {
            this.cache.active.next(hasCache);
        }
        if (options.restartTTL) {
            const ttlConfig = this.getCacheTTL();
            if (ttlConfig) {
                if (this.cache.ttl !== null) {
                    clearTimeout(this.cache.ttl);
                }
                this.cache.ttl = setTimeout(() => this.setHasCache(false), ttlConfig);
            }
        }
    }
    /**
     *
     * Sometimes we need to access the store value from a store
     *
     * @example middleware
     *
     */
    getValue() {
        return this.storeValue;
    }
    /**
     *  Set the error state
     *
     *  @example
     *
     *  store.setError({text: 'unable to load data' })
     *
     */
    setError(error) {
        if (error !== this._value().error) {
            isDev() && setAction('Set Error');
            this._setState((state) => (Object.assign(Object.assign({}, state), { error })));
        }
    }
    // @internal
    _select(project) {
        return this.store.asObservable().pipe(map((snapshot) => project(snapshot.state)), distinctUntilChanged());
    }
    // @internal
    _value() {
        return this.storeValue;
    }
    // @internal
    _cache() {
        return this.cache.active;
    }
    // @internal
    get config() {
        return this.constructor[configKey] || {};
    }
    // @internal
    get storeName() {
        return this.config.storeName || this.options.storeName || this.options.name;
    }
    // @internal
    get deepFreeze() {
        return this.config.deepFreezeFn || this.options.deepFreezeFn || deepFreeze;
    }
    // @internal
    get cacheConfig() {
        return this.config.cache || this.options.cache;
    }
    get _producerFn() {
        return this.config.producerFn || this.options.producerFn || getGlobalProducerFn();
    }
    // @internal
    get resettable() {
        return isDefined(this.config.resettable) ? this.config.resettable : this.options.resettable;
    }
    // @internal
    _setState(newState, _dispatchAction = true) {
        if (isFunction(newState)) {
            const _newState = newState(this._value());
            this.storeValue = __DEV__ ? this.deepFreeze(_newState) : _newState;
        }
        else {
            this.storeValue = newState;
        }
        if (!this.store) {
            this.store = new BehaviorSubject({ state: this.storeValue });
            if (isDev()) {
                this.store.subscribe(({ action }) => {
                    if (action) {
                        dispatchUpdate(this.storeName, action);
                    }
                });
            }
            return;
        }
        if (isTransactionInProcess()) {
            this.handleTransaction();
            return;
        }
        this.dispatch(this.storeValue, _dispatchAction);
    }
    /**
     *
     * Reset the current store back to the initial value
     *
     * @example
     *
     * store.reset()
     *
     */
    reset() {
        if (this.isResettable()) {
            isDev() && setAction('Reset');
            this._setState(() => Object.assign({}, this._initialState));
            this.setHasCache(false);
        }
        else {
            isDev() && console.warn(`You need to enable the reset functionality`);
        }
    }
    update(stateOrCallback) {
        isDev() && setAction('Update');
        let newState;
        const currentState = this._value();
        if (isFunction(stateOrCallback)) {
            newState = isFunction(this._producerFn) ? this._producerFn(currentState, stateOrCallback) : stateOrCallback(currentState);
        }
        else {
            newState = stateOrCallback;
        }
        const withHook = this.akitaPreUpdate(currentState, Object.assign(Object.assign({}, currentState), newState));
        const resolved = isPlainObject(currentState) ? withHook : new currentState.constructor(withHook);
        this._setState(resolved);
    }
    updateStoreConfig(newOptions) {
        this.options = Object.assign(Object.assign({}, this.options), newOptions);
    }
    // @internal
    akitaPreUpdate(_, nextState) {
        return nextState;
    }
    /**
     *
     * @deprecated
     *
     * This method will be removed in v7
     *
     * Akita isn't coupled to Angular and should not use Angular
     * specific code
     *
     */
    ngOnDestroy() {
        this.destroy();
    }
    /**
     *
     * Destroy the store
     *
     * @example
     *
     * store.destroy()
     *
     */
    destroy() {
        const hmrEnabled = isBrowser ? window.hmrEnabled : false;
        if (!hmrEnabled && this === __stores__[this.storeName]) {
            delete __stores__[this.storeName];
            dispatchDeleted(this.storeName);
            this.setHasCache(false);
            this.cache.active.complete();
            this.store.complete();
        }
    }
    onInit(initialState) {
        __stores__[this.storeName] = this;
        this._setState(() => initialState);
        dispatchAdded(this.storeName);
        if (this.isResettable()) {
            this._initialState = initialState;
        }
        isDev() && assertStoreHasName(this.storeName, this.constructor.name);
    }
    dispatch(state, _dispatchAction = true) {
        let action = undefined;
        if (_dispatchAction) {
            action = currentAction;
            resetCustomAction();
        }
        this.store.next({ state, action });
    }
    watchTransaction() {
        commit().subscribe(() => {
            this.inTransaction = false;
            this.dispatch(this._value());
        });
    }
    isResettable() {
        if (this.resettable === false) {
            return false;
        }
        return this.resettable || getAkitaConfig().resettable;
    }
    handleTransaction() {
        if (!this.inTransaction) {
            this.watchTransaction();
            this.inTransaction = true;
        }
    }
    getCacheTTL() {
        return (this.cacheConfig && this.cacheConfig.ttl) || getAkitaConfig().ttl;
    }
}

// @internal
function updateEntities({ state, ids, idKey, newStateOrFn, preUpdateEntity, producerFn, onEntityIdChanges }) {
    const updatedEntities = {};
    let isUpdatingIdKey = false;
    let idToUpdate;
    for (const id of ids) {
        // if the entity doesn't exist don't do anything
        if (hasEntity(state.entities, id) === false) {
            continue;
        }
        const oldEntity = state.entities[id];
        let newState;
        if (isFunction(newStateOrFn)) {
            newState = isFunction(producerFn) ? producerFn(oldEntity, newStateOrFn) : newStateOrFn(oldEntity);
        }
        else {
            newState = newStateOrFn;
        }
        const isIdChanged = newState.hasOwnProperty(idKey) && newState[idKey] !== oldEntity[idKey];
        let newEntity;
        idToUpdate = id;
        if (isIdChanged) {
            isUpdatingIdKey = true;
            idToUpdate = newState[idKey];
        }
        const merged = Object.assign(Object.assign({}, oldEntity), newState);
        if (isPlainObject(oldEntity)) {
            newEntity = merged;
        }
        else {
            /**
             * In case that new state is class of it's own, there's
             * a possibility that it will be different than the old
             * class.
             * For example, Old state is an instance of animal class
             * and new state is instance of person class.
             * To avoid run over new person class with the old animal
             * class we check if the new state is a class of it's own.
             * If so, use it. Otherwise, use the old state class
             */
            if (isPlainObject(newState)) {
                newEntity = new oldEntity.constructor(merged);
            }
            else {
                newEntity = new newState.constructor(merged);
            }
        }
        updatedEntities[idToUpdate] = preUpdateEntity(oldEntity, newEntity);
    }
    let updatedIds = state.ids;
    let stateEntities = state.entities;
    if (isUpdatingIdKey) {
        const [id] = ids;
        const _a = state.entities, _b = id, rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
        stateEntities = rest;
        updatedIds = state.ids.map((current) => (current === id ? idToUpdate : current));
        onEntityIdChanges(id, idToUpdate);
    }
    return Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, stateEntities), updatedEntities), ids: updatedIds });
}

var _b;
/**
 *
 * Store for managing a collection of entities
 *
 * @example
 *
 * export interface WidgetsState extends EntityState<Widget> { }
 *
 * @StoreConfig({ name: 'widgets' })
 *  export class WidgetsStore extends EntityStore<WidgetsState> {
 *   constructor() {
 *     super();
 *   }
 * }
 *
 *
 */
class EntityStore extends Store {
    constructor(initialState = {}, options = {}) {
        super(Object.assign(Object.assign({}, getInitialEntitiesState()), initialState), options);
        this.options = options;
        this.entityActions = new Subject();
        this.entityIdChanges = new Subject();
    }
    // @internal
    get selectEntityAction$() {
        return this.entityActions.asObservable();
    }
    // @internal
    get selectEntityIdChanges$() {
        return this.entityIdChanges.asObservable();
    }
    // @internal
    get idKey() {
        return this.config.idKey || this.options.idKey || DEFAULT_ID_KEY;
    }
    /**
     *
     * Replace current collection with provided collection
     *
     * @example
     *
     * this.store.set([Entity, Entity])
     * this.store.set({ids: [], entities: {}})
     * this.store.set({ 1: {}, 2: {}})
     *
     */
    set(entities, options = {}) {
        if (isNil(entities))
            return;
        isDev() && setAction('Set Entity');
        const isNativePreAdd = this.akitaPreAddEntity === EntityStore.prototype.akitaPreAddEntity;
        this.setHasCache(true, { restartTTL: true });
        this._setState((state) => {
            const newState = setEntities({
                state,
                entities,
                idKey: this.idKey,
                preAddEntity: this.akitaPreAddEntity,
                isNativePreAdd,
            });
            if (isUndefined(options.activeId) === false) {
                newState.active = options.activeId;
            }
            return newState;
        });
        if (this.hasInitialUIState()) {
            this.handleUICreation();
        }
        this.entityActions.next({ type: EntityActions.Set, ids: this.ids });
    }
    /**
     * Add entities
     *
     * @example
     *
     * this.store.add([Entity, Entity])
     * this.store.add(Entity)
     * this.store.add(Entity, { prepend: true })
     *
     * this.store.add(Entity, { loading: false })
     */
    add(entities, options = { loading: false }) {
        const collection = coerceArray(entities);
        if (isEmpty(collection))
            return;
        const data = addEntities({
            state: this._value(),
            preAddEntity: this.akitaPreAddEntity,
            entities: collection,
            idKey: this.idKey,
            options,
        });
        if (data) {
            isDev() && setAction('Add Entity');
            data.newState.loading = options.loading;
            this._setState(() => data.newState);
            if (this.hasInitialUIState()) {
                this.handleUICreation(true);
            }
            this.entityActions.next({ type: EntityActions.Add, ids: data.newIds });
        }
    }
    update(idsOrFnOrState, newStateOrFn) {
        if (isUndefined(newStateOrFn)) {
            super.update(idsOrFnOrState);
            return;
        }
        let ids = [];
        if (isFunction(idsOrFnOrState)) {
            // We need to filter according the predicate function
            ids = this.ids.filter((id) => idsOrFnOrState(this.entities[id]));
        }
        else {
            // If it's nil we want all of them
            ids = isNil(idsOrFnOrState) ? this.ids : coerceArray(idsOrFnOrState);
        }
        if (isEmpty(ids))
            return;
        isDev() && setAction('Update Entity', ids);
        let entityIdChanged;
        this._setState((state) => updateEntities({
            idKey: this.idKey,
            ids,
            preUpdateEntity: this.akitaPreUpdateEntity,
            state,
            newStateOrFn,
            producerFn: this._producerFn,
            onEntityIdChanges: (oldId, newId) => {
                entityIdChanged = { oldId, newId };
                this.entityIdChanges.next(Object.assign(Object.assign({}, entityIdChanged), { pending: true }));
            },
        }));
        if (entityIdChanged) {
            this.entityIdChanges.next(Object.assign(Object.assign({}, entityIdChanged), { pending: false }));
        }
        this.entityActions.next({ type: EntityActions.Update, ids });
    }
    upsert(ids, newState, onCreate, options = {}) {
        const toArray = coerceArray(ids);
        const predicate = (isUpdate) => (id) => hasEntity(this.entities, id) === isUpdate;
        const baseClass = isFunction(onCreate) ? options.baseClass : onCreate ? onCreate.baseClass : undefined;
        const isClassBased = isFunction(baseClass);
        const updateIds = toArray.filter(predicate(true));
        const newEntities = toArray.filter(predicate(false)).map((id) => {
            const newStateObj = typeof newState === 'function' ? newState({}) : newState;
            const entity = isFunction(onCreate) ? onCreate(id, newStateObj) : newStateObj;
            const withId = Object.assign(Object.assign({}, entity), { [this.idKey]: id });
            if (isClassBased) {
                return new baseClass(withId);
            }
            return withId;
        });
        // it can be any of the three types
        this.update(updateIds, newState);
        this.add(newEntities);
        isDev() && logAction('Upsert Entity');
    }
    /**
     *
     * Upsert entity collection (idKey must be present)
     *
     * @example
     *
     * store.upsertMany([ { id: 1 }, { id: 2 }]);
     *
     * store.upsertMany([ { id: 1 }, { id: 2 }], { loading: true  });
     * store.upsertMany([ { id: 1 }, { id: 2 }], { baseClass: Todo  });
     *
     */
    upsertMany(entities, options = {}) {
        const addedIds = [];
        const updatedIds = [];
        const updatedEntities = {};
        // Update the state directly to optimize performance
        for (const entity of entities) {
            const withPreCheckHook = this.akitaPreCheckEntity(entity);
            const id = withPreCheckHook[this.idKey];
            if (hasEntity(this.entities, id)) {
                const prev = this._value().entities[id];
                const merged = Object.assign(Object.assign({}, this._value().entities[id]), withPreCheckHook);
                const next = options.baseClass ? new options.baseClass(merged) : merged;
                const withHook = this.akitaPreUpdateEntity(prev, next);
                const nextId = withHook[this.idKey];
                updatedEntities[nextId] = withHook;
                updatedIds.push(nextId);
            }
            else {
                const newEntity = options.baseClass ? new options.baseClass(withPreCheckHook) : withPreCheckHook;
                const withHook = this.akitaPreAddEntity(newEntity);
                const nextId = withHook[this.idKey];
                addedIds.push(nextId);
                updatedEntities[nextId] = withHook;
            }
        }
        isDev() && logAction('Upsert Many');
        this._setState((state) => (Object.assign(Object.assign({}, state), { ids: addedIds.length ? [...state.ids, ...addedIds] : state.ids, entities: Object.assign(Object.assign({}, state.entities), updatedEntities), loading: !!options.loading })));
        updatedIds.length && this.entityActions.next({ type: EntityActions.Update, ids: updatedIds });
        addedIds.length && this.entityActions.next({ type: EntityActions.Add, ids: addedIds });
        if (addedIds.length && this.hasUIStore()) {
            this.handleUICreation(true);
        }
    }
    /**
     *
     * Replace one or more entities (except the id property)
     *
     *
     * @example
     *
     * this.store.replace(5, newEntity)
     * this.store.replace([1,2,3], newEntity)
     */
    replace(ids, newState) {
        const toArray = coerceArray(ids);
        if (isEmpty(toArray))
            return;
        const replaced = {};
        for (const id of toArray) {
            replaced[id] = Object.assign(Object.assign({}, newState), { [this.idKey]: id });
        }
        isDev() && setAction('Replace Entity', ids);
        this._setState((state) => (Object.assign(Object.assign({}, state), { entities: Object.assign(Object.assign({}, state.entities), replaced) })));
    }
    /**
     *
     * Move entity inside the collection
     *
     *
     * @example
     *
     * this.store.move(fromIndex, toIndex)
     */
    move(from, to) {
        const ids = this.ids.slice();
        ids.splice(to < 0 ? ids.length + to : to, 0, ids.splice(from, 1)[0]);
        isDev() && setAction('Move Entity');
        this._setState((state) => (Object.assign(Object.assign({}, state), { 
            // Change the entities reference so that selectAll emit
            entities: Object.assign({}, state.entities), ids })));
    }
    remove(idsOrFn) {
        if (isEmpty(this.ids))
            return;
        const idPassed = isDefined(idsOrFn);
        // null means remove all
        let ids = [];
        if (isFunction(idsOrFn)) {
            ids = this.ids.filter((entityId) => idsOrFn(this.entities[entityId]));
        }
        else {
            ids = idPassed ? coerceArray(idsOrFn) : this.ids;
        }
        if (isEmpty(ids))
            return;
        isDev() && setAction('Remove Entity', ids);
        this._setState((state) => removeEntities({ state, ids }));
        if (!idPassed) {
            this.setHasCache(false);
        }
        this.handleUIRemove(ids);
        this.entityActions.next({ type: EntityActions.Remove, ids });
    }
    /**
     *
     * Update the active entity
     *
     * @example
     *
     * this.store.updateActive({ completed: true })
     * this.store.updateActive(active => {
     *   return {
     *     config: {
     *      ..active.config,
     *      date
     *     }
     *   }
     * })
     */
    updateActive(newStateOrCallback) {
        const ids = coerceArray(this.active);
        isDev() && setAction('Update Active', ids);
        this.update(ids, newStateOrCallback);
    }
    setActive(idOrOptions) {
        const active = getActiveEntities(idOrOptions, this.ids, this.active);
        if (active === undefined) {
            return;
        }
        isDev() && setAction('Set Active', active);
        this._setActive(active);
    }
    /**
     * Add active entities
     *
     * @example
     *
     * store.addActive(2);
     * store.addActive([3, 4, 5]);
     */
    addActive(ids) {
        const toArray = coerceArray(ids);
        if (isEmpty(toArray))
            return;
        const everyExist = toArray.every((id) => this.active.indexOf(id) > -1);
        if (everyExist)
            return;
        isDev() && setAction('Add Active', ids);
        this._setState((state) => {
            /** Protect against case that one of the items in the array exist */
            const uniques = Array.from(new Set([...state.active, ...toArray]));
            return Object.assign(Object.assign({}, state), { active: uniques });
        });
    }
    /**
     * Remove active entities
     *
     * @example
     *
     * store.removeActive(2)
     * store.removeActive([3, 4, 5])
     */
    removeActive(ids) {
        const toArray = coerceArray(ids);
        if (isEmpty(toArray))
            return;
        const someExist = toArray.some((id) => this.active.indexOf(id) > -1);
        if (!someExist)
            return;
        isDev() && setAction('Remove Active', ids);
        this._setState((state) => {
            return Object.assign(Object.assign({}, state), { active: Array.isArray(state.active) ? state.active.filter((currentId) => toArray.indexOf(currentId) === -1) : null });
        });
    }
    /**
     * Toggle active entities
     *
     * @example
     *
     * store.toggle(2)
     * store.toggle([3, 4, 5])
     */
    toggleActive(ids) {
        const toArray = coerceArray(ids);
        const filterExists = (remove) => (id) => this.active.includes(id) === remove;
        const remove = toArray.filter(filterExists(true));
        const add = toArray.filter(filterExists(false));
        this.removeActive(remove);
        this.addActive(add);
        isDev() && logAction('Toggle Active');
    }
    /**
     *
     * Create sub UI store for managing Entity's UI state
     *
     * @example
     *
     * export type ProductUI = {
     *   isLoading: boolean;
     *   isOpen: boolean
     * }
     *
     * interface ProductsUIState extends EntityState<ProductUI> {}
     *
     * export class ProductsStore EntityStore<ProductsState, Product> {
     *   ui: EntityUIStore<ProductsUIState, ProductUI>;
     *
     *   constructor() {
     *     super();
     *     this.createUIStore();
     *   }
     *
     * }
     */
    createUIStore(initialState = {}, storeConfig = {}) {
        const defaults = { name: `UI/${this.storeName}`, idKey: this.idKey };
        this.ui = new EntityUIStore(initialState, Object.assign(Object.assign({}, defaults), storeConfig));
        return this.ui;
    }
    // @internal
    destroy() {
        super.destroy();
        if (this.ui instanceof EntityStore) {
            this.ui.destroy();
        }
        this.entityActions.complete();
    }
    // @internal
    akitaPreUpdateEntity(_, nextEntity) {
        return nextEntity;
    }
    // @internal
    akitaPreAddEntity(newEntity) {
        return newEntity;
    }
    // @internal
    akitaPreCheckEntity(newEntity) {
        return newEntity;
    }
    get ids() {
        return this._value().ids;
    }
    get entities() {
        return this._value().entities;
    }
    get active() {
        return this._value().active;
    }
    _setActive(ids) {
        this._setState((state) => {
            return Object.assign(Object.assign({}, state), { active: ids });
        });
    }
    handleUICreation(add = false) {
        const ids = this.ids;
        const isFunc = isFunction(this.ui._akitaCreateEntityFn);
        let uiEntities;
        const createFn = (id) => {
            const current = this.entities[id];
            const ui = isFunc ? this.ui._akitaCreateEntityFn(current) : this.ui._akitaCreateEntityFn;
            return Object.assign({ [this.idKey]: current[this.idKey] }, ui);
        };
        if (add) {
            uiEntities = this.ids.filter((id) => isUndefined(this.ui.entities[id])).map(createFn);
        }
        else {
            uiEntities = ids.map(createFn);
        }
        add ? this.ui.add(uiEntities) : this.ui.set(uiEntities);
    }
    hasInitialUIState() {
        return this.hasUIStore() && isUndefined(this.ui._akitaCreateEntityFn) === false;
    }
    handleUIRemove(ids) {
        if (this.hasUIStore()) {
            this.ui.remove(ids);
        }
    }
    hasUIStore() {
        return this.ui instanceof EntityUIStore;
    }
}
__decorate([
    transaction(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object, Object]),
    __metadata("design:returntype", void 0)
], EntityStore.prototype, "upsert", null);
__decorate([
    transaction(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [typeof (_b = typeof T !== "undefined" && T) === "function" ? _b : Object]),
    __metadata("design:returntype", void 0)
], EntityStore.prototype, "toggleActive", null);
// @internal
class EntityUIStore extends EntityStore {
    constructor(initialState = {}, storeConfig = {}) {
        super(initialState, storeConfig);
    }
    /**
     *
     * Set the initial UI entity state. This function will determine the entity's
     * initial state when we call `set()` or `add()`.
     *
     * @example
     *
     * constructor() {
     *   super();
     *   this.createUIStore().setInitialEntityState(entity => ({ isLoading: false, isOpen: true }));
     *   this.createUIStore().setInitialEntityState({ isLoading: false, isOpen: true });
     * }
     *
     */
    setInitialEntityState(createFn) {
        this._akitaCreateEntityFn = createFn;
    }
}
/**
 * @example
 *
 * query.selectEntity(2).pipe(filterNilValue())
 */
function filterNilValue() {
    return filter((value) => value !== null && value !== undefined);
}

const queryConfigKey = 'akitaQueryConfig';

// @internal
function isString(value) {
    return typeof value === 'string';
}

function compareKeys(keysOrFuncs) {
    return function (prevState, currState) {
        const isFns = isFunction(keysOrFuncs[0]);
        // Return when they are NOT changed
        return keysOrFuncs.some(keyOrFunc => {
            if (isFns) {
                return keyOrFunc(prevState) !== keyOrFunc(currState);
            }
            return prevState[keyOrFunc] !== currState[keyOrFunc];
        }) === false;
    };
}

class Query {
    constructor(store) {
        this.store = store;
        this.__store__ = store;
        if (isDev()) {
            // @internal
            __queries__[store.storeName] = this;
        }
    }
    select(project) {
        let mapFn;
        if (isFunction(project)) {
            mapFn = project;
        }
        else if (isString(project)) {
            mapFn = state => state[project];
        }
        else if (Array.isArray(project)) {
            return this.store
                ._select(state => state)
                .pipe(distinctUntilChanged(compareKeys(project)), map(state => {
                if (isFunction(project[0])) {
                    return project.map(func => func(state));
                }
                return project.reduce((acc, k) => {
                    acc[k] = state[k];
                    return acc;
                }, {});
            }));
        }
        else {
            mapFn = state => state;
        }
        return this.store._select(mapFn);
    }
    /**
     * Select the loading state
     *
     * @example
     *
     * this.query.selectLoading().subscribe(isLoading => {})
     */
    selectLoading() {
        return this.select(state => state.loading);
    }
    /**
     * Select the error state
     *
     * @example
     *
     * this.query.selectError().subscribe(error => {})
     */
    selectError() {
        return this.select(state => state.error);
    }
    /**
     * Get the store's value
     *
     * @example
     *
     * this.query.getValue()
     *
     */
    getValue() {
        return this.store._value();
    }
    /**
     * Select the cache state
     *
     * @example
     *
     * this.query.selectHasCache().pipe(
     *   switchMap(hasCache => {
     *     return hasCache ? of() : http().pipe(res => store.set(res))
     *   })
     * )
     */
    selectHasCache() {
        return this.store._cache().asObservable();
    }
    /**
     * Whether we've cached data
     *
     * @example
     *
     * this.query.getHasCache()
     *
     */
    getHasCache() {
        return this.store._cache().value;
    }
    // @internal
    get config() {
        return this.constructor[queryConfigKey];
    }
}

/**
 * @internal
 *
 * @example
 *
 * getValue(state, 'todos.ui')
 *
 */
function getValue(obj, prop) {
    /** return the whole state  */
    if (prop.split('.').length === 1) {
        return obj;
    }
    const removeStoreName = prop
        .split('.')
        .slice(1)
        .join('.');
    return removeStoreName.split('.').reduce((acc, part) => acc && acc[part], obj);
}

/**
 * @internal
 *
 * @example
 * setValue(state, 'todos.ui', { filter: {} })
 */
function setValue(obj, prop, val, replace = false) {
    const split = prop.split('.');
    if (split.length === 1) {
        return Object.assign(Object.assign({}, obj), val);
    }
    obj = Object.assign({}, obj);
    const lastIndex = split.length - 2;
    const removeStoreName = prop.split('.').slice(1);
    removeStoreName.reduce((acc, part, index) => {
        if (index !== lastIndex) {
            acc[part] = Object.assign({}, acc[part]);
            return acc && acc[part];
        }
        acc[part] = replace || Array.isArray(acc[part]) || !isObject(acc[part]) ? val : Object.assign(Object.assign({}, acc[part]), val);
        return acc && acc[part];
    }, obj);
    return obj;
}

let skipStorageUpdate = false;
const _persistStateInit = new ReplaySubject(1);
function getSkipStorageUpdate() {
    return skipStorageUpdate;
}
function isPromise(v) {
    return v && isFunction(v.then);
}
function observify(asyncOrValue) {
    if (isPromise(asyncOrValue) || isObservable(asyncOrValue)) {
        return from(asyncOrValue);
    }
    return of(asyncOrValue);
}
function persistState(params) {
    const defaults = {
        key: 'AkitaStores',
        enableInNonBrowser: false,
        storage: !hasLocalStorage() ? params.storage : localStorage,
        deserialize: JSON.parse,
        serialize: JSON.stringify,
        include: [],
        select: [],
        persistOnDestroy: false,
        preStorageUpdate: function (storeName, state) {
            return state;
        },
        preStoreUpdate: function (storeName, state) {
            return state;
        },
        skipStorageUpdate: getSkipStorageUpdate,
        preStorageUpdateOperator: () => (source) => source,
    };
    const { storage, enableInNonBrowser, deserialize, serialize, include, select, key, preStorageUpdate, persistOnDestroy, preStorageUpdateOperator, preStoreUpdate, skipStorageUpdate } = Object.assign({}, defaults, params);
    if ((isNotBrowser && !enableInNonBrowser) || !storage)
        return;
    const hasInclude = include.length > 0;
    const hasSelect = select.length > 0;
    let includeStores;
    let selectStores;
    if (hasInclude) {
        includeStores = include.reduce((acc, path) => {
            if (isFunction(path)) {
                acc.fns.push(path);
            }
            else {
                const storeName = path.split('.')[0];
                acc[storeName] = path;
            }
            return acc;
        }, { fns: [] });
    }
    if (hasSelect) {
        selectStores = select.reduce((acc, selectFn) => {
            acc[selectFn.storeName] = selectFn;
            return acc;
        }, {});
    }
    let stores = {};
    let acc = {};
    let subscriptions = [];
    const buffer = [];
    function _save(v) {
        observify(v).subscribe(() => {
            const next = buffer.shift();
            next && _save(next);
        });
    }
    // when we use the local/session storage we perform the serialize, otherwise we let the passed storage implementation to do it
    const isLocalStorage = (hasLocalStorage() && storage === localStorage) || (hasSessionStorage() && storage === sessionStorage);
    observify(storage.getItem(key)).subscribe((value) => {
        let storageState = isObject(value) ? value : deserialize(value || '{}');
        function save(storeCache) {
            storageState['$cache'] = Object.assign(Object.assign({}, (storageState['$cache'] || {})), storeCache);
            storageState = Object.assign({}, storageState, acc);
            buffer.push(storage.setItem(key, isLocalStorage ? serialize(storageState) : storageState));
            _save(buffer.shift());
        }
        function subscribe(storeName, path) {
            stores[storeName] = __stores__[storeName]
                ._select((state) => getValue(state, path))
                .pipe(skip(1), map((store) => {
                if (hasSelect && selectStores[storeName]) {
                    return selectStores[storeName](store);
                }
                return store;
            }), filter(() => skipStorageUpdate() === false), preStorageUpdateOperator())
                .subscribe((data) => {
                acc[storeName] = preStorageUpdate(storeName, data);
                Promise.resolve().then(() => save({ [storeName]: __stores__[storeName]._cache().getValue() }));
            });
        }
        function setInitial(storeName, store, path) {
            if (storeName in storageState) {
                setAction('@PersistState');
                store._setState((state) => {
                    return setValue(state, path, preStoreUpdate(storeName, storageState[storeName], state));
                });
                const hasCache = storageState['$cache'] ? storageState['$cache'][storeName] : false;
                __stores__[storeName].setHasCache(hasCache, { restartTTL: true });
            }
        }
        subscriptions.push($$deleteStore.subscribe((storeName) => {
            if (stores[storeName]) {
                if (persistOnDestroy === false) {
                    save({ [storeName]: false });
                }
                stores[storeName].unsubscribe();
                delete stores[storeName];
            }
        }));
        subscriptions.push($$addStore.subscribe((storeName) => {
            if (storeName === 'router') {
                return;
            }
            const store = __stores__[storeName];
            if (hasInclude) {
                let path = includeStores[storeName];
                if (!path) {
                    const passPredicate = includeStores.fns.some((fn) => fn(storeName));
                    if (passPredicate) {
                        path = storeName;
                    }
                    else {
                        return;
                    }
                }
                setInitial(storeName, store, path);
                subscribe(storeName, path);
            }
            else {
                setInitial(storeName, store, storeName);
                subscribe(storeName, storeName);
            }
        }));
        _persistStateInit.next();
    });
    return {
        destroy() {
            subscriptions.forEach((s) => s.unsubscribe());
            for (let i = 0, keys = Object.keys(stores); i < keys.length; i++) {
                const storeName = keys[i];
                stores[storeName].unsubscribe();
            }
            stores = {};
        },
        clear() {
            storage.clear();
        },
        clearStore(storeName) {
            if (isNil(storeName)) {
                const value = observify(storage.setItem(key, '{}'));
                value.subscribe();
                return;
            }
            const value = storage.getItem(key);
            observify(value).subscribe((v) => {
                const storageState = deserialize(v || '{}');
                if (storageState[storeName]) {
                    delete storageState[storeName];
                    const value = observify(storage.setItem(key, serialize(storageState)));
                    value.subscribe();
                }
            });
        },
    };
}

class AkitaPlugin {
    constructor(query, config) {
        this.query = query;
        if (config && config.resetFn) {
            if (getAkitaConfig().resettable) {
                this.onReset(config.resetFn);
            }
        }
    }
    /** This method is responsible for getting access to the query. */
    getQuery() {
        return this.query;
    }
    /** This method is responsible for getting access to the store. */
    getStore() {
        return this.getQuery().__store__;
    }
    /** This method is responsible tells whether the plugin is entityBased or not.  */
    isEntityBased(entityId) {
        return toBoolean(entityId);
    }
    /** This method is responsible for selecting the source; it can be the whole store or one entity. */
    selectSource(entityId, property) {
        if (this.isEntityBased(entityId)) {
            return this.getQuery().selectEntity(entityId).pipe(filterNilValue());
        }
        if (property) {
            return this.getQuery().select((state) => getValue(state, this.withStoreName(property)));
        }
        return this.getQuery().select();
    }
    getSource(entityId, property) {
        if (this.isEntityBased(entityId)) {
            return this.getQuery().getEntity(entityId);
        }
        const state = this.getQuery().getValue();
        if (property) {
            return getValue(state, this.withStoreName(property));
        }
        return state;
    }
    withStoreName(prop) {
        return `${this.storeName}.${prop}`;
    }
    get storeName() {
        return this.getStore().storeName;
    }
    /** This method is responsible for updating the store or one entity; it can be the whole store or one entity. */
    updateStore(newState, entityId, property, replace = false) {
        if (this.isEntityBased(entityId)) {
            const store = this.getStore();
            replace ? store.replace(entityId, newState) : store.update(entityId, newState);
        }
        else {
            if (property) {
                this.getStore()._setState((state) => {
                    return setValue(state, this.withStoreName(property), newState, true);
                });
                return;
            }
            const nextState = replace ? newState : (state) => (Object.assign(Object.assign({}, state), newState));
            this.getStore()._setState(nextState);
        }
    }
    /**
     * Function to invoke upon reset
     */
    onReset(fn) {
        const original = this.getStore().reset;
        this.getStore().reset = (...params) => {
            /** It should run after the plugin destroy method */
            setTimeout(() => {
                original.apply(this.getStore(), params);
                fn();
            });
        };
    }
}

const paginatorDefaults = {
    pagesControls: false,
    range: false,
    startWith: 1,
    cacheTimeout: undefined,
    clearStoreWithCache: true,
};
class PaginatorPlugin extends AkitaPlugin {
    constructor(query, config = {}) {
        super(query, {
            resetFn: () => {
                this.initial = false;
                this.destroy({ clearCache: true, currentPage: 1 });
            },
        });
        this.query = query;
        this.config = config;
        /** Save current filters, sorting, etc. in cache */
        this.metadata = new Map();
        this.pages = new Map();
        this.pagination = {
            currentPage: 1,
            perPage: 0,
            total: 0,
            lastPage: 0,
            data: [],
        };
        /**
         * When the user navigates to a different page and return
         * we don't want to call `clearCache` on first time.
         */
        this.initial = true;
        /**
         * Proxy to the query loading
         */
        this.isLoading$ = this.query.selectLoading().pipe(delay(0));
        this.config = Object.assign(Object.assign({}, paginatorDefaults), config);
        const { startWith, cacheTimeout } = this.config;
        this.page = new BehaviorSubject(startWith);
        if (isObservable(cacheTimeout)) {
            this.clearCacheSubscription = cacheTimeout.subscribe(() => this.clearCache());
        }
    }
    /**
     * Listen to page changes
     */
    get pageChanges() {
        return this.page.asObservable();
    }
    /**
     * Get the current page number
     */
    get currentPage() {
        return this.pagination.currentPage;
    }
    /**
     * Check if current page is the first one
     */
    get isFirst() {
        return this.currentPage === 1;
    }
    /**
     * Check if current page is the last one
     */
    get isLast() {
        return this.currentPage === this.pagination.lastPage;
    }
    /**
     * Whether to generate an array of pages for *ngFor
     * [1, 2, 3, 4]
     */
    withControls() {
        this.config.pagesControls = true;
        return this;
    }
    /**
     * Whether to generate the `from` and `to` keys
     * [1, 2, 3, 4]
     */
    withRange() {
        this.config.range = true;
        return this;
    }
    /**
     * Set the loading state
     */
    setLoading(value = true) {
        this.getStore().setLoading(value);
    }
    /**
     * Update the pagination object and add the page
     */
    update(response) {
        this.pagination = response;
        this.addPage(response.data);
    }
    /**
     *
     * Set the ids and add the page to store
     */
    addPage(data) {
        this.pages.set(this.currentPage, { ids: data.map((entity) => entity[this.getStore().idKey]) });
        this.getStore().upsertMany(data);
    }
    /**
     * Clear the cache.
     */
    clearCache(options = {}) {
        if (!this.initial) {
            logAction('@Pagination - Clear Cache');
            if (options.clearStore !== false && (this.config.clearStoreWithCache || options.clearStore)) {
                this.getStore().remove();
            }
            this.pages = new Map();
            this.metadata = new Map();
        }
        this.initial = false;
    }
    clearPage(page) {
        this.pages.delete(page);
    }
    /**
     * Clear the cache timeout and optionally the pages
     */
    destroy({ clearCache, currentPage } = {}) {
        if (this.clearCacheSubscription) {
            this.clearCacheSubscription.unsubscribe();
        }
        if (clearCache) {
            this.clearCache();
        }
        if (!isUndefined(currentPage)) {
            this.setPage(currentPage);
        }
        this.initial = true;
    }
    /**
     * Whether the provided page is active
     */
    isPageActive(page) {
        return this.currentPage === page;
    }
    /**
     * Set the current page
     */
    setPage(page) {
        if (page !== this.currentPage || !this.hasPage(page)) {
            this.page.next((this.pagination.currentPage = page));
        }
    }
    /**
     * Increment current page
     */
    nextPage() {
        if (this.currentPage !== this.pagination.lastPage) {
            this.setPage(this.pagination.currentPage + 1);
        }
    }
    /**
     * Decrement current page
     */
    prevPage() {
        if (this.pagination.currentPage > 1) {
            this.setPage(this.pagination.currentPage - 1);
        }
    }
    /**
     * Set current page to last
     */
    setLastPage() {
        this.setPage(this.pagination.lastPage);
    }
    /**
     * Set current page to first
     */
    setFirstPage() {
        this.setPage(1);
    }
    /**
     * Check if page exists in cache
     */
    hasPage(page) {
        return this.pages.has(page);
    }
    /**
     * Get the current page if it's in cache, otherwise invoke the request
     */
    getPage(req) {
        let page = this.pagination.currentPage;
        if (this.hasPage(page)) {
            return this.selectPage(page);
        }
        else {
            this.setLoading(true);
            return from(req()).pipe(switchMap((config) => {
                page = config.currentPage;
                applyTransaction(() => {
                    this.setLoading(false);
                    this.update(config);
                });
                return this.selectPage(page);
            }));
        }
    }
    getQuery() {
        return this.query;
    }
    refreshCurrentPage() {
        if (isNil(this.currentPage) === false) {
            this.clearPage(this.currentPage);
            this.setPage(this.currentPage);
        }
    }
    getFrom() {
        if (this.isFirst) {
            return 1;
        }
        return (this.currentPage - 1) * this.pagination.perPage + 1;
    }
    getTo() {
        if (this.isLast) {
            return this.pagination.total;
        }
        return this.currentPage * this.pagination.perPage;
    }
    /**
     * Select the page
     */
    selectPage(page) {
        return this.query.selectAll({ asObject: true }).pipe(take(1), map((entities) => {
            const response = Object.assign(Object.assign({}, this.pagination), { data: this.pages.get(page).ids.map((id) => entities[id]) });
            const { range, pagesControls } = this.config;
            /** If no total - calc it */
            if (isNaN(this.pagination.total)) {
                if (response.lastPage === 1) {
                    response.total = response.data ? response.data.length : 0;
                }
                else {
                    response.total = response.perPage * response.lastPage;
                }
                this.pagination.total = response.total;
            }
            if (range) {
                response.from = this.getFrom();
                response.to = this.getTo();
            }
            if (pagesControls) {
                response.pageControls = generatePages(this.pagination.total, this.pagination.perPage);
            }
            return response;
        }));
    }
}
__decorate([
    action('@Pagination - New Page'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], PaginatorPlugin.prototype, "update", null);
/**
 * Generate an array so we can ngFor them to navigate between pages
 */
function generatePages(total, perPage) {
    const len = Math.ceil(total / perPage);
    const arr = [];
    for (let i = 0; i < len; i++) {
        arr.push(i + 1);
    }
    return arr;
}

var StoreAction;
(function (StoreAction) {
    StoreAction["Update"] = "UPDATE";
})(StoreAction || (StoreAction = {}));
var EntityStoreAction;
(function (EntityStoreAction) {
    EntityStoreAction["Update"] = "UPDATE";
    EntityStoreAction["AddEntities"] = "ADD_ENTITIES";
    EntityStoreAction["SetEntities"] = "SET_ENTITIES";
    EntityStoreAction["UpdateEntities"] = "UPDATE_ENTITIES";
    EntityStoreAction["RemoveEntities"] = "REMOVE_ENTITIES";
    EntityStoreAction["UpsertEntities"] = "UPSERT_ENTITIES";
    EntityStoreAction["UpsertManyEntities"] = "UPSERT_MANY_ENTITIES";
})(EntityStoreAction || (EntityStoreAction = {}));

export { Query as Q, StoreConfig as S, Store as a, enableAkitaProdMode as e, persistState as p };
