import { c as createCommonjsModule, u as unwrapExports, a as commonjsGlobal } from './_commonjsHelpers-0c4b6f40.js';
import './_to-object-ded78eb9.js';
import './es6.string.iterator-9b2af4a5.js';
import './_library-528f1934.js';
import './_iter-detect-59409a32.js';
import './core.get-iterator-method-54d2e411.js';
import './web.dom.iterable-8956f9a5.js';
import { a as _asyncToGenerator, r as regenerator } from './asyncToGenerator-7c654f36.js';
import './_set-species-cede29f8.js';
import { c as cookie } from './index-db3bb315.js';
import getQuery from './getQuery.js';

var defaultParseOptions = {
  decodeValues: true,
  map: false,
  silent: false,
};

function isNonEmptyString(str) {
  return typeof str === "string" && !!str.trim();
}

function parseString(setCookieValue, options) {
  var parts = setCookieValue.split(";").filter(isNonEmptyString);
  var nameValue = parts.shift().split("=");
  var name = nameValue.shift();
  var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part

  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  var cookie = {
    name: name, // grab everything before the first =
    value: options.decodeValues ? decodeURIComponent(value) : value, // decode cookie value
  };

  parts.forEach(function (part) {
    var sides = part.split("=");
    var key = sides.shift().trimLeft().toLowerCase();
    var value = sides.join("=");
    if (key === "expires") {
      cookie.expires = new Date(value);
    } else if (key === "max-age") {
      cookie.maxAge = parseInt(value, 10);
    } else if (key === "secure") {
      cookie.secure = true;
    } else if (key === "httponly") {
      cookie.httpOnly = true;
    } else if (key === "samesite") {
      cookie.sameSite = value;
    } else {
      cookie[key] = value;
    }
  });

  return cookie;
}

function parse(input, options) {
  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  if (!input) {
    if (!options.map) {
      return [];
    } else {
      return {};
    }
  }

  if (input.headers && input.headers["set-cookie"]) {
    // fast-path for node.js (which automatically normalizes header names to lower-case
    input = input.headers["set-cookie"];
  } else if (input.headers) {
    // slow-path for other environments - see #25
    var sch =
      input.headers[
        Object.keys(input.headers).find(function (key) {
          return key.toLowerCase() === "set-cookie";
        })
      ];
    // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
    if (!sch && input.headers.cookie && !options.silent) {
      console.warn(
        "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
      );
    }
    input = sch;
  }
  if (!Array.isArray(input)) {
    input = [input];
  }

  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  if (!options.map) {
    return input.filter(isNonEmptyString).map(function (str) {
      return parseString(str, options);
    });
  } else {
    var cookies = {};
    return input.filter(isNonEmptyString).reduce(function (cookies, str) {
      var cookie = parseString(str, options);
      cookies[cookie.name] = cookie;
      return cookies;
    }, cookies);
  }
}

/*
  Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
  that are within a single set-cookie field-value, such as in the Expires portion.

  This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
  Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
  React Native's fetch does this for *every* header, including set-cookie.

  Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
  Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/
function splitCookiesString(cookiesString) {
  if (Array.isArray(cookiesString)) {
    return cookiesString;
  }
  if (typeof cookiesString !== "string") {
    return [];
  }

  var cookiesStrings = [];
  var pos = 0;
  var start;
  var ch;
  var lastComma;
  var nextStart;
  var cookiesSeparatorFound;

  function skipWhitespace() {
    while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
      pos += 1;
    }
    return pos < cookiesString.length;
  }

  function notSpecialChar() {
    ch = cookiesString.charAt(pos);

    return ch !== "=" && ch !== ";" && ch !== ",";
  }

  while (pos < cookiesString.length) {
    start = pos;
    cookiesSeparatorFound = false;

    while (skipWhitespace()) {
      ch = cookiesString.charAt(pos);
      if (ch === ",") {
        // ',' is a cookie separator if we have later first '=', not ';' or ','
        lastComma = pos;
        pos += 1;

        skipWhitespace();
        nextStart = pos;

        while (pos < cookiesString.length && notSpecialChar()) {
          pos += 1;
        }

        // currently special character
        if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
          // we found cookies separator
          cookiesSeparatorFound = true;
          // pos is inside the next cookie, so back up and return it.
          pos = nextStart;
          cookiesStrings.push(cookiesString.substring(start, lastComma));
          start = pos;
        } else {
          // in param ',' or param separator ';',
          // we continue from that comma
          pos = lastComma + 1;
        }
      } else {
        pos += 1;
      }
    }

    if (!cookiesSeparatorFound || pos >= cookiesString.length) {
      cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
    }
  }

  return cookiesStrings;
}

var setCookie = parse;
var parse_1 = parse;
var parseString_1 = parseString;
var splitCookiesString_1 = splitCookiesString;
setCookie.parse = parse_1;
setCookie.parseString = parseString_1;
setCookie.splitCookiesString = splitCookiesString_1;

var dist = createCommonjsModule(function (module, exports) {
var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.destroyCookie = exports.setCookie = exports.parseCookies = void 0;


var isBrowser = function () { return typeof window !== 'undefined'; };
function hasSameProperties(a, b) {
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    if (aProps.length !== bProps.length) {
        return false;
    }
    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];
        if (a[propName] !== b[propName]) {
            return false;
        }
    }
    return true;
}
/**
 * Compare the cookie and return true if the cookies has equivalent
 * options and the cookies would be overwritten in the browser storage.
 *
 * @param a first Cookie for comparison
 * @param b second Cookie for comparison
 */
