<|start_filename|>setupTests.js<|end_filename|>
import '@testing-library/jest-dom';

jest.mock('next/head', () => {
  const ReactDOMServer = require('react-dom/server');
  return {
    __esModule: true,
    default: ({ children }) => {
      if (children) {
        global.document.head.insertAdjacentHTML('afterbegin', ReactDOMServer.renderToString(children) || '');
      }
      return null;
    },
  };
});


<|start_filename|>tailwind.config.js<|end_filename|>
module.exports = {
  mode: 'jit',
  purge: ['design-system/**/*.{js,ts,jsx,tsx}', 'pages/**/*.{js,ts,jsx,tsx}', 'components/**/*.{js,ts,jsx,tsx}'],
  darkMode: false,
  theme: {
    extend: {
      animation: {
        'spin-slow': 'spin 12s linear infinite',
      },
      colors: {
        primary: {
          50: '#f7e4f0',
          100: '#ecbcda',
          200: '#e391c1',
          300: '#db67a8',
          400: '#d74894',
          500: '#d52a80',
          600: '#c4297a',
          700: '#ad2872',
          800: '#97266a',
          900: '#72205c',
        },
        secondary: {
          50: '#e2f8eb',
          100: '#baeecd',
          200: '#89e2ad',
          300: '#48d78b',
          400: '#00cd70',
          500: '#00c259',
          600: '#00b24e',
          700: '#009f42',
          800: '#008e36',
          900: '#006d21',
        },
      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [],
};


<|start_filename|>public/sw.js<|end_filename|>
/* eslint-disable no-console */
/*
 Copyright 2016 Google Inc. All Rights Reserved.
 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.
 */

// Names of the two caches used in this version of the service worker.
// Change to v2, etc. when you update any of the local resources, which will
// in turn trigger the install event again.
importScripts('https://cdn.jsdelivr.net/npm/crypto-js@4.0.0/crypto-js.min.js');
importScripts('https://cdn.jsdelivr.net/npm/idb-keyval@5/dist/iife/index-min.js');

const PRECACHE = 'precache';
const RUNTIME = 'runtime';

// A list of local resources we always want to be cached.
const PRECACHE_URLS = ['/'];

const store = idbKeyval.createStore('GraphQL-Cache', 'PostResponses');

// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
  event.waitUntil(
    caches
      .open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting()),
  );
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches
      .keys()
      .then(cacheNames => {
        return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
      })
      .then(cachesToDelete => {
        return Promise.all(
          cachesToDelete.map(cacheToDelete => {
            return caches.delete(cacheToDelete);
          }),
        );
      })
      .then(() => self.clients.claim()),
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    // intercept post request as this is not available on cache api
    if (event.request.method === 'POST') {
      return event.respondWith(staleWhileRevalidate(event));
    }

    event.respondWith(
      caches.match(event.request).then(cachedResponse => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then(cache => {
          return fetch(event.request).then(response => {
            // Put a copy of the response in the runtime cache.
            return cache.put(event.request, response.clone()).then(() => {
              return response;
            });
          });
        });
      }),
    );
  }
});

async function staleWhileRevalidate(event) {
  let cachedResponse = await getCache(event.request.clone());
  let fetchPromise = fetch(event.request.clone())
    .then(response => {
      setCache(event.request.clone(), response.clone());
      return response;
    })
    .catch(err => {
      console.error(err);
    });
  return cachedResponse ? Promise.resolve(cachedResponse) : fetchPromise;
}

async function serializeResponse(response) {
  let serializedHeaders = {};
  for (var entry of response.headers.entries()) {
    serializedHeaders[entry[0]] = entry[1];
  }
  let serialized = {
    headers: serializedHeaders,
    status: response.status,
    statusText: response.statusText,
  };
  serialized.body = await response.json();
  return serialized;
}

async function setCache(request, response) {
  let body = await request.json();
  let id = CryptoJS.MD5(body.query).toString();

  var entry = {
    query: body.query,
    response: await serializeResponse(response),
    timestamp: Date.now(),
  };
  idbKeyval.set(id, entry, store);
}

async function getCache(request) {
  let data;
  try {
    let body = await request.json();
    let id = CryptoJS.MD5(body.query).toString();
    data = await idbKeyval.get(id, store);
    if (!data) return null;

    // Check cache max age.
    let cacheControl = request.headers.get('Cache-Control');
    let maxAge = cacheControl ? parseInt(cacheControl.split('=')[1]) : 3600;
    if (Date.now() - data.timestamp > maxAge * 1000) {
      console.log(`Cache expired. Load from API endpoint.`);
      return null;
    }

    console.log(`Load response from cache.`);
    return new Response(JSON.stringify(data.response.body), data.response);
  } catch (err) {
    return null;
  }
}


<|start_filename|>.eslintrc.json<|end_filename|>
{
  "extends": ["next/core-web-vitals", "prettier"],
  "rules": {
    "import/no-anonymous-default-export": 0
  }
}


<|start_filename|>jest.config.js<|end_filename|>
module.exports = {
  testEnvironment: 'jsdom',
  moduleNameMapper: {
    '^components(.*)$': '<rootDir>/components/$1',
    '^design-system(.*)$': '<rootDir>/design-system$1',
    '^apollo(.*)$': '<rootDir>/apollo$1',
    '^operations(.*)$': '<rootDir>/operations$1',
    '^types(.*)$': '<rootDir>/types$1',
    '^pages(.*)$': '<rootDir>/pages$1',
    '^utils(.*)$': '<rootDir>/utils$1',
    '^langs(.*)$': '<rootDir>/langs$1',
    '^hooks(.*)$': '<rootDir>/hooks$1',
    '^package.json$': '<rootDir>/package.json',
    '^.+\\.(css|less|scss)$': 'postcss',
  },
  testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(test).[tj]s?(x)'],
  globals: {
    'ts-jest': {
      astTransformers: {
        before: ['@formatjs/ts-transformer'],
      },
    },
  },
  collectCoverageFrom: ['hooks/**/*.(ts|tsx)', 'components/**/*.(ts|tsx)', 'design-system/**/*.(ts|tsx)'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
  setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
};


<|start_filename|>scripts/exec.js<|end_filename|>
const { spawn, exec } = require('child_process');
const os = require('os');

module.exports = (command, { capture = false, echo = false } = {}) => {
  if (echo) {
    console.log(command);
  }

  const childProcess =
    os.platform() === 'win32' ? exec(command) : spawn('bash', ['-c', command], { stdio: capture ? 'pipe' : 'inherit' });

  return new Promise((resolve, reject) => {
    let stdout = '';

    if (capture) {
      childProcess.stdout.on('data', data => {
        stdout += data;
      });
    }

    childProcess.on('error', error => reject(new Error({ code: 1, error })));

    childProcess.on('close', code =>
      code > 0
        ? reject(new Error({ code, error: `Command failed with code ${code}` }))
        : resolve({ code, data: stdout }),
    );
  });
};
