@mintplex-labs/advanced-selection-hook 1.0.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/index.js ADDED
@@ -0,0 +1,611 @@
1
+ /**
2
+ * Node Selection Hook
3
+ *
4
+ * This module provides a Node.js interface for monitoring text selections
5
+ * across applications on Windows and macOS using UI Automation and Accessibility APIs.
6
+ *
7
+ * Copyright (c) 2025 0xfullex (https://github.com/0xfullex/selection-hook)
8
+ * Licensed under the MIT License
9
+ */
10
+
11
+ const EventEmitter = require("events");
12
+ const gypBuild = require("node-gyp-build");
13
+ const path = require("path");
14
+
15
+ const isWindows = process.platform === "win32";
16
+ const isMac = process.platform === "darwin";
17
+
18
+ let nativeModule = null;
19
+ // Make debugFlag a private module variable to avoid global state issues
20
+ let _debugFlag = false;
21
+
22
+ try {
23
+ if (!isWindows && !isMac) {
24
+ throw new Error(
25
+ "[selection-hook] Only supports Windows and macOS platforms",
26
+ );
27
+ }
28
+ nativeModule = gypBuild(path.resolve(__dirname));
29
+ } catch (err) {
30
+ console.error("[selection-hook] Failed to load native module:", err.message);
31
+ }
32
+
33
+ class SelectionHook extends EventEmitter {
34
+ #instance = null;
35
+ #running = false;
36
+
37
+ static SelectionMethod = {
38
+ NONE: 0,
39
+ UIA: 1,
40
+ /** @deprecated This method has been removed */
41
+ FOCUSCTL: 2,
42
+ ACCESSIBLE: 3,
43
+ AXAPI: 11,
44
+ CLIPBOARD: 99,
45
+ };
46
+
47
+ static PositionLevel = {
48
+ NONE: 0,
49
+ MOUSE_SINGLE: 1,
50
+ MOUSE_DUAL: 2,
51
+ SEL_FULL: 3,
52
+ SEL_DETAILED: 4,
53
+ };
54
+
55
+ static FilterMode = {
56
+ DEFAULT: 0,
57
+ INCLUDE_LIST: 1,
58
+ EXCLUDE_LIST: 2,
59
+ };
60
+
61
+ static FineTunedListType = {
62
+ EXCLUDE_CLIPBOARD_CURSOR_DETECT: 0,
63
+ INCLUDE_CLIPBOARD_DELAY_READ: 1,
64
+ };
65
+
66
+ constructor() {
67
+ if (!nativeModule) {
68
+ throw new Error(
69
+ "[selection-hook] Native module failed to load - only works on Windows and macOS",
70
+ );
71
+ }
72
+ super();
73
+ }
74
+
75
+ /**
76
+ * Start monitoring text selections
77
+ * @param {boolean} debug Enable debug logging
78
+ * @returns {boolean} Success status
79
+ */
80
+ start(config = null) {
81
+ const defaultConfig = this.#getDefaultConfig();
82
+
83
+ _debugFlag = config?.debug ?? defaultConfig.debug;
84
+
85
+ if (this.#running) {
86
+ this.#logDebug("Text selection hook already running");
87
+ return true;
88
+ }
89
+
90
+ if (!this.#instance) {
91
+ try {
92
+ this.#instance = new nativeModule.TextSelectionHook();
93
+ } catch (err) {
94
+ this.#handleError("Failed to create hook instance", err);
95
+ return false;
96
+ }
97
+ }
98
+
99
+ if (config) {
100
+ this.#initByConfig(defaultConfig, config);
101
+ }
102
+
103
+ try {
104
+ const callback = (data) => {
105
+ try {
106
+ if (!data || !data.type || !this.#running) return;
107
+
108
+ switch (data.type) {
109
+ case "text-selection":
110
+ const formattedData = this.#formatSelectionData(data);
111
+ if (formattedData) {
112
+ this.emit("text-selection", formattedData);
113
+ }
114
+ break;
115
+ case "mouse-event":
116
+ this.emit(data.action, data);
117
+ break;
118
+ case "keyboard-event":
119
+ this.emit(data.action, data);
120
+ break;
121
+ case "status":
122
+ this.emit("status", data.status);
123
+ break;
124
+ case "error":
125
+ this.emit("error", new Error(data.error));
126
+ break;
127
+ }
128
+ } catch (err) {
129
+ this.#handleError("Failed to process event data", err);
130
+ }
131
+ };
132
+
133
+ this.#instance.start(callback);
134
+ this.#running = true;
135
+ this.emit("status", "started");
136
+ return true;
137
+ } catch (err) {
138
+ this.#handleError("Failed to start hook", err, "fatal");
139
+ return false;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Stop monitoring text selections, can start again using start()
145
+ * @returns {boolean} Success status
146
+ */
147
+ stop() {
148
+ if (!this.#instance || !this.#running) {
149
+ this.#logDebug("Text selection hook not running");
150
+ return true;
151
+ }
152
+
153
+ try {
154
+ this.#instance.stop();
155
+ this.#running = false;
156
+ this.emit("status", "stopped");
157
+ return true;
158
+ } catch (err) {
159
+ this.#handleError("Failed to stop hook", err, "fatal");
160
+ this.#running = false;
161
+ return false;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Get current text selection
167
+ * @returns {object|null} Selection data or null
168
+ */
169
+ getCurrentSelection() {
170
+ if (!this.#instance || !this.#running) {
171
+ this.#logDebug("Text selection hook not running");
172
+ return null;
173
+ }
174
+
175
+ try {
176
+ const data = this.#instance.getCurrentSelection();
177
+ return this.#formatSelectionData(data);
178
+ } catch (err) {
179
+ this.#handleError("Failed to get current selection", err);
180
+ return null;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Enable mousemove events (high CPU usage)
186
+ * @returns {boolean} Success status
187
+ */
188
+ enableMouseMoveEvent() {
189
+ if (!this.#checkRunning()) return false;
190
+
191
+ try {
192
+ this.#instance.enableMouseMoveEvent();
193
+ return true;
194
+ } catch (err) {
195
+ this.#handleError("Failed to enable mouse move events", err);
196
+ return false;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Disable mousemove events
202
+ * @returns {boolean} Success status
203
+ */
204
+ disableMouseMoveEvent() {
205
+ if (!this.#checkRunning()) return false;
206
+
207
+ try {
208
+ this.#instance.disableMouseMoveEvent();
209
+ return true;
210
+ } catch (err) {
211
+ this.#handleError("Failed to disable mouse move events", err);
212
+ return false;
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Enable clipboard fallback for text selection
218
+ * Uses Ctrl+C as a last resort to get selected text
219
+ * @returns {boolean} Success status
220
+ */
221
+ enableClipboard() {
222
+ if (!this.#checkRunning()) return false;
223
+
224
+ try {
225
+ this.#instance.enableClipboard();
226
+ return true;
227
+ } catch (err) {
228
+ this.#handleError("Failed to enable clipboard fallback", err);
229
+ return false;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Disable clipboard fallback for text selection
235
+ * Will not use Ctrl+C to get selected text
236
+ * @returns {boolean} Success status
237
+ */
238
+ disableClipboard() {
239
+ if (!this.#checkRunning()) return false;
240
+
241
+ try {
242
+ this.#instance.disableClipboard();
243
+ return true;
244
+ } catch (err) {
245
+ this.#handleError("Failed to disable clipboard fallback", err);
246
+ return false;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Set clipboard mode and program list for text selection
252
+ *
253
+ * Configures how the clipboard fallback mechanism works for different programs.
254
+ * Mode can be:
255
+ * - DEFAULT: Use clipboard for all programs
256
+ * - INCLUDE_LIST: Only use clipboard for programs in the list
257
+ * - EXCLUDE_LIST: Use clipboard for all programs except those in the list
258
+ *
259
+ * @param {number} mode - Clipboard mode (SelectionHook.ClipboardMode)
260
+ * @param {string[]} programList - Array of program names to include/exclude.
261
+ * @returns {boolean} Success status
262
+ */
263
+ setClipboardMode(mode, programList = []) {
264
+ if (!this.#checkRunning()) return false;
265
+
266
+ const validModes = Object.values(SelectionHook.FilterMode);
267
+ if (!validModes.includes(mode)) {
268
+ this.#handleError(
269
+ "Invalid clipboard mode",
270
+ new Error("Invalid argument"),
271
+ );
272
+ return false;
273
+ }
274
+
275
+ if (!Array.isArray(programList)) {
276
+ this.#handleError(
277
+ "Program list must be an array",
278
+ new Error("Invalid argument"),
279
+ );
280
+ return false;
281
+ }
282
+
283
+ try {
284
+ this.#instance.setClipboardMode(mode, programList);
285
+ return true;
286
+ } catch (err) {
287
+ this.#handleError("Failed to set clipboard mode and list", err);
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Set global filter mode for text selection
294
+ *
295
+ * Configures how the global filter mechanism works for different programs.
296
+ * Mode can be:
297
+ * - DEFAULT: disable global filter
298
+ * - INCLUDE_LIST: Only use global filter for programs in the list
299
+ * - EXCLUDE_LIST: Use global filter for all programs except those in the list
300
+ *
301
+ * @param {number} mode - Filter mode (SelectionHook.FilterMode)
302
+ * @param {string[]} programList - Array of program names to include/exclude
303
+ * @returns {boolean} Success status
304
+ */
305
+ setGlobalFilterMode(mode, programList = []) {
306
+ if (!this.#checkRunning()) return false;
307
+
308
+ const validModes = Object.values(SelectionHook.FilterMode);
309
+ if (!validModes.includes(mode)) {
310
+ this.#handleError("Invalid filter mode", new Error("Invalid argument"));
311
+ return false;
312
+ }
313
+
314
+ if (!Array.isArray(programList)) {
315
+ this.#handleError(
316
+ "Program list must be an array",
317
+ new Error("Invalid argument"),
318
+ );
319
+ return false;
320
+ }
321
+
322
+ try {
323
+ this.#instance.setGlobalFilterMode(mode, programList);
324
+ return true;
325
+ } catch (err) {
326
+ this.#handleError("Failed to set global filter mode and list", err);
327
+ return false;
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Set fine-tuned list for specific behaviors
333
+ *
334
+ * Configures fine-tuned lists for specific application behaviors.
335
+ * List types:
336
+ * - EXCLUDE_CLIPBOARD_CURSOR_DETECT: Exclude cursor detection for clipboard operations
337
+ * - INCLUDE_CLIPBOARD_DELAY_READ: Include delay when reading clipboard content
338
+ *
339
+ * @param {number} listType - Fine-tuned list type (SelectionHook.FineTunedListType)
340
+ * @param {string[]} programList - Array of program names for the fine-tuned list
341
+ * @returns {boolean} Success status
342
+ */
343
+ setFineTunedList(listType, programList = []) {
344
+ if (!this.#checkRunning()) return false;
345
+
346
+ const validTypes = Object.values(SelectionHook.FineTunedListType);
347
+ if (!validTypes.includes(listType)) {
348
+ this.#handleError(
349
+ "Invalid fine-tuned list type",
350
+ new Error("Invalid argument"),
351
+ );
352
+ return false;
353
+ }
354
+
355
+ if (!Array.isArray(programList)) {
356
+ this.#handleError(
357
+ "Program list must be an array",
358
+ new Error("Invalid argument"),
359
+ );
360
+ return false;
361
+ }
362
+
363
+ try {
364
+ this.#instance.setFineTunedList(listType, programList);
365
+ return true;
366
+ } catch (err) {
367
+ this.#handleError("Failed to set fine-tuned list", err);
368
+ return false;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Set selection passive mode
374
+ * @param {boolean} passive - Passive mode
375
+ * @returns {boolean} Success status
376
+ */
377
+ setSelectionPassiveMode(passive) {
378
+ if (!this.#checkRunning()) return false;
379
+
380
+ try {
381
+ this.#instance.setSelectionPassiveMode(passive);
382
+ return true;
383
+ } catch (err) {
384
+ this.#handleError("Failed to set selection passive mode", err);
385
+ return false;
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Write text to clipboard
391
+ * @param {string} text - Text to write to clipboard
392
+ * @returns {boolean} Success status
393
+ */
394
+ writeToClipboard(text) {
395
+ if (!this.#checkRunning()) return false;
396
+
397
+ if (typeof text !== "string") {
398
+ this.#handleError("Text must be a string", new Error("Invalid argument"));
399
+ return false;
400
+ }
401
+
402
+ try {
403
+ return this.#instance.writeToClipboard(text);
404
+ } catch (err) {
405
+ this.#handleError("Failed to write text to clipboard", err);
406
+ return false;
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Read text from clipboard
412
+ * @returns {string|null} Text from clipboard or null if empty or error
413
+ */
414
+ readFromClipboard() {
415
+ if (!this.#checkRunning()) return null;
416
+
417
+ try {
418
+ return this.#instance.readFromClipboard();
419
+ } catch (err) {
420
+ this.#handleError("Failed to read text from clipboard", err);
421
+ return null;
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Check if the process is trusted for accessibility (macOS only)
427
+ * @returns {boolean} True if the process is trusted for accessibility, false otherwise
428
+ */
429
+ macIsProcessTrusted() {
430
+ if (!isMac) {
431
+ this.#logDebug("Not supported on this platform");
432
+ return false;
433
+ }
434
+
435
+ //don't need to be running
436
+ if (!this.#instance) {
437
+ this.#logDebug("Text selection hook instance not created");
438
+ return false;
439
+ }
440
+
441
+ try {
442
+ return this.#instance.macIsProcessTrusted();
443
+ } catch (err) {
444
+ this.#handleError("Failed to check macOS process trust status", err);
445
+ return false;
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Try to request accessibility permissions (macOS only)
451
+ * This MAY show a dialog to the user if permissions are not granted
452
+ * @returns {boolean} The current permission status, not the request result
453
+ */
454
+ macRequestProcessTrust() {
455
+ if (!isMac) {
456
+ this.#logDebug("Not supported on this platform");
457
+ return false;
458
+ }
459
+
460
+ //don't need to be running
461
+ if (!this.#instance) {
462
+ this.#logDebug("Text selection hook instance not created");
463
+ return false;
464
+ }
465
+
466
+ try {
467
+ return this.#instance.macRequestProcessTrust();
468
+ } catch (err) {
469
+ this.#handleError("Failed to request macOS process trust", err);
470
+ return false;
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Check if hook is running
476
+ * @returns {boolean} Running status
477
+ */
478
+ isRunning() {
479
+ return this.#running;
480
+ }
481
+
482
+ /**
483
+ * Release resources
484
+ */
485
+ cleanup() {
486
+ this.stop();
487
+ this.removeAllListeners();
488
+ this.#instance = null;
489
+ }
490
+
491
+ #getDefaultConfig() {
492
+ return {
493
+ debug: false,
494
+ enableMouseMoveEvent: false,
495
+ enableClipboard: true,
496
+ selectionPassiveMode: false,
497
+ clipboardMode: SelectionHook.FilterMode.DEFAULT,
498
+ globalFilterMode: SelectionHook.FilterMode.DEFAULT,
499
+ clipboardFilterList: [],
500
+ globalFilterList: [],
501
+ };
502
+ }
503
+
504
+ #initByConfig(defaultConfig, userConfig) {
505
+ const config = {};
506
+
507
+ // Only keep values that exist in userConfig and differ from defaultConfig
508
+ for (const key in userConfig) {
509
+ if (userConfig[key] !== defaultConfig[key]) {
510
+ config[key] = userConfig[key];
511
+ }
512
+ }
513
+
514
+ // Apply the filtered config
515
+ if (config.enableMouseMoveEvent !== undefined) {
516
+ if (config.enableMouseMoveEvent) {
517
+ this.#instance.enableMouseMoveEvent();
518
+ } else {
519
+ this.#instance.disableMouseMoveEvent();
520
+ }
521
+ }
522
+
523
+ if (config.enableClipboard !== undefined) {
524
+ if (config.enableClipboard) {
525
+ this.#instance.enableClipboard();
526
+ } else {
527
+ this.#instance.disableClipboard();
528
+ }
529
+ }
530
+
531
+ if (config.selectionPassiveMode !== undefined) {
532
+ this.#instance.setSelectionPassiveMode(config.selectionPassiveMode);
533
+ }
534
+
535
+ if (
536
+ config.clipboardMode !== undefined ||
537
+ config.clipboardFilterList !== undefined
538
+ ) {
539
+ this.#instance.setClipboardMode(
540
+ config.clipboardMode ?? defaultConfig.clipboardMode,
541
+ config.clipboardFilterList ?? defaultConfig.clipboardFilterList,
542
+ );
543
+ }
544
+
545
+ if (
546
+ config.globalFilterMode !== undefined ||
547
+ config.globalFilterList !== undefined
548
+ ) {
549
+ this.#instance.setGlobalFilterMode(
550
+ config.globalFilterMode ?? defaultConfig.globalFilterMode,
551
+ config.globalFilterList ?? defaultConfig.globalFilterList,
552
+ );
553
+ }
554
+ }
555
+
556
+ #formatSelectionData(data) {
557
+ if (!data) return null;
558
+
559
+ const selectionInfo = {
560
+ text: data.text,
561
+ programName: data.programName,
562
+ startTop: { x: data.startTopX, y: data.startTopY },
563
+ startBottom: { x: data.startBottomX, y: data.startBottomY },
564
+ endTop: { x: data.endTopX, y: data.endTopY },
565
+ endBottom: { x: data.endBottomX, y: data.endBottomY },
566
+ mousePosStart: { x: data.mouseStartX, y: data.mouseStartY },
567
+ mousePosEnd: { x: data.mouseEndX, y: data.mouseEndY },
568
+ method: data.method || 0,
569
+ posLevel: data.posLevel || 0,
570
+ isEditable: data.isEditable || false,
571
+ };
572
+
573
+ if (isMac) {
574
+ selectionInfo.isFullscreen = data.isFullscreen;
575
+ }
576
+
577
+ return selectionInfo;
578
+ }
579
+
580
+ // Private helper methods
581
+ #checkRunning() {
582
+ if (!this.#instance || !this.#running) {
583
+ this.#logDebug("Text selection hook not running");
584
+ return false;
585
+ }
586
+ return true;
587
+ }
588
+
589
+ // level: "error" or "fatal"
590
+ // fatal will always show the error message
591
+ #handleError(message, err, level = "error") {
592
+ if (!_debugFlag && level === "error") return;
593
+
594
+ const errorMsg = `${message}: ${err.message}`;
595
+ console.error("[selection-hook] ", errorMsg);
596
+
597
+ if (err.stack) {
598
+ console.error(err.stack);
599
+ }
600
+
601
+ this.emit("error", new Error(errorMsg));
602
+ }
603
+
604
+ #logDebug(message) {
605
+ if (_debugFlag) {
606
+ console.warn("[selection-hook] ", message);
607
+ }
608
+ }
609
+ }
610
+
611
+ module.exports = SelectionHook;
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@mintplex-labs/advanced-selection-hook",
3
+ "version": "1.0.0",
4
+ "description": "Text selection monitoring of native Node.js module with N-API across applications",
5
+ "author": "@mintplex-labs",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mintplex-labs/advanced-selection-hook.git"
9
+ },
10
+ "main": "index.js",
11
+ "types": "index.d.ts",
12
+ "files": [
13
+ "examples",
14
+ "prebuilds",
15
+ "index.d.ts",
16
+ "index.js"
17
+ ],
18
+ "scripts": {
19
+ "install": "node-gyp-build",
20
+ "rebuild": "node-gyp rebuild",
21
+ "prebuild": "npm run prebuild:win && npm run prebuild:mac",
22
+ "prebuild:win": "npm run prebuild:win:x64 && npm run prebuild:win:arm64",
23
+ "prebuild:win:x64": "prebuildify --napi --platform=win32 --arch=x64",
24
+ "prebuild:win:arm64": "prebuildify --napi --platform=win32 --arch=arm64",
25
+ "prebuild:mac": "npm run prebuild:mac:x64 && npm run prebuild:mac:arm64",
26
+ "prebuild:mac:x64": "prebuildify --napi --platform=darwin --arch=x64",
27
+ "prebuild:mac:arm64": "prebuildify --napi --platform=darwin --arch=arm64",
28
+ "demo": "node --trace-deprecation --force-node-api-uncaught-exceptions-policy=true examples/node-demo.js",
29
+ "publish": "npm publish --dry-run --access public",
30
+ "publish:prod": "npm publish --access public"
31
+ },
32
+ "keywords": [
33
+ "node",
34
+ "electron",
35
+ "text",
36
+ "selection",
37
+ "napi",
38
+ "highlight",
39
+ "hooks",
40
+ "native",
41
+ "mouse",
42
+ "keyboard",
43
+ "clipboard",
44
+ "uiautomation"
45
+ ],
46
+ "license": "UNLICENSED",
47
+ "dependencies": {
48
+ "node-addon-api": "^8.4.0",
49
+ "node-gyp-build": "^4.8.4"
50
+ },
51
+ "devDependencies": {
52
+ "node-gyp": "^11.2.0",
53
+ "prebuildify": "^6.0.1"
54
+ },
55
+ "engines": {
56
+ "node": ">=18.0.0"
57
+ },
58
+ "gypfile": true,
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }