"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createSsrMiddleware = createSsrMiddleware;
function _reactRendering() {
  const data = require("@teambit/react.rendering.ssr");
  _reactRendering = function () {
    return data;
  };
  return data;
}
function _path() {
  const data = _interopRequireDefault(require("path"));
  _path = function () {
    return data;
  };
  return data;
}
function fs() {
  const data = _interopRequireWildcard(require("fs-extra"));
  fs = function () {
    return data;
  };
  return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const denyList = /^\/favicon.ico$/;
async function createSsrMiddleware({
  root,
  port,
  title,
  logger
}) {
  const runtime = await loadRuntime(root, {
    logger
  });
  if (!runtime) return undefined;
  const {
    render
  } = runtime;
  const assets = _objectSpread(_objectSpread({}, runtime.assets), {}, {
    title
  });
  return async function serverRenderMiddleware(request, response, next) {
    const {
      query,
      url
    } = request;
    const browser = (0, _reactRendering().browserFromExpress)(request, port);
    if (denyList.test(url)) {
      logger.debug(`[ssr] skipping static denyList file ${url}`);
      next();
      return;
    }
    if (query.rendering === 'client') {
      logger.debug(`[ssr] skipping ${url}`);
      next();
      return;
    }
    logger.debug(`[ssr] ${request.method} ${url}`);
    const props = {
      assets,
      browser,
      request,
      response
    };
    try {
      const rendered = await render(props);
      response.set('Cache-Control', 'no-cache');
      response.send(rendered);
      logger.debug(`[ssr] success '${url}'`);
    } catch (e) {
      logger.error(`[ssr] failed at '${url}'`, e);
      next();
    }
  };
}
async function loadRuntime(root, {
  logger
}) {
  let render;
  let assets;
  try {
    const entryFilepath = _path().default.join(root, 'ssr', 'index.js');
    if (!fs().existsSync(entryFilepath)) {
      logger.warn(`[ssr] - Skipping setup - failed finding ssr bundle at "${entryFilepath}"`);
      return undefined;
    }
    const manifestFilepath = _path().default.join(root, 'asset-manifest.json');
    if (!fs().existsSync(manifestFilepath)) {
      logger.warn('[ssr] - Skipping setup (cannot find asset manifest file)');
      return undefined;
    }
    assets = await parseManifest(manifestFilepath);
    if (!assets) {
      logger.warn('[ssr] - Skipping setup (failed parsing assets manifest)');
      return undefined;
    }
    const imported = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(entryFilepath);
    render = imported?.default || imported?.render;
    if (!render || typeof render !== 'function') {
      logger.warn('[ssr] - index file does not export a render() function. Skipping setup.');
      return undefined;
    }
  } catch (e) {
    logger.error(e);
    return undefined;
  }
  return {
    render,
    assets
  };
}
async function parseManifest(filepath, logger) {
  try {
    const file = await fs().readFile(filepath);
    logger?.debug('[ssr] - ✓ aread manifest file');
    const contents = file.toString();
    const parsed = JSON.parse(contents);
    logger?.debug('[ssr] - ✓ prased manifest file', parsed);
    const assets = getAssets(parsed);
    logger?.debug('[ssr] - ✓ extracted data from manifest file', assets);
    return assets;
  } catch (e) {
    logger?.error('[ssr] - error parsing asset manifest', e);
    process.exit();
    return undefined;
  }
}
function getAssets(manifest) {
  const assets = {
    css: [],
    js: []
  };
  assets.css = manifest.entrypoints?.filter(x => x.endsWith('css')).map(x => _path().default.join('/', x));
  assets.js = manifest.entrypoints?.filter(x => x.endsWith('js')).map(x => _path().default.join('/', x));
  return assets;
}

//# sourceMappingURL=ssr-middleware.js.map