<commit_before>// minify HTML: https://www.willpeavy.com/minifier/
// minify JS: https://dotmaui.com/jsminify/

if (location.hostname == "localhost" || location.hostname == "127.0.0.1")
    URL = 'http://localhost:8000/api/v3/'
else
    URL = 'http://time.astrotech.io/api/v3/'

var Trial = {
    device: "lcd",
    location: "internet",
    regularity: 5,
    timeout: 3.0,
    colors: shuffle(["red", "blue", "white"]),
    clicks: [],
    start_datetime: new Date().toJSON()
};

function hide(id) {
    var element = document.getElementById(id);
    element.style.display = 'none';
}

function show(id) {
    if (id == 'test' && localStorage.getItem('.remember')) {
        hide('test');
        show('color0');
        return;
    }

    var element = document.getElementById(id);
    element.style.display = 'block';
}

function saveSurvey() {
    Trial.email = document.querySelector('input[name="email"]').value;
    Trial.survey_age = document.querySelector('input[name="age"]').value;
    Trial.survey_gender = document.querySelector('input[name="gender"]:checked').value;
    Trial.survey_condition = document.querySelector('input[name="condition"]:checked').value;
    Trial.survey_heart_rate = document.querySelector('input[name="heart_rate"]').value;
    Trial.survey_bp_systolic = document.querySelector('input[name="bp_systolic"]').value;
    Trial.survey_bp_diastolic = document.querySelector('input[name="bp_diastolic"]').value;
    Trial.survey_sleep = document.querySelector('input[name="sleep"]').value;
    Trial.survey_temperature = document.querySelector('input[name="temperature"]').value;
    Trial.survey_time = document.querySelector('input[name="time"]').value;
}

function fullscreen() {
    let bg = document.getElementById("background");

    if (bg.webkitRequestFullScreen)
        bg.webkitRequestFullScreen();
    else if (bg.mozRequestFullScreen)
        bg.mozRequestFullScreen();
    else if (bg.msRequestFullscreen)
        bg.msRequestFullscreen();
    else
        bg.requestFullscreen();
}

function shuffle(array) {
    // Knuth Random Shuffle Algorithm
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
}

function sleep(seconds) {
    let milliseconds = seconds * 1000;
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

function testAndProceed(next) {
    let color = 'gray';
    let timeout = Trial.timeout / 2;
    let background = document.getElementById('background');
    let oldBackground = background.style.background;
    let content = document.getElementById('test');
    let oldContent = content.innerHTML;

    content.innerHTML = '
Click now!
';
    background.style.background = color;

    sleep(timeout).then(() => {
        background.style.background = oldBackground;
        content.innerHTML = oldContent;
        hide('test');
        show(next);
    });
}

function runAndProceed(number, next) {
    let color = Trial.colors[number];
    let timeout = Trial.timeout;
    let id = 'color' + number;
    let oldBackground = background.style.background;
    let content = document.getElementById(id);
    let oldContent = content.innerHTML;

    content.innerHTML = '';
    background.style.background = color;
    background.addEventListener('click', click);

    sleep(timeout).then(() => {
        background.removeEventListener('click', click);
        background.style.background = oldBackground;
        content.innerHTML = oldContent;
        hide(id);
        show(next);

        if (next == 'results')
            finish();
    });
}

function click() {
    var background = document.getElementById('background');

    Trial.clicks.push({
        datetime: new Date().toJSON(),
        color: background.style.backgroundColor
    });
}

function finish() {
    let blue = Trial.clicks.filter(click => click.color=='blue').length
    let red = Trial.clicks.filter(click => click.color=='red').length
    let white = Trial.clicks.filter(click => click.color=='white').length

    if (Trial.location == "internet")
        localStorage.setItem('.remember', JSON.stringify(Trial));

    if ([blue, red, white].every(count => count > 5)) {
        Trial.end_datetime = new Date().toJSON();
        localStorage.setItem(Trial.end_datetime, JSON.stringify(Trial));
        trySyncDB();
        window.location.reload(true);
    } else {
       alert('Not enough clicks, for the experiment to be valid! Please re-run the experiment.');
       hide('results');
       show('survey');
    }
}

function request(arg) {
    var server = new XMLHttpRequest();
    server.onreadystatechange = function() {
        if (this.readyState == XMLHttpRequest.DONE)
            switch(this.status) {
                case 200: arg.onSuccess(this.status); break;
                case 201: arg.onSuccess(this.status); break;
                default: arg.onError(this.status); break;
            }
    };
    server.open(arg.method, arg.url, true);
    server.setRequestHeader("Content-type", "application/json");
    server.send(arg.data);
}

function trySyncDB() {
    if (! navigator.onLine) {
        console.log('Browser is not online.');
        return;
    }

    request({
        method: "OPTIONS",
        url: URL,
        onSuccess: function(status) {
            uploadResults();
        },
        onError: function() {
            console.log('Server cannot be contacted');
        }
    });
}

function uploadResults() {
    for (let key of Object.keys(localStorage)) {

        if (key == ".remember")
            continue;

        request({
            method: "POST",
            url: URL,
            data: localStorage.getItem(key),
            onSuccess: function(status) {
                console.log('Result uploaded');
                localStorage.removeItem(key);
            },
            onError: function(status) {
                console.log('There is a problem with uploading data. We will try later. Received status:', status);
            }
        });
    }
}

if (location.hostname !== "localhost" && location.hostname !== "127.0.0.1") {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-92351316-5', 'auto');
  ga('send', 'pageview');
}

window.addEventListener('online', trySyncDB);

<commit_msg>Timeout for debug version #time 1m<commit_after>// minify HTML: https://www.willpeavy.com/minifier/
// minify JS: https://dotmaui.com/jsminify/

if (location.hostname == "localhost" || location.hostname == "127.0.0.1")
    URL = 'http://localhost:8000/api/v3/'
else
    URL = 'http://time.astrotech.io/api/v3/'

var Trial = {
    device: "lcd",
    location: "internet",
    regularity: 5,
    timeout: 60.0,
    colors: shuffle(["red", "blue", "white"]),
    clicks: [],
    start_datetime: new Date().toJSON()
};

function hide(id) {
    var element = document.getElementById(id);
    element.style.display = 'none';
}

function show(id) {
    if (id == 'test' && localStorage.getItem('.remember')) {
        hide('test');
        show('color0');
        return;
    }

    var element = document.getElementById(id);
    element.style.display = 'block';
}

function saveSurvey() {
    Trial.email = document.querySelector('input[name="email"]').value;
    Trial.survey_age = document.querySelector('input[name="age"]').value;
    Trial.survey_gender = document.querySelector('input[name="gender"]:checked').value;
    Trial.survey_condition = document.querySelector('input[name="condition"]:checked').value;
    Trial.survey_heart_rate = document.querySelector('input[name="heart_rate"]').value;
    Trial.survey_bp_systolic = document.querySelector('input[name="bp_systolic"]').value;
    Trial.survey_bp_diastolic = document.querySelector('input[name="bp_diastolic"]').value;
    Trial.survey_sleep = document.querySelector('input[name="sleep"]').value;
    Trial.survey_temperature = document.querySelector('input[name="temperature"]').value;
    Trial.survey_time = document.querySelector('input[name="time"]').value;
}

function fullscreen() {
    let bg = document.getElementById("background");

    if (bg.webkitRequestFullScreen)
        bg.webkitRequestFullScreen();
    else if (bg.mozRequestFullScreen)
        bg.mozRequestFullScreen();
    else if (bg.msRequestFullscreen)
        bg.msRequestFullscreen();
    else
        bg.requestFullscreen();
}

function shuffle(array) {
    // Knuth Random Shuffle Algorithm
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
}

function sleep(seconds) {
    let milliseconds = seconds * 1000;
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

function testAndProceed(next) {
    let color = 'gray';
    let timeout = Trial.timeout / 2;
    let background = document.getElementById('background');
    let oldBackground = background.style.background;
    let content = document.getElementById('test');
    let oldContent = content.innerHTML;

    content.innerHTML = '
Click now!
';
    background.style.background = color;

    sleep(timeout).then(() => {
        background.style.background = oldBackground;
        content.innerHTML = oldContent;
        hide('test');
        show(next);
    });
}

function runAndProceed(number, next) {
    let color = Trial.colors[number];
    let timeout = Trial.timeout;
    let id = 'color' + number;
    let oldBackground = background.style.background;
    let content = document.getElementById(id);
    let oldContent = content.innerHTML;

    content.innerHTML = '';
    background.style.background = color;
    background.addEventListener('click', click);

    sleep(timeout).then(() => {
        background.removeEventListener('click', click);
        background.style.background = oldBackground;
        content.innerHTML = oldContent;
        hide(id);
        show(next);

        if (next == 'results')
            finish();
    });
}

function click() {
    var background = document.getElementById('background');

    Trial.clicks.push({
        datetime: new Date().toJSON(),
        color: background.style.backgroundColor
    });
}

function finish() {
    let blue = Trial.clicks.filter(click => click.color=='blue').length
    let red = Trial.clicks.filter(click => click.color=='red').length
    let white = Trial.clicks.filter(click => click.color=='white').length

    if (Trial.location == "internet")
        localStorage.setItem('.remember', JSON.stringify(Trial));

    if ([blue, red, white].every(count => count > 5)) {
        Trial.end_datetime = new Date().toJSON();
        localStorage.setItem(Trial.end_datetime, JSON.stringify(Trial));
        trySyncDB();
        window.location.reload(true);
    } else {
       alert('Not enough clicks, for the experiment to be valid! Please re-run the experiment.');
       hide('results');
       show('survey');
    }
}

function request(arg) {
    var server = new XMLHttpRequest();
    server.onreadystatechange = function() {
        if (this.readyState == XMLHttpRequest.DONE)
            switch(this.status) {
                case 200: arg.onSuccess(this.status); break;
                case 201: arg.onSuccess(this.status); break;
                default: arg.onError(this.status); break;
            }
    };
    server.open(arg.method, arg.url, true);
    server.setRequestHeader("Content-type", "application/json");
    server.send(arg.data);
}

function trySyncDB() {
    if (! navigator.onLine) {
        console.log('Browser is not online.');
        return;
    }

    request({
        method: "OPTIONS",
        url: URL,
        onSuccess: function(status) {
            uploadResults();
        },
        onError: function() {
            console.log('Server cannot be contacted');
        }
    });
}

function uploadResults() {
    for (let key of Object.keys(localStorage)) {

        if (key == ".remember")
            continue;

        request({
            method: "POST",
            url: URL,
            data: localStorage.getItem(key),
            onSuccess: function(status) {
                console.log('Result uploaded');
                localStorage.removeItem(key);
            },
            onError: function(status) {
                console.log('There is a problem with uploading data. We will try later. Received status:', status);
            }
        });
    }
}

if (location.hostname !== "localhost" && location.hostname !== "127.0.0.1") {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-92351316-5', 'auto');
  ga('send', 'pageview');
}

window.addEventListener('online', trySyncDB);

<|endoftext|>


<commit_before>/* eslint-disable @typescript-eslint/no-var-requires */

const path = require("path");
const {
  createFilePath,
  createRemoteFileNode,
} = require("gatsby-source-filesystem");

require("dotenv").config({
  path: `.env`,
});

exports.onCreateNode = ({ node, actions, getNode, getNodes }) => {
  const { createNodeField } = actions;

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode });
    createNodeField({
      name: `slug`,
      node,
      value,
    });
  }
};

