Public: anyone can read this; the crew can change it.

/tab starts in Safari and Chrome: the worker sees its host page, and the page waits for activation #17998

opened this

Merged 15h 50m ago, live in production

sold/tab-start → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/tab-start was merged into main as 7e39794.

Review

Sign in to review this change.
4 files changed +69 −6
src/tab/active.ts added +24
@@ -0,0 +1,24 @@
1 /** The registration's worker, once it is active: the point the frame may load a page it serves. */
2 export interface Worker1 {

Worker1 is a vague name. Prefer ActivatingWorker or similar.

3 state: string;
4 addEventListener(type: "statechange", listener: () => void): void;
5 }
6 export interface Registration {
7 readonly installing: Worker1 | null;
8 readonly waiting: Worker1 | null;
9 readonly active: Worker1 | null;
10 }
11
12 export function activated(registration: Registration): Promise<void> {
13 const worker = registration.installing ?? registration.waiting ?? registration.active;
14 if (worker === null) return Promise.reject(new Error("no worker registered"));
15 return new Promise((resolve, reject) => {
16 const check = (): boolean => {
17 if (worker.state === "activated") resolve();
18 else if (worker.state === "redundant") reject(new Error("worker redundant"));
19 else return false;
20 return true;
21 };

Remove the listener once the promise has settled. Also add a test for the redundant rejection and for intermediate states, which are not covered.

22 if (!check()) worker.addEventListener("statechange", check);
23 });
24 }
src/tab/boot.ts +5 −4
@@ -3,6 +3,7 @@
33 * forge in a frame. The page is the host: its requests from the worker are relayed from the
44 * service worker, so closing the tab stops the forge.
55 */
6 import { activated, type Registration } from "./active.ts";
67 import type { TabRequest } from "./forge.ts";
78
89 // The few browser globals this file touches, named here rather than pulling in the DOM library.
@@ -17,8 +18,7 @@ interface Box {
1718 interface Registrations {
1819 addEventListener(type: "message", listener: (e: MessageEvent<{ forge?: TabRequest }>) => void): void;
1920 startMessages(): void;
20 register(script: string, options: { scope: string }): Promise<unknown>;
21 readonly ready: Promise<unknown>;
21 register(script: string, options: { scope: string }): Promise<Registration>;
2222 }
2323 declare const document: { getElementById(id: string): Box | null; readonly documentElement: { readonly dataset: Record<string, string> } };
2424 declare const navigator: { readonly serviceWorker?: Registrations; readonly storage?: { getDirectory?: unknown } };
@@ -63,8 +63,9 @@ async function start(button: Box): Promise<void> {
6363 }
6464 holder = worker;
6565 try {
66 await workers.register(button.dataset.sw!, { scope: "/tab/f/" });
67 await workers.ready;
66 // Not `workers.ready`: it waits for a worker whose scope covers this page (/tab), and the scope
67 // is /tab/f/, so it never settles.
68 await activated(await workers.register(button.dataset.sw!, { scope: "/tab/f/" }));
6869 } catch (error) {
6970 console.warn("tab forge: service worker", error);
7071 holder = null;
src/tab/sw.ts +4 −2
@@ -11,7 +11,7 @@ interface Client {
1111 }
1212 interface Scope {
1313 readonly location: { readonly origin: string };
14 readonly clients: { matchAll(options: { type: "window" }): Promise<Client[]>; claim(): Promise<void> };
14 readonly clients: { matchAll(options: { type: "window"; includeUncontrolled: boolean }): Promise<Client[]>; claim(): Promise<void> };
1515 skipWaiting(): Promise<void>;
1616 addEventListener(type: "install", listener: () => void): void;
1717 addEventListener(type: "activate", listener: (e: { waitUntil(p: Promise<unknown>): void }) => void): void;
@@ -64,7 +64,9 @@ async function answer(request: Request): Promise<Response> {
6464 if (text === null) return reply({ status: 413, html: "Too large." });
6565 form = Object.fromEntries(new URLSearchParams(text));
6666 }
67 const hosts = (await sw.clients.matchAll({ type: "window" })).filter((c) => new URL(c.url).pathname === "/tab");
67 // The /tab page lies outside this worker's scope (/tab/f/), so it is never one of the clients the
68 // worker controls: without includeUncontrolled the host is invisible and the forge reads as stopped.
69 const hosts = (await sw.clients.matchAll({ type: "window", includeUncontrolled: true })).filter((c) => new URL(c.url).pathname === "/tab");
6870 if (hosts.length === 0) return stopped();
6971 const path = url.pathname.slice(PREFIX.length) || "/";
7072 // Ask every /tab window: only the one that started the forge answers, so the first reply is the
test/tab-host-visible.test.ts added +36
@@ -0,0 +1,36 @@
1 /** The tab forge's service worker sees the uncontrolled /tab page, and the page's wait ends. */
2 import { expect, test } from "bun:test";
3 import { activated } from "../src/tab/active.ts";
4
5 test("the service worker asks windows it does not control, so the /tab host is found", async () => {
6 let listener: ((e: { request: Request; respondWith(r: Promise<Response>): void }) => void) | undefined;
7 const host = {
8 url: "https://forge.test/tab",
9 postMessage(_m: unknown, [port]: any[]) {
10 port.postMessage({ status: 200, html: "ok" });
11 },
12 };
13 (globalThis as any).self = {
14 location: { origin: "https://forge.test" },
15 clients: { matchAll: async (o: { includeUncontrolled?: boolean }) => (o.includeUncontrolled === true ? [host] : []), claim: async () => {} },
16 skipWaiting: async () => {},
17 addEventListener(type: string, l: any) {
18 if (type === "fetch") listener = l;
19 },
20 };
21 await import("../src/tab/sw.ts");
22 let out: Promise<Response> | undefined;
23 listener!({ request: new Request("https://forge.test/tab/f/"), respondWith: (r) => (out = r) });
24 const res = await out!;
25 expect(res.status).toBe(200);
26 });
27
28 test("activated settles when the worker activates, without a controlled page", async () => {
29 let fire = (): void => {};
30 const worker = { state: "installing", addEventListener: (_t: "statechange", l: () => void) => (fire = l) };
31 const done = activated({ installing: worker, waiting: null, active: null });
32 worker.state = "activated";
33 fire();
34 await done;
35 await expect(activated({ installing: null, waiting: null, active: { state: "activated", addEventListener() {} } })).resolves.toBeUndefined();
36 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs