@hansenexus/hud 0.5.0 → 0.5.2

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.
package/README.md CHANGED
@@ -41,7 +41,19 @@ export default defineHud({ app: "my-app", plugins: [vitals()] });
41
41
  ```
42
42
 
43
43
  The loader, with the build gate as a literal expression around the `import()`. Next inlines both
44
- env reads, so a production build folds the ternary to `null` and emits no HUD chunk:
44
+ env reads, so a production build folds the ternary to `null` and emits no HUD chunk. That holds
45
+ only when `NEXT_PUBLIC_HUD_ENABLED` is a build-time literal: Turbopack leaves an **unset**
46
+ `NEXT_PUBLIC_*` variable as a runtime `process.env` read, the ternary does not fold, and the whole
47
+ dev HUD ships as an unreachable production chunk. Wrap the config in `withHud` (see
48
+ [Auto-config](#auto-config-hansenexushudauto)), which pins the HUD's variables to `""` when they are unset, or pin it
49
+ yourself:
50
+
51
+ ```js
52
+ // next.config.js, without withHud
53
+ export default {
54
+ env: { NEXT_PUBLIC_HUD_ENABLED: process.env.NEXT_PUBLIC_HUD_ENABLED ?? "" },
55
+ };
56
+ ```
45
57
 
46
58
  ```tsx
47
59
  // src/components/dev/hud-loader.tsx
@@ -157,6 +169,21 @@ import { withHud } from "@hansenexus/hud/next/config";
157
169
  export default withHud({ reactStrictMode: true });
158
170
  ```
159
171
 
172
+ `withHud` takes and returns the app's own config type (`NextConfig` included) and also pins
173
+ `NEXT_PUBLIC_HUD_ENABLED`, `NEXT_PUBLIC_HUD_DISABLED` and `NEXT_PUBLIC_HUD_ENV` through `env` to
174
+ their build-time value, `""` when unset; an `env` entry of the app's own wins. The entry ships as
175
+ ESM and CommonJS, so a `next.config.ts` that Next compiles to CommonJS (a package without
176
+ `"type": "module"`) loads it through `require()` too:
177
+
178
+ ```ts
179
+ // next.config.ts
180
+ import type { NextConfig } from "next";
181
+ import { withHud } from "@hansenexus/hud/next/config";
182
+
183
+ const config: NextConfig = { reactStrictMode: true };
184
+ export default withHud(config);
185
+ ```
186
+
160
187
  Without either, `@hansenexus/hud/auto` resolves to the package's stand-in: the base plugins,
161
188
  nothing dependency-driven, and a console warning once. `auto` works as the whole `plugins` value
162
189
  too (`plugins: auto()`); `defineHud` needs one of `plugins` and `auto`.
@@ -855,9 +882,10 @@ dependencies so a Node gate script can import it:
855
882
  | `HUD_REVIEW_MARKER` | `__HANSENEXUS_HUD_REVIEW__` | only where `/review` is meant to ship |
856
883
 
857
884
  CI proves both on every PR: `fixtures/next-app` mounts the dev HUD behind the loader's build gate
858
- and `<Review>` beside it, installs the packed tarball, runs `next build` and fails on any dev
859
- marker or dev-only string in `.next/static` (`bun run build && bun run --cwd fixtures/next-app
860
- gate`). `fixtures/vite-app` does the same for Vite: `hud()` in its config, the
885
+ and `<Review>` beside it, installs the packed tarball, loads `withHud` from a CommonJS config
886
+ through `require()`, runs `next build --turbopack` with `NEXT_PUBLIC_HUD_ENABLED` unset and fails
887
+ on any dev marker or dev-only string in `.next/static` (`bun run build && bun run --cwd
888
+ fixtures/next-app gate`). `fixtures/vite-app` does the same for Vite: `hud()` in its config, the
861
889
  `import.meta.env.DEV` loader gate, the packed tarball, `vite build`, no dev marker in `dist`
862
890
  (`bun run --cwd fixtures/vite-app gate`). Both fixtures define their HUD through
863
891
  `@hansenexus/hud/auto`, so the gate covers the generated module too. Either fixture's
@@ -66,7 +66,7 @@ const DATA_CSS = `
66
66
  font-family: var(--hud-mono);
67
67
  font-size: 10px;
68
68
  }
69
- .hud .data-segment:hover:not(:disabled) { background: var(--hud-bg-subtle); }
69
+ .hud .data-segment:hover:not(:disabled):not([aria-pressed="true"]) { background: var(--hud-bg-subtle); }
70
70
  .hud .data-segment[aria-pressed="true"] {
71
71
  background: var(--hud-accent);
72
72
  border-color: var(--hud-accent);
package/dist/index.js CHANGED
@@ -790,8 +790,163 @@ function Workspace({ appSlug, panels, apiRef, children }) {
790
790
  })
791
791
  });
792
792
  }
