From 5428745fbe937dea0261c7fcd320a72053eca042 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Mon, 16 Nov 2026 00:10:18 -0500 Subject: [PATCH] Keep the device-log reporter and endpoint out of production The playground's device reporter (phone-console errors and a capabilities "hello") lived as an inline script in index.html and beaconed to /__device-log on every page load, but that endpoint is dev server only. A production build shipped the beacon anyway, so every real page load fired a POST that 405s. Move the reporter into the nib-device-log Vite plugin, injected via transformIndexHtml, which (like the plugin's endpoint) is apply: "serve", so a production build carries neither the script nor any reference to the endpoint. Gate drag-trace.ts's dynamic import the same way: it also beacons to /__device-log, and editor.ts (production code) imports it behind a query param that a real visitor could still set. --- packages/app/playground/editor.ts | 5 ++- packages/app/playground/index.html | 40 ++------------------ packages/app/playground/vite.config.ts | 51 +++++++++++++++++++++++++- packages/app/tests/device-log.test.ts | 45 +++++++++++++++++++++++ 4 files changed, 102 insertions(+), 39 deletions(-) create mode 100644 packages/app/tests/device-log.test.ts diff --git a/packages/app/playground/editor.ts b/packages/app/playground/editor.ts index a4bf7a1..599e04d 100644 --- a/packages/app/playground/editor.ts +++ b/packages/app/playground/editor.ts @@ -74,7 +74,10 @@ export function startEditor({ platform, header, ask, importRepo, demo, route, op if (params.has("desktop")) shell.mode = "desktop"; document.body.append(shell); - if (params.has("dragtrace")) void import("./drag-trace.ts").then(({ traceDrags }) => traceDrags(shell)); + // Dev only: traceDrags posts to /__device-log, which a production origin has no server for. + // import.meta.env.DEV is a build-time constant, so Vite drops this branch, and drag-trace.ts + // with it, from a production build. + if (import.meta.env.DEV && params.has("dragtrace")) void import("./drag-trace.ts").then(({ traceDrags }) => traceDrags(shell)); // A sandbox lives as long as the files it runs: saving or forking keeps them, and opening another // project replaces them. The first waits for the address's project to open, so the demo shown while it diff --git a/packages/app/playground/index.html b/packages/app/playground/index.html index f8dbf05..9b4747d 100644 --- a/packages/app/playground/index.html +++ b/packages/app/playground/index.html @@ -22,43 +22,9 @@ - + diff --git a/packages/app/playground/vite.config.ts b/packages/app/playground/vite.config.ts index ed72243..ea11669 100644 --- a/packages/app/playground/vite.config.ts +++ b/packages/app/playground/vite.config.ts @@ -4,14 +4,63 @@ import { clientMetadata } from "@nibling/sdk/metadata"; import { createServer, defineConfig, type Plugin, type ViteDevServer } from "vite"; import wasm from "vite-plugin-wasm"; +/** + * The playground's device reporter: posts errors and a capabilities "hello" to `/__device-log`, + * since a phone has no console. Injected into index.html by `deviceLog` below, dev server only, so a + * production build carries neither this script nor any reference to the endpoint (it 405s there, + * since `deviceLog` is `apply: "serve"`). + */ +const DEVICE_REPORTER_SCRIPT = ` + (() => { + const send = (kind, data) => + navigator.sendBeacon?.("/__device-log", JSON.stringify({ kind, ...data })) || + fetch("/__device-log", { method: "POST", body: JSON.stringify({ kind, ...data }) }); + addEventListener("error", (e) => send("error", { message: e.message, source: e.filename, line: e.lineno, col: e.colno, stack: e.error?.stack })); + addEventListener("unhandledrejection", (e) => send("rejection", { message: String(e.reason?.message ?? e.reason), stack: e.reason?.stack })); + const probe = document.createElement("div"); + let states = false; + try { states = CSS.supports("selector(:state(x))"); } catch {} + send("hello", { + ua: navigator.userAgent, + viewport: [innerWidth, innerHeight], + coarse: matchMedia("(pointer: coarse)").matches, + states, + internals: "attachInternals" in HTMLElement.prototype, + ariaElementRefs: "ariaControlsElements" in probe, + manualSlots: "assign" in HTMLSlotElement.prototype, + lightDark: CSS.supports("color", "light-dark(red, blue)"), + containerQueries: CSS.supports("container-type", "size"), + visualViewport: "visualViewport" in window, + }); + addEventListener("load", () => + setTimeout(() => { + const shell = document.querySelector("nib-shell"); + send("load", { + defined: !!customElements.get("nib-shell"), + shadow: !!shell?.shadowRoot, + children: shell?.shadowRoot?.childElementCount ?? 0, + compact: (() => { try { return shell.matches(":state(compact)"); } catch (e) { return String(e); } })(), + size: shell && [shell.clientWidth, shell.clientHeight], + }); + }, 1500), + ); + })(); +`; + /** * Prints what the playground's device reporter posts, so errors on a phone (where there's no - * console to open) show up in the dev server's output. Dev server only. + * console to open) show up in the dev server's output. Dev server only: both the `/__device-log` + * endpoint and the reporter script it serves into index.html exist only here, never in a build. */ function deviceLog(): Plugin { return { name: "nib-device-log", apply: "serve", + transformIndexHtml(_html, ctx) { + // Only the app shell's index.html carries the reporter, as before; frame/docs/code/kernel do not. + if (!ctx.filename.endsWith("/index.html")) return; + return [{ tag: "script", injectTo: "body-prepend", children: DEVICE_REPORTER_SCRIPT }]; + }, configureServer(server) { server.middlewares.use("/__device-log", (req, res) => { let body = ""; diff --git a/packages/app/tests/device-log.test.ts b/packages/app/tests/device-log.test.ts new file mode 100644 index 0000000..6c5fd43 --- /dev/null +++ b/packages/app/tests/device-log.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { test } from 'node:test'; + +const appDir = fileURLToPath(new URL('..', import.meta.url)); + +/** + * The playground's device reporter (and its `/__device-log` endpoint) exist only in the dev server + * (the `nib-device-log` Vite plugin is `apply: "serve"`, and the reporter script is injected by that + * plugin's `transformIndexHtml`, not written into index.html). A production build must carry neither: + * the endpoint 405s outside dev, so shipping the beacon would fill every real visitor's console. + */ +test('vite build emits neither the device-log script nor any /__device-log reference', { timeout: 120_000 }, () => { + const outDir = mkdtempSync(join(tmpdir(), 'nib-app-build-')); + try { + execFileSync('npx', ['vite', 'build', 'playground', '--outDir', outDir, '--emptyOutDir'], { + cwd: appDir, + stdio: 'pipe', + }); + + const files = allFiles(outDir); + assert.ok(files.length > 0, 'expected the build to emit files'); + for (const file of files) { + const text = readFileSync(file, 'utf8'); + assert.ok(!text.includes('__device-log'), `${file} references /__device-log`); + assert.ok(!text.includes('traceDrags'), `${file} bundles the drag-trace debugging aid`); + } + } finally { + rmSync(outDir, { recursive: true, force: true }); + } +}); + +function allFiles(dir: string): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir)) { + const path = join(dir, entry); + if (statSync(path).isDirectory()) out.push(...allFiles(path)); + else out.push(path); + } + return out; +} -- knotmirror 0.0.1