var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
import cheerio from "cheerio";
import * as eslexer from "es-module-lexer";
import {fileURLToPath} from "url";
import fs from "fs";
import path from "path";
import {renderPage} from "../../runtime/server/index.js";
import {parseNpmName, canonicalURL as getCanonicalURL, codeFrame} from "../util.js";
import {generatePaginateFunction} from "./paginate.js";
import {getParams, validateGetStaticPathsModule, validateGetStaticPathsResult} from "./routing.js";
let browserHash;
const cache = new Map();
async function resolveRenderer(viteServer, renderer) {
  const resolvedRenderer = {};
  const {
    default: {name, client, polyfills, hydrationPolyfills, server}
  } = await import(renderer);
  resolvedRenderer.name = name;
  if (client)
    resolvedRenderer.source = path.posix.join(renderer, client);
  if (Array.isArray(hydrationPolyfills))
    resolvedRenderer.hydrationPolyfills = hydrationPolyfills.map((src) => path.posix.join(renderer, src));
  if (Array.isArray(polyfills))
    resolvedRenderer.polyfills = polyfills.map((src) => path.posix.join(renderer, src));
  const {url} = await viteServer.moduleGraph.ensureEntryFromUrl(path.posix.join(renderer, server));
  const {default: rendererSSR} = await viteServer.ssrLoadModule(url);
  resolvedRenderer.ssr = rendererSSR;
  const completedRenderer = resolvedRenderer;
  return completedRenderer;
}
async function resolveRenderers(viteServer, ids) {
  const renderers = await Promise.all(ids.map((renderer) => {
    if (cache.has(renderer))
      return cache.get(renderer);
    let promise = resolveRenderer(viteServer, renderer);
    cache.set(renderer, promise);
    return promise;
  }));
  return renderers;
}
async function ssr({astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer}) {
  var _a;
  try {
    const renderers = await resolveRenderers(viteServer, astroConfig.renderers);
    const mod = await viteServer.ssrLoadModule(fileURLToPath(filePath));
    let params = {};
    let pageProps = {};
    if (route && !route.pathname) {
      if (route.params.length) {
        const paramsMatch = route.pattern.exec(pathname);
        if (paramsMatch) {
          params = getParams(route.params)(paramsMatch);
        }
      }
      validateGetStaticPathsModule(mod);
      routeCache[route.component] = routeCache[route.component] || (await mod.getStaticPaths({
        paginate: generatePaginateFunction(route),
        rss: () => {
        }
      })).flat();
      validateGetStaticPathsResult(routeCache[route.component], logging);
      const routePathParams = routeCache[route.component];
      const matchedStaticPath = routePathParams.find(({params: _params}) => JSON.stringify(_params) === JSON.stringify(params));
      if (!matchedStaticPath) {
        throw new Error(`[getStaticPaths] route pattern matched, but no matching static path found. (${pathname})`);
      }
      pageProps = __spreadValues({}, matchedStaticPath.props) || {};
    }
    if (!browserHash && ((_a = viteServer._optimizeDepsMetadata) == null ? void 0 : _a.browserHash))
      browserHash = viteServer._optimizeDepsMetadata.browserHash;
    const fullURL = new URL(pathname, origin);
    const Component = await mod.default;
    const ext = path.posix.extname(filePath.pathname);
    if (!Component)
      throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);
    if (!Component.isAstroComponentFactory)
      throw new Error(`Unable to SSR non-Astro component (${route == null ? void 0 : route.component})`);
    const result = {
      styles: new Set(),
      scripts: new Set(),
      createAstro(astroGlobal, props, slots) {
        const site = new URL(origin);
        const url = new URL("." + pathname, site);
        const canonicalURL = getCanonicalURL("." + pathname, astroConfig.buildOptions.site || origin);
        return {
          __proto__: astroGlobal,
          props,
          request: {
            canonicalURL,
            params: {},
            url
          },
          slots: Object.fromEntries(Object.entries(slots || {}).map(([slotName]) => [slotName, true]))
        };
      },
      _metadata: {renderers}
    };
    let html = await renderPage(result, Component, pageProps, null);
    if (mode === "development") {
      html = injectAstroHMR(html);
      html = injectViteClient(html);
      html = resolveNpmImports(html);
    }
    return html;
  } catch (e) {
    viteServer.ssrFixStacktrace(e);
    if (e.errors) {
      const {location, pluginName, text} = e.errors[0];
      const err = new Error(text);
      if (location)
        err.loc = {file: location.file, line: location.line, column: location.column};
      const frame = codeFrame(await fs.promises.readFile(filePath, "utf8"), err.loc);
      err.frame = frame;
      err.id = location == null ? void 0 : location.file;
      err.message = `${location == null ? void 0 : location.file}: ${text}

${frame}
`;
      err.stack = e.stack;
      if (pluginName)
        err.plugin = pluginName;
      throw err;
    }
    throw e;
  }
}
function injectViteClient(html) {
  return html.replace("<head>", `<head><script type="module" src="/@vite/client"></script>`);
}
function injectAstroHMR(html) {
  return html.replace("<head>", `<head><script type="module" src="/@astro/runtime/client/hmr"></script>`);
}
function resolveViteNpmPackage(spec) {
  const pkg = parseNpmName(spec);
  if (!pkg)
    return spec;
  let viteURL = "/node_modules/.vite/";
  viteURL += `${pkg.name}${pkg.subpath ? pkg.subpath.substr(1) : ""}`.replace(/[\/\.]/g, "_");
  viteURL += ".js";
  if (browserHash)
    viteURL += `?v=${browserHash}`;
  return viteURL;
}
function resolveNpmImports(html) {
  const $ = cheerio.load(html);
  const moduleScripts = $('script[type="module"]');
  if (!moduleScripts.length)
    return html;
  moduleScripts.each((_, el) => {
    let code = $(el).html() || "";
    if (!code || $(el).attr("src"))
      return;
    try {
      const scan = () => eslexer.parse(code)[0].filter(({n}) => n && parseNpmName(n));
      let specs = scan();
      while (specs.length) {
        const next = specs[0];
        let pkgName = resolveViteNpmPackage(next.n);
        if (next.d !== -1)
          pkgName = JSON.stringify(pkgName);
        code = code.substring(0, next.s) + pkgName + code.substring(next.e);
        specs = scan();
      }
      $(el).html(code);
    } catch (err) {
    }
  });
  return $.html();
}
export {
  ssr
};
//# sourceMappingURL=data:application/json;base64, 