exports.createResolvers = ({
  actions,
  cache,
  createNodeId,
  createResolvers,
  store,
  reporter,
}) => {
  const imageFileResolver = (source, args, context, info) => {
    if (!source.image) {
      return null;
    }

    return createRemoteFileNode({
      url: source.image,
      store,
      cache,
      createNode,
      createNodeId,
      reporter,
    });
  };

  const { createNode } = actions;

  const typesWithImages = [
    "BACKEND_Post",
    "BACKEND_Page",
    "BACKEND_Sponsor",
    "BACKEND_Event",
    "BACKEND_ScheduleItem",
  ];

  const resolvers = {};

  typesWithImages.forEach(type => {
    resolvers[type] = {
      imageFile: {
        type: `File`,
        resolve: imageFileResolver,
      },
    };
  });

  createResolvers(resolvers);
};

const createPageWithSocialCards = (
  createPage,
  socialCardComponent,
  args,
  createOnlySocialCard = false,
  cardTypes = ["social", "social-square", "social-twitter"],
) => {
  cardTypes.forEach(type => {
    createPage({
      ...args,
      path: `${args.path}/${type}`,
      component: socialCardComponent,
      context: {
        ...args.context,
        cardType: type,
      },
    });
  });

  if (!createOnlySocialCard) {
    const cards = {};

    if (cardTypes.includes("social")) {
      cards.socialCard = `${args.path}/social/social.png`;
    } else if (cardTypes.includes("social-twitter")) {
      cards.socialCard = `${args.path}/social/social-twitter.png`;
    }

    if (cardTypes.includes("social-twitter")) {
      cards.socialCardTwitter = `${args.path}/social/social-twitter.png`;
    }

    createPage({
      ...args,
      context: {
        ...args.context,
        ...cards,
      },
    });
  }
};

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage, createRedirect } = actions;

  const result = await graphql(
    `
      query Pages {
        backend {
          blogPosts {
            slugEn: slug(language: "en")
            slugIt: slug(language: "it")
          }
          pages {
            slugEn: slug(language: "en")
            slugIt: slug(language: "it")
          }
          conference {
            talks {
              slug
            }
            keynotes {
              slug
            }
            days {
              day
            }
          }
          submissions {
            id
          }
        }
      }
    `,
  );

  if (result.errors) {
    console.log(result.errors);

    reporter.panicOnBuild(`Error while running GraphQL query.`);
    return;
  }

  const blogTemplate = path.resolve(`src/templates/blog/index.tsx`);
  const blogPostTemplate = path.resolve(`src/templates/blog/post.tsx`);
  const blogPostSocialTemplate = path.resolve(
    `src/templates/blog/social-card.tsx`,
  );
  const submissionTemplate = path.resolve(`src/templates/submission/index.tsx`);
  const submissionSocialTemplate = path.resolve(
    `src/templates/submission/social-card.tsx`,
  );
  const pageTemplate = path.resolve(`src/templates/page.tsx`);
  const homeTemplate = path.resolve(`src/templates/home.tsx`);
  const appTemplate = path.resolve(`src/templates/app.tsx`);
  const talkTemplate = path.resolve(`src/templates/talk/talk.tsx`);
  const talkSocialTemplate = path.resolve(`src/templates/talk/social-card.tsx`);

  createRedirect({
    fromPath: `/`,
    redirectInBrowser: true,
    toPath: `/en`,
  });

  const pages = [
    { template: homeTemplate, path: "" },
    { template: blogTemplate, path: "/blog" },
    { template: appTemplate, path: "/login", matchPath: "/login/*" },
    { template: appTemplate, path: "/signup", matchPath: "/signup/*" },
    { template: appTemplate, path: "/grants", matchPath: "/grants/*" },
    {
      template: appTemplate,
      path: "/unsubscribe",
      matchPath: "/unsubscribe/*",
    },
    { template: appTemplate, path: "/profile", matchPath: "/profile/*" },
    { template: appTemplate, path: "/cfp", matchPath: "/cfp/*" },
    { template: appTemplate, path: "/orders", matchPath: "/orders/*" },
    {
      template: appTemplate,
      path: "/submission",
      matchPath: "/submission/*",
    },
    {
      template: appTemplate,
      path: "/profile/edit",
      matchPath: "/profile/edit/*",
    },
    {
      template: appTemplate,
      path: "/submission",
      matchPath: "/submission/*",
    },
    {
      template: appTemplate,
      path: "/submission/edit",
      matchPath: "/submission/*/edit",
    },
    {
      template: appTemplate,
      path: "/reset-password",
      matchPath: "/reset-password/*",
    },
    {
      template: appTemplate,
      path: "/schedule",
      matchPath: "/schedule/*",
    },
    { template: appTemplate, path: "/tickets", matchPath: "/tickets/*" },
    {
      template: appTemplate,
      path: "/voting",
      matchPath: "/voting/*",
    },
    {
      template: appTemplate,
      path: "/ranking",
      matchPath: "/ranking/*",
    },
  ];
  const languages = ["en", "it"];

  pages.forEach(page => {
    languages.forEach(language =>
      createPage({
        path: `/${language}${page.path}`,
        component: page.template,
        matchPath: page.matchPath ? `/${language}${page.matchPath}` : null,
        context: {
          language,
          alternateLinks: {
            en: `/en${page.path}`,
            it: `/it${page.path}`,
          },
          conferenceCode: process.env.CONFERENCE_CODE || "pycon-demo",
        },
      }),
    );
  });

  result.data.backend.conference.days.forEach(({ day }) => {
    const path = `/schedule/${day}`;

    languages.forEach(language =>
      createPage({
        path: `/${language}${path}`,
        component: appTemplate,
        context: {
          language,
          alternateLinks: {
            en: `/en${path}`,
            it: `/it${path}`,
          },
          conferenceCode: process.env.CONFERENCE_CODE || "pycon-demo",
        },
      }),
    );
  });

  result.data.backend.blogPosts.forEach(({ slugEn, slugIt }) => {
    createPageWithSocialCards(createPage, blogPostSocialTemplate, {
      path: `/en/blog/${slugEn}`,
      component: blogPostTemplate,
      context: {
        slug: slugEn,
        language: "en",
        alternateLinks: {
          en: `/en/blog/${slugEn}`,
          it: `/it/blog/${slugIt}`,
        },
      },
    });

    createPageWithSocialCards(createPage, blogPostSocialTemplate, {
      path: `/it/blog/${slugIt}`,
      component: blogPostTemplate,
      context: {
        slug: slugIt,
        language: "it",
        alternateLinks: {
          en: `/en/blog/${slugEn}`,
          it: `/it/blog/${slugIt}`,
        },
      },
    });
  });

  result.data.backend.conference.talks.forEach(({ slug }) => {
    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/en/talk/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "en",
        type: "talk",
        alternateLinks: {
          en: `/en/talk/${slug}`,
          it: `/it/talk/${slug}`,
        },
      },
    });

    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/it/talk/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "it",
        type: "talk",
        alternateLinks: {
          en: `/en/talk/${slug}`,
          it: `/it/talk/${slug}`,
        },
      },
    });
  });

  result.data.backend.conference.keynotes.forEach(({ slug }) => {
    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/en/keynote/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "en",
        type: "keynote",
        alternateLinks: {
          en: `/en/keynote/${slug}`,
          it: `/it/keynote/${slug}`,
        },
      },
    });

    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/it/keynote/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "it",
        type: "keynote",
        alternateLinks: {
          en: `/en/keynote/${slug}`,
          it: `/it/keynote/${slug}`,
        },
      },
    });
  });

  result.data.backend.pages.forEach(({ slugEn, slugIt }) => {
    createPage({
      path: `/it/${slugIt}`,
      component: pageTemplate,
      context: {
        language: "it",
        slug: slugIt,
        alternateLinks: {
          en: `/en/${slugEn}`,
          it: `/it/${slugIt}`,
        },
      },
    });

    createPage({
      path: `/en/${slugEn}`,
      component: pageTemplate,
      context: {
        language: "en",
        slug: slugEn,
        alternateLinks: {
          en: `/en/${slugEn}`,
          it: `/it/${slugIt}`,
        },
      },
    });
  });

  // generic social card
  const genericSocialCardTemplate = path.resolve(
    `src/templates/social-card.tsx`,
  );

  createPageWithSocialCards(
    createPage,
    genericSocialCardTemplate,
    {
      path: "",
    },
    true,
  );
};

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage, deletePage } = actions;

  if (page.path.match(/^\/[a-z]{2}\/404\/$/)) {
    const oldPage = { ...page };

    const language = page.path.split(`/`)[1];
    page.matchPath = `/${language}/*`;

    deletePage(oldPage);
    createPage({
      ...page,
      context: {
        language,
        alternateLinks: {
          en: `/en/404`,
          it: `/it/404`,
        },
      },
    });
  }
};

exports.onCreateWebpackConfig = ({
  stage,
  rules,
  loaders,
  plugins,
  actions,
}) => {
  actions.setWebpackConfig({
    module: {
      rules: [
        {
          test: /\.graphql$/,
          exclude: /node_modules/,
          loader: "graphql-tag/loader",
        },
      ],
    },
  });
};
<commit_msg>Fix path<commit_after>/* eslint-disable @typescript-eslint/no-var-requires */

