cursedbelt 5.30.0 → 5.32.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 (40) hide show
  1. package/dist/react/components/ConfirmDialog.d.ts +4 -1
  2. package/dist/react/components/ConfirmDialog.d.ts.map +1 -1
  3. package/dist/react/components/ConfirmDialog.js +2 -2
  4. package/dist/react/components/ConfirmDialog.js.map +1 -1
  5. package/dist/react/components/DataTable/DataTable.d.ts.map +1 -1
  6. package/dist/react/components/DataTable/DataTable.js +5 -1
  7. package/dist/react/components/DataTable/DataTable.js.map +1 -1
  8. package/dist/react/components/PromptDialog.d.ts +4 -1
  9. package/dist/react/components/PromptDialog.d.ts.map +1 -1
  10. package/dist/react/components/PromptDialog.js +2 -2
  11. package/dist/react/components/PromptDialog.js.map +1 -1
  12. package/dist/react/file-tree/FileTree.d.ts +26 -1
  13. package/dist/react/file-tree/FileTree.d.ts.map +1 -1
  14. package/dist/react/file-tree/FileTree.js +182 -40
  15. package/dist/react/file-tree/FileTree.js.map +1 -1
  16. package/dist/scripts/guardrailsEnforce.d.ts +11 -0
  17. package/dist/scripts/guardrailsEnforce.d.ts.map +1 -1
  18. package/dist/testing/index.d.ts +3 -0
  19. package/dist/testing/index.d.ts.map +1 -0
  20. package/dist/testing/index.js +4 -0
  21. package/dist/testing/index.js.map +1 -0
  22. package/dist/testing/objectLeak.d.ts +23 -0
  23. package/dist/testing/objectLeak.d.ts.map +1 -0
  24. package/dist/testing/objectLeak.js +37 -0
  25. package/dist/testing/objectLeak.js.map +1 -0
  26. package/package.json +5 -5
  27. package/scripts/guardrails-baseline.json +4 -1
  28. package/scripts/guardrailsEnforce.spec.ts +163 -6
  29. package/scripts/guardrailsEnforce.ts +365 -40
  30. package/scripts/paths.ts +1 -1
  31. package/src/react/components/ConfirmDialog.tsx +5 -0
  32. package/src/react/components/DataTable/DataTable.spec.tsx +16 -0
  33. package/src/react/components/DataTable/DataTable.tsx +5 -1
  34. package/src/react/components/PromptDialog.spec.tsx +29 -1
  35. package/src/react/components/PromptDialog.tsx +5 -0
  36. package/src/react/file-tree/FileTree.spec.tsx +205 -0
  37. package/src/react/file-tree/FileTree.tsx +220 -38
  38. package/src/testing/index.ts +3 -0
  39. package/src/testing/objectLeak.spec.ts +21 -0
  40. package/src/testing/objectLeak.ts +39 -0
@@ -243,10 +243,17 @@ interface DragState {
243
243
  y: number;
244
244
  active: boolean;
245
245
  offer: DropOffer;
246
+ /** The pointer is outside the tree, where only `onDropOutside` can take the rows. */
247
+ outside: boolean;
246
248
  }
247
249
 
248
250
  const NO_OFFER: DropOffer = { target: null, refused: false, reason: null };
249
251
 
252
+ /** The chip outside the tree when the consumer did not say what is there — see `onDropOutside`. */
253
+ const OUTSIDE_WORDS = 'Drop to add it here';
254
+ /** The chip over a place outside the tree that `describeDropOutside` said takes nothing. */
255
+ const OUTSIDE_REFUSED = 'Nothing here takes it';
256
+
250
257
  /**
251
258
  * What {@link FileTree}'s `externalOverId` holds while an EXTERNAL drag is over the blank
252
259
  * space below the rows — the root. `null` already means "over nothing", and the two must
@@ -390,6 +397,28 @@ export interface FileTreeProps {
390
397
  * move named twice, and acting on both flattens the child out of its own parent.
391
398
  */
392
399
  onMoveMany?: (nodeIds: readonly string[], drop: FileTreeDrop) => void;
