@hansenexus/hud 0.4.0 → 0.5.1

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 (159) hide show
  1. package/README.md +634 -12
  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.cjs +201 -0
  57. package/dist/next/config.d.cts +87 -0
  58. package/dist/next/config.d.ts +64 -0
  59. package/dist/next/config.js +84 -0
  60. package/dist/next.d.ts +14 -4
  61. package/dist/next.js +5 -3
  62. package/dist/observe-CdDnDBRP.js +89 -0
  63. package/dist/observe-panel-Cgp1M8oT.js +347 -0
  64. package/dist/ops-panel-CEqDe_UT.js +234 -0
  65. package/dist/{payload-CLKDVZWl.d.ts → payload-MUQ9ciER.d.ts} +25 -1
  66. package/dist/plugins/a11y.d.ts +2 -0
  67. package/dist/plugins/a11y.js +2 -0
  68. package/dist/plugins/access/server.d.ts +5 -5
  69. package/dist/plugins/access/server.js +4 -3
  70. package/dist/plugins/access.d.ts +5 -5
  71. package/dist/plugins/access.js +16 -215
  72. package/dist/plugins/agent/server.d.ts +3 -38
  73. package/dist/plugins/agent/server.js +47 -21
  74. package/dist/plugins/agent.d.ts +4 -4
  75. package/dist/plugins/agent.js +6 -348
  76. package/dist/plugins/capture/server.d.ts +92 -0
  77. package/dist/plugins/capture/server.js +248 -0
  78. package/dist/plugins/capture.d.ts +24 -0
  79. package/dist/plugins/capture.js +70 -0
  80. package/dist/plugins/data/msw-browser.d.ts +2 -0
  81. package/dist/plugins/data/msw-browser.js +39 -0
  82. package/dist/plugins/data/msw-node.d.ts +36 -0
  83. package/dist/plugins/data/msw-node.js +68 -0
  84. package/dist/plugins/data/server.d.ts +257 -0
  85. package/dist/plugins/data/server.js +717 -0
  86. package/dist/plugins/data.d.ts +6 -0
  87. package/dist/plugins/data.js +51 -0
  88. package/dist/plugins/design/server.d.ts +54 -0
  89. package/dist/plugins/design/server.js +198 -0
  90. package/dist/plugins/design.d.ts +4 -124
  91. package/dist/plugins/design.js +4 -619
  92. package/dist/plugins/inspect/convex.d.ts +2 -0
  93. package/dist/plugins/inspect/convex.js +486 -0
  94. package/dist/plugins/inspect/react-query.d.ts +2 -0
  95. package/dist/plugins/inspect/react-query.js +237 -0
  96. package/dist/plugins/inspect/sockets.d.ts +51 -0
  97. package/dist/plugins/inspect/sockets.js +397 -0
  98. package/dist/plugins/inspect/swr.d.ts +2 -0
  99. package/dist/plugins/inspect/swr.js +218 -0
  100. package/dist/plugins/inspect.d.ts +4 -0
  101. package/dist/plugins/inspect.js +3 -0
  102. package/dist/plugins/observe.d.ts +4 -64
  103. package/dist/plugins/observe.js +1 -616
  104. package/dist/plugins/ops/server.d.ts +1 -1
  105. package/dist/plugins/ops/server.js +2 -1
  106. package/dist/plugins/ops.d.ts +2 -1
  107. package/dist/plugins/ops.js +15 -336
  108. package/dist/plugins/routes/server.d.ts +88 -0
  109. package/dist/plugins/routes/server.js +62 -0
  110. package/dist/plugins/routes.d.ts +3 -0
  111. package/dist/plugins/routes.js +216 -0
  112. package/dist/plugins/seo.d.ts +2 -0
  113. package/dist/plugins/seo.js +2 -0
  114. package/dist/plugins/vitals.d.ts +2 -25
  115. package/dist/plugins/vitals.js +3 -2
  116. package/dist/{plugins-CQ_0w1ot.d.ts → plugins-BZvDqGx5.d.ts} +33 -3
  117. package/dist/poll-CjKsWZi8.js +89 -0
  118. package/dist/requests-BwD6MKEq.js +282 -0
  119. package/dist/requests-CJrUf465.d.ts +50 -0
  120. package/dist/review.js +2 -2
  121. package/dist/same-origin-BGet22CC.js +21 -0
  122. package/dist/scan-DzJNXqOk.js +165 -0
  123. package/dist/seo-Dq9q_QkO.js +551 -0
  124. package/dist/seo-panel-CfiY-TnT.js +124 -0
  125. package/dist/server.d.ts +2 -2
  126. package/dist/server.js +2 -105
  127. package/dist/sessions-panel-COvhPAzv.js +98 -0
  128. package/dist/{shortcut-U6ftVY06.js → shortcut-s_mjGeU8.js} +1 -44
  129. package/dist/{types-QJUajwWq.js → state-CjjZPjPJ.js} +13 -8
  130. package/dist/store/convex.d.ts +33 -0
  131. package/dist/store/convex.js +52 -0
  132. package/dist/{vitals-panel-Dvc5dnR-.js → store-CQqIIKTc.js} +1 -29
  133. package/dist/store-Ync9eb1G.js +67 -0
  134. package/dist/store.d.ts +76 -0
  135. package/dist/store.js +188 -0
  136. package/dist/{styles--slk86ZQ.js → styles-BA8ueHoV.js} +13 -3
  137. package/dist/styles-DKU_P8MH.js +139 -0
  138. package/dist/styles-DPpDPmzi.js +68 -0
  139. package/dist/tokens-panel-CbMQfasZ.js +142 -0
  140. package/dist/types-B-ulf2Jp.js +8 -0
  141. package/dist/types-BIgGf-0C.d.ts +25 -0
  142. package/dist/types-BIkI-qN8.js +30 -0
  143. package/dist/{types-DADBRiGk.d.ts → types-Cxh4twqc.d.ts} +1 -1
  144. package/dist/types-DIdPfjtV.js +6 -0
  145. package/dist/types-DaJcsEjO.d.ts +44 -0
  146. package/dist/types-Dn68psVz.d.ts +118 -0
  147. package/dist/types-szkr2QOF.d.ts +39 -0
  148. package/dist/unlock-store-4V3vR4Eg.js +96 -0
  149. package/dist/variant-groups-TIfO3NIj.js +137 -0
  150. package/dist/variant-groups-aAIrcNK5.d.ts +36 -0
  151. package/dist/variants-panel-BDoSkwBJ.js +457 -0
  152. package/dist/variants-types-CcRf119M.d.ts +63 -0
  153. package/dist/variants.d.ts +43 -0
  154. package/dist/variants.js +83 -0
  155. package/dist/vitals-panel-BCmMUntW.js +30 -0
  156. package/dist/vite.d.ts +37 -0
  157. package/dist/vite.js +134 -0
  158. package/package.json +72 -5
  159. package/dist/define-hud-BBzsSl8b.d.ts +0 -36
