@slopit/behavioral 0.1.0 → 0.2.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.
package/dist/index.js CHANGED
@@ -1104,8 +1104,8 @@ var BehavioralCapture = class {
1104
1104
  mouseCollector = null;
1105
1105
  scrollCollector = null;
1106
1106
  inputDurationCollector = null;
1107
- attachedElement = null;
1108
1107
  trialStartTime = 0;
1108
+ attachedElement = null;
1109
1109
  listeners = /* @__PURE__ */ new Map();
1110
1110
  constructor(config) {
1111
1111
  this.config = this.normalizeConfig(config);
@@ -1462,209 +1462,119 @@ var PasteCollector = class {
1462
1462
  }
1463
1463
  };
1464
1464
 
1465
- // src/detection/text-appearance.ts
1466
- var DEFAULT_CONFIG = {
1467
- minTextLength: 50,
1468
- timeWindowMs: 2e3
1469
- };
1470
- var TextAppearanceDetector = class {
1471
- name = "text_appearance";
1472
- observer = null;
1473
- indicators = [];
1474
- lastTextLength = /* @__PURE__ */ new Map();
1475
- keystrokeCallback;
1476
- pasteCallback;
1477
- config;
1478
- startTime;
1479
- monitoredElement = null;
1480
- inputHandler = null;
1481
- /**
1482
- * Creates a new TextAppearanceDetector.
1483
- *
1484
- * @param config - Configuration options
1485
- * @param callbacks - Callbacks for checking keystroke and paste activity
1486
- */
1487
- constructor(config = {}, callbacks) {
1488
- this.config = { ...DEFAULT_CONFIG, ...config };
1489
- this.keystrokeCallback = callbacks?.getRecentKeystrokes;
1490
- this.pasteCallback = callbacks?.hadRecentPaste;
1491
- this.startTime = performance.now();
1492
- }
1493
- /**
1494
- * Returns detection results with all recorded indicators.
1495
- *
1496
- * @returns Detection result with indicators of sudden text appearance
1497
- */
1498
- detect() {
1499
- const detected = this.indicators.length > 0;
1500
- const confidence = detected ? this.calculateConfidence() : 0;
1501
- return {
1502
- detected,
1503
- confidence,
1504
- message: detected ? `Detected ${this.indicators.length} instance(s) of sudden text appearance` : "No sudden text appearance detected",
1505
- indicators: [...this.indicators]
1506
- };
1507
- }
1508
- /**
1509
- * Starts monitoring an element for sudden text appearance.
1510
- *
1511
- * Watches for text changes in input/textarea elements and content changes
1512
- * in contenteditable elements via MutationObserver.
1513
- *
1514
- * @param element - The element to monitor
1515
- */
1516
- startMonitoring(element) {
1517
- if (this.observer) {
1518
- this.stopMonitoring();
1519
- }
1520
- this.monitoredElement = element;
1521
- this.startTime = performance.now();
1522
- this.initializeTextLengths(element);
1523
- this.inputHandler = this.handleInputEvent.bind(this);
1524
- element.addEventListener("input", this.inputHandler, true);
1525
- this.observer = new MutationObserver(this.handleMutations.bind(this));
1526
- this.observer.observe(element, {
1527
- characterData: true,
1528
- childList: true,
1529
- subtree: true,
1530
- characterDataOldValue: true
1531
- });
1532
- }
1533
- /**
1534
- * Stops monitoring and cleans up resources.
1535
- */
1536
- stopMonitoring() {
1537
- if (this.observer) {
1538
- this.observer.disconnect();
1539
- this.observer = null;
1540
- }
1541
- if (this.monitoredElement && this.inputHandler) {
1542
- this.monitoredElement.removeEventListener("input", this.inputHandler, true);
1543
- this.inputHandler = null;
1544
- }
1545
- this.monitoredElement = null;
1546
- this.lastTextLength.clear();
1547
- }
1548
- /**
1549
- * Resets the detector state.
1550
- *
1551
- * @param newStartTime - Optional new start time for timing calculations
1552
- */
1553
- reset(newStartTime) {
1554
- this.indicators = [];
1555
- this.lastTextLength.clear();
1556
- if (newStartTime !== void 0) {
1557
- this.startTime = newStartTime;
1558
- }
1559
- }
1560
- /**
1561
- * Returns the current list of indicators.
1562
- *
1563
- * @returns Copy of the indicators array
1564
- */
1565
- getIndicators() {
1566
- return [...this.indicators];
1567
- }
1568
- initializeTextLengths(element) {
1569
- const inputs = element.querySelectorAll("input, textarea");
1570
- for (const input of inputs) {
1571
- if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement) {
1572
- this.lastTextLength.set(input, input.value.length);
1573
- }
1574
- }
1575
- const editables = element.querySelectorAll("[contenteditable]");
1576
- for (const editable of editables) {
1577
- this.lastTextLength.set(editable, editable.textContent?.length ?? 0);
1578
- }
1579
- if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
1580
- this.lastTextLength.set(element, element.value.length);
1581
- } else if (element.isContentEditable) {
1582
- this.lastTextLength.set(element, element.textContent?.length ?? 0);
1583
- }
1584
- }
1585
- handleInputEvent(e) {
1586
- const target = e.target;
1587
- if (!target) {
1588
- return;
1589
- }
1590
- if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
1591
- this.checkTextChange(target, target.value.length);
1592
- }
1465
+ // src/collectors/response-controls.ts
1466
+ var EVENT_TYPES = [
1467
+ "keydown",
1468
+ "keyup",
1469
+ "focusin",
1470
+ "focusout",
1471
+ "input",
1472
+ "change",
1473
+ "click",
1474
+ "submit",
1475
+ "paste",
1476
+ "copy",
1477
+ "cut",
1478
+ "pointerdown",
1479
+ "pointerup",
1480
+ "pointermove"
1481
+ ];
1482
+ var NAVIGATION_KEYS = [
1483
+ "ArrowDown",
1484
+ "ArrowLeft",
1485
+ "ArrowRight",
1486
+ "ArrowUp",
1487
+ "Backspace",
1488
+ "Delete",
1489
+ "End",
1490
+ "Enter",
1491
+ "Escape",
1492
+ "Home",
1493
+ "PageDown",
1494
+ "PageUp",
1495
+ "Tab"
1496
+ ];
1497
+ function keyCategory(key) {
1498
+ return NAVIGATION_KEYS.find((candidate) => candidate === key) ?? "redacted";
1499
+ }
1500
+ function controlType(element) {
1501
+ if (element instanceof HTMLSelectElement) return "select";
1502
+ if (element instanceof HTMLButtonElement) return "button";
1503
+ if (element instanceof HTMLTextAreaElement) return "text";
1504
+ if (!(element instanceof HTMLInputElement)) return void 0;
1505
+ switch (element.type) {
1506
+ case "radio":
1507
+ case "checkbox":
1508
+ case "range":
1509
+ return element.type;
1510
+ case "button":
1511
+ case "submit":
1512
+ case "reset":
1513
+ return "button";
1514
+ case "text":
1515
+ case "search":
1516
+ case "number":
1517
+ return "text";
1518
+ default:
1519
+ return void 0;
1593
1520
  }
1594
- handleMutations(mutations) {
1595
- for (const mutation of mutations) {
1596
- if (mutation.type === "characterData" && mutation.target.parentElement) {
1597
- const parent = mutation.target.parentElement;
1598
- if (parent.isContentEditable) {
1599
- const newLength = parent.textContent?.length ?? 0;
1600
- this.checkTextChange(parent, newLength);
1601
- }
1602
- } else if (mutation.type === "childList") {
1603
- const target = mutation.target;
1604
- if (target instanceof HTMLElement && target.isContentEditable) {
1605
- const newLength = target.textContent?.length ?? 0;
1606
- this.checkTextChange(target, newLength);
1521
+ }
1522
+ function captureResponseControls(container, config, trialStart) {
1523
+ if (!config.hasConsent() || config.signal?.aborted) return null;
1524
+ const listeners = new AbortController();
1525
+ const events = [];
1526
+ let lastMove = -Infinity;
1527
+ const detach = () => listeners.abort();
1528
+ config.signal?.addEventListener("abort", detach, { once: true });
1529
+ for (const type of EVENT_TYPES) {
1530
+ container.addEventListener(
1531
+ type,
1532
+ (event) => {
1533
+ if (!config.hasConsent()) {
1534
+ detach();
1535
+ return;
1607
1536
  }
1608
- }
1609
- }
1610
- }
1611
- checkTextChange(element, newLength) {
1612
- const previousLength = this.lastTextLength.get(element) ?? 0;
1613
- const lengthChange = newLength - previousLength;
1614
- this.lastTextLength.set(element, newLength);
1615
- if (lengthChange < this.config.minTextLength) {
1616
- return;
1617
- }
1618
- const recentKeystrokes = this.keystrokeCallback?.() ?? 0;
1619
- const hadPaste = this.pasteCallback?.() ?? false;
1620
- if (recentKeystrokes < lengthChange && !hadPaste) {
1621
- const time = performance.now() - this.startTime;
1622
- const selector = this.getSelector(element);
1623
- this.indicators.push({
1624
- type: "sudden_text_appearance",
1625
- selector,
1626
- details: {
1627
- characterCount: lengthChange,
1628
- previousLength,
1629
- newLength,
1630
- recentKeystrokes,
1631
- hadPaste,
1632
- time
1537
+ const target = typeof SubmitEvent !== "undefined" && event instanceof SubmitEvent ? event.submitter : event.target;
1538
+ if (!(target instanceof Element)) return;
1539
+ const element = target.closest(config.targetSelector);
1540
+ if (!element || !container.contains(element)) return;
1541
+ const control = controlType(element);
1542
+ if (control === void 0) return;
1543
+ const time = performance.now() - trialStart;
1544
+ const record = {
1545
+ time,
1546
+ event: type,
1547
+ control,
1548
+ trusted: event.isTrusted
1549
+ };
1550
+ if (event instanceof KeyboardEvent) record.key = keyCategory(event.key);
1551
+ if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) {
1552
+ const bounds = element.getBoundingClientRect();
1553
+ const x = event.clientX - bounds.left;
1554
+ const y = event.clientY - bounds.top;
1555
+ if (x >= 0 && x <= bounds.width && y >= 0 && y <= bounds.height) {
1556
+ record.x = x;
1557
+ record.y = y;
1558
+ }
1559
+ if (type === "pointermove") {
1560
+ if (record.x === void 0 || time - lastMove < 16) return;
1561
+ lastMove = time;
1562
+ }
1633
1563
  }
1634
- });
1635
- }
1636
- }
1637
- getSelector(element) {
1638
- if (element.id) {
1639
- return `#${element.id}`;
1640
- }
1641
- if (element.className && typeof element.className === "string") {
1642
- const classes = element.className.trim().split(/\s+/).join(".");
1643
- if (classes) {
1644
- return `${element.tagName.toLowerCase()}.${classes}`;
1645
- }
1646
- }
1647
- return element.tagName.toLowerCase();
1564
+ events.push(record);
1565
+ },
1566
+ { capture: true, signal: listeners.signal }
1567
+ );
1648
1568
  }
1649
- calculateConfidence() {
1650
- if (this.indicators.length === 0) {
1651
- return 0;
1652
- }
1653
- const totalCharacters = this.indicators.reduce((sum, ind) => {
1654
- const count = ind.details?.["characterCount"] ?? 0;
1655
- return sum + count;
1656
- }, 0);
1657
- let confidence = 0.5;
1658
- if (totalCharacters > 100) {
1659
- confidence += 0.2;
1660
- }
1661
- if (totalCharacters > 500) {
1662
- confidence += 0.2;
1569
+ return {
1570
+ finish() {
1571
+ config.signal?.removeEventListener("abort", detach);
1572
+ const revoked = listeners.signal.aborted || !config.hasConsent();
1573
+ detach();
1574
+ return revoked ? null : { schemaVersion: "1.0", events };
1663
1575
  }
1664
- confidence += Math.min(0.1 * this.indicators.length, 0.1);
1665
- return Math.min(confidence, 1);
1666
- }
1667
- };
1576
+ };
1577
+ }
1668
1578
 
1669
1579
  // src/detection/extension.ts
1670
1580
  var KNOWN_DOM_SELECTORS = [
@@ -1923,31 +1833,485 @@ function createExtensionDetector(config) {
1923
1833
  return new ExtensionDetector(config);
1924
1834
  }
1925
1835
 
1926
- // src/intervention/intervention-manager.ts
1927
- var INTERVENTION_LEVELS = ["warning", "friction", "challenge", "block"];
1928
- var InterventionManager = class {
1929
- triggers;
1930
- escalate;
1931
- interventionHistory = [];
1932
- callbacks = /* @__PURE__ */ new Map();
1933
- triggerCounts = /* @__PURE__ */ new Map();
1836
+ // src/detection/text-appearance.ts
1837
+ var DEFAULT_CONFIG = {
1838
+ minTextLength: 50,
1839
+ timeWindowMs: 2e3
1840
+ };
1841
+ var TextAppearanceDetector = class {
1842
+ name = "text_appearance";
1843
+ observer = null;
1844
+ indicators = [];
1845
+ lastTextLength = /* @__PURE__ */ new Map();
1846
+ keystrokeCallback;
1847
+ pasteCallback;
1848
+ config;
1849
+ startTime;
1850
+ monitoredElement = null;
1851
+ inputHandler = null;
1934
1852
  /**
1935
- * Creates a new InterventionManager.
1853
+ * Creates a new TextAppearanceDetector.
1936
1854
  *
1937
- * @param config - Configuration with triggers and escalation settings
1855
+ * @param config - Configuration options
1856
+ * @param callbacks - Callbacks for checking keystroke and paste activity
1938
1857
  */
1939
- constructor(config) {
1940
- this.triggers = config.triggers;
1941
- this.escalate = config.escalate ?? false;
1942
- for (const type of INTERVENTION_LEVELS) {
1943
- this.callbacks.set(type, []);
1944
- }
1945
- for (const trigger of this.triggers) {
1946
- this.triggerCounts.set(trigger, 0);
1947
- }
1858
+ constructor(config = {}, callbacks) {
1859
+ this.config = { ...DEFAULT_CONFIG, ...config };
1860
+ this.keystrokeCallback = callbacks?.getRecentKeystrokes;
1861
+ this.pasteCallback = callbacks?.hadRecentPaste;
1862
+ this.startTime = performance.now();
1948
1863
  }
1949
1864
  /**
1950
- * Evaluates triggers against the current behavioral state.
1865
+ * Returns detection results with all recorded indicators.
1866
+ *
1867
+ * @returns Detection result with indicators of sudden text appearance
1868
+ */
1869
+ detect() {
1870
+ const detected = this.indicators.length > 0;
1871
+ const confidence = detected ? this.calculateConfidence() : 0;
1872
+ return {
1873
+ detected,
1874
+ confidence,
1875
+ message: detected ? `Detected ${this.indicators.length} instance(s) of sudden text appearance` : "No sudden text appearance detected",
1876
+ indicators: [...this.indicators]
1877
+ };
1878
+ }
1879
+ /**
1880
+ * Starts monitoring an element for sudden text appearance.
1881
+ *
1882
+ * Watches for text changes in input/textarea elements and content changes
1883
+ * in contenteditable elements via MutationObserver.
1884
+ *
1885
+ * @param element - The element to monitor
1886
+ */
1887
+ startMonitoring(element) {
1888
+ if (this.observer) {
1889
+ this.stopMonitoring();
1890
+ }
1891
+ this.monitoredElement = element;
1892
+ this.startTime = performance.now();
1893
+ this.initializeTextLengths(element);
1894
+ this.inputHandler = this.handleInputEvent.bind(this);
1895
+ element.addEventListener("input", this.inputHandler, true);
1896
+ this.observer = new MutationObserver(this.handleMutations.bind(this));
1897
+ this.observer.observe(element, {
1898
+ characterData: true,
1899
+ childList: true,
1900
+ subtree: true,
1901
+ characterDataOldValue: true
1902
+ });
1903
+ }
1904
+ /**
1905
+ * Stops monitoring and cleans up resources.
1906
+ */
1907
+ stopMonitoring() {
1908
+ if (this.observer) {
1909
+ this.observer.disconnect();
1910
+ this.observer = null;
1911
+ }
1912
+ if (this.monitoredElement && this.inputHandler) {
1913
+ this.monitoredElement.removeEventListener("input", this.inputHandler, true);
1914
+ this.inputHandler = null;
1915
+ }
1916
+ this.monitoredElement = null;
1917
+ this.lastTextLength.clear();
1918
+ }
1919
+ /**
1920
+ * Resets the detector state.
1921
+ *
1922
+ * @param newStartTime - Optional new start time for timing calculations
1923
+ */
1924
+ reset(newStartTime) {
1925
+ this.indicators = [];
1926
+ this.lastTextLength.clear();
1927
+ if (newStartTime !== void 0) {
1928
+ this.startTime = newStartTime;
1929
+ }
1930
+ }
1931
+ /**
1932
+ * Returns the current list of indicators.
1933
+ *
1934
+ * @returns Copy of the indicators array
1935
+ */
1936
+ getIndicators() {
1937
+ return [...this.indicators];
1938
+ }
1939
+ initializeTextLengths(element) {
1940
+ const inputs = element.querySelectorAll("input, textarea");
1941
+ for (const input of inputs) {
1942
+ if (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement) {
1943
+ this.lastTextLength.set(input, input.value.length);
1944
+ }
1945
+ }
1946
+ const editables = element.querySelectorAll("[contenteditable]");
1947
+ for (const editable of editables) {
1948
+ this.lastTextLength.set(editable, editable.textContent?.length ?? 0);
1949
+ }
1950
+ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
1951
+ this.lastTextLength.set(element, element.value.length);
1952
+ } else if (element.isContentEditable) {
1953
+ this.lastTextLength.set(element, element.textContent?.length ?? 0);
1954
+ }
1955
+ }
1956
+ handleInputEvent(e) {
1957
+ const target = e.target;
1958
+ if (!target) {
1959
+ return;
1960
+ }
1961
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
1962
+ this.checkTextChange(target, target.value.length);
1963
+ }
1964
+ }
1965
+ handleMutations(mutations) {
1966
+ for (const mutation of mutations) {
1967
+ if (mutation.type === "characterData" && mutation.target.parentElement) {
1968
+ const parent = mutation.target.parentElement;
1969
+ if (parent.isContentEditable) {
1970
+ const newLength = parent.textContent?.length ?? 0;
1971
+ this.checkTextChange(parent, newLength);
1972
+ }
1973
+ } else if (mutation.type === "childList") {
1974
+ const target = mutation.target;
1975
+ if (target instanceof HTMLElement && target.isContentEditable) {
1976
+ const newLength = target.textContent?.length ?? 0;
1977
+ this.checkTextChange(target, newLength);
1978
+ }
1979
+ }
1980
+ }
1981
+ }
1982
+ checkTextChange(element, newLength) {
1983
+ const previousLength = this.lastTextLength.get(element) ?? 0;
1984
+ const lengthChange = newLength - previousLength;
1985
+ this.lastTextLength.set(element, newLength);
1986
+ if (lengthChange < this.config.minTextLength) {
1987
+ return;
1988
+ }
1989
+ const recentKeystrokes = this.keystrokeCallback?.() ?? 0;
1990
+ const hadPaste = this.pasteCallback?.() ?? false;
1991
+ if (recentKeystrokes < lengthChange && !hadPaste) {
1992
+ const time = performance.now() - this.startTime;
1993
+ const selector = this.getSelector(element);
1994
+ this.indicators.push({
1995
+ type: "sudden_text_appearance",
1996
+ selector,
1997
+ details: {
1998
+ characterCount: lengthChange,
1999
+ previousLength,
2000
+ newLength,
2001
+ recentKeystrokes,
2002
+ hadPaste,
2003
+ time
2004
+ }
2005
+ });
2006
+ }
2007
+ }
2008
+ getSelector(element) {
2009
+ if (element.id) {
2010
+ return `#${element.id}`;
2011
+ }
2012
+ if (element.className && typeof element.className === "string") {
2013
+ const classes = element.className.trim().split(/\s+/).join(".");
2014
+ if (classes) {
2015
+ return `${element.tagName.toLowerCase()}.${classes}`;
2016
+ }
2017
+ }
2018
+ return element.tagName.toLowerCase();
2019
+ }
2020
+ calculateConfidence() {
2021
+ if (this.indicators.length === 0) {
2022
+ return 0;
2023
+ }
2024
+ const totalCharacters = this.indicators.reduce((sum, ind) => {
2025
+ const count = ind.details?.["characterCount"] ?? 0;
2026
+ return sum + count;
2027
+ }, 0);
2028
+ let confidence = 0.5;
2029
+ if (totalCharacters > 100) {
2030
+ confidence += 0.2;
2031
+ }
2032
+ if (totalCharacters > 500) {
2033
+ confidence += 0.2;
2034
+ }
2035
+ confidence += Math.min(0.1 * this.indicators.length, 0.1);
2036
+ return Math.min(confidence, 1);
2037
+ }
2038
+ };
2039
+
2040
+ // src/intervention/challenges.ts
2041
+ var TypingTestChallenge = class {
2042
+ container = null;
2043
+ startTime = 0;
2044
+ keystrokes = [];
2045
+ boundHandlers = { keydown: null, keyup: null };
2046
+ /**
2047
+ * Render the typing test challenge.
2048
+ *
2049
+ * @param config - Challenge configuration with `data.text` containing the text to type
2050
+ * @param container - Container element for the challenge UI
2051
+ * @returns Promise resolving to challenge result with typing accuracy and keystroke data
2052
+ */
2053
+ async render(config, container) {
2054
+ this.container = container;
2055
+ this.keystrokes = [];
2056
+ const targetText = config.data?.["text"] ?? "";
2057
+ return new Promise((resolve) => {
2058
+ const wrapper = document.createElement("div");
2059
+ wrapper.className = "slopit-typing-challenge";
2060
+ const promptEl = document.createElement("p");
2061
+ promptEl.className = "slopit-challenge-prompt";
2062
+ promptEl.textContent = config.prompt;
2063
+ wrapper.appendChild(promptEl);
2064
+ const targetEl = document.createElement("div");
2065
+ targetEl.className = "slopit-typing-target";
2066
+ targetEl.textContent = targetText;
2067
+ wrapper.appendChild(targetEl);
2068
+ const inputEl = document.createElement("textarea");
2069
+ inputEl.className = "slopit-typing-input";
2070
+ inputEl.placeholder = "Type the text above...";
2071
+ inputEl.rows = 3;
2072
+ wrapper.appendChild(inputEl);
2073
+ const submitBtn = document.createElement("button");
2074
+ submitBtn.className = "slopit-challenge-submit";
2075
+ submitBtn.textContent = "Submit";
2076
+ submitBtn.type = "button";
2077
+ wrapper.appendChild(submitBtn);
2078
+ container.appendChild(wrapper);
2079
+ this.startTime = performance.now();
2080
+ this.boundHandlers.keydown = (e) => {
2081
+ this.keystrokes.push({
2082
+ key: e.key,
2083
+ time: performance.now() - this.startTime,
2084
+ event: "keydown"
2085
+ });
2086
+ };
2087
+ this.boundHandlers.keyup = (e) => {
2088
+ this.keystrokes.push({
2089
+ key: e.key,
2090
+ time: performance.now() - this.startTime,
2091
+ event: "keyup"
2092
+ });
2093
+ };
2094
+ inputEl.addEventListener("keydown", this.boundHandlers.keydown);
2095
+ inputEl.addEventListener("keyup", this.boundHandlers.keyup);
2096
+ const submit = () => {
2097
+ const completionTime = performance.now() - this.startTime;
2098
+ const response = inputEl.value;
2099
+ const accuracy = this.calculateAccuracy(targetText, response);
2100
+ const passed = accuracy >= 0.9;
2101
+ resolve({
2102
+ passed,
2103
+ response,
2104
+ completionTime,
2105
+ behavioralData: {
2106
+ keystrokes: [...this.keystrokes],
2107
+ targetText,
2108
+ accuracy
2109
+ }
2110
+ });
2111
+ };
2112
+ submitBtn.addEventListener("click", submit);
2113
+ if (config.timeLimit !== void 0) {
2114
+ setTimeout(() => {
2115
+ submit();
2116
+ }, config.timeLimit);
2117
+ }
2118
+ inputEl.focus();
2119
+ });
2120
+ }
2121
+ /**
2122
+ * Clean up challenge UI and event listeners.
2123
+ */
2124
+ cleanup() {
2125
+ if (this.container) {
2126
+ const wrapper = this.container.querySelector(".slopit-typing-challenge");
2127
+ if (wrapper) {
2128
+ const input = wrapper.querySelector(".slopit-typing-input");
2129
+ if (input && this.boundHandlers.keydown) {
2130
+ input.removeEventListener("keydown", this.boundHandlers.keydown);
2131
+ }
2132
+ if (input && this.boundHandlers.keyup) {
2133
+ input.removeEventListener("keyup", this.boundHandlers.keyup);
2134
+ }
2135
+ wrapper.remove();
2136
+ }
2137
+ this.container = null;
2138
+ }
2139
+ this.boundHandlers = { keydown: null, keyup: null };
2140
+ this.keystrokes = [];
2141
+ }
2142
+ /**
2143
+ * Calculate typing accuracy as a ratio (0-1).
2144
+ * Uses a simple character-by-character comparison with length normalization.
2145
+ */
2146
+ calculateAccuracy(target, actual) {
2147
+ if (target.length === 0) {
2148
+ return actual.length === 0 ? 1 : 0;
2149
+ }
2150
+ const maxLen = Math.max(target.length, actual.length);
2151
+ let matches = 0;
2152
+ for (let i = 0; i < Math.min(target.length, actual.length); i++) {
2153
+ if (target[i] === actual[i]) {
2154
+ matches++;
2155
+ }
2156
+ }
2157
+ return matches / maxLen;
2158
+ }
2159
+ };
2160
+ var MemoryRecallChallenge = class {
2161
+ container = null;
2162
+ startTime = 0;
2163
+ keystrokes = [];
2164
+ boundHandlers = { keydown: null, keyup: null };
2165
+ /**
2166
+ * Render the memory recall challenge.
2167
+ *
2168
+ * @param config - Challenge configuration with optional `expectedKeywords`
2169
+ * @param container - Container element for the challenge UI
2170
+ * @returns Promise resolving to challenge result with keyword matching status
2171
+ */
2172
+ async render(config, container) {
2173
+ this.container = container;
2174
+ this.keystrokes = [];
2175
+ return new Promise((resolve) => {
2176
+ const wrapper = document.createElement("div");
2177
+ wrapper.className = "slopit-memory-challenge";
2178
+ const promptEl = document.createElement("p");
2179
+ promptEl.className = "slopit-challenge-prompt";
2180
+ promptEl.textContent = config.prompt;
2181
+ wrapper.appendChild(promptEl);
2182
+ const inputEl = document.createElement("textarea");
2183
+ inputEl.className = "slopit-memory-input";
2184
+ inputEl.placeholder = "Type your answer...";
2185
+ inputEl.rows = 3;
2186
+ wrapper.appendChild(inputEl);
2187
+ const submitBtn = document.createElement("button");
2188
+ submitBtn.className = "slopit-challenge-submit";
2189
+ submitBtn.textContent = "Submit";
2190
+ submitBtn.type = "button";
2191
+ wrapper.appendChild(submitBtn);
2192
+ container.appendChild(wrapper);
2193
+ this.startTime = performance.now();
2194
+ this.boundHandlers.keydown = (e) => {
2195
+ this.keystrokes.push({
2196
+ key: e.key,
2197
+ time: performance.now() - this.startTime,
2198
+ event: "keydown"
2199
+ });
2200
+ };
2201
+ this.boundHandlers.keyup = (e) => {
2202
+ this.keystrokes.push({
2203
+ key: e.key,
2204
+ time: performance.now() - this.startTime,
2205
+ event: "keyup"
2206
+ });
2207
+ };
2208
+ inputEl.addEventListener("keydown", this.boundHandlers.keydown);
2209
+ inputEl.addEventListener("keyup", this.boundHandlers.keyup);
2210
+ const submit = () => {
2211
+ const completionTime = performance.now() - this.startTime;
2212
+ const response = inputEl.value;
2213
+ const passed = this.checkKeywords(response, config.expectedKeywords ?? []);
2214
+ resolve({
2215
+ passed,
2216
+ response,
2217
+ completionTime,
2218
+ behavioralData: {
2219
+ keystrokes: [...this.keystrokes],
2220
+ expectedKeywords: config.expectedKeywords,
2221
+ matchedKeywords: this.getMatchedKeywords(response, config.expectedKeywords ?? [])
2222
+ }
2223
+ });
2224
+ };
2225
+ submitBtn.addEventListener("click", submit);
2226
+ if (config.timeLimit !== void 0) {
2227
+ setTimeout(() => {
2228
+ submit();
2229
+ }, config.timeLimit);
2230
+ }
2231
+ inputEl.focus();
2232
+ });
2233
+ }
2234
+ /**
2235
+ * Clean up challenge UI and event listeners.
2236
+ */
2237
+ cleanup() {
2238
+ if (this.container) {
2239
+ const wrapper = this.container.querySelector(".slopit-memory-challenge");
2240
+ if (wrapper) {
2241
+ const input = wrapper.querySelector(".slopit-memory-input");
2242
+ if (input && this.boundHandlers.keydown) {
2243
+ input.removeEventListener("keydown", this.boundHandlers.keydown);
2244
+ }
2245
+ if (input && this.boundHandlers.keyup) {
2246
+ input.removeEventListener("keyup", this.boundHandlers.keyup);
2247
+ }
2248
+ wrapper.remove();
2249
+ }
2250
+ this.container = null;
2251
+ }
2252
+ this.boundHandlers = { keydown: null, keyup: null };
2253
+ this.keystrokes = [];
2254
+ }
2255
+ /**
2256
+ * Check if response contains all expected keywords.
2257
+ */
2258
+ checkKeywords(response, keywords) {
2259
+ if (keywords.length === 0) {
2260
+ return true;
2261
+ }
2262
+ const lowerResponse = response.toLowerCase();
2263
+ return keywords.every((keyword) => lowerResponse.includes(keyword.toLowerCase()));
2264
+ }
2265
+ /**
2266
+ * Get list of keywords that were matched in the response.
2267
+ */
2268
+ getMatchedKeywords(response, keywords) {
2269
+ const lowerResponse = response.toLowerCase();
2270
+ return keywords.filter((keyword) => lowerResponse.includes(keyword.toLowerCase()));
2271
+ }
2272
+ };
2273
+ function createChallenge(type) {
2274
+ switch (type) {
2275
+ case "typing_test":
2276
+ return new TypingTestChallenge();
2277
+ case "memory_recall":
2278
+ return new MemoryRecallChallenge();
2279
+ case "audio_transcription":
2280
+ case "image_description":
2281
+ case "consistency_check":
2282
+ return null;
2283
+ default: {
2284
+ const _exhaustive = type;
2285
+ return _exhaustive;
2286
+ }
2287
+ }
2288
+ }
2289
+
2290
+ // src/intervention/intervention-manager.ts
2291
+ var INTERVENTION_LEVELS = ["warning", "friction", "challenge", "block"];
2292
+ var InterventionManager = class {
2293
+ triggers;
2294
+ escalate;
2295
+ interventionHistory = [];
2296
+ callbacks = /* @__PURE__ */ new Map();
2297
+ triggerCounts = /* @__PURE__ */ new Map();
2298
+ /**
2299
+ * Creates a new InterventionManager.
2300
+ *
2301
+ * @param config - Configuration with triggers and escalation settings
2302
+ */
2303
+ constructor(config) {
2304
+ this.triggers = config.triggers;
2305
+ this.escalate = config.escalate ?? false;
2306
+ for (const type of INTERVENTION_LEVELS) {
2307
+ this.callbacks.set(type, []);
2308
+ }
2309
+ for (const trigger of this.triggers) {
2310
+ this.triggerCounts.set(trigger, 0);
2311
+ }
2312
+ }
2313
+ /**
2314
+ * Evaluates triggers against the current behavioral state.
1951
2315
  *
1952
2316
  * Checks each configured trigger against the provided state and returns
1953
2317
  * an InterventionResult if any trigger fires. Only the first matching
@@ -2222,256 +2586,6 @@ function createInterventionManager(config) {
2222
2586
  return new InterventionManager(config);
2223
2587
  }
2224
2588
 
2225
- // src/intervention/challenges.ts
2226
- var TypingTestChallenge = class {
2227
- container = null;
2228
- startTime = 0;
2229
- keystrokes = [];
2230
- boundHandlers = { keydown: null, keyup: null };
2231
- /**
2232
- * Render the typing test challenge.
2233
- *
2234
- * @param config - Challenge configuration with `data.text` containing the text to type
2235
- * @param container - Container element for the challenge UI
2236
- * @returns Promise resolving to challenge result with typing accuracy and keystroke data
2237
- */
2238
- async render(config, container) {
2239
- this.container = container;
2240
- this.keystrokes = [];
2241
- const targetText = config.data?.["text"] ?? "";
2242
- return new Promise((resolve) => {
2243
- const wrapper = document.createElement("div");
2244
- wrapper.className = "slopit-typing-challenge";
2245
- const promptEl = document.createElement("p");
2246
- promptEl.className = "slopit-challenge-prompt";
2247
- promptEl.textContent = config.prompt;
2248
- wrapper.appendChild(promptEl);
2249
- const targetEl = document.createElement("div");
2250
- targetEl.className = "slopit-typing-target";
2251
- targetEl.textContent = targetText;
2252
- wrapper.appendChild(targetEl);
2253
- const inputEl = document.createElement("textarea");
2254
- inputEl.className = "slopit-typing-input";
2255
- inputEl.placeholder = "Type the text above...";
2256
- inputEl.rows = 3;
2257
- wrapper.appendChild(inputEl);
2258
- const submitBtn = document.createElement("button");
2259
- submitBtn.className = "slopit-challenge-submit";
2260
- submitBtn.textContent = "Submit";
2261
- submitBtn.type = "button";
2262
- wrapper.appendChild(submitBtn);
2263
- container.appendChild(wrapper);
2264
- this.startTime = performance.now();
2265
- this.boundHandlers.keydown = (e) => {
2266
- this.keystrokes.push({
2267
- key: e.key,
2268
- time: performance.now() - this.startTime,
2269
- event: "keydown"
2270
- });
2271
- };
2272
- this.boundHandlers.keyup = (e) => {
2273
- this.keystrokes.push({
2274
- key: e.key,
2275
- time: performance.now() - this.startTime,
2276
- event: "keyup"
2277
- });
2278
- };
2279
- inputEl.addEventListener("keydown", this.boundHandlers.keydown);
2280
- inputEl.addEventListener("keyup", this.boundHandlers.keyup);
2281
- const submit = () => {
2282
- const completionTime = performance.now() - this.startTime;
2283
- const response = inputEl.value;
2284
- const accuracy = this.calculateAccuracy(targetText, response);
2285
- const passed = accuracy >= 0.9;
2286
- resolve({
2287
- passed,
2288
- response,
2289
- completionTime,
2290
- behavioralData: {
2291
- keystrokes: [...this.keystrokes],
2292
- targetText,
2293
- accuracy
2294
- }
2295
- });
2296
- };
2297
- submitBtn.addEventListener("click", submit);
2298
- if (config.timeLimit !== void 0) {
2299
- setTimeout(() => {
2300
- submit();
2301
- }, config.timeLimit);
2302
- }
2303
- inputEl.focus();
2304
- });
2305
- }
2306
- /**
2307
- * Clean up challenge UI and event listeners.
2308
- */
2309
- cleanup() {
2310
- if (this.container) {
2311
- const wrapper = this.container.querySelector(".slopit-typing-challenge");
2312
- if (wrapper) {
2313
- const input = wrapper.querySelector(".slopit-typing-input");
2314
- if (input && this.boundHandlers.keydown) {
2315
- input.removeEventListener("keydown", this.boundHandlers.keydown);
2316
- }
2317
- if (input && this.boundHandlers.keyup) {
2318
- input.removeEventListener("keyup", this.boundHandlers.keyup);
2319
- }
2320
- wrapper.remove();
2321
- }
2322
- this.container = null;
2323
- }
2324
- this.boundHandlers = { keydown: null, keyup: null };
2325
- this.keystrokes = [];
2326
- }
2327
- /**
2328
- * Calculate typing accuracy as a ratio (0-1).
2329
- * Uses a simple character-by-character comparison with length normalization.
2330
- */
2331
- calculateAccuracy(target, actual) {
2332
- if (target.length === 0) {
2333
- return actual.length === 0 ? 1 : 0;
2334
- }
2335
- const maxLen = Math.max(target.length, actual.length);
2336
- let matches = 0;
2337
- for (let i = 0; i < Math.min(target.length, actual.length); i++) {
2338
- if (target[i] === actual[i]) {
2339
- matches++;
2340
- }
2341
- }
2342
- return matches / maxLen;
2343
- }
2344
- };
2345
- var MemoryRecallChallenge = class {
2346
- container = null;
2347
- startTime = 0;
2348
- keystrokes = [];
2349
- boundHandlers = { keydown: null, keyup: null };
2350
- /**
2351
- * Render the memory recall challenge.
2352
- *
2353
- * @param config - Challenge configuration with optional `expectedKeywords`
2354
- * @param container - Container element for the challenge UI
2355
- * @returns Promise resolving to challenge result with keyword matching status
2356
- */
2357
- async render(config, container) {
2358
- this.container = container;
2359
- this.keystrokes = [];
2360
- return new Promise((resolve) => {
2361
- const wrapper = document.createElement("div");
2362
- wrapper.className = "slopit-memory-challenge";
2363
- const promptEl = document.createElement("p");
2364
- promptEl.className = "slopit-challenge-prompt";
2365
- promptEl.textContent = config.prompt;
2366
- wrapper.appendChild(promptEl);
2367
- const inputEl = document.createElement("textarea");
2368
- inputEl.className = "slopit-memory-input";
2369
- inputEl.placeholder = "Type your answer...";
2370
- inputEl.rows = 3;
2371
- wrapper.appendChild(inputEl);
2372
- const submitBtn = document.createElement("button");
2373
- submitBtn.className = "slopit-challenge-submit";
2374
- submitBtn.textContent = "Submit";
2375
- submitBtn.type = "button";
2376
- wrapper.appendChild(submitBtn);
2377
- container.appendChild(wrapper);
2378
- this.startTime = performance.now();
2379
- this.boundHandlers.keydown = (e) => {
2380
- this.keystrokes.push({
2381
- key: e.key,
2382
- time: performance.now() - this.startTime,
2383
- event: "keydown"
2384
- });
2385
- };
2386
- this.boundHandlers.keyup = (e) => {
2387
- this.keystrokes.push({
2388
- key: e.key,
2389
- time: performance.now() - this.startTime,
2390
- event: "keyup"
2391
- });
2392
- };
2393
- inputEl.addEventListener("keydown", this.boundHandlers.keydown);
2394
- inputEl.addEventListener("keyup", this.boundHandlers.keyup);
2395
- const submit = () => {
2396
- const completionTime = performance.now() - this.startTime;
2397
- const response = inputEl.value;
2398
- const passed = this.checkKeywords(response, config.expectedKeywords ?? []);
2399
- resolve({
2400
- passed,
2401
- response,
2402
- completionTime,
2403
- behavioralData: {
2404
- keystrokes: [...this.keystrokes],
2405
- expectedKeywords: config.expectedKeywords,
2406
- matchedKeywords: this.getMatchedKeywords(response, config.expectedKeywords ?? [])
2407
- }
2408
- });
2409
- };
2410
- submitBtn.addEventListener("click", submit);
2411
- if (config.timeLimit !== void 0) {
2412
- setTimeout(() => {
2413
- submit();
2414
- }, config.timeLimit);
2415
- }
2416
- inputEl.focus();
2417
- });
2418
- }
2419
- /**
2420
- * Clean up challenge UI and event listeners.
2421
- */
2422
- cleanup() {
2423
- if (this.container) {
2424
- const wrapper = this.container.querySelector(".slopit-memory-challenge");
2425
- if (wrapper) {
2426
- const input = wrapper.querySelector(".slopit-memory-input");
2427
- if (input && this.boundHandlers.keydown) {
2428
- input.removeEventListener("keydown", this.boundHandlers.keydown);
2429
- }
2430
- if (input && this.boundHandlers.keyup) {
2431
- input.removeEventListener("keyup", this.boundHandlers.keyup);
2432
- }
2433
- wrapper.remove();
2434
- }
2435
- this.container = null;
2436
- }
2437
- this.boundHandlers = { keydown: null, keyup: null };
2438
- this.keystrokes = [];
2439
- }
2440
- /**
2441
- * Check if response contains all expected keywords.
2442
- */
2443
- checkKeywords(response, keywords) {
2444
- if (keywords.length === 0) {
2445
- return true;
2446
- }
2447
- const lowerResponse = response.toLowerCase();
2448
- return keywords.every((keyword) => lowerResponse.includes(keyword.toLowerCase()));
2449
- }
2450
- /**
2451
- * Get list of keywords that were matched in the response.
2452
- */
2453
- getMatchedKeywords(response, keywords) {
2454
- const lowerResponse = response.toLowerCase();
2455
- return keywords.filter((keyword) => lowerResponse.includes(keyword.toLowerCase()));
2456
- }
2457
- };
2458
- function createChallenge(type) {
2459
- switch (type) {
2460
- case "typing_test":
2461
- return new TypingTestChallenge();
2462
- case "memory_recall":
2463
- return new MemoryRecallChallenge();
2464
- case "audio_transcription":
2465
- case "image_description":
2466
- case "consistency_check":
2467
- return null;
2468
- default: {
2469
- const _exhaustive = type;
2470
- return _exhaustive;
2471
- }
2472
- }
2473
- }
2474
-
2475
2589
  // src/wrappers/input-wrapper.ts
2476
2590
  var InputWrapper = class {
2477
2591
  element = null;
@@ -2743,6 +2857,6 @@ function createInputWrapper(config) {
2743
2857
  return new InputWrapper(config);
2744
2858
  }
2745
2859
 
2746
- export { BehavioralCapture, ClipboardCollector, ExtensionDetector, FocusCollector, InputWrapper, InterventionManager, KeystrokeCollector, MemoryRecallChallenge, PasteCollector, TextAppearanceDetector, TypingTestChallenge, computeFocusMetrics, computeKeystrokeMetrics, computeTimingMetrics, createBehavioralCapture, createChallenge, createExtensionDetector, createInputWrapper, createInterventionManager };
2860
+ export { BehavioralCapture, ClipboardCollector, ExtensionDetector, FocusCollector, InputWrapper, InterventionManager, KeystrokeCollector, MemoryRecallChallenge, PasteCollector, TextAppearanceDetector, TypingTestChallenge, captureResponseControls, computeFocusMetrics, computeKeystrokeMetrics, computeTimingMetrics, createBehavioralCapture, createChallenge, createExtensionDetector, createInputWrapper, createInterventionManager };
2747
2861
  //# sourceMappingURL=index.js.map
2748
2862
  //# sourceMappingURL=index.js.map