const path = require("path");
const {
  createFilePath,
  createRemoteFileNode,
} = require("gatsby-source-filesystem");

require("dotenv").config({
  path: `.env`,
});

exports.onCreateNode = ({ node, actions, getNode, getNodes }) => {
  const { createNodeField } = actions;

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode });
    createNodeField({
      name: `slug`,
      node,
      value,
    });
  }
};

exports.createResolvers = ({
  actions,
  cache,
  createNodeId,
  createResolvers,
  store,
  reporter,
}) => {
  const imageFileResolver = (source, args, context, info) => {
    if (!source.image) {
      return null;
    }

    return createRemoteFileNode({
      url: source.image,
      store,
      cache,
      createNode,
      createNodeId,
      reporter,
    });
  };

  const { createNode } = actions;

  const typesWithImages = [
    "BACKEND_Post",
    "BACKEND_Page",
    "BACKEND_Sponsor",
    "BACKEND_Event",
    "BACKEND_ScheduleItem",
  ];

  const resolvers = {};

  typesWithImages.forEach(type => {
    resolvers[type] = {
      imageFile: {
        type: `File`,
        resolve: imageFileResolver,
      },
    };
  });

  createResolvers(resolvers);
};

const createPageWithSocialCards = (
  createPage,
  socialCardComponent,
  args,
  createOnlySocialCard = false,
  cardTypes = ["social", "social-square", "social-twitter"],
) => {
  cardTypes.forEach(type => {
    createPage({
      ...args,
      path: `${args.path}/${type}`,
      component: socialCardComponent,
      context: {
        ...args.context,
        cardType: type,
      },
    });
  });

  if (!createOnlySocialCard) {
    const cards = {};

    if (cardTypes.includes("social")) {
      cards.socialCard = `${args.path}/social/social.png`;
    } else if (cardTypes.includes("social-twitter")) {
      cards.socialCard = `${args.path}/social-twitter/social.png`;
    }

    if (cardTypes.includes("social-twitter")) {
      cards.socialCardTwitter = `${args.path}/social-twitter/social.png`;
    }

    createPage({
      ...args,
      context: {
        ...args.context,
        ...cards,
      },
    });
  }
};

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage, createRedirect } = actions;

  const result = await graphql(
    `
      query Pages {
        backend {
          blogPosts {
            slugEn: slug(language: "en")
            slugIt: slug(language: "it")
          }
          pages {
            slugEn: slug(language: "en")
            slugIt: slug(language: "it")
          }
          conference {
            talks {
              slug
            }
            keynotes {
              slug
            }
            days {
              day
            }
          }
          submissions {
            id
          }
        }
      }
    `,
  );

  if (result.errors) {
    console.log(result.errors);

    reporter.panicOnBuild(`Error while running GraphQL query.`);
    return;
  }

  const blogTemplate = path.resolve(`src/templates/blog/index.tsx`);
  const blogPostTemplate = path.resolve(`src/templates/blog/post.tsx`);
  const blogPostSocialTemplate = path.resolve(
    `src/templates/blog/social-card.tsx`,
  );
  const submissionTemplate = path.resolve(`src/templates/submission/index.tsx`);
  const submissionSocialTemplate = path.resolve(
    `src/templates/submission/social-card.tsx`,
  );
  const pageTemplate = path.resolve(`src/templates/page.tsx`);
  const homeTemplate = path.resolve(`src/templates/home.tsx`);
  const appTemplate = path.resolve(`src/templates/app.tsx`);
  const talkTemplate = path.resolve(`src/templates/talk/talk.tsx`);
  const talkSocialTemplate = path.resolve(`src/templates/talk/social-card.tsx`);

  createRedirect({
    fromPath: `/`,
    redirectInBrowser: true,
    toPath: `/en`,
  });

  const pages = [
    { template: homeTemplate, path: "" },
    { template: blogTemplate, path: "/blog" },
    { template: appTemplate, path: "/login", matchPath: "/login/*" },
    { template: appTemplate, path: "/signup", matchPath: "/signup/*" },
    { template: appTemplate, path: "/grants", matchPath: "/grants/*" },
    {
      template: appTemplate,
      path: "/unsubscribe",
      matchPath: "/unsubscribe/*",
    },
    { template: appTemplate, path: "/profile", matchPath: "/profile/*" },
    { template: appTemplate, path: "/cfp", matchPath: "/cfp/*" },
    { template: appTemplate, path: "/orders", matchPath: "/orders/*" },
    {
      template: appTemplate,
      path: "/submission",
      matchPath: "/submission/*",
    },
    {
      template: appTemplate,
      path: "/profile/edit",
      matchPath: "/profile/edit/*",
    },
    {
      template: appTemplate,
      path: "/submission",
      matchPath: "/submission/*",
    },
    {
      template: appTemplate,
      path: "/submission/edit",
      matchPath: "/submission/*/edit",
    },
    {
      template: appTemplate,
      path: "/reset-password",
      matchPath: "/reset-password/*",
    },
    {
      template: appTemplate,
      path: "/schedule",
      matchPath: "/schedule/*",
    },
    { template: appTemplate, path: "/tickets", matchPath: "/tickets/*" },
    {
      template: appTemplate,
      path: "/voting",
      matchPath: "/voting/*",
    },
    {
      template: appTemplate,
      path: "/ranking",
      matchPath: "/ranking/*",
    },
  ];
  const languages = ["en", "it"];

  pages.forEach(page => {
    languages.forEach(language =>
      createPage({
        path: `/${language}${page.path}`,
        component: page.template,
        matchPath: page.matchPath ? `/${language}${page.matchPath}` : null,
        context: {
          language,
          alternateLinks: {
            en: `/en${page.path}`,
            it: `/it${page.path}`,
          },
          conferenceCode: process.env.CONFERENCE_CODE || "pycon-demo",
        },
      }),
    );
  });

  result.data.backend.conference.days.forEach(({ day }) => {
    const path = `/schedule/${day}`;

    languages.forEach(language =>
      createPage({
        path: `/${language}${path}`,
        component: appTemplate,
        context: {
          language,
          alternateLinks: {
            en: `/en${path}`,
            it: `/it${path}`,
          },
          conferenceCode: process.env.CONFERENCE_CODE || "pycon-demo",
        },
      }),
    );
  });

  result.data.backend.blogPosts.forEach(({ slugEn, slugIt }) => {
    createPageWithSocialCards(createPage, blogPostSocialTemplate, {
      path: `/en/blog/${slugEn}`,
      component: blogPostTemplate,
      context: {
        slug: slugEn,
        language: "en",
        alternateLinks: {
          en: `/en/blog/${slugEn}`,
          it: `/it/blog/${slugIt}`,
        },
      },
    });

    createPageWithSocialCards(createPage, blogPostSocialTemplate, {
      path: `/it/blog/${slugIt}`,
      component: blogPostTemplate,
      context: {
        slug: slugIt,
        language: "it",
        alternateLinks: {
          en: `/en/blog/${slugEn}`,
          it: `/it/blog/${slugIt}`,
        },
      },
    });
  });

  result.data.backend.conference.talks.forEach(({ slug }) => {
    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/en/talk/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "en",
        type: "talk",
        alternateLinks: {
          en: `/en/talk/${slug}`,
          it: `/it/talk/${slug}`,
        },
      },
    });

    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/it/talk/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "it",
        type: "talk",
        alternateLinks: {
          en: `/en/talk/${slug}`,
          it: `/it/talk/${slug}`,
        },
      },
    });
  });

  result.data.backend.conference.keynotes.forEach(({ slug }) => {
    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/en/keynote/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "en",
        type: "keynote",
        alternateLinks: {
          en: `/en/keynote/${slug}`,
          it: `/it/keynote/${slug}`,
        },
      },
    });

    createPageWithSocialCards(createPage, talkSocialTemplate, {
      path: `/it/keynote/${slug}`,
      component: talkTemplate,
      context: {
        slug,
        language: "it",
        type: "keynote",
        alternateLinks: {
          en: `/en/keynote/${slug}`,
          it: `/it/keynote/${slug}`,
        },
      },
    });
  });

  result.data.backend.pages.forEach(({ slugEn, slugIt }) => {
    createPage({
      path: `/it/${slugIt}`,
      component: pageTemplate,
      context: {
        language: "it",
        slug: slugIt,
        alternateLinks: {
          en: `/en/${slugEn}`,
          it: `/it/${slugIt}`,
        },
      },
    });

    createPage({
      path: `/en/${slugEn}`,
      component: pageTemplate,
      context: {
        language: "en",
        slug: slugEn,
        alternateLinks: {
          en: `/en/${slugEn}`,
          it: `/it/${slugIt}`,
        },
      },
    });
  });

  // generic social card
  const genericSocialCardTemplate = path.resolve(
    `src/templates/social-card.tsx`,
  );

  createPageWithSocialCards(
    createPage,
    genericSocialCardTemplate,
    {
      path: "",
    },
    true,
  );
};

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage, deletePage } = actions;

  if (page.path.match(/^\/[a-z]{2}\/404\/$/)) {
    const oldPage = { ...page };

    const language = page.path.split(`/`)[1];
    page.matchPath = `/${language}/*`;

    deletePage(oldPage);
    createPage({
      ...page,
      context: {
        language,
        alternateLinks: {
          en: `/en/404`,
          it: `/it/404`,
        },
      },
    });
  }
};

exports.onCreateWebpackConfig = ({
  stage,
  rules,
  loaders,
  plugins,
  actions,
}) => {
  actions.setWebpackConfig({
    module: {
      rules: [
        {
          test: /\.graphql$/,
          exclude: /node_modules/,
          loader: "graphql-tag/loader",
        },
      ],
    },
  });
};
<|endoftext|>


<commit_before>const gulp = require('gulp');
const config = require('../config.js');
const path = require('path');
const Remarkable = require('remarkable');
const fs = require('fs');
const gutil = require('gulp-util');
const multiDest = require('gulp-multi-dest');
const through = require('through2');
const YAML = require('yamljs');
const ReactDOMServer = require('react-dom/server');

import Loading from '../src/app/components/Loading';

import React from 'react';
import ReactMarkdown from 'react-markdown';

const md = new Remarkable({ html: true });

