<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name=timeout content=long>
<title>Resource Timing - Check that workerStart is TAO protected</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
</head>
<body>
<script>

const addFrame = url => {
  const iframe = document.createElement("iframe");
  iframe.src = url;
  document.body.appendChild(iframe);
};

const host_info = get_host_info();

// Open window to remote origin with a SW install
let openee;
promise_test(t => {
  return new Promise(resolve => {
    addEventListener("message", e => {
      if (e.data === 'installed') {
        performance.clearResourceTimings();
        resolve();
      }
    });
    openee = window.open(host_info.HTTPS_REMOTE_ORIGIN + "/resource-timing/resources/sw-install.html");
  });
}, "Install a SW")


// Add iframe to remote origin - page without TAO
promise_test(t => {
  return new Promise((resolve, reject) => {
    const observer = new PerformanceObserver(list => {
      const entries = list.getEntries();
      for (entry of entries) {
        if (entry.name.includes("green.html")) {
          observer.disconnect();
          // Observe its performance entry to make sure workerStart is zero
          if (entry.workerStart != 0) {
            reject("workerStart should be zero");
          }
          resolve();
        }
      }
    });
    observer.observe({entryTypes: ["resource"]});
    addFrame(host_info.HTTPS_REMOTE_ORIGIN + "/resource-timing/resources/green.html");
  });
}, "Add TAO-less iframe to remote origin. Make sure workerStart is zero");

// Add iframe to remote origin - page with TAO
promise_test(t => {
  let unregisterPromise = new Promise(resolve => {
    addEventListener("message", e => {
      if (e.data === "unregistered") {
        resolve();
      }
    });
  });
  t.add_cleanup(async () => {
    openee.postMessage("unregister", "*");
    await unregisterPromise;
    // Close the window.
    openee.close();
  });
  return new Promise((resolve, reject) => {
    const observer = new PerformanceObserver(list => {
      const entries = list.getEntries();
      for (entry of entries) {
        if (entry.name.includes("blank-with-tao.html")) {
          // Observe its performance entry to make sure workerStart is zero
          if (entry.workerStart == 0) {
            reject("workerStart should not be zero");
          }
          resolve();
        }
      }
    });
    observer.observe({entryTypes: ["resource"]});
    addFrame(host_info.HTTPS_REMOTE_ORIGIN + "/resource-timing/resources/blank-with-tao.html");
  });
}, "Add TAO iframe to remote origin. Make sure workerStart is not zero");
// Observe its performance entry to make sure workerStart is not zero
</script>
</body>
</html>
