<!DOCTYPE html>
<meta charset="utf-8"/>
<title>Service Worker: Partitioned Service Workers</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.sub.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<script src="resources/partitioned-utils.js"></script>

<body>
This test loads a SW in a first-party context and gets has the SW send
its list of clients from client.matchAll(). It does the same thing for the
SW in a third-party context as well and confirms that each SW see's the correct
clients and that they don't see eachother's clients.

<script>
promise_test(async t => {

  const script = './resources/partitioned-storage-sw.js'
  const scope = './resources/partitioned-'

  // Add service worker to this 1P context.
  const reg = await service_worker_unregister_and_register(t, script, scope);
  t.add_cleanup(() => reg.unregister());
  await wait_for_state(t, reg.installing, 'activated');

  // Register the message listener.
  self.addEventListener('message', messageEventHandler);

  // Create a third-party iframe that will send us its SW's clients.
  const third_party_iframe_url = new URL(
    './resources/partitioned-service-worker-third-party-iframe-matchAll.html',
    get_host_info().HTTPS_ORIGIN + self.location.pathname);

  const {urls_list: frame_3p_urls_list} = await loadAndReturnSwData(t,
    third_party_iframe_url, 'window');

  // Register a listener on the service worker container and then forward to
  // the self event listener so we can reuse the existing message promise
  // function.
  navigator.serviceWorker.addEventListener('message', evt => {
    self.postMessage(evt.data, '*');
  });

  const frame_1p_data_promise = makeMessagePromise();

  reg.active.postMessage({type: "get-match-all"});

  const {urls_list: frame_1p_urls_list} = await frame_1p_data_promise;

  // If partitioning is working, the 1p and 3p SWs should only see a single
  // client.
  assert_equals(frame_3p_urls_list.length, 1);
  assert_equals(frame_1p_urls_list.length, 1);
  // Confirm that the expected URL was seen by each.
  assert_equals(frame_3p_urls_list[0], third_party_iframe_url.toString(),
    "3p SW has the correct client url.");
  assert_equals(frame_1p_urls_list[0], window.location.href,
    "1P SW has the correct client url.");
}, "ServiceWorker's matchAll() is partitioned");


</script>

</body>