const THUMBNAIL_FACEBOOK = config.PRODUCTION_URL + '/static/images/thumbnail-facebook.png';
const THUMBNAIL_TWITTER = config.PRODUCTION_URL + '/static/images/thumbnail-twitter.png';
const META_TITLE = 'Firefox Test Pilot';
const META_DESCRIPTION = 'Test new Features. Give us feedback. Help build Firefox.';

gulp.task('pages-misc', () => {
  // We just need a dummy file to get a stream going; we're going to ignore
  // the contents in buildLandingPage
  return gulp.src(config.SRC_PATH + 'pages/*.js')
    .pipe(buildLandingPage())
    .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-experiments', () => {
  return gulp.src(config.CONTENT_SRC_PATH + 'experiments/*.yaml')
    .pipe(buildExperimentPage())
    .pipe(gulp.dest(config.DEST_PATH + 'experiments'));
});

gulp.task('pages-compiled', () => {
  return gulp.src(config.SRC_PATH + 'pages/**/*.md')
             .pipe(convertToCompiledPage())
             .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-contributing', () => {
  gulp.src('./contribute.json')
    .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-build', [
  'pages-misc',
  'pages-experiments',
  'pages-contributing',
  'pages-compiled'
]);

gulp.task('pages-watch', () => {
  gulp.watch(config.SRC_PATH + 'app.js', ['pages-build']);
  gulp.watch([config.SRC_PATH + 'pages/**/*.md'], ['pages-compiled']);
});

function buildLandingPage() {
  return through.obj(function landingPage(file, enc, cb) {
    const fileName = path.basename(file.history[0]);
    const noExtension = fileName.slice(0, fileName.indexOf('.'));
    const pageModule = path.join('..', 'src', 'pages', fileName);
    const outputPath = noExtension === 'home' ? 'index.html' : noExtension + '/index.html'
    const importedCreate = require(pageModule).default;
    const importedComponent = importedCreate();
    const pageContent = generateStaticPage(
      true,
      noExtension, '',
      importedComponent,
      {
        meta_title: META_TITLE,
        meta_description: META_DESCRIPTION,
        canonical_path: '',
        image_facebook: THUMBNAIL_FACEBOOK,
        image_twitter: THUMBNAIL_TWITTER,
        enable_pontoon: config.ENABLE_PONTOON,
        available_locales: config.AVAILABLE_LOCALES
      }
    );
    this.push(new gutil.File({
      path: outputPath,
      contents: new Buffer(pageContent)
    }));
    cb();
  });
}

function buildExperimentPage() {
  return through.obj(function experimentPage(file, enc, cb) {
    const yamlData = file.contents.toString();
    const experiment = YAML.parse(yamlData);
    const requiredCreate = require('../src/pages/experiment.js').default;
    const requiredComponent = requiredCreate(experiment.slug);
    const pageContent = generateStaticPage(
      true,
      'experiment', experiment.slug,
      requiredComponent,
      {
        meta_title: META_TITLE + ' - ' + experiment.title,
        meta_description: experiment.description,
        canonical_path: 'experiments/' + experiment.slug + '/',
        image_facebook: config.PRODUCTION_URL + experiment.image_facebook ||
          THUMBNAIL_FACEBOOK,
        image_twitter: config.PRODUCTION_URL + experiment.image_twitter ||
          THUMBNAIL_TWITTER,
        enable_pontoon: config.ENABLE_PONTOON,
        available_locales: config.AVAILABLE_LOCALES
      }
    );
    this.push(new gutil.File({
      path: experiment.slug + '/index.html',
      contents: new Buffer(pageContent)
    }));
    cb();
  });
}

function availableLanguages(path) {
  return fs.readdirSync(path)
    .map(function (f) {
      return f.split('.')[0]
    })
    .join(',');
}

function convertToCompiledPage() {
  return through.obj(function compiledConvert(file, encoding, callback) {
    const p = path.parse(file.path);
    const locale = p.name;
    const page = path.basename(p.dir);
    const noExtension = page.slice(0, page.indexOf('.'));
    const pageContent = generateStaticPageFromMarkdown(
      noExtension, '',
      file.contents.toString(),
      {
        available_locales: availableLanguages(p.dir),
        canonical_path: page,
        meta_title: META_TITLE,
        meta_description: META_DESCRIPTION,
        image_facebook: THUMBNAIL_FACEBOOK,
        image_twitter: THUMBNAIL_TWITTER
      }
    );
    const contents = new Buffer(pageContent);
    if (locale === 'en-US') {
      this.push(new gutil.File({
        path: path.join(page, 'index.html'),
        contents
      }));
    }
    this.push(new gutil.File({
      path: path.join(page, locale, 'index.html'),
      contents
    }));
    callback();
  });
}

function makeStaticString(
  prepareForClient, pageName, pageParam, headComponent,
  staticBodyComponent, dynamicBodyComponent
) {
  const head = ReactDOMServer.renderToStaticMarkup(headComponent);
  const staticRoot = ReactDOMServer.renderToStaticMarkup(staticBodyComponent);
  let dynamicRoot;
  let bootstrapScript;
  if (prepareForClient) {
    dynamicRoot = ReactDOMServer.renderToString(dynamicBodyComponent);
    bootstrapScript = '';
  } else if (dynamicBodyComponent) {
    dynamicRoot = ReactDOMServer.renderToStaticMarkup(dynamicBodyComponent);
    bootstrapScript = '';
  }
  return `<!DOCTYPE html>

  ${head}

    ${staticRoot}

${dynamicRoot}

    ${bootstrapScript}

`;
}

function generateStaticPage(prepareForClient, pageName, pageParam, component, {
  available_locales, canonical_path, meta_title, meta_description,
  image_facebook, image_twitter, enable_pontoon
}) {
  const headComponent =
    <meta charSet="utf-8" />
    <link rel="shortcut icon" href="/static/images/favicon.ico" />
    <link rel="stylesheet" href="https://code.cdn.mozilla.net/fonts/fira.css" />
    <link rel="stylesheet" href="/static/styles/experiments.css" />
    <link rel="stylesheet" href="/static/styles/main.css" />

    <meta name="defaultLanguage" content="en-US" />
    <meta name="availableLanguages" content={ available_locales } />
    <meta name="viewport" content="width=device-width" />

    <link rel="localization" href="/static/locales/{locale}/app.ftl" />
    <link rel="localization" href="/static/locales/{locale}/experiments.ftl" />

    <link rel="canonical" href={ `https://testpilot.firefox.com/${canonical_path}` } />

    <title data-l10n-id="pageTitleDefault">{ meta_title }</title>

    <meta property="og:title" content={ meta_title } />
    <meta name="twitter:title" content={ meta_title } />
    <meta name="description" content={ meta_description } />
    <meta property="og:description" content={ meta_description } />
    <meta name="twitter:description" content={ meta_description } />
    <meta name="twitter:card" content="summary" />
    <meta property="og:image" content={ image_facebook } />
    <meta name="twitter:image" content={ image_twitter } />
    <meta property="og:url" content="https://testpilot.firefox.com" />
  ;
  const bodyComponent =

Uh oh...

Test Pilot requires JavaScript.
Sorry about that.

              Find out why

    <Loading />
    { prepareForClient ?  : null }
    { enable_pontoon ?  : null }

;

  return makeStaticString(prepareForClient, pageName, pageParam, headComponent, bodyComponent, component);
}

function generateStaticPageFromMarkdown(pageName, pageParam, markdown, params) {
  const body =

        Firefox Test Pilot

      <ReactMarkdown source={ markdown } />

          Legal
          About Test Pilot
          Privacy
          Terms
          Cookies

;

  return generateStaticPage(
    false, pageName, pageParam, body, JSON.stringify(markdown), params
  );
}
<commit_msg>Fix #2440 Don't show the loading indicator on static pages.<commit_after>const gulp = require('gulp');
const config = require('../config.js');
const path = require('path');
const Remarkable = require('remarkable');
const fs = require('fs');
const gutil = require('gulp-util');
const multiDest = require('gulp-multi-dest');
const through = require('through2');
const YAML = require('yamljs');
const ReactDOMServer = require('react-dom/server');

import Loading from '../src/app/components/Loading';

import React from 'react';
import ReactMarkdown from 'react-markdown';

const md = new Remarkable({ html: true });

const THUMBNAIL_FACEBOOK = config.PRODUCTION_URL + '/static/images/thumbnail-facebook.png';
const THUMBNAIL_TWITTER = config.PRODUCTION_URL + '/static/images/thumbnail-twitter.png';
const META_TITLE = 'Firefox Test Pilot';
const META_DESCRIPTION = 'Test new Features. Give us feedback. Help build Firefox.';

gulp.task('pages-misc', () => {
  // We just need a dummy file to get a stream going; we're going to ignore
  // the contents in buildLandingPage
  return gulp.src(config.SRC_PATH + 'pages/*.js')
    .pipe(buildLandingPage())
    .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-experiments', () => {
  return gulp.src(config.CONTENT_SRC_PATH + 'experiments/*.yaml')
    .pipe(buildExperimentPage())
    .pipe(gulp.dest(config.DEST_PATH + 'experiments'));
});

gulp.task('pages-compiled', () => {
  return gulp.src(config.SRC_PATH + 'pages/**/*.md')
             .pipe(convertToCompiledPage())
             .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-contributing', () => {
  gulp.src('./contribute.json')
    .pipe(gulp.dest(config.DEST_PATH));
});

gulp.task('pages-build', [
  'pages-misc',
  'pages-experiments',
  'pages-contributing',
  'pages-compiled'
]);

gulp.task('pages-watch', () => {
  gulp.watch(config.SRC_PATH + 'app.js', ['pages-build']);
  gulp.watch([config.SRC_PATH + 'pages/**/*.md'], ['pages-compiled']);
});

function buildLandingPage() {
  return through.obj(function landingPage(file, enc, cb) {
    const fileName = path.basename(file.history[0]);
    const noExtension = fileName.slice(0, fileName.indexOf('.'));
    const pageModule = path.join('..', 'src', 'pages', fileName);
    const outputPath = noExtension === 'home' ? 'index.html' : noExtension + '/index.html'
    const importedCreate = require(pageModule).default;
    const importedComponent = importedCreate();
    const pageContent = generateStaticPage(
      true,
      noExtension, '',
      importedComponent,
      {
        meta_title: META_TITLE,
        meta_description: META_DESCRIPTION,
        canonical_path: '',
        image_facebook: THUMBNAIL_FACEBOOK,
        image_twitter: THUMBNAIL_TWITTER,
        enable_pontoon: config.ENABLE_PONTOON,
        available_locales: config.AVAILABLE_LOCALES
      }
    );
    this.push(new gutil.File({
      path: outputPath,
      contents: new Buffer(pageContent)
    }));
    cb();
  });
}