function areCookiesEqual(a, b) {
    var sameSiteSame = a.sameSite === b.sameSite;
    if (typeof a.sameSite === 'string' && typeof b.sameSite === 'string') {
        sameSiteSame = a.sameSite.toLowerCase() === b.sameSite.toLowerCase();
    }
    return (hasSameProperties(__assign(__assign({}, a), { sameSite: undefined }), __assign(__assign({}, b), { sameSite: undefined })) && sameSiteSame);
}
/**
 * Create an instance of the Cookie interface
 *
 * @param name name of the Cookie
 * @param value value of the Cookie
 * @param options Cookie options
 */
function createCookie(name, value, options) {
    var sameSite = options.sameSite;
    if (sameSite === true) {
        sameSite = 'strict';
    }
    if (sameSite === undefined || sameSite === false) {
        sameSite = 'lax';
    }
    var cookieToSet = __assign(__assign({}, options), { sameSite: sameSite });
    delete cookieToSet.encode;
    return __assign({ name: name, value: value }, cookieToSet);
}
/**
 *
 * Parses cookies.
 *
 * @param ctx
 * @param options
 */
function parseCookies(ctx, options) {
    if (ctx && ctx.req && ctx.req.headers && ctx.req.headers.cookie) {
        return cookie.parse(ctx.req.headers.cookie, options);
    }
    if (isBrowser()) {
        return cookie.parse(document.cookie, options);
    }
    return {};
}
exports.parseCookies = parseCookies;
/**
 *
 * Sets a cookie.
 *
 * @param ctx
 * @param name
 * @param value
 * @param options
 */
function setCookie$1(ctx, name, value, options) {
    if (ctx && ctx.res && ctx.res.getHeader && ctx.res.setHeader) {
        var cookies = ctx.res.getHeader('Set-Cookie') || [];
        if (typeof cookies === 'string')
            cookies = [cookies];
        if (typeof cookies === 'number')
            cookies = [];
        var parsedCookies = setCookie.parse(cookies);
        var cookiesToSet_1 = [];
        parsedCookies.forEach(function (parsedCookie) {
            if (!areCookiesEqual(parsedCookie, createCookie(name, value, options))) {
                cookiesToSet_1.push(cookie.serialize(parsedCookie.name, parsedCookie.value, __assign({}, parsedCookie)));
            }
        });
        cookiesToSet_1.push(cookie.serialize(name, value, options));
        if (!ctx.res.finished) {
            ctx.res.setHeader('Set-Cookie', cookiesToSet_1);
        }
    }
    if (isBrowser()) {
        if (options && options.httpOnly) {
            throw new Error('Can not set a httpOnly cookie in the browser.');
        }
        document.cookie = cookie.serialize(name, value, options);
    }
    return {};
}
exports.setCookie = setCookie$1;
/**
 *
 * Destroys a cookie with a particular name.
 *
 * @param ctx
 * @param name
 * @param options
 */
