<%
  // There's an issue here with trailing commas.
  // A better solution would probably be to pull the data in I need, build an object, and then dump it via JSON.stringify()
  // reference: https://jsonfeed.org/version/1.1

  const

    prependSlash = (pagePath) => `${pagePath.indexOf('/') === 0 ? '' : '/'}${pagePath}`,

    { author, copyright, language, tags } = site,

    feedData = {
      version: 'https://jsonfeed.org/version/1.1',
      title: site.title,
      home_page_url: `${site.uri}`,
      feed_url: `${site.uri}/feed.json`,
      authors: [],
      items: [],
    };
  
  if (author) {

    const { name, email, photo, site: aSite } = author || {};
    const newAuthor = {};

    if (email) newAuthor.email = email;
    if (name) newAuthor.name = name;
    if (photo) newAuthor.photo = `${site.uri}${photo}`;
    if (aSite) newAuthor.site = aSite;

    feedData.authors.push(newAuthor);

  }

  if (Array.isArray(site?.pages)) {

    feedData.items.push(...site.pages
        .sort((p1, p2) => {

          const p1Date = new Date(p1.date_upd || p1.date_pub);
          const p2Date = new Date(p2.date_upd || p2.date_pub);

          return p2Date - p1Date;

        })
        .map((page) => {

          const { body, content, date_pub, date_upd, description, path, tags } = page || {};
          const p = {
            id: `${site.uri}${prependSlash(path)}`,
            url: `${site.uri}${prependSlash(path)}`,
          };

          if (body) p.content_text = body;
          if (content) p.content_html = content;
          if (date_pub) p.date_published = date_pub;
          if (date_upd) p.date_modified = date_upd;
          if (description) p.summary = description;
          if (Array.isArray(tags)) p.tags = tags;

          return { ...p };

        })
    );

  }
-%>
<%- JSON.stringify(feedData, null, 2) -%>