function buildExperimentPage() {
  return through.obj(function experimentPage(file, enc, cb) {
    const yamlData = file.contents.toString();
    const experiment = YAML.parse(yamlData);
    const requiredCreate = require('../src/pages/experiment.js').default;
    const requiredComponent = requiredCreate(experiment.slug);
    const pageContent = generateStaticPage(
      true,
      'experiment', experiment.slug,
      requiredComponent,
      {
        meta_title: META_TITLE + ' - ' + experiment.title,
        meta_description: experiment.description,
        canonical_path: 'experiments/' + experiment.slug + '/',
        image_facebook: config.PRODUCTION_URL + experiment.image_facebook ||
          THUMBNAIL_FACEBOOK,
        image_twitter: config.PRODUCTION_URL + experiment.image_twitter ||
          THUMBNAIL_TWITTER,
        enable_pontoon: config.ENABLE_PONTOON,
        available_locales: config.AVAILABLE_LOCALES
      }
    );
    this.push(new gutil.File({
      path: experiment.slug + '/index.html',
      contents: new Buffer(pageContent)
    }));
    cb();
  });
}

function availableLanguages(path) {
  return fs.readdirSync(path)
    .map(function (f) {
      return f.split('.')[0]
    })
    .join(',');
}

function convertToCompiledPage() {
  return through.obj(function compiledConvert(file, encoding, callback) {
    const p = path.parse(file.path);
    const locale = p.name;
    const page = path.basename(p.dir);
    const noExtension = page.slice(0, page.indexOf('.'));
    const pageContent = generateStaticPageFromMarkdown(
      noExtension, '',
      file.contents.toString(),
      {
        available_locales: availableLanguages(p.dir),
        canonical_path: page,
        meta_title: META_TITLE,
        meta_description: META_DESCRIPTION,
        image_facebook: THUMBNAIL_FACEBOOK,
        image_twitter: THUMBNAIL_TWITTER
      }
    );
    const contents = new Buffer(pageContent);
    if (locale === 'en-US') {
      this.push(new gutil.File({
        path: path.join(page, 'index.html'),
        contents
      }));
    }
    this.push(new gutil.File({
      path: path.join(page, locale, 'index.html'),
      contents
    }));
    callback();
  });
}

function makeStaticString(
  prepareForClient, pageName, pageParam, headComponent,
  staticBodyComponent, dynamicBodyComponent
) {
  const head = ReactDOMServer.renderToStaticMarkup(headComponent);
  const staticRoot = ReactDOMServer.renderToStaticMarkup(staticBodyComponent);
  let dynamicRoot;
  let bootstrapScript;
  if (prepareForClient) {
    dynamicRoot = ReactDOMServer.renderToString(dynamicBodyComponent);
    bootstrapScript = '';
  } else if (dynamicBodyComponent) {
    dynamicRoot = ReactDOMServer.renderToStaticMarkup(dynamicBodyComponent);
    bootstrapScript = '';
  }
  return `<!DOCTYPE html>

  ${head}

    ${staticRoot}

${dynamicRoot}

    ${bootstrapScript}

`;
}

function generateStaticPage(prepareForClient, pageName, pageParam, component, {
  available_locales, canonical_path, meta_title, meta_description,
  image_facebook, image_twitter, enable_pontoon
}) {
  const headComponent =
    <meta charSet="utf-8" />
    <link rel="shortcut icon" href="/static/images/favicon.ico" />
    <link rel="stylesheet" href="https://code.cdn.mozilla.net/fonts/fira.css" />
    <link rel="stylesheet" href="/static/styles/experiments.css" />
    <link rel="stylesheet" href="/static/styles/main.css" />

    <meta name="defaultLanguage" content="en-US" />
    <meta name="availableLanguages" content={ available_locales } />
    <meta name="viewport" content="width=device-width" />

    <link rel="localization" href="/static/locales/{locale}/app.ftl" />
    <link rel="localization" href="/static/locales/{locale}/experiments.ftl" />

    <link rel="canonical" href={ `https://testpilot.firefox.com/${canonical_path}` } />

    <title data-l10n-id="pageTitleDefault">{ meta_title }</title>

    <meta property="og:title" content={ meta_title } />
    <meta name="twitter:title" content={ meta_title } />
    <meta name="description" content={ meta_description } />
    <meta property="og:description" content={ meta_description } />
    <meta name="twitter:description" content={ meta_description } />
    <meta name="twitter:card" content="summary" />
    <meta property="og:image" content={ image_facebook } />
    <meta name="twitter:image" content={ image_twitter } />
    <meta property="og:url" content="https://testpilot.firefox.com" />
  ;
  const bodyComponent =

Uh oh...

Test Pilot requires JavaScript.
Sorry about that.

              Find out why

    { prepareForClient ? <Loading /> : null }
    { prepareForClient ?  : null }
    { enable_pontoon ?  : null }

;

  return makeStaticString(prepareForClient, pageName, pageParam, headComponent, bodyComponent, component);
}

function generateStaticPageFromMarkdown(pageName, pageParam, markdown, params) {
  const body =

        Firefox Test Pilot

      <ReactMarkdown source={ markdown } />

          Legal
          About Test Pilot
          Privacy
          Terms
          Cookies

;

  return generateStaticPage(
    false, pageName, pageParam, body, JSON.stringify(markdown), params
  );
}
<|endoftext|>


<commit_before>/*
Copyright 2017 OpenMarket Ltd
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Promise from 'bluebird';

// This module contains all the code needed to log the console, persist it to
// disk and submit bug reports. Rationale is as follows:
//  - Monkey-patching the console is preferable to having a log library because
//    we can catch logs by other libraries more easily, without having to all
//    depend on the same log framework / pass the logger around.
//  - We use IndexedDB to persists logs because it has generous disk space
//    limits compared to local storage. IndexedDB does not work in incognito
//    mode, in which case this module will not be able to write logs to disk.
//    However, the logs will still be stored in-memory, so can still be
//    submitted in a bug report should the user wish to: we can also store more
//    logs in-memory than in local storage, which does work in incognito mode.
//    We also need to handle the case where there are 2+ tabs. Each JS runtime
//    generates a random string which serves as the "ID" for that tab/session.
//    These IDs are stored along with the log lines.
//  - Bug reports are sent as a POST over HTTPS: it purposefully does not use
//    Matrix as bug reports may be made when Matrix is not responsive (which may
//    be the cause of the bug). We send the most recent N MB of UTF-8 log data,
//    starting with the most recent, which we know because the "ID"s are
//    actually timestamps. We then purge the remaining logs. We also do this
//    purge on startup to prevent logs from accumulating.

// the frequency with which we flush to indexeddb
const FLUSH_RATE_MS = 30 * 1000;

// the length of log data we keep in indexeddb (and include in the reports)
const MAX_LOG_SIZE = 1024 * 1024 * 1; // 1 MB

// A class which monkey-patches the global console and stores log lines.
class ConsoleLogger {
    constructor() {
        this.logs = "";
    }

    monkeyPatch(consoleObj) {
        // Monkey-patch console logging
        const consoleFunctionsToLevels = {
            log: "I",
            info: "I",
            warn: "W",
            error: "E",
        };
        Object.keys(consoleFunctionsToLevels).forEach((fnName) => {
            const level = consoleFunctionsToLevels[fnName];
            const originalFn = consoleObj[fnName].bind(consoleObj);
            consoleObj[fnName] = (...args) => {
                this.log(level, ...args);
                originalFn(...args);
            };
        });
    }

    log(level, ...args) {
        // We don't know what locale the user may be running so use ISO strings
        const ts = new Date().toISOString();
        // Some browsers support string formatting which we're not doing here
        // so the lines are a little more ugly but easy to implement / quick to
        // run.
        // Example line:
        // 2017-01-18T11:23:53.214Z W Failed to set badge count
        const line = `${ts} ${level} ${args.join(' ')}\n`;
        // Using + really is the quickest way in JS
        // http://jsperf.com/concat-vs-plus-vs-join
        this.logs += line;
    }

    /**
     * Retrieve log lines to flush to disk.
     * @param {boolean} keepLogs True to not delete logs after flushing.
     * @return {string} \n delimited log lines to flush.
     */
    flush(keepLogs) {
        // The ConsoleLogger doesn't care how these end up on disk, it just
        // flushes them to the caller.
        if (keepLogs) {
            return this.logs;
        }
        const logsToFlush = this.logs;
        this.logs = "";
        return logsToFlush;
    }
}

// A class which stores log lines in an IndexedDB instance.
class IndexedDBLogStore {
    constructor(indexedDB, logger) {
        this.indexedDB = indexedDB;
        this.logger = logger;
        this.id = "instance-" + Math.random() + Date.now();
        this.index = 0;
        this.db = null;
        this.flushPromise = null;
        // set if flush() is called whilst one is ongoing
        this.flushAgainPromise = null;
    }

    /**
     * @return {Promise} Resolves when the store is ready.
     */
    connect() {
        const req = this.indexedDB.open("logs");
        return new Promise((resolve, reject) => {
            req.onsuccess = (event) => {
                this.db = event.target.result;
                // Periodically flush logs to local storage / indexeddb
                setInterval(this.flush.bind(this), FLUSH_RATE_MS);
                resolve();
            };

            req.onerror = (event) => {
                const err = (
                    "Failed to open log database: " + event.target.error.name
                );
                console.error(err);
                reject(new Error(err));
            };

            // First time: Setup the object store
            req.onupgradeneeded = (event) => {
                const db = event.target.result;
                const logObjStore = db.createObjectStore("logs", {
                    keyPath: ["id", "index"],
                });
                // Keys in the database look like: [ "instance-148938490", 0 ]
                // Later on we need to query everything based on an instance id.
                // In order to do this, we need to set up indexes "id".
                logObjStore.createIndex("id", "id", { unique: false });

                logObjStore.add(
                    this._generateLogEntry(
                        new Date() + " ::: Log database was created.",
                    ),
                );

                const lastModifiedStore = db.createObjectStore("logslastmod", {
                    keyPath: "id",
                });
                lastModifiedStore.add(this._generateLastModifiedTime());
            };
        });
    }

