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
Add repo meta: .gitattributes, .nvmrc, GitHub templates/CODEOWNERS, generic page OG endpoint, SEO meta injection
nirholas2a4637280f0d
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 000000000..553d222da--- /dev/null+++ b/.gitattributes@@ -0,0 +1,48 @@+# Normalize line endings: Git stores LF, checks out native on each platform.+* text=auto eol=lf++# Shell scripts and hooks must stay LF even on Windows checkouts.+*.sh text eol=lf+.githooks/* text eol=lf++# Windows-only scripts keep CRLF.+*.bat text eol=crlf+*.cmd text eol=crlf++# --- Generated / vendored files: collapse in diffs and exclude from language stats ---+package-lock.json linguist-generated=true -diff+CHANGELOG.md linguist-generated=true+public/changelog.json linguist-generated=true -diff+public/changelog.xml linguist-generated=true -diff+public/llms.txt linguist-generated=true+public/llms-full.txt linguist-generated=true+*.min.js linguist-generated=true -diff+*.bundle.js linguist-generated=true -diff++# --- Linguist: classify the repo as code, not vendored assets ---+docs/** linguist-documentation+examples/** linguist-documentation+*.md linguist-detectable=true++# --- Treat binary assets as binary (no diff, no EOL conversion) ---+*.glb binary+*.gltf binary+*.fbx binary+*.png binary+*.jpg binary+*.jpeg binary+*.gif binary+*.webp binary+*.ico binary+*.mp3 binary+*.mp4 binary+*.wav binary+*.ogg binary+*.hdr binary+*.ktx2 binary+*.basis binary+*.wasm binary+*.woff binary+*.woff2 binary+*.ttf binary+*.pdf binarydiff --git a/.github/CODEOWNERS b/.github/CODEOWNERSnew file mode 100644index 000000000..88cd04e43--- /dev/null+++ b/.github/CODEOWNERS@@ -0,0 +1,25 @@+# CODEOWNERS — default reviewers for three.ws.+# Order matters: the last matching pattern takes precedence.+# Docs: https://docs.github.com/articles/about-code-owners++# Default owner for everything in the repo.+* @nirholas++# Operating rules and security policy — review carefully.+/CLAUDE.md @nirholas+/.github/ @nirholas+/.well-known/ @nirholas+/public/.well-known/ @nirholas++# Smart contracts and payment rails — high blast radius.+/contracts/ @nirholas+/agent-payments-sdk/ @nirholas+/x402-buildout/ @nirholas++# Public SDKs — anything published carries an API contract.+/sdk/ @nirholas+/avatar-sdk/ @nirholas+/agent-protocol-sdk/ @nirholas+/agent-ui-sdk/ @nirholas+/solana-agent-sdk/ @nirholas+/mcp-server/ @nirholasdiff --git a/.github/FUNDING.yml b/.github/FUNDING.ymlnew file mode 100644index 000000000..995663303--- /dev/null+++ b/.github/FUNDING.yml@@ -0,0 +1,5 @@+# Adds a "Sponsor" button to the repo. Coin-agnostic by design — links to the+# product, not to any token. (Per project rules, $THREE is the only coin and is+# never promoted via funding links.)+custom:+ - https://three.wsdiff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 000000000..89fbb1a2a--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,68 @@+name: Bug report+description: Something on three.ws is broken or behaving incorrectly.+title: "[Bug]: "+labels: ["bug", "triage"]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for taking the time to file a bug. Please fill out the sections below so we can reproduce and fix it fast.+ For security vulnerabilities, **do not open an issue** — see our [security policy](https://github.com/nirholas/three.ws/security/policy).+ - type: textarea+ id: what-happened+ attributes:+ label: What happened?+ description: A clear, concise description of the bug and what you expected instead.+ placeholder: When I drag a GLB onto the viewer, the camera resets to origin instead of framing the model.+ validations:+ required: true+ - type: textarea+ id: repro+ attributes:+ label: Steps to reproduce+ description: Numbered steps. Include a public glTF/GLB link or sample if the issue is asset-specific.+ placeholder: |+ 1. Go to https://three.ws/...+ 2. Click on ...+ 3. See error+ validations:+ required: true+ - type: input+ id: url+ attributes:+ label: Affected URL or surface+ description: The exact page, API route, SDK package, or MCP server where this occurs.+ placeholder: https://three.ws/studio+ validations:+ required: false+ - type: textarea+ id: console+ attributes:+ label: Console / network errors+ description: Paste any browser console errors or failing network responses. This will be rendered as code.+ render: shell+ validations:+ required: false+ - type: dropdown+ id: area+ attributes:+ label: Area+ description: Which part of the platform?+ options:+ - Web app (viewer / studio / dashboard)+ - API (api/ functions)+ - SDK (avatar / payments / protocol / ui)+ - MCP server+ - Wallet / payments (x402)+ - Docs / changelog+ - Other / not sure+ validations:+ required: true+ - type: textarea+ id: environment+ attributes:+ label: Environment+ description: Browser + version, OS, device, and wallet (if relevant).+ placeholder: Chrome 126, macOS 14.5, Phantom wallet+ validations:+ required: falsediff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 000000000..bf4c5c3ac--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,14 @@+blank_issues_enabled: false+contact_links:+ - name: 💬 Discussions & questions+ url: https://github.com/nirholas/three.ws/discussions+ about: Ask questions, share builds, and propose ideas with the community.+ - name: 🔒 Report a security vulnerability+ url: https://github.com/nirholas/three.ws/security/advisories/new+ about: Privately report a security issue. Please do NOT open a public issue.+ - name: 📣 Follow @trythreews on X+ url: https://x.com/trythreews+ about: Product updates, releases, and announcements.+ - name: 📖 Documentation+ url: https://three.ws/docs+ about: Guides, API reference, and SDK docs.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 000000000..e57363cea--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,45 @@+name: Feature request+description: Suggest an improvement or new capability for three.ws.+title: "[Feature]: "+labels: ["enhancement", "triage"]+body:+ - type: markdown+ attributes:+ value: |+ Have an idea? We build for the end user first. The more you tell us about *who benefits and how*, the faster we can act.+ - type: textarea+ id: problem+ attributes:+ label: What problem does this solve?+ description: Describe the user need or the gap you hit. Who is the user, and what are they trying to accomplish?+ placeholder: As an agent creator, I want to ... so that I can ...+ validations:+ required: true+ - type: textarea+ id: solution+ attributes:+ label: Proposed solution+ description: What would the best version of this look like? Describe the ideal experience, not just the quickest fix.+ validations:+ required: true+ - type: textarea+ id: alternatives+ attributes:+ label: Alternatives considered+ description: Other approaches you weighed, or how you work around this today.+ validations:+ required: false+ - type: dropdown+ id: area+ attributes:+ label: Area+ options:+ - Web app (viewer / studio / dashboard)+ - API (api/ functions)+ - SDK (avatar / payments / protocol / ui)+ - MCP server+ - Wallet / payments (x402)+ - Docs / changelog+ - Other+ validations:+ required: truediff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 000000000..0a27f185c--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,43 @@+<!--+ Thanks for contributing to three.ws. Keep PRs focused and complete.+ Read CONTRIBUTING.md and CLAUDE.md (operating rules) before submitting.+-->++## What & why++<!-- What does this change do, and what problem does it solve? Link the issue it closes. -->++Closes #++## Type of change++- [ ] Feature+- [ ] Improvement+- [ ] Fix+- [ ] Docs+- [ ] Infra / chore (no user-visible effect)++## Definition of done++<!-- Per CLAUDE.md. Check what applies; explain anything you couldn't verify. -->++- [ ] Code is fully wired and reachable by the user — no dead paths, stubs, TODOs, or commented-out code.+- [ ] No mocks, fake data, or placeholder values — real APIs and real data only.+- [ ] Every interactive element has hover, active, and focus states (UI changes).+- [ ] Loading, empty, and error states are designed and helpful (UI changes).+- [ ] `npm test` passes and `npm run typecheck` is clean.+- [ ] `npm run lint` is clean (or only pre-existing warnings).+- [ ] I reviewed my own `git diff` — every changed line is justified.++## Changelog++<!--+ Every user-visible change needs an entry in data/changelog.json (date, plain-language+ title + summary, tags). Internal-only chores do not. Run `npm run build:pages` to validate.+-->++- [ ] Added a `data/changelog.json` entry, **or** this change is internal-only and needs none.++## Screenshots / recordings++<!-- For UI changes, show before/after. A short clip beats a paragraph. -->diff --git a/.github/SECURITY.md b/.github/SECURITY.mdnew file mode 100644index 000000000..2dbef5705--- /dev/null+++ b/.github/SECURITY.md@@ -0,0 +1,36 @@+# Security Policy++We take the security of three.ws and the people who use it seriously. Thank you for helping keep the platform and its users safe.++## Reporting a vulnerability++**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.**++Instead, use one of these private channels:++- **GitHub Security Advisories** (preferred): [Open a private advisory](https://github.com/nirholas/three.ws/security/advisories/new)+- **Email**: [[email protected]](mailto:[email protected])++This mirrors our machine-readable policy at [`/.well-known/security.txt`](https://three.ws/.well-known/security.txt).++Please include, where possible:++- A description of the issue and its impact.+- Steps to reproduce, a proof of concept, or affected URLs / routes / SDK packages.+- Any relevant logs, requests, or screenshots.++## What to expect++- **Acknowledgement** within 3 business days.+- **An initial assessment** (severity + planned next steps) within 7 business days.+- **Coordinated disclosure**: we will work with you on a fix and a disclosure timeline, and credit you in the advisory unless you prefer to remain anonymous.++## Scope++In scope: this repository, the three.ws web app and APIs, the published SDKs, and the official MCP servers.++Out of scope: vulnerabilities in third-party dependencies that are already publicly known and have an upstream fix pending, social-engineering attacks, and reports from automated scanners without a demonstrated, reproducible impact.++## Supported versions++three.ws is a continuously deployed platform; the deployed `main` branch is the only supported version. Security fixes ship to production directly.diff --git a/.nvmrc b/.nvmrcnew file mode 100644index 000000000..a45fd52cc--- /dev/null+++ b/.nvmrc@@ -0,0 +1 @@+24diff --git a/api/page-og.js b/api/page-og.jsnew file mode 100644index 000000000..2b9a6055a--- /dev/null+++ b/api/page-og.js@@ -0,0 +1,267 @@+// api/page-og.js — generic Open Graph / social-share image for every static+// page in data/pages.json. One endpoint renders a branded, per-page,+// per-section 1200×630 PNG card so each shared link previews with its own+// title, description, and section identity instead of a single shared image.+//+// Driven entirely by query params (no DB / filesystem read at request time):+// ?t=<title> ?d=<description> ?s=<section id> ?p=<route path>+// The SEO injector (scripts/inject-seo-meta.mjs) stamps these straight from the+// page catalog, so the card a crawler sees always matches the sitemap copy.+//+// Rendered as a real PNG via @vercel/og's ImageResponse on the NODE runtime+// (not Edge — Edge returns FUNCTION_INVOCATION_FAILED in this deployment), the+// same pattern proven in api/play-og.js. PNG (not SVG) so X, Facebook,+// LinkedIn, and iMessage — none of which render image/svg+xml OG cards — all+// show the preview.+import { ImageResponse } from '@vercel/og';++const WIDTH = 1200;+const HEIGHT = 630;++// Per-section identity. Each catalog section gets a distinct accent so a page's+// share card reads as part of its family at a glance. Falls back to the brand+// violet for anything unmapped.+const SECTIONS = {+ main: { label: 'Platform', accent: '#8b5cf6' },+ build: { label: 'Build', accent: '#06b6d4' },+ labs: { label: 'Labs', accent: '#ec4899' },+ crypto: { label: 'Crypto', accent: '#4ade80' },+ 'agent-tools': { label: 'Agent Tools', accent: '#14b8a6' },+ account: { label: 'Account', accent: '#60a5fa' },+ learn: { label: 'Learn', accent: '#fb923c' },+ blog: { label: 'Blog', accent: '#a78bfa' },+ legal: { label: 'Legal', accent: '#94a3b8' },+ machine: { label: 'Reference', accent: '#9ca3af' },+};+const DEFAULT_SECTION = { label: 'three.ws', accent: '#8b5cf6' };++function sectionFor(id) {+ return SECTIONS[String(id || '').toLowerCase()] || DEFAULT_SECTION;+}++function clamp(s, n) {+ s = String(s || '').trim();+ return s.length <= n ? s : s.slice(0, n - 1).trimEnd() + '…';+}++function card({ title, desc, section, route, accent }) {+ return {+ type: 'div',+ props: {+ style: {+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'space-between',+ padding: '70px 76px',+ background: `radial-gradient(115% 115% at 82% 8%, ${accent}26 0%, #0a0a0f 46%, #050507 100%)`,+ color: 'white',+ fontFamily: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',+ },+ children: [+ // faint engineering grid overlay+ {+ type: 'div',+ props: {+ style: {+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ display: 'flex',+ backgroundImage:+ 'linear-gradient(rgba(255,255,255,0.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.035) 1px, transparent 1px)',+ backgroundSize: '52px 52px',+ },+ },+ },+ // top row: brand wordmark + section pill+ {+ type: 'div',+ props: {+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },+ children: [+ {+ type: 'div',+ props: {+ style: { display: 'flex', alignItems: 'baseline' },+ children: [+ {+ type: 'div',+ props: {+ style: { fontSize: 30, fontWeight: 800, letterSpacing: -1, color: '#f5f5f7' },+ children: 'three.ws',+ },+ },+ {+ type: 'div',+ props: {+ style: { fontSize: 30, fontWeight: 800, letterSpacing: -1, color: accent, marginLeft: 4 },+ children: '.',+ },+ },+ ],+ },+ },+ {+ type: 'div',+ props: {+ style: {+ display: 'flex',+ alignItems: 'center',+ fontSize: 22,+ fontWeight: 700,+ letterSpacing: 1,+ textTransform: 'uppercase',+ color: accent,+ padding: '10px 22px',+ borderRadius: 999,+ background: `${accent}1f`,+ border: `1px solid ${accent}59`,+ },+ children: section.label,+ },+ },+ ],+ },+ },+ // middle: title + description+ {+ type: 'div',+ props: {+ style: { display: 'flex', flexDirection: 'column' },+ children: [+ {+ type: 'div',+ props: {+ style: {+ fontSize: title.length > 22 ? 76 : 92,+ fontWeight: 900,+ letterSpacing: -3,+ lineHeight: 1.02,+ color: '#ffffff',+ },+ children: title,+ },+ },+ desc+ ? {+ type: 'div',+ props: {+ style: {+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.3,+ marginTop: 26,+ maxWidth: 980,+ color: 'rgba(235,235,245,0.62)',+ },+ children: desc,+ },+ }+ : { type: 'div', props: { children: '' } },+ ],+ },+ },+ // bottom: route + tagline+ {+ type: 'div',+ props: {+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },+ children: [+ {+ type: 'div',+ props: {+ style: {+ display: 'flex',+ alignItems: 'center',+ fontSize: 24,+ fontWeight: 600,+ fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',+ color: 'rgba(235,235,245,0.5)',+ },+ children: [+ {+ type: 'div',+ props: {+ style: { width: 10, height: 10, borderRadius: 10, background: accent, marginRight: 14 },+ },+ },+ { type: 'div', props: { children: `three.ws${route}` } },+ ],+ },+ },+ {+ type: 'div',+ props: {+ style: { fontSize: 24, fontWeight: 500, color: 'rgba(235,235,245,0.4)' },+ children: 'Give your AI a body.',+ },+ },+ ],+ },+ },+ ],+ },+ };+}++function imageResponse(node) {+ return new ImageResponse(node, {+ width: WIDTH,+ height: HEIGHT,+ headers: {+ 'cache-control': 'public, max-age=3600, s-maxage=604800, stale-while-revalidate=86400',+ },+ });+}++// Web Response (from @vercel/og) → Node ServerResponse. Headers first, then body.+async function sendImage(res, response) {+ for (const [key, value] of response.headers.entries()) res.setHeader(key, value);+ const ab = await response.arrayBuffer();+ res.statusCode = response.status;+ res.end(Buffer.from(ab));+}++export default async function handler(req, res) {+ if (req.method === 'OPTIONS') {+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('access-control-allow-methods', 'GET,OPTIONS');+ res.statusCode = 204;+ res.end();+ return;+ }++ const url = new URL(req.url, 'http://x');+ const section = sectionFor(url.searchParams.get('s'));+ const accent = section.accent;+ const title = clamp(url.searchParams.get('t') || 'three.ws', 60);+ const desc = clamp(url.searchParams.get('d') || '', 140);+ let route = (url.searchParams.get('p') || '/').trim();+ if (!route.startsWith('/')) route = `/${route}`;+ route = clamp(route, 42);++ try {+ await sendImage(res, imageResponse(card({ title, desc, section, route, accent })));+ } catch (err) {+ // Never fail open to a broken-image box — render the coin-agnostic brand+ // card so the preview still looks intentional.+ console.error('[page-og] render failed:', err?.message || err);+ res.statusCode = 200;+ await sendImage(+ res,+ imageResponse(+ card({+ title: 'three.ws',+ desc: 'Give your AI a body. Build, embed, monetize, and trade autonomous 3D agents.',+ section: DEFAULT_SECTION,+ route: '/',+ accent: DEFAULT_SECTION.accent,+ }),+ ),+ );+ }+}diff --git a/package.json b/package.jsonindex bfdca6014..78d1812bd 100644--- a/package.json+++ b/package.json@@ -3,9 +3,17 @@"type": "module","version": "1.5.2","name": "3d-agent",- "description": "AI-powered 3D model viewer — drag-and-drop glTF/GLB preview tool.",+ "description": "three.ws — build, animate, rig, and monetize 3D AI agents on-chain. Three.js web app, SDKs, MCP servers, and x402 payment rails.","author": "nirholas","license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },"overrides": {"serialize-javascript": ">=7.0.5","@esbuild-plugins/node-globals-polyfill": "^0.2.0"@@ -14,14 +22,18 @@"node": "24.x"},"keywords": [+ "3d-agent",+ "ai-agents","3d-viewer","gltf-viewer","glb-viewer",- "3d-model-viewer","webgl","threejs",- "drag-and-drop",- "3d-agent"+ "avatar",+ "solana",+ "mcp",+ "x402",+ "onchain"],"workspaces": ["agent-payments-sdk",diff --git a/scripts/inject-seo-meta.mjs b/scripts/inject-seo-meta.mjsindex 3d3c905cf..d94e00940 100644--- a/scripts/inject-seo-meta.mjs+++ b/scripts/inject-seo-meta.mjs@@ -9,8 +9,13 @@// sitemap), so the meta a crawler sees matches the catalog exactly.//// It NEVER overwrites a tag a page already has — page bodies are owned by-// other agents; we only fill genuine gaps. Re-running is a no-op once a page-// is fully covered. Pass --write to mutate files; default is a dry-run report.+// other agents; we only fill genuine gaps. The one exception is the social+// share image: pages whose og:image/twitter:image still point at the single+// static /og-image.png are re-pointed at the per-page dynamic OG card+// (/api/page-og) so every shared link previews with its own title, section,+// and description. Custom dynamic OG images (agent/avatar/feature cards) are+// left untouched. Re-running is a no-op once a page is fully covered. Pass+// --write to mutate files; default is a dry-run report.//// Route → file resolution uses vercel.json's `routes` table (the real router),// falling back to conventional file locations.@@ -22,8 +27,23 @@ import path from 'node:path';const ROOT = process.cwd();const ORIGIN = 'https://three.ws';const DEFAULT_OG = `${ORIGIN}/og-image.png`;+// Every value a crawler might currently hold for the legacy shared card. Any of+// these gets upgraded to the page's dynamic /api/page-og image.+const LEGACY_OG = new Set([DEFAULT_OG, '/og-image.png', `${ORIGIN}/og-image.png?v=1`]);const WRITE = process.argv.includes('--write');+// Per-page dynamic social share image. Copy is carried in the URL so the+// /api/page-og renderer stays a pure, cacheable function of its params and+// always matches this catalog. Mirrors the section accents defined there.+function pageOgUrl(page, sectionId) {+ const q = new URLSearchParams();+ q.set('s', sectionId || 'main');+ q.set('t', page.title || 'three.ws');+ if (page.description) q.set('d', page.description.slice(0, 160));+ q.set('p', page.path || '/');+ return `${ORIGIN}/api/page-og?${q.toString()}`;+}+function htmlEscape(s) {return String(s).replace(/&/g, '&')@@ -102,6 +122,10 @@ const has = {twitterTitle: (h) => /<meta[^>]+name=["']twitter:title["']/i.test(h),twitterDescription: (h) => /<meta[^>]+name=["']twitter:description["']/i.test(h),twitterImage: (h) => /<meta[^>]+name=["']twitter:image["']/i.test(h),+ twitterSite: (h) => /<meta[^>]+name=["']twitter:site["']/i.test(h),+ ogImageAlt: (h) => /<meta[^>]+property=["']og:image:alt["']/i.test(h),+ ogLocale: (h) => /<meta[^>]+property=["']og:locale["']/i.test(h),+ robots: (h) => /<meta[^>]+name=["']robots["']/i.test(h),jsonld: (h) => /<script[^>]+application\/ld\+json/i.test(h),};@@ -111,40 +135,96 @@ function existingOgImage(head) {return m ? m[1] : null;}-function buildTags(page, head) {+// Re-point a page still on the single static share image at its own dynamic+// card. Touches only og:image / twitter:image whose value is exactly the legacy+// /og-image.png — custom per-entity OG cards are left alone. Returns the+// possibly-rewritten html and whether anything changed.+function repointShareImage(html, dynamicOg) {+ let changed = false;+ const next = html.replace(+ /(<meta[^>]+(?:property=["']og:image["']|name=["']twitter:image["'])[^>]+content=["'])([^"']+)(["'][^>]*>)/gi,+ (full, pre, val, post) => {+ if (!LEGACY_OG.has(val.trim())) return full;+ changed = true;+ return pre + dynamicOg + post;+ },+ );+ return { html: next, changed };+}++function buildTags(page, head, sectionId) {const url = `${ORIGIN}${page.path === '/' ? '/' : page.path}`;const title = `${page.title} · three.ws`;const desc = page.description || '';- const ogImage = existingOgImage(head) || DEFAULT_OG;+ const dynamicOg = pageOgUrl(page, sectionId);+ // Keep a page's bespoke OG card if it already has one; otherwise the dynamic+ // per-page card. (Legacy static images were already swapped by repoint.)+ const existing = existingOgImage(head);+ const ogImage = existing && !LEGACY_OG.has(existing.trim()) ? existing : dynamicOg;const lines = [];const indent = '\t';if (!has.canonical(head)) lines.push(`<link rel="canonical" href="${url}">`);+ if (!has.robots(head))+ lines.push(+ `<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">`,+ );if (!has.ogType(head)) lines.push(`<meta property="og:type" content="website">`);if (!has.ogSiteName(head)) lines.push(`<meta property="og:site_name" content="three.ws">`);+ if (!has.ogLocale(head)) lines.push(`<meta property="og:locale" content="en_US">`);if (!has.ogTitle(head)) lines.push(`<meta property="og:title" content="${htmlEscape(title)}">`);if (!has.ogDescription(head) && desc)lines.push(`<meta property="og:description" content="${htmlEscape(desc)}">`);if (!has.ogUrl(head)) lines.push(`<meta property="og:url" content="${url}">`);if (!has.ogImage(head)) {- lines.push(`<meta property="og:image" content="${ogImage}">`);+ lines.push(`<meta property="og:image" content="${htmlEscape(ogImage)}">`);lines.push(`<meta property="og:image:width" content="1200">`);lines.push(`<meta property="og:image:height" content="630">`);+ lines.push(`<meta property="og:image:type" content="image/png">`);}+ if (!has.ogImageAlt(head))+ lines.push(`<meta property="og:image:alt" content="${htmlEscape(page.title)} — three.ws">`);if (!has.twitterCard(head)) lines.push(`<meta name="twitter:card" content="summary_large_image">`);+ if (!has.twitterSite(head)) lines.push(`<meta name="twitter:site" content="@trythreews">`);if (!has.twitterTitle(head)) lines.push(`<meta name="twitter:title" content="${htmlEscape(title)}">`);if (!has.twitterDescription(head) && desc)lines.push(`<meta name="twitter:description" content="${htmlEscape(desc)}">`);- if (!has.twitterImage(head)) lines.push(`<meta name="twitter:image" content="${ogImage}">`);+ if (!has.twitterImage(head)) lines.push(`<meta name="twitter:image" content="${htmlEscape(ogImage)}">`);if (!has.jsonld(head)) {- const ld = {- '@context': 'https://schema.org',- '@type': 'WebPage',- name: page.title,- description: desc || undefined,- url,- isPartOf: { '@type': 'WebSite', name: 'three.ws', url: ORIGIN },- };+ const graph = [+ {+ '@type': 'WebPage',+ name: page.title,+ description: desc || undefined,+ url,+ isPartOf: { '@type': 'WebSite', name: 'three.ws', url: ORIGIN },+ primaryImageOfPage: ogImage,+ },+ ];+ // Breadcrumb trail for nested routes (e.g. /docs/start-here) so search+ // results render a path instead of a bare URL.+ const segs = page.path.split('/').filter(Boolean);+ if (segs.length > 1) {+ const items = [{ name: 'Home', url: `${ORIGIN}/` }];+ let acc = '';+ for (const s of segs) {+ acc += `/${s}`;+ items.push({+ name: s.replace(/[-_]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),+ url: `${ORIGIN}${acc}`,+ });+ }+ graph.push({+ '@type': 'BreadcrumbList',+ itemListElement: items.map((it, i) => ({+ '@type': 'ListItem',+ position: i + 1,+ name: it.name,+ item: it.url,+ })),+ });+ }+ const ld = { '@context': 'https://schema.org', '@graph': graph };lines.push(`<script type="application/ld+json">${JSON.stringify(ld).replace(/</g, '\\u003c')}</script>`,);@@ -191,48 +271,65 @@ async function main() {if (p.indexable === false || p.auth === 'required') continue;if (!p.path || p.path.startsWith('http')) continue;if (skip(p.path)) continue;- targets.push(p);+ targets.push({ page: p, sectionId: s.id });}}let resolved = 0;let unresolved = [];let changed = 0;+ let repointed = 0;let alreadyComplete = 0;- for (const page of targets) {+ for (const { page, sectionId } of targets) {const file = resolveFile(page.path, router);if (!file) {unresolved.push(page.path);continue;}resolved++;- const html = await readFile(file, 'utf8');+ const original = await readFile(file, 'utf8');+ // 1) Upgrade any legacy static share image to this page's dynamic card.+ const dynamicOg = pageOgUrl(page, sectionId);+ const { html, changed: didRepoint } = repointShareImage(original, dynamicOg);+ // 2) Backfill any missing head tags (computed against the post-repoint head).const head = headOf(html);- const tags = buildTags(page, head);- if (!tags.trim()) {+ const tags = buildTags(page, head, sectionId);+ if (!tags.trim() && !didRepoint) {alreadyComplete++;continue;}- const added = tags- .trim()- .split('\n')- .map((l) => l.trim().match(/(rel|property|name)=["']([^"']+)["']|<(title|script)/i))- .map((m) => (m ? m[2] || m[3] : '?'))- .join(', ');const relFile = path.relative(ROOT, file);console.log(`${page.path} → ${relFile}`);- console.log(` + ${added}`);- changed++;+ if (didRepoint) {+ repointed++;+ console.log(` ~ og:image/twitter:image → /api/page-og`);+ }+ if (tags.trim()) {+ const added = tags+ .trim()+ .split('\n')+ .map((l) => l.trim().match(/(rel|property|name)=["']([^"']+)["']|<(title|script)/i))+ .map((m) => (m ? m[2] || m[3] : '?'))+ .join(', ');+ console.log(` + ${added}`);+ changed++;+ }if (WRITE) {- const next = injectIntoHead(html, tags);- if (next) await writeFile(file, next);- else console.log(` ! no </head> — skipped`);+ let next = html;+ if (tags.trim()) {+ next = injectIntoHead(html, tags);+ if (!next) {+ console.log(` ! no </head> — skipped`);+ next = html;+ }+ }+ if (next !== original) await writeFile(file, next);}}console.log('\n──────────────────────────────────────────');- console.log(`targets: ${targets.length} resolved: ${resolved} complete-already: ${alreadyComplete} ${WRITE ? 'written' : 'would-change'}: ${changed}`);+ console.log(`targets: ${targets.length} resolved: ${resolved} complete-already: ${alreadyComplete} re-pointed: ${repointed} ${WRITE ? 'written' : 'would-change'}: ${changed}`);if (unresolved.length) console.log(`UNRESOLVED (${unresolved.length}): ${unresolved.join(', ')}`);if (!WRITE) console.log('\n(dry-run — pass --write to apply)');}