"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.clearValidationCache = clearValidationCache;
exports.validatePageComponent = validatePageComponent;

var _path = _interopRequireDefault(require("path"));

var _fsExtra = _interopRequireDefault(require("fs-extra"));

var _gatsbyCoreUtils = require("gatsby-core-utils");

const validationCache = new Set();
const isNotTestEnv = process.env.NODE_ENV !== `test`;
const isProductionEnv = process.env.NODE_ENV === `production`;

function validatePageComponent(page, directory, pluginName) {
  const {
    component
  } = page;

  if (!component) {
    throw new Error(`11322`);
  }

  const cleanComponentPath = (0, _gatsbyCoreUtils.getPathToLayoutComponent)(component);

  if (validationCache.has(cleanComponentPath)) {
    return {};
  }

  if (!_path.default.isAbsolute(cleanComponentPath)) {
    return {
      error: {
        id: `11326`,
        context: {
          pluginName,
          pageObject: page,
          component: cleanComponentPath
        }
      },
      message: `${pluginName} must set the absolute path to the page component when create creating a page`
    };
  }

  if (isNotTestEnv) {
    if (!_fsExtra.default.existsSync(cleanComponentPath)) {
      return {
        error: {
          id: `11325`,
          context: {
            pluginName,
            pageObject: page,
            component: cleanComponentPath
          }
        }
      };
    }
  } // Validate that the page component imports React and exports something
  // (hopefully a component).
  //


  if (!cleanComponentPath.includes(`/.cache/`) && isProductionEnv) {
    const fileContent = _fsExtra.default.readFileSync(cleanComponentPath, `utf-8`);

    if (fileContent === ``) {
      const relativePath = _path.default.relative(directory, cleanComponentPath);

      return {
        error: {
          id: `11327`,
          context: {
            relativePath
          }
        },
        panicOnBuild: true
      };
    } // this check only applies to js and ts, not mdx


    if ([`.js`, `.jsx`, `.ts`, `.tsx`].includes(_path.default.extname(cleanComponentPath))) {
      const includesDefaultExport = fileContent.includes(`export default`) || fileContent.includes(`module.exports`) || fileContent.includes(`exports.default`) || fileContent.includes(`exports["default"]`) || fileContent.match(/export \{.* as default.*\}/s) || fileContent.match(/export \{\s*default\s*\}/s);

      if (!includesDefaultExport) {
        return {
          error: {
            id: `11328`,
            context: {
              fileName: cleanComponentPath
            }
          },
          panicOnBuild: true
        };
      }
    }
  }

  validationCache.add(cleanComponentPath);
  return {};
}

function clearValidationCache() {
  validationCache.clear();
}
//# sourceMappingURL=validate-page-component.js.map