    /**
     * Flush logs to disk.
     *
     * There are guards to protect against race conditions in order to ensure
     * that all previous flushes have completed before the most recent flush.
     * Consider without guards:
     *  - A calls flush() periodically.
     *  - B calls flush() and wants to send logs immediately afterwards.
     *  - If B doesn't wait for A's flush to complete, B will be missing the
     *    contents of A's flush.
     * To protect against this, we set 'flushPromise' when a flush is ongoing.
     * Subsequent calls to flush() during this period will chain another flush,
     * then keep returning that same chained flush.
     *
     * This guarantees that we will always eventually do a flush when flush() is
     * called.
     *
     * @return {Promise} Resolved when the logs have been flushed.
     */
    flush() {
        // check if a flush() operation is ongoing
        if (this.flushPromise && this.flushPromise.isPending()) {
            if (this.flushAgainPromise && this.flushAgainPromise.isPending()) {
                // this is the 3rd+ time we've called flush() : return the same
                // promise.
                return this.flushAgainPromise;
            }
            // queue up a flush to occur immediately after the pending one
            // completes.
            this.flushAgainPromise = this.flushPromise.then(() => {
                return this.flush();
            });
            return this.flushAgainPromise;
        }
        // there is no flush promise or there was but it has finished, so do
        // a brand new one, destroying the chain which may have been built up.
        this.flushPromise = new Promise((resolve, reject) => {
            if (!this.db) {
                // not connected yet or user rejected access for us to r/w to
                // the db.
                reject(new Error("No connected database"));
                return;
            }
            const lines = this.logger.flush();
            if (lines.length === 0) {
                resolve();
                return;
            }
            const txn = this.db.transaction(["logs", "logslastmod"], "readwrite");
            const objStore = txn.objectStore("logs");
            txn.oncomplete = (event) => {
                resolve();
            };
            txn.onerror = (event) => {
                console.error(
                    "Failed to flush logs : ", event,
                );
                reject(
                    new Error("Failed to write logs: " + event.target.errorCode),
                );
            };
            objStore.add(this._generateLogEntry(lines));
            const lastModStore = txn.objectStore("logslastmod");
            lastModStore.put(this._generateLastModifiedTime());
        });
        return this.flushPromise;
    }

    /**
     * Consume the most recent logs and return them. Older logs which are not
     * returned are deleted at the same time, so this can be called at startup
     * to do house-keeping to keep the logs from growing too large.
     *
     * @return {Promise<Object[]>} Resolves to an array of objects. The array is
     * sorted in time (oldest first) based on when the log file was created (the
     * log ID). The objects have said log ID in an "id" field and "lines" which
     * is a big string with all the new-line delimited logs.
     */
    async consume() {
        const db = this.db;

        // Returns: a string representing the concatenated logs for this ID.
        function fetchLogs(id) {
            const o = db.transaction("logs", "readonly").objectStore("logs");
            return selectQuery(o.index("id"), IDBKeyRange.only(id),
            (cursor) => {
                return {
                    lines: cursor.value.lines,
                    index: cursor.value.index,
                };
            }).then((linesArray) => {
                // We have been storing logs periodically, so string them all
                // together *in order of index* now
                linesArray.sort((a, b) => {
                    return a.index - b.index;
                });
                return linesArray.map((l) => l.lines).join("");
            });
        }

        // Returns: A sorted array of log IDs. (newest first)
        function fetchLogIds() {
            // To gather all the log IDs, query for all records in logslastmod.
            const o = db.transaction("logslastmod", "readonly").objectStore(
                "logslastmod",
            );
            return selectQuery(o, undefined, (cursor) => {
                return {
                    id: cursor.value.id,
                    ts: cursor.value.ts,
                };
            }).then((res) => {
                // Sort IDs by timestamp (newest first)
                return res.sort((a, b) => {
                    return b.ts - a.ts;
                }).map((a) => a.id);
            });
        }

        function deleteLogs(id) {
            return new Promise((resolve, reject) => {
                const txn = db.transaction(
                    ["logs", "logslastmod"], "readwrite",
                );
                const o = txn.objectStore("logs");
                // only load the key path, not the data which may be huge
                const query = o.index("id").openKeyCursor(IDBKeyRange.only(id));
                query.onsuccess = (event) => {
                    const cursor = event.target.result;
                    if (!cursor) {
                        return;
                    }
                    o.delete(cursor.primaryKey);
                    cursor.continue();
                };
                txn.oncomplete = () => {
                    resolve();
                };
                txn.onerror = (event) => {
                    reject(
                        new Error(
                            "Failed to delete logs for " +
                            `'${id}' : ${event.target.errorCode}`,
                        ),
                    );
                };
                // delete last modified entries
                const lastModStore = txn.objectStore("logslastmod");
                lastModStore.delete(id);
            });
        }

        const allLogIds = await fetchLogIds();
        let removeLogIds = [];
        const logs = [];
        let size = 0;
        for (let i = 0; i < allLogIds.length; i++) {
            const lines = await fetchLogs(allLogIds[i]);

            // always include at least one log file, but only include
            // subsequent ones if they won't take us over the MAX_LOG_SIZE
            if (i > 0 && size + lines.length > MAX_LOG_SIZE) {
                // the remaining log IDs should be removed. If we go out of
                // bounds this is just []
                //
                // XXX: there's nothing stopping the current session exceeding
                // MAX_LOG_SIZE. We ought to think about culling it.
                removeLogIds = allLogIds.slice(i + 1);
                break;
            }

            logs.push({
                lines: lines,
                id: allLogIds[i],
            });
            size += lines.length;
        }
        if (removeLogIds.length > 0) {
            console.log("Removing logs: ", removeLogIds);
            // Don't await this because it's non-fatal if we can't clean up
            // logs.
            Promise.all(removeLogIds.map((id) => deleteLogs(id))).then(() => {
                console.log(`Removed ${removeLogIds.length} old logs.`);
            }, (err) => {
                console.error(err);
            });
        }
        return logs;
    }

    _generateLogEntry(lines) {
        return {
            id: this.id,
            lines: lines,
            index: this.index++,
        };
    }

    _generateLastModifiedTime() {
        return {
            id: this.id,
            ts: Date.now(),
        };
    }
}

/**
 * Helper method to collect results from a Cursor and promiseify it.
 * @param {ObjectStore|Index} store The store to perform openCursor on.
 * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor.
 * @param {Function} resultMapper A function which is repeatedly called with a
 * Cursor.
 * Return the data you want to keep.
 * @return {Promise<T[]>} Resolves to an array of whatever you returned from
 * resultMapper.
 */
function selectQuery(store, keyRange, resultMapper) {
    const query = store.openCursor(keyRange);
    return new Promise((resolve, reject) => {
        const results = [];
        query.onerror = (event) => {
            reject(new Error("Query failed: " + event.target.errorCode));
        };
        // collect results
        query.onsuccess = (event) => {
            const cursor = event.target.result;
            if (!cursor) {
                resolve(results);
                return; // end of results
            }
            results.push(resultMapper(cursor));
            cursor.continue();
        };
    });
}

module.exports = {

    /**
     * Configure rage shaking support for sending bug reports.
     * Modifies globals.
     * @return {Promise} Resolves when set up.
     */
    init: function() {
        if (global.mx_rage_initPromise) {
            return global.mx_rage_initPromise;
        }
        global.mx_rage_logger = new ConsoleLogger();
        global.mx_rage_logger.monkeyPatch(window.console);

        // just *accessing* indexedDB throws an exception in firefox with
        // indexeddb disabled.
        let indexedDB;
        try {
            indexedDB = window.indexedDB;
        } catch (e) {}

        if (indexedDB) {
            global.mx_rage_store = new IndexedDBLogStore(indexedDB, global.mx_rage_logger);
            global.mx_rage_initPromise = global.mx_rage_store.connect();
            return global.mx_rage_initPromise;
        }
        global.mx_rage_initPromise = Promise.resolve();
        return global.mx_rage_initPromise;
    },

    flush: function() {
        if (!global.mx_rage_store) {
            return;
        }
        global.mx_rage_store.flush();
    },

    /**
     * Clean up old logs.
     * @return Promise Resolves if cleaned logs.
     */
    cleanup: async function() {
        if (!global.mx_rage_store) {
            return;
        }
        await global.mx_rage_store.consume();
    },

    /**
     * Get a recent snapshot of the logs, ready for attaching to a bug report
     *
     * @return {Array<{lines: string, id, string}>}  list of log data
     */
    getLogsForReport: async function() {
        if (!global.mx_rage_logger) {
            throw new Error(
                "No console logger, did you forget to call init()?",
            );
        }
        // If in incognito mode, store is null, but we still want bug report
        // sending to work going off the in-memory console logs.
        if (global.mx_rage_store) {
            // flush most recent logs
            await global.mx_rage_store.flush();
            return await global.mx_rage_store.consume();
        } else {
            return [{
                lines: global.mx_rage_logger.flush(true),
                id: "-",
            }];
        }
    },
};
<commit_msg>Make rageshake use less memory<commit_after>/*
Copyright 2017 OpenMarket Ltd
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Promise from 'bluebird';

// This module contains all the code needed to log the console, persist it to
// disk and submit bug reports. Rationale is as follows:
//  - Monkey-patching the console is preferable to having a log library because
//    we can catch logs by other libraries more easily, without having to all
//    depend on the same log framework / pass the logger around.
//  - We use IndexedDB to persists logs because it has generous disk space
//    limits compared to local storage. IndexedDB does not work in incognito
//    mode, in which case this module will not be able to write logs to disk.
//    However, the logs will still be stored in-memory, so can still be
//    submitted in a bug report should the user wish to: we can also store more
//    logs in-memory than in local storage, which does work in incognito mode.
//    We also need to handle the case where there are 2+ tabs. Each JS runtime
//    generates a random string which serves as the "ID" for that tab/session.
//    These IDs are stored along with the log lines.
//  - Bug reports are sent as a POST over HTTPS: it purposefully does not use
//    Matrix as bug reports may be made when Matrix is not responsive (which may
//    be the cause of the bug). We send the most recent N MB of UTF-8 log data,
//    starting with the most recent, which we know because the "ID"s are
//    actually timestamps. We then purge the remaining logs. We also do this
//    purge on startup to prevent logs from accumulating.

// the frequency with which we flush to indexeddb
const FLUSH_RATE_MS = 30 * 1000;

// the length of log data we keep in indexeddb (and include in the reports)
const MAX_LOG_SIZE = 1024 * 1024 * 1; // 1 MB

// A class which monkey-patches the global console and stores log lines.
class ConsoleLogger {
    constructor() {
        this.logs = "";
    }

    monkeyPatch(consoleObj) {
        // Monkey-patch console logging
        const consoleFunctionsToLevels = {
            log: "I",
            info: "I",
            warn: "W",
            error: "E",
        };
        Object.keys(consoleFunctionsToLevels).forEach((fnName) => {
            const level = consoleFunctionsToLevels[fnName];
            const originalFn = consoleObj[fnName].bind(consoleObj);
            consoleObj[fnName] = (...args) => {
                this.log(level, ...args);
                originalFn(...args);
            };
        });
    }

    log(level, ...args) {
        // We don't know what locale the user may be running so use ISO strings
        const ts = new Date().toISOString();
        // Some browsers support string formatting which we're not doing here
        // so the lines are a little more ugly but easy to implement / quick to
        // run.
        // Example line:
        // 2017-01-18T11:23:53.214Z W Failed to set badge count
        const line = `${ts} ${level} ${args.join(' ')}\n`;
        // Using + really is the quickest way in JS
        // http://jsperf.com/concat-vs-plus-vs-join
        this.logs += line;
    }

    /**
     * Retrieve log lines to flush to disk.
     * @param {boolean} keepLogs True to not delete logs after flushing.
     * @return {string} \n delimited log lines to flush.
     */
    flush(keepLogs) {
        // The ConsoleLogger doesn't care how these end up on disk, it just
        // flushes them to the caller.
        if (keepLogs) {
            return this.logs;
        }
        const logsToFlush = this.logs;
        this.logs = "";
        return logsToFlush;
    }
}

