mirror of
https://github.com/expo/explore.git
synced 2026-11-15 17:32:23 -10:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9e0275a3a | ||
|
|
3392f799f6 | ||
|
|
25df16d914 | ||
|
|
068445c82b |
No files matched your search
@@ -21,8 +21,8 @@ Hosted previews are off by default. When `report.preview.hosting: eas` is set, t
|
||||
**What is protected, and how.**
|
||||
|
||||
- *The report bytes.* `ci:deploy` zips the report and encrypts it (AES-256-GCM) before upload. The key is stored only in that deployment's server environment; it never appears in a URL, a log line, or a comment. The files on the CDN are ciphertext.
|
||||
- *Access to the decrypted report.* A server route in the deployment checks the token and the expiry, fetches the ciphertext from its own deployment, decrypts it, and serves the browser the report's metadata first and each screenshot as it is shown (the browser may keep those screenshots in its own cache for up to a week, never past the link's expiry; shared caches never do). Without the exact token every path under the deployment answers `404`, including the Viewer itself; `ci:deploy` verifies this before it publishes the link.
|
||||
- *Expiry.* The expiry (`report.preview.expiresAfter`, 30 days by default, `never` to disable) is sealed into the deployment when it is created and enforced by the route, not by the browser. After it passes, the exact token still opens the Viewer for a browser, but the report routes, the Markdown index, and the agent API answer `410` and the Viewer says the link expired on that date; every other path still answers `404`. To revoke a link earlier, delete the deployment in the EAS Hosting dashboard; the CDN stops serving it within seconds and the route within a few minutes. Deleting it does not reach into a browser that already opened the link: the screenshots that browser fetched stay in its cache until they age out.
|
||||
- *Access to the decrypted report.* A server route in the deployment checks the token and the expiry, fetches the ciphertext from its own deployment, decrypts it, and streams it to the browser. Without the exact token every path under the deployment answers `404`, including the Viewer itself; `ci:deploy` verifies this before it publishes the link.
|
||||
- *Expiry.* The expiry (`report.preview.expiresAfter`, 30 days by default, `never` to disable) is sealed into the deployment when it is created and enforced by the route, not by the browser. After it passes, the exact token still opens the Viewer for a browser, but the report routes, the Markdown index, and the agent API answer `410` and the Viewer says the link expired on that date; every other path still answers `404`. To revoke a link earlier, delete the deployment in the EAS Hosting dashboard; the CDN stops serving it within seconds and the route within a few minutes.
|
||||
- *Deletion.* Nothing is deleted automatically. Each review of a pull request deploys a new preview and the comment links the newest one (recorded in a hidden `<!-- expo-explore-deployments:… -->` line under the comment marker); earlier deployments and the deployments of closed pull requests stay until someone deletes them in the EAS Hosting dashboard or with `eas deploy:delete`, so a link keeps opening for as long as its expiry allows.
|
||||
- *The Viewer itself.* The Viewer's JavaScript is public and the same for every deployment; it holds no report data.
|
||||
- *Agent access.* The same link also answers as Markdown and as a JSON API (`/llms.txt`, `/api/v1/...`, see [the agent guide](../README.md#agents)) so a coding agent can read the report without a download. Those routes are served by the same server route from the same decrypted bytes, behind the same token, expiry, `private, no-store`, and `noindex`; they add no second credential and no new place where the report is stored.
|
||||
|
||||
@@ -7,13 +7,11 @@ import type { ExplorePlatform } from "../config/explore-config.js";
|
||||
import type { RunTarget } from "../types.js";
|
||||
import { reportTarget } from "./saved-runs.js";
|
||||
import { AGENT_API_VERSION, agentApiReply, agentIndexMarkdown, loadReport, prefersHtml, type AgentContext, type LoadedReport } from "./agent-api.js";
|
||||
import { manifestBody, previewAsset } from "./preview-manifest.js";
|
||||
|
||||
/**
|
||||
* Serve review reports on this machine the way a hosted report serves them: the built Viewer at `/p/<token>`, each
|
||||
* target's manifest at `/p/<token>/manifest.json?target=…` (or `?platform=…`) and its assets at
|
||||
* `/p/<token>/assets/<sha256>.<ext>`, the whole ZIP at `/p/<token>/report.zip`, and the list at `/p/<token>/reports.json`.
|
||||
* The Viewer already knows this layout, so nothing in it changes. An agent on this machine gets what it gets from a hosted
|
||||
* target's report at `/p/<token>/report.zip?target=…` (or `?platform=…`), and the list at `/p/<token>/reports.json`. The
|
||||
* Viewer already knows this layout, so nothing in it changes. An agent on this machine gets what it gets from a hosted
|
||||
* link: the Markdown index when it fetches `/p/<token>` without asking for HTML, `/p/<token>/llms.txt`, and the JSON
|
||||
* API at `/p/<token>/api/v1/...` (agent-api.ts, shared with the hosted Worker). Loopback only; anything else answers 404.
|
||||
*/
|
||||
@@ -69,16 +67,6 @@ export async function startLocalReportServer(options: { reports: LocalReport[];
|
||||
return send(reply.status, body, reply.contentType, { vary: "Accept", ...reply.headers });
|
||||
}
|
||||
if (isPage) return send(200, await readFile(resolve(viewerRoot, "index.html")), TYPES[".html"]);
|
||||
// What the Viewer opens (preview-manifest.ts, shared with the hosted Worker): the manifest, then each asset as it is shown.
|
||||
if (url.pathname === `${page}/manifest.json` || url.pathname.startsWith(`${page}/assets/`)) {
|
||||
if (!report) return send(404, "Not found");
|
||||
if (!loaded.has(report)) loaded.set(report, loadReport(report.zip));
|
||||
const content = await loaded.get(report);
|
||||
if (!content) return send(404, "Not found");
|
||||
if (url.pathname === `${page}/manifest.json`) return send(200, manifestBody(content), TYPES[".json"]);
|
||||
const asset = await previewAsset(content, url.pathname.slice(page.length + 1));
|
||||
return asset ? send(200, asset.bytes, asset.type) : send(404, "Not found");
|
||||
}
|
||||
if (url.pathname === `${page}/report.zip`) return report ? send(200, report.zip, "application/zip") : send(404, "Not found");
|
||||
if (url.pathname === `${page}/reports.json` && options.reports.length > 1) return send(200, listing, TYPES[".json"]);
|
||||
// The Viewer's own assets, at the absolute paths its index.html names; never anything outside the build.
|
||||
|
||||
@@ -4,8 +4,7 @@ import { appendFile, cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm,
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, relative, resolve, sep } from "node:path";
|
||||
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter, configure } from "@zip.js/zip.js";
|
||||
import { loadReport, MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { manifestBody } from "./preview-manifest.js";
|
||||
import { MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { publishCiReportComment, readCiReportInput, type CiReportInput } from "./artifact.js";
|
||||
import { readZipDirectory, readZipEntry } from "./zip-reader.js";
|
||||
import { reviewChangeCount, reviewDevice } from "./pr-comment-body.js";
|
||||
@@ -775,19 +774,6 @@ async function verifyDeployment(check: { origin: string; token: string; reports:
|
||||
return deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not serve the exact report that was deployed.",
|
||||
"Rerun the deploy job; the deployment's sealed key or ciphertext did not match.", { details: { status: report.status, report: expected.query } });
|
||||
}
|
||||
// What the Viewer opens: the manifest the deployed ZIP makes, and one of its assets byte for byte.
|
||||
const loaded = await loadReport(bytes);
|
||||
const manifest = await get(`/p/${check.token}/manifest.json${expected.query}`);
|
||||
const body = manifest.status === 200 ? await manifest.text() : "";
|
||||
const asset = loaded ? Object.keys(JSON.parse(manifestBody(loaded)).entries as Record<string, number>)[0] : undefined;
|
||||
const served = asset ? await get(`/p/${check.token}/${asset}${expected.query}`) : undefined;
|
||||
const assetBytes = served?.status === 200 ? new Uint8Array(await served.arrayBuffer()) : new Uint8Array();
|
||||
if (!loaded || body !== manifestBody(loaded)
|
||||
|| (asset && createHash("sha256").update(assetBytes).digest("hex") !== asset.slice("assets/".length, "assets/".length + 64))) {
|
||||
return deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not serve the report's manifest and screenshots, which the Viewer opens.",
|
||||
"Rerun the deploy job; if it keeps failing, inspect the deployment in the EAS Hosting dashboard.",
|
||||
{ details: { status: manifest.status, ...(served ? { assetStatus: served.status } : {}), report: expected.query } });
|
||||
}
|
||||
}
|
||||
if (check.listing !== undefined) {
|
||||
const list = await get(`/p/${check.token}/reports.json`);
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* What a hosted or local report page serves the Viewer instead of the whole ZIP: the manifest (the report's metadata
|
||||
* file verbatim plus every asset's size) and each asset on request. The preview Worker, the local report server and
|
||||
* the deploy check share these, so all three agree byte for byte.
|
||||
*/
|
||||
import type { LoadedReport } from "./agent-api.js";
|
||||
import { readZipEntry } from "./zip-reader.js";
|
||||
|
||||
/** The manifest format the Viewer accepts (viewer/src/utils/artifact-report.ts). */
|
||||
export const PREVIEW_MANIFEST_FORMAT = "explore.preview-manifest/1";
|
||||
/** `assets/<sha256>.<ext>`, the only asset names a report page serves. */
|
||||
export const PREVIEW_ASSET = /^assets\/([a-f0-9]{64})\.(png|jpg|mp4)$/;
|
||||
const ASSET_TYPES: Record<string, string> = { png: "image/png", jpg: "image/jpeg", mp4: "video/mp4" };
|
||||
const MAX_ASSET_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** The metadata file verbatim plus the size of every asset, so the Viewer opens the report before any screenshot. Directory records are not assets. */
|
||||
export function manifestBody(loaded: LoadedReport): string {
|
||||
const entries: Record<string, number> = {};
|
||||
for (const [name, entry] of loaded.entries) if (name.startsWith("assets/") && !name.endsWith("/")) entries[name] = entry.size;
|
||||
return `{"format":"${PREVIEW_MANIFEST_FORMAT}","file":"${loaded.file}","entries":${JSON.stringify(entries)},"report":${new TextDecoder().decode(loaded.raw)}}`;
|
||||
}
|
||||
|
||||
/** One asset of the report, inflated from the decrypted ZIP, with its content type; undefined when the report has no such asset. */
|
||||
export async function previewAsset(loaded: LoadedReport, path: string): Promise<{ bytes: Uint8Array; type: string } | undefined> {
|
||||
const match = PREVIEW_ASSET.exec(path);
|
||||
const entry = match ? loaded.entries.get(path) : undefined;
|
||||
if (!match || !entry) return undefined;
|
||||
const bytes = await readZipEntry(loaded.zip, entry, MAX_ASSET_BYTES);
|
||||
return bytes ? { bytes, type: ASSET_TYPES[match[2]!]! } : undefined;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { BlobReader, BlobWriter, Uint8ArrayReader, ZipReader, ZipWriter, Uint8ArrayWriter } from "@zip.js/zip.js";
|
||||
import { BlobReader, BlobWriter, Uint8ArrayReader, ZipReader, ZipWriter } from "@zip.js/zip.js";
|
||||
import { chromium, expect as playwrightExpect } from "@playwright/test";
|
||||
import { PNG } from "pngjs";
|
||||
import { createBrowserVite } from "../helpers/browser-vite.mjs";
|
||||
@@ -54,18 +54,6 @@ async function archive(report = reportFixture(), extra = [], imageBytes = png) {
|
||||
return Buffer.from(await (await writer.close()).arrayBuffer());
|
||||
}
|
||||
|
||||
/** The report ZIP as the preview Worker reads it: entry bytes by name, and the manifest it answers with. */
|
||||
async function unzipped(bytes) {
|
||||
const reader = new ZipReader(new Uint8ArrayReader(new Uint8Array(bytes)), { useWebWorkers: false });
|
||||
const files = new Map();
|
||||
for (const entry of await reader.getEntries()) files.set(entry.filename, await entry.getData(new Uint8ArrayWriter()));
|
||||
await reader.close();
|
||||
const file = files.has("review.json") ? "review.json" : "exploration.json";
|
||||
const entries = Object.fromEntries([...files].filter(([name]) => name.startsWith("assets/")).map(([name, data]) => [name, data.length]));
|
||||
const manifest = `{"format":"explore.preview-manifest/1","file":"${file}","entries":${JSON.stringify(entries)},"report":${new TextDecoder().decode(files.get(file))}}`;
|
||||
return { files, manifest };
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve `/r` like the hosted Viewer: the page alone, no report endpoint; the ZIP comes from the
|
||||
* reviewer. `reportIdentity: null` opens the bare page without a linked run.
|
||||
@@ -73,30 +61,19 @@ async function unzipped(bytes) {
|
||||
async function harness(t, bytes, { app = false, open = true, name = fileName, reportIdentity = identity,
|
||||
query = "&focus=modified&screen=home&inspect=diff", fault, preview } = {}) {
|
||||
const pagePath = preview ? `/p/${preview.token}` : "/r";
|
||||
// What the preview Worker serves from the decrypted ZIP: the manifest the Viewer opens, and each asset on request.
|
||||
const served = preview && bytes ? await unzipped(bytes) : undefined;
|
||||
const vite = await createBrowserVite(t, { configFile: false,
|
||||
root: fileURLToPath(new URL("../../viewer", import.meta.url)), logLevel: "error", esbuild: { jsx: "automatic" },
|
||||
server: { host: "127.0.0.1", port: 0 }, plugins: [{ name: "report-page-fixture", configureServer(server) {
|
||||
server.middlewares.use((request, response, next) => {
|
||||
const url = new URL(request.url, "http://localhost");
|
||||
// A preview deployment's Worker: the decrypted report behind the token, or the same 404 as any other path.
|
||||
if (preview && url.pathname === `${pagePath}/manifest.json`) {
|
||||
if (preview && url.pathname === `${pagePath}/report.zip`) {
|
||||
preview.requests = (preview.requests ?? 0) + 1;
|
||||
preview.queries = [...(preview.queries ?? []), url.search];
|
||||
if (preview.status && preview.status !== 200) { response.statusCode = preview.status; return response.end(preview.body ?? "Not found"); }
|
||||
response.setHeader("content-type", "application/json");
|
||||
// A slow target (`delays` by query) keeps its manifest in flight while the reviewer moves on.
|
||||
// `padding` makes the manifest larger than the Viewer reads.
|
||||
const body = preview.padding ? " ".repeat(preview.padding) + served.manifest : served.manifest;
|
||||
return void setTimeout(() => response.end(body), preview.delays?.[url.search] ?? 0);
|
||||
}
|
||||
if (preview && url.pathname.startsWith(`${pagePath}/assets/`)) {
|
||||
const asset = served.files.get(url.pathname.slice(pagePath.length + 1));
|
||||
if (!asset) { response.statusCode = 404; return response.end("Not found"); }
|
||||
response.setHeader("content-type", "application/octet-stream");
|
||||
response.setHeader("content-length", String(asset.length));
|
||||
return response.end(asset);
|
||||
response.setHeader("content-type", "application/zip");
|
||||
response.setHeader("content-length", String(bytes.length));
|
||||
return response.end(bytes);
|
||||
}
|
||||
if (preview?.listing && url.pathname === `${pagePath}/reports.json`) {
|
||||
response.setHeader("content-type", "application/json");
|
||||
@@ -454,7 +431,7 @@ test("a hosted run of several targets opens the linked target and switches betwe
|
||||
const { page, errors } = await harness(t, await archive(report), { app: true, reportIdentity: null, preview, query: "&target=duo-open" });
|
||||
const button = page.getByRole("button", { name: "Device: iPhone Duo (open). Open another device's report" });
|
||||
await expect(button).toBeVisible();
|
||||
assert.equal(preview.queries[0], "?target=duo-open", "the Viewer asks the Worker for the linked target's report");
|
||||
assert.deepEqual(preview.queries, ["?target=duo-open"], "the Viewer asks the Worker for the linked target's report");
|
||||
await button.click();
|
||||
const items = page.getByRole("menu", { name: "Device" }).getByRole("menuitemradio");
|
||||
await expect(items).toHaveCount(4);
|
||||
@@ -462,15 +439,11 @@ test("a hosted run of several targets opens the linked target and switches betwe
|
||||
[["iPhone 17", "false"], ["iPhone Duo (closed)", "false"], ["iPhone Duo (open)", "true"], ["Android", "false"]]);
|
||||
await expect(items.nth(3)).toContainText("2 changes · Pixel 9 16");
|
||||
await expect(items.nth(1)).toContainText("Same review, other device");
|
||||
await page.evaluate(() => { window.__samePage = true; });
|
||||
await items.nth(3).click();
|
||||
await page.waitForURL(url => new URL(url).searchParams.get("platform") === "android");
|
||||
const next = new URL(page.url());
|
||||
assert.equal(next.searchParams.get("target"), null, "a target named after its platform is linked as before targets");
|
||||
// The switch stays on the page: the Worker is asked for the other target's manifest (the prefetch may already have), not for a new page.
|
||||
await expect.poll(() => preview.queries).toContain("?platform=android");
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
assert.equal(await page.evaluate(() => window.__samePage), true, "the switch stays on the page instead of reloading it");
|
||||
await expect.poll(() => preview.queries.at(-1)).toBe("?platform=android");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
@@ -481,110 +454,14 @@ test("a hosted report from before targets still switches platforms by ?platform=
|
||||
const { page, errors } = await harness(t, await archive(report), { app: true, reportIdentity: null, preview, query: "&platform=android" });
|
||||
const button = page.getByRole("button", { name: "Platform: Android. Open another platform's report" });
|
||||
await expect(button).toBeVisible();
|
||||
assert.equal(preview.queries[0], "?platform=android");
|
||||
assert.deepEqual(preview.queries, ["?platform=android"]);
|
||||
await button.click();
|
||||
const items = page.getByRole("menu", { name: "Platform" }).getByRole("menuitemradio");
|
||||
assert.deepEqual(await items.evaluateAll(rows => rows.map(row => [row.querySelector(".menu-row-label")?.firstChild?.textContent, row.getAttribute("aria-checked")])),
|
||||
[["iOS", "false"], ["Android", "true"]]);
|
||||
await expect(items.nth(0)).toContainText("3 changes");
|
||||
await page.evaluate(() => { window.__samePage = true; });
|
||||
await items.nth(0).click();
|
||||
await page.waitForURL(url => new URL(url).searchParams.get("platform") === "ios");
|
||||
await expect.poll(() => preview.queries).toContain("?platform=ios");
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
assert.equal(await page.evaluate(() => window.__samePage), true, "the switch stays on the page instead of reloading it");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
/** A two-platform deployment whose iOS manifest is slow, opened on Android with the platform menu ready. */
|
||||
async function slowSwitchHarness(t, token, delay) {
|
||||
const report = reportFixture();
|
||||
report.review.runtime = { ...report.review.runtime, platform: "android", platforms: ["ios", "android"] };
|
||||
const preview = { token, listing: [{ platform: "ios" }, { platform: "android" }], delays: { "?platform=ios": delay } };
|
||||
const opened = await harness(t, await archive(report), { app: true, reportIdentity: null, preview, query: "&platform=android" });
|
||||
await expect(opened.page.locator(".app-shell")).toBeVisible();
|
||||
const switchToIos = async () => {
|
||||
await opened.page.getByRole("button", { name: "Platform: Android. Open another platform's report" }).click();
|
||||
await opened.page.getByRole("menu", { name: "Platform" }).getByRole("menuitemradio").nth(0).click();
|
||||
await opened.page.waitForURL(url => new URL(url).searchParams.get("platform") === "ios");
|
||||
};
|
||||
return { ...opened, preview, switchToIos };
|
||||
}
|
||||
|
||||
test("a switch the prefetch joins keeps the report it shows open", { timeout: 60_000 }, async t => {
|
||||
// The switch starts the iOS download before the prefetch does; the prefetch then waits on the same download.
|
||||
const { page, errors, preview, switchToIos } = await slowSwitchHarness(t, "fghijklmnopqrstuvwxyz23456723456", 2500);
|
||||
await switchToIos();
|
||||
await expect(page.locator(".app-shell")).toBeVisible({ timeout: 10_000 });
|
||||
assert.equal(preview.queries.filter(query => query === "?platform=ios").length, 1, "the switch and the prefetch share one download");
|
||||
const screenshot = page.locator(".map-canvas img[data-screenshot-src]").first();
|
||||
await expect(screenshot).toHaveAttribute("data-screenshot-state", "ready");
|
||||
await expect.poll(() => screenshot.evaluate(image => image.naturalWidth)).toBe(32);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("switching back to a prefetched target shows the screenshots it showed before, without decoding them again", { timeout: 60_000 }, async t => {
|
||||
const { page, errors, preview, switchToIos } = await slowSwitchHarness(t, "hijklmnopqrstuvwxyz2345672345672", 0);
|
||||
const screenshot = page.locator(".map-canvas img[data-screenshot-src]").first();
|
||||
await expect(screenshot).toHaveAttribute("data-screenshot-state", "ready");
|
||||
const shown = await screenshot.getAttribute("src");
|
||||
await expect.poll(() => preview.queries).toContain("?platform=ios");
|
||||
await page.waitForTimeout(250);
|
||||
await switchToIos();
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
await expect(screenshot).toHaveAttribute("data-screenshot-state", "ready");
|
||||
assert.equal(preview.queries.filter(query => query === "?platform=ios").length, 1, "the switch opens the prefetched report without a download");
|
||||
const created = await page.evaluate(() => window.createdUrls.length);
|
||||
await page.goBack();
|
||||
await page.waitForURL(url => new URL(url).searchParams.get("platform") === "android");
|
||||
await expect(screenshot).toHaveAttribute("data-screenshot-state", "ready");
|
||||
assert.equal(await screenshot.getAttribute("src"), shown, "the Android report kept the Blob URL it was showing");
|
||||
assert.equal(await page.evaluate(url => window.revokedUrls.includes(url), shown), false);
|
||||
assert.equal(await page.evaluate(() => window.createdUrls.length), created, "nothing was decoded again");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("Forward onto a target still downloading keeps the preview link and its place in history", { timeout: 60_000 }, async t => {
|
||||
const { page, errors, switchToIos } = await slowSwitchHarness(t, "jklmnopqrstuvwxyz234567234567234", 3000);
|
||||
await page.evaluate(() => { window.location.hash = "#/map?inspect=diff"; });
|
||||
const androidUrl = page.url();
|
||||
await switchToIos();
|
||||
const iosUrl = page.url();
|
||||
await page.goBack();
|
||||
await page.waitForURL(androidUrl);
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
// iOS is not kept yet: its download is still in flight.
|
||||
await page.goForward();
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(page.url(), iosUrl, "Forward lands on the iOS link, not a rewritten /map");
|
||||
await expect(page.locator(".app-shell")).toBeVisible({ timeout: 10_000 });
|
||||
assert.equal(new URL(page.url()).pathname, new URL(iosUrl).pathname);
|
||||
assert.equal(new URL(page.url()).searchParams.get("platform"), "ios");
|
||||
await page.goBack();
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(page.url(), androidUrl, "Back restores the Android entry as it was");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("a hosted manifest larger than the Viewer reads is refused before it is parsed", { timeout: 60_000 }, async t => {
|
||||
const preview = { token: "klmnopqrstuvwxyz2345672345672345", padding: 11 * 1024 * 1024 };
|
||||
const { page, errors } = await harness(t, await archive(), { app: true, reportIdentity: null, preview, query: "" });
|
||||
const shell = page.locator(".report-loading-shell");
|
||||
await expect(shell).toHaveAttribute("data-loading-status", "failed");
|
||||
await expect(shell).toContainText("This report's index is larger than the Viewer opens.");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("going back during a switch shows the report the page was on, and the slow one does not replace it", { timeout: 60_000 }, async t => {
|
||||
const { page, errors, switchToIos } = await slowSwitchHarness(t, "ghijklmnopqrstuvwxyz234567234567", 3000);
|
||||
await switchToIos();
|
||||
await page.goBack();
|
||||
await page.waitForURL(url => new URL(url).searchParams.get("platform") === "android");
|
||||
await expect(page.locator(".app-shell")).toBeVisible({ timeout: 1500 });
|
||||
await page.locator(".app-shell").evaluate(shell => { shell.dataset.kept = "true"; });
|
||||
await page.waitForTimeout(3500);
|
||||
assert.equal(new URL(page.url()).searchParams.get("platform"), "android");
|
||||
await expect(page.locator(".app-shell")).toHaveAttribute("data-kept", "true");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
@@ -8,9 +8,6 @@ import { join } from 'node:path';
|
||||
import { appEnvironment, captureCacheDirectory, defaultBase, installDependencies, keepCapture, localInstallCommand, localReviewConfig, reportRef, reviewHeadSource, runLocalReview, snapshotWorkingTree, stopRecordedSessions } from '../../dist/ci/local-review.js';
|
||||
import { mkdir, readdir } from 'node:fs/promises';
|
||||
import { startLocalReportServer } from '../../dist/report/local-report-server.js';
|
||||
import { loadReport } from '../../dist/report/agent-api.js';
|
||||
import { manifestBody } from '../../dist/report/preview-manifest.js';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fixture, git } from '../helpers/public-ci-fixture.mjs';
|
||||
import { writeCaptureObserverPackages } from '../helpers/capture-observer-fixture.mjs';
|
||||
|
||||
@@ -232,28 +229,6 @@ test('the local Viewer serves each target of a run, by ?target= or, for links fr
|
||||
[['phone', 'iPhone 17'], ['duo-open', 'iPhone Duo (open)'], ['android', 'Android']]);
|
||||
});
|
||||
|
||||
test('the local Viewer serves the manifest and assets the Viewer opens, the same bytes the hosted Worker serves', async t => {
|
||||
const viewerRoot = await scratch(t, 'explore-local-viewer-');
|
||||
await writeFile(join(viewerRoot, 'index.html'), '<!doctype html><title>Viewer</title>');
|
||||
const review = new Uint8Array(await readFile(new URL('../fixtures/example-review-artifact.zip', import.meta.url)));
|
||||
const reports = [{ platform: 'ios', zip: review }, { platform: 'android', zip: new Uint8Array([4]) }];
|
||||
const server = await startLocalReportServer({ reports, viewerRoot });
|
||||
t.after(() => server.close());
|
||||
const loaded = await loadReport(review);
|
||||
const manifest = await fetch(`${server.url}/manifest.json`);
|
||||
assert.equal(manifest.status, 200);
|
||||
assert.match(manifest.headers.get('content-type') ?? '', /^application\/json/);
|
||||
assert.equal(await manifest.text(), manifestBody(loaded));
|
||||
const [asset] = Object.keys(JSON.parse(manifestBody(loaded)).entries);
|
||||
const served = await fetch(`${server.url}/${asset}?platform=ios`);
|
||||
assert.equal(served.status, 200);
|
||||
assert.equal(served.headers.get('content-type'), 'image/png');
|
||||
assert.equal(createHash('sha256').update(new Uint8Array(await served.arrayBuffer())).digest('hex'), asset.slice('assets/'.length, 'assets/'.length + 64));
|
||||
for (const path of [`/${asset}?platform=android`, `/assets/${'0'.repeat(64)}.png`, '/assets/review.json', '/manifest.json?platform=android', '/manifest.json?target=tablet']) {
|
||||
assert.equal((await fetch(`${server.url}${path}`)).status, 404, path);
|
||||
}
|
||||
});
|
||||
|
||||
test('a local review captures two commits of the repository in its own worktrees and packages a report', async t => {
|
||||
const f = await fixture(t, 'expo-router');
|
||||
t.mock.method(globalThis, 'fetch', async input => assert.fail(`Unmocked network request: ${input}`));
|
||||
|
||||
@@ -12,8 +12,6 @@ import { spawnSync } from "node:child_process";
|
||||
import { createDecipheriv } from "node:crypto";
|
||||
import { ZipReader, Uint8ArrayReader, TextWriter, configure } from "@zip.js/zip.js";
|
||||
import { viewerLinks } from "../../dist/report/viewer-links.js";
|
||||
import { loadReport } from "../../dist/report/agent-api.js";
|
||||
import { manifestBody, previewAsset } from "../../dist/report/preview-manifest.js";
|
||||
|
||||
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");
|
||||
const sha256 = createHash("sha256").update(png).digest("hex");
|
||||
@@ -55,12 +53,6 @@ async function fixture(t, { verified = true, preview = { hosting: "eas", expires
|
||||
configure({ useWebWorkers: false });
|
||||
const TOKEN_RE = /^[a-z2-7]{32}$/;
|
||||
|
||||
/** The fixture report as an explore:binary exploration the Worker (and so the deploy check) can open: exploration.json, same assets. */
|
||||
async function asExploration(reportPath) {
|
||||
await rm(join(reportPath, "review.json"));
|
||||
await writeFile(join(reportPath, "exploration.json"), JSON.stringify({ kind: "explore.exploration-report", map: { screens: [] } }));
|
||||
}
|
||||
|
||||
async function exportFixture(t, options) {
|
||||
const { root, inputPath } = await fixture(t, options);
|
||||
const reportPath = join(root, "report");
|
||||
@@ -74,7 +66,7 @@ async function exportFixture(t, options) {
|
||||
}
|
||||
|
||||
/** A fake EAS CLI plus a fake deployment: `deploy` captures the sealed report and .env, then serves them like the Worker would. */
|
||||
function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", aliasOrigin = "https://acme-explore--bluesky.expo.app", accounts = ["brent-org"], failDeploy = false, aliasServes = true, aliasListing, existingComment, manifestServes = true } = {}) {
|
||||
function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", aliasOrigin = "https://acme-explore--bluesky.expo.app", accounts = ["brent-org"], failDeploy = false, aliasServes = true, aliasListing, existingComment } = {}) {
|
||||
let deploys = 0;
|
||||
let latestComment = existingComment;
|
||||
const calls = []; const captured = {};
|
||||
@@ -108,7 +100,7 @@ function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", alia
|
||||
// An alias that has not moved to the new deployment yet: it answers for an earlier token, so this one is 404.
|
||||
if (!aliasServes && url.origin === aliasOrigin) return new Response("Not found", { status: 404 });
|
||||
if (url.origin === origin || (captured.alias && url.origin === aliasOrigin)) {
|
||||
const match = /^\/p\/([a-z2-7]{32})(?:\/(report\.zip|reports\.json|manifest\.json|api\/v1|assets\/[a-f0-9]{64}\.(?:png|jpg|mp4)))?$/.exec(url.pathname);
|
||||
const match = /^\/p\/([a-z2-7]{32})(?:\/(report\.zip|reports\.json|api\/v1))?$/.exec(url.pathname);
|
||||
if (!captured.env || !match || match[1] !== captured.env.EXPLORE_PREVIEW_TOKEN) return new Response("Not found", { status: 404 });
|
||||
// The token page negotiates like the real Worker: only a request that asks for HTML gets the shell.
|
||||
if (!match[2]) return (options.headers?.accept ?? "").includes("text/html")
|
||||
@@ -127,14 +119,6 @@ function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", alia
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, sealed.subarray(0, 12));
|
||||
decipher.setAAD(Buffer.from("expo-explore-preview/1")); decipher.setAuthTag(sealed.subarray(-16));
|
||||
const plain = Buffer.concat([decipher.update(sealed.subarray(12, -16)), decipher.final()]);
|
||||
// The manifest and assets the Viewer opens, as the Worker builds them; manifestServes: false is a Worker that cannot.
|
||||
if (match[2] === "manifest.json" || match[2].startsWith("assets/")) {
|
||||
const loaded = manifestServes ? await loadReport(new Uint8Array(plain)) : undefined;
|
||||
if (!loaded) return new Response("Not found", { status: 404 });
|
||||
if (match[2] === "manifest.json") return new Response(manifestBody(loaded), { status: 200, headers: { "content-type": "application/json; charset=utf-8" } });
|
||||
const asset = await previewAsset(loaded, match[2]);
|
||||
return asset ? new Response(asset.bytes, { status: 200, headers: { "content-type": asset.type } }) : new Response("Not found", { status: 404 });
|
||||
}
|
||||
return new Response(plain, { status: 200, headers: { "content-type": "application/zip" } });
|
||||
}
|
||||
const artifactNames = { 20: "explore-review-10-1", 21: "explore-review-10-1-ios", 22: "explore-review-10-1-android" };
|
||||
@@ -187,11 +171,9 @@ test("ci:deploy seals the exact report, deploys it with the preview export, veri
|
||||
assert.equal(sealed.byteLength, zip.byteLength + 12 + 16, "iv || ciphertext || tag, nothing else");
|
||||
assert.ok(!Buffer.from(sealed).includes(Buffer.from("review.json")), "the static file is ciphertext");
|
||||
// Verification hit the gate and its negatives before the comment was published.
|
||||
const previewPaths = eas.requests.filter(request => request.url.origin === "https://acme-explore--1lcbdcpwn3.expo.app").map(request => request.url.pathname.replace(/[a-f0-9]{64}/, "<sha256>"));
|
||||
const previewPaths = eas.requests.filter(request => request.url.origin === "https://acme-explore--1lcbdcpwn3.expo.app").map(request => request.url.pathname);
|
||||
const wrong = token.endsWith("a") ? `${token.slice(0, -1)}b` : `${token.slice(0, -1)}a`;
|
||||
// The ZIP, then what the Viewer opens from it: the manifest and one asset.
|
||||
assert.deepEqual(previewPaths, [`/p/${token}`, `/p/${token}/api/v1`, `/p/${token}/report.zip`, `/p/${token}/manifest.json`, `/p/${token}/assets/<sha256>.png`,
|
||||
"/", `/p/${wrong}`, `/p/${wrong}/report.zip`, `/p/${token}/viewer/index.html`]);
|
||||
assert.deepEqual(previewPaths, [`/p/${token}`, `/p/${token}/api/v1`, `/p/${token}/report.zip`, "/", `/p/${wrong}`, `/p/${wrong}/report.zip`, `/p/${token}/viewer/index.html`]);
|
||||
assert.ok(eas.requests.every(request => request.url.origin !== "https://acme-explore--1lcbdcpwn3.expo.app" || request.options.cache === "no-store"));
|
||||
const posted = eas.requests.find(request => request.options.method === "POST");
|
||||
const body = JSON.parse(posted.options.body).body;
|
||||
@@ -353,11 +335,9 @@ test("ci:deploy fans several platforms' reports into one sealed deployment, veri
|
||||
assert.deepEqual(result.reports.map(report => [report.platform, report.reportSha256, report.reportBytes, report.artifactUrl]),
|
||||
zips.map((zip, index) => [["ios", "android"][index], createHash("sha256").update(zip).digest("hex"), zip.byteLength, artifactUrl.replace(/20$/, String(21 + index))]));
|
||||
assert.equal(result.reportSha256, result.reports[0].reportSha256);
|
||||
const previewPaths = eas.requests.filter(request => request.url.origin === "https://acme-explore--1lcbdcpwn3.expo.app").map(request => (request.url.pathname + request.url.search).replace(/[a-f0-9]{64}/, "<sha256>"));
|
||||
const previewPaths = eas.requests.filter(request => request.url.origin === "https://acme-explore--1lcbdcpwn3.expo.app").map(request => request.url.pathname + request.url.search);
|
||||
const wrong = token.endsWith("a") ? `${token.slice(0, -1)}b` : `${token.slice(0, -1)}a`;
|
||||
assert.deepEqual(previewPaths, [`/p/${token}`, `/p/${token}/api/v1`,
|
||||
...["ios", "android"].flatMap(platform => [`/p/${token}/report.zip?platform=${platform}`, `/p/${token}/manifest.json?platform=${platform}`, `/p/${token}/assets/<sha256>.png?platform=${platform}`]),
|
||||
`/p/${token}/reports.json`,
|
||||
assert.deepEqual(previewPaths, [`/p/${token}`, `/p/${token}/api/v1`, `/p/${token}/report.zip?platform=ios`, `/p/${token}/report.zip?platform=android`, `/p/${token}/reports.json`,
|
||||
"/", `/p/${wrong}`, `/p/${wrong}/report.zip`, `/p/${token}/viewer/index.html`]);
|
||||
const posted = eas.requests.filter(request => request.options.method === "POST" || request.options.method === "PATCH").map(request => JSON.parse(request.options.body).body);
|
||||
assert.equal(posted.length, 2, "the second platform updates the comment the first created");
|
||||
@@ -428,7 +408,7 @@ test("a never-expiring preview seals no EXPLORE_PREVIEW_EXPIRES_AT and the comme
|
||||
|
||||
test("a standalone report deploys to a fixed alias with a fixed token, verifies both hosts, and prints the alias link", async t => {
|
||||
const { reportPath, exportPath } = await exportFixture(t);
|
||||
await asExploration(reportPath);
|
||||
await rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
const eas = easFixture();
|
||||
const token = "b".repeat(32);
|
||||
const result = await deployExplorationReport({ reportPath, project: "acme-explore", owner: "brent-org", expiresAfterDays: null, exportPath, alias: "bluesky", token,
|
||||
@@ -518,7 +498,7 @@ test("a fixture preview seals each platform's ZIP as is behind one alias and lis
|
||||
|
||||
test("a deployment that does not report the requested alias is a retryable deploy failure", async t => {
|
||||
const { reportPath, exportPath } = await exportFixture(t);
|
||||
await asExploration(reportPath);
|
||||
await rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
const eas = easFixture();
|
||||
const run = (node, [bin, ...args], options) => {
|
||||
const result = eas.run(node, [bin, ...args], options);
|
||||
@@ -637,7 +617,7 @@ test("deployLocalReports hosts one review's platforms behind one link, labelled
|
||||
|
||||
test("an explore:binary report names its platform, so an Android exploration is not served as iOS", async t => {
|
||||
const { reportPath, exportPath } = await exportFixture(t);
|
||||
await asExploration(reportPath);
|
||||
await rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
const eas = easFixture();
|
||||
await deployExplorationReport({ reportPath, platform: "android", project: "acme-explore", owner: "brent-org", expiresAfterDays: 7, exportPath,
|
||||
environment: deployEnvironment, transport: eas.transport, run: eas.run, now: () => now, verifyTimeoutMs: 1 });
|
||||
@@ -774,12 +754,3 @@ test("ci:deploy pairs target-named artifacts, deploys them in config order, and
|
||||
await assert.rejects(collectPlatformReports({ inputsPath: join(root, "inputs"), reportsPath: join(root, "reports"), environment: deployEnvironment, transport }),
|
||||
error => error.code === "PREVIEW_REPORTS_INVALID" && /holds the report of iphone/.test(error.message));
|
||||
});
|
||||
|
||||
test("ci:deploy fails a deployment whose Worker serves the ZIP but not the manifest and screenshots the Viewer opens", async t => {
|
||||
const { inputPath, reportPath, exportPath } = await exportFixture(t);
|
||||
const eas = easFixture({ manifestServes: false });
|
||||
await assert.rejects(deployPreview({ inputPath, reportPath, exportPath, artifactUrl, environment: deployEnvironment, transport: eas.transport, run: eas.run, now: () => now, verifyTimeoutMs: 1 }),
|
||||
error => error.code === "PREVIEW_VERIFY_FAILED" && /manifest and screenshots/.test(error.message) && error.details.status === 404);
|
||||
const posted = eas.requests.filter(request => request.options.method === "POST" || request.options.method === "PATCH").map(request => JSON.parse(request.options.body).body);
|
||||
assert.ok(posted.every(body => !body.includes(`/p/${eas.captured.env.EXPLORE_PREVIEW_TOKEN}`)), posted.join("\n---\n"));
|
||||
});
|
||||
@@ -25,8 +25,8 @@ The central host reads no environment variables and holds no secrets. A preview
|
||||
A hosted preview is one immutable EAS Hosting deployment per review, in the reviewed application's own EAS account, that opens the report without a download. Its export (`npm run export:preview`, written to `dist-preview/`) holds the identical staged Viewer under `/viewer/` and three API routes:
|
||||
|
||||
- `/p/<token>` serves the Viewer shell for exactly one 160-bit token (32 lowercase base32 characters) to requests that accept HTML; the shell's `#root` holds a text index of the report (title, counts, API links) until the Viewer renders, and a `Link` header names the JSON and Markdown alternates. Requests that do not prefer HTML (`Accept: */*`, `text/markdown`, `application/json`) get the same index as Markdown, so an agent handed the link finds the API by itself.
|
||||
- `/p/<token>/manifest.json` is what the Viewer opens: the report's metadata file (`review.json` or `exploration.json`) verbatim plus the size of every asset, decrypted from this deployment's own static files and ~12 KB over the wire; the shell preloads it so it downloads alongside the Viewer bundle. `/p/<token>/assets/<sha256>.<png|jpg|mp4>` serves one asset when the Viewer first shows it, `private, immutable` with a `max-age` of a week at most and never past the link's expiry, so this browser keeps it while shared caches never see it. Both answer `503` when the Worker cannot read the report at that moment, which the Viewer retries; `ci:deploy` checks that the manifest matches the deployed ZIP and that an asset serves its exact bytes. `/p/<token>/report.zip` still streams the whole decrypted ZIP (downloads, older Viewers). `/p/<token>/reports.json` lists the capture targets (up to 8, each with its platform and label) a multi-target deployment serves; `?target=<id>` selects one on every other route, and `?platform=<p>`, from links before targets, selects the target named `<p>`, else the first of that platform.
|
||||
- `/p/<token>/llms.txt` is the Markdown index at a fixed path, and `/p/<token>/api/v1/...` is the read-only agent API (`src/server/agent-api.ts`): summary, `/screens[?status=]`, `/screens/<id>`, `/transitions`, and for exploration reports `/journeys`, `/gaps`, `/frontier`, `/assets/<sha256>`, `/raw`, with `?limit=`/`?cursor=` paging (50 default, 200 max). The Worker decrypts and parses an archive when a request first needs it (`src/server/report-zip.ts` reads the stored PNGs and the deflated report JSON) and keeps the two most recently used in memory, plus every target's manifest; a manifest built for a report it is not keeping (the Viewer prefetches every target's) decrypts that report once and lets it go. The manifest and asset helpers live in `src/report/preview-manifest.ts`, shared with the local report server.
|
||||
- `/p/<token>/report.zip` fetches the encrypted report from this deployment's own static files, decrypts it, and streams the ZIP to the Viewer, which verifies and opens it exactly like a dropped file. `/p/<token>/reports.json` lists the capture targets (up to 8, each with its platform and label) a multi-target deployment serves; `?target=<id>` selects one on every other route, and `?platform=<p>`, from links before targets, selects the target named `<p>`, else the first of that platform.
|
||||
- `/p/<token>/llms.txt` is the Markdown index at a fixed path, and `/p/<token>/api/v1/...` is the read-only agent API (`src/server/agent-api.ts`): summary, `/screens[?status=]`, `/screens/<id>`, `/transitions`, and for exploration reports `/journeys`, `/gaps`, `/frontier`, `/assets/<sha256>`, `/raw`, with `?limit=`/`?cursor=` paging (50 default, 200 max). The Worker decrypts and parses the archive once per isolate (`src/server/report-zip.ts` reads the stored PNGs and the deflated report JSON) and answers from memory after that.
|
||||
- `/` and every other path, token, or method answer the same `404 Not found`, so a response never confirms that a deployment or token exists. After the sealed expiry the exact token still opens the Viewer shell for browsers, and every report route, including the Markdown index and the API, answers `410` with the expiry instant so the Viewer and agents can say the link expired.
|
||||
|
||||
`ci:deploy` seals the deployment by writing a deploy-time `.env` next to the export; EAS Hosting delivers it to the Worker and to nothing else:
|
||||
|
||||
@@ -115,9 +115,8 @@ if (!preview) {
|
||||
for (const path of [`/p/${token}`, `/p/${token}/`, `/p/${token}?view=compare&screen=home`]) {
|
||||
const response = await handlers.GET(new Request(origin + path, { headers: { accept: "text/html,*/*;q=0.8" } }));
|
||||
const body = await response.text();
|
||||
const preload = `<link rel="preload" href="/p/${token}/manifest.json" as="fetch" crossorigin>`;
|
||||
if (response.status !== 200 || response.headers.get("cache-control") !== "private, no-store" || !body.includes("<section data-explore-agent-index")
|
||||
|| !body.includes(preload) || body.replace(preload, "").replace(/<div id="root">.*<\/div>/s, '<div id="root"></div>') !== stagedHtml) {
|
||||
|| body.replace(/<div id="root">.*<\/div>/s, '<div id="root"></div>') !== stagedHtml) {
|
||||
throw new Error(`Preview page ${path} must serve the complete staged Viewer carrying the agent index`);
|
||||
}
|
||||
const markdown = await handlers.GET(new Request(origin + path));
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
* bundle under /viewer/ is public and identical to the central host's.
|
||||
*/
|
||||
import { AGENT_API_VERSION, agentApiReply, agentIndexHtml, agentIndexMarkdown, loadReport, prefersHtml, type AgentContext, type LoadedReport } from "../../../src/report/agent-api";
|
||||
import { manifestBody, previewAsset } from "../../../src/report/preview-manifest";
|
||||
|
||||
export type PreviewEnvironment = {
|
||||
/** Lowercase base32 path token the review comment links to. */
|
||||
@@ -133,44 +132,12 @@ export type PreviewRequestOptions = {
|
||||
/** Same-deployment fetch of static files; defaults to the global fetch. */
|
||||
fetchImpl?: typeof fetch;
|
||||
subtle?: SubtleCrypto;
|
||||
/** Decrypted and parsed reports by path, least recently used first, within HELD_REPORT_BYTES; defaults to a module-level cache. */
|
||||
cache?: Map<string, LoadedReport>;
|
||||
/** Decrypts in flight by path, shared by the requests that wait for them; defaults to a module-level map. */
|
||||
loading?: Map<string, Promise<LoadResult>>;
|
||||
/** Reports too large to decrypt in this isolate, by path; defaults to a module-level set. */
|
||||
oversized?: Set<string>;
|
||||
/** Bytes of decrypted reports kept, and of kept reports plus one decrypt; default to HELD_REPORT_BYTES and DECRYPT_PEAK_BYTES. */
|
||||
budget?: { held: number; peak: number };
|
||||
/** Manifest bodies by path, kept for the life of the isolate; defaults to a module-level cache. */
|
||||
manifests?: Map<string, string>;
|
||||
/** Decrypted and parsed reports by path, kept for the life of the isolate; defaults to a module-level cache. */
|
||||
cache?: Map<string, Promise<LoadedReport | undefined>>;
|
||||
};
|
||||
|
||||
const ROUTE = /^\/p\/([a-z2-7]{32})(?:\/|\/(report\.zip|reports\.json|manifest\.json|llms\.txt)|(\/api\/v1(?:\/[A-Za-z0-9._:@-]{1,200}){0,2}\/?)|\/assets\/([a-f0-9]{64}\.(?:png|jpg|mp4)))?$/;
|
||||
/**
|
||||
* Content-addressed and token-gated: this browser may keep an asset until the link expires, and for a week at most (as
|
||||
* long as the Viewer kept a whole report in Cache Storage before assets were served one by one); shared caches may not.
|
||||
*/
|
||||
const MAX_ASSET_AGE_SECONDS = 7 * 24 * 60 * 60;
|
||||
function assetCacheControl(expiresAt: number | null, now: number): string {
|
||||
const untilExpiry = expiresAt === null ? MAX_ASSET_AGE_SECONDS : Math.floor((expiresAt - now) / 1000);
|
||||
return `private, max-age=${Math.max(0, Math.min(MAX_ASSET_AGE_SECONDS, untilExpiry))}, immutable`;
|
||||
}
|
||||
/**
|
||||
* An isolate has 128 MB. It keeps decrypted reports, least recently used first, within HELD_REPORT_BYTES, and every
|
||||
* target's manifest (a few MB each at most). Decrypting needs the ciphertext and the plaintext at once, so decrypts run
|
||||
* one at a time, and before each one older reports go until the two fit in DECRYPT_PEAK_BYTES with what is kept. A
|
||||
* report too large to keep is decrypted for each request; one too large to decrypt (about 45 MB) answers 413, and the
|
||||
* isolate remembers it so it does not fetch it again.
|
||||
*/
|
||||
const HELD_REPORT_BYTES = 60 * 1024 * 1024;
|
||||
const DECRYPT_PEAK_BYTES = 90 * 1024 * 1024;
|
||||
/** A decrypted report, or why there is none: "unavailable" this time (the Viewer retries), "too-large" for this isolate, undefined never. */
|
||||
type LoadResult = LoadedReport | "unavailable" | "too-large" | undefined;
|
||||
const reportCache = new Map<string, LoadedReport>();
|
||||
const reportLoading = new Map<string, Promise<LoadResult>>();
|
||||
const manifestCache = new Map<string, string>();
|
||||
const oversizedReports = new Set<string>();
|
||||
let decrypting: Promise<unknown> = Promise.resolve();
|
||||
const ROUTE = /^\/p\/([a-z2-7]{32})(?:\/|\/(report\.zip|reports\.json|llms\.txt)|(\/api\/v1(?:\/[A-Za-z0-9._:@-]{1,200}){0,2}\/?))?$/;
|
||||
const reportCache = new Map<string, Promise<LoadedReport | undefined>>();
|
||||
|
||||
/**
|
||||
* `GET /p/<token>` serves the Viewer shell to browsers and the report's Markdown index to anything
|
||||
@@ -191,7 +158,7 @@ export async function previewResponse(request: Request, options: PreviewRequestO
|
||||
const url = new URL(request.url);
|
||||
const match = ROUTE.exec(url.pathname);
|
||||
if (!match || !sameToken(match[1]!, config.token)) return previewNotFound();
|
||||
const route = match[2] ?? (match[3] ? "api" : match[4] ? "asset" : undefined);
|
||||
const route = match[2] ?? (match[3] ? "api" : undefined);
|
||||
const expired = config.expiresAt !== null && (options.now ?? Date.now)() >= config.expiresAt;
|
||||
const pageUrl = `${url.origin}/p/${config.token}`;
|
||||
const linkHeader = `<${pageUrl}/api/${AGENT_API_VERSION}>; rel="alternate"; type="application/json", <${pageUrl}/llms.txt>; rel="alternate"; type="text/markdown"`;
|
||||
@@ -201,13 +168,8 @@ export async function previewResponse(request: Request, options: PreviewRequestO
|
||||
headers.set("Link", linkHeader);
|
||||
headers.set("Vary", "Accept");
|
||||
if (expired) return new Response(options.indexHtml, { headers });
|
||||
const selected = selectReport(config, url);
|
||||
const loaded = await loadedReport(url.origin, selected, config, options);
|
||||
if (!loaded || typeof loaded === "string") return new Response(options.indexHtml, { headers });
|
||||
const shell = shellWithIndex(options.indexHtml, agentIndexHtml(agentContext(pageUrl, config, loaded.report), loaded.loaded));
|
||||
// The same URL the Viewer will fetch for this page: its target's query when the link names one, none otherwise.
|
||||
const requested = url.searchParams.get("target") ?? url.searchParams.get("platform");
|
||||
return new Response(shellWithPreload(shell, `/p/${config.token}/manifest.json${requested ? `?${targetQuery(requested)}` : ""}`), { headers });
|
||||
const loaded = await loadedReport(url.origin, selectReport(config, url), config, options);
|
||||
return new Response(loaded ? shellWithIndex(options.indexHtml, agentIndexHtml(agentContext(pageUrl, config, loaded.report), loaded.loaded)) : options.indexHtml, { headers });
|
||||
}
|
||||
if (expired) return previewExpired(config.expiresAt!);
|
||||
if (route === "reports.json") {
|
||||
@@ -217,17 +179,7 @@ export async function previewResponse(request: Request, options: PreviewRequestO
|
||||
const report = selectReport(config, url);
|
||||
if (!report) return previewNotFound();
|
||||
if (route === "report.zip") return decryptedReport(url.origin, report.path, config, options);
|
||||
if (route === "manifest.json") {
|
||||
const body = await manifestFor(url.origin, report, config, options);
|
||||
if (body === "unavailable") return previewUnavailable();
|
||||
if (body === "too-large") return previewTooLarge();
|
||||
return body === undefined ? previewNotFound() : new Response(body, { headers: baseHeaders("application/json; charset=utf-8") });
|
||||
}
|
||||
const found = await loadedReport(url.origin, report, config, options);
|
||||
// The token and the target are right, so a report that cannot be read this time is the Worker's failure, and the Viewer retries.
|
||||
if (found === "unavailable" && route === "asset") return previewUnavailable();
|
||||
if (found === "too-large" && route === "asset") return previewTooLarge();
|
||||
const loaded = typeof found === "string" ? undefined : found;
|
||||
const loaded = await loadedReport(url.origin, report, config, options);
|
||||
if (!loaded) {
|
||||
if (route !== undefined) return previewNotFound();
|
||||
const headers = baseHeaders("text/html; charset=utf-8");
|
||||
@@ -235,7 +187,6 @@ export async function previewResponse(request: Request, options: PreviewRequestO
|
||||
headers.set("Vary", "Accept");
|
||||
return new Response(options.indexHtml, { headers });
|
||||
}
|
||||
if (route === "asset") return assetResponse(loaded.loaded, match[4]!, assetCacheControl(config.expiresAt, (options.now ?? Date.now)()));
|
||||
const context = agentContext(pageUrl, config, report);
|
||||
if (route === undefined || route === "llms.txt") {
|
||||
const headers = baseHeaders("text/markdown; charset=utf-8");
|
||||
@@ -269,57 +220,6 @@ function agentContext(pageUrl: string, config: PreviewConfig, report: PreviewRep
|
||||
}
|
||||
const PLATFORM_LABELS: Record<PreviewPlatform, string> = { ios: "iOS", android: "Android" };
|
||||
|
||||
/** `platform=<id>` for a target named after its platform (links from before targets), `target=<id>` otherwise. */
|
||||
function targetQuery(target: string): string {
|
||||
return `${target === "ios" || target === "android" ? "platform" : "target"}=${target}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the manifest download while the Viewer bundle is still loading: `crossorigin` makes the preload match
|
||||
* the Viewer's same-origin `fetch`, so the bytes arrive once.
|
||||
*/
|
||||
export function shellWithPreload(indexHtml: string, manifestPath: string): string {
|
||||
const link = `<link rel="preload" href="${manifestPath}" as="fetch" crossorigin>`;
|
||||
const at = indexHtml.indexOf("</head>") !== -1 ? indexHtml.indexOf("</head>") : indexHtml.indexOf("<script");
|
||||
return at === -1 ? indexHtml : `${indexHtml.slice(0, at)}${link}${indexHtml.slice(at)}`;
|
||||
}
|
||||
|
||||
/** The manifest of one target: kept once built, from the isolate's copy of the report or from one it decrypts and lets go. */
|
||||
async function manifestFor(origin: string, report: PreviewReport, config: PreviewConfig, options: PreviewRequestOptions): Promise<string | "unavailable" | "too-large" | undefined> {
|
||||
const manifests = options.manifests ?? manifestCache;
|
||||
const key = `${origin}${report.path}`;
|
||||
const known = manifests.get(key);
|
||||
if (known !== undefined) return known;
|
||||
const loaded = await loadedReport(origin, report, config, options, { keep: false });
|
||||
if (!loaded || typeof loaded === "string") return loaded;
|
||||
const body = manifestBody(loaded.loaded);
|
||||
manifests.set(key, body);
|
||||
return body;
|
||||
}
|
||||
|
||||
/** A report route that could not read the report this time; the same token and target work once it can. */
|
||||
function previewUnavailable(): Response {
|
||||
const headers = baseHeaders("text/plain; charset=utf-8");
|
||||
headers.set("Retry-After", "1");
|
||||
return new Response("Unavailable", { status: 503, headers });
|
||||
}
|
||||
|
||||
/** A report this Worker cannot decrypt in an isolate's memory; it never will, so the Viewer says so instead of retrying. */
|
||||
function previewTooLarge(): Response {
|
||||
return new Response(JSON.stringify({ error: "too-large" }), { status: 413, headers: baseHeaders("application/json; charset=utf-8") });
|
||||
}
|
||||
|
||||
/** One asset of the report, inflated from the decrypted ZIP the isolate holds. */
|
||||
async function assetResponse(loaded: LoadedReport, file: string, cacheControl: string): Promise<Response> {
|
||||
const asset = await previewAsset(loaded, `assets/${file}`);
|
||||
if (!asset) return previewNotFound();
|
||||
const headers = baseHeaders(asset.type);
|
||||
headers.set("Cache-Control", cacheControl);
|
||||
headers.set("Content-Length", String(asset.bytes.byteLength));
|
||||
headers.set("ETag", `"${file.slice(0, 64)}"`);
|
||||
return new Response(asset.bytes as BodyInit, { headers });
|
||||
}
|
||||
|
||||
/** The agent index as the shell's initial `#root` content; the Viewer replaces it when it renders. */
|
||||
export function shellWithIndex(indexHtml: string, indexBlock: string): string {
|
||||
const root = '<div id="root"></div>';
|
||||
@@ -328,89 +228,29 @@ export function shellWithIndex(indexHtml: string, indexBlock: string): string {
|
||||
return body === -1 ? indexHtml : `${indexHtml.slice(0, body)}${indexBlock}${indexHtml.slice(body)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A report decrypted and parsed, from the isolate's cache or decrypted now; requests for one that is decrypting wait for
|
||||
* that decrypt. `keep: false` (a manifest) does not keep a report that is not cached already.
|
||||
*/
|
||||
async function loadedReport(origin: string, report: PreviewReport | undefined, config: PreviewConfig, options: PreviewRequestOptions,
|
||||
{ keep = true }: { keep?: boolean } = {}): Promise<{ report: PreviewReport; loaded: LoadedReport } | "unavailable" | "too-large" | undefined> {
|
||||
async function loadedReport(origin: string, report: PreviewReport | undefined, config: PreviewConfig, options: PreviewRequestOptions): Promise<{ report: PreviewReport; loaded: LoadedReport } | undefined> {
|
||||
if (!report) return undefined;
|
||||
const cache = options.cache ?? reportCache;
|
||||
const loading = options.loading ?? reportLoading;
|
||||
const key = `${origin}${report.path}`;
|
||||
const oversized = options.oversized ?? oversizedReports;
|
||||
if (oversized.has(key)) return "too-large";
|
||||
const cached = cache.get(key);
|
||||
if (cached) {
|
||||
// Most recently used last, so the oldest is the first to go.
|
||||
cache.delete(key);
|
||||
cache.set(key, cached);
|
||||
return { report, loaded: cached };
|
||||
}
|
||||
let pending = loading.get(key);
|
||||
let pending = cache.get(key);
|
||||
if (!pending) {
|
||||
pending = oneAtATime(() => decryptedBytes(origin, report.path, config, options, sealed => makeRoom(cache, 2 * sealed, peak(options))))
|
||||
.then<LoadResult, LoadResult>(bytes => (bytes instanceof Uint8Array ? loadReport(bytes) : bytes), () => "unavailable");
|
||||
loading.set(key, pending);
|
||||
void pending.finally(() => { if (loading.get(key) === pending) loading.delete(key); });
|
||||
pending = decryptedBytes(origin, report.path, config, options).then(bytes => (bytes ? loadReport(bytes) : undefined));
|
||||
cache.set(key, pending);
|
||||
pending.then(loaded => { if (!loaded) cache.delete(key); }, () => cache.delete(key));
|
||||
}
|
||||
const loaded = await pending;
|
||||
if (loaded === "too-large") oversized.add(key);
|
||||
if (!loaded || typeof loaded === "string") return loaded;
|
||||
const held = options.budget?.held ?? HELD_REPORT_BYTES;
|
||||
if (keep && !cache.has(key) && loaded.zip.byteLength <= held) {
|
||||
makeRoom(cache, loaded.zip.byteLength, held);
|
||||
cache.set(key, loaded);
|
||||
}
|
||||
return { report, loaded };
|
||||
return loaded ? { report, loaded } : undefined;
|
||||
}
|
||||
|
||||
/** Lets the oldest kept reports go until `bytes` more fit beside the rest within `budget`; false when they never can. */
|
||||
function makeRoom(cache: Map<string, LoadedReport>, bytes: number, budget: number): boolean {
|
||||
if (bytes > budget) return false;
|
||||
let held = 0;
|
||||
for (const loaded of cache.values()) held += loaded.zip.byteLength;
|
||||
for (const [oldest, loaded] of cache) {
|
||||
if (held + bytes <= budget) break;
|
||||
cache.delete(oldest);
|
||||
held -= loaded.zip.byteLength;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function peak(options: PreviewRequestOptions): number {
|
||||
return options.budget?.peak ?? DECRYPT_PEAK_BYTES;
|
||||
}
|
||||
|
||||
/** Decrypts run one after another, so two of them never need their ciphertext and plaintext at once. */
|
||||
function oneAtATime<T>(task: () => Promise<T>): Promise<T> {
|
||||
const run = decrypting.then(task, task);
|
||||
decrypting = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* The report's ZIP, decrypted: "unavailable" when its file cannot be fetched now, "too-large" when `reserve` cannot make
|
||||
* room to decrypt it, undefined when the file is missing or does not decrypt.
|
||||
*/
|
||||
async function decryptedBytes(origin: string, reportPath: string, config: PreviewConfig, options: PreviewRequestOptions,
|
||||
reserve: (sealedBytes: number) => boolean = () => true): Promise<Uint8Array | "unavailable" | "too-large" | undefined> {
|
||||
async function decryptedBytes(origin: string, reportPath: string, config: PreviewConfig, options: PreviewRequestOptions): Promise<Uint8Array | undefined> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
const subtle = options.subtle ?? crypto.subtle;
|
||||
let upstream: Response;
|
||||
try { upstream = await fetchImpl(new URL(reportPath, origin).href, { headers: { accept: "application/octet-stream" } }); }
|
||||
catch { return "unavailable"; }
|
||||
if (upstream.status >= 500) return "unavailable";
|
||||
const upstream = await fetchImpl(new URL(reportPath, origin).href, { headers: { accept: "application/octet-stream" } });
|
||||
if (upstream.status !== 200 || !upstream.body) return undefined;
|
||||
const declared = Number(upstream.headers.get("content-length") ?? "0");
|
||||
if (declared > MAX_REPORT_BYTES + PREVIEW_CIPHER.ivBytes + 16) return undefined;
|
||||
if (declared && !reserve(declared)) {
|
||||
await upstream.body.cancel();
|
||||
return "too-large";
|
||||
}
|
||||
const sealed = new Uint8Array(await upstream.arrayBuffer());
|
||||
if (sealed.byteLength <= PREVIEW_CIPHER.ivBytes + 16 || sealed.byteLength > MAX_REPORT_BYTES + PREVIEW_CIPHER.ivBytes + 16) return undefined;
|
||||
if (!declared && !reserve(sealed.byteLength)) return "too-large";
|
||||
try {
|
||||
const key = await subtle.importKey("raw", config.key, "AES-GCM", false, ["decrypt"]);
|
||||
return new Uint8Array(await subtle.decrypt(
|
||||
@@ -419,12 +259,8 @@ async function decryptedBytes(origin: string, reportPath: string, config: Previe
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
/** The whole decrypted ZIP (downloads, older Viewers), decrypted in turn and within the same budget as every other decrypt. */
|
||||
async function decryptedReport(origin: string, reportPath: string, config: PreviewConfig, options: PreviewRequestOptions): Promise<Response> {
|
||||
const cache = options.cache ?? reportCache;
|
||||
const plain = await oneAtATime(() => decryptedBytes(origin, reportPath, config, options, sealed => makeRoom(cache, 2 * sealed, peak(options))));
|
||||
if (plain === "unavailable") return previewUnavailable();
|
||||
if (plain === "too-large") return previewTooLarge();
|
||||
const plain = await decryptedBytes(origin, reportPath, config, options);
|
||||
if (!plain) return previewNotFound();
|
||||
const headers = baseHeaders("application/zip");
|
||||
headers.set("Content-Length", String(plain.byteLength));
|
||||
|
||||
@@ -74,7 +74,7 @@ const explorationReport = {
|
||||
};
|
||||
const explorationZip = zip({ "exploration.json": new TextEncoder().encode(JSON.stringify(explorationReport)), [`assets/${pngSha}.png`]: png });
|
||||
|
||||
function deployment(files: Record<string, Uint8Array<ArrayBuffer>>, env: PreviewEnvironment, now?: () => number, budget?: { held: number; peak: number }) {
|
||||
function deployment(files: Record<string, Uint8Array<ArrayBuffer>>, env: PreviewEnvironment, now?: () => number) {
|
||||
const calls: string[] = [];
|
||||
const fetchImpl = (async (input: RequestInfo | URL) => {
|
||||
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
|
||||
@@ -82,7 +82,7 @@ function deployment(files: Record<string, Uint8Array<ArrayBuffer>>, env: Preview
|
||||
const body = files[url.pathname];
|
||||
return body ? new Response(body, { headers: { "content-length": String(body.byteLength) } }) : new Response("missing", { status: 404 });
|
||||
}) as typeof fetch;
|
||||
const options = { env, indexHtml: html, fetchImpl, subtle, cache: new Map(), loading: new Map(), manifests: new Map(), oversized: new Set<string>(), ...(now ? { now } : {}), ...(budget ? { budget } : {}) };
|
||||
const options = { env, indexHtml: html, fetchImpl, subtle, cache: new Map(), ...(now ? { now } : {}) };
|
||||
return { calls, get: (path: string, accept?: string) => previewResponse(new Request(`${origin}/p/${token}${path}`, accept === undefined ? {} : { headers: { accept } }), options) };
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ test("the token page negotiates: browsers get the shell carrying the agent index
|
||||
assert.ok(shell.startsWith("<!doctype html>"));
|
||||
assert.match(shell, /<div id="root"><section data-explore-agent-index style="[^"]*clip:rect\(0 0 0 0\)[^"]*"><h1>Expo Explore report: .* PR #\d+/);
|
||||
assert.match(shell, new RegExp(`href="${origin}/p/${token}/api/v1/screens\\?status=modified,accessibility-only,added,removed"`));
|
||||
assert.match(shell, /<\/section><\/div><link rel="preload" [^>]*><script type="module"/);
|
||||
assert.match(shell, /<\/section><\/div><script type="module"/);
|
||||
assert.equal(browser.headers.get("vary"), "Accept");
|
||||
assert.equal(browser.headers.get("link"), `<${origin}/p/${token}/api/v1>; rel="alternate"; type="application/json", <${origin}/p/${token}/llms.txt>; rel="alternate"; type="text/markdown"`);
|
||||
assert.equal(browser.headers.get("cache-control"), "private, no-store");
|
||||
@@ -363,111 +363,3 @@ test("a deployment of several targets keeps each target in its links and names t
|
||||
assert.equal((await (await site.get("/api/v1?platform=android")).json()).kind, "exploration");
|
||||
assert.equal((await site.get("/api/v1?target=pixel")).status, 404);
|
||||
});
|
||||
|
||||
test("the manifest and asset routes let the Viewer open a report before any screenshot, and the shell preloads the manifest", async () => {
|
||||
const site = deployment({ [reviewEnv.EXPLORE_PREVIEW_REPORT!]: await sealed(review) }, reviewEnv);
|
||||
const loaded = (await loadReport(review))!;
|
||||
const shell = await (await site.get("", "text/html")).text();
|
||||
assert.ok(shell.includes(`<link rel="preload" href="/p/${token}/manifest.json" as="fetch" crossorigin><script type="module"`), shell.slice(0, 400));
|
||||
const linked = await (await site.get("?target=ios&view=compare", "text/html")).text();
|
||||
assert.ok(linked.includes(`<link rel="preload" href="/p/${token}/manifest.json?platform=ios" as="fetch" crossorigin>`), linked.slice(0, 400));
|
||||
|
||||
const manifest = await site.get("/manifest.json");
|
||||
assert.equal(manifest.status, 200);
|
||||
assert.match(manifest.headers.get("content-type") ?? "", /^application\/json/);
|
||||
assert.equal(manifest.headers.get("cache-control"), "private, no-store");
|
||||
const body = await manifest.json() as { format: string; file: string; entries: Record<string, number>; report: { review: unknown } };
|
||||
assert.equal(body.format, "explore.preview-manifest/1");
|
||||
assert.equal(body.file, "review.json");
|
||||
assert.deepEqual(body.report, JSON.parse(new TextDecoder().decode(loaded.raw)));
|
||||
const assets = [...loaded.entries].filter(([name]) => name.startsWith("assets/"));
|
||||
assert.ok(assets.length > 0);
|
||||
assert.deepEqual(body.entries, Object.fromEntries(assets.map(([name, entry]) => [name, entry.size])));
|
||||
assert.ok(!("review.json" in body.entries));
|
||||
|
||||
const [name, entry] = assets.find(([file]) => file.endsWith(".png"))!;
|
||||
const asset = await site.get(`/${name}`);
|
||||
assert.equal(asset.status, 200);
|
||||
assert.equal(asset.headers.get("content-type"), "image/png");
|
||||
// Kept by this browser for a week, and never past the link's expiry; never by a shared cache.
|
||||
assert.equal(asset.headers.get("cache-control"), "private, max-age=604800, immutable");
|
||||
const nearExpiry = deployment({ [reviewEnv.EXPLORE_PREVIEW_REPORT!]: await sealed(review) }, reviewEnv, () => Date.parse("2029-12-31T23:59:00Z"));
|
||||
assert.equal((await nearExpiry.get(`/${name}`)).headers.get("cache-control"), "private, max-age=60, immutable");
|
||||
const never = deployment({ [reviewEnv.EXPLORE_PREVIEW_REPORT!]: await sealed(review) }, { ...reviewEnv, EXPLORE_PREVIEW_EXPIRES_AT: undefined });
|
||||
assert.equal((await never.get(`/${name}`)).headers.get("cache-control"), "private, max-age=604800, immutable");
|
||||
assert.equal(asset.headers.get("content-length"), String(entry.size));
|
||||
assert.equal(asset.headers.get("etag"), `"${name.slice("assets/".length, "assets/".length + 64)}"`);
|
||||
const bytes = new Uint8Array(await asset.arrayBuffer());
|
||||
assert.equal(bytes.byteLength, entry.size);
|
||||
assert.equal(createHash("sha256").update(bytes).digest("hex"), name.slice("assets/".length, "assets/".length + 64));
|
||||
|
||||
for (const path of ["/assets/" + "0".repeat(64) + ".png", "/assets/" + name.slice("assets/".length, -4) + ".gif", "/assets/review.json", `/${name}/`, `/${name}?platform=android`]) {
|
||||
assert.equal((await site.get(path)).status, 404, path);
|
||||
}
|
||||
// The sealed file is still decrypted once per isolate.
|
||||
assert.deepEqual(site.calls, [`${origin}${reviewEnv.EXPLORE_PREVIEW_REPORT}`]);
|
||||
});
|
||||
|
||||
test("a ZIP's directory records are not assets: the manifest the Viewer validates names files only", async () => {
|
||||
const withDirectory = zip({ "exploration.json": new TextEncoder().encode(JSON.stringify(explorationReport)), "assets/": new Uint8Array(), [`assets/${pngSha}.png`]: png });
|
||||
assert.ok(readZipDirectory(withDirectory)!.has("assets/"));
|
||||
const site = deployment({ [reviewEnv.EXPLORE_PREVIEW_REPORT!]: await sealed(withDirectory) }, reviewEnv);
|
||||
const body = await (await site.get("/manifest.json")).json() as { entries: Record<string, number> };
|
||||
assert.deepEqual(body.entries, { [`assets/${pngSha}.png`]: png.byteLength });
|
||||
});
|
||||
|
||||
test("a report the Worker cannot fetch this time answers 503, which the Viewer retries; one that never decrypts is a 404", async () => {
|
||||
const flaky = { get: (path: string) => previewResponse(new Request(`${origin}/p/${token}${path}`), {
|
||||
env: reviewEnv, indexHtml: html, subtle, cache: new Map(), loading: new Map(), manifests: new Map(),
|
||||
fetchImpl: (async () => new Response("upstream", { status: 502 })) as typeof fetch }) };
|
||||
for (const path of ["/manifest.json", `/assets/${pngSha}.png`, "/report.zip"]) {
|
||||
const response = await flaky.get(path);
|
||||
assert.equal(response.status, 503, path);
|
||||
assert.equal(response.headers.get("retry-after"), "1");
|
||||
assert.equal(response.headers.get("cache-control"), "private, no-store");
|
||||
}
|
||||
const garbage = deployment({ [reviewEnv.EXPLORE_PREVIEW_REPORT!]: new Uint8Array(64) as Uint8Array<ArrayBuffer> }, reviewEnv);
|
||||
for (const path of ["/manifest.json", `/assets/${pngSha}.png`, "/report.zip"]) assert.equal((await garbage.get(path)).status, 404, path);
|
||||
// A wrong token or an unknown target is still the same 404 as any other path.
|
||||
assert.equal((await garbage.get("/manifest.json?target=pixel")).status, 404);
|
||||
});
|
||||
|
||||
test("an isolate keeps decrypted reports within its byte budget, decrypts one at a time, and shares a decrypt between requests", async () => {
|
||||
const listing = ["iphone", "duo-open", "duo-closed"].map(target => ({ target, platform: "ios", label: target, path: `/_report/abcdefghijklmnop/${target}.zip.enc` }));
|
||||
const env: PreviewEnvironment = { ...reviewEnv, EXPLORE_PREVIEW_REPORT: undefined, EXPLORE_PREVIEW_REPORTS: JSON.stringify(listing) };
|
||||
const size = explorationZip.byteLength;
|
||||
// Room to keep two reports, and to decrypt one beside them.
|
||||
const site = deployment(Object.fromEntries(await Promise.all(listing.map(async entry => [entry.path, await sealed(explorationZip)] as const))), env,
|
||||
undefined, { held: 2 * size, peak: 4 * size + 64 });
|
||||
const decrypts = () => site.calls.length;
|
||||
// The prefetch: every target's manifest, each report decrypted once and let go.
|
||||
for (const { target } of listing) assert.equal((await site.get(`/manifest.json?target=${target}`)).status, 200);
|
||||
assert.equal(decrypts(), 3);
|
||||
for (const { target } of listing) await site.get(`/manifest.json?target=${target}`);
|
||||
assert.equal(decrypts(), 3, "manifests are kept");
|
||||
const asset = (target: string) => site.get(`/assets/${pngSha}.png?target=${target}`).then(response => response.status);
|
||||
// Requests that arrive together wait for one decrypt.
|
||||
assert.deepEqual(await Promise.all([asset("iphone"), asset("iphone"), asset("iphone")]), [200, 200, 200]);
|
||||
assert.equal(decrypts(), 4, "the report a reviewer looks at is kept");
|
||||
assert.equal(await asset("duo-open"), 200);
|
||||
assert.equal(await asset("iphone"), 200);
|
||||
assert.equal(decrypts(), 5);
|
||||
assert.equal(await asset("duo-closed"), 200);
|
||||
assert.equal(decrypts(), 6, "a third report evicts the least recently used, duo-open");
|
||||
assert.equal(await asset("iphone"), 200);
|
||||
assert.equal(decrypts(), 6);
|
||||
assert.equal(await asset("duo-open"), 200);
|
||||
assert.equal(decrypts(), 7);
|
||||
|
||||
// A report larger than the budget keeps is decrypted for each request; one too large to decrypt is unavailable.
|
||||
const perRequest = deployment({ [listing[0]!.path]: await sealed(explorationZip) }, env, undefined, { held: size - 1, peak: 4 * size });
|
||||
for (let request = 1; request <= 3; request++) {
|
||||
assert.equal(await perRequest.get(`/assets/${pngSha}.png?target=iphone`).then(response => response.status), 200);
|
||||
assert.equal(perRequest.calls.length, request);
|
||||
}
|
||||
const tooLarge = deployment({ [listing[0]!.path]: await sealed(explorationZip) }, env, undefined, { held: size, peak: size });
|
||||
for (const path of [`/assets/${pngSha}.png?target=iphone`, "/manifest.json?target=iphone", "/report.zip?target=iphone"]) {
|
||||
assert.equal((await tooLarge.get(path)).status, 413, path);
|
||||
}
|
||||
assert.equal(tooLarge.calls.length, 2, "the isolate remembers a report it cannot decrypt (report.zip is not cached)");
|
||||
});
|
||||
+7
-10
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, use
|
||||
import { createPortal, flushSync } from "react-dom";
|
||||
import { AlertCircle, RefreshCw } from "lucide-react";
|
||||
import { Toaster } from "sonner";
|
||||
import { isEmbeddedArtifactUrl, leaseEmbeddedArtifactUrl, optionalStorage, viewerLocation } from "./utils/embedded-report";
|
||||
import { isEmbeddedArtifactUrl, optionalStorage, releaseEmbeddedArtifactUrl, resolveEmbeddedArtifactUrl, viewerLocation } from "./utils/embedded-report";
|
||||
import { REPORT_SOURCE } from "./utils/report-source";
|
||||
import { CanvasToolbar } from "./components/canvas/toolbar";
|
||||
import { CanvasCameraControls } from "./components/canvas/camera-controls";
|
||||
@@ -287,8 +287,7 @@ export function App() {
|
||||
{...(droppable ? { onOpenFile: openFile } : {})}
|
||||
{...(droppable && source.status === "failed" ? { onRetry: retry } : {})} />;
|
||||
}
|
||||
// A hosted preview switches targets in place; the new report gets a fresh Viewer.
|
||||
return <ViewerApp key={source.reportKey} />;
|
||||
return <ViewerApp />;
|
||||
}
|
||||
|
||||
function ViewerApp() {
|
||||
@@ -1385,20 +1384,18 @@ function ViewerApp() {
|
||||
icon?.setAttribute("href", appIcon ?? fallback);
|
||||
return;
|
||||
}
|
||||
// A report ZIP's icon is a reference the browser cannot load: the tab holds its Blob URL while it shows. The lease
|
||||
// releases it against the report that resolved it, even after a switch to another target's report.
|
||||
// A report ZIP's icon is a reference the browser cannot load: the tab holds its Blob URL while it shows.
|
||||
let state: "pending" | "shown" | "gone" = "pending";
|
||||
const lease = leaseEmbeddedArtifactUrl(appIcon, "eager");
|
||||
lease.url.then(
|
||||
resolveEmbeddedArtifactUrl(appIcon, "eager").then(
|
||||
(url) => {
|
||||
if (state === "gone") return void lease.release();
|
||||
if (state === "gone") return void releaseEmbeddedArtifactUrl(appIcon);
|
||||
state = "shown";
|
||||
icon?.setAttribute("href", url);
|
||||
},
|
||||
() => { if (state !== "gone") icon?.setAttribute("href", fallback); },
|
||||
() => icon?.setAttribute("href", fallback),
|
||||
);
|
||||
return () => {
|
||||
if (state === "shown") lease.release();
|
||||
if (state === "shown") releaseEmbeddedArtifactUrl(appIcon);
|
||||
state = "gone";
|
||||
};
|
||||
}, [index, map, selectedScreenId]);
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Menu } from "../shared/menu";
|
||||
import { isPreviewPath, isReportTargetId, previewReportsUrl, targetQuery } from "../../utils/artifact-report";
|
||||
import { ScreenshotImage } from "../shared/screenshot-image";
|
||||
import { artifactUrl } from "../../utils/model";
|
||||
import { REPORT_SOURCE } from "../../utils/report-source";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { KeyHint } from "../shared/key-hint";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
@@ -153,7 +152,7 @@ export function AppPill(props: AppPillProps) {
|
||||
kind: "item" as const, label: target.label,
|
||||
description: [sibling.report?.changes === undefined ? undefined : `${sibling.report.changes} ${sibling.report.changes === 1 ? "change" : "changes"}`, sibling.report?.device]
|
||||
.filter(Boolean).join(" · ") || (target.platform === platform ? "Same review, other device" : "Same review, other platform"),
|
||||
checked: false, onSelect: () => { setPlatformOpen(false); if (!REPORT_SOURCE.switchTarget(target.id, sibling.url)) window.location.assign(sibling.url); },
|
||||
checked: false, onSelect: () => { setPlatformOpen(false); window.location.assign(sibling.url); },
|
||||
}] : [];
|
||||
}) : [];
|
||||
// A report whose target is not among the run's (a hand-edited one) still lists itself first, checked.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { FileEntry } from "@zip.js/zip.js";
|
||||
import { BlobReader, ZipReader, type FileEntry } from "@zip.js/zip.js";
|
||||
import type { ArtifactReport } from "../../../src/contracts/artifact-report";
|
||||
import { normalizePublicReviewForReading } from "../../../src/contracts/review-validation";
|
||||
import { reportContractGap } from "../public/public-workspace";
|
||||
@@ -66,21 +66,6 @@ export function previewReportUrl(page: URL): string | undefined {
|
||||
return `/p/${match[1]}/report.zip${target ? `?${targetQuery(target)}` : ""}`;
|
||||
}
|
||||
|
||||
/** The token of a hosted preview page, `/p/<token>`. */
|
||||
export function previewToken(page: URL): string | undefined {
|
||||
return PREVIEW_PATH.exec(page.pathname)?.[1];
|
||||
}
|
||||
|
||||
/** The manifest the Worker serves instead of the whole ZIP (`/p/<token>/manifest.json`). */
|
||||
export function previewManifestUrl(token: string, target?: string): string {
|
||||
return `/p/${token}/manifest.json${target ? `?${targetQuery(target)}` : ""}`;
|
||||
}
|
||||
|
||||
/** One asset of a hosted preview's report, `assets/<sha256>.<ext>` under `/p/<token>/`. */
|
||||
export function previewAssetUrl(token: string, path: string, target?: string): string {
|
||||
return `/p/${token}/${path}${target ? `?${targetQuery(target)}` : ""}`;
|
||||
}
|
||||
|
||||
/** The hosted preview's list of the targets it serves (`/p/<token>/reports.json`). */
|
||||
export function previewReportsUrl(page: URL): string | undefined {
|
||||
const match = PREVIEW_PATH.exec(page.pathname);
|
||||
@@ -228,49 +213,7 @@ function validateReport(value: unknown, expected?: ArtifactIdentity, fileName?:
|
||||
return { report: { ...report, review }, identity: expected ?? own };
|
||||
}
|
||||
|
||||
/** Where an archive's bytes come from: a ZIP entry in this browser, or one asset of a hosted preview. */
|
||||
type SourceEntry = { size: number; read: (limit: number, mimeType: string) => Promise<Blob> };
|
||||
type ImageEntry = { entry: SourceEntry; metadata: EmbeddedScreenshot; extension: "png" | "jpg" | "mp4" };
|
||||
|
||||
function zipEntry(entry: FileEntry): SourceEntry {
|
||||
return { size: entry.uncompressedSize, read: (limit, mimeType) => readEntry(entry, limit, mimeType) };
|
||||
}
|
||||
|
||||
/** A hosted preview asset: fetched when a screenshot is first shown, kept by the browser's HTTP cache afterwards. */
|
||||
function remoteEntry(url: string, size: number): SourceEntry {
|
||||
return { size, read: async (limit, mimeType) => {
|
||||
if (size > limit) throw new Error(`Report asset is too large: ${url}`);
|
||||
let response: Response | undefined;
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
try { response = await fetch(url, { credentials: "same-origin" }); }
|
||||
catch (error) { if (attempt) throw error; continue; }
|
||||
if (response.ok || response.status < 500) break;
|
||||
}
|
||||
if (!response?.ok) throw new Error(`The report screenshot could not be downloaded (HTTP ${response?.status ?? 0}).`);
|
||||
const bytes = await response.arrayBuffer();
|
||||
if (bytes.byteLength !== size) throw new Error("The screenshot size does not match the report.");
|
||||
return new Blob([bytes], { type: mimeType });
|
||||
} };
|
||||
}
|
||||
|
||||
/** The report page's manifest (src/report/preview-manifest.ts): the metadata file plus every asset's size. */
|
||||
export const PREVIEW_MANIFEST_FORMAT = "explore.preview-manifest/1";
|
||||
type PreviewManifest = { format: typeof PREVIEW_MANIFEST_FORMAT; file: "review.json" | "exploration.json"; entries: Record<string, number>; report: unknown };
|
||||
|
||||
function validateManifest(value: unknown): PreviewManifest {
|
||||
const invalid = () => new ReportFileError("invalid", "The hosted report manifest is invalid.");
|
||||
if (!value || typeof value !== "object") throw invalid();
|
||||
const manifest = value as PreviewManifest;
|
||||
if (manifest.format !== PREVIEW_MANIFEST_FORMAT || !["review.json", "exploration.json"].includes(manifest.file)
|
||||
|| !manifest.entries || typeof manifest.entries !== "object" || Array.isArray(manifest.entries)
|
||||
|| !manifest.report || typeof manifest.report !== "object") throw invalid();
|
||||
const entries = Object.entries(manifest.entries);
|
||||
if (entries.length > ARTIFACT_LIMITS.entries) throw invalid();
|
||||
for (const [path, size] of entries) {
|
||||
if (!safePath(path) || !Number.isSafeInteger(size) || size < 0 || size > ARTIFACT_LIMITS.image) throw invalid();
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
type ImageEntry = { entry: FileEntry; metadata: EmbeddedScreenshot; extension: "png" | "jpg" | "mp4" };
|
||||
/** Eager screenshots (the Inspector's) are decoded before lazy ones (canvas nodes and thumbnails). */
|
||||
export type ScreenshotPriority = "eager" | "lazy";
|
||||
type ImageLoad = {
|
||||
@@ -290,8 +233,6 @@ const DECODE_SLOTS = 4;
|
||||
*/
|
||||
export const RETAINED_SCREENSHOTS = 32;
|
||||
export const RETAINED_SCREENSHOT_BYTES = 128 * 1024 * 1024;
|
||||
/** A hosted preview's report in the background (another target is shown) keeps fewer, for a quick switch back. */
|
||||
export const BACKGROUND_RETAINED_SCREENSHOTS = 16;
|
||||
|
||||
/**
|
||||
* Compressed Blob + entry index. Screenshots are extracted when a caller asks for them; the last
|
||||
@@ -307,9 +248,8 @@ export class ArtifactReportArchive {
|
||||
private readonly queues: Record<ScreenshotPriority, ImageLoad[]> = { eager: [], lazy: [] };
|
||||
private disposed = false;
|
||||
private running = 0;
|
||||
private retainedLimit = RETAINED_SCREENSHOTS;
|
||||
|
||||
private constructor(private readonly close: () => void, report: ArtifactReport | ExplorationReport,
|
||||
private constructor(private readonly reader: ZipReader<Blob>, report: ArtifactReport | ExplorationReport,
|
||||
private readonly images: Map<string, ImageEntry>, readonly identity: ArtifactIdentity) {
|
||||
const assets = Object.fromEntries([...images].map(([sha, value]) => [sha, value.metadata]));
|
||||
this.data = report.kind === EXPLORATION_REPORT_KIND ? { contract: STANDALONE_REPORT_CONTRACT, exploration: report, assets }
|
||||
@@ -319,8 +259,6 @@ export class ArtifactReportArchive {
|
||||
/** Bind the ZIP to the linked run when there is one; a bare page takes the run the report names. */
|
||||
static async open(blob: Blob, identity?: ArtifactIdentity, fileName?: string): Promise<ArtifactReportArchive> {
|
||||
await checkReportFile(blob, fileName);
|
||||
// The ZIP reader is loaded on first use: a hosted preview opens its manifest and never needs it.
|
||||
const { BlobReader, ZipReader } = await import("@zip.js/zip.js");
|
||||
const reader = new ZipReader(new BlobReader(blob), { strictness: "strict", useWebWorkers: false });
|
||||
try {
|
||||
const files = new Map<string, FileEntry>();
|
||||
@@ -342,30 +280,6 @@ export class ArtifactReportArchive {
|
||||
}
|
||||
if (!entry.directory) files.set(entry.filename, entry);
|
||||
}
|
||||
const entries = new Map<string, SourceEntry>([...files].map(([name, entry]) => [name, zipEntry(entry)]));
|
||||
return await ArtifactReportArchive.fromEntries(entries, () => { void reader.close(); }, identity, fileName);
|
||||
} catch (error) {
|
||||
await reader.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a hosted preview from its manifest alone: the metadata is validated like a ZIP's, and each asset is
|
||||
* fetched from `assetUrl(path)` when a screenshot is first shown, so the first paint waits for no screenshot.
|
||||
*/
|
||||
static async openManifest(value: unknown, assetUrl: (path: string) => string, identity?: ArtifactIdentity): Promise<ArtifactReportArchive> {
|
||||
const manifest = validateManifest(value);
|
||||
const text = JSON.stringify(manifest.report);
|
||||
const metadata = new Blob([text], { type: "application/json" });
|
||||
const entries = new Map<string, SourceEntry>();
|
||||
for (const [path, size] of Object.entries(manifest.entries)) entries.set(path, remoteEntry(assetUrl(path), size));
|
||||
entries.set(manifest.file, { size: metadata.size, read: () => Promise.resolve(metadata) });
|
||||
return ArtifactReportArchive.fromEntries(entries, () => {}, identity, "report.zip");
|
||||
}
|
||||
|
||||
private static async fromEntries(files: Map<string, SourceEntry>, close: () => void, identity?: ArtifactIdentity, fileName?: string): Promise<ArtifactReportArchive> {
|
||||
{
|
||||
const indexImages = (assets: ArtifactReport["assets"]): Map<string, ImageEntry> => {
|
||||
const images = new Map<string, ImageEntry>();
|
||||
const imagePaths = new Set<string>();
|
||||
@@ -376,34 +290,34 @@ export class ArtifactReportArchive {
|
||||
}
|
||||
const extension = /\.(png|jpg|mp4)$/.exec(asset.path)?.[1] as "png" | "jpg" | "mp4" | undefined;
|
||||
const entry = files.get(asset.path);
|
||||
if (!extension || !entry || entry.size <= 0 || entry.size > ARTIFACT_LIMITS.image) {
|
||||
if (!extension || !entry || entry.uncompressedSize <= 0 || entry.uncompressedSize > ARTIFACT_LIMITS.image) {
|
||||
throw new Error("A report screenshot is missing or invalid.");
|
||||
}
|
||||
images.set(asset.sha256, { entry, extension,
|
||||
metadata: { mimeType: extension === "png" ? "image/png" : extension === "mp4" ? "video/mp4" : "image/jpeg", byteLength: entry.size } });
|
||||
metadata: { mimeType: extension === "png" ? "image/png" : extension === "mp4" ? "video/mp4" : "image/jpeg", byteLength: entry.uncompressedSize } });
|
||||
imagePaths.add(asset.path);
|
||||
}
|
||||
return images;
|
||||
};
|
||||
const explorationEntry = files.get("exploration.json");
|
||||
if (explorationEntry && !files.has("review.json")) {
|
||||
if (explorationEntry.size > ARTIFACT_LIMITS.metadata) throw new ReportFileError("too-large", `${describe(fileName)} has an exploration index over the browser limit.`);
|
||||
if (explorationEntry.uncompressedSize > ARTIFACT_LIMITS.metadata) throw new ReportFileError("too-large", `${describe(fileName)} has an exploration index over the browser limit.`);
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(await (await explorationEntry.read(ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
try { parsed = JSON.parse(await (await readEntry(explorationEntry, ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
catch { throw new ReportFileError("not-report", `${describe(fileName)} is not an Explore report: its exploration.json is not valid JSON.`); }
|
||||
const { report, identity: bound } = validateExplorationReport(parsed, identity, fileName);
|
||||
const images = indexImages(report.assets);
|
||||
for (const artifact of report.map.artifacts) {
|
||||
if (artifact.kind === "screenshot" && !images.has(artifact.sha256)) throw new Error("A captured screenshot is missing from the report image index.");
|
||||
}
|
||||
return new ArtifactReportArchive(close, report, images, bound);
|
||||
return new ArtifactReportArchive(reader, report, images, bound);
|
||||
}
|
||||
const metadata = files.get("review.json");
|
||||
if (!metadata || metadata.size > ARTIFACT_LIMITS.metadata) {
|
||||
if (!metadata || metadata.uncompressedSize > ARTIFACT_LIMITS.metadata) {
|
||||
throw new ReportFileError("not-report", `${describe(fileName)} is not an Explore report: it has no review.json. Download ${identity ? reportFileName(identity) : `the ${GENERIC_FILE_NAME} artifact`} from the workflow run.`);
|
||||
}
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(await (await metadata.read(ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
try { parsed = JSON.parse(await (await readEntry(metadata, ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
catch { throw new ReportFileError("not-report", `${describe(fileName)} is not an Explore report: its review.json is not valid JSON.`); }
|
||||
const { report, identity: bound } = validateReport(parsed, identity, fileName);
|
||||
const images = indexImages(report.assets);
|
||||
@@ -412,7 +326,10 @@ export class ArtifactReportArchive {
|
||||
if (image && !images.has(image.sha256)) throw new Error("A captured screenshot is missing from the report image index.");
|
||||
}
|
||||
}
|
||||
return new ArtifactReportArchive(close, report, images, bound);
|
||||
return new ArtifactReportArchive(reader, report, images, bound);
|
||||
} catch (error) {
|
||||
await reader.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,8 +345,6 @@ export class ArtifactReportArchive {
|
||||
async resolve(reference: string, priority: ScreenshotPriority = "lazy"): Promise<string> {
|
||||
const sha256 = IMAGE_REFERENCE.exec(reference)?.[1];
|
||||
if (!sha256) return reference;
|
||||
// Shown again: back to the full allowance.
|
||||
this.retainedLimit = RETAINED_SCREENSHOTS;
|
||||
if (this.disposed || !this.images.has(sha256)) throw new Error("This report screenshot is unavailable.");
|
||||
const existing = this.loads.get(sha256);
|
||||
if (existing) {
|
||||
@@ -473,22 +388,7 @@ export class ArtifactReportArchive {
|
||||
this.loads.clear();
|
||||
this.retained.clear();
|
||||
this.retainedBytes = 0;
|
||||
this.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Let go of every screenshot of a report nobody is looking at; its index stays open for a quick return. The Viewer that
|
||||
* used them releases them against the report shown next, so the ones still in use are dropped here instead.
|
||||
*/
|
||||
trim(): void {
|
||||
for (const load of this.queues.eager.splice(0).concat(this.queues.lazy.splice(0))) {
|
||||
load.waiting?.drop(new Error("This screenshot is no longer in use."));
|
||||
}
|
||||
// What the Viewer was showing is kept as released, most recent last, so switching back shows it at once.
|
||||
this.retainedLimit = BACKGROUND_RETAINED_SCREENSHOTS;
|
||||
for (const load of this.loads.values()) if (load.url) this.retain(load.sha256, load.url);
|
||||
this.loads.clear();
|
||||
this.evictRetained();
|
||||
void this.reader.close();
|
||||
}
|
||||
|
||||
private async decode(load: ImageLoad): Promise<string> {
|
||||
@@ -496,7 +396,7 @@ export class ArtifactReportArchive {
|
||||
await this.acquireSlot(load);
|
||||
try {
|
||||
if (this.disposed) throw new Error("This report was closed.");
|
||||
const blob = await image.entry.read(ARTIFACT_LIMITS.image, image.metadata.mimeType);
|
||||
const blob = await readEntry(image.entry, ARTIFACT_LIMITS.image, image.metadata.mimeType);
|
||||
const bytes = await blob.arrayBuffer();
|
||||
const header = new Uint8Array(bytes, 0, Math.min(8, bytes.byteLength));
|
||||
const validImage = image.extension === "png"
|
||||
@@ -511,11 +411,10 @@ export class ArtifactReportArchive {
|
||||
if (actual !== load.sha256) throw new Error("The screenshot checksum does not match the report.");
|
||||
if (this.disposed) throw new Error("This report was closed.");
|
||||
const url = URL.createObjectURL(blob);
|
||||
const current = this.loads.get(load.sha256) === load;
|
||||
if (current && load.users > 0) load.url = url;
|
||||
if (load.users > 0) load.url = url;
|
||||
else {
|
||||
// Everyone let go while it decoded, or the report was trimmed; keep the finished work for a quick return.
|
||||
if (current) this.loads.delete(load.sha256);
|
||||
// Everyone let go while it decoded; keep the finished work for a quick return.
|
||||
this.loads.delete(load.sha256);
|
||||
this.retain(load.sha256, url);
|
||||
}
|
||||
return url;
|
||||
@@ -569,22 +468,10 @@ export class ArtifactReportArchive {
|
||||
/** Keep a released URL; beyond either limit the least recently released ones are revoked. */
|
||||
private retain(sha256: string, url: string): void {
|
||||
const bytes = this.images.get(sha256)!.metadata.byteLength;
|
||||
// A decode a trim left behind can finish after a later one for the same screenshot; nothing uses a kept URL, so the older one goes.
|
||||
const replaced = this.retained.get(sha256);
|
||||
if (replaced) {
|
||||
this.retained.delete(sha256);
|
||||
this.retainedBytes -= replaced.bytes;
|
||||
if (replaced.url !== url) URL.revokeObjectURL(replaced.url);
|
||||
}
|
||||
this.retained.set(sha256, { url, bytes });
|
||||
this.retainedBytes += bytes;
|
||||
this.evictRetained();
|
||||
}
|
||||
|
||||
/** Beyond either limit, the least recently released kept URLs are revoked. */
|
||||
private evictRetained(): void {
|
||||
for (const [oldest, old] of this.retained) {
|
||||
if (this.retained.size <= this.retainedLimit && this.retainedBytes <= RETAINED_SCREENSHOT_BYTES) break;
|
||||
if (this.retained.size <= RETAINED_SCREENSHOTS && this.retainedBytes <= RETAINED_SCREENSHOT_BYTES) break;
|
||||
this.retained.delete(oldest);
|
||||
this.retainedBytes -= old.bytes;
|
||||
URL.revokeObjectURL(old.url);
|
||||
@@ -595,14 +482,7 @@ export class ArtifactReportArchive {
|
||||
export let activeArtifactReport: ArtifactReportArchive | undefined;
|
||||
|
||||
function activate(archive: ArtifactReportArchive): ArtifactReportArchive {
|
||||
if (activeArtifactReport !== archive) activeArtifactReport?.dispose();
|
||||
activeArtifactReport = archive;
|
||||
return archive;
|
||||
}
|
||||
|
||||
/** Make an archive the one screenshots resolve from, keeping the previous one open (a hosted preview's other target). */
|
||||
export function showArchive(archive: ArtifactReportArchive): ArtifactReportArchive {
|
||||
if (activeArtifactReport !== archive) activeArtifactReport?.trim();
|
||||
activeArtifactReport?.dispose();
|
||||
activeArtifactReport = archive;
|
||||
return archive;
|
||||
}
|
||||
|
||||
@@ -21,16 +21,6 @@ export function resolveEmbeddedArtifactUrl(reference: string, priority: Screensh
|
||||
return Promise.resolve(reference);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve, with a release bound to the report that resolved it: for a caller that may let go after a hosted preview has
|
||||
* switched to another target's report, whose screenshots it must not release.
|
||||
*/
|
||||
export function leaseEmbeddedArtifactUrl(reference: string, priority: ScreenshotPriority = "lazy"): { url: Promise<string>; release: () => void } {
|
||||
const archive = activeArtifactReport;
|
||||
if (!archive) return { url: resolveEmbeddedArtifactUrl(reference, priority), release: () => {} };
|
||||
return { url: archive.resolve(reference, priority), release: () => archive.release(reference) };
|
||||
}
|
||||
|
||||
/** Artifact screenshots release their Blob URL when no visible image or download uses it; the report keeps a few for a quick return. */
|
||||
export function releaseEmbeddedArtifactUrl(reference: string): boolean {
|
||||
if (!activeArtifactReport) return false;
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { EmbeddedReport } from "../../../src/contracts/standalone-report";
|
||||
import {
|
||||
ARTIFACT_LIMITS, ArtifactReportArchive, artifactIdentity, isReportPage, isReportTargetId, openCachedReport, openReportFile, previewAssetUrl,
|
||||
previewManifestUrl, previewReportsUrl, previewToken, reportDownloadUrl, reportFileName, reportTarget, ReportFileError,
|
||||
showArchive, workflowRunUrl, type ArtifactIdentity, type ArtifactLoadProgress, type ReportFileErrorCode,
|
||||
artifactIdentity, isReportPage, openCachedReport, openReportBlob, openReportFile, previewReportUrl, reportDownloadUrl,
|
||||
reportFileName, ReportFileError, workflowRunUrl, type ArtifactIdentity, type ArtifactLoadProgress, type ReportFileErrorCode,
|
||||
} from "./artifact-report";
|
||||
|
||||
export type ReportSourceStatus = "checking-cache" | "downloading" | "awaiting-file" | "opening" | "ready" | "failed";
|
||||
@@ -14,41 +13,23 @@ export type ReportSourceSnapshot = {
|
||||
error?: string;
|
||||
errorCode?: ReportFileErrorCode;
|
||||
fileName?: string;
|
||||
/** Counts the reports this page has shown; a hosted preview switching targets starts a fresh Viewer per report. */
|
||||
reportKey: number;
|
||||
};
|
||||
|
||||
/** The metadata the ZIP path accepts, plus room for the manifest's list of assets and their sizes. */
|
||||
const MAX_MANIFEST_BYTES = ARTIFACT_LIMITS.metadata + 2 * 1024 * 1024;
|
||||
/** After the shown report is ready, the deployment's other targets are fetched so a switch needs no download. */
|
||||
const PREFETCH_DELAY = 1500;
|
||||
|
||||
type PreviewPage = { token: string; target?: string };
|
||||
|
||||
/**
|
||||
* Reports never pass through a server: the report page asks the reviewer for the ZIP GitHub gave them, keeps
|
||||
* it in this browser, and opens it here. A hosted preview downloads its report from the deployment's Worker
|
||||
* instead, keeps every target it has opened, and switches between them without leaving the page.
|
||||
* it in this browser, and opens it here.
|
||||
*/
|
||||
export class ReportSource {
|
||||
data: EmbeddedReport | undefined;
|
||||
/** The hosted report page (the root, or `/r`) that opens a report ZIP for a linked run or any run. */
|
||||
readonly reportPage: boolean;
|
||||
/** A hosted preview's token and linked target; the page downloads its report instead of asking for a file. */
|
||||
private readonly preview?: PreviewPage;
|
||||
/** A hosted preview's report URL; the page downloads it instead of asking for a file. */
|
||||
readonly previewUrl?: string;
|
||||
private readonly linkIdentity?: ArtifactIdentity;
|
||||
private readonly linkError?: string;
|
||||
private snapshot: ReportSourceSnapshot;
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private pending: Promise<void> | undefined;
|
||||
/** Opened preview reports by the target key that selected them ("" for the link's default). */
|
||||
private readonly archives = new Map<string, ArtifactReportArchive>();
|
||||
private readonly loading = new Map<string, Promise<ArtifactReportArchive>>();
|
||||
/** Everyone waiting on a download hears its progress: a switch can join one the prefetch started. */
|
||||
private readonly loadingProgress = new Map<string, Set<(progress: ArtifactLoadProgress) => void>>();
|
||||
private current: string | undefined;
|
||||
private generation = 0;
|
||||
private prefetched = false;
|
||||
|
||||
subscribe = (listener: () => void): (() => void) => {
|
||||
this.listeners.add(listener);
|
||||
@@ -58,35 +39,26 @@ export class ReportSource {
|
||||
getSnapshot = (): ReportSourceSnapshot => this.snapshot;
|
||||
|
||||
constructor(page?: URL) {
|
||||
const token = page ? previewToken(page) : undefined;
|
||||
let linkError: string | undefined;
|
||||
if (token) {
|
||||
try {
|
||||
const target = reportTarget(page!);
|
||||
this.preview = { token, ...(target ? { target } : {}) };
|
||||
} catch (error) { linkError = error instanceof Error ? error.message : "Invalid report link."; }
|
||||
}
|
||||
this.reportPage = Boolean(page) && (isReportPage(page!) || Boolean(token));
|
||||
if (this.reportPage && !token) {
|
||||
const previewUrl = page ? previewReportUrl(page) : undefined;
|
||||
if (previewUrl) this.previewUrl = previewUrl;
|
||||
this.reportPage = Boolean(page) && (isReportPage(page!) || Boolean(previewUrl));
|
||||
if (this.reportPage && !previewUrl) {
|
||||
try { const identity = artifactIdentity(page!); if (identity) this.linkIdentity = identity; }
|
||||
catch (error) { linkError = error instanceof Error ? error.message : "Invalid report link."; }
|
||||
catch (error) { this.linkError = error instanceof Error ? error.message : "Invalid report link."; }
|
||||
}
|
||||
if (linkError) this.linkError = linkError;
|
||||
this.snapshot = {
|
||||
status: !this.reportPage ? "ready" : this.linkError ? "failed" : this.preview ? "downloading" : this.linkIdentity ? "checking-cache" : "awaiting-file",
|
||||
progress: this.preview ? { phase: "downloading" } : { phase: "cache" },
|
||||
status: !this.reportPage ? "ready" : this.previewUrl ? "downloading" : this.linkError ? "failed" : this.linkIdentity ? "checking-cache" : "awaiting-file",
|
||||
progress: this.previewUrl ? { phase: "downloading" } : { phase: "cache" },
|
||||
...(this.linkIdentity ? { identity: this.linkIdentity } : {}),
|
||||
...(this.linkError ? { error: this.linkError, errorCode: "invalid" as const } : {}),
|
||||
reportKey: 0,
|
||||
};
|
||||
if (this.preview && typeof window !== "undefined") window.addEventListener("popstate", this.onPopState);
|
||||
}
|
||||
|
||||
get ready(): boolean { return this.snapshot.status === "ready"; }
|
||||
get identity(): ArtifactIdentity | undefined { return this.snapshot.identity; }
|
||||
get progress(): ArtifactLoadProgress { return this.snapshot.progress; }
|
||||
/** A wrong file can be replaced by another drop; an invalid link or a hosted preview cannot. */
|
||||
get canRetry(): boolean { return this.reportPage && !this.linkError && !this.preview; }
|
||||
get canRetry(): boolean { return this.reportPage && !this.linkError && !this.previewUrl; }
|
||||
get expectedFileName(): string | undefined { return this.linkIdentity ? reportFileName(this.linkIdentity) : undefined; }
|
||||
get downloadUrl(): string | undefined { return this.linkIdentity ? reportDownloadUrl(this.linkIdentity) : undefined; }
|
||||
get workflowUrl(): string | undefined { return this.identity ? workflowRunUrl(this.identity) : undefined; }
|
||||
@@ -100,186 +72,63 @@ export class ReportSource {
|
||||
|
||||
/** Reopen the copy this browser kept of the linked report; otherwise wait for the file. */
|
||||
load(): Promise<void> {
|
||||
if (this.snapshot.status === "downloading" && this.preview) return this.pending ??= this.show(this.preview.target, this.generation).finally(() => { this.pending = undefined; });
|
||||
if (this.snapshot.status === "downloading" && this.previewUrl) return this.pending ??= this.download(this.previewUrl).finally(() => { this.pending = undefined; });
|
||||
if (this.snapshot.status !== "checking-cache") return Promise.resolve();
|
||||
const identity = this.linkIdentity!;
|
||||
this.pending ??= openCachedReport(identity, this.progressed).then(archive => {
|
||||
if (archive) {
|
||||
this.data = archive.data;
|
||||
this.set({ ...this.snapshot, status: "ready", identity: archive.identity });
|
||||
} else this.set({ ...this.snapshot, status: "awaiting-file", progress: { phase: "cache" }, identity });
|
||||
}, () => this.set({ ...this.snapshot, status: "awaiting-file", progress: { phase: "cache" }, identity }))
|
||||
this.set({ status: "ready", progress: this.snapshot.progress, identity: archive.identity });
|
||||
} else this.set({ status: "awaiting-file", progress: { phase: "cache" }, identity });
|
||||
}, () => this.set({ status: "awaiting-file", progress: { phase: "cache" }, identity }))
|
||||
.finally(() => { this.pending = undefined; });
|
||||
return this.pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show another target of this hosted preview without leaving the page: the URL changes as a link to it would, and
|
||||
* a report this page already opened appears at once. False on any other page, which navigates instead.
|
||||
* Download the report the preview deployment decrypts for this link, then open it like a dropped
|
||||
* file: the same ZIP, hash, and identity checks apply, and the browser keeps the same cached copy.
|
||||
*/
|
||||
switchTarget(target: string, url: string): boolean {
|
||||
if (!this.preview || typeof window === "undefined") return false;
|
||||
window.history.pushState(null, "", url);
|
||||
this.activateTarget(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
private onPopState = (): void => {
|
||||
let target: string | undefined;
|
||||
try { target = reportTarget(new URL(window.location.href)); } catch { return; }
|
||||
this.activateTarget(target);
|
||||
};
|
||||
|
||||
private activateTarget(target: string | undefined): void {
|
||||
const key = target ?? "";
|
||||
const archive = this.archives.get(key);
|
||||
// Already shown (a hash-only navigation); going back to it from a switch still loading or failed shows it again.
|
||||
if (this.snapshot.status === "ready" && this.current !== undefined && archive && archive === this.archives.get(this.current)) {
|
||||
this.current = key;
|
||||
return;
|
||||
}
|
||||
const generation = ++this.generation;
|
||||
this.pending = undefined;
|
||||
if (archive) {
|
||||
this.set({ ...this.snapshot, reportKey: this.snapshot.reportKey + 1 });
|
||||
this.adopt(key, archive);
|
||||
return;
|
||||
}
|
||||
this.data = undefined;
|
||||
this.set({ status: "downloading", progress: { phase: "downloading" }, reportKey: this.snapshot.reportKey + 1 });
|
||||
this.pending = this.show(target, generation).finally(() => { if (generation === this.generation) this.pending = undefined; });
|
||||
}
|
||||
|
||||
/** Download (or take from this page's opened reports) one target's report and make it the shown one. */
|
||||
private async show(target: string | undefined, generation: number): Promise<void> {
|
||||
const key = target ?? "";
|
||||
private async download(url: string): Promise<void> {
|
||||
try {
|
||||
const archive = this.archives.get(key) ?? await this.loadTarget(target, progress => { if (generation === this.generation) this.progressed(progress); });
|
||||
// A switch Back or Forward left behind still keeps what it downloaded, so returning to it needs no download.
|
||||
if (generation !== this.generation) return void this.remember(key, archive);
|
||||
this.adopt(key, archive);
|
||||
const response = await fetch(url, { credentials: "omit", cache: "no-store" });
|
||||
if (response.status === 410) throw new ReportFileError("invalid", `This preview link expired${await expiredOn(response)}. Download the report from the pull request or workflow run instead, or rerun Explore for a fresh link.`);
|
||||
if (response.status === 404) throw new ReportFileError("invalid", "This preview link is not valid, or its deployment was deleted. Ask for a new review, or download the report from the pull request or workflow run.");
|
||||
if (!response.ok || !response.body) throw new ReportFileError("invalid", `The report could not be downloaded (HTTP ${response.status}).`);
|
||||
const total = Number(response.headers.get("content-length")) || undefined;
|
||||
const reader = response.body.getReader();
|
||||
const chunks: BlobPart[] = [];
|
||||
let loaded = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
loaded += value.byteLength;
|
||||
this.progressed({ phase: "downloading", loaded, ...(total ? { total } : {}) });
|
||||
}
|
||||
this.set({ ...this.snapshot, status: "opening", progress: { phase: "verifying" } });
|
||||
const archive = await openReportBlob(new Blob(chunks, { type: "application/zip" }), undefined, { fileName: "report.zip", onProgress: this.progressed });
|
||||
this.data = archive.data;
|
||||
this.set({ status: "ready", progress: this.snapshot.progress, identity: archive.identity });
|
||||
} catch (error) {
|
||||
if (generation !== this.generation) return;
|
||||
this.set({ ...this.snapshot, status: "failed",
|
||||
this.set({ status: "failed", progress: this.snapshot.progress,
|
||||
error: error instanceof Error && error.message ? error.message : "The report could not be downloaded.",
|
||||
errorCode: error instanceof ReportFileError ? error.code : "invalid" });
|
||||
}
|
||||
}
|
||||
|
||||
private adopt(key: string, archive: ArtifactReportArchive): void {
|
||||
this.remember(key, archive);
|
||||
showArchive(archive);
|
||||
this.data = archive.data;
|
||||
this.current = key;
|
||||
this.set({ ...this.snapshot, status: "ready", identity: archive.identity });
|
||||
this.schedulePrefetch();
|
||||
}
|
||||
|
||||
/** An opened report is known by the key that selected it and by the target it says it is. */
|
||||
private remember(key: string, archive: ArtifactReportArchive): void {
|
||||
this.archives.set(key, archive);
|
||||
const own = archiveTarget(archive);
|
||||
if (own && !this.archives.has(own)) this.archives.set(own, archive);
|
||||
}
|
||||
|
||||
/** One download per target, shared between a switch and the prefetch. */
|
||||
private loadTarget(target: string | undefined, onProgress?: (progress: ArtifactLoadProgress) => void): Promise<ArtifactReportArchive> {
|
||||
const key = target ?? "";
|
||||
const listeners = this.loadingProgress.get(key) ?? new Set();
|
||||
this.loadingProgress.set(key, listeners);
|
||||
if (onProgress) listeners.add(onProgress);
|
||||
let pending = this.loading.get(key);
|
||||
if (!pending) {
|
||||
pending = this.fetchTarget(target, progress => { for (const listener of listeners) listener(progress); })
|
||||
.finally(() => { this.loading.delete(key); this.loadingProgress.delete(key); });
|
||||
this.loading.set(key, pending);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async fetchTarget(target: string | undefined, onProgress?: (progress: ArtifactLoadProgress) => void): Promise<ArtifactReportArchive> {
|
||||
const { token } = this.preview!;
|
||||
const chunks = await this.download(previewManifestUrl(token, target), onProgress);
|
||||
onProgress?.({ phase: "opening" });
|
||||
let manifest: unknown;
|
||||
try { manifest = JSON.parse(await new Blob(chunks).text()); }
|
||||
catch { throw new ReportFileError("invalid", "The hosted report manifest is not valid JSON."); }
|
||||
return ArtifactReportArchive.openManifest(manifest, path => previewAssetUrl(token, path, target));
|
||||
}
|
||||
|
||||
/** The Worker's answer for this link: the bytes, or why there are none. */
|
||||
private async download(url: string, onProgress?: (progress: ArtifactLoadProgress) => void): Promise<BlobPart[]> {
|
||||
let response = await fetch(url, { credentials: "same-origin" });
|
||||
// A 503 is the Worker not reading the report this time; the next request usually does.
|
||||
if (response.status >= 500) response = await fetch(url, { credentials: "same-origin" });
|
||||
if (response.status === 410) throw new ReportFileError("invalid", `This preview link expired${await expiredOn(response)}. Download the report from the pull request or workflow run instead, or rerun Explore for a fresh link.`);
|
||||
if (response.status === 413) throw new ReportFileError("too-large", "This report is too large to open from a hosted link. Download it from the pull request or workflow run instead, and drop it on the Viewer.");
|
||||
if (response.status === 404) throw new ReportFileError("invalid", "This preview link is not valid, or its deployment was deleted. Ask for a new review, or download the report from the pull request or workflow run.");
|
||||
if (!response.ok || !response.body) throw new ReportFileError("invalid", `The report could not be downloaded (HTTP ${response.status}).`);
|
||||
const total = Number(response.headers.get("content-length")) || undefined;
|
||||
const tooLarge = () => new ReportFileError("too-large", "This report's index is larger than the Viewer opens. Download the report from the pull request or workflow run instead.");
|
||||
if (total && total > MAX_MANIFEST_BYTES) throw tooLarge();
|
||||
const reader = response.body.getReader();
|
||||
const chunks: BlobPart[] = [];
|
||||
let loaded = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
loaded += value.byteLength;
|
||||
// Stop reading before parsing what the ZIP path would have rejected unread.
|
||||
if (loaded > MAX_MANIFEST_BYTES) { void reader.cancel(); throw tooLarge(); }
|
||||
onProgress?.({ phase: "downloading", loaded, ...(total ? { total } : {}) });
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/** Once the shown report is ready, fetch the deployment's other targets so switching needs no download. */
|
||||
private schedulePrefetch(): void {
|
||||
if (this.prefetched || !this.preview || typeof window === "undefined") return;
|
||||
this.prefetched = true;
|
||||
const connection = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection;
|
||||
if (connection?.saveData) return;
|
||||
window.setTimeout(() => { void this.prefetch(); }, PREFETCH_DELAY);
|
||||
}
|
||||
|
||||
private async prefetch(): Promise<void> {
|
||||
const url = previewReportsUrl(new URL(window.location.href));
|
||||
if (!url) return;
|
||||
let targets: string[];
|
||||
try {
|
||||
const response = await fetch(url, { credentials: "same-origin" });
|
||||
const list: unknown = response.ok ? await response.json() : undefined;
|
||||
targets = Array.isArray(list)
|
||||
? list.map(entry => (entry && typeof entry === "object" ? (entry as { target?: unknown; platform?: unknown }).target ?? (entry as { platform?: unknown }).platform : undefined)).filter(isReportTargetId)
|
||||
: [];
|
||||
} catch { return; }
|
||||
for (const target of targets) {
|
||||
if (this.archives.has(target)) continue;
|
||||
try {
|
||||
// A switch may have joined this download and shown the archive already; only a second copy is closed.
|
||||
const archive = await this.loadTarget(target);
|
||||
const known = this.archives.get(target);
|
||||
if (!known) this.remember(target, archive);
|
||||
else if (known !== archive) archive.dispose();
|
||||
} catch { /* A switch downloads it then. */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** Open the ZIP the reviewer dropped or chose; it must be the linked run's report when there is one. */
|
||||
async openFile(file: File): Promise<void> {
|
||||
if (!this.canRetry || this.snapshot.status === "opening" || this.snapshot.status === "ready" || this.pending) return;
|
||||
const identity = this.linkIdentity;
|
||||
const linked = identity ? { identity } : {};
|
||||
// A fresh snapshot: a failed drop's error must not show while the next file opens.
|
||||
const { reportKey } = this.snapshot;
|
||||
this.set({ status: "opening", progress: { phase: "verifying" }, ...linked, fileName: file.name, reportKey });
|
||||
this.set({ status: "opening", progress: { phase: "verifying" }, ...linked, fileName: file.name });
|
||||
try {
|
||||
const archive = await openReportFile(file, identity, this.progressed);
|
||||
this.data = archive.data;
|
||||
this.set({ status: "ready", progress: this.snapshot.progress, identity: archive.identity, fileName: file.name, reportKey });
|
||||
this.set({ status: "ready", progress: this.snapshot.progress, identity: archive.identity, fileName: file.name });
|
||||
} catch (error) {
|
||||
this.set({ status: "failed", progress: this.snapshot.progress, ...linked, fileName: file.name, reportKey,
|
||||
this.set({ status: "failed", progress: this.snapshot.progress, ...linked, fileName: file.name,
|
||||
error: error instanceof Error && error.message ? error.message : "The report could not be opened.",
|
||||
errorCode: error instanceof ReportFileError ? error.code : "invalid" });
|
||||
}
|
||||
@@ -288,18 +137,10 @@ export class ReportSource {
|
||||
/** Clear a failed drop so another file can be chosen. */
|
||||
retry(): void {
|
||||
if (this.snapshot.status !== "failed" || !this.canRetry) return;
|
||||
this.set({ status: "awaiting-file", progress: { phase: "cache" }, reportKey: this.snapshot.reportKey, ...(this.linkIdentity ? { identity: this.linkIdentity } : {}) });
|
||||
this.set({ status: "awaiting-file", progress: { phase: "cache" }, ...(this.linkIdentity ? { identity: this.linkIdentity } : {}) });
|
||||
}
|
||||
}
|
||||
|
||||
/** The target an opened report says it is: its run's target id, or the platform of a report from before targets. */
|
||||
function archiveTarget(archive: ArtifactReportArchive): string | undefined {
|
||||
const run = archive.data.exploration?.map.run as { target?: { id?: unknown }; platform?: unknown } | undefined;
|
||||
const runtime = (archive.data.publicReview as { runtime?: { target?: { id?: unknown }; platform?: unknown } } | undefined)?.runtime;
|
||||
const id = run?.target?.id ?? run?.platform ?? runtime?.target?.id ?? runtime?.platform;
|
||||
return isReportTargetId(id) ? id : undefined;
|
||||
}
|
||||
|
||||
export const REPORT_SOURCE = new ReportSource(typeof window === "undefined" ? undefined : new URL(window.location.href));
|
||||
|
||||
/** " on Oct 10, 2026" from the 410 body's `expiredAt`, or "" when it is missing or malformed. */
|
||||
|
||||
Reference in new issue
Block a user