See how your app actually fits together. An interactive, plain-English map of your codebase, drawn by Claude or Codex.
JavaScript ai-codingarchitecture-diagramclaudeclaude-codeclaude-code-plugincodebase-visualizationcodexcodex-plugindeveloper-toolsonboardingopenaivibe-coding
Export: a copy of the map to share, as one HTML file
Hayden Smithcdcedba856ca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f9b36a..2c37978 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- **Export a copy to share:** the map's new **Export** button saves one HTML file anyone can open in a browser, with nothing to install. It has the whole map without the Ask bar, your folder path or git remotes. Flows and notes go in by default; recent work and the health check (or a blueprint's design review) only if you tick them. Ask Claude or Codex to "export the floorplan", or run `node floorplan/serve.mjs --export`.+## 0.3.2 (2026-10-30)- **The map's server answers only to this computer's own addresses:** it refuses requests under any other host name, so a website that points its domain at 127.0.0.1 (DNS rebinding) can't load the map, read its token and ask questions about your code.diff --git a/README.md b/README.mdindex fc21505..88e58ba 100644--- a/README.md+++ b/README.md@@ -100,7 +100,7 @@ Updates re-read only what changed, and an open map reloads itself. Everything ru</tr></table>-Plus guided **flows** you can request in plain words, a one-minute **Start here** tour, search, keyboard shortcuts, and right-click actions on every card.+Plus guided **flows** you can request in plain words, a one-minute **Start here** tour, **Export** to send a copy to anyone as one HTML file, search, keyboard shortcuts, and right-click actions on every card.### Also: blueprints, for apps you haven't built yet@@ -205,6 +205,7 @@ You get a [blueprint](#also-blueprints-for-apps-you-havent-built-yet) of the pla| "Fix the important issues from the floorplan's Health check" | "If I change the users table, what breaks?" || "Add a flow showing how a new user signs up" | "Which files handle login?" || "Rewrite the floorplan for developers" | "What did we change for refunds?" |+| "Export the floorplan so I can send it to the team" | |## How it worksdiff --git a/docs/development.md b/docs/development.mdindex 01ab752..fe29364 100644--- a/docs/development.md+++ b/docs/development.md@@ -84,7 +84,8 @@ The tests use Node's built-in test runner, so there's nothing to install (`npm t| `blueprint-change.test.mjs` | changing a blueprint from the map: the agent's updated plan is checked, saved and highlighted, retried once when it fails the checks, and undone (stand-in CLI in `fixtures/fake-cli/`) || `large-files.test.mjs` | files over the scan's size limit stay on the map with their line count, and the scan, Health and the map say they weren't read || `sample-app.test.mjs` | a whole map of a two-repo shop: endpoints, cross-repo requests, Health, offline map, no secret values written, updates |-| `serve.test.mjs` | the map's server: 127.0.0.1 only, token and same-origin checks, nothing served from outside its folder |+| `serve.test.mjs` | the map's server: 127.0.0.1 only, its own host names only, token and same-origin checks, nothing served from outside its folder |+| `export.test.mjs` | exporting a copy to share: what's left out by default, the extras when asked, the Export button's endpoint || `ask.test.mjs` | asking through Claude Code or Codex: which one is used, read-only, follow-ups, sign-in errors (stand-in CLIs in `fixtures/fake-cli/`) || `agents.test.mjs` | telling Claude Code from Codex, and what a map built by each records and writes || `release.test.mjs` | the version agrees across both plugins' `plugin.json`, the README badge and the changelog |@@ -100,7 +101,8 @@ Files in `skills/floorplan/assets/ui/` are inlined into every map, in name order- navigation (`go`, `open`, `reveal`, `showBoard`, `playFlow`);- `addHeaderButton` and `addPanelSection('overview' | 'item', fn)`;- `modal`, `toast`, `store`;-- events (`on('ready' | 'render' | 'panel' | 'technical')`).+- events (`on('ready' | 'render' | 'panel' | 'technical')`);+- `exported`, set in an exported copy: leave out anything there that needs Claude, Codex or the map's server.`20-health.js` and `25-recent.js` are good examples.diff --git a/docs/privacy-and-security.md b/docs/privacy-and-security.mdindex 24406f1..2fc822f 100644--- a/docs/privacy-and-security.md+++ b/docs/privacy-and-security.md@@ -12,6 +12,7 @@| Asking questions (Codex) | a `codex exec` run on your computer, with your ChatGPT sign-in, not saved to your Codex history | your question, and the files Codex chooses to read || Changing a blueprint from the map | the same as asking questions, with Claude Code or Codex; the map's server then writes only the plan's files in `floorplan/` | your request, and the files the AI chooses to read || Asking questions (Claude app) | your claude.ai account | the map (names, descriptions, structure), never your source code. Claude asks before publishing it there |+| Exporting a copy | your computer: the map's server writes one HTML file | nothing. You decide who gets the file. It holds the map, plus Health or recent work only if you tick them, and never your folder path, git remotes or source code || Floorplan Cloud waitlist (only if you sign up) | the map's server, to Floorplan's waitlist service | the email you typed or chose, and "just me" or "with my team". See [below](#floorplan-cloud-waitlist) |Floorplan has no analytics or telemetry, no dependencies to install, and no install scripts. Its only outside connection is the opt-in waitlist below, and nothing reaches it unless you sign up. The map's few links to documentation open only when you click them.diff --git a/docs/project-files.md b/docs/project-files.mdindex 68461c7..388f352 100644--- a/docs/project-files.md+++ b/docs/project-files.md@@ -16,6 +16,7 @@ Floorplan writes to exactly two places in your project: the `floorplan/` folder,| `serve.mjs` | Serves the map locally and answers questions through the Claude Code CLI or Codex | No || `query.mjs` | Looks things up in the map from the command line; Claude and Codex use it too | No || `artifact.html` | A copy for opening in the Claude app, only if you asked for one | No |+| `<project>-map.html` | An exported copy to share, only if you exported one from Claude or Codex (the map's Export button downloads it instead) | No || `.cache/` | The scan, the description worksheets, the last update's changes, the running server's address, and, for a blueprint, the last 20 versions of the plan that **Undo** goes back to | No. Safe to delete, though Undo then has nothing to go back to || `.gitignore` | Keeps this whole folder out of git | No |diff --git a/docs/using-the-map.md b/docs/using-the-map.mdindex 2fe73f4..d5660e4 100644--- a/docs/using-the-map.md+++ b/docs/using-the-map.md@@ -58,6 +58,16 @@ Appears when Claude or Codex has just changed things. It lays the changed cards### ScreensEvery page of your app that Floorplan detected. Pick one to see everything behind it: its components, the requests it makes, the server code that answers them, the data they touch, and outside services.+### Export+Saves a copy of the map to send to anyone, such as a teammate, a client, or someone without Claude or Codex. It's one HTML file that opens in any browser with nothing to install. The copy has the whole map, search, screens, the tour and flows, but no Ask bar, no **Fix with Claude** or **Build this** requests, no editor links, and nothing about your computer, like its folder path. An **Exported** label beside the title shows the date.++You choose what goes in:+- **Flows and the tour**, and **notes pinned to files**, on by default;+- **Recent work**, off by default;+- **Health check** (or the **design review** on a blueprint), off by default. Health lists the endpoints anyone can use and where secrets sit in the code (never their values), so only include it for people you trust.++Every copy shows how the app fits together (each part, file and endpoint, with names and descriptions), but not your source code. Export needs the map's server; on a map opened straight from its file, the button shows the command to run instead. You can also ask Claude or Codex to "export the floorplan".+### Start hereReplays the one-minute tour that runs the first time you open a map.diff --git a/skills/floorplan/SKILL.md b/skills/floorplan/SKILL.mdindex 900c5c8..2c8bbf8 100644--- a/skills/floorplan/SKILL.md+++ b/skills/floorplan/SKILL.md@@ -135,6 +135,16 @@ The map has a floating Ask bar. The user types a question, and the agent answersPublishing uploads the map (paths, names, descriptions, structure), not the source code, to their private claude.ai account. Say that before you do it.- **Neither:** `floorplan/index.html` still opens directly in a browser. The Ask bar explains what's needed.+### Sharing a copy++When the user wants to send the map to someone (a teammate, a client, someone without Claude or Codex), export it. An export is the same single HTML file without the Ask bar, prompts for Claude or Codex, editor links, this machine's folder path or git remotes. The map's **Export** button does this from the browser; from here, run:++```+node floorplan/serve.mjs --export [<file>] [--include flows,notes,recent,health]+```++It writes `floorplan/<project>-map.html` unless given a file. `--include` defaults to `flows,notes` (flows and the tour, notes pinned to files); `recent` adds recent work and `health` adds the health check, or the design review on a blueprint. Leave health out unless the user asks for it, and if they do, say that it lists the endpoints anyone can use and where secrets sit in the code (never their values), so they should only send it to people they trust. Any export shows how the app fits together (every part, file and endpoint, with names and descriptions), but not the source code.+### What else the map gives them (automatic)- **Health.** A header button, with a count of important issues, opens a plain-language list of problems the scan found:diff --git a/skills/floorplan/assets/serve.mjs b/skills/floorplan/assets/serve.mjsindex 211d087..90632b8 100644--- a/skills/floorplan/assets/serve.mjs+++ b/skills/floorplan/assets/serve.mjs@@ -5,6 +5,7 @@// usage: node floorplan/serve.mjs [--port 4378] [--engine claude|codex] [--model <model>] [--claude <path>] [--codex <path>]// [--no-open] [--idle-exit <minutes>]// node floorplan/serve.mjs --stop+// node floorplan/serve.mjs --export [<file>] [--include flows,notes,recent,health] (a copy to share; default flows,notes)//// The server listens on 127.0.0.1 only. Each question runs in the codebase root, on your own account:// `claude -p` with read-only tools (Read, Grep, Glob, and Bash limited to floorplan/query.mjs), or@@ -32,6 +33,55 @@ if (has('stop')) {console.log(stopped ? `Stopped the map server (${s.url}).` : 'The map server was not running.');process.exit(0);}++// ---------- export: a copy of the map to share ----------+// The same self-contained page, marked as exported: no Ask bar, no requests for Claude or Codex, no links into+// this computer, and only the extras asked for. Used by the map's Export button and by --export.+const EXPORT_PARTS = ['flows', 'notes', 'recent', 'health'];+const EXPORT_DEFAULT = ['flows', 'notes'];+const DATA_START = '<script>window.FLOORPLAN = ';+function exportMap(include, extraFlows = []) {+ const html = fs.readFileSync(path.join(here, 'index.html'), 'utf8');+ const a = html.indexOf(DATA_START), b = html.indexOf(';</script>', a);+ if (a < 0 || b < 0) throw new Error('This map is too old to export. Ask Claude or Codex to update the floorplan first.');+ const g = JSON.parse(html.slice(a + DATA_START.length, b));+ const on = EXPORT_PARTS.filter((p) => include.includes(p));+ const out = {+ ...g,+ // the remote can carry a sign-in token; the folder path is this computer's+ meta: { ...g.meta, root: null, repos: (g.meta.repos || []).map(({ remote, ...r }) => r), exported: { at: new Date().toISOString(), include: on } },+ flows: on.includes('flows') ? [...g.flows, ...extraFlows.filter((f) => !g.flows.some((x) => x.id === f.id))] : [],+ tour: on.includes('flows') ? g.tour : [],+ files: on.includes('notes') ? g.files : g.files.map(({ note, ...f }) => f),+ };+ if (!on.includes('recent')) delete out.recent;+ if (!on.includes('health')) delete out.health;+ const json = JSON.stringify(out).replace(/<\/(script)/gi, '<\\/$1').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');+ const slug = String(g.project?.name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'floorplan';+ return { html: html.slice(0, a + DATA_START.length) + json + html.slice(b), name: `${slug}-map.html`, include: on, plan: !!g.meta?.blueprint };+}+/** Flows requested from the map since it was last built, as the page sends them: checked and trimmed. */+const cleanFlows = (list) => (Array.isArray(list) ? list : []).slice(0, 50)+ .filter((f) => f && typeof f.id === 'string' && Array.isArray(f.steps))+ .map((f) => ({+ id: f.id.slice(0, 100), title: String(f.title || 'Flow').slice(0, 200), description: String(f.description || '').slice(0, 1000), custom: true,+ steps: f.steps.slice(0, 60).filter((s) => s && typeof s.ref === 'string').map((s) => ({ ref: s.ref.slice(0, 300), note: String(s.note || '').slice(0, 2000) })),+ }))+ .filter((f) => f.steps.length >= 2);+if (has('export')) {+ const dest = opt('export');+ const include = String(opt('include', EXPORT_DEFAULT.join(','))).split(',').map((s) => s.trim().toLowerCase());+ try {+ const x = exportMap(include);+ const file = path.resolve(dest && !dest.startsWith('--') ? dest : path.join(here, x.name));+ fs.writeFileSync(file, x.html);+ console.log(`Exported the map to ${file}`);+ const label = { flows: 'flows and the tour', notes: 'notes', recent: 'recent work', health: x.plan ? 'the design review' : 'the health check' };+ console.log(`Includes: the map${x.include.map((p) => ', ' + label[p]).join('')}. One file that opens in any browser, with no Ask bar.`);+ if (x.include.includes('health') && !x.plan) console.log('It includes the health check: which endpoints are open and where secrets sit in the code (never their values). Share it only with people you trust.');+ process.exit(0);+ } catch (e) { console.error(`✗ Couldn't export the map: ${e.message}`); process.exit(1); }+}const wantPort = Number(opt('port', 4378));const idleExit = Number(opt('idle-exit', 0)) * 60000; // stop this long after the last tab closes (0 = never)const selfHash = crypto.createHash('sha1').update(fs.readFileSync(fileURLToPath(import.meta.url))).digest('hex').slice(0, 12);@@ -516,6 +566,19 @@ const server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify(r));}if (req.method === 'POST' && url.pathname === '/api/cancel') { for (const c of running.values()) c.kill(); res.writeHead(204); return res.end(); }+ if (req.method === 'POST' && url.pathname === '/api/export') {+ let raw = '';+ req.on('data', (d) => { raw += d; if (raw.length > 500000) req.destroy(); });+ req.on('end', () => {+ let body = {}; try { body = JSON.parse(raw); } catch {}+ try {+ const x = exportMap(Array.isArray(body.include) ? body.include.map(String) : EXPORT_DEFAULT, cleanFlows(body.flows));+ res.writeHead(200, { 'Content-Type': TYPES['.html'], 'Content-Disposition': `attachment; filename="${x.name}"`, 'Cache-Control': 'no-store' });+ res.end(x.html);+ } catch (e) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: e.message })); }+ });+ return;+ }if (req.method === 'POST' && url.pathname === '/api/ask') {let raw = '';req.on('data', (d) => { raw += d; if (raw.length > 20000) req.destroy(); });diff --git a/skills/floorplan/assets/ui/06-blueprint.js b/skills/floorplan/assets/ui/06-blueprint.jsindex 1c29414..991d6e2 100644--- a/skills/floorplan/assets/ui/06-blueprint.js+++ b/skills/floorplan/assets/ui/06-blueprint.js@@ -38,7 +38,7 @@SC.addPanelSection('overview', () => ({html: `<div class="sec"><h3>Blueprint</h3>- <p class="pd">Planned${BP.source ? ` from <b>${h(BP.source)}</b>` : ''}, not built yet. Every dashed card is a part the system would need. Pick one and choose <b>Build this with ${h(A.name)}</b> to start on it.</p>+ <p class="pd">Planned${BP.source ? ` from <b>${h(BP.source)}</b>` : ''}, not built yet. Every dashed card is a part the system would need.${SC.exported ? '' : ` Pick one and choose <b>Build this with ${h(A.name)}</b> to start on it.`}</p>${BP.stack?.length ? `<div class="tags" style="margin-top:10px">${BP.stack.map((s) => `<span class="tag">${h(s)}</span>`).join('')}</div>` : ''}${BP.assumptions?.length ? `<h3 style="margin-top:14px">Assumptions</h3><ul class="bp-list">${BP.assumptions.map((a) => `<li>${h(a)}</li>`).join('')}</ul>` : ''}</div>`,@@ -80,11 +80,11 @@if (id.startsWith('r:')) {const r = SC.routes[+id.slice(2)];if (!r) return '';- const text = !r.access ? 'Not decided yet. The design review lists it.' : `${Cap(r.access === 'signed-in' && r.who ? r.who : ACCESS[r.access] || r.access)}.${r.publicBecause ? ` Open on purpose: ${r.publicBecause}` : ''}`;+ const text = !r.access ? `Not decided yet.${SC.graph.health ? ' The design review lists it.' : ''}` : `${Cap(r.access === 'signed-in' && r.who ? r.who : ACCESS[r.access] || r.access)}.${r.publicBecause ? ` Open on purpose: ${r.publicBecause}` : ''}`;return `<div class="sec"><h3>Who may use it</h3><p class="pd">${h(text)}</p></div>`;}const i = SC.info(id);- if (!i || (i.type === 'node' && i.n.kind === 'external') || !filesIn(id).length) return '';+ if (SC.exported || !i || (i.type === 'node' && i.n.kind === 'external') || !filesIn(id).length) return '';return {html: `<div class="sec"><h3>Build it</h3><p class="pd">A ready request for ${h(A.app)} to build ${i.type === 'file' ? 'this file' : 'this part'} the way the plan describes.</p><div class="actions"><button class="btn soft" data-bp-build>${SC.iconI('spark')}Build this with ${h(A.name)}</button></div></div>`,diff --git a/skills/floorplan/assets/ui/20-health.js b/skills/floorplan/assets/ui/20-health.jsindex 71b4e65..67e691f 100644--- a/skills/floorplan/assets/ui/20-health.js+++ b/skills/floorplan/assets/ui/20-health.js@@ -3,7 +3,8 @@// prompt to paste into Claude Code or Codex. Talks to the viewer only through window.Floorplan.(() => {const SC = window.Floorplan;- if (!SC) return;+ // an exported copy without Health leaves the button out: an empty list would read as "all clear"+ if (!SC || (SC.exported && !SC.graph.health)) return;const { h } = SC;const A = SC.agent || { name: 'Claude', app: 'Claude Code' };const issues = (SC.graph.health && SC.graph.health.issues) || [];@@ -85,7 +86,7 @@${locText(issue)}<div class="hc-a">${onMap(issue) ? `<button class="btn soft" data-hc-show="${idx}">${SC.iconI('search')}Show on map</button>` : ''}- ${here(issue) ? `<button class="btn soft" data-hc-here="${idx}">${SC.iconI('spark')}Resolve on the map</button>` : `<button class="btn soft" data-hc-fix="${idx}">${SC.iconI('spark')}${FIX} with ${A.name}</button>`}+ ${SC.exported ? '' : here(issue) ? `<button class="btn soft" data-hc-here="${idx}">${SC.iconI('spark')}Resolve on the map</button>` : `<button class="btn soft" data-hc-fix="${idx}">${SC.iconI('spark')}${FIX} with ${A.name}</button>`}</div></div>`;const bindIssues = (el) => {@@ -108,7 +109,7 @@const list = issues.map((i, idx) => [i, idx]).filter(([i]) => i.severity === sev);return list.length ? `<div class="sec"><h3>${h(SEV[sev].group)} <span class="c">${list.length}</span></h3>${list.map(([i, idx]) => issueHtml(i, idx)).join('')}</div>` : '';}).join('');- const foot = !issues.length ? '' : `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. ${issues.some(here)+ const foot = !issues.length ? '' : SC.exported ? `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints from when this copy was exported.</div>` : `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. ${issues.some(here)? `“Resolve on the map” puts a request in the Ask bar’s Change mode: finish or edit it, press Enter, and ${A.name} updates the plan and redraws the map. Undo puts it back.`: `“${FIX} with ${A.name}” gives you a request to paste into ${A.app}; ${PLAN ? 'it explains the choice and updates the plan once you decide' : 'it checks the code before changing anything'}.`}</div>`;return top + groups + foot;diff --git a/skills/floorplan/assets/ui/60-export.js b/skills/floorplan/assets/ui/60-export.jsnew file mode 100644index 0000000..3eb1d76--- /dev/null+++ b/skills/floorplan/assets/ui/60-export.js@@ -0,0 +1,83 @@+// Export: a copy of the map to share as one HTML file, for people without Claude or Codex. The map's server+// (serve.mjs) builds it: the same page without the Ask bar, requests for Claude or Codex, or links into this+// computer, plus the extras ticked here. Talks to the viewer only through window.Floorplan.+(() => {+ const SC = window.Floorplan;+ if (!SC || SC.exported) return;+ const S = window.FLOORPLAN_SERVER;+ // opened in the Claude app: there's no map folder to export from+ if (!S && location.protocol !== 'file:') return;+ const { h } = SC;+ const G = SC.graph;+ const PLAN = !!G.meta.blueprint;+ const CMD = 'node floorplan/serve.mjs --export';++ const style = document.createElement('style');+ style.textContent = `+.xp-opts { display: flex; flex-direction: column; gap: 2px; margin: 14px 0 4px; }+.xp-opt { display: flex; gap: 12px; align-items: flex-start; padding: 10px 12px; border-radius: 12px; cursor: pointer; }+.xp-opt:hover { background: rgba(var(--ink), .05); }+.xp-opt input { margin: 3px 0 0; width: 16px; height: 16px; accent-color: var(--accent); flex: none; cursor: pointer; }+.xp-opt b { display: block; font-weight: 500; color: var(--text); }+.xp-opt span { display: block; font-size: 12.5px; color: var(--text-3); line-height: 1.5; }+.xp-opt.warn span { color: var(--warn-text); }+.xp-note { font-size: 12.5px; color: var(--text-3); line-height: 1.55; margin-top: 10px; }+.xp-err { font-size: 12.5px; color: var(--warn-text); background: var(--warn-bg); border-radius: 10px; padding: 8px 12px; margin-top: 10px; }+`;+ document.head.appendChild(style);+ SC.icons.export = '<path d="M12 15V4M7.5 8.5 12 4l4.5 4.5"/><path d="M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/>';++ // only what this map has; the extras that say how the app could be attacked are off unless ticked+ const PARTS = [+ { id: 'flows', label: 'Flows and the tour', hint: 'The guided walkthroughs, including ones you requested.', on: true, has: G.flows.length > 0 || (G.tour || []).length > 0 },+ { id: 'notes', label: 'Notes pinned to files', hint: 'The notes shown on file cards.', on: true, has: G.files.some((f) => f.note) },+ { id: 'recent', label: 'Recent work', hint: 'What was just changed, and why.', on: false, has: !!G.recent?.items?.length },+ PLAN+ ? { id: 'health', label: 'Design review', hint: 'The decisions the plan still leaves open.', on: false, has: !!G.health?.issues?.length }+ : { id: 'health', label: 'Health check', hint: 'Lists the endpoints anyone can use and where secrets sit in the code (never their values). Only include it for people you trust.', on: false, warn: true, has: !!G.health?.issues?.length },+ ].filter((p) => p.has);++ async function download(el, close) {+ const err = el.querySelector('.xp-err');+ const include = [...el.querySelectorAll('[data-xp]')].filter((c) => c.checked).map((c) => c.dataset.xp);+ // flows requested since the map was last built live only on this page so far+ const flows = G.flows.filter((f) => f.custom).map((f) => ({ id: f.id, title: f.title, description: f.description, steps: f.steps }));+ try {+ const r = await fetch('/api/export', { method: 'POST', headers: { 'content-type': 'application/json', 'x-floorplan-token': S.token }, body: JSON.stringify({ include, flows }) });+ if (r.status === 403) throw new Error('The map’s server has restarted since this page opened. Reload the page and try again.');+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The map’s server couldn’t export it.');+ const name = /filename="([^"]+)"/.exec(r.headers.get('content-disposition') || '')?.[1] || 'floorplan-map.html';+ const a = document.createElement('a');+ a.href = URL.createObjectURL(await r.blob());+ a.download = name;+ document.body.appendChild(a); a.click(); a.remove();+ setTimeout(() => URL.revokeObjectURL(a.href), 30000);+ close();+ SC.toast(`Downloaded ${name}`);+ } catch (e) {+ err.hidden = false;+ err.textContent = e.message === 'Failed to fetch' ? 'Couldn’t reach the map’s server. Ask Claude or Codex to open the floorplan again, then try again.' : e.message;+ }+ }++ function openExport() {+ if (!S) {+ SC.modal({+ title: 'Export a copy',+ html: `<p>Exporting needs the map’s server. Ask Claude or Codex to “export the floorplan”, or run this in the project folder:</p><pre>${h(CMD)}</pre>`,+ actions: [{ label: 'Copy command', primary: true, icon: 'copy', onClick: () => { SC.copy(CMD); SC.toast('Copied'); } }],+ });+ return;+ }+ const m = SC.modal({+ title: 'Export a copy',+ html: `<p>One HTML file with the whole map, to send to anyone. It opens in any browser with nothing to install, and has no Ask bar.</p>+ ${PARTS.length ? `<div class="xp-opts">${PARTS.map((p) => `<label class="xp-opt${p.warn ? ' warn' : ''}"><input type="checkbox" data-xp="${p.id}"${p.on ? ' checked' : ''}><div><b>${h(p.label)}</b><span>${h(p.hint)}</span></div></label>`).join('')}</div>` : ''}+ <p class="xp-note">It shows how ${h(G.project.name)} is put together: every part, file and endpoint, and the names of the functions inside, but not the code itself.</p>+ <div class="xp-err" hidden></div>`,+ actions: [{ label: 'Download', primary: true, icon: 'export', keepOpen: true, onClick: (close) => { download(m.el, close); } }],+ });+ }++ SC.addHeaderButton({ id: 'btn-export', label: 'Export', icon: 'export', title: 'Export a copy of this map to share', onClick: openExport });+})();diff --git a/skills/floorplan/assets/viewer.html b/skills/floorplan/assets/viewer.htmlindex 0e56be4..f751637 100644--- a/skills/floorplan/assets/viewer.html+++ b/skills/floorplan/assets/viewer.html@@ -318,6 +318,8 @@ body.no-panel #panel { transform: translateX(24px) scale(.98); opacity: 0; pointbody.resizing #panel-resize::after { background: rgba(var(--ink), .4); }body.resizing, body.resizing * { cursor: ew-resize !important; user-select: none; }body.resizing #panel, body.resizing #ask, body.resizing #flowbar { transition: none; }+body.exported #ask { display: none; }+.xtag { font-size: 11.5px; font-weight: 500; color: var(--text-3); background: rgba(var(--ink), .06); border-radius: 999px; padding: 3px 9px; margin-left: 8px; white-space: nowrap; cursor: default; }body.no-panel #panel-resize { opacity: 0; pointer-events: none; }#panel::-webkit-scrollbar { width: 12px; } #panel::-webkit-scrollbar-thumb { background: rgba(var(--ink), .1); border-radius: 10px; border: 4px solid transparent; background-clip: padding-box; }#panel > * { animation: panelIn .4s var(--ease) both; }@@ -536,6 +538,8 @@ const Cap = (t) => t[0].toUpperCase() + t.slice(1);if (!G) { document.body.innerHTML = '<p style="padding:2rem">No data. Run build.mjs.</p>'; return; }// a blueprint: planned from a PRD, so its files don't exist yet (no line counts, nothing to open in an editor)const PLAN = !!G.meta.blueprint;+// an exported copy (serve.mjs --export, or the Export button): read-only, for people without Claude or Codex+const EXPORTED = G.meta.exported || null;if (typeof ELK === 'undefined') { document.body.innerHTML = '<p style="padding:2rem">Could not load the ELK layout engine. Rebuild the map with build.mjs.</p>'; return; }const NS = 'http://www.w3.org/2000/svg';@@ -1111,7 +1115,7 @@ function itemMenu(id) {id.startsWith('x:') ? { label: `Go to ${i.name}`, icon: 'right', hint: '2×click', run: () => reveal(real) }: drillable(real) && state.container !== real ? { label: 'Open', icon: 'drill', hint: '2×click', run: () => open(real) } : null,state.container === 'q:answer' && !id.startsWith('x:') ? { label: 'Show on the map', icon: 'external', run: () => reveal(real) } : null,- { label: 'Ask about this', icon: 'spark', run: () => addAskContext(real) },+ EXPORTED ? null : { label: 'Ask about this', icon: 'spark', run: () => addAskContext(real) },{ label: 'Show details', icon: 'panel', run: () => { setPanel(true); if (id.startsWith('x:')) reveal(real); else select(id); } },'-',path ? { label: i.type === 'route' ? 'Copy endpoint' : 'Copy path', icon: 'copy', run: () => copy(path) } : null,@@ -1123,7 +1127,7 @@ function edgeMenu(e) {const ep = (x) => x.startsWith('x:') ? connEntity(x) : x.startsWith('m:') ? 'f:' + x.slice(2) : x;return [{ title: `${nameOf(e.a)} → ${nameOf(e.b)}` },- { label: 'Ask about this connection', icon: 'spark', run: () => { addAskContext(ep(e.a)); addAskContext(ep(e.b)); } },+ EXPORTED ? null : { label: 'Ask about this connection', icon: 'spark', run: () => { addAskContext(ep(e.a)); addAskContext(ep(e.b)); } },{ label: 'Show details', icon: 'panel', run: () => { setPanel(true); select({ edge: e.id }); } },'-',{ label: `Go to ${nameOf(e.a)}`, icon: 'left', run: () => reveal(ep(e.a)) },@@ -1137,7 +1141,7 @@ function canvasMenu() {state.container !== 'root' ? { label: 'Back to overview', icon: 'home', run: () => go('root') } : null,'-',{ label: 'Search', icon: 'search', hint: '/', run: openPalette },- { label: 'Ask about this view', icon: 'spark', run: () => { if (state.container !== 'root' && state.container !== 'q:answer') addAskContext(state.container); askInput.focus(); } },+ EXPORTED ? null : { label: 'Ask about this view', icon: 'spark', run: () => { if (state.container !== 'root' && state.container !== 'q:answer') addAskContext(state.container); askInput.focus(); } },];}svg.addEventListener('contextmenu', (ev) => { ev.preventDefault(); hideTip(); openMenu(ev, canvasMenu()); });@@ -1575,14 +1579,14 @@ $('#search-btn').onclick = openPalette;const fm = $('#flowmenu');fm.addEventListener('click', (ev) => ev.stopPropagation());function renderFlowMenu() {- fm.innerHTML = G.flows.map((f) => f.custom+ fm.innerHTML = G.flows.map((f) => f.custom && !EXPORTED? `<div class="r custom" data-flow="${h(f.id)}"><div class="rt"><b>${h(f.title)}<span class="yours">yours</span></b><span>${f.steps.length} steps${f.description ? ' · ' + h(f.description) : ''}</span></div><button class="del" data-del="${h(f.id)}" title="Delete flow">${iconI('x')}</button></div>`: `<div class="r" data-flow="${h(f.id)}"><b>${h(f.title)}</b><span>${f.steps.length} steps${f.description ? ' · ' + h(f.description) : ''}</span></div>`).join('')- + (G.flows.length ? '<div class="mi-sep"></div>' : '')- + `<div class="r new" data-new>${iconI('spark')}<b>Request a new flow…</b></div>`;+ + (EXPORTED ? (G.flows.length ? '' : '<div class="r" style="cursor:default"><span>No flows in this copy.</span></div>') : (G.flows.length ? '<div class="mi-sep"></div>' : '')+ + `<div class="r new" data-new>${iconI('spark')}<b>Request a new flow…</b></div>`);fm.querySelectorAll('[data-flow]').forEach((r) => r.onclick = () => { fm.classList.remove('open'); startFlow(r.dataset.flow); });fm.querySelectorAll('[data-del]').forEach((b) => b.onclick = (ev) => { ev.stopPropagation(); deleteCustomFlow(b.dataset.del); });- fm.querySelector('[data-new]').onclick = showFlowForm;+ const nf = fm.querySelector('[data-new]'); if (nf) nf.onclick = showFlowForm;}function showFlowForm() {fm.innerHTML = `<form class="ff"><label>Describe what to trace, and ${AGENT.name} builds a step-by-step flow through the map.</label>@@ -2009,12 +2013,21 @@ async function submitAsk() {}$('#ask-form').addEventListener('submit', (ev) => { ev.preventDefault(); submitAsk(); });askSend.addEventListener('click', (ev) => { if (askState.busy) { ev.preventDefault(); cancelAsk(); } });-detectEngine();+if (!EXPORTED) detectEngine();renderFlowMenu();-loadCustomFlows();+if (!EXPORTED) loadCustomFlows();// ======================= boot =======================$('#proj-name').textContent = G.project.name;+if (EXPORTED) {+ document.body.classList.add('exported');+ const at = new Date(EXPORTED.at);+ const tag = document.createElement('span');+ tag.className = 'xtag';+ tag.textContent = isNaN(at) ? 'Exported copy' : `Exported ${at.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}`;+ tag.title = 'A copy of this map to look around in. Asking questions needs Floorplan with Claude Code or Codex, in the codebase itself.';+ $('#proj-name').after(tag);+}document.title = `${G.project.name} map`;$('#btn-up').onclick = up;// drag the panel's left edge to resize it; the width sticks between visits@@ -2095,7 +2108,7 @@ const custom = { panel: null };function emit(event, data) { for (const fn of ext.listeners[event] || []) { try { fn(data); } catch (e) { console.error('floorplan extension', e); } } }window.Floorplan = Object.freeze({version: 1,- graph: G, query: Q, state, agent: AGENT,+ graph: G, query: Q, state, agent: AGENT, exported: EXPORTED,// model helpersinfo, chain, children: (id) => visibleKids(id), parentOf: (id) => parentOf.get(id), exists: (id) => Q.exists(id),files, nodes, routes, colorOf, iconKey,diff --git a/tests/export.test.mjs b/tests/export.test.mjsnew file mode 100644index 0000000..c26ab8f--- /dev/null+++ b/tests/export.test.mjs@@ -0,0 +1,134 @@+// Exporting a copy of the map to share: serve.mjs --export and the map's Export button (POST /api/export)+// write the same self-contained page, marked as exported, without this computer's details or the server's+// token, and with only the extras asked for. Health and recent work are left out unless asked for.+import { test, before, after } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { spawn, execFileSync } from 'node:child_process';+import { shopApp, run, readJson, writeJson, cleanup, FAKE_PASSWORD } from './helpers.mjs';++const TOKEN_IN_REMOTE = 'ghp-not-a-real-token-1234';+let root, server, base, token;+const serveJs = () => path.join(root, 'floorplan', 'serve.mjs');+/** The graph inside an exported page. */+const dataOf = (html) => JSON.parse(/<script>window\.FLOORPLAN = (.*?);<\/script>/s.exec(html)[1]);+/** Runs serve.mjs --export with these arguments; returns the exported page and what it printed. */+function exportCli(...args) {+ const out = execFileSync(process.execPath, [serveJs(), '--export', ...args], { cwd: root, encoding: 'utf8' });+ const file = /Exported the map to (.+)/.exec(out)[1].trim();+ return { out, html: fs.readFileSync(file, 'utf8'), file };+}++before(async () => {+ root = shopApp();+ execFileSync('git', ['-C', path.join(root, 'shop-api'), 'remote', 'add', 'origin', `https://someone:${TOKEN_IN_REMOTE}@example.com/shop-api.git`]);+ const arch = readJson(path.join(root, 'floorplan', 'architecture.json'));+ writeJson(path.join(root, 'floorplan', 'architecture.json'), {+ ...arch,+ annotations: [{ path: 'shop-api/config.js', note: 'Moving to the secrets manager next sprint.' }],+ flows: [{ id: 'refund', title: 'Refund', description: 'A customer asks for a refund.', steps: [{ node: 'web', note: 'The website asks.' }, { node: 'api', note: 'The server refunds.' }] }],+ });+ writeJson(path.join(root, 'floorplan', 'recent-work.json'), { tasks: [{ title: 'Refunds', summary: 'Added refunds.', items: [{ ref: 'shop-api/routes/orders.js', change: 'changed', note: 'Refund endpoint.' }] }] });+ run('scan.mjs', root);+ run('build.mjs', root, '--no-claude-md');++ const port = 20000 + Math.floor(Math.random() * 20000);+ server = spawn(process.execPath, [serveJs(), '--port', String(port), '--no-open'], {+ cwd: root, env: { ...process.env, FLOORPLAN_CLAUDE: path.join(root, 'no-such-cli'), FLOORPLAN_CODEX: path.join(root, 'no-such-cli'), FLOORPLAN_NO_PROMPTS: '1' }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ base = await new Promise((resolve, reject) => {+ let out = '';+ const timer = setTimeout(() => reject(new Error(`server didn't start: ${out}`)), 20000);+ server.stdout.on('data', (d) => { out += d; const m = /Floorplan: (http:\/\/\S+)/.exec(out); if (m) { clearTimeout(timer); resolve(m[1]); } });+ server.on('exit', (code) => reject(new Error(`server exited (${code}): ${out}`)));+ });+ token = /"token":"([0-9a-f]+)"/.exec(await (await fetch(base + '/')).text())[1];+});+after(async () => {+ if (server && server.exitCode === null) await new Promise((resolve) => { server.once('exit', resolve); server.kill(); });+ cleanup(root);+});++test('the map has health, recent work, a note, a flow and a remote to leave out', () => {+ const g = dataOf(fs.readFileSync(path.join(root, 'floorplan', 'index.html'), 'utf8'));+ assert.ok(g.health.issues.length > 0);+ assert.equal(g.recent.items.length, 1);+ assert.ok(g.files.some((f) => f.note));+ assert.equal(g.flows.length, 1);+ assert.ok(g.meta.root);+});++test('by default the export keeps flows and notes, and leaves out health, recent work and this computer', () => {+ const { html, file, out } = exportCli();+ assert.equal(path.basename(file), 'shop-map.html');+ assert.equal(path.dirname(file), path.join(fs.realpathSync(root), 'floorplan'));+ const g = dataOf(html);+ assert.match(g.meta.exported.at, /^\d{4}-\d\d-\d\dT/);+ assert.deepEqual(g.meta.exported.include, ['flows', 'notes']);+ assert.equal(g.health, undefined);+ assert.equal(g.recent, undefined);+ assert.equal(g.flows.length, 1);+ assert.ok(g.files.some((f) => f.note));+ assert.equal(g.meta.root, null);+ assert.ok(g.meta.repos.every((r) => !('remote' in r)));+ assert.ok(!html.includes(TOKEN_IN_REMOTE), 'no sign-in token from a git remote');+ const here = readJson(path.join(root, 'floorplan', 'graph.json')).meta.root;+ assert.ok(here && !html.includes(here), 'no folder path from this computer');+ assert.ok(!html.includes('FLOORPLAN_SERVER='), 'no server details');+ assert.match(out, /no Ask bar/);+ assert.doesNotMatch(out, /Share it only with people you trust/);+});++test('health and recent work go in only when asked for, with a warning about health', () => {+ const { html, out } = exportCli(path.join(root, 'all.html'), '--include', 'flows,notes,recent,health');+ const g = dataOf(html);+ assert.deepEqual(g.meta.exported.include, ['flows', 'notes', 'recent', 'health']);+ assert.ok(g.health.issues.length > 0);+ assert.equal(g.recent.items.length, 1);+ assert.match(out, /Share it only with people you trust/);+ // where a secret sits, never the secret itself+ assert.ok(!html.includes(FAKE_PASSWORD));+});++test('flows, the tour and notes can be left out too', () => {+ const { html } = exportCli(path.join(root, 'bare.html'), '--include', 'none');+ const g = dataOf(html);+ assert.deepEqual(g.meta.exported.include, []);+ assert.deepEqual(g.flows, []);+ assert.deepEqual(g.tour, []);+ assert.ok(g.files.every((f) => !('note' in f)));+});++test('the exported page is still the whole map, ready to open', () => {+ const { html } = exportCli(path.join(root, 'page.html'));+ const g = dataOf(html);+ const built = readJson(path.join(root, 'floorplan', 'graph.json'));+ assert.equal(g.files.length, built.files.length);+ assert.equal(g.routes.length, built.routes.length);+ assert.equal(g.links.length, built.links.length);+ assert.match(html, /^<!doctype html>/i);+ assert.match(html, /ui\/60-export\.js/);+});++const api = (body, headers = {}) => fetch(base + '/api/export', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });++test('the Export button needs the map page’s token', async () => {+ assert.equal((await api({ include: ['flows'] })).status, 403);+ assert.equal((await api({ include: ['flows'] }, { 'x-floorplan-token': 'wrong' })).status, 403);+});++test('the Export button downloads the copy, with flows requested since the last build', async () => {+ const extra = { id: 'custom-1', title: 'Admin deletes a user', description: '', steps: [{ ref: 'web', note: 'First.' }, { ref: 'api', note: 'Then.' }] };+ const r = await api({ include: ['flows', 'health'], flows: [extra, { id: 'bad', steps: 'nope' }] }, { 'x-floorplan-token': token });+ assert.equal(r.status, 200);+ assert.match(r.headers.get('content-type'), /text\/html/);+ assert.equal(r.headers.get('content-disposition'), 'attachment; filename="shop-map.html"');+ const g = dataOf(await r.text());+ assert.deepEqual(g.meta.exported.include, ['flows', 'health']);+ assert.deepEqual(g.flows.map((f) => f.id), ['refund', 'custom-1']);+ assert.equal(g.flows[1].custom, true);+ assert.ok(g.files.every((f) => !('note' in f)), 'notes weren’t ticked');+ assert.equal(g.recent, undefined);+ assert.ok(g.health);+});