/// <reference types="@fastly/js-compute" />

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

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

  // This example supports gzip compression only
  const useGzip =
    request.headers.get("accept-encoding")?.includes("gzip") ?? false;

  // Make a backend request that sets accept-encoding to gzip appropriately
  const bereq = new Request(request);
  bereq.headers.delete("accept-encoding");
  if (useGzip) {
    bereq.headers.set("accept-encoding", "gzip");
  }

  // Perform the backend request
  const beresp = await fetch(bereq, {
    backend: "origin_0"
  });

  // Decompress the gzipped body
  let originalBody;
  if (beresp.headers.get("content-encoding") === "gzip") {
    const decompressionStream = new DecompressionStream("gzip");
    const decompressedResponse = new Response(
      beresp.body.pipeThrough(decompressionStream)
    );
    originalBody = await decompressedResponse.text();
  } else {
    originalBody = await beresp.text();
  }

  // Now it is a string, work on the response body and
  // modify it at will
  const transformedBody = originalBody.replaceAll(
    '<h1 id="httpme">HTTP me!</h1>',
    '<h1 id="httpme">HTTP me (modified)!</h1>'
  );

  // Create a response with the new body
  const response = new Response(transformedBody, {
    status: beresp.status,
    headers: beresp.headers
  });

  // Don't include content-encoding header for this response.
  // The "x-compress-hint" header tells Fastly to compress your
  // modified response if the request includes the accept-encoding
  // header, so you do not need to spend C@E CPU for this
  response.headers.delete("content-encoding");
  if (useGzip) {
    // Note that the response from Fastly you'll see in Fiddle
    // won't actually show this header, and instead you'll see
    // the content-encoding header added back by Fastly.
    response.headers.set("x-compress-hint", "gzip");
  }

  return response;
}