@@ -0,0 +1,44 @@
1
+ //#region src/store/types.d.ts
2
+ /**
3
+ * The storage seam. Plugins that keep state (variant scores and decisions,
4
+ * flag overrides) read and write through this interface and never know
5
+ * where the bytes live: `file()` keeps JSON under `.hud/`, `http()` talks to
6
+ * `storeRoutes()` on a dev server, `convex()` (its own entry) to a deployment.
7
+ *
8
+ * A store holds named collections of JSON documents keyed by id. Values are
9
+ * plain JSON objects; the plugin that owns a collection validates the shape,
10
+ * since an agent may have written the file by hand.
11
+ */
12
+ type HudStoreValue = Record<string, unknown>;
13
+ interface HudStoreEntry {
14
+ id: string;
15
+ value: HudStoreValue;
16
+ }
17
+ interface HudStore {
18
+ /** The document, or null when the collection or id does not exist. */
19
+ get: (collection: string, id: string) => Promise<HudStoreValue | null>;
20
+ /** Replaces the document; the caller merges. */
21
+ set: (collection: string, id: string, value: HudStoreValue) => Promise<void>;
22
+ /** Every document of the collection, in insertion order; empty when it does not exist. */
23
+ list: (collection: string) => Promise<HudStoreEntry[]>;
24
+ }
25
+ /**
26
+ * A collection becomes a file name under `.hud/` (and a URL segment), so it
27
+ * is restricted to a slug: no dots, no slashes, no traversal.
28
+ */
29
+ declare const STORE_COLLECTION: RegExp;
30
+ /** Ids are document keys (`hero:b`); printable, one line, bounded. */
31
+ declare const STORE_ID: RegExp;
32
+ declare class HudStoreError extends Error {
33
+ /** HTTP status `storeRoutes` answers with. */
34
+ readonly status: number;
35
+ constructor(message: string,
36
+ /** HTTP status `storeRoutes` answers with. */
37
+ status?: number);
38
+ }
39
+ declare function assertCollection(collection: string): void;
40
+ declare function assertId(id: string): void;
41
+ declare function isStoreValue(value: unknown): value is HudStoreValue;
42
+ declare function assertValue(value: unknown): asserts value is HudStoreValue;
43
+ //#endregion
44
+ export { STORE_COLLECTION as a, assertId as c, HudStoreValue as i, assertValue as l, HudStoreEntry as n, STORE_ID as o, HudStoreError as r, assertCollection as s, HudStore as t, isStoreValue as u };
@@ -0,0 +1,118 @@
1
+ import { c as HudMockScenarioInfo, i as HudMockNodeStatus, t as HudMockActive } from "./mocks-CA-wM2SB.js";
2
+ import { c as HudFlagValue, o as HudFlagOverride, s as HudFlagScope } from "./flags-DVtaJ8pQ.js";
3
+ //#region src/plugins/data/types.d.ts
4
+ /** A fixture user the role switch can sign the browser in as. */
5
+ interface HudAuthUser {
6
+ /** The app's user id; what the adapter signs in as. */
7
+ id: string;
8
+ /** Shown in the panel: `Ada (admin)`. */
9
+ label: string;
10
+ /** Role name, for the panel and for `cookieImpersonation` consumers. */
11
+ role?: string;
12
+ /** `betterAuth()` signs in by email; others show it. */
13
+ email?: string;
14
+ /** `betterAuth()` signs in by password. Never sent to the browser. */
15
+ password?: string;
16
+ /** Anything else the app wants back from `readImpersonation()`. Sent to the browser. */
17
+ extra?: Record<string, string | number | boolean | null>;
18
+ }
19
+ /** What the browser is told about a user: never the password. */
20
+ type HudAuthUserInfo = Omit<HudAuthUser, "password">;
21
+ type HudFlagType = "boolean" | "string" | "number";
22
+ /** A flag the source knows about, with the value the app would read without an override. */
23
+ interface HudFlagDefinition {
24
+ key: string;
25
+ label?: string;
26
+ description?: string;
27
+ /** Default `boolean`; decides the panel's control. */
28
+ type?: HudFlagType;
29
+ /** The real value (the source's), shown beside the override. */
30
+ value?: HudFlagValue;
31
+ /** Default scope for a new override. Default `cookie`. */
32
+ scope?: HudFlagScope;
33
+ }
34
+ /**
35
+ * A seed function the app registers: fills, resets or reshapes its data from
36
+ * the panel. Runs server side with the request, so it can read cookies (who
37
+ * the role switch signed in) and reach the database.
38
+ */
39
+ interface HudSeed {
40
+ /** Unique across the app: `orders:sample`, `reset`. */
41
+ id: string;
42
+ /** Button text: `Seed 20 orders`, `Reset database`. */
43
+ label: string;
44
+ description?: string;
45
+ /** The panel asks for a second click before running it. */
46
+ danger?: boolean;
47
+ /** Whatever it returns (JSON) is shown as the result. A throw is shown as the failure. */
48
+ run: (request: Request) => unknown | Promise<unknown>;
49
+ }
50
+ /** What the browser is told about a seed: no `run`. */
51
+ type HudSeedInfo = Omit<HudSeed, "run">;
52
+ /** `GET <apiBase>/data/`. */
53
+ interface DataStateResponse {
54
+ ok: true;
55
+ auth: {
56
+ adapter: string;
57
+ label: string;
58
+ current: HudAuthUserInfo | null;
59
+ users: HudAuthUserInfo[];
60
+ } | null;
61
+ flags: {
62
+ definitions: HudFlagDefinition[];
63
+ overrides: HudFlagOverride[];
64
+ } | null;
65
+ seeds: {
66
+ definitions: HudSeedInfo[];
67
+ } | null;
68
+ mocks: {
69
+ scenarios: HudMockScenarioInfo[];
70
+ active: HudMockActive;
71
+ /** Whether the Node MSW server runs, so server fetches follow the active set. */
72
+ node: HudMockNodeStatus;
73
+ } | null;
74
+ }
75
+ /** `POST <apiBase>/data/seeds/:id`, 200 when the seed returned; its throw answers 500 with `{ ok: false, error, durationMs }`. */
76
+ interface SeedRunResponse {
77
+ ok: true;
78
+ id: string;
79
+ durationMs: number;
80
+ /** What the seed returned, as JSON (`null` for nothing). */
81
+ result: unknown;
82
+ }
83
+ /** `PUT|DELETE <apiBase>/data/mocks…`. */
84
+ interface MocksResponse {
85
+ ok: true;
86
+ active: HudMockActive;
87
+ }
88
+ /** `POST <apiBase>/data/role`. */
89
+ interface RoleSwitchBody {
90
+ id: string;
91
+ }
92
+ /**
93
+ * `POST|DELETE <apiBase>/data/role`. `storage` entries are `localStorage`
94
+ * writes the browser must make before reloading (a `null` removes the key):
95
+ * adapters whose session lives there, like Convex Auth in a Vite app, cannot
96
+ * set it from a response.
97
+ */
98
+ interface RoleSwitchResponse {
99
+ ok: true;
100
+ current: HudAuthUserInfo | null;
101
+ storage: Record<string, string | null>;
102
+ }
103
+ /** `PUT <apiBase>/data/flags/:key`. */
104
+ interface FlagOverrideBody {
105
+ value: HudFlagValue;
106
+ scope?: HudFlagScope;
107
+ }
108
+ /** `PUT|DELETE <apiBase>/data/flags…`. */
109
+ interface FlagsResponse {
110
+ ok: true;
111
+ overrides: HudFlagOverride[];
112
+ }
113
+ /** The store collection overrides live in: `.hud/flags.json` with `file()`. */
114
+ declare const FLAGS_COLLECTION = "flags";
115
+ /** The one document in that collection: `{ overrides: { key: { value, scope } } }`. */
116
+ declare const FLAGS_DOCUMENT = "overrides";
117
+ //#endregion
118
+ export { FlagsResponse as a, HudFlagDefinition as c, HudSeedInfo as d, MocksResponse as f, SeedRunResponse as h, FlagOverrideBody as i, HudFlagType as l, RoleSwitchResponse as m, FLAGS_COLLECTION as n, HudAuthUser as o, RoleSwitchBody as p, FLAGS_DOCUMENT as r, HudAuthUserInfo as s, DataStateResponse as t, HudSeed as u };
@@ -0,0 +1,39 @@
1
+ import { r as GrabPayload, t as ComponentHint } from "./payload-MUQ9ciER.js";
2
+ import { t as AgentSession } from "./types-Cxh4twqc.js";
3
+ //#region src/plugins/agent/providers/types.d.ts
4
+ /** What a provider receives: the raw request plus the prompt built from it. */
5
+ interface DispatchOrder {
6
+ note: string;
7
+ payload: GrabPayload | null;
8
+ hints: ComponentHint[];
9
+ /** `dispatchPrompt(...)` of the above; what an agent should be told. */
10
+ prompt: string;
11
+ }
12
+ type ProviderStatus = {
13
+ available: true;
14
+ } | {
15
+ available: false;
16
+ reason: string;
17
+ };
18
+ /**
19
+ * The `dispatch` provider seam. One implementation per backend: `hermes()`
20
+ * and `claudeCode()` ship with the plugin; anything with the same shape works.
21
+ * Runs server side only.
22
+ */
23
+ interface DispatchProvider {
24
+ /** Unique among the providers passed in; the client selects a target by it. */
25
+ id: string;
26
+ label: string;
27
+ description?: string;
28
+ /** Default: available. */
29
+ status?: () => ProviderStatus | Promise<ProviderStatus>;
30
+ /** Starts work and returns as soon as it is accepted, not when it finishes. */
31
+ dispatch: (order: DispatchOrder) => Promise<{
32
+ runId: string;
33
+ detail?: string;
34
+ }>;
35
+ /** Runs and sessions this backend knows about, for the Sessions panel. */
36
+ sessions?: () => Promise<AgentSession[]>;
37
+ }
38
+ //#endregion
39
+ export { DispatchProvider as n, ProviderStatus as r, DispatchOrder as t };
@@ -0,0 +1,96 @@
1
+ import { n as HudApiError } from "./plugins-DVy_vaYr.js";
2
+ import { n as hudRequiresUnlock, o as resolveHudAccess } from "./access-C7zlaqj6.js";
3
+ import { c as toHudEnv } from "./capabilities-rDSKjXpq.js";
4
+ import { useEffect, useSyncExternalStore } from "react";
5
+ //#region src/plugins/access/unlock-store.ts
6
+ /**
7
+ * Unlock state of the page's HUD. The browser never sees the password or the
8
+ * token: the cookie is httpOnly and only the server can judge it, so this
9
+ * store asks the unlock route rather than reading anything locally.
10
+ */
11
+ let state = {
12
+ env: "development",
13
+ status: "checking",
14
+ error: null
15
+ };
16
+ const listeners = /* @__PURE__ */ new Set();
17
+ function set(patch) {
18
+ state = {
19
+ ...state,
20
+ ...patch
21
+ };
22
+ for (const listener of listeners) listener();
23
+ }
24
+ function subscribe(listener) {
25
+ listeners.add(listener);
26
+ return () => listeners.delete(listener);
27
+ }
28
+ const getState = () => state;
29
+ function useUnlockState() {
30
+ return useSyncExternalStore(subscribe, getState, getState);
31
+ }
32
+ function errorOf(body) {
33
+ if (body && typeof body === "object" && "error" in body && typeof body.error === "string") return body.error;
34
+ }
35
+ /** Asks `<apiBase>/access/unlock` whether this browser is unlocked. Any failure keeps it shut. */
36
+ async function refreshUnlockStatus(apiBase) {
37
+ try {
38
+ const res = await fetch(`${apiBase.replace(/\/+$/, "")}/access/unlock`, {
39
+ cache: "no-store",
40
+ headers: { accept: "application/json" }
41
+ });
42
+ const body = await res.json().catch(() => ({}));
43
+ if (!res.ok || !body || typeof body !== "object") {
44
+ set({ status: "locked" });
45
+ return;
46
+ }
47
+ const { configured, unlocked } = body;
48
+ set({ status: configured === false ? "unconfigured" : unlocked === true ? "unlocked" : "locked" });
49
+ } catch {
50
+ set({ status: "locked" });
51
+ }
52
+ }
53
+ /** Trades the password for the unlock cookie through the plugin's own route. */
54
+ async function submitPassword(api, password) {
55
+ set({ error: null });
56
+ try {
57
+ if ((await api("/unlock", {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({ password })
61
+ }))?.unlocked === true) {
62
+ set({ status: "unlocked" });
63
+ return true;
64
+ }
65
+ set({ error: "unlock refused" });
66
+ } catch (cause) {
67
+ set({ error: cause instanceof HudApiError ? errorOf(cause.body) ?? `unlock refused (${cause.status})` : "unlock failed" });
68
+ }
69
+ return false;
70
+ }
71
+ /**
72
+ * `HudAccessControl.useUnlocked`: development is open, a disabled or unknown
73
+ * tier never unlocks, every deployed tier asks the server once per mount.
74
+ */
75
+ function useUnlocked(envName, apiBase) {
76
+ const env = toHudEnv(envName);
77
+ const access = resolveHudAccess(env);
78
+ const { status } = useUnlockState();
79
+ useEffect(() => {
80
+ const required = hudRequiresUnlock(access);
81
+ set({
82
+ env,
83
+ status: access === "open" ? "unlocked" : required ? "checking" : "locked"
84
+ });
85
+ if (required) refreshUnlockStatus(apiBase);
86
+ }, [
87
+ env,
88
+ access,
89
+ apiBase
90
+ ]);
91
+ if (access === "open") return true;
92
+ if (access === "denied") return false;
93
+ return status === "unlocked";
94
+ }
95
+ //#endregion
96
+ export { useUnlockState as n, useUnlocked as r, submitPassword as t };
@@ -0,0 +1,137 @@
1
+ //#region src/plugins/design/variant-groups.ts
2
+ /**
3
+ * Live variant groups: regions of a real page rendered in one of several
4
+ * ways, chosen by the URL. `VariantGroup` (`@hansenexus/hud/variants`)
5
+ * registers each mounted group here so the Variants panel can list and
6
+ * switch them; the choice lives in `?variant=<group>:<id>` (several groups:
7
+ * `?variant=hero:b,cta:a`), so it is linkable and survives a reload.
8
+ *
9
+ * Development only. `VariantGroup` reaches this module behind a
10
+ * `NODE_ENV === "development"` constant, so production builds drop it.
11
+ */
12
+ /** `?variant=<group>:<id>[,<group>:<id>…]`; repeated params are merged. */
13
+ const VARIANT_PARAM = "variant";
14
+ /**
15
+ * globalThis key of the store singleton, and the bundle-gate marker. One
16
+ * instance even if the module is evaluated twice (HMR, or the app's
17
+ * `VariantGroup` chunk and the HUD's panel chunk each carrying a copy).
18
+ */
19
+ const VARIANT_MARKER = "__HANSENEXUS_HUD_VARIANTS__";
20
+ /** Parses every `?variant=` value; a later entry for the same group wins. */
21
+ function parseVariantParam(values) {
22
+ const choices = {};
23
+ for (const value of values) for (const pair of value.split(",")) {
24
+ const separator = pair.indexOf(":");
25
+ if (separator <= 0) continue;
26
+ const group = pair.slice(0, separator).trim();
27
+ const id = pair.slice(separator + 1).trim();
28
+ if (group && id) choices[group] = id;
29
+ }
30
+ return choices;
31
+ }
32
+ /** The param's value: `hero:b,cta:a`; empty when nothing is chosen. */
33
+ function formatVariantParam(choices) {
34
+ return Object.entries(choices).map(([group, id]) => `${group}:${id}`).join(",");
35
+ }
36
+ function choicesFromSearch(search) {
37
+ return parseVariantParam(new URLSearchParams(search).getAll(VARIANT_PARAM));
38
+ }
39
+ /** `search` with the group's choice set (or, with null, removed). */
40
+ function withVariantChoice(search, group, id) {
41
+ const params = new URLSearchParams(search);
42
+ const choices = parseVariantParam(params.getAll(VARIANT_PARAM));
43
+ if (id === null) delete choices[group];
44
+ else choices[group] = id;
45
+ params.delete(VARIANT_PARAM);
46
+ const value = formatVariantParam(choices);
47
+ if (value) params.set(VARIANT_PARAM, value);
48
+ const text = params.toString();
49
+ return text ? `?${text}` : "";
50
+ }
51
+ /** The variant a group renders: the URL's choice when it names one of the group's variants, else the default. */
52
+ function resolveVariant(group, choices) {
53
+ const chosen = choices[group.id];
54
+ return chosen !== void 0 && group.variants.some((v) => v.id === chosen) ? chosen : group.defaultId;
55
+ }
56
+ var VariantGroupStore = class {
57
+ registrations = /* @__PURE__ */ new Map();
58
+ search = "";
59
+ snapshot = {
60
+ groups: [],
61
+ choices: {}
62
+ };
63
+ listeners = /* @__PURE__ */ new Set();
64
+ getSnapshot = () => this.snapshot;
65
+ subscribe = (listener) => {
66
+ this.listeners.add(listener);
67
+ return () => {
68
+ this.listeners.delete(listener);
69
+ };
70
+ };
71
+ /** Registers a mounted group; the returned function unregisters it. Mounts are counted. */
72
+ register(info) {
73
+ const existing = this.registrations.get(info.id);
74
+ this.registrations.set(info.id, {
75
+ info,
76
+ count: (existing?.count ?? 0) + 1
77
+ });
78
+ this.emit();
79
+ return () => {
80
+ const current = this.registrations.get(info.id);
81
+ if (!current) return;
82
+ if (current.count > 1) this.registrations.set(info.id, {
83
+ ...current,
84
+ count: current.count - 1
85
+ });
86
+ else this.registrations.delete(info.id);
87
+ this.emit();
88
+ };
89
+ }
90
+ /** Feeds the current `location.search`; a no-op when it did not change. */
91
+ syncSearch(search) {
92
+ if (search === this.search) return;
93
+ this.search = search;
94
+ this.emit();
95
+ }
96
+ /**
97
+ * Chooses a variant: rewrites `?variant=` in place (no history entry, so
98
+ * Back leaves the page rather than stepping through variants) and
99
+ * re-renders every group. Null returns the group to its default.
100
+ */
101
+ choose(group, id) {
102
+ if (typeof window === "undefined") return;
103
+ const search = withVariantChoice(window.location.search, group, id);
104
+ const url = `${window.location.pathname}${search}${window.location.hash}`;
105
+ window.history.replaceState(window.history.state, "", url);
106
+ this.syncSearch(search);
107
+ }
108
+ emit() {
109
+ this.snapshot = {
110
+ groups: [...this.registrations.values()].map(({ info }) => info),
111
+ choices: choicesFromSearch(this.search)
112
+ };
113
+ for (const listener of this.listeners) listener();
114
+ }
115
+ };
116
+ /** The page's store, created on first use. */
117
+ function getVariantGroupStore() {
118
+ const holder = globalThis;
119
+ holder[VARIANT_MARKER] ??= new VariantGroupStore();
120
+ return holder[VARIANT_MARKER];
121
+ }
122
+ /** Subscribes to the page's store and keeps it in step with back/forward navigation. */
123
+ function subscribeVariantGroups(listener) {
124
+ const store = getVariantGroupStore();
125
+ const onPopState = () => store.syncSearch(window.location.search);
126
+ window.addEventListener("popstate", onPopState);
127
+ const unsubscribe = store.subscribe(listener);
128
+ return () => {
129
+ window.removeEventListener("popstate", onPopState);
130
+ unsubscribe();
131
+ };
132
+ }
133
+ function getVariantGroupsSnapshot() {
134
+ return getVariantGroupStore().getSnapshot();
135
+ }
136
+ //#endregion
137
+ export { getVariantGroupsSnapshot as a, subscribeVariantGroups as c, getVariantGroupStore as i, VARIANT_PARAM as n, parseVariantParam as o, formatVariantParam as r, resolveVariant as s, VARIANT_MARKER as t };
@@ -0,0 +1,36 @@
1
+ //#region src/plugins/design/variant-groups.d.ts
2
+ /**
3
+ * Live variant groups: regions of a real page rendered in one of several
4
+ * ways, chosen by the URL. `VariantGroup` (`@hansenexus/hud/variants`)
5
+ * registers each mounted group here so the Variants panel can list and
6
+ * switch them; the choice lives in `?variant=<group>:<id>` (several groups:
7
+ * `?variant=hero:b,cta:a`), so it is linkable and survives a reload.
8
+ *
9
+ * Development only. `VariantGroup` reaches this module behind a
10
+ * `NODE_ENV === "development"` constant, so production builds drop it.
11
+ */
12
+ /** `?variant=<group>:<id>[,<group>:<id>…]`; repeated params are merged. */
13
+ declare const VARIANT_PARAM = "variant";
14
+ /**
15
+ * globalThis key of the store singleton, and the bundle-gate marker. One
16
+ * instance even if the module is evaluated twice (HMR, or the app's
17
+ * `VariantGroup` chunk and the HUD's panel chunk each carrying a copy).
18
+ */
19
+ declare const VARIANT_MARKER = "__HANSENEXUS_HUD_VARIANTS__";
20
+ interface VariantOption {
21
+ id: string;
22
+ label: string;
23
+ }
24
+ interface VariantGroupInfo {
25
+ id: string;
26
+ label: string;
27
+ /** Rendered when the URL names no valid variant for the group. */
28
+ defaultId: string;
29
+ variants: readonly VariantOption[];
30
+ }
31
+ /** Parses every `?variant=` value; a later entry for the same group wins. */
32
+ declare function parseVariantParam(values: readonly string[]): Record<string, string>;
33
+ /** The param's value: `hero:b,cta:a`; empty when nothing is chosen. */
34
+ declare function formatVariantParam(choices: Readonly<Record<string, string>>): string;
35
+ //#endregion
36
+ export { formatVariantParam as a, VariantOption as i, VARIANT_PARAM as n, parseVariantParam as o, VariantGroupInfo as r, VARIANT_MARKER as t };