@hansenexus/hud 0.4.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 (157) hide show
  1. package/README.md +603 -9
  2. package/dist/a11y-B5DUaiCs.js +246 -0
  3. package/dist/a11y-panel-p_t4eD7p.js +207 -0
  4. package/dist/{capabilities-CjulXFQX.js → access-C7zlaqj6.js} +1 -90
  5. package/dist/{access-CNvJOwKM.d.ts → access-D_ewAEJG.d.ts} +11 -4
  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-vEjyJfPW.d.ts → env-CApnbI0r.d.ts} +2 -0
  26. package/dist/{env-DfxpPfs9.js → env-CaiFPIhF.js} +3 -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-panel-_otVYh9i.js +97 -0
  32. package/dist/generate-C8lQl3Eh.js +53 -0
  33. package/dist/handler-BpVhxEmU.js +106 -0
  34. package/dist/{handler-WmE4Lu7l.d.ts → handler-DtYVCZY6.d.ts} +1 -1
  35. package/dist/index-BAV_1W8a.d.ts +43 -0
  36. package/dist/index-BJ26pse9.d.ts +70 -0
  37. package/dist/index-BnQ0dTZf.d.ts +19 -0
  38. package/dist/index-CwfX-W87.d.ts +72 -0
  39. package/dist/index-DcH9V3cU.d.ts +48 -0
  40. package/dist/index-DqOyNf1u.d.ts +65 -0
  41. package/dist/index-DstI_ike.d.ts +66 -0
  42. package/dist/index-Dxz4fn4j.d.ts +42 -0
  43. package/dist/index-Hhh7OXzU.d.ts +129 -0
  44. package/dist/index-ReFbhQ9p.d.ts +25 -0
  45. package/dist/index-RgXfMBuW.d.ts +48 -0
  46. package/dist/{index-BYsdS-7d.d.ts → index-gCZBO53s.d.ts} +21 -3
  47. package/dist/index.d.ts +5 -5
  48. package/dist/index.js +710 -69
  49. package/dist/inspect-C9Ft8fqn.js +142 -0
  50. package/dist/inspect-root-BkaupBMp.js +429 -0
  51. package/dist/meta-Bv0sEao3.js +6 -0
  52. package/dist/meta-C_G7MB5w.d.ts +49 -0
  53. package/dist/mocks-CA-wM2SB.d.ts +109 -0
  54. package/dist/mocks-ESiRqk9o.js +150 -0
  55. package/dist/msw-browser-wjaYgkB7.d.ts +31 -0
  56. package/dist/next/config.d.ts +52 -0
  57. package/dist/next/config.js +78 -0
  58. package/dist/next.d.ts +14 -4
  59. package/dist/next.js +5 -3
  60. package/dist/observe-CdDnDBRP.js +89 -0
  61. package/dist/observe-panel-Cgp1M8oT.js +347 -0
  62. package/dist/ops-panel-CEqDe_UT.js +234 -0
  63. package/dist/{payload-CLKDVZWl.d.ts → payload-MUQ9ciER.d.ts} +25 -1
  64. package/dist/plugins/a11y.d.ts +2 -0
  65. package/dist/plugins/a11y.js +2 -0
  66. package/dist/plugins/access/server.d.ts +5 -5
  67. package/dist/plugins/access/server.js +4 -3
  68. package/dist/plugins/access.d.ts +5 -5
  69. package/dist/plugins/access.js +16 -215
  70. package/dist/plugins/agent/server.d.ts +3 -38
  71. package/dist/plugins/agent/server.js +47 -21
  72. package/dist/plugins/agent.d.ts +4 -4
  73. package/dist/plugins/agent.js +6 -348
  74. package/dist/plugins/capture/server.d.ts +92 -0
  75. package/dist/plugins/capture/server.js +248 -0
  76. package/dist/plugins/capture.d.ts +24 -0
  77. package/dist/plugins/capture.js +70 -0
  78. package/dist/plugins/data/msw-browser.d.ts +2 -0
  79. package/dist/plugins/data/msw-browser.js +39 -0
  80. package/dist/plugins/data/msw-node.d.ts +36 -0
  81. package/dist/plugins/data/msw-node.js +68 -0
  82. package/dist/plugins/data/server.d.ts +257 -0
  83. package/dist/plugins/data/server.js +717 -0
  84. package/dist/plugins/data.d.ts +6 -0
  85. package/dist/plugins/data.js +51 -0
  86. package/dist/plugins/design/server.d.ts +54 -0
  87. package/dist/plugins/design/server.js +198 -0
  88. package/dist/plugins/design.d.ts +4 -124
  89. package/dist/plugins/design.js +4 -619
  90. package/dist/plugins/inspect/convex.d.ts +2 -0
  91. package/dist/plugins/inspect/convex.js +486 -0
  92. package/dist/plugins/inspect/react-query.d.ts +2 -0
  93. package/dist/plugins/inspect/react-query.js +225 -0
  94. package/dist/plugins/inspect/sockets.d.ts +51 -0
  95. package/dist/plugins/inspect/sockets.js +397 -0
  96. package/dist/plugins/inspect/swr.d.ts +2 -0
  97. package/dist/plugins/inspect/swr.js +218 -0
  98. package/dist/plugins/inspect.d.ts +4 -0
  99. package/dist/plugins/inspect.js +3 -0
  100. package/dist/plugins/observe.d.ts +4 -64
  101. package/dist/plugins/observe.js +1 -616
  102. package/dist/plugins/ops/server.d.ts +1 -1
  103. package/dist/plugins/ops/server.js +2 -1
  104. package/dist/plugins/ops.d.ts +2 -1
  105. package/dist/plugins/ops.js +15 -336
  106. package/dist/plugins/routes/server.d.ts +88 -0
  107. package/dist/plugins/routes/server.js +62 -0
  108. package/dist/plugins/routes.d.ts +3 -0
  109. package/dist/plugins/routes.js +216 -0
  110. package/dist/plugins/seo.d.ts +2 -0
  111. package/dist/plugins/seo.js +2 -0
  112. package/dist/plugins/vitals.d.ts +2 -25
  113. package/dist/plugins/vitals.js +3 -2
  114. package/dist/{plugins-CQ_0w1ot.d.ts → plugins-BZvDqGx5.d.ts} +33 -3
  115. package/dist/poll-CjKsWZi8.js +89 -0
  116. package/dist/requests-BwD6MKEq.js +282 -0
  117. package/dist/requests-CJrUf465.d.ts +50 -0
  118. package/dist/review.js +2 -2
  119. package/dist/same-origin-BGet22CC.js +21 -0
  120. package/dist/scan-DzJNXqOk.js +165 -0
  121. package/dist/seo-Dq9q_QkO.js +551 -0
  122. package/dist/seo-panel-CfiY-TnT.js +124 -0
  123. package/dist/server.d.ts +2 -2
  124. package/dist/server.js +2 -105
  125. package/dist/sessions-panel-COvhPAzv.js +98 -0
  126. package/dist/{shortcut-U6ftVY06.js → shortcut-s_mjGeU8.js} +1 -44
  127. package/dist/{types-QJUajwWq.js → state-CjjZPjPJ.js} +13 -8
  128. package/dist/store/convex.d.ts +33 -0
  129. package/dist/store/convex.js +52 -0
  130. package/dist/{vitals-panel-Dvc5dnR-.js → store-CQqIIKTc.js} +1 -29
  131. package/dist/store-Ync9eb1G.js +67 -0
  132. package/dist/store.d.ts +76 -0
  133. package/dist/store.js +188 -0
  134. package/dist/{styles--slk86ZQ.js → styles-BA8ueHoV.js} +13 -3
  135. package/dist/styles-DKU_P8MH.js +139 -0
  136. package/dist/styles-DPpDPmzi.js +68 -0
  137. package/dist/tokens-panel-CbMQfasZ.js +142 -0
  138. package/dist/types-B-ulf2Jp.js +8 -0
  139. package/dist/types-BIgGf-0C.d.ts +25 -0
  140. package/dist/types-BIkI-qN8.js +30 -0
  141. package/dist/{types-DADBRiGk.d.ts → types-Cxh4twqc.d.ts} +1 -1
  142. package/dist/types-DIdPfjtV.js +6 -0
  143. package/dist/types-DaJcsEjO.d.ts +44 -0
  144. package/dist/types-Dn68psVz.d.ts +118 -0
  145. package/dist/types-szkr2QOF.d.ts +39 -0
  146. package/dist/unlock-store-4V3vR4Eg.js +96 -0
  147. package/dist/variant-groups-TIfO3NIj.js +137 -0
  148. package/dist/variant-groups-aAIrcNK5.d.ts +36 -0
  149. package/dist/variants-panel-BDoSkwBJ.js +457 -0
  150. package/dist/variants-types-CcRf119M.d.ts +63 -0
  151. package/dist/variants.d.ts +43 -0
  152. package/dist/variants.js +83 -0
  153. package/dist/vitals-panel-BCmMUntW.js +30 -0
  154. package/dist/vite.d.ts +37 -0
  155. package/dist/vite.js +134 -0
  156. package/package.json +65 -5
  157. package/dist/define-hud-BBzsSl8b.d.ts +0 -36
