From 43e056036d3fa48e7b980ef4d274eb1288b6892e Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Sun, 29 Nov 2026 11:30:08 -0600 Subject: [PATCH] Publish declared source for live screen review Give reviewers the actual HTML and assets at the width they choose, so new Projects can publish from machines without a browser. Keep exact file bytes in the original request so a retry or reviewed compilation uses the same source. Check the live screen capability before uploading against an older API while preserving other commands on that API line. --- CHANGELOG.md | 9 + README.md | 4 +- docs/commands.md | 136 ++-- docs/errors.md | 18 +- package-lock.json | 19 +- package.json | 5 +- release/compatibility.json | 2 +- scripts/check-pack.js | 2 +- src/api-response.js | 8 - src/cli.js | 3 +- src/commands/sketches.js | 34 +- src/plan-state.js | 2 +- src/review-theme.js | 143 +--- src/sketch-capture.js | 939 ------------------------- src/sketch-sources.js | 165 +++++ test/package.test.js | 1 - test/sketches.test.js | 1367 ++++++++---------------------------- 17 files changed, 567 insertions(+), 2290 deletions(-) delete mode 100644 src/sketch-capture.js create mode 100644 src/sketch-sources.js diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d96ea..9b0b242 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ carry no release status. The `v` tag and npm show whether a version is Entries start with the first version prepared after this file was added, and earlier versions have none. The repository's [tags](https://github.com/firstdraft/cli/tags) identify the source of each published version. +## 0.12.2 + +- `firstdraft sketches publish` now uploads the working Plan, screen HTML and declared assets. The Project + displays each screen at the reviewer’s chosen width. Chrome is no longer required on the computer that publishes. + Declare each HTML screen and all of its local assets in `sketches/board.json` and keep the files for Compile. +- Fresh publications require live screen support, introduced in API contract 0.10.2. Other CLI commands keep + their API 0.10.x range and Plan format 0.24. An interrupted publication can still replay its original request, + including a capture created by an earlier CLI. + ## 0.12.1 - Run `firstdraft sketches publish` in a hosted interview or in a Project that already has a pushed Plan. diff --git a/README.md b/README.md index df440a4..30fa5fb 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ is the Codespaces fallback. - direct Compile-and-materialize; - retained Compilation inspection, cancellation, and artifact download; - terminal output, exit status, and recovery contracts; -- the npm package with local Chrome screen capture; and +- the npm package with live screen publication; and - package provenance and publication. The Service owns Foundation Plan meaning and server-side lifecycle. Skills own the agent conversation. This @@ -95,7 +95,7 @@ The published package: - installs the firstdraft executable; - runs reviewed JavaScript source directly; -- uses Playwright Core for local screen capture and has no install scripts; +- publishes declared HTML and assets without a browser installation; - sends nothing in the background or beyond the command the caller runs. [What the CLI sends](docs/commands.md#what-the-cli-sends) lists each command's requests and their `FirstDraft-Client` header: CLI and plugin versions, agent, and operating system. `report` and `note` read the account first and, only with reports on, print their exact body and then send it; diff --git a/docs/commands.md b/docs/commands.md index 8265d11..48ca3c6 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -8,41 +8,41 @@ login in one command or in two steps that an agent runs, local Foundation Plan initialization, hosted Project creation and screen review, local application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling, direct Compile-and-materialize, retained-Compilation inspection and cancellation, the account's report setting, progress and failure reports, notes, and maintenance-item listing, -inspection, resolution, deferral, and owner questions. It requires API contract `0.10.0` or a later patch on the same minor line. The [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG.md) describes each version. +inspection, resolution, deferral, and owner questions. The CLI accepts service API 0.10.x. Fresh live screen publication requires API 0.10.2 or a later patch on that line. The [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG.md) describes each version. [What the CLI sends](#what-the-cli-sends) lists every request and what it carries. ## Command map -| Command | Network | Purpose | -| ------------------------------------- | ------- | ------------------------------------------------------------------------- | -| `firstdraft start` | Yes | Check versions, login, and reports before other work | -| `firstdraft project start` | Yes | Create or reopen the owner’s Project before a Plan | -| `firstdraft sketches publish` | Yes | Capture the selected local screens and publish them with the working Plan | -| `firstdraft plan init` | No | Create an empty local Foundation Plan and Project identity | -| `firstdraft generate application-key` | No | Preview deterministic name-to-key derivation | -| `firstdraft generate uuid` | No | Generate one or more Foundation Plan subject identities | -| `firstdraft login` | Yes | Approve the CLI in a browser and save a token for an origin | -| `firstdraft login --no-wait` | Yes | Start a device login for an agent and exit | -| `firstdraft login --finish` | Yes | Finish that device login once the person approved | -| `firstdraft logout` | Yes | Revoke and remove the saved token for an origin | -| `firstdraft plan push` | Yes | Conditionally submit the exact whole Plan | -| `firstdraft plan status` | Yes | Read or wait for the current whole-graph analysis | -| `firstdraft plan setup` | Yes | Read the reviewed Plan’s setup steps and their Project link | -| `firstdraft plan compile` | Yes | Compile the Plan or approved review into the current folder | -| `firstdraft compilation status` | Yes | Inspect a retained Compilation by ID | -| `firstdraft compilation download` | Yes | Verify and materialize a successful retained Compilation | -| `firstdraft compilation cancel` | Yes | Cancel a queued or running Compilation by ID | -| `firstdraft account` | Yes | Show whether the account sends reports | -| `firstdraft report progress` | Yes | Print, then send, how far a generated application has come | -| `firstdraft report failure` | Yes | Print, then send, an unexpected failure in generated code | -| `firstdraft note unstated_request` | Yes | Print, then send, a request the Plan could not state | -| `firstdraft note unclear_guidance` | Yes | Print, then send, a Skill page or diagnostic that was unclear | -| `firstdraft note wrong_output` | Yes | Print, then send, analysis or generated code that was wrong | -| `firstdraft maintain` | Yes | List a deployed Environment's open items | -| `firstdraft maintain show` | Yes | Read one item with its evidence | -| `firstdraft maintain resolve` | Yes | Resolve one item with a reason | -| `firstdraft maintain defer` | Yes | Set one item aside until a time | -| `firstdraft maintain ask-owner` | Yes | Record a question for the owner about one item | +| Command | Network | Purpose | +| ------------------------------------- | ------- | --------------------------------------------------------------------- | +| `firstdraft start` | Yes | Check versions, login, and reports before other work | +| `firstdraft project start` | Yes | Create or reopen the owner’s Project before a Plan | +| `firstdraft sketches publish` | Yes | Read the declared screen files and publish them with the working Plan | +| `firstdraft plan init` | No | Create an empty local Foundation Plan and Project identity | +| `firstdraft generate application-key` | No | Preview deterministic name-to-key derivation | +| `firstdraft generate uuid` | No | Generate one or more Foundation Plan subject identities | +| `firstdraft login` | Yes | Approve the CLI in a browser and save a token for an origin | +| `firstdraft login --no-wait` | Yes | Start a device login for an agent and exit | +| `firstdraft login --finish` | Yes | Finish that device login once the person approved | +| `firstdraft logout` | Yes | Revoke and remove the saved token for an origin | +| `firstdraft plan push` | Yes | Conditionally submit the exact whole Plan | +| `firstdraft plan status` | Yes | Read or wait for the current whole-graph analysis | +| `firstdraft plan setup` | Yes | Read the reviewed Plan’s setup steps and their Project link | +| `firstdraft plan compile` | Yes | Compile the Plan or approved review into the current folder | +| `firstdraft compilation status` | Yes | Inspect a retained Compilation by ID | +| `firstdraft compilation download` | Yes | Verify and materialize a successful retained Compilation | +| `firstdraft compilation cancel` | Yes | Cancel a queued or running Compilation by ID | +| `firstdraft account` | Yes | Show whether the account sends reports | +| `firstdraft report progress` | Yes | Print, then send, how far a generated application has come | +| `firstdraft report failure` | Yes | Print, then send, an unexpected failure in generated code | +| `firstdraft note unstated_request` | Yes | Print, then send, a request the Plan could not state | +| `firstdraft note unclear_guidance` | Yes | Print, then send, a Skill page or diagnostic that was unclear | +| `firstdraft note wrong_output` | Yes | Print, then send, analysis or generated code that was wrong | +| `firstdraft maintain` | Yes | List a deployed Environment's open items | +| `firstdraft maintain show` | Yes | Read one item with its evidence | +| `firstdraft maintain resolve` | Yes | Resolve one item with a reason | +| `firstdraft maintain defer` | Yes | Set one item aside until a time | +| `firstdraft maintain ask-owner` | Yes | Record a question for the owner about one item | ## Hosted screens @@ -71,25 +71,19 @@ Write the ordered screen list to `sketches/board.json`. Paths are relative to `s List the Plan development-record UUIDs shown on a screen in `sample_keys` and related Plan subject UUIDs in `plan_subjects`. Both lists default to empty. Use `data-plan-pointer` with an RFC 6901 JSON Pointer to put a scalar value from the exact -working Plan into an element's text during capture. Keep readable fallback text for directly opening the HTML. -Use an optional element key, such as `data-sketch-key="nominee-arrival"`, for a card or control you want to recognize -across layout changes. Keys of 1–80 ASCII letters, digits, underscores and hyphens must start with a letter or digit. -Use visible text, `aria-label`, or `data-sketch-label` to name it. Services that support element selectors also make -unmarked elements selectable. Their references carry a CSS selector verified against the reviewed file. -An inline SVG is selectable as a whole. Give an individual chart bar its own key when it should be a separate target. -The pointer passes through elements styled with `pointer-events: none` and through inert subtrees. Older services -offer element selection for keyed elements only. - -Run `firstdraft sketches publish` with Google Chrome installed (or set `FIRSTDRAFT_CHROME_PATH` to its executable). -When the working Plan still matches the captured draft, an accepted publication writes the selected browser theme to `application.appearance.web_theme.overrides` in the working Plan. An existing Plan preset takes precedence over the Project preset. With no pending selection, capture renders the working Plan’s presets and overrides. Capture applies the theme stylesheet and packaged fonts to desktop and mobile screens. Retrying a pending publication reuses the saved Plan and images. If the Plan changed after capture, the result includes `published_web_theme` to reconcile with the current draft. - -The CLI serves the declared local assets to a private browser context, captures each screen at 1280 × 800 and -390 × 844 CSS pixels, and sends the exact Plan text with PNGs, thumbnails, element labels and bounds. When the service -supports linked screens, ordinary anchors to other declared screen files also publish their destination screen ID and -visible rectangle for each device. Services supporting element selectors also receive tag names, labels, optional roles and authored keys, CSS paths and visible bounds for the elements in each capture. Use suitable -examples in the Plan and screens before publishing. Captures support up to 32 screens, 8192 pixels of scroll height -per viewport, and 24 MiB for the request. Capture loads offscreen images, settles CSS animations and clips selectable elements to their visible area. Browser policy violations or undeclared assets stop capture. Supply eligible local assets in the manifest and use static markup for any scripted rendering. The capture context uses a light color scheme, en-US locale and UTC. Editable HTML, CSS, fonts and images stay local. If Chrome or hosting -is unavailable, open the local HTML screens to continue the conversation. +working Plan into an element's text when the service renders the screen. Keep readable fallback text for directly opening the HTML. +Use an optional stable element key such as `data-sketch-key="nominee-arrival"` for feedback across revisions. + +API contract 0.10.2 introduced live screen publication. Before uploading source, the CLI checks for +`FirstDraft-Screen-Source-Files: 1` on the service’s review theme response. +Run `firstdraft sketches publish` to send the exact Plan, declared screen HTML and declared assets to the Project. +Use distinct paths relative to `sketches/` for each screen and asset. Assets may be CSS, PNG, JPEG, WebP, SVG or +WOFF2. A publication supports up to 32 screens, 512 files and a 24 MiB request. The Project displays the HTML +at the reviewer’s chosen width. Use local asset paths and ordinary links to other declared screen files. + +An accepted publication writes a pending theme selection to `application.appearance.web_theme` in the working Plan. +An authored preset takes precedence over the Project preset. If the Plan changed during publication, the result +includes `published_web_theme` for reconciliation. Retrying a pending publication sends the exact saved request. Record the returned review ID with the owner's feedback. After separate Compile approval, run `firstdraft plan compile --revision `, optionally with `--output `. The CLI @@ -265,7 +259,7 @@ that stable CLI error. The CLI sends nothing on its own: no telemetry, no background request, and no separate update check. A command sends only its own requests, listed under [Service endpoints](#service-endpoints); `plan init`, `generate`, and `--help` -make none. Each request carries the selected token (except public font downloads and the OAuth requests of `login` and `logout`) and this +make none. Each request carries the selected token (except the OAuth requests of `login` and `logout`) and this header: ```text @@ -280,23 +274,23 @@ CLI without the plugin's launcher, such as a direct npm installation, may set th Beyond the header, a command sends only what it needs: -| Commands | Request content | -| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `login`, `logout` | OAuth parameters; `logout` sends the saved token to revoke it | -| `start` | An account read, and nothing without a token | -| `project start` | The reserved Project ID in the request path | -| `sketches publish` | Project ID for theme selection, the web theme for preview when needed, public catalog font paths, revision ID, previous revision and Head preconditions, exact Plan text and digest, screen names and order, source fingerprints, referenced Plan and sample IDs, viewport PNGs and thumbnails, element labels and bounds, authored IDs, supported element selectors, tags, roles and ancestor keys, and linked screen IDs with their per-device bounds | -| `plan push`, Plan-only `plan compile` | The exact local Plan bytes and the saved Head ETag | -| `plan compile --revision` | The approved revision ID and Plan ETag in request headers, with Project, analysis and Compilation reads. The Plan bytes are already hosted. | -| `plan setup` | The Project ID and, when supplied, the review ID and workshop context | -| `plan status`, `compilation *`, `account` | Only the IDs in the request path | -| `report progress`, `report failure` | An account read; with reports on, the report printed just before | -| `note ` | An account read; with reports on, the note printed just before | -| `maintain` | An account read; then the Project and Environment in the request path and `?page=N` | -| `maintain show` | Only the Project, Environment, and item IDs in the request path | -| `maintain resolve` | The reason, the cause, and any `--detail` text, whatever the reports choice | -| `maintain defer` | The `--until` time | -| `maintain ask-owner` | The `--question` text, whatever the reports choice | +| Commands | Request content | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `login`, `logout` | OAuth parameters; `logout` sends the saved token to revoke it | +| `start` | An account read, and nothing without a token | +| `project start` | The reserved Project ID in the request path | +| `sketches publish` | Project ID for theme selection, revision ID, previous revision and Head preconditions, exact Plan text and digest, screen names and order, declared HTML and asset files and their digests, and referenced Plan and sample IDs | +| `plan push`, Plan-only `plan compile` | The exact local Plan bytes and the saved Head ETag | +| `plan compile --revision` | The approved revision ID and Plan ETag in request headers, with Project, analysis and Compilation reads. The Plan bytes are already hosted. | +| `plan setup` | The Project ID and, when supplied, the review ID and workshop context | +| `plan status`, `compilation *`, `account` | Only the IDs in the request path | +| `report progress`, `report failure` | An account read; with reports on, the report printed just before | +| `note ` | An account read; with reports on, the note printed just before | +| `maintain` | An account read; then the Project and Environment in the request path and `?page=N` | +| `maintain show` | Only the Project, Environment, and item IDs in the request path | +| `maintain resolve` | The reason, the cause, and any `--detail` text, whatever the reports choice | +| `maintain defer` | The `--until` time | +| `maintain ask-owner` | The `--question` text, whatever the reports choice | ### Update line and refusals @@ -1047,9 +1041,7 @@ timeout. Each request takes its method and path from one | Method | Path | Purpose | | ------ | ------------------------------------------------------------------------------------------ | ------------------------------------ | | `PUT` | `/v1/projects/{project_id}` | Start or reopen an owned Project | -| `GET` | `/theme-fonts/{family}/{version}/{asset}` | Load a packaged public font asset | | `GET` | `/v1/projects/{project_id}/review-theme` | Read the selected review theme | -| `POST` | `/v1/projects/{project_id}/review-theme/preview` | Render an authored web theme | | `PUT` | `/v1/projects/{project_id}/sketch-reviews/{revision_id}` | Publish a board and working Plan | | `PUT` | `/v1/projects/{project_id}/foundation-plan` | Create or replace the Head | | `GET` | `/v1/projects/{project_id}/analysis` | Read the Head's current analysis | @@ -1071,7 +1063,7 @@ timeout. Each request takes its method and path from one | `POST` | `/oauth/device_authorization` | Start a device-flow login | | `POST` | `/oauth/revoke` | Revoke a saved token | -`project start` reserves or reopens the Project. A fresh `sketches publish` reads the theme selection, previews the local web theme when needed, loads its public font assets, and sends the captured review and working Plan together. A pending retry sends the saved publication. +`project start` reserves or reopens the Project. A fresh `sketches publish` reads the theme selection and sends the declared screen files and working Plan together. A pending retry sends the saved publication. `plan push` sends the Plan `PUT`, and `plan status` reads the analysis. Plan-only `plan compile` does both, while `--revision` reads analysis for the published Plan. Compile then starts a Compilation, polls it, and downloads its artifact. `compilation status` reads one retained Compilation. `compilation download` reads it and downloads its artifact. @@ -1089,7 +1081,7 @@ The first push sends `If-None-Match: *`. Later pushes and the Compilation start `If-Match`. The cancel `POST` sends no precondition header. The resolution, deferral, and owner-question `POST`s send a JSON body and no precondition header. -The `/v1` routes require API contract `0.10.0` or a later patch on the same minor line. `API_CONTRACT_RANGE` in `src/service-client.js` declares that range, +The CLI accepts API contract `0.10.0` or a later patch on the same minor line. A fresh `sketches publish` also checks the live screen capability introduced in API contract `0.10.2`. `API_CONTRACT_RANGE` in `src/service-client.js` declares that range, `release/compatibility.json` declares it for the Service's release compatibility check, and `test/release-compatibility.test.js` keeps the two equal. The CLI reads `FirstDraft-API-Contract` on every response and stops at a Service outside the range, as [update line and refusals](#update-line-and-refusals) describes: with diff --git a/docs/errors.md b/docs/errors.md index 4b7ca7a..b161550 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -21,10 +21,10 @@ remain human-readable text on standard error with exit 2. Unexpected programming ## Screen review recovery -When a screen capture fails, the detail gives its screen ID and viewport dimensions. Correct the indicated Plan -binding, image, asset URL, or layout and publish again. +If the service does not advertise live screen files, update it to API 0.10.2 or a later patch on that API line. The CLI +stops before uploading a new board. A pending publication replays its saved request. -`sketch_review_failed` describes a Project-start, capture, publication or reviewed-source problem. Retry an interrupted +`sketch_review_failed` describes a Project-start, publication or reviewed-source problem. Retry an interrupted start from the same directory. A fresh publication refused with a client error other than an HTTP 408 clears its pending request. Correct the rejected draft or login, or wait for the rate limit, then publish again. @@ -60,13 +60,13 @@ The service problem appears in `response` when the CLI can verify its shape: requested review and Plan. Inspect the current revision and Head, reconcile and publish any changes, and obtain approval for the revision before passing it to `plan compile --revision`. When graph versions differ, the Plan passed through another generation even if its current bytes match an older review. -- `422 invalid_review_theme` in `sketch_review_failed` means the service could not preview the working Plan’s - `application.appearance.web_theme`. Set all three presets together when using them, and use supported tokens - and values for overrides. Correct the theme in the Plan and run `firstdraft sketches publish` again. +- A CLI that publishes captured images can receive `422 invalid_review_theme` when previewing the working Plan. + Correct the presets or override tokens in `application.appearance.web_theme` and publish again. - `422 invalid_sketch_review` in `sketch_review_failed` means the service rejected the review bundle. Read - `response.detail`, correct the indicated board, capture or reference, and publish the corrected draft. A rejected Plan can instead return `response.diagnostics`; use those to fix the Plan. + `response.detail`. If a file is missing, add the referenced local asset to `sketches/board.json` or correct the + path in the indicated screen or stylesheet. Correct the draft and publish again. A rejected Plan can instead return `response.diagnostics`; use those to fix the Plan. - `413 sketch_quota_reached` in `sketch_review_failed` means the Project reached its stored review limit. A - smaller capture may fit if only the stored byte budget is limiting it. At the revision-count limit, continue + smaller source bundle may fit if only the stored byte budget is limiting it. At the revision-count limit, continue the walkthrough using local HTML. Restore missing approved source from the planning folder or review a reconstruction. When an older service lacks @@ -343,7 +343,7 @@ again. First Draft refuses to resolve an item that is still resolved, with `main | Commands | `error` | Exit | Meaning | | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | ---------------------------------------------------------------------------------------------------------------------------- | -| Hosted screens commands and reviewed source handoff | `sketch_review_failed` | 1 | Repair the Project, capture, publication or source handoff ([recovery](#screen-review-recovery)). | +| Hosted screens commands and reviewed source handoff | `sketch_review_failed` | 1 | Repair the Project, publication or source handoff ([recovery](#screen-review-recovery)). | | Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | | Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | | Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | diff --git a/package-lock.json b/package-lock.json index 1fcd18d..736da7e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,16 +1,15 @@ { "name": "@firstdraft.com/cli", - "version": "0.12.1", + "version": "0.12.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@firstdraft.com/cli", - "version": "0.12.1", + "version": "0.12.2", "license": "MIT", "dependencies": { - "jsonc-parser": "3.3.1", - "playwright-core": "1.65.1" + "jsonc-parser": "3.3.1" }, "bin": { "firstdraft": "bin/firstdraft.js" @@ -1186,18 +1185,6 @@ "node": ">=8" } }, - "node_modules/playwright-core": { - "version": "1.65.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", - "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" - }, - "engines": { - "node": ">=20" - } - }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", diff --git a/package.json b/package.json index 32104fb..d4b0e39 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@firstdraft.com/cli", - "version": "0.12.1", + "version": "0.12.2", "description": "Command-line interface for First Draft", "license": "MIT", "type": "module", @@ -55,7 +55,6 @@ "minimatch": "^11.0.5" }, "dependencies": { - "jsonc-parser": "3.3.1", - "playwright-core": "1.65.1" + "jsonc-parser": "3.3.1" } } diff --git a/release/compatibility.json b/release/compatibility.json index 4a39882..c3f9fae 100644 --- a/release/compatibility.json +++ b/release/compatibility.json @@ -1,7 +1,7 @@ { "format": "firstdraft.release-compatibility/1", "component": "cli", - "version": "0.12.1", + "version": "0.12.2", "requires": { "api_contract": [">= 0.10.0", "< 0.11.0"], "foundation_plan_formats": ["firstdraft.foundation-plan.sketch/0.24"] diff --git a/scripts/check-pack.js b/scripts/check-pack.js index 9b6294b..1ee71fc 100644 --- a/scripts/check-pack.js +++ b/scripts/check-pack.js @@ -64,7 +64,7 @@ if (result.status !== 0) { "src/review-theme.js", "src/root-output.js", "src/service-client.js", - "src/sketch-capture.js", + "src/sketch-sources.js", "src/uuid-v7.js", "src/version.js", ]); diff --git a/src/api-response.js b/src/api-response.js index cee4483..d5ee113 100644 --- a/src/api-response.js +++ b/src/api-response.js @@ -28,18 +28,10 @@ export class FirstDraftProtocolError extends Error { */ export const SERVICE_ROUTES = { startProject: { method: "PUT", path: "/v1/projects/{project_id}" }, - reviewFontAsset: { - method: "GET", - path: "/theme-fonts/{family}/{version}/{asset}", - }, readReviewTheme: { method: "GET", path: "/v1/projects/{project_id}/review-theme", }, - previewReviewTheme: { - method: "POST", - path: "/v1/projects/{project_id}/review-theme/preview", - }, publishSketches: { method: "PUT", path: "/v1/projects/{project_id}/sketch-reviews/{revision_id}", diff --git a/src/cli.js b/src/cli.js index 73037f2..2bf27b2 100644 --- a/src/cli.js +++ b/src/cli.js @@ -5259,7 +5259,7 @@ async function runSketchCommand({ const subcommand = start ? "start" : "publish"; const group = start ? "project" : "sketches"; const command = `firstdraft ${group} ${subcommand}`; - const help = `Usage: ${command} [--staging]${start ? "" : " [--after --head ]"}\n${start ? "Create or reopen this directory's hosted Project before drafting its Plan." : "Capture sketches/board.json and publish its screens with the local Foundation Plan."}\n`; + const help = `Usage: ${command} [--staging]${start ? "" : " [--after --head ]"}\n${start ? "Create or reopen this directory's hosted Project before drafting its Plan." : "Publish the screen files declared in sketches/board.json with the local Foundation Plan."}\n`; if (argv[1] !== subcommand) return runCommandGroup( { argv: argv.slice(1), stdout, stderr }, @@ -5321,7 +5321,6 @@ async function runSketchCommand({ start ? startProject({ cwd: cwd ?? getCwd(), ...auth }) : publishSketches({ - publicFetch: service.fetch(fetchFunction), throwIfStopped: service.throwIfStopped, cwd: cwd ?? getCwd(), ...auth, diff --git a/src/commands/sketches.js b/src/commands/sketches.js index 37a81ae..2e42a85 100644 --- a/src/commands/sketches.js +++ b/src/commands/sketches.js @@ -35,10 +35,10 @@ import { import { resolveApiUrl } from "./plan-push.js"; import { digest, - captureBoard, + sourceManifest, loadSources, SketchError, -} from "../sketch-capture.js"; +} from "../sketch-sources.js"; import { publicationTheme } from "../review-theme.js"; export { SketchError }; const privateWrite = { flag: "wx", mode: 0o600, flush: true }; @@ -131,7 +131,7 @@ function readReview(cwd, revision) { throw new SketchError("Invalid local screen review receipt."); return receipt; } -/** @typedef {Options & {capture?:typeof captureBoard, publicFetch?:typeof fetch,throwIfStopped?:()=>void, after?:string, head?:string}} PublishOptions */ +/** @typedef {Options & {throwIfStopped?:()=>void, after?:string, head?:string}} PublishOptions */ /** @param {PublishOptions} options */ export async function publishSketches(options) { return withPlanStateLock(path.join(options.cwd, ".firstdraft"), () => @@ -145,8 +145,6 @@ async function publishCurrentSketches({ apiUrl, fetchFunction, hasTokenFor, - capture = captureBoard, - publicFetch, throwIfStopped, after, head, @@ -168,12 +166,7 @@ async function publishCurrentSketches({ const planBytes = readLocalFile(planFile, 1024 * 1024); if (!isUtf8(planBytes)) throw new SketchError("The Foundation Plan must contain valid UTF-8."); - const { - source: plan_source, - theme, - includeLinks, - includeSelectors, - } = await publicationTheme( + const { source: plan_source } = await publicationTheme( planBytes.toString("utf8"), origin, state.project_id, @@ -184,15 +177,8 @@ async function publishCurrentSketches({ throw new SketchError( "The working Foundation Plan exceeds 1 MiB after applying its theme.", ); - const sources = loadSources(cwd); - const manifest = await capture( - sources, - plan_source, - theme, - publicFetch, - includeLinks, - includeSelectors, - ); + const sources = loadSources(cwd, true); + const manifest = sourceManifest(sources, plan_source); throwIfStopped?.(); const body = JSON.stringify({ previous_revision_id: previous ?? null, @@ -207,7 +193,7 @@ async function publishCurrentSketches({ throw new SketchError("The review bundle exceeds 24 MiB."); if (!readLocalFile(planFile, 1024 * 1024).equals(planBytes)) throw new SketchError( - "The working Plan changed during capture. Publish the current draft again.", + "The working Plan changed during publication. Publish the current draft again.", ); save( pendingFile, @@ -339,8 +325,8 @@ async function publishCurrentSketches({ let nextStep; if (localPlanChanged) nextStep = - "The working Plan changed after capture. Reconcile published_web_theme with application.appearance.web_theme in the current draft, then run firstdraft sketches publish again."; - else if (replay) { + "The working Plan changed after publication began. Reconcile published_web_theme with application.appearance.web_theme in the current draft, then run firstdraft sketches publish again."; + else { try { reviewedSources(cwd, pending.id); } catch (error) { @@ -349,7 +335,7 @@ async function publishCurrentSketches({ )) throw error; nextStep = - "Recovered the saved publication. The current planning files do not match this review. Run firstdraft sketches publish again to capture and publish the current draft."; + "The current planning files differ from this review. Run firstdraft sketches publish again to publish the current draft."; } } return { diff --git a/src/plan-state.js b/src/plan-state.js index 04c9b52..cd739fc 100644 --- a/src/plan-state.js +++ b/src/plan-state.js @@ -486,7 +486,7 @@ function arraysEqual(left, right) { } /** - * Serialize hosted writes from capture through durable local receipt. A response + * Serialize hosted writes from source preparation through durable local receipt. A response * can arrive after a later writer commits, even when the Plan digest repeats. * @template T * @param {string} directory @param {() => Promise} update diff --git a/src/review-theme.js b/src/review-theme.js index 0066f64..1303021 100644 --- a/src/review-theme.js +++ b/src/review-theme.js @@ -5,18 +5,16 @@ import { isProblemBody, problemProjection, readResponseBody, - readResponseBytes, sendRequest, serviceEndpoint, } from "./api-response.js"; -import { SketchError } from "./sketch-capture.js"; +import { SketchError } from "./sketch-sources.js"; -/** @typedef {{stylesheet:string,fonts:{id:string,version:string}[],origin:string}} CaptureTheme */ /** @param {any} value */ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); -/** @param {string} source @param {string} origin @param {string} project_id @param {typeof fetch} fetchFunction @param {()=>void} [throwIfStopped] @returns {Promise<{source:string, theme?:CaptureTheme, includeLinks?:boolean, includeSelectors?:boolean}>} */ +/** @param {string} source @param {string} origin @param {string} project_id @param {typeof fetch} fetchFunction @param {()=>void} [throwIfStopped] @returns {Promise<{source:string}>} */ export async function publicationTheme( source, origin, @@ -49,7 +47,7 @@ export async function publicationTheme( options, ); throwIfStopped?.(); - let descriptor = await readResponseBody(get); + const descriptor = await readResponseBody(get); if (get.status === 404) { const problem = descriptor; if (problem?.code === "project_not_found" && isProblemBody(get, problem)) @@ -58,12 +56,15 @@ export async function publicationTheme( 404, problemProjection(problem), ); - if (!authored?.overrides) return { source }; + } + if ( + get.status === 404 || + (get.status === 200 && + get.headers.get("FirstDraft-Screen-Source-Files") !== "1") + ) throw new SketchError( - "This service does not support rendering authored web theme overrides.", - 404, + "Update the First Draft service to API 0.10.2 or a later 0.10.x version that supports live screen files, then publish again.", ); - } if (get.status !== 200) throw new SketchError( "First Draft could not read the selected review theme.", @@ -77,16 +78,7 @@ export async function publicationTheme( !(descriptor.overrides === null || record(descriptor.overrides)) ) throw new SketchError("Unexpected review theme response."); - const captureOptions = - get.headers.get("FirstDraft-Screen-Manifest-Version") === "2" - ? { - includeLinks: true, - includeSelectors: - get.headers.get("FirstDraft-Screen-Element-Selectors") === "1", - } - : {}; - if (descriptor.overrides === null && authored === undefined) - return { source, ...captureOptions }; + if (descriptor.overrides === null) return { source }; if ( !record(plan?.application) || (plan.application.appearance !== undefined && @@ -114,50 +106,7 @@ export async function publicationTheme( const base = Object.keys(authoredBase).length ? authoredBase : descriptor.web_theme; - const chosen = - descriptor.overrides === null - ? authored - : { ...base, overrides: descriptor.overrides }; - const hostedTheme = - descriptor.overrides === null - ? descriptor.web_theme - : { ...descriptor.web_theme, overrides: descriptor.overrides }; - if (!isDeepStrictEqual(chosen, hostedTheme)) { - const preview = await sendRequest( - fetchFunction, - serviceEndpoint(SERVICE_ROUTES.previewReviewTheme, origin, { - project_id, - }), - { - ...options, - signal: AbortSignal.timeout(30000), - body: JSON.stringify({ web_theme: chosen }), - }, - ); - throwIfStopped?.(); - descriptor = await readResponseBody(preview); - if (preview.status !== 200) - throw new SketchError( - "First Draft could not render the working Plan’s web theme.", - preview.status, - isProblemBody(preview, descriptor) - ? problemProjection(descriptor) - : undefined, - ); - } - if ( - typeof descriptor?.stylesheet !== "string" || - !Array.isArray(descriptor.fonts) || - descriptor.fonts.some( - (/** @type {any} */ font) => - !record(font) || - typeof font.id !== "string" || - !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(font.id) || - typeof font.version !== "string" || - !/^[0-9]+\.[0-9]+\.[0-9]+$/.test(font.version), - ) - ) - throw new SketchError("Unexpected review theme stylesheet or fonts."); + const chosen = { ...base, overrides: descriptor.overrides }; if (!isDeepStrictEqual(authored, chosen)) { const location = ["application", "appearance", "web_theme"]; const onlyOverrides = authored && isDeepStrictEqual(base, authoredBase); @@ -176,71 +125,5 @@ export async function publicationTheme( "Check the working Plan for duplicate appearance properties.", ); } - return { - source, - ...captureOptions, - theme: /** @type {CaptureTheme} */ ({ - origin, - stylesheet: descriptor.stylesheet, - fonts: descriptor.fonts, - }), - }; -} - -/** @param {CaptureTheme} theme @param {typeof fetch} [publicFetch] */ -export async function captureFonts(theme, publicFetch = globalThis.fetch) { - /** @type {Map} */ - const sheets = new Map(); - /** @type {Map} */ - const allowed = new Map(); - /** @param {import("./api-response.js").ServiceEndpoint} endpoint */ - async function download(endpoint) { - const response = await sendRequest(publicFetch, endpoint, { - credentials: "omit", - redirect: "error", - signal: AbortSignal.timeout(30000), - }); - if (response.status !== 200) - throw new SketchError( - "First Draft could not load the selected review font.", - response.status, - ); - return readResponseBytes(response, 8 * 1024 * 1024); - } - for (const { id, version } of theme.fonts) { - /** @param {string} asset */ - const endpoint = (asset) => - serviceEndpoint(SERVICE_ROUTES.reviewFontAsset, theme.origin, { - family: id, - version, - asset, - }); - const sheet = endpoint("family.css"); - const name = sheet.url.pathname; - if (sheets.has(name)) continue; - const css = await download(sheet); - sheets.set(name, css); - for (const match of css - .toString() - .matchAll( - /url\(\s*["']?\.\/files\/([a-zA-Z0-9_.-]+\.woff2?)["']?\s*\)/g, - )) { - if (match[1]?.startsWith(id + "-")) { - const file = endpoint("files/" + match[1]); - allowed.set(file.url.pathname, file); - } - } - } - /** @type {Map>} */ - const binaries = new Map(); - return { - sheets, - /** @param {string} name */ - file(name) { - const endpoint = allowed.get(name); - if (!endpoint) return; - if (!binaries.has(name)) binaries.set(name, download(endpoint)); - return binaries.get(name); - }, - }; + return { source }; } diff --git a/src/sketch-capture.js b/src/sketch-capture.js deleted file mode 100644 index 27565c6..0000000 --- a/src/sketch-capture.js +++ /dev/null @@ -1,939 +0,0 @@ -import { captureFonts } from "./review-theme.js"; -/* global document, scrollX, scrollY, innerWidth, innerHeight, SVGGeometryElement, window, IntersectionObserver, getComputedStyle */ - -import { createHash } from "node:crypto"; -import { lstatSync, readFileSync, realpathSync } from "node:fs"; -import path from "node:path"; -import { isUuidV7 } from "./plan-state.js"; - -export class SketchError extends Error { - /** @param {string} message @param {number} [status] @param {unknown} [response] */ - constructor(message, status, response) { - super(message); - this.status = status; - this.response = response; - } -} -/** @param {string|Buffer} bytes */ -export function digest(bytes) { - return createHash("sha256").update(bytes).digest("hex"); -} - -const stableKey = /^[a-zA-Z0-9][-a-zA-Z0-9_]{0,79}$/; -const media = new Map( - Object.entries({ - ".html": "text/html; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".webp": "image/webp", - ".svg": "image/svg+xml", - ".woff2": "font/woff2", - }), -); -/** @param {string} cwd */ -export function loadSources(cwd) { - const root = realpathSync(path.join(cwd, "sketches")); - if (root !== path.join(realpathSync(cwd), "sketches")) - throw new SketchError("Use a local sketches directory."); - /** @param {string} name */ - function load(name) { - if ( - typeof name !== "string" || - !name - .split("/") - .every((part) => /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/.test(part)) - ) - throw new SketchError("Screen paths must be relative to sketches/."); - const file = path.join(root, name); - if (realpathSync(file) !== file || !lstatSync(file).isFile()) - throw new SketchError( - "Screen sources must be regular files inside sketches/.", - ); - return readFileSync(file); - } - const boardBytes = load("board.json"); - /** @type {{screens:{id:string,name:string,source:string,sample_keys:string[],plan_subjects:string[]}[],assets:string[]}} */ - const board = JSON.parse(boardBytes.toString()); - if ( - !board || - !Array.isArray(board.screens) || - board.screens.length < 1 || - board.screens.length > 32 || - !Array.isArray(board.assets) || - !board.assets.every((asset) => typeof asset === "string") - ) - throw new SketchError( - "board.json requires 1–32 screens and an assets array.", - ); - const ids = new Set(); - for (const screen of board.screens) { - if ( - !screen || - typeof screen.id !== "string" || - !stableKey.test(screen.id) || - typeof screen.name !== "string" || - !screen.name.trim() || - Buffer.byteLength(screen.name) > 256 || - screen.name.includes("\0") || - typeof screen.source !== "string" || - !screen.source.endsWith(".html") || - ids.has(screen.id) - ) - throw new SketchError( - "Each screen needs a unique id, a name and an HTML source.", - ); - for (const field of /** @type {const} */ ([ - "sample_keys", - "plan_subjects", - ])) { - if (screen[field] === undefined) screen[field] = []; - const references = screen[field]; - if ( - !Array.isArray(references) || - references.length > 256 || - !references.every(isUuidV7) - ) - throw new SketchError( - "sample_keys and plan_subjects must be arrays of Plan subject UUIDs.", - ); - } - ids.add(screen.id); - } - const files = new Map([["board.json", boardBytes]]); - for (const name of [ - ...board.assets, - ...board.screens.map((screen) => screen.source), - ]) { - if (!media.has(path.extname(name))) - throw new SketchError( - "Use HTML, CSS, images or WOFF2 fonts for screen sources.", - ); - files.set(name, load(name)); - } - return { board, files }; -} - -// Playwright runs this function inside the screen's document. -/** @param {string} source */ -export function bindPlanValues(source) { - const plan = JSON.parse(source); - for (const element of document.querySelectorAll("[data-plan-pointer]")) { - const pointer = element.getAttribute("data-plan-pointer") ?? ""; - if ( - (pointer !== "" && !pointer.startsWith("/")) || - /~(?:[^01]|$)/.test(pointer) - ) - return "Invalid data-plan-pointer."; - let value = plan; - for (const token of pointer.split("/").slice(1)) { - const key = token.replace(/~1/g, "/").replace(/~0/g, "~"); - if ( - value === null || - typeof value !== "object" || - (Array.isArray(value) && !/^(?:0|[1-9][0-9]*)$/.test(key)) || - !Object.hasOwn(value, key) - ) - return "A data-plan-pointer must identify a value in the Plan."; - value = value[key]; - } - if (!["string", "number", "boolean"].includes(typeof value)) - return "A data-plan-pointer must identify a scalar example value."; - element.textContent = String(value); - } - return null; -} - -/** @typedef {{x:number,y:number,width:number,height:number}} HitRect */ - -/** @param {{captureHeight:number,destinations:{id:string,source:string}[],includeSelectors:boolean, paintOrders:number[]}} options */ -async function captureHitAreas({ - captureHeight, - destinations, - includeSelectors, - paintOrders, -}) { - const measured = new Set( - document.querySelectorAll( - includeSelectors ? "body, body *" : "[data-sketch-key]", - ), - ); - /** @type {Map} */ - const anchors = new Map(); - if (destinations.length) { - for (const anchor of document.querySelectorAll("a[href]:not([download])")) { - const href = anchor.getAttribute("href")?.trim(); - if (!href || href.startsWith("#") || anchor.closest("[inert]")) continue; - const url = URL.parse(href, document.baseURI); - if ( - url?.origin !== window.location.origin || - url.username || - url.password || - url.pathname === window.location.pathname - ) - continue; - const matches = destinations.filter( - ({ source }) => "/" + source === url.pathname, - ); - if (matches.length !== 1 || !matches[0]) continue; - anchors.set(anchor, { target: matches[0].id, rects: [] }); - measured.add(anchor); - // An inline anchor's own line box can miss an image or tile inside it. - for (const descendant of anchor.querySelectorAll("*")) - measured.add(descendant); - } - } - const visible = [...measured].filter((el) => - el.checkVisibility({ visibilityProperty: true, opacityProperty: true }), - ); - if (!visible.length) return { elements: [], links: [] }; - - // Expand the root to the full-page capture; Chromium still clips scroll containers. - const intersections = - await /** @type {Promise} */ ( - new Promise((resolve) => { - const observer = new IntersectionObserver( - (entries) => { - observer.disconnect(); - resolve(entries); - }, - { - rootMargin: `0px 0px ${captureHeight}px 0px`, - }, - ); - for (const element of visible) observer.observe(element); - }) - ); - /** @param {DOMRectReadOnly} bounds @param {DOMRectReadOnly} clip */ - function rectangle(bounds, clip) { - const x = Math.max( - 0, - Math.floor(Math.max(bounds.left, clip.left) + scrollX), - ); - const y = Math.max(0, Math.floor(Math.max(bounds.top, clip.top) + scrollY)); - const width = - Math.min( - innerWidth, - Math.ceil(Math.min(bounds.right, clip.right) + scrollX), - ) - x; - const height = - Math.min( - captureHeight, - Math.ceil(Math.min(bounds.bottom, clip.bottom) + scrollY), - ) - y; - return width > 0 && height > 0 ? { x, y, width, height } : null; - } - /** @type {Map} */ - const boundsByNode = new Map( - !includeSelectors - ? [] - : intersections - .filter( - (entry) => - entry.intersectionRect.width && entry.intersectionRect.height, - ) - .map((entry) => [entry.target, entry.intersectionRect]), - ); - if (includeSelectors) { - const order = new Map( - Array.from(measured, (el, i) => [el, paintOrders[i] ?? 0]), - ); - intersections.sort( - (a, b) => (order.get(a.target) ?? 0) - (order.get(b.target) ?? 0), - ); - } - const original = /** @type {Window & {screenSource?:Document}} */ (window) - .screenSource; - const validKey = /^[a-zA-Z0-9][-a-zA-Z0-9_]{0,79}$/; - /** @type {WeakMap} */ - const siblingIndices = new WeakMap(); - /** @param {Element} node @param {Element} parent */ - function siblingIndex(node, parent) { - if (!siblingIndices.has(node)) { - const counts = new Map(); - for (const child of parent.children) { - const type = child.namespaceURI + "/" + child.localName; - const index = (counts.get(type) ?? 0) + 1; - counts.set(type, index); - siblingIndices.set(child, index); - } - } - return siblingIndices.get(node); - } - /** @param {Element} el */ - function reference(el) { - const steps = []; - let node = el; - let root = "body"; - let anchor; - while (true) { - const key = node.getAttribute("data-sketch-key"); - if (key && validKey.test(key)) { - const keyed = `[data-sketch-key="${key}"]`; - if ( - document.querySelectorAll(keyed).length === 1 && - original?.querySelectorAll(keyed).length === 1 - ) { - root = keyed; - if (node !== el) anchor = key; - break; - } - } - if (node === document.body) break; - const tag = node.localName; - if (!node.parentElement || !/^[a-z][a-z0-9-]*$/.test(tag)) return; - const index = siblingIndex(node, node.parentElement); - steps.unshift(`${tag}:nth-of-type(${index})`); - node = node.parentElement; - } - const selector = [root, ...steps].join(" > "); - if (selector.length > 2048) return; - const matches = document.querySelectorAll(selector); - if ( - matches.length === 1 && - matches[0] === el && - original?.querySelectorAll(selector).length === 1 - ) - return { selector, ...(anchor ? { anchor } : {}) }; - return undefined; - } - /** @param {Element} el */ - function visibleText(el) { - const walker = document.createTreeWalker(el, 4); - const words = []; - for (let node = walker.nextNode(); node; node = walker.nextNode()) { - const parent = node.parentElement; - if ( - !parent || - parent.closest("textarea, select, [contenteditable], svg") || - !boundsByNode.has(parent) - ) - continue; - const range = document.createRange(); - range.selectNodeContents(node); - const clip = boundsByNode.get(parent); - if ( - clip && - [...range.getClientRects()].some((fragment) => - rectangle(fragment, clip), - ) - ) - words.push(node.textContent); - if (words.join(" ").length >= 256) break; - } - return words.join(" ").trim(); - } - /** @param {Element} el */ - function elementLabel(el) { - const labelledBy = el - .getAttribute("aria-labelledby") - ?.trim() - .split(/\s+/) - .map((id) => document.getElementById(id)) - .filter((node) => node && boundsByNode.has(node)) - .map((node) => node && visibleText(node)) - .join(" "); - const labelNode = - "labels" in el && /** @type {HTMLInputElement} */ (el).labels?.[0]; - const label = - el.getAttribute("data-sketch-label") || - labelledBy || - el.getAttribute("aria-label") || - (labelNode && visibleText(labelNode)) || - el.getAttribute("alt") || - el.getAttribute("title") || - (el.namespaceURI === "http://www.w3.org/2000/svg" && - el.querySelector(":scope > title")?.textContent) || - visibleText(el) || - el.localName; - const normalized = label.replace(/\s+/g, " ").trim() || el.localName; - const buffer = new Uint8Array(256); - const { read } = new TextEncoder().encodeInto(normalized, buffer); - return normalized.slice(0, read); - } - /** @param {Element} el */ - function pointerTarget(el) { - const style = getComputedStyle(el); - if (style.pointerEvents === "none" || el.closest("[inert]")) return false; - if (!el.parentElement?.closest("svg")) return true; - if (!validKey.test(el.getAttribute("data-sketch-key") ?? "")) return false; - if ( - el instanceof SVGGeometryElement && - ["auto", "visiblepainted", "painted"].includes( - style.pointerEvents.toLowerCase(), - ) - ) - return ( - style.fill !== "none" || - (style.stroke !== "none" && parseFloat(style.strokeWidth) > 0) - ); - return true; - } - /** @type {(HitRect & {id?:string|null,label:string,tag?:string,selector?:string,anchor?:string,role?:string,rects?:HitRect[]})[]} */ - const elements = []; - const visibleKeys = new Set(); - /** @type {Element[]} */ - const targets = []; - for (const { target: el, intersectionRect: bounds } of intersections) { - // Chromium's observer can apply foreignObject x/y twice. Its client - // rectangle and its SVG parent's observed clip use document coordinates. - const foreign = - includeSelectors && el.localName === "foreignObject" && el.parentElement; - const clip = foreign ? boundsByNode.get(foreign) : bounds; - if (!clip?.width || !clip.height) continue; - const rect = rectangle(foreign ? el.getBoundingClientRect() : bounds, clip); - if (!rect) continue; - if ( - includeSelectors && - document.body.contains(el) && - pointerTarget(el) && - !el.matches("script,style,link,meta,template,noscript,option,optgroup") - ) { - const ref = reference(el); - const id = el.getAttribute("data-sketch-key"); - if (!ref || (id !== null && (!validKey.test(id) || visibleKeys.has(id)))) - return { - error: - "Visible screen elements need uniquely resolvable selectors within 2048 bytes and unique valid authored keys.", - elements, - links: [], - }; - if (id) visibleKeys.add(id); - const fragments = Array.from(el.getClientRects(), (fragment) => - rectangle(fragment, clip), - ).filter((fragment) => fragment !== null); - const role = el - .getAttribute("role") - ?.trim() - .split(/\s+/) - .find((token) => /^[a-z][a-z0-9-]{0,39}$/.test(token)); - targets.push(el); - elements.push({ - ...rect, - ...(role ? { role } : {}), - ...ref, - ...(id && ref.selector === `[data-sketch-key="${id}"]` ? { id } : {}), - tag: el.localName.toLowerCase(), - label: elementLabel(el), - ...(fragments.length > 1 && fragments.length <= 128 - ? { rects: fragments } - : {}), - }); - if (elements.length > 4096) - return { - error: - "A screen supports at most 4096 visible selectable elements per viewport.", - elements, - links: [], - }; - } else if (!includeSelectors && el.hasAttribute("data-sketch-key")) { - elements.push({ - id: el.getAttribute("data-sketch-key"), - label: ( - el.getAttribute("data-sketch-label") || - el.getAttribute("aria-label") || - el.textContent || - "" - ).trim(), - ...rect, - }); - } - const anchor = el.closest("a[href]"); - const link = anchor && anchors.get(anchor); - if ( - !link || - el.closest("[inert]") || - getComputedStyle(el).pointerEvents === "none" - ) - continue; - for (const fragment of el.getClientRects()) { - const area = rectangle(fragment, bounds); - if (area) link.rects.push(area); - } - } - const links = []; - for (const { target, rects } of anchors.values()) { - /** @type {HitRect[]} */ - const regions = []; - for (const rect of rects.sort( - (a, b) => b.width * b.height - a.width * a.height, - )) { - if ( - regions.some( - (r) => - r.x <= rect.x && - r.y <= rect.y && - r.x + r.width >= rect.x + rect.width && - r.y + r.height >= rect.y + rect.height, - ) - ) - continue; - regions.push(rect); - links.push({ target, ...rect }); - } - } - if (includeSelectors) { - // Layout snapshots group pixels into paint layers. Use actual hit stacks - // wherever separate elements overlap or a negative layer crosses its parent. - const indexByNode = new Map(targets.map((node, index) => [node, index])); - const regions = elements - .flatMap((el, i) => (el.rects ?? [el]).map((rect) => ({ ...rect, i }))) - .sort((a, b) => a.y - b.y); - const negative = targets.map( - (node) => Number(getComputedStyle(node).zIndex) < 0, - ); - /** @type {Map} */ - const points = new Map(); - let comparisons = 0; - // Dense overlapping fragments share a bounded probe budget. Unprobed - // pairs keep Chrome's snapshot order. - regionPairs: for (const [row, a] of regions.entries()) { - for (let j = row + 1; j < regions.length; j++) { - const b = regions[j]; - if (!b || b.y >= a.y + a.height) break; - if (++comparisons > 2_000_000 || points.size >= 8192) break regionPairs; - const left = Math.max(a.x, b.x); - const right = Math.min(a.x + a.width, b.x + b.width); - if (a.i === b.i || right <= left) continue; - const first = targets[a.i]; - const second = targets[b.i]; - if ( - !first || - !second || - (!negative[a.i] && - !negative[b.i] && - (first.contains(second) || second.contains(first))) - ) - continue; - const x = (left + right) / 2; - const y = (b.y + Math.min(a.y + a.height, b.y + b.height)) / 2; - points.set(x + "," + y, { x, y }); - } - } - if (points.size) { - const incoming = elements.map( - () => new Set(/** @type {number[]} */ ([])), - ); - const outgoing = elements.map( - () => new Set(/** @type {number[]} */ ([])), - ); - const initialScroll = { - left: scrollX, - top: scrollY, - behavior: /** @type {const} */ ("instant"), - }; - for (const { x, y } of [...points.values()].sort((a, b) => a.y - b.y)) { - if (y < scrollY || y >= scrollY + innerHeight) - window.scrollTo({ ...initialScroll, top: Math.floor(y) }); - if (y < scrollY || y >= scrollY + innerHeight) continue; - let above; - for (const node of document.elementsFromPoint( - x - scrollX, - y - scrollY, - )) { - const index = indexByNode.get(node); - if (index === undefined || index === above) continue; - const element = elements[index]; - if ( - !element || - !(element.rects ?? [element]).some( - (r) => - r.x <= x && x < r.x + r.width && r.y <= y && y < r.y + r.height, - ) - ) - continue; - if (above !== undefined) { - incoming[above]?.add(index); - outgoing[index]?.add(above); - } - above = index; - } - } - window.scrollTo(initialScroll); - const remaining = new Set(elements.keys()); - const ordered = []; - while (remaining.size) { - // Retain Chrome's coarse paint order for unrelated targets and for - // geometries whose sampled stacks admit no single rectangle ordering. - let next; - for (const index of remaining) { - if (!incoming[index]?.size) { - next = index; - break; - } - } - next ??= remaining.values().next().value; - if (next === undefined) break; - remaining.delete(next); - const element = elements[next]; - if (element) ordered.push(element); - for (const above of outgoing[next] ?? []) incoming[above]?.delete(next); - } - return { elements: ordered, links }; - } - } - return { elements, links }; -} - -// Resolve the layout snapshot's backend IDs to the light DOM elements in query order. -/** @param {import("playwright-core").CDPSession} session */ -async function readPaintOrders(session) { - const { root } = await session.send("DOM.getDocument"); - const { nodeIds } = await session.send("DOM.querySelectorAll", { - nodeId: root.nodeId, - selector: "body, body *", - }); - const { documents } = await session.send("DOMSnapshot.captureSnapshot", { - computedStyles: [], - includePaintOrder: true, - }); - const snapshot = documents[0]; - if (!snapshot?.nodes.backendNodeId || !snapshot.layout.paintOrders) - throw new SketchError("Chrome could not read the screen's paint order."); - const { layout, nodes } = snapshot; - const ids = /** @type {number[]} */ ( - layout.nodeIndex.map((index) => nodes.backendNodeId?.[index]) - ); - const { nodeIds: painted } = await session.send( - "DOM.pushNodesByBackendIdsToFrontend", - { backendNodeIds: ids }, - ); - const order = new Map( - painted.map((id, i) => [id, layout.paintOrders?.[i] ?? 0]), - ); - return nodeIds.map((id) => order.get(id) ?? 0); -} - -/** @param {ReturnType} sources @param {string} planSource @param {import("./review-theme.js").CaptureTheme} [theme] @param {typeof fetch} [publicFetch] @param {boolean} [includeLinks] @param {boolean} [includeSelectors] */ -export async function captureBoard( - { board, files }, - planSource, - theme, - publicFetch, - includeLinks = false, - includeSelectors = false, -) { - try { - JSON.parse(planSource); - } catch (error) { - if (!(error instanceof SyntaxError)) throw error; - throw new SketchError( - "The working Foundation Plan must contain valid JSON.", - ); - } - const { chromium, errors } = await import("playwright-core"); - let browser; - let screenViewport = ""; - let operation = "opening the screen"; - try { - browser = await chromium - .launch({ - channel: "chrome", - ...(process.env.FIRSTDRAFT_CHROME_PATH - ? { executablePath: process.env.FIRSTDRAFT_CHROME_PATH } - : {}), - }) - .catch(() => { - throw new SketchError( - "Chrome could not launch. Install Chrome or set FIRSTDRAFT_CHROME_PATH to its executable.", - ); - }); - const context = await browser.newContext({ - deviceScaleFactor: 1, - colorScheme: "light", - locale: "en-US", - timezoneId: "UTC", - reducedMotion: "reduce", - serviceWorkers: "block", - }); - const fonts = theme && (await captureFonts(theme, publicFetch)); - /** @type {unknown} */ - let fontError; - const blocked = new Set(); - let malformedPath = false; - await context.route("**/*", async (route) => { - const url = new URL(route.request().url()); - let name; - try { - name = decodeURIComponent(url.pathname.slice(1)); - } catch (error) { - if (!(error instanceof URIError)) throw error; - malformedPath = true; - await route.abort(); - return; - } - if ( - fonts && - url.origin === "https://theme.invalid" && - !url.search && - route.request().method() === "GET" - ) { - let body; - try { - body = - fonts.sheets.get(url.pathname) ?? (await fonts.file(url.pathname)); - } catch (error) { - fontError = error; - } - if (body) { - await route.fulfill({ - body, - contentType: url.pathname.endsWith(".css") - ? "text/css" - : url.pathname.endsWith(".woff2") - ? "font/woff2" - : "font/woff", - headers: { - "Access-Control-Allow-Origin": "https://sketch.invalid", - }, - }); - return; - } - } - const body = - url.origin === "https://sketch.invalid" && name !== "board.json" - ? files.get(name) - : undefined; - if (!body) { - blocked.add(url.origin); - await route.abort(); - return; - } - await route.fulfill({ - body, - contentType: media.get(path.extname(name)), - headers: { - "Content-Security-Policy": `default-src 'none'; style-src 'self' 'unsafe-inline' ${fonts ? "https://theme.invalid" : ""}; img-src 'self' data:; font-src 'self' ${fonts ? "https://theme.invalid" : ""}; base-uri 'none'; frame-src 'none'`, - }, - }); - }); - const page = await context.newPage(); - const session = includeSelectors && (await context.newCDPSession(page)); - await page.addInitScript(() => { - document.addEventListener("securitypolicyviolation", () => { - /** @type {Window & {sketchAssetBlocked?: boolean}} */ ( - window - ).sketchAssetBlocked = true; - }); - }); - async function checkAssets() { - if (fontError) throw fontError; - if (malformedPath) - throw new SketchError( - "An asset URL has invalid percent encoding. Correct the path in the screen or its stylesheet.", - ); - if ( - blocked.size || - (await page.evaluate( - () => - /** @type {Window & {sketchAssetBlocked?: boolean}} */ (window) - .sketchAssetBlocked, - )) - ) - throw new SketchError( - "A screen requested an undeclared or external asset. List eligible local assets in board.json.", - ); - } - const thumbnail = await context.newPage(); - const screens = []; - for (const screen of board.screens) { - /** @param {number} width @param {number} height */ - async function capture(width, height) { - screenViewport = `${screen.id} (${width} × ${height})`; - operation = "opening the screen"; - await page.setViewportSize({ width, height }); - await page.goto("https://sketch.invalid/" + screen.source, { - waitUntil: "load", - }); - if (theme && fonts) { - for (const name of fonts.sheets.keys()) - await page.addStyleTag({ url: "https://theme.invalid" + name }); - if (theme.stylesheet) - await page.addStyleTag({ content: theme.stylesheet }); - } - if (includeSelectors) - await page.evaluate(() => { - /** @type {Window & {screenSource?:Document}} */ ( - window - ).screenSource = /** @type {Document} */ (document.cloneNode(true)); - }); - const bindingError = await page.evaluate(bindPlanValues, planSource); - if (bindingError) throw new SketchError(bindingError); - await checkAssets(); - operation = "loading the screen’s images and fonts"; - const readiness = await page.waitForFunction( - async () => { - for (const image of document.images) image.loading = "eager"; - await document.fonts.ready; - if ([...document.fonts].some((font) => font.status === "error")) - return "invalid-font"; - try { - await Promise.all( - Array.from(document.images) - .filter( - (image) => - image.checkVisibility() && - (image.currentSrc || - image.getAttribute("src") || - image.getAttribute("srcset")), - ) - .map((image) => image.decode()), - ); - } catch (error) { - if ( - error instanceof DOMException && - error.name === "EncodingError" - ) - return "invalid-image"; - throw error; - } - return "ready"; - }, - undefined, - { timeout: 15000 }, - ); - await checkAssets(); - const status = await readiness.jsonValue(); - if (status === "invalid-font") - throw new SketchError( - "Chrome could not decode a selected font. Check its declared source.", - ); - if (status === "invalid-image") - throw new SketchError( - "Chrome could not decode a visible image. Check that its declared source is a valid image file.", - ); - await page.evaluate(() => { - for (const animation of document.getAnimations()) { - if (animation.effect?.getComputedTiming().endTime === Infinity) - animation.cancel(); - else animation.finish(); - } - }); - const fullPage = await page.evaluate(() => { - const { body, documentElement: root } = document; - // Chrome captures blank pixels below a viewport-height scrolling body. - // Let the document scroll for capture while leaving inner panels clipped. - if ( - body.scrollHeight > root.scrollHeight && - ["auto", "scroll"].includes(getComputedStyle(body).overflowY) - ) { - body.style.setProperty("overflow-y", "visible", "important"); - body.style.setProperty("overflow-x", "clip", "important"); - } - return { - width: Math.max( - body.scrollWidth, - root.scrollWidth, - body.offsetWidth, - root.offsetWidth, - body.clientWidth, - root.clientWidth, - ), - height: Math.max( - body.scrollHeight, - root.scrollHeight, - body.offsetHeight, - root.offsetHeight, - body.clientHeight, - root.clientHeight, - ), - }; - }); - const content_height = fullPage.height; - if (content_height > 8192 || fullPage.width > width) - throw new SketchError( - "Screen exceeds its viewport width or 8192px maximum height.", - ); - const { elements, links, error } = await page.evaluate( - captureHitAreas, - { - captureHeight: content_height, - paintOrders: session ? await readPaintOrders(session) : [], - includeSelectors, - destinations: includeLinks - ? board.screens.map(({ id, source }) => ({ id, source })) - : [], - }, - ); - if (error) throw new SketchError(error); - if (links.length > 512) - throw new SketchError( - "A screen supports at most 512 visible links per viewport.", - ); - if ( - !includeSelectors && - (elements.length > 512 || - new Set(elements.map((element) => element.id)).size !== - elements.length || - elements.some( - (element) => - !element.id || - !stableKey.test(element.id) || - !element.label || - element.label.includes("\0") || - Buffer.byteLength(element.label) > 256, - )) - ) - throw new SketchError( - "Visible screen elements need unique keys and labels of at most 256 bytes.", - ); - operation = "rasterizing the screen"; - const png = await page.screenshot({ fullPage: true, timeout: 15000 }); - if ( - png.readUInt32BE(16) !== width || - png.readUInt32BE(20) !== content_height - ) - throw new SketchError( - "The page dimensions changed during capture. Keep the root layout stable while its images load.", - ); - await checkAssets(); - const thumbWidth = Math.min(width, 480); - await thumbnail.setViewportSize({ - width: thumbWidth, - height: Math.ceil((content_height * thumbWidth) / width), - }); - await thumbnail.setContent( - ``, - ); - const thumb = await thumbnail.screenshot({ timeout: 15000 }); - return { - width, - height, - content_height, - elements, - ...(includeLinks ? { links } : {}), - png_base64: png.toString("base64"), - thumbnail_base64: thumb.toString("base64"), - }; - } - const { source, id, name, sample_keys, plan_subjects } = screen; - const metadata = { id, name, sample_keys, plan_subjects }; - screens.push({ - ...metadata, - source_sha256: digest(/** @type {Buffer} */ (files.get(source))), - desktop: await capture(1280, 800), - mobile: await capture(390, 844), - }); - } - return { - version: includeSelectors ? 3 : includeLinks ? 2 : 1, - plan_sha256: digest(planSource), - screens, - }; - } catch (error) { - if (error instanceof SketchError && screenViewport) - throw new SketchError( - `${screenViewport}: ${error.message}`, - error.status, - error.response, - ); - if (error instanceof errors.TimeoutError && screenViewport) - throw new SketchError( - `${screenViewport}: Chrome timed out while ${operation}.`, - ); - throw error; - } finally { - await browser?.close(); - } -} diff --git a/src/sketch-sources.js b/src/sketch-sources.js new file mode 100644 index 0000000..b497b36 --- /dev/null +++ b/src/sketch-sources.js @@ -0,0 +1,165 @@ +import { createHash } from "node:crypto"; +import { lstatSync, readFileSync, realpathSync } from "node:fs"; +import path from "node:path"; +import { isUuidV7 } from "./plan-state.js"; + +export class SketchError extends Error { + /** @param {string} message @param {number} [status] @param {unknown} [response] */ + constructor(message, status, response) { + super(message); + this.status = status; + this.response = response; + } +} +/** @param {string|Buffer} bytes */ +export function digest(bytes) { + return createHash("sha256").update(bytes).digest("hex"); +} + +const stableKey = /^[a-zA-Z0-9][-a-zA-Z0-9_]{0,79}$/; +const media = new Map( + Object.entries({ + ".html": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", + ".svg": "image/svg+xml", + ".woff2": "font/woff2", + }), +); +/** @param {string} cwd */ +export function loadSources(cwd, publishing = false) { + const root = realpathSync(path.join(cwd, "sketches")); + if (root !== path.join(realpathSync(cwd), "sketches")) + throw new SketchError("Use a local sketches directory."); + let bytesRemaining = 18 * 1024 * 1024; + /** @param {string} name */ + function load(name) { + if ( + typeof name !== "string" || + !name + .split("/") + .every((part) => /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/.test(part)) + ) + throw new SketchError("Screen paths must be relative to sketches/."); + const file = path.join(root, name); + const stat = lstatSync(file); + if (realpathSync(file) !== file || !stat.isFile()) + throw new SketchError( + "Screen sources must be regular files inside sketches/.", + ); + if (publishing && name !== "board.json") { + bytesRemaining -= stat.size; + if (bytesRemaining < 0) + throw new SketchError( + "The review bundle exceeds 24 MiB. Reduce the size of the declared source files.", + ); + } + return readFileSync(file); + } + const boardBytes = load("board.json"); + /** @type {{screens:{id:string,name:string,source:string,sample_keys:string[],plan_subjects:string[]}[],assets:string[]}} */ + const board = JSON.parse(boardBytes.toString()); + if ( + !board || + !Array.isArray(board.screens) || + board.screens.length < 1 || + board.screens.length > 32 || + !Array.isArray(board.assets) || + !board.assets.every((asset) => typeof asset === "string") + ) + throw new SketchError( + "board.json requires 1–32 screens and an assets array.", + ); + const ids = new Set(); + for (const screen of board.screens) { + if ( + !screen || + typeof screen.id !== "string" || + !stableKey.test(screen.id) || + typeof screen.name !== "string" || + !screen.name.trim() || + Buffer.byteLength(screen.name) > 256 || + screen.name.includes("\0") || + typeof screen.source !== "string" || + !screen.source.endsWith(".html") || + ids.has(screen.id) + ) + throw new SketchError( + "Each screen needs a unique id, a name and an HTML source.", + ); + for (const field of /** @type {const} */ ([ + "sample_keys", + "plan_subjects", + ])) { + if (screen[field] === undefined) screen[field] = []; + const references = screen[field]; + if ( + !Array.isArray(references) || + references.length > 256 || + !references.every(isUuidV7) + ) + throw new SketchError( + "sample_keys and plan_subjects must be arrays of Plan subject UUIDs.", + ); + } + ids.add(screen.id); + } + if (publishing) { + const names = [ + ...board.assets, + ...board.screens.map(({ source }) => source), + ]; + if (names.length > 512) + throw new SketchError("Declare at most 512 screen and asset files."); + if (new Set(names.map((name) => name.toLowerCase())).size !== names.length) + throw new SketchError( + "Declare each screen and asset path exactly once, with distinct names regardless of case.", + ); + if (board.assets.some((name) => path.extname(name) === ".html")) + throw new SketchError( + "Declare each HTML file as a screen. Use CSS, images or WOFF2 fonts in assets.", + ); + } + const files = new Map([["board.json", boardBytes]]); + for (const name of [ + ...board.assets, + ...board.screens.map((screen) => screen.source), + ]) { + if (!media.has(path.extname(name))) + throw new SketchError( + "Use HTML, CSS, images or WOFF2 fonts for screen sources.", + ); + files.set(name, load(name)); + } + return { board, files }; +} + +/** @param {ReturnType} sources @param {string} plan */ +export function sourceManifest({ board, files }, plan) { + const entries = [...files] + .filter(([name]) => name !== "board.json") + .map(([path, bytes]) => ({ + path, + sha256: digest(bytes), + bytes_base64: bytes.toString("base64"), + })); + const hashes = new Map(entries.map(({ path, sha256 }) => [path, sha256])); + return { + version: 4, + plan_sha256: digest(plan), + screens: board.screens.map( + ({ id, name, source, sample_keys, plan_subjects }) => ({ + id, + name, + source, + source_sha256: hashes.get(source), + sample_keys, + plan_subjects, + }), + ), + files: entries, + }; +} diff --git a/test/package.test.js b/test/package.test.js index ad43693..9284064 100644 --- a/test/package.test.js +++ b/test/package.test.js @@ -38,7 +38,6 @@ test("package metadata preserves the audited runtime boundary", () => { assert.deepEqual(metadata.dependencies, { "jsonc-parser": "3.3.1", - "playwright-core": "1.65.1", }); for (const property of [ "optionalDependencies", diff --git a/test/sketches.test.js b/test/sketches.test.js index b72982f..f590870 100644 --- a/test/sketches.test.js +++ b/test/sketches.test.js @@ -1,4 +1,3 @@ -/* global document, window */ import assert from "node:assert/strict"; import { existsSync, @@ -16,13 +15,7 @@ import { publishSketches as publishWithTheme, reviewedSources, } from "../src/commands/sketches.js"; -import { - SketchError, - bindPlanValues, - captureBoard, - digest, - loadSources, -} from "../src/sketch-capture.js"; +import { digest, loadSources } from "../src/sketch-sources.js"; import { initializePlan } from "../src/commands/plan-init.js"; import { prepareRootOutput, releaseRootOutput } from "../src/root-output.js"; import { pushPlan } from "../src/commands/plan-push.js"; @@ -30,34 +23,24 @@ import { ApiAuthenticationRequiredError } from "../src/api-authentication.js"; import { reviewConflict } from "../src/api-response.js"; import { generateUuidV7 } from "../src/uuid-v7.js"; +/** @param {unknown} selection */ +function liveTheme(selection) { + return Response.json(selection, { + headers: { "FirstDraft-Screen-Source-Files": "1" }, + }); +} + /** @param {Parameters[0]} options */ function publishSketches(options) { return publishWithTheme({ ...options, fetchFunction: (input, request) => String(input).endsWith("/review-theme") - ? Promise.resolve(new Response(null, { status: 404 })) + ? Promise.resolve(liveTheme({ overrides: null, web_theme: {} })) : options.fetchFunction(input, request), }); } -const chromeTest = { - skip: - !process.env.FIRSTDRAFT_CHROME_PATH && - ![ - "/Applications/Google Chrome.app", - "/opt/google/chrome/chrome", - ...[ - process.env.LOCALAPPDATA, - process.env.PROGRAMFILES, - process.env["PROGRAMFILES(X86)"], - ] - .filter((root) => root !== undefined) - .map((root) => - path.join(root, "Google", "Chrome", "Application", "chrome.exe"), - ), - ].some((file) => existsSync(file)), -}; const apiUrl = "https://firstdraft.test"; /** @param {import("node:test").TestContext} t */ function directory(t) { @@ -94,72 +77,6 @@ function draw(cwd) { ); } -test( - "published links use visible rectangles and board screen IDs on each device", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const sketches = path.join(cwd, "sketches"); - const board = JSON.parse( - readFileSync(path.join(sketches, "board.json"), "utf8"), - ); - board.screens.push({ id: "detail", name: "Detail", source: "post.html" }); - board.assets.push("cover.svg"); - writeFileSync(path.join(sketches, "board.json"), JSON.stringify(board)); - writeFileSync( - path.join(sketches, "cover.svg"), - '', - ); - writeFileSync( - path.join(sketches, "post.html"), - 'PostBack', - ); - writeFileSync( - path.join(sketches, "ballot.html"), - ` - PostRead more - OutsideHereDownload - Disabled`, - ); - const manifest = await captureBoard( - loadSources(cwd), - "{}", - undefined, - undefined, - true, - ); - assert.equal(manifest.version, 2); - const first = manifest.screens[0]; - assert(first); - assert.equal(first.desktop.links?.length, 2); - assert.equal(first.mobile.links?.length, 1); - const detail = manifest.screens[1]; - assert(detail); - for (const capture of [detail.desktop, detail.mobile]) { - assert( - capture.links?.some( - (link) => - link.target === "ballot" && - link.width === 200 && - link.height >= 150, - ), - ); - } - for (const link of first.desktop.links ?? []) { - assert.deepEqual(Object.keys(link).sort(), [ - "height", - "target", - "width", - "x", - "y", - ]); - assert.equal(link.target, "detail"); - assert(link.width > 0 && link.height > 0); - } - }, -); - test("a reserved Project survives a lost start, Plan init and an ambiguous review publication", async (t) => { const cwd = directory(t); const opts = { cwd, apiUrl }; @@ -244,15 +161,18 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async (sources, plan) => { + fetchFunction: async (_url, req) => { captures++; + const manifest = JSON.parse(String(req?.body)).manifest; + const html = manifest.files.find( + (/** @type {any} */ f) => f.path === "ballot.html", + ); assert.equal( - sources.files.get("ballot.html")?.toString(), + Buffer.from(html.bytes_base64, "base64").toString(), expectedSource, ); - return { version: 1, plan_sha256: digest(plan), screens: [] }; + return new Response(null, { status }); }, - fetchFunction: async () => new Response(null, { status }), }), /declined/, ); @@ -263,7 +183,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie publishSketches({ ...opts, hasTokenFor: () => false, - capture: async () => assert.fail("wrong origin captured"), fetchFunction: async () => assert.fail("wrong origin requested"), }), ApiAuthenticationRequiredError, @@ -272,11 +191,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async (_sources, plan) => ({ - version: 1, - plan_sha256: digest(plan), - screens: [], - }), fetchFunction: async () => { throw Error("invalid review response lost"); }, @@ -285,7 +199,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async () => assert.fail("retry recaptured"), fetchFunction: async () => Response.json( { @@ -304,16 +217,9 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie ); assert(!existsSync(path.join(cwd, ".firstdraft", "sketch-pending.json"))); let sent = ""; - /** @type {typeof captureBoard} */ - const capture = async (_sources, plan) => ({ - version: 1, - plan_sha256: digest(plan), - screens: [], - }); await assert.rejects( publishSketches({ ...opts, - capture, fetchFunction: async (_input, request) => { sent = String(request?.body); throw Error("response lost"); @@ -324,7 +230,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async () => assert.fail("retry recaptured"), fetchFunction: async (_input, request) => { assert.equal(request?.body, sent); return new Response(null, { status }); @@ -366,7 +271,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie }); const delayed = publishSketches({ ...opts, - capture, fetchFunction: async (input, request) => { const response = await accepted(input, request); markInFlight(); @@ -383,7 +287,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async () => assert.fail("busy retry recaptured"), fetchFunction: async () => assert.fail("busy retry sent a request"), }), /Another command is updating/, @@ -409,7 +312,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture, fetchFunction: async (_input, request) => { const draft = JSON.parse(String(request?.body)); assert.equal(draft.previous_revision_id, review.review.id); @@ -424,7 +326,7 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie ); const latestId = generateUuidV7(); const latestHead = "1".repeat(64); - const rebase = { ...opts, capture, after: latestId, head: latestHead }; + const rebase = { ...opts, after: latestId, head: latestHead }; await assert.rejects( publishSketches({ ...rebase, @@ -446,7 +348,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie writeFileSync(theme, "button{color:blue}"); const replacement = await publishSketches({ ...opts, - capture, after: latestId, head: latestHead, fetchFunction: async (input, request) => { @@ -481,7 +382,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie const newHead = digest(nextSource); await publishSketches({ ...opts, - capture, fetchFunction: async (input) => { writeFileSync(planPath, nextSource); await assert.rejects( @@ -514,7 +414,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture, fetchFunction: async () => assert.fail("busy publication sent a request"), after: replacement.review.id, @@ -540,7 +439,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie await assert.rejects( publishSketches({ ...opts, - capture: async () => assert.fail("invalid Plan reached capture"), fetchFunction: accepted, }), /UTF-8/, @@ -548,402 +446,6 @@ test("a reserved Project survives a lost start, Plan init and an ambiguous revie assert(!existsSync(path.join(cwd, ".firstdraft", "sketch-pending.json"))); }); -test("malformed Plan JSON produces a handled error without exposing source text", async (t) => { - const cwd = directory(t); - draw(cwd); - await assert.rejects( - captureBoard(loadSources(cwd), "private-example-record"), - (error) => { - assert(error instanceof SketchError); - assert.equal( - error.message, - "The working Foundation Plan must contain valid JSON.", - ); - assert.doesNotMatch(error.stack ?? "", /private-example-record/); - return true; - }, - ); -}); - -test( - "Chrome resolves only JSON object members and canonical array indices in Plan bindings", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const html = path.join(cwd, "sketches", "ballot.html"); - const plan = JSON.stringify({ - "a/b": { "~": [{ "": "Escaped label" }] }, - ["__proto__"]: "Own key", - "~2": "bad escape", - "~": "trailing escape", - rows: [], - name: "Mira", - }); - writeFileSync( - html, - '', - ); - const { screens } = await captureBoard(loadSources(cwd), plan); - assert.deepEqual( - screens[0]?.desktop.elements.map((e) => e.label), - ["Escaped label", "Own key"], - ); - const { chromium } = await import("playwright-core"); - const browser = await chromium.launch({ - channel: "chrome", - executablePath: process.env.FIRSTDRAFT_CHROME_PATH, - }); - t.after(() => browser.close()); - const page = await browser.newPage(); - for (const pointer of [ - "/~2", - "/~", - "/rows/length", - "/name/length", - "/name/0", - "/a~1b/~0/00", - "/rows/toString/name", - "/toString/name", - ]) { - await page.setContent( - ``, - ); - assert.match( - (await page.evaluate(bindPlanValues, plan)) ?? "", - /data-plan-pointer/, - pointer, - ); - } - }, -); - -test( - "Chrome captures responsive long screens, matching Plan values and a readable thumbnail", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const board = await captureBoard( - loadSources(cwd), - JSON.stringify({ application: { name: "Mira’s ballot" } }), - ); - const screen = board.screens[0]; - assert(screen); - const { desktop, mobile } = screen; - for (const [capture, width, height] of /** @type {const} */ ([ - [desktop, 1280, 800], - [mobile, 390, 844], - ])) { - assert.equal(capture.width, width); - assert.equal(capture.height, height); - const png = Buffer.from(capture.png_base64, "base64"); - assert.equal(png.readUInt32BE(16), width); - assert.equal(png.readUInt32BE(20), capture.content_height); - assert(capture.elements[0]); - assert(capture.content_height > height); - assert(capture.elements[0].y > height); - assert.equal(capture.elements[0].label, "Mira’s ballot"); - assert.equal(capture.elements[0].id, "submit"); - assert.equal( - capture.elements.find((element) => element.id === "cafe")?.label, - "Café — Mira’s pick", - ); - assert.equal( - Buffer.from(capture.thumbnail_base64, "base64").readUInt32BE(16), - Math.min(480, width), - ); - } - assert(mobile.elements[0] && desktop.elements[0]); - assert(mobile.elements[0].y > desktop.elements[0].y); - }, -); - -test( - "v3 screen selectors resolve on original HTML for both devices in paint order", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const file = path.join(cwd, "sketches", "ballot.html"); - const html = `
-
Foreground
Background
-
Badge action
-
-
Mobile
Desktop
- -
Many short words wrap across lines
-
Long label
- - Sales - - - -
Hi
`; - writeFileSync(file, html); - const manifest = await captureBoard( - loadSources(cwd), - "{}", - undefined, - undefined, - true, - true, - ); - assert.equal(manifest.version, 3); - const screen = manifest.screens[0]; - assert(screen); - const { chromium } = await import("playwright-core"); - const browser = await chromium.launch({ - channel: "chrome", - executablePath: process.env.FIRSTDRAFT_CHROME_PATH, - }); - t.after(() => browser.close()); - const page = await browser.newPage(); - await page.setContent(html); - for (const [capture, variant] of /** @type {const} */ ([ - [screen.desktop, "Desktop"], - [screen.mobile, "Mobile"], - ])) { - const elements = capture.elements; - const reply = elements.find((e) => e.tag === "button"); - assert(reply); - assert.equal(reply.label, "Reply"); - assert( - !elements.some( - (e) => - e.label === "Transparent badge" || - (e.tag === "button" && e.label === "Inert action"), - ), - ); - assert(elements.some((e) => e.tag === "b" && e.label === "Badge action")); - assert.equal(reply?.anchor, "thread"); - assert.equal(reply?.id, undefined); - assert.equal( - reply?.selector, - '[data-sketch-key="thread"] > article:nth-of-type(1) > button:nth-of-type(1)', - ); - assert.equal( - elements.find((e) => e.id === "thread")?.selector, - '[data-sketch-key="thread"]', - ); - assert( - elements.findIndex((e) => e.tag === "span" && e.label === "Reply") > - elements.indexOf(reply), - ); - assert( - elements.findIndex((e) => e.label === "Foreground") > - elements.findIndex((e) => e.label === "Background"), - ); - assert( - elements.some( - (e) => - e.label === variant && !e.id && e.selector?.startsWith("body >"), - ), - ); - assert(elements.some((e) => e.tag === "input" && e.label === "Password")); - assert(elements.some((e) => e.tag === "svg")); - assert(elements.some((e) => e.label === "é".repeat(128))); - assert( - elements.some((e) => e.role === "note" && e.label === "Foreground"), - ); - assert(!elements.some((e) => e.label.includes("private"))); - const bar = elements.find((e) => e.id === "chart-bar"); - const icon = elements.find((e) => e.tag === "svg" && e.label === "Icon"); - const note = elements.find((e) => e.id === "chart-note"); - assert(bar?.selector && icon?.selector && note?.selector); - assert.equal(bar.label, "Sales"); - assert.equal(note.tag, "foreignobject"); - assert.equal(bar.selector, '[data-sketch-key="chart-bar"]'); - assert.deepEqual( - elements.filter((e) => e.tag === "rect").map((e) => e.id), - ["chart-bar"], - ); - await page.setViewportSize({ - width: capture.width, - height: capture.height, - }); - for (const target of [bar, icon, note]) { - const x = target.x + target.width / 2, - y = target.y + target.height / 2; - const picked = elements.findLast( - (e) => - e.x <= x && x < e.x + e.width && e.y <= y && y < e.y + e.height, - ); - assert.equal(picked?.selector, target.selector); - const sourceMatch = await page.evaluate( - ({ x, y, selector }) => { - const actual = document.elementFromPoint(x, y); - const expected = document.querySelector(selector); - if (expected?.localName === "foreignObject") - return !!actual && expected.contains(actual); - return ( - actual?.localName === "rect" && - (actual === expected || - (expected?.localName === "svg" && - actual.closest("svg") === expected)) - ); - }, - { x, y, selector: target.selector ?? "" }, - ); - assert(sourceMatch); - } - assert(elements.some((e) => (e.rects?.length ?? 0) > 1)); - const resolved = await page.evaluate( - (selectors) => - selectors.map((selector) => { - const matches = document.querySelectorAll(selector); - return matches.length === 1 && matches[0]?.localName.toLowerCase(); - }), - elements.map((e) => e.selector ?? ""), - ); - assert.deepEqual( - resolved, - elements.map((e) => e.tag), - ); - } - assert.equal(readFileSync(file, "utf8"), html); - writeFileSync(file, html + '
Duplicate
'); - await assert.rejects( - captureBoard(loadSources(cwd), "{}", undefined, undefined, true, true), - /unique valid authored keys/, - ); - }, -); - -test( - "v3 flex and grid overlaps match Chrome's hit target", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const html = - `` + - ["row", "row reverse", "grid"] - .map( - (layout, i) => - `
`, - ) - .join(""); - writeFileSync(path.join(cwd, "sketches", "ballot.html"), html); - const { screens } = await captureBoard( - loadSources(cwd), - "{}", - undefined, - undefined, - true, - true, - ); - const screen = screens[0]; - assert(screen); - const { chromium } = await import("playwright-core"); - const browser = await chromium.launch({ - channel: "chrome", - executablePath: process.env.FIRSTDRAFT_CHROME_PATH, - }); - t.after(() => browser.close()); - const page = await browser.newPage(); - await page.setContent(html); - for (const capture of [screen.desktop, screen.mobile]) { - await page.setViewportSize({ - width: capture.width, - height: capture.height, - }); - for (const i of [0, 1, 2]) { - const front = capture.elements.find((e) => e.id === "front" + i); - const back = capture.elements.find((e) => e.id === "back" + i); - assert(front && back); - const x = - (Math.max(front.x, back.x) + - Math.min(front.x + front.width, back.x + back.width)) / - 2; - const y = front.y + front.height / 2; - const chromeTarget = await page.evaluate( - ({ x, y }) => - document.elementFromPoint(x, y)?.getAttribute("data-sketch-key"), - { x, y }, - ); - assert(chromeTarget === front.id || chromeTarget === back.id); - if (i !== 1) assert.equal(chromeTarget, front.id); - const picked = capture.elements.findLast( - (e) => - e.x <= x && x < e.x + e.width && e.y <= y && y < e.y + e.height, - ); - assert.equal(picked?.id, chromeTarget); - } - } - }, -); - -test( - "v3 negative backdrops follow Chrome's hit stack at the document and inside stacking contexts", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const html = ` -
-
-
`; - writeFileSync(path.join(cwd, "sketches", "ballot.html"), html); - const { screens } = await captureBoard( - loadSources(cwd), - "{}", - undefined, - undefined, - true, - true, - ); - const screen = screens[0]; - assert(screen); - const { chromium } = await import("playwright-core"); - const browser = await chromium.launch({ - channel: "chrome", - executablePath: process.env.FIRSTDRAFT_CHROME_PATH, - }); - t.after(() => browser.close()); - const page = await browser.newPage(); - await page.setContent(html); - for (const capture of [screen.desktop, screen.mobile]) { - await page.setViewportSize({ - width: capture.width, - height: capture.height, - }); - for (const context of ["document", "isolated", "layer"]) { - const save = capture.elements.find((e) => e.id === context + "-save"); - assert(save); - for (const x of [save.x + save.width / 2, save.x + save.width + 10]) { - const y = save.y + save.height / 2; - const picked = capture.elements.findLast( - (e) => - e.x <= x && x < e.x + e.width && e.y <= y && y < e.y + e.height, - ); - assert(picked?.selector); - const result = await page.evaluate( - ({ selector, x, y }) => { - window.scrollTo(0, Math.max(y - window.innerHeight / 2, 0)); - return ( - document.elementFromPoint(x, y - window.scrollY) === - document.querySelector(selector) - ); - }, - { selector: picked.selector, x, y }, - ); - assert(result, context + " selected " + picked.selector); - } - } - } - }, -); - test("review conflicts preserve both service preconditions, including an empty Head", () => { for (const [status, code] of /** @type {const} */ ([ [409, "sketch_review_conflict"], @@ -993,518 +495,140 @@ test("review conflicts preserve both service preconditions, including an empty H } }); -test( - "Chrome captures lazy images and hit targets in the same settled, clipped layout as the PNG", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const root = path.join(cwd, "sketches"); - const html = `
-
-
- Example`; - writeFileSync( - path.join(root, "ballot.html"), - html - .replace("ANIMATION", "animated") - .replace("", - "", - ]) { - writeFileSync( - page, - `${head}`, - ); - await assert.rejects( - captureBoard(loadSources(cwd), "{}"), - /undeclared or external asset/, - ); +test("a selected theme reaches the Plan and the replayed revision", async (t) => { + const cwd = directory(t); + const projectId = generateUuidV7(); + await startProject({ + cwd, + apiUrl, + fetchFunction: async (input) => { + const id = String(input).split("/").at(-1); + return Response.json({ project: { id, url: "/projects/" + id } }); + }, + }); + initializePlan({ + cwd, + projectId, + applicationKey: "ballot", + name: "Ballot", + }); + draw(cwd); + const planFile = path.join(cwd, ".firstdraft", "foundation-plan.json"); + const preset = { brand: "lake", typography: "serif", corners: "soft" }; + const font = readFileSync( + new URL("./fixtures/triangle.woff2", import.meta.url), + ); + const boardFile = path.join(cwd, "sketches", "board.json"); + const board = JSON.parse(readFileSync(boardFile, "utf8")); + board.assets.push("triangle.woff2"); + writeFileSync(boardFile, JSON.stringify(board)); + writeFileSync(path.join(cwd, "sketches", "triangle.woff2"), font); + const overrides = { + light: { "--primary": "#123456" }, + dark: {}, + shared: {}, + }; + const plan = JSON.parse(readFileSync(planFile, "utf8")); + plan.application.appearance = { web_theme: preset }; + const sample = '"sample": 9007199254740993,'; + writeFileSync(planFile, JSON.stringify(plan).replace("{", "{" + sample)); + /** @type {(string|undefined)[]} */ + const calls = []; + let authorizedId = ""; + let previousBody = ""; + /** @type {typeof fetch} */ + const fetchFunction = async (input, request) => { + const url = new URL(String(input)); + calls.push(request?.method); + if (request?.method === "GET") { + authorizedId = url.pathname.split("/")[3] ?? ""; + assert.equal(request.body, undefined); + return liveTheme({ + overrides, + web_theme: { ...preset, brand: "berry" }, + }); } - }, -); - -test( - "Chrome attributes malformed paths and invalid visible images to the failing screen and device", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const root = path.join(cwd, "sketches"); - const html = path.join(root, "ballot.html"); - writeFileSync(html, ''); - await assert.rejects( - captureBoard(loadSources(cwd), "{}"), - /ballot \(1280 × 800\): .*invalid percent encoding/, - ); - const board = JSON.parse( - readFileSync(path.join(root, "board.json"), "utf8"), - ); - board.assets.push("invalid.png"); - writeFileSync(path.join(root, "board.json"), JSON.stringify(board)); - writeFileSync(path.join(root, "invalid.png"), "not an image"); - writeFileSync( - html, - '', + const source = String(request?.body); + const body = JSON.parse(source); + const digestValue = digest(body.plan_source); + assert.deepEqual( + JSON.parse(readFileSync(planFile, "utf8")).application.appearance + .web_theme, + preset, ); - await assert.rejects( - captureBoard(loadSources(cwd), "{}"), - /ballot \(390 × 844\): Chrome could not decode a visible image/, + assert(body.plan_source.includes(sample)); + assert.deepEqual( + JSON.parse(body.plan_source).application.appearance.web_theme, + { ...preset, overrides }, ); - }, -); - -test( - "a selected theme reaches both local viewports, the Plan, and the replayed revision", - chromeTest, - async (t) => { - const cwd = directory(t); - const projectId = generateUuidV7(); - await startProject({ - cwd, - apiUrl, - fetchFunction: async (input) => { - const id = String(input).split("/").at(-1); - return Response.json({ project: { id, url: "/projects/" + id } }); - }, - }); - initializePlan({ - cwd, - projectId, - applicationKey: "ballot", - name: "Ballot", - }); - draw(cwd); - const planFile = path.join(cwd, ".firstdraft", "foundation-plan.json"); - const preset = { brand: "lake", typography: "serif", corners: "soft" }; - const overrides = { - light: { "--primary": "#123456" }, - dark: {}, - shared: {}, - }; - const plan = JSON.parse(readFileSync(planFile, "utf8")); - plan.application.appearance = { web_theme: preset }; - const sample = '"sample": 9007199254740993,'; - writeFileSync(planFile, JSON.stringify(plan).replace("{", "{" + sample)); - /** @type {(string|undefined)[]} */ - const calls = []; - let authorizedId = ""; - let previousBody = ""; - /** @type {typeof fetch} */ - const fetchFunction = async (input, request) => { - const url = new URL(String(input)); - calls.push(request?.method); - if (request?.method === "GET") { - authorizedId = url.pathname.split("/")[3] ?? ""; - assert.equal(request.body, undefined); - return Response.json({ - overrides, - web_theme: { ...preset, brand: "berry" }, - }); - } - if (request?.method === "POST") { - assert.deepEqual(JSON.parse(String(request.body)), { - web_theme: { ...preset, overrides }, - }); - return Response.json({ - overrides, - web_theme: preset, - stylesheet: - 'button{margin-top:72px!important;font-family:"Test Triangle"}', - fonts: [{ id: "triangle", version: "1.0.0" }], - }); - } - const source = String(request?.body); - const body = JSON.parse(source); - const digestValue = digest(body.plan_source); - assert.deepEqual( - JSON.parse(readFileSync(planFile, "utf8")).application.appearance - .web_theme, - preset, - ); - assert(body.plan_source.includes(sample)); - assert.deepEqual( - JSON.parse(body.plan_source).application.appearance.web_theme, - { ...preset, overrides }, - ); - assert.equal(body.manifest.plan_sha256, digestValue); - assert(!source.includes(" item.id === "submit", - ).y < 100, - ); - if (!previousBody) { - previousBody = source; - throw Error("lost publication response"); - } - assert.equal(source, previousBody); - return Response.json( + assert.equal(body.manifest.plan_sha256, digestValue); + const html = readFileSync(path.join(cwd, "sketches", "ballot.html")); + const css = readFileSync(path.join(cwd, "sketches", "theme.css")); + assert.deepEqual(body.manifest, { + version: 4, + plan_sha256: digestValue, + screens: [ { - project: { id: authorizedId }, - review: { - id: url.pathname.split("/").at(-1), - plan_sha256: digestValue, - }, - foundation_plan: { source_sha256: digestValue }, + id: "ballot", + name: "Guest ballot", + source: "ballot.html", + source_sha256: digest(html), + sample_keys: [], + plan_subjects: [], }, - { headers: { etag: '"sha256:' + digestValue + '"' } }, - ); - }; - /** @type {string[]} */ - const publicPaths = []; - /** @type {typeof fetch} */ - const publicFetch = async (input, init) => { - const url = new URL(String(input)); - publicPaths.push(url.pathname); - assert.equal(url.origin, apiUrl); - assert.equal(init?.credentials, "omit"); - assert.equal(new Headers(init?.headers).has("Authorization"), false); - if (url.pathname.endsWith("/family.css")) - return new Response( - '@font-face{font-family:"Test Triangle";src:url(./files/triangle-latin.woff2)}', - ); - return new Response( - readFileSync(new URL("./fixtures/triangle.woff2", import.meta.url)), - ); - }; - await assert.rejects( - publishWithTheme({ cwd, apiUrl, fetchFunction, publicFetch }), - /request failed/, - ); - const result = await publishWithTheme({ - cwd, - apiUrl, - fetchFunction, - publicFetch, - }); - assert.deepEqual(publicPaths, [ - "/theme-fonts/triangle/1.0.0/family.css", - "/theme-fonts/triangle/1.0.0/files/triangle-latin.woff2", - ]); - assert.deepEqual(calls, ["GET", "POST", "PUT", "PUT"]); - assert.equal( - reviewedSources(cwd, result.review.id)?.planSha256, - digest(readFileSync(planFile)), - ); - }, -); - -test( - "Chrome publishes both viewports and the exact Plan for a selected no-op theme", - chromeTest, - async (t) => { - const cwd = directory(t); - const opened = await startProject({ - cwd, - apiUrl, - fetchFunction: async (input) => { - const id = String(input).split("/").at(-1); - return Response.json({ project: { id, url: "/projects/" + id } }); - }, - }); - initializePlan({ - cwd, - projectId: opened.project.id, - applicationKey: "ballot", - name: "Ballot", - }); - draw(cwd); - const planFile = path.join(cwd, ".firstdraft", "foundation-plan.json"); - const original = readFileSync(planFile, "utf8"); - const selected = { light: {}, dark: {}, shared: {} }; - let acceptedSource = ""; - const result = await publishWithTheme({ - cwd, - apiUrl, - fetchFunction: async (input, init) => { - if (init?.method === "GET") - return Response.json( - { web_theme: {}, overrides: selected, stylesheet: "", fonts: [] }, - { - headers: { - "FirstDraft-Screen-Manifest-Version": "2", - "FirstDraft-Screen-Element-Selectors": "1", - }, - }, - ); - assert.equal(init?.method, "PUT"); - assert.equal(readFileSync(planFile, "utf8"), original); - const { plan_source, manifest } = JSON.parse(String(init.body)); - acceptedSource = plan_source; - const sha = digest(plan_source); - assert.equal(manifest.plan_sha256, sha); - assert.deepEqual( - JSON.parse(plan_source).application.appearance.web_theme, - { overrides: selected }, - ); - assert.equal(manifest.version, 3); - for (const [device, width] of Object.entries({ - desktop: 1280, - mobile: 390, - })) { - const capture = manifest.screens[0][device]; - assert.equal( - Buffer.from(capture.png_base64, "base64").readUInt32BE(16), - width, - ); - assert( - capture.elements.some( - (/** @type {any} */ element) => element.id === "submit", - ), - ); - } - return Response.json( - { - project: { id: opened.project.id }, - review: { id: String(input).split("/").at(-1), plan_sha256: sha }, - foundation_plan: { source_sha256: sha }, - }, - { headers: { etag: '"sha256:' + sha + '"' } }, - ); - }, + ], + files: [ + { + path: "theme.css", + sha256: digest(css), + bytes_base64: css.toString("base64"), + }, + { + path: "triangle.woff2", + sha256: digest(font), + bytes_base64: font.toString("base64"), + }, + { + path: "ballot.html", + sha256: digest(html), + bytes_base64: html.toString("base64"), + }, + ], }); - assert.equal(readFileSync(planFile, "utf8"), acceptedSource); - assert.equal(result.review.plan_sha256, digest(acceptedSource)); - assert.equal( - reviewedSources(cwd, result.review.id)?.planSha256, - digest(acceptedSource), - ); - }, -); - -test( - "a font binary HTTP error retains its status and identifies the failing viewport", - chromeTest, - async (t) => { - const cwd = directory(t); - draw(cwd); - const theme = { - origin: apiUrl, - stylesheet: 'button { font-family: "Test Triangle" }', - fonts: [{ id: "triangle", version: "1.0.0" }], - }; - await assert.rejects( - captureBoard( - loadSources(cwd), - '{"application":{"name":"Ballot"}}', - theme, - async (url) => - String(url).endsWith("/family.css") - ? new Response( - '@font-face{font-family:"Test Triangle";src:url(./files/triangle-latin.woff2)}', - ) - : new Response(null, { status: 503 }), - ), - (error) => { - assert(error instanceof SketchError); - assert.match(error.message, /ballot \(1280 × 800\): .*review font/); - assert.equal(error.status, 503); - return true; - }, - ); - }, -); - -test("font capture downloads only files named in the selected catalog stylesheet with credentials omitted", async () => { - const { captureFonts } = await import("../src/review-theme.js"); - /** @type {string[]} */ - const paths = []; - const fonts = await captureFonts( - { - origin: apiUrl, - stylesheet: "", - fonts: [{ id: "lora", version: "1.2.3" }], - }, - async (input, options) => { - assert.equal(options?.redirect, "error"); - assert.equal(options?.credentials, "omit"); - assert.equal(options?.headers, undefined); - paths.push(String(input)); - return new Response( - String(input).endsWith(".css") - ? "@font-face{src:url('./files/lora-latin-400.woff2')}" - : "font", - ); - }, - ); - const prefix = "/theme-fonts/lora/1.2.3/files/"; - assert.equal(fonts.file(prefix + "lora-other.woff2"), undefined); - assert.equal( - (await fonts.file(prefix + "lora-latin-400.woff2"))?.toString(), - "font", - ); - await fonts.file(prefix + "lora-latin-400.woff2"); - assert.deepEqual(paths, [ - apiUrl + "/theme-fonts/lora/1.2.3/family.css", - apiUrl + prefix + "lora-latin-400.woff2", - ]); -}); - -test("capture includes screen links only when the service advertises their format", async () => { - const { publicationTheme } = await import("../src/review-theme.js"); - for (const version of [null, "1", "2", "3"]) - for (const selectors of [null, "1", "2"]) { - const headers = new Headers(); - if (selectors) - headers.set("FirstDraft-Screen-Element-Selectors", selectors); - if (version) headers.set("FirstDraft-Screen-Manifest-Version", version); - const result = await publicationTheme( - "{}", - apiUrl, - generateUuidV7(), - async () => - Response.json({ overrides: null, web_theme: {} }, { headers }), - ); - assert.equal(result.includeLinks ?? false, version === "2"); - assert.equal( - result.includeSelectors ?? false, - version === "2" && selectors === "1", - ); + if (!previousBody) { + previousBody = source; + throw Error("lost publication response"); } -}); - -test("the working Plan controls the capture theme when the owner has no pending selection", async () => { - const { publicationTheme } = await import("../src/review-theme.js"); - const preset = { brand: "lake", typography: "serif", corners: "soft" }; - const overrides = { light: { "--primary": "#123456" }, dark: {}, shared: {} }; - const empty = { light: {}, dark: {}, shared: {} }; - const hostedCss = ":root{--primary:#235b85}"; - for (const { authored, css, preview } of [ - { authored: preset, css: hostedCss, preview: false }, - { - authored: { ...preset, brand: "berry" }, - css: ":root{--primary:#893956}", - preview: true, - }, - { - authored: { ...preset, overrides }, - css: ":root{--primary:#123456}", - preview: true, - }, - { authored: { overrides: empty }, css: "", preview: true }, - ]) { - const source = - JSON.stringify({ application: { appearance: { web_theme: authored } } }) + - " \n"; - /** @type {(string|undefined)[]} */ - const methods = []; - const result = await publicationTheme( - source, - apiUrl, - generateUuidV7(), - async (_url, init) => { - methods.push(init?.method); - if (init?.method === "GET") - return Response.json({ - web_theme: preset, - overrides: null, - stylesheet: hostedCss, - fonts: [], - }); - assert.deepEqual(JSON.parse(String(init?.body)), { - web_theme: authored, - }); - return Response.json({ stylesheet: css, fonts: [] }); + assert.equal(source, previousBody); + return Response.json( + { + project: { id: authorizedId }, + review: { + id: url.pathname.split("/").at(-1), + plan_sha256: digestValue, + }, + foundation_plan: { source_sha256: digestValue }, }, + { headers: { etag: '"sha256:' + digestValue + '"' } }, ); - assert.equal(result.source, source); - assert.deepEqual(result.theme, { - origin: apiUrl, - stylesheet: css, - fonts: [], - }); - assert.deepEqual(methods, preview ? ["GET", "POST"] : ["GET"]); - } - const source = JSON.stringify({ - application: { appearance: { web_theme: { ...preset, overrides } } }, - }); + }; await assert.rejects( - publicationTheme( - source, - apiUrl, - generateUuidV7(), - async () => new Response(null, { status: 404 }), - ), - /does not support/, + publishWithTheme({ cwd, apiUrl, fetchFunction }), + /request failed/, + ); + const result = await publishWithTheme({ + cwd, + apiUrl, + fetchFunction, + }); + assert.deepEqual(calls, ["GET", "PUT", "PUT"]); + assert.equal( + reviewedSources(cwd, result.review.id)?.planSha256, + digest(readFileSync(planFile)), ); }); -test("a concurrent edit during themed capture survives and no publication is sent", async (t) => { +test("a concurrent edit during publication survives and no publication is sent", async (t) => { const cwd = directory(t); const projectId = generateUuidV7(); await startProject({ @@ -1525,23 +649,16 @@ test("a concurrent edit during themed capture survives and no publication is sen apiUrl, fetchFunction: async (_url, init) => { assert.equal(init?.method, "GET"); - return Response.json({ + writeFileSync(file, edited); + return liveTheme({ overrides: { light: {}, dark: {}, shared: {} }, web_theme: { brand: "lake", typography: "serif", corners: "soft" }, stylesheet: "body{color:black}", fonts: [], }); }, - capture: async (_sources, source) => { - assert.equal( - JSON.parse(source).application.appearance.web_theme.brand, - "lake", - ); - writeFileSync(file, edited); - return { version: 1, plan_sha256: digest(source), screens: [] }; - }, }), - /changed during capture/, + /changed during publication/, ); assert.equal(readFileSync(file, "utf8"), edited); assert.equal( @@ -1587,16 +704,11 @@ test("a pushed Plan-only Project publishes its first screen against its pinned H draw(cwd); const result = await publishWithTheme({ cwd, - capture: async (_sources, plan) => ({ - version: 1, - plan_sha256: digest(plan), - screens: [], - }), fetchFunction: async (input, init) => { const url = new URL(String(input)); assert.equal(url.origin, apiUrl); if (init?.method === "GET") - return Response.json({ + return liveTheme({ web_theme: {}, overrides: { light: {}, dark: {}, shared: {} }, stylesheet: "body{color:black}", @@ -1658,16 +770,10 @@ test("a refused themed publication preserves the authored Plan when the owner cl const file = path.join(cwd, ".firstdraft", "foundation-plan.json"); const authored = readFileSync(file, "utf8"); let selected = true; - /** @type {typeof captureBoard} */ - const capture = async (_sources, source) => ({ - version: 1, - plan_sha256: digest(source), - screens: [], - }); /** @type {typeof fetch} */ const fetchFunction = async (input, init) => { if (init?.method === "GET") - return Response.json({ + return liveTheme({ web_theme: { brand: "lake", typography: "sans", corners: "soft" }, overrides: selected ? { light: {}, dark: {}, shared: {} } : null, stylesheet: "body{color:black}", @@ -1689,7 +795,7 @@ test("a refused themed publication preserves the authored Plan when the owner cl { headers: { etag: '"sha256:' + sha + '"' } }, ); }; - const options = { cwd, apiUrl, capture, fetchFunction }; + const options = { cwd, apiUrl, fetchFunction }; await assert.rejects(publishWithTheme(options), /declined/); assert.equal(readFileSync(file, "utf8"), authored); assert.equal( @@ -1701,7 +807,7 @@ test("a refused themed publication preserves the authored Plan when the owner cl assert(reviewedSources(cwd, review.review.id)); }); -test("a service stop after reading theme selection prevents capture and publication journaling", async (t) => { +test("a service stop after reading theme selection prevents publication journaling", async (t) => { const cwd = directory(t); let projectId = ""; await startProject({ @@ -1727,10 +833,9 @@ test("a service stop after reading theme selection prevents capture and publicat throwIfStopped: () => { throw Error("service stopped"); }, - capture: () => assert.fail("stopped command captured"), fetchFunction: async (_url, init) => { assert.equal(init?.method, "GET"); - return Response.json({ overrides: null, web_theme: {} }); + return liveTheme({ overrides: null, web_theme: {} }); }, }), /service stopped/, @@ -1741,40 +846,6 @@ test("a service stop after reading theme selection prevents capture and publicat ); }); -test("review-theme preview errors preserve the validated problem", async () => { - const { publicationTheme } = await import("../src/review-theme.js"); - const web_theme = { - brand: "lake", - typography: "sans", - corners: "soft", - overrides: { light: {}, dark: {}, shared: {} }, - }; - const source = JSON.stringify({ application: { appearance: { web_theme } } }); - const problem = { - title: "Authentication required", - status: 401, - code: "authentication_required", - detail: "Log in first.", - }; - await assert.rejects( - publicationTheme(source, apiUrl, generateUuidV7(), async (_url, init) => - init?.method === "GET" - ? Response.json({ overrides: null, web_theme: {} }) - : Response.json(problem, { - status: 401, - headers: { "Content-Type": "application/problem+json" }, - }), - ), - (e) => - e instanceof SketchError && - e.status === 401 && - e.response !== null && - typeof e.response === "object" && - "code" in e.response && - e.response.code === "authentication_required", - ); -}); - test("publication returns the accepted theme for reconciliation when an editor changes the working Plan during the PUT", async (t) => { const cwd = directory(t); let projectId = ""; @@ -1804,14 +875,9 @@ test("publication returns the accepted theme for reconciliation when an editor c const result = await publishWithTheme({ cwd, apiUrl, - capture: async (_sources, plan) => ({ - version: 1, - plan_sha256: digest(plan), - screens: [], - }), fetchFunction: async (input, init) => { if (init?.method === "GET") - return Response.json({ + return liveTheme({ web_theme: {}, overrides, stylesheet: "body{color:#123456}", @@ -1833,3 +899,142 @@ test("publication returns the accepted theme for reconciliation when an editor c assert.match(result.next_step ?? "", /published_web_theme/); assert.deepEqual(result.published_web_theme, { overrides }); }); + +test("publication rejects ambiguous paths, HTML outside the screen list, unsupported resources and oversized bundles", (t) => { + const cwd = directory(t); + draw(cwd); + const file = path.join(cwd, "sketches", "board.json"); + const original = JSON.parse(readFileSync(file, "utf8")); + for (const [board, message] of /** @type {const} */ ([ + [ + { + ...original, + screens: [...original.screens, { ...original.screens[0], id: "other" }], + }, + /exactly once/, + ], + [{ ...original, assets: ["theme.css", "THEME.CSS"] }, /exactly once/], + [{ ...original, assets: ["other.html"] }, /HTML file as a screen/], + [{ ...original, assets: ["script.js"] }, /images or WOFF2/], + [ + { + ...original, + assets: Array.from({ length: 512 }, (_, i) => i + ".css"), + }, + /at most 512/, + ], + ])) { + writeFileSync(file, JSON.stringify(board)); + assert.throws(() => loadSources(cwd, true), message); + } + writeFileSync(file, JSON.stringify(original)); + writeFileSync( + path.join(cwd, "sketches", "theme.css"), + Buffer.alloc(18 * 1024 * 1024), + ); + assert.throws(() => loadSources(cwd, true), /exceeds 24 MiB/); +}); + +test("retry sends persisted version 1 through 3 requests byte for byte with their original IDs", async (t) => { + const cwd = directory(t); + const { project } = await startProject({ + cwd, + apiUrl, + fetchFunction: async (input) => { + const id = String(input).split("/").at(-1); + return Response.json({ project: { id, url: "/projects/" + id } }); + }, + }); + initializePlan({ + cwd, + projectId: project.id, + applicationKey: "reading", + name: "Reading", + }); + draw(cwd); + const plan_source = readFileSync( + path.join(cwd, ".firstdraft", "foundation-plan.json"), + "utf8", + ); + const sha = digest(plan_source); + const files = Object.fromEntries( + [...loadSources(cwd).files].map(([name, bytes]) => [name, digest(bytes)]), + ); + for (const version of [1, 2, 3]) { + const id = generateUuidV7(); + const body = JSON.stringify( + { + plan_source, + manifest: { version, plan_sha256: sha, screens: [] }, + previous_revision_id: null, + expected_plan_sha256: null, + }, + null, + 2, + ); + writeFileSync( + path.join(cwd, ".firstdraft", "sketch-pending.json"), + JSON.stringify({ id, files, body }), + ); + const result = await publishWithTheme({ + cwd, + apiUrl, + fetchFunction: async (input, init) => { + assert.equal(init?.method, "PUT"); + assert.equal(init.body, body); + assert(String(input).endsWith("/" + id)); + return Response.json( + { + project: { id: project.id }, + review: { id, plan_sha256: sha }, + foundation_plan: { source_sha256: sha }, + }, + { headers: { etag: '"sha256:' + sha + '"' } }, + ); + }, + }); + assert.equal(result.review.id, id); + assert(reviewedSources(cwd, id, true)?.files.has("board.json")); + } +}); + +test("a service without live screen support leaves the Plan untouched and creates no pending publication", async (t) => { + const cwd = directory(t); + const { project } = await startProject({ + cwd, + apiUrl, + fetchFunction: async (input) => { + const id = String(input).split("/").at(-1); + return Response.json({ project: { id, url: "/projects/" + id } }); + }, + }); + initializePlan({ + cwd, + projectId: project.id, + applicationKey: "reading", + name: "Reading", + }); + const file = path.join(cwd, ".firstdraft", "foundation-plan.json"); + const authored = readFileSync(file); + for (const response of [ + new Response(null, { status: 404 }), + Response.json( + { overrides: {}, web_theme: {} }, + { headers: { "FirstDraft-Screen-Manifest-Version": "2" } }, + ), + ]) { + await assert.rejects( + publishWithTheme({ + cwd, + apiUrl, + fetchFunction: async (_url, init) => { + assert.equal(init?.method, "GET"); + return response; + }, + }), + /Update the First Draft service/, + ); + assert.deepEqual(readFileSync(file), authored); + assert(!existsSync(path.join(cwd, ".firstdraft", "sketch-pending.json"))); + } +});