function destroyCookie(ctx, name, options) {
    var opts = __assign(__assign({}, (options || {})), { maxAge: -1 });
    if (ctx && ctx.res && ctx.res.setHeader && ctx.res.getHeader) {
        var cookies = ctx.res.getHeader('Set-Cookie') || [];
        if (typeof cookies === 'string')
            cookies = [cookies];
        if (typeof cookies === 'number')
            cookies = [];
        cookies.push(cookie.serialize(name, '', opts));
        ctx.res.setHeader('Set-Cookie', cookies);
    }
    if (isBrowser()) {
        document.cookie = cookie.serialize(name, '', opts);
    }
    return {};
}
exports.destroyCookie = destroyCookie;
exports.default = {
    set: setCookie$1,
    get: parseCookies,
    destroy: destroyCookie,
};

});

unwrapExports(dist);
var dist_1 = dist.destroyCookie;
var dist_2 = dist.setCookie;
var dist_3 = dist.parseCookies;

var _this = undefined;

var getRelatedArticle = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
    var ctx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    var client = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var article = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var prevUrl = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '/';
    var articleCount = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;

    var _article$url, url, documentGroupMapping, issueGroup, content_placement, references, params, articles, filters, cookies, prevSlugs, referenceFilter, query;

    return regenerator.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _article$url = article.url;
            _article$url = _article$url === undefined ? {
              current: null
            } : _article$url;
            url = _article$url.current, documentGroupMapping = article.documentGroupMapping, issueGroup = article.issueGroup;
            content_placement = article.content_placement;
            references = [];


            content_placement = content_placement && content_placement.length > 0 && content_placement.filter(function (_ref2) {
              var identifier = _ref2.identifier;
              return identifier !== 'news';
            });
            if (content_placement && content_placement.length > 0) {
              content_placement.forEach(function (_ref3) {
                var path = _ref3.path,
                    _id = _ref3._id;

                if (!_id || typeof _id == 'undefined') {
                  return null;
                }
                var prev_url_to_check = prevUrl;
                if (prev_url_to_check.includes('?')) {
                  prev_url_to_check = prev_url_to_check.split('?')[0];
                }
                if (prev_url_to_check.endsWith(path) && _id) references.push(_id);
              });
              if (references.length === 0) {
                content_placement.forEach(function (_ref4) {
                  var _id = _ref4._id;

                  if (_id) references.push(_id);
                });
              }
            }

            if (documentGroupMapping && documentGroupMapping.length > 0) {
              documentGroupMapping.forEach(function (_ref5) {
                var _id = _ref5._id;

                if (_id) references.push(_id);
              });
            }

            if (issueGroup && issueGroup._ref) {
              references.push(issueGroup._ref);
            }

            params = { url: url, index: articleCount };
            articles = null;

            if (!(references && references.length > 0)) {
              _context.next = 26;
              break;
            }

            filters = '';

            if (ctx && url) {
              cookies = dist_3(ctx);
              prevSlugs = cookies['prevSlugs'];

              if (!!prevSlugs) {
                dist_2(ctx, 'prevSlugs', prevSlugs + ',"' + url + '"', {});
                filters = '&& !(url.current in [' + prevSlugs + '])';
              } else dist_2(ctx, 'prevSlugs', '"' + url + '"', {});
            }

            referenceFilter = references.reduce(function (acc, item, index, array) {
              if (array.length === 1) {
                acc = acc + ' references("' + item + '") ';
              } else if (index === 0) {
                acc = acc + ' (references("' + item + '") ||';
              } else if (index + 1 === array.length) {
                acc = acc + ' references("' + item + '")) ';
              } else {
                acc = acc + ' references("' + item + '") ||';
              }
              return acc;
            }, '&&');


            filters = filters + referenceFilter;
            query = getQuery('related', filters, '', articleCount).replace('&& taxonomyMapping[]._ref in $taxonomy', '');
            _context.prev = 17;
            _context.next = 20;
            return client.fetch(query, params);

          case 20:
            articles = _context.sent;
            _context.next = 26;
            break;

          case 23:
            _context.prev = 23;
            _context.t0 = _context['catch'](17);

            console.error(_context.t0);

          case 26:
            return _context.abrupt('return', articles);

          case 27:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, _this, [[17, 23]]);
  }));

  return function getRelatedArticle() {
    return _ref.apply(this, arguments);
  };
}();

export default getRelatedArticle;
