import { renderComponent, renderTemplate } from "../../runtime/server/index.js";
import { createSlotValueFromString } from "../../runtime/server/render/slot.js";
const SERVER_ISLAND_ROUTE = "/_server-islands/[name]";
const SERVER_ISLAND_COMPONENT = "_server-islands.astro";
function ensureServerIslandRoute(manifest) {
  if (manifest.routes.some((route2) => route2.route === "/_server-islands/[name]")) {
    return;
  }
  const route = {
    type: "page",
    component: SERVER_ISLAND_COMPONENT,
    generate: () => "",
    params: ["name"],
    segments: [
      [{ content: "_server-islands", dynamic: false, spread: false }],
      [{ content: "name", dynamic: true, spread: false }]
    ],
    // eslint-disable-next-line
    pattern: /^\/_server-islands\/([^/]+?)$/,
    prerender: false,
    isIndex: false,
    fallbackRoutes: [],
    route: SERVER_ISLAND_ROUTE
  };
  manifest.routes.push(route);
}
function createEndpoint(manifest) {
  const page = async (result) => {
    const params = result.params;
    const request = result.request;
    const raw = await request.text();
    const data = JSON.parse(raw);
    if (!params.name) {
      return new Response(null, {
        status: 400,
        statusText: "Bad request"
      });
    }
    const componentId = params.name;
    const imp = manifest.serverIslandMap?.get(componentId);
    if (!imp) {
      return new Response(null, {
        status: 404,
        statusText: "Not found"
      });
    }
    const props = data.props;
    const componentModule = await imp();
    const Component = componentModule[data.componentExport];
    const slots = {};
    for (const prop in data.slots) {
      slots[prop] = createSlotValueFromString(data.slots[prop]);
    }
    return renderTemplate`${renderComponent(result, "Component", Component, props, slots)}`;
  };
  page.isAstroComponentFactory = true;
  const instance = {
    default: page,
    partial: true
  };
  return instance;
}
export {
  SERVER_ISLAND_COMPONENT,
  SERVER_ISLAND_ROUTE,
  createEndpoint,
  ensureServerIslandRoute
};