400
+ /**
401
+ * Take a drag the tree cannot — rows let go OUTSIDE the tree, onto whatever the consumer
402
+ * draws beside it (a board, an editor, a drop zone). Obsidian's gesture: drag a file from the
403
+ * sidebar onto a canvas and it lands there.
404
+ *
405
+ * 🔴 The tree drags with pointer events, not HTML5 drag-and-drop (touch has none), so a row
406
+ * released over another element sends that element no `drop` event at all. This prop is
407
+ * the only way the gesture can reach past the tree. `point` is the release, in client
408
+ * coordinates — `document.elementFromPoint(point.clientX, point.clientY)` finds what is
409
+ * under it. Given this prop, a press starts a drag even when the tree cannot be rearranged.
410
+ */
411
+ onDropOutside?: (
412
+ nodeIds: readonly string[],
413
+ point: { clientX: number; clientY: number },
414
+ ) => void;
415
+ /**
416
+ * What the drag chip says while the rows are held outside the tree: words for a place that
417
+ * takes them ("Onto the canvas"), `null` for one that does not — then the chip says so and a
418
+ * release there puts the rows back without calling {@link onDropOutside}. Omit it and every
419
+ * point outside the tree takes the drop.
420
+ */
421
+ describeDropOutside?: (point: { clientX: number; clientY: number }) => string | null;
393
422
  /** See `ResolveDropOptions.allowReorder`. Off unless the consumer stores an order. */
394
423
  allowReorder?: boolean;
395
424
  /** Words for refusing a drop into a node whose `acceptsDrop` is false. */