793
+ /** Clearance kept between the pill and a host element it moves away from. */
794
+ const CLEARANCE = 8;
795
+ /** The pill never moves further than this share of the viewport height off its edge. */
796
+ const MAX_SHIFT_SHARE = .4;
797
+ /** Extra cost of a top corner when every corner needs a shift: host navs live up there. */
798
+ const TOP_PENALTY = 48;
799
+ const isBottom = (corner) => corner.startsWith("bottom");
800
+ const isRight = (corner) => corner.endsWith("right");
801
+ function pillRect({ corner, shift }, size, viewport, reserve) {
802
+ return {
803
+ left: isRight(corner) ? viewport.w - reserve.right - 12 - size.width : reserve.left + 12,
804
+ top: isBottom(corner) ? viewport.h - reserve.bottom - 12 - shift - size.height : 12 + shift,
805
+ width: size.width,
806
+ height: size.height
807
+ };
808
+ }
809
+ function intersects(a, b) {
810
+ return a.left < b.left + b.width && b.left < a.left + a.width && a.top < b.top + b.height && b.top < a.top + a.height;
811
+ }
812
+ /**
813
+ * Shifts the pill away from its corner's edge until it clears every obstacle,
814
+ * or returns null when that would take it past the shift cap.
815
+ */
816
+ function shiftWithin(corner, options) {
817
+ const { viewport, size, obstacles, reserve } = options;
818
+ const max = viewport.h * MAX_SHIFT_SHARE;
819
+ let placement = {
820
+ corner,
821
+ shift: 0
822
+ };
823
+ for (let round = 0; round <= obstacles.length; round++) {
824
+ const rect = pillRect(placement, size, viewport, reserve);
825
+ const hits = obstacles.filter((o) => intersects(rect, o));
826
+ if (hits.length === 0) return placement;
827
+ const shift = Math.max(...hits.map((o) => isBottom(corner) ? viewport.h - reserve.bottom - 12 - o.top + CLEARANCE : o.top + o.height + CLEARANCE - 12));
828
+ if (shift > max || shift <= placement.shift) return null;
829
+ placement = {
830
+ corner,
831
+ shift
832
+ };
833
+ }
834
+ return null;
835
+ }
836
+ /**
837
+ * Where the pill goes. A dragged corner is kept and only shifted. Otherwise the
838
+ * first corner that is free as is wins; when none is, the corner that needs
839
+ * the smallest shift, with top corners penalised. Null when no corner clears its obstacles within the cap:
840
+ * the caller then shrinks the pill to compact mode and tries again.
841
+ */
842
+ function placePill(options) {
843
+ if (options.pinned) return shiftWithin(options.pinned, options);
844
+ const cost = ({ corner, shift }) => shift + (isBottom(corner) ? 0 : TOP_PENALTY);
845
+ let best = null;
846
+ for (const corner of CORNERS) {
847
+ const placement = shiftWithin(corner, options);
848
+ if (placement?.shift === 0) return placement;
849
+ if (placement && (!best || cost(placement) < cost(best))) best = placement;
850
+ }
851
+ return best;
852
+ }
853
+ /** The corner a dragged pill lands in: the viewport quadrant of the drop point. */
854
+ function nearestCorner(x, y, viewport) {
855
+ return `${y > viewport.h / 2 ? "bottom" : "top"}-${x > viewport.w / 2 ? "right" : "left"}`;
856
+ }
857
+ /**
858
+ * Which plugin items fit in `budget` pixels. Higher priority first, then pill
859
+ * order; an item that does not fit is skipped, so a smaller one after it can
860
+ * still take the remaining room. `compact` keeps only prioritised items.
861
+ */
862
+ function fitItems(items, budget, { compact = false, gap = 0 } = {}) {
863
+ const ranked = items.map((item, index) => ({
864
+ item,
865
+ index
866
+ })).filter(({ item }) => !compact || item.priority > 0).sort((a, b) => b.item.priority - a.item.priority || a.index - b.index);
867
+ const visible = /* @__PURE__ */ new Set();
868
+ let left = budget;
869
+ for (const { item } of ranked) {
870
+ const cost = item.width + gap;
871
+ if (cost > left) continue;
872
+ visible.add(item.id);
873
+ left -= cost;
874
+ }
875
+ return visible;
876
+ }
877
+ /**
878
+ * How far to move `rect` so it lies inside `area`, `margin` off each edge.
879
+ * On an axis where it is too big to fit, its start is aligned with the area's.
880
+ */
881
+ function clampOffset(rect, area, margin) {
882
+ const axis = (start, size, areaStart, areaSize) => {
883
+ const min = areaStart + margin;
884
+ const max = areaStart + areaSize - margin - size;
885
+ if (max < min || start < min) return min - start;
886
+ return start > max ? max - start : 0;
887
+ };
888
+ return {
889
+ x: axis(rect.left, rect.width, area.left, area.width),
890
+ y: axis(rect.top, rect.height, area.top, area.height)
891
+ };
892
+ }
893
+ //#endregion
894
+ //#region src/shell/pill/visual-viewport.ts
895
+ function subscribe(listener) {
896
+ const vv = window.visualViewport;
897
+ window.addEventListener("resize", listener);
898
+ vv?.addEventListener("resize", listener);
899
+ vv?.addEventListener("scroll", listener);
900
+ return () => {
901
+ window.removeEventListener("resize", listener);
902
+ vv?.removeEventListener("resize", listener);
903
+ vv?.removeEventListener("scroll", listener);
904
+ };
905
+ }
906
+ let cached = {
907
+ x: 0,
908
+ y: 0,
909
+ w: 0,
910
+ h: 0,
911
+ detached: false
912
+ };
913
+ /**
914
+ * On a phone, a page wider than the screen (an image with a fixed width is
915
+ * enough) grows the layout viewport past the visible area, and a pill fixed
916
+ * to the bottom edge ends up below the fold. The visual viewport is what the
917
+ * user sees; the pill places itself in it.
918
+ */
919
+ function read() {
920
+ const root = document.documentElement;
921
+ const layoutW = root.clientWidth || window.innerWidth;
922
+ const layoutH = root.clientHeight || window.innerHeight;
923
+ const vv = window.visualViewport;
924
+ const x = vv?.offsetLeft ?? 0;
925
+ const y = vv?.offsetTop ?? 0;
926
+ const w = Math.round(vv?.width ?? layoutW);
927
+ const h = Math.round(vv?.height ?? layoutH);
928
+ const detached = x !== 0 || y !== 0 || window.innerWidth > w + 1 || window.innerHeight > h + 1;
929
+ const next = {
930
+ x,
931
+ y,
932
+ w: detached ? w : layoutW,
933
+ h: detached ? h : layoutH,
934
+ detached
935
+ };
936
+ if (next.x !== cached.x || next.y !== cached.y || next.w !== cached.w || next.h !== cached.h || next.detached !== cached.detached) cached = next;
937
+ return cached;
938
+ }
939
+ function useVisualViewport() {
940
+ return useSyncExternalStore(subscribe, read, read);
941
+ }
793
942
  //#endregion