// A class which stores log lines in an IndexedDB instance.
class IndexedDBLogStore {
    constructor(indexedDB, logger) {
        this.indexedDB = indexedDB;
        this.logger = logger;
        this.id = "instance-" + Math.random() + Date.now();
        this.index = 0;
        this.db = null;
        this.flushPromise = null;
        // set if flush() is called whilst one is ongoing
        this.flushAgainPromise = null;
    }

    /**
     * @return {Promise} Resolves when the store is ready.
     */
    connect() {
        const req = this.indexedDB.open("logs");
        return new Promise((resolve, reject) => {
            req.onsuccess = (event) => {
                this.db = event.target.result;
                // Periodically flush logs to local storage / indexeddb
                setInterval(this.flush.bind(this), FLUSH_RATE_MS);
                resolve();
            };

            req.onerror = (event) => {
                const err = (
                    "Failed to open log database: " + event.target.error.name
                );
                console.error(err);
                reject(new Error(err));
            };

            // First time: Setup the object store
            req.onupgradeneeded = (event) => {
                const db = event.target.result;
                const logObjStore = db.createObjectStore("logs", {
                    keyPath: ["id", "index"],
                });
                // Keys in the database look like: [ "instance-148938490", 0 ]
                // Later on we need to query everything based on an instance id.
                // In order to do this, we need to set up indexes "id".
                logObjStore.createIndex("id", "id", { unique: false });

                logObjStore.add(
                    this._generateLogEntry(
                        new Date() + " ::: Log database was created.",
                    ),
                );

                const lastModifiedStore = db.createObjectStore("logslastmod", {
                    keyPath: "id",
                });
                lastModifiedStore.add(this._generateLastModifiedTime());
            };
        });
    }

    /**
     * Flush logs to disk.
     *
     * There are guards to protect against race conditions in order to ensure
     * that all previous flushes have completed before the most recent flush.
     * Consider without guards:
     *  - A calls flush() periodically.
     *  - B calls flush() and wants to send logs immediately afterwards.
     *  - If B doesn't wait for A's flush to complete, B will be missing the
     *    contents of A's flush.
     * To protect against this, we set 'flushPromise' when a flush is ongoing.
     * Subsequent calls to flush() during this period will chain another flush,
     * then keep returning that same chained flush.
     *
     * This guarantees that we will always eventually do a flush when flush() is
     * called.
     *
     * @return {Promise} Resolved when the logs have been flushed.
     */
    flush() {
        // check if a flush() operation is ongoing
        if (this.flushPromise && this.flushPromise.isPending()) {
            if (this.flushAgainPromise && this.flushAgainPromise.isPending()) {
                // this is the 3rd+ time we've called flush() : return the same
                // promise.
                return this.flushAgainPromise;
            }
            // queue up a flush to occur immediately after the pending one
            // completes.
            this.flushAgainPromise = this.flushPromise.then(() => {
                return this.flush();
            });
            return this.flushAgainPromise;
        }
        // there is no flush promise or there was but it has finished, so do
        // a brand new one, destroying the chain which may have been built up.
        this.flushPromise = new Promise((resolve, reject) => {
            if (!this.db) {
                // not connected yet or user rejected access for us to r/w to
                // the db.
                reject(new Error("No connected database"));
                return;
            }
            const lines = this.logger.flush();
            if (lines.length === 0) {
                resolve();
                return;
            }
            const txn = this.db.transaction(["logs", "logslastmod"], "readwrite");
            const objStore = txn.objectStore("logs");
            txn.oncomplete = (event) => {
                resolve();
            };
            txn.onerror = (event) => {
                console.error(
                    "Failed to flush logs : ", event,
                );
                reject(
                    new Error("Failed to write logs: " + event.target.errorCode),
                );
            };
            objStore.add(this._generateLogEntry(lines));
            const lastModStore = txn.objectStore("logslastmod");
            lastModStore.put(this._generateLastModifiedTime());
        });
        return this.flushPromise;
    }

    /**
     * Consume the most recent logs and return them. Older logs which are not
     * returned are deleted at the same time, so this can be called at startup
     * to do house-keeping to keep the logs from growing too large.
     *
     * @return {Promise<Object[]>} Resolves to an array of objects. The array is
     * sorted in time (oldest first) based on when the log file was created (the
     * log ID). The objects have said log ID in an "id" field and "lines" which
     * is a big string with all the new-line delimited logs.
     */
    async consume() {
        const db = this.db;

        // Returns: a string representing the concatenated logs for this ID.
        function fetchLogs(id) {
            const objectStore = db.transaction("logs", "readonly").objectStore("logs");

            return new Promise((resolve, reject) => {
                const query = objectStore.index("id").openCursor(IDBKeyRange.only(id), 'next');
                let lines = '';
                query.onerror = (event) => {
                    reject(new Error("Query failed: " + event.target.errorCode));
                };
                query.onsuccess = (event) => {
                    const cursor = event.target.result;
                    if (!cursor) {
                        resolve(lines);
                        return; // end of results
                    }
                    lines += cursor.value.lines;
                    if (lines.length >= MAX_LOG_SIZE) {
                        resolve(lines);
                    } else {
                        cursor.continue();
                    }
                };
            });
        }

        // Returns: A sorted array of log IDs. (newest first)
        function fetchLogIds() {
            // To gather all the log IDs, query for all records in logslastmod.
            const o = db.transaction("logslastmod", "readonly").objectStore(
                "logslastmod",
            );
            return selectQuery(o, undefined, (cursor) => {
                return {
                    id: cursor.value.id,
                    ts: cursor.value.ts,
                };
            }).then((res) => {
                // Sort IDs by timestamp (newest first)
                return res.sort((a, b) => {
                    return b.ts - a.ts;
                }).map((a) => a.id);
            });
        }

        function deleteLogs(id) {
            return new Promise((resolve, reject) => {
                const txn = db.transaction(
                    ["logs", "logslastmod"], "readwrite",
                );
                const o = txn.objectStore("logs");
                // only load the key path, not the data which may be huge
                const query = o.index("id").openKeyCursor(IDBKeyRange.only(id));
                query.onsuccess = (event) => {
                    const cursor = event.target.result;
                    if (!cursor) {
                        return;
                    }
                    o.delete(cursor.primaryKey);
                    cursor.continue();
                };
                txn.oncomplete = () => {
                    resolve();
                };
                txn.onerror = (event) => {
                    reject(
                        new Error(
                            "Failed to delete logs for " +
                            `'${id}' : ${event.target.errorCode}`,
                        ),
                    );
                };
                // delete last modified entries
                const lastModStore = txn.objectStore("logslastmod");
                lastModStore.delete(id);
            });
        }

        const allLogIds = await fetchLogIds();
        let removeLogIds = [];
        const logs = [];
        let size = 0;
        for (let i = 0; i < allLogIds.length; i++) {
            const lines = await fetchLogs(allLogIds[i]);

            // always include at least one log file, but only include
            // subsequent ones if they won't take us over the MAX_LOG_SIZE
            if (i > 0 && size + lines.length > MAX_LOG_SIZE) {
                // the remaining log IDs should be removed. If we go out of
                // bounds this is just []
                removeLogIds = allLogIds.slice(i + 1);
                break;
            }

            logs.push({
                lines: lines,
                id: allLogIds[i],
            });
            size += lines.length;
        }
        if (removeLogIds.length > 0) {
            console.log("Removing logs: ", removeLogIds);
            // Don't await this because it's non-fatal if we can't clean up
            // logs.
            Promise.all(removeLogIds.map((id) => deleteLogs(id))).then(() => {
                console.log(`Removed ${removeLogIds.length} old logs.`);
            }, (err) => {
                console.error(err);
            });
        }
        return logs;
    }

    _generateLogEntry(lines) {
        return {
            id: this.id,
            lines: lines,
            index: this.index++,
        };
    }

    _generateLastModifiedTime() {
        return {
            id: this.id,
            ts: Date.now(),
        };
    }
}

/**
 * Helper method to collect results from a Cursor and promiseify it.
 * @param {ObjectStore|Index} store The store to perform openCursor on.
 * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor.
 * @param {Function} resultMapper A function which is repeatedly called with a
 * Cursor.
 * Return the data you want to keep.
 * @return {Promise<T[]>} Resolves to an array of whatever you returned from
 * resultMapper.
 */