@@ -737,6 +766,8 @@ export function FileTree({
737
766
  pinnedLabel = 'Pinned',
738
767
  onMove,
739
768
  onMoveMany,
769
+ onDropOutside,
770
+ describeDropOutside,
740
771
  allowReorder = false,
741
772
  lockedReason,
742
773
  canDrop,
@@ -773,6 +804,8 @@ export function FileTree({
773
804
  scroll = 'own',
774
805
  }: FileTreeProps): JSX.Element {
775
806
  const scrollRef = useRef<HTMLDivElement>(null);
807
+ /** The whole tree, pinned section included — "outside" for `onDropOutside` is outside this. */
808
+ const rootRef = useRef<HTMLDivElement>(null);
776
809
  const rowRefs = useRef(new Map<string, HTMLElement>());
777
810
  /**
778
811
  * The PINNED copies' elements, in a map of their own.
@@ -917,6 +950,29 @@ export function FileTree({
917
950
  mode: 'cut' | 'copy';
918
951
  ids: readonly string[];
919
952
  } | null>(null);
953
+ /**
954
+ * The text ⌘X/⌘C also put on the SYSTEM clipboard (the rows' names, one per line), once the
955
+ * write has landed — `null` while nothing of the tree's is known to be there.
956
+ *
957
+ * 🔴 Finder has one clipboard, so the newest copy always wins; this tree's own clipboard is
958
+ * a second one, and without this a row copied an hour ago beat a screenshot copied a moment
959
+ * ago (task 2371: ⌘C a row, ⌘⇧4 + ⌘C a picture, ⌘V → the row was pasted and the picture
960
+ * never arrived). With the names mirrored, the `paste` event can tell which is newer: its
961
+ * text still equal to this means the rows are the last thing copied; anything else — files,
962
+ * other text — means the person copied something since, and the rows are put down.
963
+ *
964
+ * Where the mirror cannot be written (no `navigator.clipboard`, an insecure origin, a
965
+ * refused permission) there is nothing to compare against, and ⌘V pastes the rows on the
966
+ * keydown exactly as it did before.
967
+ */
968
+ const mirrored = useRef<string | null>(null);
969
+ /** Bumped by every ⌘X/⌘C, so a slow write for an older copy cannot claim the mirror. */
970
+ const mirrorSeq = useRef(0);
971
+ /** The row a ⌘V keydown aimed at, waiting for the `paste` event to say whose it is. */
972
+ const pendingPaste = useRef<FileTreeRow | null>(null);
973
+ useEffect(() => {
974
+ if (!clipboard) mirrored.current = null;
975
+ }, [clipboard]);
920
976
 
921
977
  const shown = useMemo(() => (filter ? filterFileTree(nodes, filter) : nodes), [nodes, filter]);
922
978
  /*
@@ -972,6 +1028,24 @@ export function FileTree({
972
1028
  [clipboard],
973
1029
  );
974
1030
 
1031
+ /** Put the held rows' names on the system clipboard too — see `mirrored`. */
1032
+ const mirror = useCallback(
1033
+ (ids: readonly string[]) => {
1034
+ const seq = ++mirrorSeq.current;
1035
+ mirrored.current = null;
1036
+ const text = ids.map((id) => nameOf(shown, id)).join('\n');
1037
+ const write = globalThis.navigator?.clipboard?.writeText?.bind(globalThis.navigator.clipboard);
1038
+ if (!write) return;
1039
+ write(text).then(
1040
+ () => {
1041
+ if (mirrorSeq.current === seq) mirrored.current = text;
1042
+ },
1043
+ () => {},
1044
+ );
1045
+ },
1046
+ [shown],
1047
+ );
1048
+
975
1049
  /**
976
1050
  * Which rows a gesture aimed at `node` should act on: the selection when `node` is part of
977
1051
  * one and the consumer wired the plural verb, and `node` alone otherwise.
@@ -1328,7 +1402,13 @@ export function FileTree({
1328
1402
  // click — see `draggedJustNow`. Set for a cancelled drag too: the click arrives either
1329
1403
  // way, and Escape landing you on a different row would be its own surprise.
1330
1404
  if (state?.active) draggedJustNow.current = true;
1331
- if (commit && state?.active && state.offer.target && canRearrange) {
1405
+ if (commit && state?.active && state.outside) {
1406
+ if (!state.offer.refused) onDropOutside?.(state.ids, { clientX: state.x, clientY: state.y });
1407
+ // Folders sprung open on the way out stay open behind a drop that landed elsewhere —
1408
+ // but one that went nowhere puts them back, like any drag that went nowhere.
1409
+ if (state.offer.refused && sprung.current.length > 0) shutFolders(sprung.current);
1410
+ sprung.current = [];
1411
+ } else if (commit && state?.active && state.offer.target && canRearrange) {
1332
1412
  commitMove(state.ids, state.offer.target);
1333
1413
  sprung.current = [];
1334
1414
  } else if (sprung.current.length > 0) {
@@ -1340,14 +1420,15 @@ export function FileTree({
1340
1420
  }
1341
1421
  setDrag(null);
1342
1422
  },
1343
- [canRearrange, commitMove, shutFolders, stopAutoScroll, stopSpring],
1423
+ [canRearrange, commitMove, onDropOutside, shutFolders, stopAutoScroll, stopSpring],
1344
1424
  );
1345
1425
 
1346
1426
  const beginDrag = useCallback(
1347
1427
  (event: ReactPointerEvent<HTMLElement>, node: FileTreeNode) => {
1348
1428
  // A row the consumer marked undraggable never starts a gesture — see
1349
1429
  // `FileTreeNode.draggable`. A drag that refuses everywhere reads as a broken tree.
1350
- if (!canRearrange || event.button !== 0 || node.draggable === false) return;
1430
+ if (!(canRearrange || onDropOutside) || event.button !== 0 || node.draggable === false)
1431
+ return;
1351
1432
 
1352
1433
  /*
1353
1434
  * Press a row that is part of a selection and the whole selection comes with you —
@@ -1378,6 +1459,7 @@ export function FileTree({
1378
1459
  y: startY,
1379
1460
  active: false,
1380
1461
  offer: NO_OFFER,
1462
+ outside: false,
1381
1463
  };
1382
1464
  const target = event.currentTarget;
1383
1465
  target.setPointerCapture?.(event.pointerId);
@@ -1387,6 +1469,30 @@ export function FileTree({
1387
1469
  Math.abs(moveEvent.clientX - startX) + Math.abs(moveEvent.clientY - startY);
1388
1470
  if (!state.active && travelled < DRAG_THRESHOLD) return;
1389
1471
 
1472
+ const point = { clientX: moveEvent.clientX, clientY: moveEvent.clientY };
1473
+ const bounds = rootRef.current?.getBoundingClientRect();
1474
+ const outside = Boolean(
1475
+ onDropOutside &&
1476
+ bounds &&
1477
+ (point.clientX < bounds.left ||
1478
+ point.clientX > bounds.right ||
1479
+ point.clientY < bounds.top ||
1480
+ point.clientY > bounds.bottom),
1481
+ );
1482
+ if (outside) {
1483
+ // Nothing in the tree is under the pointer, so no spring, no autoscroll, no row lit.
1484
+ stopSpring();
1485
+ stopAutoScroll();
1486
+ const words = describeDropOutside ? describeDropOutside(point) : OUTSIDE_WORDS;
1487
+ const offer: DropOffer =
1488
+ words === null
1489
+ ? { target: null, refused: true, reason: OUTSIDE_REFUSED }
1490
+ : { target: null, refused: false, reason: words };
1491
+ state = { ...state, x: point.clientX, y: point.clientY, active: true, offer, outside };
1492
+ setDrag(state);
1493
+ return;
1494
+ }
1495
+
1390
1496
  const hit = rowAt(moveEvent.clientX, moveEvent.clientY);
1391
1497
  // One row or twenty, the same call: `resolveMultiDrop` is `resolveDrop` asked once
1392
1498
  // per carried row, and the strictest answer wins. See its header for why a single
@@ -1440,7 +1546,16 @@ export function FileTree({
1440
1546
  };
1441
1547
  }
1442
1548
 
1443
- state = { ...state, x: moveEvent.clientX, y: moveEvent.clientY, active: true, offer };
1549
+ state = {
1550
+ ...state,
1551
+ x: moveEvent.clientX,
1552
+ y: moveEvent.clientY,
1553
+ active: true,
1554
+ // A tree that cannot be rearranged still carries rows OUT — see `onDropOutside` —
1555
+ // but nothing inside it is somewhere they can land.
1556
+ offer: canRearrange ? offer : NO_OFFER,
1557
+ outside: false,
1558
+ };
1444
1559
  setDrag(state);
1445
1560
  };
1446
1561
 
@@ -1483,8 +1598,10 @@ export function FileTree({
1483
1598
  takesDrop,
1484
1599
  canRearrange,
1485
1600
  collapsed,
1601
+ describeDropOutside,
1486
1602
  endDrag,
1487
1603
  lockedReason,
1604
+ onDropOutside,
1488
1605
  onMoveMany,
1489
1606
  openFolder,
1490
1607
  rowAt,
@@ -1568,6 +1685,50 @@ export function FileTree({
1568
1685
  focusRow(previous);
1569
1686
  }, [renamingId, focusRow]);
1570
1687
 
1688
+ /**
1689
+ * ⌘V's half of the clipboard: the held rows land where `row` says, by the drop rules a
1690
+ * drag obeys (`resolveMultiDrop`).
1691
+ */
1692
+ const pasteRows = useCallback(
1693
+ (row: FileTreeRow) => {
1694
+ if (!clipboard) return;
1695
+ const offer = resolveMultiDrop({
1696
+ nodes: shown,
1697
+ row,
1698
+ // The middle of the row: "into this", never "between these two". Reordering is a
1699
+ // pointer gesture — a paste has no edge to aim at.
1700
+ offsetRatio: 0.5,
1701
+ allowReorder: false,
1702
+ /*
1703
+ * 🔴 The carried ids are declared for a COPY too, so the descendant rule applies
1704
+ * to it: a folder cannot be pasted inside itself any more than it can be dragged
1705
+ * there. What that rule does NOT refuse is the case the owner named — *"copying
1706
+ * in … the same folder"* — because a row's own parent is not a descendant of it.
1707
+ */
1708
+ dragIds: clipboard.ids,
1709
+ ...(lockedReason ? { lockedReason } : {}),
1710
+ ...(canDrop ? { canDrop } : {}),
1711
+ ...(takesDrop ? { takesDrop } : {}),
1712
+ });
1713
+ if (!offer.target) {
1714
+ setNotice(offer.reason ?? '');
1715
+ return;
1716
+ }
1717
+ setNotice(describeDrop(shown, offer.target));
1718
+ if (clipboard.mode === 'copy') {
1719
+ onCopy?.(clipboard.ids, offer.target);
1720
+ // Kept, not cleared: Finder pastes the same copy again, and *"copying in another
1721
+ // folder or the same folder"* is two pastes of one ⌘C.
1722
+ return;
1723
+ }
1724
+ commitMove(clipboard.ids, offer.target);
1725
+ // The rows have moved. A second paste would move them again from wherever they
1726
+ // now are, which is not what the person cut them for.
1727
+ setClipboard(null);
1728
+ },
1729
+ [canDrop, clipboard, commitMove, lockedReason, onCopy, shown, takesDrop],
1730
+ );
1731
+
1571
1732
  const onKeyDown = useCallback(
1572
1733
  (
1573
1734
  event: React.KeyboardEvent<HTMLElement>,
@@ -1708,6 +1869,7 @@ export function FileTree({
1708
1869
  event.preventDefault();
1709
1870
  const { ids } = actOn(row.node, Boolean(onMoveMany));
1710
1871
  setClipboard({ mode: 'cut', ids });
1872
+ mirror(ids);
1711
1873
  setNotice(ids.length > 1 ? `Cut ${ids.length} items` : `Cut ${row.node.name}`);
1712
1874
  return;
1713
1875
  }
@@ -1722,44 +1884,28 @@ export function FileTree({
1722
1884
  return;
1723
1885
  }
1724
1886
  setClipboard({ mode: 'copy', ids });
1887
+ mirror(ids);
1725
1888
  setNotice(ids.length > 1 ? `Copied ${ids.length} items` : `Copied ${row.node.name}`);
1726
1889
  return;
1727
1890
  }
1728
1891
  if (event.key === 'v' && clipboard) {
1729
- event.preventDefault();
1730
- const offer = resolveMultiDrop({
1731
- nodes: shown,
1732
- row,
1733
- // The middle of the row: "into this", never "between these two". Reordering is a
1734
- // pointer gesture — a paste has no edge to aim at.
1735
- offsetRatio: 0.5,
1736
- allowReorder: false,
1737
- /*
1738
- * 🔴 The carried ids are declared for a COPY too, so the descendant rule applies
1739
- * to it: a folder cannot be pasted inside itself any more than it can be dragged
1740
- * there. What that rule does NOT refuse is the case the owner named — *"copying
1741
- * in … the same folder"* — because a row's own parent is not a descendant of it.
1742
- */
1743
- dragIds: clipboard.ids,
1744
- ...(lockedReason ? { lockedReason } : {}),
1745
- ...(canDrop ? { canDrop } : {}),
1746
- ...(takesDrop ? { takesDrop } : {}),
1747
- });
1748
- if (!offer.target) {
1749
- setNotice(offer.reason ?? '');
1750
- return;
1751
- }
1752
- setNotice(describeDrop(shown, offer.target));
1753
- if (clipboard.mode === 'copy') {
1754
- onCopy?.(clipboard.ids, offer.target);
1755
- // Kept, not cleared: Finder pastes the same copy again, and *"copying in another
1756
- // folder or the same folder"* is two pastes of one ⌘C.
1892
+ /*
1893
+ * With the mirror written, the `paste` event decides (see `onPaste` on the root):
1894
+ * the key is left to the browser so that event fires at all. The timer is the
1895
+ * fallback for an engine that sends no `paste` to a row that is not editable — the
1896
+ * event, where it comes, comes inside this same keypress, before any timer.
1897
+ */
1898
+ if (mirrored.current !== null) {
1899
+ pendingPaste.current = row;
1900
+ setTimeout(() => {
1901
+ if (pendingPaste.current !== row) return;
1902
+ pendingPaste.current = null;
1903
+ pasteRows(row);
1904
+ }, 0);
1757
1905
  return;
1758
1906
  }
1759
- commitMove(clipboard.ids, offer.target);
1760
- // The rows have moved. A second paste would move them again from wherever they
1761
- // now are, which is not what the person cut them for.
1762
- setClipboard(null);
1907
+ event.preventDefault();
1908
+ pasteRows(row);
1763
1909
  return;
1764
1910
  }
1765
1911
  return;
@@ -1935,7 +2081,6 @@ export function FileTree({
1935
2081
  actOn,
1936
2082
  canCopy,
1937
2083
  canDrop,
1938
- takesDrop,
1939
2084
  canRearrange,
1940
2085
  canWrap,
1941
2086
  clipboard,
@@ -1952,6 +2097,8 @@ export function FileTree({
1952
2097
  onRowMenu,
1953
2098
  onSelect,
1954
2099
  onWrapStart,
2100
+ mirror,
2101
+ pasteRows,
1955
2102
  renamingId,
1956
2103
  rowEl,
1957
2104
  rows,
@@ -1961,6 +2108,39 @@ export function FileTree({
1961
2108
  ],
1962
2109
  );
1963
2110
 
2111
+ /**
2112
+ * The `paste` a ⌘V on a row leaves to the browser once the mirror is written (see
2113
+ * `mirrored`) — here it is decided whose paste it is.
2114
+ *
2115
+ * Files on the clipboard, or text that is not the rows' names, mean something was copied
2116
+ * after the rows: the rows are put down and the event goes on untouched, to whatever the
2117
+ * consumer does with a paste (desk files a screenshot into the folder). The names still
2118
+ * there mean the rows ARE the newest copy, and they are pasted — the event cancelled and
2119
+ * stopped, so nothing above pastes the same keypress a second time.
2120
+ */
2121
+ const onPaste = useCallback(
2122
+ (event: React.ClipboardEvent<HTMLDivElement>) => {
2123
+ const row = pendingPaste.current;
2124
+ pendingPaste.current = null;
2125
+ const held = mirrored.current;
2126
+ if (!clipboard || held === null) return;
2127
+ const data = event.clipboardData;
2128
+ const files =
2129
+ (data?.files?.length ?? 0) > 0 ||
2130
+ Array.from(data?.items ?? []).some((item) => item.kind === 'file');
2131
+ if (files || (data?.getData('text/plain') ?? '') !== held) {
2132
+ setClipboard(null);
2133
+ setNotice('');
2134
+ return;
2135
+ }
2136
+ if (!row) return;
2137
+ event.preventDefault();
2138
+ event.stopPropagation();
2139
+ pasteRows(row);
2140
+ },
2141
+ [clipboard, pasteRows],
2142
+ );
2143
+
1964
2144
  // ── External drags (Finder files, gallery tiles) ──────────────────────────────────────
1965
2145
 
1966
2146
  const externalWanted = useCallback(
@@ -2522,7 +2702,7 @@ export function FileTree({
2522
2702
 
2523
2703
  Decorative to a screen reader: the keyboard's move is ⌥→/⌥←, not this.
2524
2704
  */}
2525
- {canRearrange && node.draggable !== false ? (
2705
+ {(canRearrange || onDropOutside) && node.draggable !== false ? (
2526
2706
  <span className='cbft-grip' aria-hidden='true' data-cbft-grip=''>
2527
2707
  {/* Lucide's `grip-vertical`, drawn for the reason the chevron and the pin are. */}
2528
2708
  <svg
@@ -2573,6 +2753,8 @@ export function FileTree({
2573
2753
 
2574
2754
  return (
2575
2755
  <div
2756
+ ref={rootRef}
2757
+ onPaste={onPaste}
2576
2758
  className={`cbft${scroll === 'host' ? ' cbft--host-scroll' : ''}${className ? ` ${className}` : ''}`}
2577
2759
  /* See `markPath` — the path is still marked in the DOM, only not painted. */
2578
2760
  data-quiet-path={markPath ? undefined : true}
@@ -0,0 +1,3 @@
1
+ // `cursedbelt/testing` — helpers a consuming app's specs import. Each file says what it reads.
2
+ export { expectNoObjectLeak, findObjectLeak, type TextSource } from "./objectLeak";
3
+ export { hoverHint, tooltipReady } from "./tooltip";
@@ -0,0 +1,21 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { expectNoObjectLeak, findObjectLeak } from "./objectLeak";
3
+
4
+ describe("expectNoObjectLeak (task 2381)", () => {
5
+ test("🔴 throws on an object rendered as text, quoting where", () => {
6
+ const text = `Owner: ${String({ id: 1 })} · 3 files`;
7
+ expect(() => expectNoObjectLeak(text)).toThrow("Owner: [object Object] · 3 files");
8
+ });
9
+
10
+ test("reads a DOM node's text and a page's innerText alike", () => {
11
+ const node = document.createElement("div");
12
+ node.innerHTML = `<p>size</p><span>${String(Promise.resolve())}</span>`;
13
+ expect(findObjectLeak(node)).toContain("[object Promise]");
14
+ expect(findObjectLeak({ innerText: "width: undefinedpx" })).toContain("undefinedpx");
15
+ });
16
+
17
+ test("clean text passes, including the words object and undefined in prose", () => {
18
+ expect(() => expectNoObjectLeak("No object selected — the field is undefined until you pick one")).not.toThrow();
19
+ expect(findObjectLeak({ textContent: null })).toBeNull();
20
+ });
21
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `[object Object]` on a screen, caught by the test that rendered it.
3
+ *
4
+ * DESIGN.md "Core Mandate" forbids it by name — a literal `[object Object]` leaking into a view —
5
+ * and no scanner can see it coming: it is a value (`${row.owner}`, `{error}`, `String(meta)`)
6
+ * that happens to be an object at runtime, which compiles, typechecks and renders. The only
7
+ * place it is visible is the rendered text, so that is what this reads (task 2381).
8
+ *
9
+ * Plain functions that throw a plain `Error`, with no test-framework import, so the same call
10
+ * works from a `bun:test` + happy-dom spec (`expectNoObjectLeak(container)`) and from a
11
+ * browser spec that reads the page's text (`expectNoObjectLeak(await page.innerText("body"))`).
12
+ */
13
+
14
+ const LEAK_RE = /\[object (?:Object|Promise|Map|Set|Module)\]|\bundefined(?:px|rem|%)\b|\bNaN(?:px|rem|%)\b/;
15
+
16
+ /** Anything a DOM node or a page can hand over as its visible text. */
17
+ export type TextSource = string | { textContent: string | null } | { innerText: string };
18
+
19
+ function textOf(source: TextSource): string {
20
+ if (typeof source === "string") return source;
21
+ if ("innerText" in source && typeof source.innerText === "string") return source.innerText;
22
+ return (source as { textContent: string | null }).textContent ?? "";
23
+ }
24
+
25
+ /** The first leaked value in `source` with ~40 characters either side, or `null` when clean. */
26
+ export function findObjectLeak(source: TextSource): string | null {
27
+ const text = textOf(source);
28
+ const match = LEAK_RE.exec(text);
29
+ if (!match) return null;
30
+ const from = Math.max(0, match.index - 40);
31
+ const to = Math.min(text.length, match.index + match[0].length + 40);
32
+ return `${from > 0 ? "…" : ""}${text.slice(from, to).replace(/\s+/g, " ")}${to < text.length ? "…" : ""}`;
33
+ }
34
+
35
+ /** Throw when the rendered text shows a value that was never meant to be text. */
36
+ export function expectNoObjectLeak(source: TextSource): void {
37
+ const leak = findObjectLeak(source);
38
+ if (leak) throw new Error(`rendered text leaks a non-text value (DESIGN.md Core Mandate): ${leak}`);
39
+ }