/// <reference types="@fastly/js-compute" />
import { EsiTransformStream } from "@fastly/esi";

addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));

async function handleRequest(event) {
  const req = event.request;

  const headers = new Headers(req.headers);

  const beresp = await fetch(req.url, {
    headers,
    backend: 'origin_0'
  });

  const esiTransformStream = new EsiTransformStream(req.url, headers, {
    fetch(input, init) {
      return fetch(input, { ...init, backend: 'origin_0' });
    }
  });

  return new Response(
    beresp.body.pipeThrough(esiTransformStream),
    {
      status: beresp.status,
      headers: beresp.headers,
    },
  );
}