Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(docs): live runnable docs and walkthroughs
nirholasd41f04f45d5d
diff --git a/data/walkthroughs.json b/data/walkthroughs.jsonnew file mode 100644index 000000000..88dde49b4--- /dev/null+++ b/data/walkthroughs.json@@ -0,0 +1,205 @@+{+ "$schema": "./walkthroughs.schema.json",+ "version": 1,+ "description": "Authored source of truth for /walkthroughs. Copy is written by hand; every screenshot and every hotspot rectangle is captured from the live product by scripts/capture-walkthroughs.mjs, so the media can never drift from the UI it describes.",+ "viewport": { "width": 1440, "height": 900 },+ "walkthroughs": [+ {+ "slug": "forge-your-first-3d-model",+ "title": "Forge your first 3D model",+ "outcome": "A textured, downloadable GLB from one sentence of text.",+ "blurb": "The free text-to-3D lane, end to end: what to type, which engine to pick, and where the finished model lands.",+ "level": "beginner",+ "minutes": 3,+ "accent": "#8b5cf6",+ "cta": { "label": "Open Forge", "href": "/forge" },+ "related": [{ "label": "Text to 3D tutorial", "href": "/tutorials/text-to-3d" }],+ "steps": [+ {+ "path": "/forge",+ "focus": "#composer",+ "title": "One box is the whole product",+ "body": "Forge opens on a single composer. Describe an object, upload photos of a real one, or scribble a sketch. Every lane below leads to the same place: a textured GLB you own.",+ "tip": "No account and no wallet are needed to generate. Sign in only when you want the model saved to your library."+ },+ {+ "path": "/forge",+ "focus": "#text-pane",+ "before": [{ "fill": ["#prompt", "a brass compass, weathered, cracked glass"] }, { "wait": 500 }],+ "title": "Name one object and one material",+ "body": "The prompt coach under the box is live: it reads what you typed and tells you what is missing. One object plus one material beats a paragraph of adjectives every time.",+ "tip": "Stuck? Surprise me writes a known-good prompt, and Enhance rewrites yours without changing the subject."+ },+ {+ "path": "/forge",+ "focus": "#engine",+ "title": "Pick an engine, or just take the free one",+ "body": "Engines are labelled with what they cost you. The ones tagged FREE need no API key and no card. Busy and unavailable states are live, so you are never sent at a lane that cannot answer.",+ "tip": "Quality steps from Draft to High. High is a $THREE holder perk, and the note under the picker links straight to it."+ },+ {+ "path": "/forge",+ "focus": "#generate",+ "title": "Generate, then watch it build",+ "body": "One button. The stage on the right renders a preview image first, then builds the mesh, so you can bail out early if the silhouette is wrong instead of waiting on a full generation.",+ "action": { "label": "Try it on the real page", "href": "/forge" }+ },+ {+ "path": "/forge",+ "focus": "#showcase",+ "title": "Everything lands in the gallery",+ "body": "Finished models drop into Fresh from the Forge alongside everyone else's. Each card opens the model in 3D, and anything public can be remixed as the starting point for your next one.",+ "action": { "label": "Browse the gallery", "href": "/creations" }+ }+ ]+ },+ {+ "slug": "build-your-first-agent",+ "title": "Build your first agent",+ "outcome": "A named agent with a body, a personality, and a shareable URL.",+ "blurb": "Five steps, and the first one fills in the other four for you. Build the whole thing before you ever sign in.",+ "level": "beginner",+ "minutes": 4,+ "accent": "#22d3ee",+ "cta": { "label": "Open the agent builder", "href": "/create-agent" },+ "related": [{ "label": "Getting started tutorial", "href": "/tutorials/getting-started" }],+ "steps": [+ {+ "path": "/create-agent",+ "focus": "#stepper",+ "title": "Five steps, always visible",+ "body": "Basics, model, skills, personality, review. The stepper is a map, not a cage: every step you have already reached stays clickable, so you can jump back without losing what you typed.",+ "tip": "Progress is kept locally as you go. Closing the tab does not cost you the agent."+ },+ {+ "path": "/create-agent",+ "focus": "#magic-input",+ "before": [+ { "fill": ["#magic-input", "A calm meditation coach who runs short breathing sessions and speaks in a warm, unhurried voice"] },+ { "wait": 500 }+ ],+ "title": "Describe it once in plain English",+ "body": "One sentence into this box and Generate fills the name, the description, the skill selection, and the personality sliders across all five steps. The wizard becomes a review pass instead of a form.",+ "tip": "Everything it writes stays editable. It is a first draft, not a decision."+ },+ {+ "path": "/create-agent",+ "focus": "#magic-chips",+ "title": "Or start from a known-good shape",+ "body": "The chips are complete starting points, not placeholder text: meditation coach, market analyst, 3D art critic, onboarding host. Surprise me picks one you would not have thought of.",+ "tip": "Pick a chip, then edit one thing. That is usually a better agent than a blank start."+ },+ {+ "path": "/create-agent",+ "focus": "#wizard",+ "title": "The form is short on purpose",+ "body": "Each step asks for the minimum it genuinely needs and offers a sensible default for the rest. You can walk from the first step to the review screen without typing anything else.",+ "action": { "label": "Build one now", "href": "/create-agent" }+ },+ {+ "path": "/create-agent",+ "focus": "#build-free-note",+ "title": "Sign in only when you ship",+ "body": "Building costs nothing and needs no account. Signing in is what turns the draft into a hosted agent with its own page, its own URL, and a wallet it can be paid through.",+ "action": { "label": "See a live agent page", "href": "/agents" }+ }+ ]+ },+ {+ "slug": "embed-a-3d-avatar",+ "title": "Embed a 3D avatar on your site",+ "outcome": "One script tag that puts a live, animated avatar on any page you control.",+ "blurb": "Configure it by clicking, watch the code rewrite itself, then copy the tag. No build step, no framework.",+ "level": "beginner",+ "minutes": 3,+ "accent": "#f59e0b",+ "cta": { "label": "Open the playground", "href": "/#embed" },+ "related": [{ "label": "Add a 3D assistant tutorial", "href": "/tutorials/add-a-3d-assistant" }],+ "steps": [+ {+ "path": "/",+ "focus": "#embed",+ "title": "The playground is the documentation",+ "body": "Editor on the left, live avatar on the right. It is not a video or a screenshot of an IDE: the preview is the real web component running the exact code in the box.",+ "tip": "HTML, React, and Vue tabs emit the same component with the syntax each ecosystem expects."+ },+ {+ "path": "/",+ "focus": "#pg-avatars",+ "title": "Pick a body by clicking one",+ "body": "Each swatch swaps the avatar in the preview and rewrites the src attribute in the code. These are the same hosted GLBs your production embed will load.",+ "tip": "Any model you forge or upload can go here too. Swap the src for your own URL."+ },+ {+ "path": "/",+ "focus": "#pg-option-chips",+ "title": "Toggle the behaviour, not the CSS",+ "body": "Responsive sizing, a nameplate, the chat dock, eager loading. Each chip is one attribute on the tag, so what you turn on here is exactly what ships.",+ "tip": "Background chips cover the common cases: transparent over your hero, or a dark or light plate."+ },+ {+ "path": "/",+ "focus": "#pg-editor",+ "title": "The code is editable, both ways",+ "body": "Clicking a chip writes into the editor, and typing in the editor updates the preview. Break it on purpose to see how it fails before you paste it into your own page.",+ "action": { "label": "Read the embed docs", "href": "/docs/embed" }+ },+ {+ "path": "/",+ "focus": "#pg-copy",+ "title": "Copy the tag and you are done",+ "body": "One script tag and one element. It works in a static HTML file, a WordPress theme, a Shopify template, or a React app, because it is a web component and not a framework plugin.",+ "action": { "label": "Get the SDK", "href": "/avatar-sdk" }+ }+ ]+ },+ {+ "slug": "find-an-agent-worth-using",+ "title": "Find an agent worth using",+ "outcome": "A shortlist of working agents, filtered by what they do and what they cost.",+ "blurb": "The marketplace is thousands of entries deep. Here is the path from the front door to something you would actually run.",+ "level": "beginner",+ "minutes": 3,+ "accent": "#34d399",+ "cta": { "label": "Open the marketplace", "href": "/marketplace" },+ "related": [{ "label": "Search everything", "href": "/search" }],+ "steps": [+ {+ "path": "/marketplace",+ "focus": "#market-theme-strip",+ "title": "Start with the weekly theme",+ "body": "The strip at the top is a curated cut of the catalogue that rotates. When you do not yet know what you are looking for, it is a far better entry point than an empty search box.",+ "tip": "Browse opens the full theme as a filtered view rather than a static list."+ },+ {+ "path": "/marketplace",+ "focus": "#market-hero",+ "title": "Featured entries load in real 3D",+ "body": "The hero is a live viewer, not a render. Spin the avatar, open it in the 3D lobby, or fork it straight into a new agent of your own from the same card.",+ "tip": "Start an agent carries the body over, so you skip the model step in the builder."+ },+ {+ "path": "/marketplace",+ "focus": "#market-filter-chips",+ "title": "Filter by kind, then by price",+ "body": "Agents, avatars, and onchain entries are different things and the chips keep them apart. The price filter is honest about which listings are free and which charge per call.",+ "tip": "Counts on the chips are live, so an empty result is visible before you click it."+ },+ {+ "path": "/marketplace",+ "focus": "#market-cat-chips",+ "title": "Categories carry real counts",+ "body": "Academic, career, design, education, and the rest, each with the number of live entries behind it. The number is what tells you whether a category is worth opening.",+ "tip": "Category and price filters compose. Free plus Design is one click away from here."+ },+ {+ "path": "/marketplace",+ "focus": "#market-activity-strip",+ "title": "Check the pulse before you commit",+ "body": "Agents live, prompts scored today, win rate, open trades. This strip is the fastest read on whether the thing you are about to depend on is actually being used right now.",+ "action": { "label": "Watch agents work live", "href": "/agents-live" }+ }+ ]+ }+ ]+}diff --git a/data/walkthroughs.schema.json b/data/walkthroughs.schema.jsonnew file mode 100644index 000000000..3d83b422b--- /dev/null+++ b/data/walkthroughs.schema.json@@ -0,0 +1,94 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "https://three.ws/schemas/walkthroughs.schema.json",+ "title": "three.ws walkthroughs",+ "description": "Authored content for the interactive walkthrough player at /walkthroughs. Screenshots and hotspot rectangles are NOT authored here: scripts/capture-walkthroughs.mjs drives the live site and writes them into public/walkthroughs/manifest.json.",+ "type": "object",+ "required": ["version", "viewport", "walkthroughs"],+ "properties": {+ "$schema": { "type": "string" },+ "version": { "type": "integer", "minimum": 1 },+ "description": { "type": "string" },+ "viewport": {+ "type": "object",+ "required": ["width", "height"],+ "properties": {+ "width": { "type": "integer", "minimum": 320 },+ "height": { "type": "integer", "minimum": 320 }+ },+ "additionalProperties": false+ },+ "walkthroughs": {+ "type": "array",+ "minItems": 1,+ "items": { "$ref": "#/definitions/walkthrough" }+ }+ },+ "additionalProperties": false,+ "definitions": {+ "link": {+ "type": "object",+ "required": ["label", "href"],+ "properties": {+ "label": { "type": "string", "minLength": 1 },+ "href": { "type": "string", "pattern": "^/" }+ },+ "additionalProperties": false+ },+ "walkthrough": {+ "type": "object",+ "required": ["slug", "title", "outcome", "blurb", "level", "minutes", "accent", "cta", "steps"],+ "properties": {+ "slug": { "type": "string", "pattern": "^[a-z0-9-]+$" },+ "title": { "type": "string", "minLength": 1 },+ "outcome": { "type": "string", "minLength": 1, "description": "What the reader ends up holding." },+ "blurb": { "type": "string", "minLength": 1 },+ "level": { "enum": ["beginner", "intermediate", "advanced"] },+ "minutes": { "type": "integer", "minimum": 1, "maximum": 60 },+ "accent": { "type": "string", "pattern": "^#[0-9a-f]{6}$" },+ "cta": { "$ref": "#/definitions/link" },+ "related": { "type": "array", "items": { "$ref": "#/definitions/link" } },+ "steps": {+ "type": "array",+ "minItems": 2,+ "maxItems": 12,+ "items": { "$ref": "#/definitions/step" }+ }+ },+ "additionalProperties": false+ },+ "step": {+ "type": "object",+ "required": ["path", "focus", "title", "body"],+ "properties": {+ "path": { "type": "string", "pattern": "^/", "description": "Real route on three.ws that this step is captured from." },+ "focus": { "type": "string", "minLength": 1, "description": "CSS selector for the element the step is about. Capture fails loudly if it stops matching." },+ "title": { "type": "string", "minLength": 1 },+ "body": { "type": "string", "minLength": 1 },+ "tip": { "type": "string", "minLength": 1 },+ "action": { "$ref": "#/definitions/link" },+ "before": {+ "type": "array",+ "description": "Real interactions performed against the live page before the frame is taken, so a step can show a state the visitor would have to click their way into.",+ "items": {+ "type": "object",+ "properties": {+ "click": { "type": "string" },+ "fill": {+ "type": "array",+ "items": { "type": "string" },+ "minItems": 2,+ "maxItems": 2+ },+ "wait": { "type": "integer", "minimum": 0, "maximum": 15000 }+ },+ "additionalProperties": false,+ "minProperties": 1,+ "maxProperties": 1+ }+ }+ },+ "additionalProperties": false+ }+ }+}diff --git a/docs/live-docs.md b/docs/live-docs.mdnew file mode 100644index 000000000..2f5e5d08f--- /dev/null+++ b/docs/live-docs.md@@ -0,0 +1,181 @@+# Live Docs++Every code sample in these docs is editable, and the ones that can be run have a+**Run** button. An `<agent-3d>` snippet renders a real, animated avatar right+under the code. A `curl` line sends a real request to the live three.ws API and+shows you the status, the latency, and the response. A `js` snippet executes and+prints its console output.++You are reading the feature's own documentation, so every sample below is live.+Press **Edit**, change something, and press <kbd>⌘</kbd>/<kbd>Ctrl</kbd> ++<kbd>Enter</kbd>.++---++## Try it: a live avatar++This is the same embed snippet from the [`<agent-3d>` reference](web-component.md).+Press **Run preview** and it renders. Then press **Edit**, swap `michelle.glb`+for `xbot.glb`, and run it again.++```html+<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>++<agent-3d+ body="https://three.ws/avatars/michelle.glb"+ animation="idle"+ style="width:320px;height:420px"+></agent-3d>+```++Other bodies you can paste in: `xbot.glb`, `cesium-man.glb`,+`realistic-female.glb`, `default.glb`. The full catalogue is on+[/character-library](/character-library).++## Try it: a real API call++```bash+curl https://three.ws/api/version+```++That is the deployed commit and Cloud Run revision serving this page right now.+Here is one with a query string worth editing:++```bash+curl "https://three.ws/api/search?q=robot&limit=3"+```++## Try it: a script++```js+const res = await fetch('https://three.ws/api/coin/markets?limit=3');+const body = await res.json();+console.log('status', res.status);+console.log(body);+```++---++## What becomes runnable++The runner never guesses. A block is offered a **Run** button only when it+matches one of these three shapes.++| Fence language | Becomes runnable when | What Run does |+| --- | --- | --- |+| `html`, `xml`, `svg` | The snippet renders something visible: an `<agent-3d>` / `<model-viewer>` element, a full document, or ordinary structural markup | Renders it in a sandboxed frame under the code |+| `bash`, `sh`, `shell`, `zsh`, `console`, `curl` | The block is exactly one `curl` command | Sends the request from your browser and shows status, latency, size, body, and response headers |+| `js`, `javascript`, `mjs` | The snippet calls `fetch` or `console.*`, and is not a Node or bundler sample | Runs it as a module in a sandboxed frame and streams the console back |++Everything else stays exactly as it was: a `python` block, an `npm install`+line, a `json` payload, a `<meta>` tag sample. A block that would render an empty+box or produce no output is deliberately left alone, because a Run button that+does nothing visible teaches you the feature is broken.++## What can never run++A documentation page is read by people who are often signed in, evaluating the+platform, and clicking things. So the runner is narrow by construction, and the+rules are enforced in a [tested pure+module](https://github.com/nirholas/three.ws/blob/main/public/docs-live-core.js)+rather than in a click handler:++- **Only three.ws.** A sample pointing at any other host is not runnable. It+ cannot be made runnable by editing the URL to something else, either: the+ check re-runs on every keystroke.+- **Money paths are never runnable, on any verb.** Anything whose path contains+ `/pay`, `/send`, `/transfer`, `/withdraw`, `/fund`, `/swap`, `/trade`, `/buy`,+ `/sell`, `/wallet`, `/mint`, `/launch`, `/autopilot`, `/x402`, `/checkout`,+ `/billing`, `/subscribe`, `/sniper` or `/vault` is refused outright. Copy those+ and run them yourself, where you can see what you are signing.+- **Writes need a second click.** `GET` and `HEAD` send on one click. `POST`,+ `PUT`, `PATCH` and `DELETE` arm the button first and print the exact method and+ URL, and only send when you confirm.+- **Requests are anonymous.** Every fetch is sent with `credentials: 'omit'`, so+ your three.ws session never authorizes a sample by accident. If an endpoint+ needs a key, the sample says so and you supply it (see below).+- **Frames are sandboxed with no same-origin access.** Previews and scripts run+ with `sandbox="allow-scripts"` and without `allow-same-origin`, so a snippet+ gets an opaque origin: it can load the three.ws web component over the network+ but cannot read this page, its cookies, or its storage.++## Filling in placeholders++When a sample contains a slot such as `$THREEWS_API_KEY`, `<agent-id>`, or+`YOUR_WALLET`, the runner renders one input per slot and substitutes your values+before sending. Nothing is rewritten in the printed sample, so the page still+shows the canonical form.++Values for ordinary slots (an agent id, a wallet address) persist in+`sessionStorage` for the tab, so typing an agent id on one page carries to the+next. Values whose name looks like a credential (`KEY`, `TOKEN`, `SECRET`,+`PASSWORD`, `AUTH`, `PRIVATE`) are held in memory only and are never written to+any storage.++An unfilled slot is left in the URL verbatim rather than substituted with an+empty string, so a forgotten field shows up as `/api/agents/<agent-id>` in the+request line instead of silently calling `/api/agents/`.++---++## For doc authors++Nothing is required. Write a normal fenced code block and the runner decides.++**To opt a block out**, put an HTML comment on the line above it:++````markdown+<!-- live:off -->+```html+<agent-3d body="https://example.com/private.glb"></agent-3d>+```+````++Use that when a sample is illustrative rather than correct: a snippet with a+placeholder host, a deliberately broken example, or markup whose point is the+attribute list rather than the render.++**Keep samples real.** The runner makes a wrong sample visibly wrong, which is+the best reason yet to follow the existing rule that every doc sample uses a live+three.ws avatar URL and a real endpoint. A sample that 404s now 404s in front of+the reader.++**Previews follow the reader's origin.** A sample correctly hardcodes+`https://three.ws/agent-3d/…` because that is what someone pastes into their own+site. Inside the preview frame that URL is rewritten to whatever origin the+reader is on, so a preview on a dev server exercises the local build instead of+silently loading production.++---++## How it is put together++| File | Role |+| --- | --- |+| [`public/docs-live-core.js`](https://github.com/nirholas/three.ws/blob/main/public/docs-live-core.js) | Pure decisions: block classification, shell tokenizing, the `curl` parser, the safety verdict, placeholder detection, preview document construction. No DOM, no network. |+| [`public/docs-live.js`](https://github.com/nirholas/three.ws/blob/main/public/docs-live.js) | The runner: toolbar, inline editor, placeholder fields, sandboxed frames, response rendering. |+| [`public/docs-live.css`](https://github.com/nirholas/three.ws/blob/main/public/docs-live.css) | Styling, derived from the docs design tokens so the runner reads as part of the page. |+| [`tests/docs-live-core.test.js`](https://github.com/nirholas/three.ws/blob/main/tests/docs-live-core.test.js) | Pins every safety rule above, plus the parser and formatter behaviour. |++The split is the point. Everything that decides what a reader is allowed to fire+is a pure function, so it is unit-tested rather than trusted to a click handler.++The runner is loaded lazily by the docs viewer after the first page renders, and+attaches per block, so a page with no runnable samples costs nothing beyond one+cached module.++## Keyboard++| Key | Where | Action |+| --- | --- | --- |+| <kbd>⌘</kbd>/<kbd>Ctrl</kbd> + <kbd>Enter</kbd> | In the editor | Run the sample |+| <kbd>Esc</kbd> | In the editor | Leave the editor, keeping your changes |+| <kbd>Tab</kbd> | In the editor | Insert a tab (it does not move focus) |+| <kbd>Enter</kbd> | In a placeholder field | Run the request |++## Related++- [`<agent-3d>` Web Component API Reference](web-component.md) — the element most previews render+- [API reference](api-reference.md) — the endpoints most `curl` samples call+- [Embed and share](embedding.md) — putting an avatar on your own site+- [MCP tool safety](mcp-safety.md) — the same read/write/irreversible split, applied to agent toolsdiff --git a/docs/live-steps.md b/docs/live-steps.mdnew file mode 100644index 000000000..349ec1eb9--- /dev/null+++ b/docs/live-steps.md@@ -0,0 +1,154 @@+# Live steps: documentation that runs++Most API documentation asks you to believe it. A sample response was true when someone pasted it, the endpoint may have changed since, and the only way to find out is to leave the page, open a terminal, and try.++Live steps remove that gap. A tutorial can embed a card that performs a **real request against the live three.ws API, from your browser, right now**, and renders the real response. Nothing is recorded, mocked, or replayed. If the platform changed, the page shows you the change.++Open [Add wallet sign-in to your app](/tutorials/wallet-sign-in) and press **Run it** on the nonce step to see one.++---++## What a reader gets++Each card shows the method and path it will call, a plain-language line about what you are about to observe, and an editable set of query parameters where the endpoint takes them. Pressing the button performs the call and reports:++- the real HTTP status, the round-trip time in milliseconds, and the response size+- the response body, pretty-printed and syntax-coloured, with one-click copy+- for a failure, what actually went wrong and what to do about it, rather than a raw status code++Steps also **chain**. A step can publish named values out of its response, and a later step on the same page can consume them. In the wallet sign-in tutorial the nonce step publishes `nonce`, `domain`, and `uri`, and the next step assembles the exact bytes a wallet would sign from those values. Press the second button without the first and it runs the prerequisite for you, then continues.++When a page carries more than one live step, a **Run every step** bar appears above the first one and walks the whole flow in order.++---++## The security model++Documentation is content, and content must never be able to choose what request a page makes. If a markdown file could name a URL, then anyone who can land a pull request on the docs could make every reader's browser call anything, with the reader's cookies attached.++So live steps invert it: **markdown selects, code decides.**++A `live` block may only name an id that already exists in the registry in [public/live-steps.js](https://github.com/nirholas/three.ws/blob/main/public/live-steps.js). Adding an endpoint to that registry is a code change, reviewed like any other code change. Five invariants back that up, and four of them are checked at load time by `validateRegistry`, which throws rather than degrading:++| Invariant | Why |+|---|---|+| Every step is a `GET` | A live step can never mutate platform state. A registry entry with any other method fails at load. |+| Paths are literal constants matching `/^\/api\/...$/` | Nothing interpolates into the path or the origin, so a step cannot be pointed at another host. Traversal and protocol-relative paths are rejected. |+| Reader input reaches only query values, through `URLSearchParams` | A hostile value is encoded, not obeyed. `../../admin` stays a parameter value. |+| Responses render through the DOM, never `innerHTML` | A hostile response body cannot inject markup into the docs page. |+| Session-shaped fields are redacted before display | Covered below. |++An id that is not registered renders a visible "this live step is not registered" card and issues no request at all, so a typo is loud for the author and inert for the reader.++### Redaction++Fields whose names look like credentials (`sid`, `csrf`, any `*_token`, `authorization`, `cookie`, `api_key`, and friends) are replaced in the rendered copy, and the card says how many were hidden. This matters because documentation gets screenshotted, recorded, and pasted into issues, and a page that displays a working session identifier will eventually leak one.++Redaction only touches the **display**. Chained exports read the raw response body, so a step can consume a value that was never shown on screen.++---++## Authoring a live step++### 1. Write the block++In any file under `docs/tutorials/`, add a fenced block with the language `live` containing JSON:++````markdown+```live+{ "step": "siws-nonce" }+```+````++Two optional keys override the card's copy when the surrounding prose needs a different emphasis:++```json+{+ "step": "agents-public",+ "title": "See what the directory returns",+ "note": "Raise the limit and watch the cursor field appear."+}+```++On GitHub, and in any renderer that does not load the viewer, the block degrades to a small visible JSON snippet. Keep a static sample response nearby in the prose so the page still teaches when the card does not render.++### 2. If the endpoint is not registered yet, register it++Add an entry to `STEPS` in [public/live-steps.js](https://github.com/nirholas/three.ws/blob/main/public/live-steps.js):++```js+{+ id: 'platform-stats',+ kind: 'request',+ method: 'GET',+ path: '/api/platform/stats',+ title: 'Read the live platform counters',+ summary: 'Agents, avatars, widgets and chains, counted at request time.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [],+ exports: {},+}+```++- `credentials: 'include'` sends the reader's cookies. Use it only where the answer depends on who is asking, and expect to see the signed-out shape most of the time.+- `inputs` become editable text fields and are sent as query parameters. Give each one a `value` (the default), a `placeholder`, and a `hint`.+- `exports` maps a variable name to a key in the response body, making it available to later steps on the page.++### 3. For something that is not a request, add a derivation++A `derive` step runs a named pure function in the same file and performs no network call. Use it when the thing worth showing is a transform rather than a response, such as assembling the exact message a wallet signs:++```js+{+ id: 'siws-message',+ kind: 'derive',+ derive: 'siwsMessage',+ title: 'Build the exact bytes to sign',+ summary: 'Composed locally from the nonce response.',+ docs: '/tutorials/wallet-sign-in',+ uses: ['nonce', 'domain', 'uri'],+ inputs: [{ name: 'address', label: 'address', value: '', placeholder: 'Your Solana address' }],+}+```++The function itself lives in the `DERIVATIONS` map and receives one object holding every chained variable plus the reader's input values. A derivation named in a step but missing from that map fails at load.++### 4. Verify++```bash+npx vitest run tests/live-steps.test.js+```++The suite evaluates the shipped `public/live-steps.js`, exercises every invariant above against hostile inputs, and scans every markdown file under `docs/` to confirm each `live` block is valid JSON naming a registered step. A tutorial that references a step you renamed fails there rather than in a reader's browser.++---++## Where it renders++The viewer at [pages/tutorial.html](https://github.com/nirholas/three.ws/blob/main/pages/tutorial.html) loads `/live-steps.js` and `/live-steps.css` and calls `LiveSteps.mount(article)` after parsing the markdown, before the syntax-highlight pass. Any other markdown viewer can adopt live steps with the same three lines.++The card follows the reader's theme through the canonical tokens in `tokens.css`, collapses to a single column under 640px, and drops its spinner and pulse under `prefers-reduced-motion`.++---++## Currently registered steps++| id | Call | Publishes |+|---|---|---|+| `version` | `GET /api/version` | `commit` |+| `platform-stats` | `GET /api/platform/stats` | |+| `agents-public` | `GET /api/agents/public` | |+| `skills-catalog` | `GET /api/skills` | |+| `three-leaderboard` | `GET /api/leaderboard` | |+| `auth-me` | `GET /api/auth/me` | |+| `siws-nonce` | `GET /api/auth/siws/nonce` | `nonce`, `domain`, `uri`, `expiresAt` |+| `siws-message` | local derivation | |++---++## Related++- [Authentication](/docs/#authentication) covers the endpoints behind the sign-in steps+- [Add wallet sign-in to your app](/tutorials/wallet-sign-in) is the tutorial that uses them+- [API reference](/docs/#api-reference) documents every route a step can calldiff --git a/public/docs-live-core.js b/public/docs-live-core.jsnew file mode 100644index 000000000..4705bbde7--- /dev/null+++ b/public/docs-live-core.js@@ -0,0 +1,569 @@+// Live Docs — the pure half.+//+// Every runnable code sample on three.ws docs is decided here: what kind of+// runner a fenced block deserves, how a `curl` line becomes a real request,+// which requests a reader is allowed to fire from a documentation page, and how+// a snippet is wrapped into a sandboxed preview document.+//+// Nothing in this file touches the DOM, the network, or `window`. That is+// deliberate: the interesting logic (shell tokenizing, placeholder detection,+// the money-path guard) is exactly the logic that must be unit-tested in Node,+// and the runner in docs-live.js is then a thin, boring shell around it.+// tests/docs-live-core.test.js imports this module directly.+//+// Design rule that shapes the whole file: a documentation page is READ by+// people who are evaluating the platform, often signed in. A "Run" button on+// such a page is a loaded gun unless it is narrow by construction. So:+// - only three.ws origins are reachable (no arbitrary host from a snippet),+// - GET/HEAD run on one click,+// - other verbs demand an explicit second confirmation,+// - anything whose path can move money or mint is never runnable at all.+// The guard lives here, in the tested layer, not in a click handler.++/** Fence languages that can carry an inline HTML/web-component preview. */+export const PREVIEW_LANGS = Object.freeze(['html', 'xml', 'svg']);++/** Fence languages that can carry a shell request. */+export const SHELL_LANGS = Object.freeze(['bash', 'sh', 'shell', 'zsh', 'console', 'curl']);++/** Fence languages that can carry a runnable browser script. */+export const SCRIPT_LANGS = Object.freeze(['js', 'javascript', 'mjs']);++/** Origins a docs sample is allowed to call. Anything else is not runnable. */+export const ALLOWED_HOSTS = Object.freeze(['three.ws', 'www.three.ws', 'localhost', '127.0.0.1']);++// Paths that move value or create something irreversible. A reader clicking+// "Run" in a doc must never be able to reach these, confirmation or not: the+// blast radius of a mis-click is someone else's money. Matched against the+// pathname, case-insensitively, as a substring.+const IRREVERSIBLE_PATH_PARTS = Object.freeze([+ '/pay',+ '/send',+ '/transfer',+ '/withdraw',+ '/fund',+ '/swap',+ '/trade',+ '/buy',+ '/sell',+ '/wallet',+ '/mint',+ '/launch',+ '/autopilot',+ '/x402',+ '/checkout',+ '/billing',+ '/subscribe',+ '/sniper',+ '/vault',+]);++const SAFE_METHODS = Object.freeze(['GET', 'HEAD']);+const KNOWN_METHODS = Object.freeze(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']);++// ── Fence classification ─────────────────────────────────────────────────────++/**+ * Decide what a fenced code block can do.+ *+ * @param {{ lang?: string, code?: string }} block+ * @returns {null | { kind: 'preview'|'request'|'script', reason?: string, request?: object }}+ * null when the block is ordinary prose-adjacent code with nothing to run.+ */+export function classifyBlock(block = {}) {+ const lang = String(block.lang || '').toLowerCase().trim();+ const code = String(block.code || '');+ if (!code.trim()) return null;++ if (PREVIEW_LANGS.includes(lang) && hasRenderableMarkup(code)) {+ return { kind: 'preview' };+ }++ if (SHELL_LANGS.includes(lang)) {+ const request = parseCurl(code);+ if (request) return { kind: 'request', request };+ return null;+ }++ if (SCRIPT_LANGS.includes(lang) && isRunnableScript(code)) {+ return { kind: 'script' };+ }++ return null;+}++// A preview is only worth offering when the snippet actually renders something.+// A block of `<meta>` tags or a bare `<div>` produces an empty box, which reads+// as a broken feature; the three.ws embed elements and plain visible markup do+// not. `<script>`-only snippets are excluded for the same reason.+function hasRenderableMarkup(code) {+ if (/<(agent-3d|model-viewer|three-ws-[a-z-]+)\b/i.test(code)) return true;+ if (/^\s*<(!doctype|html)\b/i.test(code)) return true;+ // Visible structural markup with text or an element inside it.+ return /<(div|section|main|button|p|h[1-6]|ul|ol|table|img|canvas|iframe|form|a)\b[^>]*>/i.test(code);+}++// Scripts are only offered a runner when they visibly do something observable:+// a network call or console output. Running a snippet whose whole body is a+// type definition produces an empty result panel and teaches the reader that+// the feature is broken.+function isRunnableScript(code) {+ if (/\bimport\s+[^;]*from\s+['"][^./'"]/.test(code)) return false; // bare specifier, needs a bundler+ if (/\brequire\s*\(/.test(code)) return false; // Node sample+ if (/\bprocess\.env\b/.test(code)) return false; // Node sample+ return /\bfetch\s*\(|\bconsole\.(log|info|warn|error|table)\s*\(/.test(code);+}++// ── Shell parsing ────────────────────────────────────────────────────────────++/**+ * Split a shell command into argv, honouring single/double quotes, backslash+ * line continuations, and `$'...'`-free simple escaping. Comment lines and a+ * leading `$ ` prompt are dropped so a copy-pasted console transcript parses.+ *+ * @param {string} input+ * @returns {string[]}+ */+export function tokenizeShell(input) {+ const text = String(input || '')+ .split('\n')+ .map((line) => line.replace(/^\s*\$\s+/, ''))+ .filter((line) => !/^\s*#/.test(line))+ .join('\n')+ .replace(/\\\r?\n/g, ' ');++ const out = [];+ let cur = '';+ let quote = null;+ let started = false;++ for (let i = 0; i < text.length; i += 1) {+ const ch = text[i];+ if (quote) {+ if (ch === '\\' && quote === '"' && i + 1 < text.length) {+ i += 1;+ cur += text[i];+ continue;+ }+ if (ch === quote) {+ quote = null;+ continue;+ }+ cur += ch;+ continue;+ }+ if (ch === '"' || ch === "'") {+ quote = ch;+ started = true;+ continue;+ }+ if (ch === '\\' && i + 1 < text.length) {+ i += 1;+ cur += text[i];+ started = true;+ continue;+ }+ if (/\s/.test(ch)) {+ if (started) out.push(cur);+ cur = '';+ started = false;+ continue;+ }+ cur += ch;+ started = true;+ }+ if (started) out.push(cur);+ return out;+}++/**+ * Turn a `curl` invocation into a request description.+ *+ * Returns null for anything that is not a single, self-contained curl call:+ * pipelines, multiple commands, `curl | sh`, and non-curl shell lines all fall+ * through to "not runnable" rather than being guessed at.+ *+ * @param {string} command+ * @returns {null | { method: string, url: string, headers: Record<string,string>, body: string|null }}+ */+export function parseCurl(command) {+ const raw = String(command || '');+ // One command only. A pipeline or a chained command means the sample is a+ // recipe, not a request, and running just the curl half would mislead.+ if (/[|;]|&&/.test(raw.replace(/\\\r?\n/g, ' '))) return null;++ const argv = tokenizeShell(raw);+ if (!argv.length || argv[0] !== 'curl') return null;++ const headers = {};+ let method = null;+ let url = null;+ let body = null;++ for (let i = 1; i < argv.length; i += 1) {+ const arg = argv[i];+ const next = () => argv[++i];++ if (arg === '-X' || arg === '--request') {+ method = String(next() || '').toUpperCase();+ } else if (arg === '-H' || arg === '--header') {+ const h = String(next() || '');+ const idx = h.indexOf(':');+ if (idx > 0) headers[h.slice(0, idx).trim()] = h.slice(idx + 1).trim();+ } else if (arg === '-d' || arg === '--data' || arg === '--data-raw' || arg === '--data-binary') {+ const chunk = String(next() || '');+ body = body == null ? chunk : `${body}&${chunk}`;+ } else if (arg === '--url') {+ url = String(next() || '');+ } else if (arg === '-o' || arg === '--output' || arg === '-A' || arg === '--user-agent' || arg === '-u' || arg === '--user') {+ next(); // consumes its value; irrelevant to an in-page fetch+ } else if (arg.startsWith('-')) {+ // Bare flags (-s, -L, -i, --compressed, …) carry no value.+ continue;+ } else if (!url) {+ url = arg;+ }+ }++ if (!url) return null;+ if (!method) method = body != null ? 'POST' : 'GET';+ if (!KNOWN_METHODS.includes(method)) return null;++ return { method, url, headers, body };+}++// ── Safety ───────────────────────────────────────────────────────────────────++/**+ * Resolve a sample URL against three.ws and say whether it may be run.+ *+ * @param {{ method?: string, url?: string }} request+ * @param {{ origin?: string }} [opts] the origin a relative URL resolves against+ * @returns {{ ok: boolean, confirm: boolean, url: string|null, reason: string|null }}+ */+export function assessRequest(request = {}, opts = {}) {+ const origin = normalizeOrigin(opts.origin) || 'https://three.ws';+ const method = String(request.method || 'GET').toUpperCase();+ const deny = (reason) => ({ ok: false, confirm: false, url: null, reason });++ let parsed;+ try {+ parsed = new URL(String(request.url || ''), origin);+ } catch {+ return deny('That URL could not be parsed.');+ }++ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ return deny('Only http(s) requests can run from the docs.');+ }+ if (!ALLOWED_HOSTS.includes(parsed.hostname)) {+ return deny(`Only three.ws endpoints run here. This sample calls ${parsed.hostname}.`);+ }++ const path = parsed.pathname.toLowerCase();+ if (IRREVERSIBLE_PATH_PARTS.some((part) => path.includes(part))) {+ return deny('This endpoint can move funds or mint. Copy it and run it yourself.');+ }+ if (!KNOWN_METHODS.includes(method)) {+ return deny(`${method} is not a method the docs runner sends.`);+ }++ return {+ ok: true,+ confirm: !SAFE_METHODS.includes(method),+ url: parsed.toString(),+ reason: null,+ };+}++function normalizeOrigin(origin) {+ if (!origin) return null;+ try {+ return new URL(String(origin)).origin;+ } catch {+ return null;+ }+}++// ── Placeholders ─────────────────────────────────────────────────────────────++// Two characters is the floor, not three: `<id>` and `$ID` are both real slot+// names in the API reference, and a three-character minimum silently skipped+// them, leaving the reader with a request that called /api/agents/<id>.+const PLACEHOLDER_PATTERNS = Object.freeze([+ /\$\{([A-Z][A-Z0-9_]+)\}/g,+ /\$([A-Z][A-Z0-9_]+)\b/g,+ /<([A-Za-z][A-Za-z0-9_-]+)>/g,+ /\b(YOUR_[A-Z0-9_]+)\b/g,+]);++/**+ * Every `$API_KEY` / `<agent-id>` / `YOUR_TOKEN` slot in a request, in the order+ * a reader would fill them in. The runner renders one field per name, so a doc+ * sample stops being a thing you copy, edit elsewhere and paste back.+ *+ * @param {{ url?: string, headers?: object, body?: string|null }} request+ * @returns {Array<{ name: string, secret: boolean }>}+ */+export function findPlaceholders(request = {}) {+ const haystack = [+ String(request.url || ''),+ ...Object.entries(request.headers || {}).map(([k, v]) => `${k}: ${v}`),+ String(request.body || ''),+ ].join('\n');++ const names = [];+ const seen = new Set();+ for (const pattern of PLACEHOLDER_PATTERNS) {+ pattern.lastIndex = 0;+ let match = pattern.exec(haystack);+ while (match) {+ const name = match[1];+ if (!seen.has(name) && !isHtmlishTag(name)) {+ seen.add(name);+ names.push({ name, secret: isSecretName(name) });+ }+ match = pattern.exec(haystack);+ }+ }+ return names;+}++// `<html>`-shaped captures come from prose in a header value, not from a slot+// the reader is meant to fill.+const HTMLISH = new Set(['html', 'body', 'head', 'div', 'span', 'br', 'p', 'a', 'pre', 'code', 'em', 'strong']);+function isHtmlishTag(name) {+ return HTMLISH.has(String(name).toLowerCase());+}++/** Names whose value must never be written to storage. */+export function isSecretName(name) {+ return /(KEY|TOKEN|SECRET|PASSWORD|PASS|AUTH|CREDENTIAL|PRIVATE)/i.test(String(name));+}++/**+ * Substitute placeholder values into a parsed request. Unfilled slots are left+ * exactly as they are so the reader sees which field they skipped rather than a+ * request that silently calls `/api/agents/undefined`.+ *+ * @param {object} request+ * @param {Record<string,string>} values+ * @returns {object} a new request; the input is not mutated+ */+export function applyPlaceholders(request = {}, values = {}) {+ const fill = (text) => {+ let out = String(text == null ? '' : text);+ for (const [name, value] of Object.entries(values)) {+ if (value === '' || value == null) continue;+ const v = String(value);+ // `${NAME}` first: replacing `$NAME` first would leave a stray `}`.+ out = out.split(`\${${name}}`).join(v).split(`$${name}`).join(v).split(`<${name}>`).join(v);+ // A bare, unsigilled name is only substituted for the YOUR_* convention.+ // Replacing any bare name would rewrite unrelated prose that happens to+ // contain the same word (a header called `API_KEY`, say).+ if (/^YOUR_/.test(name)) out = out.split(name).join(v);+ }+ return out;+ };++ const headers = {};+ for (const [k, v] of Object.entries(request.headers || {})) headers[fill(k)] = fill(v);++ return {+ method: request.method,+ url: fill(request.url),+ headers,+ body: request.body == null ? null : fill(request.body),+ };+}++// ── Preview documents ────────────────────────────────────────────────────────++/**+ * Point a snippet's three.ws asset URLs at the origin the reader is actually on.+ *+ * A doc sample correctly hardcodes `https://three.ws/agent-3d/…` because that is+ * what a reader pastes into their own site. Inside the preview iframe on a dev+ * server or a preview deploy, that URL loads the PRODUCTION component, so the+ * preview stops reflecting the build under test. On three.ws itself this is a+ * no-op.+ *+ * @param {string} html+ * @param {string} origin+ * @returns {string}+ */+export function rewriteAssetOrigin(html, origin) {+ const target = normalizeOrigin(origin);+ if (!target) return String(html || '');+ if (/^https:\/\/(www\.)?three\.ws$/.test(target)) return String(html || '');+ return String(html || '').replace(/https:\/\/(?:www\.)?three\.ws(?=\/)/g, target);+}++/**+ * Wrap a snippet into a complete document for a sandboxed iframe.+ *+ * The frame runs with `allow-scripts` and WITHOUT `allow-same-origin`, so it is+ * a unique opaque origin: it can load the three.ws web component over the+ * network but cannot read cookies, storage, or the parent document. That is why+ * the preview is safe to offer on a page a signed-in reader is looking at.+ *+ * @param {string} snippet+ * @param {{ origin?: string, theme?: 'dark'|'light' }} [opts]+ * @returns {string} a full HTML document+ */+export function buildPreviewDoc(snippet, opts = {}) {+ const theme = opts.theme === 'light' ? 'light' : 'dark';+ const body = rewriteAssetOrigin(snippet, opts.origin);+ const bg = theme === 'light' ? '#f6f7f9' : '#0e0f13';+ const fg = theme === 'light' ? '#16181d' : '#e8eaf0';++ // A snippet that already declares a full document is used verbatim (minus+ // the origin rewrite): wrapping it again would nest <html> inside <body>.+ if (/^\s*<(!doctype|html)\b/i.test(body)) return body;++ return `<!doctype html>+<html lang="en" data-theme="${theme}">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<style>+ :root { color-scheme: ${theme}; }+ html, body { margin: 0; height: 100%; }+ body {+ background: ${bg};+ color: ${fg};+ font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 16px;+ box-sizing: border-box;+ }+ agent-3d, model-viewer { max-width: 100%; }+ img, canvas, iframe { max-width: 100%; }+</style>+</head>+<body>+${body}+</body>+</html>`;+}++/**+ * Wrap a JS snippet into a document that reports its console output and any+ * throw back to the parent via postMessage. Same opaque-origin sandbox as the+ * preview, so a sample's `fetch` runs without the reader's three.ws cookies.+ *+ * @param {string} snippet+ * @param {{ origin?: string }} [opts]+ * @returns {string}+ */+export function buildScriptDoc(snippet, opts = {}) {+ const code = rewriteAssetOrigin(snippet, opts.origin);+ // The snippet is injected as a module body. `</script>` inside a string+ // literal would otherwise close the tag early and break the document.+ const safe = code.replace(/<\/script/gi, '<\\/script');+ return `<!doctype html>+<html lang="en"><head><meta charset="utf-8"></head><body>+<script type="module">+const send = (level, args) => {+ const parts = args.map((a) => {+ if (typeof a === 'string') return a;+ try { return JSON.stringify(a, null, 2); } catch { return String(a); }+ });+ parent.postMessage({ __docsLive: true, level, text: parts.join(' ') }, '*');+};+for (const level of ['log', 'info', 'warn', 'error']) {+ const original = console[level].bind(console);+ console[level] = (...args) => { send(level, args); original(...args); };+}+window.addEventListener('unhandledrejection', (e) => send('error', [String(e.reason)]));+window.addEventListener('error', (e) => send('error', [String(e.message)]));+try {+${safe}+ parent.postMessage({ __docsLive: true, level: 'done' }, '*');+} catch (err) {+ send('error', [String(err && err.stack ? err.stack : err)]);+ parent.postMessage({ __docsLive: true, level: 'done' }, '*');+}+<\/script>+</body></html>`;+}++// ── Result formatting ────────────────────────────────────────────────────────++/** "1.2 kB" / "840 B" / "3.4 MB" — never a bare byte count in the UI. */+export function formatBytes(n) {+ // `Number(null)` is 0, so a missing value would otherwise render as "0 B" —+ // an unknown size dressed up as a measured one.+ if (n == null || n === '') return '—';+ const v = Number(n);+ if (!Number.isFinite(v) || v < 0) return '—';+ if (v < 1000) return `${Math.round(v)} B`;+ if (v < 1_000_000) return `${(v / 1000).toFixed(1)} kB`;+ return `${(v / 1_000_000).toFixed(2)} MB`;+}++/** "142 ms" under a second, "1.42 s" above it. */+export function formatDuration(ms) {+ if (ms == null || ms === '') return '—'; // see formatBytes: 0 is a measurement, null is not+ const v = Number(ms);+ if (!Number.isFinite(v) || v < 0) return '—';+ return v < 1000 ? `${Math.round(v)} ms` : `${(v / 1000).toFixed(2)} s`;+}++/** Colour band for an HTTP status chip. */+export function statusTone(status) {+ const s = Number(status);+ if (!Number.isFinite(s)) return 'err';+ if (s >= 200 && s < 300) return 'ok';+ if (s >= 300 && s < 400) return 'redirect';+ if (s === 402) return 'paid';+ if (s >= 400 && s < 500) return 'warn';+ return 'err';+}++/**+ * Pretty-print a response body, truncating anything a docs panel should not try+ * to render. JSON is re-indented; everything else is passed through.+ *+ * @param {string} text+ * @param {{ contentType?: string, limit?: number }} [opts]+ * @returns {{ text: string, language: string, truncated: boolean }}+ */+export function formatResponseBody(text, opts = {}) {+ const limit = Number.isFinite(opts.limit) ? opts.limit : 20_000;+ const raw = String(text == null ? '' : text);+ const type = String(opts.contentType || '').toLowerCase();++ let out = raw;+ let language = 'text';+ if (type.includes('json') || looksLikeJson(raw)) {+ try {+ out = JSON.stringify(JSON.parse(raw), null, 2);+ language = 'json';+ } catch {+ language = 'text';+ }+ } else if (type.includes('html')) {+ language = 'html';+ }++ if (out.length > limit) {+ return { text: `${out.slice(0, limit)}\n…truncated at ${formatBytes(limit)}`, language, truncated: true };+ }+ return { text: out, language, truncated: false };+}++function looksLikeJson(text) {+ const t = String(text || '').trim();+ return (t.startsWith('{') && t.endsWith('}')) || (t.startsWith('[') && t.endsWith(']'));+}++/** A one-line label for the Run button, so the verb always matches the action. */+export function runLabel(kind, request) {+ if (kind === 'preview') return 'Run preview';+ if (kind === 'script') return 'Run script';+ const method = String(request?.method || 'GET').toUpperCase();+ return SAFE_METHODS.includes(method) ? 'Send request' : `Send ${method}`;+}diff --git a/public/docs-live.css b/public/docs-live.cssnew file mode 100644index 000000000..8ec9574d5--- /dev/null+++ b/public/docs-live.css@@ -0,0 +1,584 @@+/* Live Docs — runnable code samples in the three.ws documentation.+ *+ * Loaded by docs/index.html alongside public/docs-live.js. Everything is+ * namespaced under .dlive so it can sit inside the docs prose styles without+ * fighting them, and every colour is derived from the docs tokens+ * (--docs-accent, --border, --text-muted) so the runner is visibly part of the+ * page rather than a widget dropped onto it. */++.dlive {+ --dlive-radius: 12px;+ --dlive-accent: var(--docs-accent, #8b5cf6);+ --dlive-surface: rgba(255, 255, 255, 0.03);+ --dlive-surface-2: rgba(255, 255, 255, 0.055);+ --dlive-line: var(--border, rgba(255, 255, 255, 0.09));+ --dlive-text: var(--text-body, rgba(224, 224, 224, 0.88));+ --dlive-muted: var(--text-muted, rgba(224, 224, 224, 0.62));+ margin: 1.35rem 0;+ border: 1px solid var(--dlive-line);+ border-radius: var(--dlive-radius);+ background: var(--dlive-surface);+ overflow: hidden;+}++:root[data-theme='light'] .dlive {+ --dlive-surface: rgba(10, 12, 20, 0.02);+ --dlive-surface-2: rgba(10, 12, 20, 0.045);+ --dlive-line: rgba(10, 12, 20, 0.12);+ --dlive-text: #1b1d24;+ --dlive-muted: rgba(27, 29, 36, 0.62);+}++/* ── Toolbar ──────────────────────────────────────────────────────────────── */++.dlive-bar {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 10px;+ background: var(--dlive-surface-2);+ border-bottom: 1px solid var(--dlive-line);+ flex-wrap: wrap;+}++.dlive-bar-spacer {+ flex: 1 1 auto;+ min-width: 4px;+}++.dlive-badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 3px 9px 3px 7px;+ border-radius: 999px;+ font-size: 11.5px;+ font-weight: 650;+ letter-spacing: 0.02em;+ color: var(--dlive-accent);+ background: color-mix(in srgb, var(--dlive-accent) 14%, transparent);+ border: 1px solid color-mix(in srgb, var(--dlive-accent) 32%, transparent);+ white-space: nowrap;+}++.dlive-badge svg {+ flex: none;+}++.dlive-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 11px;+ border-radius: 8px;+ border: 1px solid var(--dlive-line);+ background: transparent;+ color: var(--dlive-text);+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ line-height: 1.2;+ cursor: pointer;+ transition:+ background-color 0.14s ease,+ border-color 0.14s ease,+ color 0.14s ease,+ transform 0.12s ease;+}++.dlive-btn:hover:not(:disabled) {+ background: var(--dlive-surface-2);+ border-color: color-mix(in srgb, var(--dlive-accent) 45%, var(--dlive-line));+}++.dlive-btn:active:not(:disabled) {+ transform: translateY(1px);+}++.dlive-btn:focus-visible {+ outline: 2px solid var(--dlive-accent);+ outline-offset: 2px;+}++.dlive-btn:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}++.dlive-btn-active {+ background: var(--dlive-surface-2);+ border-color: color-mix(in srgb, var(--dlive-accent) 50%, var(--dlive-line));+ color: var(--dlive-accent);+}++.dlive-btn-primary {+ color: #fff;+ border-color: transparent;+ background: linear-gradient(135deg, var(--dlive-accent), color-mix(in srgb, var(--dlive-accent) 55%, #6366f1));+ box-shadow: 0 1px 0 rgba(255, 255, 255, 0.14) inset;+}++.dlive-btn-primary:hover:not(:disabled) {+ filter: brightness(1.08);+ border-color: transparent;+}++.dlive-btn-warn {+ background: linear-gradient(135deg, #f59e0b, #d97706);+ color: #1a1205;+}++.dlive-btn.is-busy {+ position: relative;+ color: transparent;+}++.dlive-btn.is-busy svg,+.dlive-btn.is-busy span {+ visibility: hidden;+}++.dlive-btn.is-busy::after {+ content: '';+ position: absolute;+ inset: 0;+ margin: auto;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid rgba(255, 255, 255, 0.35);+ border-top-color: #fff;+ animation: dlive-spin 0.7s linear infinite;+}++@keyframes dlive-spin {+ to {+ transform: rotate(360deg);+ }+}++/* ── Code stage ───────────────────────────────────────────────────────────── */++.dlive-stage {+ position: relative;+}++.dlive .dlive-pre {+ margin: 0 !important;+ border: 0 !important;+ border-radius: 0 !important;+ background: transparent !important;+}++.dlive-editor {+ display: block;+ width: 100%;+ min-height: 96px;+ margin: 0;+ padding: 14px 16px;+ border: 0;+ border-left: 2px solid var(--dlive-accent);+ background: rgba(0, 0, 0, 0.22);+ color: var(--dlive-text);+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);+ font-size: 13px;+ line-height: 1.6;+ tab-size: 2;+ resize: vertical;+ outline: none;+}++:root[data-theme='light'] .dlive-editor {+ background: rgba(10, 12, 20, 0.04);+}++.dlive-editor:focus {+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dlive-accent) 45%, transparent);+}++/* ── Placeholder fields ───────────────────────────────────────────────────── */++.dlive-fields {+ padding: 12px 14px;+ border-top: 1px solid var(--dlive-line);+ background: var(--dlive-surface-2);+}++.dlive-fields-hint {+ margin: 0 0 9px;+ font-size: 12.5px;+ color: var(--dlive-muted);+}++.dlive-fields-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr));+ gap: 10px;+}++.dlive-field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+}++.dlive-field > span {+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--dlive-muted);+}++.dlive-field input {+ width: 100%;+ padding: 7px 10px;+ border-radius: 8px;+ border: 1px solid var(--dlive-line);+ background: rgba(0, 0, 0, 0.25);+ color: var(--dlive-text);+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12.5px;+}++:root[data-theme='light'] .dlive-field input {+ background: #fff;+}++.dlive-field input:focus {+ outline: 2px solid var(--dlive-accent);+ outline-offset: 1px;+ border-color: transparent;+}++/* ── Result panel ─────────────────────────────────────────────────────────── */++.dlive-panel {+ border-top: 1px solid var(--dlive-line);+ background: rgba(0, 0, 0, 0.18);+ animation: dlive-reveal 0.18s ease both;+}++:root[data-theme='light'] .dlive-panel {+ background: rgba(10, 12, 20, 0.03);+}++@keyframes dlive-reveal {+ from {+ opacity: 0;+ transform: translateY(-3px);+ }+}++.dlive-panel-head {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 9px 10px 9px 12px;+ border-bottom: 1px solid var(--dlive-line);+ flex-wrap: wrap;+}++.dlive-panel-close {+ margin-left: auto;+ padding: 4px 7px;+}++.dlive-chip {+ display: inline-flex;+ align-items: center;+ padding: 2px 9px;+ border-radius: 999px;+ font-size: 11.5px;+ font-weight: 700;+ letter-spacing: 0.02em;+ white-space: nowrap;+ border: 1px solid transparent;+}++.dlive-chip-ok {+ color: #34d399;+ background: rgba(52, 211, 153, 0.13);+ border-color: rgba(52, 211, 153, 0.32);+}++.dlive-chip-run {+ color: var(--dlive-accent);+ background: color-mix(in srgb, var(--dlive-accent) 14%, transparent);+ border-color: color-mix(in srgb, var(--dlive-accent) 32%, transparent);+}++.dlive-chip-warn,+.dlive-chip-redirect {+ color: #fbbf24;+ background: rgba(251, 191, 36, 0.13);+ border-color: rgba(251, 191, 36, 0.32);+}++.dlive-chip-paid {+ color: #38bdf8;+ background: rgba(56, 189, 248, 0.13);+ border-color: rgba(56, 189, 248, 0.32);+}++.dlive-chip-err {+ color: #f87171;+ background: rgba(248, 113, 113, 0.13);+ border-color: rgba(248, 113, 113, 0.32);+}++.dlive-meta {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px;+ color: var(--dlive-muted);+ overflow-wrap: anywhere;+ min-width: 0;+}++.dlive-stats {+ font-size: 11.5px;+ font-weight: 650;+ color: var(--dlive-muted);+ white-space: nowrap;+}++.dlive-note {+ margin: 0;+ padding: 12px 14px;+ font-size: 13px;+ color: var(--dlive-text);+}++.dlive-out {+ margin: 0 !important;+ max-height: 420px;+ overflow: auto;+ padding: 12px 14px !important;+ border-radius: 0 !important;+ background: transparent !important;+ font-size: 12.5px;+ line-height: 1.6;+}++.dlive-headers {+ border-top: 1px solid var(--dlive-line);+ font-size: 12px;+}++.dlive-headers > summary {+ padding: 8px 14px;+ cursor: pointer;+ color: var(--dlive-muted);+ font-weight: 600;+}++.dlive-headers > summary:focus-visible {+ outline: 2px solid var(--dlive-accent);+ outline-offset: -2px;+}++.dlive-hrow {+ display: grid;+ grid-template-columns: minmax(120px, 30%) 1fr;+ gap: 10px;+ padding: 4px 14px;+ font-family: var(--font-mono, ui-monospace, monospace);+ color: var(--dlive-muted);+ overflow-wrap: anywhere;+}++.dlive-hrow > span:first-child {+ color: var(--dlive-text);+}++/* ── Preview frame ────────────────────────────────────────────────────────── */++.dlive-frame-wrap {+ position: relative;+ min-height: 320px;+ background:+ linear-gradient(45deg, rgba(255, 255, 255, 0.025) 25%, transparent 25%) -8px 0/16px 16px,+ linear-gradient(-45deg, rgba(255, 255, 255, 0.025) 25%, transparent 25%) -8px 0/16px 16px;+}++.dlive-frame {+ display: block;+ width: 100%;+ height: 340px;+ border: 0;+ background: transparent;+}++@media (min-width: 900px) {+ .dlive-frame {+ height: 420px;+ }+ .dlive-frame-wrap {+ min-height: 420px;+ }+}++/* ── Console output ───────────────────────────────────────────────────────── */++.dlive-console {+ max-height: 320px;+ overflow: auto;+ padding: 10px 14px;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12.5px;+ line-height: 1.65;+}++.dlive-line {+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ padding: 1px 0;+ color: var(--dlive-text);+}++.dlive-line-warn {+ color: #fbbf24;+}++.dlive-line-error {+ color: #f87171;+}++.dlive-line-muted {+ color: var(--dlive-muted);+ font-style: italic;+}++/* ── Skeletons ────────────────────────────────────────────────────────────── */++.dlive-skeleton {+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 100deg,+ transparent 20%,+ color-mix(in srgb, var(--dlive-accent) 12%, transparent) 45%,+ transparent 70%+ );+ background-size: 220% 100%;+ animation: dlive-shimmer 1.15s linear infinite;+}++.dlive-skeleton-lines {+ position: static;+ height: 96px;+ margin: 12px 14px;+ border-radius: 8px;+ background-color: var(--dlive-surface-2);+}++@keyframes dlive-shimmer {+ from {+ background-position: 120% 0;+ }+ to {+ background-position: -60% 0;+ }+}++/* ── First-visit hint ─────────────────────────────────────────────────────── */++.dlive-hint {+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 1.35rem 0;+ padding: 10px 12px;+ border-radius: 10px;+ border: 1px dashed color-mix(in srgb, var(--docs-accent, #8b5cf6) 40%, transparent);+ background: color-mix(in srgb, var(--docs-accent, #8b5cf6) 8%, transparent);+ font-size: 13px;+ color: var(--text-body, rgba(224, 224, 224, 0.88));+}++.dlive-hint-icon {+ display: inline-flex;+ color: var(--docs-accent, #8b5cf6);+ flex: none;+}++.dlive-hint kbd {+ padding: 1px 5px;+ border-radius: 5px;+ border: 1px solid var(--border, rgba(255, 255, 255, 0.14));+ background: rgba(255, 255, 255, 0.06);+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 11.5px;+}++.dlive-hint-close {+ margin-left: auto;+ flex: none;+ padding: 4px 6px;+ border-radius: 7px;+ border: 0;+ background: transparent;+ color: inherit;+ opacity: 0.65;+ cursor: pointer;+}++.dlive-hint-close:hover {+ opacity: 1;+}++.dlive-hint-close:focus-visible {+ outline: 2px solid var(--docs-accent, #8b5cf6);+ outline-offset: 2px;+}++/* ── Narrow screens ───────────────────────────────────────────────────────── */++@media (max-width: 560px) {+ .dlive-bar {+ padding: 7px 8px;+ }+ .dlive-btn span {+ display: none;+ }+ .dlive-btn-primary span,+ .dlive-btn-warn span {+ display: inline;+ }+ .dlive-hrow {+ grid-template-columns: 1fr;+ gap: 0;+ }+}++/* ── Motion preference ────────────────────────────────────────────────────── */++@media (prefers-reduced-motion: reduce) {+ .dlive-btn,+ .dlive-panel {+ transition: none;+ animation: none;+ }+ .dlive-skeleton {+ animation: none;+ background: var(--dlive-surface-2);+ }+ .dlive-btn.is-busy::after {+ animation-duration: 2.4s;+ }+}++/* Printed docs should show the published sample, not a dead control strip. */+@media print {+ .dlive-bar,+ .dlive-panel,+ .dlive-fields,+ .dlive-hint {+ display: none !important;+ }+ .dlive {+ border: 0;+ background: none;+ }+}diff --git a/public/docs-live.js b/public/docs-live.jsnew file mode 100644index 000000000..02fec6f17--- /dev/null+++ b/public/docs-live.js@@ -0,0 +1,633 @@+// Live Docs — the runner.+//+// Turns the static code samples on every three.ws documentation page into+// things a reader can edit and run without leaving the page:+//+// • an `html` sample containing <agent-3d> renders a real, animated avatar in+// a sandboxed frame, from exactly the markup printed above it;+// • a `curl` sample becomes a real request against the live API, with status,+// latency, response size and a pretty-printed body;+// • a `js` sample runs in a sandboxed module frame with its console captured.+//+// Every sample stays editable: change the prompt, the avatar URL, the query+// string, press ⌘/Ctrl+Enter, and the doc answers with the real thing. That is+// the whole point — a reader evaluating three.ws should never have to set up a+// project to find out whether the platform does what the page claims.+//+// All decisions about what may run live in docs-live-core.js and are unit+// tested; this file is the DOM, the network call and the presentation.+//+// Mounted by docs/index.html after each page render:+// import('/docs-live.js').then(m => m.enhance(contentEl))+// enhance() is idempotent per block and safe to call on every navigation.++import {+ applyPlaceholders,+ assessRequest,+ buildPreviewDoc,+ buildScriptDoc,+ classifyBlock,+ findPlaceholders,+ formatBytes,+ formatDuration,+ formatResponseBody,+ isSecretName,+ parseCurl,+ runLabel,+ statusTone,+} from './docs-live-core.js';++const MARK = 'docsLiveReady';+const HINT_KEY = 'tws:docs-live-hint';+const REQUEST_TIMEOUT_MS = 20_000;+const SCRIPT_TIMEOUT_MS = 15_000;++// Placeholder values a reader types. Secrets stay in memory for the tab's life+// and are never written to storage; everything else survives a reload so an+// agent id typed on one page still applies on the next.+const secretValues = new Map();+const STORE_PREFIX = 'tws:docs-live:';++function readValue(name) {+ if (isSecretName(name)) return secretValues.get(name) || '';+ try {+ return sessionStorage.getItem(STORE_PREFIX + name) || '';+ } catch {+ return '';+ }+}++function writeValue(name, value) {+ if (isSecretName(name)) {+ secretValues.set(name, value);+ return;+ }+ try {+ sessionStorage.setItem(STORE_PREFIX + name, value);+ } catch {+ /* private mode — the value still applies for this run */+ }+}++// ── Icons ────────────────────────────────────────────────────────────────────++const I = {+ play: '<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" fill="currentColor"><path d="M8 5.6v12.8a1 1 0 0 0 1.53.85l10-6.4a1 1 0 0 0 0-1.7l-10-6.4A1 1 0 0 0 8 5.6Z"/></svg>',+ edit: '<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',+ reset: '<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>',+ close: '<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>',+ spark: '<svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true" fill="currentColor"><path d="M12 2.6 13.8 8l5.6.2-4.4 3.4 1.5 5.4L12 13.9 7.5 17l1.5-5.4L4.6 8.2 10.2 8 12 2.6Z"/></svg>',+};++// ── Entry point ──────────────────────────────────────────────────────────────++/**+ * Attach runners to every runnable sample inside `root`.+ * @param {ParentNode} root+ * @returns {number} how many blocks became runnable+ */+export function enhance(root) {+ const scope = root || document;+ let count = 0;+ scope.querySelectorAll('pre > code').forEach((code) => {+ const pre = code.parentElement;+ if (!pre || pre.dataset[MARK]) return;+ pre.dataset[MARK] = '1';+ if (optedOut(pre)) return;++ const source = code.textContent || '';+ const lang = languageOf(code);+ const verdict = classifyBlock({ lang, code: source });+ if (!verdict) return;++ mountRunner({ pre, code, lang, source, verdict });+ count += 1;+ });+ if (count) showHintOnce(scope);+ return count;+}++// An author opts a block out with an HTML comment on the line above it:+// <!-- live:off -->+function optedOut(pre) {+ let node = pre.previousSibling;+ let hops = 0;+ while (node && hops < 3) {+ if (node.nodeType === 8 && /live\s*:\s*off/i.test(node.nodeValue || '')) return true;+ if (node.nodeType === 1 || (node.nodeType === 3 && node.nodeValue.trim())) break;+ node = node.previousSibling;+ hops += 1;+ }+ return false;+}++function languageOf(code) {+ const cls = code.className || '';+ const match = cls.match(/language-([a-z0-9+#-]+)/i);+ return match ? match[1].toLowerCase() : '';+}++// ── Runner shell ─────────────────────────────────────────────────────────────++function mountRunner({ pre, code, lang, source, verdict }) {+ const wrap = document.createElement('div');+ wrap.className = `dlive dlive-${verdict.kind}`;+ pre.parentNode.insertBefore(wrap, pre);++ const bar = document.createElement('div');+ bar.className = 'dlive-bar';++ const label = verdict.kind === 'preview' ? 'Live preview' : verdict.kind === 'script' ? 'Runnable' : requestChip(verdict.request);+ bar.innerHTML = `+ <span class="dlive-badge" title="This sample runs for real, right here">${I.spark}<span>${escapeHtml(label)}</span></span>+ <span class="dlive-bar-spacer"></span>+ <button type="button" class="dlive-btn dlive-edit" title="Edit this sample, then run it">${I.edit}<span>Edit</span></button>+ <button type="button" class="dlive-btn dlive-reset" title="Restore the sample as published" hidden>${I.reset}<span>Reset</span></button>+ <button type="button" class="dlive-btn dlive-run dlive-btn-primary">${I.play}<span></span></button>`;+ wrap.appendChild(bar);++ // The published <pre> becomes the display half of an editor pair. The+ // textarea is created lazily so a reader who never edits pays nothing.+ const stage = document.createElement('div');+ stage.className = 'dlive-stage';+ pre.parentNode.insertBefore(stage, pre);+ stage.appendChild(pre);+ pre.classList.add('dlive-pre');++ const fields = document.createElement('div');+ fields.className = 'dlive-fields';+ fields.hidden = true;+ wrap.appendChild(stage);+ wrap.appendChild(fields);++ const panel = document.createElement('div');+ panel.className = 'dlive-panel';+ panel.hidden = true;+ panel.setAttribute('aria-live', 'polite');+ wrap.appendChild(panel);++ const state = {+ kind: verdict.kind,+ lang,+ original: source,+ current: source,+ editor: null,+ armed: false,+ busy: false,+ fields,+ panel,+ stage,+ pre,+ code,+ wrap,+ };++ const runBtn = bar.querySelector('.dlive-run');+ const editBtn = bar.querySelector('.dlive-edit');+ const resetBtn = bar.querySelector('.dlive-reset');++ setRunLabel(runBtn, state);+ renderFields(state, runBtn);++ editBtn.addEventListener('click', () => toggleEditor(state, editBtn, resetBtn, runBtn));+ resetBtn.addEventListener('click', () => resetSource(state, editBtn, resetBtn, runBtn));+ runBtn.addEventListener('click', () => run(state, runBtn));+}++function requestChip(request) {+ const verdict = assessRequest(request, { origin: location.origin });+ if (!verdict.ok) return 'Reference only';+ return `${request.method} · live API`;+}++function setRunLabel(btn, state) {+ const request = state.kind === 'request' ? parseCurl(state.current) : null;+ const span = btn.querySelector('span');+ if (state.kind === 'request') {+ const verdict = request ? assessRequest(request, { origin: location.origin }) : { ok: false, reason: 'That is no longer a curl command.' };+ btn.disabled = !verdict.ok;+ btn.title = verdict.ok ? 'Send this request to the live three.ws API' : verdict.reason;+ span.textContent = verdict.ok ? runLabel(state.kind, request) : 'Not runnable';+ return;+ }+ btn.disabled = false;+ btn.title = state.kind === 'preview' ? 'Render this markup in a sandboxed frame' : 'Run this script in a sandboxed frame';+ span.textContent = runLabel(state.kind, null);+}++// ── Editing ──────────────────────────────────────────────────────────────────++function toggleEditor(state, editBtn, resetBtn, runBtn) {+ if (state.editor) {+ commitEditor(state, editBtn, resetBtn, runBtn);+ return;+ }+ const ta = document.createElement('textarea');+ ta.className = 'dlive-editor';+ ta.value = state.current;+ ta.spellcheck = false;+ ta.setAttribute('aria-label', 'Editable code sample');+ ta.rows = Math.min(28, Math.max(4, state.current.split('\n').length + 1));+ ta.addEventListener('input', () => {+ state.current = ta.value;+ autoGrow(ta);+ setRunLabel(runBtn, state);+ renderFields(state, runBtn);+ });+ ta.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {+ e.preventDefault();+ run(state, runBtn);+ }+ if (e.key === 'Escape') {+ e.preventDefault();+ commitEditor(state, editBtn, resetBtn, runBtn);+ }+ if (e.key === 'Tab') {+ // A code editor that tabs to the next button is not a code editor.+ e.preventDefault();+ const { selectionStart: s, selectionEnd: end, value } = ta;+ ta.value = `${value.slice(0, s)}\t${value.slice(end)}`;+ ta.selectionStart = ta.selectionEnd = s + 1;+ state.current = ta.value;+ }+ });++ state.pre.hidden = true;+ state.stage.appendChild(ta);+ state.editor = ta;+ autoGrow(ta);+ ta.focus();++ editBtn.querySelector('span').textContent = 'Done';+ editBtn.classList.add('dlive-btn-active');+ resetBtn.hidden = false;+}++function commitEditor(state, editBtn, resetBtn, runBtn) {+ if (!state.editor) return;+ state.current = state.editor.value;+ state.editor.remove();+ state.editor = null;+ state.pre.hidden = false;+ repaint(state);+ editBtn.querySelector('span').textContent = 'Edit';+ editBtn.classList.remove('dlive-btn-active');+ resetBtn.hidden = state.current === state.original;+ setRunLabel(runBtn, state);+ renderFields(state, runBtn);+}++function resetSource(state, editBtn, resetBtn, runBtn) {+ state.current = state.original;+ if (state.editor) {+ state.editor.value = state.original;+ autoGrow(state.editor);+ }+ repaint(state);+ resetBtn.hidden = true;+ setRunLabel(runBtn, state);+ renderFields(state, runBtn);+}++// Re-render the display half from the edited source, re-highlighting with the+// docs page's own highlight.js when it is available so an edited sample keeps+// the typography of the published one.+function repaint(state) {+ state.code.textContent = state.current;+ state.code.className = state.lang ? `language-${state.lang}` : '';+ if (window.hljs && state.lang && window.hljs.getLanguage(state.lang)) {+ try {+ state.code.innerHTML = window.hljs.highlight(state.current, { language: state.lang }).value;+ } catch {+ /* the plain-text render above is already correct */+ }+ }+}++function autoGrow(ta) {+ ta.style.height = 'auto';+ ta.style.height = `${Math.min(560, ta.scrollHeight + 2)}px`;+}++// ── Placeholder fields ───────────────────────────────────────────────────────++function renderFields(state, runBtn) {+ if (state.kind !== 'request') return;+ const request = parseCurl(state.current);+ const slots = request ? findPlaceholders(request) : [];+ if (!slots.length) {+ state.fields.hidden = true;+ state.fields.innerHTML = '';+ return;+ }++ const existing = new Set([...state.fields.querySelectorAll('input')].map((i) => i.name));+ const wanted = new Set(slots.map((s) => s.name));+ if (existing.size === wanted.size && [...wanted].every((n) => existing.has(n))) return;++ state.fields.hidden = false;+ state.fields.innerHTML = `+ <p class="dlive-fields-hint">Fill these in and the request runs with your values. ${slots.some((s) => s.secret) ? 'Secrets stay in this tab and are never stored.' : ''}</p>+ <div class="dlive-fields-grid">+ ${slots+ .map(+ (s) => `<label class="dlive-field">+ <span>${escapeHtml(s.name)}</span>+ <input name="${escapeAttr(s.name)}" type="${s.secret ? 'password' : 'text'}"+ autocomplete="off" spellcheck="false"+ placeholder="${s.secret ? 'your value, kept in this tab' : 'your value'}"+ value="${escapeAttr(readValue(s.name))}" />+ </label>`,+ )+ .join('')}+ </div>`;++ state.fields.querySelectorAll('input').forEach((input) => {+ input.addEventListener('input', () => writeValue(input.name, input.value));+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ run(state, runBtn);+ }+ });+ });+}++function collectValues(state) {+ const values = {};+ state.fields.querySelectorAll('input').forEach((input) => {+ if (input.value) values[input.name] = input.value;+ });+ return values;+}++// ── Running ──────────────────────────────────────────────────────────────────++async function run(state, btn) {+ if (state.busy || btn.disabled) return;+ if (state.kind === 'preview') return runPreview(state);+ if (state.kind === 'script') return runScript(state, btn);+ return runRequest(state, btn);+}++function runPreview(state) {+ const doc = buildPreviewDoc(state.current, { origin: location.origin, theme: currentTheme() });+ openPanel(state, `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-ok">Rendering</span>+ <span class="dlive-meta">Sandboxed frame · scripts only, no access to this page</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Close preview">${I.close}</button>+ </div>+ <div class="dlive-frame-wrap"><div class="dlive-skeleton" aria-hidden="true"></div></div>`);++ const host = state.panel.querySelector('.dlive-frame-wrap');+ const frame = document.createElement('iframe');+ frame.className = 'dlive-frame';+ frame.setAttribute('sandbox', 'allow-scripts');+ frame.setAttribute('title', 'Live preview of this code sample');+ frame.setAttribute('loading', 'lazy');+ frame.srcdoc = doc;+ frame.addEventListener('load', () => {+ host.querySelector('.dlive-skeleton')?.remove();+ state.panel.querySelector('.dlive-chip').textContent = 'Live';+ });+ host.appendChild(frame);+}++function runScript(state, btn) {+ state.busy = true;+ btn.classList.add('is-busy');+ openPanel(state, `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-run">Running</span>+ <span class="dlive-meta">Sandboxed module frame · console captured</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Close output">${I.close}</button>+ </div>+ <div class="dlive-console" role="log"></div>`);++ const out = state.panel.querySelector('.dlive-console');+ const frame = document.createElement('iframe');+ frame.setAttribute('sandbox', 'allow-scripts');+ frame.style.display = 'none';+ frame.srcdoc = buildScriptDoc(state.current, { origin: location.origin });++ let settled = false;+ const finish = (note) => {+ if (settled) return;+ settled = true;+ state.busy = false;+ btn.classList.remove('is-busy');+ window.removeEventListener('message', onMessage);+ clearTimeout(timer);+ frame.remove();+ const chip = state.panel.querySelector('.dlive-chip');+ if (chip) {+ chip.textContent = note;+ chip.className = `dlive-chip ${note === 'Timed out' ? 'dlive-chip-warn' : 'dlive-chip-ok'}`;+ }+ if (!out.childElementCount) {+ out.innerHTML = '<div class="dlive-line dlive-line-muted">Ran with no console output.</div>';+ }+ };++ const onMessage = (event) => {+ const data = event.data;+ if (!data || data.__docsLive !== true) return;+ if (event.source !== frame.contentWindow) return;+ if (data.level === 'done') return finish('Finished');+ const line = document.createElement('div');+ line.className = `dlive-line dlive-line-${data.level}`;+ line.textContent = data.text;+ out.appendChild(line);+ };++ window.addEventListener('message', onMessage);+ const timer = setTimeout(() => finish('Timed out'), SCRIPT_TIMEOUT_MS);+ state.panel.appendChild(frame);+}++async function runRequest(state, btn) {+ const parsed = parseCurl(state.current);+ if (!parsed) return;+ const request = applyPlaceholders(parsed, collectValues(state));+ const verdict = assessRequest(request, { origin: location.origin });++ if (!verdict.ok) {+ openPanel(state, errorPanel('Not runnable', verdict.reason));+ return;+ }++ // A non-GET sample is armed on the first click and sent on the second. The+ // docs runner is the one place on the site where a reader can fire a write+ // without having meant to, so the second click is the consent.+ if (verdict.confirm && !state.armed) {+ state.armed = true;+ btn.classList.add('dlive-btn-warn');+ btn.querySelector('span').textContent = `Confirm ${request.method}`;+ openPanel(state, `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-warn">Confirm</span>+ <span class="dlive-meta">${escapeHtml(request.method)} ${escapeHtml(verdict.url)}</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Cancel">${I.close}</button>+ </div>+ <p class="dlive-note">This writes to the live API. Click <strong>Confirm ${escapeHtml(request.method)}</strong> to send it, or close this to cancel.</p>`);+ state.panel.querySelector('.dlive-panel-close').addEventListener('click', () => disarm(state, btn), { once: true });+ return;+ }+ disarm(state, btn);++ state.busy = true;+ btn.classList.add('is-busy');+ openPanel(state, `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-run">Sending</span>+ <span class="dlive-meta">${escapeHtml(request.method)} ${escapeHtml(verdict.url)}</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Close response">${I.close}</button>+ </div>+ <div class="dlive-skeleton dlive-skeleton-lines" aria-hidden="true"></div>`);++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);+ const started = performance.now();++ try {+ const headers = { ...request.headers };+ // The reader's three.ws session must not silently authorize a sample.+ // Docs requests are anonymous unless the sample itself carries a key.+ const res = await fetch(verdict.url, {+ method: request.method,+ headers,+ body: request.body == null ? undefined : request.body,+ credentials: 'omit',+ signal: controller.signal,+ });+ const text = await res.text();+ const ms = performance.now() - started;+ renderResponse(state, { res, text, ms, url: verdict.url, method: request.method });+ } catch (err) {+ const aborted = err && err.name === 'AbortError';+ openPanel(+ state,+ errorPanel(+ aborted ? 'Timed out' : 'Request failed',+ aborted+ ? `No response in ${formatDuration(REQUEST_TIMEOUT_MS)}. The endpoint may be cold or rate limited.`+ : `${String(err && err.message ? err.message : err)}. If this is a cross-origin call the endpoint may not send CORS headers; copy the command and run it in a terminal.`,+ ),+ );+ } finally {+ clearTimeout(timer);+ state.busy = false;+ btn.classList.remove('is-busy');+ }+}++function disarm(state, btn) {+ if (!state.armed) return;+ state.armed = false;+ btn.classList.remove('dlive-btn-warn');+ setRunLabel(btn, state);+}++function renderResponse(state, { res, text, ms, url, method }) {+ const contentType = res.headers.get('content-type') || '';+ const body = formatResponseBody(text, { contentType });+ const tone = statusTone(res.status);+ const bytes = new TextEncoder().encode(text).byteLength;++ const headerRows = [...res.headers.entries()]+ .map(([k, v]) => `<div class="dlive-hrow"><span>${escapeHtml(k)}</span><span>${escapeHtml(v)}</span></div>`)+ .join('');++ openPanel(state, `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-${tone}">${res.status} ${escapeHtml(res.statusText || '')}</span>+ <span class="dlive-meta">${escapeHtml(method)} ${escapeHtml(url)}</span>+ <span class="dlive-stats">${formatDuration(ms)} · ${formatBytes(bytes)}</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Close response">${I.close}</button>+ </div>+ ${res.status === 402 ? '<p class="dlive-note">This endpoint is paid (x402). The 402 body describes the price and how to settle it.</p>' : ''}+ <pre class="dlive-out"><code class="language-${escapeAttr(body.language)}">${escapeHtml(body.text)}</code></pre>+ ${headerRows ? `<details class="dlive-headers"><summary>Response headers</summary>${headerRows}</details>` : ''}`);++ const out = state.panel.querySelector('.dlive-out code');+ if (out && window.hljs && window.hljs.getLanguage(body.language)) {+ try {+ out.innerHTML = window.hljs.highlight(body.text, { language: body.language }).value;+ } catch {+ /* the escaped text above is already correct */+ }+ }+}++function errorPanel(title, message) {+ return `+ <div class="dlive-panel-head">+ <span class="dlive-chip dlive-chip-err">${escapeHtml(title)}</span>+ <button type="button" class="dlive-btn dlive-panel-close" aria-label="Close">${I.close}</button>+ </div>+ <p class="dlive-note">${escapeHtml(message)}</p>`;+}++function openPanel(state, html) {+ state.panel.innerHTML = html;+ state.panel.hidden = false;+ const close = state.panel.querySelector('.dlive-panel-close');+ if (close) {+ close.addEventListener('click', () => {+ state.panel.hidden = true;+ state.panel.innerHTML = '';+ });+ }+}++function currentTheme() {+ return document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';+}++// ── One-time hint ────────────────────────────────────────────────────────────++// The badge alone does not tell a first-time reader that anything on the page+// is interactive. One dismissible line, once per browser, does.+function showHintOnce(scope) {+ try {+ if (localStorage.getItem(HINT_KEY)) return;+ } catch {+ return; // no storage — do not nag on every navigation+ }+ const first = (scope.querySelector ? scope : document).querySelector('.dlive');+ if (!first || document.querySelector('.dlive-hint')) return;++ const hint = document.createElement('div');+ hint.className = 'dlive-hint';+ hint.setAttribute('role', 'note');+ hint.innerHTML = `+ <span class="dlive-hint-icon">${I.spark}</span>+ <span>Samples on this page are live. Press <kbd>Edit</kbd>, change anything, then <kbd>${navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}</kbd>+<kbd>Enter</kbd> to run it for real.</span>+ <button type="button" class="dlive-hint-close" aria-label="Dismiss">${I.close}</button>`;+ first.parentNode.insertBefore(hint, first);+ hint.querySelector('.dlive-hint-close').addEventListener('click', () => {+ hint.remove();+ try {+ localStorage.setItem(HINT_KEY, '1');+ } catch {+ /* dismissed for this view */+ }+ });+}++// ── Escaping ─────────────────────────────────────────────────────────────────++function escapeHtml(text) {+ return String(text == null ? '' : text)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++function escapeAttr(text) {+ return escapeHtml(text).replace(/"/g, '"');+}++export default { enhance };diff --git a/public/live-steps.css b/public/live-steps.cssnew file mode 100644index 000000000..17ae341fa--- /dev/null+++ b/public/live-steps.css@@ -0,0 +1,522 @@+/******************************************************************************+ * Live steps - the runnable API card embedded in three.ws documentation.+ * ════════════════════════════════════════════════════════════════════════════+ * Paired with /live-steps.js. Every colour resolves through the canonical+ * tokens in tokens.css, so the card follows the reader's theme (dark and+ * light) without a second palette. Motion is opt-out via prefers-reduced-motion+ * and the layout collapses to a single column under 640px.+ *****************************************************************************/++.ls-card {+ --ls-accent: var(--accent, #fff);+ position: relative;+ margin: 2rem 0;+ padding: 1.15rem 1.25rem 1.25rem;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ transition:+ border-color 0.2s ease,+ box-shadow 0.25s ease;+}++/* A thin status rail on the leading edge: idle is quiet, a result is not. */+.ls-card::before {+ content: '';+ position: absolute;+ inset: 0 auto 0 0;+ width: 2px;+ border-radius: var(--radius-lg, 14px) 0 0 var(--radius-lg, 14px);+ background: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ transition: background 0.25s ease;+}+.ls-card[data-state='running']::before {+ background: var(--ls-accent);+}+.ls-card[data-state='ok'] {+ border-color: color-mix(in srgb, var(--success, #4ade80) 32%, transparent);+}+.ls-card[data-state='ok']::before {+ background: var(--success, #4ade80);+}+.ls-card[data-state='error'] {+ border-color: color-mix(in srgb, var(--danger, #f87171) 34%, transparent);+}+.ls-card[data-state='error']::before {+ background: var(--danger, #f87171);+}++/* ── Header ──────────────────────────────────────────────────────────────── */++.ls-head {+ display: flex;+ align-items: flex-start;+ gap: 0.7rem;+}++.ls-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ flex: none;+ margin-top: 0.15rem;+ padding: 0.2rem 0.45rem;+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+ font-size: 0.58rem;+ letter-spacing: 0.12em;+}+.ls-badge-dot {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--success, #4ade80);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--success, #4ade80) 60%, transparent);+ animation: ls-pulse 2.4s ease-out infinite;+}+.ls-badge-bad {+ color: var(--danger, #f87171);+ border-color: color-mix(in srgb, var(--danger, #f87171) 40%, transparent);+}++@keyframes ls-pulse {+ 0% {+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--success, #4ade80) 55%, transparent);+ }+ 70%,+ 100% {+ box-shadow: 0 0 0 6px transparent;+ }+}++.ls-titles {+ flex: 1 1 auto;+ min-width: 0;+}+.ls-title {+ margin: 0;+ font-size: 0.98rem;+ font-weight: 600;+ line-height: 1.35;+ color: var(--ink-bright, #fff);+}+.ls-target {+ display: flex;+ align-items: center;+ gap: 0.45rem;+ flex-wrap: wrap;+ margin: 0.3rem 0 0;+ font-size: 0.75rem;+}+.ls-method {+ padding: 0.1rem 0.36rem;+ border-radius: var(--radius-sm, 6px);+ background: color-mix(in srgb, var(--success, #4ade80) 16%, transparent);+ color: var(--success, #4ade80);+ font-family: var(--font-mono, monospace);+ font-size: 0.63rem;+ letter-spacing: 0.06em;+}+.ls-method-local {+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+}+.ls-path {+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+ font-size: 0.72rem;+ overflow-wrap: anywhere;+}++.ls-ref {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ flex: none;+ padding: 0.25rem 0.5rem;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-sm, 6px);+ color: var(--ink-dim, #888);+ font-size: 0.7rem;+ text-decoration: none;+ transition:+ color 0.16s,+ border-color 0.16s,+ background 0.16s;+}+.ls-ref:hover {+ color: var(--ink-bright, #fff);+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+}+.ls-ref svg {+ width: 11px;+ height: 11px;+}++/* ── Copy ────────────────────────────────────────────────────────────────── */++.ls-summary {+ margin: 0.7rem 0 0;+ color: var(--ink, #e8e8e8);+ font-size: 0.86rem;+ line-height: 1.6;+ opacity: 0.82;+}++.ls-chain {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin: 0.6rem 0 0;+ color: var(--ink-dim, #888);+ font-size: 0.76rem;+}+.ls-chain svg {+ width: 13px;+ height: 13px;+ flex: none;+}++/* ── Inputs ──────────────────────────────────────────────────────────────── */++.ls-inputs {+ display: flex;+ flex-wrap: wrap;+ gap: 0.7rem;+ margin-top: 0.9rem;+}+.ls-field {+ display: flex;+ flex-direction: column;+ gap: 0.28rem;+ min-width: min(100%, 13rem);+}+.ls-field-label {+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+ font-size: 0.66rem;+ letter-spacing: 0.05em;+}+.ls-input {+ padding: 0.42rem 0.55rem;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-sm, 6px);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-bright, #fff);+ font-family: var(--font-mono, monospace);+ font-size: 0.78rem;+ transition:+ border-color 0.16s,+ background 0.16s;+}+.ls-input:hover {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+}+.ls-input:focus-visible {+ outline: 2px solid var(--ls-accent);+ outline-offset: 1px;+ border-color: transparent;+}+.ls-field-hint {+ color: var(--ink-dim, #888);+ font-size: 0.68rem;+ opacity: 0.75;+}++/* ── Actions ─────────────────────────────────────────────────────────────── */++.ls-actions {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ flex-wrap: wrap;+ margin-top: 1rem;+}++.ls-run {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ flex: none;+ padding: 0.45rem 0.85rem;+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-md, 10px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ color: var(--ink-bright, #fff);+ font-size: 0.8rem;+ font-weight: 600;+ cursor: pointer;+ transition:+ transform 0.14s ease,+ background 0.16s,+ border-color 0.16s,+ opacity 0.16s;+}+.ls-run:hover:not(:disabled) {+ background: color-mix(in srgb, var(--ls-accent) 14%, transparent);+ border-color: color-mix(in srgb, var(--ls-accent) 45%, transparent);+}+.ls-run:active:not(:disabled) {+ transform: translateY(1px);+}+.ls-run:focus-visible {+ outline: 2px solid var(--ls-accent);+ outline-offset: 2px;+}+.ls-run:disabled {+ opacity: 0.55;+ cursor: progress;+}+.ls-run svg {+ width: 13px;+ height: 13px;+}++.ls-url {+ flex: 1 1 12rem;+ min-width: 0;+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+ font-size: 0.72rem;+ overflow-wrap: anywhere;+}++.ls-meta {+ display: inline-flex;+ align-items: center;+ gap: 0.45rem;+ flex: none;+ margin-left: auto;+ font-size: 0.71rem;+}+.ls-meta:empty {+ display: none;+}+.ls-pill {+ padding: 0.12rem 0.4rem;+ border-radius: var(--radius-pill, 999px);+ font-family: var(--font-mono, monospace);+ font-size: 0.66rem;+}+.ls-pill-ok {+ background: color-mix(in srgb, var(--success, #4ade80) 18%, transparent);+ color: var(--success, #4ade80);+}+.ls-pill-bad {+ background: color-mix(in srgb, var(--danger, #f87171) 18%, transparent);+ color: var(--danger, #f87171);+}+.ls-dim {+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+}++.ls-spinner {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ border: 2px solid color-mix(in srgb, var(--ls-accent) 25%, transparent);+ border-top-color: var(--ls-accent);+ animation: ls-spin 0.7s linear infinite;+}+@keyframes ls-spin {+ to {+ transform: rotate(360deg);+ }+}++/* ── Result ──────────────────────────────────────────────────────────────── */++.ls-result:empty {+ display: none;+}++.ls-body {+ position: relative;+ margin-top: 0.85rem;+}+.ls-pre {+ max-height: 22rem;+ margin: 0;+ padding: 0.85rem 0.95rem;+ overflow: auto;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-md, 10px);+ background: var(--bg-0, #0a0a0a);+ font-family: var(--font-mono, monospace);+ font-size: 0.76rem;+ line-height: 1.65;+ white-space: pre;+ tab-size: 2;+}+.ls-pre code {+ background: none;+ padding: 0;+ font: inherit;+ color: var(--ink, #e8e8e8);+}+.ls-key {+ color: var(--ls-accent);+ opacity: 0.9;+}+.ls-str {+ color: var(--success, #4ade80);+}+.ls-num {+ color: var(--warn, #fbbf24);+}+.ls-lit {+ color: var(--danger, #f87171);+}++.ls-copy {+ position: absolute;+ top: 8px;+ right: 8px;+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ padding: 0.26rem 0.5rem;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-sm, 6px);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ color: var(--ink-dim, #888);+ font-family: var(--font-mono, monospace);+ font-size: 0.66rem;+ cursor: pointer;+ opacity: 0;+ transition:+ opacity 0.16s ease,+ color 0.16s,+ border-color 0.16s;+}+.ls-body:hover .ls-copy,+.ls-copy:focus-visible {+ opacity: 1;+}+.ls-copy:hover {+ color: var(--ink-bright, #fff);+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+}+.ls-copy:focus-visible {+ outline: 2px solid var(--ls-accent);+ outline-offset: 2px;+}+.ls-copy.is-copied {+ color: var(--success, #4ade80);+ border-color: color-mix(in srgb, var(--success, #4ade80) 45%, transparent);+}+.ls-copy svg {+ width: 11px;+ height: 11px;+}+@media (hover: none) {+ .ls-copy {+ opacity: 1;+ }+}++.ls-note {+ display: flex;+ align-items: flex-start;+ gap: 0.4rem;+ margin: 0.7rem 0 0;+ font-size: 0.78rem;+ line-height: 1.6;+}+.ls-note svg {+ width: 13px;+ height: 13px;+ flex: none;+ margin-top: 0.2rem;+}+.ls-note.is-hint {+ color: var(--ink-dim, #888);+}+.ls-note.is-ok {+ color: var(--success, #4ade80);+}+.ls-note.is-error {+ color: var(--danger, #f87171);+}++/* ── Toolbar ─────────────────────────────────────────────────────────────── */++.ls-toolbar {+ display: flex;+ align-items: center;+ gap: 1rem;+ flex-wrap: wrap;+ margin: 2rem 0 0;+ padding: 0.85rem 1rem;+ border: 1px dashed var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+}+.ls-toolbar-text {+ flex: 1 1 16rem;+ color: var(--ink-dim, #888);+ font-size: 0.82rem;+ line-height: 1.55;+}+.ls-toolbar-text strong {+ color: var(--ink-bright, #fff);+}+.ls-run-all {+ margin-left: auto;+}++/* ── Responsive ──────────────────────────────────────────────────────────── */++@media (max-width: 640px) {+ .ls-card {+ padding: 1rem;+ }+ .ls-head {+ flex-wrap: wrap;+ }+ .ls-ref {+ order: 3;+ }+ .ls-field {+ min-width: 100%;+ }+ .ls-meta {+ margin-left: 0;+ width: 100%;+ }+ .ls-run,+ .ls-run-all {+ width: 100%;+ justify-content: center;+ margin-left: 0;+ }+ .ls-pre {+ font-size: 0.71rem;+ }+}++/* ── Motion opt-out ──────────────────────────────────────────────────────── */++@media (prefers-reduced-motion: reduce) {+ .ls-card,+ .ls-card::before,+ .ls-run,+ .ls-copy,+ .ls-ref,+ .ls-input {+ transition: none;+ }+ .ls-badge-dot,+ .ls-spinner {+ animation: none;+ }+ .ls-spinner {+ border-top-color: color-mix(in srgb, var(--ls-accent) 25%, transparent);+ background: var(--ls-accent);+ }+}diff --git a/public/live-steps.js b/public/live-steps.jsnew file mode 100644index 000000000..e0b60d975--- /dev/null+++ b/public/live-steps.js@@ -0,0 +1,817 @@+/*+ * Live steps - runnable API calls embedded directly in three.ws documentation.+ * ============================================================================+ *+ * WHAT IT IS+ * A tutorial author writes a fenced ```live block naming a step id. The viewer+ * replaces that block with an interactive card that performs the REAL request+ * against the live three.ws API, in the reader's browser, and renders the real+ * response. No mocked payloads, no recorded fixtures: the reader sees what the+ * platform is actually returning right now, and can copy it.+ *+ * THE SECURITY MODEL (the reason this design, and not "let markdown name a URL")+ * Markdown is content. Content must never be able to choose what request the+ * page makes. So:+ *+ * 1. Markdown SELECTS, code DECIDES. A ```live block may only reference a+ * step id from the STEPS registry below. An unknown id renders a visible+ * "unknown step" card and issues no request at all.+ * 2. GET only. validateRegistry() throws at load if any entry declares+ * another method, so no live step can ever mutate platform state.+ * 3. Paths are literal constants. Reader input and chained values only ever+ * land in query-string values, URL-encoded. Nothing interpolates into the+ * path or the origin, so no live step can be pointed at another host.+ * 4. Responses render through the DOM (textContent + built spans), never+ * innerHTML, so a hostile payload cannot inject markup.+ * 5. Session-shaped fields (sid, csrf, tokens) are redacted from the DISPLAY+ * before painting. Chained exports read the raw body, so a redacted field+ * still works as an input to the next step without ever being on screen.+ *+ * WIRING+ * Loaded as a classic script (like /tutorials-manifest.js) and used as:+ *+ * LiveSteps.mount(articleElement);+ *+ * called after the markdown has been parsed into the article. Styles live in+ * /live-steps.css. Authoring guide: /docs/live-steps.md.+ */+(function () {+ 'use strict';++ /* ══════════════════════════════════════════════════════════════════════+ * Derivations - pure client-side transforms, referenced by name from the+ * registry. A derive step performs no network call; it turns values that+ * earlier steps exported into the exact artifact the reader needs to see.+ * ══════════════════════════════════════════════════════════════════════ */++ const SIWS_STATEMENT =+ 'Sign in to three.ws. This request will not trigger any blockchain transaction or cost ' ++ 'any fees. By signing, you agree to the Terms of Service (https://three.ws/legal/tos) and ' ++ 'Privacy Policy (https://three.ws/legal/privacy).';++ const DERIVATIONS = {+ /*+ * Assemble the CAIP-122 message a Solana wallet signs. This is the step+ * integrations get wrong most often: the blank lines are structural, the+ * chain id is a network name rather than an EIP-155 number, and domain+ * and uri must come from the nonce response rather than from location.+ */+ siwsMessage(vars) {+ const address = vars.address || '<your-solana-address>';+ const issuedAt = new Date();+ const expiration = new Date(issuedAt.getTime() + 5 * 60 * 1000);+ return [+ `${vars.domain} wants you to sign in with your Solana account:`,+ address,+ '',+ SIWS_STATEMENT,+ '',+ `URI: ${vars.uri}`,+ 'Version: 1',+ 'Chain ID: mainnet',+ `Nonce: ${vars.nonce}`,+ `Issued At: ${issuedAt.toISOString()}`,+ `Expiration Time: ${expiration.toISOString()}`,+ ].join('\n');+ },+ };++ /* ══════════════════════════════════════════════════════════════════════+ * The registry - the complete set of calls documentation is allowed to+ * make. Adding a row here is a code change, reviewed like any other.+ *+ * id referenced from markdown+ * kind 'request' (network) or 'derive' (pure, local)+ * title card heading+ * summary one line explaining what the reader is about to observe+ * docs deep link to the reference entry for this endpoint+ * inputs reader-editable query parameters+ * uses variable names this step consumes from earlier steps+ * exports variable name -> key in the response body+ * ══════════════════════════════════════════════════════════════════════ */++ const STEPS = [+ {+ id: 'version',+ kind: 'request',+ method: 'GET',+ path: '/api/version',+ title: 'Ask the platform what it is running',+ summary:+ 'Returns the exact commit and Cloud Run revision serving this page. Useful as a first call when a fix you expect is not showing up.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [],+ exports: { commit: 'commitShort' },+ },+ {+ id: 'platform-stats',+ kind: 'request',+ method: 'GET',+ path: '/api/platform/stats',+ title: 'Read the live platform counters',+ summary:+ 'Agents, avatars, widgets and chains, counted at request time. These are the numbers behind the homepage.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [],+ exports: {},+ },+ {+ id: 'agents-public',+ kind: 'request',+ method: 'GET',+ path: '/api/agents/public',+ title: 'List public agents',+ summary:+ 'The public agent directory, cursor-paginated. No key and no session: this is the same data the discover page renders.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [+ {+ name: 'limit',+ label: 'limit',+ value: '3',+ placeholder: '3',+ hint: 'How many agents to return (1-50).',+ },+ ],+ exports: {},+ },+ {+ id: 'skills-catalog',+ kind: 'request',+ method: 'GET',+ path: '/api/skills',+ title: 'Browse the skill catalog',+ summary:+ 'Every published skill with its category, install count, rating and per-call price. This is what an agent shops from.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [+ {+ name: 'limit',+ label: 'limit',+ value: '3',+ placeholder: '3',+ hint: 'How many skills to return.',+ },+ ],+ exports: {},+ },+ {+ id: 'three-leaderboard',+ kind: 'request',+ method: 'GET',+ path: '/api/leaderboard',+ title: 'Read the $THREE holder leaderboard',+ summary:+ 'Live holder ranks, tiers and supply share for $THREE, read straight from chain state. Holder tier is what gates the premium surfaces.',+ docs: '/docs/#api-reference',+ credentials: 'omit',+ inputs: [+ {+ name: 'limit',+ label: 'limit',+ value: '3',+ placeholder: '3',+ hint: 'How many ranked holders to return.',+ },+ ],+ exports: {},+ },+ {+ id: 'auth-me',+ kind: 'request',+ method: 'GET',+ path: '/api/auth/me',+ title: 'Ask who you are signed in as',+ summary:+ 'Sent with your cookies. If you are signed in on this browser you will see your own account; if not, you will see the signed-out shape that trips most integrations.',+ docs: '/docs/#authentication',+ credentials: 'include',+ inputs: [],+ exports: {},+ },+ {+ id: 'siws-nonce',+ kind: 'request',+ method: 'GET',+ path: '/api/auth/siws/nonce',+ title: 'Mint a Solana sign-in nonce',+ summary:+ 'A single-use nonce with a five minute life, plus the canonical domain and uri your signed message must carry. Reading it here costs nothing and signs you into nothing.',+ docs: '/docs/#authentication',+ credentials: 'include',+ inputs: [],+ exports: {+ nonce: 'nonce',+ domain: 'domain',+ uri: 'uri',+ expiresAt: 'expiresAt',+ },+ },+ {+ id: 'siws-message',+ kind: 'derive',+ derive: 'siwsMessage',+ title: 'Build the exact bytes to sign',+ summary:+ 'Composed locally from the nonce response. This is the string your wallet signs, byte for byte, and the one place integrations most often go wrong.',+ docs: '/tutorials/wallet-sign-in',+ uses: ['nonce', 'domain', 'uri'],+ inputs: [+ {+ name: 'address',+ label: 'address',+ value: '',+ placeholder: 'Your Solana address (optional)',+ hint: 'Left blank, the message shows a placeholder in the address line.',+ },+ ],+ },+ ];++ /* ══════════════════════════════════════════════════════════════════════+ * Registry validation. These are the invariants the security model rests+ * on, so they are checked at load and throw rather than degrade.+ * ══════════════════════════════════════════════════════════════════════ */++ const SAFE_PATH = /^\/api\/[A-Za-z0-9][A-Za-z0-9/_-]*$/;+ const SAFE_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;++ function validateRegistry(steps) {+ const seen = new Set();+ const produced = new Set();+ for (const step of steps) {+ if (!step.id || seen.has(step.id)) {+ throw new Error(`live-steps: duplicate or missing step id "${step.id}"`);+ }+ seen.add(step.id);+ if (step.kind !== 'request' && step.kind !== 'derive') {+ throw new Error(`live-steps: ${step.id} has unknown kind "${step.kind}"`);+ }+ for (const input of step.inputs || []) {+ if (!SAFE_NAME.test(input.name)) {+ throw new Error(`live-steps: ${step.id} has unsafe input name "${input.name}"`);+ }+ }+ for (const name of step.uses || []) {+ if (!produced.has(name)) {+ throw new Error(+ `live-steps: ${step.id} uses "${name}", which no earlier step exports`,+ );+ }+ }+ if (step.kind === 'request') {+ if (step.method !== 'GET') {+ throw new Error(+ `live-steps: ${step.id} declares ${step.method}; live steps are read-only`,+ );+ }+ if (!SAFE_PATH.test(step.path) || step.path.includes('..')) {+ throw new Error(`live-steps: ${step.id} has an unsafe path "${step.path}"`);+ }+ for (const name of Object.keys(step.exports || {})) {+ if (!SAFE_NAME.test(name)) {+ throw new Error(`live-steps: ${step.id} exports unsafe name "${name}"`);+ }+ produced.add(name);+ }+ } else {+ if (typeof DERIVATIONS[step.derive] !== 'function') {+ throw new Error(`live-steps: ${step.id} names unknown derivation "${step.derive}"`);+ }+ if (!(step.uses || []).length) {+ throw new Error(`live-steps: ${step.id} is a derive step with no inputs to derive from`);+ }+ }+ }+ return true;+ }++ validateRegistry(STEPS);++ const BY_ID = new Map(STEPS.map((s) => [s.id, s]));+ /* variable name -> id of the step that produces it, for prerequisite chasing. */+ const PRODUCER = new Map();+ for (const step of STEPS) {+ for (const name of Object.keys(step.exports || {})) {+ if (!PRODUCER.has(name)) PRODUCER.set(name, step.id);+ }+ }++ /* ══════════════════════════════════════════════════════════════════════+ * Redaction. Session-shaped fields are stripped from the rendered copy so+ * that a reader screenshotting the docs, or a page recorded by a session+ * replay tool, never carries a usable credential. Exports read the raw+ * body, so redaction costs the reader nothing.+ * ══════════════════════════════════════════════════════════════════════ */++ const SECRET_KEY =+ /^(sid|csrf|csrf_token|token|access_token|refresh_token|id_token|secret|authorization|cookie|session|password|private_key|privatekey|api_key|apikey)$/i;+ const REDACTED = '[redacted in this view]';++ function redact(value) {+ let count = 0;+ const walk = (node) => {+ if (Array.isArray(node)) return node.map(walk);+ if (node && typeof node === 'object') {+ const out = {};+ for (const [key, val] of Object.entries(node)) {+ if (SECRET_KEY.test(key) && val !== null && val !== '') {+ out[key] = REDACTED;+ count += 1;+ } else {+ out[key] = walk(val);+ }+ }+ return out;+ }+ return node;+ };+ return { value: walk(value), count };+ }++ /* ══════════════════════════════════════════════════════════════════════+ * URL building. Query values are the only place reader input reaches the+ * request, and they go through URLSearchParams, so they are encoded.+ * ══════════════════════════════════════════════════════════════════════ */++ function buildUrl(step, values) {+ const params = new URLSearchParams();+ for (const input of step.inputs || []) {+ const raw = values[input.name];+ if (raw === undefined || raw === null || String(raw).trim() === '') continue;+ params.set(input.name, String(raw).trim());+ }+ const qs = params.toString();+ return qs ? `${step.path}?${qs}` : step.path;+ }++ /* ══════════════════════════════════════════════════════════════════════+ * Rendering helpers.+ * ══════════════════════════════════════════════════════════════════════ */++ const SVG = 'http://www.w3.org/2000/svg';++ function icon(paths, extra) {+ const svg = document.createElementNS(SVG, 'svg');+ svg.setAttribute('viewBox', '0 0 24 24');+ svg.setAttribute('fill', 'none');+ svg.setAttribute('stroke', 'currentColor');+ svg.setAttribute('stroke-width', extra || '2');+ svg.setAttribute('stroke-linecap', 'round');+ svg.setAttribute('stroke-linejoin', 'round');+ svg.setAttribute('aria-hidden', 'true');+ for (const d of paths) {+ const p = document.createElementNS(SVG, 'path');+ p.setAttribute('d', d);+ svg.appendChild(p);+ }+ return svg;+ }++ const ICONS = {+ play: () => icon(['M7 4.5v15l12-7.5z'], '1.6'),+ check: () => icon(['M20 6 9 17l-5-5'], '2.4'),+ copy: () => icon(['M9 9h9a2 2 0 0 1 2 2v9H9z', 'M5 15V5a2 2 0 0 1 2-2h10']),+ alert: () => icon(['M12 8v5', 'M12 17h.01', 'M12 3 2 20h20z']),+ link: () => icon(['M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 1 0-7.07-7.07l-1.72 1.71', 'M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 1 0 7.07 7.07l1.71-1.71']),+ chain: () => icon(['M4 12h6', 'M14 12h6', 'M11 8l3 8'], '1.8'),+ };++ function el(tag, className, text) {+ const node = document.createElement(tag);+ if (className) node.className = className;+ if (text !== undefined) node.textContent = text;+ return node;+ }++ /*+ * Paint JSON without innerHTML: tokens become spans, everything else stays+ * a text node, so no response body can inject markup into the page.+ */+ const JSON_TOKEN =+ /("(?:\\.|[^"\\])*"\s*:)|("(?:\\.|[^"\\])*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(true|false|null)/g;++ function paintJson(text) {+ const frag = document.createDocumentFragment();+ let last = 0;+ let match;+ JSON_TOKEN.lastIndex = 0;+ while ((match = JSON_TOKEN.exec(text)) !== null) {+ if (match.index > last) {+ frag.appendChild(document.createTextNode(text.slice(last, match.index)));+ }+ const cls = match[1] ? 'ls-key' : match[2] ? 'ls-str' : match[3] ? 'ls-num' : 'ls-lit';+ frag.appendChild(el('span', cls, match[0]));+ last = match.index + match[0].length;+ }+ if (last < text.length) frag.appendChild(document.createTextNode(text.slice(last)));+ return frag;+ }++ function copyButton(getText) {+ const btn = el('button', 'ls-copy');+ btn.type = 'button';+ const label = el('span', null, 'Copy');+ btn.append(ICONS.copy(), label);+ btn.setAttribute('aria-label', 'Copy this response to the clipboard');+ let timer = null;+ btn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(getText());+ btn.replaceChildren(ICONS.check(), el('span', null, 'Copied'));+ btn.classList.add('is-copied');+ } catch {+ btn.replaceChildren(ICONS.copy(), el('span', null, 'Press Ctrl+C'));+ }+ clearTimeout(timer);+ timer = setTimeout(() => {+ btn.classList.remove('is-copied');+ btn.replaceChildren(ICONS.copy(), el('span', null, 'Copy'));+ }, 1800);+ });+ return btn;+ }++ function formatBytes(n) {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+ }++ /*+ * Turn a failed request into something the reader can act on. A live step+ * that says "something went wrong" teaches nothing, so every branch here+ * names the cause and the next move.+ */+ function explainFailure(status, body) {+ if (status === 0) {+ return 'The request never reached the API. You are probably offline, or an extension is blocking requests from this page.';+ }+ if (status === 401 || status === 403) {+ return 'The API answered, and told us this call needs a signed-in session. That is the correct answer for a signed-out browser.';+ }+ if (status === 404) {+ return 'The API answered, but no route matched. If you are reading a cached copy of this page, reload it.';+ }+ if (status === 429) {+ return 'Rate limited. The live steps share your IP allowance with the rest of the site, so wait a few seconds and run it again.';+ }+ if (status >= 500) {+ return 'The API failed on its side. This is a real production response, not a mock, so it is worth reporting if it persists.';+ }+ const described = body && (body.error_description || body.error);+ return described+ ? `The API rejected the request: ${described}`+ : 'The API answered with an unexpected status.';+ }++ /* ══════════════════════════════════════════════════════════════════════+ * The card.+ * ══════════════════════════════════════════════════════════════════════ */++ function createCard(step, block, ctx) {+ const card = el('section', 'ls-card');+ card.dataset.step = step.id;+ card.dataset.state = 'idle';+ card.setAttribute('role', 'group');+ card.setAttribute('aria-label', `Live step: ${step.title}`);++ /* Header: what this call is, and where the reference for it lives. */+ const head = el('header', 'ls-head');+ const badge = el('span', 'ls-badge');+ badge.append(+ el('span', 'ls-badge-dot'),+ el('span', null, step.kind === 'derive' ? 'LOCAL' : 'LIVE'),+ );+ head.appendChild(badge);++ const titles = el('div', 'ls-titles');+ titles.appendChild(el('h4', 'ls-title', block.title || step.title));+ const target = el('p', 'ls-target');+ if (step.kind === 'request') {+ target.append(el('span', 'ls-method', step.method), el('code', 'ls-path', step.path));+ } else {+ target.append(el('span', 'ls-method ls-method-local', 'DERIVE'), el('code', 'ls-path', 'runs in this page, no request'));+ }+ titles.appendChild(target);+ head.appendChild(titles);++ if (step.docs) {+ const ref = el('a', 'ls-ref');+ ref.href = step.docs;+ ref.append(ICONS.link(), el('span', null, 'Reference'));+ head.appendChild(ref);+ }+ card.appendChild(head);++ card.appendChild(el('p', 'ls-summary', block.note || step.summary));++ /* Chained variables: name what this step needs and where it comes from. */+ if ((step.uses || []).length) {+ const chain = el('p', 'ls-chain');+ chain.appendChild(ICONS.chain());+ chain.appendChild(+ el(+ 'span',+ null,+ `Uses ${step.uses.join(', ')} from the ${BY_ID.get(PRODUCER.get(step.uses[0])).title.toLowerCase()} step above.`,+ ),+ );+ card.appendChild(chain);+ }++ /* Reader-editable query parameters. */+ const values = {};+ if ((step.inputs || []).length) {+ const form = el('div', 'ls-inputs');+ for (const input of step.inputs) {+ values[input.name] = input.value;+ const field = el('label', 'ls-field');+ field.appendChild(el('span', 'ls-field-label', input.label));+ const box = el('input', 'ls-input');+ box.type = 'text';+ box.value = input.value;+ box.placeholder = input.placeholder || '';+ box.spellcheck = false;+ box.autocomplete = 'off';+ if (input.hint) box.title = input.hint;+ box.addEventListener('input', () => {+ values[input.name] = box.value;+ if (step.kind === 'request') urlPreview.textContent = buildUrl(step, values);+ });+ field.appendChild(box);+ if (input.hint) field.appendChild(el('span', 'ls-field-hint', input.hint));+ form.appendChild(field);+ }+ card.appendChild(form);+ }++ /* Action row: the button, the resolved URL, and the result meta. */+ const actions = el('div', 'ls-actions');+ const run = el('button', 'ls-run');+ run.type = 'button';+ run.append(ICONS.play(), el('span', 'ls-run-label', step.kind === 'derive' ? 'Build it' : 'Run it'));+ actions.appendChild(run);++ const urlPreview = el('code', 'ls-url');+ urlPreview.textContent = step.kind === 'request' ? buildUrl(step, values) : '';+ if (step.kind === 'request') actions.appendChild(urlPreview);++ const meta = el('span', 'ls-meta');+ actions.appendChild(meta);+ card.appendChild(actions);++ /* Result region. Announced politely so a screen reader hears the outcome. */+ const result = el('div', 'ls-result');+ result.setAttribute('aria-live', 'polite');+ card.appendChild(result);++ function setState(state) {+ card.dataset.state = state;+ }++ function showBody(text, isJson) {+ result.replaceChildren();+ const shell = el('div', 'ls-body');+ const pre = el('pre', 'ls-pre');+ const code = el('code');+ if (isJson) code.appendChild(paintJson(text));+ else code.textContent = text;+ pre.appendChild(code);+ shell.append(pre, copyButton(() => text));+ result.appendChild(shell);+ return shell;+ }++ function showNote(className, text) {+ const note = el('p', `ls-note ${className}`);+ if (className === 'is-error') note.appendChild(ICONS.alert());+ note.appendChild(el('span', null, text));+ result.appendChild(note);+ }++ async function execute() {+ if (card.dataset.state === 'running') return;++ /* A derive step needs its inputs; offer to produce them rather than fail. */+ if (step.kind === 'derive') {+ const missing = (step.uses || []).filter((name) => !(name in ctx.vars));+ if (missing.length) {+ const producerId = PRODUCER.get(missing[0]);+ setState('idle');+ result.replaceChildren();+ showNote(+ 'is-hint',+ `This step needs ${missing.join(', ')}. Running the ${BY_ID.get(producerId).title.toLowerCase()} step first.`,+ );+ const ok = await ctx.runStep(producerId);+ if (!ok) return;+ }+ const vars = Object.assign({}, ctx.vars, values);+ const text = DERIVATIONS[step.derive](vars);+ setState('ok');+ meta.replaceChildren(el('span', 'ls-pill ls-pill-ok', 'built'), el('span', 'ls-dim', `${text.length} chars`));+ showBody(text, false);+ showNote('is-hint', 'Every line matters: the two blank lines are structural, and Chain ID is a network name rather than a number.');+ return true;+ }++ setState('running');+ run.disabled = true;+ meta.replaceChildren(el('span', 'ls-spinner'), el('span', 'ls-dim', 'calling the live API'));+ result.replaceChildren();++ const url = buildUrl(step, values);+ urlPreview.textContent = url;+ const started = performance.now();+ let status = 0;+ let text = '';+ let parsed = null;+ try {+ const res = await fetch(url, {+ method: step.method,+ credentials: step.credentials === 'include' ? 'include' : 'omit',+ headers: { accept: 'application/json' },+ });+ status = res.status;+ text = await res.text();+ } catch {+ status = 0;+ }+ const ms = Math.round(performance.now() - started);+ run.disabled = false;++ try {+ parsed = JSON.parse(text);+ } catch {+ parsed = null;+ }++ const ok = status >= 200 && status < 300;+ setState(ok ? 'ok' : 'error');+ meta.replaceChildren(+ el('span', `ls-pill ${ok ? 'ls-pill-ok' : 'ls-pill-bad'}`, status ? String(status) : 'no response'),+ el('span', 'ls-dim', `${ms} ms`),+ el('span', 'ls-dim', formatBytes(new Blob([text]).size)),+ );++ if (parsed !== null) {+ const { value, count } = redact(parsed);+ showBody(JSON.stringify(value, null, 2), true);+ if (count) {+ showNote(+ 'is-hint',+ `${count} session-shaped ${count === 1 ? 'field is' : 'fields are'} hidden in this view so the page never carries a usable credential. Your own call receives the real values.`,+ );+ }+ } else if (text) {+ showBody(text, false);+ }++ if (!ok) {+ showNote('is-error', explainFailure(status, parsed));+ return false;+ }++ /* Publish exports for later steps, from the RAW body. */+ const exported = [];+ for (const [name, key] of Object.entries(step.exports || {})) {+ if (parsed && parsed[key] !== undefined && parsed[key] !== null) {+ ctx.vars[name] = parsed[key];+ exported.push(name);+ }+ }+ if (exported.length) {+ showNote('is-ok', `Later steps on this page can now use ${exported.join(', ')}.`);+ ctx.onExport();+ }+ return true;+ }++ run.addEventListener('click', () => {+ execute();+ });++ return { card, execute, step };+ }++ /* ══════════════════════════════════════════════════════════════════════+ * Unknown-step placeholder. A typo in markdown must be visible to the+ * author and inert for the reader, never a silent no-op.+ * ══════════════════════════════════════════════════════════════════════ */++ function unknownCard(id) {+ const card = el('section', 'ls-card');+ card.dataset.state = 'error';+ const head = el('header', 'ls-head');+ head.appendChild(el('span', 'ls-badge ls-badge-bad', 'UNKNOWN'));+ const titles = el('div', 'ls-titles');+ titles.appendChild(el('h4', 'ls-title', 'This live step is not registered'));+ titles.appendChild(el('p', 'ls-target', `No step with id "${id}" exists.`));+ head.appendChild(titles);+ card.appendChild(head);+ card.appendChild(+ el(+ 'p',+ 'ls-summary',+ 'Documentation may only run calls that are registered in public/live-steps.js, so nothing was requested. Add the step to the registry, or fix the id in the markdown.',+ ),+ );+ return card;+ }++ /* ══════════════════════════════════════════════════════════════════════+ * Toolbar. Appears once a page carries more than one live step, so a+ * reader can watch the whole flow run in order without hunting buttons.+ * ══════════════════════════════════════════════════════════════════════ */++ function createToolbar(cards, ctx) {+ const bar = el('div', 'ls-toolbar');+ const label = el('div', 'ls-toolbar-text');+ label.appendChild(el('strong', null, 'This page runs.'));+ label.appendChild(+ el(+ 'span',+ null,+ ` ${cards.length} steps below call the live three.ws API from your browser and show the real response.`,+ ),+ );+ bar.appendChild(label);++ const runAll = el('button', 'ls-run ls-run-all');+ runAll.type = 'button';+ runAll.append(ICONS.play(), el('span', null, 'Run every step'));+ runAll.addEventListener('click', async () => {+ runAll.disabled = true;+ runAll.replaceChildren(el('span', 'ls-spinner'), el('span', null, 'Running'));+ for (const entry of cards) {+ entry.card.scrollIntoView({ block: 'center', behavior: ctx.reduceMotion ? 'auto' : 'smooth' });+ await entry.execute();+ }+ runAll.disabled = false;+ runAll.replaceChildren(ICONS.check(), el('span', null, 'Ran every step'));+ });+ bar.appendChild(runAll);+ return bar;+ }++ /* ══════════════════════════════════════════════════════════════════════+ * mount(root) - swap every ```live block in `root` for a card.+ * ══════════════════════════════════════════════════════════════════════ */++ function mount(root) {+ if (!root) return [];+ const blocks = root.querySelectorAll('pre > code.language-live');+ if (!blocks.length) return [];++ const ctx = {+ vars: Object.create(null),+ reduceMotion:+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches,+ onExport() {},+ async runStep(id) {+ const entry = mounted.find((m) => m.step.id === id);+ return entry ? entry.execute() : false;+ },+ };++ const mounted = [];+ for (const code of blocks) {+ const pre = code.parentElement;+ let spec;+ try {+ spec = JSON.parse(code.textContent);+ } catch {+ spec = null;+ }+ const step = spec && BY_ID.get(spec.step);+ if (!step) {+ pre.replaceWith(unknownCard(spec ? spec.step : 'malformed block'));+ continue;+ }+ const entry = createCard(step, spec, ctx);+ pre.replaceWith(entry.card);+ mounted.push(entry);+ }++ if (mounted.length > 1) {+ mounted[0].card.parentNode.insertBefore(createToolbar(mounted, ctx), mounted[0].card);+ }+ return mounted;+ }++ window.LiveSteps = {+ STEPS,+ DERIVATIONS,+ validateRegistry,+ redact,+ buildUrl,+ explainFailure,+ mount,+ };+})();diff --git a/public/runnable-extract.js b/public/runnable-extract.jsnew file mode 100644index 000000000..a06cf7868--- /dev/null+++ b/public/runnable-extract.js@@ -0,0 +1,350 @@+// three.ws runnable-sample extractor.+//+// One source of truth for the question "is this documentation code block safe to+// execute for the reader, and if so, what exactly does it call?" It is imported+// unchanged by two very different callers:+//+// • public/runnable-samples.js — the browser, to put a Run button on a block+// • scripts/check-runnable-docs.mjs — Node, to execute every runnable sample in+// docs/ against the live API and fail the build when a documented call rots+//+// Because both sides share this file, a sample the gate proves alive is exactly+// the sample the reader can run, and a rule tightened here tightens both at once.+//+// The module is deliberately DOM-free and dependency-free so it loads in a plain+// <script type="module"> and in Node with no build step.++/** Hosts whose URLs we are willing to call on the reader's behalf. */+export const SAFE_HOSTS = new Set(['three.ws', 'www.three.ws']);++/**+ * Paths that are never runnable even when the request is a bare GET.+ * Some are account-scoped (the reader would only ever see their own 401), some+ * move money or run scheduled work, and some are pure plumbing that teaches the+ * reader nothing. A GET here is not dangerous so much as dishonest: a Run button+ * that always returns 401 is a broken promise.+ */+export const BLOCKED_PREFIXES = [+ '/api/admin',+ '/api/auth',+ '/api/cron',+ '/api/credits',+ '/api/csrf-token',+ '/api/logout',+ '/api/pay',+ '/api/session',+ '/api/user',+ '/api/wallet',+ '/api/webhook',+];++/**+ * Request headers that mean the sample only works with a secret, a session, or a+ * device identity the reader does not have. A Run button on one of these can+ * only ever show the reader a 400 or a 401.+ */+const CREDENTIAL_HEADERS =+ /^(authorization|cookie|x-api-key|x-payment|x-forge-provider-key|x-admin-|x-cron-|x-signature|x-irl-|x-device|x-session)/i;++/** curl flags that take a value we must skip over when scanning for the URL. */+const VALUE_FLAGS = new Set([+ '-H',+ '--header',+ '-d',+ '--data',+ '--data-raw',+ '--data-binary',+ '--data-urlencode',+ '-F',+ '--form',+ '-X',+ '--request',+ '-o',+ '--output',+ '-u',+ '--user',+ '-b',+ '--cookie',+ '-A',+ '--user-agent',+ '-e',+ '--referer',+ '-T',+ '--upload-file',+ '-w',+ '--write-out',+ '--connect-timeout',+ '--max-time',+ '-m',+ '--retry',+]);++/** Flags that prove the sample writes, uploads, or authenticates. */+const DISQUALIFYING_FLAGS = new Set([+ '-d',+ '--data',+ '--data-raw',+ '--data-binary',+ '--data-urlencode',+ '-F',+ '--form',+ '-T',+ '--upload-file',+ '-u',+ '--user',+ '-b',+ '--cookie',+ '-O',+ '--remote-name',+ '-o',+ '--output',+]);++/**+ * Anything that says "the author left a blank here". A Run button on a URL with+ * a placeholder in it produces a confusing 400 and teaches the reader nothing.+ */+const PLACEHOLDER_PATTERNS = [+ /[$<>{}]/, // shell vars, angle placeholders, template braces+ /\.\.\./,+ /…/, // ellipsis character+ /[A-Z][A-Z0-9]*_[A-Z0-9_]+/, // JOB_ID, AGENT_ID, YOUR_KEY+ /\byour[-_]/i,+ /\bexample\.(com|org|net)\b/i,+ /\breplace[-_]me\b/i,+];++/** Split a shell-ish command into tokens, honouring single and double quotes. */+export function tokenize(command) {+ const tokens = [];+ let current = '';+ let quote = null;+ let started = false;+ for (let i = 0; i < command.length; i++) {+ const ch = command[i];+ if (quote) {+ if (ch === quote) quote = null;+ else current += ch;+ continue;+ }+ if (ch === '"' || ch === "'") {+ quote = ch;+ started = true;+ continue;+ }+ if (/\s/.test(ch)) {+ if (started || current) tokens.push(current);+ current = '';+ started = false;+ continue;+ }+ current += ch;+ }+ if (started || current) tokens.push(current);+ return tokens;+}++/**+ * Reduce a fenced shell block to the single command it contains, or null.+ * Handles backslash line-continuations, `$`/`>` prompts, and `#` comments. A+ * block holding two commands is not runnable: we will not guess which one the+ * reader meant.+ */+export function singleCommand(source) {+ const joined = String(source || '')+ .replace(/\\\r?\n[ \t]*/g, ' ')+ .replace(/\r/g, '');+ const lines = joined+ .split('\n')+ .map((line) => line.replace(/^\s*[$>]\s+/, '').trim())+ .filter((line) => line && !line.startsWith('#'));+ if (lines.length !== 1) return null;+ return lines[0];+}++function hasPlaceholder(value) {+ return PLACEHOLDER_PATTERNS.some((re) => re.test(value));+}++function blocked(pathname) {+ return BLOCKED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));+}++/**+ * Parse an author directive written as an HTML comment directly above a fence:+ *+ * <!-- runnable: no the vault id is illustrative -->+ * <!-- runnable: 402 the x402 challenge is the lesson -->+ *+ * `no` opts a block out of the Run button and out of the gate. A status code+ * declares what this endpoint is supposed to answer, so the gate can hold a+ * paywalled or deliberately-empty endpoint to its real contract instead of+ * demanding a blanket 200.+ *+ * @param {string|null|undefined} comment the comment's inner text+ * @returns {{skip: true, note: string}|{expectStatus: number, note: string}|null}+ */+export function parseDirective(comment) {+ if (!comment) return null;+ const match = String(comment)+ .trim()+ .match(/^runnable:\s*(no|\d{3})\b\s*(.*)$/is);+ if (!match) return null;+ const note = match[2].trim();+ if (/^no$/i.test(match[1])) return { skip: true, note };+ return { expectStatus: Number(match[1]), note };+}++/**+ * Decide whether a documentation code block can be executed for the reader.+ *+ * @param {string} source raw text of the code block+ * @param {string} [lang] the fence language, when the caller knows it+ * @param {string} [comment] an author directive comment sitting above the fence+ * @returns {{runnable: true, method: 'GET', url: string, path: string, accept: string|null,+ * expectStatus: number|null, note: string}+ * |{runnable: false, reason: string}}+ */+export function extractRunnable(source, lang, comment) {+ const directive = parseDirective(comment);+ if (directive && directive.skip) {+ return { runnable: false, reason: directive.note || 'the author opted this block out' };+ }+ if (lang && !/^(bash|sh|shell|console|zsh|curl)$/i.test(lang)) {+ return { runnable: false, reason: 'not a shell block' };+ }+ const command = singleCommand(source);+ if (!command) return { runnable: false, reason: 'not a single command' };+ if (!/^curl(\s|$)/.test(command)) return { runnable: false, reason: 'not a curl command' };++ const tokens = tokenize(command);+ let method = 'GET';+ let accept = null;+ let url = null;++ for (let i = 1; i < tokens.length; i++) {+ const token = tokens[i];++ if (token === '-X' || token === '--request') {+ method = String(tokens[++i] || '').toUpperCase();+ continue;+ }+ if (token === '-H' || token === '--header') {+ const header = String(tokens[++i] || '');+ if (CREDENTIAL_HEADERS.test(header.trim())) {+ return { runnable: false, reason: 'needs a credential header' };+ }+ const [name, ...rest] = header.split(':');+ if (/^accept$/i.test(name.trim())) accept = rest.join(':').trim();+ continue;+ }+ if (DISQUALIFYING_FLAGS.has(token)) {+ return { runnable: false, reason: 'writes, uploads, or authenticates' };+ }+ if (VALUE_FLAGS.has(token)) {+ i++;+ continue;+ }+ if (token.startsWith('-')) continue; // a bundled boolean flag such as -sL or -i+ if (url) return { runnable: false, reason: 'more than one URL' };+ url = token;+ }++ if (method !== 'GET' && method !== 'HEAD') {+ return { runnable: false, reason: `method ${method} is not read-only` };+ }+ if (!url) return { runnable: false, reason: 'no URL in the command' };+ if (hasPlaceholder(url)) return { runnable: false, reason: 'the URL contains a placeholder' };++ let parsed;+ try {+ parsed = new URL(url);+ } catch {+ return { runnable: false, reason: 'not an absolute URL' };+ }+ if (parsed.protocol !== 'https:') return { runnable: false, reason: 'not https' };+ if (!SAFE_HOSTS.has(parsed.hostname)) return { runnable: false, reason: 'not a three.ws URL' };+ if (blocked(parsed.pathname)) return { runnable: false, reason: 'account-scoped or privileged path' };++ // Runnable paths are API calls and small JSON manifests. Everything else on+ // the site is a page or a multi-megabyte binary; neither belongs in an+ // inline response console.+ const isApi = parsed.pathname.startsWith('/api/');+ const isJson = parsed.pathname.endsWith('.json');+ if (!isApi && !isJson) return { runnable: false, reason: 'not an API or JSON path' };++ return {+ runnable: true,+ method: 'GET',+ url: parsed.toString(),+ path: `${parsed.pathname}${parsed.search}`,+ accept,+ expectStatus: directive ? directive.expectStatus : null,+ note: directive ? directive.note : '',+ };+}++/**+ * Pull every fenced code block out of a markdown document, along with any author+ * directive comment on the line above it.+ * @returns {Array<{lang: string, code: string, line: number, comment: string|null}>}+ */+export function codeBlocks(markdown) {+ const out = [];+ const lines = String(markdown || '').split('\n');+ let fence = null;+ let lang = '';+ let start = 0;+ let comment = null;+ let buffer = [];+ let lastComment = null;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!fence) {+ const html = line.match(/^\s*<!--([\s\S]*?)-->\s*$/);+ if (html) {+ lastComment = html[1];+ continue;+ }+ }+ const open = line.match(/^\s*(`{3,}|~{3,})\s*([A-Za-z0-9_-]*)\s*$/);+ if (!fence && open) {+ fence = open[1][0].repeat(3);+ lang = open[2] || '';+ start = i + 2;+ comment = lastComment;+ lastComment = null;+ buffer = [];+ continue;+ }+ if (fence) {+ const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);+ if (close && close[1][0] === fence[0]) {+ out.push({ lang, code: buffer.join('\n'), line: start, comment });+ fence = null;+ comment = null;+ buffer = [];+ continue;+ }+ buffer.push(line);+ continue;+ }+ // A directive only binds to the fence it immediately precedes.+ if (line.trim()) lastComment = null;+ }+ return out;+}++/**+ * Every runnable sample in a markdown document, in document order.+ * @returns {Array<{url: string, path: string, accept: string|null, expectStatus: number|null,+ * note: string, line: number, code: string}>}+ */+export function runnableSamples(markdown) {+ const out = [];+ for (const block of codeBlocks(markdown)) {+ const verdict = extractRunnable(block.code, block.lang, block.comment);+ if (verdict.runnable) out.push({ ...verdict, line: block.line, code: block.code });+ }+ return out;+}diff --git a/scripts/capture-walkthroughs.mjs b/scripts/capture-walkthroughs.mjsnew file mode 100644index 000000000..e2b78d84b--- /dev/null+++ b/scripts/capture-walkthroughs.mjs@@ -0,0 +1,192 @@+#!/usr/bin/env node+// capture-walkthroughs.mjs — build the media for the interactive walkthrough+// player at /walkthroughs by driving the real, running product.+//+// What this produces is deliberately NOT the same artifact as+// scripts/capture-guide-shots.mjs. That script bakes numbered callouts into+// cropped PNGs for the markdown tutorials. This one captures CLEAN, unmarked+// full-viewport frames plus the normalized rectangle of the element each step+// is about, because the player draws its spotlight, its zoom and its callouts+// live in the DOM on top of the frame. Burned-in annotations would fight it.+//+// Every step declares a real route and a real CSS selector. If a selector stops+// matching, the capture fails loudly instead of leaving a stale picture behind,+// which is what keeps the walkthroughs honest as the UI moves.+//+// Usage:+// node scripts/capture-walkthroughs.mjs # capture all, against production+// node scripts/capture-walkthroughs.mjs --base http://localhost:3000+// node scripts/capture-walkthroughs.mjs --only forge-your-first-3d-model+// node scripts/capture-walkthroughs.mjs --verify # drift check, writes nothing+//+// Writes JPEGs to public/walkthroughs/shots/ and the player manifest to+// public/walkthroughs/manifest.json.++import { chromium } from 'playwright';+import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, readdirSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const SOURCE = join(ROOT, 'data', 'walkthroughs.json');+const OUT_DIR = join(ROOT, 'public', 'walkthroughs');+const SHOT_DIR = join(OUT_DIR, 'shots');++function arg(name, fallback = null) {+ const i = process.argv.indexOf(`--${name}`);+ return i > -1 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : fallback;+}++const BASE = arg('base', process.env.BASE_URL || 'https://three.ws').replace(/\/+$/, '');+const ONLY = arg('only');+const VERIFY = process.argv.includes('--verify');+const SETTLE = Number(arg('settle', '4000'));++// Transient page furniture that belongs to the site rather than to the step+// being explained. Left visible it drifts across frames and dates them.+const SUPPRESS = ['#tws-corner-stack', '.tws-corner-stack', '#cookie-banner', '.cookie-banner', '#nav-pop-build', '#nav-pop-discover', '#nav-pop-learn'];++const HIDE_CSS = `${SUPPRESS.join(',')} { display: none !important; }+* { scroll-behavior: auto !important; }+.h-footer-glow-line, .cursor { animation: none !important; }`;++function log(...a) {+ console.log(...a);+}++async function applyBefore(page, before) {+ for (const act of before || []) {+ if (act.click) {+ await page.locator(act.click).first().click({ timeout: 15000 });+ } else if (act.fill) {+ const [sel, value] = act.fill;+ await page.locator(sel).first().fill(value, { timeout: 15000 });+ } else if (typeof act.wait === 'number') {+ await page.waitForTimeout(act.wait);+ }+ }+}++/**+ * Measure the focused element against the viewport, after centring it.+ * Returns the hotspot in normalized [0,1] viewport coordinates, which is the+ * only form the player needs: it renders the frame at an arbitrary size.+ */+async function measureHotspot(page, selector, viewport) {+ const el = page.locator(selector).first();+ await el.waitFor({ state: 'visible', timeout: 25000 });+ await el.evaluate((node) => node.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }));+ await page.waitForTimeout(450);+ const box = await el.boundingBox();+ if (!box) throw new Error(`element ${selector} has no box`);+ const clamp = (n) => Math.max(0, Math.min(1, n));+ const x = clamp(box.x / viewport.width);+ const y = clamp(box.y / viewport.height);+ const w = clamp((box.x + box.width) / viewport.width) - x;+ const h = clamp((box.y + box.height) / viewport.height) - y;+ if (w <= 0 || h <= 0) throw new Error(`element ${selector} is outside the viewport after centring`);+ return { x: +x.toFixed(5), y: +y.toFixed(5), w: +w.toFixed(5), h: +h.toFixed(5) };+}++async function main() {+ const source = JSON.parse(readFileSync(SOURCE, 'utf8'));+ const viewport = source.viewport;+ const list = source.walkthroughs.filter((w) => !ONLY || w.slug === ONLY);+ if (!list.length) {+ console.error(`No walkthrough matches --only ${ONLY}`);+ process.exit(2);+ }++ if (!VERIFY) {+ mkdirSync(SHOT_DIR, { recursive: true });+ if (!ONLY) {+ for (const f of existsSync(SHOT_DIR) ? readdirSync(SHOT_DIR) : []) {+ if (f.endsWith('.jpg')) rmSync(join(SHOT_DIR, f));+ }+ }+ }++ const browser = await chromium.launch();+ const ctx = await browser.newContext({+ viewport,+ deviceScaleFactor: 2,+ reducedMotion: 'reduce',+ colorScheme: 'dark',+ });+ await ctx.addInitScript(() => {+ try {+ // The player's own frames should show the platform as a first-time+ // visitor sees it, minus the one-off promo furniture.+ localStorage.setItem('tws:getting-started-dismissed', '1');+ } catch (_) {+ /* storage unavailable in this context; the CSS suppression still applies */+ }+ });+ const page = await ctx.newPage();++ const failures = [];+ const out = [];++ for (const w of list) {+ log(`\n▸ ${w.slug}`);+ const steps = [];+ for (let i = 0; i < w.steps.length; i++) {+ const step = w.steps[i];+ const n = String(i + 1).padStart(2, '0');+ const file = `${w.slug}-${n}.jpg`;+ const label = `${w.slug} step ${i + 1} (${step.path} ${step.focus})`;+ try {+ await page.goto(BASE + step.path, { waitUntil: 'domcontentloaded', timeout: 60000 });+ await page.addStyleTag({ content: HIDE_CSS });+ await page.waitForTimeout(SETTLE);+ await applyBefore(page, step.before);+ const hotspot = await measureHotspot(page, step.focus, viewport);+ const pageTitle = await page.title();+ if (!VERIFY) {+ await page.screenshot({ path: join(SHOT_DIR, file), type: 'jpeg', quality: 84 });+ }+ steps.push({+ ...step,+ shot: `/walkthroughs/shots/${file}`,+ hotspot,+ pageTitle,+ });+ log(` ✓ step ${i + 1} ${step.focus}`);+ } catch (err) {+ failures.push(`${label}: ${err.message.split('\n')[0]}`);+ log(` ✗ step ${i + 1} ${step.focus} — ${err.message.split('\n')[0]}`);+ }+ }+ out.push({ ...w, cover: steps[0]?.shot || null, steps });+ }++ await browser.close();++ if (failures.length) {+ console.error(`\n${failures.length} step(s) failed:`);+ for (const f of failures) console.error(` - ${f}`);+ console.error('\nA failure here means the page or the selector moved. Fix data/walkthroughs.json, do not ship a stale frame.');+ process.exit(1);+ }++ if (VERIFY) {+ log(`\nAll ${out.reduce((n, w) => n + w.steps.length, 0)} step(s) still resolve against ${BASE}.`);+ return;+ }++ const manifest = {+ generatedAt: new Date().toISOString(),+ baseUrl: BASE,+ viewport,+ version: source.version,+ walkthroughs: out,+ };+ mkdirSync(OUT_DIR, { recursive: true });+ writeFileSync(join(OUT_DIR, 'manifest.json'), `${JSON.stringify(manifest, null, '\t')}\n`);+ log(`\nWrote public/walkthroughs/manifest.json (${out.length} walkthrough(s), ${out.reduce((n, w) => n + w.steps.length, 0)} frame(s)).`);+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/scripts/check-runnable-docs.mjs b/scripts/check-runnable-docs.mjsnew file mode 100644index 000000000..bc3bceab5--- /dev/null+++ b/scripts/check-runnable-docs.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+/**+ * check-runnable-docs.mjs+ *+ * Executes every runnable sample in docs/ against a real three.ws API and fails+ * when a documented call no longer answers the way the doc says it does.+ *+ * Documentation rots silently. A curl command in a tutorial can point at an+ * endpoint that was renamed two quarters ago and nothing notices, because the+ * doc still reads fine. This turns that class of rot into a build failure: if+ * the reader can press Run on a sample, CI can press Run on the same sample,+ * using literally the same extractor (public/runnable-extract.js).+ *+ * A sample passes when the live response status matches its contract:+ * • by default, any 2xx+ * • or the exact status declared above the fence, for endpoints whose correct+ * answer is not 200:+ *+ * <!-- runnable: 402 the x402 challenge is the lesson here -->+ * ```bash+ * curl -s https://three.ws/api/x402/model-check+ * ```+ *+ * Opt a block out entirely (illustrative ids, endpoints needing a key) with:+ *+ * <!-- runnable: no the vault id is illustrative -->+ *+ * Usage:+ * npm run check:runnable-docs+ * npm run check:runnable-docs -- --base http://localhost:3000+ * npm run check:runnable-docs -- --list (print the inventory, call nothing)+ * npm run check:runnable-docs -- --only api/forge+ */+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, resolve, dirname, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { runnableSamples } from '../public/runnable-extract.js';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const DOCS = join(ROOT, 'docs');++const argv = process.argv.slice(2);+const flag = (name, fallback = null) => {+ const i = argv.indexOf(`--${name}`);+ return i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;+};+const BASE = (flag('base') || process.env.RUNNABLE_DOCS_BASE || 'https://three.ws').replace(/\/$/, '');+const LIST_ONLY = argv.includes('--list');+const ONLY = flag('only');+const CONCURRENCY = Math.max(1, Math.min(12, Number(flag('concurrency', '6')) || 6));+const TIMEOUT_MS = Math.max(5000, Number(flag('timeout', '30000')) || 30000);++function walk(dir, out = []) {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) walk(path, out);+ else if (entry.name.endsWith('.md')) out.push(path);+ }+ return out;+}++function inventory() {+ const byUrl = new Map();+ for (const file of walk(DOCS)) {+ const rel = relative(ROOT, file);+ for (const sample of runnableSamples(readFileSync(file, 'utf8'))) {+ if (ONLY && !sample.url.includes(ONLY)) continue;+ const existing = byUrl.get(sample.url);+ if (existing) {+ existing.sites.push(`${rel}:${sample.line}`);+ // The strictest declared contract wins, so one lax copy of a sample+ // cannot quietly weaken the check for every other copy.+ if (sample.expectStatus && !existing.expectStatus) {+ existing.expectStatus = sample.expectStatus;+ existing.note = sample.note;+ }+ continue;+ }+ byUrl.set(sample.url, {+ url: sample.url,+ path: sample.path,+ accept: sample.accept,+ expectStatus: sample.expectStatus,+ note: sample.note,+ sites: [`${rel}:${sample.line}`],+ });+ }+ }+ return [...byUrl.values()].sort((a, b) => a.url.localeCompare(b.url));+}++async function probe(sample) {+ const url = `${BASE}${sample.path}`;+ const started = Date.now();+ try {+ const res = await fetch(url, {+ headers: { accept: sample.accept || 'application/json, */*' },+ redirect: 'follow',+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ const expected = sample.expectStatus+ ? res.status === sample.expectStatus+ : res.status >= 200 && res.status < 300;+ return { ...sample, status: res.status, ms: Date.now() - started, ok: expected };+ } catch (err) {+ return {+ ...sample,+ status: 'ERR',+ ms: Date.now() - started,+ ok: false,+ error: String(err.message || err).slice(0, 120),+ };+ }+}++async function main() {+ if (!statSync(DOCS, { throwIfNoEntry: false })) {+ console.error(`No docs directory at ${DOCS}`);+ process.exit(1);+ }+ const samples = inventory();+ if (!samples.length) {+ console.error('check-runnable-docs: no runnable samples found. That is almost certainly a bug in the extractor.');+ process.exit(1);+ }++ if (LIST_ONLY) {+ for (const sample of samples) {+ const contract = sample.expectStatus ? `expects ${sample.expectStatus}` : 'expects 2xx';+ console.log(`${contract.padEnd(13)} ${sample.url}`);+ for (const site of sample.sites) console.log(` ${site}`);+ }+ console.log(`\n${samples.length} runnable sample(s) across docs/.`);+ return;+ }++ console.log(`check-runnable-docs: ${samples.length} sample(s) against ${BASE}\n`);+ const results = [];+ let cursor = 0;+ await Promise.all(+ Array.from({ length: CONCURRENCY }, async () => {+ while (cursor < samples.length) {+ const sample = samples[cursor++];+ const result = await probe(sample);+ results.push(result);+ const mark = result.ok ? 'ok ' : 'FAIL';+ console.log(+ ` ${mark} ${String(result.status).padEnd(4)} ${String(`${result.ms}ms`).padStart(7)} ${result.path}`,+ );+ }+ }),+ );++ const failures = results.filter((r) => !r.ok).sort((a, b) => a.url.localeCompare(b.url));+ if (!failures.length) {+ console.log(`\ncheck-runnable-docs: all ${results.length} documented calls answer as documented.`);+ return;+ }++ console.error(`\ncheck-runnable-docs: ${failures.length} documented call(s) no longer answer as documented:\n`);+ for (const failure of failures) {+ const want = failure.expectStatus ? `expected ${failure.expectStatus}` : 'expected 2xx';+ console.error(` ${failure.url}`);+ console.error(` got ${failure.status}${failure.error ? ` (${failure.error})` : ''}, ${want}`);+ for (const site of failure.sites) console.error(` at ${site}`);+ console.error(+ ' fix the URL, or declare the real contract above the fence with' ++ ' <!-- runnable: <status> reason --> / <!-- runnable: no reason -->\n',+ );+ }+ process.exit(1);+}++main().catch((err) => {+ console.error(`check-runnable-docs: ${err.stack || err.message}`);+ process.exit(1);+});diff --git a/src/walkthrough-geometry.js b/src/walkthrough-geometry.jsnew file mode 100644index 000000000..69de7a771--- /dev/null+++ b/src/walkthrough-geometry.js@@ -0,0 +1,95 @@+// Pure geometry for the walkthrough player.+//+// Every captured frame is stored with the hotspot (the element the step is+// about) as a normalized rectangle in [0,1] viewport space. The player renders+// that frame into a stage of the SAME aspect ratio, so image space and stage+// space are the same coordinate system and the maths below stays in normalized+// units all the way to the CSS transform.+//+// Kept free of DOM access on purpose: this is the part with the edge cases+// (tiny hotspots, hotspots against an edge, hotspots wider than the frame), so+// it is the part that gets unit tests.++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++/**+ * Zoom and pan that brings a hotspot to the middle of the stage.+ *+ * The frame is never allowed to pull away from an edge: the returned offsets+ * are clamped so the scaled image still covers the stage completely, which is+ * why a hotspot in a corner ends up off-centre rather than dragging a grey+ * gutter into view.+ *+ * @param {{x:number,y:number,w:number,h:number}} hotspot normalized frame coords+ * @param {{fill?:number,maxScale?:number}} [opts] fill = share of the stage the hotspot should occupy+ * @returns {{scale:number,x:number,y:number}} transform, offsets in normalized stage units+ */+export function frameTransform(hotspot, opts = {}) {+ const fill = opts.fill ?? 0.58;+ const maxScale = opts.maxScale ?? 3.2;+ const w = Math.max(hotspot.w, 1e-4);+ const h = Math.max(hotspot.h, 1e-4);+ const scale = clamp(Math.min(fill / w, fill / h), 1, maxScale);+ const cx = hotspot.x + hotspot.w / 2;+ const cy = hotspot.y + hotspot.h / 2;+ // Bounds: the image spans [offset, offset + scale]; it must cover [0, 1].+ const x = clamp(0.5 - scale * cx, 1 - scale, 0);+ const y = clamp(0.5 - scale * cy, 1 - scale, 0);+ return { scale, x, y };+}++/**+ * Where the hotspot ends up on the stage once the transform is applied.+ * @param {{x:number,y:number,w:number,h:number}} hotspot+ * @param {{scale:number,x:number,y:number}} transform+ * @returns {{x:number,y:number,w:number,h:number}} normalized stage coords+ */+export function projectHotspot(hotspot, transform) {+ return {+ x: hotspot.x * transform.scale + transform.x,+ y: hotspot.y * transform.scale + transform.y,+ w: hotspot.w * transform.scale,+ h: hotspot.h * transform.scale,+ };+}++/**+ * Pick the side of the hotspot with room for the callout card, and the point+ * on the hotspot it should attach to.+ *+ * Order of preference is right, left, below, above, then centred over the+ * dimmed frame when the hotspot is too large to sit beside anything. Anchors+ * on the vertical sides are pulled back from the top and bottom edges so a+ * card attached near a corner still renders inside the stage.+ *+ * @param {{x:number,y:number,w:number,h:number}} spot projected hotspot+ * @param {{need?:number,needBlock?:number}} [opts] normalized space the card needs+ * @returns {{side:'right'|'left'|'bottom'|'top'|'over',x:number,y:number}}+ */+export function calloutPlacement(spot, opts = {}) {+ const need = opts.need ?? 0.3;+ const needBlock = opts.needBlock ?? 0.24;+ const midX = spot.x + spot.w / 2;+ const midY = clamp(spot.y + spot.h / 2, 0.2, 0.8);+ const right = 1 - (spot.x + spot.w);+ const bottom = 1 - (spot.y + spot.h);++ if (right >= need) return { side: 'right', x: spot.x + spot.w, y: midY };+ if (spot.x >= need) return { side: 'left', x: spot.x, y: midY };+ if (bottom >= needBlock) return { side: 'bottom', x: clamp(midX, 0.2, 0.8), y: spot.y + spot.h };+ if (spot.y >= needBlock) return { side: 'top', x: clamp(midX, 0.2, 0.8), y: spot.y };+ return { side: 'over', x: 0.5, y: 0.5 };+}++/**+ * Everything the renderer needs for one step, in one call.+ * @param {{x:number,y:number,w:number,h:number}} hotspot+ * @param {{fill?:number,maxScale?:number,need?:number,needBlock?:number,motion?:boolean}} [opts]+ */+export function stepLayout(hotspot, opts = {}) {+ // With motion off the frame is shown whole, so the hotspot keeps its+ // captured position instead of being zoomed under the reader.+ const transform = opts.motion === false ? { scale: 1, x: 0, y: 0 } : frameTransform(hotspot, opts);+ const spot = projectHotspot(hotspot, transform);+ return { transform, spot, callout: calloutPlacement(spot, opts) };+}diff --git a/src/walkthrough.js b/src/walkthrough.jsnew file mode 100644index 000000000..cfde2a7ae--- /dev/null+++ b/src/walkthrough.js@@ -0,0 +1,380 @@+// /walkthroughs/<slug> — the interactive walkthrough player.+//+// Each step is a real frame captured from the live product+// (scripts/capture-walkthroughs.mjs) plus the normalized rectangle of the+// element the step is about. The player zooms and pans the frame to that+// rectangle, cuts a spotlight out of a dimming layer around it, and anchors a+// callout to whichever side has room. The result reads like a screen recording+// but is a handful of JPEGs: instant, deep-linkable per step, translatable,+// keyboard-operable, and it degrades to a plain annotated still when the+// visitor asks for reduced motion.+//+// Geometry lives in ./walkthrough-geometry.js so its edge cases are unit+// testable without a DOM.++import { stepLayout } from './walkthrough-geometry.js';++const AUTOPLAY_MS = 7600;+const MANIFEST_URL = '/walkthroughs/manifest.json';++const state = {+ walkthrough: null,+ index: 0,+ playing: false,+ timer: null,+ motion: true,+};++const el = {};++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++function slugFromLocation() {+ const m = location.pathname.match(/\/walkthroughs\/([a-z0-9-]+)\/?$/);+ return m ? m[1] : '';+}++function stepFromHash() {+ const m = location.hash.match(/^#step-(\d+)$/);+ if (!m) return 0;+ return Math.max(0, Number(m[1]) - 1);+}++function setState(root, name) {+ root.setAttribute('data-state', name);+}++// ── Rendering ────────────────────────────────────────────────────────────────++function shellHtml(w) {+ const steps = w.steps.length;+ return `+ <header class="wt-head">+ <a class="wt-back" href="/walkthroughs">+ <span aria-hidden="true">←</span> All walkthroughs+ </a>+ <h1 class="wt-title">${esc(w.title)}</h1>+ <p class="wt-outcome">${esc(w.outcome)}</p>+ <ul class="wt-meta">+ <li class="wt-chip wt-chip-level">${esc(w.level)}</li>+ <li class="wt-chip">${w.minutes} min read</li>+ <li class="wt-chip">${steps} steps</li>+ </ul>+ </header>++ <div class="wt-stagewrap">+ <button type="button" class="wt-arrow wt-arrow-prev" id="wt-prev" aria-label="Previous step">+ <span aria-hidden="true">‹</span>+ </button>+ <figure class="wt-stage" id="wt-stage" role="group" aria-roledescription="walkthrough" aria-label="${esc(w.title)}">+ <img class="wt-frame" id="wt-frame" alt="" decoding="async" />+ <div class="wt-spot" id="wt-spot" aria-hidden="true"></div>+ <div class="wt-callout" id="wt-callout" data-side="right">+ <p class="wt-callout-count" id="wt-count"></p>+ <h2 class="wt-callout-title" id="wt-steptitle"></h2>+ <p class="wt-callout-body" id="wt-body"></p>+ <p class="wt-callout-tip" id="wt-tip"></p>+ <a class="wt-callout-action" id="wt-action" href="/"></a>+ </div>+ <figcaption class="wt-caption" id="wt-caption"></figcaption>+ </figure>+ <button type="button" class="wt-arrow wt-arrow-next" id="wt-next" aria-label="Next step">+ <span aria-hidden="true">›</span>+ </button>+ </div>++ <div class="wt-bar">+ <button type="button" class="wt-play" id="wt-play" aria-pressed="false">+ <span class="wt-play-icon" aria-hidden="true"></span>+ <span class="wt-play-label">Play</span>+ </button>+ <ol class="wt-rail" id="wt-rail"></ol>+ <a class="wt-visit" id="wt-visit" href="${esc(w.cta.href)}">${esc(w.cta.label)} <span aria-hidden="true">↗</span></a>+ </div>++ <div class="wt-progress" id="wt-progress" aria-hidden="true"><span id="wt-progress-fill"></span></div>++ <footer class="wt-foot">+ <div class="wt-foot-next">+ <p class="wt-foot-label">When you are ready</p>+ <a class="wt-foot-cta" href="${esc(w.cta.href)}">${esc(w.cta.label)}</a>+ </div>+ ${+ w.related && w.related.length+ ? `<div class="wt-foot-related">+ <p class="wt-foot-label">Keep going</p>+ <ul>${w.related.map((r) => `<li><a href="${esc(r.href)}">${esc(r.label)}</a></li>`).join('')}</ul>+ </div>`+ : ''+ }+ </footer>++ <p class="wt-sr" id="wt-live" role="status" aria-live="polite"></p>`;+}++function cacheNodes(root) {+ const ids = [+ 'wt-stage',+ 'wt-frame',+ 'wt-spot',+ 'wt-callout',+ 'wt-count',+ 'wt-steptitle',+ 'wt-body',+ 'wt-tip',+ 'wt-action',+ 'wt-caption',+ 'wt-rail',+ 'wt-play',+ 'wt-prev',+ 'wt-next',+ 'wt-visit',+ 'wt-live',+ 'wt-progress-fill',+ ];+ for (const id of ids) el[id] = root.querySelector('#' + id);+}++function renderRail(w) {+ el['wt-rail'].innerHTML = w.steps+ .map(+ (s, i) =>+ `<li><button type="button" class="wt-rail-btn" data-step="${i}" aria-label="Step ${i + 1}: ${esc(s.title)}"><span class="wt-rail-n">${i + 1}</span><span class="wt-rail-t">${esc(s.title)}</span></button></li>`,+ )+ .join('');+}++function applyStep(i, opts = {}) {+ const w = state.walkthrough;+ state.index = Math.max(0, Math.min(w.steps.length - 1, i));+ const step = w.steps[state.index];+ const layout = stepLayout(step.hotspot, { motion: state.motion });++ el['wt-frame'].src = step.shot;+ el['wt-frame'].alt = `${step.pageTitle || w.title}: ${step.title}`;+ el['wt-frame'].style.transform = `translate(${(layout.transform.x * 100).toFixed(4)}%, ${(layout.transform.y * 100).toFixed(4)}%) scale(${layout.transform.scale.toFixed(4)})`;++ const s = layout.spot;+ const spot = el['wt-spot'];+ spot.style.left = `${(s.x * 100).toFixed(4)}%`;+ spot.style.top = `${(s.y * 100).toFixed(4)}%`;+ spot.style.width = `${(s.w * 100).toFixed(4)}%`;+ spot.style.height = `${(s.h * 100).toFixed(4)}%`;++ const c = el['wt-callout'];+ c.dataset.side = layout.callout.side;+ c.style.left = `${(layout.callout.x * 100).toFixed(4)}%`;+ c.style.top = `${(layout.callout.y * 100).toFixed(4)}%`;++ el['wt-count'].textContent = `Step ${state.index + 1} of ${w.steps.length}`;+ el['wt-steptitle'].textContent = step.title;+ el['wt-body'].textContent = step.body;+ el['wt-tip'].textContent = step.tip || '';+ el['wt-tip'].hidden = !step.tip;++ const action = step.action || { label: `Open ${step.path}`, href: step.path };+ el['wt-action'].textContent = action.label;+ el['wt-action'].href = action.href;++ el['wt-caption'].textContent = `Captured from ${step.path}`;+ el['wt-visit'].href = step.path;+ el['wt-visit'].firstChild.textContent = `Open ${step.path} `;++ el['wt-prev'].disabled = state.index === 0;+ el['wt-next'].disabled = state.index === w.steps.length - 1;++ for (const btn of el['wt-rail'].querySelectorAll('.wt-rail-btn')) {+ const on = Number(btn.dataset.step) === state.index;+ btn.setAttribute('aria-current', on ? 'step' : 'false');+ }++ el['wt-progress-fill'].style.width = `${(((state.index + 1) / w.steps.length) * 100).toFixed(2)}%`;+ el['wt-live'].textContent = `Step ${state.index + 1} of ${w.steps.length}. ${step.title}. ${step.body}`;++ if (!opts.silent) {+ const hash = `#step-${state.index + 1}`;+ if (location.hash !== hash) history.replaceState(null, '', location.pathname + hash);+ }++ preloadNeighbours();+}++function preloadNeighbours() {+ const w = state.walkthrough;+ for (const i of [state.index + 1, state.index - 1]) {+ const s = w.steps[i];+ if (!s) continue;+ const img = new Image();+ img.decoding = 'async';+ img.src = s.shot;+ }+}++// ── Playback ─────────────────────────────────────────────────────────────────++function stop() {+ state.playing = false;+ clearInterval(state.timer);+ state.timer = null;+ el['wt-play'].setAttribute('aria-pressed', 'false');+ el['wt-play'].querySelector('.wt-play-label').textContent = 'Play';+ el['wt-play'].classList.remove('is-playing');+}++function play() {+ if (state.index === state.walkthrough.steps.length - 1) applyStep(0);+ state.playing = true;+ el['wt-play'].setAttribute('aria-pressed', 'true');+ el['wt-play'].querySelector('.wt-play-label').textContent = 'Pause';+ el['wt-play'].classList.add('is-playing');+ clearInterval(state.timer);+ state.timer = setInterval(() => {+ if (state.index >= state.walkthrough.steps.length - 1) {+ stop();+ return;+ }+ applyStep(state.index + 1);+ }, AUTOPLAY_MS);+}++function togglePlay() {+ if (state.playing) stop();+ else play();+}++function go(delta) {+ stop();+ applyStep(state.index + delta);+}++// ── Wiring ───────────────────────────────────────────────────────────────────++function bind(root) {+ el['wt-prev'].addEventListener('click', () => go(-1));+ el['wt-next'].addEventListener('click', () => go(1));+ el['wt-play'].addEventListener('click', togglePlay);+ el['wt-rail'].addEventListener('click', (e) => {+ const btn = e.target.closest('.wt-rail-btn');+ if (!btn) return;+ stop();+ applyStep(Number(btn.dataset.step));+ });++ el['wt-stage'].addEventListener('click', (e) => {+ if (e.target.closest('.wt-callout')) return;+ go(1);+ });++ root.addEventListener('keydown', (e) => {+ if (e.target.matches('input, textarea')) return;+ if (e.key === 'ArrowRight') {+ e.preventDefault();+ go(1);+ } else if (e.key === 'ArrowLeft') {+ e.preventDefault();+ go(-1);+ } else if (e.key === 'Home') {+ e.preventDefault();+ stop();+ applyStep(0);+ } else if (e.key === 'End') {+ e.preventDefault();+ stop();+ applyStep(state.walkthrough.steps.length - 1);+ } else if (e.key === ' ' || e.key === 'Spacebar') {+ e.preventDefault();+ togglePlay();+ } else if (e.key === 'Escape') {+ stop();+ }+ });++ window.addEventListener('hashchange', () => applyStep(stepFromHash(), { silent: true }));++ // Autoplay is a convenience, never a trap: any hover or focus inside the+ // stage hands control back to the reader.+ for (const evt of ['pointerdown', 'focusin']) {+ el['wt-stage'].addEventListener(evt, (e) => {+ if (state.playing && e.target.closest('.wt-callout')) stop();+ });+ }++ const mq = window.matchMedia('(prefers-reduced-motion: reduce)');+ const syncMotion = () => {+ state.motion = !mq.matches;+ root.classList.toggle('wt-static', !state.motion);+ if (state.walkthrough) applyStep(state.index, { silent: true });+ };+ mq.addEventListener('change', syncMotion);+ state.motion = !mq.matches;+ root.classList.toggle('wt-static', !state.motion);+}++function renderError(root, heading, detail, retry) {+ setState(root, 'error');+ root.innerHTML = `+ <div class="wt-msg">+ <h1>${esc(heading)}</h1>+ <p>${esc(detail)}</p>+ <div class="wt-msg-actions">+ <a class="wt-msg-btn" href="/walkthroughs">Browse all walkthroughs</a>+ ${retry ? '<button type="button" class="wt-msg-btn wt-msg-btn-ghost" id="wt-retry">Try again</button>' : ''}+ </div>+ </div>`;+ const btn = root.querySelector('#wt-retry');+ if (btn) btn.addEventListener('click', () => boot());+}++async function boot() {+ const root = document.getElementById('wt-root');+ if (!root) return;+ const slug = slugFromLocation();+ if (!slug) {+ renderError(root, 'No walkthrough selected', 'The address is missing a walkthrough name.', false);+ return;+ }++ setState(root, 'loading');+ root.innerHTML = `+ <div class="wt-skeleton" aria-hidden="true">+ <div class="wt-sk-line wt-sk-line-lg"></div>+ <div class="wt-sk-line wt-sk-line-sm"></div>+ <div class="wt-sk-stage"></div>+ <div class="wt-sk-bar"></div>+ </div>+ <p class="wt-sr" role="status" aria-live="polite">Loading walkthrough</p>`;++ let manifest;+ try {+ const res = await fetch(MANIFEST_URL, { cache: 'no-cache' });+ if (!res.ok) throw new Error(`manifest ${res.status}`);+ manifest = await res.json();+ } catch (err) {+ renderError(root, 'Could not load the walkthroughs', `The walkthrough media did not load (${err.message}). Your connection may have dropped.`, true);+ return;+ }++ const w = (manifest.walkthroughs || []).find((x) => x.slug === slug);+ if (!w || !w.steps.length) {+ renderError(root, 'That walkthrough does not exist', `Nothing is published under "${slug}".`, false);+ return;+ }++ document.title = `${w.title} · Walkthrough · three.ws`;+ const desc = document.querySelector('meta[name="description"]');+ if (desc) desc.setAttribute('content', `${w.outcome} ${w.blurb}`);+ document.documentElement.style.setProperty('--wt-accent', w.accent);++ state.walkthrough = w;+ setState(root, 'ready');+ root.innerHTML = shellHtml(w);+ cacheNodes(root);+ renderRail(w);+ bind(root);+ applyStep(stepFromHash(), { silent: true });+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);+else boot();diff --git a/tests/docs-live-core.test.js b/tests/docs-live-core.test.jsnew file mode 100644index 000000000..01b195299--- /dev/null+++ b/tests/docs-live-core.test.js@@ -0,0 +1,371 @@+// Live Docs core — the decisions that must never be wrong.+//+// public/docs-live.js puts a "Run" button on documentation pages. Everything+// that decides WHAT that button is allowed to do lives in docs-live-core.js,+// and this file is the reason that split exists: the guard against a docs+// reader firing a write (or a spend) they did not intend is a pure function,+// so it can be pinned here rather than trusted to a click handler.++import { describe, expect, it } from 'vitest';++import {+ applyPlaceholders,+ assessRequest,+ buildPreviewDoc,+ buildScriptDoc,+ classifyBlock,+ findPlaceholders,+ formatBytes,+ formatDuration,+ formatResponseBody,+ isSecretName,+ parseCurl,+ rewriteAssetOrigin,+ runLabel,+ statusTone,+ tokenizeShell,+} from '../public/docs-live-core.js';++describe('classifyBlock', () => {+ it('offers a preview for an <agent-3d> embed sample', () => {+ const out = classifyBlock({ lang: 'html', code: '<agent-3d src="https://three.ws/a/demo.glb"></agent-3d>' });+ expect(out).toEqual({ kind: 'preview' });+ });++ it('offers a preview for plain visible markup', () => {+ expect(classifyBlock({ lang: 'html', code: '<div class="card">Hello</div>' })).toEqual({ kind: 'preview' });+ });++ it('does NOT offer a preview for a snippet that renders nothing', () => {+ // A meta-tag sample would render an empty box, which reads as a bug.+ expect(classifyBlock({ lang: 'html', code: '<meta name="x" content="y">' })).toBeNull();+ });++ it('offers a request runner for a curl sample', () => {+ const out = classifyBlock({ lang: 'bash', code: 'curl https://three.ws/api/version' });+ expect(out.kind).toBe('request');+ expect(out.request.method).toBe('GET');+ });++ it('leaves a non-curl shell sample alone', () => {+ expect(classifyBlock({ lang: 'bash', code: 'npm install @three-ws/sdk' })).toBeNull();+ });++ it('offers a script runner only when the sample does something observable', () => {+ expect(classifyBlock({ lang: 'js', code: 'const res = await fetch("/api/version");' })).toEqual({ kind: 'script' });+ expect(classifyBlock({ lang: 'js', code: 'const x = 1;' })).toBeNull();+ });++ it('refuses Node-shaped and bundler-shaped scripts', () => {+ expect(classifyBlock({ lang: 'js', code: 'const a = require("fs"); console.log(a);' })).toBeNull();+ expect(classifyBlock({ lang: 'js', code: 'import x from "express"; console.log(x);' })).toBeNull();+ expect(classifyBlock({ lang: 'js', code: 'console.log(process.env.KEY);' })).toBeNull();+ });++ it('ignores empty blocks and unknown languages', () => {+ expect(classifyBlock({ lang: 'html', code: ' ' })).toBeNull();+ expect(classifyBlock({ lang: 'rust', code: 'fn main() {}' })).toBeNull();+ expect(classifyBlock({})).toBeNull();+ });+});++describe('tokenizeShell', () => {+ it('honours single and double quotes', () => {+ expect(tokenizeShell(`curl -H 'a: b c' -H "d: e f" url`)).toEqual(['curl', '-H', 'a: b c', '-H', 'd: e f', 'url']);+ });++ it('joins backslash line continuations', () => {+ expect(tokenizeShell('curl \\\n -X POST \\\n https://three.ws/api/x')).toEqual([+ 'curl',+ '-X',+ 'POST',+ 'https://three.ws/api/x',+ ]);+ });++ it('drops a copy-pasted shell prompt and comment lines', () => {+ expect(tokenizeShell('# fetch it\n$ curl https://three.ws/api/version')).toEqual(['curl', 'https://three.ws/api/version']);+ });++ it('keeps an empty quoted argument', () => {+ expect(tokenizeShell(`curl -d '' url`)).toEqual(['curl', '-d', '', 'url']);+ });+});++describe('parseCurl', () => {+ it('parses a plain GET', () => {+ expect(parseCurl('curl -s https://three.ws/api/version')).toEqual({+ method: 'GET',+ url: 'https://three.ws/api/version',+ headers: {},+ body: null,+ });+ });++ it('infers POST from a body and collects headers', () => {+ const out = parseCurl(+ `curl https://three.ws/api/forge \\\n -H "Content-Type: application/json" \\\n -d '{"prompt":"a robot"}'`,+ );+ expect(out.method).toBe('POST');+ expect(out.headers['Content-Type']).toBe('application/json');+ expect(out.body).toBe('{"prompt":"a robot"}');+ });++ it('respects an explicit -X', () => {+ expect(parseCurl('curl -X DELETE https://three.ws/api/thing').method).toBe('DELETE');+ });++ it('reads --url and skips flags that carry an irrelevant value', () => {+ const out = parseCurl('curl -o out.json -u me:pw --url https://three.ws/api/version');+ expect(out.url).toBe('https://three.ws/api/version');+ });++ it('refuses anything that is not a single curl command', () => {+ expect(parseCurl('curl https://three.ws/x | jq .')).toBeNull();+ expect(parseCurl('cd app && curl https://three.ws/x')).toBeNull();+ expect(parseCurl('npm run dev')).toBeNull();+ expect(parseCurl('curl -X TELEPORT https://three.ws/x')).toBeNull();+ expect(parseCurl('curl -s')).toBeNull();+ });+});++describe('assessRequest', () => {+ const origin = 'https://three.ws';++ it('runs a same-host GET on one click', () => {+ const out = assessRequest({ method: 'GET', url: 'https://three.ws/api/version' }, { origin });+ expect(out).toMatchObject({ ok: true, confirm: false });+ });++ it('resolves a relative URL against the current origin', () => {+ const out = assessRequest({ method: 'GET', url: '/api/version' }, { origin: 'http://localhost:3000' });+ expect(out.url).toBe('http://localhost:3000/api/version');+ expect(out.ok).toBe(true);+ });++ it('requires a confirmation for every write verb', () => {+ for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {+ const out = assessRequest({ method, url: 'https://three.ws/api/forge' }, { origin });+ expect(out, method).toMatchObject({ ok: true, confirm: true });+ }+ });++ it('refuses any host that is not three.ws', () => {+ const out = assessRequest({ method: 'GET', url: 'https://evil.example/api' }, { origin });+ expect(out.ok).toBe(false);+ expect(out.reason).toMatch(/evil\.example/);+ });++ it('refuses every money path, on any verb', () => {+ // This is the guard the whole feature rests on: a docs reader must not be+ // able to reach a spend endpoint from a code sample, confirmed or not.+ const paths = [+ '/api/user/wallet/fund-agent',+ '/api/x402/fact-check',+ '/api/agents/1/autopilot/run',+ '/api/pump/launch',+ '/api/trade/swap',+ '/api/vault/withdraw',+ ];+ for (const path of paths) {+ for (const method of ['GET', 'POST']) {+ const out = assessRequest({ method, url: `https://three.ws${path}` }, { origin });+ expect(out.ok, `${method} ${path}`).toBe(false);+ }+ }+ });++ it('refuses a non-http scheme', () => {+ expect(assessRequest({ method: 'GET', url: 'file:///etc/passwd' }, { origin }).ok).toBe(false);+ expect(assessRequest({ method: 'GET', url: 'javascript:alert(1)' }, { origin }).ok).toBe(false);+ });++ it('refuses an unparseable URL', () => {+ expect(assessRequest({ method: 'GET', url: 'http://' }, { origin }).ok).toBe(false);+ });++ it('falls back to three.ws when no origin is supplied', () => {+ expect(assessRequest({ method: 'GET', url: '/api/version' }).url).toBe('https://three.ws/api/version');+ });+});++describe('findPlaceholders', () => {+ it('finds every slot shape a doc sample uses', () => {+ const names = findPlaceholders({+ url: 'https://three.ws/api/agents/<agent-id>/profile',+ headers: { Authorization: 'Bearer $THREEWS_API_KEY' },+ body: '{"owner":"YOUR_WALLET"}',+ }).map((p) => p.name);+ expect(names).toContain('THREEWS_API_KEY');+ expect(names).toContain('agent-id');+ expect(names).toContain('YOUR_WALLET');+ });++ it('marks credential-shaped names as secret', () => {+ const found = findPlaceholders({ url: 'https://three.ws/x?k=$API_KEY&id=<agent-id>' });+ expect(found.find((p) => p.name === 'API_KEY').secret).toBe(true);+ expect(found.find((p) => p.name === 'agent-id').secret).toBe(false);+ });++ it('does not mistake HTML tags in a header value for slots', () => {+ const found = findPlaceholders({ headers: { Accept: 'text/<html>' } });+ expect(found).toEqual([]);+ });++ it('returns each name once', () => {+ const found = findPlaceholders({ url: 'https://three.ws/$ID/x/$ID', body: '$ID' });+ expect(found.filter((p) => p.name === 'ID')).toHaveLength(1);+ });+});++describe('isSecretName', () => {+ it('recognises credential-shaped names', () => {+ for (const n of ['API_KEY', 'THREEWS_TOKEN', 'my_secret', 'PRIVATE_KEY', 'AUTH']) {+ expect(isSecretName(n), n).toBe(true);+ }+ expect(isSecretName('agent-id')).toBe(false);+ });+});++describe('applyPlaceholders', () => {+ it('substitutes every sigil form', () => {+ const out = applyPlaceholders(+ {+ method: 'POST',+ url: 'https://three.ws/api/agents/<agent-id>',+ headers: { Authorization: 'Bearer ${API_KEY}' },+ body: '{"k":"$API_KEY"}',+ },+ { 'agent-id': '42', API_KEY: 'sk-live' },+ );+ expect(out.url).toBe('https://three.ws/api/agents/42');+ expect(out.headers.Authorization).toBe('Bearer sk-live');+ expect(out.body).toBe('{"k":"sk-live"}');+ });++ it('leaves an unfilled slot visible rather than substituting nothing', () => {+ const out = applyPlaceholders({ url: 'https://three.ws/api/agents/<agent-id>' }, { 'agent-id': '' });+ expect(out.url).toBe('https://three.ws/api/agents/<agent-id>');+ });++ it('substitutes a bare YOUR_* name but never a bare ordinary one', () => {+ expect(applyPlaceholders({ url: 'https://three.ws/YOUR_ID' }, { YOUR_ID: '7' }).url).toBe('https://three.ws/7');+ // `ID` appears inside the path segment "IDENTITY"; replacing it would corrupt the URL.+ expect(applyPlaceholders({ url: 'https://three.ws/IDENTITY' }, { ID: '7' }).url).toBe('https://three.ws/IDENTITY');+ });++ it('does not mutate the input request', () => {+ const input = { method: 'GET', url: 'https://three.ws/$A', headers: {}, body: null };+ applyPlaceholders(input, { A: 'x' });+ expect(input.url).toBe('https://three.ws/$A');+ });+});++describe('rewriteAssetOrigin', () => {+ it('points production asset URLs at a dev origin so the preview tests the local build', () => {+ const out = rewriteAssetOrigin('<script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>', 'http://localhost:3000');+ expect(out).toContain('http://localhost:3000/agent-3d/latest/agent-3d.js');+ });++ it('is a no-op on three.ws itself', () => {+ const html = '<script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>';+ expect(rewriteAssetOrigin(html, 'https://three.ws')).toBe(html);+ expect(rewriteAssetOrigin(html, 'https://www.three.ws')).toBe(html);+ });++ it('leaves other hosts untouched', () => {+ const html = '<img src="https://cdn.example/x.png">';+ expect(rewriteAssetOrigin(html, 'http://localhost:3000')).toBe(html);+ });+});++describe('buildPreviewDoc', () => {+ it('wraps a fragment into a complete document', () => {+ const doc = buildPreviewDoc('<agent-3d src="/a.glb"></agent-3d>', { origin: 'https://three.ws' });+ expect(doc.startsWith('<!doctype html>')).toBe(true);+ expect(doc).toContain('<agent-3d src="/a.glb"></agent-3d>');+ });++ it('does not double-wrap a snippet that is already a document', () => {+ const doc = buildPreviewDoc('<!doctype html><html><body>hi</body></html>', { origin: 'https://three.ws' });+ expect(doc.match(/<!doctype/gi)).toHaveLength(1);+ });++ it('carries the reader theme into the frame', () => {+ expect(buildPreviewDoc('<div>x</div>', { theme: 'light' })).toContain('data-theme="light"');+ expect(buildPreviewDoc('<div>x</div>', { theme: 'dark' })).toContain('data-theme="dark"');+ });+});++describe('buildScriptDoc', () => {+ it('embeds the snippet and captures console output', () => {+ const doc = buildScriptDoc('console.log("hi")');+ expect(doc).toContain('console.log("hi")');+ expect(doc).toContain('postMessage');+ });++ it('neutralises a closing script tag inside the snippet', () => {+ // Without this the injected module would terminate early and the rest of+ // the sample would be parsed as HTML.+ const doc = buildScriptDoc('const s = "</script>";');+ expect(doc).not.toContain('const s = "</script>"');+ expect(doc).toContain('<\\/script');+ });+});++describe('formatting', () => {+ it('formats bytes at each magnitude', () => {+ expect(formatBytes(840)).toBe('840 B');+ expect(formatBytes(1200)).toBe('1.2 kB');+ expect(formatBytes(3_400_000)).toBe('3.40 MB');+ expect(formatBytes(-1)).toBe('—');+ expect(formatBytes('nope')).toBe('—');+ });++ it('formats durations across the second boundary', () => {+ expect(formatDuration(142)).toBe('142 ms');+ expect(formatDuration(1420)).toBe('1.42 s');+ expect(formatDuration(null)).toBe('—');+ });++ it('bands HTTP statuses, with 402 called out on its own', () => {+ expect(statusTone(200)).toBe('ok');+ expect(statusTone(301)).toBe('redirect');+ expect(statusTone(402)).toBe('paid');+ expect(statusTone(404)).toBe('warn');+ expect(statusTone(500)).toBe('err');+ expect(statusTone(undefined)).toBe('err');+ });++ it('re-indents JSON and reports the language', () => {+ const out = formatResponseBody('{"a":1}', { contentType: 'application/json' });+ expect(out.text).toBe('{\n "a": 1\n}');+ expect(out.language).toBe('json');+ expect(out.truncated).toBe(false);+ });++ it('detects JSON even when the content type lies', () => {+ expect(formatResponseBody('[1,2]', { contentType: 'text/plain' }).language).toBe('json');+ });++ it('passes malformed JSON through as text instead of throwing', () => {+ const out = formatResponseBody('{oops', { contentType: 'application/json' });+ expect(out.language).toBe('text');+ expect(out.text).toBe('{oops');+ });++ it('truncates a body a docs panel should not try to render', () => {+ const out = formatResponseBody('x'.repeat(500), { limit: 100 });+ expect(out.truncated).toBe(true);+ expect(out.text).toContain('truncated');+ });+});++describe('runLabel', () => {+ it('names the action the button actually performs', () => {+ expect(runLabel('preview')).toBe('Run preview');+ expect(runLabel('script')).toBe('Run script');+ expect(runLabel('request', { method: 'GET' })).toBe('Send request');+ expect(runLabel('request', { method: 'POST' })).toBe('Send POST');+ });+});diff --git a/tests/live-steps.test.js b/tests/live-steps.test.jsnew file mode 100644index 000000000..ad1631926--- /dev/null+++ b/tests/live-steps.test.js@@ -0,0 +1,280 @@+/**+ * Live steps - the runnable API cards embedded in documentation.+ *+ * public/live-steps.js ships as a classic script (like tutorials-manifest.js),+ * so these tests evaluate the real shipped file in a sandbox and exercise the+ * exported surface. That keeps the security invariants under test in the exact+ * artifact the browser loads, rather than in a parallel copy.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync, statSync } from 'node:fs';+import { resolve, join } from 'node:path';+import vm from 'node:vm';++const ROOT = resolve(__dirname, '..');+const SOURCE = readFileSync(join(ROOT, 'public/live-steps.js'), 'utf8');++function load() {+ const sandbox = { window: {} };+ vm.createContext(sandbox);+ vm.runInContext(SOURCE, sandbox, { filename: 'live-steps.js' });+ return sandbox.window.LiveSteps;+}++const LiveSteps = load();++describe('live-steps registry', () => {+ it('loads and exposes the documented surface', () => {+ expect(LiveSteps).toBeTruthy();+ for (const name of ['STEPS', 'validateRegistry', 'redact', 'buildUrl', 'mount']) {+ expect(typeof LiveSteps[name]).not.toBe('undefined');+ }+ expect(LiveSteps.STEPS.length).toBeGreaterThan(0);+ });++ it('every registered request is a read-only GET', () => {+ for (const step of LiveSteps.STEPS) {+ if (step.kind !== 'request') continue;+ expect(step.method).toBe('GET');+ }+ });++ it('every registered path is a literal same-origin /api path', () => {+ for (const step of LiveSteps.STEPS) {+ if (step.kind !== 'request') continue;+ expect(step.path.startsWith('/api/')).toBe(true);+ expect(step.path).not.toContain('..');+ expect(step.path).not.toContain('//');+ // A template in the path would let markdown steer the request.+ expect(step.path).not.toContain('{');+ expect(step.path).not.toContain(':');+ }+ });++ it('every step carries reader-facing copy and a reference link', () => {+ for (const step of LiveSteps.STEPS) {+ expect(step.title.length).toBeGreaterThan(4);+ expect(step.summary.length).toBeGreaterThan(20);+ expect(step.docs.startsWith('/')).toBe(true);+ }+ });+});++describe('validateRegistry rejects unsafe entries', () => {+ const base = {+ id: 'x',+ kind: 'request',+ method: 'GET',+ path: '/api/version',+ title: 'x',+ summary: 'x',+ docs: '/docs/',+ inputs: [],+ exports: {},+ };++ it('refuses a method other than GET', () => {+ expect(() => LiveSteps.validateRegistry([{ ...base, method: 'POST' }])).toThrow(/read-only/);+ });++ it('refuses an absolute URL as the path', () => {+ expect(() => LiveSteps.validateRegistry([{ ...base, path: 'https://evil.test/api/x' }])).toThrow(+ /unsafe path/,+ );+ });++ it('refuses a traversal path', () => {+ expect(() => LiveSteps.validateRegistry([{ ...base, path: '/api/../admin' }])).toThrow(+ /unsafe path/,+ );+ });++ it('refuses a protocol-relative path', () => {+ expect(() => LiveSteps.validateRegistry([{ ...base, path: '//evil.test/api' }])).toThrow(+ /unsafe path/,+ );+ });++ it('refuses duplicate ids', () => {+ expect(() => LiveSteps.validateRegistry([base, base])).toThrow(/duplicate/);+ });++ it('refuses an input name that is not a plain identifier', () => {+ expect(() =>+ LiveSteps.validateRegistry([{ ...base, inputs: [{ name: 'a b', label: 'x', value: '' }] }]),+ ).toThrow(/unsafe input name/);+ });++ it('refuses a step that consumes a variable nothing earlier produces', () => {+ expect(() =>+ LiveSteps.validateRegistry([+ { ...base, kind: 'derive', derive: 'siwsMessage', uses: ['nonce'] },+ ]),+ ).toThrow(/no earlier step exports/);+ });++ it('refuses a derivation that is not implemented in code', () => {+ expect(() =>+ LiveSteps.validateRegistry([+ { ...base, exports: { nonce: 'nonce' } },+ { ...base, id: 'y', kind: 'derive', derive: 'notAThing', uses: ['nonce'] },+ ]),+ ).toThrow(/unknown derivation/);+ });++ it('accepts the shipped registry', () => {+ expect(LiveSteps.validateRegistry(LiveSteps.STEPS)).toBe(true);+ });+});++describe('buildUrl', () => {+ const step = {+ path: '/api/agents/public',+ inputs: [{ name: 'limit', label: 'limit', value: '3' }],+ };++ it('appends inputs as encoded query values', () => {+ expect(LiveSteps.buildUrl(step, { limit: '5' })).toBe('/api/agents/public?limit=5');+ });++ it('drops blank inputs rather than sending an empty parameter', () => {+ expect(LiveSteps.buildUrl(step, { limit: ' ' })).toBe('/api/agents/public');+ expect(LiveSteps.buildUrl(step, {})).toBe('/api/agents/public');+ });++ it('cannot be steered off the path by a hostile input value', () => {+ const url = LiveSteps.buildUrl(step, { limit: '../../admin?x=1#y' });+ expect(url.startsWith('/api/agents/public?')).toBe(true);+ expect(url).not.toContain('/admin');+ expect(url).toContain('limit=..%2F..%2Fadmin%3Fx%3D1%23y');+ });++ it('ignores values for parameters the step does not declare', () => {+ expect(LiveSteps.buildUrl(step, { limit: '2', secret: 'nope' })).toBe(+ '/api/agents/public?limit=2',+ );+ });+});++describe('redact', () => {+ it('hides session-shaped fields and counts them', () => {+ const { value, count } = LiveSteps.redact({+ nonce: 'keep-me',+ csrf: 'hide-me',+ user: { sid: 'hide-me-too', email: '[email protected]' },+ });+ expect(count).toBe(2);+ expect(value.nonce).toBe('keep-me');+ expect(value.csrf).not.toBe('hide-me');+ expect(value.user.sid).not.toBe('hide-me-too');+ expect(value.user.email).toBe('[email protected]');+ });++ it('walks arrays', () => {+ const { value, count } = LiveSteps.redact({ sessions: [{ token: 'a' }, { token: 'b' }] });+ expect(count).toBe(2);+ expect(value.sessions.every((s) => s.token !== 'a' && s.token !== 'b')).toBe(true);+ });++ it('leaves an already-empty field alone rather than inventing a secret', () => {+ const { value, count } = LiveSteps.redact({ token: null, csrf: '' });+ expect(count).toBe(0);+ expect(value.token).toBe(null);+ expect(value.csrf).toBe('');+ });++ it('does not mutate the input, so exports still read real values', () => {+ const raw = { csrf: 'real-value' };+ LiveSteps.redact(raw);+ expect(raw.csrf).toBe('real-value');+ });+});++describe('explainFailure', () => {+ it('names a cause and a next move for every branch', () => {+ for (const status of [0, 401, 404, 429, 500]) {+ const text = LiveSteps.explainFailure(status, null);+ expect(text.length).toBeGreaterThan(30);+ }+ expect(LiveSteps.explainFailure(0, null)).toMatch(/offline|blocking/i);+ expect(LiveSteps.explainFailure(429, null)).toMatch(/rate limited/i);+ });++ it('surfaces the API error description when there is one', () => {+ expect(LiveSteps.explainFailure(400, { error_description: 'limit must be a number' })).toContain(+ 'limit must be a number',+ );+ });+});++describe('the SIWS message derivation', () => {+ const message = LiveSteps.DERIVATIONS.siwsMessage({+ domain: 'three.ws',+ uri: 'https://three.ws',+ nonce: 'TEST_NONCE',+ address: 'YourWa11etAddress',+ });+ const lines = message.split('\n');++ it('opens with the domain from the nonce response, not the page host', () => {+ expect(lines[0]).toBe('three.ws wants you to sign in with your Solana account:');+ });++ it('keeps both structural blank lines the verify parser depends on', () => {+ expect(lines[1]).toBe('YourWa11etAddress');+ expect(lines[2]).toBe('');+ expect(lines[4]).toBe('');+ });++ it('uses a Solana network name for Chain ID, never an EIP-155 number', () => {+ expect(message).toContain('Chain ID: mainnet');+ expect(message).not.toMatch(/Chain ID: \d/);+ });++ it('carries the nonce and a five minute expiry window', () => {+ expect(message).toContain('Nonce: TEST_NONCE');+ const issued = Date.parse(message.match(/Issued At: (.+)/)[1]);+ const expires = Date.parse(message.match(/Expiration Time: (.+)/)[1]);+ expect(expires - issued).toBe(5 * 60 * 1000);+ });++ it('falls back to a visible placeholder when no address is supplied', () => {+ const anon = LiveSteps.DERIVATIONS.siwsMessage({+ domain: 'three.ws',+ uri: 'https://three.ws',+ nonce: 'N',+ });+ expect(anon.split('\n')[1]).toBe('<your-solana-address>');+ });+});++describe('shipped documentation only references registered steps', () => {+ function walk(dir, out = []) {+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ if (statSync(full).isDirectory()) walk(full, out);+ else if (name.endsWith('.md')) out.push(full);+ }+ return out;+ }++ const ids = new Set(LiveSteps.STEPS.map((s) => s.id));+ const blocks = [];+ for (const file of walk(join(ROOT, 'docs'))) {+ const md = readFileSync(file, 'utf8');+ const re = /```live\n([\s\S]*?)```/g;+ let m;+ while ((m = re.exec(md)) !== null) blocks.push({ file, body: m[1] });+ }++ it('finds live blocks in the docs', () => {+ expect(blocks.length).toBeGreaterThan(0);+ });++ it('every live block is valid JSON naming a registered step', () => {+ for (const block of blocks) {+ const spec = JSON.parse(block.body);+ expect(ids.has(spec.step), `${block.file} references unknown step "${spec.step}"`).toBe(true);+ }+ });+});