fix(studio): a service worker a project left behind is gone before a preview frame loads (#8067)

* fix(studio): a service worker a project left behind is gone before a preview frame loads

* fix(cli): the player page's inlined script list is escaped for a script tag
This commit is contained in:
Miguel Ángel
2026-11-17 11:05:40 +00:00
committed by GitHub
parent 3599623f92
commit 7a0bec6828
7 changed files with 94 additions and 18 deletions
+2 -1
View File
@@ -38,6 +38,7 @@ import {
listenOnFreePort,
refuseUnknownHosts,
sandboxForAnotherSite,
scriptsAfterWorkersDropped,
refuseProxyWorkForAnotherSite,
injectRuntime,
injectMediaCodecMap,
@@ -342,7 +343,7 @@ function buildPlayerPage(projectName: string): string {
<hyperframes-player src="/composition/index.html" controls muted></hyperframes-player>
</div>
<div class="info">${projectName} — hyperframes play</div>
<script src="/player.js"></script>
${scriptsAfterWorkersDropped(["/player.js"])}
</body>
</html>`;
}
+2 -2
View File
@@ -30,6 +30,7 @@ import {
refuseUnknownHosts,
refuseFramingByOtherSites,
sandboxForAnotherSite,
scriptsAfterWorkersDropped,
assetContentType,
} from "../utils/compositionServer.js";
import { isPrivateCompositionFile } from "../utils/privateProjectFile.js";
@@ -219,8 +220,7 @@ function buildPresentPage(projectName: string, islandJson: string): string {
hyperframes-slideshow { display: block; position: relative; width: 100vw; height: 100vh; }
hyperframes-player { position: absolute; inset: 0; }
</style>
<script src="/player.js"></script>
<script src="/slideshow.js"></script>
${scriptsAfterWorkersDropped(["/player.js", "/slideshow.js"])}
</head>
<body>
<hyperframes-slideshow tabindex="0" sound>
@@ -3,7 +3,11 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { hostname, networkInterfaces, tmpdir } from "node:os";
import { join } from "node:path";
import { Hono } from "hono";
import { buildRangeResponse, refuseUnknownHosts } from "./compositionServer.js";
import {
buildRangeResponse,
refuseUnknownHosts,
scriptsAfterWorkersDropped,
} from "./compositionServer.js";
const TAGGED_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGNJQ1ABAQABlXPCVgAAAAxJREFUeJxj0NfXBwABHgCOTp25kgAAAABJRU5ErkJggg==",
@@ -89,3 +93,25 @@ describe("refuseUnknownHosts", () => {
expect(await res.text()).toBe("project file");
});
});
describe("scriptsAfterWorkersDropped", () => {
it("adds the page's scripts in order only after every worker on the origin is unregistered", async () => {
const steps: string[] = [];
const registrations = [{ unregister: async () => void steps.push("unregister") }];
const navigator = { serviceWorker: { getRegistrations: async () => registrations } };
const head = { append: (s: { src: string }) => void steps.push(`load ${s.src}`) };
const document = { head, createElement: () => ({ src: "", async: true }) };
const html = scriptsAfterWorkersDropped(["/player.js", "/slideshow.js"]);
const script = html.slice("<script>".length, -"</script>".length);
await new Function("navigator", "document", `return ${script.replace(/;$/, "")}`)(
navigator,
document,
);
expect(steps).toEqual(["unregister", "load /player.js", "load /slideshow.js"]);
});
it("keeps a source that holds a closing tag inside its one script", () => {
const html = scriptsAfterWorkersDropped(["/a</script><b>.js"]);
expect(html.indexOf("</script>")).toBe(html.length - "</script>".length);
});
});
+15 -1
View File
@@ -9,7 +9,10 @@ import { fileURLToPath } from "node:url";
import { getMimeType, openRangeEnd } from "@hyperframes/studio-server";
import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
import { PREVIEW_FOR_ANOTHER_SITE_META } from "@hyperframes/core/studio-preview-mark";
import {
PREVIEW_FOR_ANOTHER_SITE_META,
dropServiceWorkers,
} from "@hyperframes/core/studio-preview-mark";
import {
PREVIEW_ALLOWED_HOSTS_ENV,
previewAllowedHostsFromEnv,
@@ -299,3 +302,14 @@ export async function listenOnFreePort(server: PortBindable, startPort: number):
}
throw new Error(`No free port found in [${startPort}, ${startPort + 9}]`);
}
export function scriptsAfterWorkersDropped(srcs: readonly string[]): string {
const add =
'var s=document.createElement("script");s.src=src;s.async=false;document.head.append(s)';
const list = JSON.stringify(srcs).replace(
/[<>/\u2028\u2029]/g,
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,
);
const load = `function(){${list}.forEach(function(src){${add}})}`;
return `<script>(${dropServiceWorkers.toString()})().then(${load});</script>`;
}
+22 -2
View File
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { refusedPreviewMessage, refusedPreviewStatus } from "./studioPreviewMark";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
dropServiceWorkers,
refusedPreviewMessage,
refusedPreviewStatus,
} from "./studioPreviewMark";
describe("refusedPreviewStatus", () => {
it.each([404, 410, 500])("reads %i back out of the refused page's message", (status) => {
@@ -14,3 +18,19 @@ describe("refusedPreviewStatus", () => {
expect(refusedPreviewStatus(cause)).toBeNull();
});
});
describe("dropServiceWorkers", () => {
const stub = (workers: unknown) => vi.stubGlobal("navigator", { serviceWorker: workers });
afterEach(() => vi.unstubAllGlobals());
it("unregisters every worker on the origin, and resolves when there is none or the browser refuses", async () => {
const all = [{ unregister: vi.fn(async () => true) }, { unregister: vi.fn(async () => true) }];
stub({ getRegistrations: async () => all });
await dropServiceWorkers();
for (const each of all) expect(each.unregister).toHaveBeenCalledOnce();
stub(undefined);
await expect(dropServiceWorkers()).resolves.toBeUndefined();
stub({ getRegistrations: async () => Promise.reject(new Error("SecurityError")) });
await expect(dropServiceWorkers()).resolves.toBeUndefined();
});
});
+12
View File
@@ -88,3 +88,15 @@ export function applyAuthoredTiming(
for (const [name, value] of attrs) el.setAttribute(name, value);
el.removeAttribute(RUNTIME_STAMPED_ATTR);
}
export function dropServiceWorkers(): Promise<void> {
const workers = typeof navigator === "undefined" ? undefined : navigator.serviceWorker;
if (!workers) return Promise.resolve();
return workers
.getRegistrations()
.then((all) => Promise.all(all.map((each) => each.unregister())))
.then(
() => undefined,
() => undefined,
);
}
+14 -11
View File
@@ -13,6 +13,7 @@ import {
} from "./utils/rejectionTelemetry";
import { prefetchPreviewForHash } from "./utils/previewPrefetch";
import { bindThumbnailPageLifecycle } from "./player/lib/thumbnailPageLifecycle";
import { dropServiceWorkers } from "@hyperframes/core/studio-preview-mark";
import "./styles/studio.css";
const unbindThumbnailPageLifecycle = bindThumbnailPageLifecycle(window, document);
@@ -110,16 +111,18 @@ window.addEventListener("unhandledrejection", (event) => {
trackStudioEvent("unhandled_promise_rejection", props);
});
createRoot(document.getElementById("root")!).render(
<StrictMode>
{/* One icon size and weight for the whole app, taken from the theme file.
void dropServiceWorkers().then(() =>
createRoot(document.getElementById("root")!).render(
<StrictMode>
{/* One icon size and weight for the whole app, taken from the theme file.
Icons that pass their own size or weight still win. */}
<IconContext.Provider value={readIconTokens()}>
<StudioErrorBoundary>
<ShowThemeToggle.Provider value>
<StudioApp />
</ShowThemeToggle.Provider>
</StudioErrorBoundary>
</IconContext.Provider>
</StrictMode>,
<IconContext.Provider value={readIconTokens()}>
<StudioErrorBoundary>
<ShowThemeToggle.Provider value>
<StudioApp />
</ShowThemeToggle.Provider>
</StudioErrorBoundary>
</IconContext.Provider>
</StrictMode>,
),
);