@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
@@ -0,0 +1,300 @@
1
+ import { _ as captureBuffer, c as readCapped, h as redactUrl, i as capturedText, l as requestBuffer, m as redactHeaders, n as captureRequestBody, r as captureResponse, s as parseRawHeaders, u as takeReplay } from "./requests-BwD6MKEq.js";
2
+ //#region src/plugins/observe/capture.ts
3
+ const MAX_TEXT = 300;
4
+ let installs = 0;
5
+ let requestWatchers = 0;
6
+ const restorers = [];
7
+ const isHudRoute = (url) => url.includes("/api/hud/");
8
+ function toText(args) {
9
+ return args.map((arg) => {
10
+ if (typeof arg === "string") return arg;
11
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
12
+ try {
13
+ return JSON.stringify(arg) ?? String(arg);
14
+ } catch {
15
+ return String(arg);
16
+ }
17
+ }).join(" ").slice(0, MAX_TEXT);
18
+ }
19
+ /**
20
+ * Pushes on a microtask. React logs dev warnings with `console.error` while it
21
+ * renders; a synchronous push would notify the console tab's store in the
22
+ * middle of that render, React would warn about the update, and the warning
23
+ * would land here again.
24
+ */
25
+ function record(input) {
26
+ queueMicrotask(() => captureBuffer.push(input));
27
+ }
28
+ function patchConsole() {
29
+ for (const kind of [
30
+ "log",
31
+ "warn",
32
+ "error"
33
+ ]) {
34
+ const original = console[kind];
35
+ console[kind] = (...args) => {
36
+ record({
37
+ kind,
38
+ text: toText(args)
39
+ });
40
+ original.apply(console, args);
41
+ };
42
+ restorers.push(() => {
43
+ console[kind] = original;
44
+ });
45
+ }
46
+ }
47
+ function listenErrors() {
48
+ const onError = (event) => {
49
+ record({
50
+ kind: "error",
51
+ text: toText([event.error instanceof Error ? event.error : event.message])
52
+ });
53
+ };
54
+ const onRejection = (event) => {
55
+ record({
56
+ kind: "error",
57
+ text: `Unhandled rejection: ${toText([event.reason])}`
58
+ });
59
+ };
60
+ window.addEventListener("error", onError);
61
+ window.addEventListener("unhandledrejection", onRejection);
62
+ restorers.push(() => {
63
+ window.removeEventListener("error", onError);
64
+ window.removeEventListener("unhandledrejection", onRejection);
65
+ });
66
+ }
67
+ function hasInternalHeader(input, init) {
68
+ try {
69
+ if (new Headers(init?.headers).has("x-hud-internal")) return true;
70
+ return input instanceof Request && input.headers.has("x-hud-internal");
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ /** The request headers a fetch will send: the `Request`'s own, overlaid by `init.headers`. */
76
+ function fetchHeaders(input, init) {
77
+ const headers = new Headers(input instanceof Request ? input.headers : void 0);
78
+ try {
79
+ for (const [name, value] of new Headers(init?.headers)) headers.set(name, value);
80
+ } catch {}
81
+ return headers;
82
+ }
83
+ /**
84
+ * Starts a detailed record for a fetch. The body is read from the `Request`
85
+ * clone in the background when the app passed one; `init.body` is described
86
+ * synchronously.
87
+ */
88
+ function startFetchRecord(input, init, method, url) {
89
+ const headers = fetchHeaders(input, init);
90
+ const contentType = headers.get("content-type") ?? void 0;
91
+ const actionId = headers.get("next-action");
92
+ const replayOf = takeReplay();
93
+ const request = { headers: redactHeaders(headers) };
94
+ const entry = {
95
+ transport: "fetch",
96
+ method,
97
+ url: redactUrl(url),
98
+ request,
99
+ ...actionId ? { actionId } : {},
100
+ ...replayOf !== void 0 ? { replayOf } : {}
101
+ };
102
+ const { id } = requestBuffer.push(entry);
103
+ const patchRequest = (payload) => requestBuffer.update(id, { request: {
104
+ ...request,
105
+ ...payload
106
+ } });
107
+ if (init?.body !== void 0 && init.body !== null) patchRequest(captureRequestBody(init.body, contentType));
108
+ else if (input instanceof Request && input.body && !input.bodyUsed) try {
109
+ readCapped(input.clone().body ?? new ReadableStream(), contentType).then(patchRequest).catch(() => patchRequest({ bodyNote: "[unreadable]" }));
110
+ } catch {
111
+ patchRequest({ bodyNote: "[unreadable]" });
112
+ }
113
+ return id;
114
+ }
115
+ function finishFetchRecord(id, response, durationMs) {
116
+ const payload = captureResponse(response, (body) => {
117
+ const current = requestBuffer.getSnapshot().find((entry) => entry.id === id)?.response;
118
+ requestBuffer.update(id, { response: {
119
+ ...current ?? payload,
120
+ ...body
121
+ } });
122
+ });
123
+ requestBuffer.update(id, {
124
+ status: response.status,
125
+ durationMs,
126
+ response: payload
127
+ });
128
+ }
129
+ function patchFetch(ignore) {
130
+ const originalFetch = window.fetch;
131
+ const callOriginal = originalFetch.bind(window);
132
+ const patched = async (input, init) => {
133
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
134
+ if (ignore(url) || hasInternalHeader(input, init)) return callOriginal(input, init);
135
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
136
+ const detail = requestWatchers > 0 ? startFetchRecord(input, init, method, url) : void 0;
137
+ const started = performance.now();
138
+ const elapsed = () => Math.round(performance.now() - started);
139
+ try {
140
+ const response = await callOriginal(input, init);
141
+ const durationMs = elapsed();
142
+ record({
143
+ kind: "fetch",
144
+ text: `${method} ${url}`.slice(0, MAX_TEXT),
145
+ status: response.status,
146
+ durationMs
147
+ });
148
+ if (detail !== void 0) finishFetchRecord(detail, response, durationMs);
149
+ return response;
150
+ } catch (error) {
151
+ const durationMs = elapsed();
152
+ record({
153
+ kind: "fetch",
154
+ text: `${method} ${url} — ${toText([error])}`.slice(0, MAX_TEXT),
155
+ status: 0,
156
+ durationMs
157
+ });
158
+ if (detail !== void 0) requestBuffer.update(detail, {
159
+ status: 0,
160
+ durationMs,
161
+ error: toText([error])
162
+ });
163
+ throw error;
164
+ }
165
+ };
166
+ window.fetch = Object.assign(patched, originalFetch);
167
+ restorers.push(() => {
168
+ window.fetch = originalFetch;
169
+ });
170
+ }
171
+ /** The text of an XHR response, by its `responseType`. */
172
+ function xhrResponseBody(xhr) {
173
+ const type = xhr.responseType;
174
+ if (type === "" || type === "text") return { body: xhr.responseText };
175
+ if (type === "json") try {
176
+ return { body: JSON.stringify(xhr.response) };
177
+ } catch {
178
+ return { bodyNote: "[json]" };
179
+ }
180
+ return { bodyNote: `[${type}]` };
181
+ }
182
+ function patchXhr(ignore) {
183
+ if (typeof XMLHttpRequest === "undefined") return;
184
+ const proto = XMLHttpRequest.prototype;
185
+ const { open, send, setRequestHeader } = proto;
186
+ const meta = /* @__PURE__ */ new WeakMap();
187
+ proto.open = function patchedOpen(method, url, async = true, user, password) {
188
+ meta.set(this, {
189
+ method: String(method).toUpperCase(),
190
+ url: String(url),
191
+ headers: {}
192
+ });
193
+ return open.call(this, method, url, async, user ?? null, password ?? null);
194
+ };
195
+ proto.setRequestHeader = function patchedSetRequestHeader(name, value) {
196
+ const m = meta.get(this);
197
+ if (m) m.headers[name.toLowerCase()] = value;
198
+ return setRequestHeader.call(this, name, value);
199
+ };
200
+ proto.send = function patchedSend(body) {
201
+ const m = meta.get(this);
202
+ if (!m || ignore(m.url) || "x-hud-internal" in m.headers) return send.call(this, body);
203
+ const { method, url } = m;
204
+ const started = performance.now();
205
+ let detail;
206
+ if (requestWatchers > 0) {
207
+ const request = {
208
+ headers: redactHeaders(m.headers),
209
+ ...captureRequestBody(body, m.headers["content-type"])
210
+ };
211
+ const actionId = m.headers["next-action"];
212
+ detail = requestBuffer.push({
213
+ transport: "xhr",
214
+ method,
215
+ url: redactUrl(url),
216
+ request,
217
+ ...actionId ? { actionId } : {}
218
+ }).id;
219
+ }
220
+ this.addEventListener("loadend", () => {
221
+ const durationMs = Math.round(performance.now() - started);
222
+ const status = this.status;
223
+ record({
224
+ kind: "xhr",
225
+ text: `${method} ${url}`.slice(0, MAX_TEXT),
226
+ status,
227
+ durationMs
228
+ });
229
+ if (detail === void 0) return;
230
+ const headers = parseRawHeaders(this.getAllResponseHeaders());
231
+ const response = { headers };
232
+ if (status !== 0) {
233
+ const captured = xhrResponseBody(this);
234
+ if (captured.body !== void 0) Object.assign(response, capturedText(captured.body, headers["content-type"]));
235
+ else if (captured.bodyNote) response.bodyNote = captured.bodyNote;
236
+ }
237
+ requestBuffer.update(detail, {
238
+ status,
239
+ durationMs,
240
+ response,
241
+ ...status === 0 ? { error: "request failed" } : {}
242
+ });
243
+ });
244
+ return send.call(this, body);
245
+ };
246
+ restorers.push(() => {
247
+ proto.open = open;
248
+ proto.send = send;
249
+ proto.setRequestHeader = setRequestHeader;
250
+ });
251
+ }
252
+ function observeLongTasks() {
253
+ if (typeof PerformanceObserver === "undefined") return;
254
+ try {
255
+ const observer = new PerformanceObserver((list) => {
256
+ for (const entry of list.getEntries()) {
257
+ const durationMs = Math.round(entry.duration);
258
+ record({
259
+ kind: "longtask",
260
+ text: `long task ${durationMs} ms`,
261
+ durationMs
262
+ });
263
+ }
264
+ });
265
+ observer.observe({
266
+ type: "longtask",
267
+ buffered: true
268
+ });
269
+ restorers.push(() => observer.disconnect());
270
+ } catch {}
271
+ }
272
+ /**
273
+ * Installs the patches on the first call and returns a release function; the
274
+ * last release restores the originals. Reference counted so StrictMode's
275
+ * mount-unmount-mount and two HUDs on one page neither double-patch nor
276
+ * unpatch under each other. The first caller's `ignore` wins; `requests` is
277
+ * counted on its own, so request detail flows while any holder asked for it.
278
+ */
279
+ function installCapture({ ignore = isHudRoute, requests = false } = {}) {
280
+ if (typeof window === "undefined") return () => {};
281
+ if (installs === 0) {
282
+ patchConsole();
283
+ listenErrors();
284
+ patchFetch(ignore);
285
+ patchXhr(ignore);
286
+ observeLongTasks();
287
+ }
288
+ installs++;
289
+ if (requests) requestWatchers++;
290
+ let released = false;
291
+ return () => {
292
+ if (released) return;
293
+ released = true;
294
+ installs--;
295
+ if (requests) requestWatchers--;
296
+ if (installs === 0) while (restorers.length > 0) restorers.pop()?.();
297
+ };
298
+ }
299
+ //#endregion
300
+ export { installCapture as t };
@@ -0,0 +1,35 @@
1
+ //#region src/plugins/observe/capture-buffer.d.ts
2
+ type CaptureKind = "log" | "warn" | "error" | "fetch" | "xhr" | "longtask";
3
+ interface Stamped {
4
+ id: number;
5
+ ts: number;
6
+ }
7
+ interface CaptureEntryInput {
8
+ kind: CaptureKind;
9
+ text: string;
10
+ status?: number;
11
+ durationMs?: number;
12
+ }
13
+ interface CaptureEntry extends CaptureEntryInput, Stamped {}
14
+ /**
15
+ * Fixed-size ring buffer with a referentially-stable snapshot, shaped for
16
+ * `useSyncExternalStore`: the snapshot array is replaced on every mutation
17
+ * and reused between mutations. Entries get an increasing `id` and a `ts`.
18
+ */
19
+ declare class RingBuffer<Input extends object> {
20
+ private entries;
21
+ private snapshot;
22
+ private listeners;
23
+ private nextId;
24
+ private readonly maxEntries;
25
+ constructor(maxEntries?: number);
26
+ push(input: Input): Input & Stamped;
27
+ /** Merges `patch` into the entry with `id`; a no-op once the ring has dropped it. */
28
+ update(id: number, patch: Partial<Input>): void;
29
+ clear(): void;
30
+ getSnapshot: () => readonly (Input & Stamped)[];
31
+ subscribe: (listener: () => void) => (() => void);
32
+ private emit;
33
+ }
34
+ //#endregion
35
+ export { Stamped as i, CaptureKind as n, RingBuffer as r, CaptureEntry as t };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.js ADDED
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+ import { r as isExcluded } from "./scan-DzJNXqOk.js";
3
+ //#region src/plugins/routes/sweep.ts
4
+ /** Console errors every dev server produces that never mean a broken page. */
5
+ const DEFAULT_CONSOLE_IGNORE = [
6
+ /favicon\.ico/i,
7
+ /Download the React DevTools/i,
8
+ /\[Fast Refresh\]/i
9
+ ];
10
+ const PLAYWRIGHT_MODULES = [
11
+ "playwright",
12
+ "@playwright/test",
13
+ "playwright-core"
14
+ ];
15
+ /** Whichever Playwright package the app has; `@playwright/test` re-exports `chromium`. */
16
+ async function loadPlaywright(importer = (specifier) => import(specifier)) {
17
+ for (const name of PLAYWRIGHT_MODULES) try {
18
+ const mod = await importer(name);
19
+ if (mod.chromium) return mod;
20
+ } catch {}
21
+ throw new Error("hud sweep needs Playwright: add `playwright` (or `@playwright/test`) to the app and run `npx playwright install chromium`");
22
+ }
23
+ async function launchChromium() {
24
+ return (await loadPlaywright()).chromium.launch({ headless: true });
25
+ }
26
+ function joinUrl(base, path) {
27
+ return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
28
+ }
29
+ /** The route list from the running app's `routes` plugin. */
30
+ async function fetchRoutes(base, apiBase, doFetch = fetch) {
31
+ const url = joinUrl(base, `${apiBase.replace(/^\/+|\/+$/g, "")}/routes/routes`);
32
+ let res;
33
+ try {
34
+ res = await doFetch(url, { headers: { accept: "application/json" } });
35
+ } catch (error) {
36
+ throw new Error(`hud sweep: ${url} unreachable (${describe(error)})`);
37
+ }
38
+ if (res.status === 404) throw new Error(`hud sweep: ${url} answered 404: mount routes() in createHudHandler and run the server in development`);
39
+ const body = await res.json().catch(() => void 0);
40
+ if (!res.ok || !body || body.ok !== true) {
41
+ const detail = body && "error" in body && body.error ? `: ${body.error}` : "";
42
+ throw new Error(`hud sweep: ${url} answered ${res.status}${detail}`);
43
+ }
44
+ return body.routes;
45
+ }
46
+ function describe(error) {
47
+ return error instanceof Error ? error.message : String(error);
48
+ }
49
+ async function visit(browser, url, { timeoutMs, settleMs, ignore, hudApi }) {
50
+ const page = await browser.newPage();
51
+ const consoleErrors = [];
52
+ const pageErrors = [];
53
+ page.on("console", (message) => {
54
+ if (message.type() !== "error") return;
55
+ if (message.location?.().url.startsWith(hudApi)) return;
56
+ consoleErrors.push(message.text());
57
+ });
58
+ page.on("pageerror", (error) => pageErrors.push(error.message));
59
+ try {
60
+ const response = await page.goto(url, {
61
+ waitUntil: "load",
62
+ timeout: timeoutMs
63
+ });
64
+ if (settleMs > 0) await page.waitForTimeout(settleMs);
65
+ return {
66
+ status: response ? response.status() : null,
67
+ finalUrl: page.url(),
68
+ consoleErrors: consoleErrors.filter((text) => !ignore.some((re) => re.test(text))),
69
+ pageErrors
70
+ };
71
+ } catch (error) {
72
+ return {
73
+ status: null,
74
+ finalUrl: null,
75
+ consoleErrors: [],
76
+ pageErrors,
77
+ error: describe(error)
78
+ };
79
+ } finally {
80
+ await page.close();
81
+ }
82
+ }
83
+ /** Fetches the route list, visits every resolved URL and returns the report. Never throws per route. */
84
+ async function sweep(options) {
85
+ const base = options.base.replace(/\/+$/, "");
86
+ const apiBase = options.apiBase ?? "/api/hud";
87
+ const timeoutMs = options.timeoutMs ?? 3e4;
88
+ const settleMs = options.settleMs ?? 500;
89
+ const ignore = [...DEFAULT_CONSOLE_IGNORE, ...options.ignoreConsole ?? []];
90
+ const hudApi = `${joinUrl(base, apiBase)}/`;
91
+ const routes = await fetchRoutes(base, apiBase, options.fetch);
92
+ const results = [];
93
+ const report = (result) => {
94
+ results.push(result);
95
+ options.onResult?.(result);
96
+ };
97
+ const browser = await (options.launch ?? launchChromium)();
98
+ try {
99
+ for (const route of routes) {
100
+ if (isExcluded(route, options.exclude)) continue;
101
+ if (route.unresolved.length > 0) {
102
+ report({
103
+ pattern: route.pattern,
104
+ url: route.path,
105
+ status: null,
106
+ finalUrl: null,
107
+ consoleErrors: [],
108
+ pageErrors: [],
109
+ ok: true,
110
+ skipped: true,
111
+ reason: `no fixture: ${route.unresolved.join(", ")}`
112
+ });
113
+ continue;
114
+ }
115
+ for (const { url } of route.urls) {
116
+ const outcome = await visit(browser, joinUrl(base, url), {
117
+ timeoutMs,
118
+ settleMs,
119
+ ignore,
120
+ hudApi
121
+ });
122
+ const ok = outcome.error === void 0 && (outcome.status === null || outcome.status < 500) && outcome.consoleErrors.length === 0 && outcome.pageErrors.length === 0;
123
+ report({
124
+ pattern: route.pattern,
125
+ url,
126
+ ...outcome,
127
+ ok,
128
+ skipped: false
129
+ });
130
+ }
131
+ }
132
+ } finally {
133
+ await browser.close();
134
+ }
135
+ return {
136
+ base,
137
+ total: results.length,
138
+ visited: results.filter((r) => !r.skipped).length,
139
+ skipped: results.filter((r) => r.skipped).length,
140
+ failed: results.filter((r) => !r.ok).length,
141
+ results
142
+ };
143
+ }
144
+ /** One line per result, for a terminal. */
145
+ function formatResult(result) {
146
+ if (result.skipped) return ` · skip ${result.url} (${result.reason ?? "skipped"})`;
147
+ const mark = result.ok ? "✓" : "✗";
148
+ const status = result.status === null ? "---" : String(result.status).padStart(3);
149
+ const notes = [];
150
+ if (result.error) notes.push(result.error);
151
+ if (result.pageErrors.length) notes.push(`${result.pageErrors.length} uncaught`);
152
+ if (result.consoleErrors.length) notes.push(`${result.consoleErrors.length} console error(s)`);
153
+ const detail = [...result.pageErrors, ...result.consoleErrors].slice(0, 3).map((line) => `\n ${line.split("\n")[0]?.slice(0, 160)}`).join("");
154
+ return ` ${mark} ${status} ${result.url}${notes.length ? ` (${notes.join(", ")})` : ""}${detail}`;
155
+ }
156
+ function formatSweepReport(report) {
157
+ const verdict = report.failed > 0 ? `${report.failed} failed` : report.visited > 0 ? "no 5xx, no uncaught errors, no console errors" : "nothing visited";
158
+ return `${report.visited} visited · ${report.skipped} skipped · ${verdict}`;
159
+ }
160
+ //#endregion
161
+ //#region src/cli/args.ts
162
+ const USAGE = `hud sweep --base <url> [options]
163
+
164
+ Visits every route the running app's routes plugin lists, headless, and fails on
165
+ a 5xx answer, an uncaught error or a console error.
166
+
167
+ Options
168
+ --base <url> dev server origin, e.g. http://localhost:3000 (required)
169
+ --api <path> where createHudHandler is mounted (default /api/hud)
170
+ --json print the report as JSON instead of lines
171
+ --timeout <ms> per-navigation timeout (default 30000)
172
+ --wait <ms> settle time after load (default 500)
173
+ --ignore-console <re> ignore console errors matching this pattern (repeatable)
174
+ --exclude <path> skip a URL path or folder pattern, trailing * allowed (repeatable)
175
+
176
+ Exit codes: 0 clean, 1 at least one route failed, 2 usage or setup error.`;
177
+ var UsageError = class extends Error {};
178
+ function next(argv, i, flag) {
179
+ const value = argv[i + 1];
180
+ if (value === void 0 || value.startsWith("--")) throw new UsageError(`${flag} needs a value`);
181
+ return value;
182
+ }
183
+ function integer(value, flag) {
184
+ const n = Number(value);
185
+ if (!Number.isInteger(n) || n < 0) throw new UsageError(`${flag} needs a non-negative integer`);
186
+ return n;
187
+ }
188
+ /** `argv` without the runtime and script. */
189
+ function parseArgs(argv) {
190
+ const [command, ...rest] = argv;
191
+ if (command === void 0 || command === "--help" || command === "-h" || command === "help") return { command: "help" };
192
+ if (command !== "sweep") throw new UsageError(`unknown command "${command}"`);
193
+ const args = {
194
+ command: "sweep",
195
+ base: "",
196
+ apiBase: "/api/hud",
197
+ json: false,
198
+ timeoutMs: 3e4,
199
+ settleMs: 500,
200
+ ignoreConsole: [],
201
+ exclude: []
202
+ };
203
+ for (let i = 0; i < rest.length; i++) {
204
+ const flag = rest[i] ?? "";
205
+ const [name, inline] = flag.includes("=") ? flag.split(/=(.*)/s, 2) : [flag, void 0];
206
+ const value = () => {
207
+ if (inline !== void 0) return inline;
208
+ const v = next(rest, i, flag);
209
+ i++;
210
+ return v;
211
+ };
212
+ switch (name) {
213
+ case "--base":
214
+ args.base = value();
215
+ break;
216
+ case "--api":
217
+ args.apiBase = value();
218
+ break;
219
+ case "--json":
220
+ args.json = true;
221
+ break;
222
+ case "--timeout":
223
+ args.timeoutMs = integer(value(), name);
224
+ break;
225
+ case "--wait":
226
+ args.settleMs = integer(value(), name);
227
+ break;
228
+ case "--ignore-console":
229
+ args.ignoreConsole.push(new RegExp(value(), "i"));
230
+ break;
231
+ case "--exclude":
232
+ args.exclude.push(value());
233
+ break;
234
+ default: throw new UsageError(`unknown option "${flag}"`);
235
+ }
236
+ }
237
+ if (!args.base) throw new UsageError("--base <url> is required");
238
+ if (!/^https?:\/\//.test(args.base)) throw new UsageError("--base must start with http:// or https://");
239
+ return args;
240
+ }
241
+ //#endregion
242
+ //#region src/cli/index.ts
243
+ async function main(argv) {
244
+ const args = parseArgs(argv);
245
+ if (args.command === "help") {
246
+ process.stdout.write(`${USAGE}\n`);
247
+ return 0;
248
+ }
249
+ const quiet = args.json;
250
+ const log = (line) => {
251
+ if (!quiet) process.stdout.write(`${line}\n`);
252
+ };
253
+ log(`hud sweep ${args.base}`);
254
+ const report = await sweep({
255
+ base: args.base,
256
+ apiBase: args.apiBase,
257
+ timeoutMs: args.timeoutMs,
258
+ settleMs: args.settleMs,
259
+ ignoreConsole: args.ignoreConsole,
260
+ exclude: args.exclude,
261
+ onResult: (result) => log(formatResult(result))
262
+ });
263
+ if (args.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
264
+ else log(formatSweepReport(report));
265
+ return report.failed > 0 ? 1 : 0;
266
+ }
267
+ main(process.argv.slice(2)).then((code) => {
268
+ process.exitCode = code;
269
+ }, (error) => {
270
+ const message = error instanceof Error ? error.message : String(error);
271
+ process.stderr.write(`${message}\n`);
272
+ if (error instanceof UsageError) process.stderr.write(`\n${USAGE}\n`);
273
+ process.exitCode = 2;
274
+ });
275
+ //#endregion