@hansenexus/hud 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/README.md +782 -6
  2. package/dist/a11y-B5DUaiCs.js +246 -0
  3. package/dist/a11y-panel-p_t4eD7p.js +207 -0
  4. package/dist/access-C7zlaqj6.js +100 -0
  5. package/dist/access-D_ewAEJG.d.ts +61 -0
  6. package/dist/access-panel-CEfTr9ZI.js +123 -0
  7. package/dist/adapter-BYoxPYTI.d.ts +33 -0
  8. package/dist/adapter-hcwmJtNx.js +65 -0
  9. package/dist/auto/runtime.d.ts +65 -0
  10. package/dist/auto/runtime.js +50 -0
  11. package/dist/auto.d.ts +15 -0
  12. package/dist/auto.js +33 -0
  13. package/dist/capabilities-rDSKjXpq.js +110 -0
  14. package/dist/capture-CwrIwLqi.js +300 -0
  15. package/dist/capture-buffer-Bbbo6omF.d.ts +35 -0
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +275 -0
  18. package/dist/data-panel-DhxAmP91.js +817 -0
  19. package/dist/data-store-ChF1td_P.js +164 -0
  20. package/dist/define-hud-CHPedaQ5.d.ts +50 -0
  21. package/dist/design-D0kGgPoP.js +87 -0
  22. package/dist/detect-BxHZ0pxW.d.ts +25 -0
  23. package/dist/detect-CHZiSeZs.js +63 -0
  24. package/dist/dispatch-panel-B-xr_Giy.js +279 -0
  25. package/dist/env-CApnbI0r.d.ts +19 -0
  26. package/dist/env-CaiFPIhF.js +31 -0
  27. package/dist/file-xdSaQ2uR.js +103 -0
  28. package/dist/flags-DVtaJ8pQ.d.ts +58 -0
  29. package/dist/flags.d.ts +2 -0
  30. package/dist/flags.js +82 -0
  31. package/dist/force-state-BaqWsmrf.js +153 -0
  32. package/dist/force-state-CCqoTfVB.d.ts +23 -0
  33. package/dist/force-state-panel-_otVYh9i.js +97 -0
  34. package/dist/generate-C8lQl3Eh.js +53 -0
  35. package/dist/handler-BpVhxEmU.js +106 -0
  36. package/dist/handler-DtYVCZY6.d.ts +39 -0
  37. package/dist/index-BAV_1W8a.d.ts +43 -0
  38. package/dist/index-BJ26pse9.d.ts +70 -0
  39. package/dist/index-BnQ0dTZf.d.ts +19 -0
  40. package/dist/index-CwfX-W87.d.ts +72 -0
  41. package/dist/index-DcH9V3cU.d.ts +48 -0
  42. package/dist/index-DqOyNf1u.d.ts +65 -0
  43. package/dist/index-DstI_ike.d.ts +66 -0
  44. package/dist/index-Dxz4fn4j.d.ts +42 -0
  45. package/dist/index-Hhh7OXzU.d.ts +129 -0
  46. package/dist/index-ReFbhQ9p.d.ts +25 -0
  47. package/dist/index-RgXfMBuW.d.ts +48 -0
  48. package/dist/index-gCZBO53s.d.ts +73 -0
  49. package/dist/index.d.ts +6 -36
  50. package/dist/index.js +798 -240
  51. package/dist/inspect-C9Ft8fqn.js +142 -0
  52. package/dist/inspect-root-BkaupBMp.js +429 -0
  53. package/dist/marker-C66LxOhJ.d.ts +9 -0
  54. package/dist/marker-CMrvxPmS.d.ts +12 -0
  55. package/dist/marker-DjeGvL-F.js +9 -0
  56. package/dist/marker-uZYPOJ4M.js +12 -0
  57. package/dist/markers.d.ts +3 -0
  58. package/dist/markers.js +3 -0
  59. package/dist/meta-Bv0sEao3.js +6 -0
  60. package/dist/meta-C_G7MB5w.d.ts +49 -0
  61. package/dist/mocks-CA-wM2SB.d.ts +109 -0
  62. package/dist/mocks-ESiRqk9o.js +150 -0
  63. package/dist/msw-browser-wjaYgkB7.d.ts +31 -0
  64. package/dist/next/config.d.ts +52 -0
  65. package/dist/next/config.js +78 -0
  66. package/dist/next.d.ts +14 -19
  67. package/dist/next.js +7 -30
  68. package/dist/observe-CdDnDBRP.js +89 -0
  69. package/dist/observe-panel-Cgp1M8oT.js +347 -0
  70. package/dist/ops-panel-CEqDe_UT.js +234 -0
  71. package/dist/payload-MUQ9ciER.d.ts +92 -0
  72. package/dist/plugins/a11y.d.ts +2 -0
  73. package/dist/plugins/a11y.js +2 -0
  74. package/dist/plugins/access/server.d.ts +122 -0
  75. package/dist/plugins/access/server.js +340 -0
  76. package/dist/plugins/access.d.ts +41 -0
  77. package/dist/plugins/access.js +51 -0
  78. package/dist/plugins/agent/server.d.ts +94 -0
  79. package/dist/plugins/agent/server.js +455 -0
  80. package/dist/plugins/agent.d.ts +37 -0
  81. package/dist/plugins/agent.js +69 -0
  82. package/dist/plugins/capture/server.d.ts +92 -0
  83. package/dist/plugins/capture/server.js +248 -0
  84. package/dist/plugins/capture.d.ts +24 -0
  85. package/dist/plugins/capture.js +70 -0
  86. package/dist/plugins/data/msw-browser.d.ts +2 -0
  87. package/dist/plugins/data/msw-browser.js +39 -0
  88. package/dist/plugins/data/msw-node.d.ts +36 -0
  89. package/dist/plugins/data/msw-node.js +68 -0
  90. package/dist/plugins/data/server.d.ts +257 -0
  91. package/dist/plugins/data/server.js +717 -0
  92. package/dist/plugins/data.d.ts +6 -0
  93. package/dist/plugins/data.js +51 -0
  94. package/dist/plugins/design/server.d.ts +54 -0
  95. package/dist/plugins/design/server.js +198 -0
  96. package/dist/plugins/design.d.ts +5 -0
  97. package/dist/plugins/design.js +4 -0
  98. package/dist/plugins/inspect/convex.d.ts +2 -0
  99. package/dist/plugins/inspect/convex.js +486 -0
  100. package/dist/plugins/inspect/react-query.d.ts +2 -0
  101. package/dist/plugins/inspect/react-query.js +225 -0
  102. package/dist/plugins/inspect/sockets.d.ts +51 -0
  103. package/dist/plugins/inspect/sockets.js +397 -0
  104. package/dist/plugins/inspect/swr.d.ts +2 -0
  105. package/dist/plugins/inspect/swr.js +218 -0
  106. package/dist/plugins/inspect.d.ts +4 -0
  107. package/dist/plugins/inspect.js +3 -0
  108. package/dist/plugins/observe.d.ts +4 -0
  109. package/dist/plugins/observe.js +2 -0
  110. package/dist/plugins/ops/server.d.ts +82 -0
  111. package/dist/plugins/ops/server.js +381 -0
  112. package/dist/plugins/ops.d.ts +27 -0
  113. package/dist/plugins/ops.js +41 -0
  114. package/dist/plugins/routes/server.d.ts +88 -0
  115. package/dist/plugins/routes/server.js +62 -0
  116. package/dist/plugins/routes.d.ts +3 -0
  117. package/dist/plugins/routes.js +216 -0
  118. package/dist/plugins/seo.d.ts +2 -0
  119. package/dist/plugins/seo.js +2 -0
  120. package/dist/plugins/vitals.d.ts +2 -25
  121. package/dist/plugins/vitals.js +4 -86
  122. package/dist/plugins-BZvDqGx5.d.ts +144 -0
  123. package/dist/{plugins-CzUiTn_r.js → plugins-DVy_vaYr.js} +3 -1
  124. package/dist/poll-CjKsWZi8.js +89 -0
  125. package/dist/requests-BwD6MKEq.js +282 -0
  126. package/dist/requests-CJrUf465.d.ts +50 -0
  127. package/dist/review.d.ts +181 -0
  128. package/dist/review.js +1017 -0
  129. package/dist/same-origin-BGet22CC.js +21 -0
  130. package/dist/scan-DzJNXqOk.js +165 -0
  131. package/dist/selector-NSYSe7AZ.js +28 -0
  132. package/dist/seo-Dq9q_QkO.js +551 -0
  133. package/dist/seo-panel-CfiY-TnT.js +124 -0
  134. package/dist/server.d.ts +3 -39
  135. package/dist/server.js +2 -105
  136. package/dist/sessions-panel-COvhPAzv.js +98 -0
  137. package/dist/shortcut-s_mjGeU8.js +179 -0
  138. package/dist/state-CjjZPjPJ.js +40 -0
  139. package/dist/state-boundary.d.ts +26 -0
  140. package/dist/state-boundary.js +61 -0
  141. package/dist/store/convex.d.ts +33 -0
  142. package/dist/store/convex.js +52 -0
  143. package/dist/store-CQqIIKTc.js +59 -0
  144. package/dist/store-Ync9eb1G.js +67 -0
  145. package/dist/store.d.ts +76 -0
  146. package/dist/store.js +188 -0
  147. package/dist/styles-BA8ueHoV.js +342 -0
  148. package/dist/styles-DKU_P8MH.js +139 -0
  149. package/dist/styles-DPpDPmzi.js +68 -0
  150. package/dist/tokens-panel-CbMQfasZ.js +142 -0
  151. package/dist/types-B-ulf2Jp.js +8 -0
  152. package/dist/types-BIgGf-0C.d.ts +25 -0
  153. package/dist/types-BIkI-qN8.js +30 -0
  154. package/dist/types-Cxh4twqc.d.ts +50 -0
  155. package/dist/types-DIdPfjtV.js +6 -0
  156. package/dist/types-DaJcsEjO.d.ts +44 -0
  157. package/dist/types-Dn68psVz.d.ts +118 -0
  158. package/dist/types-f3jlNxzw.d.ts +92 -0
  159. package/dist/types-szkr2QOF.d.ts +39 -0
  160. package/dist/unlock-store-4V3vR4Eg.js +96 -0
  161. package/dist/variant-groups-TIfO3NIj.js +137 -0
  162. package/dist/variant-groups-aAIrcNK5.d.ts +36 -0
  163. package/dist/variants-panel-BDoSkwBJ.js +457 -0
  164. package/dist/variants-types-CcRf119M.d.ts +63 -0
  165. package/dist/variants.d.ts +43 -0
  166. package/dist/variants.js +83 -0
  167. package/dist/vitals-panel-BCmMUntW.js +30 -0
  168. package/dist/vite.d.ts +37 -0
  169. package/dist/vite.js +134 -0
  170. package/package.json +85 -5
  171. package/dist/define-hud-BHQR8Lbv.d.ts +0 -31
  172. package/dist/plugins-1QmTmZyL.d.ts +0 -76