function selectQuery(store, keyRange, resultMapper) {
    const query = store.openCursor(keyRange);
    return new Promise((resolve, reject) => {
        const results = [];
        query.onerror = (event) => {
            reject(new Error("Query failed: " + event.target.errorCode));
        };
        // collect results
        query.onsuccess = (event) => {
            const cursor = event.target.result;
            if (!cursor) {
                resolve(results);
                return; // end of results
            }
            results.push(resultMapper(cursor));
            cursor.continue();
        };
    });
}

module.exports = {

    /**
     * Configure rage shaking support for sending bug reports.
     * Modifies globals.
     * @return {Promise} Resolves when set up.
     */
    init: function() {
        if (global.mx_rage_initPromise) {
            return global.mx_rage_initPromise;
        }
        global.mx_rage_logger = new ConsoleLogger();
        global.mx_rage_logger.monkeyPatch(window.console);

        // just *accessing* indexedDB throws an exception in firefox with
        // indexeddb disabled.
        let indexedDB;
        try {
            indexedDB = window.indexedDB;
        } catch (e) {}

        if (indexedDB) {
            global.mx_rage_store = new IndexedDBLogStore(indexedDB, global.mx_rage_logger);
            global.mx_rage_initPromise = global.mx_rage_store.connect();
            return global.mx_rage_initPromise;
        }
        global.mx_rage_initPromise = Promise.resolve();
        return global.mx_rage_initPromise;
    },

    flush: function() {
        if (!global.mx_rage_store) {
            return;
        }
        global.mx_rage_store.flush();
    },

    /**
     * Clean up old logs.
     * @return Promise Resolves if cleaned logs.
     */
    cleanup: async function() {
        if (!global.mx_rage_store) {
            return;
        }
        await global.mx_rage_store.consume();
    },

    /**
     * Get a recent snapshot of the logs, ready for attaching to a bug report
     *
     * @return {Array<{lines: string, id, string}>}  list of log data
     */
    getLogsForReport: async function() {
        if (!global.mx_rage_logger) {
            throw new Error(
                "No console logger, did you forget to call init()?",
            );
        }
        // If in incognito mode, store is null, but we still want bug report
        // sending to work going off the in-memory console logs.
        if (global.mx_rage_store) {
            // flush most recent logs
            await global.mx_rage_store.flush();
            return await global.mx_rage_store.consume();
        } else {
            return [{
                lines: global.mx_rage_logger.flush(true),
                id: "-",
            }];
        }
    },
};
<|endoftext|>


<commit_before>/*
 * Xccessors Standard: Cross-browser ECMAScript 5 accessors
 * http://purl.eligrey.com/github/Xccessors
 *
 * 2010-06-21
 *
 * By Eli Grey, http://eligrey.com
 *
 * A shim that partially implements Object.defineProperty,
 * Object.getOwnPropertyDescriptor, and Object.defineProperties in browsers that have
 * legacy __(define|lookup)[GS]etter__ support.
 *
 * Licensed under the X11/MIT License
 *   See LICENSE.md
*/

/*jslint white: true, onevar: true, undef: true, eqeqeq: true, plusplus: true,
  bitwise: true, regexp: true, strict: true, newcap: true, immed: true, maxlen: 90 */

/*! @source http://purl.eligrey.com/github/Xccessors/blob/master/xccessors-standard.js*/

"use strict";

(function () {
	var ObjectProto = Object.prototype,
	True = !0,
	False = !1,
	defineGetter = ObjectProto.__defineGetter__,
	defineSetter = ObjectProto.__defineSetter__,
	lookupGetter = ObjectProto.__lookupGetter__,
	lookupSetter = ObjectProto.__lookupSetter__,
	hasOwnProp = ObjectProto.hasOwnProperty;

	if (defineGetter && defineSetter && lookupGetter && lookupSetter) {

		if (!Object.defineProperty) {
			Object.defineProperty = function (obj, prop, descriptor) {
				if (arguments.length < 3) { // all arguments required
					throw new TypeError("Arguments not optional");
				}

				prop += ""; // convert prop to string

				if (hasOwnProp.call(descriptor, "value")) {
					if (!lookupGetter.call(obj, prop) && !lookupSetter.call(obj, prop)) {
						// data property defined and no pre-existing accessors
						obj[prop] = descriptor.value;
					}

					if ((hasOwnProp.call(descriptor, "get") ||
					     hasOwnProp.call(descriptor, "set")))
					{
						// descriptor has a value prop but accessor already exists
						throw new TypeError("Cannot specify an accessor and a value");
					}
				}

				// can't switch off these features in ECMAScript 3
				// so throw a TypeError if any are false
				if (!(descriptor.writable && descriptor.enumerable && descriptor.configurable))
				{
					throw new TypeError(
						"This implementation of Object.defineProperty does not support" +
						" false for configurable, enumerable, or writable."
					);
				}

				if (descriptor.get) {
					defineGetter.call(obj, prop, descriptor.get);
				}
				if (descriptor.set) {
					defineSetter.call(obj, prop, descriptor.set);
				}

				return obj;
			};
		}

		if (!Object.getOwnPropertyDescriptor) {
			Object.getOwnPropertyDescriptor = function (obj, prop) {
				if (arguments.length < 2) { // all arguments required
					throw new TypeError("Arguments not optional.");
				}

				prop += ""; // convert prop to string

				var descriptor = {
					configurable: True,
					enumerable  : True,
					writable    : True
				},
				getter = lookupGetter.call(obj, prop),
				setter = lookupSetter.call(obj, prop);

				if (!hasOwnProp.call(obj, prop)) {
					// property doesn't exist or is inherited
					return descriptor;
				}
				if (!getter && !setter) { // not an accessor so return prop
					descriptor.value = obj[prop];
					return descriptor;
				}

				// there is an accessor, remove descriptor.writable;
				// populate descriptor.get and descriptor.set (IE's behavior)
				delete descriptor.writable;
				descriptor.get = descriptor.set = undefined;

				if (getter) {
					descriptor.get = getter;
				}
				if (setter) {
					descriptor.set = setter;
				}

				return descriptor;
			};
		}

		if (!Object.defineProperties) {
			Object.defineProperties = function (obj, props) {
				for (var prop in props) {
					if (hasOwnProp.call(props, prop)) {
						Object.defineProperty(obj, prop, props[prop]);
					}
				}
			};
		}

	}
}());
<commit_msg>Removed some useless minification stuff.<commit_after>/*
 * Xccessors Standard: Cross-browser ECMAScript 5 accessors
 * http://purl.eligrey.com/github/Xccessors
 *
 * 2010-06-21
 *
 * By Eli Grey, http://eligrey.com
 *
 * A shim that partially implements Object.defineProperty,
 * Object.getOwnPropertyDescriptor, and Object.defineProperties in browsers that have
 * legacy __(define|lookup)[GS]etter__ support.
 *
 * Licensed under the X11/MIT License
 *   See LICENSE.md
*/

/*jslint white: true, onevar: true, undef: true, eqeqeq: true, plusplus: true,
  bitwise: true, regexp: true, strict: true, newcap: true, immed: true, maxlen: 90 */

/*! @source http://purl.eligrey.com/github/Xccessors/blob/master/xccessors-standard.js*/

"use strict";

(function () {
	var ObjectProto = Object.prototype,
	defineGetter = ObjectProto.__defineGetter__,
	defineSetter = ObjectProto.__defineSetter__,
	lookupGetter = ObjectProto.__lookupGetter__,
	lookupSetter = ObjectProto.__lookupSetter__,
	hasOwnProp = ObjectProto.hasOwnProperty;

	if (defineGetter && defineSetter && lookupGetter && lookupSetter) {

		if (!Object.defineProperty) {
			Object.defineProperty = function (obj, prop, descriptor) {
				if (arguments.length < 3) { // all arguments required
					throw new TypeError("Arguments not optional");
				}

				prop += ""; // convert prop to string

				if (hasOwnProp.call(descriptor, "value")) {
					if (!lookupGetter.call(obj, prop) && !lookupSetter.call(obj, prop)) {
						// data property defined and no pre-existing accessors
						obj[prop] = descriptor.value;
					}

					if ((hasOwnProp.call(descriptor, "get") ||
					     hasOwnProp.call(descriptor, "set")))
					{
						// descriptor has a value prop but accessor already exists
						throw new TypeError("Cannot specify an accessor and a value");
					}
				}

				// can't switch off these features in ECMAScript 3
				// so throw a TypeError if any are false
				if (!(descriptor.writable && descriptor.enumerable && descriptor.configurable))
				{
					throw new TypeError(
						"This implementation of Object.defineProperty does not support" +
						" false for configurable, enumerable, or writable."
					);
				}

				if (descriptor.get) {
					defineGetter.call(obj, prop, descriptor.get);
				}
				if (descriptor.set) {
					defineSetter.call(obj, prop, descriptor.set);
				}

				return obj;
			};
		}

		if (!Object.getOwnPropertyDescriptor) {
			Object.getOwnPropertyDescriptor = function (obj, prop) {
				if (arguments.length < 2) { // all arguments required
					throw new TypeError("Arguments not optional.");
				}

				prop += ""; // convert prop to string

				var descriptor = {
					configurable: true,
					enumerable  : true,
					writable    : true
				},
				getter = lookupGetter.call(obj, prop),
				setter = lookupSetter.call(obj, prop);

				if (!hasOwnProp.call(obj, prop)) {
					// property doesn't exist or is inherited
					return descriptor;
				}
				if (!getter && !setter) { // not an accessor so return prop
					descriptor.value = obj[prop];
					return descriptor;
				}

				// there is an accessor, remove descriptor.writable;
				// populate descriptor.get and descriptor.set (IE's behavior)
				delete descriptor.writable;
				descriptor.get = descriptor.set = undefined;

				if (getter) {
					descriptor.get = getter;
				}
				if (setter) {
					descriptor.set = setter;
				}

				return descriptor;
			};
		}

		if (!Object.defineProperties) {
			Object.defineProperties = function (obj, props) {
				for (var prop in props) {
					if (hasOwnProp.call(props, prop)) {
						Object.defineProperty(obj, prop, props[prop]);
					}
				}
			};
		}

	}
}());
<|endoftext|>