"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

/**
 * @param {{
 *   recentActionsToTrack?: number
 *   maxByteSize?: number
 * }} [options]
 * @returns
 */
const getRecentActionsBundle = ({
  recentActionsToTrack = 20,
  maxByteSize = 10000
} = {}) => ({
  name: 'recentActions',
  init: store => {
    store.getRecentActions = () => {
      try {
        const getLen = items => JSON.stringify(items).length;

        const isTooBig = items => getLen(items) > maxByteSize;

        const copy = [...store.meta.recentActions];
        const allowedPerEntry = Math.round((maxByteSize - 5) / copy.length);

        if (isTooBig(copy)) {
          // this is important so we can trim down really large action payloads
          for (let i = 0, len = copy.length; i < len; i++) {
            const entry = copy[i];

            if (getLen(entry) > allowedPerEntry) {
              copy[i] = {
                type: entry.type,
                payload: '_LONG_'
              };
            }
          }
        } // trim until we fit (this shouldn't be necessary)


        while (isTooBig(copy)) {
          copy.shift();
        }

        return copy;
      } catch (e) {
        return 'error serializing recent actions';
      }
    };
  },
  getMiddleware: () => store => next => action => {
    // only log non-idle actions
    if (action.type !== 'APP_IDLE') {
      const recentActions = store.meta.recentActions || (store.meta.recentActions = []);
      recentActions.push(action);

      if (recentActions.length > recentActionsToTrack) {
        recentActions.shift();
      }
    }

    return next(action);
  }
});

var _default = getRecentActionsBundle;
exports.default = _default;