@@ -0,0 +1,33 @@
1
+ import { ComponentType } from "react";
2
+ //#region src/plugins/inspect/adapter.d.ts
3
+ /**
4
+ * An inspect adapter adds a tab to the Inspect panel for one data source:
5
+ * Convex, React Query, SWR, sockets. Each adapter is its own subpath export
6
+ * (`@hansenexus/hud/plugins/inspect/<id>`), so an app that omits one ships
7
+ * none of its code; the inspect core only knows this interface.
8
+ */
9
+ interface InspectAdapter {
10
+ /** Tab id, unique among the adapters of one inspect plugin. */
11
+ id: string;
12
+ /** Tab label. */
13
+ title: string;
14
+ /** Tab content. Rendered inside the Inspect panel, so `.insp-*` classes apply. */
15
+ Panel: ComponentType;
16
+ /** Hook returning the count shown next to the tab label. */
17
+ useCount?: () => number;
18
+ /**
19
+ * Called when the HUD mounts (and again after a StrictMode re-mount), for
20
+ * work that must run after the app's bootstrap: re-checking a patched
21
+ * global, say.
22
+ */
23
+ install?: () => void;
24
+ /** Undoes what the factory installed (patches, subscriptions). Test seam. */
25
+ dispose?: () => void;
26
+ }
27
+ interface Preview {
28
+ /** Redacted JSON, at most `MAX_BODY` characters. */
29
+ text: string;
30
+ truncated: boolean;
31
+ }
32
+ //#endregion
33
+ export { Preview as n, InspectAdapter as t };
@@ -0,0 +1,65 @@
1
+ import { p as redactBody, t as MAX_BODY } from "./requests-BwD6MKEq.js";
2
+ import { useEffect, useState } from "react";
3
+ //#region src/plugins/inspect/adapter.ts
4
+ /**
5
+ * A value as the inspector shows it: JSON with sensitive keys redacted,
6
+ * capped at the request body limit. Values that cannot be serialised
7
+ * (cycles, bigints) are described instead.
8
+ */
9
+ function preview(value) {
10
+ let json;
11
+ try {
12
+ json = value === void 0 ? "undefined" : JSON.stringify(value) ?? String(value);
13
+ } catch (error) {
14
+ return {
15
+ text: `[unserialisable: ${error instanceof Error ? error.message : String(error)}]`,
16
+ truncated: false
17
+ };
18
+ }
19
+ const truncated = json.length > MAX_BODY;
20
+ return {
21
+ text: redactBody(truncated ? json.slice(0, MAX_BODY) : json, "application/json"),
22
+ truncated
23
+ };
24
+ }
25
+ /** Pretty-printed form of a `preview()` text, for a detail view. */
26
+ function prettyPreview({ text, truncated }) {
27
+ let body = text;
28
+ try {
29
+ body = JSON.stringify(JSON.parse(text), null, 2);
30
+ } catch {}
31
+ return truncated ? `${body}\n… (truncated)` : body;
32
+ }
33
+ /** `3 s ago`, `2 min ago`, `just now`; `never` without a timestamp. */
34
+ function ago(ts, now) {
35
+ if (ts === void 0 || ts === 0) return "never";
36
+ const seconds = Math.max(0, Math.round((now - ts) / 1e3));
37
+ if (seconds < 1) return "just now";
38
+ if (seconds < 60) return `${seconds} s ago`;
39
+ const minutes = Math.round(seconds / 60);
40
+ if (minutes < 60) return `${minutes} min ago`;
41
+ return `${Math.round(minutes / 60)} h ago`;
42
+ }
43
+ /** The current time, refreshed every `intervalMs` while mounted, for relative timestamps. */
44
+ function useNow(intervalMs = 1e3) {
45
+ const [now, setNow] = useState(() => Date.now());
46
+ useEffect(() => {
47
+ const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
48
+ return () => window.clearInterval(timer);
49
+ }, [intervalMs]);
50
+ return now;
51
+ }
52
+ /** A short one-line form of a value for a row: a string as is, anything else as compact JSON. */
53
+ function oneLine(value, max = 60) {
54
+ const text = typeof value === "string" ? value : preview(value).text;
55
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
56
+ }
57
+ /** Bytes of a frame or body, for sockets and blobs. */
58
+ function byteSize(data) {
59
+ if (typeof data === "string") return new TextEncoder().encode(data).byteLength;
60
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
61
+ if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return data.byteLength;
62
+ return 0;
63
+ }
64
+ //#endregion
65
+ export { preview as a, prettyPreview as i, byteSize as n, useNow as o, oneLine as r, ago as t };
@@ -0,0 +1,65 @@
1
+ import { t as HudAutoDetected } from "../detect-BxHZ0pxW.js";
2
+ import { o as HudPlugin } from "../plugins-BZvDqGx5.js";
3
+ import { n as a11y, t as A11yOptions } from "../index-DqOyNf1u.js";
4
+ import { n as data } from "../index-DstI_ike.js";
5
+ import { t as forceState } from "../index-Hhh7OXzU.js";
6
+ import { t as InspectAdapter } from "../adapter-BYoxPYTI.js";
7
+ import { n as InspectOptions, r as inspect } from "../index-CwfX-W87.js";
8
+ import { r as inspectConvex, t as ConvexClientLike } from "../index-BJ26pse9.js";
9
+ import { i as inspectReactQuery, n as QueryClientLike } from "../index-RgXfMBuW.js";
10
+ import { o as inspectSwr, t as InspectSwrOptions } from "../index-Dxz4fn4j.js";
11
+ import { n as observe, t as ObserveOptions } from "../index-BAV_1W8a.js";
12
+ import { t as routes } from "../index-BnQ0dTZf.js";
13
+ import { t as seo } from "../index-DcH9V3cU.js";
14
+ import { t as vitals } from "../index-ReFbhQ9p.js";
15
+ //#region src/auto/runtime.d.ts
16
+ /**
17
+ * What `auto()` takes: the instances a detected adapter wraps (a package can
18
+ * find a dependency, not the app's client object) and the options of the base
19
+ * plugins. Everything is optional; a detected adapter without its instance
20
+ * shows a tab that says what to pass.
21
+ */
22
+ export interface HudAutoOptions {
23
+ /** The app's Convex client, when `convex` is detected: the Convex tab wraps it in place. */
24
+ convex?: ConvexClientLike | undefined;
25
+ /** The app's `QueryClient`, when `@tanstack/react-query` is detected. */
26
+ queryClient?: QueryClientLike | undefined;
27
+ /** The SWR cache and `mutate`, when `swr` is detected. */
28
+ swr?: InspectSwrOptions | undefined;
29
+ /** Passed on to `observe()`: env values and the user hook for the Info tab. */
30
+ observe?: ObserveOptions | undefined;
31
+ /** Passed on to `inspect()`: URLs to leave out of the capture. */
32
+ inspect?: Pick<InspectOptions, "ignore"> | undefined;
33
+ /** Passed on to `a11y()`: your own axe loader. */
34
+ a11y?: A11yOptions | undefined;
35
+ }
36
+ /**
37
+ * The factories the generated module imports. Base ones are always there;
38
+ * the rest only when detection turned the feature on, so an undetected
39
+ * plugin is not in the module graph.
40
+ */
41
+ export interface HudAutoFactories {
42
+ vitals: typeof vitals;
43
+ observe: typeof observe;
44
+ inspect: typeof inspect;
45
+ forceState: typeof forceState;
46
+ a11y: typeof a11y;
47
+ seo: typeof seo;
48
+ routes?: typeof routes | undefined;
49
+ data?: typeof data | undefined;
50
+ inspectConvex?: typeof inspectConvex | undefined;
51
+ inspectReactQuery?: typeof inspectReactQuery | undefined;
52
+ inspectSwr?: typeof inspectSwr | undefined;
53
+ }
54
+ /** A tab standing in for a detected adapter whose instance was not passed. */
55
+ export declare function unwired(id: string, title: string, dep: string, hint: string): InspectAdapter;
56
+ /**
57
+ * The plugin list behind `auto()`: the base plugins (vitals, observe, inspect
58
+ * with one tab per detected data source, force-state, a11y, seo), plus
59
+ * routes for a Next app and data where an auth library or MSW is installed.
60
+ * Pill order is this order; `defineHud({ auto, plugins })` replaces an entry
61
+ * by id and appends the rest.
62
+ */
63
+ export declare function assembleAuto(detected: HudAutoDetected, factories: HudAutoFactories, options?: HudAutoOptions): HudPlugin[];
64
+ //#endregion
65
+ export type { HudAutoDetected };
@@ -0,0 +1,50 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ //#region src/auto/runtime.tsx
3
+ /** A tab standing in for a detected adapter whose instance was not passed. */
4
+ function unwired(id, title, dep, hint) {
5
+ return {
6
+ id,
7
+ title,
8
+ Panel: () => /* @__PURE__ */ jsxs("p", {
9
+ className: "empty",
10
+ "data-auto-unwired": id,
11
+ children: [
12
+ /* @__PURE__ */ jsx("code", { children: dep }),
13
+ " is installed. Pass its instance to see it here:",
14
+ " ",
15
+ /* @__PURE__ */ jsxs("code", { children: [
16
+ "auto(",
17
+ `{ ${hint} }`,
18
+ ")"
19
+ ] })
20
+ ]
21
+ })
22
+ };
23
+ }
24
+ /**
25
+ * The plugin list behind `auto()`: the base plugins (vitals, observe, inspect
26
+ * with one tab per detected data source, force-state, a11y, seo), plus
27
+ * routes for a Next app and data where an auth library or MSW is installed.
28
+ * Pill order is this order; `defineHud({ auto, plugins })` replaces an entry
29
+ * by id and appends the rest.
30
+ */
31
+ function assembleAuto(detected, factories, options = {}) {
32
+ const adapters = [];
33
+ if (factories.inspectConvex) adapters.push(options.convex ? factories.inspectConvex({ client: options.convex }) : unwired("convex", "Convex", "convex", "convex: client"));
34
+ if (factories.inspectReactQuery) adapters.push(options.queryClient ? factories.inspectReactQuery({ queryClient: options.queryClient }) : unwired("react-query", "Query", "@tanstack/react-query", "queryClient"));
35
+ if (factories.inspectSwr) adapters.push(options.swr ? factories.inspectSwr(options.swr) : unwired("swr", "SWR", "swr", "swr: { cache, mutate }"));
36
+ const plugins = [
37
+ factories.vitals(),
38
+ factories.observe(options.observe),
39
+ factories.inspect({
40
+ ...options.inspect,
41
+ adapters
42
+ })
43
+ ];
44
+ if (factories.routes && detected.next) plugins.push(factories.routes());
45
+ if (factories.data && (detected.betterAuth || detected.convexAuth || detected.msw)) plugins.push(factories.data());
46
+ plugins.push(factories.forceState(), factories.a11y(options.a11y), factories.seo());
47
+ return plugins;
48
+ }
49
+ //#endregion
50
+ export { assembleAuto, unwired };
package/dist/auto.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { t as HudAutoDetected } from "./detect-BxHZ0pxW.js";
2
+ import { o as HudPlugin } from "./plugins-BZvDqGx5.js";
3
+ import "./index-gCZBO53s.js";
4
+ import { HudAutoFactories, HudAutoOptions } from "./auto/runtime.js";
5
+ //#region src/auto/index.d.ts
6
+ /** Nothing detected: this is the stand-in (`configured: false`). */
7
+ export declare const detected: HudAutoDetected;
8
+ /**
9
+ * The base plugins only. The generated module, served when `hud()` is in
10
+ * vite.config or `withHud()` wraps next.config, adds one inspect tab per
11
+ * detected data source, routes for Next and data for an auth library or MSW.
12
+ */
13
+ export declare function auto(options?: HudAutoOptions): HudPlugin[];
14
+ //#endregion
15
+ export { type HudAutoDetected, type HudAutoFactories, type HudAutoOptions, auto as default };
package/dist/auto.js ADDED
@@ -0,0 +1,33 @@
1
+ import { t as NOTHING_DETECTED } from "./detect-CHZiSeZs.js";
2
+ import { t as a11y } from "./a11y-B5DUaiCs.js";
3
+ import { t as forceState } from "./design-D0kGgPoP.js";
4
+ import { n as inspect } from "./inspect-C9Ft8fqn.js";
5
+ import { t as observe } from "./observe-CdDnDBRP.js";
6
+ import { t as seo } from "./seo-Dq9q_QkO.js";
7
+ import { vitals } from "./plugins/vitals.js";
8
+ import { assembleAuto } from "./auto/runtime.js";
9
+ //#region src/auto/index.ts
10
+ /** Nothing detected: this is the stand-in (`configured: false`). */
11
+ const detected = NOTHING_DETECTED;
12
+ let warned = false;
13
+ /**
14
+ * The base plugins only. The generated module, served when `hud()` is in
15
+ * vite.config or `withHud()` wraps next.config, adds one inspect tab per
16
+ * detected data source, routes for Next and data for an auth library or MSW.
17
+ */
18
+ function auto(options) {
19
+ if (!warned) {
20
+ warned = true;
21
+ console.warn("hud: @hansenexus/hud/auto is the stand-in, no bundler plugin read package.json. Add hud() from @hansenexus/hud/vite to vite.config, or wrap next.config with withHud() from @hansenexus/hud/next/config, to enable plugins per dependency.");
22
+ }
23
+ return assembleAuto(detected, {
24
+ vitals,
25
+ observe,
26
+ inspect,
27
+ forceState,
28
+ a11y,
29
+ seo
30
+ }, options);
31
+ }
32
+ //#endregion
33
+ export { auto, auto as default, detected };
@@ -0,0 +1,110 @@
1
+ //#region src/plugins/access/capabilities.ts
2
+ /** The capability vocabulary of the default matrix. Development grants these and any other. */
3
+ const HUD_CAPABILITIES = [
4
+ "observe.app",
5
+ "observe.estate",
6
+ "cicd.read",
7
+ "cicd.trigger",
8
+ "inject.seed",
9
+ "mock.toggle",
10
+ "auth.impersonate",
11
+ "dispatch.local",
12
+ "dispatch.hermes",
13
+ "variants.switch",
14
+ "variants.vote",
15
+ "variants.generate",
16
+ "state.force",
17
+ "routes.read",
18
+ "inspect.read",
19
+ "data.read",
20
+ "data.write",
21
+ "capture.screenshot"
22
+ ];
23
+ /**
24
+ * Capabilities no production matrix may grant. `data.*` switches who the
25
+ * page is signed in as and what the app reads: on production that is a
26
+ * breach, not a tool, so `hasCapability` denies it there whatever an app's
27
+ * `matrix` says, and `resolveMatrix` strips it from a production override.
28
+ */
29
+ function isProductionDenied(capability) {
30
+ return capability.startsWith("data.");
31
+ }
32
+ /**
33
+ * The access plugin's own capability. The guard lets the unlock route through
34
+ * on every enabled tier, so it never needs a matrix entry; nothing else may use it.
35
+ */
36
+ const ACCESS_UNLOCK_CAPABILITY = "access.unlock";
37
+ /**
38
+ * Default-deny capability matrix. Client filtering is convenience only: the
39
+ * guard re-checks every route against the same matrix server side.
40
+ * Staging's `auth.impersonate` is further flag-gated by the plugin that uses it.
41
+ */
42
+ const CAPABILITY_MATRIX = {
43
+ development: HUD_CAPABILITIES,
44
+ staging: [
45
+ "observe.app",
46
+ "observe.estate",
47
+ "cicd.read",
48
+ "mock.toggle",
49
+ "auth.impersonate",
50
+ "variants.switch",
51
+ "variants.vote",
52
+ "routes.read",
53
+ "inspect.read"
54
+ ],
55
+ preview: [
56
+ "observe.app",
57
+ "observe.estate",
58
+ "cicd.read",
59
+ "mock.toggle",
60
+ "variants.switch",
61
+ "variants.vote",
62
+ "routes.read",
63
+ "inspect.read"
64
+ ],
65
+ production: [
66
+ "observe.app",
67
+ "observe.estate",
68
+ "cicd.read"
69
+ ],
70
+ disabled: []
71
+ };
72
+ /**
73
+ * The default matrix with an app's tier lists swapped in. `access.unlock` is
74
+ * stripped from them (it is the guard's exemption, never a grant), and so is
75
+ * `data.*` from production (see `isProductionDenied`).
76
+ */
77
+ function resolveMatrix(override = {}) {
78
+ const matrix = { ...CAPABILITY_MATRIX };
79
+ for (const [tier, list] of Object.entries(override)) if (list) matrix[tier] = list.filter((capability) => capability !== "access.unlock" && !(tier === "production" && isProductionDenied(capability)));
80
+ return matrix;
81
+ }
82
+ /** Core assumes development, so development grants every capability, listed or not. */
83
+ function hasCapability(env, capability, matrix = CAPABILITY_MATRIX) {
84
+ if (env === "disabled") return false;
85
+ if (env === "development") return true;
86
+ if (env === "production" && isProductionDenied(capability)) return false;
87
+ return matrix[env].includes(capability);
88
+ }
89
+ /**
90
+ * Whether the HUD exists at all. Outside development a deployed tier also
91
+ * needs its overlay to set `NEXT_PUBLIC_HUD_ENABLED=true`.
92
+ */
93
+ function isHudVisible(env, enabled = process.env.NEXT_PUBLIC_HUD_ENABLED === "true") {
94
+ if (env === "disabled") return false;
95
+ if (env === "development") return true;
96
+ return enabled;
97
+ }
98
+ const ENVS = [
99
+ "development",
100
+ "preview",
101
+ "staging",
102
+ "production",
103
+ "disabled"
104
+ ];
105
+ /** Narrows the loader's env string; anything unrecognised is treated as disabled. */
106
+ function toHudEnv(env) {
107
+ return ENVS.includes(env) ? env : "disabled";
108
+ }
109
+ //#endregion
110
+ export { isHudVisible as a, toHudEnv as c, hasCapability as i, CAPABILITY_MATRIX as n, isProductionDenied as o, HUD_CAPABILITIES as r, resolveMatrix as s, ACCESS_UNLOCK_CAPABILITY as t };
@@ -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 };