Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
150a70c361 | ||
|
|
b0a500eb72 | ||
|
|
c59ccce32b | ||
|
|
5cbb4f7da9 | ||
|
|
c24049c443 | ||
|
|
d229410312 | ||
|
|
10c8820988 | ||
|
|
50fb56f387 | ||
|
|
871310eaf7 | ||
|
|
9a53b1d032 |
No files matched your search
@@ -3,29 +3,29 @@
|
||||
Explore maps your app: a screenshot of every screen, connected by the taps between them. On each pull request it captures the screens the PR changes, before and after, on EAS Simulator, and posts a visual review. On your Mac it can also run on a local simulator.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-hero-dark.png">
|
||||
<img alt="Explore's Map of a euxy pull request, zoomed in on the new About screen, marked Added among the modified Patterns screens, with its transitions highlighted and the Inspector open on it, shown as a window on a soft stage" src="docs/screenshots/readme-hero-light.png">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-hero-dark.svg">
|
||||
<img alt="Explore's Map of a euxy pull request, animated: the screen cards appear row by row, the new About screen marked Added among the modified Patterns screens, the transitions between them wipe in, then a click selects About, its transitions light up and the Inspector slides in on it, shown as a window on a soft stage" src="docs/screenshots/readme-hero-light.svg">
|
||||
</picture>
|
||||
|
||||
**See a real report:** [euxy](https://explore-example--euxy.expo.app/p/rfcoic27ccgnrmzgijubxkmuzmptcrva?platform=ios), a MIDI sequencer, reviewed by Explore. It is redeployed with the current Viewer on every merge to main.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-compare-dark.svg">
|
||||
<img alt="The euxy Patterns screen wiping from its capture before the pull request to its capture after it: each pattern row's tempo moves out of the subtitle into its own column on the right, then the changed subtitles are outlined" src="docs/screenshots/readme-compare-light.svg">
|
||||
</picture>
|
||||
|
||||
**Compare**: each changed screen before and after, with the changed regions outlined.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-compare-dark.png">
|
||||
<img width="100%" alt="The Compare view with the euxy Patterns screen's before and after captures side by side: each pattern row's tempo moved out of the subtitle into its own column on the right, the changed subtitles outlined in both" src="docs/screenshots/readme-compare-light.png">
|
||||
</picture>
|
||||
<strong>Compare</strong>: each changed screen before and after, with the changed regions outlined.
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<td width="50%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-screens-dark.png">
|
||||
<img width="100%" alt="The Screens view of a euxy review: the app/ route tree on the left under Changed 9 and All 19, and a grid of screen cards beside it in the same order, each with its route below the screenshot and a dot before it: green for the new /about, orange for modified screens such as /activity-log, /settings and /patterns, red for the removed /channel-surf" src="docs/screenshots/readme-screens-light.png">
|
||||
</picture>
|
||||
<strong>Screens</strong>: every capture in one grid, beside the route tree, with a dot for what changed.
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<td width="50%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-pr-comment-dark.png">
|
||||
<img width="100%" alt="Explore's GitHub PR comment on a euxy PR: the heading links to the iOS and Android reports, a table with one row per platform giving device, result and an Open link, the Added, Removed, Modified, Needs review and Source-affected screens as collapsed lists, fading out below them" src="docs/screenshots/readme-pr-comment-light.png">
|
||||
@@ -80,7 +80,10 @@ describes, never for a password in chat. Open the report, and if I need to log i
|
||||
something first, tell me the command.
|
||||
```
|
||||
|
||||
You need Node.js 24.12+. Reviewing a change needs an Expo account and an Expo SDK 57+ app with Expo Router or React Navigation: it is built on EAS and captured on EAS Simulator ([join the waitlist](https://expo.dev/services/simulators)) or, with Xcode, on a simulator on your Mac. Exploring a build needs a Claude Code or Codex login, and EAS Simulator or a simulator on your Mac; on your Mac, no Expo account. No API keys, no CI.
|
||||
You need Node.js 24.12+. Reviewing a change needs an Expo account and an Expo SDK 57+ app with Expo Router or React Navigation: it is built on EAS and captured on EAS Simulator or, with Xcode, on a simulator on your Mac. Exploring a build needs a Claude Code or Codex login, and EAS Simulator or a simulator on your Mac; on your Mac, no Expo account. No API keys, no CI.
|
||||
|
||||
> [!NOTE]
|
||||
> EAS Simulator is in preview. [Join the waitlist](https://expo.dev/services/simulators), or pass `--simulator local` to capture on a simulator on your Mac.
|
||||
|
||||
<details>
|
||||
<summary><strong>Run it yourself</strong></summary>
|
||||
@@ -123,6 +126,9 @@ Explore starts an EAS Simulator, installs the build, taps through the app with y
|
||||
|
||||
</details>
|
||||
|
||||
> [!WARNING]
|
||||
> A review runs both commits' code on your machine, as you: it installs their dependencies, evaluates the app config and bundles the JavaScript. Review only commits you would run yourself, and someone else's branch only if you trust it.
|
||||
|
||||
Every run is kept on your machine for 30 days. `npx @expo/explore reports` lists your local reviews, explorations and uploaded reports with their commits, and reopens or hosts one without capturing again:
|
||||
|
||||
<picture>
|
||||
@@ -141,7 +147,6 @@ npx @expo/explore capture --base v1.3.0 --head v1.4.0 --scope all --upload
|
||||
|
||||
- It checks out both commits as temporary worktrees, installs their dependencies, captures every configured platform or [target](#targets) on EAS Simulator or a [local simulator](#simulator), and opens the report in a local Viewer. `--target` or `--platform` picks some; they run at once, at most `--parallel N` at a time. `--upload` hosts it for 30 days (`--expires-in` changes that) and prints the link; `report:upload <report.zip>` hosts one you already have.
|
||||
- Your checkout, index and branches are never touched. Your uncommitted changes, untracked files included, are reviewed as `eas build` would upload them; `--committed`, or `cli.requireCommit: true` in `eas.json`, leaves them out.
|
||||
- It runs both commits' code on your machine, as you: installing their dependencies, evaluating the app config, and bundling the JavaScript. That is what checking them out and running them would do, so review only commits you would run, and someone else's branch only if you trust it.
|
||||
- Installs run without credential environment variables, which keeps tokens out of reach of a registry a commit's `.npmrc` names; that is not a sandbox. A registry that needs `${NPM_TOKEN}` in the project's `.npmrc` must be authenticated in your own `~/.npmrc`.
|
||||
- Captures are cached in `~/.cache/expo-explore`, so the same base is not captured twice (`--no-cache` skips it); a capture unused for 30 days goes, and the cache stays under 2 GB. Ctrl+C stops the run's simulator sessions and local devices; when a run is stopped harder than that, the next local run stops what it left running.
|
||||
- Like a CI review, it builds on EAS (reusing a matching build) and, unless it captures on a local simulator, runs EAS Simulator sessions: expect several minutes and EAS usage.
|
||||
@@ -512,11 +517,28 @@ curl -s "$LINK/api/v1/screens?status=modified" | jq '.items[] | {route, status,
|
||||
<details>
|
||||
<summary><strong>How it works</strong></summary>
|
||||
|
||||
1. The review workflow runs on open, non-draft PRs from the repository whose author has write access. Bots such as Devin go under `ci.trustedAuthors` in `.expo-explore/config.yaml`.
|
||||
2. Explore reads the diff and your router source to pick the affected screens.
|
||||
3. It builds both revisions on EAS (reusing a build with the same native fingerprint) and captures each screen on EAS Simulator (or, on your machine, a local simulator), reusing a baseline of the base commit when one exists. If EAS fails to start a session, Explore starts a new one, up to five times within 30 minutes.
|
||||
4. It compares the captures. A screen with a source change is **Modified** if its captures differ.
|
||||
5. It uploads the report to GitHub Actions and posts a PR comment.
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant PR as Pull request
|
||||
participant GA as GitHub Actions
|
||||
participant B as EAS Build
|
||||
participant S as EAS Simulator
|
||||
PR->>GA: opened or updated
|
||||
GA->>GA: read the diff and router source, pick the affected screens
|
||||
GA->>B: build base and head
|
||||
Note over B: reuses a build with the same native fingerprint
|
||||
B-->>GA: simulator builds
|
||||
GA->>S: capture each affected screen, in each appearance
|
||||
Note over S: the base reuses its baseline when one exists
|
||||
S-->>GA: screenshots
|
||||
GA->>GA: compare the captures, outline the changed regions
|
||||
GA->>PR: upload the report, comment with its links
|
||||
```
|
||||
|
||||
- The review workflow runs on open, non-draft PRs from the repository whose author has write access. Bots such as Devin go under `ci.trustedAuthors` in `.expo-explore/config.yaml`.
|
||||
- A screen with a source change is **Modified** if its captures differ.
|
||||
- If EAS fails to start a session, Explore starts a new one, up to five times within 30 minutes. On your machine, a local simulator can stand in for EAS Simulator.
|
||||
|
||||
The same review runs for any two commits without a PR ([`explore-compare.yml`](#compare-any-two-commits), linking the report from the run summary) and on your machine (`capture`, [above](#quick-start)). The workflows' logic lives in `expo-explore ci:*` commands, so a fix reaches CI with the `@expo/explore` version the workflows pin.
|
||||
|
||||
|
||||
@@ -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 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.
|
||||
- *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.
|
||||
- *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.
|
||||
|
||||
@@ -362,6 +362,16 @@ Capture uses the automatic GitHub token with `pull-requests: write`, so it can k
|
||||
|
||||
The sticky comment is one comment for the whole run: a header with the base and head commits, one row per captured platform (device, result, **Open** / **zip** / **run** links), every changed screen listed once with a link per platform, and a collapsed validation table with one column per platform. Each platform's job updates only its own hidden record in the comment, so iOS and Android jobs never overwrite each other. When a new run starts (a push, a rerun), the earlier run moves to a collapsed **Previous runs** list that keeps its head commit, result, report and run links; the last five runs are kept. A run that finishes after the PR moved on is still published, under previous runs, instead of failing. The failure job posts through the same renderer (`ci:failure`), so a crash before the pipeline's own comment still lands in that platform's row.
|
||||
|
||||
The comment can also draw a map of the change: the added, removed and visually changed screens, the screens one step before them, and the transitions among them, as a collapsed Mermaid flowchart that GitHub draws in place. It is off by default; turn it on with:
|
||||
|
||||
```yaml
|
||||
report:
|
||||
comment:
|
||||
map: true # default false
|
||||
```
|
||||
|
||||
The map leaves out screens whose source changed but whose captures match, and it is skipped when more than 30 routes changed or when the comment would be over GitHub's size limit.
|
||||
|
||||
PR review links always use [explore-preview.expo.app](https://explore-preview.expo.app/); no viewer-origin variable is needed or accepted by the CI publisher. Reports stay in GitHub Actions: the comment's **zip** link fetches the `explore-review-<run>-<attempt>.zip` artifact (GitHub asks for sign-in and repository read access), and the page that **Open** opens takes that ZIP by drag-and-drop or **Choose file**. Nothing is enabled per repository on Expo's side. See [report access](private-review.md).
|
||||
|
||||
Credentialed capture accepts open, non-draft, same-repository PRs whose authors have current write access, or are listed under `ci.trustedAuthors` in the default branch's `.expo-explore/config.yaml` (for bots such as `devin-ai-integration[bot]`). Fork PRs cannot receive capture credentials. Tools are loaded from the pinned reviewed commit, not the PR checkout. Build execution still runs the authorized application's code.
|
||||
|
||||
|
Before Width: | Height: | Size: 451 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 600" width="1000" height="600" role="img" aria-label="The /patterns screen of euxy wiping from its capture before the pull request to its capture after it, with the changed regions outlined"><style>.after{animation:wipe 7s cubic-bezier(.65,0,.35,1) infinite}@keyframes wipe{0.00%{clip-path:inset(0 100% 0 0)}14.29%{clip-path:inset(0 100% 0 0)}37.14%{clip-path:inset(0 0 0 0)}82.86%{clip-path:inset(0 0 0 0)}97.14%{clip-path:inset(0 100% 0 0)}100.00%{clip-path:inset(0 100% 0 0)}}.divider{opacity:0;animation:divider 7s cubic-bezier(.65,0,.35,1) infinite}@keyframes divider{0.00%{transform:translateX(0);opacity:0}11.43%{transform:translateX(0);opacity:1}14.29%{transform:translateX(0);opacity:1}37.14%{transform:translateX(248px);opacity:1}41.43%{transform:translateX(248px);opacity:0}82.86%{transform:translateX(248px);opacity:0}85.71%{transform:translateX(248px);opacity:1}97.14%{transform:translateX(0);opacity:1}100.00%{transform:translateX(0);opacity:0}}.regions{animation:regions 7s ease-in-out infinite}@keyframes regions{0.00%{opacity:0}38.57%{opacity:0}44.29%{opacity:1}51.43%{opacity:.3}58.57%{opacity:1}81.43%{opacity:1}85.71%{opacity:0}100.00%{opacity:0}}.before-label{opacity:.3;animation:before-label 7s linear infinite}.after-label{animation:after-label 7s linear infinite}@keyframes before-label{0.00%{opacity:1}25.71%{opacity:1}28.57%{opacity:.3}88.57%{opacity:.3}91.43%{opacity:1}100.00%{opacity:1}}@keyframes after-label{0.00%{opacity:.3}25.71%{opacity:.3}28.57%{opacity:1}88.57%{opacity:1}91.43%{opacity:.3}100.00%{opacity:.3}}@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style><defs><clipPath id="stage"><rect width="1000" height="600" rx="16"/></clipPath><clipPath id="phone"><rect x="376" y="30" width="248" height="540" rx="40"/></clipPath><filter id="shadow" x="-20%" y="-20%" width="140%" height="140%"><feDropShadow dx="0" dy="8" stdDeviation="14" flood-color="rgba(1,4,9,0.6)"/></filter></defs><g clip-path="url(#stage)"><rect width="1000" height="600" fill="#151B23"/><rect x="376" y="30" width="248" height="540" rx="40" fill="#151B23" filter="url(#shadow)"/><g clip-path="url(#phone)"><image href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAYEBAUEBAYFBQUGBgYHCQ4JCQgICRINDQoOFRIWFhUSFBQXGiEcFxgfGRQUHScdHyIjJSUlFhwpLCgkKyEkJST/2wBDAQYGBgkICREJCREkGBQYJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCT/wAARCANqAZIDASIAAhEBAxEB/8QAHAABAAICAwEAAAAAAAAAAAAAAAMFBAYBAgcI/8QAWBAAAQMDAQQECwQHBAUKBQQDAQACAwQFERIGEyExFEFR0QcVIjJSU2GBkZKTNFRxsQgjM2OhouEWQmLBJHJ1gtIYNkNVVrKz1OLwFzdzlJUmNThEg8Px/8QAGAEBAQEBAQAAAAAAAAAAAAAAAAEDAgT/xAAdEQEBAAMBAAMBAAAAAAAAAAAAEQECAwQSMUFR/9oADAMBAAIRAxEAPwD5UREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBFs2wdn2aut0kftXeZrbbaZgkdHTRa6ircXACKIHgHHOdTuAAXptz8CuzVB4X9sLRPUXCHZPZS3suVSWva6olbuI37priManOecHHIY9qDwxF6dtdsfspd/B5Dt9sZT19sp4Lj4suNurZxPuXFupkrHhoJaRwII5nhy449DsjsFs/tZc6faXa2K8Wm3UQqIDZ8g3KcgEQNeQQzBJy49nUeQecovVdtdiNjpdktlNsrGa/Z2gvVdJQ1NLXvNTuGscA6eNzWhz2AZyMZzwCu6fYTwZbVWvaaLZ2j2lo4rHbpa2n2jrZR0atdHgBroyxujWT5IB1ezIwg8PREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEReh+C3YDZbaenr7xthtdDZLXb3sjdSwDXW1TneaImYPPB4gO4jl1oPPEX0xUeDTwVMt5kqvB34VrbQacm7vpc7tvrHMy4hvXnR7l414T9iLNsXdaQbP7U0O0druEHSaeaA4ljZnGmVv913A+3gcgckGmIvQPA/4M5PCZtDFao5IY3SF+XzaiyJjG5c4hpBceLQACOJ4ngve/wDkWUn/AGlt3/4qf/ziD5ERfXf/ACLKT/tJbv8A8VP/AOcXgHhU8GtT4P8AaOstGGSvpHfrHQajG5hYx7ZAHZLQQ8Agk4IPEhBoaIiAiIgIiICIiAiIgIiIJaRwZVQucQAHtJJ6uK+jL54QNlLp4afCLQTXyljsW1tqit8F2YdcMM7aeIMc4j+4HBwJ6j2DJXzciD17aipsuwXgiOwlNtBar/d7rdm3GsltMxmp6eBjNLGCTABeSM+zjnqzjbJbPeC7a3wkSOddp9ntkKWGObc3ioa2eqeAAYg9uQ0F2SSMkDlgnh5UiD2HwsNprxe7Vc7xtlsxWWKKojoIbTs1O6R1so+JJjY6NoOA3ieZcR1YxttnqLBsfZ7xS3vwmWLarYQ0M8dssYeZqt0jsmI7osG4e0k+UCME9XV84ogIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgszQ2/pMEfTsxvYS93onsURpaPo1TJ0r9ZHIWxtx57e1YKIMuvp6aDddGqN9qbl3+ErI2a2iuGyV+ob7aZWRV1DKJYXPYHgEdoPAjGQqxEH0HV+HF9u2Lt+1Nr8I21VXttUTaaq01W7dQMx553OjS1mCNJack9mDjwKsq5q+rnq6l+ueeR0sjsAanOOScDgOJ6lCiD1DwD+Eel8HG1ENzqoRPGzeMki3jY3Pje0AlrnEN1AtacOIBGeIX0t/yuNiP+rLz9eg/80vhlEH3N/wArjYj/AKsvP16D/wA0vmbwzeEwbb7WXC7UDRTMrf1Zia9shZCGRsDXOHAuOgk6SQMgZPFeZIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIilhpZ6jO6ie/HMgcB+JQRIsw2qrAzu2fUb3rHlp5YDiSNzOzI5oI0REBERARSw0s9RndRPfjmQOA/Eqc2qLine truncated
|
||||
|
After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 452 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 600" width="1000" height="600" role="img" aria-label="The /patterns screen of euxy wiping from its capture before the pull request to its capture after it, with the changed regions outlined"><style>.after{animation:wipe 7s cubic-bezier(.65,0,.35,1) infinite}@keyframes wipe{0.00%{clip-path:inset(0 100% 0 0)}14.29%{clip-path:inset(0 100% 0 0)}37.14%{clip-path:inset(0 0 0 0)}82.86%{clip-path:inset(0 0 0 0)}97.14%{clip-path:inset(0 100% 0 0)}100.00%{clip-path:inset(0 100% 0 0)}}.divider{opacity:0;animation:divider 7s cubic-bezier(.65,0,.35,1) infinite}@keyframes divider{0.00%{transform:translateX(0);opacity:0}11.43%{transform:translateX(0);opacity:1}14.29%{transform:translateX(0);opacity:1}37.14%{transform:translateX(248px);opacity:1}41.43%{transform:translateX(248px);opacity:0}82.86%{transform:translateX(248px);opacity:0}85.71%{transform:translateX(248px);opacity:1}97.14%{transform:translateX(0);opacity:1}100.00%{transform:translateX(0);opacity:0}}.regions{animation:regions 7s ease-in-out infinite}@keyframes regions{0.00%{opacity:0}38.57%{opacity:0}44.29%{opacity:1}51.43%{opacity:.3}58.57%{opacity:1}81.43%{opacity:1}85.71%{opacity:0}100.00%{opacity:0}}.before-label{opacity:.3;animation:before-label 7s linear infinite}.after-label{animation:after-label 7s linear infinite}@keyframes before-label{0.00%{opacity:1}25.71%{opacity:1}28.57%{opacity:.3}88.57%{opacity:.3}91.43%{opacity:1}100.00%{opacity:1}}@keyframes after-label{0.00%{opacity:.3}25.71%{opacity:.3}28.57%{opacity:1}88.57%{opacity:1}91.43%{opacity:.3}100.00%{opacity:.3}}@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style><defs><clipPath id="stage"><rect width="1000" height="600" rx="16"/></clipPath><clipPath id="phone"><rect x="376" y="30" width="248" height="540" rx="40"/></clipPath><filter id="shadow" x="-20%" y="-20%" width="140%" height="140%"><feDropShadow dx="0" dy="8" stdDeviation="14" flood-color="rgba(17,17,17,0.14)"/></filter></defs><g clip-path="url(#stage)"><rect width="1000" height="600" fill="#F6F8FA"/><rect x="376" y="30" width="248" height="540" rx="40" fill="#F6F8FA" filter="url(#shadow)"/><g clip-path="url(#phone)"><image href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAYEBAUEBAYFBQUGBgYHCQ4JCQgICRINDQoOFRIWFhUSFBQXGiEcFxgfGRQUHScdHyIjJSUlFhwpLCgkKyEkJST/2wBDAQYGBgkICREJCREkGBQYJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCT/wAARCANqAZIDASIAAhEBAxEB/8QAHQABAAEFAQEBAAAAAAAAAAAAAAECAwQFBgcICf/EAFkQAAEDAwICBwQHBAYFCgQDCQEAAgMEBREGEiExBxMUQVFSkSIyYaEVM1NxgZLhCCNisRgkNELR0xZWlJXBJTdDcnN1gqKz8Bdjk9QmNTY4RlV0g4Sy0vH/xAAYAQEBAQEBAAAAAAAAAAAAAAAAAQIDBP/EABoRAQEBAQEBAQAAAAAAAAAAAAARAQIDIQT/2gAMAwEAAhEDEQA/APpxERFEREBERAREQEREBERAREQEREBERARYl0u9uslI6sulfSUFMz3pqmVsbB+LiAuCuH7RnRXbZDHNq6mkcOH9XgmmHqxhHzQekIvKv6UPRP8A6zSf7vqf8tP6UPRP/rNJ/u+p/wAtB6qi8q/pQ9E/+s0n+76n/LT+lD0T/wCs0n+76n/LQeqovKv6UPRP/rNJ/u+p/wAtP6UPRP8A6zSf7vqf8tB6qi8q/pQ9E/8ArNJ/u+p/y0/pQ9E/+s0n+76n/LQeqovKv6UPRP8A6zSf7vqf8tP6UPRP/rNJ/u+p/wAtB6qi8vpv2mOiipeGN1W1hP2lFUMHqY8Lt9O6z03q2IyWG+W65hoy4U07XuZ/1mg5H4hBuUREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBFq9TXK4Wix1NZabTJeK9m1sFFHIIzK9zg0ZceDWjOSe4Aryaz9NOobTofXl91ZTW2W4aauLqCKChDmxPkO1rW5JJI3uHHngIPbUXkdFq/X+jdTaYpNcVFor6DUzzTf1KndC+3VRbubHkuO9p93J48M93HprprLVD7Vqf6F0ZXPudrnbTW9lW5rIrhuIHWtOR7DcknjxAxnOQA7ZF5PZ9Va6030lWLSOqrjZ73HfaSeoD6GmMD6F0TdxyMndGfdBOCT4YwadM9I2trl0s02nb9Z6KzWyutUlxpqPcZKpjWybGmVwO0OOCdoHAEDOcoPWkREBERAXE9LvSdQ9FWkZbzUMbUVkrupoqUnHXSkZ4+DQOJP4cyF2y+MP2wtRT3LpIpbNvPZrVRM2s7usk9pzvxb1Y/BB5NrLXWodfXZ901DcpqyZxOxhOI4R5WN5NH3fjkrQIiIIiICIiAiIgIiICIiAsm3XKttFbFXW+rno6qF26OaCQsew+II4hYyIPtX9nDp2m6RaaTTuopGfT9HH1kc4AaK2IcCcDgHt4ZxzBz3Fe5L83ujTUU+k9f2C8wPLDTVsW/H96Nztr2/i0uH4r9IUUREQEREBEXn/AEn681RpmooLRpHSc15udwY97aqc7KKla3mZH5HLI4Et4Hn3IPQEXzbT9JHSk+vEdL0g9Flyrt3C0sqcb3fZtfhoLu7G/wDFew9GetbxrK11Zv8Apiu09c6Cfs1RDOMxSOxndE7+83iPhxGCeaDsUXBdLnSTH0bWCW6SRyyNjDcMh2h8r3uw1oLgQ0cHEkg8BwHFeEf0y6r/AFcuH+9IP/tEH1oi+TP6ZdV/q5cP96Qf/aL3rou6R6bXunaS7ZfEyrb+7bPtEjXhz2ujJbgOILCQQBkEcAUHcoiICIiAiIgIiICIiAiIgLwGp6ML/qTSPSxZ+xS0lVdL/JXW0zjY2oDHMe0tJ4YdtLc8uK9+RB4pPUak6WdV6LbU6RvNgpNP1QudznuUIiY6oY3DI4eJ6wF2fa8F2t0uut9MWrVF1qKCl1AWTA2S321jhMYzhoEue8E5OM8A74AdsiDxHogq7jBqB9x1Lo3V79U3r2a281tGxlLSsALhDH7ZLIhgAcMuOCe7HS3CxXOT9oK13xlDO62Radlpn1Yb+7bKZiQwnxxxwvSUQEREBERAXxV+19Yprd0ox3NzD1FzoYnsf3FzMsc37wA0/wDiC+1VLine truncated
|
||||
|
After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 847 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" width="1600" height="900" role="img" aria-label="Explore's Map of a euxy pull request: the screen cards appear row by row, the transitions between them wipe in, then a click selects /about and the Inspector opens on it"><style>.c0{transform-origin:0 0;animation:c0 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c0{0.00%{opacity:0;transform:scale(.92)}4.33%{opacity:0;transform:scale(.92)}8.08%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c1{transform-origin:0 0;animation:c1 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c1{0.00%{opacity:0;transform:scale(.92)}4.00%{opacity:0;transform:scale(.92)}7.75%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c2{transform-origin:0 0;animation:c2 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c2{0.00%{opacity:0;transform:scale(.92)}4.67%{opacity:0;transform:scale(.92)}8.42%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c3{transform-origin:0 0;animation:c3 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c3{0.00%{opacity:0;transform:scale(.92)}6.08%{opacity:0;transform:scale(.92)}9.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c4{transform-origin:0 0;animation:c4 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c4{0.00%{opacity:0;transform:scale(.92)}6.41%{opacity:0;transform:scale(.92)}10.16%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c5{transform-origin:0 0;animation:c5 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c5{0.00%{opacity:0;transform:scale(.92)}6.75%{opacity:0;transform:scale(.92)}10.50%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c6{transform-origin:0 0;animation:c6 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c6{0.00%{opacity:0;transform:scale(.92)}7.08%{opacity:0;transform:scale(.92)}10.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c7{transform-origin:0 0;animation:c7 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c7{0.00%{opacity:0;transform:scale(.92)}3.66%{opacity:0;transform:scale(.92)}7.41%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c8{transform-origin:0 0;animation:c8 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c8{0.00%{opacity:0;transform:scale(.92)}7.41%{opacity:0;transform:scale(.92)}11.16%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c9{transform-origin:0 0;animation:c9 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c9{0.00%{opacity:0;transform:scale(.92)}7.75%{opacity:0;transform:scale(.92)}11.50%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c10{transform-origin:0 0;animation:c10 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c10{0.00%{opacity:0;transform:scale(.92)}8.08%{opacity:0;transform:scale(.92)}11.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c11{transform-origin:0 0;animation:c11 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c11{0.00%{opacity:0;transform:scale(.92)}8.42%{opacity:0;transform:scale(.92)}12.17%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.full{animation:full 12s cubic-bezier(.45,0,.25,1) infinite}@keyframes full{0.00%{clip-path:inset(0 0 100% 0)}10.83%{clip-path:inset(0 0 100% 0)}21.67%{clip-path:inset(0 0 0 0)}100.00%{clip-path:inset(0 0 0 0)}}.ptr{opacity:0;animation:ptr 12s cubic-bezier(.4,0,.2,1) infinite}@keyframes ptr{0.00%{opacity:0;transform:translate(978.5px,714.0px)}25.83%{opacity:0;transform:translate(978.5px,714.0px)}27.50%{opacity:1;transform:translate(978.5px,714.0px)}35.83%{opacity:1;transform:translate(718.5px,505.2px)}36.67%{opacity:1;transform:translate(718.5px,505.2px) scale(.82)}37.92%{opacity:1;transform:translate(718.5px,505.2px)}45.83%{opacity:0;transform:translate(718.5px,505.2px)}100.00%{opacity:0;transform:translate(718.5px,505.2px)}}.sel{animation:sel 12s ease-out infinite}@keyframes sel{0.00%{opacity:0}36.67%{opacity:0}39.17%{opacity:1}100.00%{opacity:1}}.insp{animation:insp 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes insp{0.00%{opacity:0;transform:translateX(48px)}37.08%{opacity:0;transform:translateX(48px)}42.08%{opacity:1;transform:translateX(0)}100.00%{opacity:1;transform:translateX(0)}}.cover{opacity:0;animation:cover 12s linear infinite}@keyframes cover{0.00%{opacity:1}1.67%{opacity:0}94.17%{opacity:0}100.00%{opacity:1}}@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style><defs><image id="empty" width="1376" height="774" href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAALine truncated
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 830 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" width="1600" height="900" role="img" aria-label="Explore's Map of a euxy pull request: the screen cards appear row by row, the transitions between them wipe in, then a click selects /about and the Inspector opens on it"><style>.c0{transform-origin:0 0;animation:c0 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c0{0.00%{opacity:0;transform:scale(.92)}4.33%{opacity:0;transform:scale(.92)}8.08%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c1{transform-origin:0 0;animation:c1 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c1{0.00%{opacity:0;transform:scale(.92)}4.00%{opacity:0;transform:scale(.92)}7.75%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c2{transform-origin:0 0;animation:c2 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c2{0.00%{opacity:0;transform:scale(.92)}4.67%{opacity:0;transform:scale(.92)}8.42%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c3{transform-origin:0 0;animation:c3 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c3{0.00%{opacity:0;transform:scale(.92)}6.08%{opacity:0;transform:scale(.92)}9.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c4{transform-origin:0 0;animation:c4 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c4{0.00%{opacity:0;transform:scale(.92)}6.41%{opacity:0;transform:scale(.92)}10.16%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c5{transform-origin:0 0;animation:c5 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c5{0.00%{opacity:0;transform:scale(.92)}6.75%{opacity:0;transform:scale(.92)}10.50%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c6{transform-origin:0 0;animation:c6 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c6{0.00%{opacity:0;transform:scale(.92)}7.08%{opacity:0;transform:scale(.92)}10.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c7{transform-origin:0 0;animation:c7 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c7{0.00%{opacity:0;transform:scale(.92)}3.66%{opacity:0;transform:scale(.92)}7.41%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c8{transform-origin:0 0;animation:c8 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c8{0.00%{opacity:0;transform:scale(.92)}7.41%{opacity:0;transform:scale(.92)}11.16%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c9{transform-origin:0 0;animation:c9 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c9{0.00%{opacity:0;transform:scale(.92)}7.75%{opacity:0;transform:scale(.92)}11.50%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c10{transform-origin:0 0;animation:c10 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c10{0.00%{opacity:0;transform:scale(.92)}8.08%{opacity:0;transform:scale(.92)}11.83%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.c11{transform-origin:0 0;animation:c11 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes c11{0.00%{opacity:0;transform:scale(.92)}8.42%{opacity:0;transform:scale(.92)}12.17%{opacity:1;transform:scale(1)}100.00%{opacity:1;transform:scale(1)}}.full{animation:full 12s cubic-bezier(.45,0,.25,1) infinite}@keyframes full{0.00%{clip-path:inset(0 0 100% 0)}10.83%{clip-path:inset(0 0 100% 0)}21.67%{clip-path:inset(0 0 0 0)}100.00%{clip-path:inset(0 0 0 0)}}.ptr{opacity:0;animation:ptr 12s cubic-bezier(.4,0,.2,1) infinite}@keyframes ptr{0.00%{opacity:0;transform:translate(978.5px,714.0px)}25.83%{opacity:0;transform:translate(978.5px,714.0px)}27.50%{opacity:1;transform:translate(978.5px,714.0px)}35.83%{opacity:1;transform:translate(718.5px,505.2px)}36.67%{opacity:1;transform:translate(718.5px,505.2px) scale(.82)}37.92%{opacity:1;transform:translate(718.5px,505.2px)}45.83%{opacity:0;transform:translate(718.5px,505.2px)}100.00%{opacity:0;transform:translate(718.5px,505.2px)}}.sel{animation:sel 12s ease-out infinite}@keyframes sel{0.00%{opacity:0}36.67%{opacity:0}39.17%{opacity:1}100.00%{opacity:1}}.insp{animation:insp 12s cubic-bezier(.2,.8,.2,1) infinite}@keyframes insp{0.00%{opacity:0;transform:translateX(48px)}37.08%{opacity:0;transform:translateX(48px)}42.08%{opacity:1;transform:translateX(0)}100.00%{opacity:1;transform:translateX(0)}}.cover{opacity:0;animation:cover 12s linear infinite}@keyframes cover{0.00%{opacity:1}1.67%{opacity:0}94.17%{opacity:0}100.00%{opacity:1}}@media (prefers-reduced-motion: reduce){*{animation:none!important}}</style><defs><image id="empty" width="1376" height="774" href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAALine truncated
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 642 KiB After Width: | Height: | Size: 640 KiB |
|
Before Width: | Height: | Size: 643 KiB After Width: | Height: | Size: 642 KiB |
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.7",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/repack-app": "0.10.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.7",
|
||||
"description": "Source-driven mobile app maps, deterministic CI capture, and visual reviews",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// The README's two animated SVGs, written by readme-screenshots.mjs. Each is a plain image: CSS keyframes on one loop,
|
||||
// every picture inlined as a JPEG data URI (an SVG shown with <img> loads nothing), and with prefers-reduced-motion
|
||||
// it shows its last frame, which is also what a viewer that does not animate SVG shows.
|
||||
//
|
||||
// readme-hero the Viewer's Map, built from real Viewer frames: the screens appear row by row, the transitions
|
||||
// wipe in from the top, then a click selects a screen and the Inspector slides in
|
||||
// readme-compare one modified screen wiping from its base capture to its head capture, the changed regions pulsing
|
||||
import { ZipReader, Uint8ArrayReader, Uint8ArrayWriter } from "@zip.js/zip.js";
|
||||
|
||||
/** The soft stage the PR comment picture sits on too (stagedComment in readme-screenshots.mjs), and its accents. */
|
||||
const STAGE = {
|
||||
light: { stage: "#F6F8FA", border: "#D1D9E0", shadow: "rgba(17,17,17,0.14)", text: "#1F2328", muted: "#59636E", accent: "#0969DA", region: "#D4520F" },
|
||||
dark: { stage: "#151B23", border: "#3D444D", shadow: "rgba(1,4,9,0.6)", text: "#F0F6FC", muted: "#9198A1", accent: "#4493F8", region: "#F0883E" },
|
||||
};
|
||||
const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif";
|
||||
const MONO = "ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace";
|
||||
const JPEG_QUALITY = 82;
|
||||
|
||||
const dataUri = jpeg => `data:image/jpeg;base64,${jpeg.toString("base64")}`;
|
||||
const escapeXml = text => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
const box = ({ x, y, width, height }) => `x="${x}" y="${y}" width="${width}" height="${height}"`;
|
||||
|
||||
/** Keyframes given in seconds on a shared loop, so every element stays in step. */
|
||||
function keyframes(name, loop, frames) {
|
||||
return `@keyframes ${name}{${frames.map(([at, css]) => `${((at / loop) * 100).toFixed(2)}%{${css}}`).join("")}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photographs the hero's states from a Viewer page whose Map has its camera set and nothing selected: the Map without
|
||||
* its screens, without its edges, and whole; then it clicks `select`, which opens the Inspector without moving the
|
||||
* camera, and photographs that. Returns the frames and where each screen card, the Inspector and the selected card are.
|
||||
*/
|
||||
export async function captureHeroFrames(page, { select, viewport }) {
|
||||
const shoot = () => page.screenshot({ type: "jpeg", quality: JPEG_QUALITY });
|
||||
const neutral = () => page.mouse.move(viewport.width - 4, viewport.height - 4);
|
||||
const rect = locator => locator.boundingBox().then(b => b && { x: Math.round(b.x), y: Math.round(b.y), width: Math.round(b.width), height: Math.round(b.height) });
|
||||
const camera = () => page.locator(".react-flow__viewport").evaluate(el => el.style.transform);
|
||||
const target = page.locator(`.screen-screenshot-target[title="${select}"]`);
|
||||
|
||||
// A card under the pointer dims the others and highlights its edges; let that fade before the first frame.
|
||||
await neutral();
|
||||
await page.waitForTimeout(1000);
|
||||
const at = await camera();
|
||||
const selected = await rect(target);
|
||||
if (!selected) throw new Error(`The hero needs ${select} on the Map.`);
|
||||
const cards = [];
|
||||
for (const node of await page.locator(".react-flow__node").all()) {
|
||||
const b = await rect(node);
|
||||
if (b && b.x < viewport.width && b.y < viewport.height && b.x + b.width > 0 && b.y + b.height > 0) cards.push(b);
|
||||
}
|
||||
const full = await shoot();
|
||||
const hide = async css => {
|
||||
const style = await page.addStyleTag({ content: `${css} { visibility: hidden !important; }` });
|
||||
await page.waitForTimeout(300);
|
||||
return style;
|
||||
};
|
||||
const edges = await hide(".react-flow__edges, .react-flow__edge, .react-flow__edgelabel-renderer");
|
||||
const screensOnly = await shoot();
|
||||
const nodes = await hide(".react-flow__node");
|
||||
const empty = await shoot();
|
||||
for (const style of [edges, nodes]) await style.evaluate(el => el.remove());
|
||||
|
||||
await target.click();
|
||||
await neutral();
|
||||
await page.waitForTimeout(1500);
|
||||
const inspector = await rect(page.locator("aside.right-panel"));
|
||||
if (!inspector) throw new Error(`Selecting ${select} did not open the Inspector.`);
|
||||
if ((await camera()) !== at) throw new Error(`The Map's camera moved when ${select} was selected: ${at} → ${await camera()}.`);
|
||||
const inspecting = await shoot();
|
||||
return { viewport, empty, screensOnly, full, inspecting, cards, selected, inspector };
|
||||
}
|
||||
|
||||
/**
|
||||
* The hero: the frames from captureHeroFrames as a window on a rounded 1600×900 stage. Each screen
|
||||
* card is a clip of the screens-only frame, so what appears is exactly what the Viewer draws.
|
||||
*/
|
||||
export function heroSvg(frames, theme, alt) {
|
||||
const t = STAGE[theme];
|
||||
const LOOP = 12;
|
||||
const W = 1600, H = 900;
|
||||
const { viewport: v } = frames;
|
||||
const wx = (W - v.width) / 2, wy = (H - v.height) / 2;
|
||||
const css = [];
|
||||
const defs = [];
|
||||
const layers = [];
|
||||
const image = (id, jpeg) => defs.push(`<image id="${id}" width="${v.width}" height="${v.height}" href="${dataUri(jpeg)}"/>`);
|
||||
image("empty", frames.empty);
|
||||
image("screens", frames.screensOnly);
|
||||
image("full", frames.full);
|
||||
image("inspecting", frames.inspecting);
|
||||
|
||||
// Cards appear a row at a time, top to bottom, as the Map lays out taps from launch; a row's cards left to right.
|
||||
const PAD = 18;
|
||||
const rows = [...new Set(frames.cards.map(c => c.y))].sort((a, b) => a - b);
|
||||
frames.cards.forEach((card, i) => {
|
||||
const appear = 0.4 + rows.indexOf(card.y) * 0.35 + (card.x / v.width) * 0.3;
|
||||
const clip = { x: card.x - PAD, y: card.y - PAD, width: card.width + PAD * 2, height: card.height + PAD * 2 };
|
||||
defs.push(`<clipPath id="c${i}"><rect ${box(clip)}/></clipPath>`);
|
||||
css.push(`.c${i}{transform-origin:0 0;animation:c${i} ${LOOP}s cubic-bezier(.2,.8,.2,1) infinite}`);
|
||||
css.push(keyframes(`c${i}`, LOOP, [[0, "opacity:0;transform:scale(.92)"], [appear, "opacity:0;transform:scale(.92)"], [appear + 0.45, "opacity:1;transform:scale(1)"], [LOOP, "opacity:1;transform:scale(1)"]]));
|
||||
// Scaled about the card's centre: the class sits on a group whose origin is there.
|
||||
const cx = card.x + card.width / 2, cy = card.y + card.height / 2;
|
||||
layers.push(`<g transform="translate(${cx} ${cy})"><g class="c${i}"><g transform="translate(${-cx} ${-cy})" clip-path="url(#c${i})"><use href="#screens"/></g></g></g>`);
|
||||
});
|
||||
const settled = 0.4 + (rows.length - 1) * 0.35 + 0.75;
|
||||
|
||||
// The transitions wipe in from the top: the full frame over the cards, which it draws in the same places.
|
||||
const EDGES = settled - 0.2, EDGES_END = EDGES + 1.3;
|
||||
css.push(`.full{animation:full ${LOOP}s cubic-bezier(.45,0,.25,1) infinite}`);
|
||||
css.push(keyframes("full", LOOP, [[0, "clip-path:inset(0 0 100% 0)"], [EDGES, "clip-path:inset(0 0 100% 0)"], [EDGES_END, "clip-path:inset(0 0 0 0)"], [LOOP, "clip-path:inset(0 0 0 0)"]]));
|
||||
layers.push(`<use class="full" href="#full"/>`);
|
||||
|
||||
// A pointer glides to the selected card and clicks; the selection lands and the Inspector slides in.
|
||||
const { selected: s, inspector: p } = frames;
|
||||
const target = { x: s.x + s.width * 0.55, y: s.y + s.height * 0.45 };
|
||||
const start = { x: Math.min(v.width - 120, target.x + 260), y: Math.min(v.height - 60, target.y + 220) };
|
||||
const MOVE = EDGES_END + 0.5, CLICK = MOVE + 1.2;
|
||||
const pointer = (x, y, extra = "") => `transform:translate(${x.toFixed(1)}px,${y.toFixed(1)}px)${extra}`;
|
||||
css.push(`.ptr{opacity:0;animation:ptr ${LOOP}s cubic-bezier(.4,0,.2,1) infinite}`);
|
||||
css.push(keyframes("ptr", LOOP, [
|
||||
[0, `opacity:0;${pointer(start.x, start.y)}`], [MOVE, `opacity:0;${pointer(start.x, start.y)}`], [MOVE + 0.2, `opacity:1;${pointer(start.x, start.y)}`],
|
||||
[CLICK, `opacity:1;${pointer(target.x, target.y)}`], [CLICK + 0.1, `opacity:1;${pointer(target.x, target.y, " scale(.82)")}`],
|
||||
[CLICK + 0.25, `opacity:1;${pointer(target.x, target.y)}`], [CLICK + 1.2, `opacity:0;${pointer(target.x, target.y)}`], [LOOP, `opacity:0;${pointer(target.x, target.y)}`],
|
||||
]));
|
||||
defs.push(`<clipPath id="canvas"><rect x="0" y="0" width="${p.x}" height="${v.height}"/></clipPath>`);
|
||||
defs.push(`<clipPath id="panel"><rect ${box(p)}/></clipPath>`);
|
||||
css.push(`.sel{animation:sel ${LOOP}s ease-out infinite}`);
|
||||
css.push(keyframes("sel", LOOP, [[0, "opacity:0"], [CLICK + 0.1, "opacity:0"], [CLICK + 0.4, "opacity:1"], [LOOP, "opacity:1"]]));
|
||||
css.push(`.insp{animation:insp ${LOOP}s cubic-bezier(.2,.8,.2,1) infinite}`);
|
||||
css.push(keyframes("insp", LOOP, [[0, "opacity:0;transform:translateX(48px)"], [CLICK + 0.15, "opacity:0;transform:translateX(48px)"], [CLICK + 0.75, "opacity:1;transform:translateX(0)"], [LOOP, "opacity:1;transform:translateX(0)"]]));
|
||||
layers.push(`<use class="sel" href="#inspecting" clip-path="url(#canvas)"/>`);
|
||||
layers.push(`<g class="insp"><use href="#inspecting" clip-path="url(#panel)"/></g>`);
|
||||
layers.push(`<g class="ptr"><path d="M0 0L0 22L6 16.5L10.5 26L14 24.5L9.8 15.2L18 15.2Z" fill="#111" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></g>`);
|
||||
|
||||
// The empty Map covers the reset: it fades in over the last frame, and the loop starts again beneath it.
|
||||
css.push(`.cover{opacity:0;animation:cover ${LOOP}s linear infinite}`);
|
||||
css.push(keyframes("cover", LOOP, [[0, "opacity:1"], [0.2, "opacity:0"], [LOOP - 0.7, "opacity:0"], [LOOP, "opacity:1"]]));
|
||||
layers.push(`<use class="cover" href="#empty"/>`);
|
||||
|
||||
css.push("@media (prefers-reduced-motion: reduce){*{animation:none!important}}");
|
||||
defs.push(`<clipPath id="window"><rect width="${v.width}" height="${v.height}" rx="14"/></clipPath>`);
|
||||
defs.push(`<filter id="shadow" x="-10%" y="-10%" width="120%" height="125%"><feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="${t.shadow}" flood-opacity=".3"/><feDropShadow dx="0" dy="30" stdDeviation="35" flood-color="${t.shadow}"/></filter>`);
|
||||
defs.push(`<clipPath id="stage"><rect width="${W}" height="${H}" rx="22"/></clipPath>`);
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${escapeXml(alt)}">`
|
||||
+ `<style>${css.join("")}</style><defs>${defs.join("")}</defs>`
|
||||
+ `<g clip-path="url(#stage)"><rect width="${W}" height="${H}" fill="${t.stage}"/>`
|
||||
+ `<rect x="${wx}" y="${wy}" width="${v.width}" height="${v.height}" rx="14" fill="${t.stage}" filter="url(#shadow)"/>`
|
||||
+ `<g transform="translate(${wx} ${wy})"><g clip-path="url(#window)"><use href="#empty"/>${layers.join("")}</g>`
|
||||
+ `<rect x=".5" y=".5" width="${v.width - 1}" height="${v.height - 1}" rx="14" fill="none" stroke="${t.border}"/></g></g></svg>`;
|
||||
}
|
||||
|
||||
/** review.json and an asset reader from a sealed review report's bytes. */
|
||||
export async function openReport(bytes) {
|
||||
const reader = new ZipReader(new Uint8ArrayReader(new Uint8Array(bytes)));
|
||||
const entries = new Map((await reader.getEntries()).map(entry => [entry.filename, entry]));
|
||||
const read = async name => {
|
||||
const entry = entries.get(name);
|
||||
if (!entry) throw new Error(`The report has no ${name}.`);
|
||||
return Buffer.from(await entry.getData(new Uint8ArrayWriter()));
|
||||
};
|
||||
const review = JSON.parse((await read("review.json")).toString("utf8")).review;
|
||||
return { review, asset: sha => read(`assets/${sha}.png`) };
|
||||
}
|
||||
|
||||
/** A PNG as a JPEG at most `maxHeight` tall, drawn by the browser so the script needs no image library. */
|
||||
async function toJpeg(browser, png, maxHeight) {
|
||||
const page = await browser.newPage();
|
||||
try {
|
||||
const base64 = await page.evaluate(async ({ png, maxHeight, quality }) => {
|
||||
const bitmap = await createImageBitmap(await (await fetch(`data:image/png;base64,${png}`)).blob());
|
||||
const scale = Math.min(1, maxHeight / bitmap.height);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.round(bitmap.width * scale);
|
||||
canvas.height = Math.round(bitmap.height * scale);
|
||||
const context = canvas.getContext("2d");
|
||||
context.imageSmoothingQuality = "high";
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
return canvas.toDataURL("image/jpeg", quality).split(",")[1];
|
||||
}, { png: png.toString("base64"), maxHeight, quality: JPEG_QUALITY / 100 });
|
||||
return Buffer.from(base64, "base64");
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The surface of the Compare key `key` (the slug of the Viewer's #/compare/<key>, which is the route without its
|
||||
* slash) in `theme`, among the report's visually modified screens.
|
||||
*/
|
||||
export function compareSurface(review, key, theme) {
|
||||
const route = `/${key}`;
|
||||
const surface = review.surfaces.find(s => (s.head ?? s.base)?.route === route && s.colorScheme === theme && s.visual?.verdict === "modified");
|
||||
if (!surface) throw new Error(`No visually modified ${route} in ${theme} in this report; pass --compare <key> from a #/compare/<key> URL.`);
|
||||
return surface;
|
||||
}
|
||||
|
||||
/** The Compare picture: `surface`'s base capture wiping to its head capture, its changed regions outlined. */
|
||||
export async function compareSvg(browser, report, surface, theme, alt) {
|
||||
const t = STAGE[theme];
|
||||
const LOOP = 7;
|
||||
const W = 1000, H = 600;
|
||||
const { baseImage, headImage } = surface;
|
||||
const PH = 540, PW = Math.round(PH * headImage.width / headImage.height);
|
||||
const x = (W - PW) / 2, y = (H - PH) / 2;
|
||||
const k = PW / headImage.width;
|
||||
const before = dataUri(await toJpeg(browser, await report.asset(baseImage.sha256), PH * 2));
|
||||
const after = dataUri(await toJpeg(browser, await report.asset(headImage.sha256), PH * 2));
|
||||
const { pullRequest } = report.review;
|
||||
const css = [];
|
||||
// The After capture is revealed left to right, and the divider rides the edge of the reveal.
|
||||
css.push(`.after{animation:wipe ${LOOP}s cubic-bezier(.65,0,.35,1) infinite}`);
|
||||
css.push(keyframes("wipe", LOOP, [[0, "clip-path:inset(0 100% 0 0)"], [1.0, "clip-path:inset(0 100% 0 0)"], [2.6, "clip-path:inset(0 0 0 0)"], [5.8, "clip-path:inset(0 0 0 0)"], [6.8, "clip-path:inset(0 100% 0 0)"], [LOOP, "clip-path:inset(0 100% 0 0)"]]));
|
||||
css.push(`.divider{opacity:0;animation:divider ${LOOP}s cubic-bezier(.65,0,.35,1) infinite}`);
|
||||
css.push(keyframes("divider", LOOP, [[0, "transform:translateX(0);opacity:0"], [0.8, "transform:translateX(0);opacity:1"], [1.0, "transform:translateX(0);opacity:1"], [2.6, `transform:translateX(${PW}px);opacity:1`], [2.9, `transform:translateX(${PW}px);opacity:0`], [5.8, `transform:translateX(${PW}px);opacity:0`], [6.0, `transform:translateX(${PW}px);opacity:1`], [6.8, "transform:translateX(0);opacity:1"], [LOOP, "transform:translateX(0);opacity:0"]]));
|
||||
css.push(`.regions{animation:regions ${LOOP}s ease-in-out infinite}`);
|
||||
css.push(keyframes("regions", LOOP, [[0, "opacity:0"], [2.7, "opacity:0"], [3.1, "opacity:1"], [3.6, "opacity:.3"], [4.1, "opacity:1"], [5.7, "opacity:1"], [6.0, "opacity:0"], [LOOP, "opacity:0"]]));
|
||||
css.push(`.before-label{opacity:.3;animation:before-label ${LOOP}s linear infinite}.after-label{animation:after-label ${LOOP}s linear infinite}`);
|
||||
css.push(keyframes("before-label", LOOP, [[0, "opacity:1"], [1.8, "opacity:1"], [2.0, "opacity:.3"], [6.2, "opacity:.3"], [6.4, "opacity:1"], [LOOP, "opacity:1"]]));
|
||||
css.push(keyframes("after-label", LOOP, [[0, "opacity:.3"], [1.8, "opacity:.3"], [2.0, "opacity:1"], [6.2, "opacity:1"], [6.4, "opacity:.3"], [LOOP, "opacity:.3"]]));
|
||||
css.push("@media (prefers-reduced-motion: reduce){*{animation:none!important}}");
|
||||
const regions = surface.visual.regions.map(({ rect: r }) =>
|
||||
`<rect x="${(x + r.x * k - 3).toFixed(1)}" y="${(y + r.y * k - 3).toFixed(1)}" width="${(r.width * k + 6).toFixed(1)}" height="${(r.height * k + 6).toFixed(1)}" rx="3" fill="none" stroke="${t.region}" stroke-width="2"/>`).join("");
|
||||
const label = (cls, anchor, lx, title, sub, note) => `<g class="${cls}" font-family="${FONT}" text-anchor="${anchor}">`
|
||||
+ `<text x="${lx}" y="${y + PH / 2 - 14}" font-size="26" font-weight="700" fill="${t.text}">${title}</text>`
|
||||
+ `<text x="${lx}" y="${y + PH / 2 + 12}" font-family="${MONO}" font-size="13" fill="${t.muted}">${escapeXml(sub)}</text>`
|
||||
+ (note ? `<text x="${lx}" y="${y + PH / 2 + 36}" font-size="13" font-weight="600" fill="${t.region}">${note}</text>` : "") + "</g>";
|
||||
const count = surface.visual.regions.length;
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${escapeXml(alt)}">`
|
||||
+ `<style>${css.join("")}</style>`
|
||||
+ `<defs><clipPath id="stage"><rect width="${W}" height="${H}" rx="16"/></clipPath><clipPath id="phone"><rect x="${x}" y="${y}" width="${PW}" height="${PH}" rx="40"/></clipPath>`
|
||||
+ `<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%"><feDropShadow dx="0" dy="8" stdDeviation="14" flood-color="${t.shadow}"/></filter></defs>`
|
||||
+ `<g clip-path="url(#stage)"><rect width="${W}" height="${H}" fill="${t.stage}"/>`
|
||||
+ `<rect x="${x}" y="${y}" width="${PW}" height="${PH}" rx="40" fill="${t.stage}" filter="url(#shadow)"/>`
|
||||
+ `<g clip-path="url(#phone)"><image href="${before}" x="${x}" y="${y}" width="${PW}" height="${PH}"/>`
|
||||
+ `<image class="after" href="${after}" x="${x}" y="${y}" width="${PW}" height="${PH}"/></g>`
|
||||
+ `<rect x="${x}" y="${y}" width="${PW}" height="${PH}" rx="40" fill="none" stroke="${t.border}"/>`
|
||||
+ `<g class="divider"><rect x="${x - 1.5}" y="${y}" width="3" height="${PH}" fill="${t.accent}"/><circle cx="${x}" cy="${y + PH / 2}" r="13" fill="${t.accent}"/>`
|
||||
+ `<path d="M${x - 5} ${y + PH / 2 - 4}l-3 4l3 4M${x + 5} ${y + PH / 2 - 4}l3 4l-3 4" stroke="#fff" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></g>`
|
||||
+ `<g class="regions">${regions}</g>`
|
||||
+ label("before-label", "end", x - 44, "Before", `${pullRequest.base.ref} ·${pullRequest.base.sha.slice(0, 7)}`)
|
||||
+ label("after-label", "start", x + PW + 44, "After", `PR #${pullRequest.number} · ${pullRequest.head.sha.slice(0, 7)}`, `${count} changed region${count === 1 ? "" : "s"}`)
|
||||
+ "</g></svg>";
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Regenerates the Viewer screenshots in docs/screenshots from a review report, in light and dark
|
||||
// Regenerates the README's pictures in docs/screenshots from a review report, in light and dark
|
||||
// (the README shows them with <picture>; GitHub Mobile ignores the dark source and shows light). The reference app is euxy
|
||||
// (github.com/brentvatne/euxy): skills/readme-refresh/SKILL.md says which report to pass and how.
|
||||
//
|
||||
@@ -7,8 +7,10 @@
|
||||
//
|
||||
// --report a sealed review report (the hosted link's report.zip?platform=ios, or the PR's zip artifact)
|
||||
// --select the route selected on the hero Map (opens the Inspector); default /settings. The hero zooms in around it
|
||||
// (--zoom, default 73%) and is framed as a window on a soft stage, like the PR comment
|
||||
// --compare the Compare key of a modified screen: the slug in the Viewer's #/compare/<key> URL; default patterns
|
||||
// (--zoom, default 73%) and is an animated SVG of a window on a soft stage (readme-animations.mjs): the
|
||||
// Map's cards appear, its transitions wipe in, and a click on this screen opens the Inspector
|
||||
// --compare the Compare key of a modified screen: the slug in the Viewer's #/compare/<key> URL; default patterns.
|
||||
// It becomes readme-compare-*.svg, its before capture wiping to its after capture
|
||||
// --pr a GitHub PR URL whose Explore comment becomes readme-pr-comment-light.png (public repository): the comment
|
||||
// at its own size on a soft stage, cut off with a fade after the list of changed screens
|
||||
import { chromium } from "@playwright/test";
|
||||
@@ -16,6 +18,7 @@ import { readFile, writeFile } from "node:fs/promises";
|
||||
import { parseArgs } from "node:util";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { startReportViewer } from "../test/ci/lib/report-viewer.mjs";
|
||||
import { captureHeroFrames, compareSurface, compareSvg, heroSvg, openReport } from "./readme-animations.mjs";
|
||||
|
||||
const { values: args } = parseArgs({
|
||||
options: {
|
||||
@@ -33,15 +36,22 @@ if (!args.report) {
|
||||
|
||||
const out = fileURLToPath(new URL("../docs/screenshots/", import.meta.url));
|
||||
const SHOTS = [
|
||||
{ file: "readme-hero", hash: "#/map", viewport: { width: 1376, height: 774 }, click: "Fit canvas", select: args.select, zoom: Number(args.zoom), framed: true },
|
||||
{ file: "readme-compare", hash: `#/compare/${args.compare}`, viewport: { width: 1760, height: 1000 } },
|
||||
{ file: "readme-hero", hash: "#/map", viewport: { width: 1376, height: 774 }, click: "Fit canvas", select: args.select, zoom: Number(args.zoom), animated: true },
|
||||
{ file: "readme-screens", hash: "#/screens", viewport: { width: 1760, height: 1000 } },
|
||||
];
|
||||
|
||||
const bytes = await readFile(args.report);
|
||||
const report = await openReport(bytes);
|
||||
const { server, url } = await startReportViewer({ bytes, watch: false });
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const surface = compareSurface(report.review, args.compare, theme);
|
||||
const path = `${out}readme-compare-${theme}.svg`;
|
||||
await writeFile(path, await compareSvg(browser, report, surface, theme,
|
||||
`The ${surface.head.route} screen of euxy wiping from its capture before the pull request to its capture after it, with the changed regions outlined`));
|
||||
console.log(path);
|
||||
}
|
||||
for (const theme of ["light", "dark"]) for (const shot of SHOTS) {
|
||||
const context = await browser.newContext({ viewport: shot.viewport, deviceScaleFactor: 2, colorScheme: theme });
|
||||
await context.addInitScript(value => localStorage.setItem("expo-explore:theme", value), theme);
|
||||
@@ -54,8 +64,8 @@ try {
|
||||
await page.mouse.move(400, shot.viewport.height - 30);
|
||||
await page.waitForTimeout(1500);
|
||||
}
|
||||
if (shot.select) {
|
||||
// Selecting a screen opens the Inspector without moving the fitted camera.
|
||||
if (shot.select && !shot.animated) {
|
||||
// Selecting a screen opens the Inspector without moving the fitted camera. The animated hero selects it last.
|
||||
await page.locator(`.screen-screenshot-target[title="${shot.select}"]`).click();
|
||||
await page.mouse.move(400, shot.viewport.height - 30);
|
||||
await page.waitForTimeout(1500);
|
||||
@@ -76,12 +86,12 @@ try {
|
||||
await page.mouse.move(shot.viewport.width - 60, shot.viewport.height / 2);
|
||||
await page.waitForTimeout(1200);
|
||||
}
|
||||
if (shot.hash.startsWith("#/compare/") && !page.url().includes(shot.hash)) {
|
||||
throw new Error(`Compare key ${args.compare} is not a screen of this report (the Viewer went to ${page.url()}); pass --compare <key> from a #/compare/<key> URL.`);
|
||||
}
|
||||
const path = `${out}${shot.file}-${theme}.png`;
|
||||
if (shot.framed) await writeFile(path, await stagedWindow(browser, await page.screenshot(), shot.viewport, theme));
|
||||
else await page.screenshot({ path });
|
||||
const path = `${out}${shot.file}-${theme}.${shot.animated ? "svg" : "png"}`;
|
||||
if (shot.animated) {
|
||||
const frames = await captureHeroFrames(page, { select: shot.select, viewport: shot.viewport });
|
||||
await writeFile(path, heroSvg(frames, theme,
|
||||
`Explore's Map of a euxy pull request: the screen cards appear row by row, the transitions between them wipe in, then a click selects ${shot.select} and the Inspector opens on it`));
|
||||
} else await page.screenshot({ path });
|
||||
console.log(path);
|
||||
await context.close();
|
||||
}
|
||||
@@ -114,26 +124,6 @@ try {
|
||||
await server.close?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* A Viewer screenshot as a window on a rounded 1600×900 stage (drawn at 2x), with a hairline border and a soft shadow,
|
||||
* as the post about Explore frames it. The corners outside the stage stay transparent, so it sits on either GitHub theme.
|
||||
*/
|
||||
async function stagedWindow(browser, shot, viewport, theme) {
|
||||
const dark = theme === "dark";
|
||||
const stage = dark ? "#151B23" : "#F6F8FA";
|
||||
const border = dark ? "#3D444D" : "#D1D9E0";
|
||||
const shadow = dark ? "0 2px 4px rgba(1,4,9,0.4), 0 30px 70px rgba(1,4,9,0.6)" : "0 2px 4px rgba(17,17,17,0.04), 0 30px 70px rgba(17,17,17,0.14)";
|
||||
const context = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 2 });
|
||||
const page = await context.newPage();
|
||||
await page.setContent(`<!doctype html><html><body style="margin:0;background:transparent">
|
||||
<div id="stage" style="position:relative;width:1600px;height:900px;background:${stage};border-radius:22px;overflow:hidden">
|
||||
<img src="data:image/png;base64,${shot.toString("base64")}" style="position:absolute;left:${(1600 - viewport.width) / 2}px;top:${(900 - viewport.height) / 2}px;width:${viewport.width}px;height:${viewport.height}px;box-sizing:border-box;border:1px solid ${border};border-radius:14px;box-shadow:${shadow}">
|
||||
</div></body></html>`);
|
||||
const png = await page.locator("#stage").screenshot({ omitBackground: true });
|
||||
await context.close();
|
||||
return png;
|
||||
}
|
||||
|
||||
/**
|
||||
* The comment on a rounded stage as wide as the README column (880 px, drawn at 2x), with a soft shadow and a fade at
|
||||
* the cut. The corners outside the stage stay transparent, so the image sits on either GitHub theme.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: readme-refresh
|
||||
description: Refresh Expo Explore's README.md with euxy (github.com/brentvatne/euxy) as the reference app. Regenerate every screenshot in docs/screenshots from a current euxy review report and PR comment, then re-read the README as a first-time user: the top level only says what Explore does, links the live euxy example, gives one quick-start prompt to copy that reviews a change to your own app or explores a build you point it to, and one for setting up CI; everything else lives in collapsibles. Use after a Viewer or PR-comment change that the README shows, a new command or setting, or a release that made a README claim stale. Not for the docs/ guides or the shipped skills.
|
||||
description: Refresh Expo Explore's README.md with euxy (github.com/brentvatne/euxy) as the reference app. Regenerate every screenshot and animated SVG in docs/screenshots from a current euxy review report and PR comment, then re-read the README as a first-time user: the top level only says what Explore does, links the live euxy example, gives one quick-start prompt to copy that reviews a change to your own app or explores a build you point it to, and one for setting up CI; everything else lives in collapsibles. Use after a Viewer or PR-comment change that the README shows, a new command or setting, or a release that made a README claim stale. Not for the docs/ guides or the shipped skills.
|
||||
---
|
||||
|
||||
# Refresh the README
|
||||
@@ -24,17 +24,25 @@ scripts/refresh-viewer-preview-fixtures.sh '<hosted link>' brentvatne/euxy#<n>
|
||||
|
||||
Do not pick a same-tree demo PR, where every change is noise. The refreshed fixtures reach the live example on the next push to main, or when you run **Example report** from GitHub Actions. `curl -s "<hosted link>/api/v1/screens?status=added,removed,modified&platform=ios"` lists what changed, which tells you which screen to select and compare.
|
||||
|
||||
## 2. Regenerate every screenshot
|
||||
## 2. Regenerate every screenshot and animation
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
node scripts/readme-screenshots.mjs --report ~/euxy-report/ios.zip --select /settings --compare patterns --pr https://github.com/brentvatne/euxy/pull/<n>
|
||||
node scripts/readme-screenshots.mjs --report ~/euxy-report/ios.zip --select /about --compare patterns --pr https://github.com/brentvatne/euxy/pull/<n>
|
||||
```
|
||||
|
||||
- `--select` is the route selected on the hero Map (the Inspector opens on it): choose an added or clearly modified screen.
|
||||
- `--compare` is the key in the Viewer's `#/compare/<key>` URL for a **modified** screen with outlined regions (open the report, click the screen in Compare, copy the key). The script fails if the key is not in the report.
|
||||
- `--select` is the route the hero's pointer clicks on the Map (the Inspector opens on it): choose an added or clearly modified screen. The script zooms in around it, so it must be a screen the Map shows.
|
||||
- `--compare` is the key in the Viewer's `#/compare/<key>` URL for a **modified** screen with outlined regions (open the report, click the screen in Compare, copy the key): the route without its slash. The script fails if the report has no visually modified screen at that route.
|
||||
- `--pr` screenshots the Explore comment on that PR: the fixtures' `source`. Headless Chromium needs a colour emoji font for the result glyphs (`sudo apt-get install fonts-noto-color-emoji` on Debian/Ubuntu); a comment with hollow boxes where 🟩 should be is not acceptable.
|
||||
- The script serves the report through the Viewer's Vite dev server, so no build is needed. It writes a `-light` and a `-dark` PNG for every shot (the PR comment too: signed-out github.com follows `prefers-color-scheme`). The README shows each pair with `<picture>`: a `<source media="(prefers-color-scheme: dark)">` for the dark file and an `<img>` with the alt text and the light file, which is what GitHub Mobile shows (it ignores the dark source), so the light file is the one that must always be right.
|
||||
- The script serves the report through the Viewer's Vite dev server, so no build is needed. It writes a `-light` and a `-dark` file for every picture (the PR comment too: signed-out github.com follows `prefers-color-scheme`). The README shows each pair with `<picture>`: a `<source media="(prefers-color-scheme: dark)">` for the dark file and an `<img>` with the alt text and the light file, which is what GitHub Mobile shows (it ignores the dark source), so the light file is the one that must always be right.
|
||||
|
||||
Two of the pictures are animated SVGs, built by `scripts/readme-animations.mjs` in the same run; there is nothing else to run when the screenshots change:
|
||||
|
||||
- `readme-hero-*.svg` is made of real Viewer frames at the zoomed Map camera: the Map without screens, the screens without edges, the whole Map, and the Map after the pointer clicks `--select`. The cards appear row by row, the edges wipe in from the top, then the pointer clicks and the Inspector slides in. Each is about 1.4 MB: four 2x JPEG frames inlined, since an SVG shown with `<img>` can load nothing. Anything the Viewer draws on the Map or in the Inspector shows up here on the next run, so regenerate it after a Viewer change the hero shows.
|
||||
- `readme-compare-*.svg` is the `--compare` screen's base capture wiping to its head capture, with the report's changed regions pulsing. It is drawn from `review.json` and the report's assets, not from a Viewer screenshot, so a Viewer change does not stale it, but a new report does.
|
||||
- Both loop on CSS keyframes, and with `prefers-reduced-motion` they hold the last frame: Inspector open, regions outlined. That frame is also what a viewer that does not animate SVG shows, so it must read on its own.
|
||||
|
||||
Open each SVG in a browser before committing, light and dark, and watch a full loop: every card should appear once and land where the whole Map has it, with no hover highlight in the frames before the click; the pointer should click the `--select` card; the Inspector should open on that screen; Compare's outlines should sit on the changed text, not beside it. To look at one moment, pause the animations in the console: `document.getAnimations().forEach(a => { a.pause(); a.currentTime = 5000; })`. Keep the README's `<img>` and `<source>` pointing at the `.svg` files.
|
||||
|
||||
`docs/screenshots/readme-exploration-light.png` is the black-box map and comes from a euxy `explore:binary` run (`npx @expo/explore explore:binary <euxy simulator build> --no-upload`, then `expo-explore view --dir <output>` at 1760×1000, Map, Fit canvas). It has no dark variant and is a plain Markdown image. Regenerate it when the Map's rendering of edges or labels changed; otherwise keep it, and say so in the PR.
|
||||
|
||||
@@ -53,18 +61,18 @@ cd - && npm run build:cli && node scripts/readme-reports-rows.mjs > /tmp/reports
|
||||
- The script renders the picker as the CLI draws it (96 columns, the newest run selected) and writes the terminal body as HTML: each coloured piece is exactly its characters wide, so columns line up, and the wordmark is drawn as cell rectangles, since a design tool's font does not draw `█▀▄` cell for cell.
|
||||
- In Paper, replace the frame named "Terminal" inside each artboard's window with that HTML, check both artboards in a screenshot (crisp wordmark, aligned columns, the selected row highlighted to the end, coloured counts), and export both at 2x as `readme-reports-light.png` and `readme-reports-dark.png`. The window's title bar reads `npx @expo/explore reports`, as people run it.
|
||||
|
||||
Look at every PNG you produced before committing, light and dark: the selected screen should be the one you asked for, the Compare view must show Before and After with outlines, the Screens grid must show the added, removed and modified status dots, the PR comment must show the heading links and result glyphs. Describe each in its Markdown alt text as what the picture shows, not what the feature is.
|
||||
Look at every PNG you produced before committing, light and dark: the Screens grid must show the added, removed and modified status dots, the PR comment must show the heading links and result glyphs. Describe each in its Markdown alt text as what the picture shows, not what the feature is.
|
||||
|
||||
## 3. Pass over the content as a first-time user
|
||||
|
||||
Read the README top to bottom once without opening a collapsible. At that level it may only answer, in this order:
|
||||
|
||||
1. What Explore is (one short paragraph), the hero image, and the link to the live euxy example (`explore-example--euxy.expo.app`, redeployed on every merge to main by `.github/workflows/example-report.yml`). Under it, one table row of three pictures with a one-line caption each: Compare, Screens, and the PR comment (which says it needs CI), then the agent prompt collapsed as **Ask an agent about a report**. The hero is a zoomed Map framed as a window on a stage (`stagedWindow` in the script); the three below are plain.
|
||||
2. **Quick start**: one path. A single prompt to paste into Claude Code or Codex that reviews a change to the reader's own Expo app through the explore-setup skill's "Review a change on this machine" section, or, when they point it to a build (or the app is not an Expo project), explores a simulator build through the explore-binary skill. Then one sentence on what each case needs (a review needs an Expo account, is built on EAS, and is captured on EAS Simulator or a local simulator; exploring a build needs a Claude Code or Codex login and EAS Simulator or a local simulator, and no Expo account locally). Then one **Run it yourself** collapsible with both by hand: the numbered steps for a review, with nothing optional in them (make the app buildable on EAS: login, init, bundle identifier, a simulator profile named `explore`, and commit, since the before build is the last commit; then edit a screen near its top and run `capture`, or `capture --simulator local`), and the `explore:binary` commands, including `--simulator local`. Then the `reports` picker image (`readme-reports-*.png`) with one sentence on saved runs, at the top level, and one collapsible for other commits (`--committed`, `--base`/`--head`) and what a review does on the machine. Run the steps on a fresh `create-expo-app` before changing them.
|
||||
1. What Explore is (one short paragraph), the hero image, and the link to the live euxy example (`explore-example--euxy.expo.app`, redeployed on every merge to main by `.github/workflows/example-report.yml`). Under it, Compare at full width with a one-line caption, then one table row of two pictures with a one-line caption each: Screens and the PR comment (which says it needs CI), then the agent prompt collapsed as **Ask an agent about a report**. The hero is the animated zoomed Map, framed as a window on a stage, and Compare is the animated wipe (both from `readme-animations.mjs`); the Screens and PR comment pictures are PNGs. Compare gets its own row because a phone wiping from before to after is unreadable at a third of the column.
|
||||
2. **Quick start**: one path. A single prompt to paste into Claude Code or Codex that reviews a change to the reader's own Expo app through the explore-setup skill's "Review a change on this machine" section, or, when they point it to a build (or the app is not an Expo project), explores a simulator build through the explore-binary skill. Then one sentence on what each case needs (a review needs an Expo account, is built on EAS, and is captured on EAS Simulator or a local simulator; exploring a build needs a Claude Code or Codex login and EAS Simulator or a local simulator, and no Expo account locally), and under it one `> [!NOTE]` alert: EAS Simulator is in preview, with the waitlist link and `--simulator local` as the alternative. Then one **Run it yourself** collapsible with both by hand: the numbered steps for a review, with nothing optional in them (make the app buildable on EAS: login, init, bundle identifier, a simulator profile named `explore`, and commit, since the before build is the last commit; then edit a screen near its top and run `capture`, or `capture --simulator local`), and the `explore:binary` commands, including `--simulator local`. Right after **Run it yourself**, one `> [!WARNING]` alert: a review runs both commits' code on the reader's machine, so review only commits they would run. These are the README's only two alerts; do not add more, or they stop standing out. Then the `reports` picker image (`readme-reports-*.png`) with one sentence on saved runs, at the top level, and one collapsible for other commits (`--committed`, `--base`/`--head`) and what a review does on the machine. Run the steps on a fresh `create-expo-app` before changing them.
|
||||
3. **Map every screen of any app**: one sentence on what exploring a build shows (pointing back to the quick start, which runs it), then its collapsibles: its options, exploring a session already started, and what a run without source shows.
|
||||
4. **Set up CI**: one sentence, then two subsections, each a sentence on what it gives and a prompt to paste: **Review on every PR** (the setup prompt, then a few grouped collapsibles: Hosted previews first, then Manual setup (the setup prompt's steps done by hand, in order: setup, doctor, secrets, baseline, first PR), Capture modes: deterministic or agent, iOS, Android, or both, Keep your setup current) and **Compare any two commits** (a prompt that follows the explore-setup skill's "Compare any two commits" section, the ways to snapshot a release as bullets, then the comparison workflow collapsed).
|
||||
|
||||
Lead with prompts, not explanations: a reader should be able to copy something and see Explore work. Everything else, the manual commands, requirements, options, the manual setup, capture modes, hosted previews, iOS and Android, agent mode, repository settings, how agents read a report, how it works, limitations, contributing, goes into a `<details>` block under the section it belongs to, with a `<summary>` that says what the reader will find. Keep bullets to one or two sentences. Group related collapsibles rather than adding one per topic, so a section shows a handful, not nine. Requirements sit collapsed right under the example report link. Keep the collapsibles' `id` attributes that other docs link to (`#hosted-previews`, `#platforms`, `#compare`, `#agents`); the Terms and How agents read a report collapsibles live under Additional information, and keep the Inspiration section (screenmap and Revyl's Atlas).
|
||||
Lead with prompts, not explanations: a reader should be able to copy something and see Explore work. Everything else, the manual commands, requirements, options, the manual setup, capture modes, hosted previews, iOS and Android, agent mode, repository settings, how agents read a report, how it works, limitations, contributing, goes into a `<details>` block under the section it belongs to, with a `<summary>` that says what the reader will find. Keep bullets to one or two sentences. Group related collapsibles rather than adding one per topic, so a section shows a handful, not nine. Requirements sit collapsed right under the example report link. The **How it works** collapsible opens with a Mermaid `sequenceDiagram` of a PR review (pull request, GitHub Actions, EAS Build, EAS Simulator), followed by the facts it cannot show as bullets: who triggers a review, what Modified means, session retries. Check its steps against `CI-FLOW.md` and the `ci:*` commands, and edit the diagram's text, not a picture: GitHub draws it. Keep the collapsibles' `id` attributes that other docs link to (`#hosted-previews`, `#platforms`, `#compare`, `#agents`); the Terms and How agents read a report collapsibles live under Additional information, and keep the Inspiration section (screenmap and Revyl's Atlas).
|
||||
|
||||
Check that each prompt still works as written:
|
||||
- the skill links it names (`https://unpkg.com/@expo/explore/skills/...`) are files the package ships (`files` in `package.json`), and they open from the published release;
|
||||
|
||||
@@ -150,7 +150,8 @@ async function prepareCiRun(options: Pick<PublicCiOptions, "baseProject" | "head
|
||||
links: viewerLinks({ repository: presentation.repository, headSha: presentation.head.sha, runId: environment.GITHUB_RUN_ID!,
|
||||
runAttempt: environment.GITHUB_RUN_ATTEMPT!, configPath: repositoryConfigPath }),
|
||||
startedAt: now(), updatedAt: now(), build: { platform: config.app.platform, easProfile: config.app.easProfile }, artifactOnly: true,
|
||||
...(config.target ? { target: config.target } : {}), ...(options.targets && options.targets.length > 1 ? { targets: options.targets } : {}) };
|
||||
...(config.target ? { target: config.target } : {}), ...(options.targets && options.targets.length > 1 ? { targets: options.targets } : {}),
|
||||
...(config.report?.comment?.map ? { map: true } : {}) };
|
||||
return { projects, output, state };
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,9 @@ export type ExploreConfig = {
|
||||
setup?: ExploreSetupAction[];
|
||||
agent?: { provider: "openai" | "anthropic"; model: string; instructions?: string };
|
||||
/** Hosted previews: one token-gated EAS Hosting deployment per review, see docs/private-review.md. */
|
||||
report?: { preview?: { hosting: "eas"; /** null: the link never expires; the deployment lives until someone deletes it. */ expiresAfterDays: number | null; owner?: string; project?: string } };
|
||||
report?: { preview?: { hosting: "eas"; /** null: the link never expires; the deployment lives until someone deletes it. */ expiresAfterDays: number | null; owner?: string; project?: string };
|
||||
/** `map`: the PR comment draws a Mermaid map of the changed screens and the screens that lead to them. Off by default. */
|
||||
comment?: { map: boolean } };
|
||||
/**
|
||||
* `trustedAuthors`: GitHub logins (e.g. `devin-ai-integration[bot]`) whose same-repository pull
|
||||
* requests the review workflow captures although they lack write access. The workflow reads this
|
||||
@@ -588,9 +590,23 @@ function trustedAuthorList(value: unknown): string[] {
|
||||
function reportConfig(value: unknown): ExploreConfig["report"] {
|
||||
if (value === undefined) return undefined;
|
||||
const report = record(value, "report");
|
||||
exactKeys(report, ["preview"], "report");
|
||||
if (report.preview === undefined) return {};
|
||||
const preview = record(report.preview, "report.preview");
|
||||
exactKeys(report, ["preview", "comment"], "report");
|
||||
const comment = commentConfig(report.comment);
|
||||
const preview = previewConfig(report.preview);
|
||||
return { ...(preview ? { preview } : {}), ...(comment ? { comment } : {}) };
|
||||
}
|
||||
|
||||
function commentConfig(value: unknown): NonNullable<ExploreConfig["report"]>["comment"] {
|
||||
if (value === undefined) return undefined;
|
||||
const comment = record(value, "report.comment");
|
||||
exactKeys(comment, ["map"], "report.comment");
|
||||
if (typeof comment.map !== "boolean") fail("report.comment.map must be true or false", "report.comment.map");
|
||||
return { map: comment.map };
|
||||
}
|
||||
|
||||
function previewConfig(value: unknown): NonNullable<ExploreConfig["report"]>["preview"] {
|
||||
if (value === undefined) return undefined;
|
||||
const preview = record(value, "report.preview");
|
||||
exactKeys(preview, ["hosting", "expiresAfter", "owner", "project"], "report.preview");
|
||||
const owner = optionalText(preview.owner, "report.preview.owner", 64);
|
||||
if (owner !== undefined && !/^[a-z0-9][a-z0-9_-]*$/.test(owner)) {
|
||||
@@ -600,12 +616,12 @@ function reportConfig(value: unknown): ExploreConfig["report"] {
|
||||
if (project !== undefined && !/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(project)) {
|
||||
fail("report.preview.project must be a lowercase EAS project slug", "report.preview.project");
|
||||
}
|
||||
return { preview: {
|
||||
return {
|
||||
hosting: literal(preview.hosting, ["eas"] as const, "report.preview.hosting"),
|
||||
expiresAfterDays: previewDays(preview.expiresAfter, "report.preview.expiresAfter"),
|
||||
...(owner === undefined ? {} : { owner }),
|
||||
...(project === undefined ? {} : { project }),
|
||||
} };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,11 +7,13 @@ 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 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
|
||||
* 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
|
||||
* 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.
|
||||
*/
|
||||
@@ -67,6 +69,16 @@ 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.
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { PublicReview } from "../contracts/capture.js";
|
||||
import type { RunTarget } from "../types.js";
|
||||
import type { SimulatorRuntimeMetadata } from "../capture/run.js";
|
||||
import { CI_COMMENT_MARKER } from "./pr-comment.js";
|
||||
import { CHANGE_GROUPS, MAX_COMMENT_TARGETS, changeCountText, compareTargets, defaultTargetLabel, foldRecord, strongerGroup, historyLine, orderedRecords, readCommentRecords, recordLabel, recordLine, recordSummary, recordTarget,
|
||||
type ChangeGroup, type CommentTarget, type CommentRecords, type HistoryEntry, type PlatformRecord } from "./pr-comment-record.js";
|
||||
import { CHANGE_GROUPS, MAX_COMMENT_TARGETS, MAX_NAVIGATION_EDGES, MAX_NAVIGATION_NODES, changeCountText, compareTargets, defaultTargetLabel, foldRecord, strongerGroup, historyLine, orderedRecords, readCommentRecords, recordLabel, recordLine, recordSummary, recordTarget,
|
||||
type ChangeGroup, type CommentNavigation, type CommentTarget, type CommentRecords, type HistoryEntry, type NavigationGroup, type NavigationKind, type PlatformRecord } from "./pr-comment-record.js";
|
||||
import { isAccessibilityOnlyChange } from "../contracts/review-validation.js";
|
||||
import type { PublicCaptureHealth, PublicEvidenceSummary } from "../review/evidence-assessment.js";
|
||||
import type { ReviewPresentation } from "../contracts/review.js";
|
||||
@@ -57,6 +57,8 @@ export type PublicCommentState = {
|
||||
artifactOnly?: boolean;
|
||||
/** The PR moved while this run worked; the comment keeps its report under previous runs. */
|
||||
superseded?: boolean;
|
||||
/** report.comment.map: draw the map of the changed screens. */
|
||||
map?: true;
|
||||
};
|
||||
|
||||
type ReviewGroup = ChangeGroup;
|
||||
@@ -310,6 +312,8 @@ export function platformRecordOf(state: PublicCommentState, target?: CommentTarg
|
||||
const scheme = schemeOf(surface.id);
|
||||
record.changes.push({ id: surface.id, route: routeOf(surface), group, description: descriptionOf(surface, group), ...(scheme ? { scheme } : {}) });
|
||||
}
|
||||
const navigation = state.map ? navigationOf(state.review, new Map(record.changes.map(change => [change.id, change.group]))) : undefined;
|
||||
if (navigation) record.navigation = navigation;
|
||||
const notCompared = state.review.surfaces.filter(notComparedChange).length;
|
||||
if (notCompared) record.notCompared = notCompared;
|
||||
record.context = contextLines(state.review).filter(line => line.length);
|
||||
@@ -336,6 +340,104 @@ export function platformRecordOf(state: PublicCommentState, target?: CommentTarg
|
||||
return record;
|
||||
}
|
||||
|
||||
const NAVIGATION_GROUPS: NavigationGroup[] = ["added", "removed", "modified"];
|
||||
const NAVIGATION_KINDS: NavigationKind[] = ["push", "replace", "navigate", "dismissTo", "redirect"];
|
||||
|
||||
/** "/p/[d]" for the route file app/(tabs)/(patterns)/p/[d].tsx: the route without its groups, which a dynamic route's variants share. */
|
||||
function routePattern(route: NonNullable<Surface["head"]>): string {
|
||||
const path = `/${route.logicalPath.replace(/^\/+/, "")}`.split("/").filter(segment => !/^\(.*\)$/.test(segment)).join("/");
|
||||
return plainText(path.replace(/\/index$/, ""), MAX_ROUTE_LENGTH) || "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* The map the comment draws: every route added, removed or changed visually (a screen whose source changed but looks
|
||||
* the same is not one), the routes one step before them, and the transitions among those. A route's appearances and
|
||||
* variants are one node. Switching tabs reaches every tab from every other, so tab transitions are not edges: the
|
||||
* routes a tab switch shows are grouped instead. Removed routes and the transitions into them come from the base.
|
||||
*/
|
||||
function navigationOf(review: PublicReview, groups: Map<string, ChangeGroup>): CommentNavigation | undefined {
|
||||
if (!review.navigation) return undefined;
|
||||
const keyOf = new Map<string, string>();
|
||||
const groupOf = new Map<string, NavigationGroup>();
|
||||
for (const surface of review.surfaces) {
|
||||
const route = surface.head ?? surface.base;
|
||||
if (!route || route.kind === "redirect") continue;
|
||||
const key = routePattern(route);
|
||||
keyOf.set(surface.id.replace(/@(light|dark)$/, ""), key);
|
||||
const group = groups.get(surface.id);
|
||||
if (group !== "added" && group !== "removed" && group !== "modified") continue;
|
||||
const current = groupOf.get(key);
|
||||
if (!current || NAVIGATION_GROUPS.indexOf(group) < NAVIGATION_GROUPS.indexOf(current)) groupOf.set(key, group);
|
||||
}
|
||||
if (!groupOf.size || groupOf.size > MAX_NAVIGATION_NODES) return undefined;
|
||||
const tabs = new Set<string>();
|
||||
const links = new Map<string, { from: string; to: string; kinds: Set<NavigationKind>; base: boolean }>();
|
||||
const add = (edge: NonNullable<PublicReview["navigation"]>["head"]["edges"][number], base: boolean) => {
|
||||
const from = keyOf.get(edge.from), to = keyOf.get(edge.to);
|
||||
if (!from || !to || from === to) return;
|
||||
if (edge.kind === "tab") { tabs.add(to); return; }
|
||||
const link = links.get(`${from}\n${to}`) ?? { from, to, kinds: new Set(), base };
|
||||
link.kinds.add(edge.kind);
|
||||
links.set(`${from}\n${to}`, link);
|
||||
};
|
||||
for (const edge of review.navigation.head.edges) add(edge, false);
|
||||
for (const edge of review.navigation.base.edges) if (groupOf.get(keyOf.get(edge.to) ?? "") === "removed") add(edge, true);
|
||||
// The routes that lead to the most changed ones first, while the map has room.
|
||||
const leads = new Map<string, number>();
|
||||
for (const link of links.values()) if (groupOf.has(link.to) && !groupOf.has(link.from)) leads.set(link.from, (leads.get(link.from) ?? 0) + 1);
|
||||
const before = [...leads].sort(([a, m], [b, n]) => n - m || (a < b ? -1 : 1)).slice(0, MAX_NAVIGATION_NODES - groupOf.size).map(([key]) => key);
|
||||
const keys = [...groupOf.keys(), ...before].sort();
|
||||
const index = new Map(keys.map((key, position) => [key, position]));
|
||||
const edges = [...links.values()].filter(link => index.has(link.from) && index.has(link.to))
|
||||
.sort((a, b) => Number(groupOf.has(b.to)) - Number(groupOf.has(a.to)) || index.get(a.from)! - index.get(b.from)! || index.get(a.to)! - index.get(b.to)!)
|
||||
.slice(0, MAX_NAVIGATION_EDGES)
|
||||
.sort((a, b) => index.get(a.from)! - index.get(b.from)! || index.get(a.to)! - index.get(b.to)!)
|
||||
.map(link => ({ from: index.get(link.from)!, to: index.get(link.to)!, kinds: NAVIGATION_KINDS.filter(kind => link.kinds.has(kind)), ...(link.base ? { base: true as const } : {}) }));
|
||||
if (!edges.length) return undefined;
|
||||
return { nodes: keys.map(key => ({ route: key, ...(groupOf.has(key) ? { group: groupOf.get(key)! } : {}), ...(tabs.has(key) ? { tab: true as const } : {}) })), edges };
|
||||
}
|
||||
|
||||
/** A route as a quoted Mermaid label, with Mermaid's entity codes for what would end the label, the line or the fence. */
|
||||
function mermaidLabel(route: string): string {
|
||||
return `"${plainText(route, MAX_ROUTE_LENGTH).replace(/#/g, "#35;").replace(/"/g, "#quot;").replace(/</g, "#lt;").replace(/>/g, "#gt;").replace(/`/g, "#96;")}"`;
|
||||
}
|
||||
|
||||
/** Outlines, not fills: GitHub draws Mermaid in the reader's theme, and a fixed fill is wrong in one of them. */
|
||||
const MAP_CLASSES: Record<NavigationGroup, string> = {
|
||||
added: "stroke:#1a7f37,stroke-width:3px",
|
||||
modified: "stroke:#bc4c00,stroke-width:3px",
|
||||
removed: "stroke:#cf222e,stroke-width:2px,stroke-dasharray:5 4",
|
||||
};
|
||||
|
||||
function mermaidMap(navigation: CommentNavigation): string[] {
|
||||
const node = (index: number) => `n${index}[${mermaidLabel(navigation.nodes[index]!.route)}]`;
|
||||
const tabs = navigation.nodes.flatMap((entry, index) => entry.tab ? [index] : []);
|
||||
const lines = ["```mermaid", "flowchart LR"];
|
||||
if (tabs.length) lines.push(` subgraph tabs["Tabs"]`, ...tabs.map(index => ` ${node(index)}`), " end");
|
||||
lines.push(...navigation.nodes.flatMap((entry, index) => entry.tab ? [] : [` ${node(index)}`]));
|
||||
lines.push(...navigation.edges.map(edge => ` n${edge.from} ${edge.base ? "-.->" : "-->"}|${edge.kinds.join(", ")}| n${edge.to}`));
|
||||
for (const group of ["added", "modified", "removed"] as const) {
|
||||
const members = navigation.nodes.flatMap((entry, index) => entry.group === group ? [`n${index}`] : []);
|
||||
if (members.length) lines.push(` classDef ${group} ${MAP_CLASSES[group]}`, ` class ${members.join(",")} ${group}`);
|
||||
}
|
||||
return [...lines, "```"];
|
||||
}
|
||||
|
||||
/** One collapsed map per distinct navigation: targets with the same routes share one, named when the targets' maps differ. */
|
||||
function mapSection(ready: PlatformRecord[]): string[] {
|
||||
const maps = new Map<string, { navigation: CommentNavigation; records: PlatformRecord[] }>();
|
||||
for (const record of ready) {
|
||||
if (!record.navigation) continue;
|
||||
const key = JSON.stringify(record.navigation);
|
||||
maps.set(key, { navigation: record.navigation, records: [...(maps.get(key)?.records ?? []), record] });
|
||||
}
|
||||
return [...maps.values()].flatMap(({ navigation, records }) => {
|
||||
const named = maps.size > 1 || records.length < ready.length ? `${records.map(labelOf).join(" · ")} · ` : "";
|
||||
return details(`${named}Map (${plural(navigation.nodes.length, "screen")})`, ["", ...mermaidMap(navigation), "",
|
||||
"Outlined: green added, orange changed, red dashed removed; the others lead to them. Tabs groups the screens a tab switch shows.", ""]);
|
||||
});
|
||||
}
|
||||
|
||||
const commitLink = (repository: string, sha: string) => link(inlineText(sha.slice(0, 8), 8), `https://github.com/${repository.split("/").map(encodeURIComponent).join("/")}/commit/${encodeURIComponent(sha)}`);
|
||||
|
||||
function surfaceLink(report: string, id: string): string | undefined {
|
||||
@@ -431,7 +533,7 @@ function renderChangeRow(row: ChangeRow, records: PlatformRecord[]): string {
|
||||
return `- ${route} — ${inlineText(row.description, MAX_DESCRIPTION_LENGTH)}${where.length ? ` · ${where.join(" · ")}` : ""}`;
|
||||
}
|
||||
|
||||
function changesSection(records: PlatformRecord[], rowCap: number): string[] {
|
||||
function changesSection(records: PlatformRecord[], rowCap: number, withMap: boolean): string[] {
|
||||
const ready = records.filter(record => record.phase === "ready");
|
||||
if (!ready.length) return [];
|
||||
const groups = changeRows(ready);
|
||||
@@ -454,6 +556,7 @@ function changesSection(records: PlatformRecord[], rowCap: number): string[] {
|
||||
content.push("");
|
||||
lines.push(...details(`${GROUP_LABEL[group]} (${rows.length})`, content));
|
||||
}
|
||||
if (withMap) lines.push(...mapSection(ready));
|
||||
const seen = new Set<string>();
|
||||
for (const record of ready) for (const line of record.context ?? []) {
|
||||
if (seen.has(line)) continue;
|
||||
@@ -594,13 +697,13 @@ export function renderCommentRecords(records: CommentRecords, existing?: string,
|
||||
...historySection("", records.history)].join("\n");
|
||||
const first = current[0]!;
|
||||
const repository = repositoryOf(first.links.run);
|
||||
const render = (rowCap: number): string => {
|
||||
const render = (rowCap: number, withMap: boolean): string => {
|
||||
const lines: string[] = [...hidden, heading(current), "",
|
||||
`<sub>base ${commitLink(repository, first.baseSha)} → ${commitLink(repository, first.headSha)}</sub>`, ""];
|
||||
if (first.superseded) lines.push(SUPERSEDED_NOTE, "");
|
||||
lines.push(`| | Device | Result | Report |`, `|---|---|---|---|`,
|
||||
...current.map(record => `| ${labelOf(record)} | ${deviceCell(record)} | ${resultCell(record)} | ${reportCell(record)} |`), "");
|
||||
lines.push(...changesSection(current, rowCap));
|
||||
lines.push(...changesSection(current, rowCap, withMap));
|
||||
lines.push(...validationSection(current));
|
||||
lines.push(...historySection(repository, records.history));
|
||||
const expiries = current.filter(record => record.phase === "ready" && record.links.expiresAt !== undefined).map(record => record.links.expiresAt);
|
||||
@@ -613,9 +716,11 @@ export function renderCommentRecords(records: CommentRecords, existing?: string,
|
||||
lines.push(footer.join(" · "));
|
||||
return lines.join("\n");
|
||||
};
|
||||
// The map goes first when the body is over budget, then the change lists shrink.
|
||||
let rowCap = MAX_ROWS_PER_GROUP;
|
||||
let body = render(rowCap);
|
||||
while (body.length > budget && rowCap > 1) { rowCap = Math.max(1, Math.floor(rowCap / 2)); body = render(rowCap); }
|
||||
let body = render(rowCap, true);
|
||||
if (body.length > budget) body = render(rowCap, false);
|
||||
while (body.length > budget && rowCap > 1) { rowCap = Math.max(1, Math.floor(rowCap / 2)); body = render(rowCap, false); }
|
||||
return body;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,23 @@ export function changeCountText(groups: readonly ChangeGroup[]): string {
|
||||
return [visual ? `${visual} visual change${visual === 1 ? "" : "s"}` : undefined, `${accessibility} accessibility only`].filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
export type NavigationGroup = "added" | "modified" | "removed";
|
||||
export type NavigationKind = "push" | "replace" | "navigate" | "redirect" | "tab" | "dismissTo";
|
||||
const NAVIGATION_GROUPS: NavigationGroup[] = ["added", "modified", "removed"];
|
||||
const NAVIGATION_KINDS: NavigationKind[] = ["push", "replace", "navigate", "redirect", "tab", "dismissTo"];
|
||||
export const MAX_NAVIGATION_NODES = 30;
|
||||
export const MAX_NAVIGATION_EDGES = 80;
|
||||
|
||||
/**
|
||||
* The comment's map: one node per route that was added, removed or changed visually, and per route one step before
|
||||
* one of them; edges index `nodes`. `tab` marks a route a tab switch shows, `base` an edge into a removed route, which
|
||||
* only the base revision's navigation has.
|
||||
*/
|
||||
export type CommentNavigation = {
|
||||
nodes: { route: string; group?: NavigationGroup; tab?: true }[];
|
||||
edges: { from: number; to: number; kinds: NavigationKind[]; base?: true }[];
|
||||
};
|
||||
|
||||
export type SideHealth = { planned: number; captured: number; verified: number; unverified: number; unavailable: number };
|
||||
|
||||
export type PlatformRecord = {
|
||||
@@ -92,6 +109,7 @@ export type PlatformRecord = {
|
||||
notCompared?: number;
|
||||
/** Differences stated once rather than per screen (variants, app-wide source changes). */
|
||||
context?: string[];
|
||||
navigation?: CommentNavigation;
|
||||
diagnostics?: { side?: "base" | "head"; route: string; code: string; message: string; nextAction: string }[];
|
||||
diagnosticCount?: number;
|
||||
failure?: { step: string; message: string };
|
||||
@@ -236,6 +254,8 @@ export function parsePlatformRecord(value: unknown): PlatformRecord | undefined
|
||||
? [{ id: entry.id, route: entry.route, group: entry.group as ChangeGroup, description: entry.description, ...(isString(entry.scheme, 20) ? { scheme: entry.scheme } : {}) }] : []);
|
||||
if (changes.length <= 2000) record.changes = changes;
|
||||
}
|
||||
const navigation = parseNavigation(value.navigation);
|
||||
if (navigation) record.navigation = navigation;
|
||||
if (Array.isArray(value.context)) record.context = value.context.filter((entry): entry is string => isString(entry, 2000)).slice(0, 10);
|
||||
if (Array.isArray(value.diagnostics)) {
|
||||
record.diagnostics = value.diagnostics.flatMap((entry): NonNullable<PlatformRecord["diagnostics"]> => isRecord(entry) && isString(entry.route, 2000) && isString(entry.code, 200)
|
||||
@@ -249,6 +269,25 @@ export function parsePlatformRecord(value: unknown): PlatformRecord | undefined
|
||||
return record;
|
||||
}
|
||||
|
||||
function parseNavigation(value: unknown): CommentNavigation | undefined {
|
||||
if (!isRecord(value) || !Array.isArray(value.nodes) || !Array.isArray(value.edges) || value.nodes.length > MAX_NAVIGATION_NODES
|
||||
|| value.edges.length > MAX_NAVIGATION_EDGES) return undefined;
|
||||
const nodes: CommentNavigation["nodes"] = [];
|
||||
for (const node of value.nodes) {
|
||||
if (!isRecord(node) || !isString(node.route, 200) || !optional(node.group, (group): group is NavigationGroup => NAVIGATION_GROUPS.includes(group as NavigationGroup))
|
||||
|| !(node.tab === undefined || node.tab === true)) return undefined;
|
||||
nodes.push({ route: node.route, ...(node.group ? { group: node.group } : {}), ...(node.tab ? { tab: true } : {}) });
|
||||
}
|
||||
const edges: CommentNavigation["edges"] = [];
|
||||
const isNode = (index: unknown): index is number => isCount(index) && index < nodes.length;
|
||||
for (const edge of value.edges) {
|
||||
if (!isRecord(edge) || !isNode(edge.from) || !isNode(edge.to) || !Array.isArray(edge.kinds) || !edge.kinds.length
|
||||
|| !edge.kinds.every(kind => NAVIGATION_KINDS.includes(kind as NavigationKind)) || !(edge.base === undefined || edge.base === true)) return undefined;
|
||||
edges.push({ from: edge.from, to: edge.to, kinds: [...new Set(edge.kinds as NavigationKind[])], ...(edge.base ? { base: true } : {}) });
|
||||
}
|
||||
return nodes.length && edges.length ? { nodes, edges } : undefined;
|
||||
}
|
||||
|
||||
export function parseHistory(value: unknown): HistoryEntry[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const entries: HistoryEntry[] = [];
|
||||
|
||||
@@ -4,7 +4,8 @@ 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 { MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { loadReport, MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { manifestBody } from "./preview-manifest.js";
|
||||
import { publishCiReportComment, readCiReportInput, type CiReportInput } from "./artifact.js";
|
||||
import { readZipDirectory, readZipEntry } from "./zip-reader.js";
|
||||
import { reviewChangeCount, reviewDevice } from "./pr-comment-body.js";
|
||||
@@ -774,6 +775,19 @@ 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`);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 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 } from "@zip.js/zip.js";
|
||||
import { BlobReader, BlobWriter, Uint8ArrayReader, ZipReader, ZipWriter, Uint8ArrayWriter } 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,6 +54,18 @@ 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.
|
||||
@@ -61,19 +73,30 @@ async function archive(report = reportFixture(), extra = [], imageBytes = png) {
|
||||
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}/report.zip`) {
|
||||
if (preview && url.pathname === `${pagePath}/manifest.json`) {
|
||||
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/zip");
|
||||
response.setHeader("content-length", String(bytes.length));
|
||||
return response.end(bytes);
|
||||
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);
|
||||
}
|
||||
if (preview?.listing && url.pathname === `${pagePath}/reports.json`) {
|
||||
response.setHeader("content-type", "application/json");
|
||||
@@ -431,7 +454,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.deepEqual(preview.queries, ["?target=duo-open"], "the Viewer asks the Worker for the linked target's report");
|
||||
assert.equal(preview.queries[0], "?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);
|
||||
@@ -439,11 +462,15 @@ 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");
|
||||
await expect.poll(() => preview.queries.at(-1)).toBe("?platform=android");
|
||||
// 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");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
@@ -454,14 +481,110 @@ 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.deepEqual(preview.queries, ["?platform=android"]);
|
||||
assert.equal(preview.queries[0], "?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, []);
|
||||
});
|
||||
|
||||
|
||||
@@ -191,6 +191,15 @@ test("report.preview opts into hosted previews with a bounded expiry and an opti
|
||||
assert.throws(() => validateExploreConfig({ ...base(), report: { hosting: "eas" } }), /report/);
|
||||
});
|
||||
|
||||
test("report.comment.map opts the PR comment into its map of changed screens, beside or without a hosted preview", () => {
|
||||
assert.deepEqual(validateExploreConfig({ ...base(), report: { comment: { map: true } } }).report, { comment: { map: true } });
|
||||
assert.deepEqual(validateExploreConfig({ ...base(), report: { comment: { map: false }, preview: { hosting: "eas" } } }).report,
|
||||
{ comment: { map: false }, preview: { hosting: "eas", expiresAfterDays: 30 } });
|
||||
for (const comment of [{}, { map: "yes" }, { map: true, graph: true }, true]) {
|
||||
assert.throws(() => validateExploreConfig({ ...base(), report: { comment } }), /Invalid .expo-explore\/config.yaml: report.comment/);
|
||||
}
|
||||
});
|
||||
|
||||
test("platforms: a flat config is iOS-only and resolves to itself", () => {
|
||||
const config = validateExploreConfig(base());
|
||||
assert.deepEqual(configPlatforms(config), ["ios"]);
|
||||
|
||||
@@ -8,6 +8,9 @@ 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';
|
||||
|
||||
@@ -229,6 +232,28 @@ 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,6 +12,8 @@ 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");
|
||||
@@ -53,6 +55,12 @@ 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");
|
||||
@@ -66,7 +74,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 } = {}) {
|
||||
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 } = {}) {
|
||||
let deploys = 0;
|
||||
let latestComment = existingComment;
|
||||
const calls = []; const captured = {};
|
||||
@@ -100,7 +108,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|api\/v1))?$/.exec(url.pathname);
|
||||
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);
|
||||
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")
|
||||
@@ -119,6 +127,14 @@ 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" };
|
||||
@@ -171,9 +187,11 @@ 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);
|
||||
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 wrong = token.endsWith("a") ? `${token.slice(0, -1)}b` : `${token.slice(0, -1)}a`;
|
||||
assert.deepEqual(previewPaths, [`/p/${token}`, `/p/${token}/api/v1`, `/p/${token}/report.zip`, "/", `/p/${wrong}`, `/p/${wrong}/report.zip`, `/p/${token}/viewer/index.html`]);
|
||||
// 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.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;
|
||||
@@ -335,9 +353,11 @@ 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);
|
||||
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 wrong = token.endsWith("a") ? `${token.slice(0, -1)}b` : `${token.slice(0, -1)}a`;
|
||||
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`,
|
||||
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`,
|
||||
"/", `/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");
|
||||
@@ -408,7 +428,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 rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
await asExploration(reportPath);
|
||||
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,
|
||||
@@ -498,7 +518,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 rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
await asExploration(reportPath);
|
||||
const eas = easFixture();
|
||||
const run = (node, [bin, ...args], options) => {
|
||||
const result = eas.run(node, [bin, ...args], options);
|
||||
@@ -617,7 +637,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 rename(join(reportPath, "review.json"), join(reportPath, "exploration.json"));
|
||||
await asExploration(reportPath);
|
||||
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 });
|
||||
@@ -754,3 +774,12 @@ 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"));
|
||||
});
|
||||
@@ -31,8 +31,10 @@ for (const provider of ['expo-router', 'react-navigation']) {
|
||||
const before = f.requests.length;
|
||||
const output = join(f.root, 'review');
|
||||
const result = await runPublicCi({ baseProject: f.baseProject, headProject: f.headProject, pullRequestPath: f.pullRequestPath, output,
|
||||
config: f.config, environment: { ...f.environment, EXPLORE_CAPTURE_CACHE: baseline.directory }, transport: f.transport, runner: f.runner, now: f.now, sleep: f.sleep });
|
||||
config: { ...f.config, report: { comment: { map: true } } }, environment: { ...f.environment, EXPLORE_CAPTURE_CACHE: baseline.directory },
|
||||
transport: f.transport, runner: f.runner, now: f.now, sleep: f.sleep });
|
||||
const plan = JSON.parse(await readFile(join(output, 'execution-plan.json'), 'utf8'));
|
||||
assert.equal(JSON.parse(await readFile(result.inputPath, 'utf8')).commentState.map, true, 'report.comment.map reaches the comment the publish job renders');
|
||||
assert.equal(result.review.contract, 'explore.review');
|
||||
assert.equal(result.review.runtime.appVersion, '3.0.0', 'the Viewer header shows the captured app version');
|
||||
assert.equal(result.review.runtime.appBuildNumber, '7', 'the Viewer header shows the captured build number');
|
||||
@@ -122,6 +124,7 @@ test('unreachable screens do not fail CI: both revisions, the report and an Inco
|
||||
.map(line => line.replace('(home)', `(${result.review.surfaces.find(surface => surface.head?.route === '/home')?.id})`)).sort());
|
||||
assert.ok(progress.includes('2 screens are unavailable in this report'));
|
||||
const reportInput = JSON.parse(await readFile(join(output, 'report-input.json'), 'utf8'));
|
||||
assert.equal(reportInput.commentState.map, undefined, 'the comment draws no map unless the config asks for one');
|
||||
assert.equal(reportInput.publicReview.surfaces.filter(surface => surface.headOutcome && surface.headOutcome.status !== 'captured').length, 0);
|
||||
assert.equal(reportInput.publicReview.surfaces.filter(surface => surface.headOutcome?.landing === 'unverified' && surface.headImage).length, 1);
|
||||
assert.equal(reportInput.publicReview.surfaces.filter(surface => surface.baseOutcome && surface.baseOutcome.status !== 'captured').length, 1);
|
||||
|
||||
@@ -588,3 +588,57 @@ test('a comment written by a per-platform version keeps parsing, and malformed t
|
||||
const many = Array.from({ length: 10 }, (_, index) => line(`t${index}`, { ...valid, target: `t${index}` }));
|
||||
assert.equal(parse(...many).length, 8, 'a comment holds at most one record per configurable target');
|
||||
});
|
||||
|
||||
test('with report.comment.map, the map draws the added, removed and visually changed screens, the screens one step before them, and tabs as a group', async () => {
|
||||
const { readCommentRecords } = await import('../../dist/report/pr-comment-body.js');
|
||||
const edge = (from, to, kind) => ({ from, to, kind, sourceFile: 'src/app/_layout.tsx', provenance: 'source' });
|
||||
const graph = edges => ({ contract: 'explore.navigation', edges, modalSurfaceIds: [], unresolved: [] });
|
||||
const base = evidenceReview();
|
||||
const dark = surface('settings@dark', 'modified', { route: '/settings', extra: base.surfaces[2].review && { review: base.surfaces[2].review, visual: base.surfaces[2].visual } });
|
||||
const withNavigation = { ...base, surfaces: [...base.surfaces, dark], navigation: {
|
||||
// home is a redirect, not a screen; cats and settings are tabs; cats changed only in source, so it is drawn as the way to care-guide.
|
||||
head: graph([edge('cats', 'care-guide', 'push'), edge('cats', 'settings', 'tab'), edge('settings', 'cats', 'tab'), edge('home', 'cats', 'replace')]),
|
||||
base: graph([edge('cats', 'sweet-bee', 'push'), edge('cats', 'settings', 'tab')]),
|
||||
} };
|
||||
// Off by default: most reviews do not need it, so a config opts in with report.comment.map.
|
||||
assert.ok(!/<summary>Map/.test(renderPublicComment(state({ artifactOnly: true, review: withNavigation }))));
|
||||
assert.equal(platformRecordOf(state({ review: withNavigation })).navigation, undefined);
|
||||
const body = renderPublicComment(state({ artifactOnly: true, map: true, review: withNavigation }));
|
||||
assert.deepEqual(summaries(body), ['🟩 Added (1)', '🟥 Removed (1)', '🟧 Modified (2)', 'Map (4 screens)', 'Validation · iOS 🟩 8/8 captured']);
|
||||
const map = body.slice(body.indexOf('```mermaid'), body.indexOf('```\n', body.indexOf('```mermaid')) + 3);
|
||||
assert.equal(map, ['```mermaid', 'flowchart LR', ' subgraph tabs["Tabs"]', ' n0["/cats"]', ' n3["/settings"]', ' end',
|
||||
' n1["/cats/care-guide"]', ' n2["/cats/sweet-bee"]', ' n0 -->|push| n1', ' n0 -.->|push| n2',
|
||||
' classDef added stroke:#1a7f37,stroke-width:3px', ' class n1 added', ' classDef modified stroke:#bc4c00,stroke-width:3px', ' class n3 modified',
|
||||
' classDef removed stroke:#cf222e,stroke-width:2px,stroke-dasharray:5 4', ' class n2 removed', '```'].join('\n'));
|
||||
assert.ok(body.indexOf('<summary>🟧 Modified') < body.indexOf('<summary>Map') && body.indexOf('<summary>Map') < body.indexOf('<summary>Validation'));
|
||||
assert.match(body, /<summary>Map \(4 screens\)<\/summary>\n\n```mermaid\n/, 'a blank line opens the fence inside the collapsible');
|
||||
assert.deepEqual(readCommentRecords(body).current.ios.navigation, platformRecordOf(state({ map: true, review: withNavigation })).navigation, 'the map is carried in the record');
|
||||
|
||||
// A label cannot end itself, its line or the fence.
|
||||
const odd = { ...withNavigation, surfaces: withNavigation.surfaces.map(entry => entry.id === 'care-guide'
|
||||
? { ...entry, head: { ...entry.head, logicalPath: 'cats/"a"#<b>`c`' } } : entry) };
|
||||
assert.match(renderPublicComment(state({ map: true, review: odd })), /\n {2}n1\["\/cats\/#quot;a#quot;#35;#lt;b#gt;#96;c#96;"\]\n/);
|
||||
// No navigation, or nothing changed visually: no map.
|
||||
assert.ok(!summaries(renderPublicComment(state({ map: true }))).includes('Map (4 screens)'));
|
||||
const unchanged = { ...withNavigation, surfaces: withNavigation.surfaces.filter(entry => entry.status !== 'added' && entry.status !== 'removed' && !entry.id.startsWith('settings')) };
|
||||
assert.ok(!/<summary>Map/.test(renderPublicComment(state({ map: true, review: unchanged }))));
|
||||
});
|
||||
|
||||
test('the map is dropped before the change lists shrink, and a malformed map is dropped from the record', async () => {
|
||||
const { encodeRecordPayload } = await import('../../dist/report/pr-comment-record.js');
|
||||
const { readCommentRecords, renderCommentRecords } = await import('../../dist/report/pr-comment-body.js');
|
||||
const record = { ...platformRecordOf(state()), navigation: { nodes: [{ route: '/a', group: 'modified' }, { route: '/b' }], edges: [{ from: 1, to: 0, kinds: ['push'] }] } };
|
||||
const records = { current: { ios: record }, history: [] };
|
||||
assert.match(renderCommentRecords(records), /<summary>Map \(2 screens\)<\/summary>/);
|
||||
const tight = renderCommentRecords(records, undefined, renderCommentRecords(records).length - 1);
|
||||
assert.ok(!tight.includes('```mermaid'));
|
||||
assert.match(tight, /<summary>🟧 Modified \(1\)<\/summary>/);
|
||||
const parse = navigation => readCommentRecords(`<!-- expo-explore-record:ios:${encodeRecordPayload({ ...record, navigation })} -->`).current.ios;
|
||||
assert.deepEqual(parse(record.navigation).navigation, record.navigation);
|
||||
for (const navigation of [{ ...record.navigation, edges: [{ from: 0, to: 2, kinds: ['push'] }] }, { ...record.navigation, edges: [{ from: 0, to: 1, kinds: ['teleport'] }] },
|
||||
{ ...record.navigation, nodes: [{ route: '/a', group: 'needs-review' }, { route: '/b' }] }, { nodes: [], edges: [] }]) {
|
||||
const parsed = parse(navigation);
|
||||
assert.ok(parsed, 'the rest of the record still parses');
|
||||
assert.equal(parsed.navigation, undefined);
|
||||
}
|
||||
});
|
||||
@@ -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>/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.
|
||||
- `/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.
|
||||
- `/` 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,8 +115,9 @@ 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.replace(/<div id="root">.*<\/div>/s, '<div id="root"></div>') !== stagedHtml) {
|
||||
|| !body.includes(preload) || body.replace(preload, "").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,6 +6,7 @@
|
||||
* 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. */
|
||||
@@ -132,12 +133,44 @@ 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, kept for the life of the isolate; defaults to a module-level cache. */
|
||||
cache?: Map<string, Promise<LoadedReport | undefined>>;
|
||||
/** 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>;
|
||||
};
|
||||
|
||||
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>>();
|
||||
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();
|
||||
|
||||
/**
|
||||
* `GET /p/<token>` serves the Viewer shell to browsers and the report's Markdown index to anything
|
||||
@@ -158,7 +191,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" : undefined);
|
||||
const route = match[2] ?? (match[3] ? "api" : match[4] ? "asset" : 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"`;
|
||||
@@ -168,8 +201,13 @@ 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 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 });
|
||||
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 });
|
||||
}
|
||||
if (expired) return previewExpired(config.expiresAt!);
|
||||
if (route === "reports.json") {
|
||||
@@ -179,7 +217,17 @@ 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);
|
||||
const loaded = await loadedReport(url.origin, report, 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;
|
||||
if (!loaded) {
|
||||
if (route !== undefined) return previewNotFound();
|
||||
const headers = baseHeaders("text/html; charset=utf-8");
|
||||
@@ -187,6 +235,7 @@ 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");
|
||||
@@ -220,6 +269,57 @@ 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>';
|
||||
@@ -228,29 +328,89 @@ export function shellWithIndex(indexHtml: string, indexBlock: string): string {
|
||||
return body === -1 ? indexHtml : `${indexHtml.slice(0, body)}${indexBlock}${indexHtml.slice(body)}`;
|
||||
}
|
||||
|
||||
async function loadedReport(origin: string, report: PreviewReport | undefined, config: PreviewConfig, options: PreviewRequestOptions): Promise<{ report: PreviewReport; loaded: LoadedReport } | undefined> {
|
||||
/**
|
||||
* 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> {
|
||||
if (!report) return undefined;
|
||||
const cache = options.cache ?? reportCache;
|
||||
const loading = options.loading ?? reportLoading;
|
||||
const key = `${origin}${report.path}`;
|
||||
let pending = cache.get(key);
|
||||
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);
|
||||
if (!pending) {
|
||||
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));
|
||||
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); });
|
||||
}
|
||||
const loaded = await pending;
|
||||
return loaded ? { report, loaded } : undefined;
|
||||
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 };
|
||||
}
|
||||
|
||||
async function decryptedBytes(origin: string, reportPath: string, config: PreviewConfig, options: PreviewRequestOptions): Promise<Uint8Array | 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> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
const subtle = options.subtle ?? crypto.subtle;
|
||||
const upstream = await fetchImpl(new URL(reportPath, origin).href, { headers: { accept: "application/octet-stream" } });
|
||||
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";
|
||||
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(
|
||||
@@ -259,8 +419,12 @@ 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 plain = await decryptedBytes(origin, reportPath, config, options);
|
||||
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();
|
||||
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) {
|
||||
function deployment(files: Record<string, Uint8Array<ArrayBuffer>>, env: PreviewEnvironment, now?: () => number, budget?: { held: number; peak: 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(), ...(now ? { now } : {}) };
|
||||
const options = { env, indexHtml: html, fetchImpl, subtle, cache: new Map(), loading: new Map(), manifests: new Map(), oversized: new Set<string>(), ...(now ? { now } : {}), ...(budget ? { budget } : {}) };
|
||||
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><script type="module"/);
|
||||
assert.match(shell, /<\/section><\/div><link rel="preload" [^>]*><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,3 +363,111 @@ 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)");
|
||||
});
|
||||
@@ -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, optionalStorage, releaseEmbeddedArtifactUrl, resolveEmbeddedArtifactUrl, viewerLocation } from "./utils/embedded-report";
|
||||
import { isEmbeddedArtifactUrl, leaseEmbeddedArtifactUrl, optionalStorage, 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,7 +287,8 @@ export function App() {
|
||||
{...(droppable ? { onOpenFile: openFile } : {})}
|
||||
{...(droppable && source.status === "failed" ? { onRetry: retry } : {})} />;
|
||||
}
|
||||
return <ViewerApp />;
|
||||
// A hosted preview switches targets in place; the new report gets a fresh Viewer.
|
||||
return <ViewerApp key={source.reportKey} />;
|
||||
}
|
||||
|
||||
function ViewerApp() {
|
||||
@@ -1384,18 +1385,20 @@ 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.
|
||||
// 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.
|
||||
let state: "pending" | "shown" | "gone" = "pending";
|
||||
resolveEmbeddedArtifactUrl(appIcon, "eager").then(
|
||||
const lease = leaseEmbeddedArtifactUrl(appIcon, "eager");
|
||||
lease.url.then(
|
||||
(url) => {
|
||||
if (state === "gone") return void releaseEmbeddedArtifactUrl(appIcon);
|
||||
if (state === "gone") return void lease.release();
|
||||
state = "shown";
|
||||
icon?.setAttribute("href", url);
|
||||
},
|
||||
() => icon?.setAttribute("href", fallback),
|
||||
() => { if (state !== "gone") icon?.setAttribute("href", fallback); },
|
||||
);
|
||||
return () => {
|
||||
if (state === "shown") releaseEmbeddedArtifactUrl(appIcon);
|
||||
if (state === "shown") lease.release();
|
||||
state = "gone";
|
||||
};
|
||||
}, [index, map, selectedScreenId]);
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -152,7 +153,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); window.location.assign(sibling.url); },
|
||||
checked: false, onSelect: () => { setPlatformOpen(false); if (!REPORT_SOURCE.switchTarget(target.id, sibling.url)) 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 { BlobReader, ZipReader, type FileEntry } from "@zip.js/zip.js";
|
||||
import 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,6 +66,21 @@ 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);
|
||||
@@ -213,7 +228,49 @@ function validateReport(value: unknown, expected?: ArtifactIdentity, fileName?:
|
||||
return { report: { ...report, review }, identity: expected ?? own };
|
||||
}
|
||||
|
||||
type ImageEntry = { entry: FileEntry; metadata: EmbeddedScreenshot; extension: "png" | "jpg" | "mp4" };
|
||||
/** 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;
|
||||
}
|
||||
/** Eager screenshots (the Inspector's) are decoded before lazy ones (canvas nodes and thumbnails). */
|
||||
export type ScreenshotPriority = "eager" | "lazy";
|
||||
type ImageLoad = {
|
||||
@@ -233,6 +290,8 @@ 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
|
||||
@@ -248,8 +307,9 @@ 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 reader: ZipReader<Blob>, report: ArtifactReport | ExplorationReport,
|
||||
private constructor(private readonly close: () => void, 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 }
|
||||
@@ -259,6 +319,8 @@ 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>();
|
||||
@@ -280,6 +342,30 @@ 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>();
|
||||
@@ -290,34 +376,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.uncompressedSize <= 0 || entry.uncompressedSize > ARTIFACT_LIMITS.image) {
|
||||
if (!extension || !entry || entry.size <= 0 || entry.size > 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.uncompressedSize } });
|
||||
metadata: { mimeType: extension === "png" ? "image/png" : extension === "mp4" ? "video/mp4" : "image/jpeg", byteLength: entry.size } });
|
||||
imagePaths.add(asset.path);
|
||||
}
|
||||
return images;
|
||||
};
|
||||
const explorationEntry = files.get("exploration.json");
|
||||
if (explorationEntry && !files.has("review.json")) {
|
||||
if (explorationEntry.uncompressedSize > ARTIFACT_LIMITS.metadata) throw new ReportFileError("too-large", `${describe(fileName)} has an exploration index over the browser limit.`);
|
||||
if (explorationEntry.size > 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 readEntry(explorationEntry, ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
try { parsed = JSON.parse(await (await explorationEntry.read(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(reader, report, images, bound);
|
||||
return new ArtifactReportArchive(close, report, images, bound);
|
||||
}
|
||||
const metadata = files.get("review.json");
|
||||
if (!metadata || metadata.uncompressedSize > ARTIFACT_LIMITS.metadata) {
|
||||
if (!metadata || metadata.size > 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 readEntry(metadata, ARTIFACT_LIMITS.metadata, "application/json")).text()); }
|
||||
try { parsed = JSON.parse(await (await metadata.read(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);
|
||||
@@ -326,10 +412,7 @@ 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(reader, report, images, bound);
|
||||
} catch (error) {
|
||||
await reader.close();
|
||||
throw error;
|
||||
return new ArtifactReportArchive(close, report, images, bound);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,6 +428,8 @@ 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) {
|
||||
@@ -388,7 +473,22 @@ export class ArtifactReportArchive {
|
||||
this.loads.clear();
|
||||
this.retained.clear();
|
||||
this.retainedBytes = 0;
|
||||
void this.reader.close();
|
||||
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();
|
||||
}
|
||||
|
||||
private async decode(load: ImageLoad): Promise<string> {
|
||||
@@ -396,7 +496,7 @@ export class ArtifactReportArchive {
|
||||
await this.acquireSlot(load);
|
||||
try {
|
||||
if (this.disposed) throw new Error("This report was closed.");
|
||||
const blob = await readEntry(image.entry, ARTIFACT_LIMITS.image, image.metadata.mimeType);
|
||||
const blob = await image.entry.read(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"
|
||||
@@ -411,10 +511,11 @@ 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);
|
||||
if (load.users > 0) load.url = url;
|
||||
const current = this.loads.get(load.sha256) === load;
|
||||
if (current && load.users > 0) load.url = url;
|
||||
else {
|
||||
// Everyone let go while it decoded; keep the finished work for a quick return.
|
||||
this.loads.delete(load.sha256);
|
||||
// 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);
|
||||
this.retain(load.sha256, url);
|
||||
}
|
||||
return url;
|
||||
@@ -468,10 +569,22 @@ 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 <= RETAINED_SCREENSHOTS && this.retainedBytes <= RETAINED_SCREENSHOT_BYTES) break;
|
||||
if (this.retained.size <= this.retainedLimit && this.retainedBytes <= RETAINED_SCREENSHOT_BYTES) break;
|
||||
this.retained.delete(oldest);
|
||||
this.retainedBytes -= old.bytes;
|
||||
URL.revokeObjectURL(old.url);
|
||||
@@ -482,7 +595,14 @@ export class ArtifactReportArchive {
|
||||
export let activeArtifactReport: ArtifactReportArchive | undefined;
|
||||
|
||||
function activate(archive: ArtifactReportArchive): ArtifactReportArchive {
|
||||
activeArtifactReport?.dispose();
|
||||
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 = archive;
|
||||
return archive;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,16 @@ 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,7 +1,8 @@
|
||||
import type { EmbeddedReport } from "../../../src/contracts/standalone-report";
|
||||
import {
|
||||
artifactIdentity, isReportPage, openCachedReport, openReportBlob, openReportFile, previewReportUrl, reportDownloadUrl,
|
||||
reportFileName, ReportFileError, workflowRunUrl, type ArtifactIdentity, type ArtifactLoadProgress, type ReportFileErrorCode,
|
||||
ARTIFACT_LIMITS, ArtifactReportArchive, artifactIdentity, isReportPage, isReportTargetId, openCachedReport, openReportFile, previewAssetUrl,
|
||||
previewManifestUrl, previewReportsUrl, previewToken, reportDownloadUrl, reportFileName, reportTarget, ReportFileError,
|
||||
showArchive, workflowRunUrl, type ArtifactIdentity, type ArtifactLoadProgress, type ReportFileErrorCode,
|
||||
} from "./artifact-report";
|
||||
|
||||
export type ReportSourceStatus = "checking-cache" | "downloading" | "awaiting-file" | "opening" | "ready" | "failed";
|
||||
@@ -13,23 +14,41 @@ 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.
|
||||
* 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.
|
||||
*/
|
||||
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 report URL; the page downloads it instead of asking for a file. */
|
||||
readonly previewUrl?: string;
|
||||
/** A hosted preview's token and linked target; the page downloads its report instead of asking for a file. */
|
||||
private readonly preview?: PreviewPage;
|
||||
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);
|
||||
@@ -39,26 +58,35 @@ export class ReportSource {
|
||||
getSnapshot = (): ReportSourceSnapshot => this.snapshot;
|
||||
|
||||
constructor(page?: URL) {
|
||||
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) { this.linkError = error instanceof Error ? error.message : "Invalid report link."; }
|
||||
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) {
|
||||
try { const identity = artifactIdentity(page!); if (identity) this.linkIdentity = identity; }
|
||||
catch (error) { linkError = error instanceof Error ? error.message : "Invalid report link."; }
|
||||
}
|
||||
if (linkError) this.linkError = linkError;
|
||||
this.snapshot = {
|
||||
status: !this.reportPage ? "ready" : this.previewUrl ? "downloading" : this.linkError ? "failed" : this.linkIdentity ? "checking-cache" : "awaiting-file",
|
||||
progress: this.previewUrl ? { phase: "downloading" } : { phase: "cache" },
|
||||
status: !this.reportPage ? "ready" : this.linkError ? "failed" : this.preview ? "downloading" : this.linkIdentity ? "checking-cache" : "awaiting-file",
|
||||
progress: this.preview ? { 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.previewUrl; }
|
||||
get canRetry(): boolean { return this.reportPage && !this.linkError && !this.preview; }
|
||||
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; }
|
||||
@@ -72,63 +100,186 @@ 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.previewUrl) return this.pending ??= this.download(this.previewUrl).finally(() => { this.pending = undefined; });
|
||||
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 !== "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({ 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 }))
|
||||
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 }))
|
||||
.finally(() => { this.pending = undefined; });
|
||||
return this.pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
private async download(url: string): Promise<void> {
|
||||
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 ?? "";
|
||||
try {
|
||||
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 });
|
||||
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);
|
||||
} catch (error) {
|
||||
this.set({ status: "failed", progress: this.snapshot.progress,
|
||||
if (generation !== this.generation) return;
|
||||
this.set({ ...this.snapshot, status: "failed",
|
||||
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 } : {};
|
||||
this.set({ status: "opening", progress: { phase: "verifying" }, ...linked, fileName: file.name });
|
||||
// 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 });
|
||||
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 });
|
||||
this.set({ status: "ready", progress: this.snapshot.progress, identity: archive.identity, fileName: file.name, reportKey });
|
||||
} catch (error) {
|
||||
this.set({ status: "failed", progress: this.snapshot.progress, ...linked, fileName: file.name,
|
||||
this.set({ status: "failed", progress: this.snapshot.progress, ...linked, fileName: file.name, reportKey,
|
||||
error: error instanceof Error && error.message ? error.message : "The report could not be opened.",
|
||||
errorCode: error instanceof ReportFileError ? error.code : "invalid" });
|
||||
}
|
||||
@@ -137,10 +288,18 @@ 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" }, ...(this.linkIdentity ? { identity: this.linkIdentity } : {}) });
|
||||
this.set({ status: "awaiting-file", progress: { phase: "cache" }, reportKey: this.snapshot.reportKey, ...(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. */
|
||||
|
||||