794
943
  //#region src/shell/panels/pill-menu.tsx
944
+ /** Distance the open menu keeps from the edges of the visible area. */
945
+ const MENU_MARGIN = 8;
946
+ const NO_OFFSET = {
947
+ x: 0,
948
+ y: 0
949
+ };
795
950
  /**
796
951
  * The pill's "⋯" menu: every panel, every command with its shortcut, and Reset
797
952
  * layout. `overflow` counts the pill items that did not fit; their panels are
@@ -803,6 +958,34 @@ function PillMenu({ overflow = 0 }) {
803
958
  const apple = useMemo(isApplePlatform, []);
804
959
  const [open, setOpen] = useState(false);
805
960
  const ref = useRef(null);
961
+ const menuRef = useRef(null);
962
+ const visual = useVisualViewport();
963
+ const [offset, setOffset] = useState(NO_OFFSET);
964
+ useLayoutEffect(() => {
965
+ const menu = menuRef.current;
966
+ if (!open || !menu) {
967
+ setOffset(NO_OFFSET);
968
+ return;
969
+ }
970
+ const box = menu.getBoundingClientRect();
971
+ if (box.width === 0 && box.height === 0) return;
972
+ const next = clampOffset({
973
+ left: box.left - offset.x,
974
+ top: box.top - offset.y,
975
+ width: box.width,
976
+ height: box.height
977
+ }, {
978
+ left: visual.x,
979
+ top: visual.y,
980
+ width: visual.w,
981
+ height: visual.h
982
+ }, MENU_MARGIN);
983
+ if (next.x !== offset.x || next.y !== offset.y) setOffset(next);
984
+ }, [
985
+ open,
986
+ visual,
987
+ offset
988
+ ]);
806
989
  useEffect(() => {
807
990
  if (!open) return;
808
991
  const onPointerDown = (e) => {
@@ -833,9 +1016,11 @@ function PillMenu({ overflow = 0 }) {
833
1016
  children: ["+", overflow]
834
1017
  })]
835
1018
  }), open && /* @__PURE__ */ jsxs("div", {
1019
+ ref: menuRef,
836
1020
  className: "menu",
837
1021
  role: "menu",
838
1022
  "aria-label": "HUD menu",
1023
+ style: offset.x || offset.y ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : void 0,
839
1024
  children: [
840
1025
  /* @__PURE__ */ jsx("div", {
841
1026
  className: "menu-label",
@@ -1232,139 +1417,6 @@ function useObstacles() {
1232
1417
  }, []);
1233
1418
  return rects;
1234
1419
  }
1235
- /** Clearance kept between the pill and a host element it moves away from. */
1236
- const CLEARANCE = 8;
1237
- /** The pill never moves further than this share of the viewport height off its edge. */
1238
- const MAX_SHIFT_SHARE = .4;
1239
- /** Extra cost of a top corner when every corner needs a shift: host navs live up there. */
1240
- const TOP_PENALTY = 48;
1241
- const isBottom = (corner) => corner.startsWith("bottom");
1242
- const isRight = (corner) => corner.endsWith("right");
1243
- function pillRect({ corner, shift }, size, viewport, reserve) {
1244
- return {
1245
- left: isRight(corner) ? viewport.w - reserve.right - 12 - size.width : reserve.left + 12,
1246
- top: isBottom(corner) ? viewport.h - reserve.bottom - 12 - shift - size.height : 12 + shift,
1247
- width: size.width,
1248
- height: size.height
1249
- };
1250
- }
1251
- function intersects(a, b) {
1252
- return a.left < b.left + b.width && b.left < a.left + a.width && a.top < b.top + b.height && b.top < a.top + a.height;
1253
- }
1254
- /**
1255
- * Shifts the pill away from its corner's edge until it clears every obstacle,
1256
- * or returns null when that would take it past the shift cap.
1257
- */
1258
- function shiftWithin(corner, options) {
1259
- const { viewport, size, obstacles, reserve } = options;
1260
- const max = viewport.h * MAX_SHIFT_SHARE;
1261
- let placement = {
1262
- corner,
1263
- shift: 0
1264
- };
1265
- for (let round = 0; round <= obstacles.length; round++) {
1266
- const rect = pillRect(placement, size, viewport, reserve);
1267
- const hits = obstacles.filter((o) => intersects(rect, o));
1268
- if (hits.length === 0) return placement;
1269
- const shift = Math.max(...hits.map((o) => isBottom(corner) ? viewport.h - reserve.bottom - 12 - o.top + CLEARANCE : o.top + o.height + CLEARANCE - 12));
1270
- if (shift > max || shift <= placement.shift) return null;
1271
- placement = {
1272
- corner,
1273
- shift
1274
- };
1275
- }
1276
- return null;
1277
- }
1278
- /**
1279
- * Where the pill goes. A dragged corner is kept and only shifted. Otherwise the
1280
- * first corner that is free as is wins; when none is, the corner that needs
1281
- * the smallest shift, with top corners penalised. Null when no corner clears its obstacles within the cap:
1282
- * the caller then shrinks the pill to compact mode and tries again.
1283
- */
1284
- function placePill(options) {
1285
- if (options.pinned) return shiftWithin(options.pinned, options);
1286
- const cost = ({ corner, shift }) => shift + (isBottom(corner) ? 0 : TOP_PENALTY);
1287
- let best = null;
1288
- for (const corner of CORNERS) {
1289
- const placement = shiftWithin(corner, options);
1290
- if (placement?.shift === 0) return placement;
1291
- if (placement && (!best || cost(placement) < cost(best))) best = placement;
1292
- }
1293
- return best;
1294
- }
1295
- /** The corner a dragged pill lands in: the viewport quadrant of the drop point. */
1296
- function nearestCorner(x, y, viewport) {
1297
- return `${y > viewport.h / 2 ? "bottom" : "top"}-${x > viewport.w / 2 ? "right" : "left"}`;
1298
- }
1299
- /**
1300
- * Which plugin items fit in `budget` pixels. Higher priority first, then pill
1301
- * order; an item that does not fit is skipped, so a smaller one after it can
1302
- * still take the remaining room. `compact` keeps only prioritised items.
1303
- */
1304
- function fitItems(items, budget, { compact = false, gap = 0 } = {}) {
1305
- const ranked = items.map((item, index) => ({
1306
- item,
1307
- index
1308
- })).filter(({ item }) => !compact || item.priority > 0).sort((a, b) => b.item.priority - a.item.priority || a.index - b.index);
1309
- const visible = /* @__PURE__ */ new Set();
1310
- let left = budget;
1311
- for (const { item } of ranked) {
1312
- const cost = item.width + gap;
1313
- if (cost > left) continue;
1314
- visible.add(item.id);
1315
- left -= cost;
1316
- }
1317
- return visible;
1318
- }
1319
- //#endregion
1320
- //#region src/shell/pill/visual-viewport.ts
1321
- function subscribe(listener) {
1322
- const vv = window.visualViewport;
1323
- window.addEventListener("resize", listener);
1324
- vv?.addEventListener("resize", listener);
1325
- vv?.addEventListener("scroll", listener);
1326
- return () => {
1327
- window.removeEventListener("resize", listener);
1328
- vv?.removeEventListener("resize", listener);
1329
- vv?.removeEventListener("scroll", listener);
1330
- };
1331
- }
1332
- let cached = {
1333
- x: 0,
1334
- y: 0,
1335
- w: 0,
1336
- h: 0,
1337
- detached: false
1338
- };
1339
- /**
1340
- * On a phone, a page wider than the screen (an image with a fixed width is
1341
- * enough) grows the layout viewport past the visible area, and a pill fixed
1342
- * to the bottom edge ends up below the fold. The visual viewport is what the
1343
- * user sees; the pill places itself in it.
1344
- */
1345
- function read() {
1346
- const root = document.documentElement;
1347
- const layoutW = root.clientWidth || window.innerWidth;
1348
- const layoutH = root.clientHeight || window.innerHeight;
1349
- const vv = window.visualViewport;
1350
- const x = vv?.offsetLeft ?? 0;
1351
- const y = vv?.offsetTop ?? 0;
1352
- const w = Math.round(vv?.width ?? layoutW);
1353
- const h = Math.round(vv?.height ?? layoutH);
1354
- const detached = x !== 0 || y !== 0 || window.innerWidth > w + 1 || window.innerHeight > h + 1;
1355
- const next = {
1356
- x,
1357
- y,
1358
- w: detached ? w : layoutW,
1359
- h: detached ? h : layoutH,
1360
- detached
1361
- };
1362
- if (next.x !== cached.x || next.y !== cached.y || next.w !== cached.w || next.h !== cached.h || next.detached !== cached.detached) cached = next;
1363
- return cached;
1364
- }
1365
- function useVisualViewport() {
1366
- return useSyncExternalStore(subscribe, read, read);
1367
- }
1368
1420
  //#endregion
1369
1421
  //#region src/shell/pill/pill.tsx
1370
1422
  /** `.pill` gap, padding and border, which the item widths do not include. */
@@ -0,0 +1,201 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_fs = require("node:fs");
3
+ let node_path = require("node:path");
4
+ //#region src/auto/detect.ts
5
+ /** Which package turns on which feature. */
6
+ const AUTO_RULES = {
7
+ next: "next",
8
+ convex: "convex",
9
+ reactQuery: "@tanstack/react-query",
10
+ swr: "swr",
11
+ msw: "msw",
12
+ betterAuth: "better-auth",
13
+ convexAuth: "@convex-dev/auth"
14
+ };
15
+ const AUTO_FEATURES = Object.keys(AUTO_RULES);
16
+ /** The stand-in: nothing detected, nothing configured. */
17
+ const NOTHING_DETECTED = Object.freeze({
18
+ configured: false,
19
+ next: false,
20
+ convex: false,
21
+ reactQuery: false,
22
+ swr: false,
23
+ msw: false,
24
+ betterAuth: false,
25
+ convexAuth: false
26
+ });
27
+ const SECTIONS = [
28
+ "dependencies",
29
+ "devDependencies",
30
+ "peerDependencies",
31
+ "optionalDependencies"
32
+ ];
33
+ /** Every package the manifest names, whatever the section. */
34
+ function listDependencies(pkg) {
35
+ const names = /* @__PURE__ */ new Set();
36
+ for (const section of SECTIONS) {
37
+ const entries = pkg[section];
38
+ if (typeof entries !== "object" || entries === null) continue;
39
+ for (const name of Object.keys(entries)) names.add(name);
40
+ }
41
+ return names;
42
+ }
43
+ /**
44
+ * Detection from a parsed package.json: a feature is on when its package is
45
+ * listed in any dependency section (dev dependencies count: `msw` lives there).
46
+ */
47
+ function detectHudAuto(pkg) {
48
+ const names = listDependencies(pkg);
49
+ const detected = {
50
+ ...NOTHING_DETECTED,
51
+ configured: true
52
+ };
53
+ for (const feature of AUTO_FEATURES) detected[feature] = names.has(AUTO_RULES[feature]);
54
+ return Object.freeze(detected);
55
+ }
56
+ /** Parses package.json text; a broken file detects nothing rather than crashing the dev server. */
57
+ function parsePackageJson(text) {
58
+ try {
59
+ const parsed = JSON.parse(text);
60
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
61
+ } catch {
62
+ return {};
63
+ }
64
+ }
65
+ //#endregion
66
+ //#region src/auto/generate.ts
67
+ const PACKAGE = "@hansenexus/hud";
68
+ /** Which import each feature adds: `name` from `subpath`. */
69
+ const FEATURE_IMPORTS = {
70
+ configured: null,
71
+ next: ["routes", "plugins/routes"],
72
+ convex: ["inspectConvex", "plugins/inspect/convex"],
73
+ reactQuery: ["inspectReactQuery", "plugins/inspect/react-query"],
74
+ swr: ["inspectSwr", "plugins/inspect/swr"],
75
+ msw: ["data", "plugins/data"],
76
+ betterAuth: ["data", "plugins/data"],
77
+ convexAuth: ["data", "plugins/data"]
78
+ };
79
+ /** The base plugins every auto HUD carries. */
80
+ const BASE_IMPORTS = [
81
+ ["a11y", "plugins/a11y"],
82
+ ["forceState", "plugins/design"],
83
+ ["inspect", "plugins/inspect"],
84
+ ["observe", "plugins/observe"],
85
+ ["seo", "plugins/seo"],
86
+ ["vitals", "plugins/vitals"]
87
+ ];
88
+ /** The factories the generated module hands `assembleAuto`, in import order. */
89
+ function autoImports(detected) {
90
+ const imports = new Map(BASE_IMPORTS);
91
+ for (const [feature, entry] of Object.entries(FEATURE_IMPORTS)) if (entry && detected[feature]) imports.set(entry[0], entry[1]);
92
+ return imports;
93
+ }
94
+ /**
95
+ * The generated module. `source` names where detection read from, for the
96
+ * header comment. Exports match the stand-in in `src/auto/index.ts`
97
+ * (`detected`, `auto`, default), so the types in `dist/auto.d.ts` apply.
98
+ */
99
+ function generateAutoModule(detected, source = "package.json") {
100
+ const imports = [...autoImports(detected)].sort(([, a], [, b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, subpath]) => `import { ${name} } from "${PACKAGE}/${subpath}";`);
101
+ const factories = [...autoImports(detected).keys()].sort().join(", ");
102
+ return [
103
+ `// Generated by ${PACKAGE} from ${source}. Do not edit: it is rewritten on every start.`,
104
+ `import { assembleAuto } from "${PACKAGE}/auto/runtime";`,
105
+ ...imports,
106
+ "",
107
+ `export const detected = Object.freeze(${JSON.stringify(detected)});`,
108
+ "",
109
+ "export function auto(options) {",
110
+ ` return assembleAuto(detected, { ${factories} }, options);`,
111
+ "}",
112
+ "",
113
+ "export default auto;",
114
+ ""
115
+ ].join("\n");
116
+ }
117
+ //#endregion
118
+ //#region src/next/config.ts
119
+ /** What the app imports; the wrapper aliases it to the generated file. */
120
+ const AUTO_ID = "@hansenexus/hud/auto";
121
+ /** Where the generated module lives, relative to the app dir. Add it to .gitignore. */
122
+ const AUTO_FILE = ".hud/auto.mjs";
123
+ /**
124
+ * The client variables the loader gate and the env ladder read. Next inlines a
125
+ * `NEXT_PUBLIC_*` read only when the variable is set at build time; Turbopack
126
+ * leaves an unset one as a runtime `process.env` lookup, so the gate
127
+ * `NODE_ENV === "development" || NEXT_PUBLIC_HUD_ENABLED === "true"` does not
128
+ * fold and the dev HUD ships as a production chunk (hud#64). `withHud` pins
129
+ * each to a build-time literal, `""` when unset.
130
+ */
131
+ const HUD_PUBLIC_ENV = [
132
+ "NEXT_PUBLIC_HUD_ENABLED",
133
+ "NEXT_PUBLIC_HUD_DISABLED",
134
+ "NEXT_PUBLIC_HUD_ENV"
135
+ ];
136
+ /** Reads, detects and writes `.hud/auto.mjs`; returns the detection and the file's absolute path. */
137
+ function writeAutoModule({ dir = process.cwd(), packageJson } = {}) {
138
+ const manifest = packageJson ?? (0, node_path.resolve)(dir, "package.json");
139
+ let text = "{}";
140
+ try {
141
+ text = (0, node_fs.readFileSync)(manifest, "utf8");
142
+ } catch {
143
+ console.warn(`hud: ${manifest} not found; @hansenexus/hud/auto enables the base plugins only`);
144
+ }
145
+ const detected = detectHudAuto(parsePackageJson(text));
146
+ const file = (0, node_path.resolve)(dir, AUTO_FILE);
147
+ const source = generateAutoModule(detected, manifest);
148
+ let current;
149
+ try {
150
+ current = (0, node_fs.readFileSync)(file, "utf8");
151
+ } catch {}
152
+ if (current !== source) {
153
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(file), { recursive: true });
154
+ (0, node_fs.writeFileSync)(file, source, "utf8");
155
+ }
156
+ return {
157
+ detected,
158
+ file
159
+ };
160
+ }
161
+ function withHud(config, options = {}) {
162
+ const base = config ?? {};
163
+ const { file } = writeAutoModule(options);
164
+ const webpack = base.webpack;
165
+ const pinned = {};
166
+ for (const key of HUD_PUBLIC_ENV) pinned[key] = process.env[key] ?? "";
167
+ return {
168
+ ...base,
169
+ env: {
170
+ ...pinned,
171
+ ...base.env
172
+ },
173
+ turbopack: {
174
+ ...base.turbopack,
175
+ resolveAlias: {
176
+ ...base.turbopack?.resolveAlias,
177
+ [AUTO_ID]: `./${AUTO_FILE}`
178
+ }
179
+ },
180
+ webpack(webpackConfig, context) {
181
+ const own = webpack ? webpack.call(base, webpackConfig, context) : webpackConfig;
182
+ const resolveOptions = own.resolve ?? {};
183
+ const alias = resolveOptions.alias;
184
+ resolveOptions.alias = Array.isArray(alias) ? [...alias, {
185
+ name: AUTO_ID,
186
+ alias: file
187
+ }] : {
188
+ ...alias,
189
+ [`${AUTO_ID}$`]: file
190
+ };
191
+ own.resolve = resolveOptions;
192
+ return own;
193
+ }
194
+ };
195
+ }
196
+ //#endregion
197
+ exports.AUTO_FILE = AUTO_FILE;
198
+ exports.AUTO_ID = AUTO_ID;
199
+ exports.HUD_PUBLIC_ENV = HUD_PUBLIC_ENV;
200
+ exports.withHud = withHud;
201
+ exports.writeAutoModule = writeAutoModule;
@@ -0,0 +1,87 @@
1
+ //#region src/auto/detect.d.ts
2
+ /** What the bundler plugin found in the app's package.json. */
3
+ interface HudAutoDetected {
4
+ /**
5
+ * False in the stand-in module the package ships: no bundler plugin read the
6
+ * app's package.json, so only the base plugins are on.
7
+ */
8
+ configured: boolean;
9
+ /** `next`: the routes plugin (route index, `hud sweep`). */
10
+ next: boolean;
11
+ /** `convex`: the Convex tab of the inspect plugin. */
12
+ convex: boolean;
13
+ /** `@tanstack/react-query`: the Query tab. */
14
+ reactQuery: boolean;
15
+ /** `swr`: the SWR tab. */
16
+ swr: boolean;
17
+ /** `msw`: the data plugin (mock scenarios). */
18
+ msw: boolean;
19
+ /** `better-auth`: the data plugin (role switch). */
20
+ betterAuth: boolean;
21
+ /** `@convex-dev/auth`: the data plugin (role switch). */
22
+ convexAuth: boolean;
23
+ }
24
+ //#endregion
25
+ //#region src/next/config.d.ts
26
+ /** What the app imports; the wrapper aliases it to the generated file. */
27
+ export declare const AUTO_ID = "@hansenexus/hud/auto";
28
+ /** Where the generated module lives, relative to the app dir. Add it to .gitignore. */
29
+ export declare const AUTO_FILE = ".hud/auto.mjs";
30
+ export interface WithHudOptions {
31
+ /** The app directory. Default: `process.cwd()`, which is where Next loads next.config from. */
32
+ dir?: string;
33
+ /** The package.json detection reads. Default: `<dir>/package.json`. */
34
+ packageJson?: string;
35
+ }
36
+ interface WebpackConfigLike {
37
+ resolve?: {
38
+ alias?: Record<string, unknown> | unknown[] | undefined;
39
+ [key: string]: unknown;
40
+ };
41
+ [key: string]: unknown;
42
+ }
43
+ /**
44
+ * The slice of `NextConfig` the wrapper touches, structurally, so `next` is
45
+ * neither imported nor a peer. No index signatures: Next's own `NextConfig`
46
+ * and `TurbopackOptions` are interfaces without one (hud#66). Method syntax
47
+ * keeps Next's own `webpack` signature assignable.
48
+ */
49
+ export interface NextConfigLike {
50
+ env?: Record<string, string | undefined> | undefined;
51
+ turbopack?: {
52
+ resolveAlias?: Record<string, unknown> | undefined;
53
+ } | undefined;
54
+ webpack?(config: WebpackConfigLike, context: unknown): WebpackConfigLike;
55
+ }
56
+ /**
57
+ * The client variables the loader gate and the env ladder read. Next inlines a
58
+ * `NEXT_PUBLIC_*` read only when the variable is set at build time; Turbopack
59
+ * leaves an unset one as a runtime `process.env` lookup, so the gate
60
+ * `NODE_ENV === "development" || NEXT_PUBLIC_HUD_ENABLED === "true"` does not
61
+ * fold and the dev HUD ships as a production chunk (hud#64). `withHud` pins
62
+ * each to a build-time literal, `""` when unset.
63
+ */
64
+ export declare const HUD_PUBLIC_ENV: readonly ["NEXT_PUBLIC_HUD_ENABLED", "NEXT_PUBLIC_HUD_DISABLED", "NEXT_PUBLIC_HUD_ENV"];
65
+ /** Reads, detects and writes `.hud/auto.mjs`; returns the detection and the file's absolute path. */
66
+ export declare function writeAutoModule({ dir, packageJson }?: WithHudOptions): {
67
+ detected: HudAutoDetected;
68
+ file: string;
69
+ };
70
+ /**
71
+ * Wraps next.config: reads the app's package.json, writes `.hud/auto.mjs`
72
+ * (a module importing only the plugins the dependencies call for) and
73
+ * aliases `@hansenexus/hud/auto` to it, for Turbopack and webpack alike.
74
+ * Runs on every `next dev` and `next build`, so the file follows
75
+ * package.json; it belongs in .gitignore. It also pins the HUD's
76
+ * `NEXT_PUBLIC_*` variables (`HUD_PUBLIC_ENV`) through `env`, so the loader
77
+ * gate folds when they are unset; an app's own `env` entry wins.
78
+ *
79
+ * ```js
80
+ * // next.config.js (ESM), or next.config.ts through `require()`
81
+ * import { withHud } from "@hansenexus/hud/next/config";
82
+ * export default withHud({ reactStrictMode: true });
83
+ * ```
84
+ */
85
+ export declare function withHud(config?: undefined, options?: WithHudOptions): NextConfigLike;
86
+ export declare function withHud<C extends object>(config: C, options?: WithHudOptions): C;
87
+ //#endregion
@@ -19,17 +19,26 @@ interface WebpackConfigLike {
19
19
  }
20
20
  /**
21
21
  * The slice of `NextConfig` the wrapper touches, structurally, so `next` is
22
- * neither imported nor a peer. Method syntax keeps Next's own `webpack`
23
- * signature assignable.
22
+ * neither imported nor a peer. No index signatures: Next's own `NextConfig`
23
+ * and `TurbopackOptions` are interfaces without one (hud#66). Method syntax
24
+ * keeps Next's own `webpack` signature assignable.
24
25
  */
25
26
  export interface NextConfigLike {
27
+ env?: Record<string, string | undefined> | undefined;
26
28
  turbopack?: {
27
29
  resolveAlias?: Record<string, unknown> | undefined;
28
- [key: string]: unknown;
29
30
  } | undefined;
30
31
  webpack?(config: WebpackConfigLike, context: unknown): WebpackConfigLike;
31
- [key: string]: unknown;
32
32
  }
33
+ /**
34
+ * The client variables the loader gate and the env ladder read. Next inlines a
35
+ * `NEXT_PUBLIC_*` read only when the variable is set at build time; Turbopack
36
+ * leaves an unset one as a runtime `process.env` lookup, so the gate
37
+ * `NODE_ENV === "development" || NEXT_PUBLIC_HUD_ENABLED === "true"` does not
38
+ * fold and the dev HUD ships as a production chunk (hud#64). `withHud` pins
39
+ * each to a build-time literal, `""` when unset.
40
+ */
41
+ export declare const HUD_PUBLIC_ENV: readonly ["NEXT_PUBLIC_HUD_ENABLED", "NEXT_PUBLIC_HUD_DISABLED", "NEXT_PUBLIC_HUD_ENV"];
33
42
  /** Reads, detects and writes `.hud/auto.mjs`; returns the detection and the file's absolute path. */
34
43
  export declare function writeAutoModule({ dir, packageJson }?: WithHudOptions): {
35
44
  detected: HudAutoDetected;
@@ -40,13 +49,16 @@ export declare function writeAutoModule({ dir, packageJson }?: WithHudOptions):
40
49
  * (a module importing only the plugins the dependencies call for) and
41
50
  * aliases `@hansenexus/hud/auto` to it, for Turbopack and webpack alike.
42
51
  * Runs on every `next dev` and `next build`, so the file follows
43
- * package.json; it belongs in .gitignore.
52
+ * package.json; it belongs in .gitignore. It also pins the HUD's
53
+ * `NEXT_PUBLIC_*` variables (`HUD_PUBLIC_ENV`) through `env`, so the loader
54
+ * gate folds when they are unset; an app's own `env` entry wins.
44
55
  *
45
56
  * ```js
46
- * // next.config.js
57
+ * // next.config.js (ESM), or next.config.ts through `require()`
47
58
  * import { withHud } from "@hansenexus/hud/next/config";
48
59
  * export default withHud({ reactStrictMode: true });
49
60
  * ```
50
61
  */
51
- export declare function withHud<C extends NextConfigLike>(config?: C, options?: WithHudOptions): C;
62
+ export declare function withHud(config?: undefined, options?: WithHudOptions): NextConfigLike;
63
+ export declare function withHud<C extends object>(config: C, options?: WithHudOptions): C;
52
64
  //#endregion
@@ -7,6 +7,19 @@ import { dirname, resolve } from "node:path";
7
7
  const AUTO_ID = "@hansenexus/hud/auto";
8
8
  /** Where the generated module lives, relative to the app dir. Add it to .gitignore. */
9
9
  const AUTO_FILE = ".hud/auto.mjs";
10
+ /**
11
+ * The client variables the loader gate and the env ladder read. Next inlines a
12
+ * `NEXT_PUBLIC_*` read only when the variable is set at build time; Turbopack
13
+ * leaves an unset one as a runtime `process.env` lookup, so the gate
14
+ * `NODE_ENV === "development" || NEXT_PUBLIC_HUD_ENABLED === "true"` does not
15
+ * fold and the dev HUD ships as a production chunk (hud#64). `withHud` pins
16
+ * each to a build-time literal, `""` when unset.
17
+ */
18
+ const HUD_PUBLIC_ENV = [
19
+ "NEXT_PUBLIC_HUD_ENABLED",
20
+ "NEXT_PUBLIC_HUD_DISABLED",
21
+ "NEXT_PUBLIC_HUD_ENV"
22
+ ];
10
23
  /** Reads, detects and writes `.hud/auto.mjs`; returns the detection and the file's absolute path. */
11
24
  function writeAutoModule({ dir = process.cwd(), packageJson } = {}) {
12
25
  const manifest = packageJson ?? resolve(dir, "package.json");
@@ -32,25 +45,18 @@ function writeAutoModule({ dir = process.cwd(), packageJson } = {}) {
32
45
  file
33
46
  };
34
47
  }
35
- /**
36
- * Wraps next.config: reads the app's package.json, writes `.hud/auto.mjs`
37
- * (a module importing only the plugins the dependencies call for) and
38
- * aliases `@hansenexus/hud/auto` to it, for Turbopack and webpack alike.
39
- * Runs on every `next dev` and `next build`, so the file follows
40
- * package.json; it belongs in .gitignore.
41
- *
42
- * ```js
43
- * // next.config.js
44
- * import { withHud } from "@hansenexus/hud/next/config";
45
- * export default withHud({ reactStrictMode: true });
46
- * ```
47
- */
48
48
  function withHud(config, options = {}) {
49
49
  const base = config ?? {};
50
50
  const { file } = writeAutoModule(options);
51
51
  const webpack = base.webpack;
52
+ const pinned = {};
53
+ for (const key of HUD_PUBLIC_ENV) pinned[key] = process.env[key] ?? "";
52
54
  return {
53
55
  ...base,
56
+ env: {
57
+ ...pinned,
58
+ ...base.env
59
+ },
54
60
  turbopack: {
55
61
  ...base.turbopack,
56
62
  resolveAlias: {
@@ -75,4 +81,4 @@ function withHud(config, options = {}) {
75
81
  };
76
82
  }
77
83
  //#endregion
78
- export { AUTO_FILE, AUTO_ID, withHud, writeAutoModule };
84
+ export { AUTO_FILE, AUTO_ID, HUD_PUBLIC_ENV, withHud, writeAutoModule };
@@ -25,7 +25,7 @@ function DataPill({ ctx }) {
25
25
  }
26
26
  //#endregion
27
27
  //#region src/plugins/data/index.tsx
28
- const Panel = lazy(() => import("../data-panel-DhxAmP91.js"));
28
+ const Panel = lazy(() => import("../data-panel-BmcHCQnM.js"));
29
29
  /**
30
30
  * Role switch, feature-flag overrides, seeds and mock scenarios. The pill
31
31
  * shows who the page is signed in as, how many flags are overridden and how
@@ -12,11 +12,23 @@ const MAX_ROWS = 100;
12
12
  function inspectReactQuery({ queryClient }) {
13
13
  const cache = queryClient.getQueryCache();
14
14
  let version = 0;
15
+ let scheduled = false;
16
+ let disposed = false;
15
17
  const listeners = /* @__PURE__ */ new Set();
16
- const unsubscribe = cache.subscribe(() => {
17
- version++;
18
- for (const listener of listeners) listener();
18
+ const unsubscribeCache = cache.subscribe(() => {
19
+ if (scheduled) return;
20
+ scheduled = true;
21
+ queueMicrotask(() => {
22
+ scheduled = false;
23
+ if (disposed) return;
24
+ version++;
25
+ for (const listener of listeners) listener();
26
+ });
19
27
  });
28
+ const unsubscribe = () => {
29
+ disposed = true;
30
+ unsubscribeCache();
31
+ };
20
32
  const subscribe = (listener) => {
21
33
  listeners.add(listener);
22
34
  return () => listeners.delete(listener);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hansenexus/hud",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Modular dev HUD for React apps: status pill, floating panels, element grabber, plugin API.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,8 +33,14 @@
33
33
  "import": "./dist/next.js"
34
34
  },
35
35
  "./next/config": {
36
- "types": "./dist/next/config.d.ts",
37
- "import": "./dist/next/config.js"
36
+ "import": {
37
+ "types": "./dist/next/config.d.ts",
38
+ "default": "./dist/next/config.js"
39
+ },
40
+ "require": {
41
+ "types": "./dist/next/config.d.cts",
42
+ "default": "./dist/next/config.cjs"
43
+ }
38
44
  },
39
45
  "./vite": {
40
46
  "types": "./dist/vite.d.ts",
@@ -141,6 +147,7 @@
141
147
  "convex": "^1.46.0",
142
148
  "jsdom": "^30.1.2",
143
149
  "msw": "^3.0.2",
150
+ "next": "^16.4.0",
144
151
  "playwright": "1.63.0",
145
152
  "rolldown": "^1.2.12",
146
153
  "swr": "^2.5.1",