package/README.md CHANGED
@@ -3,8 +3,7 @@
3
3
  A dev HUD for React apps: a status pill and floating panels, rendered in a shadow root so a
4
4
  client site's CSS cannot touch it and it cannot touch the site.
5
5
 
6
- > Early. The element grabber is tracked in
7
- > [the PRD](https://github.com/hansenexus/hud/issues/1).
6
+ > Early. The roadmap is tracked in [the PRD](https://github.com/hansenexus/hud/issues/1).
8
7
 
9
8
  ## Develop
10
9
 
@@ -12,6 +11,7 @@ client site's CSS cannot touch it and it cannot touch the site.
12
11
  bun install
13
12
  bun run dev # playground on http://localhost:5173, HUD imported from source (HMR)
14
13
  bun run check # lint, typecheck, test, build
14
+ bun run test:e2e # Playwright against the playground (pill, overflow, drag, variants) and both fixtures (plugin routes, auto-config)
15
15
  ```
16
16
 
17
17
  The playground (`playground/`) is a fake client site with every element that has fought a dev
@@ -68,12 +68,206 @@ export const { GET, POST, PUT, PATCH, DELETE } = createHudHandler([/* plugins/<i
68
68
  `createHudHandler` answers 404 to everything unless `NODE_ENV` is `development`; pass `guard` to
69
69
  open deployed tiers deliberately. `HUD_DEV_MARKER` is rendered on the HUD root for a CI grep.
70
70
 
71
+ ## Use (Vite)
72
+
73
+ The same `hud.tsx`. The plugin routes come from `@hansenexus/hud/vite`: `hud()` runs
74
+ `createHudHandler` as dev-server middleware under `/api/hud/*`, ahead of Vite's own middlewares,
75
+ and is inert in `vite build` and `vite preview`:
76
+
77
+ ```ts
78
+ // vite.config.ts
79
+ import { ops } from "@hansenexus/hud/plugins/ops/server";
80
+ import { hud } from "@hansenexus/hud/vite";
81
+ import react from "@vitejs/plugin-react";
82
+ import { defineConfig } from "vite";
83
+
84
+ export default defineConfig({
85
+ plugins: [react(), hud({ plugins: [ops({ /* providers */ })] })],
86
+ });
87
+ ```
88
+
89
+ `hud()` takes the same `basePath`, `guard` and `can` as `createHudHandler`; the default guard
90
+ answers 404 unless `NODE_ENV` is `development`, which `vite dev` sets. `vite` is an optional peer
91
+ dependency (6 or newer).
92
+
93
+ A Vite client has no `process`, so gate the loader on `import.meta.env.DEV` and hand it the tier.
94
+ Both are literals Vite folds, so a production build drops the `import()` and emits no HUD chunk:
95
+
96
+ ```tsx
97
+ // src/hud-loader.tsx
98
+ import { createHudLoader } from "@hansenexus/hud/next";
99
+
100
+ export const HudLoader = createHudLoader(import.meta.env.DEV ? () => import("./hud") : null, {
101
+ env: import.meta.env.DEV ? "development" : "production",
102
+ });
103
+ ```
104
+
105
+ Without `env`, `resolveHudEnv()` answers `production` where `process` is missing, so no
106
+ `define: { "process.env.NEXT_PUBLIC_HUD_…" }` shim is needed. `fixtures/vite-app` is a complete
107
+ example, CI-gated like the Next fixture (see Bundle gate).
108
+
109
+ ## Auto-config (`@hansenexus/hud/auto`)
110
+
111
+ Instead of the hand-written plugin list, let the bundler pick plugins from the app's
112
+ dependencies. `@hansenexus/hud/auto` is a module the Vite plugin or the Next config wrapper
113
+ generates from `package.json` at build time, in dev and build alike; it imports only what the
114
+ dependencies call for, so an undetected plugin is not in the module graph at all (no chunk, in
115
+ dev or build). Hand it to `defineHud` as `auto`:
116
+
117
+ ```tsx
118
+ // hud.tsx
119
+ import { defineHud } from "@hansenexus/hud";
120
+ import { auto } from "@hansenexus/hud/auto";
121
+ import { ops } from "@hansenexus/hud/plugins/ops";
122
+
123
+ export default defineHud({
124
+ app: "my-app",
125
+ auto: auto({ convex }), // or just `auto`, when no detected adapter needs an instance
126
+ plugins: [ops()], // explicit: replaces a detected plugin with the same id, in place; the rest are appended
127
+ });
128
+ ```
129
+
130
+ What `auto` turns on:
131
+
132
+ | detected package | plugin |
133
+ | --------------------------------------------- | ----------------------------------------------------------------- |
134
+ | always | `vitals`, `observe`, `inspect`, `forceState` (states), `a11y`, `seo` |
135
+ | `next` | `routes` |
136
+ | `convex` | Convex tab of `inspect`; pass `auto({ convex: client })` |
137
+ | `@tanstack/react-query` | Query tab; pass `auto({ queryClient })` |
138
+ | `swr` | SWR tab; pass `auto({ swr: { cache, mutate } })` |
139
+ | `msw`, `better-auth`, `@convex-dev/auth` | `data` |
140
+
141
+ Any dependency section counts (`devDependencies` included). A detected adapter whose instance
142
+ was not passed shows a tab saying what to pass instead of hiding. `auto()` also takes `observe`,
143
+ `inspect` (`ignore`) and `a11y` options for the base plugins. Server halves stay explicit: mount
144
+ `routes()`, `dataServer()` and the rest in `createHudHandler` or `hud({ plugins })` as before.
145
+ Plugins that need server config or secrets (`access`, `ops`, `agent`, `capture`) are never picked;
146
+ list them in `plugins`.
147
+
148
+ Vite: `hud()` from `@hansenexus/hud/vite` (see above) serves the module and watches
149
+ `package.json`; nothing else to configure (`packageJson` overrides the path). Next: wrap the
150
+ config, which writes `.hud/auto.mjs` next to `package.json` on every start and aliases the
151
+ import for Turbopack and webpack. Add `.hud/auto.mjs` to `.gitignore`.
152
+
153
+ ```js
154
+ // next.config.js
155
+ import { withHud } from "@hansenexus/hud/next/config";
156
+
157
+ export default withHud({ reactStrictMode: true });
158
+ ```
159
+
160
+ Without either, `@hansenexus/hud/auto` resolves to the package's stand-in: the base plugins,
161
+ nothing dependency-driven, and a console warning once. `auto` works as the whole `plugins` value
162
+ too (`plugins: auto()`); `defineHud` needs one of `plugins` and `auto`.
163
+
164
+ ## Use (Hono, Bun.serve, any Fetch server)
165
+
166
+ `createHudHandler(...).handle` is a plain `(Request) => Promise<Response>`, so any server that
167
+ speaks Fetch mounts it. It checks `basePath` itself, so mount it at the same prefix:
168
+
169
+ ```ts
170
+ import { createHudHandler } from "@hansenexus/hud/server";
171
+
172
+ const hud = createHudHandler([/* plugins/<id>/server */]);
173
+
174
+ // Hono
175
+ app.all("/api/hud/*", (c) => hud.handle(c.req.raw));
176
+
177
+ // Bun.serve
178
+ Bun.serve({
179
+ fetch(request) {
180
+ if (new URL(request.url).pathname.startsWith("/api/hud/")) return hud.handle(request);
181
+ return app.fetch(request);
182
+ },
183
+ });
184
+ ```
185
+
186
+ The default guard applies here too: 404 unless `NODE_ENV` is `development`. Pass `guard`
187
+ (`accessGuard()` from the access plugin) to open a deployed tier. The client side is the Vite
188
+ loader above; an app served this way is a Vite app at build time.
189
+
190
+ ## Deployed tiers (access plugin)
191
+
192
+ Core assumes development: without the `access` plugin `defineHud` renders nothing on any other
193
+ tier and `createHudHandler` answers 404. To open preview, staging or production deliberately, add
194
+ both halves:
195
+
196
+ ```tsx
197
+ // hud.tsx
198
+ import { access } from "@hansenexus/hud/plugins/access";
199
+ export default defineHud({ app: "my-app", plugins: [access(), vitals()] });
200
+ ```
201
+
202
+ ```ts
203
+ // app/api/hud/[...hud]/route.ts
204
+ import { accessGuard, accessServer } from "@hansenexus/hud/plugins/access/server";
205
+
206
+ export const { GET, POST, PUT, PATCH, DELETE } = createHudHandler([accessServer(), /* ... */], {
207
+ guard: accessGuard(),
208
+ });
209
+ ```
210
+
211
+ The tier comes from the env ladder (`NEXT_PUBLIC_HUD_DISABLED` → `NODE_ENV` → `NEXT_PUBLIC_HUD_ENV`
212
+ → `VERCEL_ENV` → production). A deployed tier also needs `NEXT_PUBLIC_HUD_ENABLED=true` (in the
213
+ loader's build gate and on the server) and `HUD_ACCESS_PASSWORD`. Every plugin route then answers,
214
+ in this order:
215
+
216
+ | status | when |
217
+ | ------ | ---------------------------------------------------------------------------- |
218
+ | 404 | the tier has not opted in, or is disabled |
219
+ | 403 | the tier's matrix denies the plugin's capability, or the route declares none |
220
+ | 401 | permitted, but no valid unlock cookie (or no password configured) |
221
+
222
+ The denial comes before the lock, so a password never widens the matrix. Every 403 carries the
223
+ same `{ "error": "forbidden" }` body, naming neither tier nor capability. The matrix is
224
+ default-deny; production grants `observe.app`, `observe.estate` and `cicd.read`. Pass the same
225
+ `{ matrix: { staging: [...] } }` to `access()` and `accessGuard()` to replace a tier's list.
226
+ `data.*` (`data.read`, `data.write`: the data plugin and `storeServer()`) is hard-denied on
227
+ production: a production list naming it is stripped, and the guard answers 403 whatever the matrix
228
+ says. Staging and preview get it only through the matrix.
229
+ Until the operator unlocks (12 h on preview/staging, 2 h on production), the pill shows only the
230
+ lock. Client-side hiding is display only; the guard is what enforces the tier.
231
+
232
+ Server-only variables (never prefix them `NEXT_PUBLIC_`, never pass them to client code):
233
+
234
+ | variable | does |
235
+ | --------------------- | ------------------------------------------------------------------------------------ |
236
+ | `HUD_ACCESS_PASSWORD` | the unlock password. **Make it long and random** (a generated 32+ character string): it is the only barrier in front of the deployed HUD |
237
+ | `HUD_ACCESS_SECRET` | optional. Signs the unlock cookie instead of the password, so a leaked cookie gives nothing to guess the password against |
238
+ | `HUD_DISABLED` | `true` turns every HUD route into a 404 at request time |
239
+
240
+ The cookie (`__Host-hud-unlock`, httpOnly, `SameSite=Strict`) is signed with a key derived per
241
+ tier, so a staging cookie does not open production. Wrong passwords are budgeted per client
242
+ (`x-real-ip`, else the last `x-forwarded-for` entry, which your proxy must append; the leftmost
243
+ entries are client-controlled and ignored): ten per client per ten minutes, then 429 for every
244
+ attempt, the right password included. Past a hundred failures overall, every client with recent
245
+ failures of its own is throttled too, while a client without any still unlocks.
246
+
247
+ `NEXT_PUBLIC_*` flags are inlined at build time: changing `NEXT_PUBLIC_HUD_ENABLED` or
248
+ `NEXT_PUBLIC_HUD_DISABLED` needs a rebuild. To switch a running deployment off, set
249
+ `HUD_DISABLED=true` and restart.
250
+
251
+ In the playground, `?env=staging` runs this flow with the password `playground`.
252
+
71
253
  ## Write a plugin
72
254
 
73
- A plugin is `{ id, title?, capability?, panel?, pill?, commands?, routes? }`, shipped as two
255
+ A plugin is `{ id, title?, capability?, panel?, pill?, pillPriority?, commands?, routes? }`, shipped as two
74
256
  halves with the same `id`: the client half (`panel`, `pill`, `commands`) and the server half
75
257
  (`routes`), so route code never reaches a client bundle. The panel is a plain React component
76
- receiving `ctx`:
258
+ receiving `ctx`. Make it a dynamic import, so its code loads on first open and the pill stays
259
+ light; the shell shows "Loading…" meanwhile and contains a panel that fails to load or throws:
260
+
261
+ ```tsx
262
+ import { lazy } from "react";
263
+ import { definePlugin } from "@hansenexus/hud";
264
+
265
+ export const notes = () =>
266
+ definePlugin({ id: "notes", title: "Notes", panel: lazy(() => import("./notes-panel")) });
267
+ ```
268
+
269
+ Only what the pill needs runs at HUD mount (a store, a capture hook); every built-in panel
270
+ follows this split, see [Bundle budget](#bundle-budget).
77
271
 
78
272
  | `ctx` | does |
79
273
  | ------------- | --------------------------------------------------------------------- |
@@ -81,6 +275,8 @@ receiving `ctx`:
81
275
  | `api(path)` | JSON fetch from the plugin's routes at `/api/hud/<id>/<path>` |
82
276
  | `pin(edge)` | pin the panel to `left`, `right` or `bottom` |
83
277
  | `close()` | close the panel |
278
+ | `open()` | open the panel |
279
+ | `grab` | the element grabber: `start()`, `cancel()`, `clear()`, `amend(patch)`, `highlight(el, label)`, `clearHighlight()`; read it with `useGrab(ctx.grab)` |
84
280
 
85
281
  Routes are keyed by path, then method: `routes: { "/runs/:id": { GET: (req, { params }) => ... } }`.
86
282
  An unknown path answers 404, a known path with another method 405.
@@ -88,6 +284,21 @@ An unknown path answers 404, a known path with another method 405.
88
284
  `playground/src/plugins/server-info` is a working example: the playground serves its routes
89
285
  through MSW with the same `createHudHandler` an app mounts.
90
286
 
287
+ ## Pill
288
+
289
+ - The pill starts bottom-left. It scans the page for `position: fixed` and `sticky` elements
290
+ (cookie banners, chat launchers, booking CTAs, sticky navs) and takes the first corner none of
291
+ them covers; when every corner is covered, it shifts off the edge that needs the smallest move,
292
+ bottom corners preferred. Backdrops covering more than half the viewport are ignored.
293
+ - When the pill is wider than the viewport, items move into the `⋯` menu (the badge counts
294
+ them). `pillPriority` decides what stays: `access` 30, `observe` (errors) 20, `ops` (CI) 10,
295
+ everything else 0, then pill order. When no corner is free even after shifting, the pill
296
+ turns compact and keeps only prioritised items.
297
+ - Drag the env badge to another corner to keep the pill there; it still shifts within that
298
+ corner to clear host elements. `⋯ → Reset layout` forgets the corner.
299
+ - On a phone, a page wider than the screen grows the layout viewport past what is visible; the
300
+ pill places itself in the visible area instead.
301
+
91
302
  ## Panels and shortcuts
92
303
 
93
304
  - Open panels from the pill (`⋯` lists every panel and command). Drag by the title bar; a click
@@ -98,12 +309,577 @@ through MSW with the same `createHudHandler` an app mounts.
98
309
  - The layout (open panels, positions, pins) is kept per `appSlug` in `localStorage`.
99
310
  `⋯ → Reset layout` clears it.
100
311
  - Below 768 px panels open as one full-width bottom sheet with a tab per panel; no pinning.
101
- - `⌘⇧H` (Ctrl+Shift+H elsewhere) hides and restores the layout. `⌘⇧G` is reserved for the
102
- element grabber.
312
+ - `⌘⇧H` (Ctrl+Shift+H elsewhere) hides and restores the layout.
103
313
 
104
314
  A plugin's panel can pin itself with `ctx.pin("right")`. Plugin `commands` join the registry as
105
315
  `<plugin id>.<command id>`, appear in the `⋯` menu and bind their `shortcut`.
106
316
 
317
+ ## Element grabber
318
+
319
+ `⌘⇧G` or the pill's ⌖ starts a grab: hover outlines an element and labels it with the React
320
+ component and file that rendered it, a click picks it, `Esc` cancels. Open panels stay mounted
321
+ and usable meanwhile. The pick becomes a `GrabPayload` (route, selector, label, component,
322
+ viewport) handed to every plugin's `onGrab(payload, ctx)` and kept in `ctx.grab`. The source line
323
+ comes from React's dev stack and points into the dev server's transformed module, so it can sit a
324
+ few lines below the original. A plugin that enriches a grab after the fact (the `capture` plugin
325
+ attaching a screenshot) merges into it with `ctx.grab.amend(patch)`.
326
+
327
+ `ctx.grab.highlight(element, label)` draws the same outline on an element without entering grab
328
+ mode, for a panel that points at the page (the a11y findings do this). It follows scrolling and
329
+ goes away on `Esc`, on a click on the page, on the next grab or with `clearHighlight()`.
330
+
331
+ `ElementPicker` and `ElementOutline` are exported on their own and carry no dev marker, for the
332
+ review entrypoint.
333
+
334
+ ## Agent plugins
335
+
336
+ Two plugins from one module: `agentDispatch()` (Dispatch panel: the last grab plus an
337
+ instruction, sent to a provider; opens itself on a grab) and `agentSessions()` (Sessions panel:
338
+ runs and sessions of every provider).
339
+
340
+ ```tsx
341
+ import { agentDispatch, agentSessions } from "@hansenexus/hud/plugins/agent";
342
+ defineHud({ app: "my-app", plugins: [agentDispatch({ componentHints }), agentSessions()] });
343
+ ```
344
+
345
+ ```ts
346
+ import { agentDispatch, agentSessions, claudeCode, hermes } from "@hansenexus/hud/plugins/agent/server";
347
+
348
+ const providers = [
349
+ claudeCode(), // `claude -p <prompt> --permission-mode acceptEdits` in the dev server's cwd
350
+ hermes({ baseUrl: "http://hn-hub.ts.hansenexus.dev:8642", token: process.env.HERMES_API_TOKEN }),
351
+ ];
352
+ export const { GET, POST } = createHudHandler([agentDispatch({ providers }), agentSessions({ providers })]);
353
+ ```
354
+
355
+ A provider is `{ id, label, status?, dispatch(order), sessions? }`; `order.prompt` is the built
356
+ task text. `POST /dispatch` refuses cross-site requests (`Sec-Fetch-Site`) and anything not
357
+ `application/json`, so another origin cannot start an agent through the developer's browser.
358
+ `claudeCode()` loads Node built-ins on first use, so the server entry also imports where `node:`
359
+ modules are missing.
360
+
361
+ ## Capture plugin (screenshot)
362
+
363
+ `@hansenexus/hud/plugins/capture` attaches a screenshot to every grab, so a dispatched agent sees
364
+ what was meant. `screenshot()` has no panel: on a grab it posts the page URL, the grabbed selector
365
+ and the viewport to its server half, which renders the page headless with Playwright and answers
366
+ the PNG; the Dispatch panel shows the thumbnail and sends it with the dispatch
367
+ (`payload.screenshot`), and `claudeCode()` writes it beside the run's log and names the file in
368
+ the prompt.
369
+
370
+ ```tsx
371
+ import { screenshot } from "@hansenexus/hud/plugins/capture";
372
+ defineHud({ app: "my-app", plugins: [agentDispatch(), screenshot()] });
373
+ ```
374
+
375
+ ```ts
376
+ import { screenshot } from "@hansenexus/hud/plugins/capture/server";
377
+ export const { GET, POST } = createHudHandler([agentDispatch({ providers }), screenshot()]);
378
+ ```
379
+
380
+ - `POST /api/hud/capture/screenshot` takes `{ url, selector?, viewport? }`. The URL must share
381
+ the request's origin (or the page's `Origin`) and be `http(s)`; anything else answers 400, and
382
+ cross-site or non-JSON requests are refused, so the dev server never renders the web for
383
+ someone else. The page loads at the grab's viewport with the request's cookies, so it renders
384
+ the developer's session; the HUD itself is hidden. When the selector is not there headless
385
+ (hover state, hydration) the answer is the viewport, marked `scope: "viewport"`.
386
+ - `playwright` is an optional peer dependency, loaded on first use. Without it, or without its
387
+ Chromium, the route answers 503 with a setup hint
388
+ (`bun add -d playwright && bunx playwright install chromium`); the grab carries the reason, the
389
+ Dispatch panel shows the hint and the dispatch goes on without an image. Apps that already pin
390
+ `@playwright/test` have `playwright` through it. Next externalises `playwright` on the server by
391
+ default; pass `launch` to use another browser or an existing one.
392
+ - Needs `capture.screenshot`: granted in development only. A dispatch waits up to 30 s for a
393
+ screenshot still rendering.
394
+
395
+ ## Routes plugin and `hud sweep`
396
+
397
+ Every page of the app's `app/` tree, one click away, and a CI sweep over the same list.
398
+
399
+ ```tsx
400
+ // hud.tsx
401
+ import { routes } from "@hansenexus/hud/plugins/routes";
402
+ export default defineHud({ app: "my-app", plugins: [routes(), /* ... */] });
403
+ ```
404
+
405
+ ```ts
406
+ // app/api/hud/[...hud]/route.ts
407
+ import { routes } from "@hansenexus/hud/plugins/routes/server";
408
+
409
+ export const { GET, POST, PUT, PATCH, DELETE } = createHudHandler([
410
+ routes({ fixtures: { slug: ["hello", "welt"], locale: "" }, exclude: ["/(admin)/*"] }),
411
+ ]);
412
+ ```
413
+
414
+ The server half walks `app/` (or `src/app/`, or `dir`) on every request: `page.{tsx,jsx,ts,js,mdx}`
415
+ folders become routes, route groups drop out of the URL, private `_x`, parallel `@x` and
416
+ intercepting `(.)x` folders are skipped. Dynamic segments are filled from `fixtures`, keyed by
417
+ param name: a string, several strings (one URL each) or a function returning either, called per
418
+ route. A catch-all takes `a/b`; the empty string drops the segment (an `as-needed` default
419
+ locale); an optional catch-all without a fixture resolves to its parent. A segment without a
420
+ fixture leaves its route listed but unresolved. Capability: `routes.read` (development, staging,
421
+ preview).
422
+
423
+ The panel groups routes by route group, filters by path, marks the current page and navigates on
424
+ click. `GET /api/hud/routes/routes` answers the same list as JSON.
425
+
426
+ `hud sweep` visits that list headless and fails the build on a 5xx answer, an uncaught error or a
427
+ console error on any page. It needs Playwright in the app (`playwright` or `@playwright/test`,
428
+ with `npx playwright install chromium`) and the dev server running:
429
+
430
+ ```sh
431
+ npx hud sweep --base http://localhost:3000 # lines per route, exit 1 on failure
432
+ npx hud sweep --base http://localhost:3000 --json # the report as JSON, for CI
433
+ npx hud sweep --base http://localhost:3000 --exclude "/broken" --ignore-console "Warning: .*key"
434
+ ```
435
+
436
+ `--api` names another `createHudHandler` mount, `--timeout` and `--wait` tune navigation and
437
+ settle time. Console errors the HUD's own routes cause (a plugin route the app has not mounted)
438
+ are not counted; `favicon.ico`, React DevTools and Fast Refresh messages are ignored. Exit codes:
439
+ 0 clean, 1 at least one route failed, 2 usage or setup error. `fixtures/next-app` runs this in CI.
440
+
441
+ ## Design plugin
442
+
443
+ `@hansenexus/hud/plugins/design` exports three client-only plugins:
444
+
445
+ ```tsx
446
+ import { forceState, tokens, variants } from "@hansenexus/hud/plugins/design";
447
+
448
+ tokens({
449
+ groups: [
450
+ { label: "Theme", tokens: ["--background", "--primary", { cssVar: "--ring", label: "ring" }] },
451
+ { label: "Brand", tokens: ["--brand"], scope: { attribute: "data-theme", value: "brand" } },
452
+ ],
453
+ sourceHint: "src/app/globals.css",
454
+ });
455
+ variants();
456
+ forceState();
457
+ ```
458
+
459
+ - **Tokens** reads each value from the host document (a hidden probe in `<body>` carrying the
460
+ group's `scope` attribute), so themed and scoped tokens show what the page renders. It re-reads
461
+ when `<html>`/`<body>` attributes, stylesheets or the OS color scheme change.
462
+ - **Variants** lists the page's live variant groups (below) with a switcher, agent scores and
463
+ Decide. An optional adapter (`variants({ categories, generate })`) adds the app's own variant
464
+ registry and the generate-brief queue (`variants.generate`).
465
+ - **States** toggles every mounted `StateBoundary` between real, loading, empty and error. It
466
+ needs `state.force`.
467
+
468
+ `StateBoundary` is app code and production-safe to import. Outside development it renders
469
+ `children(null)` and the bundler drops the store; `?__state=loading|empty|error` forces the
470
+ top-level boundaries and `?__state=<id>:error` one boundary:
471
+
472
+ ```tsx
473
+ import { StateBoundary } from "@hansenexus/hud/state-boundary";
474
+
475
+ <StateBoundary id="blog-post">
476
+ {(forced) => (forced === "loading" || post === undefined ? <Skeleton /> : <Post post={post} />)}
477
+ </StateBoundary>;
478
+ ```
479
+
480
+ `FORCE_STATE_MARKER` (`__HANSENEXUS_HUD_FORCE_STATE__`) is the store's global key; grep production
481
+ chunks for it to prove the fold.
482
+
483
+ ### Variant groups
484
+
485
+ Design work happens on real pages with real data, not on fixture pages. `VariantGroup` from
486
+ `@hansenexus/hud/variants` wraps a region of a page with several alternatives; the choice lives in
487
+ the URL, so a link to `?variant=hero:bold` shows a colleague exactly that state:
488
+
489
+ ```tsx
490
+ import { VariantGroup } from "@hansenexus/hud/variants";
491
+
492
+ <VariantGroup
493
+ id="hero"
494
+ label="Hero"
495
+ default="current"
496
+ variants={{
497
+ current: { label: "Current", render: () => <Hero /> },
498
+ bold: { label: "Bold claim", render: () => <HeroBold /> },
499
+ }}
500
+ />;
501
+ ```
502
+
503
+ `VariantGroup` is a client component; use it from client code, since the render functions
504
+ cannot cross a server/client boundary as props. Several groups go in one param:
505
+ `?variant=hero:bold,cta:short`. The Variants panel lists every
506
+ mounted group under "Live on this page"; clicking a variant rewrites `?variant=` in place (no
507
+ history entry) and re-renders the group. Production-safe to import: outside development the
508
+ component renders the default and the bundler drops the registry and the URL parsing
509
+ (`VARIANT_MARKER`, `__HANSENEXUS_HUD_VARIANTS__`, is the global key to grep for).
510
+
511
+ Agents score variants, a human decides. The panel reads `score`, `rationale` and `scoredBy` per
512
+ variant through the storage seam and ranks them; with `file()` that is `.hud/variants.json`,
513
+ keyed `<group>:<id>`, which an agent writes by hand:
514
+
515
+ ```json
516
+ {
517
+ "hero:bold": { "score": 8.5, "scoredBy": "claude-code", "rationale": "Clear promise, concrete next step." },
518
+ "hero:current": { "score": 6, "scoredBy": "claude-code", "rationale": "Informative but generic." }
519
+ }
520
+ ```
521
+
522
+ **Decide** (needs `variants.decide`, granted on development only by default) writes
523
+ `status: "decided"` and `decidedAt` on the winner and `status: "rejected"` on the rest, then queues
524
+ a cleanup brief ("inline the winner, delete the losers and the wrapper, run the checks") through
525
+ the dispatch seam. The server half:
526
+
527
+ ```ts
528
+ import { variantsServer } from "@hansenexus/hud/plugins/design/server";
529
+ import { claudeCode } from "@hansenexus/hud/plugins/agent/server";
530
+ import { file } from "@hansenexus/hud/store";
531
+
532
+ export const { GET, POST } = createHudHandler([
533
+ variantsServer({ store: file(), dispatch: claudeCode() }),
534
+ ]);
535
+ ```
536
+
537
+ Without `dispatch` the decision is recorded and nothing is queued. `GET <apiBase>/variants/` lists
538
+ the records, `POST <apiBase>/variants/<group>/decide` decides; both answer only to same-origin
539
+ JSON requests. In the playground the hero is a variant group with seeded scores, and Decide logs
540
+ the brief to the browser console through the echo provider.
541
+
542
+ ## Storage seam
543
+
544
+ Plugins that keep state (variant scores and decisions, flag overrides) go through
545
+ `HudStore { get, set, list }` from `@hansenexus/hud/store`: named collections of JSON documents
546
+ keyed by id, values are plain objects. Three adapters implement it:
547
+
548
+ | adapter | where the bytes live |
549
+ | ---------- | ------------------------------------------------------------------------------------------------- |
550
+ | `file()` | default. One pretty-printed `<collection>.json` per collection under `.hud/` in the dev server's cwd (`{ dir }` to move it). Server side only; collection names are slugs and the resolved path is checked against the directory, so no request can name a file outside it. Writes are atomic and serialised per collection |
551
+ | `http()` | `{ baseUrl }` of `storeRoutes()` or `storeServer()`: `GET <base>/<collection>`, `GET`/`PUT <base>/<collection>/<id>`. Runs in the browser or on a server |
552
+ | `convex()` | `@hansenexus/hud/store/convex`, the one module in the package that imports the Convex client (optional peer). `{ url }` plus the deployment's `hudStore:get`, `hudStore:set` and `hudStore:list` functions (`{ functions }` renames them) |
553
+
554
+ `memory()` is the fourth, for tests and the playground. `storeServer({ store })` exposes a store
555
+ at `<apiBase>/store/…` and carries `data.write`, which the deployed-tier matrix never grants;
556
+ `storeRoutes(store)` are the same routes for a plugin's own `routes`. Writes refuse cross-site
557
+ requests.
558
+
559
+ ## Inspect plugin
560
+
561
+ `@hansenexus/hud/plugins/inspect` is a data inspector on top of the observe capture. The pill
562
+ counts requests; the panel lists every `fetch`, XHR and Next Server Action with method, status,
563
+ timing, request and response headers and bodies, and replays one on demand.
564
+
565
+ ```tsx
566
+ import { inspect } from "@hansenexus/hud/plugins/inspect";
567
+ defineHud({ app: "my-app", plugins: [inspect()] });
568
+ ```
569
+
570
+ - Capture starts when the HUD mounts (with or without `observe()`), so requests made before the
571
+ panel opens are already listed. The last 200 requests are kept; bodies are capped at 16 KB.
572
+ - A Server Action is recognised by its `Next-Action` header and shown with the action id; the
573
+ `actions` filter lists only those.
574
+ - **Redaction** happens before anything is stored: `authorization`, `cookie`, `set-cookie` and
575
+ every header, query parameter, JSON key, form field or multipart part whose name looks like a
576
+ token (`token`, `secret`, `password`, `api-key`, `auth`, `jwt`, …) shows as `[redacted]`, as do
577
+ bearer tokens and JWTs inside text bodies. `redactHeaders`, `redactBody` and `redactUrl` are
578
+ exported for tests.
579
+ - **Replay** sends the request again through the page's `fetch` (cookies included) and lists the
580
+ result tagged `replay`. Redacted headers and fields are not resent: their values are gone. A
581
+ request whose body could only be described (a file upload, a stream, a truncated body) cannot
582
+ be replayed; the button says why.
583
+ - Needs `inspect.read`: granted in development, preview and staging, not production.
584
+
585
+ ### Inspect adapters
586
+
587
+ Adapters add a tab each to the Inspect panel. Every adapter is its own subpath export, so an
588
+ app that omits one ships none of its code (`src/bundle.test.ts` proves it); the React Query and
589
+ SWR adapters read their caches structurally and import nothing from the libraries.
590
+
591
+ ```tsx
592
+ import { inspect } from "@hansenexus/hud/plugins/inspect";
593
+ import { inspectConvex } from "@hansenexus/hud/plugins/inspect/convex";
594
+ import { inspectReactQuery } from "@hansenexus/hud/plugins/inspect/react-query";
595
+ import { inspectSockets } from "@hansenexus/hud/plugins/inspect/sockets";
596
+ import { inspectSwr } from "@hansenexus/hud/plugins/inspect/swr";
597
+ import { mutate } from "swr";
598
+ import { cache } from "swr/_internal";
599
+
600
+ inspect({
601
+ adapters: [
602
+ inspectConvex({ client: convex }), // the app's ConvexReactClient (or ConvexClient / ConvexHttpClient)
603
+ inspectReactQuery({ queryClient }),
604
+ inspectSwr({ cache, mutate }), // the default cache; with a provider, pass that cache and its scoped mutate
605
+ inspectSockets(),
606
+ ],
607
+ });
608
+ ```
609
+
610
+ - **Convex** wraps the client's `watchQuery`, `onUpdate`, `mutation`, `action` and `query` in
611
+ place, so `useQuery`, `useQueries` and `usePaginatedQuery` are covered. Live queries list with
612
+ the latency to their first result, update count, subscriber count and last result; mutations,
613
+ actions and one-shot queries with their duration, result or error. Args and results are
614
+ redacted like request bodies. Needs the `convex` peer.
615
+ - **Query** (React Query) lists every cache entry with its key, status, freshness (`fetching`,
616
+ `inactive`, `invalidated`, `stale`, `fresh`), observer count and age, the data redacted, and
617
+ offers Invalidate (exact key) and Remove per entry plus invalidate-all.
618
+ - **SWR** lists every cache key with its validation state, age and data (redacted); Revalidate
619
+ calls `mutate` with the key the app passed, tuple keys included. The cache's `set` and `delete`
620
+ are wrapped in place to timestamp writes.
621
+ - **Sockets** patches `WebSocket` and `EventSource` when the factory runs and checks again when
622
+ the HUD mounts: a mock layer that wrapped them in between (MSW's `worker.start()`) is wrapped
623
+ in turn, so the socket the app holds is the one recorded. Connections show state, time to
624
+ open, protocol and close code; frames in both directions show size and redacted text (named SSE
625
+ events included), binaries as a note. `ignore` leaves URLs out; the HUD's own routes are
626
+ ignored by default.
627
+
628
+ Each factory returns an `InspectAdapter` (`{ id, title, Panel, useCount?, install?, dispose? }`),
629
+ the whole contract an adapter of your own needs. `dispose()` restores what the factory wrapped.
630
+ The playground (`bun run dev`) carries a demo per adapter in the page's "Daten" section.
631
+
632
+ ## A11y and SEO plugins
633
+
634
+ Both are client only and need no server half.
635
+
636
+ ```tsx
637
+ import { a11y } from "@hansenexus/hud/plugins/a11y";
638
+ import { seo } from "@hansenexus/hud/plugins/seo";
639
+
640
+ defineHud({ app: "my-app", plugins: [a11y(), seo()] });
641
+ ```
642
+
643
+ - **A11y** runs [axe-core](https://github.com/dequelabs/axe-core) on demand. Nothing is fetched
644
+ until Run (or the `Run accessibility audit` command): by default the plugin appends a script
645
+ from jsDelivr (`AXE_URL`, pinned to `AXE_VERSION`); pass
646
+ `a11y({ load: () => import("axe-core") })` to serve the package you installed as its own chunk
647
+ instead, or `axeUrl` for another host. The HUD's own host is excluded from the audit. Findings
648
+ list one row per element, highest impact first; clicking one outlines the element with the
649
+ grabber overlay and `?` opens the rule's documentation. The pill shows the count after a run.
650
+ - **SEO** checks the page from mount on and again whenever `<head>` changes (client-side routers,
651
+ `document.title`) or history moves: `<title>` and `meta description` present and within length,
652
+ `rel=canonical` absolute and pointing at this page, Open Graph title/description/image (url and
653
+ type recommended), every JSON-LD script parses and carries `@context` and `@type`, `hreflang`
654
+ links are absolute, valid tags with `x-default` and a self-reference, and `robots`/`googlebot`
655
+ directives that keep the page out of results. The pill counts the errors; the panel lists every
656
+ check with its value or what is wrong. `runSeoChecks(document, url)` is exported for tests and
657
+ CI scripts.
658
+
659
+ The playground's `index.html` and the "Newsletter" section carry deliberately broken meta and
660
+ markup for both panels.
661
+ ## Data plugin
662
+
663
+ `@hansenexus/hud/plugins/data` switches who the page is signed in as and overrides feature flags
664
+ from one panel. The pill shows the current user and the number of overridden flags.
665
+
666
+ ```tsx
667
+ import { data } from "@hansenexus/hud/plugins/data";
668
+ defineHud({ app: "my-app", plugins: [data()] });
669
+ ```
670
+
671
+ ```ts
672
+ import { cookieImpersonation, dataServer } from "@hansenexus/hud/plugins/data/server";
673
+ import { file } from "@hansenexus/hud/store";
674
+
675
+ const users = [
676
+ { id: "u_ada", label: "Ada (admin)", role: "admin" },
677
+ { id: "u_cleo", label: "Cleo (customer)", role: "customer" },
678
+ ];
679
+ export const { GET, POST, PUT, DELETE } = createHudHandler([
680
+ dataServer({
681
+ auth: cookieImpersonation({ users }),
682
+ flags: [
683
+ { key: "new-checkout", label: "New checkout", value: false },
684
+ { key: "promo-text", type: "string", value: "", scope: "local" },
685
+ ],
686
+ store: file(),
687
+ }),
688
+ ]);
689
+ ```
690
+
691
+ Both halves carry `data.write`, which `access` grants in development, on staging or preview only
692
+ through the matrix, and never on production (see Deployed tiers).
693
+
694
+ ### Role switch (auth seam)
695
+
696
+ Picking a user signs the browser in as that fixture user and reloads the page. The adapter knows
697
+ where its library keeps the session; the app supplies the one thing only it can, a session for a
698
+ fixture user:
699
+
700
+ | adapter | signs in by | the app honours it through |
701
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
702
+ | `convexAuth({ users, mint })` | `mint(user)` → `{ token, refreshToken }` from the app's development-only Convex action; written to `__convexAuthJWT`/`__convexAuthRefreshToken` (`__Host-` off localhost) and, with `storageNamespace`, into Convex Auth's `localStorage` keys for the Vite flavour | `@convex-dev/auth` reads them like any session |
703
+ | `betterAuth({ users, auth })` | `auth.api.signInEmail({ email, password })` for the fixture user's credentials; the cookies better-auth sets are forwarded | better-auth reads its own session cookie |
704
+ | `cookieImpersonation({ users })` | a signed `hud-impersonate` cookie naming the user (signed with `HUD_ACCESS_SECRET` or `HUD_ACCESS_PASSWORD` when set, unsigned in development) | `readImpersonation(request)` in the app's auth layer: when it names a user, act as that user |
705
+
706
+ `users` is the fixture list (`{ id, label, role?, email?, password? }`; passwords never reach the
707
+ browser) or a loader. "Signed in as" asks the adapter for the current user on every panel load.
708
+ A `HudAuthAdapter` of your own is `{ id, label, users, current, signIn, signOut }`.
709
+
710
+ ### Feature flags
711
+
712
+ `flags` is the flag source: the definitions themselves, or `{ list(request) }` over the app's real
713
+ source (PostHog, Unleash, a table). The panel shows each flag's real value and sets an override
714
+ in one of two scopes:
715
+
716
+ | scope | lives in | read by |
717
+ | -------- | ---------------------------------------------------------- | -------------------------------------------------- |
718
+ | `cookie` | the `hud-flags` cookie (URL-encoded JSON, not httpOnly) | the server (SSR, Server Actions, routes) and the client |
719
+ | `local` | `localStorage["hud-flags"]` | the client |
720
+
721
+ The override persists through the storage seam (`.hud/flags.json` with `file()`, one document
722
+ `{ "overrides": { "new-checkout": { "value": true, "scope": "cookie" } } }`) until reset; every panel
723
+ load re-emits the cookie and mirrors the local scope, so a fresh browser is in step with the file.
724
+ The app reads overrides through the production-safe, dependency-free `@hansenexus/hud/flags`:
725
+
726
+ ```ts
727
+ import { flagOverride, readFlagOverrides } from "@hansenexus/hud/flags";
728
+
729
+ // server: the request's cookie header
730
+ const newCheckout = flagOverride("new-checkout", { cookie: request.headers.get("cookie") }, flags.newCheckout);
731
+ // client: cookie and localStorage, local winning
732
+ const all = readFlagOverrides({ cookie: document.cookie, storage: localStorage });
733
+ ```
734
+
735
+ Gate the read like the HUD itself (`NODE_ENV`, `NEXT_PUBLIC_HUD_ENABLED`): a visitor can set a
736
+ cookie by hand, and production never gets one from the HUD. In the playground, `?auth=convex` and
737
+ `?auth=better` run the role switch through the other two adapters against stand-in backends; the
738
+ CTA text, a promo banner and the number of content sections follow the three demo flags.
739
+
740
+ ### Seeds
741
+
742
+ `seeds` are functions the panel runs on the server, with the request (so a seed can act as the
743
+ user the role switch signed in): fill a table, reset the database, put an account into a state.
744
+
745
+ ```ts
746
+ dataServer({
747
+ seeds: [
748
+ { id: "orders:sample", label: "Seed 20 orders", run: () => seedOrders(20) },
749
+ { id: "reset", label: "Reset database", danger: true, run: () => resetDatabase() },
750
+ ],
751
+ });
752
+ ```
753
+
754
+ Run posts `POST <apiBase>/data/seeds/:id`; what the seed returns is shown as JSON next to the
755
+ duration, a throw as the failure. A `danger` seed asks for a second click (Confirm).
756
+
757
+ ### Mock scenarios (MSW)
758
+
759
+ Scenarios are alternative answers per endpoint, `real | empty | error | slow` in the panel, at most
760
+ one active per endpoint. They are declared msw-free, in one module every side imports:
761
+
762
+ ```ts
763
+ // hud/scenarios.ts
764
+ import type { HudMockScenario } from "@hansenexus/hud/plugins/data";
765
+
766
+ export const scenarios: HudMockScenario[] = [
767
+ { id: "orders:empty", endpoint: "GET /api/orders", label: "empty", json: [] },
768
+ { id: "orders:error", endpoint: "GET /api/orders", label: "error", status: 503, json: { error: "down" } },
769
+ { id: "orders:slow", endpoint: "GET /api/orders", label: "slow", delay: 2000 },
770
+ {
771
+ id: "order:missing",
772
+ endpoint: "GET /api/orders/:id",
773
+ label: "missing",
774
+ respond: (_request, { params }) => Response.json({ error: `no order ${params.id}` }, { status: 404 }),
775
+ },
776
+ ];
777
+ ```
778
+
779
+ `endpoint` is `METHOD path`: a relative path matches on every origin, an absolute URL on that
780
+ origin only, `:name` captures a segment, a trailing `*` the rest, `*` as the method any method.
781
+ `json`/`status`/`headers` build the answer, `respond` takes over, `delay` waits first; a scenario
782
+ with only `delay` passes the real answer through late. The active set is one document in the store
783
+ (`.hud/mocks.json`: `{ "active": { "GET /api/orders": "orders:empty" } }`) and toggles through
784
+ `PUT|DELETE <apiBase>/data/mocks/:id` and `DELETE <apiBase>/data/mocks`.
785
+
786
+ Three places take the list:
787
+
788
+ ```ts
789
+ // app/api/hud/[...hud]/route.ts: lists and toggles them
790
+ dataServer({ mocks: scenarios, store: file() });
791
+
792
+ // app/hud.tsx: client fetches, through an MSW worker loaded on demand
793
+ data({ mocks: { scenarios, worker: () => import("@hansenexus/hud/plugins/data/msw-browser") } });
794
+
795
+ // instrumentation.ts: server fetches (RSC, Server Actions, route handlers), through msw/node
796
+ export async function register() {
797
+ if (process.env.NEXT_RUNTIME === "nodejs" && process.env.NODE_ENV === "development") {
798
+ const { startMockServer } = await import("@hansenexus/hud/plugins/data/msw-node");
799
+ const { scenarios } = await import("./hud/scenarios");
800
+ await startMockServer({ scenarios, store: file() });
801
+ }
802
+ }
803
+ ```
804
+
805
+ `msw` is an optional peer; only the two `msw-*` entries load it, at run time, so the panel, the
806
+ route and the scenario module never depend on it. Install it with `bun add -d msw` and put its
807
+ worker script in `public/` with `npx msw init public/` (the fixture copies it in its `dev` script).
808
+ The panel shows a `client` and a `server` badge: `live` when that side intercepts, `off` with a
809
+ setup hint when the loader or `startMockServer()` is missing, `failed` with the reason when a
810
+ start rejected (no worker script, `msw` not installed). Nothing crashes either way; toggles keep
811
+ working for the side that is live. The worker starts when the HUD mounts, after the page's own
812
+ first fetches, which go to the network; the Node side covers the initial server render. An app
813
+ that already runs an MSW worker passes its own `{ startMockWorker }` module and registers the
814
+ HUD's catch-all on that worker (`worker.use(http.all("*", ({ request }) => resolve(request)))`),
815
+ as the playground does in `plugins/data-mocks.ts`. `fixtures/next-app` wires every side: `/orders`
816
+ renders the orders count through a React Server Component, a Server Action and a client fetch,
817
+ and `e2e/data-fixture.spec.ts` toggles the scenarios against all three.
818
+
819
+ ## Review entrypoint (production)
820
+
821
+ `@hansenexus/hud/review` is the client review widget: a pill on the right edge, the element
822
+ picker and a docked review sheet with the page's pins. It is safe to ship in production and
823
+ carries none of the dev shell or its plugins. It needs `convex` (an optional peer dependency).
824
+
825
+ The gate is a prop, not a build flag, so one image can serve a client production with the widget
826
+ off and a staging production with it on. Read the URL on the server per deployment and pass it
827
+ down; empty renders nothing:
828
+
829
+ ```tsx
830
+ "use client";
831
+ import { Review } from "@hansenexus/hud/review";
832
+
833
+ export function ReviewMount({ convexUrl, locale }: { convexUrl?: string; locale: string }) {
834
+ return <Review convexUrl={convexUrl} projectSlug="elbe-akustik" locale={locale} />;
835
+ }
836
+ ```
837
+
838
+ Even with a URL the widget stays invisible until the visitor opens a review link (`?rv=<grant>`,
839
+ redeemed once and stripped from the address bar) or has a stored session. Pins are stored per
840
+ locale-stripped route (`/en/standorte` and `/standorte` are one route) and per viewport bucket;
841
+ a pin that cannot be placed is listed under "Ohne Position", never moved onto a neighbour. The
842
+ widget talks to the review app's Convex functions `access:redeemGrant`, `access:whoami`,
843
+ `pins:listForRoute` and `pins:plant`; pass `backend` (a `ReviewBackend`) instead of `convexUrl`
844
+ to run it against anything else. In the playground, `?review` mounts it with an in-memory
845
+ backend.
846
+
847
+ ### Bundle gate
848
+
849
+ `@hansenexus/hud/markers` exports the literals to grep production client chunks for, with no
850
+ dependencies so a Node gate script can import it:
851
+
852
+ | marker | value | expected in production chunks |
853
+ | ------------------- | --------------------------- | ----------------------------------------- |
854
+ | `HUD_DEV_MARKER` | `__HANSENEXUS_HUD_DEV__` | never |
855
+ | `HUD_REVIEW_MARKER` | `__HANSENEXUS_HUD_REVIEW__` | only where `/review` is meant to ship |
856
+
857
+ CI proves both on every PR: `fixtures/next-app` mounts the dev HUD behind the loader's build gate
858
+ and `<Review>` beside it, installs the packed tarball, runs `next build` and fails on any dev
859
+ marker or dev-only string in `.next/static` (`bun run build && bun run --cwd fixtures/next-app
860
+ gate`). `fixtures/vite-app` does the same for Vite: `hud()` in its config, the
861
+ `import.meta.env.DEV` loader gate, the packed tarball, `vite build`, no dev marker in `dist`
862
+ (`bun run --cwd fixtures/vite-app gate`). Both fixtures define their HUD through
863
+ `@hansenexus/hud/auto`, so the gate covers the generated module too. Either fixture's
864
+ `scripts/check-bundle.js` is a starting point for an app's own gate.
865
+
866
+ ### Bundle budget
867
+
868
+ `bun run check:size` (part of `bun run check` and CI) bundles each entry from `dist/` the way an
869
+ app would, React external and minified, and splits the output into what runs at HUD mount (the
870
+ entry and its static imports) and what sits behind `import()`. The eager part is the budget, gzip:
871
+
872
+ | entry | eager budget | also required |
873
+ | -------------------- | --------------------- | ----------------------------------- |
874
+ | core (`defineHud`) | 40 KB | |
875
+ | each `plugins/<id>` | 8 KB on top of core | at least one lazy chunk (the panel) |
876
+ | `auto` (stand-in) | 24 KB on top of core | at least one lazy chunk |
877
+
878
+ The dev core sits at about 13 KB; a plugin's eager cost is its pill and whatever must run from
879
+ mount (console capture, request capture, the SEO check). The script prints a row per entry with
880
+ the lazy chunk sizes, so a panel that slips into the eager graph shows up as a missing lazy chunk
881
+ and a growing eager number.
882
+
107
883
  ## Release
108
884
 
109
885
  Versions are driven by [Changesets](https://github.com/changesets/changesets). A PR that changes